text
stringlengths
14
6.51M
{******************************************************************************* Title: T2Ti ERP Description: Controller relacionado à tabela [NOTA_FISCAL_CABECALHO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> Albert Eije (T2Ti.COM) @version 2.0 *******************************************************************************} unit NotaFiscalCabecalhoController; interface uses Classes, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, NotaFiscalCabecalhoVO, NotaFiscalDetalheVO, Generics.Collections; type TNotaFiscalCabecalhoController = class(TController) private class var FDataSet: TClientDataSet; class function Inserir(pObjeto: TNotaFiscalCabecalhoVO): Integer; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TNotaFiscalCabecalhoVO>; class function ConsultaObjeto(pFiltro: String): TNotaFiscalCabecalhoVO; class procedure Insere(pObjeto: TNotaFiscalCabecalhoVO); class procedure InsereObjeto(pObjeto: TNotaFiscalCabecalhoVO); class function Altera(pObjeto: TNotaFiscalCabecalhoVO): 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; class procedure TNotaFiscalCabecalhoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TNotaFiscalCabecalhoVO>; begin try Retorno := TT2TiORM.Consultar<TNotaFiscalCabecalhoVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TNotaFiscalCabecalhoVO>(Retorno); finally end; end; class function TNotaFiscalCabecalhoController.ConsultaLista(pFiltro: String): TObjectList<TNotaFiscalCabecalhoVO>; begin try Result := TT2TiORM.Consultar<TNotaFiscalCabecalhoVO>(pFiltro, '-1', True); finally end; end; class function TNotaFiscalCabecalhoController.ConsultaObjeto(pFiltro: String): TNotaFiscalCabecalhoVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TNotaFiscalCabecalhoVO>(pFiltro, True); finally end; end; class procedure TNotaFiscalCabecalhoController.Insere(pObjeto: TNotaFiscalCabecalhoVO); var UltimoID: Integer; begin try UltimoID := Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class procedure TNotaFiscalCabecalhoController.InsereObjeto(pObjeto: TNotaFiscalCabecalhoVO); var UltimoID: Integer; begin try UltimoID := Inserir(pObjeto); TratarRetorno<TNotaFiscalCabecalhoVO>(ConsultaObjeto('ID=' + IntToStr(UltimoID))); finally end; end; class function TNotaFiscalCabecalhoController.Inserir(pObjeto: TNotaFiscalCabecalhoVO): Integer; var Detalhe: TNotaFiscalDetalheVO; DetalheEnumerator: TEnumerator<TNotaFiscalDetalheVO>; begin try Result := TT2TiORM.Inserir(pObjeto); // Detalhes DetalheEnumerator := pObjeto.ListaNotaFiscalDetalheVO.GetEnumerator; try with DetalheEnumerator do begin while MoveNext do begin Detalhe := Current; Detalhe.IdNfCabecalho := Result; TT2TiORM.Inserir(Detalhe); end; end; finally FreeAndNil(DetalheEnumerator); end; finally end; end; class function TNotaFiscalCabecalhoController.Altera(pObjeto: TNotaFiscalCabecalhoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TNotaFiscalCabecalhoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TNotaFiscalCabecalhoVO; begin try ObjetoLocal := TNotaFiscalCabecalhoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal); end; end; class function TNotaFiscalCabecalhoController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TNotaFiscalCabecalhoController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TNotaFiscalCabecalhoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TNotaFiscalCabecalhoVO>(TObjectList<TNotaFiscalCabecalhoVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TNotaFiscalCabecalhoController); finalization Classes.UnRegisterClass(TNotaFiscalCabecalhoController); end.
unit FMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts; type TFormMain = class(TForm) LayoutTop: TLayout; ButtonTest: TButton; MemoLog: TMemo; ButtonTestCycle: TButton; procedure FormCreate(Sender: TObject); procedure ButtonTestClick(Sender: TObject); procedure ButtonTestCycleClick(Sender: TObject); private { Private declarations } procedure Log(const AMsg: String; const AArgs: array of const); public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses SmartPointer; type TBar = class; TFoo = class private FBar: TSmartPtr<TBar>; public property Bar: TSmartPtr<TBar> read FBar write FBar; end; TBar = class private FFoo: TSmartPtr<TFoo>; public property Foo: TSmartPtr<TFoo> read FFoo write FFoo; end; procedure TFormMain.ButtonTestClick(Sender: TObject); begin MemoLog.Lines.Clear; { Create a smart pointer for a TStringList. Note that you *cannot* use type inference here, since that would make List1 of type TSmartPtr<> instead of ISmartPtr<>! } var List1 := TSmartPtr<TStringList>.Create(TStringList.Create); Log('Reference count: %d (should be 1)', [List1.GetRefCount]); { Add some strings } List1.Ref.Add('Foo'); List1.Ref.Add('Bar'); begin { Copy the smart pointer } var List2 := List1; Log('Reference count: %d (should be 2)', [List1.GetRefCount]); { Check contents of List2 } Log('Number of items in list: %d (should be 2)', [List2.Ref.Count]); Log('First item: %s (should be Foo)', [List2.Ref[0]]); Log('Second item: %s (should be Bar)', [List2.Ref[1]]); { List2 will go out of scope here, so only List1 will keep a reference to the string list. } end; { There should be only 1 reference left. } Log('Reference count: %d (should be 1)', [List1.GetRefCount]); { Check contents of List1 again } Log('Number of items in list: %d (should be 2)', [List1.Ref.Count]); { TStringList will automatically be destroyed when the last ISmartPtr reference goes out of scope } end; procedure TFormMain.ButtonTestCycleClick(Sender: TObject); begin { Create smart pointers for TFoo and TBar } var Foo := TSmartPtr<TFoo>.Create(TFoo.Create); var Bar := TSmartPtr<TBar>.Create(TBar.Create); { Make a reference cycle } Foo.Ref.Bar := Bar; Bar.Ref.Foo := Foo; { This will result in a memory leak since the smart pointers reference each other. When you shut down the application (on Windows), you should get a message reporting 2 memory leaks: TFoo and TBar. } MemoLog.Lines.Text := 'Created a Reference Cycle, resulting in a memory leak'; end; procedure TFormMain.FormCreate(Sender: TObject); begin { To test the smart pointer implementation for memory leaks. } ReportMemoryLeaksOnShutdown := True; end; procedure TFormMain.Log(const AMsg: String; const AArgs: array of const); begin MemoLog.Lines.Add(Format(AMsg, AArgs)); MemoLog.GoToTextEnd; end; end.
unit Progress; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ComCtrls, JvExComCtrls, BCControls.ProgressBar, Vcl.ExtCtrls, ActnList, BCDialogs.Dlg, System.Actions, JvProgressBar; type TProgressDialog = class(TDialog) ActionList: TActionList; CancelAction: TAction; CancelButton: TButton; InformationLabel: TLabel; ProgressBar: TBCProgressBar; ProgressPanel: TPanel; TopPanel: TPanel; procedure CancelActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FOnProgress: Boolean; procedure SetInformationText(Value: string); procedure SetProgressPosition(Value: Integer); public { Public declarations } procedure Open(ProgressMin: Integer; ProgressMax: Integer; ShowCancel: Boolean; Marquee: Boolean = False); procedure SetRange(ProgressMin: Integer; ProgressMax: Integer); property InformationText: string write SetInformationText; property OnProgress: Boolean read FOnProgress; property ProgressPosition: Integer write SetProgressPosition; end; function ProgressDialog(AOwner: TComponent): TProgressDialog; implementation {$R *.dfm} uses BCCommon.StyleUtils; var FProgressDialog: TProgressDialog; function ProgressDialog(AOwner: TComponent): TProgressDialog; begin if not Assigned(FProgressDialog) then FProgressDialog := TProgressDialog.Create(AOwner); Result := FProgressDialog; end; procedure TProgressDialog.CancelActionExecute(Sender: TObject); begin FOnProgress := False; InformationLabel.Caption := 'Canceling...'; Repaint; Application.ProcessMessages; end; procedure TProgressDialog.FormDestroy(Sender: TObject); begin FProgressDialog := nil; end; procedure TProgressDialog.SetRange(ProgressMin: Integer; ProgressMax: Integer); begin ProgressBar.Position := 0; ProgressBar.Min := ProgressMin; ProgressBar.Max := ProgressMax; ProgressBar.Invalidate; Application.ProcessMessages; end; procedure TProgressDialog.Open(ProgressMin: Integer; ProgressMax: Integer; ShowCancel: Boolean; Marquee: Boolean = False); begin FOnProgress := True; SetRange(ProgressMin, ProgressMax); InformationText := ''; CancelButton.Visible := ShowCancel; if ShowCancel then Height := 140 else Height := 99; OrigHeight := Height; SetStyledFormSize(Self); ProgressBar.Marquee := Marquee; Visible := True; end; procedure TProgressDialog.SetInformationText(Value: string); begin if FOnProgress then begin InformationLabel.Caption := Value; Invalidate; Application.ProcessMessages; end; end; procedure TProgressDialog.SetProgressPosition(Value: Integer); begin if FOnProgress then begin ProgressBar.Position := Value; Invalidate; Application.ProcessMessages; end; end; end.
unit GameTutorial3; {$mode objfpc}{$H+} //step3: //a platformer where everything is 1 hit kill //Warning: While it's tempting to read through the code to find out how to beat this, try it first without interface uses windows, Classes, SysUtils, gamepanel, guitextobject, staticguiobject, gamebase, target, bullet,Dialogs, Graphics, playerwithhealth, math, gl, glext, glu, gamecube, platformenemy, platformplayer; type Tdoor=class(TObject) private w: single; h: single; fx,fy: single; flocked: boolean; door: TStaticGUIObject; lock: TStaticGUIObject; public function isinside(_x,_y: single): boolean; procedure render; constructor create; destructor destroy; override; property locked: boolean read flocked write flocked; property x: single read fx write fx; property y: single read fy write fy; end; TGame3=class(TGameBase) private fpanel: Tgamepanel; pplayer: TPlatformPlayer; platforms: array of TgameCube; enemies: array of TPlatformEnemy; //change from gamecube to gameobject after testing info: TGUITextObject; infobutton: TStaticGUIObject; pausescreen: TGUITextObject; pausebutton: TStaticGUIObject; door: Tdoor; gametime: qword; walkdirection: single; jumpkeydown: boolean; yvelocity: single; falling: boolean; fuckplayer: boolean; //when true the platformenemies will move to form a barrier around the door fuckplayertime: qword; procedure fuckplayercode; //code to call each gametick when the game has been won function pauseclick(sender: tobject): boolean; function infoPopup(sender: tobject): boolean; function HideInfo(sender: tobject): boolean; procedure spawnPlayer; procedure resetgame; public greencount: integer; procedure gametick(currentTime: qword; diff: integer); override; procedure render; override; function KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean; override; constructor create(p: TGamePanel); destructor destroy; override; end; implementation uses registry; function TDoor.isinside(_x,_y: single): boolean; begin result:=(_x>x - w/2) and (_x<x + w/2) and (_y>y - h/2) and (_y<y + h/2); end; procedure TDoor.render; begin door.x:=fx; door.y:=fy; lock.x:=fx; lock.y:=fy; door.render; if flocked then lock.render; end; destructor TDoor.destroy; begin freeandnil(door); freeandnil(lock); inherited destroy; end; constructor TDoor.create; begin flocked:=true; w:=0.08; h:=0.18; door:=TStaticGUIObject.create(nil,'door.png',h,w); lock:=TStaticGUIObject.create(nil,'lock.png',h,w); door.rotationpoint.x:=0; door.rotationpoint.y:=0; lock.rotationpoint.x:=0; lock.rotationpoint.y:=0; x:=1-(w/2); y:=1-(h/2)-0.05; end; function TGame3.KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean; var x: boolean; i: integer; bulletpos: integer; ct: qword; begin if (pplayer=nil) or (pplayer.blownup) then exit; if iskeydown(VK_W) and iskeydown(VK_I) and iskeydown(VK_N) then begin usedcheats:=true; for i:=0 to length(enemies)-1 do enemies[i].explode; door.locked:=false; exit; end; if iskeydown(VK_D) and iskeydown(VK_I) and iskeydown(VK_E) then begin pplayer.explode; exit; end; if iskeydown(VK_F) and iskeydown(VK_C) and iskeydown(VK_K) then begin door.locked:=false; fuckplayer:=true; fuckplayertime:=gametime; exit; end; // if player.isdead then exit; if keventtype=0 then begin ct:=GetTickCount64; case key of VK_P: pauseclick(nil); VK_LEFT,VK_A: if walkdirection>=0 then walkdirection:=-0.1; //starts with a lot of inertia VK_RIGHT,VK_D: if walkdirection<=0 then walkdirection:=0.1; VK_SPACE, VK_W,VK_UP: begin jumpkeydown:=true; //makes mountaingoating easier if falling=false then begin yvelocity:=1.45; end; end; end; end else begin case key of VK_LEFT,VK_A: if walkdirection<0 then walkdirection:=0; VK_RIGHT,VK_D: if walkdirection>0 then walkdirection:=0; VK_SPACE,VK_W,VK_UP: begin jumpkeydown:=false; end; end; end; result:=false; end; procedure TGame3.render; var i: integer; begin for i:=0 to length(platforms)-1 do platforms[i].render; if info<>nil then info.render else begin if infobutton<>nil then infobutton.render; end; pausebutton.render; if pausescreen<>nil then pausescreen.render; if pplayer<>nil then pplayer.render; for i:=0 to length(enemies)-1 do begin if enemies[i]<>nil then enemies[i].render; end; if door<>nil then door.render; end; procedure TGame3.fuckplayercode; //in 2 seconds take positions var t: qword; pos: single; targetx, targety: single; distance: single; begin t:=gametime-fuckplayertime; pos:=t/2000; if length(enemies)>=3 then begin if enemies[0]<>nil then begin //move it to the bottom left rotated 45 degress to the left //take 2 seconds to rotate targetx:=door.x-(door.w/2)-(enemies[0].width/2); if pos>=1 then begin enemies[0].rotation:=360-90; enemies[0].x:=targetx; end else begin enemies[0].rotation:=360-(90*pos); distance:=targetx-enemies[0].x; enemies[0].x:=enemies[0].x+distance*pos; end; end; if enemies[1]<>nil then begin //move it to the topleft rotated 45 degrees to the left targetx:=door.x-(door.w/2)-(enemies[0].width/2); targety:=enemies[0].y-(enemies[0].height/2)-(enemies[1].height/2); if pos>=1 then begin enemies[1].rotation:=360-90; enemies[1].x:=targetx; enemies[1].y:=targety; end else begin enemies[1].rotation:=360-(90*pos); distance:=targetx-enemies[1].x; enemies[1].x:=enemies[1].x+distance*pos; distance:=targety-enemies[1].y; enemies[1].y:=enemies[1].y+distance*pos; end; end; if enemies[2]<>nil then begin //move it to the topright targetx:=door.x; targety:=door.y-(door.h/2)-(enemies[2].width/2); if pos>=1 then begin enemies[2].x:=targetx; enemies[2].y:=targety; end else begin distance:=targetx-enemies[2].x; enemies[2].x:=enemies[2].x+distance*pos; distance:=targety-enemies[2].y; enemies[2].y:=enemies[2].y+distance*pos; end; end; end; end; procedure TGame3.gametick(currentTime: qword; diff: integer); var i,j: integer; oldx, oldy: single; newx, newy: single; oldplayerfeet, newplayerfeet: single; platformwalky: single; begin if ticking=false then exit; if pausescreen<>nil then exit; inc(gametime,diff); oldx:=pplayer.x; oldy:=pplayer.y; newy:=pplayer.y-(yvelocity*(diff/1000)); oldplayerfeet:=oldy+pplayer.height/2; newplayerfeet:=newy+pplayer.height/2; pplayer.y:=newy; if yvelocity<0 then begin //falling down //check the platforms that are between oldy and pplayer.y for i:=0 to length(platforms)-1 do begin platformwalky:=platforms[i].y-(platforms[i].height/2); if (oldplayerfeet<=platformwalky) and (newplayerfeet>=platformwalky) then begin //it passed this platform. Check if the width is good enough if (pplayer.x>platforms[i].x-platforms[i].width/2) and (pplayer.x<platforms[i].x+platforms[i].width/2) then begin //yes, it landed on top if platforms[i].color.g=0 then inc(greencount); //I could of course check if all are green, but this provides an easy hackable spot to speed things up platforms[i].color.r:=0; platforms[i].color.g:=1; falling:=false; yvelocity:=0; pplayer.y:=platformwalky-pplayer.height/2; //put it on top of the platform break; end; end; end; end; if yvelocity<>0 then falling:=true; if jumpkeydown and not falling then begin yvelocity:=1.45 end else yvelocity:=yvelocity-0.1; if walkdirection<>0 then walkdirection:=walkdirection*1.035; if walkdirection<-0.7 then walkdirection:=-0.7; if walkdirection>0.7 then walkdirection:=0.7; if (pplayer<>nil) and (walkdirection<>0) then begin pplayer.x:=pplayer.x+(walkdirection*(diff/1000)); end; if pplayer.x>(1-pplayer.width/2) then pplayer.x:=(1-pplayer.width/2); if pplayer.x<(-1+pplayer.width/2) then pplayer.x:=(-1+pplayer.width/2); if fuckplayer then fuckplayercode else begin for i:=0 to length(enemies)-1 do begin if enemies[i]<>nil then enemies[i].travel(diff); end; end; for i:=0 to length(enemies)-1 do begin if (enemies[i]<>nil) then begin if (not enemies[i].exploding) and enemies[i].checkCollision(pplayer) then pplayer.explode; if enemies[i].blownup then freeandnil(enemies[i]); end; end; if (door.locked) and (greencount>=length(platforms)) then begin door.locked:=false; fuckplayer:=true; //what happens when you nop this out ? fuckplayertime:=gametime; //another point of attack end; //I 'could' do a constant check for door.unlocked and then enter the fuckplayer mode, but just being nice and making it possible to unlock the door without having to mark all green if (pplayer<>nil) and (not pplayer.exploding) and (door.locked=false) and door.isinside(pplayer.x,pplayer.y) then begin ticking:=false; showmessage('well done'); with tregistry.create do begin if OpenKey('\Software\Cheat Engine\GTutorial', true) then WriteBool('This does not count as a solution for tutorial 3',True); free; end; gamewon; end; if (pplayer<>nil) and (pplayer.blownup) then begin //recreate the player //game over, restart freeandnil(pplayer); resetgame; end; end; function TGame3.pauseclick(sender: tobject): boolean; begin if pausescreen<>nil then freeandnil(pausescreen) else begin pausescreen:=TGUITextObject.create(fpanel); pausescreen.firstTextBecomesMinWidth:=true; pausescreen.width:=0.8; pausescreen.height:=0.8; pausescreen.x:=0; pausescreen.y:=0; pausescreen.rotationpoint.x:=0; pausescreen.rotationpoint.y:=0; pausescreen.color:=clRED; pausescreen.bcolor:=clWhite; pausescreen.font.Size:=18; pausescreen.text:='!PAUSED!'; end; result:=true; end; function TGame3.infoPopup(sender: tobject): boolean; begin if info<>nil then exit(false); info:=TGUITextObject.create(fpanel); info.firstTextBecomesMinWidth:=true; info.width:=0.8; info.height:=0.8; info.x:=0; info.y:=0; info.rotationpoint.x:=0; info.rotationpoint.y:=0; info.color:=clBlack; info.bcolor:=clWhite; info.backgroundAlpha:=190; info.font.Size:=9; info.text:='Step 3:'#13#10+ 'Mark all platforms green to'#13#10+ 'unlock the door'#13#10+ ' '#13#10+ 'Beware: Enemies are 1 hit kill'#13#10+ ' (and bad losers)'#13#10+ ' '#13#10+ ' '#13#10+ 'Have fun!'#13#10+ ' '#13#10+ 'Hint: There are multiple solutions'#13#10+ ' e.g: Find collisiton detect with '#13#10+ ' enemies, or teleport, or fly'#13#10+ ' or ....'#13#10; info.OnClick:=@HideInfo; result:=true; end; function TGame3.HideInfo(sender: tobject): boolean; begin freeandnil(info); result:=true; end; procedure TGame3.spawnPlayer; begin if pplayer=nil then pplayer:=tplatformplayer.create; //temporary holder pplayer.x:=-1+0.1; pplayer.y:=1-0.05-0.15/2; end; procedure TGame3.resetgame; var i: integer; begin spawnplayer; if length(platforms)<12 then setlength(platforms,12); for i:=0 to length(platforms)-1 do begin if platforms[i]=nil then platforms[i]:=Tgamecube.create; platforms[i].color.b:=0; platforms[i].color.r:=0.8; platforms[i].color.g:=0; end; //ground platforms[0].width:=2; platforms[0].height:=0.05; platforms[0].x:=0; platforms[0].y:=0.975; //p1 platforms[1].width:=0.3; platforms[1].height:=0.05; platforms[1].x:=-0.4; platforms[1].y:=0.7; platforms[2].width:=0.3; platforms[2].height:=0.05; platforms[2].x:=0.1; platforms[2].y:=0.7; platforms[3].width:=0.2; platforms[3].height:=0.05; platforms[3].x:=0; platforms[3].y:=0.42; platforms[4].width:=0.2; platforms[4].height:=0.05; platforms[4].x:=0.4; platforms[4].y:=0.2; platforms[5].width:=0.2; platforms[5].height:=0.05; platforms[5].x:=0.6; platforms[5].y:=-0.05; platforms[6].width:=0.4; platforms[6].height:=0.05; platforms[6].x:=0.75; platforms[6].y:=-0.3; platforms[7].width:=0.1; platforms[7].height:=0.05; platforms[7].x:=0.0; platforms[7].y:=-0.3; platforms[8].width:=0.4; platforms[8].height:=0.05; platforms[8].x:=-0.3; platforms[8].y:=-0.5; platforms[9].width:=0.2; platforms[9].height:=0.05; platforms[9].x:=-0.4; platforms[9].y:=-0.7; platforms[10].width:=0.2; platforms[10].height:=0.05; platforms[10].x:=-0.8; platforms[10].y:=-0.7; platforms[11].width:=0.1; platforms[11].height:=0.05; platforms[11].x:=-0.8; platforms[11].y:=0; fuckplayer:=false; if length(enemies)<3 then setlength(enemies,3); if enemies[0]=nil then enemies[0]:=TPlatformEnemy.create; enemies[0].x:=-0.5; enemies[0].y:=1-enemies[0].height/2-platforms[0].height; enemies[0].minx:=-0.6; enemies[0].maxx:=0-enemies[0].width/2; enemies[0].rotation:=0; if enemies[1]=nil then enemies[1]:=TPlatformEnemy.create; enemies[1].x:=0+enemies[0].width/2; enemies[1].y:=1-enemies[1].height/2-platforms[2].height; enemies[1].minx:=0; enemies[1].maxx:=0.9; enemies[1].rotation:=0; if enemies[2]=nil then enemies[2]:=TPlatformEnemy.create; enemies[2].x:=0+enemies[0].width/2; enemies[2].y:=platforms[8].y-(enemies[2].height/2)-(platforms[8].height/2); enemies[2].minx:=platforms[8].x-platforms[8].width/2; enemies[2].maxx:=platforms[8].x+platforms[8].width/2; enemies[2].speed:=enemies[1].speed/2; //got to keep the illusion the player can potentially win greencount:=0; door.locked:=true; end; destructor TGame3.destroy; begin if pplayer<>nil then freeandnil(pplayer); if infobutton<>nil then freeandnil(infobutton); if info<>nil then freeandnil(info); inherited destroy; end; constructor TGame3.create(p: TGamePanel); var i: integer; begin fpanel:=p; infobutton:=TStaticGUIObject.create(p,'infobutton.png',0.1,0.1); infobutton.rotationpoint.y:=1; //so the bottom will be the y pos infobutton.x:=-1; infobutton.y:=1-0.05; infobutton.OnClick:=@infopopup; pausebutton:=TStaticGUIObject.create(p,'pausebutton.png',0.1,0.1); pausebutton.rotationpoint.y:=1; pausebutton.x:=-1+0.1; pausebutton.y:=1-0.05; pausebutton.OnClick:=@pauseclick; door:=Tdoor.create; resetgame; infopopup(infobutton); ticking:=true; { p.background.r:=0; p.background.g:=0; p.background.b:=1;} end; end.
unit Frames.JoinGame; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, System.Actions, FMX.ActnList , FrameStand, SubjectStand ; type TJoinFrame = class(TFrame) Layout1: TLayout; YourNameEdit: TEdit; Label6: TLabel; Layout2: TLayout; Layout3: TLayout; Label1: TLabel; GamesListView: TListView; JoinGameButton: TButton; GameKeyEdit: TEdit; Label2: TLabel; ActionList1: TActionList; JoinGameAction: TAction; LastCheckLabel: TLabel; ClearGameKeyButton: TButton; procedure JoinGameActionUpdate(Sender: TObject); procedure GameKeyEditChangeTracking(Sender: TObject); procedure JoinGameActionExecute(Sender: TObject); procedure ClearGameKeyButtonClick(Sender: TObject); private [FrameInfo] FI: TFrameInfo<TJoinFrame>; procedure RenderGames; public [BeforeShow] procedure FrameOnShow; procedure AfterConstruction; override; end; implementation {$R *.fmx} uses datamodel , Data.Remote, Data.Main, Utils.Messages, System.Messaging; { TJoinFrame } procedure TJoinFrame.AfterConstruction; begin inherited; GameKeyEdit.MaxLength := cPasswordLen; TGamesChanged.Subscribe( procedure (const Sender: TObject; const M: TMessage) begin RenderGames; LastCheckLabel.Text := TimeToStr(Now); end ); end; procedure TJoinFrame.ClearGameKeyButtonClick(Sender: TObject); begin GameKeyEdit.Text := ''; end; procedure TJoinFrame.FrameOnShow; begin RemoteData.StartPollingForGames(); end; procedure TJoinFrame.GameKeyEditChangeTracking(Sender: TObject); begin GamesListView.Enabled := not (GameKeyEdit.Text.Trim.Length = cPasswordLen); end; procedure TJoinFrame.JoinGameActionExecute(Sender: TObject); var LSessionID: string; LSelected: TListViewItem; begin // LSessionID := GameKeyEdit.Text.Trim; LSelected := GamesListView.Selected as TListViewItem; if GamesListView.Enabled and Assigned(LSelected) then LSessionID := LSelected.Data['SessionID'].AsString; if LSessionID = '' then Exit; RemoteData.JoinGame(YourNameEdit.Text.Trim, LSessionID , procedure begin MainData.CurrentView := GreenRoom; end , procedure(const AErrorMessage: string) begin ShowMessage(AErrorMessage); FI.HideAndClose(); MainData.CurrentView := Home; end ); end; procedure TJoinFrame.JoinGameActionUpdate(Sender: TObject); begin JoinGameAction.Enabled := (YourNameEdit.Text.Trim.Length > 3) and ( (GameKeyEdit.Text.Trim.Length = cPasswordLen) or (GamesListView.Selected <> nil) ); end; procedure TJoinFrame.RenderGames; var LPreviouslySelectedSessionID: string; LPreviouslySelected: TListViewItem; begin GamesListView.BeginUpdate; try LPreviouslySelected := GamesListView.Selected as TListViewItem; LPreviouslySelectedSessionID := ''; if Assigned(LPreviouslySelected) then LPreviouslySelectedSessionID := LPreviouslySelected.Data['SessionID'].AsString; GamesListView.Items.Clear; LPreviouslySelected := nil; MainData.Games.ForEach( procedure (const game: IGameData) var LItem: TListViewItem; begin LItem := GamesListView.Items.Add; LItem.Text := game.SessionName; LItem.Detail := game.UserCount.ToString + '/' + game.MinUser.ToString; LItem.Data['SessionID'] := game.SessionID; // borderline if game.SessionID = LPreviouslySelectedSessionID then LPreviouslySelected := LItem; end ); GamesListView.Selected := LPreviouslySelected; finally GamesListView.EndUpdate; end; end; end.
unit UCadastroUsuario; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Objects; type TFrmCadastroUsuario = class(TForm) layoutBase: TLayout; LayoutTopo: TLayout; LabelNome: TLabel; EditNome: TEdit; LayoutForm: TLayout; LabelEmail: TLabel; EditEmail: TEdit; LabelObservacao: TLabel; EditObservacao: TEdit; ScrollBoxForm: TScrollBox; ToolBarCadastro: TToolBar; LabelTitleCadastro: TLabel; RectangleUser: TRectangle; LayoutFoto: TLayout; ImageLogoApp: TImage; LayoutUsuario: TLayout; LabelEntidade: TLabel; CaptionEntidade: TLabel; LabelLogin: TLabel; CaptionLogin: TLabel; RoundRectCadastro: TRoundRect; BtnSalvar: TSpeedButton; ImageSalvar: TImage; procedure GravarUsuario(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormFocusChanged(Sender: TObject); procedure FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); procedure EditNomeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure EditEmailKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); procedure EditObservacaoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); private { Private declarations } FWBounds : TRectF; FNeedOffSet : Boolean; procedure GravarUsuarioApp; public { Public declarations } procedure CalcContentBounds(Sender : TObject; var ContentBounds : TRectF); procedure RestorePosition; procedure UpdatePosition; end; var FrmCadastroUsuario: TFrmCadastroUsuario; implementation uses UDados , USplashUI , app.Funcoes , classes.Constantes , dao.Usuario , System.Threading , System.JSON, UPrincipal; {$R *.fmx} {$R *.iPhone55in.fmx IOS} procedure TFrmCadastroUsuario.CalcContentBounds(Sender: TObject; var ContentBounds: TRectF); begin if (FNeedOffSet and (FWBounds.Top > 0)) then begin ContentBounds.Bottom := Max(ContentBounds.Bottom, 2 * ClientHeight - FWBounds.Top); end; end; procedure TFrmCadastroUsuario.EditEmailKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (Key = vkReturn) then EditObservacao.SetFocus; end; procedure TFrmCadastroUsuario.EditNomeKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (Key = vkReturn) then EditEmail.SetFocus; end; procedure TFrmCadastroUsuario.EditObservacaoKeyUp(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState); begin if (Key = vkReturn) then GravarUsuario(RoundRectCadastro); end; procedure TFrmCadastroUsuario.FormCreate(Sender: TObject); var aUsuario : TUsuarioDao; begin aUsuario := TUsuarioDao.GetInstance; CaptionEntidade.Text := AnsiUpperCase(COMPANY_NAME); CaptionLogin.Text := AnsiUpperCase(aUsuario.Model.Codigo); EditNome.Text := aUsuario.Model.Nome; EditEmail.Text := aUsuario.Model.Email; EditObservacao.Text := aUsuario.Model.Observacao; ScrollBoxForm.OnCalcContentBounds := CalcContentBounds; end; procedure TFrmCadastroUsuario.FormFocusChanged(Sender: TObject); begin UpdatePosition; end; procedure TFrmCadastroUsuario.FormVirtualKeyboardHidden(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin FWBounds.Create(0, 0, 0, 0); FNeedOffSet := False; RestorePosition; end; procedure TFrmCadastroUsuario.FormVirtualKeyboardShown(Sender: TObject; KeyboardVisible: Boolean; const Bounds: TRect); begin FWBounds := TRectF.Create(Bounds); FWBounds.TopLeft := ScreenToClient(FWBounds.TopLeft); FWBounds.BottomRight := ScreenToClient(FWBounds.BottomRight); UpdatePosition; end; procedure TFrmCadastroUsuario.GravarUsuario(Sender: TObject); var aKey , aLogin , aNome , aEmail , aObs , aMsg : String; aControle : TComponent; iError : Integer; aUsuario : TUsuarioDao; aTaskPost : ITask; begin aMsg := EmptyStr; aControle := nil; aKey := MD5(FormatDateTime('dd/mm/yyyy', Date)); aLogin := Trim(CaptionLogin.Text); aNome := Trim(EditNome.Text); aEmail := Trim(EditEmail.Text); aObs := Trim(EditObservacao.Text); if (Trim(EditNome.Text) = EmptyStr) then begin aControle := EditNome; aMsg := 'Informe seu nome.'; end else if (Trim(EditEmail.Text) = EmptyStr) then begin aControle := EditEmail; aMsg := 'Informe seu e-mail.'; end else if not IsEmailValido(EditEmail.Text) then begin aControle := EditEmail; aMsg := 'E-mail inválido.'; end; if (aMsg <> EmptyStr) then begin {$IF (DEFINED (MACOS)) || (DEFINED (IOS))} MessageDlg(aMsg, TMsgDlgType.mtwarning, [TMsgDlgBtn.mbok], 0); {$ELSE} ShowMessage(aMsg); {$ENDIF} if (aControle <> nil) then TEdit(aControle).SetFocus; end else begin aUsuario := TUsuarioDao.GetInstance; if (aUsuario.Model.Id = GUID_NULL) then aUsuario.Model.NewId; aTaskPost := TTask.Create( procedure var aMsg : String; aJsonArray : TJSONArray; aJsonObject : TJSONObject; aErr : Boolean; begin aMsg := 'Autenticando...'; try aErr := False; try aUsuario.Model.Codigo := aLogin; aUsuario.Model.Nome := aNome; aUsuario.Model.Email := aEmail; aUsuario.Model.Observacao := aObs; aUsuario.Model.Ativo := False; aJsonArray := DtmDados.HttpPostUsuario(aKey) as TJSONArray; except On E : Exception do begin iError := 99; aErr := True; aMsg := 'Servidor da entidade não responde ...' + #13 + E.Message; end; end; if not aErr then begin aJsonObject := aJsonArray.Items[0] as TJSONObject; iError := StrToInt(aJsonObject.GetValue('cd_error').Value); case iError of 0 : aUsuario.Model.Ativo := True; else aMsg := aJsonObject.GetValue('ds_error').Value; end; end; finally if (iError > 0) then begin TThread.queue(nil, procedure begin {$IF (DEFINED (MACOS)) || (DEFINED (IOS))} MessageDlg(aMsg, TMsgDlgType.mtwarning, [TMsgDlgBtn.mbok], 0); {$ELSE} ShowMessage(aMsg); {$ENDIF} end); end else begin if (iError = 0) then GravarUsuarioApp; end; end; end ); aTaskPost.Start; end; end; procedure TFrmCadastroUsuario.GravarUsuarioApp; var aUsuario : TUsuarioDao; begin aUsuario := TUsuarioDao.GetInstance; try if not aUsuario.Find(aUsuario.Model.Codigo, aUsuario.Model.Email, False) then aUsuario.Insert() else aUsuario.Update(); finally if (aUsuario.MainMenu and Assigned(FrmPrincipal)) then FrmPrincipal.MenuPrincipal else FrmSplashUI.AbrirMenu; end; end; procedure TFrmCadastroUsuario.RestorePosition; begin ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, 0); LayoutForm.Align := TAlignLayout.Client; ScrollBoxForm.RealignContent; end; procedure TFrmCadastroUsuario.UpdatePosition; var LFocused : TControl; LFocusRect : TRectF; begin FNeedOffSet := False; if Assigned(Focused) then begin LFocused := TControl(Focused.GetObject); LFocusRect := LFocused.AbsoluteRect; LFocusRect.Offset(ScrollBoxForm.ViewportPosition); if (LFocusRect.IntersectsWith(TRectF.Create(FWBounds)) and (LFocusRect.Bottom > FWBounds.Top)) then begin FNeedOffSet := True; LayoutForm.Align := TAlignLayout.Horizontal; ScrollBoxForm.RealignContent; Application.ProcessMessages; ScrollBoxForm.ViewportPosition := PointF(ScrollBoxForm.ViewportPosition.X, LFocusRect.Bottom - FWBounds.Top); end; end; if not FNeedOffSet then RestorePosition; end; end.
unit galaga_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,namco_snd,controls_engine,gfx_engine,namcoio_06xx_51xx_53xx, rom_engine,pal_engine,sound_engine,galaga_stars_const; procedure Cargar_Galagahw; function iniciar_galagahw:boolean; procedure reset_galagahw; procedure cerrar_galagahw; //Galaga procedure galaga_principal; function galaga_getbyte(direccion:word):byte; procedure galaga_putbyte(direccion:word;valor:byte); function galaga_sub_getbyte(direccion:word):byte; function galaga_sub2_getbyte(direccion:word):byte; //DigDug procedure digdug_principal; function digdug_getbyte(direccion:word):byte; procedure digdug_putbyte(direccion:word;valor:byte); function digdug_sub_getbyte(direccion:word):byte; function digdug_sub2_getbyte(direccion:word):byte; //Namco IO's procedure namco_06xx_nmi; function namco_51xx_io0:byte; function namco_51xx_io1:byte; function namco_51xx_io2:byte; function namco_51xx_io3:byte; function namco_53xx_r_r(port:byte):byte; function namco_53xx_k_r:byte; implementation const //Galaga galaga_rom:array[0..4] of tipo_roms=( (n:'gg1_1b.3p';l:$1000;p:0;crc:$ab036c9f),(n:'gg1_2b.3m';l:$1000;p:$1000;crc:$d9232240), (n:'gg1_3.2m';l:$1000;p:$2000;crc:$753ce503),(n:'gg1_4b.2l';l:$1000;p:$3000;crc:$499fcc76),()); galaga_sub:tipo_roms=(n:'gg1_5b.3f';l:$1000;p:0;crc:$bb5caae3); galaga_sub2:tipo_roms=(n:'gg1_7b.2c';l:$1000;p:0;crc:$d016686b); galaga_prom:array[0..3] of tipo_roms=( (n:'prom-5.5n';l:$20;p:0;crc:$54603c6b),(n:'prom-4.2n';l:$100;p:$20;crc:$59b6edab), (n:'prom-3.1c';l:$100;p:$120;crc:$4a04bb6b),()); galaga_char:tipo_roms=(n:'gg1_9.4l';l:$1000;p:0;crc:$58b2f47c); galaga_sound:tipo_roms=(n:'prom-1.1d';l:$100;p:0;crc:$7a2815b4); galaga_sprites:array[0..2] of tipo_roms=( (n:'gg1_11.4d';l:$1000;p:0;crc:$ad447c80),(n:'gg1_10.4f';l:$1000;p:$1000;crc:$dd6f1afc),()); //Dig Dug digdug_rom:array[0..4] of tipo_roms=( (n:'dd1a.1';l:$1000;p:0;crc:$a80ec984),(n:'dd1a.2';l:$1000;p:$1000;crc:$559f00bd), (n:'dd1a.3';l:$1000;p:$2000;crc:$8cbc6fe1),(n:'dd1a.4';l:$1000;p:$3000;crc:$d066f830),()); digdug_sub:array[0..2] of tipo_roms=( (n:'dd1a.5';l:$1000;p:0;crc:$6687933b),(n:'dd1a.6';l:$1000;p:$1000;crc:$843d857f),()); digdug_sub2:tipo_roms=(n:'dd1.7';l:$1000;p:0;crc:$a41bce72); digdug_prom:array[0..3] of tipo_roms=( (n:'136007.113';l:$20;p:0;crc:$4cb9da99),(n:'136007.111';l:$100;p:$20;crc:$00c7c419), (n:'136007.112';l:$100;p:$120;crc:$e9b3e08e),()); digdug_sound:tipo_roms=(n:'136007.110';l:$100;p:0;crc:$7a2815b4); digdug_chars:tipo_roms=(n:'dd1.9';l:$800;p:0;crc:$f14a6fe1); digdug_sprites:array[0..4] of tipo_roms=( (n:'dd1.15';l:$1000;p:0;crc:$e22957c8),(n:'dd1.14';l:$1000;p:$1000;crc:$2829ec99), (n:'dd1.13';l:$1000;p:$2000;crc:$458499e9),(n:'dd1.12';l:$1000;p:$3000;crc:$c58252a0),()); digdug_chars2:tipo_roms=(n:'dd1.11';l:$1000;p:0;crc:$7b383983); digdug_background:tipo_roms=(n:'dd1.10b';l:$1000;p:0;crc:$2cf399c2); var main_irq,sub_irq,sub2_nmi:boolean; //Galaga galaga_starcontrol:array[0..5] of byte; stars_scrollx,stars_scrolly:dword; //Dig Dug digdug_bg:array[0..$fff] of byte; custom_mod,bg_select,bg_color_bank,bg_disable,tx_color_mode:byte; bg_repaint:boolean; procedure Cargar_galagahw; begin llamadas_maquina.iniciar:=iniciar_galagahw; case main_vars.tipo_maquina of 65:llamadas_maquina.bucle_general:=galaga_principal; 167:llamadas_maquina.bucle_general:=digdug_principal; end; llamadas_maquina.cerrar:=cerrar_galagahw; llamadas_maquina.reset:=reset_galagahw; llamadas_maquina.fps_max:=60.6060606060; end; function iniciar_galagahw:boolean; var colores:tpaleta; f:word; ctemp1:byte; memoria_temp:array[0..$3fff] of byte; const map:array[0..3] of byte=($00,$47,$97,$de); pc_x_digdug:array[0..7] of dword=(7, 6, 5, 4, 3, 2, 1, 0); pc_y_digdug:array[0..7] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8); procedure galaga_chr(ngfx:byte;num:word); const 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); begin init_gfx(ngfx,8,8,num); gfx_set_desc_data(2,0,16*8,0,4); convert_gfx(ngfx,0,@memoria_temp[0],@pc_x[0],@pc_y[0],true,false); end; procedure galaga_spr(num:word); const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8, 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); 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); begin init_gfx(1,16,16,num); gfx_set_desc_data(2,0,64*8,0,4); convert_gfx(1,0,@memoria_temp[0],@ps_x[0],@ps_y[0],true,false); end; begin iniciar_galagahw:=false; iniciar_audio(false); //Pantallas: principal+char y sprites screen_init(1,224,288,true); screen_init(2,256,512,false,true); screen_init(3,224,288); //Digdug background iniciar_video(224,288); //Main CPU main_z80:=cpu_z80.create(3072000,264); //Sub CPU snd_z80:=cpu_z80.create(3072000,264); //Sub2 CPU sub_z80:=cpu_z80.create(3072000,264); //Sound namco_sound_init(3,false); //IO's namco_51xx.read_port[0]:=namco_51xx_io0; namco_51xx.read_port[1]:=namco_51xx_io1; namco_51xx.read_port[2]:=namco_51xx_io2; namco_51xx.read_port[3]:=namco_51xx_io3; case main_vars.tipo_maquina of 65:begin //Galaga //CPU's //Main main_z80.change_ram_calls(galaga_getbyte,galaga_putbyte); //Sub1 snd_z80.change_ram_calls(galaga_sub_getbyte,galaga_putbyte); //Sub2 sub_z80.change_ram_calls(galaga_sub2_getbyte,galaga_putbyte); //Init IO's namco_06xx_init(0,IO51XX,NONE,NONE,NONE,namco_06xx_nmi); //cargar roms if not(cargar_roms(@memoria[0],@galaga_rom[0],'galaga.zip',0)) then exit; if not(cargar_roms(@mem_snd[0],@galaga_sub,'galaga.zip',1)) then exit; if not(cargar_roms(@mem_misc[0],@galaga_sub2,'galaga.zip',1)) then exit; //cargar sonido & iniciar_sonido if not(cargar_roms(@namco_sound.onda_namco[0],@galaga_sound,'galaga.zip',1)) then exit; //convertir chars if not(cargar_roms(@memoria_temp[0],@galaga_char,'galaga.zip',1)) then exit; galaga_chr(0,$100); //convertir sprites if not(cargar_roms(@memoria_temp[0],@galaga_sprites[0],'galaga.zip',0)) then exit; galaga_spr($80); //poner la paleta if not(cargar_roms(@memoria_temp[0],@galaga_prom[0],'galaga.zip',0)) then exit; for f:=0 to $1f 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+$47*((ctemp1 shr 6) and 1)+$97*((ctemp1 shr 7) and 1); end; //paleta de las estrellas for f:=0 to $3f do begin ctemp1:=(f shr 0) and $03; colores[$20+f].r:=map[ctemp1]; ctemp1:=(f shr 2) and $03; colores[$20+f].g:=map[ctemp1]; ctemp1:=(f shr 4) and $03; colores[$20+f].b:=map[ctemp1]; end; set_pal(colores,32+64); //CLUT for f:=0 to $ff do begin gfx[0].colores[f]:=memoria_temp[$20+f]+$10; gfx[1].colores[f]:=memoria_temp[$120+f]; end; end; 167:begin //DigDug //Main main_z80.change_ram_calls(digdug_getbyte,digdug_putbyte); //Sub1 snd_z80.change_ram_calls(digdug_sub_getbyte,digdug_putbyte); //Sub2 sub_z80.change_ram_calls(digdug_sub2_getbyte,digdug_putbyte); //Init IO's namco_06xx_init(0,IO51XX,IO53XX,NONE,NONE,namco_06xx_nmi); //Namco 53XX namcoio_53xx_init(namco_53xx_k_r,namco_53xx_r_r,'digdug.zip'); //cargar roms if not(cargar_roms(@memoria[0],@digdug_rom[0],'digdug.zip',0)) then exit; if not(cargar_roms(@mem_snd[0],@digdug_sub,'digdug.zip',0)) then exit; if not(cargar_roms(@mem_misc[0],@digdug_sub2,'digdug.zip',1)) then exit; //cargar sonido & iniciar_sonido if not(cargar_roms(@namco_sound.onda_namco[0],@digdug_sound,'digdug.zip',1)) then exit; //convertir chars if not(cargar_roms(@memoria_temp[0],@digdug_chars,'digdug.zip',1)) then exit; init_gfx(0,8,8,$200); gfx[0].trans[0]:=true; gfx_set_desc_data(1,0,8*8,0); convert_gfx(0,0,@memoria_temp[$0],@pc_x_digdug[0],@pc_y_digdug[0],true,false); //sprites if not(cargar_roms(@memoria_temp[0],@digdug_sprites,'digdug.zip',0)) then exit; galaga_spr($100); //Background if not(cargar_roms(@digdug_bg[0],@digdug_background,'digdug.zip',1)) then exit; if not(cargar_roms(@memoria_temp[0],@digdug_chars2,'digdug.zip',1)) then exit; galaga_chr(2,$100); //poner la paleta if not(cargar_roms(@memoria_temp[0],@digdug_prom[0],'digdug.zip',0)) then exit; for f:=0 to $1f 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+$47*((ctemp1 shr 6) and 1)+$97*((ctemp1 shr 7) and 1); end; set_pal(colores,32); //CLUT for f:=0 to 15 do begin //chars gfx[0].colores[f*2+0]:=$0; gfx[0].colores[f*2+1]:=f; end; for f:=0 to $ff do begin gfx[1].colores[f]:=memoria_temp[$20+f]+$10; //sprites gfx[2].colores[f]:=memoria_temp[$120+f]; //background end; end; end; //final reset_galagahw; iniciar_galagahw:=true; end; procedure cerrar_galagahw; begin main_z80.free; snd_z80.free; sub_z80.free; if main_vars.tipo_maquina=167 then namco_53xx_close; close_audio; close_video; end; procedure draw_sprites_galaga; var nchar,f,atrib,a,b,c,d,flipx_v,flipy_v:byte; color,x,y:word; flipx,flipy:boolean; begin for f:=0 to $3f do begin nchar:=memoria[$8b80+(f*2)] and $7f; color:=(memoria[$8b81+(f*2)] and $3f) shl 2; y:=memoria[$9381+(f*2)]-40+$100*(memoria[$9b81+(f*2)] and 3); x:=memoria[$9380+(f*2)]-16-1; // sprites are buffered and delayed by one scanline atrib:=memoria[$9b80+(f*2)]; flipx:=(atrib and $02)<>0; flipy:=(atrib and $01)<>0; flipx_v:=atrib and $02; flipy_v:=atrib and $01; case (atrib and $0c) of 0:begin //16x16 put_gfx_sprite_mask(nchar,color,flipx,flipy,1,$f,$f); actualiza_gfx_sprite(x,y,2,1); end; 4:begin //16x32 a:=0 xor flipy_v; b:=1 xor flipy_v; put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$f,$f,0,16); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$f,$f,0,0); actualiza_gfx_sprite_size(x,y,2,16,32); end; 8:begin //32x16 a:=0 xor flipx_v; b:=2 xor flipx_v; put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$f,$f,16,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$f,$f,0,0); actualiza_gfx_sprite_size(x,y,2,32,16); end; $c:begin //32x32 a:=0 xor flipy_v xor flipx_v; b:=1 xor flipy_v xor flipx_v; c:=2 xor flipy_v xor flipx_v; d:=3 xor flipy_v xor flipx_v; put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$f,$f,16,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$f,$f,16,16); put_gfx_sprite_mask_diff(nchar+c,color,flipx,flipy,1,$f,$f,0,0); put_gfx_sprite_mask_diff(nchar+d,color,flipx,flipy,1,$f,$f,0,16); actualiza_gfx_sprite_size(x,y,2,32,32); end; end; end; end; procedure update_stars;inline; const speeds:array[0..7] of integer=(-1,-2,-3,0,3,2,1,0); var s0,s1,s2:byte; begin s0:=galaga_starcontrol[0] and 1; s1:=galaga_starcontrol[1] and 1; s2:=galaga_starcontrol[2] and 1; stars_scrolly:=stars_scrolly+speeds[s0+s1*2+s2*4]; end; procedure draw_stars;inline; const MAX_STARS=252; var star_cntr,set_a,set_b:byte; x,y,color:word; begin if (galaga_starcontrol[5] and 1)=1 then begin // two sets of stars controlled by these bits */ set_a:=galaga_starcontrol[3] and 1; set_b:=(galaga_starcontrol[4] and 1) or $2; for star_cntr:=0 to (MAX_STARS-1) do begin if ((set_a=star_seed_tab[star_cntr].set_) or (set_b=star_seed_tab[star_cntr].set_)) then begin y:=(star_seed_tab[star_cntr].y+stars_scrolly) mod 256+16; x:=(112+star_seed_tab[star_cntr].x+stars_scrollx) mod 256; color:=paleta[32+star_seed_tab[star_cntr].col]; putpixel(x+ADD_SPRITE,y+ADD_SPRITE,1,@color,2); end; end; end; end; procedure update_video_galaga;inline; var color,nchar,pos:word; sx,sy,x,y:byte; begin fill_full_screen(2,100); draw_stars; draw_sprites_galaga; for x:=0 to 27 do begin for y:=0 to 35 do begin sx:=29-x; sy:=y-2; if (sy and $20)<>0 then pos:=sx+((sy and $1f) shl 5) else pos:=sy+(sx shl 5); if gfx[0].buffer[pos] then begin color:=(memoria[$8400+pos] and $3f) shl 2; nchar:=memoria[$8000+pos]; put_gfx_mask(x*8,y*8,nchar,color,1,0,$f,$f); gfx[0].buffer[pos]:=false; end; end; end; actualiza_trozo(0,0,224,288,1,0,0,224,288,2); actualiza_trozo_final(0,0,224,288,2); update_stars; end; procedure eventos_galaga; 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.right[0] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.start[1] 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 $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); end; end; procedure galaga_principal; var frame_m,frame_s1,frame_s2:single; f,scanline:word; begin init_controls(false,false,false,true); frame_m:=main_z80.tframes; frame_s1:=snd_z80.tframes; frame_s2:=sub_z80.tframes; scanline:=63; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin //Main CPU main_z80.run(frame_m); frame_m:=frame_m+main_z80.tframes-main_z80.contador; //Sub CPU snd_z80.run(frame_s1); frame_s1:=frame_s1+snd_z80.tframes-snd_z80.contador; //Sub 2 CPU sub_z80.run(frame_s2); frame_s2:=frame_s2+sub_z80.tframes-sub_z80.contador; if (f=scanline) then begin if sub2_nmi then sub_z80.pedir_nmi:=PULSE_LINE; scanline:=scanline+128; if (scanline>=272) then scanline:=63; end; if f=223 then begin if main_irq then main_z80.pedir_irq:=ASSERT_LINE; if sub_irq then snd_z80.pedir_irq:=ASSERT_LINE; update_video_galaga; copymemory(@buffer_sprites[0],@memoria[$fe00],$200); end; end; if sound_status.hay_sonido then begin namco_playsound; play_sonido; end; eventos_galaga; video_sync; end; end; procedure galaga_latch(dir,val:byte);inline; var bit:byte; begin bit:=val and 1; case dir of $0:begin // IRQ1 */ main_irq:=bit<>0; if not(main_irq) then main_z80.pedir_irq:=CLEAR_LINE; end; $1:begin // IRQ2 */ sub_irq:=bit<>0; if not(sub_irq) then snd_z80.pedir_irq:=CLEAR_LINE; end; $2:sub2_nmi:=(bit=0); // NMION */ $3:if (bit<>0) then begin // RESET */ snd_z80.pedir_reset:=CLEAR_LINE; sub_z80.pedir_reset:=CLEAR_LINE; end else begin snd_z80.pedir_reset:=ASSERT_LINE; sub_z80.pedir_reset:=ASSERT_LINE; end; $4:; //n.c. $05:custom_mod:=(custom_mod and $fe) or (bit shl 0); // MOD 0 $06:custom_mod:=(custom_mod and $fd) or (bit shl 1); // MOD 1 $07:custom_mod:=(custom_mod and $fb) or (bit shl 2); // MOD 2 end; end; procedure reset_galagahw; var f:byte; begin main_z80.reset; snd_z80.reset; sub_z80.reset; case main_vars.tipo_maquina of 65:begin for f:=0 to 5 do galaga_starcontrol[f]:=0; stars_scrollx:=0; stars_scrolly:=0; end; 167:begin namcoio_53xx_reset; custom_mod:=0; bg_select:=0; bg_color_bank:=0; bg_disable:=0; tx_color_mode:=0; bg_repaint:=true; end; end; namco_sound_reset; reset_audio; namcoio_51xx_reset; namcoio_06xx_reset(0); main_irq:=false; sub_irq:=false; sub2_nmi:=false; marcade.in0:=$ff; marcade.in1:=$ff; for f:=0 to 7 do galaga_latch(f,0); end; procedure galaga_putbyte(direccion:word;valor:byte); begin if (direccion<$4000) then exit; case direccion of $6800..$681f:namco_sound.registros_namco[direccion and $1f]:=valor; $6820..$6827:galaga_latch(direccion and $7,valor); $7000..$70ff:namco_06xx_data_w(direccion and $ff,0,valor); $7100..$7100:namco_06xx_ctrl_w(0,valor); $8000..$87ff:begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $8800..$8bff,$9000..$93ff,$9800..$9bff:memoria[direccion]:=valor; $a000..$a005:galaga_starcontrol[direccion and $7]:=valor; $a007:main_screen.flip_main_screen:=(valor and 1)<>0; end; end; function galaga_getbyte(direccion:word):byte; begin case direccion of 0..$3fff,$8000..$8bff,$9000..$93ff,$9800..$9bff:galaga_getbyte:=memoria[direccion]; $6800..$6802,$6804,$6807:galaga_getbyte:=$3; //Leer DSW A y B $6803:galaga_getbyte:=$0; $6805,$6806:galaga_getbyte:=$2; $7000..$70ff:galaga_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:galaga_getbyte:=namco_06xx_ctrl_r(0); end; end; function galaga_sub_getbyte(direccion:word):byte; begin case direccion of $0..$3fff:galaga_sub_getbyte:=mem_snd[direccion]; $6800..$6802,$6804,$6807:galaga_sub_getbyte:=$3; //Leer DSW A y B $6803:galaga_sub_getbyte:=$0; $6805,$6806:galaga_sub_getbyte:=$2; $7000..$70ff:galaga_sub_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:galaga_sub_getbyte:=namco_06xx_ctrl_r(0); $8800..$8bff,$9000..$93ff,$9800..$9bff:galaga_sub_getbyte:=memoria[direccion]; end; end; function galaga_sub2_getbyte(direccion:word):byte; begin case direccion of $0..$3fff:galaga_sub2_getbyte:=mem_misc[direccion]; $6800..$6802,$6804,$6807:galaga_sub2_getbyte:=$3; //Leer DSW A y B $6803:galaga_sub2_getbyte:=$0; $6805,$6806:galaga_sub2_getbyte:=$2; $7000..$70ff:galaga_sub2_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:galaga_sub2_getbyte:=namco_06xx_ctrl_r(0); $8800..$8bff,$9000..$93ff,$9800..$9bff:galaga_sub2_getbyte:=memoria[direccion]; end; end; //DigDug procedure draw_sprites_digdug;inline; var nchar,f,atrib,a,b,c,d,flipx_v,flipy_v:byte; color,x:word; y:integer; flipx,flipy:boolean; begin for f:=0 to $3f do begin nchar:=memoria[$8b80+(f*2)]; color:=(memoria[$8b81+(f*2)] and $3f) shl 2; y:=memoria[$9381+(f*2)]-40+1; if y<=0 then y:=256+y; x:=memoria[$9380+(f*2)]-16-1; // sprites are buffered and delayed by one scanline atrib:=memoria[$9b80+(f*2)]; flipx:=(atrib and $02)<>0; flipy:=(atrib and $01)<>0; if (nchar and $80)=0 then begin //16x16 put_gfx_sprite_mask(nchar,color,flipx,flipy,1,$1f,$1f); actualiza_gfx_sprite(x,y,2,1); end else begin //32x32 flipx_v:=atrib and $02; flipy_v:=atrib and $01; a:=0 xor flipy_v xor flipx_v; b:=1 xor flipy_v xor flipx_v; c:=2 xor flipy_v xor flipx_v; d:=3 xor flipy_v xor flipx_v; nchar:=(nchar and $c0) or ((nchar and $3f) shl 2); put_gfx_sprite_mask_diff(nchar+a,color,flipx,flipy,1,$1f,$1f,16,0); put_gfx_sprite_mask_diff(nchar+b,color,flipx,flipy,1,$1f,$1f,16,16); put_gfx_sprite_mask_diff(nchar+c,color,flipx,flipy,1,$1f,$1f,0,0); put_gfx_sprite_mask_diff(nchar+d,color,flipx,flipy,1,$1f,$1f,0,16); actualiza_gfx_sprite_size(x,y,2,32,32); end; end; end; procedure update_video_digdug;inline; var color,nchar,pos:word; sx,sy,x,y:byte; begin for x:=0 to 27 do begin for y:=0 to 35 do begin sx:=29-x; sy:=y-2; if (sy and $20)<>0 then pos:=sx+((sy and $1f) shl 5) else pos:=sy+(sx shl 5); //Background if bg_repaint then begin nchar:=digdug_bg[pos or (bg_select shl 10)]; if bg_disable<>0 then color:=$f else color:=(nchar shr 4); put_gfx(x*8,y*8,nchar,(color or bg_color_bank) shl 2,3,2); end; //Chars if gfx[0].buffer[pos] then begin nchar:=memoria[$8000+pos]; color:=((nchar shr 4) and $0e) or ((nchar shr 3) and 2); put_gfx_trans(x*8,y*8,nchar and $7f,color shl 1,1,0); gfx[0].buffer[pos]:=false; end; end; end; actualiza_trozo(0,0,224,288,3,0,0,224,288,2); actualiza_trozo(0,0,224,288,1,0,0,224,288,2); draw_sprites_digdug; actualiza_trozo_final(0,0,224,288,2); end; procedure digdug_principal; var frame_m,frame_s1,frame_s2:single; f,scanline:word; begin init_controls(false,false,false,true); frame_m:=main_z80.tframes; frame_s1:=snd_z80.tframes; frame_s2:=sub_z80.tframes; scanline:=63; while EmuStatus=EsRuning do begin for f:=0 to 263 do begin //Main CPU main_z80.run(frame_m); frame_m:=frame_m+main_z80.tframes-main_z80.contador; //Sub CPU snd_z80.run(frame_s1); frame_s1:=frame_s1+snd_z80.tframes-snd_z80.contador; //Sub 2 CPU sub_z80.run(frame_s2); frame_s2:=frame_s2+sub_z80.tframes-sub_z80.contador; //IO's run_namco_53xx; if (f=scanline) then begin if sub2_nmi then sub_z80.pedir_nmi:=PULSE_LINE; scanline:=scanline+128; if (scanline>=272) then scanline:=63; end; if f=223 then begin if main_irq then main_z80.pedir_irq:=ASSERT_LINE; if sub_irq then snd_z80.pedir_irq:=ASSERT_LINE; update_video_digdug; end; end; if sound_status.hay_sonido then begin namco_playsound; play_sonido; end; eventos_galaga; video_sync; end; end; //Main CPU procedure digdug_putbyte(direccion:word;valor:byte); var mask,shift:byte; begin if (direccion<$4000) then exit; case direccion of $6800..$681f:namco_sound.registros_namco[direccion and $1f]:=valor; $6820..$6827:galaga_latch(direccion and $7,valor); $7000..$70ff:namco_06xx_data_w(direccion and $ff,0,valor); $7100..$7100:namco_06xx_ctrl_w(0,valor); $8000..$83ff:begin gfx[0].buffer[direccion and $3ff]:=true; memoria[direccion]:=valor; end; $8400..$8bff,$9000..$93ff,$9800..$9bff:memoria[direccion]:=valor; $a000..$a007:case (direccion and $7) of //port_w 0,1:begin // select background picture shift:=direccion and $7; mask:=1 shl shift; if ((bg_select and mask)<>((valor and 1) shl shift)) then begin bg_select:=(bg_select and not(mask)) or ((valor and 1) shl shift); bg_repaint:=true; end; end; 2:if (tx_color_mode<>(valor and 1)) then tx_color_mode:=valor and 1; // select alpha layer color mode 3:if (bg_disable<>(valor and 1)) then begin // "disable" background bg_disable:=valor and 1; bg_repaint:=true; end; 4,5:begin //background color bank shift:=direccion and $7; mask:=1 shl shift; if ((bg_color_bank and mask)<>((valor and 1) shl shift)) then begin bg_color_bank:=(bg_color_bank and not(mask)) or ((valor and 1) shl shift); bg_repaint:=true; end; end; 6:; // n.c. */ 7:main_screen.flip_main_screen:=(valor and 1)<>0; // FLIP */ end; $b800..$b840:memoria[direccion]:=valor; //eeprom end; end; function digdug_getbyte(direccion:word):byte; begin case direccion of 0..$3fff,$8000..$8bff,$9000..$93ff,$9800..$9bff:digdug_getbyte:=memoria[direccion]; $7000..$70ff:digdug_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:digdug_getbyte:=namco_06xx_ctrl_r(0); $b800..$b83f:digdug_getbyte:=memoria[direccion]; //eeprom end; end; //Sub1 CPU function digdug_sub_getbyte(direccion:word):byte; begin case direccion of $0..$3fff:digdug_sub_getbyte:=mem_snd[direccion]; $7000..$70ff:digdug_sub_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:digdug_sub_getbyte:=namco_06xx_ctrl_r(0); $8000..$8bff,$9000..$93ff,$9800..$9bff:digdug_sub_getbyte:=memoria[direccion]; $b800..$b83f:digdug_sub_getbyte:=memoria[direccion]; //eeprom end; end; //Sub2 CPU function digdug_sub2_getbyte(direccion:word):byte; begin case direccion of $0..$3fff:digdug_sub2_getbyte:=mem_misc[direccion]; $7000..$70ff:digdug_sub2_getbyte:=namco_06xx_data_r(direccion and $ff,0); $7100..$7100:digdug_sub2_getbyte:=namco_06xx_ctrl_r(0); $8000..$8bff,$9000..$93ff,$9800..$9bff:digdug_sub2_getbyte:=memoria[direccion]; $b800..$b83f:digdug_sub2_getbyte:=memoria[direccion]; //eeprom end; end; //Namco IO procedure namco_06xx_nmi; begin main_z80.pedir_nmi:=PULSE_LINE; end; function namco_51xx_io0:byte; begin namco_51xx_io0:=marcade.in0 and $f; end; function namco_51xx_io1:byte; begin namco_51xx_io1:=marcade.in0 shr 4; end; function namco_51xx_io2:byte; begin namco_51xx_io2:=marcade.in1 and $f; end; function namco_51xx_io3:byte; begin namco_51xx_io3:=marcade.in1 shr 4; end; function namco_53xx_r_r(port:byte):byte; begin case port of //DSW A+B 0:namco_53xx_r_r:=$9; // DIP A low 1:namco_53xx_r_r:=$9; // DIP A high 2:namco_53xx_r_r:=$4; // DIP B low 3:namco_53xx_r_r:=$2; // DIP B high end; end; function namco_53xx_k_r:byte; begin namco_53xx_k_r:=custom_mod shl 1; end; end.
unit uLog; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TLogProc = procedure (s : string); var FLogProc : TLogProc = nil; procedure SetLogProc (lp : TLogProc); procedure Log (s : string); implementation procedure SetLogProc (lp : TLogProc); begin FLogProc := lp; end; procedure Log (s : string); begin if Assigned (FLogProc) then FLogProc (s); end; end.
Unit F03; {Unit untuk mengurutkan buku dan mencari berdasarkan kategori yang diinput user} interface uses typelist,F13; procedure ngurutbuku (var Tbuku : List_Buku); {prosedur untuk mengurutkan buku-buku yang tersimpan dalam array secara leksikografis} procedure caribukukategori (var Tbuku : List_Buku); {prosedur untuk mencetak ke layar ID buku, nama buku, dan author buku untuk buku-buku yang sesuai dengan kategori inputan user} implementation procedure ngurutbuku (var Tbuku : List_Buku); {prosedur untuk mengurutkan buku-buku yang tersimpan dalam array secara leksikografis} {Kamus Lokal} var i,j,k : integer; stop : boolean; temps : string; tempi : integer; begin // dilakukan sorting for i:= 1 to Tbuku.Neff do begin for j:= i + 1 to Tbuku.Neff do begin stop := false ; // analisis kasus // ketika judul buku yang dibandingkan sama panjang if (length(Tbuku.listbuku[i].Judul_Buku)) = (length(Tbuku.listbuku[j].Judul_Buku)) then begin // inisialisasi k := 1 ; while (k <= length(Tbuku.listbuku[i].Judul_Buku)) and (stop=false) do begin // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih besar maka akan dilakukan swapping atau penukaran if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) > ord((Tbuku.listbuku[j].Judul_Buku)[k])) then begin // aksi penukaran Tempi := Tbuku.listbuku[i].ID_Buku ; Tbuku.listbuku[i].ID_Buku := Tbuku.listbuku[j].ID_Buku ; Tbuku.listbuku[j].ID_Buku := tempi ; Temps := Tbuku.listbuku[i].Judul_Buku ; Tbuku.listbuku[i].Judul_Buku := Tbuku.listbuku[j].Judul_Buku ; Tbuku.listbuku[j].Judul_Buku := temps ; Temps := Tbuku.listbuku[i].Author ; Tbuku.listbuku[i].Author := Tbuku.listbuku[j].Author ; Tbuku.listbuku[j].Author := temps ; Tempi := Tbuku.listbuku[i].Jumlah_Buku ; Tbuku.listbuku[i].Jumlah_Buku := Tbuku.listbuku[j].Jumlah_Buku ; Tbuku.listbuku[j].Jumlah_Buku := tempi ; Tempi := Tbuku.listbuku[i].Tahun_Penerbit ; Tbuku.listbuku[i].Tahun_Penerbit := Tbuku.listbuku[j].Tahun_Penerbit ; Tbuku.listbuku[j].Tahun_Penerbit := tempi ; Temps := Tbuku.listbuku[i].Kategori ; Tbuku.listbuku[i].Kategori := Tbuku.listbuku[j].Kategori ; Tbuku.listbuku[j].Kategori := temps ; stop := true ; // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih kecil maka tidak akan dilakukan swapping atau penukaran melainkan loop diberi sinyal untuk berhenti end else if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) < ord((Tbuku.listbuku[j].Judul_Buku)[k])) and (ord((Tbuku.listbuku[i].Judul_Buku)[k]) <> ord((Tbuku.listbuku[j].Judul_Buku)[k])) then begin // loop diberi sinyal untuk berhenti stop := true ; end ; // increment k := k + 1; end; // Ketika judul buku yang satu lebih kecil dari yang lain end else if (length(Tbuku.listbuku[i].Judul_Buku)) < (length(Tbuku.listbuku[j].Judul_Buku)) then begin // inisialisasi k := 1 ; while (k <= length(Tbuku.listbuku[i].Judul_Buku)) and (stop=false) do begin // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih besar maka akan dilakukan swapping atau penukaran if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) > ord((Tbuku.listbuku[j].Judul_Buku)[k])) then begin // aksi penukaran Tempi := Tbuku.listbuku[i].ID_Buku ; Tbuku.listbuku[i].ID_Buku := Tbuku.listbuku[j].ID_Buku ; Tbuku.listbuku[j].ID_Buku := tempi ; Temps := Tbuku.listbuku[i].Judul_Buku ; Tbuku.listbuku[i].Judul_Buku := Tbuku.listbuku[j].Judul_Buku ; Tbuku.listbuku[j].Judul_Buku := temps ; Temps := Tbuku.listbuku[i].Author ; Tbuku.listbuku[i].Author := Tbuku.listbuku[j].Author ; Tbuku.listbuku[j].Author := temps ; Tempi := Tbuku.listbuku[i].Jumlah_Buku ; Tbuku.listbuku[i].Jumlah_Buku := Tbuku.listbuku[j].Jumlah_Buku ; Tbuku.listbuku[j].Jumlah_Buku := tempi ; Tempi := Tbuku.listbuku[i].Tahun_Penerbit ; Tbuku.listbuku[i].Tahun_Penerbit := Tbuku.listbuku[j].Tahun_Penerbit ; Tbuku.listbuku[j].Tahun_Penerbit := tempi ; Temps := Tbuku.listbuku[i].Kategori ; Tbuku.listbuku[i].Kategori := Tbuku.listbuku[j].Kategori ; Tbuku.listbuku[j].Kategori := temps ; stop := true ; // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih kecil maka tidak akan dilakukan swapping atau penukaran melainkan loop diberi sinyal untuk berhenti end else if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) < ord((Tbuku.listbuku[j].Judul_Buku)[k])) and (ord((Tbuku.listbuku[i].Judul_Buku)[k]) <> ord((Tbuku.listbuku[j].Judul_Buku)[k])) then begin // loop diberi sinyal untuk berhenti stop := true ; end ; // increment k := k + 1; end; // jika karakter pertama pada judul-judul buku yang dibandingkan selalu memliki nilai ASCII yang sama sampai seluruh karakter selesai dibandingkan // ketika buku yang judulnya lebih panjang berada pada index yang lebih besar maka akan dilakukan swapping atau penukaran if (stop = false) and (k > length(Tbuku.listbuku[i].Judul_Buku)) then begin //aksi penukaran Tempi := Tbuku.listbuku[i].ID_Buku ; Tbuku.listbuku[i].ID_Buku := Tbuku.listbuku[j].ID_Buku ; Tbuku.listbuku[j].ID_Buku := tempi ; Temps := Tbuku.listbuku[i].Judul_Buku ; Tbuku.listbuku[i].Judul_Buku := Tbuku.listbuku[j].Judul_Buku ; Tbuku.listbuku[j].Judul_Buku := temps ; Temps := Tbuku.listbuku[i].Author ; Tbuku.listbuku[i].Author := Tbuku.listbuku[j].Author ; Tbuku.listbuku[j].Author := temps ; Tempi := Tbuku.listbuku[i].Jumlah_Buku ; Tbuku.listbuku[i].Jumlah_Buku := Tbuku.listbuku[j].Jumlah_Buku ; Tbuku.listbuku[j].Jumlah_Buku := tempi ; Tempi := Tbuku.listbuku[i].Tahun_Penerbit ; Tbuku.listbuku[i].Tahun_Penerbit := Tbuku.listbuku[j].Tahun_Penerbit ; Tbuku.listbuku[j].Tahun_Penerbit := tempi ; Temps := Tbuku.listbuku[i].Kategori ; Tbuku.listbuku[i].Kategori := Tbuku.listbuku[j].Kategori ; Tbuku.listbuku[j].Kategori := temps ; end; // Ketika judul buku yang satu lebih besar dari yang lain end else begin //inisialisasi k := 1 ; while (k <= length(Tbuku.listbuku[j].Judul_Buku)) and (stop=false) do begin // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih besar maka akan dilakukan swapping atau penukaran if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) > ord((Tbuku.listbuku[j].Judul_Buku)[k])) then begin // aksi penukaran Tempi := Tbuku.listbuku[i].ID_Buku ; Tbuku.listbuku[i].ID_Buku := Tbuku.listbuku[j].ID_Buku ; Tbuku.listbuku[j].ID_Buku := tempi ; Temps := Tbuku.listbuku[i].Judul_Buku ; Tbuku.listbuku[i].Judul_Buku := Tbuku.listbuku[j].Judul_Buku ; Tbuku.listbuku[j].Judul_Buku := temps ; Temps := Tbuku.listbuku[i].Author ; Tbuku.listbuku[i].Author := Tbuku.listbuku[j].Author ; Tbuku.listbuku[j].Author := temps ; Tempi := Tbuku.listbuku[i].Jumlah_Buku ; Tbuku.listbuku[i].Jumlah_Buku := Tbuku.listbuku[j].Jumlah_Buku ; Tbuku.listbuku[j].Jumlah_Buku := tempi ; Tempi := Tbuku.listbuku[i].Tahun_Penerbit ; Tbuku.listbuku[i].Tahun_Penerbit := Tbuku.listbuku[j].Tahun_Penerbit ; Tbuku.listbuku[j].Tahun_Penerbit := tempi ; Temps := Tbuku.listbuku[i].Kategori ; Tbuku.listbuku[i].Kategori := Tbuku.listbuku[j].Kategori ; Tbuku.listbuku[j].Kategori := temps ; stop := true ; // jika buku yang indexnya lebih kecil memiliki karakter pertama yang nilai ASCIInya lebih kecil maka tidak akan dilakukan swapping atau penukaran melainkan loop diberi sinyal untuk berhenti end else if (ord((Tbuku.listbuku[i].Judul_Buku)[k]) < ord((Tbuku.listbuku[j].Judul_Buku)[k])) and (ord((Tbuku.listbuku[i].Judul_Buku)[k]) <> ord((Tbuku.listbuku[k].Judul_Buku)[k])) then begin // loop diberi sinyal untuk berhenti stop := true ; end ; // increment k := k + 1; end; end; end; end; end; procedure caribukukategori (var Tbuku : List_Buku); {prosedur untuk mencetak ke layar ID buku, nama buku, dan author buku untuk buku-buku yang sesuai dengan kategori inputan user} {Kamus Lokal} var ikategori : string ; i : integer ; stop : Boolean ; count : integer ; begin // inisialisasi stop := false ; count := 0 ; // skema validasi kategori inputan user repeat write('Masukkan kategori: '); readln(ikategori); if (ikategori = 'sastra') or (ikategori = 'sains') or (ikategori = 'manga') or (ikategori = 'sejarah') or (ikategori = 'programming') then begin writeln('Hasil pencarian:'); stop := true ; end else // masukan user tidak valid begin writeln('Kategori ',ikategori,' tidak valid.'); end; until(stop = True); // looping untuk mencari buku dengan kategori yang sesuai dengan inputan user for i := 1 to Tbuku.Neff do begin // analisis kasus if ((Tbuku.listbuku[i].kategori) = ikategori) then begin // aksi yang dilakukan ketika kategori buku pada listbuku index ke-i sama dengan kategori yang diinginkan user writeln(Tbuku.listbuku[i].ID_Buku,' | ',Tbuku.listbuku[i].Judul_Buku,' | ',Tbuku.listbuku[i].Author); count := count + 1 ; end; end; // analisis kasus if (count = 0) then begin // aksi yang dilakukan ketika tidak ada buku yang kategorinya sesuai dengan kategori inputan user writeln('Tidak ada buku dalam kategori ini.') end; end; end.
unit UFormSpaceLimit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, siComp, UMainFOrm; type TfrmSpaceLimit = class(TForm) SeValue: TSpinEdit; cbSpaceType: TComboBox; lbType: TLabel; btnOK: TButton; btnCancel: TButton; siLang_frmSpaceLimit: TsiLang; procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCancelClick(Sender: TObject); private { Private declarations } public procedure AddSmallerThan; procedure AddLargerThan; public function getSpaceValue : Int64; end; const LabelType_Smaller = 'Smaller than'; LabelType_Larger = 'Larger than'; var frmSpaceLimit: TfrmSpaceLimit; implementation Uses UMyUtil; {$R *.dfm} { TfrmSpaceLimit } procedure TfrmSpaceLimit.AddLargerThan; begin lbType.Caption := siLang_frmSpaceLimit.GetText( 'lbBigThan' ); end; procedure TfrmSpaceLimit.AddSmallerThan; begin lbType.Caption := siLang_frmSpaceLimit.GetText( 'lbSmallThan' ); end; procedure TfrmSpaceLimit.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmSpaceLimit.btnOKClick(Sender: TObject); begin Close; ModalResult := mrOk; end; procedure TfrmSpaceLimit.FormShow(Sender: TObject); begin ModalResult := mrCancel; end; function TfrmSpaceLimit.getSpaceValue: Int64; begin Result := MySize.getSpaceValue( SeValue.Value, cbSpaceType.Text ); end; end.
{ Create a list of faces from OCO plugin and assign them randomly to selected NPC records according to race and gender. NPCs of unknown races (not in OCO) are skipped. NPCs with the same FormIDs as in OCO will receive their faces from OCO plugin. Hairs and eyes (and everything else) are not modified. } unit UserScript; const OCOFileName = 'Oblivion_Character_Overhaul.esp'; var slRace: TStringList; lOCOForms: TList; arNPC: array [0..10000] of IInterface; npccount: integer; //======================================================================================== function IsOCOnizedPlugin(aFileName: string): boolean; begin // add checks for plugins with correct OCO faces here using "or" // the more the merrier (bigger faces variety) Result := SameText(aFileName, OCOFileName); // or SameText(aFileName, 'SomeOtherMod.esp'); end; //======================================================================================== // build a list of npc records with correct OCO faces procedure CollectOCOnizedNPC; var lst: TList; i, j, idx: integer; race: string; plugin, npcs, npc: IInterface; begin npccount := 0; // iterate over all loaded mods in reverse order // so overriding records come first for i := FileCount - 1 downto 0 do begin plugin := FileByIndex(i); // check plugin name if IsOCOnizedPlugin(GetFileName(plugin)) then begin // get NPC_ group from plugin npcs := GroupBySignature(plugin, 'NPC_'); // iterate over all records for j := 0 to ElementCount(npcs) - 1 do begin npc := ElementByIndex(npcs, j); // build unique race + gender key string race := GetElementEditValues(npc, 'RNAM'); if race = '' then Continue; if GetElementNativeValues(npc, 'ACBS\Flags') and 1 > 0 then race := race + ' Female' else race := race + ' Male'; arNPC[npccount] := npc; // check if key string already exists, or add a new one idx := slRace.IndexOf(race); if idx = -1 then begin // list holding indexes if NPC records in array of race + gender lst := TList.Create; slRace.AddObject(race, lst); end else lst := TList(slRace.Objects[idx]); // add npc to array lst.Add(TObject(npccount)); // add FormID of npc record for a quick lookup later lOCOForms.Add(TObject(GetLoadOrderFormID(npc))); // increate array counter Inc(npccount); end; end; end; end; //======================================================================================== function Initialize: integer; begin // lookup list to races and genders slRace := TStringList.Create; // lookup list of FormIDs with OCO faces lOCOForms := TList.Create; CollectOCOnizedNPC; if npccount = 0 then begin MessageDlg(OCOFileName + ' is not loaded.', mtInformation, [mbOk], 0); Finalize; Result := 1; Exit; end; // initialize pseudo random numbers generator with the current time Randomize; end; //======================================================================================== function Process(e: IInterface): integer; var i, idx: integer; race: string; lst: TList; begin // skip anything but NPC_ records if Signature(e) <> 'NPC_' then Exit; // don't patch records in already OCOnized plugins if IsOCOnizedPlugin(GetFileName(e)) then Exit; // check if npc record has the same FormID as one of the OCOnized records idx := lOCOForms.IndexOf(TObject(GetLoadOrderFormID(e))); // if not, select random OCOnized NPC of the same race and gender if idx = -1 then begin race := GetElementEditValues(e, 'RNAM'); if race = '' then Exit; if GetElementNativeValues(e, 'ACBS\Flags') and 1 > 0 then race := race + ' Female' else race := race + ' Male'; idx := slRace.IndexOf(race); // skip unknown races if idx = -1 then Exit; lst := TList(slRace.Objects[idx]); idx := integer(lst[Random(lst.Count)]); end; // copy facegen data ElementAssign(ElementByPath(e, 'FaceGen Data'), LowInteger, ElementByPath(arNPC[idx], 'FaceGen Data'), False); ElementAssign(ElementByPath(e, 'FNAM'), LowInteger, ElementByPath(arNPC[idx], 'FNAM'), False); // just in case end; //======================================================================================== function Finalize: integer; begin // cleanup slRace.Free; lOCOForms.Free; end; end.
unit Main.DependencyInjectionContainer; interface procedure Execute_DependencyInjectionContainerDemo; implementation uses System.TypInfo, System.SysUtils, RTTI; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- type IDependency = interface ['{618030A2-DB17-4532-81D0-D5AA6F73DC66}'] procedure IntroduceYourself; end; TDependencyA = class(TInterfacedObject, IDependency) public procedure IntroduceYourself; end; TDependencyB = class(TInterfacedObject, IDependency) public procedure IntroduceYourself; end; TConsumer = class private FDependency: IDependency; public constructor Create(aDependency: IDependency); procedure ProcessUsingDependency; end; { TDependencyA } procedure TDependencyA.IntroduceYourself; begin WriteLn('Instance of type TDependencyA'); end; { TDependencyB } procedure TDependencyB.IntroduceYourself; begin WriteLn('Instance of type TDependencyB'); end; { TConsumer } constructor TConsumer.Create(aDependency: IDependency); begin FDependency := aDependency; end; procedure TConsumer.ProcessUsingDependency; begin if FDependency <> nil then FDependency.IntroduceYourself; end; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- type TDependencyContainer = class FInterfaceGUID: TGUID; FClass: TClass; public function Reg<T: IInterface>(C: TClass): T; function Resolve<T: IInterface>: T; end; function TDependencyContainer.Reg<T>(C: TClass): T; var data: PTypeData; begin data := System.TypInfo.GetTypeData(TypeInfo(T)); if ifHasGuid in data.IntfFlags then FInterfaceGUID := data.Guid else raise Exception.Create('Unsupported interface. GUID is required'); FClass := C; end; function TDependencyContainer.Resolve<T>: T; var ctx: TRttiContext; Obj: TObject; rttiType: TRttiType; CreateMethod: TRttiMethod; Value: TValue; data: PTypeData; begin data := System.TypInfo.GetTypeData(TypeInfo(T)); if ifHasGuid in data.IntfFlags then begin if data.Guid = FInterfaceGUID then begin ctx := TRttiContext.Create; rttiType := ctx.GetType(FClass.ClassInfo); if rttiType <> nil then begin CreateMethod := rttiType.GetMethod('Create'); Value := CreateMethod.Invoke(FClass, []); System.SysUtils.Supports(Value.AsInterface, data.Guid, Result); end; end else raise Exception.Create('Cant find Interface in Container'); end else raise Exception.Create('Unsupported interface. GUID is required'); end; // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- type TOptionAB = (Option_A_, Option_B_); TAppConfiguration = record ExecutionOption: TOptionAB; end; var GlobalAppConfiguration: TAppConfiguration = // ---- (ExecutionOption: Option_B_); GlobalDependencyContainer: TDependencyContainer; procedure DefineDependencies(); begin if GlobalAppConfiguration.ExecutionOption = Option_A_ then GlobalDependencyContainer.Reg<IDependency>(TDependencyA) else GlobalDependencyContainer.Reg<IDependency>(TDependencyB); end; procedure Execute_DependencyInjectionContainerDemo; var Dependency: IDependency; SomeConsumerObj: TConsumer; begin GlobalDependencyContainer := TDependencyContainer.Create; DefineDependencies(); Dependency := GlobalDependencyContainer.Resolve<IDependency>; SomeConsumerObj := TConsumer.Create(Dependency); SomeConsumerObj.ProcessUsingDependency; SomeConsumerObj.Free; GlobalDependencyContainer.Free; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, OYApplication, OYProgressForm, OYPackageF, OYPackage, OYProcessingInfoF, OYXmlConsumer, OYSyntaxView, ComCtrls; type TForm1 = class(TForm, IOYLinguineExecutionContext, IOYLinguineProcessingOptions) Label1: TLabel; Edit1: TEdit; Button1: TButton; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Memo1: TMemo; TabSheet3: TTabSheet; Memo2: TMemo; TabSheet4: TTabSheet; Memo3: TMemo; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private fIProgress : IOYProgress; fProgressForm : TOYProgressForm; protected // IOYLinguineExecutionContext function IProgress : IOYProgress; // IOYLinguineProcessingOptions function GetDefines : WideString; function GetSearchPaths : WideString; function IgnoreWhitespace : Boolean; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var package : IOYLinguineLanguagePackage; libName : String; info : IOYLinguineProcessingInfo; consumer : TOYXmlTransientTree; iconsumer : IOYLinguineConsumer; lb : TSyntaxListBox; high : IOYSyntaxHighlight; b : Boolean; sz: Integer; i : Integer; begin // load Delphi Object Pascal parsing lirary DLL libName := ExtractFilePath(Application.ExeName) + '/bop130.llp'; package := OYCreateInstance(libName, self); // create simple XML consumer that will capture abstract // syntax tree (AST) while parsing consumer := TOYXmlTransientTree.Create(); iconsumer := consumer; // parse source file into XML b := package.ProduceFullXmlTreeForUrl(Edit1.Text, self, self, consumer, info); if not b then begin // show text of error Memo1.Lines.Clear; memo1.Lines.add('Error: ' + info.GetReason + '. Please configure search path.'); ShowMessage('Error: ' + info.GetReason); end else begin // dump lex into memo Memo2.Lines.Clear; Memo2.Lines.BeginUpdate; Memo2.Lines.add('Lex tokens <t> - ' + IntToStr(package.ILexSchema.GetCount)); for i := 0 to package.ILexSchema.GetCount - 1 do begin Memo2.Lines.add(IntToStr(package.ILexSchema.GetId(i)) + ': ' + package.ILexSchema.GetName(i)); end; Memo2.Lines.EndUpdate; // dump yacc Memo3.Lines.Clear; Memo3.Lines.BeginUpdate; Memo3.Lines.add('YACC rules <r> - ' + IntToStr(package.IYaccSchema.GetCount)); for i := 0 to package.IYaccSchema.GetCount - 1 do begin Memo3.Lines.add(IntToStr(package.IYaccSchema.GetId(i)) + ': ' + package.IYaccSchema.GetName(i) + ' = ' + package.IYaccSchema.GetSemantics(i)); end; Memo3.Lines.EndUpdate; // dump AST into memo Memo1.Lines.Clear; memo1.Lines.add(consumer.Xml); end; // parse again and create syntax highlihgter package.CreateSyntaxHighlighterForUrl(Edit1.Text, self, self, high, info); // create syntax view and load the file into it lb := TSyntaxListBox.Create(self, high); lb.Font.Name := 'Courier New'; lb.Parent := TabSheet2; lb.Align := alClient; lb.LoadFromFile(Edit1.text); end; procedure TForm1.FormCreate(Sender: TObject); procedure _AttachProgressWidget; var aIHotSwap : IOYHotSwapProgress; begin if Succeeded(fIProgress.QueryInterface(IOYHotSwapProgress, aIHotSwap)) then begin fProgressForm := TOYProgressForm.Create(Self); if not aIHotSwap.AttachWidget(fProgressForm) then begin fProgressForm.Free; fProgressForm := nil; end else begin fProgressForm.Parent := nil; fProgressForm.ParentWindow := Handle; end; end; end; begin fIProgress := OYProgressForm.OYCreateInstance(nil); Edit1.text := ExtractFilePath(Application.ExeName) + '..\source\sample\unit1.pas'; end; function TForm1.IProgress : IOYProgress; begin Result := fIProgress; end; function TForm1.GetDefines : WideString; begin Result := ''; end; function TForm1.GetSearchPaths : WideString; begin Result := ExtractFilePath(Application.ExeName) + '..\source\inc\'; end; function TForm1.IgnoreWhitespace : Boolean; begin Result := True; end; end.
UNIT DanFW.Data.Export; INTERFACE USES System.Sysutils, System.Classes, Vcl.Dialogs, DB, Winapi.Windows; FUNCTION ExportarCSV(Adataset: Tdataset): Integer; FUNCTION ExportarHTML(Adataset: Tdataset): Integer; FUNCTION ExportarTXT(Adataset: Tdataset): Integer; IMPLEMENTATION CONST HTMLCSS_EstiloSimples: STRING = '<style>' + '#hor-minimalist-b' + #13#10 + '{' + #13#10 + ' font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;' + #13#10 + ' font-size: 12px;' + #13#10 + ' background: #fff;' + #13#10 + ' margin: 45px;' + #13#10 + ' width: 480px;' + #13#10 + ' border-collapse: collapse;' + #13#10 + ' text-align: left;' + #13#10 + '}' + #13#10 + '#hor-minimalist-b th' + #13#10 + '{' + #13#10 + ' font-size: 14px;' + #13#10 + ' font-weight: normal;' + #13#10 + ' color: #039;' + #13#10 + ' padding: 10px 8px;' + #13#10 + ' border-bottom: 2px solid #6678b1;' + #13#10 + '}' + #13#10 + '#hor-minimalist-b td' + #13#10 + '{' + #13#10 + ' border-bottom: 1px solid #ccc;' + #13#10 + ' color: #669;' + #13#10 + ' padding: 6px 8px;' + #13#10 + '}' + #13#10 + '#hor-minimalist-b tbody tr:hover td' + #13#10 + '{' + #13#10 + ' color: #009;' + #13#10 + '}' + '</style>'; HTMLCSS_EstiloNewsPaper: STRING = '<style>' + '' + #13#10 + '#newspaper-a' + #13#10 + '{' + #13#10 + ' font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;' + #13#10 + ' font-size: 12px;' + #13#10 + ' margin: 45px;' + #13#10 + ' width: 480px;' + #13#10 + ' text-align: left;' + #13#10 + ' border-collapse: collapse;' + #13#10 + ' border: 1px solid #69c;' + #13#10 + '}' + #13#10 + '#newspaper-a th' + #13#10 + '{' + #13#10 + ' padding: 12px 17px 12px 17px;' + #13#10 + ' font-weight: normal;' + #13#10 + ' font-size: 14px;' + #13#10 + ' color: #039;' + #13#10 + ' border-bottom: 1px dashed #69c;' + #13#10 + '}' + #13#10 + '#newspaper-a td' + #13#10 + '{' + #13#10 + ' padding: 7px 17px 7px 17px;' + #13#10 + ' color: #669;' + #13#10 + '}' + #13#10 + '#newspaper-a tbody tr:hover td' + #13#10 + '{' + #13#10 + ' color: #339;' + #13#10 + ' background: #d0dafd;' + #13#10 + '}' + '</style>'; FUNCTION GetFieldValueInText(Afield: TField): STRING; BEGIN { detectar los valores y convertirlos a texto } CASE Afield.DataType OF FtUnknown: ; FtString: Result := Afield.Text; FtSmallint, FtInteger, FtWord: Result := Afield.Text; FtBoolean: Result := Afield.Text; FtFloat: Result := Afield.AsFloat.ToString; FtCurrency: Result := Afield.Text; // ftBCD: ; FtDate: Result := Afield.Text; FtTime: Result := Afield.Text; FtDateTime: Result := Afield.Text; FtBytes: Result := Afield.Text; // ftVarBytes: ; // ftAutoInc: ; // ftBlob: ; // ftMemo: ; // ftGraphic: ; // ftFmtMemo: ; // ftParadoxOle: ; // ftDBaseOle: ; // ftTypedBinary: ; // ftCursor: ; // ftFixedChar: ; FtWideString: Result := Afield.Text; FtLargeint: Result := Afield.Text; // ftADT: ; FtArray: Result := '[array]'.QuotedString; // ftReference: ; // ftDataSet: ; // ftOraBlob: ; // ftOraClob: ; // ftVariant: result := ; // ftInterface: ; // ftIDispatch: ; // ftGuid: ; // ftTimeStamp: ; // ftFMTBcd: ; // ftFixedWideChar: ; // ftWideMemo: ; // ftOraTimeStamp: ; // ftOraInterval: ; // ftLongWord: ; // ftShortint: ; // ftByte: ; // ftExtended: ; // ftConnection: ; // ftParams: ; // ftStream: ; // ftTimeStampOffset: ; FtObject: Result := '[obj]'.QuotedString; FtSingle: Result := Afield.AsFloat.ToString; ELSE Result := ''.QuotedString; END; END; /// <summary> Generar un archivo CSV del dataset especificado </summary> /// <param name="Adataset"> /// una tabla o query /// </param> FUNCTION ExportarCSV(Adataset: Tdataset): Integer; VAR Dlg: TSaveDialog; Cabecera: STRING; Dato: STRING; Datos: Tstringlist; Cursor: TBookmark; I: Integer; BEGIN Dlg := TSaveDialog.Create(NIL); Dlg.Title := 'Exportar datos a...'; Dlg.Filter := 'Archivos de texto (*.csv)|*.csv'; Dlg.FilterIndex := 0; Dlg.FileName := 'Datos_' + FormatDateTime('ddmmyyyyHHnnss', Now); IF Dlg.Execute THEN BEGIN { bloquear dataset para exportar } WITH Adataset DO BEGIN Cursor := GetBookmark; { recordar posicion } First; DisableControls; { generar cabecera de datos } Cabecera := Adataset.FieldDefList.CommaText.Replace(',', ';'); { volcar contenido } Datos := Tstringlist.Create; { cabecera } Datos.Add(Cabecera); { exportar los datos en linea } First; REPEAT Dato := ''; FOR I := 0 TO Fields.Count - 1 DO BEGIN { concatenar datos } IF I = 0 THEN Dato := GetFieldValueInText(Fields[I]) ELSE Dato := Dato + ';' + GetFieldValueInText(Fields[I]); END; { volcar } Datos.Add(Dato); Next; UNTIL Eof = True; { cerrar volcado } Datos.SaveToFile(ChangeFileExt(Dlg.FileName, '.csv')); Datos.Free; IF BookmarkValid(Cursor) THEN Bookmark := Cursor; FreeBookmark(Cursor); EnableControls; END; END; { exportar datos de un dataset } Dlg.Free; Result := 0; END; FUNCTION ExportarHTML(Adataset: Tdataset): Integer; VAR Dlg: TSaveDialog; Dato: STRING; Datos: Tstringlist; Cursor: TBookmark; I: Integer; CONST Startrow: STRING = '<tr>'; Endrow: STRING = '</tr>'; Startheader: STRING = '<th>'; Endheader: STRING = '</th>'; Startdata: STRING = '<td>'; Enddata: STRING = '</td>'; BEGIN Dlg := TSaveDialog.Create(NIL); Dlg.Title := 'Exportar datos a...'; Dlg.Filter := 'Archivos de HTML (*.html)|*.html'; Dlg.FilterIndex := 0; Dlg.FileName := 'Datos_' + FormatDateTime('ddmmyyyyHHnnss', Now); IF Dlg.Execute THEN BEGIN { bloquear dataset para exportar } WITH Adataset DO BEGIN Cursor := GetBookmark; { recordar posicion } First; DisableControls; { generar cabecera de datos } { volcar contenido } Datos := Tstringlist.Create; Datos.Text := HTMLCSS_EstiloSimples; Datos.Add('<table id="hor-minimalist-b">'); { inicio de tabla } Datos.Add(Startrow); { cabecera } FOR I := 0 TO FieldDefs.Count - 1 DO BEGIN Datos.Add(Startheader + FieldDefs[I].Name + Endheader); END; Datos.Add(Endrow); { exportar los datos en linea } First; REPEAT Dato := ''; Datos.Add(Startrow); FOR I := 0 TO Fields.Count - 1 DO BEGIN { concatenar datos } IF I = 0 THEN Dato := Startdata + GetFieldValueInText(Fields[I]) + Enddata ELSE Dato := Dato + Startdata + GetFieldValueInText(Fields[I]) + Enddata; END; { volcar } Datos.Add(Dato); Datos.Add(Endrow); Next; UNTIL Eof = True; { cerrar volcado } Datos.Add('</table>'); { cierre de tabla } Datos.SaveToFile(ChangeFileExt(Dlg.FileName, '.html')); Datos.Free; IF BookmarkValid(Cursor) THEN Bookmark := Cursor; FreeBookmark(Cursor); EnableControls; END; END; { exportar datos de un dataset } Dlg.Free; Result := 0; END; FUNCTION ExportarTXT(Adataset: Tdataset): Integer; VAR Dlg: TSaveDialog; Cabecera: STRING; Dato: STRING; Datos: Tstringlist; Cursor: TBookmark; I: Integer; BEGIN Dlg := TSaveDialog.Create(NIL); Dlg.Title := 'Exportar datos a...'; Dlg.Filter := 'Archivos de texto (*.txt)|*.txt'; Dlg.FilterIndex := 0; Dlg.FileName := 'Datos_' + FormatDateTime('ddmmyyyyHHnnss', Now); IF Dlg.Execute THEN BEGIN { bloquear dataset para exportar } WITH Adataset DO BEGIN Cursor := GetBookmark; { recordar posicion } First; DisableControls; { generar cabecera de datos } //Cabecera := Adataset.FieldDefList.CommaText.Replace(',', ';'); { volcar contenido } Datos := Tstringlist.Create; { cabecera } //Datos.Add(Cabecera); { exportar los datos en linea } First; REPEAT Dato := ''; FOR I := 0 TO Fields.Count - 1 DO BEGIN { concatenar datos } IF I = 0 THEN Dato := GetFieldValueInText(Fields[I]) ELSE Dato := Dato + '' + GetFieldValueInText(Fields[I]); END; { volcar } Datos.Add(Dato); Next; UNTIL Eof = True; { cerrar volcado } Datos.SaveToFile(ChangeFileExt(Dlg.FileName, '.txt')); Datos.Free; IF BookmarkValid(Cursor) THEN Bookmark := Cursor; FreeBookmark(Cursor); EnableControls; END; END; { exportar datos de un dataset } Dlg.Free; Result := 0; end; END.
{$i deltics.pointers.inc} unit Deltics.Pointers.Memory; interface uses Deltics.Pointers.Types; type Memory = class public class procedure Alloc(var aPointer: Pointer; const aNumBytes: Integer); {$ifdef InlineMethods} inline; {$endif} class procedure AllocCopy(var aPointer: Pointer; const aNumBytes: Integer; const aSource: Pointer); //{$ifdef InlineMethods} inline; {$endif} class procedure AllocZeroed(var aPointer: Pointer; const aNumBytes: Integer); {$ifdef InlineMethods} inline; {$endif} class function ByteOffset(const aPointer: Pointer; const aOffset: Integer): Pointer; class procedure Copy(const aSource: Pointer; const aDest: Pointer; aNumBytes: Integer); class procedure Free(var aPointer: Pointer); overload; {$ifdef InlineMethods} inline; {$endif} class procedure Free(aPointers: PPointerArray); overload; class procedure Randomize(const aDest: Pointer; const aNumBytes: Integer); overload; class procedure Randomize(const aDest: Pointer; const aNumBytes: Integer; const aMin: Byte); overload; class procedure Randomize(const aDest: Pointer; const aNumBytes: Integer; const aMin, aMax: Byte); overload; class procedure Zeroize(const aDest: Pointer; const aNumBytes: Integer); overload; {$ifdef InlineMethods} inline; {$endif} end; implementation uses Classes, {$ifdef 64BIT} {$ifdef MSWINDOWS} Windows, {$else} {$message fatal '64-bit platform not supported'} {$endif} {$endif} Deltics.Pointers; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } procedure CopyBytes(const aSource; var aDest; aCount: Integer); {$ifdef 64BIT} begin CopyMemory(@aDest, @aSource, aCount); end; {$else} asm // ECX = Count // EAX = Const Source // EDX = Var Dest // If there are no bytes to copy, just quit // altogether; there's no point pushing registers. Cmp ECX,0 Je @JustQuit // Preserve the critical Delphi registers. push ESI push EDI // Move Source into ESI (SOURCE register). // Move Dest into EDI (DEST register). // This might not actually be necessary, as I'm not using MOVsb etc. // I might be able to just use EAX and EDX; // there could be a penalty for not using ESI, EDI, but I doubt it. // This is another thing worth trying! Mov ESI, EAX Mov EDI, EDX // The following loop is the same as repNZ MovSB, but oddly quicker! @Loop: Mov AL, [ESI] // get a source byte Inc ESI // bump source address Mov [EDI], AL // Put it into the destination Inc EDI // bump destination address Dec ECX // Dec ECX to note how many we have left to copy Jnz @Loop // If ECX <> 0, then loop. // Pop the critical Delphi registers that we've altered. pop EDI pop ESI @JustQuit: end; {$endif} { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Alloc(var aPointer: Pointer; const aNumBytes: Integer); begin GetMem(aPointer, aNumBytes); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.AllocCopy(var aPointer: Pointer; const aNumBytes: Integer; const aSource: Pointer); begin GetMem(aPointer, aNumBytes); CopyBytes(aSource^, aPointer^, aNumBytes); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.AllocZeroed(var aPointer: Pointer; const aNumBytes: Integer); begin GetMem(aPointer, aNumBytes); FillChar(aPointer^, aNumBytes, 0); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class function Memory.ByteOffset(const aPointer: Pointer; const aOffset: Integer): Pointer; begin result := Pointer(IntPointer(aPointer) + Cardinal(aOffset)); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Copy(const aSource: Pointer; const aDest: Pointer; aNumBytes: Integer); begin CopyBytes(aSource^, aDest^, aNumBytes); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Free(var aPointer: Pointer); begin FreeMem(aPointer); aPointer := NIL; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Free(aPointers: PPointerArray); var i: Integer; begin for i := Low(aPointers) to High(aPointers) do begin FreeMem(aPointers[i]^); aPointers[i]^ := NIL; end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Randomize(const aDest: Pointer; const aNumBytes: Integer); var i: Integer; intPtr: PInteger; bytePtr: PByte absolute intPtr; bytesLeft: Integer; begin intPtr := PInteger(aDest); for i := 1 to (aNumBytes div 4) do begin intPtr^ := Random(MaxInt); Inc(intPtr); end; bytesLeft := aNumBytes mod 4; for i := 1 to bytesLeft do begin bytePtr^ := Byte(Random(255)); Inc(bytePtr); end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Randomize(const aDest: Pointer; const aNumBytes: Integer; const aMin: Byte); begin Randomize(aDest, aNumBytes, aMin, 255); end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Randomize(const aDest: Pointer; const aNumBytes: Integer; const aMin, aMax: Byte); var i: Integer; range: Integer; bytePtr: PByte; begin bytePtr := aDest; range := aMax - aMin + 1; for i := 1 to aNumBytes do begin bytePtr^ := Byte(Random(range)) + aMin; Inc(bytePtr); end; end; { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - } class procedure Memory.Zeroize(const aDest: Pointer; const aNumBytes: Integer); begin FillChar(aDest^, aNumBytes, 0); end; end.
{$SCOPEDENUMS ON} unit classGPXUtils; interface uses System.SysUtils; type TStringNotifyEvent = procedure (Sender: TObject; aMessage: string); TGPXFunction = (rename); TGPXFunctions = set of TGPXFunction; TGPXFileOption = (incDate, incName, incCreator, incOriginalName); TGPXFileOptions = set of TGPXFileOption; TExceptionProc = reference to procedure(E: Exception); TStringProc = reference to procedure(S : string); TGPXFileRenamer = class private fOptions : TGPXFileOptions; fOnMessage: TStringNotifyEvent; fCreator: string; fActivityName: string; fActivityDate: TDateTime; fTargetFolder: string; function GetIncCreator: boolean; function GetIncDate: boolean; function GetIncName: boolean; function GetIncOriginalName: boolean; procedure SetIncCreator(const Value: boolean); procedure SetIncDate(const Value: boolean); procedure SetIncName(const Value: boolean); procedure SetIncOriginalName(const Value: boolean); public property TargetFolder: string read fTargetFolder write fTargetFolder; property OnMessage: TStringNotifyEvent read fOnMessage write fOnMessage; property Options: TGPXFileOptions read fOptions write fOptions; property incDate: boolean read GetIncDate write SetIncDate; property incName: boolean read GetIncName write SetIncName; property IncCreator: boolean read GetIncCreator write SetIncCreator; property IncOriginalName: boolean read GetIncOriginalName write SetIncOriginalName; function GetNewName(const aInputFileName: string; const aTargetFolder: string): string; function RenameGPXFile(const aInputFileName: string; const aTargetFolder: string): string; function CopyGPXFile(const aInputFileName: string; const aTargetFolder: string; Options: TGPXFileOptions): boolean; property ActivityDate: TDateTime read fActivityDate; property ActivityName: string read fActivityName; property Creator: string read fCreator; end; TGPXFolderRenamer = class private fFolderPath: string; public property FolderPath: string read fFolderPath write fFolderPath; function Execute(aFolderPath: string; const aTargetFolderPath: string; Options: TGPXFileOptions; onLog: TStringProc; onError: TExceptionProc; OnMessage: TStringNotifyEvent): boolean; end; implementation uses System.IOUtils, OmniXML, OmniXMLUtils, System.DateUtils ; const FILE_MASK = '*.gpx'; CHAR_SEP = '_'; { TGPXFolderRenamer } function TGPXFolderRenamer.Execute(aFolderPath: string; const aTargetFolderPath: string; Options: TGPXFileOptions; onLog: TStringProc; onError: TExceptionProc; OnMessage: TStringNotifyEvent): boolean; var R : Integer; SR : TSearchRec; FileRenamer: TGPXFileRenamer; aFilename, NewFilename, aTargetFolder: string; begin try if aFolderPath <> EmptyStr then fFolderPath := aFolderPath; if aTargetFolderPath <> EmptyStr then aTargetFolder := aTargetFolderPath else aTargetFolder := fFolderPath; if not TDirectory.Exists(fFolderPath) then EXIT(False); FileRenamer := TGPXFileRenamer.Create; try FileRenamer.Options := Options; FileRenamer.OnMessage := OnMessage; R := System.SysUtils.FindFirst(TPath.Combine(fFolderPath, '*.gpx'), faAnyFile, SR); try if R = 0 then repeat aFilename := TPath.Combine(fFolderPath, SR.Name); NewFilename := FileRenamer.RenameGPXFile(aFileName, aTargetFolder); // logging if assigned(onLog) then begin if NewFileName = aFileName then onLog(Format('%s not renamed', [aFileName])) else onLog(Format('%s => %s', [aFilename, NewFilename])); end; until FindNext(SR) <> 0; finally FindClose(SR); end; finally FileRenamer.Free; end; except on e:Exception do if assigned(onError) then onError(E) else raise; end; end; { TGPXFileRenamer } function TGPXFileRenamer.CopyGPXFile(const aInputFileName: string; const aTargetFolder: string; Options: TGPXFileOptions): boolean; var aNewName: string; begin aNewName := GetNewName(aInputFilename, aTargetFolder); if aNewName <> aInputFileName then begin TFile.Copy(aInputFileName, aNewName); // set the date of the file to the date of the activity if (TGPXFileOption.incDate in fOptions) then FileSetDate(aNewName, DateTimeToFileDate(fActivityDate)); result := TRUE; end else result := FALSE; end; function TGPXFileRenamer.GetIncCreator: boolean; begin result := TGPXFileOption.incCreator in fOptions; end; function TGPXFileRenamer.GetIncDate: boolean; begin result := TGPXFileOption.incDate in fOptions; end; function TGPXFileRenamer.GetIncName: boolean; begin result := TGPXFileOption.incName in fOptions; end; function TGPXFileRenamer.GetIncOriginalName: boolean; begin result := TGPXFileOption.incOriginalName in fOptions; end; function TGPXFileRenamer.GetNewName(const aInputFileName: string; const aTargetFolder: string): string; var xmlDoc: IXMLDocument; Root: IXMLElement; Creator: IXMLAttr; Meta, Time, Trk, aName: IXMLNode; HasTime, HasName, HasCreator: boolean; begin try result := aInputFileName; HasTime := false; HasName := false; HasCreator := false; fTargetFolder := aTargetFolder; if fTargetFolder = EmptyStr then fTargetFolder := TPath.GetDirectoryName(aInputFilename); fCreator := ''; fActivityDate := FileDateToDateTime(FileAge(aInputFileName)); fActivityName := ''; result := ''; // this is where we crack open the file and get the relevant node values // and then construct the new filename xmlDoc := CreateXMLDoc; try xmlDoc.Load(aInputFilename); if not assigned(xmlDoc.DocumentElement) then raise Exception.Create('XML document is empty'); if not assigned(xmlDoc.DocumentElement) then raise Exception.Create('XML document is empty'); if assigned(fOnMessage) then fOnMessage(Self, 'Root tag: ' + xmlDoc.DocumentElement.NodeName); Root := xmlDoc.DocumentElement; Creator := Root.GetAttributeNode('creator'); if assigned(Creator) then begin if assigned(fOnMessage) then fOnMessage(self, 'Creator = ' + Creator.Value); HasCreator := True; end; Meta := Root.SelectSingleNode('metadata'); if assigned(Meta) then begin Time := Meta.SelectSingleNode('time'); if assigned(Time) then begin HasTime := True; if assigned(fOnMessage) then fOnMessage(self, Time.NodeName + ' = ' + Time.Text.ToLower + ' (' + Time.XML + ')'); end else if assigned(fOnMessage) then fOnMessage(self, 'Time node not found'); end else if assigned(fOnMessage) then fOnMessage(self, 'Metadata node not found'); Trk := Root.SelectSingleNode('trk'); if assigned(Trk) then begin aName := Trk.SelectSingleNode('name'); if assigned(aName) then begin HasName := True; if assigned(fOnMessage) then fOnMessage(self, aName.NodeName + ' = ' + aName.Text + ' (' + aName.XML + ')'); end else if assigned(fOnMessage) then fOnMessage(Self, 'Name node not found'); end else if assigned(fOnMessage) then fOnMessage(Self, 'Trk not found'); finally xmlDoc := nil; end; if HasTime and (TGPXFileOption.incDate in FOptions) then begin result := result + Time.Text.ToLower; fActivityDate := ISO8601ToDate(Time.text); end; if HasName and (TGPXFileOption.incName in fOptions) then begin fActivityName := aName.Text; if result <> EmptyStr then result := result + CHAR_SEP; result := result + aName.Text; end; if HasCreator and (TGPXFileOption.incCreator in fOptions) then begin fCreator := Creator.Value; if result <> EmptyStr then result := result + CHAR_SEP; result := result + Creator.Value; end; if (TGPXFileOption.incOriginalName in fOptions) then begin if result <> EmptyStr then result := result + CHAR_SEP; result := result + TPath.GetFileNameWithoutExtension(aInputFileName); // is Strava's activity ID I think end; // add the path and the .gpx extension result := TPath.Combine(fTargetFolder, TPath.ChangeExtension(result, '.gpx')); if assigned(fOnMessage) then fOnMessage(self, 'New Filename = ' + result); except on e:Exception do begin result := aInputFileName; if assigned(fOnMessage) then fOnMessage(self, Format('Error %s getting new name for %s', [e.Message, aInputFileName])); end; end; end; function TGPXFileRenamer.RenameGPXFile(const aInputFileName: string; const aTargetFolder: string): string; begin result := GetNewName(aInputFilename, aTargetFolder); if not RenameFile(aInputFilename, result) then result := aInputFilename; // set the date of the file to the date of the activity if (TGPXFileOption.incDate in fOptions) then FileSetDate(result, DateTimeToFileDate(fActivityDate)); end; procedure TGPXFileRenamer.SetIncCreator(const Value: boolean); begin if Value then Include(fOptions, TGPXFileOption.incCreator) else Exclude(fOptions, TGPXFileOption.incCreator); end; procedure TGPXFileRenamer.SetIncDate(const Value: boolean); begin if Value then Include(fOptions, TGPXFileOption.incDate) else Exclude(fOptions, TGPXFileOption.incDate); end; procedure TGPXFileRenamer.SetIncName(const Value: boolean); begin if Value then Include(fOptions, TGPXFileOption.incName) else Exclude(fOptions, TGPXFileOption.incName); end; procedure TGPXFileRenamer.SetIncOriginalName(const Value: boolean); begin if Value then Include(fOptions, TGPXFileOption.incOriginalName) else Exclude(fOptions, TGPXFileOption.incOriginalName); end; end.
unit zstreamext; {$mode delphi} interface uses Classes, SysUtils, zstream; type TCompressionstreamWithPositionSupport=class(Tcompressionstream) private public function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; end; implementation resourcestring rsASeekWasDoneForAnotherPurpose = 'A seek was done for another purpose than getting the position'; function TcompressionstreamWithPositionSupport.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin if (origin=soCurrent) and (offset=0) then result:=raw_written //fsource.position else raise exception.create(rsASeekWasDoneForAnotherPurpose); end; end.
program Exercicio_3; type Ivetor = array[1..3] of integer; var v : Ivetor; j : integer; {Swap de variaveis básico} procedure troca_variaveis(var a, b: integer); var temp : integer; begin temp := a; a := b; b := temp; writeln('Trocado: ', b, ' por ', a); end; { Algoritmo bubble sort para ordenação de vetores } procedure BubbleSort(var vetor : Ivetor); var trocado : boolean; i : integer; begin repeat trocado := false; for i := 1 to 2 do begin if vetor[i] > vetor[i+1] then begin troca_variaveis(vetor[i], vetor[i+1]); trocado := true; end; end; until (not trocado); end; {Programa principal} begin for j := 1 to 3 do begin write('Digite o valor ', j,' : '); readln(v[j]); end; { Reorganizar vetor } BubbleSort(v); {Exibindo valores na ordem crescente} writeln('Exibindo em ordem Crescente'); for j := 1 to 3 do begin write(v[j], ' '); end; end.
unit FFreeNotifications; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Messaging, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FBase, UBase, USampleClasses; type TFrameFreeNotifications = class(TFrameBase) ButtonCreateObjects: TButton; ButtonFreeFirst: TButton; ButtonFreeSecond: TButton; procedure ButtonCreateObjectsClick(Sender: TObject); procedure ButtonFreeFirstClick(Sender: TObject); procedure ButtonFreeSecondClick(Sender: TObject); private { Private declarations } FObject1, FObject2: TFreeNotificationObject; procedure FreeNotificationListener(const Sender: TObject; const M: TMessage); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.fmx} procedure TFrameFreeNotifications.ButtonCreateObjectsClick(Sender: TObject); begin ButtonCreateObjects.Enabled := False; ButtonFreeFirst.Enabled := True; ButtonFreeSecond.Enabled := True; { Create two objects. } FObject1 := TFreeNotificationObject.Create(nil, 'Object1'); FObject2 := TFreeNotificationObject.Create(nil, 'Object2'); { Enable free notifications for both objects. Because we subscribed to the TFreeNotification message in the constructor, we will get notified when these objects are destroyed. } FObject1.EnableFreeNotification; FObject2.EnableFreeNotification; Log('----------------------------------------------------'); Log('Created two objects and enabled free notifications for both objects.'); Log(' * TFreeNotificationObject.InstanceCount = %d', [TFreeNotificationObject.InstanceCount]); Log(''); end; procedure TFrameFreeNotifications.ButtonFreeFirstClick(Sender: TObject); begin ButtonFreeFirst.Enabled := False; Log('About to free the first object. This will result in a TFreeNotification message.'); { Because we subscribed to the TFreeNotification message, freeing this object will send a notification message. Note that we need to set the reference to nil to really free the object on ARC platforms. } FreeAndNil(FObject1); Log('Completed freeing the first object.'); Log(' * TFreeNotificationObject.InstanceCount = %d', [TFreeNotificationObject.InstanceCount]); Log(''); if (TFreeNotificationObject.InstanceCount = 0) then ButtonCreateObjects.Enabled := True; end; procedure TFrameFreeNotifications.ButtonFreeSecondClick(Sender: TObject); begin ButtonFreeSecond.Enabled := False; Log('About to free the second object. This will result in a TFreeNotification message.'); { Because we subscribed to the TFreeNotification message, freeing this object will send a notification message. Note that we need to set the reference to nil to really free the object on ARC platforms. } FreeAndNil(FObject2); Log('Completed freeing the second object.'); Log(' * TFreeNotificationObject.InstanceCount = %d', [TFreeNotificationObject.InstanceCount]); Log(''); if (TFreeNotificationObject.InstanceCount = 0) then ButtonCreateObjects.Enabled := True; end; constructor TFrameFreeNotifications.Create(AOwner: TComponent); begin inherited; { Subscribe to the TFreeNotification message to get notified when objects derived from TFreeNotificationBase are freed. } TMessageManager.DefaultManager.SubscribeToMessage(TFreeNotificationMessage, FreeNotificationListener); end; destructor TFrameFreeNotifications.Destroy; begin { Unsubscribe from the TFreeNotification message. } TMessageManager.DefaultManager.Unsubscribe(TFreeNotificationMessage, FreeNotificationListener); inherited; end; procedure TFrameFreeNotifications.FreeNotificationListener( const Sender: TObject; const M: TMessage); begin { This method is called when an object derived from TFreeNotificationBase (whose EnableFreeNotification has been called) method is about to be freed. The Sender parameter contains the object that is about to freed. We don't care about the M parameter, since it is just used to describe the message type (which should be TFreeNotification). } Assert(M is TFreeNotificationMessage); Assert(Sender is TFreeNotificationObject); Log('TFreeNotificationMessage received for: ' + TFreeNotificationObject(Sender).Name); end; end.
{ ********************************************************************* * * Autor: Efimov A.A. * E-mail: infocean@gmail.com * GitHub: https://github.com/AndrewEfimov * Permissions: "android.permission.VIBRATE" * Platform (API 19+): Android 4.4.2 - 10 * IDE: Delphi 10.1/10.2/10.3 (Berlin/Tokyo/Rio) * ******************************************************************** } unit uVibratorHelper; interface uses Androidapi.Helpers, Androidapi.JNI.Os, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, System.SysUtils, Androidapi.JNI.Os.Vibration; type TJavaArrayHelper = class public class function ArrayStrToJavaArrayInt64(const ASource: array of string): TJavaArray<Int64>; class function ArrayInt64ToJavaArrayInt64(const ASource: array of Int64): TJavaArray<Int64>; end; TVibratorHelper = class(TObject) private class var FSDK_INT: Integer; class var FJVibrator: JVibrator; class constructor Create; public /// <summary> Turn the vibrator off. </summary> class procedure cancel; /// <summary> Check whether the hardware has a vibrator. </summary> class function hasVibrator: Boolean; /// <summary> Vibrate constantly for the specified period of time. </summary> class procedure vibrate(const AMilliseconds: Int64); overload; /// <summary> Vibrate with a given pattern. </summary> class procedure vibrate(const APattern: TJavaArray<Int64>; const ARepeat: Integer); overload; class procedure vibrate(const APattern: array of Int64; const ARepeat: Integer); overload; class procedure vibrate(const APattern: array of string; const ARepeat: Integer); overload; end; implementation { TJavaArrayHelper } class function TJavaArrayHelper.ArrayInt64ToJavaArrayInt64(const ASource: array of Int64): TJavaArray<Int64>; var I: Integer; begin Result := TJavaArray<Int64>.Create(Length(ASource)); for I := Low(ASource) to High(ASource) do Result.Items[I] := ASource[I]; end; class function TJavaArrayHelper.ArrayStrToJavaArrayInt64(const ASource: array of string): TJavaArray<Int64>; var I: Integer; begin Result := TJavaArray<Int64>.Create(Length(ASource)); for I := Low(ASource) to High(ASource) do Result.Items[I] := ASource[I].ToInt64; end; { TVibrator } class procedure TVibratorHelper.cancel; begin if hasVibrator then FJVibrator.cancel; end; class constructor TVibratorHelper.Create; begin FSDK_INT := TJBuild_VERSION.JavaClass.SDK_INT; FJVibrator := TJVibrator.Wrap(TAndroidHelper.Context.getSystemService(TJContext.JavaClass.VIBRATOR_SERVICE)) end; class function TVibratorHelper.hasVibrator: Boolean; begin Result := (FJVibrator <> nil) and FJVibrator.hasVibrator; end; class procedure TVibratorHelper.vibrate(const AMilliseconds: Int64); begin if hasVibrator then if FSDK_INT >= 26 then FJVibrator.vibrate(TJVibrationEffect.JavaClass.createOneShot(AMilliseconds, TJVibrationEffect.JavaClass.DEFAULT_AMPLITUDE)) else FJVibrator.vibrate(AMilliseconds); end; class procedure TVibratorHelper.vibrate(const APattern: array of string; const ARepeat: Integer); begin TVibratorHelper.vibrate(TJavaArrayHelper.ArrayStrToJavaArrayInt64(APattern), ARepeat); end; class procedure TVibratorHelper.vibrate(const APattern: array of Int64; const ARepeat: Integer); begin TVibratorHelper.vibrate(TJavaArrayHelper.ArrayInt64ToJavaArrayInt64(APattern), ARepeat); end; // pattern: an array of longs of times for which to turn the vibrator on or off. // repeat: the index into pattern at which to repeat, or -1 if you don't want to repeat. // array pattern(pause and vibrate in milliseconds): [pause, vibrate, pause, ... , vibrate, pause] class procedure TVibratorHelper.vibrate(const APattern: TJavaArray<Int64>; const ARepeat: Integer); begin if hasVibrator then if FSDK_INT >= 26 then FJVibrator.vibrate(TJVibrationEffect.JavaClass.createWaveform(APattern, ARepeat)) else FJVibrator.vibrate(APattern, ARepeat); end; end.
{******************************************************************************* Title: T2Ti ERP 3.0 Description: Service relacionado à tabela [NFE_CONFIGURACAO] The MIT License Copyright: Copyright (C) 2021 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 @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit NfeConfiguracaoService; interface uses NfeConfiguracao, Empresa, EmpresaService, Biblioteca, ACbrMonitorPorta, AcbrMonitorPortaService, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils, Vcl.Forms, Winapi.Windows, IniFiles, ShellApi, MVCFramework.Logger; type TNfeConfiguracaoService = class(TServiceBase) private class procedure CriarPastaAcbrMonitor(ACnpj: string); class procedure ConfigurarArquivoIniMonitor(ANfeConfiguracao: TNfeConfiguracao; ADecimaisQuantidade: Integer; ADecimaisValor: Integer; APorta: Integer); public class function ConsultarLista: TObjectList<TNfeConfiguracao>; class function ConsultarListaFiltro(AWhere: string): TObjectList<TNfeConfiguracao>; class function ConsultarObjeto(AId: Integer): TNfeConfiguracao; class function ConsultarObjetoFiltro(AWhere: string): TNfeConfiguracao; class procedure Inserir(ANfeConfiguracao: TNfeConfiguracao); class function Alterar(ANfeConfiguracao: TNfeConfiguracao): Integer; class function Excluir(ANfeConfiguracao: TNfeConfiguracao): Integer; // class function AtualizarDados(ANfeConfiguracao: TNfeConfiguracao; ACnpj: string; ADecimaisQuantidade: Integer; ADecimaisValor: Integer): TNfeConfiguracao; end; var sql, CaminhoComCnpj: string; Empresa: TEmpresa; implementation { TNfeConfiguracaoService } class function TNfeConfiguracaoService.ConsultarLista: TObjectList<TNfeConfiguracao>; begin sql := 'SELECT * FROM NFE_CONFIGURACAO ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TNfeConfiguracao>; finally Query.Close; Query.Free; end; end; class function TNfeConfiguracaoService.ConsultarListaFiltro(AWhere: string): TObjectList<TNfeConfiguracao>; begin sql := 'SELECT * FROM NFE_CONFIGURACAO where ' + AWhere; try Result := GetQuery(sql).AsObjectList<TNfeConfiguracao>; finally Query.Close; Query.Free; end; end; class function TNfeConfiguracaoService.ConsultarObjeto(AId: Integer): TNfeConfiguracao; begin sql := 'SELECT * FROM NFE_CONFIGURACAO WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TNfeConfiguracao>; end else Result := nil; finally Query.Close; Query.Free; end; end; class function TNfeConfiguracaoService.ConsultarObjetoFiltro(AWhere: string): TNfeConfiguracao; begin sql := 'SELECT * FROM NFE_CONFIGURACAO where ' + AWhere; try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TNfeConfiguracao>; end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TNfeConfiguracaoService.Inserir(ANfeConfiguracao: TNfeConfiguracao); begin ANfeConfiguracao.ValidarInsercao; ANfeConfiguracao.Id := InserirBase(ANfeConfiguracao, 'NFE_CONFIGURACAO'); end; class function TNfeConfiguracaoService.Alterar(ANfeConfiguracao: TNfeConfiguracao): Integer; begin ANfeConfiguracao.ValidarAlteracao; Result := AlterarBase(ANfeConfiguracao, 'NFE_CONFIGURACAO'); end; class function TNfeConfiguracaoService.Excluir(ANfeConfiguracao: TNfeConfiguracao): Integer; begin ANfeConfiguracao.ValidarExclusao; Result := ExcluirBase(ANfeConfiguracao.Id, 'NFE_CONFIGURACAO'); end; class function TNfeConfiguracaoService.AtualizarDados(ANfeConfiguracao: TNfeConfiguracao; ACnpj: string; ADecimaisQuantidade: Integer; ADecimaisValor: Integer): TNfeConfiguracao; var Configuracao: TNfeConfiguracao; Filtro: string; PortaMonitor: TACbrMonitorPorta; begin Filtro := 'CNPJ = "' + ACnpj + '"'; Empresa := TEmpresaService.ConsultarObjetoFiltro(filtro); if Assigned(Empresa) then begin ANfeConfiguracao.IdEmpresa := Empresa.Id; ANfeConfiguracao.CaminhoSalvarXml := StringReplace(ANfeConfiguracao.CaminhoSalvarXml, '\', '\\', [rfReplaceAll, rfIgnoreCase]); ANfeConfiguracao.CaminhoSalvarPdf := StringReplace(ANfeConfiguracao.CaminhoSalvarPdf, '\', '\\', [rfReplaceAll, rfIgnoreCase]); Filtro := 'ID_EMPRESA = ' + Empresa.Id.ToString; Configuracao := ConsultarObjetoFiltro(filtro); if Assigned(Configuracao) then begin ANfeConfiguracao.Id := Configuracao.Id; AlterarBase(ANfeConfiguracao, 'NFE_CONFIGURACAO'); end else begin ANfeConfiguracao.Id := InserirBase(ANfeConfiguracao, 'NFE_CONFIGURACAO'); end; // verificar se já existe uma porta definida para o monitor da empresa // ALTER TABLE acbr_monitor_porta AUTO_INCREMENT=3435; - executa um comando no banco de dados para definir a porta inicial para o ID Filtro := 'ID_EMPRESA = ' + Empresa.Id.ToString; PortaMonitor := TAcbrMonitorPortaService.ConsultarObjetoFiltro(filtro); if not Assigned(PortaMonitor) then begin PortaMonitor := TACbrMonitorPorta.Create; PortaMonitor.IdEmpresa := Empresa.Id; PortaMonitor.Id := InserirBase(PortaMonitor, 'ACBR_MONITOR_PORTA'); end; // criar a pasta do monitor para a empresa CriarPastaAcbrMonitor(ACnpj); // configurar o arquivo INI ConfigurarArquivoIniMonitor(ANfeConfiguracao, ADecimaisQuantidade, ADecimaisValor, PortaMonitor.Id); Result := ANfeConfiguracao; end; end; class procedure TNfeConfiguracaoService.CriarPastaAcbrMonitor(ACnpj: string); begin if not System.SysUtils.DirectoryExists('C:\ACBrMonitor\' + ACnpj) then begin Biblioteca.ExecAndWait('c:\AcbrMonitor\CopiarBase.bat ' + ACnpj, SW_HIDE); end; end; class procedure TNfeConfiguracaoService.ConfigurarArquivoIniMonitor(ANfeConfiguracao: TNfeConfiguracao; ADecimaisQuantidade: Integer; ADecimaisValor: Integer; APorta: Integer); var ACBrMonitorIni: TIniFile; CaminhoExecutavel: PWideChar; begin CaminhoComCnpj := 'C:\ACBrMonitor\' + Empresa.Cnpj + '\'; ANfeConfiguracao.CaminhoSalvarPdf := CaminhoComCnpj + 'PDF'; ANfeConfiguracao.CaminhoSalvarXml := CaminhoComCnpj + 'DFes'; ACBrMonitorIni := TIniFile.Create(CaminhoComCnpj + 'ACBrMonitor.ini'); try //******************************************************************************************* // [ACBrMonitor] //******************************************************************************************* ACBrMonitorIni.WriteString('ACBrMonitor', 'TCP_Porta', APorta.ToString); //******************************************************************************************* // [ACBrNFeMonitor] //******************************************************************************************* ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'Arquivo_Log_Comp', CaminhoComCnpj + 'LOG_DFe.TXT'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServices', CaminhoComCnpj + 'ACBrNFeServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServicesCTe', CaminhoComCnpj + 'ACBrCTeServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServicesMDFe', CaminhoComCnpj + 'ACBrMDFeServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServicesGNRe', CaminhoComCnpj + 'ACBrGNREServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServiceseSocial', CaminhoComCnpj + 'ACBreSocialServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServicesReinf', CaminhoComCnpj + 'ACBrReinfServicos.ini'); ACBrMonitorIni.WriteString('ACBrNFeMonitor', 'ArquivoWebServicesBPe', CaminhoComCnpj + 'ACBrBPeServicos.ini'); //******************************************************************************************* // [WebService] //******************************************************************************************* // tpAmb - 1-Produção/ 2-Homologação // OBS: o monitor leva em conta o índice do Radiogroup, ou seja, será 0 para produção e 1 para homologação ACBrMonitorIni.WriteString('WebService', 'Ambiente', (ANfeConfiguracao.WebserviceAmbiente-1).ToString); ACBrMonitorIni.WriteString('WebService', 'UF', Empresa.Uf); //******************************************************************************************* // [RespTecnico] //******************************************************************************************* if ANfeConfiguracao.RespTecHashCsrt <> '0' then ACBrMonitorIni.WriteString('RespTecnico', 'CSRT', ANfeConfiguracao.RespTecHashCsrt); if ANfeConfiguracao.RespTecIdCsrt <> '0' then ACBrMonitorIni.WriteString('RespTecnico', 'idCSRT', ANfeConfiguracao.RespTecIdCsrt); //******************************************************************************************* // [NFCe] //******************************************************************************************* ACBrMonitorIni.WriteString('NFCe', 'IdToken', ANfeConfiguracao.NfceIdCsc); ACBrMonitorIni.WriteString('NFCe', 'Token', ANfeConfiguracao.NfceCsc); if ANfeConfiguracao.NfceModeloImpressao = 'A4' then ACBrMonitorIni.WriteString('NFCe', 'ModoImpressaoEvento', '0') else ACBrMonitorIni.WriteString('NFCe', 'ModoImpressaoEvento', '1'); if ANfeConfiguracao.NfceImprimirItensUmaLinha = 'S' then ACBrMonitorIni.WriteString('NFCe', 'ImprimirItem1Linha', '1') else ACBrMonitorIni.WriteString('NFCe', 'ImprimirItem1Linha', '0'); if ANfeConfiguracao.NfceImprimirDescontoPorItem = 'S' then ACBrMonitorIni.WriteString('NFCe', 'ImprimirDescAcresItem', '1') else ACBrMonitorIni.WriteString('NFCe', 'ImprimirDescAcresItem', '0'); if ANfeConfiguracao.NfceImprimirQrcodeLateral = 'S' then ACBrMonitorIni.WriteString('NFCe', 'QRCodeLateral', '1') else ACBrMonitorIni.WriteString('NFCe', 'QRCodeLateral', '0'); if ANfeConfiguracao.NfceImprimirGtin = 'S' then ACBrMonitorIni.WriteString('NFCe', 'UsaCodigoEanImpressao', '1') else ACBrMonitorIni.WriteString('NFCe', 'UsaCodigoEanImpressao', '0'); if ANfeConfiguracao.NfceImprimirNomeFantasia = 'S' then ACBrMonitorIni.WriteString('NFCe', 'ImprimeNomeFantasia', '1') else ACBrMonitorIni.WriteString('NFCe', 'ImprimeNomeFantasia', '0'); if ANfeConfiguracao.NfceImpressaoTributos = 'S' then ACBrMonitorIni.WriteString('NFCe', 'ExibeTotalTributosItem', '1') else ACBrMonitorIni.WriteString('NFCe', 'ExibeTotalTributosItem', '0'); //******************************************************************************************* // [DANFCe] //******************************************************************************************* ACBrMonitorIni.WriteString('DANFCe', 'MargemInf', ANfeConfiguracao.NfceMargemInferior.ToString.Replace('.', ',')); ACBrMonitorIni.WriteString('DANFCe', 'MargemSup', ANfeConfiguracao.NfceMargemSuperior.ToString.Replace('.', ',')); ACBrMonitorIni.WriteString('DANFCe', 'MargemDir', ANfeConfiguracao.NfceMargemDireita.ToString.Replace('.', ',')); ACBrMonitorIni.WriteString('DANFCe', 'MargemEsq', ANfeConfiguracao.NfceMargemEsquerda.ToString.Replace('.', ',')); ACBrMonitorIni.WriteString('DANFCe', 'LarguraBobina', ANfeConfiguracao.NfceResolucaoImpressao.ToString); //******************************************************************************************* // [FonteLinhaItem] //******************************************************************************************* ACBrMonitorIni.WriteString('FonteLinhaItem', 'Size', ANfeConfiguracao.NfceTamanhoFonteItem.ToString); //******************************************************************************************* // [DANFE] //******************************************************************************************* ACBrMonitorIni.WriteString('DANFE', 'PathPDF', ANfeConfiguracao.CaminhoSalvarPdf); ACBrMonitorIni.WriteString('DANFE', 'DecimaisQTD', ADecimaisQuantidade.ToString); ACBrMonitorIni.WriteString('DANFE', 'DecimaisValor', ADecimaisValor.ToString); //******************************************************************************************* // [Arquivos] //******************************************************************************************* ACBrMonitorIni.WriteString('Arquivos', 'PathNFe', ANfeConfiguracao.CaminhoSalvarXml); ACBrMonitorIni.WriteString('Arquivos', 'PathInu', CaminhoComCnpj + 'Inutilizacao'); ACBrMonitorIni.WriteString('Arquivos', 'PathDPEC', CaminhoComCnpj + 'EPEC'); ACBrMonitorIni.WriteString('Arquivos', 'PathEvento', CaminhoComCnpj + 'Evento'); ACBrMonitorIni.WriteString('Arquivos', 'PathArqTXT', CaminhoComCnpj + 'TXT'); ACBrMonitorIni.WriteString('Arquivos', 'PathDonwload', CaminhoComCnpj + 'DistribuicaoDFe'); finally Biblioteca.KillTask('ACBrMonitor_' + Empresa.Cnpj + '.exe'); CaminhoExecutavel := PWideChar(CaminhoComCnpj + 'ACBrMonitor_' + Empresa.Cnpj + '.exe'); ShellExecute(0, 'open', (CaminhoExecutavel), nil, nil, SW_HIDE); ACBrMonitorIni.Free; end; end; end.
{single instance priority queue main parts contributed by Rassim Eminli} {$INCLUDE switches.pas} unit Pile; interface procedure Create(Size: integer); procedure Free; procedure Empty; function Put(Item, Value: integer): boolean; function TestPut(Item, Value: integer): boolean; function Get(var Item, Value: integer): boolean; implementation const MaxSize=9600; type TheapItem = record Item: integer; Value: integer; end; var bh: array[0..MaxSize-1] of TheapItem; Ix: array[0..MaxSize-1] of integer; n, CurrentSize: integer; {$IFDEF DEBUG}InUse: boolean;{$ENDIF} procedure Create(Size: integer); begin {$IFDEF DEBUG}assert(not InUse, 'Pile is a single instance class, ' +'no multiple usage possible. Always call Pile.Free after use.');{$ENDIF} assert(Size<=MaxSize); if (n <> 0) or (Size > CurrentSize) then begin FillChar(Ix, Size*sizeOf(integer), 255); n := 0; end; CurrentSize := Size; {$IFDEF DEBUG}InUse:=true;{$ENDIF} end; procedure Free; begin {$IFDEF DEBUG}assert(InUse);InUse:=false;{$ENDIF} end; procedure Empty; begin if n <> 0 then begin FillChar(Ix, CurrentSize*sizeOf(integer), 255); n := 0; end; end; //Parent(i) = (i-1)/2. function Put(Item, Value: integer): boolean; //O(lg(n)) var i, j: integer; begin assert(Item<CurrentSize); i := Ix[Item]; if i >= 0 then begin if bh[i].Value <= Value then begin result := False; exit; end; end else begin i := n; Inc(n); end; while i > 0 do begin j := (i-1) shr 1; //Parent(i) = (i-1)/2 if Value >= bh[j].Value then break; bh[i] := bh[j]; Ix[bh[i].Item] := i; i := j; end; // Insert the new Item at the insertion point found. bh[i].Value := Value; bh[i].Item := Item; Ix[bh[i].Item] := i; result := True; end; function TestPut(Item, Value: integer): boolean; var i: integer; begin assert(Item<CurrentSize); i := Ix[Item]; result := (i < 0) or (bh[i].Value > Value); end; //Left(i) = 2*i+1. //Right(i) = 2*i+2 => Left(i)+1 function Get(var Item, Value: integer): boolean; //O(lg(n)) var i, j: integer; last: TheapItem; begin if n = 0 then begin result := False; exit; end; Item := bh[0].Item; Value := bh[0].Value; Ix[Item] := -1; dec(n); if n > 0 then begin last := bh[n]; i := 0; j := 1; while j < n do begin // Right(i) = Left(i)+1 if(j < n-1) and (bh[j].Value > bh[j + 1].Value)then inc(j); if last.Value <= bh[j].Value then break; bh[i] := bh[j]; Ix[bh[i].Item] := i; i := j; j := j shl 1+1; //Left(j) = 2*j+1 end; // Insert the root in the correct place in the heap. bh[i] := last; Ix[last.Item] := i; end; result := True end; initialization n:=0; CurrentSize:=0; {$IFDEF DEBUG}InUse:=false;{$ENDIF} end.
unit ExpandingComponent; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OurCollection; type TExpandingRecord = class(TPersistent) private FIntegerProp : Integer; FStringProp : String; FCollectionProp : TOurCollection; procedure SetCollectionProp(const Value: TOurCollection); public constructor Create(AOwner : TComponent); destructor Destroy; override; procedure Assign(Source : TPersistent); override; published property IntegerProp : Integer read FIntegerProp write FIntegerProp; property StringProp : String read FStringProp write FStringProp; property CollectionProp : TOurCollection read FCollectionProp write SetCollectionProp; end; TExpandingComponent = class(TComponent) private { Private declarations } FProperty1, FProperty2, FProperty3 : TExpandingRecord; protected { Protected declarations } procedure SetProperty1(const Value : TExpandingRecord); procedure SetProperty2(const Value : TExpandingRecord); procedure SetProperty3(const Value : TExpandingRecord); public { Public declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; published { Published declarations } property Property1 : TExpandingRecord read FProperty1 write SetProperty1; property Property2 : TExpandingRecord read FProperty2 write SetProperty2; property Property3 : TExpandingRecord read FProperty3 write SetProperty3; end; procedure Register; implementation procedure Register; begin RegisterComponents('Article', [TExpandingComponent]); end; { TExpandingRecord } procedure TExpandingRecord.Assign(Source: TPersistent); begin if Source is TExpandingRecord then with TExpandingRecord(Source) do begin Self.IntegerProp := IntegerProp; Self.StringProp := StringProp; Self.CollectionProp := CollectionProp; //This actually assigns end else inherited; //raises an exception end; constructor TExpandingRecord.Create(AOwner : TComponent); begin inherited Create; FCollectionProp := TOurCollection.Create(AOwner); end; destructor TExpandingRecord.Destroy; begin FCollectionProp.Free; inherited; end; procedure TExpandingRecord.SetCollectionProp(const Value: TOurCollection); begin FCollectionProp.Assign(Value); end; { TExpandingComponent } constructor TExpandingComponent.Create(AOwner: TComponent); begin inherited; FProperty1 := TExpandingRecord.Create(Self); FProperty2 := TExpandingRecord.Create(Self); FProperty3 := TExpandingRecord.Create(Self); end; destructor TExpandingComponent.Destroy; begin FProperty1.Free; FProperty2.Free; FProperty3.Free; inherited; end; procedure TExpandingComponent.SetProperty1(const Value: TExpandingRecord); begin FProperty1.Assign(Value); end; procedure TExpandingComponent.SetProperty2(const Value: TExpandingRecord); begin FProperty2.Assign(Value); end; procedure TExpandingComponent.SetProperty3(const Value: TExpandingRecord); begin FProperty3.Assign(Value); end; end.
{ Batch text replacement in textures and materials file names inside *.nif files Optionally perform replacement inside material files (*.bgsm and *.bgem) Search is case insensitive. Supports all game NIF formats starting from Morrowind. } unit NifBatchTextureReplacement; const bFixAbsolutePaths = True; // automatically fix absolute paths if found iShowProgress = 100; // show progress message for each 100 processed files, 0 to disable sDefaultSourcePath = ''; // Data folder will be used if empty sDefaultDestinationPath = ''; // Data folder will be used if empty sDefaultReplacement = 'Textures\'#13'Textures\New\'; // default replacements var bMaterial, bInMaterial, bReportOnly: Boolean; //============================================================================ procedure BatchReplace(aSrcPath, aDstPath: string; aFind, aReplace: TStringList); var TDirectory: TDirectory; // to access member functions i, j, k, p, Processed, Updated: integer; Elements: TList; el: TdfElement; Nif: TwbNifFile; Block: TwbNifBlock; BGSM: TwbBGSMFile; BGEM: TwbBGEMFile; files: TStringDynArray; f, f2, ext: string; s, s2: WideString; bChanged: Boolean; begin if (aSrcPath = '') or (aDstPath = '') then Exit; aSrcPath := IncludeTrailingBackslash(aSrcPath); aDstPath := IncludeTrailingBackslash(aDstPath); Processed := 0; Updated := 0; Elements := TList.Create; Nif := TwbNifFile.Create; BGSM := TwbBGSMFile.Create; BGEM := TwbBGEMFile.Create; try // list of all files in the source folder files := TDirectory.GetFiles(aSrcPath, '*.*', soAllDirectories); AddMessage('Processing files in "' + aSrcPath + '", press and hold ESC to abort...'); // processing files for i := 0 to Pred(Length(files)) do begin f := files[i]; f2 := aDstPath + Copy(f, Length(aSrcPath) + 1, Length(f)); ext := ExtractFileExt(f); Inc(Processed); // break the files processing loop if Escape is pressed if GetKeyState(VK_ESCAPE) and 128 = 128 then Break; // show progress if set if iShowProgress > 0 then if (i > 0) and (i mod iShowProgress = 0) then AddMessage(IntToStr(i) + ' files processed'); // collecting elements with textures // *.NIF file if SameText(ext, '.nif') then begin Nif.LoadFromFile(f); // iterate over all blocks in a nif file and locate elements holding textures for j := 0 to Pred(Nif.BlocksCount) do begin Block := Nif.Blocks[j]; // BGSM/BGEM file in the Name field of FO4 meshes if bMaterial and (Nif.NifVersion = nfFO4) and (Block.BlockType = 'BSLightingShaderProperty') then Elements.Add(Block.Elements['Name']) else if Block.BlockType = 'BSShaderTextureSet' then begin el := Block.Elements['Textures']; for j := 0 to Pred(el.Count) do Elements.Add(el[j]); end else if Block.BlockType = 'BSEffectShaderProperty' then begin Elements.Add(Block.Elements['Source Texture']); Elements.Add(Block.Elements['Grayscale Texture']); Elements.Add(Block.Elements['Env Map Texture']); Elements.Add(Block.Elements['Normal Texture']); Elements.Add(Block.Elements['Env Mask Texture']); // BGSM/BGEM file in the Name field of FO4 meshes if bMaterial and (Nif.NifVersion = nfFO4) then Elements.Add(Block.Elements['Name']); end else if (Block.BlockType = 'BSShaderNoLightingProperty') or (Block.BlockType = 'TallGrassShaderProperty') or (Block.BlockType = 'TileShaderProperty') then Elements.Add(Block.Elements['File Name']) else if Block.BlockType = 'BSSkyShaderProperty' then Elements.Add(Block.Elements['Source Texture']) // any block inherited from NiTexture else if Block.IsNiObject('NiTexture', True) then Elements.Add(Block.Elements['File Name']); end; end // *.BGSM file else if SameText(ext, '.bgsm') then begin BGSM.LoadFromFile(f); el := BGSM.Elements['Textures']; for j := 0 to Pred(el.Count) do Elements.Add(el[j]); end // *.BGEM file else if SameText(ext, '.bgem') then begin BGEM.LoadFromFile(f); el := BGEM.Elements['Textures']; for j := 0 to Pred(el.Count) do Elements.Add(el[j]); end; // skip to the next file if nothing was found if Elements.Count = 0 then Continue; // do text replacement in collected elements for j := 0 to Pred(Elements.Count) do begin if not Assigned(Elements[j]) then Continue else el := TdfElement(Elements[j]); // getting file name stored in element s := el.EditValue; // skip to the next element if empty if s = '' then Continue; // perform replacements, trim whitespaces just in case s2 := Trim(s); for k := 0 to Pred(aFind.Count) do begin if aFind[k] <> '' then // replace if text to find is not empty s2 := StringReplace(s2, aFind[k], aReplace[k], [rfIgnoreCase, rfReplaceAll]) else // prepend if empty s2 := aReplace[k] + s2; end; if bFixAbsolutePaths then // detect an absolute path if (Length(s2) > 2) and (Copy(s2, 2, 1) = ':') then begin // remove path up to Data including it p := Pos('\data\', LowerCase(s2)); if p <> 0 then s2 := Copy(s2, p + 6, Length(s2)); // remove path up to Data Files including it for Morrowind if p = 0 then begin p := Pos('\data files\', LowerCase(s2)); if p <> 0 then s2 := Copy(s, p + 12, Length(s2)); end; end; // if element's value has changed if s <> s2 then begin // store it el.EditValue := s2; // report if not bChanged then AddMessage(#13#10 + f); AddMessage(#9 + el.Path + #13#10#9#9'"' + s + '"'#13#10#9#9'"' + el.EditValue + '"'); // mark file to be saved bChanged := True; end; end; // save the file if changed and not in report only mode if bChanged and not bReportOnly then begin // create the same folders structure as the source file in the destination folder s := ExtractFilePath(f2); if not DirectoryExists(s) then if not ForceDirectories(s) then raise Exception.Create('Can not create destination directory ' + s); // get the root of the last processed element (the file element itself) and save el.Root.SaveToFile(f2); Inc(Updated); end; // clear mark and elements list bChanged := False; Elements.Clear; end; AddMessage(Format(#13#10'Processed Files: %d, Updated: %d', [Processed, Updated])); finally Elements.Free; Nif.Free; BGSM.Free; BGEM.Free; end; end; //============================================================================ procedure btnSrcClick(Sender: TObject); var ed: TLabeledEdit; s: string; begin ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edSrc')); s := SelectDirectory('Select source', '', ed.Text, nil); if s <> '' then begin ed.Text := s; ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edDst')); if ed.Text = '' then ed.Text := s; end; end; //============================================================================ procedure btnDstClick(Sender: TObject); var ed: TLabeledEdit; s: string; begin ed := TLabeledEdit(TForm(Sender.Parent).FindComponent('edDst')); s := SelectDirectory('Select destination', '', ed.Text, nil); if s <> '' then ed.Text := s; end; //============================================================================ function Initialize: Integer; var frm: TForm; edSrc, edDst: TLabeledEdit; lblReplace: TLabel; memoReplace: TMemo; btnOk, btnCancel, btnSrc, btnDst: TButton; chkMaterial, chkInMaterial, chkReportOnly: TCheckBox; pnl: TPanel; slFind, slReplace: TStringList; i: integer; begin slFind := TStringList.Create; slReplace := TStringList.Create; frm := TForm.Create(nil); try frm.Caption := 'NIF/BGSM/BGEM Batch Textures Replacement'; frm.Width := 500; frm.Height := 400; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; edSrc := TLabeledEdit.Create(frm); edSrc.Parent := frm; edSrc.Name := 'edSrc'; edSrc.Left := 12; edSrc.Top := 24; edSrc.Width := frm.Width - 70; edSrc.LabelPosition := lpAbove; edSrc.EditLabel.Caption := 'Source folder'; if sDefaultSourcePath <> '' then edSrc.Text := sDefaultSourcePath else edSrc.Text := wbDataPath; btnSrc := TButton.Create(frm); btnSrc.Parent := frm; btnSrc.Top := edSrc.Top - 1; btnSrc.Left := edSrc.Left + edSrc.Width + 6; btnSrc.Width := 32; btnSrc.Height := 22; btnSrc.Caption := '...'; btnSrc.OnClick := btnSrcClick; edDst := TLabeledEdit.Create(frm); edDst.Parent := frm; edDst.Name := 'edDst'; edDst.Left := 12; edDst.Top := edSrc.Top + 46; edDst.Width := frm.Width - 70; edDst.LabelPosition := lpAbove; edDst.EditLabel.Caption := 'Destination folder'; if sDefaultDestinationPath <> '' then edDst.Text := sDefaultDestinationPath else edDst.Text := wbDataPath; btnDst := TButton.Create(frm); btnDst.Parent := frm; btnDst.Top := edDst.Top - 1; btnDst.Left := edDst.Left + edDst.Width + 6; btnDst.Width := 32; btnDst.Height := 22; btnDst.Caption := '...'; btnDst.OnClick := btnDstClick; chkMaterial := TCheckBox.Create(frm); chkMaterial.Parent := frm; chkMaterial.Left := edDst.Left + 12; chkMaterial.Top := edDst.Top + 32; chkMaterial.Width := frm.Width - 60; chkMaterial.Caption := '[FO4] Replace in material file names defined in NIF'; chkMaterial.Checked := True; chkInMaterial := TCheckBox.Create(frm); chkInMaterial.Parent := frm; chkInMaterial.Left := chkMaterial.Left; chkInMaterial.Top := chkMaterial.Top + 24; chkInMaterial.Width := frm.Width - 60; chkInMaterial.Caption := '[FO4] Replace textures inside material files (*.BGSM, *.BGEM)'; chkInMaterial.Checked := True; chkReportOnly := TCheckBox.Create(frm); chkReportOnly.Parent := frm; chkReportOnly.Left := chkMaterial.Left; chkReportOnly.Top := chkInMaterial.Top + 24; chkReportOnly.Width := frm.Width - 60; chkReportOnly.Caption := 'Report only, do not save any changes'; lblReplace := TLabel.Create(frm); lblReplace.Parent := frm; lblReplace.Left := 12; lblReplace.Top := chkReportOnly.Top + 34; lblReplace.AutoSize := False; lblReplace.WordWrap := True; lblReplace.Width := frm.Width - 34; lblReplace.Height := 30; lblReplace.Caption := 'Replacement pair(s): odd lines specify what text to replace, even lines text to replace with. If odd line is empty then replacement text is prepended to all textures.'; memoReplace := TMemo.Create(frm); memoReplace.Parent := frm; memoReplace.Left := 12; memoReplace.Top := lblReplace.Top + lblReplace.Height + 8; memoReplace.Height := 90; memoReplace.Width := frm.Width - 34; memoReplace.ScrollBars := ssVertical; memoReplace.Lines.Text := sDefaultReplacement; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width - 176; btnOk.Top := frm.Height - 62; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 8; btnCancel.Top := btnOk.Top; pnl := TPanel.Create(frm); pnl.Parent := frm; pnl.Left := 8; pnl.Top := btnOk.Top - 12; pnl.Width := frm.Width - 20; pnl.Height := 2; if frm.ShowModal = mrOk then begin bMaterial := chkMaterial.Checked; bInMaterial := chkInMaterial.Checked; bReportOnly := chkReportOnly.Checked; for i := 0 to memoReplace.Lines.Count div 2 do // skip if both odd and even lines are empty if (memoReplace.Lines[i * 2] <> '') or (memoReplace.Lines[i * 2 + 1] <> '') then begin slFind.Add(memoReplace.Lines[i * 2]); slReplace.Add(memoReplace.Lines[i * 2 + 1]); end; if slFind.Count <> 0 then BatchReplace( edSrc.Text, edDst.Text, slFind, slReplace ) else AddMessage('No replacements specified!'); end; finally frm.Free; slFind.Free; slReplace.Free; end; Result := 1; 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.StdCtrls, Vcl.Mask, Vcl.ExtCtrls, Vcl.Imaging.pngimage,STRUtils; type TForm1 = class(TForm) TimeInterval: TMaskEdit; ComboBox1: TComboBox; KeyText: TEdit; MouseBTN: TComboBox; Fechar: TImage; Footer: TImage; Header: TImage; Maximizar: TImage; Minimizar: TImage; Timer1: TTimer; Start: TButton; MilliInterval: TLabel; Stop: TButton; KeyBTN: TComboBox; PremadeKey: TComboBox; Version: TLabel; Lang: TComboBox; AlwaysTop: TCheckBox; AutoClick: TRadioButton; AlwaysClicked: TRadioButton; procedure ComboBox1Change(Sender: TObject); procedure StartClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure StopClick(Sender: TObject); procedure KeyBTNChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure KeyTextClick(Sender: TObject); procedure AlwaysTopClick(Sender: TObject); procedure AutoClickClick(Sender: TObject); private { Private declarations } Key : Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} //== Função da Versão do Aplicativo ============================================ Function VersaoExe: String; type PFFI = ^vs_FixedFileInfo; var F : PFFI; Handle : Dword; Len : Longint; Data : Pchar; Buffer : Pointer; Tamanho : Dword; Parquivo: Pchar; Arquivo : String; begin Arquivo := Application.ExeName; Parquivo := StrAlloc(Length(Arquivo) + 1); StrPcopy(Parquivo, Arquivo); Len := GetFileVersionInfoSize(Parquivo, Handle); Result := ''; if Len > 0 then begin Data:=StrAlloc(Len+1); if GetFileVersionInfo(Parquivo,Handle,Len,Data) then begin VerQueryValue(Data, '',Buffer,Tamanho); F := PFFI(Buffer); Result := Format('%d.%d.%d.%d', [HiWord(F^.dwFileVersionMs), LoWord(F^.dwFileVersionMs), HiWord(F^.dwFileVersionLs), Loword(F^.dwFileVersionLs)] ); end; StrDispose(Data); end; StrDispose(Parquivo); end; //=== Selecionar Premade Key =================================================== Procedure SelectPreKey; begin if Form1.PremadeKey.ItemIndex=0 then Form1.Key := VK_LBUTTON; if Form1.PremadeKey.ItemIndex=1 then Form1.Key := VK_RBUTTON; if Form1.PremadeKey.ItemIndex=2 then Form1.Key := VK_CANCEL; if Form1.PremadeKey.ItemIndex=3 then Form1.Key := VK_MBUTTON; if Form1.PremadeKey.ItemIndex=4 then Form1.Key := VK_BACK; if Form1.PremadeKey.ItemIndex=5 then Form1.Key := VK_TAB; if Form1.PremadeKey.ItemIndex=6 then Form1.Key := VK_CLEAR; if Form1.PremadeKey.ItemIndex=7 then Form1.Key := VK_RETURN; if Form1.PremadeKey.ItemIndex=8 then Form1.Key := VK_SHIFT; if Form1.PremadeKey.ItemIndex=9 then Form1.Key := VK_CONTROL; if Form1.PremadeKey.ItemIndex=10 then Form1.Key := VK_MENU; if Form1.PremadeKey.ItemIndex=11 then Form1.Key := VK_PAUSE; if Form1.PremadeKey.ItemIndex=12 then Form1.Key := VK_CAPITAL; if Form1.PremadeKey.ItemIndex=13 then Form1.Key := VK_KANA; if Form1.PremadeKey.ItemIndex=14 then Form1.Key := VK_HANGUL; if Form1.PremadeKey.ItemIndex=15 then Form1.Key := VK_JUNJA; if Form1.PremadeKey.ItemIndex=16 then Form1.Key := VK_FINAL; if Form1.PremadeKey.ItemIndex=17 then Form1.Key := VK_HANJA; if Form1.PremadeKey.ItemIndex=18 then Form1.Key := VK_KANJI; if Form1.PremadeKey.ItemIndex=19 then Form1.Key := VK_CONVERT; if Form1.PremadeKey.ItemIndex=20 then Form1.Key := VK_NONCONVERT; if Form1.PremadeKey.ItemIndex=21 then Form1.Key := VK_ACCEPT; if Form1.PremadeKey.ItemIndex=22 then Form1.Key := VK_MODECHANGE; if Form1.PremadeKey.ItemIndex=23 then Form1.Key := VK_ESCAPE; if Form1.PremadeKey.ItemIndex=24 then Form1.Key := VK_SPACE; if Form1.PremadeKey.ItemIndex=25 then Form1.Key := VK_PRIOR; if Form1.PremadeKey.ItemIndex=26 then Form1.Key := VK_NEXT; if Form1.PremadeKey.ItemIndex=27 then Form1.Key := VK_END; if Form1.PremadeKey.ItemIndex=28 then Form1.Key := VK_HOME; if Form1.PremadeKey.ItemIndex=29 then Form1.Key := VK_LEFT; if Form1.PremadeKey.ItemIndex=30 then Form1.Key := VK_UP; if Form1.PremadeKey.ItemIndex=31 then Form1.Key := VK_RIGHT; if Form1.PremadeKey.ItemIndex=32 then Form1.Key := VK_DOWN; if Form1.PremadeKey.ItemIndex=33 then Form1.Key := VK_SELECT; if Form1.PremadeKey.ItemIndex=34 then Form1.Key := VK_PRINT; if Form1.PremadeKey.ItemIndex=35 then Form1.Key := VK_EXECUTE; if Form1.PremadeKey.ItemIndex=36 then Form1.Key := VK_SNAPSHOT; if Form1.PremadeKey.ItemIndex=37 then Form1.Key := VK_INSERT; if Form1.PremadeKey.ItemIndex=38 then Form1.Key := VK_DELETE; if Form1.PremadeKey.ItemIndex=39 then Form1.Key := VK_HELP; if Form1.PremadeKey.ItemIndex=40 then Form1.Key := VK_LWIN; if Form1.PremadeKey.ItemIndex=41 then Form1.Key := VK_RWIN; if Form1.PremadeKey.ItemIndex=42 then Form1.Key := VK_APPS; if Form1.PremadeKey.ItemIndex=43 then Form1.Key := VK_NUMPAD0; if Form1.PremadeKey.ItemIndex=44 then Form1.Key := VK_NUMPAD1; if Form1.PremadeKey.ItemIndex=45 then Form1.Key := VK_NUMPAD2; if Form1.PremadeKey.ItemIndex=46 then Form1.Key := VK_NUMPAD3; if Form1.PremadeKey.ItemIndex=47 then Form1.Key := VK_NUMPAD4; if Form1.PremadeKey.ItemIndex=48 then Form1.Key := VK_NUMPAD5; if Form1.PremadeKey.ItemIndex=49 then Form1.Key := VK_NUMPAD6; if Form1.PremadeKey.ItemIndex=50 then Form1.Key := VK_NUMPAD7; if Form1.PremadeKey.ItemIndex=51 then Form1.Key := VK_NUMPAD8; if Form1.PremadeKey.ItemIndex=52 then Form1.Key := VK_NUMPAD9; if Form1.PremadeKey.ItemIndex=53 then Form1.Key := VK_MULTIPLY; if Form1.PremadeKey.ItemIndex=54 then Form1.Key := VK_ADD; if Form1.PremadeKey.ItemIndex=55 then Form1.Key := VK_SEPARATOR; if Form1.PremadeKey.ItemIndex=56 then Form1.Key := VK_SUBTRACT; if Form1.PremadeKey.ItemIndex=57 then Form1.Key := VK_DECIMAL; if Form1.PremadeKey.ItemIndex=58 then Form1.Key := VK_DIVIDE; if Form1.PremadeKey.ItemIndex=59 then Form1.Key := VK_F1; if Form1.PremadeKey.ItemIndex=60 then Form1.Key := VK_F2; if Form1.PremadeKey.ItemIndex=61 then Form1.Key := VK_F3; if Form1.PremadeKey.ItemIndex=62 then Form1.Key := VK_F4; if Form1.PremadeKey.ItemIndex=63 then Form1.Key := VK_F5; if Form1.PremadeKey.ItemIndex=64 then Form1.Key := VK_F6; if Form1.PremadeKey.ItemIndex=65 then Form1.Key := VK_F7; if Form1.PremadeKey.ItemIndex=66 then Form1.Key := VK_F8; if Form1.PremadeKey.ItemIndex=67 then Form1.Key := VK_F9; if Form1.PremadeKey.ItemIndex=68 then Form1.Key := VK_F10; if Form1.PremadeKey.ItemIndex=69 then Form1.Key := VK_F11; if Form1.PremadeKey.ItemIndex=70 then Form1.Key := VK_F12; if Form1.PremadeKey.ItemIndex=71 then Form1.Key := VK_F13; if Form1.PremadeKey.ItemIndex=72 then Form1.Key := VK_F14; if Form1.PremadeKey.ItemIndex=73 then Form1.Key := VK_F15; if Form1.PremadeKey.ItemIndex=74 then Form1.Key := VK_F16; if Form1.PremadeKey.ItemIndex=75 then Form1.Key := VK_F17; if Form1.PremadeKey.ItemIndex=76 then Form1.Key := VK_F18; if Form1.PremadeKey.ItemIndex=77 then Form1.Key := VK_F19; if Form1.PremadeKey.ItemIndex=78 then Form1.Key := VK_F20; if Form1.PremadeKey.ItemIndex=79 then Form1.Key := VK_F21; if Form1.PremadeKey.ItemIndex=80 then Form1.Key := VK_F22; if Form1.PremadeKey.ItemIndex=81 then Form1.Key := VK_F23; if Form1.PremadeKey.ItemIndex=82 then Form1.Key := VK_F24; if Form1.PremadeKey.ItemIndex=83 then Form1.Key := VK_NUMLOCK; if Form1.PremadeKey.ItemIndex=84 then Form1.Key := VK_SCROLL; if Form1.PremadeKey.ItemIndex=85 then Form1.Key := VK_LSHIFT; if Form1.PremadeKey.ItemIndex=86 then Form1.Key := VK_RSHIFT; if Form1.PremadeKey.ItemIndex=87 then Form1.Key := VK_LCONTROL; if Form1.PremadeKey.ItemIndex=88 then Form1.Key := VK_RCONTROL; if Form1.PremadeKey.ItemIndex=89 then Form1.Key := VK_LMENU; if Form1.PremadeKey.ItemIndex=90 then Form1.Key := VK_RMENU; if Form1.PremadeKey.ItemIndex=91 then Form1.Key := VK_PROCESSKEY; if Form1.PremadeKey.ItemIndex=92 then Form1.Key := VK_ATTN; if Form1.PremadeKey.ItemIndex=93 then Form1.Key := VK_CRSEL; if Form1.PremadeKey.ItemIndex=94 then Form1.Key := VK_EXSEL; if Form1.PremadeKey.ItemIndex=95 then Form1.Key := VK_EREOF; if Form1.PremadeKey.ItemIndex=96 then Form1.Key := VK_PLAY; if Form1.PremadeKey.ItemIndex=97 then Form1.Key := VK_ZOOM; if Form1.PremadeKey.ItemIndex=98 then Form1.Key := VK_NONAME; if Form1.PremadeKey.ItemIndex=99 then Form1.Key := VK_PA1; if Form1.PremadeKey.ItemIndex=100 then Form1.Key := VK_OEM_CLEAR; end; //============================================================================== //=== Converter o "Time" em Mileseconds ======================================== Function GetTimeInMilliSeconds(theTime : TTime): Int64; var Hour, Min, Sec, MSec: Word; begin DecodeTime(theTime,Hour, Min, Sec, MSec); Result := (Hour * 3600000) + (Min * 60000) + (Sec * 1000) + MSec; end; //============================================================================== //=== Botão Start ============================================================== procedure TForm1.StartClick(Sender: TObject); var Time1:TTime; Time2:String; begin //Inicio do Timer e Visuais Start.Enabled:=False; Stop.Enabled:=True; ComboBox1.Enabled:=False; KeyBTN.Enabled:=False; KeyText.Enabled:=False; MouseBTN.Enabled:=False; PremadeKey.Enabled:=False; TimeInterval.Enabled:=False; SelectPreKey; if AutoClick.Checked then begin Time1:=StrToTime(copy(TimeInterval.Text,0,8)); Time2:=copy(TimeInterval.Text,10,12); Timer1.Interval:= GetTimeInMilliSeconds(Time1)+StrToInt(Time2); MilliInterval.Caption := IntToStr(Timer1.Interval)+' Milliseconds'; Timer1.Enabled:=True; end else begin Keybd_event(Key,0,0,0); end; end; //=== Botão Stop =============================================================== procedure TForm1.StopClick(Sender: TObject); begin //Final do Timer e Visuais Timer1.Enabled:=False; Start.Enabled:=True; Stop.Enabled:=False; KeyText.Enabled:=True; MouseBTN.Enabled:=True; PremadeKey.Enabled:=True; if AutoClick.Checked then begin ComboBox1.Enabled := True; KeyBTN.Enabled := True; TimeInterval.Enabled := True; end else begin keybd_event(Key,0,KEYEVENTF_KEYUP,0); end; end; //=== Sempre no topo =========================================================== procedure TForm1.AlwaysTopClick(Sender: TObject); begin if AlwaysTop.Checked then begin SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NoMove or SWP_NoSize); end else begin SetWindowPos(Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NoMove or SWP_NoSize); end; end; //=== Mudança de modo ========================================================== procedure TForm1.AutoClickClick(Sender: TObject); begin if AutoClick.Checked then begin ComboBox1.Enabled := True; KeyBTN.Enabled := True; TimeInterval.Enabled := True; MilliInterval.Enabled := True; end else begin ComboBox1.ItemIndex := 1; ComboBox1.OnChange(Self); ComboBox1.Enabled := False; KeyBTN.ItemIndex := 1; KeyBTN.OnChange(Self); KeyBTN.Enabled := False; TimeInterval.Enabled := False; MilliInterval.Enabled := False; end; end; //=== Troca entre Teclado e Mouse ============================================== procedure TForm1.ComboBox1Change(Sender: TObject); begin if Combobox1.ItemIndex=1 then begin KeyText.Visible:=True; KeyBTN.Visible:=True; KeyBTN.ItemIndex := 0; MouseBTN.Visible:=False; PremadeKey.Visible:=False; end; if Combobox1.ItemIndex=0 then begin KeyText.Visible:=False; KeyBTN.Visible:=False; MouseBTN.Visible:=True; PremadeKey.Visible:=False; end; end; //=== Criação do Form ========================================================== procedure TForm1.FormCreate(Sender: TObject); begin //Sempre no topo AlwaysTop.OnClick(Self); //modos AlwaysClicked.OnClick := AutoClick.OnClick; //Versão do Aplicativo Version.Caption:='[ '+VersaoExe+' ]';; end; //=== Trocar entre custom e premade ============================================ procedure TForm1.KeyBTNChange(Sender: TObject); begin //KeyText On if KeyBTN.ItemIndex = 0 then begin PremadeKey.Visible:=False; KeyText.Visible:=True; end; //PremadeKey On if KeyBTN.ItemIndex = 1 then begin PremadeKey.Visible:=True; KeyText.Visible:=False; end; end; procedure TForm1.KeyTextClick(Sender: TObject); begin KeyText.SelectAll; end; //=== Timer funcionando ======================================================== procedure TForm1.Timer1Timer(Sender: TObject); var iPos: Integer; begin //Mouse if Combobox1.ItemIndex=0 then begin //Botão Esquerdo (Left) do Mouse if MouseBTN.ItemIndex=0 then begin mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0); end; //Botão Direito (Right) do Mouse if MouseBTN.ItemIndex=1 then begin mouse_event(MOUSEEVENTF_RIGHTDOWN,0,0,0,0); mouse_event(MOUSEEVENTF_RIGHTUP,0,0,0,0); end; end; //Teclado (Keyboard) if Combobox1.ItemIndex=1 then begin //Custom Key if KeyBTN.ItemIndex=0 then begin keybd_event(Ord(KeyText.Text[1]),0,0,0); keybd_event(Ord(KeyText.Text[1]),0,KEYEVENTF_KEYUP,0); end; //Premade Key if KeyBTN.ItemIndex=1 then begin keybd_event(Key,0,0,0); keybd_event(Key,0,KEYEVENTF_KEYUP,0); end; end; end; //============================================================================== end.
{$include kode.inc} unit kode_filter_rms; { one pole filter for RMS approximation usage example: dspRMS rmsfilter; rmsfilter.setup(300, 44100); // 300ms, samplerate (can be updateSampleRate()) float rmsout = rmsfilter.process(input); // process input sample rmsfilter.reset(); // to reset the rms value } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type KFilter_RMS = class private win,fout,a0,b1 : Single; public constructor create; procedure setup(winlen:Single; srate:Single); function process(input:Single) : Single; procedure reset; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses //math, kode_const; //---------- constructor KFilter_RMS.create; begin reset; setup(300, 44100); end; //---------- { set filter coeff winlen : window length (ms) srate : sample rate } procedure KFilter_RMS.setup(winlen:Single; srate:Single); begin b1 := exp(-1/(winlen*srate*0.001)); a0 := 1 - b1; end; //---------- function KFilter_RMS.process(input:Single) : Single; begin fout := a0*input*input + b1*fout + KODE_DENORM; result := sqrt(fout); end; //---------- procedure KFilter_RMS.reset; begin win := 0; fout := 0; a0 := 0; b1 := 0; end; //---------------------------------------------------------------------- end.
unit FunChar; interface function IsAlpha(c:char):boolean; function IsDigit(c:char):boolean; function IsAlphaDigit(c:char):boolean; implementation function IsAlpha(c:char):boolean; begin IsAlpha:=((UpCase(c)>='A') and (UpCase(c)<='Z')); end; function IsDigit(c:char):boolean; begin IsDigit:=((c>='0') and (c<='9')); end; function IsAlphaDigit(c:char):boolean; begin IsAlphaDigit:=((UpCase(c)>='A') and (UpCase(c)<='Z')) or ((c>='0') and (c<='9')); end; end.
unit Compiler; interface uses Classes, Types, Generics.Collections, SysUtils, D16Parser, LineMapping, CompilerDefines, PascalUnit, UnitCache, D16Writer; type TCompiler = class(TObject) private FParser: TD16Parser; FUnits: TUnitCache; FWriter: TD16Writer; function GetErrors: Integer; function GetFatals: Integer; function GetHints: Integer; function GetLineMapping: TObjectList<TLineMapping>; function GetOnMessage: TOnMessage; function GetPeekMode: Boolean; function GetSearchPath: TStringlist; function GetWarning: Integer; procedure SetOnMessage(const Value: TOnMessage); procedure SetPeekMode(const Value: Boolean); public constructor Create(); destructor Destroy(); override; procedure CompileFile(AFile: string); procedure CompilerSource(ASource: string; AAsProgram: Boolean); procedure Reset(); function PeekCompile(ASource, AUnitName: string; AAsProgram: Boolean; var AUnit: TPascalUnit): Boolean; function GetDCPUSource(): string; function GetMappingByASMLine(ALine: Integer): TLineMapping; property SearchPath: TStringlist read GetSearchPath; property OnMessage: TOnMessage read GetOnMessage write SetOnMessage; property Errors: Integer read GetErrors; property Warnings: Integer read GetWarning; property Fatals: Integer read GetFatals; property Hints: Integer read GetHints; property PeekMode: Boolean read GetPeekMode write SetPeekMode; property Units: TUnitCache read FUnits; property LineMapping: TObjectList<TLineMapping> read GetLineMapping; end; implementation uses StrUtils; { TCompiler } procedure TCompiler.CompileFile(AFile: string); begin FParser.ParseFile(AFile); end; procedure TCompiler.CompilerSource(ASource: string; AAsProgram: Boolean); begin FParser.ParseSource(ASource, AAsProgram); end; constructor TCompiler.Create; begin inherited; FUnits := TUnitCache.Create(); FWriter := TD16Writer.Create(); FParser := TD16Parser.Create(FUnits); end; destructor TCompiler.Destroy; begin FParser.Free; FUnits.Free; FWriter.Free(); inherited; end; function TCompiler.GetDCPUSource: string; var LUnit: TPascalUnit; begin for LUnit in FUnits do begin FWriter.CurrentUnit := LUnit.Name; LUnit.GetDCPUSource(FWriter); end; Result := FWriter.Source.Text; end; function TCompiler.GetErrors: Integer; begin Result := FParser.Errors; end; function TCompiler.GetFatals: Integer; begin Result := FParser.Fatals; end; function TCompiler.GetHints: Integer; begin Result := FParser.Hints; end; function TCompiler.GetLineMapping: TObjectList<TLineMapping>; begin Result := FWriter.LineMapping; end; function TCompiler.GetMappingByASMLine(ALine: Integer): TLineMapping; begin Result := FWriter.GetMappingByASMLine(ALine); end; function TCompiler.GetOnMessage: TOnMessage; begin Result := FParser.OnMessage; end; function TCompiler.GetPeekMode: Boolean; begin Result := FParser.PeekMode; end; function TCompiler.GetSearchPath: TStringlist; begin Result := FParser.SearchPath; end; function TCompiler.GetWarning: Integer; begin Result := FParser.Warnings; end; function TCompiler.PeekCompile(ASource, AUnitName: string; AAsProgram: Boolean; var AUnit: TPascalUnit): Boolean; begin try FParser.ResetResults(); FParser.Units.ClearUnitCache(AUnitName); FParser.ParseSource(ASource, AAsProgram); AUnit := FParser.Units.GetUnitByName(AUnitName); Result := Assigned(AUnit) and (FParser.Fatals = 0) and (FParser.Errors = 0); except Result := False; end; end; procedure TCompiler.Reset; begin FParser.Reset(); end; procedure TCompiler.SetOnMessage(const Value: TOnMessage); begin FParser.OnMessage := Value; end; procedure TCompiler.SetPeekMode(const Value: Boolean); begin FParser.PeekMode := Value; end; end.
unit iaRTL.SyncBucket.Items; interface uses System.Generics.Collections, Data.DB, FireDAC.Comp.Client, iaRTL.Cloud.S3Object; type TSyncStatus = (Unknown, StatusCleared, NoChangesDetected, ChangedItem, NewItem, NotFound); TSyncItem = class private fDB:TFDConnection; fObjectKey:string; fETag:string; fSize:Int64; fSyncStatus:TSyncStatus; protected procedure SetFromDataSet(const DataSet:TDataSet); public constructor Create(const FDConnection:TFDConnection); property ObjectKey:string read fObjectKey write fObjectKey; property ETag:string read fETag write fETag; property SyncStatus:TSyncStatus read fSyncStatus write fSyncStatus; property Size:Int64 read fSize write fSize; procedure Clear; procedure SetFromS3Object(const SourceObject:TS3Object; const NewSyncStatus:TSyncStatus); function GetFromDB(const ObjectKeyToFind:string):Boolean; procedure InsertIntoDB; procedure UpdateDB; procedure UpdateDBSyncStatus; procedure DeleteFromDB; end; TSyncItemList = class(TObjectList<TSyncItem>) private fDB:TFDConnection; public constructor Create(const FDConnection:TFDConnection); procedure GetSyncItemsFromDB(const SyncStatusToFind:TSyncStatus); end; implementation uses System.SysUtils; constructor TSyncItem.Create(const FDConnection:TFDConnection); begin fDB := FDConnection; end; procedure TSyncItem.Clear; begin ObjectKey := ''; ETag := ''; Size := 0; SyncStatus := TSyncStatus.Unknown; end; procedure TSyncItem.SetFromDataSet(const DataSet:TDataSet); begin ObjectKey := DataSet.FieldByName('ObjectKey').AsString; ETag := DataSet.FieldByName('ETag').AsString; Size := DataSet.FieldByName('Size').AsLargeInt; SyncStatus := TSyncStatus(DataSet.FieldByName('SyncStatus').AsInteger); end; procedure TSyncItem.SetFromS3Object(const SourceObject:TS3Object; const NewSyncStatus:TSyncStatus); begin ObjectKey := SourceObject.ObjectKey; ETag := SourceObject.ETag; Size := SourceObject.Size; SyncStatus := NewSyncStatus; end; procedure TSyncItem.InsertIntoDB; begin fDB.ExecSQL('INSERT INTO SyncItems (ObjectKey, ETag, Size, SyncStatus) VALUES (:ObjectKey, :ETag, :Size, :SyncStatus)', [ObjectKey, ETag, Size, Ord(SyncStatus)]); end; procedure TSyncItem.UpdateDB; begin fDB.ExecSQL('UPDATE SyncItems SET ETag=:ETag, Size=:Size, SyncStatus=:Status WHERE ObjectKey=:ObjectKey', [ETag, Size, Ord(SyncStatus), ObjectKey]) end; procedure TSyncItem.UpdateDBSyncStatus; begin fDB.ExecSQL('UPDATE SyncItems SET SyncStatus=:Status WHERE ObjectKey=:ObjectKey', [Ord(SyncStatus), ObjectKey]) end; procedure TSyncItem.DeleteFromDB; begin fDB.ExecSQL('DELETE FROM SyncItems WHERE ObjectKey=:ObjectKey', [ObjectKey]); end; function TSyncItem.GetFromDB(const ObjectKeyToFind:string):Boolean; var Query:TFDQuery; begin Result := False; Self.Clear; ObjectKey := ObjectKeyToFind; SyncStatus := TSyncStatus.NewItem; Query := TFDQuery.Create(nil); try Query.Connection := fDB; Query.Open('SELECT * FROM SyncItems WHERE ObjectKey=:ObjectKey', [ObjectKeyToFind]); if not Query.IsEmpty then begin SetFromDataSet(Query); Result := True; end; finally Query.Free; end; end; constructor TSyncItemList.Create(const FDConnection:TFDConnection); begin inherited Create; fDB := FDConnection; end; procedure TSyncItemList.GetSyncItemsFromDB(const SyncStatusToFind:TSyncStatus); var Query:TFDQuery; SyncItem:TSyncItem; begin Self.Clear; Query := TFDQuery.Create(nil); try Query.Connection := fDB; Query.Open('SELECT * FROM SyncItems WHERE SyncStatus=:SyncStatus ORDER BY ObjectKey', [Ord(SyncStatusToFind)]); while not Query.Eof do begin SyncItem := TSyncItem.Create(fDB); SyncItem.SetFromDataSet(Query); Self.Add(SyncItem); Query.Next; end; finally Query.Free; end; end; end.
{ Convert between strings and portable time values. } module string_time; %include 'string2.ins.pas'; define string_t_time1; { ******************************************************************************** * * Subroutine STRING_T_TIME1 (S, LOCAL, TIME, STAT) * * Convert the string S to the time T. The string is interpreted as a local * time when LOCAL is TRUE, otherwise as a coordinated universal time. } procedure string_t_time1 ( {make time from string} in s: univ string_var_arg_t; {input string, YYYY/MM/DD.HH:MM:SS.SSS} in local: boolean; {interpret as local time, not coor univ} out time: sys_clock_t; {returned absolute time} out stat: sys_err_t); {returned completion status} val_param; var date: sys_date_t; {intermediate date/time descriptor} begin string_t_date1 ( {convert the string to its expanded date/time} s, {the input string} local, {select local versus coordinate universal time} date, {returned expanded date/time} stat); if sys_error(stat) then return; time := sys_clock_from_date (date); {convert to absolute time} end;
unit UAposta; { as apostas a serem feitas } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Generics.Collections, Generics.Defaults, UNumeros; type TAposta = class(TObject) private FNumerosAposta: TNumeros; FAcertos: Integer; public constructor Create; destructor Destroy; override; procedure Clear; procedure VerificaAcertos(ANumerosSorteados: TNumeros); property Acertos: Integer read FAcertos write FAcertos; property NumerosAposta: TNumeros read FNumerosAposta write FNumerosAposta; end; TApostas = class(TObjectList<TAposta>) end; TApostaComparer = class(TComparer<TAposta>) public function Compare(const Item1, Item2: TAposta): Integer; override; end; implementation { TAposta } procedure TAposta.Clear; begin FAcertos := 0; end; constructor TAposta.Create; begin FNumerosAposta := TNumeros.Create; end; destructor TAposta.Destroy; begin FreeAndNil(FNumerosAposta); inherited; end; procedure TAposta.VerificaAcertos(ANumerosSorteados: TNumeros); begin FAcertos := FNumerosAposta.Acertos(ANumerosSorteados); end; { TTApostaComparer } function TApostaComparer.Compare(const Item1, Item2: TAposta): Integer; begin if (Item1.Acertos < Item2.Acertos) then Result := -1 else if (Item1.Acertos > Item2.Acertos) then Result := 1 else Result := 0; end; end.
unit AboutUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TAboutForm = class(TForm) lbTitle: TLabel; Label2: TLabel; lbProgrammer: TLabel; lbLastModifiedVersion: TLabel; procedure FormCreate(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var AboutForm: TAboutForm; implementation uses GenesisConsts; {$R *.dfm} procedure TAboutForm.FormCreate(Sender: TObject); begin lbTitle.Caption := CGenTitle; lbLastModifiedVersion.Caption := 'v'+CGenVersion + ' ' + CGenLastModified; lbProgrammer.Caption := CGenProgrammer; lbTitle.Left := (Width-lbTitle.Width) div 2; lbLastModifiedVersion.Left := (Width-lbLastModifiedVersion.Width) div 2; lbProgrammer.Left := (Width-lbProgrammer.Width) div 2; end; end.
unit ucTIPOIMPRESSAO; interface uses Classes, SysUtils, TypInfo; type TTipoImpressao = (tpiArquivo, tpiEmail, tpiImpressora, tpiVisualizar); TcTipoImpressao = class private FTip : TTipoImpressao; function GetDes: String; public constructor Create(pTip : TTipoImpressao); published property _Tip : TTipoImpressao read FTip; property _Des : String read GetDes; end; function lst() : TStringList; function tip(pTip : String) : TTipoImpressao; function cod(pTip : TTipoImpressao) : String; function des(pTip : TTipoImpressao) : String; implementation { TcTipoImpressao } constructor TcTipoImpressao.Create(pTip: TTipoImpressao); begin FTip := pTip; end; function TcTipoImpressao.GetDes: String; begin Result := des(FTip); end; { TcTIPOIMPRESSAO } const TTipoImpressaoArray : Array[TTipoImpressao] of String = ('Arquivo', 'Email', 'Impressora', 'Vizualizar'); function lst: TStringList; var vTipo : TcTipoImpressao; I : Integer; begin Result := TStringList.Create; for I := Ord(Low(TTipoImpressao)) to Ord(High(TTipoImpressao)) do begin vTipo := TcTipoImpressao.Create(TTipoImpressao(I)); Result.AddObject(vTipo._Des, vTipo); end; end; function tip(pTip: String): TTipoImpressao; begin Result := TTipoImpressao(GetEnumValue(TypeInfo(TTipoImpressao), pTip)); if ord(Result) = -1 then Result := tpiVisualizar; end; function cod(pTip: TTipoImpressao): String; begin Result := GetEnumName(TypeInfo(TTipoImpressao), Integer(pTip)); end; function des(pTip: TTipoImpressao): String; begin Result := TTipoImpressaoArray[pTip]; end; end.
unit CreateObjectDialog; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Ora, Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, ActnList, ComCtrls, ToolWin, BCDialogs.Dlg, JvExComCtrls, SynEdit, Vcl.ExtCtrls, Vcl.StdCtrls, JvComCtrls, BCControls.PageControl, DAScript, BCControls.ToolBar, System.Actions, BCControls.ImageList; type TCreateObjectBaseDialog = class(TDialog) ActionList: TActionList; CancelButton: TButton; CopyToClipboardAction: TAction; CopyToClipboardToolButton: TToolButton; ImageList: TBCImageList; OKAction: TAction; OKButton: TButton; PageControl: TBCPageControl; SaveAsToolButton: TToolButton; SaveToFileAction: TAction; SourcePanel: TPanel; SourceSynEdit: TSynEdit; SourceTabSheet: TTabSheet; SourceToolBar: TBCToolBar; SourceTopPanel: TPanel; SQLEditorAction: TAction; SQLEditorToolButton: TToolButton; SynSQLSyn: TSynSQLSyn; TopPanel: TPanel; StatusBar1: TStatusBar; procedure CopyToClipboardActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure OKActionExecute(Sender: TObject); procedure OraScriptError(Sender: TObject; E: Exception; SQL: string; var Action: TErrorAction); procedure PageControlChange(Sender: TObject); procedure SaveToFileActionExecute(Sender: TObject); procedure SQLEditorActionExecute(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } function GetSQL: string; protected FObjectName: string; FOraSession: TOraSession; FSchemaParam: string; function CheckFields: Boolean; virtual; procedure CreateSQL; virtual; procedure Initialize; virtual; public { Public declarations } function ExecuteSQL: Boolean; function Open(OraSession: TOraSession; SchemaParam: string): Boolean; overload; function Open(OraSession: TOraSession; SchemaParam: string; ObjectName: string): Boolean; overload; end; implementation {$R *.dfm} uses Main, OraScript, OraError, Lib, Vcl.Themes, BCCommon.StyleUtils, BCCommon.Messages; procedure TCreateObjectBaseDialog.PageControlChange(Sender: TObject); begin CreateSQL; end; procedure TCreateObjectBaseDialog.CopyToClipboardActionExecute(Sender: TObject); begin Lib.CopyAllToClipboard(SourceSynEdit); end; procedure TCreateObjectBaseDialog.OKActionExecute(Sender: TObject); begin if not CheckFields then Exit; ModalResult := mrOk; end; procedure TCreateObjectBaseDialog.SaveToFileActionExecute(Sender: TObject); begin Lib.SaveSQL(Handle, SourceSynEdit); end; procedure TCreateObjectBaseDialog.SQLEditorActionExecute(Sender: TObject); begin MainForm.LoadSQLIntoEditor(Format('%s@%s', [FOraSession.Schema, FOraSession.Server]), SourceSynEdit.Text); ModalResult := mrCancel; end; function TCreateObjectBaseDialog.CheckFields: Boolean; begin Result := True; end; procedure TCreateObjectBaseDialog.Initialize; begin SourceSynEdit.Text := ''; UpdateMargin(SourceSynEdit); UpdateSQLSynColors(SynSQLSyn); if Assigned(TStyleManager.ActiveStyle) then PageControl.DoubleBuffered := TStyleManager.ActiveStyle.Name = 'Windows'; end; function TCreateObjectBaseDialog.Open(OraSession: TOraSession; SchemaParam: string): Boolean; begin FOraSession := OraSession; Lib.SetSession(Self, OraSession); FSchemaParam := SchemaParam; Initialize; Result := ShowModal = mrOk; end; function TCreateObjectBaseDialog.Open(OraSession: TOraSession; SchemaParam: string; ObjectName: string): Boolean; begin FObjectName := ObjectName; Result := Open(OraSession, SchemaParam); end; procedure TCreateObjectBaseDialog.CreateSQL; begin ; end; function TCreateObjectBaseDialog.GetSQL: string; begin CreateSQL; Result := SourceSynEdit.Text; end; procedure TCreateObjectBaseDialog.OraScriptError(Sender: TObject; E: Exception; SQL: string; var Action: TErrorAction); begin ShowErrorMessage(E.Message); Action := eaFail; end; function TCreateObjectBaseDialog.ExecuteSQL: Boolean; begin Result := True; with TOraScript.Create(nil) do try Session := FOraSession; SQL.Text := GetSQL; OnError := OraScriptError; try Execute; except on E: EOraError do Result := False; end; finally Free; end; end; procedure TCreateObjectBaseDialog.FormDestroy(Sender: TObject); var i: Integer; begin for i := 0 to ComponentCount - 1 do if (Components[i] is TOraQuery) then if TOraQuery(Components[i]).Active then TOraQuery(Components[i]).Close; end; procedure TCreateObjectBaseDialog.FormShow(Sender: TObject); begin inherited; PageControl.ActivePageIndex := 0; SourceTabSheet.Caption := 'Source'; { page control inheritance bug fix } end; end.
unit ShowMsg; interface uses Classes, Controls, Forms, StdCtrls, ExtCtrls, Buttons; procedure ShowMessageEx(Title, Text: string); implementation procedure FreeAndNil(var Obj); var Temp: TObject; begin Temp := TObject(Obj); Pointer(Obj) := nil; Temp.Free; end; function Max(const A, B: Integer): Integer; begin if A > B then Result := A else Result := B; end; procedure ShowMessageEx(Title, Text: string); var Dialog: TForm; Button: TBitBtn; Caption: TLabel; Panel: TPanel; List: TStringList; Wdth, Hght, I: Integer; begin Dialog := TForm.Create(Application); Dialog.Position := poScreenCenter; Dialog.BorderStyle := bsSingle; Dialog.BorderIcons := [biSystemMenu]; Dialog.Font.Name := 'Tahoma'; Dialog.Font.Size := 8; Dialog.Caption := Title; Button := TBitBtn.Create(Dialog); Button.Parent := Dialog; Button.Caption := 'OK'; Button.Cursor := crHandPoint; Button.ModalResult := mrOk; Panel := TPanel.Create(Dialog); Panel.Parent := Dialog; Panel.Anchors := [akLeft, akTop, akRight, akBottom]; Panel.Width := Dialog.ClientWidth; Panel.Height := (Dialog.ClientHeight - Button.Height) - 6; Panel.Ctl3D := false; Panel.Color := 16777215; // clWhite; Panel.FullRepaint := true; Panel.ParentColor := false; Panel.ParentBackground := false; Button.Top := Panel.Height + 4; Button.Left := (Dialog.ClientWidth - Button.Width) - 3; Button.Anchors := [akRight, akBottom]; Button.Font.Name := 'Tahoma'; Button.Font.Size := 8; List := TStringList.Create; List.Text := Text; Caption := TLabel.Create(Panel); Caption.Parent := Panel; Caption.Anchors := [akLeft, akTop, akRight, akBottom]; Caption.Alignment := taLeftJustify; Caption.WordWrap := true; Caption.Caption := List.Text; Caption.ParentColor := false; Caption.Color := 16777215; // clWhite; Caption.Top := 5; Caption.Left := 5; Caption.Width := Panel.ClientWidth - 10; Caption.Height := Panel.ClientHeight - 10; Caption.Transparent := false; Wdth := 0; Hght := 0; if List.Count >= 0 then begin for I := 0 to List.Count - 1 do Wdth := Max(Wdth, Caption.Canvas.TextWidth(List.Strings[I])); Hght := Caption.Canvas.TextHeight('Hg') * List.Count - 1; end; Dialog.ClientWidth := Wdth + 10; Dialog.ClientHeight := Hght + ((Dialog.ClientHeight - Panel.Height) + 15); Dialog.ShowModal; FreeAndNil(List); FreeAndNil(Caption); FreeAndNil(Button); FreeAndNil(Panel); FreeAndNil(Dialog); end; end.
unit HttpServerCommand; interface uses vcl.forms, IdContext, IdCustomHTTPServer, CommandRegistry, System.SysUtils, classes; type TOnLogMessage = procedure (const msg: String) of Object; type THttpServerCommand = class(TComponent) strict private FOnLogMessage: TOnLogMessage; FCommands: THttpServerCommandRegister; private function FindCommand(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo): boolean; procedure SendError(ACmd: TRESTCommandREG;AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; E: Exception); procedure LogMessage(const msg: String); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); property Commands: THttpServerCommandRegister read FCommands; property OnLogMessage: TOnLogMessage read FOnLogMessage write FOnLogMessage; end; implementation { THttpServerCommand } procedure THttpServerCommand.LogMessage(const msg: String); begin if assigned(FOnLogMessage) then OnLogMessage(msg); end; function THttpServerCommand.FindCommand(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo): boolean; var cmdReg: TRESTCommandREG; cmd: TRESTCommand; Params: TStringList; begin Params:= TStringList.Create; try cmdReg:= FCommands.FindCommand(ARequestInfo.Command,ARequestInfo.URI, Params); if cmdReg=nil then exit(false); try cmd := cmdReg.FCommand.create; try cmd.Start(cmdReg, AContext, ARequestInfo, AResponseInfo, Params); LogMessage(cmd.StreamContents); cmd.Execute(self.Owner as TForm); // Again with the TForm finally cmd.Free; end; except on e:Exception do begin SendError(cmdReg, AContext, ARequestInfo, AResponseInfo, e); end; end; result:= true; finally params.Free; end; end; procedure THttpServerCommand.SendError(ACmd: TRESTCommandREG; AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; E: Exception); begin AResponseInfo.ResponseNo := 404; end; procedure THttpServerCommand.CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); begin if not FindCommand(AContext,ARequestInfo,AResponseInfo) then AResponseInfo.ResponseNo := 404; end; constructor THttpServerCommand.Create(AOwner: TComponent); begin inherited Create(AOwner); FCommands:= THttpServerCommandRegister.Create(self); end; destructor THttpServerCommand.Destroy; begin FCommands.Free; inherited; end; end.
unit VisibleDSA.CircleData; interface uses System.SysUtils; type TCircleData = class(TObject) private _depth: integer; _startR: integer; _startX: integer; _startY: integer; _step: integer; public constructor Create(x, y, r, depth, step: integer); destructor Destroy; override; property StartX: integer read _startX; property StartY: integer read _startY; property StartR: integer read _startR; property Depth: integer read _depth; property Step: integer read _step; end; implementation { TCircleData } constructor TCircleData.Create(x, y, r, depth, step: integer); begin _startX := x; _startY := y; _startR := r; _depth := depth; _step := step; end; destructor TCircleData.Destroy; begin inherited Destroy; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 365 of 367 From : Peter Beeftink 1:163/307.25 11 Apr 93 16:03 To : Bo Bendtsen 2:231/111.0 Subj : International characters ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ Hello Bo! Friday April 09 1993 12:28, Bo Bendtsen wrote to All: BB> Upper/lower changing of strings are always a difficult problem, BB> but as a person living in Denmark i must normally care about BB> danish characters, Possibly you like the method as shown underneath Bo! I picked this up in this echo I believe. You can modify the 'special changes' as required. Peter } function StrUpper(Str: String): String; Assembler; ASM jmp @Start { Jump over Table declared in the Code Segment } @Table: { characters from ASCII 0 --> ASCII 96 stay the same } DB 00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21 DB 22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43 DB 44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65 DB 66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87 DB 88,89,90,91,92,93,94,95,96 { characters from ASCII 97 "a" --> ASCII 122 "z" get translated } { to characters ASCII 65 "A" --> ASCII 90 "Z" } DB 65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86 DB 87,88,89,90 { characters from ASCII 123 --> ASCII 127 stay the same } DB 123,124,125,126,127 { characters from ASCII 128 --> ASCII 165 some changes #129 --> #154, #130 --> #144, #132 --> #142, #134 --> #143 #135 --> #128, #145 --> #146, #148 --> #153, #164 --> #165} DB 128,154,144,131,142,133,143,128,136,137,138,139,140,141,142,143 DB 144,146,146,147,153,149,150,151,152,153,154,155,156,157,158,159 DB 160,161,162,163,165,165 { characters from ASCII 166 --> ASCII 255 stay the same } DB 166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181 DB 182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197 DB 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213 DB 214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229 DB 230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245 DB 246,247,248,249,250,251,252,253,254,255 @Start: push DS { Save Turbo's Data Segment address } lds SI,Str { DS:SI points to Str[0] } les DI,@Result { ES:DI points to StrUpper[0] } cld { Set direction to forward } xor CX,CX { CX = 0 } mov BX,OFFSET @Table { BX = Offset address of LookUpTable } lodsb { AL = Length(Str); SI -> Str[1] } mov CL,AL { CL = Length(Str) } stosb { Move Length(Str) to Length(StrUpper) } jcxz @Exit { Get out if Length(Str) is zero } @GetNext: lodsb { Load next character into AL } segcs XLAT { Translate char using the LookupTable } { located in Code Segment at offset BX } stosb { Save next translated char in StrUpper} loop @GetNext { Get next character } @Exit: pop DS { Restore Turbo's Data Segment address } end {StrUpper};
{$include kode.inc} unit syn_s2_voice; //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_voice, syn_s2_env, syn_s2_lfo, syn_s2_osc, syn_s2_mix; //syn_s2_osc_phase, //syn_s2_osc_phase_shape, //syn_s2_osc_wave, //syn_s2_osc_wave_shape, //syn_s2_osc_filter, //syn_s2_osc_volume, type s2_voice = class(KVoice) private avg_count : longint; avg_value : single; private FEnv : array[0..2] of s2_env_proc; FLfo : array[0..2] of s2_lfo_proc; FOsc : array[0..2] of s2_osc_proc; FMix : s2_mix_proc; private FMidiNote : Single; FMidiVel : Single; FPitchBend : Single; public property midinote : Single read FMidiNote; property midivel : Single read FMidiVel; property pitchbend : Single read FPitchBend; public constructor create(AManager:Pointer); destructor destroy; override; public function getEnv(AIndex:LongInt) : s2_env_proc; function getLfo(AIndex:LongInt) : s2_lfo_proc; function getOsc(AIndex:LongInt) : s2_osc_proc; procedure checkReleased(val:Single); public procedure on_noteOn(ANote,AVel:Single); override; procedure on_noteOff(ANote,AVel:Single); override; procedure on_pitchBend(ABend:Single); override; procedure on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); override; procedure on_process(outs:PSingle); override; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses math, // power kode_const, kode_debug, kode_flags, syn_s2, syn_s2_const, syn_s2_voicemanager; const S2_AVG_SIZE = 2048; S2_AVG_THRESHOLD = 0.001; //---------- constructor s2_voice.create(AManager:Pointer); var i : longint; begin inherited; for i := 0 to 2 do FEnv[i] := s2_env_proc.create(self,i); for i := 0 to 2 do FLfo[i] := s2_lfo_proc.create(self,i); for i := 0 to 2 do FOsc[i] := s2_osc_proc.create(self,i); FMix := s2_mix_proc.create(self); avg_count := 0; avg_value := 0; FMidiNote := 0; FMidiVel := 0; FPitchBend := 0; end; //---------- destructor s2_voice.destroy; var i : longint; begin for i := 0 to 2 do FEnv[i].destroy; for i := 0 to 2 do FLfo[i].destroy; for i := 0 to 2 do FOsc[i].destroy; FMix.destroy; inherited; end; //---------------------------------------------------------------------- function s2_voice.getEnv(AIndex:LongInt) : s2_env_proc; begin result := FEnv[AIndex]; end; //---------- function s2_voice.getLfo(AIndex:LongInt) : s2_lfo_proc; begin result := FLfo[AIndex]; end; //---------- function s2_voice.getOsc(AIndex:LongInt) : s2_osc_proc; begin result := FOsc[AIndex]; end; //---------- procedure s2_voice.checkReleased(val:Single); begin //if state = kvs_released then state := kvs_off; if FState = kvs_released then begin if avg_count < S2_AVG_SIZE then begin avg_value += (val*val); // avg_value := (avg_value * 0.999) + (o*o); avg_count += 1; end else begin //if sqrt(avg_value) < 0.01 {KODE_TINY} then FState := voice_state_off; if avg_value < S2_AVG_THRESHOLD then FState := kvs_off; avg_value := 0; avg_count := 0; end; end; end; //---------------------------------------------------------------------- procedure s2_voice.on_noteOn(ANote,AVel:Single); var i : longint; //vm : s2_voice_manager; begin FMidiNote := ANote; FMidiVel := AVel; //vm := s2_voice_manager(manager); //vm.setModValue( s2m_key, ANote ); //vm.setModValue( s2m_key, ANote ); //FPitch := ANote - 69.0 + FPitchBend + (FOct*12) + FSemi + (FCent*KODE_INV50); //FHz := 440 * power(2.0,FPitch*KODE_INV12); FState := kvs_playing; for i := 0 to 2 do FEnv[i].noteOn(ANote,AVel); for i := 0 to 2 do FLfo[i].noteOn(ANote,AVel); for i := 0 to 2 do FOsc[i].noteOn(ANote,AVel); avg_count := 0; avg_value := 0; end; //---------- procedure s2_voice.on_noteOff(ANote,AVel:Single); var i : LongInt; begin FState := kvs_released; for i := 0 to 2 do FEnv[i].noteOff(ANote,AVel); for i := 0 to 2 do FLfo[i].noteOff(ANote,AVel); for i := 0 to 2 do FOsc[i].noteOff(ANote,AVel); end; //---------- procedure s2_voice.on_pitchBend(ABend:Single); var i : longint; vm : s2_voicemanager; begin FPitchBend := ABend; vm := s2_voicemanager(voicemanager); vm.setModValue( s2m_bend, ABend ); for i := 0 to 2 do FEnv[i].pitchBend(ABend); for i := 0 to 2 do FLfo[i].pitchBend(ABend); for i := 0 to 2 do FOsc[i].pitchBend(ABend); end; //---------- procedure s2_voice.on_control(AIndex:LongInt; AVal:Single; AGroup:LongInt=-1; ASubGroup:LongInt=-1); var osc,env,lfo : longint; begin case AGroup of s2g_osc1, s2g_osc2, s2g_osc3: begin osc := AGroup - s2g_osc1; FOsc[osc].control(ASubGroup,AIndex,AVal); end; s2g_mix: FMix.control(AIndex,AVal); s2g_env1, s2g_env2, s2g_env3: begin env := AGroup - s2g_env1; FEnv[env].control(AIndex,AVal); end; s2g_lfo1, s2g_lfo2, s2g_lfo3: begin lfo := AGroup - s2g_lfo1; FLfo[lfo].control(AIndex,AVal); end; end; end; //---------- procedure s2_voice.on_process(outs:PSingle); var vm : s2_voicemanager; i : longint; val : single; //left,right : single; begin vm := s2_voicemanager(voicemanager); for i := 0 to 2 do vm.setModValue( s2m_env1+i, FEnv[i].process ); for i := 0 to 2 do vm.setModValue( s2m_lfo1+i, FLfo[i].process ); for i := 0 to 2 do vm.setModValue( s2m_osc1+i, FOsc[i].process(i) ); //left := FMix.process; //right := left; val := FMix.process; outs[0] := val;//left; outs[1] := val;//right; checkReleased(val); end; //---------------------------------------------------------------------- end.
(* @file UMenuLine.pas * @author Willi Schinmeyer * @date 2011-10-28 * * UMenuLine Unit * * Contains the TMenuLine type. *) unit UMenuLine; interface type (* @brief Represents a line of text in a menu part. * * Can be centered. *) TMenuLine = record text : string; centered : boolean; end; implementation begin end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, simpftp, ComCtrls, Menus, WinInetControl; type TformMain = class(TForm) lboxStatus: TListBox; ftpc: TSimpleFTP; butnUpload: TButton; chckUploadAll: TCheckBox; chckProxy: TCheckBox; Label2: TLabel; Label3: TLabel; Label5: TLabel; lablProxyLabel: TLabel; lablServer: TLabel; lablUsername: TLabel; lablDestination: TLabel; lablProxy: TLabel; Label6: TLabel; lablFile: TLabel; MainMenu1: TMainMenu; File1: TMenuItem; itemFile_Exit: TMenuItem; N1: TMenuItem; itemFile_CreateDefaultConfig: TMenuItem; itemFile_Upload: TMenuItem; lablCurrent: TLabel; Label1: TLabel; ProgressBar1: TProgressBar; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure butnUploadClick(Sender: TObject); procedure chckProxyClick(Sender: TObject); procedure itemFile_ExitClick(Sender: TObject); procedure itemFile_CreateDefaultConfigClick(Sender: TObject); private procedure LoadFile(const sFile: String); public slstParams: TStringList; msProxy, msInputFile, msSource, msDest: String; mbSubDirs: Boolean; procedure Upload(const psPath: string; const pbUploadAll: Boolean; const pbIsSubDir: boolean); end; var formMain: TformMain; implementation {$R *.DFM} Uses Edit , GlobalWinshoe; procedure TformMain.LoadFile; begin if FileExists(msInputFile) then slstParams.LoadFromFile(msInputFile); lablFile.Caption := ExtractFileName(msInputFile); msSource := slstParams.Values['Source']; if length(msSource) = 0 then msSource := ExtractFilePath(msInputFile); if Copy(msSource, Length(msSource), 1) <> '\' then msSource := msSource + '\'; msProxy := 'proxy'; lablProxy.Caption := msProxy; msDest := slstParams.Values['Dest']; if Pos(Copy(msDest, Length(msDest), 1), '\/') = 0 then msDest := msDest + '/'; lablDestination.Caption := msDest; lablUsername.Caption := slstParams.Values['User']; lablServer.Caption := slstParams.Values['Server']; end; procedure TformMain.FormCreate(Sender: TObject); begin slstParams := TStringList.Create; if ParamCount > 0 then msInputFile := ParamStr(1) else msInputFile := ExtractFilePath(Application.EXEName) + 'default.bftp'; LoadFile(msInputFile); end; procedure TformMain.FormDestroy(Sender: TObject); begin slstParams.Free; end; procedure TformMain.Upload; var i: integer; bResult: Boolean; srch: TSearchRec; begin ftpc.LocalDir := msSource + psPath; if not ftpc.ChangeRemoteDir(msDest + StringReplace(psPath, '\', '/' , [rfReplaceall])) then begin ftpc.MkDir(msDest + StringReplace(psPath, '\', '/', [rfReplaceall])); ftpc.ChangeRemoteDir(msDest + StringReplace(psPath, '\', '/', [rfReplaceall])); end; i := FindFirst(msSource + psPath + '*.*', faReadOnly + faArchive, srch); try while i = 0 do begin if ((FileGetAttr(msSource + psPath + srch.Name) and faArchive) <> 0) or pbUploadAll then begin lboxStatus.Items.Add(psPath + srch.name); lboxStatus.ItemIndex := lboxStatus.Items.Count - 1; bResult := ftpc.PutFile(srch.name); if bResult then FileSetAttr(msSource + psPath + srch.Name, FileGetAttr(msSource + psPath + srch.Name) and (not faArchive)) else lboxStatus.Items.Add(' Put Failed: ' + ftpc.LastError); end; i := FindNext(srch); end; finally FindClose(srch); end; if mbSubDirs then begin i := FindFirst(msSource + psPath + '*.*', faDirectory, srch); Try while i = 0 do begin if (srch.name <> '.') and (srch.name <> '..') and ((srch.Attr and faDirectory) <> 0) then Upload(psPath + srch.Name + '\', pbUploadAll, True); i := FindNext(srch); end; finally FindClose(srch); end; end; end; procedure TformMain.butnUploadClick(Sender: TObject); begin lboxStatus.Items.Clear; butnUpload.Enabled := False; try mbSubDirs := slstParams.Values['NoSubDirs'] = ''; if not mbSubDirs then mbSubDirs := UpperCase(slstParams.Values['NoSubDirs'][1]) <> 'F'; with ftpc do begin if chckProxy.checked then begin Hostname := msProxy; Username := slstParams.Values['User'] + '@' + slstParams.Values['Server']; end else begin Hostname := slstParams.Values['Server']; Username := slstParams.Values['User']; end; Password := slstParams.Values['Password']; if length(Password) = 0 then Password := Trim(InputBox('', 'Enter Password:', '')); lboxStatus.Items.Add('Connecting to ' + Hostname); Connect; Try Upload('', chckUploadAll.Checked, False); finally Disconnect; end; end; finally lboxStatus.Items.Add('----Done'); lboxStatus.ItemIndex := lboxStatus.Items.Count - 1; butnUpload.Enabled := True; end; end; procedure TformMain.chckProxyClick(Sender: TObject); begin lablProxy.Visible := chckProxy.Checked; lablProxyLabel.Visible := lablProxy.Visible; end; procedure TformMain.itemFile_ExitClick(Sender: TObject); begin Close; end; procedure TformMain.itemFile_CreateDefaultConfigClick(Sender: TObject); begin with TFormEdit.Create(Self) do try LoadFile(ExtractFilePath(Application.EXEName) + 'default.bftp'); if ShowModal = mrOK then LoadFile(btedFile.text); finally free; end; end; end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, TeeProcs, TeEngine, Chart, ComCtrls, Series, Math; const Ball_const = 15; LENGTH = 1; PERIOD = 50; DT = 0.05; g = 9.8; n = 2000; type myArray = array [0..n]of double; TBall = record Length : Single; Angle : Single; Velocity : Single; end; TForm1 = class(TForm) Label1: TLabel; OscPlot: TChart; TrackBarDamping: TTrackBar; TrackBarInitialAngle: TTrackBar; Label2: TLabel; Label3: TLabel; Label4: TLabel; TrackBarForce: TTrackBar; Button1: TButton; Button2: TButton; Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Series1: TLineSeries; Timer1: TTimer; imagePendulum: TImage; GroupBox1: TGroupBox; Label5: TLabel; Label6: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure TrackBarDampingChange(Sender: TObject); procedure TrackBarInitialAngleChange(Sender: TObject); procedure TrackBarForceChange(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GambarPendulum(teta: Double); procedure GambarGrafik(); procedure Button2Click(Sender: TObject); private { Private declarations } time : Integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var x0, y0 : integer; x1, y1 : integer; teta0, teta1: real; begin time := 0; x0 := 100; y0 := 60; teta0 := degtorad (StrToFloat(Edit2.Text)); x1 := Round (x0 + 400*sin(teta0)); y1 := Round (y0 + 200*cos(teta0)); Canvas.MoveTo(x0,y0); Canvas.LineTo(x1,y1); Canvas.Ellipse(x1-15, y1-15, x1+15, y1+15); end; procedure TForm1.GambarPendulum(teta: Double); var x0, y0 : integer; x1, y1 : integer; teta0, teta1: real; begin x0 := 100; y0 := 50; teta0 := degtorad(teta); x1 := Round (x0 + 400 * sin(teta0)); y1 := Round (y0 + 200 * cos(teta0)); //with imagePendulum.Canvas do //begin //Canvas.Brush.Color := clWhite; Canvas.Rectangle(imagePendulum.Left, imagePendulum.Top, imagePendulum.Left + imagePendulum.Width, imagePendulum.Top + imagePendulum.Height); Canvas.MoveTo(x0,y0); Canvas.LineTo(x1,y1); Canvas.Ellipse(x1-15, y1-15, x1+15, y1+15); //end;} end; procedure TForm1.Button1Click(Sender: TObject); begin time := 0; Timer1.Enabled := true; TrackBarDamping.Enabled := false; TrackBarInitialAngle.Enabled := false; TrackBarForce.Enabled := false; end; procedure TForm1.GambarGrafik; var teta1, D, angle : real; omega, teta, t : myArray; i : integer; F, teta0, q : double; begin F := StrToFloat(Edit3.Text); teta0 := StrToFloat(Edit2.Text); q := StrToFloat(Edit1.Text); D := 0.2; t[0] := 0; omega[0] := 1; teta[0] := degtorad (teta0); OscPlot.Series[0].Clear; for i := 1 to time do begin omega[i+1] := omega[i] - ((g/LENGTH) * sin (degtorad(teta[i]))+ q * omega[i] + F * sin (degtorad(D * t[i]))) * dt; teta[i+1] := teta[i] + omega[i+1]*dt; t[i+1] := t[i] + dt; OscPlot.Series[0].AddXY(t[i],teta[i]); end; GambarPendulum(teta[time]); end; procedure TForm1.TrackBarDampingChange(Sender: TObject); var q: double; begin q := TrackBarDamping.Position; Edit1.Text := FLoatToStr(q/10); end; procedure TForm1.TrackBarInitialAngleChange(Sender: TObject); var teta0 : double; begin teta0 := TrackBarInitialAngle.Position; Edit2.Text := FLoatToStr(teta0); GambarPendulum(teta0); end; procedure TForm1.TrackBarForceChange(Sender: TObject); var F : double; begin F := TrackBarForce.Position; Edit3.Text := FLoatToStr(F/10); end; procedure TForm1.Timer1Timer(Sender: TObject); begin time := time + 1; if (time = n) then time := 0; GambarGrafik; end; procedure TForm1.Button2Click(Sender: TObject); begin Timer1.Enabled := false; TrackBarDamping.Enabled := True; TrackBarInitialAngle.Enabled := True; TrackBarForce.Enabled := True; end; end.
unit BinData; interface type HCkBinData = Pointer; HCkStringBuilder = Pointer; HCkByteData = Pointer; HCkString = Pointer; function CkBinData_Create: HCkBinData; stdcall; procedure CkBinData_Dispose(handle: HCkBinData); stdcall; function CkBinData_getLastMethodSuccess(objHandle: HCkBinData): wordbool; stdcall; procedure CkBinData_putLastMethodSuccess(objHandle: HCkBinData; newPropVal: wordbool); stdcall; function CkBinData_getNumBytes(objHandle: HCkBinData): Integer; stdcall; function CkBinData_AppendBd(objHandle: HCkBinData; binData: HCkBinData): wordbool; stdcall; function CkBinData_AppendBinary(objHandle: HCkBinData; data: HCkByteData): wordbool; stdcall; function CkBinData_AppendBom(objHandle: HCkBinData; charset: PWideChar): wordbool; stdcall; function CkBinData_AppendEncoded(objHandle: HCkBinData; encData: PWideChar; encoding: PWideChar): wordbool; stdcall; function CkBinData_AppendEncodedSb(objHandle: HCkBinData; sb: HCkStringBuilder; encoding: PWideChar): wordbool; stdcall; function CkBinData_AppendSb(objHandle: HCkBinData; sb: HCkStringBuilder; charset: PWideChar): wordbool; stdcall; function CkBinData_AppendString(objHandle: HCkBinData; str: PWideChar; charset: PWideChar): wordbool; stdcall; function CkBinData_Clear(objHandle: HCkBinData): wordbool; stdcall; function CkBinData_ContentsEqual(objHandle: HCkBinData; binData: HCkBinData): wordbool; stdcall; function CkBinData_GetBinary(objHandle: HCkBinData; outData: HCkByteData): wordbool; stdcall; function CkBinData_GetBinaryChunk(objHandle: HCkBinData; offset: Integer; numBytes: Integer; outData: HCkByteData): wordbool; stdcall; function CkBinData_GetEncoded(objHandle: HCkBinData; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkBinData__getEncoded(objHandle: HCkBinData; encoding: PWideChar): PWideChar; stdcall; function CkBinData_GetEncodedChunk(objHandle: HCkBinData; offset: Integer; numBytes: Integer; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkBinData__getEncodedChunk(objHandle: HCkBinData; offset: Integer; numBytes: Integer; encoding: PWideChar): PWideChar; stdcall; function CkBinData_GetEncodedSb(objHandle: HCkBinData; encoding: PWideChar; sb: HCkStringBuilder): wordbool; stdcall; function CkBinData_GetString(objHandle: HCkBinData; charset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkBinData__getString(objHandle: HCkBinData; charset: PWideChar): PWideChar; stdcall; function CkBinData_LoadBinary(objHandle: HCkBinData; data: HCkByteData): wordbool; stdcall; function CkBinData_LoadEncoded(objHandle: HCkBinData; encData: PWideChar; encoding: PWideChar): wordbool; stdcall; function CkBinData_LoadFile(objHandle: HCkBinData; path: PWideChar): wordbool; stdcall; function CkBinData_RemoveChunk(objHandle: HCkBinData; offset: Integer; numBytes: Integer): wordbool; stdcall; function CkBinData_SecureClear(objHandle: HCkBinData): wordbool; stdcall; function CkBinData_WriteFile(objHandle: HCkBinData; path: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkBinData_Create; external DLLName; procedure CkBinData_Dispose; external DLLName; function CkBinData_getLastMethodSuccess; external DLLName; procedure CkBinData_putLastMethodSuccess; external DLLName; function CkBinData_getNumBytes; external DLLName; function CkBinData_AppendBd; external DLLName; function CkBinData_AppendBinary; external DLLName; function CkBinData_AppendBom; external DLLName; function CkBinData_AppendEncoded; external DLLName; function CkBinData_AppendEncodedSb; external DLLName; function CkBinData_AppendSb; external DLLName; function CkBinData_AppendString; external DLLName; function CkBinData_Clear; external DLLName; function CkBinData_ContentsEqual; external DLLName; function CkBinData_GetBinary; external DLLName; function CkBinData_GetBinaryChunk; external DLLName; function CkBinData_GetEncoded; external DLLName; function CkBinData__getEncoded; external DLLName; function CkBinData_GetEncodedChunk; external DLLName; function CkBinData__getEncodedChunk; external DLLName; function CkBinData_GetEncodedSb; external DLLName; function CkBinData_GetString; external DLLName; function CkBinData__getString; external DLLName; function CkBinData_LoadBinary; external DLLName; function CkBinData_LoadEncoded; external DLLName; function CkBinData_LoadFile; external DLLName; function CkBinData_RemoveChunk; external DLLName; function CkBinData_SecureClear; external DLLName; function CkBinData_WriteFile; external DLLName; end.
unit Sqlctrls; interface uses SysUtils,Controls,Classes,Menus,DBTables,StdCtrls; Type TValueNotifyEvent=procedure(Sender:TObject;var sl:TStringList) of object; Type TSetValueNotifyEvent=procedure(Sender:TObject;var q:TQuery) of object; const DeltaX=4; const DeltaY=4; Type TSQLControl=class(TWinControl) protected fFieldName:string; fCaptionID:longint; fValueEvent:TValueNotifyEvent; fSetValueEvent:TSetValueNotifyEvent; procedure WriteCaptionID(l:longint); public procedure SetBoundsEx(x,y,dx,dy:integer); procedure SetRight(c:TControl;dx,dy:integer); procedure SetDown(c:TControl;dx,dy:integer); procedure Value(sl:TStringList); virtual; procedure SetValue(var q:TQuery); virtual; procedure GetValue(sl:TStringList;SepFlag:boolean); virtual; procedure SetValueF(q:TQuery;fn:string); published property Enabled; property Visible; property FieldName:string read fFieldName write fFieldName; property CaptionID:longint read fCaptionID write WriteCaptionID; property OnGetValue:TValueNotifyEvent read fValueEvent write fValueEvent; property OnSetValue:TSetValueNotifyEvent read fSetValueEvent write fSetValueEvent; end; implementation Uses tenvirnt,lbledit; {=========== TSQLControl ==============} procedure TSQLControl.SetValue(var q:TQuery); begin end; procedure TSQLControl.Value(sl:TStringList); begin end; procedure TSQLControl.GetValue(sl:TStringList;SepFlag:boolean); begin Value(sl); if SepFlag then sl.Add(','); end; procedure TSQLControl.SetBoundsEx(x,y,dx,dy:integer); begin if dy=-1 then dy:=Height; SetBounds(x,y,dx,dy); end; procedure TSQLControl.SetRight(c:TControl;dx,dy:integer); begin SetBoundsEx(c.Left+c.Width+DeltaX,c.Top,dx,dy); end; procedure TSQLControl.SetDown(c:TControl;dx,dy:integer); begin if dx=-1 then dx:=c.Width; SetBoundsEx(c.Left,c.Top+c.Height+DeltaY,dx,dy); end; procedure TSQLControl.SetValueF(q:TQuery;fn:string); var oldfn:string; begin oldfn:=FieldName; FieldName:=fn; SetValue(q); FieldName:=oldfn; end; procedure TSQLControl.WriteCaptionID(l:longint); var i:longint; s:string; begin fCaptionID:=l; if (Enviroment<>NIL) and (l<>0) then begin for i:=0 to ControlCount-1 do begin if Controls[i] is TLabel then begin s:=Enviroment.GetCaption(l); if s<>'' then TLabel(Controls[i]).Caption:=s+':'; end; if Controls[i] is TLabelEdit then begin s:=Enviroment.GetCaption(l); if s<>'' then TLabelEdit(Controls[i]).Caption:=s+':'; end; end; end; end; end.
unit Linea; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox, FMX.StdCtrls, FMX.Layouts, FMX.Edit, FMX.Controls.Presentation; type TLineas = class(TForm) ToolBar1: TToolBar; EditLinea: TEdit; Layout1: TLayout; btnGuardarLinea: TButton; ComboLinea: TComboBox; BtnBorrarLinea: TButton; LayoutLinea: TLayout; LayoutEmp: TLayout; Layout3: TLayout; EditEmp: TEdit; BtnGuardarEmp: TButton; ComboEmpleado: TComboBox; BtnBorrarEmp: TButton; EdtGanancia: TEdit; Layout2: TLayout; Layout4: TLayout; EdtTrabajo: TEdit; BtnGuardarTrabajo: TButton; BtnBorrarTrabajo: TButton; ComboTrabajo: TComboBox; EdtInfo: TEdit; procedure InsertarLinea; procedure InsertarEmpleado; procedure InsertarTrabajo; procedure BorrarEmpleado; procedure BorrarLinea; procedure BorrarTrabajo; procedure BuscarLinea; procedure BuscarEmp; procedure BuscarTrabajo; procedure btnGuardarLineaClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnBorrarLineaClick(Sender: TObject); procedure BtnGuardarEmpClick(Sender: TObject); procedure BtnGuardarTrabajoClick(Sender: TObject); procedure BtnBorrarTrabajoClick(Sender: TObject); procedure BtnBorrarEmpClick(Sender: TObject); procedure ComboLineaChange(Sender: TObject); procedure ComboTrabajoChange(Sender: TObject); procedure ComboEmpleadoChange(Sender: TObject); private { Private declarations } Empleado,Trabajo,Linea:Boolean; public { Public declarations } end; var Lineas: TLineas; implementation {$R *.fmx} uses Main, Androidapi.JNI.Toasts, FGX.Toasts, FGX.Toasts.Android, Funciones_Android; { TLineas } procedure TLineas.BorrarEmpleado; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('Delete from Empleado where Nombre='+''''+ComboEmpleado.Selected.Text+''''); MainForm.FDQueryInsertar.ExecSQL; BuscarEmp; ToastImagen('Empleado eliminado',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); end; except on E:exception do ShowMessage('No se pudo borrar el empleado '+e.Message); end; end; procedure TLineas.BorrarLinea; var Toast: TfgToast; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('Delete from Linea where Nombre='+''''+ComboLinea.Selected.Text+''''); MainForm.FDQueryInsertar.ExecSQL; BuscarLinea; ToastImagen('Linea eliminada',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); end; except on E:exception do ShowMessage('No se pudo borrar la linea '+e.Message); end; end; procedure TLineas.BorrarTrabajo; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('Delete from Trabajo where Trabajo='+''''+ComboTrabajo.Selected.Text+''''); MainForm.FDQueryInsertar.ExecSQL; BuscarTrabajo; ToastImagen('Trabajo eliminado',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); end; except on E:exception do ShowMessage('No se pudo borrar la linea '+e.Message); end; end; // procedure TLineas.BtnBorrarEmpClick(Sender: TObject); begin if Empleado then begin MessageDlg('¿Desea eliminar el empleado? ', System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbOK,System.UITypes.TMsgDlgBtn.mbNo], 0, procedure(const AResult: System.UITypes.TModalResult) begin case AResult of mrOk: begin BorrarEmpleado; end; mrNo: end; end); end; end; procedure TLineas.BtnBorrarLineaClick(Sender: TObject); begin if Linea then begin MessageDlg('¿Desea eliminar la linea seleccionada? ', System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbOK,System.UITypes.TMsgDlgBtn.mbNo], 0, procedure(const AResult: System.UITypes.TModalResult) begin case AResult of mrOk: begin BorrarLinea; end; mrNo: end; end); end; end; procedure TLineas.BtnBorrarTrabajoClick(Sender: TObject); begin if Trabajo then begin MessageDlg('¿Desea eliminar el tipo de trabajo seleccionado? ', System.UITypes.TMsgDlgType.mtInformation, [System.UITypes.TMsgDlgBtn.mbOK,System.UITypes.TMsgDlgBtn.mbNo], 0, procedure(const AResult: System.UITypes.TModalResult) begin case AResult of mrOk: begin BorrarTrabajo; end; mrNo: end; end); end; end; procedure TLineas.BtnGuardarTrabajoClick(Sender: TObject); begin if EdtTrabajo.Text.Equals('') then ShowMessage('Inserte un tipo de trabajo') else begin InsertarTrabajo; end; end; procedure TLineas.BuscarEmp; begin try with MainForm.FDQueryBuscar,SQL do begin ComboEmpleado.Clear; Active := False; Clear; Add('Select Nombre From Empleado'); Close; Open; while not eof do begin try begin ComboEmpleado.Items.Add(Fields[0].AsString); Next; end; except on e: Exception do begin ShowMessage(e.Message); end; end; end; end; except on E:exception do showmessage(e.Message); end; end; procedure TLineas.BuscarLinea; begin try with MainForm.FDQueryBuscar,SQL do begin ComboLinea.Clear; Active := False; Clear; Add('Select Nombre From Linea'); Close; Open; while not eof do begin try begin ComboLinea.Items.Add(Fields[0].AsString); Next; end; except on e: Exception do begin ShowMessage(e.Message); end; end; end; end; except on E:exception do showmessage(e.Message); end; end; procedure TLineas.BuscarTrabajo; begin try with MainForm.FDQueryBuscar,SQL do begin ComboTrabajo.Clear; Active := False; Clear; Add('Select Trabajo From Trabajo'); Close; Open; while not eof do begin try begin ComboTrabajo.Items.Add(Fields[0].AsString); Next; end; except on e: Exception do begin ShowMessage(e.Message); end; end; end; end; except on E:exception do showmessage(e.Message); end; end; procedure TLineas.ComboEmpleadoChange(Sender: TObject); begin Empleado:=True; end; procedure TLineas.ComboLineaChange(Sender: TObject); begin Linea:=True; end; procedure TLineas.ComboTrabajoChange(Sender: TObject); begin Trabajo:=True; end; procedure TLineas.BtnGuardarEmpClick(Sender: TObject); begin if EditEmp.Text.Equals('') or EdtGanancia.Text.Equals('') then ShowMessage('Inserte nombre y ganancia del empleado') else begin InsertarEmpleado; end; MainForm.ObtenerEmpleadosLista; MainForm.ObtenerEmpleadosTrabajo; end; procedure TLineas.btnGuardarLineaClick(Sender: TObject); begin if EditLinea.Text.Equals('') then ShowMessage('Inserte una linea') else begin InsertarLinea; MainForm.ObtenerLineas; end; end; procedure TLineas.FormShow(Sender: TObject); begin BuscarLinea; BuscarEmp; BuscarTrabajo; end; procedure TLineas.InsertarEmpleado; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('insert into Empleado (Nombre,Ganancia) '); Add('values (:Nombre,:Ganancia)'); Params[0].AsString:=EditEmp.Text; Params[1].AsString:=EdtGanancia.Text; MainForm.FDQueryInsertar.ExecSQL; EditEmp.Text:=''; EdtGanancia.Text:=''; BuscarEmp; ToastImagen('Empleado insertado exitosamente',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); OcultarTeclado; end; except on E:exception do ShowMessage('No se pudo insertar el empleado '+e.Message); end; end; procedure TLineas.InsertarLinea; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('insert into linea (Nombre) values ('+''''+EditLinea.Text+''''+')'); MainForm.FDQueryInsertar.ExecSQL; BuscarLinea; EditLinea.Text:=''; OcultarTeclado; ToastImagen('Linea insertada exitosamente',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); OcultarTeclado; end; except on E:exception do ShowMessage('No se pudo insertar la linea '+e.Message); end; end; procedure TLineas.InsertarTrabajo; begin try with MainForm.FDQueryInsertar,SQL do begin Clear; Add('insert into Trabajo (Trabajo,Informacion)'); Add('values (:Trabajo,:Informacion)'); Params[0].AsString:=EdtTrabajo.Text; Params[1].AsString:=EdtInfo.Text; MainForm.FDQueryInsertar.ExecSQL; EdtTrabajo.Text:=''; EdtInfo.Text:=''; BuscarTrabajo; ToastImagen('Trabajo insertado exitosamente',false,MainForm.LogoVirma.Bitmap,$FFFFFF,$FF000000); OcultarTeclado; end; except on E:exception do ShowMessage('No se pudo insertar el trabajo '+e.Message); end; end; end.
unit CustomizeScreenControl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, LayoutManager, StdCtrls, ExtCtrls, ActnList, InfraGUIBuilderIntf, InfraGUIBuilder, Mask, GUIAnnotationIntf, GUIAnnotation; type TCustomizeScreenControl = class(TForm) pnlBottom: TPanel; btbtCancel: TButton; btbtOK: TButton; actlActions: TActionList; actnClose: TAction; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actnCloseExecute(Sender: TObject); procedure btbtCancelClick(Sender: TObject); procedure btbtOKClick(Sender: TObject); procedure FormShow(Sender: TObject); private // componentes de tela LayoutManager1: TLayoutManager; editName: TEdit; editCaption: TEdit; ckbxVisible: TCheckBox; ckbxCaptionVisible: TCheckBox; combCaptionPosition: TComboBox; editItemHeight: TMaskEdit; combItemHeightMeasureType: TComboBox; editItemWidth: TMaskEdit; combItemWidthMeasureType: TComboBox; editPutAfter: TEdit; editPutBefore: TEdit; // variaveis do form FExecute: Boolean; FGUIControl: IGUIControl; function GetGUIControl: IGUIControl; procedure SetGUIControl(const Value: IGUIControl); protected procedure InterfaceToObject; procedure ObjectToInterface; public function Execute: Boolean; property GUIControl: IGUIControl read GetGUIControl write SetGUIControl; end; implementation {$R *.dfm} procedure TCustomizeScreenControl.FormCreate(Sender: TObject); begin LayoutManager1 := TLayoutManager.Create(Self); with LayoutManager1 do begin Name := 'LayoutManager1'; Parent := Self; SetBounds(0, 0, 586, 246); AlignMode := alClient; editName := TEdit.Create(Self); with editName do begin Parent := Self; Color := clSilver; Font.Name := 'Tahoma'; Font.Style := [fsBold]; ReadOnly := True; end; with AddControl(editName) do begin Name := 'Name'; Caption := 'Name'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 100; end; editCaption := TEdit.Create(Self); with editCaption do begin Name := 'editCaption'; Parent := Self; end; with AddControl(editCaption) do begin Name := 'Caption'; Caption := 'Caption'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 100; end; ckbxVisible := TCheckBox.Create(Self); with ckbxVisible do begin Name := 'ckbxVisible'; Parent := Self; Caption := 'Visible'; end; with AddControl(ckbxVisible) do begin Name := 'Visible'; Caption := 'CheckBox1'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 25; end; ckbxCaptionVisible := TCheckBox.Create(Self); with ckbxCaptionVisible do begin Name := 'ckbxCaptionVisible'; Parent := Self; Caption := 'Caption Visible'; end; with AddControl(ckbxCaptionVisible) do begin Name := 'CaptionVisible'; Caption := 'CheckBox1'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 25; end; combCaptionPosition := TComboBox.Create(Self); with combCaptionPosition do begin Name := 'combCaptionPosition'; Parent := Self; Style := csDropDownList; ItemHeight := 13; Items.Clear; Items.Add('Above'); Items.Add('Below'); Items.Add('Left'); Items.Add('Right'); end; with AddControl(combCaptionPosition) do begin Name := 'CaptionPosition'; Caption := 'Caption Position'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 50; end; editItemHeight := TMaskEdit.Create(Self); with editItemHeight do begin Name := 'editItemHeight'; Parent := Self; EditMask := '999;1; '; MaxLength := 3; Text := ' '; end; with AddControl(editItemHeight) do begin Name := 'ItemHeight'; Caption := 'Item Height'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 49.84076433121019; end; combItemHeightMeasureType := TComboBox.Create(Self); with combItemHeightMeasureType do begin Name := 'combItemHeightMeasureType'; Parent := Self; Style := csDropDownList; ItemHeight := 13; Items.Clear; Items.Add('Fix'); Items.Add('Percent'); end; with AddControl(combItemHeightMeasureType) do begin Name := 'ItemHeightMeasureType'; Caption := 'Item Height Measure Type'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 50; end; editItemWidth := TMaskEdit.Create(Self); with editItemWidth do begin Name := 'editItemWidth'; Parent := Self; EditMask := '999;1; '; MaxLength := 3; Text := ' '; end; with AddControl(editItemWidth) do begin Name := 'ItemWidth'; Caption := 'Item Width'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 49.84076433121019; end; combItemWidthMeasureType := TComboBox.Create(Self); with combItemWidthMeasureType do begin Name := 'combItemWidthMeasureType'; Parent := Self; Style := csDropDownList; ItemHeight := 13; Items.Clear; Items.Add('Fix'); Items.Add('Percent'); end; with AddControl(combItemWidthMeasureType) do begin Name := 'ItemWidthMeasureType'; Caption := 'Item Width Measure Type'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 50; end; editPutAfter := TEdit.Create(Self); with editPutAfter do begin Name := 'editPutAfter'; Parent := Self; Text := ''; end; with AddControl(editPutAfter) do begin Name := 'PutAfter'; Caption := 'Put After'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 50; end; editPutBefore := TEdit.Create(Self); with editPutBefore do begin Name := 'editPutBefore'; Parent := Self; Text := ''; end; with AddControl(editPutBefore) do begin Name := 'PutBefore'; Caption := 'Put Before'; WidthOptions.MeasureType := mtPercent; WidthOptions.Size := 50; end; end; end; procedure TCustomizeScreenControl.FormDestroy(Sender: TObject); begin editName.Free; editCaption.Free; ckbxVisible.Free; ckbxCaptionVisible.Free; combCaptionPosition.Free; editItemHeight.Free; combItemHeightMeasureType.Free; editItemWidth.Free; combItemWidthMeasureType.Free; editPutAfter.Free; editPutBefore.Free; LayoutManager1.Free; end; procedure TCustomizeScreenControl.actnCloseExecute(Sender: TObject); begin Close; end; procedure TCustomizeScreenControl.btbtCancelClick(Sender: TObject); begin Close; end; procedure TCustomizeScreenControl.btbtOKClick(Sender: TObject); begin InterfaceToObject; FExecute := True; Close; end; function TCustomizeScreenControl.Execute: Boolean; begin ShowModal; Result := FExecute; end; procedure TCustomizeScreenControl.FormShow(Sender: TObject); begin //Height.Enabled := Supports(GUIControl.ScreenItem, IScreenControl) or // (not Assigned(GUIControl.ScreenItem)); //Width.Enabled := Supports(GUIControl.ScreenItem, IScreenControl) or // (not Assigned(GUIControl.ScreenItem)); ObjectToInterface; end; function TCustomizeScreenControl.GetGUIControl: IGUIControl; begin Result := FGUIControl; end; procedure TCustomizeScreenControl.InterfaceToObject; var //bAssign: Boolean; vValue: Variant; lpValue: TLabelPosition; mtValue: TMeasureType; procedure VerityScreenControlInstance; begin if not Assigned(GUIControl.ScreenItem) then GUIControl.ScreenItem := TScreenControl.Create; end; begin //Visible vValue := ckbxVisible.Checked; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.Visible.IsNull) and (GUIControl.ScreenItem.Visible.AsBoolean <> vValue) or (GUIControl.Item.Visible <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.Visible.AsBoolean := vValue; end; //Caption vValue := Trim(editCaption.Text); if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.Caption.IsNull) and (GUIControl.ScreenItem.Caption.AsString <> vValue) or (GUIControl.Item.Caption <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.Caption.AsString := vValue; end; //CaptionVisible vValue := ckbxCaptionVisible.Checked; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.CaptionVisible.IsNull) and (GUIControl.ScreenItem.CaptionVisible.AsBoolean <> vValue) or (GUIControl.Item.CaptionVisible <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.CaptionVisible.AsBoolean := vValue; end; //CaptionPosition lpValue := TLabelPosition(combCaptionPosition.ItemIndex); if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.CaptionPosition <> lpValue) or (GUIControl.Item.CaptionOptions.Position <> lpValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.CaptionPosition := lpValue; end; //ItemHeight vValue := StrToIntDef(Trim(editItemHeight.Text), 0); if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.ItemHeight.IsNull) and (GUIControl.ScreenItem.ItemHeight.AsInteger <> vValue) or (GUIControl.Item.HeightOptions.Size <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.ItemHeight.AsInteger := vValue; end; //ItemHeightMeasureType mtValue := TMeasureType(combItemHeightMeasureType.ItemIndex); if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemHeightMeasureType <> mtValue) or (GUIControl.Item.HeightOptions.MeasureType <> mtValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.ItemHeightMeasureType := mtValue; end; //ItemWidth vValue := StrToIntDef(Trim(editItemWidth.Text), 0); if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.ItemWidth.IsNull) and (GUIControl.ScreenItem.ItemWidth.AsInteger <> vValue) or (GUIControl.Item.WidthOptions.Size <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.ItemWidth.AsInteger := vValue; end; //ItemWidthMeasureType mtValue := TMeasureType(combItemWidthMeasureType.ItemIndex); if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemWidthMeasureType <> mtValue) or (GUIControl.Item.WidthOptions.MeasureType <> mtValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.ItemWidthMeasureType := mtValue; end; //Height {bAssign := False; vValue := StrToIntDef(Trim(editHeight.Text), 0); if (Assigned(GUIControl.ScreenItem)) and (Supports(GUIControl.ScreenItem, IScreenControl) and (not (GUIControl.ScreenItem as IScreenControl).Height.IsNull) and ((GUIControl.ScreenItem as IScreenControl).Height.AsInteger <> vValue)) then bAssign := True else if (not (Assigned(GUIControl.ScreenItem))) or ((Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemHeightMeasureType <> mtPercent)) and (GUIControl.Control.Height <> vValue) then bAssign := True; if bAssign then begin VerityScreenControlInstance; (GUIControl.ScreenItem as IScreenControl).Height.AsInteger := vValue; end; } //Width {bAssign := False; vValue := StrToIntDef(Trim(editWidth.Text), 0); if (Assigned(GUIControl.ScreenItem)) and (Supports(GUIControl.ScreenItem, IScreenControl) and (not (GUIControl.ScreenItem as IScreenControl).Width.IsNull) and ((GUIControl.ScreenItem as IScreenControl).Width.AsInteger <> vValue)) then bAssign := True else if (not (Assigned(GUIControl.ScreenItem))) or ((Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemWidthMeasureType <> mtPercent)) and (GUIControl.Control.Width <> vValue) then bAssign := True; if bAssign then begin VerityScreenControlInstance; (GUIControl.ScreenItem as IScreenControl).Width.AsInteger := vValue; end;} //PutAfter vValue := Trim(editPutAfter.Text); if Assigned(GUIControl.ScreenItem) and (GUIControl.ScreenItem.PutAfter <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.PutBefore := ''; GUIControl.ScreenItem.PutAfter := vValue; end; //PutBefore vValue := Trim(editPutBefore.Text); if Assigned(GUIControl.ScreenItem) and (GUIControl.ScreenItem.PutBefore <> vValue) then begin VerityScreenControlInstance; GUIControl.ScreenItem.PutAfter := ''; GUIControl.ScreenItem.PutBefore := vValue; end; end; procedure TCustomizeScreenControl.ObjectToInterface; begin editName.Text := GUIControl.PropertyName; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.Visible.IsNull) then ckbxVisible.Checked := GUIControl.ScreenItem.Visible.AsBoolean else ckbxVisible.Checked := True; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.Caption.IsNull) then editCaption.Text := GUIControl.ScreenItem.Caption.AsString else editCaption.Text := GUIControl.PropertyName; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.CaptionVisible.IsNull) then ckbxCaptionVisible.Checked := GUIControl.ScreenItem.CaptionVisible.AsBoolean else ckbxCaptionVisible.Checked := GUIControl.Item.CaptionVisible; if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.CaptionPosition <> lpLeft) then begin case GUIControl.ScreenItem.CaptionPosition of lpAbove: combCaptionPosition.ItemIndex := 0; lpBelow: combCaptionPosition.ItemIndex := 1; lpRight: combCaptionPosition.ItemIndex := 3; end; end else combCaptionPosition.ItemIndex := 2; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.ItemHeight.IsNull) then editItemHeight.Text := IntToStr(GUIControl.ScreenItem.ItemHeight.AsInteger) else editItemHeight.Text := FloatToStr(GUIControl.Item.HeightOptions.Size); if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemHeightMeasureType <> mtFix) then combItemHeightMeasureType.ItemIndex := 1 else combItemHeightMeasureType.ItemIndex := 0; if (Assigned(GUIControl.ScreenItem)) and (not GUIControl.ScreenItem.ItemWidth.IsNull) then editItemWidth.Text := IntToStr(GUIControl.ScreenItem.ItemWidth.AsInteger) else editItemWidth.Text := FloatToStr(GUIControl.Item.WidthOptions.Size); if (Assigned(GUIControl.ScreenItem)) and (GUIControl.ScreenItem.ItemWidthMeasureType <> mtFix) then combItemWidthMeasureType.ItemIndex := 1 else combItemWidthMeasureType.ItemIndex := 0; {if (Assigned(GUIControl.ScreenItem)) and (Supports(GUIControl.ScreenItem, IScreenControl)) and (not (GUIControl.ScreenItem as IScreenControl).Height.IsNull) then editHeight.Text := IntToStr((GUIControl.ScreenItem as IScreenControl).Height.AsInteger) else editHeight.Text := IntToStr(GUIControl.Control.Height); if (Assigned(GUIControl.ScreenItem)) and (Supports(GUIControl.ScreenItem, IScreenControl)) and (not (GUIControl.ScreenItem as IScreenControl).Width.IsNull) then editWidth.Text := IntToStr((GUIControl.ScreenItem as IScreenControl).Width.AsInteger) else editWidth.Text := IntToStr(GUIControl.Control.Width);} if Assigned(GUIControl.ScreenItem) then editPutAfter.Text := GUIControl.ScreenItem.PutAfter; if Assigned(GUIControl.ScreenItem) then editPutBefore.Text := GUIControl.ScreenItem.PutBefore; end; procedure TCustomizeScreenControl.SetGUIControl(const Value: IGUIControl); begin FGUIControl := Value; end; end.
// unit DNK_RoundSlider // // round slider with 3d and flat appearace // it is almost fully customizable, except you can't specify background bitmap. // // !WARNING! the control is subclassed from Timage, because drawing on Timage's canvas // is 'FLICKER FREE', because of that there are 2 problems and 2 advantages: // - the control won't repaint if resized at design or runtime excpt if you manualy call paint procedure // - the control has additional peoperties and events // from Timage (like center and stretch) please LEAVE those peoperties set to default // it will cause strange behaviour... // - the transparent property can be used as with normal Timage component // - the control is flicker free unit DNK_RoundSlider; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, math, extctrls; type TDNK_Roundslider = class(Timage) private { Private declarations } fcolor : TColor; fcolor_light : TColor; fcolor_shadow : TColor; fbordercolor : TColor; MDown: TMouseEvent; MUp: TMouseEvent; Enab: Boolean; fflat:boolean; Fspacer: integer; Flinesize: integer; Fbordersize: integer; fposition: integer; fmax: integer; fmin: integer; fbarcolor: tcolor; fonchange : TNotifyEvent; procedure Setposition(Value: integer); procedure Setmax(Value: integer); procedure Setmin(Value: integer); procedure Setbarcolor(Value: tcolor); procedure setspacer(Value: integer); procedure setbordersize(Value: integer); procedure setlinesize(Value: integer); procedure SetCol(Value: TColor); procedure set_color_light(Value: TColor); procedure set_color_shadow(Value: TColor); procedure set_bordercolor(Value: TColor); procedure setflat(Value: boolean); procedure setEnab(value:boolean); protected { Protected declarations } updating: boolean; procedure translatecoordinates(x, y: integer); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint;// override; procedure Resize;// override; published { Published declarations } property OnChange : TNotifyEvent index 0 read fonchange write fonchange; property Spacer : integer read Fspacer write setspacer; property BorderSize : integer read Fbordersize write setbordersize; //[ doesn't work yet! ] property LineSize : integer read flinesize write setlinesize; property Color : TColor read fColor write SetCol; property Color_light : TColor read fcolor_light write set_color_light default clwhite ; property Color_shadow : TColor read fcolor_shadow write set_color_shadow default clgray ; property Bordercolor : TColor read fbordercolor write set_bordercolor default clgray ; property Enabled : Boolean read Enab write setEnab; property Flat : Boolean read fflat write setflat; property OnMouseDown: TMouseEvent read MDown write MDown; property OnMouseUp: TMouseEvent read MUp write MUp; property barcolor: tcolor read fbarcolor write Setbarcolor; property position: integer read fposition write Setposition; property max: integer read fmax write Setmax; property min: integer read fmin write Setmin; property ShowHint; property OnMouseMove; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property Visible; property Popupmenu; property Cursor; property Dragkind; property Dragmode; property Dragcursor; { property Autosize index -1; property Center index -1; property Incrementaldisplay index -1; property Stretch index -1;} end; procedure Register; implementation procedure TDNK_Roundslider.Resize; begin paint; end; procedure TDNK_Roundslider.translatecoordinates(x, y: integer); var angle: integer; xcoord: integer; ycoord: integer; radius: integer; begin radius:= height div 2; xcoord:= x- radius; ycoord:= y- radius; angle:= round(max + (max div 2)* arctan2(- ycoord, xcoord)/ pi); if angle < min then angle:= angle+ max else if angle > max then angle:= angle- max; position:= angle; if Assigned (fonchange) then Onchange (self); paint; end; procedure TDNK_Roundslider.setspacer(Value: integer); begin Fspacer:= value; Paint; end; procedure TDNK_Roundslider.setlinesize(Value: integer); begin Flinesize:= value; Paint; end; procedure TDNK_Roundslider.setbordersize(Value: integer); begin //showmessage(inttostr(value mod 2)); Fbordersize:= value; Paint; end; constructor TDNK_Roundslider.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 100; Height := 100; fposition:= 0; fmax:= 100; fmin:= 0; fColor := clbtnface; fcolor_light := $00E8E8E8; fcolor_shadow := $008C8C8C; fbordercolor:=clblack; fbarcolor:= clblue; fspacer:= 3; fbordersize:= 2; Enab := true; paint; end; destructor TDNK_Roundslider.Destroy; begin inherited Destroy; end; procedure TDNK_Roundslider.Paint; var b: Tbitmap; angle: real; radius: integer; procedure paintbmptransparent(from: Tbitmap; drawonthis: Tcanvas; transpcolor: Tcolor); begin drawonthis.brush.Style:= bsclear; drawonthis.BrushCopy(rect(0,0, from.width, from.height), from, rect(0,0, from.width, from.height), transpcolor); end; begin try picture.bitmap.Width:= width; picture.bitmap.height:= height; with canvas do begin pen.color:= color_light; brush.color:= color_light; Canvas.Polygon([ Point(width, 0), Point(0,0), Point(0, height) ]); pen.color:= color_shadow; brush.color:= color_shadow; Canvas.Polygon([ Point(width, 0), Point(width, height), Point(0, height) ]); b:= Tbitmap.create; b.width:= width; b.height:= height; b.canvas.Pen.Color:= color; b.canvas.Brush.Color:= color; b.canvas.FillRect(b.Canvas.ClipRect); b.canvas.Pen.Color:= clFuchsia; b.canvas.Brush.Color:= color; b.canvas.pen.Width:= BorderSize; b.canvas.Ellipse(1+ BorderSize div 2, 1+ BorderSize div 2, width-BorderSize div 2, height-BorderSize div 2); paintbmptransparent(b, canvas, clfuchsia); b.canvas.copyrect(rect(0,0, width, height), canvas, rect(0,0, width, height)); b.canvas.Pen.Color:= clFuchsia; b.canvas.Brush.Color:= clFuchsia; b.canvas.Ellipse(spacer+1, spacer+1, width-spacer-1, height-spacer-1); radius:= width div 2; angle:= -position * pi / (max div 2); Canvas.Pen.Width:= linesize; canvas.pen.color:= barcolor; canvas.moveto(radius, radius); canvas.lineto(radius + round(radius *sin(angle)), radius + round(radius *cos(angle))); paintbmptransparent(b, canvas, clfuchsia); b.free; if flat= false then begin Pen.Color:= bordercolor; pen.Width:= 1; Brush.style:= bsclear; Ellipse(0, 0, width, height); end; end; except end; end; // paint procedure TDNK_Roundslider.SetCol(Value: TColor); begin fColor := Value; Paint; end; procedure TDNK_Roundslider.set_color_light(Value: TColor); begin fcolor_light := Value; Paint; end; procedure TDNK_Roundslider.set_color_shadow(Value: TColor); begin fcolor_shadow := Value; Paint; end; procedure TDNK_Roundslider.set_bordercolor(Value: TColor); begin fbordercolor := Value; Paint; end; procedure TDNK_Roundslider.Setflat(Value: boolean); begin fflat := value; Paint; end; procedure TDNK_Roundslider.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; updating:= true; translatecoordinates(y, x); end; procedure TDNK_Roundslider.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; updating:= false end; procedure TDNK_Roundslider.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if enabled then if updating then translatecoordinates(y, x) end; procedure TDNK_Roundslider.Setposition(Value: integer); begin if value < min then value:=min; if value > max then value:=max; if value <> fposition then begin fposition:=value; if Assigned (fonchange) then Onchange (self); paint; end; end; procedure TDNK_Roundslider.Setbarcolor(value : tcolor); begin fbarcolor:=value; Paint; end; procedure TDNK_Roundslider.Setmax(Value: integer); begin fmax:=value; paint; end; procedure TDNK_Roundslider.Setmin(Value: integer); begin fmin:=value; paint; end; procedure TDNK_Roundslider.setEnab(value:boolean); begin Enab:=value; Paint; end; procedure Register; begin RegisterComponents('DNK Components', [TDNK_Roundslider]); end; end.
unit uObserverPatternInterfaces; interface uses uGameInfo ; type IObserver = interface ['{69B40B25-B2C8-4F11-B442-39B7DC26FE80}'] procedure Update(aGameInfo: TGameInfo); end; IDisplay = interface ['{1517E56B-DDB3-4E04-AF1A-C70CF16293B2}'] procedure Display; end; ISubject = interface ['{A9240295-B0C2-441D-BD43-932AF735832A}'] procedure RegisterObserver(aObserver: IObserver); procedure RemoveObserver(aObserver: IObserver); procedure NotifyObservers; end; implementation end.
unit SettingsDialog; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyrigh, FMX.Layouts, FMX.ListBoxt notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.EditBox, FMX.SpinBox, FMX.Edit, FMX.StdCtrls, FMX.TabControl, FMX.Controls.Presentation, IniFiles, System.Rtti, FMX.Grid.Style, FMX.Grid, FMX.ScrollBox, FMX.Layouts, FMX.ListBox, ToolkitSettings, EditRegisteredServerDialogFMX, SmartOnFhirUtilities; type TSettingsForm = class(TForm) Panel1: TPanel; Button1: TButton; Button2: TButton; TabControl1: TTabControl; TabItem1: TTabItem; Label1: TLabel; Label2: TLabel; edtProxy: TEdit; edtTimeout: TSpinBox; Label3: TLabel; Label4: TLabel; TabItem2: TTabItem; btnAdd: TButton; btnUp: TButton; btnDown: TButton; btnDelete: TButton; lbServers: TListBox; btnEdit: TButton; TabItem3: TTabItem; cbCheckUpgrades: TCheckBox; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; edtUsername: TEdit; edtPassword: TEdit; procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnUpClick(Sender: TObject); procedure btnDownClick(Sender: TObject); procedure lbServersClick(Sender: TObject); procedure btnEditClick(Sender: TObject); private FSettings : TFHIRToolkitSettings; procedure SetSettings(const Value: TFHIRToolkitSettings); public Destructor Destroy; override; Property Settings : TFHIRToolkitSettings read FSettings write SetSettings; end; var SettingsForm: TSettingsForm; implementation {$R *.fmx} procedure TSettingsForm.btnAddClick(Sender: TObject); var form : TEditRegisteredServerForm; begin form := TEditRegisteredServerForm.create(self); try form.Server := TRegisteredFHIRServer.Create; if form.ShowModal = mrOk then begin FSettings.registerServer('Terminology', form.Server); FSettings.ListServers('Terminology', lbServers.Items); lbServersClick(nil); end; finally form.Free; end; end; procedure TSettingsForm.btnDeleteClick(Sender: TObject); var i : integer; begin i := lbServers.ItemIndex; FSettings.DeleteServer('Terminology', lbServers.ItemIndex); lbServers.items.Delete(i); if i = lbServers.items.Count then dec(i); lbServers.ItemIndex := i; lbServersClick(nil); end; procedure TSettingsForm.btnDownClick(Sender: TObject); var i : integer; begin i := lbServers.ItemIndex; FSettings.moveServer('Terminology', i, 2); FSettings.ListServers('Terminology', lbServers.Items); lbServers.ItemIndex := i+1; lbServersClick(nil); end; procedure TSettingsForm.btnEditClick(Sender: TObject); var i : integer; form : TEditRegisteredServerForm; begin form := TEditRegisteredServerForm.create(self); try form.Server := FSettings.serverInfo('Terminology', lbServers.ItemIndex); if form.ShowModal = mrOk then begin FSettings.updateServerInfo('Terminology', lbServers.ItemIndex, form.Server); FSettings.ListServers('Terminology', lbServers.Items); lbServersClick(nil); end; finally form.Free; end; end; procedure TSettingsForm.btnUpClick(Sender: TObject); var i : integer; begin i := lbServers.ItemIndex; FSettings.moveServer('Terminology', i, -1); FSettings.ListServers('Terminology', lbServers.Items); lbServers.ItemIndex := i-1; lbServersClick(nil); end; destructor TSettingsForm.Destroy; begin FSettings.Free; inherited; end; procedure TSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); var s : String; begin if ModalResult = mrOk then begin FSettings.Proxy := edtProxy.Text; FSettings.timeout := trunc(edtTimeout.Value); FSettings.CheckForUpgradesOnStart := cbCheckUpgrades.IsChecked; FSettings.RegistryUsername := edtUsername.Text; FSettings.RegistryPassword := edtPassword.Text; end; end; procedure TSettingsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := true; end; procedure TSettingsForm.FormShow(Sender: TObject); begin TabControl1.ActiveTab := TabItem1; edtProxy.Text := FSettings.Proxy; edtTimeout.Value := FSettings.timeout; cbCheckUpgrades.IsChecked := FSettings.CheckForUpgradesOnStart; FSettings.ListServers('Terminology', lbServers.Items); lbServers.ItemIndex := 0; lbServersClick(nil); edtUsername.Text := FSettings.RegistryUsername; edtPassword.Text := FSettings.RegistryPassword; end; procedure TSettingsForm.lbServersClick(Sender: TObject); begin btnEdit.Enabled := lbServers.ItemIndex >= 0; btnAdd.enabled := true; btnDown.enabled := (lbServers.ItemIndex > -1) and (lbServers.ItemIndex < FSettings.ServerCount('Terminology') - 1); btnUp.enabled := lbServers.ItemIndex > 0; btnDelete.enabled := (lbServers.ItemIndex >= 0) and (FSettings.ServerCount('Terminology') > 1); end; procedure TSettingsForm.SetSettings(const Value: TFHIRToolkitSettings); begin FSettings.Free; FSettings := Value; end; end.
namespace Sugar.Test; interface uses Sugar, Sugar.TestFramework; type EncodingTest = public class (Testcase) private method ByteArrayEquals(Expected: array of Byte; Actual: array of Byte); method CharArrayEquals(Expected: array of Char; Actual: array of Char); public method GetBytes; method GetBytes2; method GetChars; method GetString; method GetEncoding; end; implementation method EncodingTest.ByteArrayEquals(Expected: array of Byte; Actual: array of Byte); begin Assert.CheckInt(Expected.Length, Actual.Length); for i: Integer := 0 to Expected.Length - 1 do Assert.CheckInt(Expected[i], Actual[i]); end; method EncodingTest.CharArrayEquals(Expected: array of Char; Actual: array of Char); begin Assert.CheckInt(Expected.Length, Actual.Length); for i: Integer := 0 to Expected.Length - 1 do Assert.CheckBool(true, Expected[i] = Actual[i], String.Format("Invalid chars. Expected [{0}] but was [{1}]", Expected[i], Actual[i])); end; method EncodingTest.GetBytes; begin ByteArrayEquals([72, 101, 108, 108, 111, 194, 169], Encoding.UTF8.GetBytes("Hello©")); ByteArrayEquals([72, 0, 101, 0, 108, 0, 108, 0, 111, 0], Encoding.UTF16LE.GetBytes("Hello")); ByteArrayEquals([0, 72, 0, 101, 0, 108, 0, 108, 0, 111], Encoding.UTF16BE.GetBytes("Hello")); ByteArrayEquals([72, 101, 108, 108, 111, 63], Encoding.ASCII.GetBytes("Hello©")); // © - is outside of ASCII should be replaced by ? ByteArrayEquals([63, 230], Encoding.GetEncoding("Windows-1251").GetBytes("æж")); var Value: String := nil; Assert.IsException(->Encoding.UTF8.GetBytes(Value)); end; method EncodingTest.GetBytes2; begin ByteArrayEquals([72, 101, 108, 108, 111, 194, 169], Encoding.UTF8.GetBytes(['H', 'e', 'l', 'l', 'o', '©'])); ByteArrayEquals([72, 0, 101, 0, 108, 0, 108, 0, 111, 0], Encoding.UTF16LE.GetBytes(['H', 'e', 'l', 'l', 'o'])); ByteArrayEquals([0, 72, 0, 101, 0, 108, 0, 108, 0, 111], Encoding.UTF16BE.GetBytes(['H', 'e', 'l', 'l', 'o'])); ByteArrayEquals([72, 101, 108, 108, 111, 63], Encoding.ASCII.GetBytes(['H', 'e', 'l', 'l', 'o', '©'])); ByteArrayEquals([63, 230], Encoding.GetEncoding("Windows-1251").GetBytes(['æ', 'ж'])); ByteArrayEquals([108, 108, 111], Encoding.UTF8.GetBytes(['H', 'e', 'l', 'l', 'o', '©'], 2, 3)); Assert.IsException(->Encoding.UTF8.GetBytes(['a', 'b'], 5, 1)); Assert.IsException(->Encoding.UTF8.GetBytes(['a', 'b'], 1, 5)); Assert.IsException(->Encoding.UTF8.GetBytes(['a', 'b'], -1, 1)); Assert.IsException(->Encoding.UTF8.GetBytes(['a', 'b'], 1, -1)); var Value: array of Char := nil; Assert.IsException(->Encoding.UTF8.GetBytes(Value, 1, 1)); Assert.IsException(->Encoding.UTF8.GetBytes(Value)); end; method EncodingTest.GetChars; begin CharArrayEquals(['H', 'e', 'l', 'l', 'o', '©'], Encoding.UTF8.GetChars([72, 101, 108, 108, 111, 194, 169])); CharArrayEquals(['H', 'e', 'l', 'l', 'o'], Encoding.UTF16LE.GetChars([72, 0, 101, 0, 108, 0, 108, 0, 111, 0])); CharArrayEquals(['H', 'e', 'l', 'l', 'o'], Encoding.UTF16BE.GetChars([0, 72, 0, 101, 0, 108, 0, 108, 0, 111])); CharArrayEquals(['H', 'e', 'l', 'l', 'o', '?'], Encoding.ASCII.GetChars([72, 101, 108, 108, 111, 214])); CharArrayEquals(['ж'], Encoding.GetEncoding("Windows-1251").GetChars([230])); CharArrayEquals(['l', 'l', 'o'], Encoding.UTF8.GetChars([72, 101, 108, 108, 111, 194, 169], 2, 3)); var Value: array of Byte := nil; Assert.IsException(->Encoding.ASCII.GetChars(Value)); Assert.IsException(->Encoding.ASCII.GetChars(Value, 5, 1)); Assert.IsException(->Encoding.ASCII.GetChars([1, 2], 5, 1)); Assert.IsException(->Encoding.ASCII.GetChars([1, 2], 1, 5)); Assert.IsException(->Encoding.ASCII.GetChars([1, 2], -1, 1)); Assert.IsException(->Encoding.ASCII.GetChars([1, 2], 1, -1)); end; method EncodingTest.GetString; begin Assert.CheckString("Hello©", Encoding.UTF8.GetString([72, 101, 108, 108, 111, 194, 169])); Assert.CheckString("Hello", Encoding.UTF16LE.GetString([72, 0, 101, 0, 108, 0, 108, 0, 111, 0])); Assert.CheckString("Hello", Encoding.UTF16BE.GetString([0, 72, 0, 101, 0, 108, 0, 108, 0, 111])); Assert.CheckString("Hello?", Encoding.ASCII.GetString([72, 101, 108, 108, 111, 214])); //214 - is outside of ASCII range Assert.CheckString("Ёж", Encoding.GetEncoding("Windows-1251").GetString([168, 230])); Assert.CheckString("llo", Encoding.UTF8.GetString([72, 101, 108, 108, 111, 194, 169], 2, 3)); Assert.CheckString("", Encoding.UTF8.GetString([])); var Value: array of Byte := nil; Assert.IsException(->Encoding.UTF8.GetString(Value)); Assert.IsException(->Encoding.UTF8.GetString(Value, 1, 1)); Assert.IsException(->Encoding.UTF8.GetString([1, 2], 5, 1)); Assert.IsException(->Encoding.UTF8.GetString([1, 2], 1, 5)); Assert.IsException(->Encoding.UTF8.GetString([1, 2], -1, 1)); Assert.IsException(->Encoding.UTF8.GetString([1, 2], 1, -1)); end; method EncodingTest.GetEncoding; begin Assert.IsNotNull(Encoding.ASCII); Assert.IsNotNull(Encoding.UTF8); Assert.IsNotNull(Encoding.UTF16LE); Assert.IsNotNull(Encoding.UTF16BE); Assert.IsNotNull(Encoding.GetEncoding("Windows-1251")); Assert.IsException(->Encoding.GetEncoding(nil)); Assert.IsException(->Encoding.GetEncoding("")); Assert.IsException(->Encoding.GetEncoding("Something completely different")); end; end.
unit uStrListParser; { Catarinka Lua Library - String List Parser Object Copyright (c) 2013-2014 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface uses Classes, SysUtils, Lua, LuaObject, CatStringLoop; type { TCatarinkaStrListParser } TCatarinkaStrListParser = class(TLuaObject) private public obj: TStringLoop; constructor Create(LuaState: PLua_State; AParent: TLuaObject = nil); overload; override; function GetPropValue(propName: String): Variant; override; function SetPropValue(propName: String; const AValue: Variant) : Boolean; override; destructor Destroy; override; end; procedure RegisterCatarinkaStrListParser(L: PLua_State); implementation uses pLua; function method_parsing(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); lua_pushboolean(L, ht.obj.found); result := 1; end; function method_clear(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.clear; result := 1; end; function method_stop(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.stop; result := 1; end; function method_reset(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.reset; result := 1; end; function method_delete(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.delete; result := 1; end; function method_add(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.List.add(lua_tostring(L, 2)); result := 1; end; function method_loadfromstr(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.loadfromstring(lua_tostring(L, 2)); result := 1; end; function method_loadfromfile(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.loadfromfile(lua_tostring(L, 2)); result := 1; end; function method_savetofile(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); ht.obj.List.savetofile(lua_tostring(L, 2)); result := 1; end; function method_getvalue(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); lua_pushstring(L, ht.obj.getvalue(lua_tostring(L, 2))); result := 1; end; function method_indexof(L: PLua_State): Integer; cdecl; var ht: TCatarinkaStrListParser; begin ht := TCatarinkaStrListParser(LuaToTLuaObject(L, 1)); lua_pushinteger(L, ht.obj.indexof(lua_tostring(L, 2))); result := 1; end; procedure register_methods(L: PLua_State; classTable: Integer); begin RegisterMethod(L, 'indexof', @method_indexof, classTable); RegisterMethod(L, 'load', @method_loadfromstr, classTable); RegisterMethod(L, 'loadfromfile', @method_loadfromfile, classTable); RegisterMethod(L, 'parsing', @method_parsing, classTable); RegisterMethod(L, 'savetofile', @method_savetofile, classTable); RegisterMethod(L, 'stop', @method_stop, classTable); RegisterMethod(L, 'reset', @method_reset, classTable); RegisterMethod(L, 'clear', @method_clear, classTable); RegisterMethod(L, 'curgetvalue', @method_getvalue, classTable); RegisterMethod(L, 'curdelete', @method_delete, classTable); RegisterMethod(L, 'add', @method_add, classTable); end; const objname = 'ctk_listparser'; function new_callback(L: PLua_State; AParent: TLuaObject = nil): TLuaObject; begin result := TCatarinkaStrListParser.Create(L, AParent); end; function Create(L: PLua_State): Integer; cdecl; var p: TLuaObjectNewCallback; begin p := @new_callback; result := new_LuaObject(L, objname, p); end; procedure RegisterCatarinkaStrListParser(L: PLua_State); begin RegisterTLuaObject(L, objname, @Create, @register_methods); end; constructor TCatarinkaStrListParser.Create(LuaState: PLua_State; AParent: TLuaObject); begin inherited Create(LuaState, AParent); obj := TStringLoop.Create; end; function TCatarinkaStrListParser.GetPropValue(propName: String): Variant; begin if CompareText(propName, 'commatext') = 0 then result := obj.List.CommaText else if CompareText(propName, 'count') = 0 then result := obj.Count else if CompareText(propName, 'current') = 0 then result := obj.Current else if CompareText(propName, 'curindex') = 0 then result := obj.Index(false) else if CompareText(propName, 'text') = 0 then result := obj.List.Text else result := inherited GetPropValue(propName); end; function TCatarinkaStrListParser.SetPropValue(propName: String; const AValue: Variant): Boolean; begin result := true; if CompareText(propName, 'commatext') = 0 then begin obj.List.CommaText := AValue; obj.reset; end else if CompareText(propName, 'current') = 0 then obj.Current := AValue else if CompareText(propName, 'iscsv') = 0 then obj.iscsv := AValue else if CompareText(propName, 'text') = 0 then obj.loadfromstring(AValue) else result := inherited SetPropValue(propName, AValue); end; destructor TCatarinkaStrListParser.Destroy; begin obj.free; inherited Destroy; end; end.
program ejercicio14partica2parte2; const precio=320; type localidad=string [30]; procedure leer (var loc:localidad;var ha:integer; var zona:integer); begin writeln ('ingrese localidad'); readln (loc); writeln ('Ingrese hectareas'); readln (ha); writeln ('ingrese tipo de zona de siembra 1:muy fertil, 2:zona estandar, 3:zona arida'); readln (zona); end; function rendimiento (ha,zona:integer):real; var rend:real; begin if (zona = 1) then begin rend:=6*ha; rendimiento:=rend*precio; end else if (zona = 2) then begin rend:=2.6*ha; rendimiento:=rend*precio; end else begin rend:=1.4*ha; rendimiento:=rend*precio; end; end; procedure maxrendidor (Re:real;loc:localidad;VAR max:real;VAR maxloc:localidad); begin if (re > max) then begin maxloc:=loc; max:=re; end; end; procedure minrendidor (Re:real;loc:localidad;VAR min:real;VAR minloc:localidad); begin if (re < min) then begin minloc:=loc; min:=re; end; end; function promedio (total:real;cant:integer):real; begin promedio:=total/cant; end; var mas10mil,ha,zona,cant:integer; re,max,min,total:real; minloc,maxloc,loc:localidad; begin { programa principal } mas10mil:=0;cant:=0;total:=0; min:=99999999999999; max:=-1; repeat leer (loc,ha,zona); cant :=cant+1; Re:=rendimiento (ha,zona); total:=total + Re; if (loc = 'tres de febrero') and (Re > 10000)then mas10mil:=mas10mil + 1; maxrendidor (re,loc,max,maxloc); minrendidor (re,loc,min,minloc); until (ha = 900) and (loc = 'saladillo'); writeln ('la cantidad de campos en Tres de Febrero con rendiemineto mayor a u$s 10000 son ', mas10mil); writeln (maxloc,' es la localidad con mayor rendimiento'); writeln (minloc,' es la localidad con menor rendimiento'); writeln (promedio (total,cant):2:2,' es el rendimiento economico promedio'); end. program ej1; function suma (numA,numB:integer):integer; begin suma:= numA+numB; end; function multi (numA,numB:integer):integer; begin multi:= numA*numB; end; var i,numA,numB,totalS,totalM:integer; begin totalS:=0; totalM:=1; For i:=1 to 10 do begin writeln('ingrese el primer numero'); readln(NumA); writeln('ingrese el segundo numero'); readln(numB); totalM:=totalM*multi(numA,NumB); totalS:=totalS+suma(numA,NumB); end; writeln('total de pares sumados: ',totalS); writeln('total de pares multiplicados: ',totalM); end. procedure sumaYproducto(n1,n2:integer;var suma,prod:integer); var j:integer; begin suma:=0; prod:=1; for j:=n1 to n2 do begin suma:=suma+j; prod:=prod*j; end; end; Program actividad2; Procedure SUMA_PROD (numX,numY: integer; VAR suma, producto: integer); Var indice: integer; Begin suma:= 0; producto:= 1; If (numX > numY) then For indice:= numX downto numY do begin suma:= suma + indice; producto:= producto * indice; end ELSE If (numX < numY) then For indice:= numX to numY do begin suma:= suma + indice; producto:= producto * indice; end; end; VAR i,numX,numY,suma,producto: integer; Begin For i:= 1 to 10 do begin suma:=0; writeln('ingrese el primer numero: '); readln(numX); writeln('ingrese el segundo numero: '); readln(numY); SUMA_PROD(numX,numY,suma,producto); writeln('La suma es de: ',suma); writeln('El producto es de: ',producto); writeln(' '); end; readln(); End. program actividad3; Type cod= 1 .. 200; Procedure leer (VAR codigo: cod; VAR precio:real); Begin writeln ('Ingrese un CODIGO:'); readln( codigo); writeln('Ingrese un PRECIO:'); readln(precio); end; Procedure MINIMOS (VAR precio_min1,precio_min2: real; VAR cod_min1,cod_min2: cod; precio: real; codigo:cod); Begin IF (precio < precio_min1) then begin precio_min2:= precio_min1; precio_min1:= precio; cod_min2:= cod_min1; cod_min1:= codigo; end ELSE IF (precio < precio_min2) then begin precio_min2:= precio; cod_min2:= codigo; end; end; FUNCTION PAR(precio: real; codigo:cod): boolean; Begin IF (precio > 16) AND ((codigo MOD 2)=0) then PAR:= true ELSE PAR:= false; PAR:=(precio > 16) AND ((codigo MOD 2)=0); end; Var codigo, cod_min1,cod_min2: cod; precio,precio_min1,precio_min2: real; cant_16,indice: integer; Begin precio_min1:= 9999; precio_min2:= 9999; cant_16:= 0; FOR indice:= 1 to 5 do begin leer (codigo,precio); MINIMOS (precio_min1,precio_min2,cod_min1,cod_min2,precio,codigo); If (PAR(precio,codigo)) then cant_16:= cant_16 + 1; writeln(' '); end; writeln('El CODIGO del producto MAS BARATO es: ',cod_min1,' y del SEGUNDO MAS BARATO es: ',cod_min2); writeln('La cantidad de productos de mas de 16 pesos con codigo par es: ',cant_16); readln(); End. program Hello; type rango=1..200; procedure masBarato (precio:real; codigo:rango; var min1,min2:real; var codbarato1,codbarato2:rango); begin if (precio < min1) then begin min2:=min1; codbarato2:=codbarato1; min1:=precio; codbarato1:=codigo; end else if (precio < min2) then begin min2:=precio; codbarato2:=codigo; end; end; var i,cantidad16: integer; codigo, codbarato1, codbarato2: rango; precio,min1,min2: real; begin min1:=999; min2:=999; cantidad16:=0; for i:=1 to 6 do begin// use 6 para probar writeln ('CÓDIGO:'); readln(codigo); writeln ('PRECIO:'); readln(precio); masBarato(precio,codigo,min1,min2,codbarato1,codbarato2); if ((precio > 16) and ((codigo mod 2) = 0)) then //podria hacer una función pero no vale la pena por dos lineas... cantidad16:=cantidad16 + 1; end; writeln ('Los códigos de los dos productos más baratos: ', codbarato1, 'y ', codbarato2); writeln ('La cantidad de productos de más de 16 pesos con código par es: ',cantidad16); end. program ejercio6practica1parte2; const cant=200; type codigo=1..200; procedure leer (VAR cod:codigo; VAR precio:real); begin writeln ('Ingrese el codigo del producto'); readln(cod); writeln ('Ingrese el precio'); readln(precio); end; procedure minimo (precio:real;cod:codigo; VAR min1,min2:real;VAR codmin1,codmin2:codigo) ; begin if (precio < min1 ) then begin // min1 min2:=min1; codmin2:=codmin1; min1:=precio; codmin1:=cod; end else if (precio < min2) then // min2 begin min2:=precio; codmin2:=cod; end; end; var codmin1,codmin2,cod:codigo; min1,min2,precio:real; cant16,i:integer; begin min1:=9999; min2:=9999; cant16:=0; For i := 1 to cant do begin leer (cod,precio); minimo (precio,cod,min1,min2,codmin1,codmin2); if (precio > 16) and ((cod MOD 2=0)) then cant16:=cant16 + 1 end; writeln('los codigos de los productos mas baratos son ',codmin1, ' y ', codmin2 ); writeln ('la cantidad de productos de mas 16$ con codigo par es ',cant16 ); end.
unit uKeyBoardMouseEvnet; interface uses Windows, Messages, uConversion, uKeyScanCode; //点击 procedure ClickSpecifyPosition(const AHandle: HWND; const xPos, yPos: Integer; bSendMessage: Boolean = False; const AClickSpace: Integer = 10); //双击 procedure DBClickSpecifyPosition(const AHandle: HWND; const xPos, yPos: Integer; bSendMessage: Boolean = False); // procedure ClickButton(const AHandle: HWND); //将滚动条移动到最上方 procedure MoveScrollToTop(const AHandle: HWND; AIsVerticalScroll: Boolean = True); //将滚动条移动到最下方 procedure MoveScrollToBottom(const AHandle: HWND; AIsVerticalScroll: Boolean = True); //将滚动条移下一个位置 procedure MoveScrollToNextPosition(const AHandle: HWND; AIsVerticalScroll: Boolean = True); //将滚动条移下一个位置 procedure MoveScrollToUpNextPosition(const AHandle: HWND; AIsVerticalScroll: Boolean = True); procedure SetValueBit(var nValue: Integer; nCode: Word; ABeginBit: Integer); overload; procedure SetValueBit(var nValue: Integer; nCode: Byte; ABeginBit: Integer); overload; //编译 SHIFT 键 的LPARAM procedure BuildShift(var lParam: Integer; const ALeftShiftButton: Boolean); function FocusInput(const AScanCodes: array of Word): Boolean; overload; procedure FocusInput(const AScanCode: Word; const AIsNeedShift: Boolean); overload; procedure FocusInput(const AStr: string); overload; implementation procedure ClickSpecifyPosition(const AHandle: HWND; const xPos, yPos: Integer; bSendMessage: Boolean = False; const AClickSpace: Integer = 10); var lParam: Integer; begin lParam := MakeLParam(xPos, yPos); if bSendMessage then begin SendMessage(AHandle, WM_LBUTTONDOWN, MK_LBUTTON, lParam); Sleep(AClickSpace); SendMessage(AHandle, WM_LBUTTONUP, MK_LBUTTON, lParam); end else begin PostMessage(AHandle, WM_LBUTTONDOWN, MK_LBUTTON, lParam); Sleep(AClickSpace); PostMessage(AHandle, WM_LBUTTONUP, MK_LBUTTON, lParam); end; end; procedure DBClickSpecifyPosition(const AHandle: HWND; const xPos, yPos: Integer; bSendMessage: Boolean = False); var lParam: Integer; begin ClickSpecifyPosition(AHandle, xPos, yPos, bSendMessage); lParam := MakeLparam(xPos, yPos); if bSendMessage then SendMessage(AHandle, WM_LBUTTONDBLCLK, 0, lParam) else PostMessage(AHandle, WM_LBUTTONDBLCLK, 0, lParam); end; procedure ClickButton(const AHandle: HWND); var R: TRect; begin GetWindowRect(AHandle, R); ClickSpecifyPosition(AHandle, (R.Right - R.Left) div 2, (R.Bottom - R.Top) div 2, True); end; procedure MoveScrollToBottom(const AHandle: HWND; AIsVerticalScroll: Boolean = True); begin if AIsVerticalScroll then begin SendMessage(AHandle, WM_VSCROLL, SB_BOTTOM, 0); SendMessage(AHandle, WM_VSCROLL, SB_ENDSCROLL, 0); end else begin SendMessage(AHandle, WM_HSCROLL, SB_BOTTOM, 0); SendMessage(AHandle, WM_HSCROLL, SB_ENDSCROLL, 0); end; end; procedure MoveScrollToTop(const AHandle: HWND; AIsVerticalScroll: Boolean = True); begin if AIsVerticalScroll then begin SendMessage(AHandle, WM_VSCROLL, SB_TOP, 0); SendMessage(AHandle, WM_VSCROLL, SB_ENDSCROLL, 0); end else begin SendMessage(AHandle, WM_HSCROLL, SB_TOP, 0); SendMessage(AHandle, WM_HSCROLL, SB_ENDSCROLL, 0); end; end; procedure MoveScrollToNextPosition(const AHandle: HWND; AIsVerticalScroll: Boolean = True); begin if AIsVerticalScroll then begin PostMessage(AHandle, WM_VSCROLL, SB_LINEDOWN, 0); Sleep(10); PostMessage(AHandle, WM_VSCROLL, SB_ENDSCROLL, 0); end else begin PostMessage(AHandle, WM_HSCROLL, SB_LINEDOWN, 0); Sleep(10); PostMessage(AHandle, WM_HSCROLL, SB_ENDSCROLL, 0); end; end; procedure MoveScrollToUpNextPosition(const AHandle: HWND; AIsVerticalScroll: Boolean = True); begin if AIsVerticalScroll then begin PostMessage(AHandle, WM_VSCROLL, SB_LINEUP, 0); Sleep(10); PostMessage(AHandle, WM_VSCROLL, SB_ENDSCROLL, 0); end else begin PostMessage(AHandle, WM_HSCROLL, SB_LINEUP, 0); Sleep(10); PostMessage(AHandle, WM_HSCROLL, SB_ENDSCROLL, 0); end; end; { //Left Shift 000 0000 0 00101010 0000000000000001 WM_KEYDOWN nVirtKey:VK_SHIFT cRepeat:1 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:0 fUp:0 0000000000000001 WM_KEYUP nVirtKey:VK_SHIFT cRepeat:1 ScanCode:2A fExtended:0 fAltDown:0 fRepeat:1 fUp:1 //Right Shift <00003> 000A0830 P WM_KEYDOWN nVirtKey:VK_SHIFT cRepeat:1 ScanCode:36 fExtended:0 fAltDown:0 fRepeat:0 fUp:0 <00004> 000A0830 P WM_KEYUP nVirtKey:VK_SHIFT cRepeat:1 ScanCode:36 fExtended:0 fAltDown:0 fRepeat:1 fUp:1 //Left Ctrl <00005> 000A0830 P WM_KEYDOWN nVirtKey:VK_CONTROL cRepeat:1 ScanCode:1D fExtended:0 fAltDown:0 fRepeat:0 fUp:0 <00006> 000A0830 P WM_KEYUP nVirtKey:VK_CONTROL cRepeat:1 ScanCode:1D fExtended:0 fAltDown:0 fRepeat:1 fUp:1 //Rifht Ctrl <00007> 000A0830 P WM_KEYDOWN nVirtKey:VK_CONTROL cRepeat:1 ScanCode:1D fExtended:1 fAltDown:0 fRepeat:0 fUp:0 <00008> 000A0830 P WM_KEYUP nVirtKey:VK_CONTROL cRepeat:1 ScanCode:1D fExtended:1 fAltDown:0 fRepeat:1 fUp:1 } procedure SetValueBit(var nValue: Integer; nCode: Word; ABeginBit: Integer); overload; var i, iCode: Integer; nSize: Integer; begin nSize := sizeof(nCode); iCode := 0; for i := ABeginBit to ABeginBit + nSize - 1 do begin SetBit( nValue, i, GetBit(nCode, iCode) ); Inc(iCode); end; end; procedure SetValueBit(var nValue: Integer; nCode: Byte; ABeginBit: Integer); overload; var i, iCode: Integer; nSize: Integer; begin nSize := sizeof(nCode); iCode := 0; for i := ABeginBit to ABeginBit + nSize - 1 do begin SetBit( nValue, i, GetBit(nCode, iCode) ); Inc(iCode); end; end; procedure BuildShift(var lParam: Integer; const ALeftShiftButton: Boolean); var nScanCode, cRepeat: Word; begin if ALeftShiftButton then nScanCode := $2A else nScanCode := $36; cRepeat := 1; lParam := 0; SetValueBit( lParam, cRepeat, 0 ); SetValueBit( lParam, nScanCode, 16 ); end; function FocusInput(const AScanCodes: array of Word): Boolean; const KEYEVENTF_SCANCODE = $00000008; var aryIt: array[0..1] of TInput; nCount: Integer; nIndex: Integer; begin nCount := Length( AScanCodes ); nIndex := 0; while nIndex < nCount do begin aryIt[0].Itype := INPUT_KEYBOARD; aryIt[0].ki.wScan := AScanCodes[nIndex]; aryIt[0].ki.dwFlags := KEYEVENTF_SCANCODE; aryIt[0].ki.time := 0; aryIt[1].Itype := INPUT_KEYBOARD; aryIt[1].ki.wScan := AScanCodes[nIndex]; aryIt[1].ki.dwFlags := KEYEVENTF_SCANCODE or KEYEVENTF_KEYUP; aryIt[1].ki.time := 0; Inc( nIndex ); SendInput( 1, aryIt[0], SizeOf(TInPut) ); Sleep(1); end; Result := nIndex = nCount; end; procedure FocusInput(const AScanCode: Word; const AIsNeedShift: Boolean); const KEYEVENTF_SCANCODE = $00000008; var aryIt: array[0..1] of TInput; begin if AIsNeedShift then begin aryIt[0].Itype := INPUT_KEYBOARD; aryIt[0].ki.wScan := $2A; aryIt[0].ki.dwFlags := KEYEVENTF_SCANCODE; aryIt[0].ki.time := 0; SendInput( 1, aryIt[0], SizeOf(TInPut) ) end; aryIt[0].Itype := INPUT_KEYBOARD; aryIt[0].ki.wScan := AScanCode; aryIt[0].ki.dwFlags := KEYEVENTF_SCANCODE; aryIt[0].ki.time := 0; aryIt[1].Itype := INPUT_KEYBOARD; aryIt[1].ki.wScan := AScanCode; aryIt[1].ki.dwFlags := KEYEVENTF_SCANCODE or KEYEVENTF_KEYUP; aryIt[1].ki.time := 0; SendInput( 1, aryIt[0], SizeOf(TInPut) ); if AIsNeedShift then begin aryIt[0].Itype := INPUT_KEYBOARD; aryIt[0].ki.wScan := $2A; aryIt[0].ki.dwFlags := KEYEVENTF_SCANCODE or KEYEVENTF_KEYUP; aryIt[0].ki.time := 0; SendInput( 1, aryIt[0], SizeOf(TInPut) ) end; end; procedure FocusInput(const AStr: string); var i: Integer; nScanCode: Word; bIsShift: Boolean; begin for i := 1 to Length(AStr) do begin if CharToScanCode(AStr[i], nScanCode, bIsShift) then FocusInput( nScanCode, bIsShift ); end; end; end.
unit renderobject; {$mode objfpc}{$H+} {$modeswitch advancedrecords} interface uses Classes, SysUtils,GL, GLext, glu, types; type TRenderObject=class(TObject) private children: array of TRenderObject; fTextureCoords: record x: single; y: single; x2: single; y2: single; end; protected fChildrenOnly: boolean; procedure renderRelative; virtual; function getWidth:single; virtual; abstract; procedure setWidth(w: single); virtual; function getHeight:single; virtual; abstract; procedure setHeight(h: single); virtual; function getTexture: integer; virtual; abstract; function getLeft: single; virtual; function getRight: single; virtual; function getTop: single; virtual; function getBottom: single; virtual; public valid: boolean; x,y: single; rotationpoint: TPointF; rotation: single; procedure render; virtual; procedure addChild(child: TRenderObject); procedure removeChild(child: TRenderObject); procedure setTextureCoords(_x: single; _y: single; _x2: single; _y2: single); constructor create; property width: single read getWidth write setWidth; property height: single read getHeight write setHeight; property left: single read getLeft; property right: single read getRight; property top: single read getTop; property bottom: single read getBottom; property texture: integer read getTexture; property childrenonly: boolean read fChildrenOnly write fChildrenOnly; end; implementation function TRenderObject.getLeft: single; begin //todo: deal with rotation (or just let the caller deal with that) result:=x-width*((rotationpoint.x+1)/2); end; function TRenderObject.getRight: single; begin //rx=-1 : x+0 | x+w*0 //rx=0 : x+w/2 | x+w*0.5 //rx=1 : x+w/1 | x+w*1 //(rx+1)/2: //-1 -> (-1+1)/2=0/2=0 //0 -> (0+1)/2=1/2=0.5 //1 -> (1+1)/2=2/2=1 result:=x+width*((rotationpoint.x+1)/2); end; function TRenderObject.getTop: single; begin result:=y-height*((rotationpoint.y+1)/2); end; function TRenderObject.getBottom: single; begin result:=y+height*((rotationpoint.y+1)/2); end; procedure TRenderObject.setWidth(w: single); begin // end; procedure TRenderObject.setHeight(h: single); begin // end; procedure TRenderObject.addChild(child: TRenderObject); begin setlength(children, length(children)+1); children[length(children)-1]:=child; end; procedure TRenderObject.removeChild(child: TRenderObject); var i,j: integer; begin for i:=0 to length(children)-1 do if children[i]=child then begin for j:=i to length(children)-2 do children[j]:=children[j+1]; setlength(children, length(children)-1); end; end; procedure TRenderObject.setTextureCoords(_x: single; _y: single; _x2: single; _y2: single); begin fTextureCoords.x:=_x; fTextureCoords.y:=_y; fTextureCoords.x2:=_x2; fTextureCoords.y2:=_y2; end; procedure TRenderObject.renderRelative; var w, h: single; dw,dh: single; rx,ry: single; i: integer; begin //set the texture glBindTexture(GL_TEXTURE_2D, getTexture); glActiveTexture(GL_TEXTURE0); w:=width; // / 2; h:=height;// / 2; dw:=width / 2; dh:=height / 2; glTranslatef(x,-y,0); glRotatef(-rotation,0,0,0.5); rx:=-rotationpoint.x; ry:=-rotationpoint.y; if rx<>0 then rx:=dw*rx; if ry<>0 then ry:=-1*dh*ry; if fChildrenOnly=false then begin glBegin(GL_QUADS); // Each set of 4 vertices form a quad glTexCoord2f(fTextureCoords.x,fTextureCoords.y2); glVertex2f(rx+dw*-1, ry+dh*-1); glTexCoord2f(fTextureCoords.x2,fTextureCoords.y2); glVertex2f(rx+dw, ry+dh*-1); glTexCoord2f(fTextureCoords.x2,fTextureCoords.y); glVertex2f(rx+dw, ry+dh); glTexCoord2f(fTextureCoords.x,fTextureCoords.y); glVertex2f(rx+dw*-1, ry+dh); glEnd(); end; //render children for i:=0 to length(children)-1 do begin glPushMatrix(); children[i].renderRelative; glPopMatrix(); end; end; procedure TRenderObject.render; begin glLoadIdentity(); glPushMatrix(); renderRelative(); glPopMatrix(); end; constructor TRenderObject.create; begin fTextureCoords.x:=0; fTextureCoords.y:=0; fTextureCoords.x2:=1; fTextureCoords.y2:=1; end; end.
unit uPNL; interface uses uModApp, uUnit, System.Generics.Collections; type TModPNLReport = class; TModPNLSetting = class; TModPNLReportItem = class; TModPNLSettingItem = class(TModApp) private FFormula: string; FIndent: Integer; FKode: string; FLevel: Integer; FNama: string; FPercentOf: string; FPNLSetting: TModPNLSetting; FRowStyle: string; FStyle: string; FUrutan: Integer; public class function GetTableName: String; override; published property Formula: string read FFormula write FFormula; property Indent: Integer read FIndent write FIndent; property Kode: string read FKode write FKode; property Level: Integer read FLevel write FLevel; property Nama: string read FNama write FNama; property PercentOf: string read FPercentOf write FPercentOf; [AttributeOfHeader] property PNLSetting: TModPNLSetting read FPNLSetting write FPNLSetting; property RowStyle: string read FRowStyle write FRowStyle; property Style: string read FStyle write FStyle; property Urutan: Integer read FUrutan write FUrutan; end; TModPNLReportItem = class(TModApp) private FActual: Double; FActualPercent: Double; FBudget: Double; FBudgetPercent: Double; FLastYear: Double; FLastYearPercent: Double; FPNLReport: TModPNLReport; FPNLSettingItem: TModPNLSettingItem; public class function GetTableName: String; override; property LastYear: Double read FLastYear write FLastYear; property LastYearPercent: Double read FLastYearPercent write FLastYearPercent; published property Actual: Double read FActual write FActual; property ActualPercent: Double read FActualPercent write FActualPercent; property Budget: Double read FBudget write FBudget; property BudgetPercent: Double read FBudgetPercent write FBudgetPercent; [AttributeOfHeader] property PNLReport: TModPNLReport read FPNLReport write FPNLReport; property PNLSettingItem: TModPNLSettingItem read FPNLSettingItem write FPNLSettingItem; end; TModPNLReport = class(TModApp) private FActionPlan: string; FBulan: Integer; FGeneralCommentary: string; FIssue: string; FItems: TObjectList<TModPNLReportItem>; FKeterangan: string; FTahun: Integer; FTglInput: TDatetime; FUnitUsaha: TModUnit; function GetItems: TObjectList<TModPNLReportItem>; public class function GetTableName: String; override; property Items: TObjectList<TModPNLReportItem> read GetItems write FItems; published property ActionPlan: string read FActionPlan write FActionPlan; property Bulan: Integer read FBulan write FBulan; property GeneralCommentary: string read FGeneralCommentary write FGeneralCommentary; property Issue: string read FIssue write FIssue; property Keterangan: string read FKeterangan write FKeterangan; property Tahun: Integer read FTahun write FTahun; property TglInput: TDatetime read FTglInput write FTglInput; property UnitUsaha: TModUnit read FUnitUsaha write FUnitUsaha; end; TModPNLSetting = class(TModApp) private FIsActive: Integer; FItems: TObjectList<TModPNLSettingItem>; FNama: string; FUnitUsaha: TModUnit; function GetItems: TObjectList<TModPNLSettingItem>; public class function GetTableName: String; override; property Items: TObjectList<TModPNLSettingItem> read GetItems write FItems; published property IsActive: Integer read FIsActive write FIsActive; property Nama: string read FNama write FNama; property UnitUsaha: TModUnit read FUnitUsaha write FUnitUsaha; end; implementation function TModPNLReport.GetItems: TObjectList<TModPNLReportItem>; begin if not Assigned(FItems) then FItems := TObjectList<TModPNLReportItem>.Create(); Result := FItems; end; { TModPNLReport } class function TModPNLReport.GetTableName: String; begin Result := 'TPNLReport'; end; function TModPNLSetting.GetItems: TObjectList<TModPNLSettingItem>; begin if not Assigned(FItems) then FItems := TObjectList<TModPNLSettingItem>.Create(); Result := FItems; end; { TModPNLSetting } class function TModPNLSetting.GetTableName: String; begin Result := 'TPNLSetting'; end; { TModPNLReportItem } class function TModPNLReportItem.GetTableName: String; begin Result := 'TPNLReportItem'; end; { TModPNLSettingItem } class function TModPNLSettingItem.GetTableName: String; begin Result := 'TPNLSettingItem'; end; initialization TModPNLReport.RegisterRTTI; TModPNLReportItem.RegisterRTTI; TModPNLSetting.RegisterRTTI; TModPNLSettingItem.RegisterRTTI; end.
{------------------------------------------------------------------------------- $File$, (C) 2006..2007 by Bernd Gabriel. All rights reserved. -------------------------------------------------------------------------------- Author : $Author: Bernd $ Last CheckIn : $Date: 2007/01/18 22:57:51 $ Revision : $Revision: 1.5 $ mailto: info@fast-function-factory.de Log: ==== $Log: BegaSplitter.pas,v $ Revision 1.5 2007/01/18 22:57:51 Bernd no message Revision 1.4 2007/01/14 20:43:02 Bernd TBegaSplitter (V) 2.0 Revision 1.3 2007/01/11 00:42:37 Bernd no message Revision 1.2 2007/01/10 22:18:14 Bernd no message Revision 1.1 2006/12/24 15:25:37 Bernd no message -------------------------------------------------------------------------------} unit BegaSplitter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Math, // own units BegaObjects; const cVersion = '(V) 2.0, 12/2006, 01/2007'; cMinHandledSize = 7; type //------------------------------------------------------------------------------ // BG, 14.01.2007: modified copy of Delphi6-TSplitter //------------------------------------------------------------------------------ TBegaCustomSplitter = class(TGraphicControl) private FActiveControl: TWinControl; FAutoSnap: Boolean; FBeveled: Boolean; FBrush: TBrush; FControl: TControl; FDownPos: TPoint; FLineDC: HDC; FLineVisible: Boolean; FMaxSize: Integer; FMinSize: NaturalNumber; FNewSize: Integer; FOldKeyDown: TKeyEvent; FOldSize: Integer; FOnCanResize: TCanResizeEvent; FOnMoved: TNotifyEvent; FOnPaint: TNotifyEvent; FPrevBrush: HBrush; FResizeStyle: TResizeStyle; FSplit: Integer; procedure AllocateLineDC; procedure CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); procedure DrawLine; function FindControl: TControl; procedure FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ReleaseLineDC; procedure SetBeveled(Value: Boolean); procedure UpdateControlSize; procedure UpdateSize(X, Y: Integer); protected function CanResize(var NewSize: Integer): Boolean; reintroduce; virtual; function DoCanResize(var NewSize: Integer): Boolean; virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Paint; override; procedure RequestAlign; override; procedure StopSizing; dynamic; procedure updateNeighborhood; virtual; property Align default alLeft; property AutoSnap: Boolean read FAutoSnap write FAutoSnap default True; property Beveled: Boolean read FBeveled write SetBeveled default False; property MinSize: NaturalNumber read FMinSize write FMinSize default 30; property ResizeStyle: TResizeStyle read FResizeStyle write FResizeStyle default rsPattern; property OnCanResize: TCanResizeEvent read FOnCanResize write FOnCanResize; property OnMoved: TNotifyEvent read FOnMoved write FOnMoved; property OnPaint: TNotifyEvent read FOnPaint write FOnPaint; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; //------------------------------------------------------------------------------ // BG, 14.01.2007: splitter with button to quickly hide one neighbor. //------------------------------------------------------------------------------ TBegaArrowOrientation = (aoLeft, aoRight, aoUp, aoDown); TBegaSplitterButtonAlign = (baLeftTop, baCenter, baRightBottom); TBegaSplitterButtonKind = (bkNone, bkNormal, bkFlat); TBegaSplitter = class(TBegaCustomSplitter) private FButtonAlign: TBegaSplitterButtonAlign; FButtonKind: TBegaSplitterButtonKind; FButtonSize: Integer; FSplitCursor: TCursor; FControl: TControl; FOldControlSize: Integer; procedure setButtonAlign(const Value: TBegaSplitterButtonAlign); procedure setButtonKind(const Value: TBegaSplitterButtonKind); procedure setButtonSize(const Value: Integer); function ButtonRect: TRect; procedure updateCursor(const Pt: TPoint); function getClosed: Boolean; procedure setClosed(const Value: Boolean); protected function isInButton(const Pt: TPoint): Boolean; procedure Paint; override; procedure Loaded; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure updateNeighborhood; override; public constructor Create(AOwner: TComponent); override; property Closed: Boolean read getClosed write setClosed default False; published property Align; property AutoSnap; property Beveled; property Color; property Constraints; property Enabled; property ButtonAlign: TBegaSplitterButtonAlign read FButtonAlign write setButtonAlign default baLeftTop; property ButtonKind: TBegaSplitterButtonKind read FButtonKind write setButtonKind default bkNormal; property ButtonSize: Integer read FButtonSize write setButtonSize default 80; property MinSize; property OnCanResize; property OnMoved; property OnPaint; property ParentColor; property ResizeStyle; property Visible; end; implementation uses Types; { TBegaCustomSplitter } type TWinControlAccess = class(TWinControl); constructor TBegaCustomSplitter.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoSnap := True; Align := alLeft; Width := 7; Cursor := crHSplit; FMinSize := 30; FResizeStyle := rsPattern; FOldSize := -1; end; destructor TBegaCustomSplitter.Destroy; begin FBrush.Free; inherited Destroy; end; procedure TBegaCustomSplitter.AllocateLineDC; begin FLineDC := GetDCEx(Parent.Handle, 0, DCX_CACHE or DCX_CLIPSIBLINGS or DCX_LOCKWINDOWUPDATE); if ResizeStyle = rsPattern then begin if FBrush = nil then begin FBrush := TBrush.Create; FBrush.Bitmap := AllocPatternBitmap(clBlack, clWhite); end; FPrevBrush := SelectObject(FLineDC, FBrush.Handle); end; end; procedure TBegaCustomSplitter.DrawLine; var P: TPoint; begin FLineVisible := not FLineVisible; P := Point(Left, Top); if Align in [alLeft, alRight] then P.X := Left + FSplit else P.Y := Top + FSplit; with P do PatBlt(FLineDC, X, Y, Width, Height, PATINVERT); end; procedure TBegaCustomSplitter.ReleaseLineDC; begin if FPrevBrush <> 0 then SelectObject(FLineDC, FPrevBrush); ReleaseDC(Parent.Handle, FLineDC); if FBrush <> nil then begin FBrush.Free; FBrush := nil; end; end; function TBegaCustomSplitter.FindControl: TControl; var P: TPoint; I: Integer; R: TRect; begin Result := nil; P := Point(Left, Top); case Align of alLeft: Dec(P.X); alRight: Inc(P.X, Width); alTop: Dec(P.Y); alBottom: Inc(P.Y, Height); else Exit; end; for I := 0 to Parent.ControlCount - 1 do begin Result := Parent.Controls[I]; if Result.Visible and Result.Enabled then begin R := Result.BoundsRect; if (R.Right - R.Left) = 0 then if Align in [alTop, alLeft] then Dec(R.Left) else Inc(R.Right); if (R.Bottom - R.Top) = 0 then if Align in [alTop, alLeft] then Dec(R.Top) else Inc(R.Bottom); if PtInRect(R, P) then Exit; end; end; Result := nil; end; procedure TBegaCustomSplitter.RequestAlign; begin inherited RequestAlign; if (Cursor <> crVSplit) and (Cursor <> crHSplit) then Exit; if Align in [alBottom, alTop] then Cursor := crVSplit else Cursor := crHSplit; end; procedure TBegaCustomSplitter.Paint; const XorColor = $00FFD8CE; var FrameBrush: HBRUSH; R: TRect; begin R := ClientRect; Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); if Beveled then begin if Align in [alLeft, alRight] then InflateRect(R, -1, 2) else InflateRect(R, 2, -1); OffsetRect(R, 1, 1); FrameBrush := CreateSolidBrush(ColorToRGB(clBtnHighlight)); FrameRect(Canvas.Handle, R, FrameBrush); DeleteObject(FrameBrush); OffsetRect(R, -2, -2); FrameBrush := CreateSolidBrush(ColorToRGB(clBtnShadow)); FrameRect(Canvas.Handle, R, FrameBrush); DeleteObject(FrameBrush); end; // if csDesigning in ComponentState then // { Draw outline } // with Canvas do // begin // Pen.Style := psDot; // Pen.Mode := pmXor; // Pen.Color := XorColor; // Brush.Style := bsClear; // Rectangle(0, 0, ClientWidth, ClientHeight); // end; FLineVisible := False; if Assigned(FOnPaint) then FOnPaint(Self); end; function TBegaCustomSplitter.DoCanResize(var NewSize: Integer): Boolean; begin Result := CanResize(NewSize); if Result and (NewSize <= MinSize) and FAutoSnap then NewSize := 0; end; function TBegaCustomSplitter.CanResize(var NewSize: Integer): Boolean; begin Result := True; if Assigned(FOnCanResize) then FOnCanResize(Self, NewSize, Result); end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var I: Integer; begin inherited MouseDown(Button, Shift, X, Y); if Enabled then if Button = mbLeft then begin updateNeighborhood; FDownPos := Point(X, Y); if Assigned(FControl) then begin if Align in [alLeft, alRight] then begin FMaxSize := Parent.ClientWidth - FMinSize; for I := 0 to Parent.ControlCount - 1 do with Parent.Controls[I] do if Visible and (Align in [alLeft, alRight]) then Dec(FMaxSize, Width); Inc(FMaxSize, FControl.Width); end else begin FMaxSize := Parent.ClientHeight - FMinSize; for I := 0 to Parent.ControlCount - 1 do with Parent.Controls[I] do if Align in [alTop, alBottom] then Dec(FMaxSize, Height); Inc(FMaxSize, FControl.Height); end; UpdateSize(X, Y); AllocateLineDC; with ValidParentForm(Self) do if ActiveControl <> nil then begin FActiveControl := ActiveControl; FOldKeyDown := TWinControlAccess(FActiveControl).OnKeyDown; TWinControlAccess(FActiveControl).OnKeyDown := FocusKeyDown; end; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.UpdateControlSize; begin if FNewSize <> FOldSize then begin Parent.DisableAlign; try case Align of alLeft: begin FControl.Width := FNewSize; Left := FControl.Width; end; alTop: begin FControl.Height := FNewSize; Top := FControl.Height; end; alRight: begin FControl.Left := FControl.Left + (FControl.Width - FNewSize); FControl.Width := FNewSize; Left := max(FControl.Left - 1, 0); end; alBottom: begin FControl.Top := FControl.Top + (FControl.Height - FNewSize); FControl.Height := FNewSize; Top := max(FControl.Top, -1); end; end; finally Parent.EnableAlign; end; Update; if Assigned(FOnMoved) then FOnMoved(Self); FOldSize := FNewSize; end; end; procedure TBegaCustomSplitter.CalcSplitSize(X, Y: Integer; var NewSize, Split: Integer); var S: Integer; begin if Align in [alLeft, alRight] then Split := X - FDownPos.X else Split := Y - FDownPos.Y; S := 0; case Align of alLeft: S := FControl.Width + Split; alRight: S := FControl.Width - Split; alTop: S := FControl.Height + Split; alBottom: S := FControl.Height - Split; end; NewSize := S; if S < FMinSize then NewSize := FMinSize else if S > FMaxSize then NewSize := FMaxSize; if S <> NewSize then begin if Align in [alRight, alBottom] then S := S - NewSize else S := NewSize - S; Inc(Split, S); end; end; procedure TBegaCustomSplitter.UpdateSize(X, Y: Integer); begin CalcSplitSize(X, Y, FNewSize, FSplit); end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.MouseMove(Shift: TShiftState; X, Y: Integer); var NewSize, Split: Integer; begin inherited; if Enabled then if (ssLeft in Shift) and Assigned(FControl) then begin CalcSplitSize(X, Y, NewSize, Split); if DoCanResize(NewSize) then begin if ResizeStyle in [rsLine, rsPattern] then DrawLine; FNewSize := NewSize; FSplit := Split; if ResizeStyle = rsUpdate then UpdateControlSize; if ResizeStyle in [rsLine, rsPattern] then DrawLine; end; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Enabled then if Assigned(FControl) then begin if ResizeStyle in [rsLine, rsPattern] then DrawLine; UpdateControlSize; StopSizing; end; end; procedure TBegaCustomSplitter.FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then StopSizing else if Assigned(FOldKeyDown) then FOldKeyDown(Sender, Key, Shift); end; procedure TBegaCustomSplitter.SetBeveled(Value: Boolean); begin FBeveled := Value; Repaint; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.StopSizing; begin if Assigned(FControl) then begin if FLineVisible then DrawLine; ReleaseLineDC; if Assigned(FActiveControl) then begin TWinControlAccess(FActiveControl).OnKeyDown := FOldKeyDown; FActiveControl := nil; end; end; if Assigned(FOnMoved) then FOnMoved(Self); end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; case Operation of opRemove: if FControl = AComponent then FControl := nil; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaCustomSplitter.updateNeighborhood; begin if csLoading in ComponentState then exit; FControl := FindControl; end; { TBegaSplitter} //- BG ----------------------------------------------------------- 14.01.2007 -- procedure calcAlignment( AlignToStart, AlignToEnd, AlignedSize: Integer; Align: TBegaSplitterButtonAlign; out AlignedStart, AlignedEnd: Integer); begin case Align of baLeftTop: AlignedStart := AlignToStart; baCenter: AlignedStart := max((AlignToStart + AlignToEnd - AlignedSize) div 2, AlignToStart); baRightBottom: AlignedStart := max(AlignToEnd - AlignedSize, AlignToStart); end; AlignedEnd := min(AlignedStart + AlignedSize, AlignToEnd); end; //- BG ----------------------------------------------------------- 14.01.2007 -- function TBegaSplitter.ButtonRect: TRect; begin case Align of alTop, alBottom: begin Result.Top := 0; Result.Bottom := Height; calcAlignment(0, Width, ButtonSize, ButtonAlign, Result.Left, Result.Right); end; alLeft, alRight: begin Result.Left := 0; Result.Right := Width; calcAlignment(0, Height, ButtonSize, ButtonAlign, Result.Top, Result.Bottom); end; else calcAlignment(0, Width, ButtonSize, ButtonAlign, Result.Left, Result.Right); calcAlignment(0, Height, ButtonSize, ButtonAlign, Result.Top, Result.Bottom); end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- constructor TBegaSplitter.Create(AOwner: TComponent); begin inherited; FButtonAlign := baLeftTop; FButtonKind := bkNormal; FButtonSize := 80; end; //- BG ----------------------------------------------------------- 14.01.2007 -- function TBegaSplitter.getClosed: Boolean; begin Result := FOldSize = 0; if Parent <> nil then case Align of alLeft : Result := Left <= 0; alRight : Result := Left + Width >= Parent.Width; alTop : Result := Top <= 0; alBottom : Result := Top + Height >= Parent.Height; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- function TBegaSplitter.isInButton(const Pt: TPoint): Boolean; begin if ButtonKind <> bkNone then Result := PtInRect(ButtonRect, Pt) else Result := False; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.Loaded; begin inherited; FSplitCursor := Cursor; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.MouseMove(Shift: TShiftState; X, Y: Integer); begin updateCursor(Point(X,Y)); inherited; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Enabled then if isInButton(Point(X,Y)) then Closed := not Closed; inherited; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.Paint; procedure paintArrow(Rect: TRect; PointTo: TBegaArrowOrientation); var Size: Integer; Center: TPoint; begin Size := (min(Rect.Right - Rect.Left, Rect.Bottom - Rect.Top) + 1) div 2; if Size >= 1 then begin Center.X := (Rect.Right + Rect.Left) div 2; Center.Y := (Rect.Top + Rect.Bottom) div 2; Rect.Left := Center.X - Size; Rect.Right := Center.X + Size; Rect.Top := Center.Y - Size; Rect.Bottom := Center.Y + Size; with Canvas do begin Pen.Color := clBtnText; Brush.Color := clBtnText; case PointTo of aoLeft: Polygon([ Point(Rect.Right, Rect.Top - 1), Point(Rect.Right, Rect.Bottom + 1), Point(Rect.Left, Center.Y)]); aoRight: Polygon([ Point(Rect.Left, Rect.Top - 1), Point(Rect.Left, Rect.Bottom + 1), Point(Rect.Right, Center.Y)]); aoUp: Polygon([ Point(Rect.Left - 1, Rect.Bottom), Point(Rect.Right + 1, Rect.Bottom), Point(Center.X, Rect.Top)]); aoDown: Polygon([ Point(Rect.Left - 1, Rect.Top), Point(Rect.Right + 1, Rect.Top), Point(Center.X, Rect.Bottom)]); end; Brush.Color := Color; end; end; end; var Rc: TRect; begin inherited; if ButtonKind <> bkNone then begin Rc := ButtonRect; if (Rc.Left < Rc.Right) and (Rc.Top < Rc.Bottom) then // if (csDesigning in ComponentState) and not Enabled then // with Canvas do // begin // InflateRect(Rc, -1, -1); // Rectangle(Rc); // end // else if Enabled then with Canvas do begin Brush.Color := Color; Brush.Style := bsSolid; Pen.Mode := pmCopy; Pen.Style := psSolid; if ButtonKind = bkFlat then begin dec(Rc.Right); dec(Rc.Bottom); Pen.Color := clBtnHighlight; Polyline([Point(Rc.Left, Rc.Bottom), Point(Rc.Right, Rc.Bottom), Point(Rc.Right, Rc.Top)]); Pen.Color := clBtnShadow; Polyline([Point(Rc.Right, Rc.Top), Point(Rc.Left, Rc.Top), Point(Rc.Left, Rc.Bottom)]); inc(Rc.Left); inc(Rc.Top); end; Pen.Color := clBtnHighlight; Rectangle(Rc); dec(Rc.Right); dec(Rc.Bottom); Pen.Color := clBtnShadow; Polyline([Point(Rc.Left, Rc.Bottom), Point(Rc.Right, Rc.Bottom), Point(Rc.Right, Rc.Top)]); InflateRect(Rc, -2, -2); if Closed then case Align of alTop: paintArrow(Rc, aoDown); alBottom: paintArrow(Rc, aoUp); alLeft: paintArrow(Rc, aoRight); alRight: paintArrow(Rc, aoLeft); end else case Align of alTop: paintArrow(Rc, aoUp); alBottom: paintArrow(Rc, aoDown); alLeft: paintArrow(Rc, aoLeft); alRight: paintArrow(Rc, aoRight); end; end; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.setButtonAlign(const Value: TBegaSplitterButtonAlign); begin if FButtonAlign <> Value then begin FButtonAlign := Value; invalidate; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.setButtonKind(const Value: TBegaSplitterButtonKind); begin if FButtonKind <> Value then begin FButtonKind := Value; invalidate; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.setButtonSize(const Value: Integer); begin if FButtonSize <> Value then begin FButtonSize := Value; invalidate; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.setClosed(const Value: Boolean); begin if Value <> Closed then begin if Value then begin //close UpdateNeighborhood; if FOldSize = -1 then begin // first time if FControl = nil then case Align of alLeft : FOldSize := Left; alRight : if Parent <> nil then FOldSize := Parent.Width - Left - Width else FOldSize := 30; alTop : FOldSize := Top; alBottom : if Parent <> nil then FOldSize := Parent.Height - Top - Height else FOldSize := 30; end else case Align of alTop, alBottom: FOldSize := FControl.Height; alLeft, alRight: FOldSize := FControl.Width; end; end; FOldControlSize := FOldSize; FNewSize := 0; end else begin //open; FNewSize := FOldControlSize; end; UpdateControlSize; end; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.updateCursor(const Pt: TPoint); begin if isInButton(Pt) then Cursor := crDefault else Cursor := FSplitCursor; end; //- BG ----------------------------------------------------------- 14.01.2007 -- procedure TBegaSplitter.updateNeighborhood; begin if not Closed then inherited; end; end.
unit SQLHistory; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, JvExGrids, BCControls.StringGrid, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ImgList, Vcl.ActnList, JvStringGrid, BCControls.ImageList, BCControls.ToolBar, Vcl.ExtCtrls, System.Actions; type TSQLHistoryFrame = class(TFrame) ActionList: TActionList; SQLEditorAction: TAction; ImageList: TBCImageList; CleanUpAction: TAction; RefreshAction: TAction; ButtonPanel: TPanel; ToolBar: TBCToolBar; ToolButton1: TToolButton; GridPanel: TPanel; SQLHistoryStringGrid: TBCStringGrid; ToolBar2: TBCToolBar; ToolButton6: TToolButton; ToolBar3: TBCToolBar; ToolButton7: TToolButton; Bevel1: TBevel; Bevel2: TBevel; EditHistoryAction: TAction; ToolButton2: TToolButton; procedure SQLEditorActionExecute(Sender: TObject); procedure CleanUpActionExecute(Sender: TObject); procedure RefreshActionExecute(Sender: TObject); procedure EditHistoryActionExecute(Sender: TObject); private { Private declarations } procedure ReadSQLHistoryFile; procedure WriteSQLHistoryFile; procedure SetFields; function AllRowsSelected: Boolean; function RowsSelected: Boolean; procedure RemoveSelectedRows; public { Public declarations } procedure DoInit; procedure AssignOptions; procedure SelectAll; end; implementation {$R *.dfm} uses Main, Lib, BCCommon.OptionsContainer, HistoryEdit, BCCommon.Messages, BCCommon.StringUtils, BCCommon.Lib; const GRID_COLUMN_BOOLEAN = 0; GRID_COLUMN_DATETIME = 1; GRID_COLUMN_SCHEMA = 2; GRID_COLUMN_SQL_STATEMENT = 3; GRID_COLUMN_SQL = 4; procedure TSQLHistoryFrame.SQLEditorActionExecute(Sender: TObject); begin if SQLEditorAction.Enabled then MainForm.LoadSQLIntoEditor(SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, SQLHistoryStringGrid.Row], SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.Row]); end; procedure TSQLHistoryFrame.AssignOptions; begin if OptionsContainer.ObjectFrameAlign = 'Bottom' then ToolBar.Align := alBottom else ToolBar.Align := alTop; end; function TSQLHistoryFrame.AllRowsSelected: Boolean; var i: Integer; begin Result := True; for i := 1 to SQLHistoryStringGrid.RowCount - 1 do if SQLHistoryStringGrid.Cells[GRID_COLUMN_BOOLEAN, i] = 'False' then begin Result := False; Break; end; end; function TSQLHistoryFrame.RowsSelected: Boolean; var i: Integer; begin Result := False; for i := 1 to SQLHistoryStringGrid.RowCount - 1 do if SQLHistoryStringGrid.Cells[GRID_COLUMN_BOOLEAN, i] = 'True' then begin Result := True; Break; end; end; procedure TSQLHistoryFrame.SelectAll; var i: Integer; begin for i := 1 to SQLHistoryStringGrid.RowCount - 1 do SQLHistoryStringGrid.Cells[GRID_COLUMN_BOOLEAN, i] := 'True'; end; procedure TSQLHistoryFrame.RemoveSelectedRows; var i: Integer; begin i := 1; while i < SQLHistoryStringGrid.RowCount do begin if SQLHistoryStringGrid.Cells[GRID_COLUMN_BOOLEAN, i] = 'True' then SQLHistoryStringGrid.RemoveRow(i) else Inc(i); end; end; procedure TSQLHistoryFrame.CleanUpActionExecute(Sender: TObject); begin if CleanUpAction.Enabled then begin if AllRowsSelected then begin if AskYesOrNo('Clean SQL history, are you sure?') then begin System.SysUtils.DeleteFile(Lib.GetHistoryFile); DoInit; end; end else if RowsSelected then begin if AskYesOrNo('Clean selected row(s) from SQL history, are you sure?') then begin RemoveSelectedRows; WriteSQLHistoryFile; DoInit; end; end else ShowMessage('Select rows to clean. Select all with Ctrl + A.'); end; end; procedure TSQLHistoryFrame.DoInit; begin SQLHistoryStringGrid.HideCol(GRID_COLUMN_SQL); ReadSQLHistoryFile; SetFields; AutoSizeCol(SQLHistoryStringGrid, 1); end; procedure TSQLHistoryFrame.EditHistoryActionExecute(Sender: TObject); begin with HistoryEditDialog do try HistoryDate := SQLHistoryStringGrid.Cells[GRID_COLUMN_DATETIME, SQLHistoryStringGrid.Row]; Schema := SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, SQLHistoryStringGrid.Row]; SQLStatement := SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.Row]; if Open then begin if AskYesOrNo('Save changes?') then begin SQLHistoryStringGrid.Cells[GRID_COLUMN_DATETIME, SQLHistoryStringGrid.Row] := HistoryDate; SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, SQLHistoryStringGrid.Row] := Schema; SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.Row] := SQLStatement; SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.Row] := Copy(SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.Row], 0, 200); if Length(SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.Row]) > 200 then SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.Row] := SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.Row] + '...'; WriteSQLHistoryFile; end; end; finally Free; end; end; procedure TSQLHistoryFrame.WriteSQLHistoryFile; var i: Integer; History: TStringList; begin History := TStringList.Create; try // date;schema;sql#!ENDSQL!# for i := 1 to SQLHistoryStringGrid.RowCount - 1 do History.Add(EncryptString( SQLHistoryStringGrid.Cells[GRID_COLUMN_DATETIME, i] + ';' + SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, i] + ';' + SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, i] + END_OF_SQL_STATEMENT)); History.SaveToFile(GetHistoryFile); finally History.Free; end; end; procedure TSQLHistoryFrame.ReadSQLHistoryFile; var i: Integer; s: string; History: TStringList; begin SQLHistoryStringGrid.Clear; Application.ProcessMessages; SQLHistoryStringGrid.RowCount := 2; if FileExists(GetHistoryFile) then begin History := TStringList.Create; History.LoadFromFile(GetHistoryFile); for i := 0 to History.Count - 1 do History.Strings[i] := DecryptString(History.Strings[i]); try i := 0; while i < History.Count do begin SQLHistoryStringGrid.Cells[GRID_COLUMN_BOOLEAN, SQLHistoryStringGrid.RowCount - 1] := 'False'; s := History.Strings[i]; SQLHistoryStringGrid.Cells[GRID_COLUMN_DATETIME, SQLHistoryStringGrid.RowCount - 1] := Copy(s, 0, Pos(';', s) - 1); s := Copy(s, Pos(';', s) + 1, Length(s)); SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, SQLHistoryStringGrid.RowCount - 1] := Lib.FormatSchema(Copy(s, 0, Pos(';', s) - 1)); s := Copy(s, Pos(';', s) + 1, Length(s)); while Pos(END_OF_SQL_STATEMENT, s) = 0 do begin SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1] := SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1] + s + ' '; Inc(i); s := History.Strings[i]; end; SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1] := SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1] + Copy(s, 0, Pos(END_OF_SQL_STATEMENT, s) - 1); SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.RowCount - 1] := Copy(SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1], 0, 200); if Length(SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, SQLHistoryStringGrid.RowCount - 1]) > 200 then SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.RowCount - 1] := SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, SQLHistoryStringGrid.RowCount - 1] + '...'; Inc(i); if i < History.Count then SQLHistoryStringGrid.RowCount := SQLHistoryStringGrid.RowCount + 1; end; finally History.Free; end; end; end; procedure TSQLHistoryFrame.RefreshActionExecute(Sender: TObject); begin DoInit; end; procedure TSQLHistoryFrame.SetFields; var ItemsFound: Boolean; begin SQLHistoryStringGrid.Cells[GRID_COLUMN_DATETIME, 0] := 'Date'; SQLHistoryStringGrid.Cells[GRID_COLUMN_SCHEMA, 0] := 'Schema'; SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL_STATEMENT, 0] := 'SQL Statement'; ItemsFound := (SQLHistoryStringGrid.RowCount > 1) and (SQLHistoryStringGrid.Cells[GRID_COLUMN_SQL, 1] <> ''); SQLEditorAction.Enabled := ItemsFound; CleanUpAction.Enabled := ItemsFound; end; end.
{ by Adrian D. Bonev The following unit is a visual component inherited of Tpanel, which has the OnPaint and Canvas exposed. Do not Draw Rectangles in response to OnPaint - result is not good - Use Polyline or LineTo instead } unit PanelPaintCanvas; interface uses Classes, Controls, ExtCtrls; type TPanelPaintCanvas = class (TPanel) private { Private declarations } FOnPaint : TNotifyEvent; //this Exposes OnPiant not exposed in TLabel; protected { Protected declarations } public { Public declarations } property Canvas; procedure Paint; override; published { Published declarations } property OnPaint : TNotifyEvent read FOnPaint write FOnPaint; //exposes Onpaint not exposed in TPanel end; procedure Register; implementation procedure Register; begin RegisterComponents('Standard', [TPanelPaintCanvas]); end; { TPanelPaintCanvas } procedure TPanelPaintCanvas.Paint; begin inherited Paint; if assigned(FOnPaint) then FOnPaint(Self); {call Paint Event} end; end.
unit uFileZilla; interface uses GnuGettext, uBaseModule, SysUtils, Classes, Windows, ExtCtrls, StdCtrls, Buttons, uNetstatTable, uTools, uProcesses; type tFileZilla = class(tBaseModule) OldPIDs, OldPorts: string; procedure ServiceInstall; override; procedure ServiceUnInstall; override; procedure Start; override; procedure Stop; override; procedure Admin; override; procedure UpdateStatus; override; procedure CheckIsService; reintroduce; procedure AddLog(Log: string; LogType: tLogType=ltDefault); reintroduce; constructor Create(pbbService: TBitBtn; pStatusPanel: tPanel; pPIDLabel, pPortLabel: tLabel; pStartStopButton, pAdminButton: tBitBtn); destructor Destroy; override; end; implementation const cServiceName = 'FileZilla Server'; cModuleName = 'FileZilla'; { tFileZilla } procedure tFileZilla.AddLog(Log: string; LogType: tLogType); begin inherited AddLog('filezilla', Log, LogType); end; procedure tFileZilla.Admin; var App: string; begin App:=BaseDir+'filezillaftp\filezilla server interface.exe'; Addlog(Format(_('Executing "%s"'),[App]),ltDebug); ExecuteFile(App,'','',SW_SHOW); end; procedure tFileZilla.CheckIsService; var s: string; begin inherited CheckIsService(cServiceName); if isService then s:=_('Service installed') else s:=_('Service not installed'); AddLog(Format(_('Checking for service (name="%s"): %s'),[cServiceName,s]),ltDebug); end; constructor tFileZilla.Create; var PortBlocker: string; ServerApp: string; ServerPort: Integer; begin inherited; ModuleName:=cModuleName; isService:=false; AddLog(_('Initializing module...'),ltDebug); ServerApp:=basedir+'FileZillaFTP\FileZillaServer.exe'; ServerPort:=21; if not FileExists(ServerApp) then AddLog(Format(_('Possible problem detected: file "%s" not found - run this program from your XAMPP root directory!'),[ServerApp]),ltError); CheckIsService; if Config.CheckDefaultPorts then begin AddLog(_('Checking default ports...'),ltDebug); PortBlocker:=NetStatTable.isPortInUse(ServerPort); if (PortBlocker<>'') then begin if (LowerCase(PortBlocker)=LowerCase(ServerApp)) then begin AddLog(Format(_('"%s" seems to be running on port %d?'),[ServerApp,ServerPort]),ltError); end else begin AddLog(Format(_('Possible problem detected: Port %d in use by "%s"!'),[ServerPort,PortBlocker]),ltError); end; end; end; end; destructor tFileZilla.Destroy; begin inherited; end; procedure tFileZilla.ServiceInstall; var App, Param: string; RC: Integer; begin App:=BaseDir+'filezillaftp\filezillaserver.exe'; AddLog(_('Installing service...')); Addlog(Format(_('Executing "%s"'),[App]),ltDebug); RC:=RunAsAdmin(App,Param,SW_HIDE); if RC=0 then AddLog(Format(_('Return code: %d'),[RC]),ltDebug) else AddLog(Format(_('There may be an error, return code: %d - %s'),[RC,SystemErrorMessage(RC)]),ltError); end; procedure tFileZilla.ServiceUnInstall; var App, Param: string; RC: Cardinal; begin App:='sc'; Param:='delete "'+cServiceName+'"'; AddLog('Uninstalling service...'); Addlog(Format(_('Executing "%s" "%s"'),[App,Param]),ltDebug); RC:=RunAsAdmin(App,Param,SW_HIDE); if RC=0 then AddLog(Format(_('Return code: %d'),[RC]),ltDebug) else AddLog(Format(_('There may be an error, return code: %d - %s'),[RC,SystemErrorMessage(RC)]),ltError); end; procedure tFileZilla.Start; var App: string; RC: Cardinal; begin if isService then begin AddLog(Format(_('Starting %s service...'),[cModuleName])); App:=Format('start "%s"',[cServiceName]); Addlog(Format(_('Executing "%s"'),['net '+App]),ltDebug); RC:=RunAsAdmin('net',App,SW_HIDE); if RC=0 then AddLog(Format(_('Return code: %d'),[RC]),ltDebug) else AddLog(Format(_('There may be an error, return code: %d - %s'),[RC,SystemErrorMessage(RC)]),ltError); end else begin AddLog(_('FileZilla must be run as service!')); end; end; procedure tFileZilla.Stop; var App: string; RC: Cardinal; begin if isService then begin AddLog(Format(_('Stopping %s service...'),[cModuleName])); App:=Format('stop "%s"',[cServiceName]); Addlog(Format(_('Executing "%s"'),['net '+App]),ltDebug); RC:=RunAsAdmin('net',App,SW_HIDE); if RC=0 then AddLog(Format(_('Return code: %d'),[RC]),ltDebug) else AddLog(Format(_('There may be an error, return code: %d - %s'),[RC,SystemErrorMessage(RC)]),ltError); end else begin AddLog(_('FileZilla must be run as service!')); end; end; procedure tFileZilla.UpdateStatus; var p: Integer; ProcInfo: TProcInfo; s: string; ports: string; begin isRunning:=false; PIDList.Clear; for p:=0 to Processes.ProcessList.Count-1 do begin ProcInfo:=Processes.ProcessList[p]; if { (pos(BaseDir,ProcInfo.ExePath)=1) and } (pos('filezillaserver.exe',ProcInfo.Module)=1) then begin isRunning:=true; PIDList.Add(Pointer(ProcInfo.PID)); end; end; // Checking processes s:=''; for p:=0 to PIDList.Count-1 do begin if p=0 then s:=IntToStr(Integer(PIDList[p])) else s:=s+#13+IntToStr(Integer(PIDList[p])); end; if s<>OldPIDs then begin lPID.Caption:=s; OldPIDs:=s; end; // Checking netstats s:=''; for p:=0 to PIDList.Count-1 do begin ports:=NetStatTable.GetPorts4PID(Integer(PIDList[p])); if ports<>'' then begin if s='' then s:=ports else s:=s+', '+ports; end; end; if s<>OldPorts then begin lPort.Caption:=s; OldPorts:=s; end; if byte(isRunning)<>oldIsRunningByte then begin if oldIsRunningByte<>2 then begin if isRunning then s:=_('running') else s:=_('stopped'); AddLog(_('Status change detected:')+' '+s); end; oldIsRunningByte:=byte(isRunning); if isRunning then begin pStatus.Color:=cRunningColor; bStartStop.Caption:=_('Stop'); bAdmin.Enabled:=true; end else begin pStatus.Color:=cStoppedColor; bStartStop.Caption:=_('Start'); bAdmin.Enabled:=false; end; end; if AutoStart then begin AutoStart:=false; if isRunning then begin AddLog(_('Autostart active: modul is already running - aborted'),ltError); end else begin AddLog(_('Autostart active: starting...')); Start; end; end; end; end.
unit SkyboxUnit; {******************************************************************************} { } { SkyBoxes } { } { The initial developer of this Pascal code was : } { Ariel Jacob <ariel@global-rd.com> } { } { Portions created by Ariel Jacob are } { Copyright (C) 2000 - 2001 Ariel Jacob. } { } { } { Contributor(s) } { -------------- } { } { Obtained through: } { Joint Endeavour of Delphi Innovators ( Project JEDI ) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } { Description } { ----------- } { SkyBoxes (for now only one) } { } { } { Requires } { -------- } { SDL.dll on Windows platforms } { libSDL-1.1.so.0 on Linux platform } { OpenGL12 } { } { Programming Notes } { ----------------- } { } { } { } { } { Revision History } { ---------------- } { } { } { } {******************************************************************************} interface uses OpenGL12, Math3D, SDL_Image, SDL, GLInit; type TSkybox = Class protected BACK_ID, FRONT_ID, BOTTOM_ID, TOP_ID, TOPFX_ID, LEFT_ID, RIGHT_ID : TGLUInt; size : T3DVector; CamPos : P3DVector; addHight : single; U, V, USpeed, VSpeed : single; procedure SkyboxLoadTexture(var PTexture: TGLUInt; filename: String); Published procedure Draw; virtual; constructor Create(Name, ext: String; _size: T3DVector; _CamPos: P3DVector); procedure Free; property FloorLevel: single read addHight write addHight; end; implementation constructor TSkybox.Create(Name, ext: String; _size: T3DVector; _CamPos: P3DVector); begin inherited Create; // Load the Textures SkyboxLoadTexture( BACK_ID, Name+'BK'+ext ); SkyboxLoadTexture( FRONT_ID, Name+'FT'+ext ); SkyboxLoadTexture( BOTTOM_ID, Name+'DN'+ext ); SkyboxLoadTexture( TOP_ID, Name+'UP'+ext ); LoadGLTextures( TOPFX_ID, Name+'FX'+ext ); SkyboxLoadTexture( LEFT_ID, Name+'LF'+ext ); SkyboxLoadTexture( RIGHT_ID, Name+'RT'+ext ); // set the box size size:= _size; addHight:= size.Y / 2; // get the ^ to the CamPos value CamPos:= _CamPos; U:= 0; V:= 0; USpeed:= 0.00007; VSpeed:= -0.000055; end; procedure TSkybox.Free; begin glDeleteTextures(1, @BACK_ID); glDeleteTextures(1, @FRONT_ID); glDeleteTextures(1, @BOTTOM_ID); glDeleteTextures(1, @TOP_ID); glDeleteTextures(1, @TOPFX_ID); glDeleteTextures(1, @LEFT_ID); glDeleteTextures(1, @RIGHT_ID); inherited; end; procedure TSkybox.SkyboxLoadTexture(var PTexture: TGLUInt; filename: String); var TextureImage: PSDL_Surface; begin TextureImage := IMG_Load(PChar(filename)); if (TextureImage <> nil) then begin // Create Texture glGenTextures(1, @PTexture); glPixelStorei (GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, PTexture); { gluBuild2DMipmaps(GL_TEXTURE_2D, 3, TextureImage.w, TextureImage.h, GL_RGB, GL_UNSIGNED_BYTE, TextureImage.pixels); //} if TextureImage^.Format^.BytesPerPixel = 3 then glTexImage2D(GL_TEXTURE_2D, 0, TextureImage.Format.BytesPerPixel, TextureImage.w, TextureImage.h, 0, GL_RGB, GL_UNSIGNED_BYTE, TextureImage.pixels) else glTexImage2D(GL_TEXTURE_2D, 0, TextureImage.Format.BytesPerPixel, TextureImage.w, TextureImage.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, TextureImage.pixels); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); end; if TextureImage <> nil then SDL_FreeSurface(TextureImage); end; // (0,1) (1,1) // ________ // | | // | | // | | // -------- // (0,0) (1,0) procedure TSkybox.Draw; const I = 1; def = 0.8; test = 0; var x,y,z :single; begin glColor4f(1, 1, 1, 1); x:= CamPos^.X; y:= CamPos^.Y; z:= CamPos^.Z; x:= x - size.X / 2; y:= y - addHight; z:= z - size.Z / 2; glBindTexture(GL_TEXTURE_2D, BACK_ID); glBegin(GL_QUADS); glTexCoord2f(1.0, 1.0); glVertex3f(x, y, z); glTexCoord2f(1.0, 0.0); glVertex3f(x, y + size.Y, z); glTexCoord2f(0.0, 0.0); glVertex3f(x + size.X, y + size.Y, z); glTexCoord2f(0.0, 1.0); glVertex3f(x + size.X, y, z); glEnd(); glBindTexture(GL_TEXTURE_2D, FRONT_ID); glBegin(GL_QUADS); glTexCoord2f(0.0, 1.0); glVertex3f(x, y, z + size.Z); glTexCoord2f(0.0, 0.0); glVertex3f(x, y + size.Y, z + size.Z); glTexCoord2f(1.0, 0.0); glVertex3f(x + size.X, y + size.Y, z + size.Z); glTexCoord2f(1.0, 1.0); glVertex3f(x + size.X, y, z + size.Z); glEnd(); glBindTexture(GL_TEXTURE_2D, BOTTOM_ID); glBegin(GL_QUADS); glTexCoord2f(0.0, 1.0); glVertex3f(x, y, z); glTexCoord2f(0.0, 0.0); glVertex3f(x, y, z + size.Z); glTexCoord2f(1.0, 0.0); glVertex3f(x + size.X, y, z + size.Z); glTexCoord2f(1.0, 1.0); glVertex3f(x + size.X, y, z); glEnd(); glBindTexture(GL_TEXTURE_2D, LEFT_ID); glBegin(GL_QUADS); glTexCoord2f(0.0, 1.0); glVertex3f(x, y, z); glTexCoord2f(1.0, 1.0); glVertex3f(x, y, z + size.Z); glTexCoord2f(1.0, 0.0); glVertex3f(x, y + size.Y, z + size.Z); glTexCoord2f(0.0, 0.0); glVertex3f(x, y + size.Y, z); glEnd(); glBindTexture(GL_TEXTURE_2D, RIGHT_ID); glBegin(GL_QUADS); glTexCoord2f(1.0, 1.0); glVertex3f(x + size.X, y, z); glTexCoord2f(0.0, 1.0); glVertex3f(x + size.X, y, z + size.Z); glTexCoord2f(0.0, 0.0); glVertex3f(x + size.X, y + size.Y, z + size.Z); glTexCoord2f(1.0, 0.0); glVertex3f(x + size.X, y + size.Y, z); glEnd(); glBindTexture(GL_TEXTURE_2D, TOP_ID); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(x, y + size.Y, z); glTexCoord2f(0.0, 1.0); glVertex3f(x, y + size.Y, z + size.Z); glTexCoord2f(1.0, 1.0); glVertex3f(x + size.X, y + size.Y, z + size.Z); glTexCoord2f(1.0, 0.0); glVertex3f(x + size.X, y + size.Y, z); glEnd(); //{ // TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP glBindTexture(GL_TEXTURE_2D, TOPFX_ID); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); // glBlendFunc(GL_BLEND_DST, GL_ONE); glEnable( GL_BLEND ); glBegin(GL_QUADS); glTexCoord2f(0.0 + U/I, 0.0 + V/I); glVertex3f(x, y + size.Y - (size.Y / 3)+def, z); glTexCoord2f(0.0 + U/I, 1.0 + V/I); glVertex3f(x, y + size.Y - (size.Y / 3)+def, z + size.Z); glTexCoord2f(1.0 + U/I, 1.0 + V/I); glVertex3f(x + size.X, y + size.Y - (size.Y / 3)+def, z + size.Z); glTexCoord2f(1.0 + U/I, 0.0 + V/I); glVertex3f(x + size.X, y + size.Y - (size.Y / 3)+def, z); glEnd(); glColor4f(0.4, 0.4, 0.4, 1); glBlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR); glBegin(GL_QUADS); glTexCoord2f(0.0 + U + test, 0.0 + V + test); glVertex3f(x, y + size.Y - (size.Y / 3), z); glTexCoord2f(0.0 + U + test, 1.0 + V + test); glVertex3f(x, y + size.Y - (size.Y / 3), z + size.Z); glTexCoord2f(1.0 + U + test, 1.0 + V + test); glVertex3f(x + size.X, y + size.Y - (size.Y / 3), z + size.Z); glTexCoord2f(1.0 + U + test, 0.0 + V + test); glVertex3f(x + size.X, y + size.Y - (size.Y / 3), z); glEnd(); glDisable( GL_BLEND ); glColor4f(1, 1, 1, 1); // TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP TEMP //} U:= U + USpeed; V:= V + VSpeed; end; end.
UNIT ForBuildIndex; // INTERFACE CONST Letters = ['A' .. 'Z', 'a' .. 'z', 'А' .. 'п', 'р' .. 'я']; max = 30; TYPE LittleString = STRING[31]; Keys = RECORD S: LittleString; I: INTEGER END; Pointers = ^Node; Node = RECORD Key: Keys; Next: Pointers END; PROCEDURE ReadWord(VAR InpF: TEXT; VAR Strg: LittleString; VAR Overfloww: BOOLEAN); PROCEDURE SearchAndInsert(VAR Strg: LittleString; VAR Overfloww, Firstt: BOOLEAN); PROCEDURE PrintWords(VAR OutpF: TEXT; Overfloww: BOOLEAN); // IMPLEMENTATION VAR FirstPtrr, NewPtrr: Pointers; PROCEDURE ReadWord(VAR InpF: TEXT; VAR Strg: LittleString; VAR Overfloww: BOOLEAN); VAR Ch: CHAR; BEGIN READ(InpF, Ch); WHILE (Overfloww = FALSE) AND (Ch IN Letters) DO BEGIN Strg := Strg + Ch; READ(InpF, Ch); IF (LENGTH(Strg) > max) THEN Overfloww := TRUE END; END; PROCEDURE Inserting(Equall: BOOLEAN; VAR NewPtrr, Currr, Prevv, FirstPtrr: Pointers; VAR Strg: LittleString); BEGIN IF Equall = FALSE THEN BEGIN NEW(NewPtrr); NewPtrr^.Key.I := 1; NewPtrr^.Key.S := Strg; NewPtrr^.Next := Currr; IF Prevv = NIL THEN FirstPtrr := NewPtrr ELSE Prevv^.Next := NewPtrr END END; PROCEDURE SearchAndInsert(VAR Strg: LittleString; VAR Overfloww, Firstt: BOOLEAN); VAR Foundd, Equall: BOOLEAN; Prevv, Currr, FirstPtrrr, NewPtrrr: Pointers; BEGIN IF (Strg <> '') AND (Overfloww = FALSE) THEN BEGIN IF Firstt = FALSE THEN BEGIN FirstPtrrr := NIL; Firstt := TRUE END; Prevv := NIL; Currr := FirstPtrr; Foundd := FALSE; Equall := FALSE; WHILE (Currr <> NIL) AND NOT Foundd DO IF Strg > Currr^.Key.S THEN BEGIN Prevv := Currr; Currr := Currr^.Next END ELSE IF Strg = Currr^.Key.S THEN BEGIN INC(Currr^.Key.I); Equall := TRUE; Foundd := TRUE END ELSE Foundd := TRUE; Inserting(Equall, NewPtrrr, Currr, Prevv, FirstPtrrr, Strg); END; FirstPtrr := FirstPtrrr; NewPtrr := NewPtrrr; END; PROCEDURE PrintWords(VAR OutpF: TEXT; Overfloww: BOOLEAN); BEGIN IF Overfloww = FALSE THEN BEGIN NewPtrr := FirstPtrr; WHILE NewPtrr <> NIL DO BEGIN WRITELN(OutpF, NewPtrr^.Key.S, ' - ', NewPtrr^.Key.I); NewPtrr := NewPtrr^.Next END END ELSE IF (Overfloww = TRUE) THEN WRITELN(OutpF, 'ERROR. Word has more 30 chars.'); END; BEGIN {ForBuildIndex} // здесь можно инициализировать все переменные для модуля. END. {ForBuildIndex}
{ Routines that append numerical values to the end of a existing string. } module string_append_num; define string_append_bin; define string_append_eng; define string_append_fp_fixed; define string_append_fp_free; define string_append_hex; define string_append_ints; define string_append_intu; %include 'string2.ins.pas'; { ******************************************************************************** * * Subroutine STRING_APPEND_BIN (STR, II, NB) * * Append the binary representation of the integer II to the string STR. NB is * the number of bits. This is both the number of characters that will be * appended and the number of low bits of II that are relevant. The input * value is in the low NB bits of II. } procedure string_append_bin ( {append binary integer to string} in out str: univ string_var_arg_t; {string to append to} in ii: sys_int_machine_t; {integer value to append in low NB bits} in nb: sys_int_machine_t); {number of bits, higher bits in II ignored} val_param; var ival: sys_int_machine_t; {input value with unused bits set to 0} tk: string_var32_t; {the string to append} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} ival := ii & ~lshft(~0, nb); {make input value with unused bits masked off} string_f_int_max_base ( {make the binary string} tk, {output string} ival, {input value} 2, {number base} nb, {fixed field width} [ string_fi_leadz_k, {write leading zeros} string_fi_unsig_k], {consider the input value to be unsigned} stat); if not sys_error(stat) then begin string_append (str, tk); end; end; { ******************************************************************************** * * Subroutine STRING_APPEND_ENG (STR, FP, MIN_SIG) * * Append the value of FP in engineering notation to STR. MIN_SIG is the * minimum required number of significant digits. The exponent of 1000 will be * chosen so that 1-3 digits are left of the point. For exponents with a * common one-character abbreviation (like "k" for 1000), the number will be * written, followed by a space, followed by the multiple of 1000 abbreviation. * For exponents of 1000 outside the named range, the number will be written, * followed by "e", followed by the exponent of 1000 multiplier, followed by a * space. } procedure string_append_eng ( {append number in engineering notation} in out str: univ string_var_arg_t; {string to append to} in fp: sys_fp_max_t; {input floating point number} in min_sig: sys_int_machine_t); {min required significant digits} val_param; var tk: string_var32_t; {number string} un: string_var32_t; {exponent of 1000 name string} begin tk.max := size_char(tk.str); {init local var string} string_f_fp_eng ( {make engineering notation strings} tk, {returned number string} fp, {the value to convert} min_sig, {min required significan digits} un); {power of 1000 units prefix} string_append (str, tk); {append the raw number} if un.len <= 0 then begin {no power of 1000 name} string_append1 (str, ' '); end else begin {have named power of 1000} string_append (str, un); end ; end; { ******************************************************************************** * * Subroutine STRING_APPEND_FP_FIXED (STR, FP, FW, DIG_RIGHT) * * Append the floating point string representation of the FP to the string STR. * FW is the fixed number of characters to append. The floating point string * will be padded with leading blanks to fill the field. The special FW value * of 0 indicates to not add any leading blanks. DIG_RIGHT is the fixed number * of digits right of the decimal point. } procedure string_append_fp_fixed ( {append fixed-format floating point to string} in out str: univ string_var_arg_t; {string to append to} in fp: sys_fp_max_t; {input floating point number} in fw: sys_int_machine_t; {total field width, 0 for min left of point} in dig_right: sys_int_machine_t); {digits to right of decimal point} val_param; var tk: string_var32_t; {the string to append} ii, jj: sys_int_machine_t; {scratch integers and loop counters} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} string_f_fp ( {make string from floating point value} tk, {output string} fp, {input value} fw, {fixed field width for number} 0, {no fixed field width for exponent} 0, {min required significant digits} 12, {max digits allowed left of point} dig_right, dig_right, {min and max digits right of point} [string_ffp_group_k], {write digit group characters} stat); if {"star out" the number on error} sys_error(stat) or {hard error converting to string ?} ((fw > 0) and (tk.len > fw)) {field overflow ?} then begin for ii := 1 to fw do begin string_append1 (str, '*'); end; return; end; if fw > 0 then begin {fixed field width ?} jj := fw - tk.len; {number of leading blanks to add} for ii := 1 to jj do begin {add the leading blanks} string_append1 (str, ' '); end; end; string_append (str, tk); {add the number string} end; { ******************************************************************************** * * Subroutine STRING_APPEND_FP_FIXED (STR, FP, MIN_SIG) * * Append the floating point string representation of the FP to the string STR. * MIN_SIG is the minimum required number of significant digits in the string * representation of FP. } procedure string_append_fp_free ( {append free-format floating point to string} in out str: univ string_var_arg_t; {string to append to} in fp: sys_fp_max_t; {input floating point number} in min_sig: sys_int_machine_t); {min required significant digits} val_param; var tk: string_var32_t; {the string to append} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} string_f_fp ( {make string from floating point value} tk, {output string} fp, {input value} 0, {no fixed field width for number} 0, {no fixed field width for exponent} min_sig, {min required significant digits} min_sig + 6, {max digits allowed left of point} 0, 6, {min and max digits right of point} [ string_ffp_exp_eng_k, {exponent always multiple of 3} string_ffp_group_k], {write digit group characters} stat); string_append (str, tk); end; { ******************************************************************************** * * Subroutine STRING_APPEND_HEX (STR, II, NB) * * Append the hexadecimal (base 16) representation of the integer in the low NB * bits of II to the string STR. The appended string will (NB + 3) div 4 * characters long. } procedure string_append_hex ( {append hexadecimal integer to string} in out str: univ string_var_arg_t; {string to append to} in ii: sys_int_machine_t; {integer value to append in low NB bits} in nb: sys_int_machine_t); {number of bits, higher bits in II ignored} val_param; var ival: sys_int_machine_t; {input value with unused bits set to 0} tk: string_var32_t; {the string to append} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} ival := ii & ~lshft(~0, nb); {make input value with unused bits masked off} string_f_int_max_base ( {make the binary string} tk, {output string} ival, {input value} 16, {number base} (nb + 3) div 4, {fixed field width} [ string_fi_leadz_k, {write leading zeros} string_fi_unsig_k], {consider the input value to be unsigned} stat); if not sys_error(stat) then begin string_append (str, tk); end; end; { ******************************************************************************** * * Subroutine STRING_APPEND_INTS (STR, II, FW) * * Append the decimal integer representation of the signed value II to the * string STR. FW is the fixed field width to use. Leading blanks will be * added to fill the field as necessary. The special FW value of 0 causes as * many digits as necessary but without leading zeros or blanks to be appended * to STR. } procedure string_append_ints ( {append signed decimal integer to string} in out str: univ string_var_arg_t; {string to append to} in ii: sys_int_machine_t; {integer value to append} in fw: sys_int_machine_t); {fixed field width, or 0 for min required} val_param; var tk: string_var32_t; {the string to append} jj: sys_int_machine_t; {scratch integer and loop counter} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} string_f_int_max_base ( {make the binary string} tk, {output string} ii, {input value} 10, {number base} fw, {fixed field width, 0 for free form} [], {no additional modifiers} stat); if {"star out" the number on error} sys_error(stat) and {hard error converting to string ?} (fw > 0) {need to fill fixed field ?} then begin for jj := 1 to fw do begin string_append1 (str, '*'); end; return; end; if not sys_error(stat) then begin string_append (str, tk); end; end; { ******************************************************************************** * * Subroutine STRING_APPEND_INTS (STR, II, FW) * * Append the decimal integer representation of the unsigned value II to the * string STR. FW is the fixed field width to use. Leading blanks will be * added to fill the field as necessary. The special FW value of 0 causes as * many digits as necessary but without leading zeros or blanks to be appended * to STR. } procedure string_append_intu ( {append unsigned decimal integer to string} in out str: univ string_var_arg_t; {string to append to} in ii: sys_int_machine_t; {integer value to append} in fw: sys_int_machine_t); {fixed field width, or 0 for min required} val_param; var tk: string_var32_t; {the string to append} jj: sys_int_machine_t; {scratch integer and loop counter} stat: sys_err_t; {completion status} begin tk.max := size_char(tk.str); {init local var string} string_f_int_max_base ( {make the binary string} tk, {output string} ii, {input value} 10, {number base} fw, {fixed field width, 0 for free form} [string_fi_unsig_k], {the input number is unsigned} stat); if {"star out" the number on error} sys_error(stat) and {hard error converting to string ?} (fw > 0) {need to fill fixed field ?} then begin for jj := 1 to fw do begin string_append1 (str, '*'); end; return; end; if not sys_error(stat) then begin string_append (str, tk); end; end;
unit uProtocolEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, 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; type TfrmProtEdit = class(TfrmForm) btnOk: TButton; btnCancel: TButton; lePort: TLabeledEdit; leName: TLabeledEdit; Image1: TImage; leScheme: TLabeledEdit; procedure FormShow(Sender: TObject); private FXMLNode: IXMLNode; procedure FillControls; public procedure ApplyXML; property XMLNode: IXMLNode read FXMLNode write FXMLNode; end; var frmProtEdit: TfrmProtEdit; implementation {$R *.dfm} uses uCommonTools, uClasses, uXMLTools; { TfrmSoftEdit } procedure TfrmProtEdit.ApplyXML; begin xmlSetItemString(FXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE, icsB64Encode(leName.Text)); xmlSetItemString(FXMLNode.ChildNodes[ND_PORT], ND_PARAM_VALUE, lePort.Text); xmlSetItemString(FXMLNode.ChildNodes[ND_SCHEME], ND_PARAM_VALUE, leScheme.Text); end; procedure TfrmProtEdit.FillControls; begin leName.Text := icsB64Decode(xmlGetItemString(FXMLNode.ChildNodes[ND_NAME], ND_PARAM_VALUE)); lePort.Text := xmlGetItemString(FXMLNode.ChildNodes[ND_PORT], ND_PARAM_VALUE); leScheme.Text := xmlGetItemString(FXMLNode.ChildNodes[ND_SCHEME], ND_PARAM_VALUE); end; procedure TfrmProtEdit.FormShow(Sender: TObject); begin inherited; FillControls; end; end.
unit LuaStream; {$mode delphi} interface uses Classes, SysUtils, lua, lauxlib, lualib, math; procedure stream_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); implementation uses LuaClass, LuaHandler, LuaObject{$ifdef darwin},mactypes{$endif}; function stream_getSize(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); lua_pushinteger(L, stream.Size); result:=1; end; function stream_setSize(L: PLua_State): integer; cdecl; var stream: Tstream; oldsize: integer; newsize: integer; diff: integer; begin result:=0; stream:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin newsize:=lua_tointeger(L,1); if stream is TMemoryStream then begin oldsize:=stream.size; stream.size:=newsize; //zero the new bytes FillByte(pointer(ptruint(tmemorystream(stream).Memory)+oldsize)^, newsize-oldsize,0); end else stream.Size:=newsize; end; end; function stream_getPosition(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); lua_pushinteger(L, stream.Position); result:=1; end; function stream_setPosition(L: PLua_State): integer; cdecl; var stream: Tstream; begin result:=0; stream:=luaclass_getClassObject(L); if lua_gettop(L)=1 then stream.Position:=lua_tointeger(L,-1); end; function stream_copyFrom(L: PLua_State): integer; cdecl; var stream: Tstream; s: tstream; count: integer; begin result:=0; stream:=luaclass_getClassObject(L); if lua_gettop(L)=2 then begin s:=lua_ToCEUserData(L, 1); count:=lua_tointeger(L, 2); stream.CopyFrom(s, count); end; end; function stream_read(L: PLua_State): integer; cdecl; var stream: Tstream; count: integer; buf: PByteArray; table: integer; i: integer; begin result:=0; stream:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin if lua_isnumber(L, 1) then begin count:=lua_tointeger(L, 1); getmem(buf, count); try stream.Read(buf^, count); //everything ok, create a table lua_newtable(L); //pobably 2 table:=lua_gettop(L); for i:=0 to count-1 do begin lua_pushinteger(L, i+1); lua_pushinteger(L, buf[i]); lua_settable(L, table); //set table[i+1]=buf[i] end; result:=1; except end; FreeMemAndNil(buf); end; end; end; function stream_readByte(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); try lua_pushinteger(L,stream.ReadByte); except lua_pushstring(L,'stream error'); lua_error(L); end; result:=1; end; function stream_writeByte(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); try stream.WriteByte(lua_tointeger(L,1)); finally end; result:=0; end; function stream_readWord(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); try lua_pushinteger(L,stream.ReadWord); except lua_pushstring(L,'stream error'); lua_error(L); end; result:=1; end; function stream_writeWord(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); stream.WriteWord(lua_tointeger(L,1)); result:=0; end; function stream_readDword(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); try lua_pushinteger(L,stream.ReadDword); except lua_pushstring(L,'stream error'); lua_error(L); end; result:=1; end; function stream_writeDword(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); stream.WriteDword(lua_tointeger(L,1)); result:=0; end; function stream_readQword(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); try lua_pushinteger(L,stream.ReadQword); except lua_pushstring(L,'stream error'); lua_error(L); end; result:=1; end; function stream_writeQword(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); stream.WriteQword(lua_tointeger(L,1)); result:=0; end; function stream_readFloat(L: PLua_State): integer; cdecl; var stream: Tstream; f: single; begin stream:=luaclass_getClassObject(L); try stream.Read(f,sizeof(f)); except lua_pushstring(L,'stream error'); lua_error(L); end; lua_pushnumber(L,f); result:=1; end; function stream_writeFloat(L: PLua_State): integer; cdecl; var stream: Tstream; f: single; begin stream:=luaclass_getClassObject(L); f:=lua_tonumber(L,1); stream.Write(f, sizeof(f)); result:=0; end; function stream_readDouble(L: PLua_State): integer; cdecl; var stream: Tstream; d: double; begin stream:=luaclass_getClassObject(L); try stream.Read(d,sizeof(d)); except lua_pushstring(L,'stream error'); lua_error(L); end; lua_pushnumber(L,d); result:=1; end; function stream_writeDouble(L: PLua_State): integer; cdecl; var stream: Tstream; d: double; begin stream:=luaclass_getClassObject(L); d:=lua_tonumber(L,1); stream.Write(d, sizeof(d)); result:=0; end; function stream_readString(L: PLua_State): integer; cdecl; var stream: Tstream; size: integer; s: pchar; begin stream:=luaclass_getClassObject(L); result:=0; if lua_gettop(L)>=1 then begin size:=lua_tointeger(L,1); getmem(s,size+1); stream.ReadBuffer(s^,size); s[size]:=#0; lua_pushstring(L,s); result:=1; end else begin lua_pushnil(L); lua_pushstring(L,rsIncorrectNumberOfParameters); end; end; function stream_writeString(L: PLua_State): integer; cdecl; var stream: Tstream; s: string; includeterminator: boolean; begin stream:=luaclass_getClassObject(L); result:=0; if lua_gettop(L)>=1 then begin s:=Lua_ToString(L,1); if lua_gettop(L)>=2 then includeterminator:=lua_toboolean(L,2) else includeterminator:=false; stream.WriteBuffer(s[1],length(s)); if includeterminator then stream.WriteByte(0); end else begin lua_pushnil(L); lua_pushstring(L,rsIncorrectNumberOfParameters); end; end; function stream_readAnsiString(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); lua_pushstring(L,stream.ReadAnsiString); result:=1; end; function stream_writeAnsiString(L: PLua_State): integer; cdecl; var stream: Tstream; begin stream:=luaclass_getClassObject(L); stream.WriteAnsiString(Lua_ToString(L,1)); result:=0; end; function stream_write(L: PLua_State): integer; cdecl; var stream: Tstream; count: integer; buf: PByteArray; i: integer; begin result:=0; stream:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin //table index is at 1 if lua_istable(L, 1) then begin if lua_gettop(L)>=2 then {$if FPC_FULLVERSION < 030200} count:=min(int64(lua_objlen(L, 1)), int64(lua_tointeger(L, 2))) {$else} count:=min(lua_objlen(L, 1), lua_tointeger(L, 2)) //prevent the length from exeeding the table {$endif} else count:=lua_objlen(L, 1); getmem(buf, count); try for i:=0 to count-1 do begin lua_pushinteger(L, i+1); lua_gettable(L, 1); //get table[i+1] buf[i]:=lua_tointeger(L, -1); lua_pop(L, 1); end; stream.Write(buf^, count); except end; FreeMemAndNil(buf); end; end; end; procedure stream_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'copyFrom', stream_copyFrom); luaclass_addClassFunctionToTable(L, metatable, userdata, 'read', stream_read); luaclass_addClassFunctionToTable(L, metatable, userdata, 'write', stream_write); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readByte', stream_readByte); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeByte', stream_writeByte); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readWord', stream_readWord); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeWord', stream_writeWord); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readDword', stream_readDword); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeDword', stream_writeDword); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readQword', stream_readQword); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeQword', stream_writeQword); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readFloat', stream_readFloat); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeFloat', stream_writeFloat); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readDouble', stream_readDouble); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeDouble', stream_writeDouble); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readString', stream_readString); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeString', stream_writeString); luaclass_addClassFunctionToTable(L, metatable, userdata, 'readAnsiString', stream_readAnsiString); luaclass_addClassFunctionToTable(L, metatable, userdata, 'writeAnsiString', stream_writeAnsiString); luaclass_addPropertyToTable(L, metatable, userdata, 'Size', stream_getSize, stream_setSize); luaclass_addPropertyToTable(L, metatable, userdata, 'Position', stream_getPosition, stream_setPosition); end; function memorystream_getMemory(L: PLua_State): integer; cdecl; var ms: Tmemorystream; begin ms:=luaclass_getClassObject(L); lua_pushinteger(L, ptruint(ms.Memory)); result:=1; end; function memorystream_loadFromFile(L: PLua_State): integer; cdecl; var ms: Tmemorystream; begin ms:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then ms.LoadFromFile(Lua_ToString(L,1)); result:=0; end; function memorystream_saveToFile(L: PLua_State): integer; cdecl; var ms: Tmemorystream; begin ms:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then ms.SaveToFile(Lua_ToString(L,1)); result:=0; end; function memorystream_loadFromFileNoError(L: PLua_State): integer; cdecl; var ms: Tmemorystream; r: boolean=false; begin result:=0; ms:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then try ms.LoadFromFile(Lua_ToString(L,1)); lua_pushboolean(L,true); result:=1; except on e:exception do begin lua_pushboolean(L,false); lua_pushstring(L,e.message); result:=2; end; end; end; function memorystream_saveToFileNoError(L: PLua_State): integer; cdecl; var ms: Tmemorystream; begin result:=0; ms:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then try ms.SaveToFile(Lua_ToString(L,1)); lua_pushboolean(L,true); result:=1; except on e:exception do begin lua_pushboolean(L,false); lua_pushstring(L,e.message); result:=2; end; end; end; function memorystream_clear(L: PLua_State): integer; cdecl; begin tmemorystream(luaclass_getClassObject(L)).Clear; result:=0; end; procedure memorystream_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin stream_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'loadFromFile', memorystream_loadFromFile); luaclass_addClassFunctionToTable(L, metatable, userdata, 'saveToFile', memorystream_saveToFile); luaclass_addClassFunctionToTable(L, metatable, userdata, 'loadFromFileNoError', memorystream_loadFromFileNoError); luaclass_addClassFunctionToTable(L, metatable, userdata, 'saveToFileNoError', memorystream_saveToFileNoError); luaclass_addClassFunctionToTable(L, metatable, userdata, 'clear', memorystream_clear); luaclass_addPropertyToTable(L, metatable, userdata, 'Memory', memorystream_getMemory, nil); end; function stringstream_getDataString(L: PLua_State): integer; cdecl; var ss: TStringStream; ms: TMemoryStream; oldpos: integer; begin ss:=luaclass_getClassObject(L); ms:=TMemoryStream.create; oldpos:=ss.Position; ss.position:=0; ms.LoadFromStream(ss); lua_pushlstring(L, ms.Memory, ms.Size); result:=1; ss.position:=oldpos; ms.free; end; procedure stringstream_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin memorystream_addMetaData(L, metatable, userdata); luaclass_addPropertyToTable(L, metatable, userdata, 'DataString', stringstream_getDataString, nil); end; initialization luaclass_register(TStream, stream_addMetaData); luaclass_register(TMemoryStream, memorystream_addMetaData); luaclass_register(TStringStream, stringstream_addMetaData); end.
unit serverwinshoehostname; interface //////////////////////////////////////////////////////////////////////////////// // Author: Ozz Nixon (RFC 953) // .. // 5.13.99 Final Version // 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers) //////////////////////////////////////////////////////////////////////////////// uses Classes, ServerWinshoe; Const KnownCommands:Array [1..9] of string= ( 'HNAME', 'HADDR', 'ALL', 'HELP', 'VERSION', 'ALL-OLD', 'DOMAINS', 'ALL-DOM', 'ALL-INGWAY' ); Type TGetEvent = procedure(Thread: TWinshoeServerThread) of object; TOneParmEvent = procedure(Thread: TWinshoeServerThread;Parm:String) of object; TWinshoeHOSTNAMEListener = class(TWinshoeListener) private FOnCommandHNAME:TOneParmEvent; FOnCommandHADDR:TOneParmEvent; FOnCommandALL:TGetEvent; FOnCommandHELP:TGetEvent; FOnCommandVERSION:TGetEvent; FOnCommandALLOLD:TGetEvent; FOnCommandDOMAINS:TGetEvent; FOnCommandALLDOM:TGetEvent; FOnCommandALLINGWAY:TGetEvent; protected function DoExecute(Thread: TWinshoeServerThread): boolean; override; public constructor Create(AOwner: TComponent); override; published property OnCommandHNAME: TOneParmEvent read fOnCommandHNAME write fOnCommandHNAME; property OnCommandHADDR: TOneParmEvent read fOnCommandHADDR write fOnCommandHADDR; property OnCommandALL: TGetEvent read fOnCommandALL write fOnCommandALL; property OnCommandHELP: TGetEvent read fOnCommandHELP write fOnCommandHELP; property OnCommandVERSION: TGetEvent read fOnCommandVERSION write fOnCommandVERSION; property OnCommandALLOLD: TGetEvent read fOnCommandALLOLD write fOnCommandALLOLD; property OnCommandDOMAINS: TGetEvent read fOnCommandDOMAINS write fOnCommandDOMAINS; property OnCommandALLDOM: TGetEvent read fOnCommandALLDOM write fOnCommandALLDOM; property OnCommandALLINGWAY: TGetEvent read fOnCommandALLINGWAY write fOnCommandALLINGWAY; end; procedure Register; implementation uses GlobalWinshoe, SysUtils, StringsWinshoe, Winshoes; procedure Register; begin RegisterComponents('Winshoes Servers', [TWinshoeHOSTNAMEListener]); end; constructor TWinshoeHOSTNAMEListener.Create(AOwner: TComponent); begin inherited Create(AOwner); Port := 101; end; function TWinshoeHOSTNAMEListener.DoExecute(Thread: TWinshoeServerThread): boolean; Var S,sCmd:String; begin result := inherited DoExecute(Thread); if result then exit; with Thread.Connection do begin While Connected do begin S:=Readln; sCmd := UpperCase(Fetch(s,CHAR32)); Case Succ(PosInStrArray(Uppercase(sCmd),KnownCommands)) of 1:{hname} if assigned(OnCommandHNAME) then OnCommandHNAME(Thread,S); 2:{haddr} if assigned(OnCommandHADDR) then OnCommandHADDR(Thread,S); 3:{all} if assigned(OnCommandALL) then OnCommandALL(Thread); 4:{help} if assigned(OnCommandHELP) then OnCommandHELP(Thread); 5:{version} if assigned(OnCommandVERSION) then OnCommandVERSION(Thread); 6:{all-old} if assigned(OnCommandALLOLD) then OnCommandALLOLD(Thread); 7:{domains} if assigned(OnCommandDOMAINS) then OnCommandDOMAINS(Thread); 8:{all-dom} if assigned(OnCommandALLDOM) then OnCommandALLDOM(Thread); 9:{all-ingway} if assigned(OnCommandALLINGWAY) then OnCommandALLINGWAY(Thread); End; {case} End; Disconnect; end; {with} end; {doExecute} end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,Registry, StdCtrls, ExtCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Button2: TButton; OpenDialog1: TOpenDialog; Button3: TButton; Label1: TLabel; Label2: TLabel; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Timer1Timer(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} {$R UAC.res}//请求UAC权限声明 procedure TForm1.Button1Click(Sender: TObject); var Reg:TRegistry;//首先定义一个TRegistry类型的变量Reg begin if Edit1.Text <> '' then begin Reg:=TRegistry.Create;//创建一个新键 Reg.RootKey:=HKEY_LOCAL_MACHINE;//将根键设置为HKEY_LOCAL_MACHINE Reg.OpenKey('SOFTWARE\Microsoft\windows\CurrentVersion\Run',true);//打开一个键 Reg.WriteString('FEIQ',PChar('"' + Edit1.Text + '"' +' ' +'1'));//在Reg这个键中写入数据名称和数据数值 Reg.CloseKey;//关闭键 end else MessageBox(Handle,'还未选择飞秋路径!','提示',MB_OK + MB_ICONASTERISK); end; procedure TForm1.Button2Click(Sender: TObject); begin if opendialog1.Execute then edit1.text:=opendialog1.FileName ; end; procedure TForm1.Button3Click(Sender: TObject); var Reg:TRegistry;//首先定义一个TRegistry类型的变量Reg begin Reg:=TRegistry.Create;//创建一个新键 Reg.RootKey:=HKEY_LOCAL_MACHINE;//将根键设置为HKEY_LOCAL_MACHINE Reg.OpenKey('SOFTWARE\Microsoft\windows\CurrentVersion\Run',true);//打开一个键 Reg.DeleteValue('FEIQ');//删除注册表键值 Reg.CloseKey;//关闭键 MessageBox(Handle,'已经取消飞秋开机启动!','提示',MB_OK + MB_ICONASTERISK); end; procedure TForm1.Button4Click(Sender: TObject); begin // AnimateWindow(Self.Handle, 500, aw_center or AW_Hide);//500为关闭窗口时间,单位是ms Application.Terminate; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin // AnimateWindow(Self.Handle, 500, aw_center or AW_Hide);//500为关闭窗口时间,单位是ms end; procedure TForm1.Timer1Timer(Sender: TObject);//添加Timer组件 begin if Self.AlphaBlendValue <= 250 then Self.AlphaBlendValue := Self.AlphaBlendValue + 5; end; procedure TForm1.FormCreate(Sender: TObject); begin //Self.AlphaBlend := True; //Self.AlphaBlendValue := 0; end; end.
unit LuaInternet; {$mode delphi} interface uses Classes, SysUtils {$ifdef windows}, wininet {$else} , fphttpclient,opensslsockets,openssl, StringHashList {$endif} ; {$ifndef standalone} procedure initializeLuaInternet; {$endif} type TWinInternet=class private {$ifdef windows} internet: HINTERNET; fheader: string; {$else} fname: string; internet: TFPHTTPClient; procedure setHeader(s: string); function getHeader: string; procedure recreateFPHTTPClient; procedure storeCookies(urlstring: string); procedure loadCookies(urlstring: string); {$endif} public function getURL(urlstring: string; results: tstream): boolean; function postURL(urlstring: string; urlencodedpostdata: string; results: tstream): boolean; constructor create(name: string); destructor destroy; override; published {$ifdef windows} property Header: string read fheader write fheader; {$else} property Header: string read getHeader write setHeader; {$endif} end; implementation uses {$ifdef darwin}macport, registry,{$endif}{$ifndef standalone}MainUnit2, lua, LuaClass, LuaObject, LuaHandler,{$endif} URIParser, dialogs; {$ifndef windows} var cookies: tstringhashlist; {$endif} {$ifndef windows} procedure TWinInternet.setHeader(s: string); begin internet.RequestHeaders.Text:=s; end; function TWinInternet.getHeader: string; begin result:=internet.RequestHeaders.Text; end; procedure TWinInternet.storeCookies(urlstring: string); var uri: TURI; c: tstringlist; i,j: integer; s: string; cname,cname2: string; cvalue,cvalue2: string; found: boolean; p: integer; begin if internet.Cookies.Text='' then exit; //no new cookies uri:=ParseURI(urlstring); c:=cookies[uri.Host]; if c=nil then begin c:=tstringlist.create; cookies[uri.Host]:=c; end; //update the cookies with the new values for i:=0 to internet.ResponseHeaders.count-1 do begin s:=internet.ResponseHeaders[i]; if (LowerCase(Copy(S,1,10))='set-cookie') then begin Delete(s,1,Pos(':',S)); cname:=trim(copy(s,1,pos('=',s)-1)); cvalue:=trim(copy(s,pos('=',s)+1)); cvalue:=copy(cvalue,1,pos(';',cvalue)-1); found:=false; for j:=0 to c.Count-1 do begin s:=c[j]; cname2:=trim(copy(s,1,pos('=',s)-1)); if cname=cname2 then begin c[j]:=cname+'='+cvalue; //update found:=true; break; end; end; if not found then c.add(cname+'='+cvalue); end; end; end; procedure TWinInternet.loadCookies(urlstring: string); var uri: TURI; c: tstringlist; begin uri:=ParseURI(urlstring); c:=cookies[uri.Host]; if c<>nil then begin internet.Cookies.Text:=c.text; end; end; function TWinInternet.postURL(urlstring: string; urlencodedpostdata: string; results: tstream): boolean; begin result:=false; try recreateFPHTTPClient; loadCookies(urlstring); internet.FormPost(urlstring,urlencodedpostdata,results); storeCookies(urlstring); result:=true; except result:=false; end; end; function TWinInternet.getURL(urlstring: string; results: tstream): boolean; begin result:=false; try loadCookies(urlstring); internet.Get(urlstring, results); storeCookies(urlstring); result:=true; except end; end; procedure TWinInternet.recreateFPHTTPClient; begin if internet<>nil then freeandnil(internet); internet:=TFPHTTPClient.Create(nil); internet.AddHeader('User-Agent',fname); internet.AllowRedirect:=true; end; {$else} function TWinInternet.postURL(urlstring: string; urlencodedpostdata: string; results: tstream): boolean; var url: HINTERNET; c,r: HInternet; available,actualread: dword; buf: PByteArray; u: TURI; port: dword; username, password: pchar; h: string; requestflags: dword; err: integer; begin h:='Content-Type: application/x-www-form-urlencoded'; result:=false; if internet<>nil then begin //InternetConnect(internet, ); requestflags:=INTERNET_FLAG_PRAGMA_NOCACHE; u:=ParseURI(urlstring); port:=INTERNET_DEFAULT_HTTP_PORT; if lowercase(u.Protocol)='https' then begin port:=INTERNET_DEFAULT_HTTPS_PORT; requestflags:=requestflags or INTERNET_FLAG_SECURE; end else begin // requestflags:=requestflags or INTERNET_FLAG_NO_AUTO_REDIRECT; end; if u.Port<>0 then port:=u.port; if u.Username<>'' then username:=pchar(u.Username) else username:=nil; if u.Password<>'' then password:=pchar(u.Password) else password:=nil; if u.params<>'' then u.params:='?'+u.params; c:=InternetConnect(internet, pchar(u.Host), port, username, password, INTERNET_SERVICE_HTTP, 0,0); if c<>nil then begin r:=HttpOpenRequest(c, PChar('POST'), pchar(u.path+u.Document+u.Params), nil, nil, nil, requestflags, 0); if r<>nil then begin if HttpSendRequest(r,pchar(h),length(h),pchar(urlencodedpostdata), length(urlencodedpostdata)) then begin while InternetQueryDataAvailable(r, available, 0, 0) do begin if available=0 then break; getmem(buf, available+32); try if InternetReadFile(r, buf, available,actualread)=false then break; if actualread>0 then begin results.WriteBuffer(buf[0], actualread); result:=true; //something was read end; finally FreeMemAndNil(buf); end; end; end else begin err:=getLastOSError; if err=0 then beep; end; InternetCloseHandle(r); end; InternetCloseHandle(c); end; end; end; function TWinInternet.getURL(urlstring: string; results: tstream): boolean; var url: HINTERNET; available,actualread: dword; buf: PByteArray; begin result:=false; if internet<>nil then begin if header='' then url:=InternetOpenUrl(internet, pchar(urlstring),nil,0,INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_RESYNCHRONIZE or INTERNET_FLAG_DONT_CACHE, 0) else url:=InternetOpenUrl(internet, pchar(urlstring), @fheader[1], length(fheader), INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_RESYNCHRONIZE or INTERNET_FLAG_DONT_CACHE,0); if url=nil then exit; while InternetQueryDataAvailable(url, available, 0, 0) do begin if available=0 then break; getmem(buf, available+32); try if InternetReadFile(url, buf, available+32,actualread)=false then break; if actualread>0 then begin results.WriteBuffer(buf[0], actualread); result:=true; //something was read end; finally FreeMemAndNil(buf); end; end; InternetCloseHandle(url); end; end; {$endif} constructor TWinInternet.create(name: string); begin {$ifdef windows} internet:=InternetOpen(pchar(name),0, nil, nil,0); {$else} fname:=name; openssl.DLLVersions[1]:=openssl.DLLVersions[2]; openssl.DLLVersions[1]:='.46'; openssl.DLLVersions[2]:='.44'; InitSSLInterface; openssl.ErrClearError; recreateFPHTTPClient; {$endif} end; destructor TWinInternet.destroy; begin if internet<>nil then {$ifdef windows} InternetCloseHandle(internet); {$else} freeandnil(internet); {$endif} inherited destroy; end; {$ifndef standalone} function getInternet(L: Plua_State): integer; cdecl; begin if lua_gettop(l)>0 then luaclass_newClass(L, TWinInternet.create({$ifdef altname}'Cheat Engine'{$else}cename{$endif}+' : luascript-'+Lua_ToString(L,1))) else luaclass_newClass(L, TWinInternet.create({$ifdef altname}'Cheat Engine'{$else}cename{$endif}+' : luascript')); result:=1; end; function wininternet_getURL(L: Plua_State): integer; cdecl; var i: TWinInternet; s: TMemoryStream; begin result:=0; i:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin s:=TMemoryStream.create; try if i.getURL(Lua_ToString(L, -1), s) then begin lua_pushlstring(L, s.Memory, s.Size); result:=1; end; finally s.free; end; end; end; function wininternet_postURL(L: Plua_State): integer; cdecl; var i: TWinInternet; s: TMemoryStream; param: string; begin result:=0; i:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin s:=TMemoryStream.create; try if lua_gettop(L)>=2 then param:=Lua_ToString(L, 2) else param:=''; if i.postURL(Lua_ToString(L, 1), param, s) then begin lua_pushlstring(L, s.Memory, s.Size); result:=1; end; finally s.free; end; end; end; procedure wininternet_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getURL', wininternet_getURL); luaclass_addClassFunctionToTable(L, metatable, userdata, 'postURL', wininternet_postURL); end; procedure initializeLuaInternet; begin lua_register(LuaVM, 'getInternet', getInternet); end; {$ifndef windows} procedure loadCookiesFromRegistry; var r: TRegistry; names: tstringlist; i: integer; c: tstringlist; begin macPortFixRegPath; r:=tregistry.Create; r.RootKey:=HKEY_CURRENT_USER; try if r.OpenKey('Cookies',false) then begin names:=tstringlist.create; try r.GetValueNames(names); for i:=0 to names.count-1 do begin c:=tstringlist.create; r.ReadStringList(names[i],c); cookies[names[i]]:=c; end; finally names.free; end; end; except end; r.free; end; procedure saveCookiesToRegistry; var r: TRegistry; i: integer; e: PStringHashItem; host: string; begin r:=TRegistry.Create; r.RootKey:=HKEY_CURRENT_USER; if r.OpenKey('Cookies',true) then begin for i:=0 to cookies.count-1 do begin e:=cookies.List[i]; if e<>nil then begin host:=e^.Key; r.WriteStringList(host,tstringlist(e^.Data)); end; end; end; r.free; end; {$endif} initialization {$ifndef windows} cookies:=TStringHashList.Create(false); loadCookiesFromRegistry; {$endif} luaclass_register(TWinInternet, wininternet_addMetaData); {$ifndef windows} finalization saveCookiesToRegistry; {$endif} {$endif} end.
unit uDBModulo; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Phys.OracleDef, FireDAC.Phys.PGDef, FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL, FireDAC.Phys.PG, FireDAC.Phys.Oracle, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, IniFiles; Var Archivo: String; IniFile: TIniFile; UserName: String; Password: String; BaseDato: String; DriverName: String; RutaBaseDato: String; Port: String; type TDBModulo = class(TDataModule) sqlFBConexion: TFDConnection; sqlQuery: TFDQuery; FDPhysOracleDriverLink1: TFDPhysOracleDriverLink; FDPhysPgDriverLink1: TFDPhysPgDriverLink; FDPhysMySQLDriverLink1: TFDPhysMySQLDriverLink; procedure sqlFBConexionBeforeConnect(Sender: TObject); procedure DataModuleCreate(Sender: TObject); private procedure EstablecerVariablesConexion; procedure CargarVariablesIniciales; public function Conexion: Boolean; procedure CerrarConexion; procedure ConfirmarConexion; procedure CancelarConexion; { Public declarations } end; var DBModulo: TDBModulo; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} procedure TDBModulo.CancelarConexion; begin try sqlFBConexion.Rollback; except on E: Exception do raise Exception.Create(E.Message); end; end; procedure TDBModulo.CargarVariablesIniciales; begin Archivo := GetCurrentDir + '\' + 'server.ini'; IniFile := TIniFile.Create(Archivo); RutaBaseDato := IniFile.ReadString('PARAMETERS', 'PATH', ''); BaseDato := IniFile.ReadString('PARAMETERS', 'NAME', ''); UserName := IniFile.ReadString('PARAMETERS', 'USER', ''); Password := IniFile.ReadString('PARAMETERS', 'PASS', ''); DriverName := IniFile.ReadString('PARAMETERS', 'DRIVER', ''); Port := IniFile.ReadString('PARAMETERS', 'PORT', ''); try except on E: Exception do raise Exception.Create('No existe un archivo de configuración. ' + E.Message); end; end; procedure TDBModulo.CerrarConexion; begin sqlFBConexion.Close; end; function TDBModulo.Conexion: Boolean; begin Result := False; try if not sqlFBConexion.Connected then sqlFBConexion.Open; Result := True; except on E: Exception do raise Exception.Create ('Ha ocurrido un error durante la conexión en el servidor.'); end; end; procedure TDBModulo.ConfirmarConexion; begin try sqlFBConexion.Commit; except on E: Exception do raise Exception.Create ('Ha ocurrido un error al confirmar la transacción.'); end; end; procedure TDBModulo.DataModuleCreate(Sender: TObject); begin CargarVariablesIniciales; end; procedure TDBModulo.EstablecerVariablesConexion; begin try sqlFBConexion.DriverName := DriverName; sqlFBConexion.Params.Values['Database'] := RutaBaseDato + BaseDato; sqlFBConexion.Params.Values['User_Name'] := UserName; sqlFBConexion.Params.Values['Password'] := Password; sqlFBConexion.Params.Values['Port'] := Port; except on E: Exception do raise Exception.Create ('No ha sido posible realizar la conexión con la base de datos ' + E.Message); end; end; procedure TDBModulo.sqlFBConexionBeforeConnect(Sender: TObject); begin EstablecerVariablesConexion; end; end.
{ Subroutine STRING_F_BITSC (S, BITS) * * Make 8 digit binary string from the bits in the character BITS. The string * will be truncated on the right to the maximum length of S. } module string_f_bitsc; define string_f_bitsc; %include 'string2.ins.pas'; procedure string_f_bitsc ( {make 8 digit binary string from character} in out s: univ string_var_arg_t; {output string} in bits: char); {input byte} val_param; var i: sys_int_max_t; {integer of right format for convert routine} stat: sys_err_t; {error code} begin i := ord(bits) & 16#FF; {into format for convert routine} string_f_int_max_base ( {make string from integer} s, {output string} i, {input integer} 2, {number base} 8, {output field width} [string_fi_leadz_k, {write leading zeros} string_fi_unsig_k], {input number is unsigned} stat); sys_error_abort (stat, 'string', 'internal', nil, 0); end;
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [IBPT] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit IbptVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('IBPT')] TIbptVO = class(TVO) private FID: Integer; FNCM: String; FEX: String; FTIPO: String; FDESCRICAO: String; FNACIONAL_FEDERAL: Extended; FIMPORTADOS_FEDERAL: Extended; FESTADUAL: Extended; FMUNICIPAL: Extended; FVIGENCIA_INICIO: TDateTime; FVIGENCIA_FIM: TDateTime; FCHAVE: String; FVERSAO: String; FFONTE: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('NCM', 'Ncm', 64, [ldGrid, ldLookup, ldCombobox], False)] property Ncm: String read FNCM write FNCM; [TColumn('EX', 'Ex', 16, [ldGrid, ldLookup, ldCombobox], False)] property Ex: String read FEX write FEX; [TColumn('TIPO', 'Tipo', 8, [ldGrid, ldLookup, ldCombobox], False)] property Tipo: String read FTIPO write FTIPO; [TColumn('DESCRICAO', 'Descricao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Descricao: String read FDESCRICAO write FDESCRICAO; [TColumn('NACIONAL_FEDERAL', 'Nacional Federal', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property NacionalFederal: Extended read FNACIONAL_FEDERAL write FNACIONAL_FEDERAL; [TColumn('IMPORTADOS_FEDERAL', 'Importados Federal', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ImportadosFederal: Extended read FIMPORTADOS_FEDERAL write FIMPORTADOS_FEDERAL; [TColumn('ESTADUAL', 'Estadual', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Estadual: Extended read FESTADUAL write FESTADUAL; [TColumn('MUNICIPAL', 'Municipal', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Municipal: Extended read FMUNICIPAL write FMUNICIPAL; [TColumn('VIGENCIA_INICIO', 'Vigencia Inicio', 80, [ldGrid, ldLookup, ldCombobox], False)] property VigenciaInicio: TDateTime read FVIGENCIA_INICIO write FVIGENCIA_INICIO; [TColumn('VIGENCIA_FIM', 'Vigencia Fim', 80, [ldGrid, ldLookup, ldCombobox], False)] property VigenciaFim: TDateTime read FVIGENCIA_FIM write FVIGENCIA_FIM; [TColumn('CHAVE', 'Chave', 48, [ldGrid, ldLookup, ldCombobox], False)] property Chave: String read FCHAVE write FCHAVE; [TColumn('VERSAO', 'Versao', 48, [ldGrid, ldLookup, ldCombobox], False)] property Versao: String read FVERSAO write FVERSAO; [TColumn('FONTE', 'Fonte', 272, [ldGrid, ldLookup, ldCombobox], False)] property Fonte: String read FFONTE write FFONTE; //Transientes end; implementation initialization Classes.RegisterClass(TIbptVO); finalization Classes.UnRegisterClass(TIbptVO); end.
unit sql.connection.FireDac; interface uses System.Classes, System.SysUtils, System.Generics.Collections, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.Comp.ScriptCommands, FireDAC.Stan.Util, FireDAC.Comp.Script, FireDAC.DApt, FireDAC.Phys.IBBase, FireDAC.Comp.Client, FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Comp.DataSet, FireDAC.Stan.Consts, Data.DB, Data.DBXCommon, sql.consts, sql.connection; type TFDScriptOutputKind = {$IFDEF VER280}TFDScriptOuputKind{$ELSE}TFDScriptOutputKind{$ENDIF}; type TSQLConnectionFD = Class(TDBConnection) private FDriverLink : TFDPhysDriverLink; FConnection : TFDConnection; FTransact : TFDTransaction; FDBXReaders : TObjectList<TDBXReader>; FOnProgress : TOnProgress; function FactoryQry : TFDQuery; procedure DoOnProgress(Sender : TObject); procedure DoOnConsolePut(AEngine: TFDScript; const AMessage: String; AKind: TFDScriptOutputKind); public Constructor Create; Override; Destructor Destroy; Override; function SQLGetMetaData(Kind : TFDPhysMetaInfoKind; Name : String = '') : TDataSet; function Connect : Boolean; Override; procedure Disconnect; Override; function Connected : Boolean; Override; function IsStart(Transact : Integer = 1) : Boolean; Override; function Start(Transact : Integer = 1) : Boolean; Override; function Commit(Transact : Integer = 1) : Boolean; Override; function Rollback(Transact : Integer = 1) : Boolean; Override; function ExecuteScript(Value : TStrings; OnProgress : TOnProgress) : Boolean; Override; function Execute(Value : String) : Boolean; Override; function Execute(Value : TStrings) : Boolean; Override; function Execute(Value : TStrings; Blobs : TList<TBlobData>) : Boolean; Override; function Open(Value : String) : TDataSet; Override; function Open(Value : TStrings) : TDataSet; Override; function Open(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Override; procedure Open(DataSet : TDataSet; Value : String); Override; function OpenQry(Value : String) : TDataSet; Override; function OpenExec(Value : String) : TDataSet; Override; function OpenExec(Value : TStrings) : TDataSet; Override; function OpenExec(Value : TStrings; Blobs : TList<TBlobData>) : TDataSet; Override; procedure SortIndex(Value : TDataSet; AscFields, DescFields : String); Override; End; implementation { TSQLConnectionDBX } function TSQLConnectionFD.Commit(Transact : Integer): Boolean; begin Result := IsStart; Try If Result Then FConnection.Commit; Result := True; Except On E:Exception Do Begin Error := E.Message; Result := False; End; End; end; function TSQLConnectionFD.Connect: Boolean; procedure SetFirebird; begin With FConnection Do Begin ConnectionName := ''; DriverName := 'FB'; Params.Values[S_FD_ConnParam_Common_DriverID] := 'FB'; Params.Values[S_FD_ConnParam_ADS_Protocol] := 'TCPIP'; Params.Values[S_FD_ConnParam_Common_Server] := DataBase.Server; Params.Values[S_FD_ConnParam_Common_Database] := DataBase.DataBase; Params.Values[S_FD_ConnParam_Common_Port] := FormatFloat('0',DataBase.Port); Params.Values[S_FD_ConnParam_Common_UserName] := DataBase.User; Params.Values[S_FD_ConnParam_Common_Password] := DataBase.Password; Params.Values[S_FD_ConnParam_IB_SQLDialect] := FormatFloat('0',DataBase.Dialect); End; FDriverLink := TFDPhysFBDriverLink.Create(FConnection); FDriverLink.VendorLib := 'fbclient.dll'; end; procedure SetSQLServer; begin With FConnection Do begin {DriverName := 'MSSQL'; ConnectionName := 'MSSQLConnection'; Params.Values[TDBXPropertyNames.HostName] := DataBase.Server; Params.Values[TDBXPropertyNames.Database] := DataBase.DataBase; Params.Values[TDBXPropertyNames.UserName] := DataBase.User; Params.Values[TDBXPropertyNames.Password] := DataBase.Password; Params.Values[TDBXPropertyNames.ErrorResourceFile] := 'C:\bti\sqlerro.txt';} end; end; procedure SetMySQL; begin With FConnection Do begin {DriverName := 'MySQL'; ConnectionName := 'MySQLConnection'; LibraryName := 'dbxmys.dll'; VendorLib := 'LIBMYSQL.dll'; Params.Values[TDBXPropertyNames.DriverName] := 'MySQL'; Params.Values[TDBXPropertyNames.HostName] := DataBase.Server; Params.Values[TDBXPropertyNames.Database] := DataBase.DataBase; Params.Values[TDBXPropertyNames.UserName] := DataBase.User; Params.Values[TDBXPropertyNames.Password] := DataBase.Password; Params.Values[TDBXPropertyNames.ErrorResourceFile] := 'C:\bti\sqlerro.txt';} end; end; procedure SetOracle; begin With FConnection Do begin end; end; begin Result := False; FConnection.Connected := False; FConnection.LoginPrompt := False; Try Case SQL.SQLDB Of dbFirebird : SetFirebird; dbSQLServer: SetSQLServer; dbMySQL : SetMySQL; dbOracle : SetOracle; End; Finally Try FConnection.LoginPrompt := False; FConnection.Connected := True; Result := FConnection.Connected; Except On E : Exception Do Error := E.Message; End; End; end; constructor TSQLConnectionFD.Create; begin inherited; FDBXReaders := TObjectList<TDBXReader>.Create; FConnection := TFDConnection.Create(nil); FTransact := TFDTransaction.Create(FConnection); //FTransact.TransactionID := 1; FTransact.Options.Isolation := xiReadCommitted; FConnection.ResourceOptions.SilentMode := True; end; destructor TSQLConnectionFD.Destroy; begin inherited; FreeAndNil(FDBXReaders); FreeAndNil(FTransact); FreeAndNil(FConnection); end; procedure TSQLConnectionFD.Disconnect; begin inherited; Try FConnection.Close; Except End; end; procedure TSQLConnectionFD.DoOnConsolePut(AEngine: TFDScript; const AMessage: String; AKind: TFDScriptOutputKind); begin If (AKind in [TFDScriptOutputKind.soEcho]) Then FSQLCurrent := AMessage Else If (AKind in [TFDScriptOutputKind.soError]) Then Error := AMessage; end; procedure TSQLConnectionFD.DoOnProgress(Sender: TObject); begin If Assigned(FOnProgress) Then FOnProgress(TFDScript(Sender).TotalJobDone,TFDScript(Sender).TotalJobSize,'Executando Script'); end; function TSQLConnectionFD.Execute(Value: TStrings; Blobs: TList<TBlobData>): Boolean; var Qry : TFDQuery; S : String; I : Integer; begin AddLog(Value); Error := ''; Try Qry := FactoryQry; For S in Value Do Begin If S.IsEmpty Then Continue; Qry.Close; Qry.SQL.Clear; Qry.SQL.Text := S; For I := 0 To (Qry.Params.Count - 1) Do Begin Qry.Params[I].DataType := ftBlob; Qry.Params[I].SetData(Pointer(Blobs[I]),High(Blobs[I])); End; Try Start; Qry.ExecSQL; Result := True; Except On E:Exception Do Begin Result := False; Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally FreeAndNil(Qry); End; end; function TSQLConnectionFD.ExecuteScript(Value: TStrings; OnProgress: TOnProgress): Boolean; var S : TFDScript; I : Integer; begin FOnProgress := OnProgress; S := TFDScript.Create(FConnection); Try S.Connection := FConnection; S.ScriptOptions.CommandSeparator := '^'; For I := 0 To (Value.Count - 1) Do Value[I] := Value[I] + S.ScriptOptions.CommandSeparator; S.ScriptOptions.EchoCommandTrim := 0; S.OnConsolePut := DoOnConsolePut; S.OnProgress := DoOnProgress; S.ExecuteScript(Value); Result := S.ExecuteAll And (S.TotalErrors = 0); Finally If Result Then FConnection.Commit Else FConnection.Rollback; FreeAndNil(S); End; end; function TSQLConnectionFD.Execute(Value: TStrings): Boolean; var S : String; begin Result := False; For S in Value Do Result := Execute(S); end; function TSQLConnectionFD.Execute(Value: String): Boolean; var Qry : TFDQuery; begin AddLog(Value); Error := ''; Try Qry := FactoryQry; Qry.SQL.Clear; Qry.SQL.Text := Value; Try Start; If (Trim(Value) <> '') Then Qry.ExecSQL; Result := True; Except On E:Exception Do Begin Result := False; Error := E.Message + '('+ Value +')'; AddLog(Error); End; End; Finally Qry.Close; FreeAndNil(Qry); End; end; function TSQLConnectionFD.FactoryQry: TFDQuery; begin Result := TFDQuery.Create(FConnection); Result.Connection := FConnection; Result.CachedUpdates := True; Result.Close; end; function TSQLConnectionFD.IsStart(Transact : Integer): Boolean; begin Result := FConnection.InTransaction; end; function TSQLConnectionFD.Open(Value: TStrings): TDataSet; var S : String; begin Result := nil; For S in Value Do Result := Open(S); end; function TSQLConnectionFD.OpenExec(Value: String): TDataSet; var Qry : TFDQuery; begin AddLog(Value); Qry := FactoryQry; Try Qry.SQL.Clear; Qry.SQL.Text := Value; Qry.Open; Finally Result := Qry; FDataSet.Add(Result); End; end; function TSQLConnectionFD.OpenExec(Value: TStrings): TDataSet; var S : String; begin Result := nil; For S in Value Do Result := OpenExec(S); end; function TSQLConnectionFD.Open(Value: String): TDataSet; var Qry : TFDQuery; begin AddLog(Value); Qry := FactoryQry; Result := Qry; Try Qry.SQL.Clear; Qry.SQL.Text := Value; Qry.Open; Finally FDataSet.Add(Result); End; end; function TSQLConnectionFD.Connected: Boolean; begin Result := (FConnection.Connected) {And FConnection.CheckActive}; end; function TSQLConnectionFD.Rollback(Transact : Integer): Boolean; begin Result := IsStart(Transact); Try If Result Then FConnection.Rollback; Result := True; Except Result := False; End; end; procedure TSQLConnectionFD.SortIndex(Value: TDataSet; AscFields, DescFields : String); begin inherited; If (Value is TFDDataSet) Then Begin With TFDDataSet(Value) Do Begin If IndexName <> '' Then DeleteIndex(IndexName); IndexName := ''; IndexDefs.Clear; Indexes.Clear; AddIndex('_index',AscFields,'',[],DescFields); IndexName := '_index'; End; End; end; function TSQLConnectionFD.SQLGetMetaData(Kind: TFDPhysMetaInfoKind; Name: String): TDataSet; var Inf : TFDMetaInfoQuery; begin Inf := TFDMetaInfoQuery.Create(nil); Inf.Connection := FConnection; Inf.MetaInfoKind := Kind; Inf.ObjectName := Name; Inf.Open; Result := Inf; end; function TSQLConnectionFD.Start(Transact : Integer): Boolean; begin Result := IsStart; Try If not Result Then FConnection.StartTransaction; Result := True; Except Result := False; End; end; procedure TSQLConnectionFD.Open(DataSet: TDataSet; Value: String); var Qry : TFDQuery; begin AddLog(Value); Qry := TFDQuery(DataSet); Qry.DisableControls; Qry.Close; Try Try Qry.IndexName := ''; Qry.IndexDefs.Clear; Except End; Qry.SQL.Clear; Qry.SQL.Text := Value; Qry.Open; Finally Qry.EnableControls; End; end; function TSQLConnectionFD.Open(Value: TStrings; Blobs: TList<TBlobData>): TDataSet; var Qry : TFDQuery; S : String; I : Integer; begin AddLog(Value); Error := ''; Qry := FactoryQry; Result := Qry; Qry.DisableControls; Try For S in Value Do Begin If S.IsEmpty Then Continue; Try Qry.Close; Qry.SQL.Clear; Qry.SQL.Text := S; For I := 0 To (Qry.Params.Count - 1) Do Begin Qry.Params[I].DataType := ftBlob; Qry.Params[I].SetData(Pointer(Blobs[I]),High(Blobs[I])); End; Qry.Open; Except On E:Exception Do Begin Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally Qry.EnableControls; FDataSet.Add(Result); End; end; function TSQLConnectionFD.OpenExec(Value: TStrings; Blobs: TList<TBlobData>): TDataSet; var Qry : TFDQuery; S : String; I : Integer; begin AddLog(Value); Error := ''; Qry := FactoryQry; Try For S in Value Do Begin If S.IsEmpty Then Continue; Qry.Close; Qry.SQL.Clear; Qry.SQL.Text := S; For I := 0 To (Qry.Params.Count - 1) Do Begin Qry.Params[I].DataType := ftBlob; Qry.Params[I].SetData(Pointer(Blobs[I]),High(Blobs[I])); End; Try Start; Qry.Open; Except On E:Exception Do Begin Qry.Close; Error := E.Message + '('+ S +')'; AddLog(Error); End; End; End; Finally Result := Qry; FDataSet.Add(Result) End; end; function TSQLConnectionFD.OpenQry(Value: String): TDataSet; var Qry : TFDQuery; begin AddLog(Value); Qry := FactoryQry; Result := Qry; Try Qry.SQL.Clear; Qry.SQL.Text := Value; Qry.Open; Finally FDataSet.Add(Result); End; end; end.
unit Expedicao.Services.uSeguradoraMock; interface uses Generics.Collections, Expedicao.Interfaces.uSeguradoraPersistencia, Expedicao.Models.uSeguradora; type TSeguradoraMock = class(TInterfacedObject, ISeguradoraPersistencia) private FListaSeguradora: TObjectList<TSeguradora>; public constructor Create; destructor Destroy; override; function ObterListaSeguradora: TList<TSeguradora>; function ObterSeguradora(pSeguradoraOID: Integer): TSeguradora; function IncluirSeguradora(pSeguradora: TSeguradora): Boolean; function AlterarSeguradora(pSeguradora: TSeguradora): Boolean; function ExcluirSeguradora(pSeguradoraOID: Integer): Boolean; end; implementation { TSeguradoraMock } constructor TSeguradoraMock.Create; var lSeguradora: TSeguradora; begin FListaSeguradora := TObjectList<TSeguradora>.Create; lSeguradora := TSeguradora.Create; lSeguradora.SeguradoraOID := 1; lSeguradora.Descricao := 'Seguradora X'; lSeguradora.CNPJ := '11.111.111/00001-11'; lSeguradora.Telefone := '(11) 1111-1111'; FListaSeguradora.Add(lSeguradora); lSeguradora := TSeguradora.Create; lSeguradora.SeguradoraOID := 2; lSeguradora.Descricao := 'Seguradora Y'; lSeguradora.CNPJ := '22.222.222/00002-22'; lSeguradora.Telefone := '(22) 2222-2222'; FListaSeguradora.Add(lSeguradora); end; destructor TSeguradoraMock.Destroy; begin FListaSeguradora.Clear; FListaSeguradora.Free; inherited; end; function TSeguradoraMock.AlterarSeguradora(pSeguradora: TSeguradora): Boolean; var lSeguradora: TSeguradora; begin Result := False; for lSeguradora in FListaSeguradora do if lSeguradora.SeguradoraOID = pSeguradora.SeguradoraOID then begin lSeguradora.Descricao := pSeguradora.Descricao; lSeguradora.CNPJ := pSeguradora.CNPJ; lSeguradora.Telefone := pSeguradora.Telefone; lSeguradora.Corretor := pSeguradora.Corretor; Result := True; Exit; end; end; function TSeguradoraMock.ExcluirSeguradora(pSeguradoraOID: Integer): Boolean; var lSeguradora: TSeguradora; begin Result := False; for lSeguradora in FListaSeguradora do if lSeguradora.SeguradoraOID = pSeguradoraOID then begin FListaSeguradora.Remove(lSeguradora); Result := True; Exit; end; end; function TSeguradoraMock.IncluirSeguradora(pSeguradora: TSeguradora): Boolean; begin pSeguradora.SeguradoraOID := FListaSeguradora.Count + 1; FListaSeguradora.Add(pSeguradora); Result := True; end; function TSeguradoraMock.ObterListaSeguradora: TList<TSeguradora>; var lSeguradora: TSeguradora; begin Result := TList<TSeguradora>.Create; for lSeguradora in FListaSeguradora do Result.Add(lSeguradora); end; function TSeguradoraMock.ObterSeguradora(pSeguradoraOID: Integer): TSeguradora; var lSeguradora: TSeguradora; begin Result := nil; for lSeguradora in FListaSeguradora do if lSeguradora.SeguradoraOID = pSeguradoraOID then begin Result := lSeguradora; Exit; end; end; end.
unit AI_Unit; { Unit zur logischen verarbeitung aller daten und eingaben waerend des programmlaufs sie stellt sowohl die ki funktionen als auch die verarbeitung fuer alle menschlichen zuege } interface uses TypeUnit ,System.SysUtils, Vcl.Graphics, DATA_Unit; { ueberpruefung der geklickten position @param x,y koordinaten auf die geklickt wurde @return die station auf die geklickt wurde 0 wenn keine getroffen wurde } function checkClickPos(x,y:integer):byte; { kodiert, von welchen tickets der uebergebene spieler noch welche hat, auf einem byte @param player dessen tickets benoetigt werden beispiel 5: Blacktickets 0: Taxiticket 7: Bustikets 0: U-Bahntickets resultirende codierung => (0000 1010) @return kodiertes byte } function getTickets(player:TPlayer):byte; { validiert die klickposition fuer den aktuellen spieler und gibt codiert ob er zur gekickten position ziehen kann und gibt codiert auf einem byte alle verwendbaren tickets und die anzahl der unterschiedlichen nutzbaren tickets zurueck @param x,y klickkoordinaten @return kodiertes byte mit allen moeglichen tickets } function checkMove(x,y:integer):byte; { uberpruefung ob eine der gewinn bedingungen erreicht ist @return ob das spiel vorbei ist } function gameOver():boolean; { benutzt das ticket und setzt den spieler auf die neue position und schreibt den zug in die logdatei @param ticket das zu nutzende ticket @param taktik die genutzte taktik @param eval wertung des zuges @return ob fehler beim schreiben der logdatei aufgetreten sind } function useTicket(ticket: TVehicles;taktik:byte;eval:real):boolean; { uberprueft ob der spieler zur angegebenen position ziehen darf und gibt kodiert alle moeglichen tickets zurueck @param dest ziel des zuges @param player nummer des spielers beispiel: black: false taxi: true bus: true u-bahn: false resultirende codierung => (0010 0110) @return kodiertes byte mit allen moeglichen tickets } function canGo(dest,player:byte):byte; { ueberpruefung ob sich der spieler im naechsten zug bewegen kann @return kann sich (nicht) bewegen } function canMove(player:byte):boolean; { bestimmt welcher spieler als naechstes drann ist } procedure nextPlayer(); { erstellt die moeglichen zielpositionen von misterX anhand seiner benutzten tickets } function getTargetsMr(ticket:TVehicles;targets:TTargets):TTargets; { verwaltung der ki zuege @return ergebnisse zur uebergabe an die gui } function aiTurn():TAiTurn; implementation //ueberprueft die geklickte position ob eine station getroffen wurde //@param x,y: koordinaten an denen geklickt wurde //@return die geklickte station 0 wenn keine getroffen wurde function checkClickPos(x,y:integer):byte; var distance:uint16; i,dest:byte; begin i:=1; dest:=0; while ( I < 200 ) and ( dest = 0 ) do begin distance := round(sqrt(sqr(x-Stations[i].posX)+sqr(y-Stations[i].posY))); if distance < 15 then dest:=i; inc(i); end; checkClickPos := dest; end; //erstellt eine maenge an unterschiedlichen tickets die der uebergebene //spieler noch hat //@param player: spieler dessen tickets getestet werden sollen //@return die menge an tickets die dieser noch hat function getTickets(player:TPlayer):byte; var tickets:byte; i:TVehicles; begin tickets := 0; for i:= SUBWAY to BOAT do begin if player.vehicles[i] > 0 then tickets := tickets or (1 shl ord(i)); end; getTickets:=tickets; end; //kann der aktuelle spieler an die geklickte position ziehen //@param dest station die getestet werden soll //@param player nummer des zu testenden spielers //@return die menge an tickets die dafuer in frage kommen function canGo(dest,player:byte):byte; var I:TVehicles; count,tickets,mrTicket,current: byte; isUsed:boolean; begin isUsed:=false; { ist das feld } for count:=1 to Length(Players) -1 do if Players[count].current = dest then isUsed:=true; count:=0; current:=Players[player].current; if not isUsed then begin tickets := getTickets(Players[player]); mrTicket:=0; for I:= SUBWAY to BOAT do begin if dest in Stations[current].destinations[I] then begin mrTicket := mrTicket or (1 shl ord(I)); inc(count); end; end; { erstellen der schnitt menge von vorhanden tickets und den verkehrsmitteln ueber die die station erreichbar waere } mrTicket := tickets and mrTicket; //wenn misterX am zug ist und er noch blacktickets besitzt hinzufuegen in die menge if player = 0 then begin if ((tickets and 8) > 0) and (count > 0) and not (mrTicket = 8) then begin mrTicket:= mrTicket or 8; inc(count); end end; { hinzufuegen der anzahl der moeglichkeiten } if (mrTicket = 0) then canGo := mrTicket else canGo := mrTicket or (count shl 4); end else canGo:=0; end; //ueberpruefung des klicks obs ein valieder zug ist //@param x,y: koordinaten an denen geklickt wurde //@return menge und anzahl der tickets die fuer den zug benutzt werden koennen // 0 wenn es keines gibt function checkMove(x,y:integer):byte; var dest,check:byte; begin check:=0; dest:=checkClickPos(x,y); if dest <> 0 then begin check := canGo(dest,GameStat.CurrentPlayer); if check <> 0 then Destination := dest; end; checkMove := check; end; //ob sich ein spieler ueberhaupt bewegen kann... //@param player zu testende spieler //@return true wenn dieser spieler mindestens eine moeglichkeit // hat sich zu bewegen sonnst false function canMove(player:byte):boolean; var other,tickets:byte; check:boolean; I:TVehicles; others:TTargets; begin others:=[]; tickets := getTickets(Players[player]); check:=false; if tickets > 0 then begin for other:=1 to Length(Players) -1 do others:=others + [Players[other].current]; for I:= SUBWAY to BOAT do if (tickets and (1 shl ord(I))) > 0 then if (Stations[Players[Player].current].destinations[I] <> []) then if not (Stations[Players[Player].current].destinations[I] <= others) then check:=true; end; canMove:=check; end; { hilfsfunction die die positionen aller detektive als menge zurueckliefert } function getDetPos():TTargets; var i:byte; res:TTargets; begin res:=[]; for i := 1 to GameStat.countDet do res:=res + [Players[i].current]; getDetPos:=res; end; { erstellt moegliche zielpositionsmenge fuer misterX } function getTargetsMr(ticket:TVehicles;targets:TTargets):TTargets; var i:byte; nextTargets:TTargets; begin nextTargets:=[]; targets:=targets - getDetPos(); for i := 1 to 199 do begin if i in targets then begin nextTargets:=nextTargets + Stations[i].destinations[ticket]; if ticket = BOAT then begin repeat dec(ticket); nextTargets:=nextTargets + Stations[i].destinations[ticket]; until ticket = SUBWAY ; end; end; end; nextTargets:=nextTargets - getDetPos(); getTargetsMR:=nextTargets; end; //decrementiert das ausgewaehlte ticket //und setzt die neue position des aktuellen spielers //wenn nich Mr.X am zug ist wird das benutzte ticket bei ihm erhoet function useTicket(ticket: TVehicles;taktik:byte;eval:real):boolean; var show: set of byte; log:boolean; begin show:= [3,8,13,18,24]; dec(Players[GameStat.CurrentPlayer].vehicles[ticket]); log:=writelog(taktik,eval); Players[GameStat.CurrentPlayer].current:=Destination; Destination:=0; if GameStat.CurrentPlayer <> 0 then begin inc(Players[0].vehicles[ticket]); end else begin if GameStat.rou in show then begin GameStat.MRpos:=Players[0].current; GameStat.posibleTargets:= [GameStat.MRpos]; end else GameStat.posibleTargets:=getTargetsMr(ticket,GameStat.posibleTargets); GameStat.moveTable[GameStat.rou]:=ticket; end; useTicket:=log; end; //setzen des naechsten spielers procedure nextPlayer(); var lastPlayer:byte; begin lastPlayer:=GameStat.CurrentPlayer; repeat inc(GameStat.CurrentPlayer); if GameStat.CurrentPlayer >= length(Players) then begin GameStat.CurrentPlayer:=0; inc(GameStat.rou); end; until canmove(GameStat.CurrentPlayer); GameStat.update:= lastPlayer=0; end; //ueberpruefung ob das spiel zuende ist also ob und wer gewonnen hat //ausserdem wird das Winnerlabel gesetzt //@return true wenn eine seite gewonnen hat ansonsten false function gameOver():boolean; var i,stuck:byte; over:boolean; begin over:=false; stuck:=0; for i:=1 to GameStat.countDet do begin if Players[0].current = Players[i].current then begin WinnerLabel:='Mr. X wurde von '+ pName(i) +' gefangen!!'; over:=true; GameStat.winner:=2; end else if not canMove(i) then inc(stuck); end; if (stuck = Length(Players) -1) or (GameStat.rou > 24) then begin WinnerLabel:='Mr. X ist Entkommen!!!'; GameStat.winner:=1; over:=true; end; gameOver:=over; end; { gibt das ticket zurueck von dem der spieler noch die meisten hat aus der menge der in tickets kodierten auswahl @param player zu testender spieler @param tickets auswahl der tickets @return das am heufigsten vorhandene ticket aus der auswahl } function hasMoreOf(player:TPlayer;tickets:byte):TVehicles; var ticket,toUse:TVehicles; lastTest:byte; begin lastTest:=0; toUse:=TVehicles.NONE; for ticket := SUBWAY to BOAT do if ((tickets and (1 shl ord(ticket))<>0)) and (player.vehicles[ticket] >= lastTest ) then begin lastTest:=player.vehicles[ticket]; toUse:=ticket; end; hasMoreOf:=toUse; end; { moegliche zielpositionen anhand der ausgewaelten tickets @param tickets auswahl von tickets @param menge der positionen von denen aus getestet werden soll @return resultierende zielpositionsmenge } function getTargets(tickets:byte;current:TTargets):TTargets; var targets:TTargets; hasticket:TVehicles; from :byte; begin targets:=[]; for from := 1 to 199 do begin if from in current then begin for hasticket := SUBWAY to BOAT do if ((tickets and (1 shl ord(hasticket))) <> 0) or ((tickets and (1 shl ord(BOAT)))<>0) then targets:=targets + Stations[from].destinations[hasticket]; end; end; for from := 1 to GameStat.countDet do targets:=targets - getDetPos(); getTargets:=targets; end; { erstellt einen weg von einer position zu einer anderen und nutzt dafuer nur die in tickets uebergebene auswahl von verkehrsmitteln @param tickets auswahl an verkehrsmitteln @param from startposition @param target zielposition @return den reiseweg als array } function getWay(tickets,from,target:byte):TWay; var way:TWay; i,findRound,fillway:byte; targets:TTargets; begin for i:=1 to 199 do begin way[i].step:= -1; way[i].from:= 0; end; way[from].step:=0; findRound:=1; while (findround <= 10) and (way[target].step = -1) do begin for i := 1 to 199 do begin if way[i].step = (findRound - 1) then begin targets:=getTargets(tickets,[i]); for fillway := 1 to 199 do begin if (fillway in targets) and (way[fillway].step = -1) then begin way[fillway].step:=findRound; way[fillway].from:=i; end; end; end; end; inc(findRound); end; getWay:=way; end; { erste ki taktik kann auf eine moegliche zielposition von misterX gezogen werden @param player der spieler @param current nummer des spielers @return zielposition und zu nutzendes ticket } function tacticOne(player:TPlayer;current:byte):TMove; var tickets, target:byte; posTargets, playerTargets:TTargets; move:TMove; begin posTargets:= GameStat.posibleTargets; tickets:=getTickets(player); playerTargets:=getTargets(tickets,[player.current]); move.target:=0; move.ticket:=TVehicles.NONE; playerTargets:= playerTargets * posTargets; if playerTargets <> [] then begin target:=1; repeat if target in playerTargets then begin move.ticket:=hasMoreOf(player,cango(target,current)); if move.ticket <> TVehicles.NONE then move.target:=target; end; inc(target); until ((move.target <> 0)and (move.ticket<>TVehicles.NONE)) or (target >= 200) ; end; tacticOne:=move; end; { zweite ki taktik kann auf eine station mit ubahn verbindung gezogen werden @param player der spieler @param current nummer des spielers @return zielposition und zu nutzendes ticket } function tacticTwo(player:TPlayer;current:byte):TMove; var tickets, target:byte; targets:TTargets; move:TMove; begin tickets:=getTickets(player); targets:=getTargets(tickets,[player.current]); move.target:=0; move.ticket:=TVehicles.NONE; target:=1; repeat if target in targets then if Stations[target].destinations[SUBWAY] <> [] then begin move.ticket:=hasMoreOf(player,cango(target,current)); if move.ticket <> TVehicles.NONE then move.target:=target; end; inc(target); until((move.target <> 0)and (move.ticket<>TVehicles.NONE)) or (target >= 200) ; tacticTwo:=move; end; { dritte ki taktik laufe in richtung zur letzten zeigeposition von misterX @param player der spieler @param current nummer des spielers @return zielposition des ersten schritts und zu nutzendes ticket } function tacticThree(player:TPlayer;current:byte):TMove; var way: TWay; findRound, tickets:byte; detPos:TTargets; move:TMove; begin move.target:=0; move.ticket:=TVehicles.NONE; if GameStat.MRpos <> 0 then begin tickets:= getTickets(player); detPos:=getDetPos(); if not(GameStat.MRpos in detPos) then begin way:=getWay(tickets,player.current,GameStat.MRpos); if (way[GameStat.MRpos].step <> -1) then begin findRound:=GameStat.MRpos; while way[findRound].from <> player.current do begin findRound:=way[findRound].from; end; move.ticket:=hasMoreOf(player,cango(findRound,current)); if move.ticket <> TVehicles.NONE then move.target:=findRound; end; end; end; tacticThree:=move; end; { vierte ki taktik bewege dich auf die station mit kleinst moeglicher nummer @param player der spieler @param current nummer des spielers @return zielposition und zu nutzendes ticket } function tacticFour(player:TPlayer;current:byte):TMove; var targets:TTargets; target,tickets:byte; move:TMove; begin tickets:=getTickets(player); targets:=getTargets(tickets,[player.current]); move.target:=0; move.ticket:=TVehicles.NONE; target:=1; repeat if target in targets then begin move.ticket:=hasMoreOf(player,cango(target,current)); if move.ticket <> TVehicles.NONE then move.target:=target; end; inc(target); until ((move.target <> 0)and (move.ticket<>TVehicles.NONE)) or (target >= 200); tacticFour:=move; end; { zaelt elemente einer menge @param targets menge deren elemente gezaelt werden sollen @return anzahl der elemente } function countTargets(targets:TTargets):byte; var i, count: byte; begin count:=0; for i := 1 to 199 do begin if i in targets then inc(count); end; countTargets:=count; end; { erste bewertungs funktion wie viele moegliche zielpositionen von misterX sind nach dem aktuellen zug durch von detektiven erreichbar geteilt durch gesammt anzah moeglicherzielpositionen multipliziert mit 10 @param target ticket und ziel des zu bewertenden zuges @return resultat der oben beschriebenen rechnung } function ratingOne(target:TMove):double; var posibletargets,detTargets:TTargets; player,tickets, countMr, count:byte; current:TPlayer; begin detTargets:=[]; posibletargets:=GameStat.posibleTargets - [target.target]; current:=Players[GameStat.CurrentPlayer]; dec(current.vehicles[target.ticket]); if posibletargets <> [] then begin for player := 1 to GameStat.countDet do begin if player = GameStat.CurrentPlayer then begin tickets:=getTickets(current); detTargets:=detTargets + getTargets(tickets,[target.target]); end else begin tickets:=getTickets(Players[player]); detTargets:=detTargets + getTargets(tickets,[Players[player].current]); end; end; countMr:=countTargets(posibletargets); count:=countTargets(posibletargets * detTargets); ratingOne:= (count / countMr) *10; end else ratingOne:=0.0; end; { zweite bewertungs funktion wie viele schritte werden benoetigt um misterX mittlere moegliche zielposition zu erreichen wertung = 10 - noetige schritte @param target ticket und ziel des zu bewertenden zuges @return resultat der oben beschriebenen rechnung } function ratingTwo(target:TMove):byte; var posTargets,detPos:TTargets; i, dest, count:byte; mX,mY,distance, oldd:longint; way: TWay; tickets:byte; findRound:integer; begin posTargets:=GameStat.posibleTargets - [target.target]; if (posTargets <> []) and (target.target <> 0) then begin mX:=0; mY:=0; dest:=0; for i := 1 to 199 do begin if i in posTargets then begin mX:=mX + Stations[i].posX; mY:=mY + Stations[i].posY; end; end; count:=countTargets(posTargets); mX:= round(mX/count); mY:= round(mY/count); oldd:=700; for i := 1 to 199 do begin distance := round(sqrt(sqr(mX-Stations[i].posX)+sqr(mY-Stations[i].posY))); if distance < oldd then begin oldd:=distance; dest:=i; end; end; detPos:=getDetPos(); if (dest > 0) and not (dest in detPos) and (dest < 200) then begin tickets:= getTickets(Players[GameStat.CurrentPlayer]); way:=getWay(tickets,target.target,dest); findround := way[dest].step; if findround <> -1 then ratingTwo:= 10 - findround else ratingTwo:= 0; end else ratingTwo:= 0; end else ratingTwo:= 0; end; { dritte ki bewertungsfunktion wie viele stationen koennen nach dem zug mit den noch vorhandenen tickets in einem zug erreicht werden berechnung = anzahlziele / 13 * 4 @param target ticket und ziel des zu bewertenden zuges @return resultat der oben beschriebenen rechnung } function ratingThree(target:TMove):double; var tickets:byte; count:byte; player:TPlayer; begin if (target.target <> 0) and (target.ticket <> TVehicles.NONE) then begin player:=Players[GameStat.CurrentPlayer]; dec(player.vehicles[target.ticket]); tickets:=getTickets(player); count:=countTargets(getTargets(tickets,[target.target])); ratingThree:= (count/13)*4; end else ratingThree:=0; end; { vierte ki bewertungsfunktion sind noch genug tickets da sind von allen tickets noch mehr als 3 da ergibt sich das ergebnis zu drei sonnst die kleinste anzahl der verbliebenen tickets @param target ticket und ziel des zu bewertenden zuges @return resultat der oben beschriebenen rechnung } function ratingFour(target:TMove):byte; var player:TPlayer; ticket:TVehicles; count:byte; begin count:=3; player:=Players[GameStat.CurrentPlayer]; dec(player.vehicles[target.ticket]); for ticket := SUBWAY to TAXI do if player.vehicles[ticket] < count then count:=player.vehicles[ticket]; ratingFour:=count; end; { bedingtes fuellen des ergebnis struckts @param taktic genutzte taktik @param target ticket und ziel des zu bewertenden zuges @param wertung des zugs } procedure DetAi(taktic:byte;target:TMove;rating:double;var res:TAiTurn); begin if rating > res.eval then begin res.taktic:=taktic; res.eval:=rating; res.ticket:=target.ticket; res.target:=target.target; end; end; { bewertungs function fuer die zuege von misterX die wertung ergibt sich aus der anzahl der detecktive die ihn nach dem zug in einem schritt erreichen koennten, wie viele zielpositionen er nach dem schritt zur auswahl hat und wie viele tickets er nach dem schritt von jeder sorte noch besitzt } function mRating(target:byte):double; var tickets,count,det:byte; rating:double; ticket:TVehicles; mr:TPlayer; begin count:=0; for det := 1 to GameStat.countDet do begin tickets:=getTickets(Players[det]); if target in getTargets(tickets,[Players[det].current]) then inc(count); end; rating:= (GameStat.countDet-count)*10; mr:=Players[0]; dec( mr.vehicles[ hasMoreOf( mr, cango( target, 0) ) ] ); count:=countTargets( getTargets( getTickets(mr), [target])); rating:=rating + ((count/13)*4); count:=3; for ticket := SUBWAY to TAXI do if mr.vehicles[ticket] < count then count:=mr.vehicles[ticket]; rating:= rating + count; mRating := rating; end; { misterX ki zug geht alle moeglichen zielpositionen durch und gibt die bestbewertete zurueck inclusive ihrer wertung und des zu nutzenden tickets } function misterAiTurn():TAiTurn; var posTargets:TTargets; i,tickets:byte; rating:double; turn:TAiTurn; begin turn.taktic:=1; turn.eval:=0.0; turn.target:=0; turn.ticket:=TVehicles.NONE; tickets:=getTickets(Players[0]); posTargets:= getTargets(tickets,[Players[0].current]); for i := 1 to 199 do if (i in posTargets) then begin rating:= mRating(i); if rating > turn.eval then begin turn.ticket:=hasMoreOf(Players[0],cango(i,0)); turn.target:=i; turn.eval:=rating; end; end; misterAiTurn:=turn; end; { ki zug verwaltung ruft fuer die detektive alle vier takticken auf und gibt die bestbewertete zurueck falls misterX am zug ist wird seine taktik ausgefuert } function aiTurn():TAiTurn; var res:TAiTurn; rating:double; target:TMove; begin if GameStat.CurrentPlayer <> 0 then begin res.taktic:=0; res.eval:=0.0; res.target:=0; res.ticket:=TVehicles.NONE; target:=tacticOne(Players[Gamestat.CurrentPlayer],Gamestat.CurrentPlayer); if (target.target <> 0) and (target.ticket <> TVehicles.NONE) then begin rating:=ratingOne(target) + ratingTwo(target) + ratingThree(target) + ratingFour(target); DetAi(1,target,rating,res); end; target:=tacticTwo(Players[Gamestat.CurrentPlayer],Gamestat.CurrentPlayer); if (target.target <> 0) and (target.ticket <> TVehicles.NONE) then begin rating:=ratingOne(target) + ratingTwo(target) + ratingThree(target) + ratingFour(target); DetAi(2,target,rating,res); end; target:=tacticThree(Players[Gamestat.CurrentPlayer],Gamestat.CurrentPlayer); if (target.target <> 0) and (target.ticket <> TVehicles.NONE)then begin rating:=ratingOne(target) + ratingTwo(target) + ratingThree(target) + ratingFour(target); DetAi(3,target,rating,res); end; target:=tacticFour(Players[Gamestat.CurrentPlayer],Gamestat.CurrentPlayer); if (target.target <> 0) and (target.ticket <> TVehicles.NONE) then begin rating:=ratingOne(target) + ratingTwo(target) + ratingThree(target) + ratingFour(target); DetAi(4,target,rating,res); end; Destination:=res.target; aiTurn:=res; end else begin res:=misterAiTurn(); Destination:=res.target; aiTurn:=res; end; end; end.
unit SQLDBBackup; interface uses Windows, SysUtils, Variants, Classes, Controls, Forms, ExtCtrls, StdCtrls, Buttons, Dialogs, ShlObj, IniFiles; type TSQLDBBackupForm = class(TForm) Panel1: TPanel; EdtAddr: TEdit; Label1: TLabel; BtnSel1: TBitBtn; Label2: TLabel; EdtRestore: TEdit; BtnSel2: TBitBtn; OpenDialog1: TOpenDialog; BtnBackup: TBitBtn; BtnRestore: TBitBtn; ClostBtn: TButton; BtnCompact: TButton; procedure BtnSel2Click(Sender: TObject); procedure BtnBackupClick(Sender: TObject); procedure BtnRestoreClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BtnSel1Click(Sender: TObject); procedure ClostBtnClick(Sender: TObject); procedure BtnCompactClick(Sender: TObject); private function SelectFolder(const DlgTitle: string): string; //选择路径 procedure BackupDatabase(); { Private declarations } public Path: string; { Public declarations } end; var SQLDBBackupForm: TSQLDBBackupForm; implementation uses QueryDM; {$R *.dfm} procedure TSQLDBBackupForm.BackupDatabase(); //备份数据库 var BackupPath, DBName: string; myini: TiniFile; begin if myini = nil then myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'db.ini'); try DBName := myini.ReadString('db', 'DBName', 'weight20'); finally myini.Free; end; BackupPath := '''' + EdtAddr.Text + '\' + FormatDateTime('yyyy-mm-dd hh-nn-ss', now) + '.BAK'''; with QueryDataModule.ADOQExec do begin Close; SQL.Text := 'use master'; ExecSQL; SQL.Text := 'backup database ' + DBName + ' to disk=' + BackupPath; try ExecSQL; MessageDlg(pchar('数据库备份成功!' + #13 + '备份路径: ' + BackupPath), mtInformation, [mbOK], 0); SQL.Text := 'use ' + dbname; ExecSQL; except on E: Exception do begin MessageDlg(pchar(E.Message), mtInformation, [mbOK], 0); end; end; SQL.Text := 'Use weight20'; ExecSQL; end; end; function TSQLDBBackupForm.SelectFolder(const DlgTitle: string): string; var bi: TBrowseInfo; PathIdList: PItemIdList; strPath: string; begin strPath := stringOfChar(' ', 512); bi.hwndOwner := self.Handle; bi.pidlRoot := nil; bi.pszDisplayName := nil; bi.lpszTitle := pchar(DlgTitle); bi.ulFlags := BIF_ReturnOnlyFsDirs; bi.lpfn := nil; bi.lParam := 0; bi.iImage := 0; result := ''; PathIdList := SHBrowseForFolder(bi); if PathIdList <> nil then if SHGetPathFromIdList(PathIdList, pchar(strPath)) then result := trim(strPath); end; procedure TSQLDBBackupForm.BtnSel2Click(Sender: TObject); begin if OpenDialog1.Execute then EdtRestore.Text := OpenDialog1.FileName; end; procedure TSQLDBBackupForm.BtnBackupClick(Sender: TObject); var myini: TIniFile; begin if EdtAddr.Text = '' then begin MessageDlg('数据库备份路径没有选择,无法进行备份!', mtWarning, [mbOK], 0); exit; end; if myini = nil then myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'db.ini'); try myini.WriteString('db', 'backup_addr', EdtAddr.Text); finally myini.Free; end; BackupDatabase(); end; procedure TSQLDBBackupForm.BtnRestoreClick(Sender: TObject); begin if EdtRestore.Text = '' then begin MessageDlg('数据库恢复路径没有选择,无法进行恢复!', mtWarning, [mbOK], 0); exit; end; with QueryDataModule.ADOQExec do begin Close; SQL.Text := 'Use master'; ExecSQL; SQL.Text := 'restore database :database from disk=:path with replace'; Parameters.ParamByName('database').Value := 'weight20'; Parameters.ParamByName('path').Value := EdtRestore.Text; try ExecSQL; MessageDlg('数据库恢复成功!' + #13 + '软件会自动关闭,请自行启动。', mtInformation, [mbOK], 0); Application.Terminate; except MessageDlg('数据库恢复失败!', mtInformation, [mbOK], 0); end; SQL.Text := 'Use weight20'; ExecSQL; end; end; procedure TSQLDBBackupForm.FormShow(Sender: TObject); var myini: TIniFile; begin if myini = nil then myini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'db.ini'); try EdtAddr.Text := myini.ReadString('db', 'backup_addr', ''); finally myini.Free; end; end; procedure TSQLDBBackupForm.BtnSel1Click(Sender: TObject); begin EdtAddr.Text := SelectFolder('选择备份路径'); end; procedure TSQLDBBackupForm.ClostBtnClick(Sender: TObject); begin Close; end; procedure TSQLDBBackupForm.BtnCompactClick(Sender: TObject); begin with QueryDataModule.ADOQExec do begin Close; SQL.Clear; SQL.Add('dbcc shrinkdatabase weight20'); try ExecSQL; MessageBox(0, '数据库压缩成功!', '提示', MB_OK + MB_ICONINFORMATION); except on E: Exception do MessageBox(0, PChar(E.Message), '警告', MB_OK + MB_ICONWARNING); end; end; end; end.
unit MainFormUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Generics.Collections, System.Diagnostics, System.TimeSpan, BlocksUnit, System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls, Vcl.ActnMenus, Vcl.ExtCtrls, CryptoVirtualTreeUnit; type TMainForm = class(TForm) Memo1: TMemo; Button2: TButton; Button1: TButton; procedure FormCreate(Sender: TObject); procedure Button2Click(Sender: TObject); private fBlockFilePath: string; aBlocks: TBlocks; nblocks: uint64; Stopwatch: TStopwatch; TimeSpan: TTimeSpan; protected procedure StartingParsingBlockFiles(Sender: TObject); procedure FinishedParsingBlockFiles(Sender: TObject); procedure StartProcessFiles(const aBlockFiles: TList<String>); // procedure EndFoundFileBlock(const aBlockFiles: TList<String>); procedure BeforeProcessAFile(const aBlockFile: TBlockFile; var next: boolean); procedure AfterProcessAFile(const aBlockFile: TBlockFile; var next: boolean); procedure FoundMagicBlock(const aBlock: TBlockRecord; var findnext: boolean); procedure BlockProcessStep(const aPos, aSize: int64); procedure EndProcessBlockFile(const aBlockFile: TBlockFile); public constructor Create(Owner: TComponent); override; end; var MainForm: TMainForm; implementation uses datamodule, inifiles, dateutils, SeSHA256, System.Threading; {$R *.dfm} procedure TMainForm.BeforeProcessAFile(const aBlockFile: TBlockFile; var next: boolean); begin Memo1.Lines.Add(format(' Start process %s file %d of %d', [aBlockFile.aFileName, aBlockFile.aBlockNumber, aBlockFile.parent.Count])); end; procedure TMainForm.BlockProcessStep(const aPos, aSize: int64); begin if (aPos mod 25) = 0 then Memo1.Lines.Add(IntToStr(aPos * 100 div aSize) + '%'); end; procedure TMainForm.Button2Click(Sender: TObject); begin aBlocks.aBlocksDirectory := fBlockFilePath; aBlocks.start; end; constructor TMainForm.Create(Owner: TComponent); begin inherited; aBlocks := TBlocks.Create(true); aBlocks.FreeOnTerminate := true; // Starts and ends processing all .dat files aBlocks.OnStartingParsingBlockfiles := StartingParsingBlockFiles; aBlocks.OnFinishedParsingBlockFiles := FinishedParsingBlockFiles; // Starts and ends process each .dat file aBlocks.OnStartProcessFiles := StartProcessFiles; // aBlocks.OnEndProcessBlockFile := EndProcessBlockFile; // Stars and ends block aBlocks.OnBeforeFileBlockProcess := BeforeProcessAFile; aBlocks.OnAfterFileBlockProcessed := AfterProcessAFile; aBlocks.OnMagicBlockFound := FoundMagicBlock; aBlocks.OnBlockProcessStep := BlockProcessStep; end; { procedure TMainForm.EndFoundFileBlock(const aBlockFiles: TList<String>); var nbsec: double; begin TimeSpan := Stopwatch.Elapsed; nbsec := nblocks / TimeSpan.TotalSeconds; Memo1.Lines.Add(nbsec.ToString); aBlockFiles.Free; end; } procedure TMainForm.FinishedParsingBlockFiles(Sender: TObject); begin Memo1.Lines.Add(' End parsing all files'); end; procedure TMainForm.EndProcessBlockFile(const aBlockFile: TBlockFile); begin Memo1.Lines.Add(' End processing ' + aBlockFile.aFileName); end; procedure TMainForm.FormCreate(Sender: TObject); var aFileDir: string; aINIFile: TIniFile; begin // Create data directories aFileDir := ExtractFilePath(Application.ExeName); if DirectoryExists(aFileDir + '\data\') = false then CreateDir(aFileDir + '\data\'); if DirectoryExists(aFileDir + '\btc') = false then CreateDir(aFileDir + '\btc'); // Load settings from IniFile aINIFile := TIniFile.Create(aFileDir + '\config.ini'); fBlockFilePath := aINIFile.ReadString('File', 'BlockFilePath', ''); aINIFile.Free; end; procedure TMainForm.AfterProcessAFile(const aBlockFile: TBlockFile; var next: boolean); begin Memo1.Lines.Add(' Processed ' + aBlockFile.aFileName); next := true; // next := false; end; procedure TMainForm.FoundMagicBlock(const aBlock: TBlockRecord; var findnext: boolean); var k, j, i: integer; t: string; begin // Performance inc(nblocks); // exit; if (nblocks <> 12 ) then exit; Memo1.Lines.Add(' Hash: ' + aBlock.hash); Memo1.Lines.Add(' '); Memo1.Lines.Add(datetimetostr(Unixtodatetime(aBlock.header.time)) + ' UTC ' + ' Bits: ' + aBlock.header.DifficultyTarget.ToString + ' nonce: ' + aBlock.header.nonce.ToString); Memo1.Lines.Add(' Hash: ' + aBlock.hash); Memo1.Lines.Add(' Prev. block: ' + T32ToString(aBlock.header.aPreviousBlockHash)); Memo1.Lines.Add(' MerkleRoot: ' + T32ToString(aBlock.header.aMerkleRoot)); Memo1.Lines.Add(' Transactions ' + aBlock.transactions.Count.ToString); Memo1.Lines.Add(' '); for k := 0 to aBlock.transactions.Count - 1 do begin Memo1.Lines.Add(' Transacción ' + IntToStr(k)); Memo1.Lines.Add(' version ' + aBlock.transactions[k].version.ToString); if aBlock.transactions[k].inputs.Count > 0 then for j := 0 to aBlock.transactions[k].inputs.Count - 1 do begin Memo1.Lines.Add(format(' input %s', [T32ToString(aBlock.transactions[k].inputs[j].aTXID)])); Memo1.Lines.Add(format(' %.8f BTC', [(aBlock.transactions[k].inputs[j].aVOUT / 100000000)])); t := ''; for i := 0 to aBlock.transactions[k].inputs[j].CoinBaseLength - 1 do begin t := t + IntToHex(aBlock.transactions[k].inputs[j].CoinBase[i]); end; Memo1.Lines.Add(' coinbase: ' + t); Memo1.Lines.Add(' '); end; if aBlock.transactions[k].outputs.Count > 0 then for j := 0 to aBlock.transactions[k].outputs.Count - 1 do begin Memo1.Lines.Add(format(' output %.8f BTC', [aBlock.transactions[k].outputs[j].nValue / 100000000])); t := ''; for i := 0 to aBlock.transactions[k].outputs[j].OutputScriptLength - 1 do begin t := t + IntToHex(aBlock.transactions[k].outputs[j].OutputScript[i]); end; Memo1.Lines.Add(' outputscript: ' + t); Memo1.Lines.Add(' '); end; Memo1.Lines.Add(' '); end; end; procedure TMainForm.StartingParsingBlockFiles(Sender: TObject); begin Memo1.Lines.Add('Start parsing component'); end; procedure TMainForm.StartProcessFiles(const aBlockFiles: TList<String>); begin Memo1.Lines.Add(' Block files found to process ' + aBlockFiles.Count.ToString); nblocks := 0; Stopwatch := TStopwatch.StartNew; end; end.
unit Atm.Tests.Stubs.CardReader; interface uses Atm.Services.CardReader; function CreateCardReaderStub: IAtmCardReader; implementation uses System.SysUtils, Atm.Tests.Globals; type TAtmCardReaderStub = class(TInterfacedObject, IAtmCardReader) public function CheckForValidPin(const APin: string): Boolean; end; function TAtmCardReaderStub.CheckForValidPin(const APin: string): Boolean; begin Result := SameText(APin, PinRightValue); end; function CreateCardReaderStub: IAtmCardReader; begin Result := TAtmCardReaderStub.Create; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [VENDA_CABECALHO] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit VendaCabecalhoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, DB, ViewPessoaTransportadoraVO, NotaFiscalTipoVO, ViewPessoaClienteVO, VendedorVO, VendaCondicoesPagamentoVO, VendaOrcamentoCabecalhoVO, VendaDetalheVO, VendaComissaoVO; type [TEntity] [TTable('VENDA_CABECALHO')] TVendaCabecalhoVO = class(TVO) private FID: Integer; FID_VENDA_ROMANEIO_ENTREGA: Integer; FID_VENDA_ORCAMENTO_CABECALHO: Integer; FID_VENDA_CONDICOES_PAGAMENTO: Integer; FID_TRANSPORTADORA: Integer; FID_TIPO_NOTA_FISCAL: Integer; FID_CLIENTE: Integer; FID_VENDEDOR: Integer; FDATA_VENDA: TDateTime; FDATA_SAIDA: TDateTime; FHORA_SAIDA: String; FNUMERO_FATURA: Integer; FLOCAL_ENTREGA: String; FLOCAL_COBRANCA: String; FVALOR_SUBTOTAL: Extended; FTAXA_COMISSAO: Extended; FVALOR_COMISSAO: Extended; FTAXA_DESCONTO: Extended; FVALOR_DESCONTO: Extended; FVALOR_TOTAL: Extended; FTIPO_FRETE: String; FFORMA_PAGAMENTO: String; FVALOR_FRETE: Extended; FVALOR_SEGURO: Extended; FOBSERVACAO: String; FSITUACAO: String; //Transientes FTransportadoraNome: String; FTipoNotaFiscalModelo: String; FClienteNome: String; FVendedorNome: String; FVendaCondicoesPagamentoNome: String; FVendaOrcamentoCabecalhoCodigo: String; FTransportadoraVO: TViewPessoaTransportadoraVO; FTipoNotaFiscalVO: TNotaFiscalTipoVO; FClienteVO: TViewPessoaClienteVO; FVendedorVO: TVendedorVO; FVendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO; FVendaOrcamentoCabecalhoVO: TVendaOrcamentoCabecalhoVO; FVendaComissaoVO: TVendaComissaoVO; FListaVendaDetalheVO: TObjectList<TVendaDetalheVO>; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_VENDA_ROMANEIO_ENTREGA', 'Id Venda Romaneio Entrega', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendaRomaneioEntrega: Integer read FID_VENDA_ROMANEIO_ENTREGA write FID_VENDA_ROMANEIO_ENTREGA; [TColumn('ID_VENDA_ORCAMENTO_CABECALHO', 'Id Venda Orcamento Cabecalho', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendaOrcamentoCabecalho: Integer read FID_VENDA_ORCAMENTO_CABECALHO write FID_VENDA_ORCAMENTO_CABECALHO; [TColumnDisplay('ORCAMENTO_VENDA_CABECALHO.CODIGO', 'Código Orçamento', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'VendaOrcamentoCabecalhoVO.TVendaOrcamentoCabecalhoVO', True)] property VendaOrcamentoCabecalhoCodigo: String read FVendaOrcamentoCabecalhoCodigo write FVendaOrcamentoCabecalhoCodigo; [TColumn('ID_VENDA_CONDICOES_PAGAMENTO', 'Id Venda Condicoes Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendaCondicoesPagamento: Integer read FID_VENDA_CONDICOES_PAGAMENTO write FID_VENDA_CONDICOES_PAGAMENTO; [TColumnDisplay('CONDICOESPAGAMENTO.NOME', 'Condições Pagamento', 100, [ldGrid, ldLookup, ldComboBox], ftString, 'VendaCondicoesPagamentoVO.TVendaCondicoesPagamentoVO', True)] property VendaCondicoesPagamentoNome: String read FVendaCondicoesPagamentoNome write FVendaCondicoesPagamentoNome; [TColumn('ID_TRANSPORTADORA', 'Id Transportadora', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdTransportadora: Integer read FID_TRANSPORTADORA write FID_TRANSPORTADORA; [TColumnDisplay('TRANSPORTADORA.NOME', 'Transportadora Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'ViewPessoaTransportadoraVO.TViewPessoaTransportadoraVO', True)] property TransportadoraNome: String read FTransportadoraNome write FTransportadoraNome; [TColumn('ID_TIPO_NOTA_FISCAL', 'Id Tipo Nota Fiscal', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdTipoNotaFiscal: Integer read FID_TIPO_NOTA_FISCAL write FID_TIPO_NOTA_FISCAL; [TColumnDisplay('NOTAFISCALTIPO.MODELO', 'Tipo Nota Fiscal', 90, [ldGrid, ldLookup, ldComboBox], ftString, 'NotaFiscalTipoVO.TNotaFiscalTipoVO', True)] property TipoNotaFiscalModelo: String read FTipoNotaFiscalModelo write FTipoNotaFiscalModelo; [TColumn('ID_CLIENTE', 'Id Cliente', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE; [TColumnDisplay('CLIENTE.NOME', 'Cliente Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'ViewPessoaClienteVO.TViewPessoaClienteVO', True)] property ClienteNome: String read FClienteNome write FClienteNome; [TColumn('ID_VENDEDOR', 'Id Vendedor', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendedor: Integer read FID_VENDEDOR write FID_VENDEDOR; [TColumnDisplay('VENDEDOR.NOME', 'Vendedor Nome', 300, [ldGrid, ldLookup, ldComboBox], ftString, 'VendedorVO.TVendedorVO', True)] property VendedorNome: String read FVendedorNome write FVendedorNome; [TColumn('DATA_VENDA', 'Data Venda', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataVenda: TDateTime read FDATA_VENDA write FDATA_VENDA; [TColumn('DATA_SAIDA', 'Data Saida', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataSaida: TDateTime read FDATA_SAIDA write FDATA_SAIDA; [TColumn('HORA_SAIDA', 'Hora Saida', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraSaida: String read FHORA_SAIDA write FHORA_SAIDA; [TColumn('NUMERO_FATURA', 'Numero Fatura', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property NumeroFatura: Integer read FNUMERO_FATURA write FNUMERO_FATURA; [TColumn('LOCAL_ENTREGA', 'Local Entrega', 450, [ldGrid, ldLookup, ldCombobox], False)] property LocalEntrega: String read FLOCAL_ENTREGA write FLOCAL_ENTREGA; [TColumn('LOCAL_COBRANCA', 'Local Cobranca', 450, [ldGrid, ldLookup, ldCombobox], False)] property LocalCobranca: String read FLOCAL_COBRANCA write FLOCAL_COBRANCA; [TColumn('VALOR_SUBTOTAL', 'Valor Subtotal', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorSubtotal: Extended read FVALOR_SUBTOTAL write FVALOR_SUBTOTAL; [TColumn('TAXA_COMISSAO', 'Taxa Comissao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaComissao: Extended read FTAXA_COMISSAO write FTAXA_COMISSAO; [TColumn('VALOR_COMISSAO', 'Valor Comissao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorComissao: Extended read FVALOR_COMISSAO write FVALOR_COMISSAO; [TColumn('TAXA_DESCONTO', 'Taxa Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; [TColumn('VALOR_DESCONTO', 'Valor Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO; [TColumn('VALOR_TOTAL', 'Valor Total', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; [TColumn('TIPO_FRETE', 'Tipo Frete', 8, [ldGrid, ldLookup, ldCombobox], False)] property TipoFrete: String read FTIPO_FRETE write FTIPO_FRETE; [TColumn('FORMA_PAGAMENTO', 'Forma Pagamento', 8, [ldGrid, ldLookup, ldCombobox], False)] property FormaPagamento: String read FFORMA_PAGAMENTO write FFORMA_PAGAMENTO; [TColumn('VALOR_FRETE', 'Valor Frete', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE; [TColumn('VALOR_SEGURO', 'Valor Seguro', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO; [TColumn('OBSERVACAO', 'Observacao', 450, [ldGrid, ldLookup, ldCombobox], False)] property Observacao: String read FOBSERVACAO write FOBSERVACAO; [TColumn('SITUACAO', 'Situacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property Situacao: String read FSITUACAO write FSITUACAO; //Transientes [TAssociation('ID', 'ID_TRANSPORTADORA')] property TransportadoraVO: TViewPessoaTransportadoraVO read FTransportadoraVO write FTransportadoraVO; [TAssociation('ID', 'ID_CLIENTE')] property ClienteVO: TViewPessoaClienteVO read FClienteVO write FClienteVO; [TAssociation('ID', 'ID_VENDEDOR')] property VendedorVO: TVendedorVO read FVendedorVO write FVendedorVO; [TAssociation('ID', 'ID_VENDA_CONDICOES_PAGAMENTO')] property VendaCondicoesPagamentoVO: TVendaCondicoesPagamentoVO read FVendaCondicoesPagamentoVO write FVendaCondicoesPagamentoVO; [TAssociation('ID', 'ID_TIPO_NOTA_FISCAL')] property TipoNotaFiscalVO: TNotaFiscalTipoVO read FTipoNotaFiscalVO write FTipoNotaFiscalVO; [TAssociation('ID', 'ID_VENDA_ORCAMENTO_CABECALHO')] property VendaOrcamentoCabecalhoVO: TVendaOrcamentoCabecalhoVO read FVendaOrcamentoCabecalhoVO write FVendaOrcamentoCabecalhoVO; [TAssociation('ID', 'ID_VENDA_CABECALHO')] property VendaComissaoVO: TVendaComissaoVO read FVendaComissaoVO write FVendaComissaoVO; [TManyValuedAssociation('ID_VENDA_CABECALHO', 'ID')] property ListaVendaDetalheVO: TObjectList<TVendaDetalheVO> read FListaVendaDetalheVO write FListaVendaDetalheVO; end; implementation constructor TVendaCabecalhoVO.Create; begin inherited; FTransportadoraVO := TViewPessoaTransportadoraVO.Create; FTipoNotaFiscalVO := TNotaFiscalTipoVO.Create; FClienteVO := TViewPessoaClienteVO.Create; FVendedorVO := TVendedorVO.Create; FVendaCondicoesPagamentoVO := TVendaCondicoesPagamentoVO.Create; FVendaOrcamentoCabecalhoVO := TVendaOrcamentoCabecalhoVO.Create; FVendaComissaoVO := TVendaComissaoVO.Create; FListaVendaDetalheVO := TObjectList<TVendaDetalheVO>.Create; end; destructor TVendaCabecalhoVO.Destroy; begin FreeAndNil(FTransportadoraVO); FreeAndNil(FTipoNotaFiscalVO); FreeAndNil(FClienteVO); FreeAndNil(FVendedorVO); FreeAndNil(FVendaCondicoesPagamentoVO); FreeAndNil(FVendaOrcamentoCabecalhoVO); FreeAndNil(FVendaComissaoVO); FreeAndNil(FListaVendaDetalheVO); inherited; end; initialization Classes.RegisterClass(TVendaCabecalhoVO); finalization Classes.UnRegisterClass(TVendaCabecalhoVO); end.
unit uhistory; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ValEdit, CheckLst, ExtCtrls, StdCtrls; type { TFrmHistory } TFrmHistory = class(TForm) CheckListBox1: TCheckListBox; Edit1: TEdit; lbHistory: TLabel; Panel1: TPanel; procedure CheckListBox1ItemClick(Sender: TObject; Index: integer); procedure CheckListBox1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CheckListBox1SelectionChange(Sender: TObject; User: boolean); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Limpa; private public procedure Add( cStr: String ); end; var FrmHistory: TFrmHistory; implementation {$R *.lfm} { TFrmHistory } procedure TFrmHistory.FormCreate(Sender: TObject); begin if FileExists( ExtractFilePath( Application.ExeName ) + 'history.sys' ) then begin CheckListBox1.Items.LoadFromFile( ExtractFilePath( Application.ExeName ) + 'history.sys' ); end; end; procedure TFrmHistory.FormShow(Sender: TObject); var i: integer; begin for i:= 0 to CheckListBox1.Items.count-1 do begin ChecklistBox1.Checked[i]:= false; end; end; procedure TFrmHistory.CheckListBox1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i: Integer; begin lbHistory.caption:= ''; if Key = 13 then begin if CheckListBox1.SelCount > 0 then begin for i:= 0 to CheckListBox1.Items.count-1 do begin if CheckListBox1.Selected[i] then lbHistory.caption:= CheckListBox1.Items[i]; end; end; ModalResult:= mrOk; end else if Key = 10 then ModalResult:= mrOk else if Key = 27 then ModalResult:= mrCancel; end; procedure TFrmHistory.CheckListBox1SelectionChange(Sender: TObject; User: boolean); var i: integer; begin for i:= 0 to CheckListBox1.Items.count-1 do begin if CheckListBox1.Checked[i] then lbHistory.caption:= CheckListBox1.Items[i]; end; end; procedure TFrmHistory.CheckListBox1ItemClick(Sender: TObject; Index: integer); begin end; procedure TFrmHistory.Limpa; begin CheckListBox1.Items.Clear; CheckListBox1.Items.SaveToFile( ExtractFilePath( Application.ExeName ) + 'history.sys' ); end; procedure TFrmHistory.Add( cStr: String ); var lMore: Boolean; begin lMore:= False; if CheckListBox1.Items.count >0 then begin lMore:= True; end; if not lMore then CheckListBox1.Items.Insert( 0, cStr ) else if ( trim( CheckListBox1.Items[0] ) <> trim( cStr ) ) then CheckListBox1.Items.Insert( 0, cStr ); CheckListBox1.Items.SaveToFile( ExtractFilePath( Application.ExeName ) + 'history.sys' ); end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.ListBox; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.UxTheme, Winapi.GDIPOBJ, Vcl.Graphics, Vcl.Controls, {$ELSE} SysUtils, Windows, Messages, Classes, Controls, Graphics, CommCtrl, Themes, UxTheme, DwmApi, PNGImage, StdCtrls, Winapi.GDIPOBJ, {$ENDIF} NTS.Code.Common.Types, UI.Aero.Core.BaseControl, UI.Aero.Core.Images, UI.Aero.Core.CustomControl.Animation, UI.Aero.Globals, UI.Aero.Core; type TAeroListItem = Class; TAeroItems = Class; TBaseAeroListBox = Class; TAeroListItem = class(TCollectionItem) Private ItemRect: TRect; AParent: TBaseAeroListBox; fText: String; fImage: TImageFileName; fData: Integer; fsTag: String; fTag: Integer; procedure SetImage(const Value: TImageFileName); Function GetDrawState: Integer; Protected ImageData: TBitmap; procedure DrawItem(const PaintDC: hDC; X,Y: Integer); procedure PaintItem(const ACanvas: TCanvas; X,Y: Integer); public Constructor Create(Collection: TCollection); override; Destructor Destroy; override; Published property Text: String Read fText Write fText; property Image: TImageFileName Read fImage Write SetImage; property Data: Integer Read fData Write fData; property Tag: Integer Read fTag Write fTag; property sTag: String Read fsTag Write fsTag; end; TAeroItems = Class(TCollection) private FOwner: TBaseAeroListBox; function GetItem(Index: Integer): TAeroListItem; procedure SetItem(Index: Integer; const Value: TAeroListItem); Public function Add: TAeroListItem; Function Owner: TBaseAeroListBox; Constructor Create(AOwner: TBaseAeroListBox); Virtual; Property Items[Index: Integer]: TAeroListItem read GetItem write SetItem; default; End; TItemChangeEvent = procedure(Sender: TBaseAeroListBox; AItemIndex: Integer) of object; TBaseAeroListBox = Class(TCustomAeroControlWithAnimation) private fBackGround: BooLean; fTextGlow: BooLean; fItemWidth, fItemHeight, fItemsInWidth, fItemsInHeight, fItemsOnPage, WidthSpaseSize, HeightSpaseSize, fCurrentPage, fHightLightItem, fItemIndex, fDownItem, fPageCount: Integer; fOnItemDblClick: TItemChangeEvent; fOnItemChange: TItemChangeEvent; fOnCalculatePages: TNotifyEvent; fItems: TAeroItems; fHightLightCursor, fNoramlCursor: TCursor; procedure SetItems(const Value: TAeroItems); procedure SetItemSize(const Index, Value: Integer); procedure SetCurrentPage(const Value: Integer); procedure SetItemIndex(const Value: Integer); procedure SetBackGround(const Value: BooLean); procedure SetTextGlow(const Value: BooLean); protected procedure CalculatePages; function GetThemeClassName: PWideChar; override; procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure Click; override; procedure DblClick; override; procedure Resize; override; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; public Constructor Create(AOwner: TComponent); OverRide; Destructor Destroy; OverRide; published property TabStop Default True; property Items: TAeroItems Read fItems Write SetItems; property ItemWidth: Integer Index 0 Read fItemWidth Write SetItemSize Default 154; property ItemHeight: Integer Index 1 Read fItemHeight Write SetItemSize Default 108; property ItemsOnPage: Integer Read fItemsOnPage; property CurrentPage: Integer Read fCurrentPage Write SetCurrentPage Default 0; property HightLightItem: Integer Read fHightLightItem; property ItemIndex: Integer Read fItemIndex Write SetItemIndex Default -1; property Pages: Integer Read fPageCount; property BackGround: BooLean Read fBackGround Write SetBackGround Default False; property TextGlow: BooLean Read fTextGlow Write SetTextGlow Default False; property HightLightCursor: TCursor Read fHightLightCursor Write fHightLightCursor Default crDefault; Property OnItemChange: TItemChangeEvent Read fOnItemChange Write fOnItemChange; Property OnItemDblClick: TItemChangeEvent Read fOnItemDblClick Write fOnItemDblClick; Property OnCalculatePages: TNotifyEvent Read fOnCalculatePages Write fOnCalculatePages; end; TAeroListBox = Class(TBaseAeroListBox) protected function GetRenderState: TARenderConfig; OverRide; procedure RenderState(const PaintDC: hDC; var Surface: TGPGraphics; var RConfig: TARenderConfig; const DrawState: Integer); OverRide; procedure ClassicRender(const ACanvas: TCanvas; const DrawState: Integer); OverRide; procedure DrawPage(const PaintDC: hDC;const APageIndex: Integer); procedure PaintPage(const ACanvas: TCanvas;const APageIndex: Integer); procedure PostRender(const Surface: TCanvas; const RConfig: TARenderConfig; const DrawState: Integer); override; end; implementation Uses UI.Aero.Window; { TAeroListItem } Constructor TAeroListItem.Create(Collection: TCollection); begin Inherited Create(Collection); AParent:= TAeroItems(Collection).Owner; ItemRect:= Rect(0,0,0,0); fText:= 'Item '+IntToStr(Index); ImageData:= nil; fData:= 0; fTag:= 0; fsTag:= ''; end; Destructor TAeroListItem.Destroy; begin if Assigned(ImageData) then ImageData.Free; Inherited Destroy; end; function TAeroListItem.GetDrawState: Integer; function Get_LISS_HOTSELECTED: Integer; begin if TAeroWindow.RunWindowsVista then Result:= LISS_HOTSELECTED else Result:= LIS_HOT; end; begin if AParent.ItemIndex = Index then begin if AParent.HightLightItem = Index then Result:= Get_LISS_HOTSELECTED else if AParent.Focused then Result:= LIS_SELECTED else Result:= LIS_SELECTEDNOTFOCUS; end else if AParent.HightLightItem = Index then Result:= LIS_HOT else Result:= LIS_NORMAL; end; procedure TAeroListItem.DrawItem(const PaintDC: hDC; X, Y: Integer); var fState: Integer; procedure DrawItemText; Const TextFormat = (DT_SINGLELINE or DT_VCENTER or DT_CENTER); var TextRect: TRect; begin TextRect:= ItemRect; if Assigned(ImageData) then TextRect.Top:= TextRect.Top+ImageData.Height+4; AeroCore.RenderText(PaintDC,AParent.ThemeData,LVP_LISTITEM,fState,AParent.Font,TextFormat,TextRect,fText,AParent.TextGlow); end; procedure DrawImage; var ImgPos: TPoint; begin ImgPos.Y:= Y+2; ImgPos.X:= X+( (AParent.ItemWidth div 2)-(ImageData.Width div 2) ); AeroPicture.Draw(PaintDC,ImageData,ImgPos); end; begin ItemRect:= Bounds(X,Y,AParent.ItemWidth,AParent.ItemHeight); fState:= GetDrawState; if fState <> LIS_NORMAL then DrawThemeBackground(AParent.ThemeData,PaintDC,LVP_LISTITEM,fState,ItemRect,@ItemRect); if Assigned(ImageData) then DrawImage; if fText <> '' then DrawItemText; end; procedure TAeroListItem.PaintItem(const ACanvas: TCanvas; X, Y: Integer); var fState: Integer; procedure SetPaintColor(APen,ABrush: TColor); begin ACanvas.Pen.Color:= APen; ACanvas.Brush.Color:= ABrush; ACanvas.Rectangle(ItemRect); end; procedure DrawImage; var ImgPos: TPoint; begin ImgPos.Y:= Y+2; ImgPos.X:= X+( (AParent.ItemWidth div 2)-(ImageData.Width div 2) ); AeroPicture.Draw(ACanvas.Handle,ImageData,ImgPos); end; procedure DrawItemText; Const TextFormat = (DT_SINGLELINE or DT_VCENTER or DT_CENTER); var TextRect: TRect; begin TextRect:= ItemRect; if Assigned(ImageData) then TextRect.Top:= TextRect.Top+ImageData.Height+4; AeroCore.RenderText(ACanvas.Handle,AParent.Font,TextFormat,TextRect,fText); end; begin ItemRect:= Bounds(X,Y,AParent.ItemWidth,AParent.ItemHeight); fState:= GetDrawState; case fState of // LIS_NORMAL: SetPaintColor(clWindow,clWindow); LIS_HOT, LISS_HOTSELECTED: SetPaintColor(clHighlight,clWindow); LIS_SELECTED, LIS_SELECTEDNOTFOCUS: SetPaintColor(clActiveBorder,clWindow); end; if Assigned(ImageData) then DrawImage; if fText <> '' then DrawItemText; end; procedure TAeroListItem.SetImage(const Value: TImageFileName); begin if fImage <> Value then begin fImage:= Value; if Assigned(ImageData) then ImageData.Free; ImageData:= AeroPicture.LoadImage(fImage); end; end; { TAeroItems } function TAeroItems.Add: TAeroListItem; begin Result:= TAeroListItem(Inherited Add); end; Constructor TAeroItems.Create(AOwner: TBaseAeroListBox); begin Inherited Create(TAeroListItem); FOwner:= AOwner; end; function TAeroItems.GetItem(Index: Integer): TAeroListItem; begin Result:= TAeroListItem(Inherited GetItem(Index)); end; function TAeroItems.Owner: TBaseAeroListBox; begin Result:= FOwner; end; procedure TAeroItems.SetItem(Index: Integer; const Value: TAeroListItem); begin Inherited SetItem(Index, Value); end; { TBaseAeroListBox } Constructor TBaseAeroListBox.Create(AOwner: TComponent); begin Inherited Create(AOwner); fItems:= TAeroItems.Create(Self); fItemWidth:= 154; fItemHeight:= 108; fCurrentPage:= 0; fHightLightItem:= -1; fItemIndex:= -1; fDownItem:= -1; fPageCount:= 0; fOnItemChange:= nil; fOnItemDblClick:= nil; fOnCalculatePages:= nil; fBackGround:= False; fTextGlow:= False; fHightLightCursor:= crDefault; fNoramlCursor:= Cursor; end; Destructor TBaseAeroListBox.Destroy; begin fItems.Free; Inherited Destroy; end; function TBaseAeroListBox.GetThemeClassName: PWideChar; begin if TAeroWindow.RunWindowsVista then Result:= 'Explorer::ListView' else Result:= 'ListView'; end; procedure TBaseAeroListBox.Click; begin Inherited Click; SetFocus; end; procedure TBaseAeroListBox.CMEnabledChanged(var Message: TMessage); begin Inherited; Invalidate; end; procedure TBaseAeroListBox.DblClick; begin Inherited DblClick; if fHightLightItem <> -1 then begin if Assigned(fOnItemDblClick) then fOnItemDblClick(Self,fHightLightItem); end; end; procedure TBaseAeroListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Inherited MouseDown(Button,Shift,X,Y); if (Button = mbLeft) and (fHightLightItem <> -1) then fDownItem:= fHightLightItem; end; procedure TBaseAeroListBox.MouseMove(Shift: TShiftState; X, Y: Integer); var IndexValue, ItIndex, ItemsOnLine, OldHightLightItem, ItemX, ItemY: Integer; begin Inherited MouseMove(Shift,0,0); if Items.Count > 0 then begin IndexValue:= (fCurrentPage*fItemsOnPage); ItemX:= WidthSpaseSize; ItemY:= HeightSpaseSize; ItemsOnLine:= 0; OldHightLightItem:= fHightLightItem; fHightLightItem:= -1; for ItIndex:=IndexValue to IndexValue+fItemsOnPage do if ItIndex = Items.Count then Break else begin if PtInRect(Items.Items[ItIndex].ItemRect,Point(X,Y)) then begin fHightLightItem:= ItIndex; Break; end; // ItemX:= ItemX+ItemWidth+WidthSpaseSize; Inc(ItemsOnLine); if ItemsOnLine = fItemsInWidth then begin ItemsOnLine:= 0; ItemX:= WidthSpaseSize; ItemY:= ItemY+ItemHeight+HeightSpaseSize; end; end; if OldHightLightItem <> fHightLightItem then Invalidate; end; // For Temp... Leter if fHightLightItem = -1 then Cursor:= fNoramlCursor else if Cursor <> HightLightCursor then begin fNoramlCursor:= Cursor; Cursor:= HightLightCursor; end; end; procedure TBaseAeroListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Inherited MouseUp(Button,Shift,X,Y); if (Button = mbLeft) and (fHightLightItem = fDownItem) then begin fDownItem:= -1; if fHightLightItem <> -1 then ItemIndex:= fHightLightItem; end; end; procedure TBaseAeroListBox.Resize; begin Inherited Resize; CalculatePages; Invalidate; end; procedure TBaseAeroListBox.SetBackGround(const Value: BooLean); begin if fBackGround <> Value then begin fBackGround:= Value; Invalidate; end; end; procedure TBaseAeroListBox.SetCurrentPage(const Value: Integer); begin if fCurrentPage <> Value then begin if Value >= fPageCount+1 then fCurrentPage:= fPageCount else fCurrentPage:= Value; NewAniState:= fCurrentPage; Invalidate; end; end; procedure TBaseAeroListBox.SetItemIndex(const Value: Integer); begin if fItemIndex <> Value then begin fItemIndex:= Value; Invalidate; if Assigned(fOnItemChange) then fOnItemChange(Self,Value); end; end; procedure TBaseAeroListBox.SetItems(const Value: TAeroItems); begin fItems.Assign(Value); Invalidate; end; procedure TBaseAeroListBox.SetItemSize(const Index, Value: Integer); begin case Index of 0: fItemWidth:= Value; 1: fItemHeight:= Value; end; CalculatePages; Invalidate; end; procedure TBaseAeroListBox.SetTextGlow(const Value: BooLean); begin if fTextGlow <> Value then begin fTextGlow:= Value; Invalidate; end; end; procedure TBaseAeroListBox.CalculatePages; var FreeInWidth, FreeInHeight: Integer; begin fItemsInWidth:= Width div fItemWidth; fItemsInHeight:= Height div fItemHeight; FreeInWidth:= Width-(fItemsInWidth*fItemWidth); FreeInHeight:= Height-(fItemsInHeight*fItemHeight); WidthSpaseSize:= FreeInWidth div (fItemsInWidth+1); HeightSpaseSize:= FreeInHeight div (fItemsInHeight+1); if WidthSpaseSize < 4 then begin Dec(fItemsInWidth); FreeInWidth:= Width-(fItemsInWidth*fItemWidth); WidthSpaseSize:= FreeInWidth div (fItemsInWidth+1); end; if HeightSpaseSize < 4 then begin Dec(fItemsInHeight); FreeInHeight:= Height-(fItemsInHeight*fItemHeight); HeightSpaseSize:= FreeInHeight div (fItemsInHeight+1); end; fItemsOnPage:= fItemsInWidth*fItemsInHeight; if (Items.Count = 0) or (fItemsOnPage = 0) then fPageCount:= 0 else fPageCount:= Items.Count div fItemsOnPage; if Assigned(fOnCalculatePages) then fOnCalculatePages(Self); end; { TAeroListBox } function TAeroListBox.GetRenderState: TARenderConfig; begin Result:= []; end; procedure TAeroListBox.RenderState(const PaintDC: hDC; var Surface: TGPGraphics; var RConfig: TARenderConfig; const DrawState: Integer); var bgRect: TRect; begin if fBackGround then begin bgRect:= GetClientRect; DrawThemeBackground(ThemeData,PaintDC,LVP_LISTITEM,LIS_NORMAL,bgRect,@bgRect); end; if Items.Count > 0 then DrawPage(PaintDC,DrawState); end; procedure TAeroListBox.ClassicRender(const ACanvas: TCanvas; const DrawState: Integer); begin ACanvas.Font.Assign(Self.Font); ACanvas.Brush.Color:= clWindow; ACanvas.Pen.Color:= clWindowFrame; ACanvas.Rectangle(GetClientRect); if Items.Count > 0 then PaintPage(ACanvas,DrawState); end; procedure TAeroListBox.PaintPage(const ACanvas: TCanvas; const APageIndex: Integer); var ItIndex,IndexValue, ItemsOnLine, DrawX, DrawY: Integer; begin IndexValue:= (APageIndex*fItemsOnPage); DrawX:= WidthSpaseSize; DrawY:= HeightSpaseSize; ItemsOnLine:= 0; for ItIndex:= 0 to Items.Count-1 do Items.Items[ItIndex].ItemRect:= Bounds(-5,-5,1,1); for ItIndex:=IndexValue to IndexValue+(fItemsOnPage-1) do if ItIndex >= Items.Count then Break else begin Items.Items[ItIndex].PaintItem(ACanvas,DrawX,DrawY); DrawX:= DrawX+ItemWidth+WidthSpaseSize; Inc(ItemsOnLine); if ItemsOnLine = fItemsInWidth then begin ItemsOnLine:= 0; DrawX:= WidthSpaseSize; DrawY:= DrawY+ItemHeight+HeightSpaseSize; end; end; end; procedure TAeroListBox.PostRender(const Surface: TCanvas; const RConfig: TARenderConfig; const DrawState: Integer); begin end; procedure TAeroListBox.DrawPage(const PaintDC: hDC; const APageIndex: Integer); var ItIndex,IndexValue, ItemsOnLine, DrawX, DrawY: Integer; begin SelectObject(PaintDC,Self.Font.Handle); IndexValue:= (APageIndex*fItemsOnPage); DrawX:= WidthSpaseSize; DrawY:= HeightSpaseSize; ItemsOnLine:= 0; for ItIndex:= 0 to Items.Count-1 do Items.Items[ItIndex].ItemRect:= Bounds(-5,-5,1,1); for ItIndex:=IndexValue to IndexValue+(fItemsOnPage-1) do if ItIndex >= Items.Count then Break else begin Items.Items[ItIndex].DrawItem(PaintDC,DrawX,DrawY); DrawX:= DrawX+ItemWidth+WidthSpaseSize; Inc(ItemsOnLine); if ItemsOnLine = fItemsInWidth then begin ItemsOnLine:= 0; DrawX:= WidthSpaseSize; DrawY:= DrawY+ItemHeight+HeightSpaseSize; end; end; end; end.
unit uBombaController; interface uses uBomba, DBClient; type TBombaController = class public function Inserir(oBomba: TBomba; var sError: string): Boolean; function Atualizar(oBomba: TBomba; var sError: string): Boolean; function Excluir(oBomba: TBomba; var sError: string): Boolean; function Consultar(oBomba: TBomba; pFiltro: string; var sError: string): TClientDataSet; procedure ConsultarId(oBomba: TBomba; pFiltro: string; var sError: string); function CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; end; implementation uses uPersistencia, SysUtils; { TBombaController } function TBombaController.Atualizar(oBomba: TBomba; var sError: string): Boolean; begin Result := TPersistencia.Atualizar(oBomba, sError); end; function TBombaController.CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; begin Result := TPersistencia.CarregaLookupChaveEstrangeira(pObjeto, pCampo); end; function TBombaController.Consultar(oBomba: TBomba; pFiltro: string; var sError: string): TClientDataSet; begin Result := TPersistencia.Consultar(oBomba, 'NOME', pFiltro, sError); end; procedure TBombaController.ConsultarId(oBomba: TBomba; pFiltro: string; var sError: string); var ds: TClientDataSet; begin ds := TPersistencia.Consultar(oBomba, 'ID', pFiltro, sError); oBomba.Nome := ds.FieldByName('NOME').AsString; oBomba.Tanque := ds.FieldByName('TANQUE').AsInteger; end; function TBombaController.Excluir(oBomba: TBomba; var sError: string): Boolean; begin Result := TPersistencia.Excluir(oBomba, sError); end; function TBombaController.Inserir(oBomba: TBomba; var sError: string): Boolean; begin Result := TPersistencia.Inserir(oBomba, sError); end; end.
(* Category: SWAG Title: SORTING ROUTINES Original name: 0059.PAS Description: Sort a data file on disk Author: MARIO POLYCARPOU Date: 11-22-95 13:26 *) {$A+,B-,D-,E-,F-,G+,I-,K-,L-,N-,O-,P-,Q-,R-,S-,T-,V-,W-,X-,Y-} {Sorts a data file on disk} {*WARNING*: This program will create two .5Mb files for test purposes. Reduce the constant "Max" to about 100 if you only want a quick look at the program.} PROGRAM DiskSort; USES Dos; {For start/stop time} CONST Max=1000; {Number of records} TYPE OneRecord=RECORD {550 bytes} S:String[20]; {The sorted field} W:Word; {Some other fields..} B:Byte; I:Integer; R:Real; P:Pointer; L:LongInt; X:String; Y:String; END; FileType=File OF OneRecord; {------------------------------------------------} {This routine creates the data file and writes randomly generated records in it for testing.} PROCEDURE CreateDataFile(FileName:String); VAR This:OneRecord; F:FileType; N,X,C:Integer; BEGIN Assign(F,FileName); Rewrite(F); FOR N:=1 TO Max DO BEGIN FillChar(This,SizeOf(This),#0); FOR X:=1 TO 20 DO BEGIN REPEAT C:=Random(100); UNTIL C IN [65..90]; This.S:=This.S+Chr(C); END; Write(F,This); END; Close(F); END; {------------------------------------------------} {This routine sorts the data file and puts the sorted records in the temp file.} PROCEDURE SortDataFile(FileName,TempName:String); VAR Old,This,Saved,Temp:OneRecord; F1,F2:FileType; N1,N2,N3:LongInt; SavedStr:String[20]; {-----------------------------------------------} PROCEDURE CheckIt; {comparison routine} BEGIN IF This.S<SavedStr THEN BEGIN SavedStr:=This.S; Temp:=This; This:=Saved; Saved:=Temp; N3:=Pred(FilePos(F1)); END; END; {-----------------------------------------------} BEGIN Assign(F1,FileName); Reset(F1); Assign(F2,TempName); Rewrite(F2); N1:=0; N2:=FileSize(F1); N3:=0; REPEAT Seek(F1,N1); Read(F1,Old); SavedStr:=Old.S; This:=Old; Saved:=Old; WHILE NOT EOF(F1) DO BEGIN CheckIt; Read(F1,This); END; CheckIt; Seek(F1,N3); Write(F1,Old); Seek(F2,FileSize(F2)); Write(F2,Saved); Inc(N1); UNTIL N1>=N2; Close(F1); Close(F2); END; {------------------------------------------------} VAR S1,S2:String; H,M,S,U:Word; BEGIN Randomize; S1:='MIXED.DAT'; S2:='SORTED.DAT'; Writeln; Writeln('Creating the data file ',S1); CreateDataFile(S1); Writeln; Writeln('Now sorting it as ',S2); GetTime(H,M,S,U); Writeln('Start : ',H,':',M,':',S,'.',U); SortDataFile(S1,S2); GetTime(H,M,S,U); Writeln('Stop : ',H,':',M,':',S,'.',U); END.
unit delphiDatadog.utils; interface uses delphiDatadog.header; function DataTagsToText(Tags: TDataDogTags): string; function DataTagsEventPriorityToText(Priority: TDataDogEventPriority): string; function DataTagsEventAlertToText(AlertType: TDataDogEventAlertType): string; function EscapedMessage(Title: string): string; implementation uses System.SysUtils; function DataTagsToText(Tags: TDataDogTags): string; var I: Integer; Tag: string; begin Result := ''; if Length(Tags) = 0 then Exit; for Tag in Tags do begin if Result.IsEmpty then Result := Tag else Result := Result + ',' + Tag end; Result := '|#' + Result; end; function DataTagsEventPriorityToText(Priority: TDataDogEventPriority): string; begin case Priority of ddLow: Result := 'low'; ddNormal: Result := 'normal'; end; end; function DataTagsEventAlertToText(AlertType: TDataDogEventAlertType): string; begin case AlertType of ddError: Result := 'error'; ddWarning: Result := 'warning'; ddInfo: Result := 'info'; ddSuccess: Result := 'success'; ddUndefined: Result := ''; end; end; function EscapedMessage(Title: string): string; begin Result := Title.Replace('\n', '\\n'); end; end.
// TITLE: Pop3 Demo for Winshoes Pop3 Component // DATE: 8-JULY-1999 // AUTHOR: Hadi Hariri // UNIT NAME: main.pas // FORM NAME: fmMAIN // UTILITY: Demonstrate the user of POP3 component from Winshoes package unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, WinshoeMessage, Winshoes, Pop3Winshoe, Buttons, ExtCtrls, Grids, ComCtrls, fileio; type TfmMAIN = class(TForm) Panel2: TPanel; Label1: TLabel; Label2: TLabel; POP: TWinshoePOP3; Label3: TLabel; Label4: TLabel; edSERVER: TEdit; edACCOUNT: TEdit; edPORT: TEdit; edPASSWORD: TEdit; Panel1: TPanel; btCONNECT: TSpeedButton; btDISCONNECT: TSpeedButton; btDELETE: TSpeedButton; btRETRIEVE: TSpeedButton; sgHEADERS: TStringGrid; StatusBar1: TStatusBar; Msg: TWinshoeMessage; procedure FormCreate(Sender: TObject); procedure btCONNECTClick(Sender: TObject); procedure POPStatus(Sender: TComponent; const sOut: String); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btDISCONNECTClick(Sender: TObject); procedure btDELETEClick(Sender: TObject); procedure btRETRIEVEClick(Sender: TObject); private { Private declarations } procedure RetrievePOPHeaders; procedure ToggleButtons(boolConnected: boolean); public { Public declarations } end; var fmMAIN: TfmMAIN; implementation uses msg; {$R *.DFM} ////////////////////////////////////////////////////////////////// // PROCEDURE: Toggle the buttons depending on the status ////////////////////////////////////////////////////////////////// procedure TfmMAIN.ToggleButtons(boolConnected: boolean); begin btCONNECT.Enabled := not boolConnected ; btDISCONNECT.Enabled := boolConnected ; btDELETE.Enabled := boolConnected ; btRETRIEVE.Enabled := boolConnected ; end; ////////////////////////////////////////////////////////////////// // EVENT: On Form Create ////////////////////////////////////////////////////////////////// procedure TfmMAIN.FormCreate(Sender: TObject); begin // Set the titles for the string grid sgHEADERS.Cells [ 0,0 ] := 'Subject'; sgHEADERS.Cells [ 1,0 ] := 'From'; sgHEADERS.Cells [ 2,0 ] := 'Date'; sgHEADERS.Cells [ 3,0 ] := 'Size (bytes)'; sgHEADERS.Cells [ 4,0 ] := ''; Statusbar1.SimpleText := 'Not connected'; ToggleButtons ( False ); end; ////////////////////////////////////////////////////////////////// // EVENT: On CONNECT click ////////////////////////////////////////////////////////////////// procedure TfmMAIN.btCONNECTClick(Sender: TObject); begin // Check to see params are filled in. if (edSERVER.Text = '') or (edACCOUNT.Text = '') or (edPASSWORD.Text = '') then MessageDlg('Configuration missing',mtError,[mbOk],0) else begin // Set the settings in POP3 POP.Host := edSERVER.Text ; if (edPORT.Text = '') then POP.Port := 110 else POP.Port := StrToInt(edPORT.Text); POP.UserID := edACCOUNT.Text ; POP.Password := edPASSWORD.Text ; POP.Connect ; if POP.Connected then begin ToggleButtons ( True ); // Retrieve headers // Check to see if there are messages if POP.CheckMessages > 0 then RetrievePOPHeaders else MessageDlg('No messages on server',mtInformation,[mbOk],0); end ; end ; end; ////////////////////////////////////////////////////////////////// // EVENT: on POP status change ////////////////////////////////////////////////////////////////// procedure TfmMAIN.POPStatus(Sender: TComponent; const sOut: String); begin Statusbar1.SimpleText := sOut ; end; ////////////////////////////////////////////////////////////////// // PROCEDURE: Retrieves the message headers ////////////////////////////////////////////////////////////////// procedure TfmMAIN.RetrievePOPHeaders; var intIndex: integer ; begin sgHEADERS.RowCount := POP.CheckMessages + 1; for intIndex := 1 to POP.CheckMessages do begin // Clear the message properties Msg.Clear ; // Retrieve message Msg.ExtractAttachments := True ; POP.RetrieveHeader( intIndex, Msg ) ; // Add info to string grid sgHEADERS.Cells [ 0, intIndex ] := Msg.Subject ; sgHEADERS.Cells [ 1, intIndex ] := Msg.From ; sgHEADERS.Cells [ 2, intIndex ] := DateToStr (Msg.Date) ; sgHEADERS.Cells [ 3, intIndex ] := IntToStr(POP.RetrieveSize(intIndex) div 8); sgHEADERS.Cells [ 4, intIndex ] := ''; end ; end; ////////////////////////////////////////////////////////////////// // EVENT: On Close ////////////////////////////////////////////////////////////////// procedure TfmMAIN.FormClose(Sender: TObject; var Action: TCloseAction); begin { if POP.Connected then POP.Disconnect ; }end; ////////////////////////////////////////////////////////////////// // EVENT: On DISCONNECT click ////////////////////////////////////////////////////////////////// procedure TfmMAIN.btDISCONNECTClick(Sender: TObject); begin if POP.Connected then POP.Disconnect ; ToggleButtons ( False ); end; ////////////////////////////////////////////////////////////////// // EVENT: On DELETE button click ////////////////////////////////////////////////////////////////// procedure TfmMAIN.btDELETEClick(Sender: TObject); begin POP.Delete ( sgHEADERS.Row ) ; sgHEADERS.Cells [ 4 , sgHEADERS.Row ] := ' * ' ; end; procedure TfmMAIN.btRETRIEVEClick(Sender: TObject); var intIndex: integer ; begin Msg.Clear ; fmMESSAGE.meBODY.Clear ; fmMESSAGE.lbATTACH.Clear ; POP.Retrieve ( sgHEADERS.Row , Msg ) ; fmMESSAGE.Edit1.Text := Msg.From ; fmMESSAGE.Edit2.Text := Msg.Too.Text ; fmMESSAGE.Edit3.Text := Msg.CCList.Text ; fmMESSAGE.Edit4.Text := Msg.Subject ; fmMESSAGE.meBODY.Lines.Assign(Msg.Text); for intIndex := 0 to Msg.Attachments.Count - 1 do fmMESSAGE.lbATTACH.Items.Add ( Msg.Attachments.Items[intIndex].Filename ) ; fmMESSAGE.ShowModal; end; end.
(*NIM/Nama :Stevanno Hero Leadervand*) (*Nama file :udatasaham.pas*) (*Topik :prosedural pascal*) (*Tanggal :27 April 2016*) (*Deskripsi :mengelola data kepemilikan saham perusahaan dari beberapa pemilik perseorangan*) unit udataSaham; { DEKLARASI TYPE FUNGSI DAN PROSEDUR } interface uses sysutils; const NMax = 100; type dataSaham = record IdPemilik : string; IdPT: string; Nilai: integer; end; tabPemilikSaham = record TSaham : array [1..NMax] of dataSaham; Neff: integer; end; { DEKLARASI FUNGSI DAN PROSEDUR } function EOP (rek : dataSaham) : boolean; { Menghasilkan true jika rek = mark } procedure LoadDataNilai (filename : string; var T : tabPemilikSaham); { I.S. : filename terdefinisi, T sembarang } { F.S. : Tabel T terisi data kepemilikan saham dengan data yang dibaca dari file dg nama = filename T.Neff = 0 jika tidak ada file kosong; T diisi dengan seluruh isi file atau sampai T penuh. } procedure UrutPemilikAsc (var T : tabPemilikSaham); { I.S. : T terdefinisi; T mungkin kosong } { F.S. : Isi tabel T terurut membesar menurut IdPemilik. T tetap jika T kosong. } { Proses : Gunakan salah satu algoritma sorting yang diajarkan di kelas. Tuliskan nama algoritmanya dalam bentuk komentar. } procedure HitungRataRata (T : tabPemilikSaham); { I.S. : T terdefinisi; T mungkin kosong } { F.S. : Menampilkan IdPemilik dan nilai rata-rata kepemilikan saham dalam tabel dengan format: <IdPemilik>=<rata-rata> Nilai rata-rata dibulatkan ke integer terdekat. Gunakan fungsi round. Jika tabel kosong, tuliskan "Data kosong" } { Proses : Menggunakan ide algoritma konsolidasi tanpa separator pada file eksternal, hanya saja diberlakukan pada tabel. } procedure SaveDataNilai (filename : string; T : tabPemilikSaham); { I.S. : T dan filename terdefinisi; T mungkin kosong } { F.S. : Isi tabel T dituliskan pada file dg nama = filename } { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation function EOP (rek : dataSaham) : boolean; begin begin EOP:= (rek.IdPemilik='99999999') and (rek.IdPT='XX9999') and (rek.Nilai=-999); end; end; procedure LoadDataNilai (filename : string; var T : tabPemilikSaham); var inFile : Text; Temp : dataSaham; i : integer; tempIdPemilik, tempIdPT, tempNilai : string; begin // Inisialisasi nilai i:= 0; assign(inFile, filename); reset(inFile); repeat readln(inFile, tempIdPemilik); readln(inFile, tempIdPT); readln(inFile, tempNilai); Temp.IdPemilik:= tempIdPemilik; Temp.IdPT:= tempIdPT; Temp.Nilai:= StrToInt(tempNilai); if not(EOP(Temp)) then begin inc(i); T.TSaham[i]:=Temp; end; until (EOP(Temp)) or (i=NMax); close(inFile); T.Neff:= i; end; procedure UrutPemilikAsc (var T : tabPemilikSaham); var i, pass, idxS : integer; temp : dataSaham; tempIdPemilik, min : longint; begin i:=1; // Selection Sort if (T.Neff > 1) then begin for pass:=1 to (T.Neff-1) do begin temp:= T.TSaham[pass]; val(T.TSaham[i].IdPemilik,min); idxS:= pass; // Search Min for i:=(pass+1) to T.Neff do begin val(T.TSaham[i].IdPemilik,tempIdPemilik); if (tempIdPemilik < min) then begin min:= tempIdPemilik; idxS:= i; end; end; T.TSaham[pass]:= T.TSaham[idxS]; T.TSaham[idxS]:= temp; end; end; end; procedure HitungRataRata (T : tabPemilikSaham); var check : string; i : integer; count, sum, avg : integer; switch : boolean; begin // Inisialisasi nilai i:= 1; if (T.Neff > 0) then begin repeat check:= (T.TSaham[i].IdPemilik); switch:= false; sum:= 0; count:= 0; repeat inc(count); sum:= sum + T.TSaham[i].Nilai; inc(i); switch:= (check <> T.TSaham[i].IdPemilik); until switch or (i=T.Neff); avg:= round(sum / count); writeln(T.TSaham[i-1].IdPemilik,'=',avg); until (i=T.Neff); end; end; procedure SaveDataNilai (filename : string; T : tabPemilikSaham); var outFile : text; i : integer; Mark : dataSaham; tempIdPemilik, tempIdPT, tempNilai : string; begin // Inisialisasi Mark Mark.IdPemilik:= '99999999'; Mark.IdPT:= 'XX9999'; Mark.Nilai:= -999; assign(outFile, filename); rewrite(outFile); // External Write if (T.Neff > 0) then begin for i:=1 to T.Neff do begin tempIdPemilik:= T.TSaham[i].IdPemilik; tempIdPT:= T.TSaham[i].IdPT; tempNilai:= IntToStr(T.TSaham[i].Nilai); writeln(outFile, tempIdPemilik); writeln(outFile, tempIdPT); writeln(outFile, tempNilai); end; end; writeln(outFile, Mark.IdPemilik); writeln(outFile, Mark.IdPT); writeln(outFile, Mark.Nilai); close(outFile); end; end.
// ezBOO - TSuperSubLabel version 1.20 // // http://www.ezboo.com // info@ezboo.com unit SuperSubLabel; interface uses Windows, Classes, Controls, Graphics, StdCtrls; type TSuperSubLabel = class(TLabel) private { Private declarations } procedure DoDrawSuperSubLabel(var Rect: TRect; Flags: Word); protected { Protected declarations } procedure Paint;override; public { Public declarations } published { Published declarations } end; procedure SuperSubLabelOut(Canvas:TCanvas; const aRect:TRect; X, Y:integer; text:String); procedure Register; implementation /////////////////////////////////////////////////////////////////////////////// procedure Register; begin RegisterComponents('Standard',[TSuperSubLabel]); end; /////////////////////////////////////////////////////////////////////////////// function extractCaption(str: String) : string; var i:byte; outstring: string; begin outstring :=''; for i:=1 to length(str) do begin if (str[i] <> '_') and (str[i] <> '^') then outstring := outstring + str[i]; end; extractCaption := outstring; end; /////////////////////////////////////////////////////////////////////////////// procedure TSuperSubLabel.DoDrawSuperSubLabel(var Rect: TRect; Flags: Word); begin Canvas.Font := Font; if not Enabled then Canvas.Font.Color := clGrayText; if Alignment = taCenter then SuperSubLabelOut(Canvas, Rect, trunc( (Rect.Right-Canvas.TextWidth(extractCaption(caption)))/2), Rect.Top, Caption); if Alignment = taLeftJustify then SuperSubLabelOut(Canvas, Rect, Rect.Left, Rect.Top, Caption); if Alignment = taRightJustify then SuperSubLabelOut(Canvas, Rect, Rect.Right-Canvas.TextWidth(extractCaption(caption)), Rect.Top, Caption); end; /////////////////////////////////////////////////////////////////////////////// procedure TSuperSubLabel.Paint; const Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect: TRect; begin with Canvas do begin if not Transparent then begin Brush.Color := Self.Color; Brush.Style := bsSolid; FillRect(ClientRect); end; Brush.Style := bsClear; Rect := ClientRect; DoDrawSuperSubLabel(Rect, (DT_EXPANDTABS or DT_WORDBREAK) or Alignments[Alignment]); end; end; /////////////////////////////////////////////////////////////////////////////// procedure SuperSubLabelOut(Canvas:TCanvas; const aRect:TRect; X, Y:integer; text:String); var i,xx,DefTextHeight:integer; subScript, superScript, Symbol : boolean; DefFont:TFont; begin Canvas.FillRect(aRect); DefFont:=TFont.Create; DefFont.Assign(Canvas.Font); with Canvas do begin xx:=X; for i:=1 to length(text) do begin if text[i-1] = '_' then subScript:=true else subScript:=false; if text[i-1] = '^' then superScript:=true else superScript:=false; if text[i-1] = '|' then Symbol := true else Symbol := false; if (text[i] <> '_' ) and (text[i] <> '^' ) and (text[i] <> '|') then begin if ( subScript ) then begin Canvas.Font.Style := Canvas.Font.Style - [fsUnderline]; Canvas.Font.Height:=Canvas.Font.Height*8 div 10; TextRect(Rect(xx,aRect.Top,xx+TextWidth(text[i]),aRect.Bottom),xx, Y+abs(8*Canvas.Font.Height-10*DefFont.Height) div 10, text[i]); inc(xx,TextWidth(text[i])); end; if ( not subScript) and ( not superScript ) then begin Canvas.Font := DefFont; if (Symbol) then begin DefTextHeight := TextHeight(text[i]); Canvas.Font.Name := 'Symbol'; TextRect(Rect(xx,aRect.Top,xx+TextWidth(text[i]),aRect.Bottom),xx,Y-(TextHeight(text[i])-DefTextHeight),text[i]); end; if Not(Symbol) then TextRect(Rect(xx,aRect.Top,xx+TextWidth(text[i]),aRect.Bottom),xx, Y, text[i]); inc(xx,TextWidth(text[i])); end; if ( superScript ) then begin Canvas.Font.Style := Canvas.Font.Style - [fsUnderline]; Canvas.Font.Height:=Canvas.Font.Height*9 div 10; TextRect(Rect(xx,aRect.Top,xx+TextWidth(text[i]),aRect.Bottom),xx, Y-abs(8*Canvas.Font.Height-10*DefFont.Height) div 20, text[i]); inc(xx,TextWidth(text[i])); end; Canvas.Font:=DefFont; end; end; //for loop end; // with DefFont.Free; end; /////////////////////////////////////////////////////////////////////////////// end.
unit UJSLDefaultConf; interface const JSLOptionsCount = 45; type TJSLConfEntry = record checked: Boolean; key: string; desc: string; end; TJSLConf = array[0..JSLOptionsCount - 1] of TJSLConfEntry; function JSLConfEntry(checked: Boolean; key: string; desc: string): TJSLConfEntry; var DefaultConf: TJSLConf; implementation function JSLConfEntry(checked: Boolean; key: string; desc: string): TJSLConfEntry; begin Result.checked := checked; Result.key := key; Result.desc := desc; end; initialization DefaultConf[0] := JSLConfEntry(True, 'no_return_value', 'function {0} does not always return a value'); DefaultConf[1] := JSLConfEntry(True, 'duplicate_formal', 'duplicate formal argument {0}'); DefaultConf[2] := JSLConfEntry(True, 'equal_as_assign', 'test for equality (==) mistyped as assignment (=)?{0}'); DefaultConf[3] := JSLConfEntry(True, 'var_hides_arg', 'variable {0} hides argument'); DefaultConf[4] := JSLConfEntry(True, 'redeclared_var', 'redeclaration of {0} {1}'); DefaultConf[5] := JSLConfEntry(True, 'anon_no_return_value', 'anonymous function does not always return a value'); DefaultConf[6] := JSLConfEntry(True, 'missing_semicolon', 'missing semicolon'); DefaultConf[7] := JSLConfEntry(True, 'meaningless_block', 'meaningless block; curly braces have no impact'); DefaultConf[8] := JSLConfEntry(True, 'comma_separated_stmts', 'multiple statements separated by commas (use semicolons?)'); DefaultConf[9] := JSLConfEntry(True, 'unreachable_code', 'unreachable code'); DefaultConf[10] := JSLConfEntry(True, 'missing_break', 'missing break statement'); DefaultConf[11] := JSLConfEntry(True, 'missing_break_for_last_case', 'missing break statement for last case in switch'); DefaultConf[12] := JSLConfEntry(True, 'comparison_type_conv', 'comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==)'); DefaultConf[13] := JSLConfEntry(True, 'inc_dec_within_stmt', 'increment (++) and decrement (--) operators used as part of greater statement'); DefaultConf[14] := JSLConfEntry(True, 'useless_void', 'use of the void type may be unnecessary (void is always undefined)'); DefaultConf[15] := JSLConfEntry(True, 'multiple_plus_minus', 'unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs'); DefaultConf[16] := JSLConfEntry(True, 'use_of_label', 'use of label'); DefaultConf[17] := JSLConfEntry(False, 'block_without_braces', 'block statement without curly braces'); DefaultConf[18] := JSLConfEntry(True, 'leading_decimal_point', 'leading decimal point may indicate a number or an object member'); DefaultConf[19] := JSLConfEntry(True, 'trailing_decimal_point', 'trailing decimal point may indicate a number or an object member'); DefaultConf[20] := JSLConfEntry(True, 'octal_number', 'leading zeros make an octal number'); DefaultConf[21] := JSLConfEntry(True, 'nested_comment', 'nested comment'); DefaultConf[22] := JSLConfEntry(True, 'misplaced_regex', 'regular expressions should be preceded by a left parenthesis, assignment, colon, or comma'); DefaultConf[23] := JSLConfEntry(True, 'ambiguous_newline', 'unexpected end of line; it is ambiguous whether these lines are part of the same statement'); DefaultConf[24] := JSLConfEntry(True, 'empty_statement', 'empty statement or extra semicolon'); DefaultConf[25] := JSLConfEntry(False, 'missing_option_explicit', 'the "option explicit" control comment is missing'); DefaultConf[26] := JSLConfEntry(True, 'partial_option_explicit', 'the "option explicit" control comment, if used, must be in the first script tag'); DefaultConf[27] := JSLConfEntry(True, 'dup_option_explicit', 'duplicate "option explicit" control comment'); DefaultConf[28] := JSLConfEntry(True, 'useless_assign', 'useless assignment'); DefaultConf[29] := JSLConfEntry(True, 'ambiguous_nested_stmt', 'block statements containing block statements should use curly braces to resolve ambiguity'); DefaultConf[30] := JSLConfEntry(True, 'ambiguous_else_stmt', 'the else statement could be matched with one of multiple if statements (use curly braces to indicate intent)'); DefaultConf[31] := JSLConfEntry(True, 'missing_default_case', 'missing default case in switch statement'); DefaultConf[32] := JSLConfEntry(True, 'duplicate_case_in_switch', 'duplicate case in switch statements'); DefaultConf[33] := JSLConfEntry(True, 'default_not_at_end', 'the default case is not at the end of the switch statement'); DefaultConf[34] := JSLConfEntry(True, 'legacy_cc_not_understood', 'couldn''t understand control comment using /*@keyword@*/ syntax'); DefaultConf[35] := JSLConfEntry(True, 'jsl_cc_not_understood', 'couldn''t understand control comment using /*jsl:keyword*/ syntax'); DefaultConf[36] := JSLConfEntry(True, 'useless_comparison', 'useless comparison; comparing identical expressions'); DefaultConf[37] := JSLConfEntry(True, 'with_statement', 'with statement hides undeclared variables; use temporary variable instead'); DefaultConf[38] := JSLConfEntry(True, 'trailing_comma_in_array', 'extra comma is not recommended in array initializers'); DefaultConf[39] := JSLConfEntry(True, 'assign_to_function_call', 'assignment to a function call'); DefaultConf[40] := JSLConfEntry(True, 'parseint_missing_radix', 'parseInt missing radix parameter'); DefaultConf[41] := JSLConfEntry(True, 'legacy_control_comments', 'legacy control comments are enabled by default for backward compatibility.'); DefaultConf[42] := JSLConfEntry(False, 'jscript_function_extensions', 'JScript Function Extensions'); DefaultConf[43] := JSLConfEntry(False, 'always_use_option_explicit', 'By default, "option explicit" is enabled on a per-file basis.'); DefaultConf[44] := JSLConfEntry(True, 'lambda_assign_requires_semicolon', 'By default, assignments of an anonymous function to a variable or property (such as a function prototype) must be followed by a semicolon.'); end.
unit PessoaJuridicaDTO; interface uses Atributos, Constantes, Classes, SynCommons, mORMot; type TPessoa_Juridica = class(TSQLRecord) private FID_PESSOA: TID; FCNPJ: RawUTF8; FFANTASIA: RawUTF8; FINSCRICAO_MUNICIPAL: RawUTF8; FINSCRICAO_ESTADUAL: RawUTF8; FDATA_CONSTITUICAO: TDateTime; FTIPO_REGIME: RawUTF8; FCRT: RawUTF8; FSUFRAMA: RawUTF8; published [TColumn('ID_PESSOA','Id Pessoa',[ldGrid, ldLookup],False)] property Id_Pessoa: TID read FID_PESSOA write FID_PESSOA; [TColumn('CNPJ','Cnpj',[ldGrid, ldLookup],False)] property Cnpj: RawUTF8 read FCNPJ write FCNPJ; [TColumn('FANTASIA','Fantasia',[ldGrid, ldLookup],False)] property Fantasia: RawUTF8 read FFANTASIA write FFANTASIA; [TColumn('INSCRICAO_MUNICIPAL','Inscrição Municipal',[ldGrid, ldLookup],False)] property Inscricao_Municipal: RawUTF8 read FINSCRICAO_MUNICIPAL write FINSCRICAO_MUNICIPAL; [TColumn('INSCRICAO_ESTADUAL','Inscrição Estadual',[ldGrid, ldLookup],False)] property Inscricao_Estadual: RawUTF8 read FINSCRICAO_ESTADUAL write FINSCRICAO_ESTADUAL; [TColumn('DATA_CONSTITUICAO','Data Constituição',[ldGrid, ldLookup],False)] property Data_Constituicao: TDateTime read FDATA_CONSTITUICAO write FDATA_CONSTITUICAO; [TColumn('TIPO_REGIME','Tipo Regime',[ldGrid, ldLookup],False)] property Tipo_Regime: RawUTF8 read FTIPO_REGIME write FTIPO_REGIME; [TColumn('CRT','Crt',[ldGrid, ldLookup],False)] property Crt: RawUTF8 read FCRT write FCRT; [TColumn('SUFRAMA','Suframa',[ldGrid, ldLookup],False)] property Suframa: RawUTF8 read FSUFRAMA write FSUFRAMA; end; implementation end.
{*************************************************} {* Базовая форма линейного справочника *} {*************************************************} unit BaseDictUnit; interface uses Windows, forms,Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, MaximizedUnit, StdCtrls, DBCtrls, ComCtrls, ToolWin, ExtCtrls, ImgList, ExtraUnit, DbGridUnit, DB, DataUnit, IBCustomDataSet, IBQuery, IBUpdateSQL, DBGridEh, GFunctions, Menus; type TBaseDictForm = class(TMaximizedForm) ToolPanel: TPanel; ToolBar: TToolBar; Panel: TPanel; GridFrame: TDbGridFrame; StatusBar: TStatusBar; ToolImages: TImageList; RefreshBtn: TToolButton; AddBtn: TToolButton; DelBtn: TToolButton; SaveBtn: TToolButton; CancelBtn: TToolButton; MainQuery: TIBQuery; MainUpdate: TIBUpdateSQL; procedure AddBtnClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure DelBtnClick(Sender: TObject); procedure GridFrameDataSourceDataChange(Sender: TObject; Field: TField); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure RefreshBtnClick(Sender: TObject); procedure SaveBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure GridFrameDataSourceStateChange(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); procedure MainQueryAfterDelete(DataSet: TDataSet); procedure MainQueryAfterPost(DataSet: TDataSet); procedure MainQueryBeforePost(DataSet: TDataSet); procedure MainQueryPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure GridFrameSelectColumnMenuItemClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); protected FReadOnly : Boolean; FAutoCommit : Boolean; FIDFieldName: string; FDoRefresh: boolean; procedure CommonRefresh; virtual; procedure CommonOpen; virtual; procedure CommonCancel; virtual; procedure CommonPost; virtual; function CommonEditState: boolean; virtual; procedure DoDelete; virtual; procedure SetSaveBtns; procedure SetReadOnly(AValue : Boolean);virtual; public fFieldList : String; property AutoCommit : Boolean read FAutoCommit write FAutoCommit; property ReadOnly : Boolean read FReadOnly write SetReadOnly; end; var BaseDictForm: TBaseDictForm; implementation //uses FMainUnit, DepincoFMainUnit; {$R *.dfm} procedure TBaseDictForm.FormCreate(Sender: TObject); begin inherited; FAutoCommit := True; FIDFieldName := 'ID'; //если поле первичного ключа называется иначе, в наследнике присваиваем нужное значение FReadOnly := True; SetReadOnly(False); end; procedure TBaseDictForm.FormShow(Sender: TObject); begin inherited; CommonOpen; FDoRefresh := false; end; procedure TBaseDictForm.FormActivate(Sender: TObject); begin inherited; if FDoRefresh then CommonRefresh; FDoRefresh := true; end; procedure TBaseDictForm.CommonRefresh; begin GridFrame.RefreshGridByID(MainQuery.FindField(FIDFieldName)); end; procedure TBaseDictForm.CommonOpen; begin MainQuery.Close; MainQuery.Open; end; procedure TBaseDictForm.CommonPost; begin if (MainQuery.State in dsEditModes) then begin MainQuery.UpdateRecord; MainQuery.Post; end; end; procedure TBaseDictForm.CommonCancel; begin if (MainQuery.State in dsEditModes) then MainQuery.Cancel; end; function TBaseDictForm.CommonEditState: boolean; begin Result := MainQuery.State in dsEditModes; end; procedure TBaseDictForm.RefreshBtnClick(Sender: TObject); begin if CommonEditState then CommonPost; CommonRefresh; end; procedure TBaseDictForm.AddBtnClick(Sender: TObject); begin if CommonEditState then CommonPost; if ActiveControl<>GridFrame.Grid then //..ActiveControl := GridFrame.Grid; namy GridFrame.Grid.SetFocus; MainQuery.Append; end; procedure TBaseDictForm.DelBtnClick(Sender: TObject); begin DoDelete; end; procedure TBaseDictForm.DoDelete; begin if MainQuery.State = dsInsert then MainQuery.Cancel else begin if not ConfirmDelete('Удалить запись?', MainQuery) then exit; MainQuery.Delete; end; end; procedure TBaseDictForm.SaveBtnClick(Sender: TObject); begin if CommonEditState then CommonPost; end; procedure TBaseDictForm.CancelBtnClick(Sender: TObject); begin if CommonEditState then CommonCancel; end; procedure TBaseDictForm.GridFrameDataSourceDataChange(Sender: TObject; Field: TField); begin DelBtn.Enabled := (not (MainQuery.EOF and MainQuery.BOF)) and ( not ReadOnly); end; procedure TBaseDictForm.GridFrameDataSourceStateChange(Sender: TObject); begin SetSaveBtns; end; procedure TBaseDictForm.SetSaveBtns; var XE: boolean; begin XE := CommonEditState; SaveBtn.Enabled := XE; CancelBtn.Enabled := XE; end; procedure TBaseDictForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:=true; if CommonEditState then begin try CommonPost; except CanClose:=false; end; end; end; procedure TBaseDictForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Shift=[]) then begin case Key of VK_F5: begin RefreshBtn.Click; Key := 0; end; VK_F2: begin SaveBtn.Click; Key := 0; end; end; end; end; procedure TBaseDictForm.FormDestroy(Sender: TObject); begin inherited; if CommonEditState then CommonPost; end; procedure TBaseDictForm.MainQueryAfterDelete(DataSet: TDataSet); begin if FAutoCommit then MainQuery.Transaction.CommitRetaining; end; procedure TBaseDictForm.MainQueryAfterPost(DataSet: TDataSet); begin if FAutoCommit then MainQuery.Transaction.CommitRetaining; end; procedure TBaseDictForm.MainQueryBeforePost(DataSet: TDataSet); begin //обрезание пробелов и превращение пустых строк в NULL TrimAndNullFields(DataSet); //проверка обязательных полей CheckRequiredFields(DataSet); end; procedure TBaseDictForm.MainQueryPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin ProcDBErr(E); ActiveControl := GridFrame.Grid; Action := daAbort; end; procedure TBaseDictForm.GridFrameSelectColumnMenuItemClick( Sender: TObject); begin inherited; GridFrame.SelectColumnMenuItemClick(Sender); end; procedure TBaseDictForm.SetReadOnly(AValue : Boolean); begin if AValue <> FReadOnly then begin AddBtn.Enabled := not AValue; DelBtn.Enabled := not AValue; if AValue then begin GridFrame.Grid.AllowedOperations := []; StatusBar.Panels[0].Text := 'Только для чтения'; GridFrame.DataSource.AutoEdit := False; MainQuery.UpdateObject := nil; end else begin GridFrame.Grid.AllowedOperations := [alopInsertEh, alopUpdateEh, alopDeleteEh, alopAppendEh]; StatusBar.Panels[0].Text := ''; GridFrame.DataSource.AutoEdit := True; MainQuery.UpdateObject := MainUpdate end; FReadOnly := AValue; end; end; procedure TBaseDictForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; // if Application.MainForm is TDepincoFMainForm then // TDepincoFMainform(Application.MainForm).removefromWindowmenu(self); // if Application.MainForm is TFMainForm then // TFMainform(Application.MainForm).removefromWindowmenu(self); end; end.
unit View.Vcl.SortResults; interface uses Vcl.ExtCtrls, Model.SortResults, View.SortResults; type TSortResultsView = class(TInterfacedObject, ISortResultsView) private FPaintbox: TPaintBox; FSortResult: TSortResults; public constructor CreateAndInit(APaintbox: TPaintBox; ASortResult: TSortResults); procedure DrawResults; end; implementation uses System.SysUtils, Vcl.Graphics; constructor TSortResultsView.CreateAndInit(APaintbox: TPaintBox; ASortResult: TSortResults); begin inherited Create; FPaintbox := APaintbox; FSortResult := ASortResult; end; procedure TSortResultsView.DrawResults; begin FPaintbox.Canvas.Brush.Style := bsClear; FPaintbox.Canvas.Font.Height := 18; FPaintbox.Canvas.Font.Style := [fsBold]; FPaintbox.Canvas.TextOut(10, 5, FSortResult.Name); FPaintbox.Canvas.Font.Style := []; FPaintbox.Canvas.TextOut(10, 25, Format('items: %d', [FSortResult.DataSize])); FPaintbox.Canvas.TextOut(10, 45, Format('time: %.3f', [FSortResult.ElapsedTime.TotalSeconds])); FPaintbox.Canvas.TextOut(10, 65, Format('swaps: %d', [FSortResult.SwapCounter])); end; end.
unit WPClientDictEditForm; interface uses Windows, Classes, Forms, Controls, StdCtrls, SysUtils, ComCtrls, Grids, Buttons, Messages, Menus; type TDictAttributeRecord = record iAttributeID: integer; sAttributeName: shortstring; sRusAttributeName: shortstring; pvDict: PVariant; end; TDictTableRecord = record iTableID: integer; sTableName: shortstring; darKey: TDictAttributeRecord; arrAttribute: array of TDictAttributeRecord; pvDict: PVariant; end; TfrmDictEdit = class(TForm) lblDictList: TLabel; cmbxDictList: TComboBox; prgbrDictLoad: TProgressBar; strgrCurrentDict: TStringGrid; btnRefresh: TSpeedButton; edtSearch: TEdit; btnFirst: TSpeedButton; btnLast: TSpeedButton; btnInsert: TSpeedButton; btnEdit: TSpeedButton; btnDelete: TSpeedButton; ppmnDictRow: TPopupMenu; mniInsert: TMenuItem; mniEdit: TMenuItem; mniDelete: TMenuItem; mniBreak1: TMenuItem; mniBreak2: TMenuItem; chbxShowIDs: TCheckBox; lblSearch: TLabel; procedure cmbxDictListChange(Sender: TObject); procedure strgrCurrentDictMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure btnFirstClick(Sender: TObject); procedure btnLastClick(Sender: TObject); procedure edtSearchChange(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnInsertClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure chbxShowIDsClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure strgrCurrentDictDblClick(Sender: TObject); private { Private declarations } dtrArray: array[0..3] of TDictTableRecord; dtrCurrentDict: TDictTableRecord; vCurrentDictStructure: variant; sAttrs: string; procedure PrepareFormForCurrentDict(AForm: TForm); procedure InsertCurrentDictRow(var strarrValues: array of string); procedure UpdateCurrentDictRow(var strarrValues: array of string); public { Public declarations } end; var frmDictEdit: TfrmDictEdit; implementation uses StraDictCommon, ClientCommon, WPClientAddDictItemForm; {$R *.DFM} procedure TfrmDictEdit.cmbxDictListChange(Sender: TObject); var vDict: variant; iAttrCount: byte; i, j, iRes: smallint; vQR: variant; begin if cmbxDictList.ItemIndex >= 0 then begin strgrCurrentDict.Visible:= false; for i:=0 to strgrCurrentDict.ColCount - 1 do for j:=0 to strgrCurrentDict.RowCount - 1 do strgrCurrentDict.Cells[i, j]:= ''; strgrCurrentDict.RowCount:= 2; strgrCurrentDict.ColCount:= 2; dtrCurrentDict.iTableID:= GetObjectID(vTableDict, cmbxDictList.Items[cmbxDictList.ItemIndex], 2); dtrCurrentDict.sTableName:= GetObjectName(vTableDict, dtrCurrentDict.iTableID); for i:=0 to high(dtrArray) do if UpperCase(dtrArray[i].sTableName) = UpperCase(dtrCurrentDict.sTableName) then begin if varIsEmpty(dtrArray[i].pvDict^) then begin vDict:=GetDictEx(dtrArray[i].sTableName); dtrArray[i].pvDict^:= vDict; end; dtrCurrentDict:= dtrArray[i]; break; end; sAttrs:=''; iAttrCount:=Length(dtrCurrentDict.arrAttribute); if iAttrCount > 0 then begin strgrCurrentDict.ColCount:=iAttrCount + 1; //все неключевые атрибуты + ключевой sAttrs:=', '; for i:=0 to iAttrCount - 1 do begin sAttrs:=sAttrs + dtrCurrentDict.arrAttribute[i].sAttributeName + ', '; strgrCurrentDict.Cells[i + 1, 0]:= dtrCurrentDict.arrAttribute[i].sRusAttributeName; if strgrCurrentDict.Cells[i + 1, 0] <> '' then strgrCurrentDict.ColWidths[i + 1]:= Length(dtrCurrentDict.arrAttribute[i].sRusAttributeName)*7; end; System.Delete(sAttrs, Length(sAttrs) - 1, 2); end;//if iAttrCount > 0 strgrCurrentDict.Cells[0, 0]:= dtrCurrentDict.darKey.sRusAttributeName; if not chbxShowIDs.Checked then strgrCurrentDict.ColWidths[0]:= 1 else strgrCurrentDict.ColWidths[0]:= 30; iRes:=IServer.SelectRows(dtrCurrentDict.sTableName, dtrCurrentDict.darKey.sAttributeName + sAttrs);//, '', null); if iRes > 0 then begin strgrCurrentDict.RowCount:= iRes + 1; vQR:= IServer.QueryResult; vCurrentDictStructure:= IServer.QueryResultStructure; for i:=0 to varArrayHighBound(vQR, 2) do begin strgrCurrentDict.Cells[0, i + 1]:= GetSingleValue(vQR, 0, i); for j:=0 to iAttrCount - 1 do if not Assigned(dtrCurrentDict.arrAttribute[j].pvDict) or varIsEmpty(dtrCurrentDict.arrAttribute[j].pvDict^) then strgrCurrentDict.Cells[j + 1, i + 1]:= GetSingleValue(vQR, j + 1, i) else strgrCurrentDict.Cells[j + 1, i + 1]:= GetObjectName(dtrCurrentDict.arrAttribute[j].pvDict^, vQR[j + 1, i]); end; end else begin strgrCurrentDict.RowCount:= 2; strgrCurrentDict.ColCount:= 2; for i:=0 to 2 do for j:=0 to 2 do strgrCurrentDict.Cells[i, j]:=''; end; strgrCurrentDict.Visible:=true; end;//if cmbxDictList.ItemIndex >= 0 end; procedure TfrmDictEdit.strgrCurrentDictMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i, iCol, iRow: integer; strlst: TStringList; // iKey: word; begin strgrCurrentDict.MouseToCell(X, Y, iCol, iRow); //Сортировка таблицы по столбцу, если по нему щёлкнули правой кнопкой с шифтом if (Button = mbLeft) and (ssShift in Shift) then begin if (iRow = 0) then begin strlst:= TStringList.Create(); strlst.Capacity:= strgrCurrentDict.RowCount - 1; for i:= 1 to strgrCurrentDict.RowCount - 1 do strlst.Add(strgrCurrentDict.Cells[iCol, i] + ';' + strgrCurrentDict.Cells[0, i] + '=' + strgrCurrentDict.Rows[i].Text); strlst.Sort(); strgrCurrentDict.Hide(); prgbrDictLoad.Position:=0; prgbrDictLoad.Max:= strgrCurrentDict.RowCount - 1; prgbrDictLoad.Step:= 1; try for i:= 1 to strgrCurrentDict.RowCount - 1 do begin strgrCurrentDict.Rows[i].Text:= strlst.Values[strlst.Names[i - 1]]; prgbrDictLoad.StepIt(); prgbrDictLoad.Update(); end; finally strgrCurrentDict.Show(); end;//try strlst.Free(); prgbrDictLoad.Position:=0; end;//if (iRow = 0) end; { if (iLastEditedRow > 0) and (iRow <> iLastEditedRow) then begin iKey:= VK_UP; strgrCurrentDictKeyUp(strgrCurrentDict, iKey, []); end;} end; procedure TfrmDictEdit.btnFirstClick(Sender: TObject); var grFirstCell: TGridRect; begin grFirstCell.Left:= 1; grFirstCell.Right:= 1; grFirstCell.Top:= 1; grFirstCell.Bottom:= 1; strgrCurrentDict.Selection:=grFirstCell; strgrCurrentDict.Perform(WM_KEYDOWN, VK_DOWN, 0); strgrCurrentDict.Perform(WM_KEYDOWN, VK_UP, 0); end; procedure TfrmDictEdit.btnLastClick(Sender: TObject); var grLastCell: TGridRect; begin grLastCell.Left:= 1; grLastCell.Right:= 1; grLastCell.Top:= strgrCurrentDict.RowCount - 1; grLastCell.Bottom:= grLastCell.Top; strgrCurrentDict.Selection:= grLastCell; strgrCurrentDict.Perform(WM_KEYDOWN, VK_UP, 0); strgrCurrentDict.Perform(WM_KEYDOWN, VK_DOWN, 0); end; procedure TfrmDictEdit.edtSearchChange(Sender: TObject); var sSimilar: shortstring; iID: integer; i, j: word; grLastCell: TGridRect; bNoValue: boolean; //наличие такого текста в строке begin if Trim(edtSearch.Text) <> '' then begin //если в строке есть такой текст (вообще) if Pos(ANSIUpperCase(Trim(edtSearch.Text)), strgrCurrentDict.Rows[strgrCurrentDict.Row].Text) > 0 then begin bNoValue:= true; //просматриваем строку по ячейкам - ищем начинающиеся с такого текста for i:= 1 to strgrCurrentDict.ColCount - 1 do if Pos(ANSIUpperCase(Trim(edtSearch.Text)), strgrCurrentDict.Cells[i, strgrCurrentDict.Row]) = 1 then begin bNoValue:= false; break; end; end else bNoValue:= true; if bNoValue then for i:= 1 to strgrCurrentDict.ColCount - 1 do begin sSimilar:= varAsType(GetFirstSimilarName(dtrCurrentDict.pvDict^, Trim(edtSearch.Text), iID, i), varOleStr); if iID > 0 then begin for j:= 1 to strgrCurrentDict.RowCount - 1 do if strgrCurrentDict.Cells[0, j] = IntToStr(iID) then begin grLastCell.Left:= i; grLastCell.Right:= i; grLastCell.Top:= j; grLastCell.Bottom:= j; strgrCurrentDict.Selection:= grLastCell; //если строка не первая, то можно сначала перейти вверх, а потом вниз if j > 1 then begin strgrCurrentDict.Perform(WM_KEYDOWN, VK_UP, 0); strgrCurrentDict.Perform(WM_KEYDOWN, VK_DOWN, 0); end //иначе - вверх перейти нельзя, поэтому вниз-вверх else begin strgrCurrentDict.Perform(WM_KEYDOWN, VK_DOWN, 0); strgrCurrentDict.Perform(WM_KEYDOWN, VK_UP, 0); end; break; end; break; end; end; end; //if Trim(edtSearch.Text) <> '' end; procedure TfrmDictEdit.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close(); end; procedure TfrmDictEdit.btnInsertClick(Sender: TObject); var strarr: array of string; i: byte; begin if (cmbxDictList.ItemIndex >= 0) and(strgrCurrentDict.Row > 0) then begin frmWPClientAddDictItem:= TfrmWPClientAddDictItem.Create(Self); PrepareFormForCurrentDict(frmWPClientAddDictItem as TForm); if frmWPClientAddDictItem.ShowModal() = mrOK then begin SetLength(strarr, strgrCurrentDict.ColCount - 1); if Length(strarr) > 0 then begin for i:= 0 to Length(strarr) - 1 do if (frmWPClientAddDictItem.arrEdit[i] is TEdit) then strarr[i]:=(frmWPClientAddDictItem.arrEdit[i] as TEdit).Text else if (frmWPClientAddDictItem.arrEdit[i] is TComboBox) then strarr[i]:= dtrCurrentDict.arrAttribute[i].pvDict^[0,TComboBox(frmWPClientAddDictItem.arrEdit[i]).ItemIndex]; InsertCurrentDictRow(strarr); end; end; frmWPClientAddDictItem.Free(); frmWPClientAddDictItem:= nil; end; end; procedure TfrmDictEdit.btnEditClick(Sender: TObject); var strarr: array of string; i: byte; begin if (cmbxDictList.ItemIndex >= 0) and(strgrCurrentDict.Row > 0) then begin frmWPClientAddDictItem:= TfrmWPClientAddDictItem.Create(Self); PrepareFormForCurrentDict(frmWPClientAddDictItem as TForm); for i:= 1 to strgrCurrentDict.ColCount - 1 do if (frmWPClientAddDictItem.arrEdit[i - 1] is TEdit) then TEdit(frmWPClientAddDictItem.arrEdit[i - 1]).Text:= strgrCurrentDict.Cells[i, strgrCurrentDict.Row] else if (frmWPClientAddDictItem.arrEdit[i - 1] is TComboBox) then TComboBox(frmWPClientAddDictItem.arrEdit[i - 1]).ItemIndex:= TComboBox(frmWPClientAddDictItem.arrEdit[i - 1]).Items.IndexOf(strgrCurrentDict.Cells[i, strgrCurrentDict.Row]); if frmWPClientAddDictItem.ShowModal() = mrOK then begin SetLength(strarr, strgrCurrentDict.ColCount - 1); if Length(strarr) > 0 then begin for i := 0 to Length(strarr) - 1 do if frmWPClientAddDictItem.arrEdit[i] is TEdit then strarr[i]:=TEdit(frmWPClientAddDictItem.arrEdit[i]).Text else if frmWPClientAddDictItem.arrEdit[i] is TComboBox then strarr[i]:= dtrCurrentDict.arrAttribute[i].pvDict^[0,TComboBox(frmWPClientAddDictItem.arrEdit[i]).ItemIndex]; UpdateCurrentDictRow(strarr); end; end; frmWPClientAddDictItem.Free(); frmWPClientAddDictItem:= nil; end; end; procedure TfrmDictEdit.PrepareFormForCurrentDict(AForm: TForm); var iAttrCount: byte; i: byte; j: integer; begin if AForm is TfrmWPClientAddDictItem then with AForm as TfrmWPClientAddDictItem do begin iAttrCount:= Length(dtrCurrentDict.arrAttribute); if iAttrCount > 0 then begin AForm.ClientHeight:= 40 + iAttrCount * 40; btnOK:= TButton.Create(AForm); with btnOK do begin Parent:= AForm; Height:= 25; Width:= 75; Caption:= 'OK'; Left:= 50; Top:= AForm.ClientHeight - 30; ModalResult:= mrOK; Default:= true; TabOrder:= iAttrCount; end; btnCancel:= TButton.Create(AForm); with btnCancel do begin Parent:= AForm; Height:= 25; Width:= 75; Caption:= 'Отмена'; Left:= 130; Top:= AForm.ClientHeight - 30; ModalResult:= mrCancel; TabOrder:= iAttrCount + 1; end; for i:=0 to iAttrCount - 1 do begin SetLength(arrLabel, i + 1); arrLabel[i]:= TLabel.Create(AForm); //with arrLabel[i] begin arrLabel[i].Parent:= AForm; arrLabel[i].Left:= 5; arrLabel[i].Height:= 15; arrLabel[i].Top:= i * 40 + 5; arrLabel[i].Caption:= dtrCurrentDict.arrAttribute[i].sRusAttributeName; end; SetLength(arrEdit, i + 1); if not Assigned(dtrCurrentDict.arrAttribute[i].pvDict) then begin arrEdit[i]:= TEdit.Create(AForm); arrEdit[i].Parent := AForm; end else begin arrEdit[i]:= TComboBox.Create(AForm); arrEdit[i].Parent := AForm; TComboBox(arrEdit[i]).Style := csDropDownList; if not varIsEmpty(dtrCurrentDict.arrAttribute[i].pvDict^) then for j := 0 to varArrayHighBound(dtrCurrentDict.arrAttribute[i].pvDict^, 2) do TComboBox(arrEdit[i]).Items.Add(dtrCurrentDict.arrAttribute[i].pvDict^[1, j]); end; with arrEdit[i] do begin Left:= 5; Width:= 200; Height:= 20; Top:= i * 40 + 20; TabOrder:= i; end; ActiveControl:= arrEdit[0]; end; end;//if iAttrCount > 0 end; end; procedure TfrmDictEdit.InsertCurrentDictRow(var strarrValues: array of string); var iRes: smallint; vQR: variant; i, iRow: word; vValues, vColumns: variant; begin iRes:= IServer.SelectRows(dtrCurrentDict.sTableName, 'MAX(' + dtrCurrentDict.darKey.sAttributeName + ') + 1', '', null); if iRes > 0 then begin vQR:= IServer.QueryResult; iRow:= strgrCurrentDict.RowCount; strgrCurrentDict.RowCount:= iRow + 1; strgrCurrentDict.Row:= iRow; strgrCurrentDict.Cells[0, iRow]:= IntToStr(GetSingleValue(vQR)); strgrCurrentDict.Col:= 1; vValues:= varArrayCreate([0, strgrCurrentDict.ColCount - 1], varVariant); vValues[0]:= StrToInt(strgrCurrentDict.Cells[0, strgrCurrentDict.Row]); for i:= 1 to strgrCurrentDict.ColCount - 1 do begin if (vCurrentDictStructure[i, 1] = 'I') then vValues[i]:= StrToIntEx(strarrValues[i - 1]) else if (vCurrentDictStructure[i, 1] = 'F') or (vCurrentDictStructure[i, 1] = 'B') or (vCurrentDictStructure[i, 1] = 'N') or (vCurrentDictStructure[i, 1] = 'Y') then vValues[i]:= StrToFloatEx(strarrValues[i - 1]) else vValues[i]:= strarrValues[i - 1]; end; vColumns:= varArrayCreate([0, Length(dtrCurrentDict.arrAttribute)], varOleStr); vColumns[0]:=dtrCurrentDict.darKey.sAttributeName; for i:=0 to Length(dtrCurrentDict.arrAttribute) - 1 do vColumns[i + 1]:=dtrCurrentDict.arrAttribute[i].sAttributeName; iRes:= IServer.InsertRow(dtrCurrentDict.sTableName, vColumns, vValues); if iRes >= 0 then begin MessageBox(Self.Handle, 'Строка успешно добавлена.', 'Сообщение', mb_OK + mb_IconInformation); for i:= 1 to strgrCurrentDict.ColCount - 1 do if not Assigned(dtrCurrentDict.arrAttribute[i-1].pvDict) then strgrCurrentDict.Cells[i, iRow]:= strarrValues[i - 1] else if not varIsEmpty(dtrCurrentDict.arrAttribute[i-1].pvDict^) then strgrCurrentDict.Cells[i, iRow]:= GetObjectName(dtrCurrentDict.arrAttribute[i-1].pvDict^, StrToFloat(strarrValues[i - 1])); // обновляем справочник dtrCurrentDict.pvDict^ := GetDictEx(dtrCurrentDict.sTableName); end else begin MessageBox(Self.Handle, 'Не удалось добавить строку!', 'Сообщение', mb_OK + mb_IconError); exit; end; end; end; procedure TfrmDictEdit.UpdateCurrentDictRow(var strarrValues: array of string); var iRes: smallint; i: word; vValues, vColumns: variant; begin vValues:= varArrayCreate([0, strgrCurrentDict.ColCount - 1], varVariant); vValues[0]:= StrToInt(strgrCurrentDict.Cells[0, strgrCurrentDict.Row]); for i:= 1 to strgrCurrentDict.ColCount - 1 do begin if (vCurrentDictStructure[i, 1] = 'I') then vValues[i]:= StrToIntEx(strarrValues[i - 1]) else if (vCurrentDictStructure[i, 1] = 'F') or (vCurrentDictStructure[i, 1] = 'B') or (vCurrentDictStructure[i, 1] = 'N') or (vCurrentDictStructure[i, 1] = 'Y') then vValues[i]:= StrToFloatEx(strarrValues[i - 1]) else vValues[i]:= strarrValues[i - 1]; end; vColumns:= varArrayCreate([0, Length(dtrCurrentDict.arrAttribute)], varOleStr); vColumns[0]:=dtrCurrentDict.darKey.sAttributeName; for i:=0 to Length(dtrCurrentDict.arrAttribute) - 1 do vColumns[i + 1]:=dtrCurrentDict.arrAttribute[i].sAttributeName; iRes:= IServer.UpdateRow(dtrCurrentDict.sTableName, vColumns, vValues, 'WHERE ' + dtrCurrentDict.darKey.sAttributeName + ' = ' + IntToStr(vValues[0])); if iRes >= 0 then begin MessageBox(Self.Handle, 'Строка успешно изменена.', 'Сообщение', mb_OK + mb_IconInformation); for i := 1 to strgrCurrentDict.ColCount - 1 do if not Assigned(dtrCurrentDict.arrAttribute[i-1].pvDict) then strgrCurrentDict.Cells[i, strgrCurrentDict.Row]:= strarrValues[i - 1] else if not varIsEmpty(dtrCurrentDict.arrAttribute[i-1].pvDict^) then strgrCurrentDict.Cells[i, strgrCurrentDict.Row]:= GetObjectName(dtrCurrentDict.arrAttribute[i-1].pvDict^, StrToFloat(strarrValues[i - 1])); // обновляем справочник dtrCurrentDict.pvDict^ := GetDictEx(dtrCurrentDict.sTableName); end else MessageBox(Self.Handle, 'Не удалось изменить строку', 'Сообщение', mb_OK + mb_IconError); end; procedure TfrmDictEdit.btnDeleteClick(Sender: TObject); var iRes: smallint; begin if (cmbxDictList.ItemIndex >= 0) and(strgrCurrentDict.Row > 0) then if MessageBox(Self.Handle, 'Вы действительно хотите удалить' + #10 + #13 + 'строку справочника?', 'Подтверждение', mb_YesNo + mb_IconWarning) = IDYes then begin iRes:= IServer.DeleteRow(dtrCurrentDict.sTableName, 'WHERE ' + dtrCurrentDict.darKey.sAttributeName + ' = ' + strgrCurrentDict.Cells[0, strgrCurrentDict.Row]); if iRes >= 0 then begin strgrCurrentDict.Rows[strgrCurrentDict.Row].Clear();//(strgrCurrentDict.Row); strgrCurrentDict.RowCount := strgrCurrentDict.RowCount - 1; MessageBox(Self.Handle, 'Строка успешно удалена', 'Сообщение', mb_OK + mb_IconInformation); end else MessageBox(Self.Handle, 'Не удалось удалить строку.'+#13#10 + 'Возможно, на неё ссылаются другие таблицы. ', 'Сообщение', mb_OK + mb_IconError); end; end; procedure TfrmDictEdit.btnRefreshClick(Sender: TObject); begin cmbxDictListChange(cmbxDictList); end; procedure TfrmDictEdit.chbxShowIDsClick(Sender: TObject); begin if not chbxShowIDs.Checked then strgrCurrentDict.ColWidths[0]:= -1 else strgrCurrentDict.ColWidths[0]:= 30; end; procedure TfrmDictEdit.FormCreate(Sender: TObject); var j, m: byte; i, k, l: word; iRes: smallint; vQR: variant; iResult: integer; vDict: variant; begin dtrArray[0].sTableName:='tbl_Taxonomy_Type_dict'; dtrArray[0].pvDict:= @Dicts.vTaxonomyType; dtrArray[1].sTableName:='tbl_Taxonomy_dict'; dtrArray[1].pvDict:= @Dicts.vTaxonomy; dtrArray[2].sTableName:='tbl_Stratigraphy_Name_dict'; dtrArray[2].pvDict:= @Dicts.vStratNames; dtrArray[3].sTableName:='tbl_Stratotype_Region_dict'; dtrArray[3].pvDict:= @Dicts.vStratRegions; Self.Update(); iResult := IServer.SelectRows('SPD_GET_TABLES', varArrayOf(['distinct Table_ID', 'vch_Table_Name', 'vch_Rus_Table_Name']), '',varArrayOf([iClientAppType, iGroupID, 2])); if iResult>0 then vTableDict:=IServer.QueryResult; prgbrDictLoad.Position:=0; if not varIsEmpty(vTableDict) then for j:=0 to High(dtrArray) do begin for i:=0 to varArrayHighBound(vTableDict, 2) do if UpperCase(vTableDict[1, i]) = UpperCase(dtrArray[j].sTableName) then begin cmbxDictList.Items.Add(vTableDict[2, i]); dtrArray[j].iTableID:= vTableDict[0, i]; prgbrDictLoad.StepIt(); prgbrDictLoad.Update(); iRes:= IServer.ExecuteQuery('select att.ATTRIBUTE_ID, att.VCH_ATTRIBUTE_NAME, att.VCH_RUS_ATTRIBUTE_NAME, tbat.num_Is_Key ' + ' from tbl_Attribute att, tbl_Table_Attribute tbat ' + ' where tbat.Table_ID = ' + IntToStr(vTableDict[0, i]) + ' and tbat.Attribute_ID = att.Attribute_ID'); if iRes > 0 then begin vQR:= IServer.QueryResult; m:=0; for k:=0 to iRes - 1 do if varAsType(GetSingleValue(vQR, 3, k), varSmallint) <> 1 then begin SetLength(dtrArray[j].arrAttribute, m + 1); dtrArray[j].arrAttribute[m].iAttributeID:= GetSingleValue(vQR, 0, k); dtrArray[j].arrAttribute[m].sAttributeName:= GetSingleValue(vQR, 1, k); dtrArray[j].arrAttribute[m].sRusAttributeName:= GetSingleValue(vQR, 2, k); if pos('_ID', UpperCase(dtrArray[j].arrAttribute[m].sAttributeName)) > 0 then for l := 0 to j - 1 do if UpperCase(dtrArray[j].arrAttribute[m].sAttributeName) = UpperCase(dtrArray[l].darKey.sAttributeName) then begin vDict:=GetDictEx(dtrArray[l].sTableName); dtrArray[l].pvDict^ := vDict; dtrArray[j].arrAttribute[m].pvDict := dtrArray[l].pvDict; break; end; inc(m); end else begin dtrArray[j].darKey.iAttributeID:= GetSingleValue(vQR, 0, k); dtrArray[j].darKey.sAttributeName:= GetSingleValue(vQR, 1, k); dtrArray[j].darKey.sRusAttributeName:= GetSingleValue(vQR, 2, k); end; prgbrDictLoad.StepIt(); prgbrDictLoad.Update(); end; break; end; prgbrDictLoad.Position:=i; prgbrDictLoad.Update(); end; cmbxDictList.Sorted:=true; prgbrDictLoad.Position:=0; end; procedure TfrmDictEdit.strgrCurrentDictDblClick(Sender: TObject); begin btnEditClick(Sender); end; end.
unit URegFunctions; interface uses Registry, Windows; type TRegFunctions = class private class procedure OpenRegistry(var Registry: TRegistry; Root: HKey; const Key: string; const CanCreate: boolean = true; const ReadOnly: boolean = true); public class function ItemExists(Root: HKEY; const Key, Item: string): boolean; class function DelRegisterItem(Root: HKey; const Key, Item: string): boolean; class function ReadRegisterBool(Root: HKEY; const Key, Item: string; const DefaultReturn: boolean = false; const CanCreate: boolean = false): boolean; class function ReadRegisterInt(Root: HKEY; const Key, Item: string; const DefaultReturn: integer = 0; const CanCreate: boolean = false): integer; class function ReadRegisterStr(Root: HKey; const Key, Item: string; const DefaultReturn: string = ''; const CanCreate: boolean = False): string; class function ReadRegisterDouble(Root: HKEY; const Key, Item: string; const DefaultReturn: double = 0; const CanCreate: boolean = false): double; class function WriteRegisterBool(Root: HKey; const Key, Item: string; const Value: boolean): boolean; class function WriteRegisterInt(Root: HKey; const Key, Item: string; const Value: integer): boolean; class function WriteRegisterStr(Root: HKey; const Key, Item, Value: string): boolean; class function WriteRegisterDouble(Root: HKey; const Key, Item: string; const Value: double): boolean; end; implementation uses UStringFunctions, SysUtils; { TRegFunctions } class function TRegFunctions.DelRegisterItem(Root: HKey; const Key, Item: string): boolean; var Registry: TRegistry; begin Registry := nil; OpenRegistry(Registry, Root, Key, False, False); Result := Registry.DeleteValue(Item); end; class function TRegFunctions.ItemExists(Root: HKEY; const Key, Item: string): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, False); Result := Registry.ValueExists(Item); Registry.CloseKey; FreeAndNil(Registry); except on E:Exception do begin Result := False; if Assigned(Registry) then FreeAndNil(Registry); end; end; end; class procedure TRegFunctions.OpenRegistry(var Registry: TRegistry; Root: HKey; const Key: string; const CanCreate: boolean; const ReadOnly: boolean); begin if not Assigned(Registry) then Registry := TRegistry.Create; Registry.RootKey := Root; if ReadOnly then Registry.OpenKeyReadOnly(Key) else Registry.OpenKey(Key, CanCreate); end; class function TRegFunctions.ReadRegisterBool(Root: HKEY; const Key, Item: string; const DefaultReturn, CanCreate: boolean): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, CanCreate); Result := Registry.ReadBool(Item); Registry.CloseKey; FreeAndNil(Registry); except Result := DefaultReturn; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.ReadRegisterDouble(Root: HKEY; const Key, Item: string; const DefaultReturn: double; const CanCreate: boolean): double; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, CanCreate); Result := Registry.ReadFloat(Item); Registry.CloseKey; FreeAndNil(Registry); except Result := DefaultReturn; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.ReadRegisterInt(Root: HKEY; const Key, Item: string; const DefaultReturn: integer; const CanCreate: boolean): integer; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, CanCreate); Result := Registry.ReadInteger(Item); Registry.CloseKey; FreeAndNil(Registry); except Result := DefaultReturn; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.ReadRegisterStr(Root: HKey; const Key, Item: string; const DefaultReturn: string; const CanCreate: Boolean): string; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, CanCreate); Result := Registry.ReadString(Item); Registry.CloseKey; FreeAndNil(Registry); except on E:Exception do begin Result := ''; if Assigned(Registry) then FreeAndNil(Registry); end; end; if TStringFunctions.IsEmpty(Result) then Result := DefaultReturn; end; class function TRegFunctions.WriteRegisterBool(Root: HKey; const Key, Item: string; const Value: boolean): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, True, False); Registry.WriteBool(Item, Value); Registry.CloseKey; FreeAndNil(Registry); Result := True; except Result := False; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.WriteRegisterDouble(Root: HKey; const Key, Item: string; const Value: double): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, False, False); Registry.WriteFloat(Item, Value); Registry.CloseKey; FreeAndNil(Registry); Result := True; except Result := False; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.WriteRegisterInt(Root: HKey; const Key, Item: string; const Value: integer): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, True, False); Registry.WriteInteger(Item, Value); Registry.CloseKey; FreeAndNil(Registry); Result := True; except Result := False; if Assigned(Registry) then FreeAndNil(Registry); end; end; class function TRegFunctions.WriteRegisterStr(Root: HKey; const Key, Item, Value: string): boolean; var Registry: TRegistry; begin Registry := nil; try OpenRegistry(Registry, Root, Key, True, False); Registry.WriteString(Item, Value); Registry.CloseKey; FreeAndNil(Registry); Result := True; except on E:Exception do begin Result := False; if Assigned(Registry) then FreeAndNil(Registry); end; end; end; end.
//*| -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //*| OPENGL CAMERA //*| --------------------------------------------------------------------------- //*| by Georgy Moshkin //*| //*| email : tmtlib@narod.ru //*| WWW : http://www.tmtlib.narod.ru/ //*| //*| License: Public Domain //*| =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*= unit camera; interface uses OpenGL; // -=( тип, описывающий положение камеры )=- type TCamera=record eye_x,eye_y,eye_z:single; // x,y,z end; // -=( переменная, для хранения параметров камеры )=- var Camera1:TCamera; var CameraElapsed:single; procedure SetThirdPersonCamera(x,y,z,phi:single); // установка камеры в нужное место // процедура устанавливает камеру // в положение "вид от третьего лица" implementation //////////////////////////////////////////////////////////////////////////////// procedure SetThirdPersonCamera(x,y,z,phi:single); // установка камеры в нужное место var need_x,need_y,need_z:single; begin need_x:=x-25*sin(phi*3.14/180); // это что мы хотим получить need_y:=y+10; need_z:=z-25*cos(phi*3.14/180); with Camera1 do // здесь берём что есть и изменяем так, чтобы получить желаемое begin eye_x:=eye_x+(need_x-eye_x)*(0.002*CameraElapsed); eye_y:=eye_y+(need_y-eye_y)*(0.002*CameraElapsed); eye_z:=eye_z+(need_z-eye_z)*(0.002*CameraElapsed); end; gluLookAt(Camera1.eye_x,Camera1.eye_y,Camera1.eye_z, // подаём значения в OpenGL x, need_y-3 ,z, 0,1,0); end; end.
// number of discs, move 1 to n from to dest procedure hanoi(n:integer;from,dest:integer); var other:integer; begin if n = 0 then exit; other:=6-dest-from; hanoi(n-1,from,other); writeln('move ',n,' from ',from, 'to ', dest); hanoi(n-1, other, dest); end; begin end;
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [FOLHA_PARAMETRO] 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 @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit FolhaParametroVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('FOLHA_PARAMETRO')] TFolhaParametroVO = class(TVO) private FID: Integer; FID_EMPRESA: Integer; FCOMPETENCIA: String; FCONTRIBUI_PIS: String; FALIQUOTA_PIS: Extended; FDISCRIMINAR_DSR: String; FDIA_PAGAMENTO: String; FCALCULO_PROPORCIONALIDADE: String; FDESCONTAR_FALTAS_13: String; FPAGAR_ADICIONAIS_13: String; FPAGAR_ESTAGIARIOS_13: String; FMES_ADIANTAMENTO_13: String; FPERCENTUAL_ADIANTAM_13: Extended; FFERIAS_DESCONTAR_FALTAS: String; FFERIAS_PAGAR_ADICIONAIS: String; FFERIAS_ADIANTAR_13: String; FFERIAS_PAGAR_ESTAGIARIOS: String; FFERIAS_CALC_JUSTA_CAUSA: String; FFERIAS_MOVIMENTO_MENSAL: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('COMPETENCIA', 'Competencia', 56, [ldGrid, ldLookup, ldCombobox], False)] property Competencia: String read FCOMPETENCIA write FCOMPETENCIA; [TColumn('CONTRIBUI_PIS', 'Contribui Pis', 8, [ldGrid, ldLookup, ldCombobox], False)] property ContribuiPis: String read FCONTRIBUI_PIS write FCONTRIBUI_PIS; [TColumn('ALIQUOTA_PIS', 'Aliquota Pis', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaPis: Extended read FALIQUOTA_PIS write FALIQUOTA_PIS; [TColumn('DISCRIMINAR_DSR', 'Discriminar Dsr', 8, [ldGrid, ldLookup, ldCombobox], False)] property DiscriminarDsr: String read FDISCRIMINAR_DSR write FDISCRIMINAR_DSR; [TColumn('DIA_PAGAMENTO', 'Dia Pagamento', 16, [ldGrid, ldLookup, ldCombobox], False)] property DiaPagamento: String read FDIA_PAGAMENTO write FDIA_PAGAMENTO; [TColumn('CALCULO_PROPORCIONALIDADE', 'Calculo Proporcionalidade', 8, [ldGrid, ldLookup, ldCombobox], False)] property CalculoProporcionalidade: String read FCALCULO_PROPORCIONALIDADE write FCALCULO_PROPORCIONALIDADE; [TColumn('DESCONTAR_FALTAS_13', 'Descontar Faltas 13', 8, [ldGrid, ldLookup, ldCombobox], False)] property DescontarFaltas13: String read FDESCONTAR_FALTAS_13 write FDESCONTAR_FALTAS_13; [TColumn('PAGAR_ADICIONAIS_13', 'Pagar Adicionais 13', 8, [ldGrid, ldLookup, ldCombobox], False)] property PagarAdicionais13: String read FPAGAR_ADICIONAIS_13 write FPAGAR_ADICIONAIS_13; [TColumn('PAGAR_ESTAGIARIOS_13', 'Pagar Estagiarios 13', 8, [ldGrid, ldLookup, ldCombobox], False)] property PagarEstagiarios13: String read FPAGAR_ESTAGIARIOS_13 write FPAGAR_ESTAGIARIOS_13; [TColumn('MES_ADIANTAMENTO_13', 'Mes Adiantamento 13', 16, [ldGrid, ldLookup, ldCombobox], False)] property MesAdiantamento13: String read FMES_ADIANTAMENTO_13 write FMES_ADIANTAMENTO_13; [TColumn('PERCENTUAL_ADIANTAM_13', 'Percentual Adiantam 13', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property PercentualAdiantam13: Extended read FPERCENTUAL_ADIANTAM_13 write FPERCENTUAL_ADIANTAM_13; [TColumn('FERIAS_DESCONTAR_FALTAS', 'Ferias Descontar Faltas', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasDescontarFaltas: String read FFERIAS_DESCONTAR_FALTAS write FFERIAS_DESCONTAR_FALTAS; [TColumn('FERIAS_PAGAR_ADICIONAIS', 'Ferias Pagar Adicionais', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasPagarAdicionais: String read FFERIAS_PAGAR_ADICIONAIS write FFERIAS_PAGAR_ADICIONAIS; [TColumn('FERIAS_ADIANTAR_13', 'Ferias Adiantar 13', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasAdiantar13: String read FFERIAS_ADIANTAR_13 write FFERIAS_ADIANTAR_13; [TColumn('FERIAS_PAGAR_ESTAGIARIOS', 'Ferias Pagar Estagiarios', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasPagarEstagiarios: String read FFERIAS_PAGAR_ESTAGIARIOS write FFERIAS_PAGAR_ESTAGIARIOS; [TColumn('FERIAS_CALC_JUSTA_CAUSA', 'Ferias Calc Justa Causa', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasCalcJustaCausa: String read FFERIAS_CALC_JUSTA_CAUSA write FFERIAS_CALC_JUSTA_CAUSA; [TColumn('FERIAS_MOVIMENTO_MENSAL', 'Ferias Movimento Mensal', 8, [ldGrid, ldLookup, ldCombobox], False)] property FeriasMovimentoMensal: String read FFERIAS_MOVIMENTO_MENSAL write FFERIAS_MOVIMENTO_MENSAL; //Transientes end; implementation initialization Classes.RegisterClass(TFolhaParametroVO); finalization Classes.UnRegisterClass(TFolhaParametroVO); end.
unit Visao.CadastroTanque; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Visao.FormPadrao, Vcl.StdCtrls, Vcl.ExtCtrls, Controle.CadastroTanque; type TFrmCadastroTanque = class(TFrmPadrao) cbTipoCombustivel: TComboBox; lblCombustivel: TLabel; lblCodBomba: TLabel; edtCodBomba: TEdit; procedure btnGravarClick(Sender: TObject); procedure btnNovoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure edtCodigoKeyPress(Sender: TObject; var Key: Char); procedure cbTipoCombustivelKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var FrmCadastroTanque: TFrmCadastroTanque; Controle: TControleTanque; implementation uses uTipos, Classes.Funcoes; {$R *.dfm} procedure TFrmCadastroTanque.btnGravarClick(Sender: TObject); var vTipoCombustivel: TTipoCombustivel; begin inherited; if SameText(edtCodBomba.Text, EmptyStr) then begin MessageBox(Handle, 'Favor informar um código de bomba associada!', 'Aviso', Mb_ok); Exit; end else begin vTipoCombustivel := TFuncao.iif(cbTipoCombustivel.ItemIndex = 0, tcGasolina, tcDiesel); with Controle.Tanque do begin Codigo := StrToIntDef(edtCodigo.Text, 1); Descricao := edtDescricao.Text; TipoCombustivel := vTipoCombustivel; CodBomba := StrToIntDef(edtCodBomba.Text, 1); end; Controle.SalvarTanque(Evento); end; end; procedure TFrmCadastroTanque.btnNovoClick(Sender: TObject); var vCodigoTanque: Integer; begin inherited; vCodigoTanque := Controle.ObtemNumeroVago; Inc(vCodigoTanque); edtCodigo.Text := IntToStr(vCodigoTanque); end; procedure TFrmCadastroTanque.cbTipoCombustivelKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then Perform(WM_NEXTDLGCTL, 0,0); end; procedure TFrmCadastroTanque.edtCodigoKeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then begin with Controle do begin if CarregaTanque(edtCodigo.Text) then begin with Tanque do begin edtDescricao.Text := Descricao; cbTipoCombustivel.ItemIndex := TFuncao.iif(TipoCombustivel = tcGasolina, 0, 1); edtCodBomba.Text := IntToStr(CodBomba); end; Evento := teNavegacao; AlteraBotoes(4); end; end; end; end; procedure TFrmCadastroTanque.FormCreate(Sender: TObject); begin inherited; if not Assigned(Controle) then Controle := TControleTanque.Create; end; procedure TFrmCadastroTanque.FormDestroy(Sender: TObject); begin inherited; if Assigned(Controle) then FreeAndNil(Controle); end; end.
unit uPokerTest; interface uses DUnitX.TestFramework; type [TestFixture] PokerTest = class(TObject) public [Test] // [Ignore('Comment the "[Ignore]" statement to run the test')] procedure One_hand; [Test] [Ignore] procedure Nothing_vs_one_pair; [Test] [Ignore] procedure Two_pairs; [Test] [Ignore] procedure One_pair_vs_double_pair; [Test] [Ignore] procedure Two_double_pairs; [Test] [Ignore] procedure Double_pair_vs_three; [Test] [Ignore] procedure Two_threes; [Test] [Ignore] procedure Three_vs_straight; [Test] [Ignore] procedure Two_straights; [Test] [Ignore] procedure Straight_vs_flush; [Test] [Ignore] procedure Two_flushes; [Test] [Ignore] procedure Flush_vs_full; [Test] [Ignore] procedure Two_fulls; [Test] [Ignore] procedure Full_vs_square; [Test] [Ignore] procedure Two_squares; [Test] [Ignore] procedure Square_vs_straight_flush; [Test] [Ignore] procedure Two_straight_flushes; [Test] [Ignore] procedure Three_hand_with_tie; [Test] [Ignore] procedure Straight_to_5_against_a_pair_of_jacks; end; implementation uses Generics.Collections, uPoker; procedure PokerTest.One_hand; const hand: string = '5S 4S 7H 8D JC'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange(hand); expectedHands := TList<string>.Create; expectedHands.AddRange(hand); ActualHands := Poker.BestHands(inputHands); Assert.AreEqual(expectedHands.Count,ActualHands.Count); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Nothing_vs_one_pair; const nothing: string = '4S 5H 6S 8D JH'; pairOf4: string = '2S 4H 6S 4D JH'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([nothing, pairOf4]); expectedHands := TList<string>.Create; expectedHands.AddRange(pairOf4); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_pairs; const pairOf2: string = '4S 2H 6D 2D JD'; pairOf4: string = '2S 4H 6S 4D JH'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.create; inputHands.AddRange([pairOf2, pairOf4]); expectedHands := TList<string>.Create; expectedHands.AddRange(pairOf4); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.One_pair_vs_double_pair; const pairOf8: string = '2S 8H 6S 8D JH'; doublePair: string = '4C 5C 4S 8D 5H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([pairOf8, doublePair]); expectedHands := TList<string>.Create; expectedHands.Add(doublePair); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_double_pairs; const doublePair2And8: string = '2D 8H 2S 8D JH'; doublePair4And5: string = '4S 5C 4C 8D 5H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([doublePair2And8, doublePair4And5]); expectedHands := TList<string>.Create; expectedHands.Add(doublePair2And8); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Double_pair_vs_three; const doublePair2And8: string = '2D 8H 2S 8D JH'; threeOf4: string = '4D 5H 4S 8D 4H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([doublePair2And8, threeOf4]); expectedHands := TList<string>.Create; expectedHands.Add(threeOf4); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_threes; const threeOf2: string = '2S 2H 2S 8D JH'; threeOf1: string = '4S AH AS 8D AH'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([threeOf2, threeOf1]); expectedHands := TList<string>.Create; expectedHands.Add(threeOf1); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Three_vs_straight; const threeOf4: string = '4S 5D 4C 8D 4H'; straight: string = '3S 4D 2S 6D 5H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([threeOf4, straight]); expectedHands := TList<string>.Create; expectedHands.Add(straight); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_straights; const straightTo8: string = '4S 6H 7S 8D 5H'; straightTo9: string = '5S 7H 8S 9D 6H'; straightTo1: string = 'AS QH KS TD JH'; straightTo5: string = '4S AH 3S 2D 5H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([straightTo8, straightTo9]); expectedHands := TList<string>.Create; expectedHands.Add(straightTo9); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); inputHands.Clear; inputHands.AddRange([straightTo1, straightTo5]); expectedHands.Clear; expectedHands.Add(straightTo1); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Straight_vs_flush; const straightTo8: string = '4S 6H 7S 8D 5H'; flushTo7: string = '2S 4S 5S 6S 7S'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([straightTo8, flushTo7]); expectedHands := TList<string>.Create; expectedHands.Add(flushTo7); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_flushes; const flushTo8: string = '3H 6H 7H 8H 5H'; flushTo7: string = '2S 4S 5S 6S 7S'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([flushTo8, flushTo7]); expectedHands := TList<string>.Create; expectedHands.Add(flushTo8); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Flush_vs_full; const flushTo8: string = '3H 6H 7H 8H 5H'; full: string = '4S 5H 4S 5D 4H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([flushTo8, full]); expectedHands := TList<string>.Create; expectedHands.Add(full); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_fulls; const fullOf4By9: string = '4H 4S 4D 9S 9D'; fullOf5By8: string = '5H 5S 5D 8S 8D'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([fullOf4By9, fullOf5By8]); expectedHands := TList<string>.Create; expectedHands.Add(fullOf5By8); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Full_vs_square; const full: string = '4S 5H 4S 5D 4H'; squareOf3: string = '3S 3H 2S 3D 3H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([squareOf3,full]); expectedHands := TList<string>.Create; expectedHands.Add(squareOf3); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_squares; const squareOf2: string = '2S 2H 2S 8D 2H'; squareOf5: string = '4S 5H 5S 5D 5H'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([squareOf2, squareOf5]); expectedHands := TList<string>.Create; expectedHands.Add(squareOf5); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Square_vs_straight_flush; const squareOf5: string = '4S 5H 5S 5D 5H'; straightFlushTo9: string = '5S 7S 8S 9S 6S'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([squareOf5, straightFlushTo9]); expectedHands := TList<string>.Create; expectedHands.Add(straightFlushTo9); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Two_straight_flushes; const straightFlushTo8: string = '4H 6H 7H 8H 5H'; straightFlushTo9: string = '5S 7S 8S 9S 6S'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([straightFlushTo8, straightFlushTo9]); expectedHands := TList<string>.Create; expectedHands.Add(straightFlushTo9); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Three_hand_with_tie; const spadeStraightTo9: string = '9S 8S 7S 6S 5S'; diamondStraightTo9: string = '9D 8D 7D 6D 5D'; threeOf4: string = '4D 4S 4H QS KS'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([spadeStraightTo9, threeOf4, diamondStraightTo9]); expectedHands := TList<string>.Create; expectedHands.AddRange([spadeStraightTo9, diamondStraightTo9]); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; procedure PokerTest.Straight_to_5_against_a_pair_of_jacks; const straightTo5: string = '2S 4D 5C 3S AS'; twoJacks: string = 'JD 8D 7D JC 5D'; var expectedHands, inputHands: TList<string>; ActualHands: TList<string>; expectedHandsArray, ActualHandsArray: TArray<string>; i: integer; begin inputHands := TList<string>.Create; inputHands.AddRange([straightTo5, twoJacks]); expectedHands := TList<string>.Create; expectedHands.AddRange(straightTo5); ActualHands := Poker.BestHands(inputHands); expectedHandsArray := expectedHands.ToArray; ActualHandsArray := ActualHands.ToArray; Assert.AreEqual(expectedHands.Count,ActualHands.Count); for i := Low(expectedHandsArray) to High(expectedHandsArray) do Assert.AreEqual(expectedHandsArray[i], ActualHandsArray[i]); end; initialization TDUnitX.RegisterTestFixture(PokerTest); end.
unit BranchUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Mask, ToolEdit, CurrEdit; type TBranchForm = class(TForm) BitBtnSave: TBitBtn; BitBtnCancel: TBitBtn; Label2: TLabel; CurrencyEditBedDay2: TCurrencyEdit; MemoBranchName: TEdit; Label1: TLabel; CurrencyEditBedDay1: TCurrencyEdit; procedure BitBtnCancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure BitBtnSaveClick(Sender: TObject); procedure MemoBranchNameEnter(Sender: TObject); private { Private declarations } public { Public declarations } HospitalNum:Integer; BranchNum:Integer; end; var BranchForm: TBranchForm; implementation uses DataUnit, InsNewMedUnit, InsNewHealthUnit; {$R *.DFM} procedure TBranchForm.BitBtnCancelClick(Sender: TObject); begin Close; end; procedure TBranchForm.FormActivate(Sender: TObject); begin with DataModuleHM.AsaStoredProcShowBranch do begin ParamByName('@BranchNum').Value:=BranchNum; Open; MemoBranchName.Text:=DataModuleHM.AsaStoredProcShowBranchBranchName.Value; CurrencyEditBedDay1.Value:=DataModuleHM.AsaStoredProcShowBranchBedDay1.Value; CurrencyEditBedDay2.Value:=DataModuleHM.AsaStoredProcShowBranchBedDay2.Value; Close; end; // with MemoBranchName.SetFocus; end; procedure TBranchForm.BitBtnSaveClick(Sender: TObject); var new:Boolean; begin new:=BranchNum=-1; if MemoBranchName.Text='' then begin ShowMessage('Введи Название'); MemoBranchName.SetFocus; Exit; end; try // statements to try begin with DataModuleHM do begin AsaSessionHM.StartTransaction; AsaStoredProcRefrBranch.ParamByName('@BranchNum').Value:=BranchNum; AsaStoredProcRefrBranch.ParamByName('@BranchName').Value:=MemoBranchName.Text; AsaStoredProcRefrBranch.ParamByName('@HospitalNum').Value:=HospitalNum; AsaStoredProcRefrBranch.ParamByName('@BedDay1').Value:=CurrencyEditBedDay1.Value; AsaStoredProcRefrBranch.ParamByName('@BedDay2').Value:=CurrencyEditBedDay2.Value; AsaStoredProcRefrBranch.ExecProc; BranchNum:=AsaStoredProcRefrBranch.ParamByName('@BranchNum').Value; AsaSessionHM.Commit; end; if new then with InsNewMedForm.ComboBoxBranch do begin Items.AddObject(MemoBranchName.Text, TObject(BranchNum)); ItemIndex:=Items.Count-1; end; // with end; except on e: Exception do begin ShowMessage('Ошибка '+ e.Message); DataModuleHM.AsaSessionHM.RollBack; end; end; // try/except Close; end; procedure TBranchForm.MemoBranchNameEnter(Sender: TObject); begin LoadKeyboardLayout('00000419', KLF_ACTIVATE); // русский 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.Parser; interface uses DUnitX.TestFramework, Casbin.Parser.Types, Casbin.Core.Defaults; type [TestFixture] TTestParser = class(TObject) private fParser: IParser; procedure checkParserError; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure testLogger; [Test] [TestCase('Simple Header', '[default],default')] [TestCase('EOL in heading', '[def \\'+EOL+'ault],default')] [TestCase('Tab','[def'+#9+'ault],default')] procedure testHeadersInPolicy(const aInput, aExpected: String); [Test] [TestCase('Header 1', '[default],default')] procedure testHeaderAssignment(const aInput, aExpected: string); [Test] [TestCase('Matchers respect spaces', '[matchers]'+sLineBreak+ 'm=r.sub == p.sub'+sLineBreak+ '[request_definition]'+sLineBreak+ '[policy_definition]'+sLineBreak+ '[policy_effect]'+'#'+ 'm=r.sub == p.sub', '#')] procedure testMatchersSection(const aInput, aExpected: string); //We use Policy parser for this test [Test] [TestCase('Header 1', 'p,sub, obj, act#p.sub','#')] procedure testStatementOutputString(const aInput, aExpected: string); [Test] [TestCase('Space before assignment', 'na me = 123'+'#'+'default','#')] procedure testHeadersInConfig(const aInput, aExpected: String); [Test] [TestCase('Double [ in header', '[req[]')] [TestCase('Missed [ in header', 'req]')] [TestCase('Missing section', '[request_definition]'+EOL+ 'r=sub, obj, act'+EOL+ '[policy_definition]')] procedure testErrors(const aInput: String); [Test] //This should be for Policy or Config file only [TestCase('Missing Header', 'r = sub, obj, act'+sLineBreak+'p=sub'+ '#'+'default','#')] [TestCase('Start with EOL', sLineBreak+'r = sub, obj, act#default','#')] [TestCase('Start with multiple EOL', sLineBreak+sLineBreak+sLineBreak+'r = sub, obj, act#default','#')] procedure testFix(const aInput: String; const aExpected: String); [Test] // We use Policy parser for this test // We pass the string as a policy rule (which is in the wrong format) // because we ONLY want to check that the quotes are removed correctly [TestCase ('Has double and single quotes', 'p,r.sub=p.sub||r.sub=''root''||r.sub=""guest"#'+ 'r.sub=p.sub||r.sub=root||r.sub=guest','#')] procedure testFixParseString(const aInput: String; const aExpected: String); //We use Policy parser for this test [Test] [TestCase('Header Only', '[default],[default]')] [TestCase('Header With Statement', '[default]'+sLineBreak+'p,sub,obj,act'+ '#[default]'+sLineBreak+'p,sub,obj,act','#')] [TestCase('Header With Multiple Statement and Sections', '[default]'+sLineBreak+'p,sub,obj,act'+sLineBreak+ '[default]'+sLineBreak+'p,alice,files,delete'+sLineBreak+ 'p,alice,files,read'+sLineBreak+ '#[default]'+sLineBreak+'p,sub,obj,act'+sLineBreak+sLineBreak+ '[default]'+sLineBreak+'p,alice,files,delete'+sLineBreak+ 'p,alice,files,read' ,'#')] [TestCase('Roles Rules','[default]'+sLineBreak+'g,_,_'+sLineBreak+ 'g2,_,_,_'+ '#[default]'+sLineBreak+'g,_,_'+sLineBreak+'g2,_,_,_','#')] procedure testHeaderOutputString(const aInput, aExpected: String); end; implementation uses Casbin.Parser, System.SysUtils, Casbin.Parser.AST.Types, System.Generics.Collections; procedure TTestParser.checkParserError; begin Assert.IsFalse(fParser.Status = psError,'Parsing Error: '+fParser.ErrorMessage); end; procedure TTestParser.Setup; begin end; procedure TTestParser.TearDown; begin end; procedure TTestParser.testLogger; begin fParser:=TParser.Create('', ptModel); Assert.IsNotNull(fParser.Logger); end; procedure TTestParser.testMatchersSection(const aInput, aExpected: string); begin fParser:=TParser.Create(aInput, ptModel); fParser.parse; Assert.AreEqual(4, fParser.Nodes.Headers.Count, 'Header count: '+fParser.ErrorMessage); Assert.AreEqual(1, fParser.Nodes.Headers.Items[0].ChildNodes.Count, 'Child count'+fParser.ErrorMessage); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].ChildNodes.Items[0].toOutputString, 'Assertion'+fParser.ErrorMessage); end; procedure TTestParser.testStatementOutputString(const aInput, aExpected: string); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; checkParserError; Assert.IsTrue(fParser.Nodes.Headers.Count = 1, 'Header count'); Assert.IsTrue(fParser.Nodes.Headers.Items[0].ChildNodes.Count = 1, 'Child count'); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].ChildNodes.Items[0]. AssertionList.Items[0].toOutputString, 'Output String'); fParser:=nil; end; procedure TTestParser.testErrors(const aInput: String); begin fParser:=TParser.Create(aInput, ptModel); fParser.parse; Assert.AreEqual(psError, fParser.Status); fParser:=nil; end; procedure TTestParser.testFix(const aInput: String; const aExpected: String); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; Assert.IsTrue(fParser.Nodes.Headers.Count >= 1); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].Value); fParser:=nil; end; procedure TTestParser.testFixParseString(const aInput, aExpected: String); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; Assert.IsTrue(fParser.Nodes.Headers.Count >= 1); Assert.IsTrue(fParser.Nodes.Headers.Items[0].ChildNodes.Count >= 1); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0]. ChildNodes.Items[0].Value); fParser:=nil; end; procedure TTestParser.testHeaderAssignment(const aInput, aExpected: string); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; checkParserError; Assert.IsTrue(fParser.Nodes.Headers.Count = 1); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].Value); fParser:=nil; end; procedure TTestParser.testHeaderOutputString(const aInput, aExpected: String); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; checkParserError; Assert.AreEqual(trim(aExpected), Trim(fParser.Nodes.toOutputString)); fParser:=nil; end; procedure TTestParser.testHeadersInConfig(const aInput, aExpected: String); begin fParser:=TParser.Create(aInput, ptConfig); fParser.parse; Assert.IsTrue(fParser.Nodes.Headers.Count = 1); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].Value); fParser:=nil; end; procedure TTestParser.testHeadersInPolicy(const aInput, aExpected: String); begin fParser:=TParser.Create(aInput, ptPolicy); fParser.parse; Assert.IsTrue(fParser.Nodes.Headers.Count = 1); Assert.AreEqual(aExpected, fParser.Nodes.Headers.Items[0].Value); fParser:=nil; end; initialization TDUnitX.RegisterTestFixture(TTestParser); end.
unit CVNRUNASSERVICE; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs; type TConvnet2 = class(TService) procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure ServiceExecute(Sender: TService); private { Private declarations } public function GetServiceController: TServiceController; override; { Public declarations } end; var Convnet2: TConvnet2; implementation uses clientUI, CVN_CreateGroup, CVN_FfindGroup, CVN_Ffinduser, CVN_modifyGroupinfo, CVN_PrivateSetup, CVN_PeerOrd, CVN_FConnectionPass, CVN_ViewUserInfo, CVN_FAutoconnection,CVN_messageWin, CVN_faddautouser, CVN_regist, CVN_MessageWindow, CVN_CSYS, CVN_ClientMSG, FrmMainU; {$R *.DFM} procedure ServiceController(CtrlCode: DWord); stdcall; begin Convnet2.Controller(CtrlCode); end; function TConvnet2.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TConvnet2.ServiceStart(Sender: TService; var Started: Boolean); begin if checkrunning then begin Started:=false; exit; end; outputdebugstring('start'); SetThreadLocale( DWORD(Word(SORT_DEFAULT) shl 16) or DWORD(Word(SUBLANG_CHINESE_SIMPLIFIED) shl 10) or DWORD(Word(LANG_CHINESE)) ); Svcmgr.Application.CreateForm(Tfclientui, fclientui); SetActiveLanguage(fclientui); outputdebugstring('start2'); Svcmgr.Application.CreateForm(TfMSGWIN, fMSGWIN); Svcmgr.Application.CreateForm(TfAutoconnection, fAutoconnection); Svcmgr.Application.CreateForm(TfRegist, fRegist); Svcmgr.Application.CreateForm(Tfcreategroup, fcreategroup); Svcmgr.Application.CreateForm(TfindGroup, findGroup); Svcmgr.Application.CreateForm(TfindUser, findUser); Svcmgr.Application.CreateForm(TFModifyGroup, FModifyGroup); Svcmgr.Application.CreateForm(TfPrivateSetup, fPrivateSetup); Svcmgr.Application.CreateForm(TfPeerOrd, fPeerOrd); fpeerOrd.CVN_MSG:=TcvnMSG.Create; outputdebugstring('start3'); Svcmgr.Application.CreateForm(TfNeedPass, fNeedPass); outputdebugstring('start3.1'); Svcmgr.Application.CreateForm(TfUserinfo, fUserinfo); outputdebugstring('start3.2'); Svcmgr.Application.CreateForm(Taddautouser, addautouser); outputdebugstring('start3.3'); // Svcmgr.Application.CreateForm(TFCVNMSG, FCVNMSG); outputdebugstring('start3.4'); Svcmgr.Application.CreateForm(TFrmMain, FrmMain); outputdebugstring('start4'); if fclientui.checkAutoLogin.Checked then begin fclientui.blogin.Click; end; outputdebugstring('start5'); Started:=TRUE; fclientui.Show; { Svcmgr.Application.CreateForm(Tfclientui, fclientui); Svcmgr.Application.CreateForm(TfRegist, fRegist); Svcmgr.Application.CreateForm(Tfcreategroup, fcreategroup); Svcmgr.Application.CreateForm(TfindGroup, findGroup); Svcmgr.Application.CreateForm(TfindUser, findUser); Svcmgr.Application.CreateForm(TFModifyGroup, FModifyGroup); Svcmgr.Application.CreateForm(TfPrivateSetup, fPrivateSetup); Svcmgr.Application.CreateForm(TfMSGWIN, fMSGWIN); Svcmgr.Application.CreateForm(TfPeerOrd, fPeerOrd); Svcmgr.Application.CreateForm(TfNeedPass, fNeedPass); Svcmgr.Application.CreateForm(TfUserinfo, fUserinfo); Svcmgr.Application.CreateForm(TfAutoconnection, fAutoconnection); Svcmgr.Application.CreateForm(Taddautouser, addautouser); {fclientui:=Tfclientui.Create(self); dm4Server:=Tdm4Server.Create(self); dmUpnp:=TdmUpnp.Create(self); fRegist:=TfRegist.Create(self); fcreategroup:=Tfcreategroup.Create(self); findGroup:=TfindGroup.Create(self); findUser:=TfindUser.Create(self); FModifyGroup:=TFModifyGroup.Create(self); fPrivateSetup:=TfPrivateSetup.Create(self); fMSGWIN:=TfMSGWIN.Create(self); fPeerOrd:=TfPeerOrd.Create(self); fNeedPass:=TfNeedPass.Create(self); fUserinfo:=TfUserinfo.Create(self); fAutoconnection:=TfAutoconnection.Create(self); addautouser:=Taddautouser.Create(self);} end; procedure TConvnet2.ServiceStop(Sender: TService; var Stopped: Boolean); begin fclientui.Close; //ÊÍ·Å×ÊÔ´ fpeerOrd.CVN_MSG.Free; stopped:=true; end; procedure TConvnet2.ServiceExecute(Sender: TService); begin while not Terminated do begin Sleep(0); ServiceThread.ProcessRequests(False); end; end; end.
unit RDTPSQLConnectionServer; {GEN} {TYPE SERVER} {ANCESTOR TRDTPProcessor} {IMPLIB RDTPSQLConnectionSErverImplib} {TEMPLATE RDTP_gen_server_template.pas} {RQFILE RDTPSQLConnectionRQs.txt} {CLASS TRDTPSQLConnectionServer} {END} interface uses StorageEngineTypes, RDTPProcessorForMySQL, typex, packet, systemx, betterobject, genericRDTPClient, sysutils, windows, variants, rdtpprocessor, packethelpers, debug, RDTPServerList; type TRDTPSQLConnectionServerBase = class(TRDTPProcessorForMYSQL) private procedure RQ_HANDLE_Test(proc: TRDTPProcessorForMYSQL); procedure RQ_HANDLE_WriteQuery_string(proc: TRDTPProcessorForMYSQL); procedure RQ_HANDLE_ReadyToWriteBehind(proc: TRDTPProcessorForMYSQL); procedure RQ_HANDLE_WriteBehind_string(proc: TRDTPProcessorForMYSQL); procedure RQ_HANDLE_ReadQuery_string(proc: TRDTPProcessorForMYSQL); protected public constructor Create;override; destructor Destroy;override; function RQ_Test():integer;overload;virtual;abstract; function RQ_WriteQuery(sQuery:string):boolean;overload;virtual;abstract; function RQ_ReadyToWriteBehind():boolean;overload;virtual;abstract; procedure RQ_WriteBehind(sQuery:string);overload;virtual;abstract; function RQ_ReadQuery(sQuery:string):TSERowSet;overload;virtual;abstract; function Dispatch: boolean;override; end; procedure LocalDebug(s: string; sfilter: string = ''); implementation uses RDTPSQLConnectionSErverImplib, ImpJunk; //-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x- procedure TRDTPSQLConnectionServerBase.RQ_HANDLE_Test(proc: TRDTPProcessorForMYSQL); var res: integer; begin res := RQ_Test(); WriteintegerToPacket(proc.response, res); end; //-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x- procedure TRDTPSQLConnectionServerBase.RQ_HANDLE_WriteQuery_string(proc: TRDTPProcessorForMYSQL); var res: boolean; sQuery:string; begin GetstringFromPacket(proc.request, sQuery); res := RQ_WriteQuery(sQuery); WritebooleanToPacket(proc.response, res); end; //-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x- procedure TRDTPSQLConnectionServerBase.RQ_HANDLE_ReadyToWriteBehind(proc: TRDTPProcessorForMYSQL); var res: boolean; begin res := RQ_ReadyToWriteBehind(); WritebooleanToPacket(proc.response, res); end; //-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x- procedure TRDTPSQLConnectionServerBase.RQ_HANDLE_WriteBehind_string(proc: TRDTPProcessorForMYSQL); var sQuery:string; begin GetstringFromPacket(proc.request, sQuery); RQ_WriteBehind(sQuery); proc.ForgetResult := true end; //-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-x-xx-x-x-x-x-x-x- procedure TRDTPSQLConnectionServerBase.RQ_HANDLE_ReadQuery_string(proc: TRDTPProcessorForMYSQL); var res: TSERowSet; sQuery:string; begin GetstringFromPacket(proc.request, sQuery); res := RQ_ReadQuery(sQuery); WriteTSERowSetToPacket(proc.response, res); end; { TRDTPSQLConnectionServer } procedure LocalDebug(s: string; sfilter: string = ''); begin Debug.Log(nil, s, sFilter); end; constructor TRDTPSQLConnectionServerBase.create; begin inherited; ServiceName := 'RDTPSQLConnection'; end; destructor TRDTPSQLConnectionServerBase.destroy; begin inherited; end; function TRDTPSQLConnectionServerBase.Dispatch: boolean; var iRQ: integer; begin result := false; iRQ := request.data[0]; request.seqseek(3); case iRQ of 0: begin result := true; // beeper.Beep(100,100); end; //Test $1110: begin {$IFDEF RDTP_LOGGING} LocalDebug('Begin Server Handling of Test','RDTPCALLS'); {$ENDIF} result := true;//set to true BEFORE calling in case of exception RQ_HANDLE_Test(self); {$IFDEF RDTP_LOGGING} LocalDebug('End Server Handling of Test','RDTPCALLS'); {$ENDIF} end; //WriteQuery $1111: begin {$IFDEF RDTP_LOGGING} LocalDebug('Begin Server Handling of WriteQuery','RDTPCALLS'); {$ENDIF} result := true;//set to true BEFORE calling in case of exception RQ_HANDLE_WriteQuery_string(self); {$IFDEF RDTP_LOGGING} LocalDebug('End Server Handling of WriteQuery','RDTPCALLS'); {$ENDIF} end; //ReadyToWriteBehind $1112: begin {$IFDEF RDTP_LOGGING} LocalDebug('Begin Server Handling of ReadyToWriteBehind','RDTPCALLS'); {$ENDIF} result := true;//set to true BEFORE calling in case of exception RQ_HANDLE_ReadyToWriteBehind(self); {$IFDEF RDTP_LOGGING} LocalDebug('End Server Handling of ReadyToWriteBehind','RDTPCALLS'); {$ENDIF} end; //WriteBehind $1113: begin {$IFDEF RDTP_LOGGING} LocalDebug('Begin Server Handling of WriteBehind','RDTPCALLS'); {$ENDIF} result := true;//set to true BEFORE calling in case of exception RQ_HANDLE_WriteBehind_string(self); {$IFDEF RDTP_LOGGING} LocalDebug('End Server Handling of WriteBehind','RDTPCALLS'); {$ENDIF} end; //ReadQuery $1114: begin {$IFDEF RDTP_LOGGING} LocalDebug('Begin Server Handling of ReadQuery','RDTPCALLS'); {$ENDIF} result := true;//set to true BEFORE calling in case of exception RQ_HANDLE_ReadQuery_string(self); {$IFDEF RDTP_LOGGING} LocalDebug('End Server Handling of ReadQuery','RDTPCALLS'); {$ENDIF} end; end; if not result then result := Inherited Dispatch; end; end.