text
stringlengths
14
6.51M
unit LuaWinControl; {$mode delphi} interface uses {$ifdef windows}windows,{$endif} Classes, SysUtils, controls, lua, lualib, lauxlib,LuaHandler, graphics; procedure initializeLuaWinControl; procedure wincontrol_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); implementation uses LuaCaller, luacontrol, luaclass; function wincontrol_getHandle(L: PLua_State): integer; cdecl; begin lua_pushinteger(L, twincontrol(luaclass_getClassObject(L)).Handle); result:=1; end; function wincontrol_getDoubleBuffered(L: PLua_State): integer; cdecl; begin lua_pushboolean(L, twincontrol(luaclass_getClassObject(L)).DoubleBuffered); result:=1; end; function wincontrol_setDoubleBuffered(L: PLua_State): integer; cdecl; begin if lua_gettop(L)=1 then twincontrol(luaclass_getClassObject(L)).DoubleBuffered:=lua_toboolean(L, 1); result:=0; end; function wincontrol_getControlCount(L: PLua_State): integer; cdecl; begin lua_pushinteger(L, twincontrol(luaclass_getClassObject(L)).ControlCount); result:=1; end; function wincontrol_getControl(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; index: integer; begin wincontrol:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin index:=lua_tointeger(L,-1); luaclass_newClass(L, wincontrol.Controls[index]); end else lua_pushnil(L); result:=1; end; function wincontrol_getControlAtPos(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; x,y: integer; paramstart, paramcount: integer; begin wincontrol:=luaclass_getClassObject(L, @paramstart, @paramcount); result:=0; if paramcount>=2 then begin x:=lua_tointeger(L,paramstart); y:=lua_tointeger(L,paramstart+1); luaclass_newClass(L, wincontrol.ControlAtPos(point(x,y),[capfOnlyClientAreas, capfAllowWinControls, capfRecursive])); result:=1; end; end; function wincontrol_getOnEnter(L: PLua_State): integer; cdecl; var c: twincontrol; begin c:=luaclass_getClassObject(L); LuaCaller_pushMethodProperty(L, TMethod(c.OnEnter), 'TNotifyEvent'); result:=1; end; function wincontrol_setOnEnter(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; f: integer; routine: string; lc: TLuaCaller; begin wincontrol:=luaclass_getClassObject(L); result:=0; if lua_gettop(L)>=1 then begin CleanupLuaCall(tmethod(wincontrol.OnEnter)); wincontrol.OnEnter:=nil; if lua_isfunction(L,-1) then begin routine:=Lua_ToString(L,-1); f:=luaL_ref(L,LUA_REGISTRYINDEX); lc:=TLuaCaller.create; lc.luaroutineIndex:=f; wincontrol.OnEnter:=lc.NotifyEvent; end else if lua_isstring(L,-1) then begin routine:=lua_tostring(L,-1); lc:=TLuaCaller.create; lc.luaroutine:=routine; wincontrol.OnEnter:=lc.NotifyEvent; end; end; end; function wincontrol_getOnExit(L: PLua_State): integer; cdecl; var c: twincontrol; begin c:=luaclass_getClassObject(L); LuaCaller_pushMethodProperty(L, TMethod(c.OnExit), 'TNotifyEvent'); result:=1; end; function wincontrol_setOnExit(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; f: integer; routine: string; lc: TLuaCaller; begin wincontrol:=luaclass_getClassObject(L); result:=0; if lua_gettop(L)>=1 then begin CleanupLuaCall(tmethod(wincontrol.onExit)); wincontrol.onExit:=nil; if lua_isfunction(L,-1) then begin routine:=Lua_ToString(L,-1); f:=luaL_ref(L,LUA_REGISTRYINDEX); lc:=TLuaCaller.create; lc.luaroutineIndex:=f; wincontrol.OnExit:=lc.NotifyEvent; end else if lua_isstring(L,-1) then begin routine:=lua_tostring(L,-1); lc:=TLuaCaller.create; lc.luaroutine:=routine; wincontrol.OnExit:=lc.NotifyEvent; end; end; end; function wincontrol_canFocus(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; begin wincontrol:=luaclass_getClassObject(L); lua_pushboolean(L, wincontrol.CanFocus); result:=1; end; function wincontrol_focused(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; begin wincontrol:=luaclass_getClassObject(L); lua_pushboolean(L, wincontrol.Focused); result:=1; end; function wincontrol_setFocus(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; begin wincontrol:=luaclass_getClassObject(L); wincontrol.SetFocus; result:=0 end; function wincontrol_setShape(L: PLua_State): integer; cdecl; var wincontrol: TWinControl; x: TObject; begin wincontrol:=luaclass_getClassObject(L); result:=0; if lua_gettop(L)>=1 then begin x:=lua_toceuserdata(L, -1); if (x is TBitmap) then wincontrol.SetShape(TBitmap(x)) else if (x is TRegion) then wincontrol.SetShape(TRegion(x)); end; end; function wincontrol_setLayeredAttributes(L: PLua_State): integer; cdecl; var h: thandle; key: dword; alpha: byte; flags: byte; begin //only works on forms in windows 7 and earlier, but also works on child components in windows 8 and later result:=0; {$ifdef windows} if lua_gettop(L)>=3 then begin h:=twincontrol(luaclass_getClassObject(L)).handle; if SetWindowLong(h, GWL_EXSTYLE, GetWindowLong(h, GWL_EXSTYLE) or WS_EX_LAYERED)=0 then begin result:=1; lua_pushboolean(L, false); exit; //not supported end; key:=lua_tointeger(L, 1); alpha:=lua_tointeger(L, 2); flags:=lua_tointeger(L, 3); result:=1; lua_pushboolean(L, SetLayeredWindowAttributes(h, key, alpha, flags)); end; {$endif} end; procedure wincontrol_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin control_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getControlCount', wincontrol_getControlCount); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getControl', wincontrol_getControl); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getControlAtPos', wincontrol_getControlAtPos); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOnEnter', wincontrol_setOnEnter); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setOnExit', wincontrol_setOnExit); luaclass_addClassFunctionToTable(L, metatable, userdata, 'canFocus', wincontrol_canFocus); luaclass_addClassFunctionToTable(L, metatable, userdata, 'focused', wincontrol_focused); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setFocus', wincontrol_setFocus); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setShape', wincontrol_setShape); luaclass_addClassFunctionToTable(L, metatable, userdata, 'setLayeredAttributes', wincontrol_setLayeredAttributes); luaclass_addPropertyToTable(L, metatable, userdata, 'DoubleBuffered', wincontrol_getDoubleBuffered, wincontrol_setDoubleBuffered); luaclass_addPropertyToTable(L, metatable, userdata, 'ControlCount', wincontrol_getControlCount, nil); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Control', wincontrol_getControl); luaclass_addPropertyToTable(L, metatable, userdata, 'OnEnter', wincontrol_getOnEnter, wincontrol_setOnEnter); luaclass_addPropertyToTable(L, metatable, userdata, 'OnExit', wincontrol_getOnExit, wincontrol_setOnExit); luaclass_addPropertyToTable(L, metatable, userdata, 'Handle', wincontrol_getHandle, nil); end; procedure initializeLuaWinControl; begin lua_register(LuaVM, 'wincontrol_getControlCount', wincontrol_getControlCount); lua_register(LuaVM, 'wincontrol_getControl', wincontrol_getControl); lua_register(LuaVM, 'wincontrol_getControlAtPos', wincontrol_getControlAtPos); lua_register(LuaVM, 'wincontrol_onEnter', wincontrol_setOnEnter); lua_register(LuaVM, 'wincontrol_onExit', wincontrol_setOnExit); lua_register(LuaVM, 'wincontrol_canFocus', wincontrol_canFocus); lua_register(LuaVM, 'wincontrol_focused', wincontrol_focused); lua_register(LuaVM, 'wincontrol_setFocus', wincontrol_setFocus); lua_register(LuaVM, 'wincontrol_setShape', wincontrol_setShape); end; initialization luaclass_register(TWinControl, wincontrol_addMetaData ); end.
unit PWInfoWellParamsFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, ToolWin, ComCtrls, StdCtrls, ExtCtrls, Well, BaseObjects, Parameter, ActnList, ImgList, CommonValueDictFrame; type TfrmInfoWellParams = class(TfrmCommonFrame) Splitter1: TSplitter; GroupBox1: TGroupBox; tvAllParametrs: TTreeView; gbx: TGroupBox; ToolBar1: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; actnLst: TActionList; imgLst: TImageList; actnAddParameter: TAction; actnDelParameter: TAction; actnEditParameter: TAction; GroupBox3: TGroupBox; edtVchValue: TEdit; GroupBox4: TGroupBox; GroupBox5: TGroupBox; edtIntValue: TEdit; dtmValue: TDateTimePicker; ToolBar2: TToolBar; ToolButton4: TToolButton; actnSaveValue: TAction; ToolButton5: TToolButton; ToolButton6: TToolButton; actnAddGroupParams: TAction; frmFilterMUnits: TfrmFilter; frmFilterMUs: TfrmFilter; ToolButton7: TToolButton; actnDelValue: TAction; procedure actnAddParameterExecute(Sender: TObject); procedure actnDelParameterExecute(Sender: TObject); procedure actnEditParameterExecute(Sender: TObject); procedure actnSaveValueExecute(Sender: TObject); procedure actnAddGroupParamsExecute(Sender: TObject); procedure tvAllParametrsClick(Sender: TObject); procedure edtIntValueChange(Sender: TObject); procedure edtVchValueChange(Sender: TObject); procedure dtmValueChange(Sender: TObject); procedure edtIntValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edtVchValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure dtmValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure actnDelValueExecute(Sender: TObject); private FChanging: boolean; FPreActiveParametr: TParameterByWell; function GetWell: TDinamicWell; function GetActiveParametr: TParameterByWell; function GetActiveParametrValue: TParameterValueByWell; function GetActiveGroupParametr: TParametersGroupByWell; protected procedure FillControls(ABaseObject: TIDObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; function GetParentCollection: TIDObjects; override; public property Well: TDinamicWell read GetWell; property Changing: boolean read FChanging write FChanging; property ActiveGroupParametr: TParametersGroupByWell read GetActiveGroupParametr; property ActiveParametr: TParameterByWell read GetActiveParametr; property PreActiveParametr: TParameterByWell read FPreActiveParametr write FPreActiveParametr; property ActiveParametrValue: TParameterValueByWell read GetActiveParametrValue; procedure Clear; override; procedure Save(AObject: TIDObject = nil); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmInfoWellParams: TfrmInfoWellParams; implementation uses Facade, AddUnits, AddObjectFrame, Math, MeasureUnits, SDFacade, Registrator; {$R *.dfm} { TfrmInfoWellParams } procedure TfrmInfoWellParams.ClearControls; begin inherited; (TMainFacade.GetInstance as TMainFacade).AllParametersGroups.MakeList(tvAllParametrs, true, true); frmFilterMUnits.AllObjects := TMainFacade.GetInstance.AllMeasureUnits; frmFilterMUs.AllObjects := TMainFacade.GetInstance.AllMeasureUnits; frmFilterMUnits.cbxActiveObject.Text := '<не указана>'; frmFilterMUs.cbxActiveObject.Text := '<не указана>'; Clear; end; constructor TfrmInfoWellParams.Create(AOwner: TComponent); begin inherited; EditingClass := TDinamicWell; FChanging := false; end; destructor TfrmInfoWellParams.Destroy; begin inherited; end; procedure TfrmInfoWellParams.FillControls(ABaseObject: TIDObject); begin inherited; with EditingObject as TDinamicWell do begin if Assigned (ActiveParametr) then if Assigned (ActiveParametr.MeasureUnit) then begin frmFilterMUnits.ActiveObject := ActiveParametr.MeasureUnit; frmFilterMUs.ActiveObject := ActiveParametr.MeasureUnit; end; if Assigned (ActiveParametrValue) then begin edtIntValue.Text := IntToStr(ActiveParametrValue.INTValue); edtVchValue.Text := ActiveParametrValue.VCHValue; dtmValue.Date := ActiveParametrValue.DTMValue; end; end; end; procedure TfrmInfoWellParams.FillParentControls; begin inherited; end; function TfrmInfoWellParams.GetActiveParametr: TParameterByWell; begin Result := nil; if tvAllParametrs.Items.Count > 0 then if Assigned (tvAllParametrs.Selected) then if tvAllParametrs.Selected.Level = 1 then Result := TParameterByWell(tvAllParametrs.Selected.Data); end; function TfrmInfoWellParams.GetParentCollection: TIDObjects; begin Result := nil; end; function TfrmInfoWellParams.GetWell: TDinamicWell; begin if EditingObject is TDinamicWell then Result := EditingObject as TDinamicWell else Result := nil; end; procedure TfrmInfoWellParams.RegisterInspector; begin inherited; end; procedure TfrmInfoWellParams.Save; begin inherited; //if (not Assigned(EditingObject)) or (EditingObject is ParentClass) then // FEditingObject := TMainFacade.GetInstance.AllWells.Items[TMainFacade.GetInstance.AllWells.Count - 1]; with Well.ParametrValues do begin end; end; procedure TfrmInfoWellParams.actnAddParameterExecute(Sender: TObject); var o: TParameterByWell; begin inherited; frmEditor := TfrmEditor.Create(Self); frmEditor.Caption := 'Группа параметров "' + ActiveGroupParametr.Name + '"'; frmEditor.frmAddObject.frmFilterDicts.Visible := true; frmEditor.frmAddObject.edtName.Width := frmEditor.frmAddObject.gbx.Width - 15; frmEditor.frmAddObject.frmFilterDicts.gbx.Caption := 'Ед. изм.'; frmEditor.frmAddObject.frmFilterDicts.AllObjects := TMainFacade.GetInstance.AllMeasureUnits; frmEditor.frmAddObject.frmFilterDicts.cbxActiveObject.Text := '<не указана>'; if frmEditor.ShowModal = mrOk then if frmEditor.frmAddObject.Save then begin o := TParameterByWell.Create(ActiveGroupParametr.Parameters); o.Name := frmEditor.frmAddObject.Name; if Assigned (frmEditor.frmAddObject.frmFilterDicts.ActiveObject) then o.MeasureUnit := frmEditor.frmAddObject.frmFilterDicts.ActiveObject as TMeasureUnit; o.Update; ActiveGroupParametr.Parameters.Add(o); (TMainFacade.GetInstance as TMainFacade).AllParametersGroups.MakeList(tvAllParametrs, true, true); end; frmEditor.Free; end; procedure TfrmInfoWellParams.actnDelParameterExecute(Sender: TObject); begin inherited; if MessageBox(0, 'Вы действительно хотите удалить объект ?', 'Вопрос', MB_YESNO + MB_ICONWARNING + MB_APPLMODAL) = ID_YES then begin ActiveGroupParametr.Parameters.Remove(ActiveParametr); (TMainFacade.GetInstance as TMainFacade).AllParametersGroups.MakeList(tvAllParametrs, true, true); end; end; procedure TfrmInfoWellParams.actnEditParameterExecute(Sender: TObject); begin inherited; if Assigned (ActiveParametr) then begin frmEditor := TfrmEditor.Create(Self); frmEditor.Caption := 'Группа параметров "' + ActiveGroupParametr.Name + '"'; frmEditor.frmAddObject.Name := trim(ActiveParametr.Name); frmEditor.frmAddObject.frmFilterDicts.Visible := true; frmEditor.frmAddObject.edtName.Width := frmEditor.frmAddObject.gbx.Width - 15; frmEditor.frmAddObject.frmFilterDicts.gbx.Caption := 'Ед. изм.'; frmEditor.frmAddObject.frmFilterDicts.AllObjects := TMainFacade.GetInstance.AllMeasureUnits; if Assigned (ActiveParametr.MeasureUnit) then frmEditor.frmAddObject.frmFilterDicts.ActiveObject := ActiveParametr.MeasureUnit else frmEditor.frmAddObject.frmFilterDicts.cbxActiveObject.Text := '<не указана>'; if frmEditor.ShowModal = mrOk then if frmEditor.frmAddObject.Save then begin ActiveParametr.Name := frmEditor.frmAddObject.Name; if Assigned (frmEditor.frmAddObject.frmFilterDicts.ActiveObject) then ActiveParametr.MeasureUnit := frmEditor.frmAddObject.frmFilterDicts.ActiveObject as TMeasureUnit; ActiveParametr.Update; end; frmEditor.Free; end else MessageBox(0, 'Параметр для редактирования не задан.', 'Ошибка', MB_OK + MB_ICONERROR + MB_APPLMODAL); end; procedure TfrmInfoWellParams.actnSaveValueExecute(Sender: TObject); var o : TParameterValueByWell; begin inherited; if not Assigned (ActiveParametrValue) then begin o := TParameterValueByWell.Create(Well.ParametrValues); o.ParametrWell := PreActiveParametr; Well.ParametrValues.Add(o); end; with ActiveParametrValue do begin ParametrWell := PreActiveParametr; INTValue := StrToInt(trim(edtIntValue.Text)); VCHValue := trim(edtVchValue.Text); DTMValue := Date; end; end; function TfrmInfoWellParams.GetActiveParametrValue: TParameterValueByWell; var i: integer; begin Result := nil; if Assigned (PreActiveParametr) then if Well.ParametrValues.Count > 0 then begin for i := 0 to Well.ParametrValues.Count - 1 do if well.ParametrValues.Items[i].ParametrWell.ID = PreActiveParametr.ID then Result := Well.ParametrValues.Items[i]; end; end; procedure TfrmInfoWellParams.actnAddGroupParamsExecute(Sender: TObject); var o: TParametersGroupByWell; begin inherited; frmEditor := TfrmEditor.Create(Self); frmEditor.Caption := 'Укажате название новой группы параметров'; if frmEditor.ShowModal = mrOk then if frmEditor.frmAddObject.Save then begin o := TParametersGroupByWell.Create((TMainFacade.GetInstance as TMainFacade).AllParametersGroups); o.Name := frmEditor.frmAddObject.Name; o.Update; (TMainFacade.GetInstance as TMainFacade).AllParametersGroups.Add(o); (TMainFacade.GetInstance as TMainFacade).AllParametersGroups.MakeList(tvAllParametrs); end; frmEditor.Free; end; function TfrmInfoWellParams.GetActiveGroupParametr: TParametersGroupByWell; begin Result := nil; if tvAllParametrs.Items.Count > 0 then if tvAllParametrs.Selected.Level = 0 then Result := TParametersGroupByWell(tvAllParametrs.Selected.Data) else if tvAllParametrs.Selected.Level = 1 then Result := TParametersGroupByWell(tvAllParametrs.Selected.Parent.Data) end; procedure TfrmInfoWellParams.tvAllParametrsClick(Sender: TObject); begin inherited; if Assigned (PreActiveParametr) then if FChanging then if MessageBox(0, PChar('Значение параметра "' + trim(PreActiveParametr.Name) + '" было изменено. Сохранить изменения ?'), 'Вопрос', MB_ICONWARNING + MB_YESNO + MB_APPLMODAL) = ID_YES then actnSaveValue.Execute; FChanging := false; Clear; if tvAllParametrs.Items.Count > 0 then if Assigned (tvAllParametrs.Selected) then case tvAllParametrs.Selected.Level of 0 : begin Clear; end; 1 : begin gbx.Caption := 'Значение параметра "' + trim(ActiveParametr.Name) + '"'; PreActiveParametr := ActiveParametr; FillControls(Well); end; end; end; procedure TfrmInfoWellParams.Clear; begin gbx.Caption := 'Значение параметра'; edtIntValue.Text := ''; edtVchValue.Text := ''; dtmValue.Date := Date; frmFilterMUnits.ActiveObject := nil; frmFilterMUs.ActiveObject := nil; frmFilterMUnits.cbxActiveObject.Text := '<не указана>'; frmFilterMUs.cbxActiveObject.Text := '<не указана>'; end; procedure TfrmInfoWellParams.edtIntValueChange(Sender: TObject); begin inherited; //FChanging := true; end; procedure TfrmInfoWellParams.edtVchValueChange(Sender: TObject); begin inherited; //FChanging := true; end; procedure TfrmInfoWellParams.dtmValueChange(Sender: TObject); begin inherited; //FChanging := true; end; procedure TfrmInfoWellParams.edtIntValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; FChanging := true; end; procedure TfrmInfoWellParams.edtVchValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; FChanging := true; end; procedure TfrmInfoWellParams.dtmValueKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; FChanging := true; end; procedure TfrmInfoWellParams.actnDelValueExecute(Sender: TObject); begin inherited; if Assigned (ActiveParametrValue) then begin Well.ParametrValues.Remove(ActiveParametrValue); FillControls(Well); end else MessageBox(0, '', '', MB_ICONERROR + MB_OK + MB_APPLMODAL); end; end.
unit Neon.Tests.Serializer; interface uses DUnitX.TestFramework, Neon.Tests.Utils; type [TestFixture] TTestSerializer = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] [TestCase('TestInteger', '42')] procedure TestInteger(const AValue: Integer); [Test] [TestCase('TestString', 'Lorem "Ipsum" \n \\ {}')] procedure TestString(const AValue: string); end; implementation procedure TTestSerializer.Setup; begin end; procedure TTestSerializer.TearDown; begin end; procedure TTestSerializer.TestInteger(const AValue: Integer); var LJSON: string; begin LJSON := TTestUtils.SerializeValueFrom<Integer>(AValue); Assert.AreEqual('42', LJSON); end; procedure TTestSerializer.TestString(const AValue: string); var LJSON: string; begin LJSON := TTestUtils.SerializeValueFrom<string>(AValue); Assert.AreEqual('"Lorem \"Ipsum\" \\n \\\\ {}"', LJSON); end; initialization TDUnitX.RegisterTestFixture(TTestSerializer); end.
unit Screen; interface uses CRT; Function GetChar(x,y:byte):char; Function GetColorByte(x,y:byte):byte; Function GetTextColor(x,y:byte):byte; Function GetBackGroundColor(x,y:byte):byte; Function GetBlink(x,y:byte):boolean; Function ColorByte(ColorText,ColorBackGround:byte;BlinkOn:boolean):byte; Procedure SetChar(x,y:byte;Symbol:char); Procedure SetColorByte(x,y:byte;ColorByte:byte); Procedure SetTextColor(x,y,Color:byte); Procedure SetBackGroundColor(x,y,Color:byte); Procedure OutStringXY(x,y,Color:byte;S:string); implementation type Cell = record Symbol:char; Color:byte; end; TDisplay = array [1..25,1..80] of Cell; var Display:TDisplay absolute $B800:$0000; Function GetChar(x,y:byte):char; begin GetChar:=Display[y,x].Symbol end; Function GetColorByte(x,y:byte):byte; begin GetColorByte:=Display[y,x].Color end; Function GetTextColor(x,y:byte):byte; begin GetTextColor:=Display[y,x].Color and $0F end; Function GetBackGroundColor(x,y:byte):byte; begin GetBackGroundColor:=(Display[y,x].Color and $70)shr 4 end; Function GetBlink(x,y:byte):boolean; begin if(Display[y,x].Color and $80)=$80 then GetBlink:=True; end; Function ColorByte(ColorText,ColorBackGround:byte;BlinkOn:boolean):byte; var Color:byte; begin Color:=ColorText+16*ColorBackGround; if BlinkOn then ColorByte:=Color+$80; end; Procedure SetChar(x,y:byte;Symbol:char); begin Display[y,x].Symbol:=Symbol end; Procedure SetColorByte(x,y:byte;ColorByte:byte); begin Display[y,x].Color:=ColorByte; end; Procedure SetTextColor(x,y,Color:byte); begin Display[y,x].Color:=(Display[y,x].Color and $F0)+Color end; Procedure SetBackGroundColor(x,y,Color:byte); begin Display[y,x].Color:=(Color shl 4)+(Display[y,x].Color and $8F) end; Procedure OutStringXY(x,y,Color:byte;S:string); var i:byte; begin for i:=1 to Length(s) do begin SetChar(x+i-1,y,s[i]);SetColorByte(x+i-1,y,Color) end; end; end.
unit uBairroModel; interface uses System.SysUtils, FireDAC.Comp.Client, Data.DB, FireDAC.DApt, FireDAC.Comp.UI, FireDAC.Comp.DataSet, uBairroDto, uClassSingletonConexao; type TBairroModel = class private oQueryListaBairros: TFDQuery; public function BuscarID: Integer; function Alterar(var ABairro: TBairroDto): Boolean; function Inserir(var ABairro: TBairroDto): Boolean; procedure ListarBairros(var DsBairro: TDataSource); function Deletar(const AIDBairro: Integer): Boolean; function Pesquisar(ANome: String): Boolean; function VerificarBairro(ABairro: TBairroDto): Boolean; function VerificarExcluir(AId: Integer): Boolean; constructor Create; destructor Destroy; override; end; implementation { TBairrosModel } function TBairroModel.Alterar(var ABairro: TBairroDto): Boolean; var sSql: String; begin sSql := 'update bairro set nome = ' + QuotedStr(ABairro.Nome) + ' , bairro_idMunicipio = ' + IntToStr(ABairro.oMunicipio.idMunicipio) + ' where idBairro = ' + IntToStr(ABairro.idBairro); Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0; end; function TBairroModel.BuscarID: Integer; var oQuery: TFDQuery; begin Result := 1; oQuery := TFDQuery.Create(nil); try oQuery.Connection := TSingletonConexao.GetInstancia; oQuery.Open('select max(idBairro) as ID' + ' from bairro'); if (not(oQuery.IsEmpty)) then Result := oQuery.FieldByName('ID').AsInteger + 1; finally if Assigned(oQuery) then FreeAndNil(oQuery); end; end; constructor TBairroModel.Create; begin oQueryListaBairros := TFDQuery.Create(nil); end; function TBairroModel.Deletar(const AIDBairro: Integer): Boolean; begin Result := TSingletonConexao.GetInstancia.ExecSQL ('delete from bairro where idBairro = ' + IntToStr(AIDBairro)) > 0; end; destructor TBairroModel.Destroy; begin oQueryListaBairros.Close; if Assigned(oQueryListaBairros) then FreeAndNil(oQueryListaBairros); inherited; end; function TBairroModel.Inserir(var ABairro: TBairroDto): Boolean; var sSql: String; begin sSql := 'insert into bairro (idBairro, Nome, bairro_idMunicipio) values (' + IntToStr(ABairro.idBairro) + ', ' + QuotedStr(ABairro.Nome) + ', ' + IntToStr(ABairro.oMunicipio.idMunicipio) + ')'; Result := TSingletonConexao.GetInstancia.ExecSQL(sSql) > 0; end; procedure TBairroModel.ListarBairros(var DsBairro: TDataSource); begin oQueryListaBairros.Connection := TSingletonConexao.GetInstancia; oQueryListaBairros.Open ('select b.idBairro, b.nome, m.nome as nomeMunicipio from bairro b inner join municipio m on b.bairro_idMunicipio = m.idMunicipio'); DsBairro.DataSet := oQueryListaBairros; end; function TBairroModel.Pesquisar(ANome: String): Boolean; begin oQueryListaBairros.Open ('select b.idBairro, b.Nome, m.Nome from bairro b inner join municipio as m on b.bairro_idMunicipio = m.idMunicipio WHERE b.Nome LIKE "%' + ANome + '%"'); if (not(oQueryListaBairros.IsEmpty)) then begin Result := True; end else begin Result := False; oQueryListaBairros.Open ('select b.idBairro, b.nome, m.nome as nomeMunicipio from bairro b inner join municipio m on b.bairro_idMunicipio = m.idMunicipio'); end; end; function TBairroModel.VerificarBairro(ABairro: TBairroDto): Boolean; var oQuery: TFDQuery; begin oQuery := TFDQuery.Create(nil); try oQuery.Connection := TSingletonConexao.GetInstancia; oQuery.Open('select IdBairro from bairro where Nome=' + QuotedStr(ABairro.Nome) + ' AND bairro_idMunicipio=' + IntToStr(ABairro.oMunicipio.idMunicipio)); if (oQuery.IsEmpty) then Result := True else Result := False; finally if Assigned(oQuery) then FreeAndNil(oQuery); end; end; function TBairroModel.VerificarExcluir(AId: Integer): Boolean; var oQuery: TFDQuery; begin oQuery := TFDQuery.Create(nil); try oQuery.Connection := TSingletonConexao.GetInstancia; oQuery.Open('select idCliente from cliente where cliente_idBairro = ' + IntToStr(AId)); if (oQuery.IsEmpty) then Result := True else Result := False; finally if Assigned(oQuery) then FreeAndNil(oQuery); end; end; end.
{********************************************************} { } { Zeos Database Objects } { Oracle8 Transaction component } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZOraSqlTr; interface {$R *.dcr} uses {$IFNDEF LINUX} Windows, Db, {$ELSE} DB, {$ENDIF} SysUtils, Classes, ZDirOraSql, ZOraSqlCon, ZTransact, ZSqlExtra, ZLibOraSql, ZToken, ZSqlTypes; {$IFNDEF LINUX} {$INCLUDE ..\Zeos.inc} {$ELSE} {$INCLUDE ../Zeos.inc} {$ENDIF} type { Transaction Interbase component } TZOraSqlTransact = class(TZTransact) private function GetDatabase: TZOraSqlDatabase; procedure SetDatabase(Value: TZOraSqlDatabase); function GetTransIsolation: TZOraSqlTransIsolation; procedure SetTransIsolation(const Value: TZOraSqlTransIsolation); public constructor Create(AOwner: TComponent); override; // function ExecSqlParams(Sql: WideString; Params: TVarRecArray; // ParamCount: Integer): LongInt; override; function ExecFunc(Func: WideString): WideString; override; procedure AddMonitor(Monitor: TZMonitor); override; procedure DeleteMonitor(Monitor: TZMonitor); override; published property Database: TZOraSqlDatabase read GetDatabase write SetDatabase; property TransIsolation: TZOraSqlTransIsolation read GetTransIsolation write SetTransIsolation; end; implementation uses ZDbaseConst, ZDirSql; {***************** TZOraSqlTransact implementation *****************} { Class constructor } constructor TZOraSqlTransact.Create(AOwner: TComponent); begin inherited Create(AOwner); FHandle := TDirOraSqlTransact.Create(nil); FQuery := TDirOraSqlQuery.Create(nil, TDirOraSqlTransact(FHandle)); FDatabaseType := dtOracle; end; { Get transaction type } function TZOraSqlTransact.GetTransIsolation: TZOraSqlTransIsolation; begin Result := TDirOraSqlTransact(FHandle).TransIsolation; end; { Set transaction type } procedure TZOraSqlTransact.SetTransIsolation(const Value: TZOraSqlTransIsolation); begin if Value <> TDirOraSqlTransact(FHandle).TransIsolation then begin Disconnect; TDirOraSqlTransact(FHandle).TransIsolation := Value; end; end; { Add monitor into monitor list } procedure TZOraSqlTransact.AddMonitor(Monitor: TZMonitor); begin ZDirOraSql.MonitorList.AddMonitor(Monitor); end; { Delete monitor from monitor list } procedure TZOraSqlTransact.DeleteMonitor(Monitor: TZMonitor); begin ZDirOraSql.MonitorList.DeleteMonitor(Monitor); end; { Get database component } function TZOraSqlTransact.ExecFunc(Func: WideString): WideString; begin if Pos('FROM', UpperCase(Func)) <= 0 then Func := Func + ' FROM DUAL'; Result := inherited ExecFunc(Func); end; { Get database component } function TZOraSqlTransact.GetDatabase: TZOraSqlDatabase; begin Result := TZOraSqlDatabase(FDatabase); end; { Set database component } procedure TZOraSqlTransact.SetDatabase(Value: TZOraSqlDatabase); begin inherited SetDatabase(Value); end; (* { Execute a query } function TZOraSqlTransact.ExecSqlParams(Sql: WideString; Params: TVarRecArray; ParamCount: Integer): LongInt; var OldCursor: TCursor; Error: string; begin if not FConnected then DatabaseError(LoadStr(SNotConnected)); OldCursor := Screen.Cursor; try if toHourGlass in FOptions then Screen.Cursor := crSqlWait; FQuery.Sql := Sql; Result := TDirOraSqlQuery(FQuery).ExecuteParams(Params, ParamCount); if FQuery.Status <> qsCommandOk then begin Error := FQuery.Error; Recovery(False); DatabaseError(Error); end else DoDataChange(Sql); if FAutoCommit then Commit; finally Screen.Cursor := OldCursor; end; end; *) end.
unit uCalcHash; //{$DEFINE ThreadClass} interface uses Windows, SysUtils, Classes,MD4,Forms; type TCalcEd2kHashProgressEvent = procedure(Sender:TObject;ACalcBytes:Int64;ATitalBytes:Int64;var AStop:Boolean) of object; TCalcFinishEvent = procedure(Sender:TObject) of object; TCalcEd2kHashThread = class( {$IFDEF ThreadClass} TThread {$ELSE} TObject {$ENDIF} ) private FFileName:string; FCalcBytes:Int64; FStop:Boolean; FFileHash:TMD4Digest; FFileSize:Int64; FFastCalc:Boolean; FOnCalcHashProgress: TCalcEd2kHashProgressEvent; FOnCalcFinish :TCalcFinishEvent; FWebHash: TMD4Digest; FFullHash: string; procedure SynchronizeProgress; procedure DoCalcFinish; function CalcHash(const FileName: string; var Digest: TMD4Digest; PAbort: PBoolean; AFastCalc: Boolean): Boolean; function CalcHashStream(const Stream: TStream; var Digest: TMD4Digest; PAbort: PBoolean = nil; AFastCalc: Boolean = True): Boolean; protected {$IFDEF ThreadClass} procedure Execute; override; {$ELSE} procedure Execute; {$ENDIF} public constructor Create(const AFileName:string;AFastCalc:Boolean=True); property OnCalcHashProgress:TCalcEd2kHashProgressEvent read FOnCalcHashProgress write FOnCalcHashProgress; property OnCalcFinish:TCalcFinishEvent read FOnCalcFinish write FOnCalcFinish; property FileHash:TMD4Digest read FFileHash; property WebHash:TMD4Digest read FWebHash; property FullHash:string read FFullHash; property FileName:string read FFileName; property FileSize:Int64 read FFileSize; end; {$IFNDEF ThreadClass} procedure CalcFileHash(const AFileName: string; var AFileHash: TMD4Digest; var AFileSize: Int64); {$ENDIF} implementation { TCalcHashThread } procedure CalcFileHash(const AFileName: string; var AFileHash: TMD4Digest; var AFileSize: Int64); begin with TCalcEd2kHashThread.Create(AFileName, True) do begin Execute; AFileHash := FileHash; AFileSize := FileSize; end; end; function TCalcEd2kHashThread.CalcHash(const FileName: string; var Digest: TMD4Digest; PAbort: PBoolean; AFastCalc: Boolean): Boolean; var hFile: THandle; Stream: TFileStream; begin Result := False; OutputDebugString(PChar(Format('FileName:%s',[FileName]))); //这样打开,可以优化文件读取,而且文件打开失败(不存在)也不会触发异常 hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, 0); if hFile = INVALID_HANDLE_VALUE then //文件打开失败 Exit; Stream := TFileStream.Create(hFile); try Result := CalcHashStream(Stream, Digest, PAbort, AFastCalc); finally Stream.Free; end; end; function TCalcEd2kHashThread.CalcHashStream(const Stream: TStream; var Digest: TMD4Digest; PAbort: PBoolean; AFastCalc: Boolean): Boolean; type TSegment = record SegmentID: Integer; //从0开始 SegmentSize: Int64; SegmentHash: TMD4Digest; end; TFileSegmentInfo = record FileSize: Int64; SegmentSize: Int64; SegmentCount: Integer; Segments: array of TSegment; end; const CSegmentSize = 9728000; var MemStream: TMemoryStream; AInfo: TFileSegmentInfo; I: Integer; ModCount: Integer; Buffer: array[0..16383] of Byte; SavePos: Int64; function CalcHash(ASegmentID: Integer;var ASegmentHash:TMD4Digest): Boolean; var ReadBytes:Integer; LeftBytes:Integer; Context:TMD4Context; begin Result := True; if (Stream = nil) or (ASegmentID < 0) or (ASegmentID >= AInfo.SegmentCount) then Exit; LeftBytes :=AInfo.Segments[ASegmentID].SegmentSize; ZeroMemory(@ASegmentHash, SizeOf(TMD4Digest)); MD4Init(Context); Stream.Seek(ASegmentID * AInfo.SegmentSize, soFromBeginning); repeat if LeftBytes >= SizeOf(Buffer) then ReadBytes := Stream.Read(Buffer, SizeOf(Buffer)) else ReadBytes := Stream.Read(Buffer, LeftBytes); LeftBytes := LeftBytes - ReadBytes; MD4Update(Context, Buffer, ReadBytes); FCalcBytes := FCalcBytes + ReadBytes; //Synchronize(SynchronizeProgress); SynchronizeProgress; if (PAbort <> nil) and PAbort^ then //是否停止计算 begin Result := False; Exit; end; if (not AFastCalc) then begin if GetCurrentThreadID = MainThreadID then Application.ProcessMessages; Sleep(3); end; until (ReadBytes = 0) or (LeftBytes <= 0); MD4Final(Context,ASegmentHash); end; begin Result := True; //Synchronize(SynchronizeProgress); SynchronizeProgress; SavePos := Stream.Position; MemStream := TMemoryStream.Create; try AInfo.FileSize := Stream.Size; FFileSize := AInfo.FileSize; FCalcBytes := 0; ModCount :=0; AInfo.SegmentSize := CSegmentSize; if AInfo.FileSize <= CSegmentSize then begin AInfo.SegmentCount := 1; AInfo.SegmentSize := AInfo.FileSize; end else begin AInfo.SegmentSize := CSegmentSize; ModCount := AInfo.FileSize mod AInfo.SegmentSize; AInfo.SegmentCount := AInfo.FileSize div AInfo.SegmentSize; if ModCount > 0 then Inc(AInfo.SegmentCount); end; SetLength(AInfo.Segments, AInfo.SegmentCount); ZeroMemory(@AInfo.Segments[0], Sizeof(TSegment) * AInfo.SegmentCount); for I := 0 to AInfo.SegmentCount - 1 do begin AInfo.Segments[I].SegmentID := I; if (I < AInfo.SegmentCount - 1) or (ModCount = 0) then begin AInfo.Segments[I].SegmentSize := AInfo.SegmentSize; Result := CalcHash(I,AInfo.Segments[I].SegmentHash); if not Result then Exit; end else begin AInfo.Segments[I].SegmentSize := ModCount; Result := CalcHash(I,AInfo.Segments[I].SegmentHash); if not Result then Exit; end; if (PAbort <> nil) and PAbort^ then //是否停止计算 begin Result := False; Exit; end; if (not AFastCalc) then begin if GetCurrentThreadID = MainThreadID then Application.ProcessMessages; Sleep(3); end; MemStream.WriteBuffer(AInfo.Segments[I].SegmentHash, SizeOf(TMD4Digest)); FFullHash := FFullHash + MD4DigestToStr(AInfo.Segments[I].SegmentHash); end; if AInfo.SegmentCount>1 then Result := MD4Stream(MemStream, Digest, PAbort, AFastCalc) else if AInfo.SegmentCount =1 then begin Digest := AInfo.Segments[0].SegmentHash; Result := True; end; finally Stream.Seek(SavePos, soFromBeginning); SetLength(AInfo.Segments, 0); MemStream.Free; end; end; constructor TCalcEd2kHashThread.Create(const AFileName: string;AFastCalc:Boolean); begin {$IFDEF ThreadClass} inherited Create(True); FreeOnTerminate := True; {$ENDIF} FFileName := AFileName; FFullHash := ''; FCalcBytes := 0; FFastCalc := AFastCalc; FStop := False; ZeroMemory(@FFileHash,SizeOf(TMD4Digest)); ZeroMemory(@FWebHash,SizeOf(TMD4Digest)); end; procedure TCalcEd2kHashThread.DoCalcFinish; begin if Assigned(FOnCalcFinish) then FOnCalcFinish(Self); end; procedure TCalcEd2kHashThread.Execute; begin CalcHash(FFileName,FFileHash,@FStop,FFastCalc); GetWebHash(FFileName,FWebHash); DoCalcFinish; end; procedure TCalcEd2kHashThread.SynchronizeProgress; begin if Assigned(FOnCalcHashProgress) then FOnCalcHashProgress(Self,FCalcBytes,FFileSize,FStop); end; end.
unit FreeOTFEExplorerfrmNewDirDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SDUForms; type TfrmNewDirDlg = class(TSDUForm) edDirName: TEdit; Label1: TLabel; pbOK: TButton; pbCancel: TButton; procedure edDirNameChange(Sender: TObject); procedure FormShow(Sender: TObject); private function GetDirName(): WideString; procedure SetDirName(newName: WideString); protected procedure EnableDisableControls(); public published property DirName: WideString read GetDirName write SetDirName; end; implementation {$R *.dfm} uses SDUGeneral; procedure TfrmNewDirDlg.edDirNameChange(Sender: TObject); begin EnableDisableControls(); end; procedure TfrmNewDirDlg.EnableDisableControls(); begin SDUEnableControl(pbOK, (trim(DirName) <> '')); end; function TfrmNewDirDlg.GetDirName(): WideString; begin Result := edDirName.text; end; procedure TfrmNewDirDlg.SetDirName(newName: WideString); begin edDirName.Text := newName; EnableDisableControls(); end; procedure TfrmNewDirDlg.FormShow(Sender: TObject); begin DirName := ''; EnableDisableControls(); end; END.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain A copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvSerialMaker.PAS, released on 2001-02-28. The Initial Developer of the Original Code is Sébastien Buysse [sbuysse att buypin dott com] Portions created by Sébastien Buysse are Copyright (C) 2001 Sébastien Buysse. All Rights Reserved. Contributor(s): Michael Beck [mbeck att bigfoot dott com]. You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvSerialMaker.pas 13138 2011-10-26 23:17:50Z jfudickar $ unit JvSerialMaker; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, JvComponentBase; type {$IFDEF RTL230_UP} [ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32)] {$ENDIF RTL230_UP} TJvSerialMaker = class(TJvComponent) private FUserName: string; FBase: Integer; FSerial: string; FDummy: string; procedure ChangeUser(AUserName: string); procedure ChangeBase(ABase: Integer); public function GiveSerial(ABase: Integer; AUserName: string): string; function SerialIsCorrect(ABase: Integer; AUserName: string; Serial: string): Boolean; published property UserName: string read FUserName write ChangeUser; property Base: Integer read FBase write ChangeBase; { Do not store dummies } property Serial: string read FSerial write FDummy stored False; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvSerialMaker.pas $'; Revision: '$Revision: 13138 $'; Date: '$Date: 2011-10-27 01:17:50 +0200 (jeu. 27 oct. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses JvResources; procedure TJvSerialMaker.ChangeUser(AUserName: string); begin FUserName := AUserName; FSerial := GiveSerial(Base, AUserName); end; procedure TJvSerialMaker.ChangeBase(ABase: Integer); begin FBase := ABase; FSerial := GiveSerial(ABase, UserName); end; function TJvSerialMaker.GiveSerial(ABase: Integer; AUserName: string): string; var A: Integer; begin if (ABase <> 0) and (AUserName <> '') then begin A := ABase * Length(AUserName) + Ord(AUserName[1]) * 666; Result := IntToStr(A) + '-'; A := ABase * Ord(AUserName[1]) * 123; Result := Result + IntToStr(A) + '-'; A := ABase + (Length(AUserName) * Ord(AUserName[1])) * 6613; Result := Result + IntToStr(A); end else Result := RsError; end; function TJvSerialMaker.SerialIsCorrect(ABase: Integer; AUserName: string; Serial: string): Boolean; begin if (AUserName <> '') and (ABase <> 0) then Result := Serial = GiveSerial(ABase, AUserName) else Result := False; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit Marvin.Desktop.GUI.Cadastro.Cliente; interface uses { sistema } Marvin.AulaMulticamada.Classes.Cliente, Marvin.AulaMulticamada.Listas.Cliente, Marvin.AulaMulticamada.Classes.TipoCliente, Marvin.AulaMulticamada.Listas.TipoCliente, Marvin.Desktop.GUI.Cadastro.Base, { padrão } System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Actions, { firemonkey } FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ActnList, FMX.TabControl, FMX.Effects, FMX.Objects, FMX.Controls.Presentation, FMX.ListView, FMX.Edit, FMX.DateTimeCtrls, FMX.ListBox, FMX.Layouts; type TfraCadastroClientes = class(TfraCadastroBase) edtId: TEdit; lblId: TLabel; GlowEffect2: TGlowEffect; edtNome: TEdit; lblNome: TLabel; GlowEffect3: TGlowEffect; edtNumeroDocumento: TEdit; lblNumeroDocumento: TLabel; GlowEffect4: TGlowEffect; dtpDataCadastro: TDateEdit; dtpHoraCadastro: TTimeEdit; lblDataHoraCadastro: TLabel; GlowEffect5: TGlowEffect; GlowEffect6: TGlowEffect; cbbTipoCliente: TComboBox; lblTipoCliente: TLabel; GlowEffect7: TGlowEffect; rectInformacoesBasicas: TRectangle; sdw1: TShadowEffect; lblTituloInformacoesBasicas: TLabel; inrglwfct1: TInnerGlowEffect; retOutrasInformacoes: TRectangle; sdw2: TShadowEffect; ret1: TRectangle; ret2: TRectangle; lbl1: TLabel; inrglwfct2: TInnerGlowEffect; lin1: TLine; lin2: TLine; private FCliente: TMRVCliente; FListaClientes: TMRVListaCliente; FListaTiposCliente: TMRVListaTipoCliente; procedure DoGetClientes; procedure DoShowClientes; protected { métodos de dados } procedure GetTiposCliente; procedure SetTiposCliente; procedure DoCarregarDadosAuxiliares; { métodos de interface GUI } procedure DoRefresh; override; procedure DoSalvar; override; procedure DoExcluir; override; procedure DoInterfaceToObject(const AItem: TListViewItem); override; procedure DoObjectToInterface; procedure DoGetFromInterface; function DoGetTipoClienteFromInterface: Integer; function DoGetPositionTipoCliente: Integer; procedure DoInitInterface; override; procedure DoInit; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Cliente: TMRVCliente read FCliente; end; var fraCadastroClientes: TfraCadastroClientes; implementation {$R *.fmx} uses FMX.Ani, FMX.InertialMovement; { TfraCadastroClientes } constructor TfraCadastroClientes.Create(AOwner: TComponent); begin inherited; FCliente := TMRVCliente.Create; FListaClientes := TMRVListaCliente.Create; FListaTiposCliente := TMRVListaTipoCliente.Create; end; destructor TfraCadastroClientes.Destroy; begin FreeAndNil(FListaTiposCliente); FreeAndNil(FListaClientes); FreeAndNil(FCliente); inherited; end; procedure TfraCadastroClientes.DoCarregarDadosAuxiliares; begin { faz a carga dos dados no combobox de tipos de cliente } Self.GetTiposCliente; Self.SetTiposCliente; end; procedure TfraCadastroClientes.DoExcluir; var LMensagem: string; LCliente: TMRVCliente; begin inherited; LCliente := TMRVCliente.Create; try LCliente.Assign(FCliente); { manda o ClientModule excluir } LMensagem := Self.ClientClasses.ClientesExcluir(LCliente); finally LCliente.DisposeOf; end; Self.ShowMessageBox(LMensagem); { atualiza a lista } Self.DoRefresh; { muda para a aba de lista } ChangeTabActionListagem.ExecuteTarget(lvLista); end; procedure TfraCadastroClientes.DoGetClientes; var LCliente: TMRVCliente; LListaClientes: TMRVListaCliente; begin LListaClientes := nil; { recupera os dados para o listview } LCliente := TMRVCliente.Create; try { pede para o ClientModule recuperar os tipos de clientes cadastrados } LListaClientes := Self.ClientClasses.ClientesProcurarItens(LCliente) as TMRVListaCliente; { limpa a lista } if Assigned(LListaClientes) then begin FListaClientes.Clear; FListaClientes.AssignObjects(LListaClientes); LListaClientes.DisposeOf; end; finally LCliente.DisposeOf; end; end; procedure TfraCadastroClientes.DoGetFromInterface; var LId: Integer; begin LId := 0; if (edtId.Text.Trim <> EmptyStr) then begin LId := edtId.Text.toInteger; end; { recupera os dados da GUI } FCliente.Clienteid := LId; FCliente.Nome := edtNome.Text; FCliente.Numerodocumento := edtNumeroDocumento.Text; FCliente.Datahoracadastro := dtpDataCadastro.Date + dtpHoraCadastro.Time; { recupera o tipo do cliente } FCliente.TipoClienteId := Self.DoGetTipoClienteFromInterface; end; function TfraCadastroClientes.DoGetPositionTipoCliente: Integer; var LIndex: Integer; LTipoCliente: TMRVTipoCliente; LResult: Integer; begin LResult := -1; for LIndex := 0 to FListaTiposCliente.Count - 1 do begin FListaTiposCliente.ProcurarPorIndice(LIndex, LTipoCliente); if LTipoCliente.TipoClienteId = FCliente.TipoClienteId then begin LResult := LIndex; Break; end; end; Result := LResult; end; function TfraCadastroClientes.DoGetTipoClienteFromInterface: Integer; var LTipoCliente: TMRVTipoCliente; begin Result := 0; if cbbTipoCliente.ItemIndex >= 0 then begin FListaTiposCliente.ProcurarPorIndice(cbbTipoCliente.ItemIndex, LTipoCliente); Result := LTipoCliente.TipoClienteId; end; end; procedure TfraCadastroClientes.DoInit; begin inherited; end; procedure TfraCadastroClientes.DoInitInterface; begin inherited; { limpa } edtId.Text := EmptyStr; edtNome.Text := EmptyStr; edtNumeroDocumento.Text := EmptyStr; dtpDataCadastro.Date := Now; dtpHoraCadastro.Time := Time; { vai para o index inicial } if cbbTipoCliente.Items.Count > 0 then begin cbbTipoCliente.ItemIndex := -1; end; { ajusta } edtId.Enabled := False; edtNome.SetFocus; { carrega dados auxiliares } Self.DoCarregarDadosAuxiliares; end; procedure TfraCadastroClientes.DoInterfaceToObject(const AItem: TListViewItem); var LCliente: TMRVCliente; begin inherited; { recupera } FCliente.Clear; FCliente.ClienteId := AItem.Detail.toInteger; FCliente.Nome := AItem.Text; { recupera os dados da lista } FListaClientes.ProcurarPorChave(FCliente.GetKey, LCliente); FCliente.Assign(LCliente); { carrega dados auxiliares } Self.DoCarregarDadosAuxiliares; { exibe } Self.DoObjectToInterface; end; procedure TfraCadastroClientes.DoObjectToInterface; begin edtId.Text := FCliente.Clienteid.ToString; edtNome.Text := FCliente.Nome; edtNumeroDocumento.Text := FCliente.Numerodocumento; dtpDataCadastro.Date := FCliente.Datahoracadastro; dtpHoraCadastro.Time := FCliente.Datahoracadastro; { carrega o combo tipos de cliente } cbbTipoCliente.ItemIndex := Self.DoGetPositionTipoCliente; end; procedure TfraCadastroClientes.DoRefresh; begin inherited; { carrega a lista de clientes no listview } Self.DoGetClientes; { exibe os dados } Self.DoShowClientes; end; procedure TfraCadastroClientes.DoSalvar; var LCliente: TMRVCliente; begin inherited; LCliente := nil; Self.DoGetFromInterface; case Self.EstadoCadastro of ecNovo: begin { manda o ClientModule incluir } LCliente := Self.ClientClasses.ClientesInserir(FCliente) as TMRVCliente; Self.EstadoCadastro := ecAlterar; end; ecAlterar: begin { manda o ClientModule alterar } LCliente := Self.ClientClasses.ClientesAlterar(FCliente) as TMRVCliente; end; end; try FCliente.Assign(LCliente); { exibe a resposta } Self.DoObjectToInterface; finally { libera o retorno } LCliente.DisposeOf; end; end; procedure TfraCadastroClientes.DoShowClientes; var LCont: Integer; LItem: TListViewItem; LCliente: TMRVCliente; begin lvLista.BeginUpdate; try { limpa o listview } lvLista.Items.Clear; for LCont := 0 to FListaClientes.Count - 1 do begin FListaClientes.ProcurarPorIndice(LCont, LCliente); { exibe na lista } LItem := lvLista.Items.Add; LItem.Text := LCliente.Nome; LItem.Detail := LCliente.ClienteId.ToString; end; finally lvLista.EndUpdate; end; { carrega dados auxiliares } Self.DoCarregarDadosAuxiliares; end; procedure TfraCadastroClientes.GetTiposCliente; var LTipoCliente: TMRVTipoCliente; LTiposCliente: TMRVListaTipoCliente; begin LTipoCliente := TMRVTipoCliente.Create; try { recupera os tipos de cliente no ClientModule } LTiposCliente := Self.ClientClasses.TiposClienteProcurarItens(LTipoCliente) as TMRVListaTipoCliente; try FListaTiposCliente.Clear; FListaTiposCliente.AssignObjects(LTiposCliente); finally LTiposCliente.DisposeOf; end; finally LTipoCliente.DisposeOf; end; end; procedure TfraCadastroClientes.SetTiposCliente; var LCont: Integer; LTipoCliente: TMRVTipoCliente; begin { limpa os itens } cbbTipoCliente.Items.Clear; cbbTipoCliente.Enabled := False; try { adiciona os itens da lista de objetos } for LCont := 0 to FListaTiposCliente.Count - 1 do begin FListaTiposCliente.ProcurarPorIndice(LCont, LTipoCliente); cbbTipoCliente.Items.Add(LTipoCliente.GetKey); end; finally cbbTipoCliente.Enabled := True; end; end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [CST_PIS] The MIT License Copyright: Copyright (C) 2020 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 CstPisService; interface uses CstPis, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TCstPisService = class(TServiceBase) private public class function ConsultarLista: TObjectList<TCstPis>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TCstPis>; class function ConsultarObjeto(AId: Integer): TCstPis; class procedure Inserir(ACstPis: TCstPis); class function Alterar(ACstPis: TCstPis): Integer; class function Excluir(ACstPis: TCstPis): Integer; end; var sql: string; implementation { TCstPisService } class function TCstPisService.ConsultarLista: TObjectList<TCstPis>; begin sql := 'SELECT * FROM CST_PIS ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TCstPis>; finally Query.Close; Query.Free; end; end; class function TCstPisService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TCstPis>; begin sql := 'SELECT * FROM CST_PIS where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TCstPis>; finally Query.Close; Query.Free; end; end; class function TCstPisService.ConsultarObjeto(AId: Integer): TCstPis; begin sql := 'SELECT * FROM CST_PIS WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TCstPis>; end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TCstPisService.Inserir(ACstPis: TCstPis); begin ACstPis.ValidarInsercao; ACstPis.Id := InserirBase(ACstPis, 'CST_PIS'); end; class function TCstPisService.Alterar(ACstPis: TCstPis): Integer; begin ACstPis.ValidarAlteracao; Result := AlterarBase(ACstPis, 'CST_PIS'); end; class function TCstPisService.Excluir(ACstPis: TCstPis): Integer; begin ACstPis.ValidarExclusao; Result := ExcluirBase(ACstPis.Id, 'CST_PIS'); end; end.
unit ULevelFile; interface uses SysUtils, UObjectFile, types, Windows, Graphics, classes, consts, Utils, Math, UMetaData; const DEFAULT_SNAP_THRESHOLD = 10; END_OF_USER_SCRIPT_PART = 'UserScriptEnd'; // метка в level-скрипте, что конца юзерскрипта достигли EOUSP_LENGTH = 13; // Длина той строки, что выше //NOTE: Lua чуствителен к регистру type PObjectPropsNode = ^TObjectPropsNode; TObjectPropsNode = record SnapStateX: Boolean; // состояние снэппинга, если true, то к данному объекту идёт снэп, иначе - нет SnapStateY: Boolean; SnappedX, SnappedY : Boolean; HasBeenSnappedX, HasBeenSnappedY: Boolean; XSnapIndex, YSnapIndex: Integer; Selected : Boolean; x, px : Integer; y, py : Integer; width : Integer; height : Integer; prev : PObjectPropsNode; next : PObjectPropsNode; Proto : PObjectFileProps; // Указатель на соответствующ этому экземпляру прототип Params : TObjectFileProps; // Уникальный для этого объекта список параметров function GetX(): Integer; function GetY(): Integer; procedure SetX(AX: Integer); procedure SetY(AY: Integer); end; TLevelFile = class(TObject) private FirstObject: PObjectPropsNode; numObjects: cardinal; buffer: TBitmap; // А это что?? numTypes: cardinal; xpos, ypos: PInteger; // Что это за координаты, чего бля? public pScript: PAnsiChar; SnapThreshold: Integer; procedure TrySnap(); function GetSelectionUpperLeft(var x, y: Integer): Boolean; function numObjectsSelected(): Integer; procedure OffsetSelected(dx, dy: Integer); function PtInSelection(x, y: Integer): Boolean; function GetObjectRect(DstObj: TObjectPropsNode): TRect; procedure Clear(); procedure ClearSelection(); procedure SelectObjects(x1, y1, x2, y2: Integer); procedure AddToSelection(x1, y1, x2, y2: Integer); procedure ClearSelected(); constructor Create(vObjects: TObjectFilePropsArr; vxpos, vypos: PInteger); function CountObjects():cardinal; function GetNumType(): cardinal; procedure Free(); function AddObject(AX, AY: Integer): PObjectPropsNode; procedure DelObject(AObject: PObjectPropsNode); function SaveToFile(filename: string): Boolean; function LoadFromFile(filename: string): Boolean; function LoadScript(filename: string): Boolean; procedure DrawObjects(BoundingRect: TRect; canvas: TCanvas); function FirstSelected(): TObjectPropsNode; end; implementation { Скопипастено из Graphics.pas Исключая тот факт, что временные битмапы не создаются во время выполнения. Также часть процедуры для старых версий венды удалена. } procedure OutOfResources; begin raise EOutOfResources.Create(SOutOfResources); end; procedure GDIError; var ErrorCode: Integer; Buf: array [Byte] of Char; begin ErrorCode := GetLastError; if (ErrorCode <> 0) and (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, ErrorCode, LOCALE_USER_DEFAULT, Buf, sizeof(Buf), nil) <> 0) then raise EOutOfResources.Create(Buf) else OutOfResources; end; function GDICheck(Value: Integer): Integer; begin if Value = 0 then GDIError; Result := Value; end; function MyTransparentStretchBlt(DstDC: HDC; DstX, DstY, DstW, DstH: Integer; SrcDC: HDC; SrcX, SrcY, SrcW, SrcH: Integer; maskhandle: HBITMAP; MaskX, MaskY: Integer): Boolean; const ROP_DstCopy = $00AA0029; begin Result := True; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (SrcW = DstW) and (SrcH = DstH) then begin MaskBlt(DstDC, DstX, DstY, DstW, DstH, SrcDC, SrcX, SrcY, maskhandle, MaskX, MaskY, MakeRop4(ROP_DstCopy, SrcCopy)); Exit; end; end; { TLevelFile } function TLevelFile.AddObject(AX, AY: Integer): PObjectPropsNode; var cObj, tmp: ^PObjectPropsNode; ParamTmp: PParamLexeme; begin // Вместо этого ебаного поиска конца ввести LastNode tmp := nil; cObj := @FirstObject; while cObj^ <> nil do begin tmp := cObj; cObj := @(cObj^.next); end; cObj^ := VirtualAlloc(nil, SizeOf(TObjectPropsNode), MEM_COMMIT, PAGE_READWRITE); with cObj^^ do begin Proto := ProtoSelected; // assign params: inherite from tpersistent and overload assign(); Params := TObjectFileProps.Create(); ParamTmp := Proto.FindParam('FunctionName'); if ParamTmp <> nil then FunctionByName(ParamTmp.ParamValue)^.SuperMegaAssignTo(@Params); Params.FindParam('ProtoName').ParamValue := Proto.FindParam('name').ParamValue; SetX(AX); SetY(AY); width := Proto.GetPreview().Width; height := Proto.GetPreview().Height; selected := false; SnapStateX := true; SnapStateY := true; SnappedX := false; SnappedY := false; HasBeenSnappedX := false; HasBeenSnappedY := false; next := nil; if cObj = @FirstObject then prev := nil else prev := tmp^; end; // Log('LEVEL', 'Object with ID %d of type %s added', [cObj^.objectID, // GetObjectByID(Prototypes, _typeID).FindParam('NAME').ParamValue]); Result := cObj^; end; procedure TLevelFile.AddToSelection(x1, y1, x2, y2: Integer); var cObj: PObjectPropsNode; tmpRect: TRect; begin cObj := FirstObject; While cObj <> nil do begin with cObj^ do if IntersectRect(tmpRect, Rect(x1, y1, x2, y2), Rect(x, y, x + width, y + height)) then cObj^.selected := not (cObj^.selected); cObj := cObj^.next; end; end; procedure TLevelFile.Clear; var tmp, cObj: PObjectPropsNode; begin cObj := FirstObject; if cObj = nil then Exit; while cObj^.next <> nil do cObj := cObj^.next; while cObj <> nil do begin tmp := cObj; cObj := cObj^.prev; DelObject(tmp); end; end; procedure TLevelFile.ClearSelected; var tmp, cObj: PObjectPropsNode; begin cObj := FirstObject; while cObj <> nil do begin tmp := cObj; cObj := cObj^.next; if tmp^.selected then DelObject(tmp); end; end; procedure TLevelFile.ClearSelection; var cObj: PObjectPropsNode; begin cObj := FirstObject; While cObj <> nil do begin cObj^.selected := false;; cObj := cObj^.next; end; end; function TLevelFile.CountObjects: cardinal; var cObj: PObjectPropsNode; begin cObj := FirstObject; Result := 0; while cObj <> nil do begin Inc(Result); cObj := cObj^.next; end; end; constructor TLevelFile.Create(vObjects: TObjectFilePropsArr; vxpos, vypos: PInteger); begin inherited Create; SnapThreshold := DEFAULT_SNAP_THRESHOLD; Prototypes := vObjects; Buffer := TBitmap.Create; FirstObject := nil; numObjects := 0; numTypes := 0; xpos := vxpos; ypos := vypos; pScript := nil; end; procedure TLevelFile.DelObject(AObject: PObjectPropsNode); var temp: PObjectPropsNode; begin temp := AObject; if temp^.prev <> nil then temp^.prev^.next := temp^.next; if temp^.next <> nil then temp.next^.prev := temp^.prev; if temp = FirstObject then FirstObject := FirstObject^.next; VirtualFree(temp, 0, MEM_RELEASE); end; procedure TLevelFile.DrawObjects(BoundingRect: TRect; canvas: TCanvas); var srcRect, dstRect, tmpRect, GoodRect, BBox: TRect; //OMG... cObj: PObjectPropsNode; begin with GoodRect do begin left := MAXINT; Right := -MAXINT; Top := MAXINT; Bottom := -MAXINT; end; buffer.Width := BoundingRect.Right; buffer.Height := BoundingRect.Bottom; with buffer.Canvas do begin Brush.Color := clBlack; buffer.Canvas.FillRect(BoundingRect); // White cross in the middle of level { pen.Color := clwhite; moveto(Round(GetWidth / 2) + xpos^, Round(GetHeight / 2) - 100 + ypos^); lineto(Round(GetWidth / 2) + xpos^, Round(GetHeight / 2) + 100 + ypos^); moveto(Round(GetWidth / 2) - 100 + xpos^, Round(GetHeight / 2) + ypos^); lineto(Round(GetWidth / 2) + 100 + xpos^, Round(GetHeight / 2) + ypos^); } cObj := FirstObject; while cObj <> nil do begin with srcRect do begin left := 0; top := 0; right := CObj^.Proto.GetPreview().Width; bottom := CObj^.Proto.GetPreview().height; end; dstRect := Rect(cObj^.x , cObj^.y, srcRect.Right + cObj^.x, srcRect.Bottom + cObj^.y); OffsetRect(dstRect, xpos^, ypos^); if cObj^.selected then begin with GoodRect do begin left := Min(Left, cObj^.x + xpos^); Right := Max(Right, cObj^.x + cobj^.width + xpos^); Top := Min(Top, cObj^.y + ypos^); Bottom := Max(Bottom, cObj^.y + cObj^.height + ypos^); end; end; if IntersectRect(tmpRect, BoundingRect, dstRect) then begin MyTransparentStretchBlt(Handle, cObj^.x + xpos^, cObj^.y + ypos^, cObj^.width, cObj^.height, CObj^.Proto.GetPreview.Canvas.Handle, 0, 0, cObj^.width, cObj^.height, CObj^.Proto.MaskHandle, 0, 0); { if cObj^.selected then with cObj^ do begin Pen.width := 1; Pen.Style := psDash; Brush.Style := bsClear; Pen.Color := RGB(125, 0, 90); Rectangle(x+xpos^, y+ypos^, x+width+xpos^, y+height+ypos^); end;} end; cObj := cObj^.next; end; cObj := FirstObject; while cObj <> nil do begin dstRect := Rect(cObj^.x , cObj^.y, srcRect.Right + cObj^.x, srcRect.Bottom + cObj^.y); OffsetRect(dstRect, xpos^, ypos^); if IntersectRect(tmpRect, BoundingRect, dstRect) then begin if cObj^.selected then with cObj^ do begin Pen.width := 1; Pen.Style := psDot; Brush.Style := bsClear; Pen.Color := RGB(125, 0, 90); Rectangle(x+xpos^, y+ypos^, x+width+xpos^, y+height+ypos^); end; BBox := cOBj^.Proto.BBOX; with cObj^ do begin Pen.width := 1; Pen.Style := psDot; Brush.Style := bsClear; Pen.Color := RGB(0, 90, 125); Rectangle(x + BBox.Left+xpos^,y + BBox.Top+ypos^, x + BBox.Right+xpos^,y + BBox.Bottom+ypos^); end; end; cObj := cObj^.next; end; Pen.width := 1; Pen.Style := psDot; Brush.Style := bsClear; Pen.Color := RGB(240, 111, 20); Rectangle(GoodRect); end; canvas.Draw(0, 0, buffer); end; function TLevelFile.FirstSelected: TObjectPropsNode; var cObj: PObjectPropsNode; begin cObj := FirstObject; while (not CObj^.Selected) and (cObj <> nil) do cObj := cObj^.next; Result := cObj^; end; procedure TLevelFile.Free; var temp, cObj: PObjectPropsNode; begin inherited Free; Buffer.Free; cObj := FirstObject; while cObj <> nil do begin temp := cObj; cobj := cObj^.next; // Log('LEVEL', 'Object with ID %d of type %s deleted', [temp^.objectID, // GetObjectByID(Prototypes, temp^.typeID).FindParam('NAME').ParamValue]); VirtualFree(temp, 0, MEM_RELEASE); end; end; function TLevelFile.GetNumType: cardinal; begin Result := numTypes; end; function TLevelFile.GetObjectRect(DstObj: TObjectPropsNode): TRect; begin with DstObj, Result do begin Left := x; Right := x + width; Top := y; Bottom := y + height; end; end; function TLevelFile.GetSelectionUpperLeft(var x, y: Integer): Boolean; var cObj: PObjectPropsNode; begin cObj := FirstObject; Result := false; if cObj = nil then Exit; x := MAXINT; y := MAXINT; while cObj <> nil do begin if cObj^.selected then begin if x > cObj^.x then x := cObj^.x; if y > cObj^.y then y := cObj^.y; end; cObj := cObj^.next; end; if (x = MAXINT) or (y = MAXINT) then Exit; Result := true; end; function TLevelFile.LoadFromFile(filename: string): Boolean; var sfile: file; i, j, ArgCount: Integer; ch: char; FuncName, buffer, tmp: string; objTmp: PObjectPropsNode; paramTmp: PObjectFileProps; LexTmp: PParamLexeme; Args: array of string; ArgTypes: array of TParamType; function SkipSpace(): Boolean; begin while (not Eof(sFile)) and (ch in [' ',#13,#9,#10]) do begin BlockRead(sFile, ch, 1); end; Result := Eof(sFile); end; begin Result := false; buffer := ''; AssignFile(sfile, filename); Reset(sfile, 1); SetLength(tmp, EOUSP_LENGTH); while 1=1 do begin BlockRead(sFile, ch, 1); if Eof(sFile) then break; if ch <> '-' then buffer := buffer + ch else begin buffer := buffer + ch; BlockRead(sFile, ch, 1); if Eof(sFile) then break; if ch <> '-' then buffer := buffer + ch else begin buffer := buffer + ch; BlockRead(sFile, tmp[1], EOUSP_LENGTH); if CompareStr(tmp, END_OF_USER_SCRIPT_PART) <> 0 then begin buffer := buffer + tmp; end else break; end; end; end; tmp := ''; pScript := @(buffer[1]); while not Eof(sFile) do begin BlockRead(sFile, ch, 1); SkipSpace(); while (ch <> #13) and (not Eof(sFile)) do begin tmp := tmp + ch; BlockRead(sFile, ch, 1); end; ArgCount := 1; for i := 1 to Length(tmp) do begin if tmp[i] = ',' then Inc(ArgCount); end; i := 1; while tmp[i] <> '(' do begin FuncName := FuncName + tmp[i]; Inc(i); end; Inc(i); SetLength(Args, ArgCount); SetLength(ArgTypes, ArgCount); for j := 0 to ArgCount-1 do begin if tmp[i] in ['0'..'9', '-', '+'] then ArgTypes[j] := ptInteger else if tmp[i] = '"' then begin ArgTypes[j] := ptString; Inc(i) end else ArgTypes[j] := ptConst; while not (tmp[i] in [',', ')', '"']) do begin Args[j] := Args[j] + Tmp[i]; Inc(i); end; case tmp[i] of ',': Inc(i, 2); ')': ; '"': Inc(i, 3); end; end; tmp := ''; // Вот тут (где-то тут) имена ф-й хорощо бы кешировать, и если совпадают, то ебаный // квадратичный поиск много лишних раз не вызывать // хотя нет! ProtoSelected := ProtoByName(Args[0]); objTmp := AddObject(0, 0); FuncName := ''; LexTmp := objTmp.Params.FirstParam.next.next; for i := 0 to ArgCount-1 do begin if LexTmp^.ParamName = 'x' then begin objTmp.x := StrToInt(Args[i]); end; if LexTmp^.ParamName = 'y' then begin objTmp.y := StrToInt(Args[i]); end; LexTmp.ParamValue :=Args[i]; LexTmp.ParamType :=ArgTypes[i]; LexTmp := LexTmp.next; Args[i] := ''; end; // Prototypes. //ID := GetTypeIDbyName(Prototypes, name); //AddObject(ID, x, y, p1, p2); end; CloseFile(sfile); Result := true; Exit; //LoadScript(filename); end; function TLevelFile.LoadScript(filename: string): Boolean; var sfile: file; chcount, offset: Integer; ch: char; pch: PCHAR; SIG: array [0..2] of char; script: array of char; begin AssignFIle(sfile, filename); reset(sfile, 1); blockread(sfile, ch, 1); while ch <> 'E' do begin blockread(sfile, ch, 1); if ch = 'E' then begin SIG[0] := ch; BlockRead(sfile, ch, 1); SIG[1] := ch; BlockRead(sfile, ch, 1); SIG[2] := ch; if sig = 'EOL' then begin offset := FilePos(sfile); break; end; end; end; chcount := FileSize(sfile) - offset; SetLength(script, chcount+1); pch := @(script[0]); blockread(sfile, pch^, chcount); script[chcount] := #0; pScript := pch;//pch; CloseFile(sfile); Result := true; end; function TLevelFile.numObjectsSelected: Integer; var cObj: PObjectPropsNode; counter: Integer; begin Result := -1; cObj := FirstObject; if (cObj = nil) then Exit; Counter := 0; while cObj <> nil do begin if cObj^.selected then Inc(counter); cObj := cObj^.next; end; end; procedure TLevelFile.OffsetSelected(dx, dy: Integer); var cObj: PObjectPropsNode; begin cObj := FirstObject; if cObj = nil then Exit; while cObj <> nil do begin if cObj^.selected then begin cObj^.SetX(cObj^.GetX() + dx); cObj^.SetY(cObj^.GetY() + dy); end; cObj := cObj^.next; end; end; function TLevelFile.PtInSelection(x, y: Integer): Boolean; var cObj: PObjectPropsNode; begin Result := true; cObj := FirstObject; if cObj = nil then begin Result := false; Exit; end; while cObj <> nil do begin if cObj^.selected then if ptinrect(Rect(cObj^.x, cObj^.y, cObj^.x + cObj^.width, cObj^.y + cObj^.height), Point(x, y)) then Exit; cObj := cObj^.next; end; Result := false; end; function TLevelFile.SaveToFile(filename: string): Boolean; var dfile: file; strtmp: string; slen, i, j: Integer; Yes: Boolean; chtmp: char; tmpObj: PObjectPropsNode; typec: cardinal; LexTmp: PParamLexeme; ExTypes: array of Integer; numExTypes: Integer; cObj: PObjectPropsNode; begin cObj := FirstObject; chtmp := #0; AssignFile(dfile, filename); rewrite(dfile, 1); Yes := false; numExTypes := 0; //blockwrite(dfile, numTypes, sizeof(numTypes)); BlockWrite(dfile, pScript^, Length(pScript)); BlockWrite(dfile, #13#10'--' + END_OF_USER_SCRIPT_PART+#13#10, EOUSP_LENGTH+6); SetLength(ExTypes, numTypes); while CObj <> nil do begin // for i := 0 to numExTypes-1 do // if ExTypes[i] = CObj^.typeID then // Yes := true; // if not Yes then // begin // Inc(numExTypes); // ExTypes[numExTypes-1] := cObj^.typeID; // end; // Yes := false; strtmp := cObj.Params.FirstParam.next^.ParamValue + '('; LexTmp := cObj.Params.FirstParam.next^.next; while LexTmp <> nil do begin if (LexTmp.ParamValue <> '') and (LexTmp.prev.ParamName <> 'name') then strtmp := strtmp + ', '; if LexTmp.ParamValue <> '' then begin if LexTmp.ParamType = ptString then strtmp := strtmp + '"'; strtmp := strtmp + LexTmp.ParamValue; if LexTmp.ParamType = ptString then strtmp := strtmp + '"'; end; if LexTmp.next = nil then strtmp := strtmp + ');'#13#10; LexTmp := LexTmp.next; end; slen := strLen(PAnsiChar(strtmp)); for j := 1 to slen do blockwrite(dfile, strtmp[j], 1); CObj := CObj^.next; end; { for i := 0 to numExTypes-1 do begin CObj := FirstObject; while (CObj <> nil) and (CObj^.typeID <> ExTypes[i]) do CObj := CObj.next; strtmp := 'CreateSprite("' + GetObjectByID(Prototypes, CObj^.typeID).FindParam('name').ParamValue + ', '; slen := strLen(PAnsiChar(strtmp)); for j := 1 to slen do blockwrite(dfile, strtmp[j], 1); blockwrite(dfile, chtmp, 1); typec := CountObjectsType(cObj^.typeID); blockwrite(dfile, typec, 4); tmpObj := FirstObject; while tmpObj <> nil do begin if tmpObj^.typeID = ExTypes[i] then begin blockwrite(dfile, tmpObj^.x, 4); blockwrite(dfile, tmpObj^.y, 4); blockwrite(dfile, tmpObj^.param1, 2); blockwrite(dfile, tmpObj^.param2, 2); blockwrite(dfile, tmpObj^.objectID, 4); end; tmpObj := tmpObj^.next; end; end; BlockWrite(dfile, 'EOL', 3); } // тра-та та-та та-та та...хитрый план ебать кота CloseFile(dfile); Result := true; end; procedure TLevelFile.SelectObjects(x1, y1, x2, y2: Integer); var cObj: PObjectPropsNode; tmpRect: TRect; begin cObj := FirstObject; While cObj <> nil do begin with cObj^ do if IntersectRect(tmpRect, Rect(x1, y1, x2, y2), Rect(x, y, x + width, y + height)) then cObj^.selected := true; cObj := cObj^.next; end; end; function SegIn(a1, a2, b1, b2: Integer): Boolean; begin Result := true; if (a2 < b1) or (b2 < a1) then Result := false; end; procedure TLevelFile.TrySnap; var cObj, srcObj: PObjectPropsNode; b1, b2: TRect; // Короткие имена здесь, потому что иначе слишком громоздко и p1, p2: TPoint; // нихрена не понятно 1 - src 2 - всё остальное i: Integer; function DistX(index: Integer): Integer; begin case index of 1: Result := abs( p2.x + b2.Left - p1.x - b1.right ); 2: Result := abs( p2.x + b2.Right - p1.x - b1.Left ); 3: Result := abs( p2.x + b2.Left - p1.x - b1.left ); 4: Result := abs( p2.x + b2.Right - p1.x - b1.Right ); end; end; function DistY(index: Integer): Integer; begin case index of 1: Result := abs( p2.y + b2.Top - p1.y - b1.Bottom ); 2: Result := abs( p2.y + b2.Bottom - p1.y - b1.Top ); 3: Result := abs( p2.y + b2.Top - p1.y - b1.Top ); 4: Result := abs( p2.y + b2.Bottom - p1.y - b1.Bottom ); end; end; procedure SetX(index: Integer); begin case index of 1: srcObj^.x := p2.x + b2.Left - b1.Right; 2: srcObj^.x := p2.x + b2.Right - b1.Left; 3: srcObj^.x := p2.x + b2.Left; 4: srcObj^.x := p2.x + b2.Right - b1.Right; end; cObj^.SnapStateX := false; cObj^.XSnapIndex := index; srcObj^.SnappedX := true; end; procedure SetY(index: Integer); begin case index of 1: srcObj^.y := p2.y + b2.Top - b1.Bottom; 2: srcObj^.y := p2.y + b2.Bottom - b1.Top; 3: srcObj^.y := p2.y + b2.Top; 4: srcObj^.y := p2.y + b2.Bottom - b1.Bottom; end; cObj^.SnapStateY := false; cObj^.YSnapIndex := index; srcObj^.SnappedY := true; end; begin cObj := FirstObject; srcObj := nil; While cObj <> nil do begin if cObj^.selected then begin srcObj := cObj; break; end; cObj := cObj^.next; end; if srcObj = nil then Exit; b1 := srcObj^.Proto.BBOX; if srcObj^.SnappedX then p1.x := srcObj^.px else p1.x := srcObj^.x; if srcObj^.SnappedY then p1.y := srcObj^.py else p1.y := srcObj^.y; cObj := FirstObject; While cObj <> nil do begin if cObj = srcObj then begin cObj := cObj.next; Continue; end; b2 := cObj^.Proto.BBOX; p2 := Point(cObj^.x, cObj^.y); case cObj^.SnapStateX of true: if SegIn(p2.y + b2.Top, p2.y + b2.Bottom, p1.y + b1.Top, p1.y + b1.Bottom) then for i := 1 to 4 do if DistX(i) < SnapThreshold then begin SetX(i); break; end; false: if DistX(cObj^.XSnapIndex) > SnapThreshold then begin cObj^.SnapStateX := true; srcObj^.SnappedX := false; end; end; case cObj^.SnapStateY of true: if SegIn(p2.x + b2.Left, p2.x + b2.Right, p1.x + b1.Left, p1.x + b1.Right) then for i := 1 to 4 do if DistY(i) < SnapThreshold then begin SetY(i); break; end; false: begin if DistY(cObj^.YSnapIndex) > SnapThreshold then begin cObj^.SnapStateY := true; srcObj^.SnappedY := false; end; end; end; cObj := cObj^.next; end; end; { TObjectPropsNode } function TObjectPropsNode.GetX: Integer; begin if SnappedX and HasBeenSnappedX then Result := px else Result := x; end; function TObjectPropsNode.GetY: Integer; begin if SnappedY and HasBeenSnappedY then Result := py else Result := y; end; procedure TObjectPropsNode.SetX(AX: Integer); var ParamTmp: PParamLexeme; begin if SnappedX and HasBeenSnappedX then px := AX else if (HasBeenSnappedX) and (not SnappedX) then begin x := px; HasBeenSnappedX := false; end else if (SnappedX) and (not HasBeenSnappedX) then begin px := AX; HasBeenSnappedX := true; end else x := AX; ParamTmp := nil; if Params <> nil then ParamTmp := Params.FindParam('x'); if ParamTmp <> nil then begin ParamTmp.ParamValue := IntToStr(x); ParamTmp.ParamType := ptInteger; end; end; procedure TObjectPropsNode.SetY(AY: Integer); var ParamTmp: PParamLexeme; begin if SnappedY and HasBeenSnappedY then py := AY else if (HasBeenSnappedY) and (not SnappedY) then begin y := py; HasBeenSnappedY := false; end else if (SnappedY) and (not HasBeenSnappedY) then begin py := AY; HasBeenSnappedY := true; end else y := AY; ParamTmp := nil; if Params <> nil then ParamTmp := Params.FindParam('y'); if ParamTmp <> nil then begin ParamTmp.ParamValue := IntToStr(y); ParamTmp.ParamType := ptInteger; end; end; end.
// ***************************************************************************** // File : UServer.pas // Project : MicroServer.dpr // Easy example of TCP Server with indy component : TidTCPSever // // see indy doc: http://www.indyproject.org/sockets/docs/index.en.aspx // // // ***************************************************************************** unit UServer; {.$DEFINE UDP_ACTIVE} interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdComponent, Vcl.StdCtrls, IdUDPServer, IdSocketHandle, IdBaseComponent, IdCustomTCPServer, IdThreadSafe, IdTCPConnection, IdYarn, IdTCPServer, Vcl.ExtCtrls, IdGlobal, IdUDPBase, uPacket, System.Zlib, System.IOUtils, Soap.EncdDecd, uCompression; type TFServer = class(TForm) Title: TLabel; btn_start: TButton; btn_stop: TButton; btn_clear: TButton; clients_connected: TLabel; Label1: TLabel; Panel1: TPanel; messagesLog: TMemo; btn_send: TButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure btn_startClick(Sender: TObject); procedure btn_stopClick(Sender: TObject); procedure btn_clearClick(Sender: TObject); procedure IdTCPServerConnect(AContext: TIdContext); procedure IdTCPServerDisconnect(AContext: TIdContext); procedure IdTCPServerExecute(AContext: TIdContext); procedure IdTCPServerStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure IdUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); procedure ShowNumberOfClients(p_disconnected: Boolean = False); procedure BroadcastMessage(p_message: string); procedure Display(p_sender, p_message: string); function GetNow(): string; procedure btn_sendClick(Sender: TObject); private function LoadFileToStr(const FileName: TFileName): String; procedure StrToFile(const FileName, SourceString: string); function Unzip(const zipped: string): string; function ByteArrayToStream(const aContent: TArray<Byte>): TMemoryStream; function StreamToByteArray(aStream: TMemoryStream): TArray<Byte>; { Private declarations } public { Public declarations } end; // ... // ... listening port // const GUEST_CLIENT_PORT = 20010; const HOST_IP = '127.0.0.1'; GUEST_CLIENT_PORT = 13102; // GUEST_CLIENT_PORT = 50001; {$IFDEF UDP_ACTIVE} GUEST_UDPCLIENT_PORT = 61001; {$ENDIF} const TMP_FILE_NAME = '35.070000_128.830000_31.380000_121.600000.rtz'; // TMP_FILE_NAME = '35.003333_128.791667_33.691667_-118.173333.rtz'; var FServer: TFServer; // ... Id TCP Server IdTCPServer: TIdTCPServer; {$IFDEF UDP_ACTIVE} IdUDPServer: TIdUDPServer; {$ENDIF} PacketHeader: TReqPacketHeader; FS, FSZIP: TFileStream; SendContext: TIdContext; implementation {$R *.dfm} // ***************************************************************************** // EVENT : onCreate() // ON FORM CREATE // ***************************************************************************** procedure TFServer.FormCreate(Sender: TObject); begin // ... create idTCPServer IdTCPServer := TIdTCPServer.Create(self); IdTCPServer.Active := False; // ... set properties IdTCPServer.MaxConnections := 20; // ... etc.. // ... assign a new context class (if you need) // IdTCPServer.ContextClass := TYourContext; // ... add some callback functions IdTCPServer.OnConnect := IdTCPServerConnect; IdTCPServer.OnDisconnect := IdTCPServerDisconnect; IdTCPServer.OnExecute := IdTCPServerExecute; IdTCPServer.OnStatus := IdTCPServerStatus; // ... etc.. // ... add UDP functions {$IFDEF UDP_ACTIVE} // ... create idUDPServer IdUDPServer := TIdUDPServer.Create(self); IdUDPServer.Active := False; // IdUDPServer.OnUDPException := IdUDPException; IdUDPServer.OnUDPRead := IdUDPRead; {$ENDIF} end; // ............................................................................. // ***************************************************************************** // EVENT : onShow() // ON FORM SHOW // ***************************************************************************** procedure TFServer.FormShow(Sender: TObject); begin // ... INITIALIZE: // ... clear message log messagesLog.Lines.Clear; // ... zero to clients connected clients_connected.Caption := inttostr(0); // ... set buttons btn_start.enabled := True; btn_stop.enabled := False; end; // ............................................................................. // ***************************************************************************** // EVENT : btn_startClick() // CLICK ON START BUTTON // ***************************************************************************** procedure TFServer.btn_startClick(Sender: TObject); begin // ... START SERVER: // ... clear the Bindings property ( ... Socket Handles ) IdTCPServer.Bindings.Clear; // ... Bindings is a property of class: TIdSocketHandles; // ... add listening ports: // ... add a port for connections from guest clients. IdTCPServer.Bindings.Add.Port := GUEST_CLIENT_PORT; // ... etc.. // ... ok, Active the Server! IdTCPServer.Active := True; // ... disable start button btn_start.enabled := False; // ... enable stop button btn_stop.enabled := True; // ... message log Display('SERVER', 'STARTED!'); {$IFDEF UDP_ACTIVE} IdUDPServer.Bindings.Clear; IdUDPServer.Bindings.Add.Port := GUEST_UDPCLIENT_PORT; IdUDPServer.Active := True; Display('UDPSERVER', 'STARTED!'); {$ENDIF} end; // ............................................................................. // ***************************************************************************** // EVENT : btn_stopClick() // CLICK ON STOP BUTTON // ***************************************************************************** procedure TFServer.btn_stopClick(Sender: TObject); begin // ... before stopping the server ... send 'good bye' to all clients connected BroadcastMessage('Goodbye Client '); // ... stop server! IdTCPServer.Active := False; // ... hide stop button btn_stop.enabled := False; // ... show start button btn_start.enabled := True; // ... message log Display('SERVER', 'STOPPED!'); // ... stop UDP server! {$IFDEF UDP_ACTIVE} IdUDPServer.Active := False; {$ENDIF} end; // ............................................................................. // ***************************************************************************** // EVENT : btn_clearClick() // CLICK ON CLEAR BUTTON // ***************************************************************************** procedure TFServer.btn_clearClick(Sender: TObject); begin //... clear messages log MessagesLog.Lines.Clear; end; // ............................................................................. // ............................................................................. // ............................................................................. // ............................................................................. // ***************************************************************************** // EVENT : onConnect() // OCCURS ANY TIME A CLIENT IS CONNECTED // ***************************************************************************** procedure TFServer.IdTCPServerConnect(AContext: TIdContext); var ip: string; port: Integer; peerIP: string; peerPort: Integer; nClients: Integer; msgToClient: string; typeClient: string; begin // ... OnConnect is a TIdServerThreadEvent property that represents the event // handler signalled when a new client connection is connected to the server. // ... Use OnConnect to perform actions for the client after it is connected // and prior to execution in the OnExecute event handler. // ... see indy doc: // http://www.indyproject.org/sockets/docs/index.en.aspx // ... getting IP address and Port of Client that connected ip := AContext.Binding.IP; port := AContext.Binding.Port; peerIP := AContext.Binding.PeerIP; peerPort := AContext.Binding.PeerPort; // ... message log Display('SERVER', 'Client Connected!'); Display('SERVER', 'Port=' + IntToStr(port) + ' ' + '(PeerIP=' + peerIP + ' - ' + 'PeerPort=' + IntToStr(peerPort) + ')'); // ... display the number of clients connected ShowNumberOfClients(); // ... CLIENT CONNECTED: case port of GUEST_CLIENT_PORT: begin // ... GUEST CLIENTS typeClient := 'GUEST'; end; // ... end; // ... send the Welcome message to Client connected msgToClient := 'Welcome ' + typeClient + ' ' + 'Client :)'; AContext.Connection.IOHandler.WriteLn(msgToClient); end; // ............................................................................. // ***************************************************************************** // EVENT : onDisconnect() // OCCURS ANY TIME A CLIENT IS DISCONNECTED // ***************************************************************************** procedure TFServer.IdTCPServerDisconnect(AContext: TIdContext); var ip: string; port: Integer; peerIP: string; peerPort: Integer; nClients: Integer; begin // ... getting IP address and Port of Client that connected ip := AContext.Binding.IP; port := AContext.Binding.Port; peerIP := AContext.Binding.PeerIP; peerPort := AContext.Binding.PeerPort; // ... message log Display('SERVER', 'Client Disconnected! Peer=' + peerIP + ':' + IntToStr(peerPort)); // ... display the number of clients connected ShowNumberOfClients(true); end; // ............................................................................. // ***************************************************************************** // EVENT : onExecute() // ON EXECUTE THREAD CLIENT // ***************************************************************************** procedure TFServer.IdTCPServerExecute(AContext: TIdContext); var Port: Integer; PeerPort: Integer; PeerIP: string; msgFromClient: string; msgToClient: string; byteMsgFromClient: TIdBytes; byteBodyFromServer: TIdBytes; tmpBytes: TIdBytes; FileStream: TMemoryStream; LZip: TZCompressionStream; zipString, zipString2, zipString3: string; ansiStr: AnsiString; ZipStream, UnZipStream: TStream; size: Int64; len: Integer; tmpHeader: TReqPacketHeader; begin // ... OnExecute is a TIdServerThreadEvents event handler used to execute // the task for a client connection to the server. // ... here you can check connection status and buffering before reading // messages from client // ... see doc: // ... AContext.Connection.IOHandler.InputBufferIsEmpty // ... AContext.Connection.IOHandler.CheckForDataOnSource(<milliseconds>); // (milliseconds to wait for the connection to become readable) // ... AContext.Connection.IOHandler.CheckForDisconnect; // ... received a message from the client // ... get message from client msgFromClient := AContext.Connection.IOHandler.ReadLn; // ... getting IP address, Port and PeerPort from Client that connected PeerIP := AContext.Binding.PeerIP; PeerPort := AContext.Binding.PeerPort; // ... message log Display('CLIENT', '(Peer=' + PeerIP + ':' + IntToStr(PeerPort) + ') ' + msgFromClient); // ... // ... process message from Client byteMsgFromClient := IndyTextEncoding_ASCII.GetBytes(msgFromClient); if (byteMsgFromClient[0] = PACKET_DELIMITER_1) and (byteMsgFromClient[1] = PACKET_DELIMITER_2) then begin SetPacketHeader(byteMsgFromClient, PacketHeader); case PacketHeader.MsgType of PACKET_TYPE_REQ: begin PacketHeader.MsgType := 3; // Read BinaryFile FileStream := TMemoryStream.Create; try FileStream.LoadFromFile('3_1011.txt'); FileStream.Position := 0; SetLength(tmpBytes, FileStream.Size); FileStream.Read(tmpBytes[0], FileStream.Size); finally FileStream.Free; end; FillChar(tmpHeader, SizeOf(TReqPacketHeader), 0); SetPacketHeader(tmpBytes, tmpHeader); len := tmpHeader.BodySize; PacketHeader.BodySize := len; byteMsgFromClient := GetPacketHeaderBytes(PacketHeader); SetLength(byteBodyFromServer, len); // FillChar(byteBodyFromServer, len, #0); Move(tmpBytes[SizeOf(TReqPacketHeader)], byteBodyFromServer[0], len); // if FileExists('temp1.txt') then // DeleteFile('temp1.txt'); // Stream1 := TIdFileCreateStream.Create('temp1.txt'); // try // Stream1.WriteBuffer(Pointer(byteBodyFromServer)^, Length(byteBodyFromServer)); // finally // Stream1.Free; // end; AContext.Connection.IOHandler.Write(byteMsgFromClient); AContext.Connection.IOHandler.Write(byteBodyFromServer); end; PACKET_TYPE_NOTI: ; PACKET_TYPE_RES: begin len := PacketHeader.BodySize; SetLength(byteBodyFromServer, len); // FillChar(byteBodyFromServer, len, #0); Move(byteMsgFromClient[SizeOf(TReqPacketHeader)], byteBodyFromServer[0], len); AContext.Connection.IOHandler.Write(byteMsgFromClient); AContext.Connection.IOHandler.Write(byteBodyFromServer); end; end; end; // ... // ... send response to Client // FS := TFileStream.Create(TMP_FILE_NAME+'.gz', fmOpenRead or fmShareDenyWrite); // Decompress(TMP_FILE_NAME+'.gz', TMP_FILE_NAME+'.gz'+'.un'); // AContext.Connection.IOHandler.WriteLn('... message sent from server :)'); end; procedure TFServer.btn_sendClick(Sender: TObject); var byteMsgFromServer: TIdBytes; byteBodyFromServer: TIdBytes; FileStream: TMemoryStream; Stream1: TStream; len: Integer; begin // Read BinaryFile FileStream := TMemoryStream.Create; try FileStream.LoadFromFile('3_1011.txt'); FileStream.Position := 0; SetLength(byteMsgFromServer, FileStream.Size); FileStream.Read(byteMsgFromServer[0], FileStream.Size); finally FileStream.Free; end; // Response ¹ÞÀ½ if (byteMsgFromServer[0] = PACKET_DELIMITER_1) and (byteMsgFromServer[1] = PACKET_DELIMITER_2) then begin SetPacketHeader(byteMsgFromServer, PacketHeader); case PacketHeader.MsgType of PACKET_TYPE_REQ: ; PACKET_TYPE_NOTI: ; PACKET_TYPE_RES: begin len := PacketHeader.BodySize; SetLength(byteBodyFromServer, len); // FillChar(byteBodyFromServer, len, #0); Move(byteMsgFromServer[SizeOf(TReqPacketHeader)], byteBodyFromServer[0], len); SendContext.Connection.IOHandler.Write(byteMsgFromServer); SendContext.Connection.IOHandler.Write(byteBodyFromServer); if FileExists('temp1.txt') then DeleteFile('temp1.txt'); Stream1 := TIdFileCreateStream.Create('temp1.txt'); try Stream1.WriteBuffer(Pointer(byteBodyFromServer)^, Length(byteBodyFromServer)); finally Stream1.Free; end; end; end; end; end; // ............................................................................. // ***************************************************************************** // EVENT : onStatus() // ON STATUS CONNECTION // ***************************************************************************** procedure TFServer.IdTCPServerStatus(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin // ... OnStatus is a TIdStatusEvent property that represents the event handler // triggered when the current connection state is changed... // ... message log Display('SERVER', AStatusText); end; // ............................................................................. // ............................................................................. // ............................................................................. // ............................................................................. // ***************************************************************************** // EVENT : IdUDPRead() // OCCURS ANY TIME A CLIENT SEND MESSAGE // ***************************************************************************** procedure TFServer.IdUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var // DataStringStream: TStringStream; s: string; Port: Integer; PeerPort: Integer; PeerIP: string; msgFromClient: string; begin // DataStringStream := TStringStream.Create(''); // try try // ... get message from client // DataStringStream.CopyFrom(AData, AData.Size); // msgFromClient := DataStringStream.DataString; msgFromClient := BytesToString(AData); Display('UDPCLIENT', '(Peer=' + PeerIP + ':' + IntToStr(PeerPort) + ') ' + msgFromClient); // Memo1.Text := s; except on E: Exception do begin end; end; // finally // FreeAndNil(DataStringStream); // end; end; // ............................................................................. // ***************************************************************************** // FUNCTION : getNow() // GET MOW DATE TIME // ***************************************************************************** function TFServer.getNow(): string; begin Result := FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ': '; end; // ............................................................................. // ***************************************************************************** // PROCEDURE : broadcastMessage() // BROADCAST A MESSAGE TO ALL CLIENTS CONNECTED // ***************************************************************************** procedure TFServer.broadcastMessage(p_message: string); var tmpList: TList; contexClient: TidContext; nClients: Integer; i: integer; begin // ... send a message to all clients connected // ... get context Locklist tmpList := IdTCPServer.Contexts.LockList; try i := 0; while (i < tmpList.Count) do begin // ... get context (thread of i-client) contexClient := tmpList[i]; // ... send message to client contexClient.Connection.IOHandler.WriteLn(p_message); i := i + 1; end; finally // ... unlock list of clients! IdTCPServer.Contexts.UnlockList; end; end; // ............................................................................. // ***************************************************************************** // PROCEDURE : Display() // DISPLAY MESSAGE UPON SYSOUT // ***************************************************************************** procedure TFServer.Display(p_sender: string; p_message: string); begin // ... DISPLAY MESSAGE TThread.Queue(nil, procedure begin MessagesLog.Lines.Add('[' + p_sender + '] - ' + getNow() + ': ' + p_message); end); // ... see doc.. // ... TThread.Queue() causes the call specified by AMethod to // be asynchronously executed using the main thread, thereby avoiding // multi-thread conflicts. end; // ............................................................................. // ***************************************************************************** // PROCEDURE : ShowNumberOfClients() // NUMBER OF CLIENTS CONNECTD // ***************************************************************************** procedure TFServer.ShowNumberOfClients(p_disconnected: Boolean = False); var nClients: integer; begin try // ... get number of clients connected nClients := IdTCPServer.Contexts.LockList.Count; finally IdTCPServer.Contexts.UnlockList; end; // ... client disconnected? if p_disconnected then dec(nClients); // ... display TThread.Queue(nil, procedure begin clients_connected.Caption := IntToStr(nClients); end); end; // ............................................................................. function TFServer.LoadFileToStr(const FileName: TFileName): String; var FileStream : TFileStream; Bytes: TBytes; begin Result:= ''; FileStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try if FileStream.Size>0 then begin SetLength(Bytes, FileStream.Size); FileStream.Read(Bytes[0], FileStream.Size); end; Result:= TEncoding.ASCII.GetString(Bytes); finally FileStream.Free; end; end; procedure TFServer.StrToFile(const FileName, SourceString : string); var Stream : TFileStream; begin Stream:= TFileStream.Create(FileName, fmCreate); try Stream.WriteBuffer(Pointer(SourceString)^, Length(SourceString)); finally Stream.Free; end; end; function TFServer.Unzip(const zipped: string): string; var DecompressionStream: TDecompressionStream; Compressed: TBytesStream; Decompressed: TStringStream; begin Compressed := TBytesStream.Create(DecodeBase64(AnsiString(zipped))); try // window bits set to 15 + 16 for gzip DecompressionStream := TDecompressionStream.Create(Compressed, 15 + 16); try Decompressed := TStringStream.Create('', TEncoding.UTF8); try Decompressed.LoadFromStream(DecompressionStream); Result := Decompressed.DataString; finally Decompressed.Free; end; finally DecompressionStream.Free; end; finally Compressed.Free; end; end; function TFServer.ByteArrayToStream(const aContent: TArray<Byte>): TMemoryStream; begin Result := TMemoryStream.Create; try if Length(aContent) > 0 then Result.WriteBuffer(aContent[0], Length(aContent)); Result.Position := 0; except Result.Free; raise; end; end; function TFServer.StreamToByteArray(aStream: TMemoryStream): TArray<Byte>; begin if Assigned(aStream) then begin SetLength(Result, aStream.Size); if Length(Result) > 0 then Move(aStream.Memory^, Result[0], aStream.Size); end else SetLength(Result, 0); end; end.
unit Atributos; interface type // Mapeia uma classe como uma entidade persistente TEntity = class(TCustomAttribute) end; // Informa que um campo nao é persistente TTransient = class(TCustomAttribute) end; // Mapeia a classe de acordo com a tabela do banco de dados TTable = class(TCustomAttribute) private FName: String; FCatalog: String; FSchema: String; public constructor Create(pName, pCatalog, pSchema: String); overload; constructor Create(pName, pSchema: String); overload; constructor Create(pName: String); overload; property Name: String read FName write FName; property Catalog: String read FCatalog write FCatalog; property Schema: String read FSchema write FSchema; end; // Mapeia o identificador da classe, a chave primária na tabela do banco de dados TId = class(TCustomAttribute) private FNameField: String; public constructor Create(pNameField: String); property NameField: String read FNameField write FNameField; end; // Mapeia um campo de uma tabela no banco de dados TColumn = class(TCustomAttribute) private FName: String; FUnique: Boolean; FLength: Integer; public constructor Create(pName: String; pUnique: Boolean; pLength: Integer); overload; constructor Create(pName: String; pUnique: Boolean); overload; constructor Create(pName: String; pLength: Integer); overload; constructor Create(pName: String); overload; property Name: String read FName write FName; property Unique: Boolean read FUnique write FUnique; property Length: Integer read FLength write FLength; end; // Informa a estratégia de geração de valores para chaves primárias TGeneratedValue = class(TCustomAttribute) private { TABLE = chave gerada por uma tabela exclusiva para este fim SEQUENCE = utilização se sequence do banco de dados IDENTITY = utilização se identity do banco de dados AUTO = o provedor de persistência escolhe a estratégia mais adequada dependendo do banco de dados } FStrategy: String; FGenerator: String; public constructor Create(pStrategy, pGenerator: String); overload; constructor Create(pStrategy: String); overload; property Strategy: String read FStrategy write FStrategy; property Generator: String read FGenerator write FGenerator; end; implementation { TTable } constructor TTable.Create(pName, pCatalog, pSchema: String); begin FName := pName; FCatalog := pCatalog; FSchema := pSchema; end; constructor TTable.Create(pName, pSchema: String); begin FName := pName; FSchema := pSchema; end; constructor TTable.Create(pName: String); begin FName := pName; end; { TId } constructor TId.Create(pNameField: String); begin FNameField := pNameField; end; { TColumn } constructor TColumn.Create(pName: String; pUnique: Boolean; pLength: Integer); begin FName := pName; FUnique := pUnique; FLength := pLength; end; constructor TColumn.Create(pName: String; pLength: Integer); begin FName := pName; FLength := pLength; end; constructor TColumn.Create(pName: String; pUnique: Boolean); begin FName := pName; FUnique := pUnique; end; constructor TColumn.Create(pName: String); begin FName := pName; end; { TGeneratedValue } constructor TGeneratedValue.Create(pStrategy, pGenerator: String); begin FStrategy := pStrategy; FGenerator := pGenerator; end; constructor TGeneratedValue.Create(pStrategy: String); begin FStrategy := pStrategy; end; end.
{ Program PIC_CTRL options * * Control the individual lines of a PIC programmer. } program pic_ctrl; %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'stuff.ins.pas'; %include 'picprg.ins.pas'; const max_msg_args = 2; {max arguments we can pass to a message} type opt_k_t = ( {command line option internal opcode} opt_vdd_k, {set Vdd to R1 volts} opt_vpp_k, {set Vpp to R1 volts} opt_pgc_k, {set PGC to I1, either 0 or 1} opt_pgd_k, {set PGD to I1, either 0 or 1} opt_off_k); {high impedence to the extent possible} opt_p_t = ^opt_t; opt_t = record {info about one command line option} next_p: opt_p_t; {pointer to next sequential command line option} i1: sys_int_machine_t; {integer parameter} r1: real; {floating point parameter} opt: opt_k_t; {command line option ID} end; var pr: picprg_t; {PICPRG library state} opt_first_p: opt_p_t; {pointer to start of command line options chain} opt_last_p: opt_p_t; {pointer to last command line option in chain} opt_p: opt_p_t; {pointer to current stored command line option} r1: real; {scratch floating point parameter} newname: {new name to set in programmer} %include '(cog)lib/string256.ins.pas'; set_name: boolean; {set new name in programmer} opt: {upcased command line option} %include '(cog)lib/string_treename.ins.pas'; parm: {command line option parameter} %include '(cog)lib/string_treename.ins.pas'; pick: sys_int_machine_t; {number of token picked from list} msg_parm: {references arguments passed to a message} array[1..max_msg_args] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label next_opt, done_opt, err_parm, err_conflict, parm_bad, done_opts, done_cmd, cmd_nimp, dshow_vdd, dshow_vpp; { ****************************************************************** * * Subroutine OPT_ADD (OPT, I1, R1) * * Add a new command line option to the end of the chain of command line options. } procedure opt_add ( {add command line option to end of chain} in opt: opt_k_t; {ID for this command line option} in i1: sys_int_machine_t; {integer parameter} in r1: real); {floating point parameter} val_param; internal; var opt_p: opt_p_t; {pointer to new option descriptor} begin sys_mem_alloc (sizeof(opt_p^), opt_p); {allocate memory for new option descriptor} opt_p^.next_p := nil; {init to no option following} opt_p^.opt := opt; {fill in data about this command line option} opt_p^.i1 := i1; opt_p^.r1 := r1; if opt_last_p = nil then begin {this is first option in the chain} opt_first_p := opt_p; {init end of chain pointer} end else begin {there is an existing chain to link to the end of} opt_last_p^.next_p := opt_p; {link this new option to the end of the chain} end ; opt_last_p := opt_p; {update end of chain pointer} end; { ****************************************************************** * * Function NOT_IMPLEMENTED (STAT) * * Returns TRUE iff STAT indicates command not implemented within the PICPRG * subsystem. In that case STAT is cleared, else it is not altered. } function not_implemented ( {test STAT for PIC programmer command not implemented} in out stat: sys_err_t) {status to test, reset if not implemented indicated} :boolean; {TRUE if PIC programmer command not implemented} val_param; internal; begin not_implemented := sys_stat_match (picprg_subsys_k, picprg_stat_cmdnimp_k, stat); end; { ****************************************************************** * * Function OP_DONE (STAT) * * Check that an operation was performed and has completed without error. * STAT must be the status returned from the PICPRG call to perform * the operation. This function returns FALSE with no error if the operation * is not supported by the programmer. The program is aborted with an * appropriate error message is STAT indicates a hard error. * * If STAT indicates no error, then this routine waits for the operation to * complete and checks for resulting error to the extent supported by the * programmer. If an error is encountered, the program is aborted with * an appropriate error message. In that case, the operation indicated * by OPT_P is assumed to be what was performed. If the operation completed * successfully this function returns TRUE with STAT indicating no error. } function op_done ( {check for operation completed properly} in out stat: sys_err_t) {resulting status from initiating the operation} :boolean; {FALSE for not implemented, TRUE for success} val_param; internal; var flags: int8u_t; {flags returned by WAITCHK command} begin if not_implemented (stat) then begin {operation not implemented in programmer ?} op_done := false; return; end; sys_error_abort (stat, '', '', nil, 0); op_done := true; {indicate operation completed} picprg_cmdw_waitchk (pr, flags, stat); {try to get status after operation done} if not_implemented(stat) then return; {can't get completion status from this programmer ?} if (flags & 2#0001) <> 0 then begin {Vdd too low ?} sys_message_bomb ('picprg', 'vdd_low', 0, 0); end; if (flags & 2#0010) <> 0 then begin {Vdd too high ?} sys_message_bomb ('picprg', 'vdd_high', 0, 0); end; if (flags & 2#0100) <> 0 then begin {Vpp too low ?} sys_message_bomb ('picprg', 'vpp_low', 0, 0); end; if (flags & 2#1000) <> 0 then begin {Vpp too high ?} sys_message_bomb ('picprg', 'vpp_high', 0, 0); end; end; { ****************************************************************** * * Start of main routine. } begin string_cmline_init; {init for reading the command line} { * Initialize our state before reading the command line options. } picprg_init (pr); {select defaults for opening PICPRG library} opt_first_p := nil; {init chain of command line options to empty} opt_last_p := nil; set_name := false; {init to not set programmer name string} sys_envvar_get ( {init programmer name from environment variable} string_v('PICPRG_NAME'), {environment variable name} parm, {returned environment variable value} stat); if not sys_error(stat) then begin {envvar exists and got its value ?} string_copy (parm, pr.prgname); {initialize target programmer name} end; { * Back here each new command line option. } next_opt: string_cmline_token (opt, stat); {get next command line option name} if string_eos(stat) then goto done_opts; {exhausted command line ?} sys_error_abort (stat, 'string', 'cmline_opt_err', nil, 0); string_upcase (opt); {make upper case for matching list} string_tkpick80 (opt, {pick command line option name from list} '-SIO -VDD -VPP -CLKH -CLKL -DATH -DATL -OFF -N -SETNAME', pick); {number of keyword picked from list} case pick of {do routine for specific option} { * -SIO n } 1: begin string_cmline_token_int (pr.sio, stat); pr.devconn := picprg_devconn_sio_k; end; { * -VDD volts } 2: begin string_cmline_token_fpm (r1, stat); if sys_error(stat) then goto err_parm; opt_add (opt_vdd_k, 0, r1); end; { * -VPP volts } 3: begin string_cmline_token_fpm (r1, stat); if sys_error(stat) then goto err_parm; opt_add (opt_vpp_k, 0, r1); end; { * -CLKH } 4: begin opt_add (opt_pgc_k, 1, 0.0); end; { * -CLKL } 5: begin opt_add (opt_pgc_k, 0, 0.0); end; { * -DATH } 6: begin opt_add (opt_pgd_k, 1, 0.0); end; { * -DATL } 7: begin opt_add (opt_pgd_k, 0, 0.0); end; { * -OFF } 8: begin opt_add (opt_off_k, 0, 0.0); end; { * -N name } 9: begin string_cmline_token (pr.prgname, stat); {get programmer name} if sys_error(stat) then goto err_parm; end; { * -SETNAME name } 10: begin string_cmline_token (newname, stat); if sys_error(stat) then goto err_parm; set_name := true; end; { * Unrecognized command line option. } otherwise string_cmline_opt_bad; {unrecognized command line option} end; {end of command line option case statement} done_opt: {done handling this command line option} err_parm: {jump here on error with parameter} string_cmline_parm_check (stat, opt); {check for bad command line option parameter} goto next_opt; {back for next command line option} err_conflict: {this option conflicts with a previous opt} sys_msg_parm_vstr (msg_parm[1], opt); sys_message_bomb ('string', 'cmline_opt_conflict', msg_parm, 1); parm_bad: {jump here on got illegal parameter} string_cmline_reuse; {re-read last command line token next time} string_cmline_token (parm, stat); {re-read the token for the bad parameter} sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_vstr (msg_parm[2], opt); sys_message_bomb ('string', 'cmline_parm_bad', msg_parm, 2); done_opts: {done with all the command line options} { * All done reading the command line. } picprg_open (pr, stat); {open connection to the PIC programmer} sys_error_abort (stat, '', '', nil, 0); { * Set the user definable name in the programmer, if this was selected. } if set_name then begin {set new name in programmer ?} picprg_cmdw_nameset (pr, newname, stat); sys_error_abort (stat, '', '', nil, 0); end; { ******************** * * Loop thru all the stored command line options in sequence and perform each * action in turn. } opt_p := opt_first_p; {make first command line option current} while opt_p <> nil do begin {loop thru the list of command line options} case opt_p^.opt of { * Set Vdd to voltage R1. } opt_vdd_k: begin string_vstring (opt, '-VDD '(0), -1); {make equivalent command line option string} string_f_fp_fixed (parm, opt_p^.r1, 3); string_append (opt, parm); if abs(opt_p^.r1) < 0.001 then begin {0V specified ?} picprg_cmdw_vddoff (pr, stat); goto done_cmd; end; if pr.fwinfo.varvdd then begin {the programmer implements variable Vdd} if (opt_p^.r1 < pr.fwinfo.vddmin) or (opt_p^.r1 > pr.fwinfo.vddmax) then begin sys_msg_parm_real (msg_parm[1], pr.fwinfo.vddmin); sys_msg_parm_real (msg_parm[2], pr.fwinfo.vddmax); sys_message_bomb ('picprg', 'unsup_vdd', msg_parm, 2); end; if pr.fwinfo.cmd[65] then begin {VDD command is implemented} picprg_cmdw_vddoff (pr, stat); {make sure VDD off so new values takes effect} if sys_error(stat) then goto done_cmd; picprg_cmdw_vdd (pr, opt_p^.r1, stat); if sys_error(stat) then goto done_cmd; end else begin {no VDD command, try old VDDVALS} picprg_cmdw_vddvals (pr, opt_p^.r1, opt_p^.r1, opt_p^.r1, stat); if sys_error(stat) then goto done_cmd; end ; if sys_error(stat) then goto done_cmd; picprg_cmdw_vddnorm (pr, stat); end else begin {the programmer does not implement variable Vdd} if (opt_p^.r1 >= pr.fwinfo.vddmin) and (opt_p^.r1 <= pr.fwinfo.vddmax) then begin picprg_cmdw_vddnorm (pr, stat); {enable the fixed Vdd level} goto done_cmd; end; sys_msg_parm_real (msg_parm[1], (pr.fwinfo.vddmin + pr.fwinfo.vddmax) / 2.0); sys_message_bomb ('picprg', 'unsup_varvdd', msg_parm, 1); end ; end; { * Set Vpp to voltage R1. } opt_vpp_k: begin string_vstring (opt, '-VPP '(0), -1); {make equivalent command line option string} string_f_fp_fixed (parm, opt_p^.r1, 3); string_append (opt, parm); if abs(opt_p^.r1) < 0.001 then begin {0V specified ?} picprg_cmdw_vppoff (pr, stat); goto done_cmd; end; if (opt_p^.r1 <= pr.fwinfo.vppmax) and (opt_p^.r1 >= pr.fwinfo.vppmin) {this Vpp OK ?} then begin if pr.fwinfo.cmd[61] then begin {VPP command is implemented ?} picprg_cmdw_vppoff (pr, stat); {make sure off so that new value takes effect} if sys_error(stat) then goto done_cmd; picprg_cmdw_vpp (pr, opt_p^.r1, stat); if sys_error(stat) then goto done_cmd; end; picprg_cmdw_vppon (pr, stat); if sys_error(stat) then goto done_cmd; goto done_cmd; end; sys_msg_parm_real (msg_parm[1], pr.fwinfo.vppmin); sys_msg_parm_real (msg_parm[2], pr.fwinfo.vppmax); sys_message_bomb ('picprg', 'unsup_vpp', msg_parm, 2); end; { * Set PGC high/low according to I1. } opt_pgc_k: begin if opt_p^.i1 = 0 then begin {set PGC low} string_vstring (opt, '-CLKL'(0), -1); picprg_cmdw_clkl (pr, stat); end else begin {set PGC high} string_vstring (opt, '-CLKH'(0), -1); picprg_cmdw_clkh (pr, stat); end ; end; { * Set PGD high/low according to I1. } opt_pgd_k: begin if opt_p^.i1 = 0 then begin {set PGD low} string_vstring (opt, '-DATL'(0), -1); picprg_cmdw_datl (pr, stat); end else begin {set PGD high} string_vstring (opt, '-DATH'(0), -1); picprg_cmdw_dath (pr, stat); end ; end; { * Set all lines to high impedence to the extent possible. } opt_off_k: begin string_vstring (opt, '-OFF'(0), -1); picprg_cmdw_off (pr, stat); end; { * Unexpected command line option. } otherwise sys_msg_parm_int (msg_parm[1], ord(opt_p^.opt)); sys_message_bomb ('picprg', 'pic_ctrl_bad_opt', msg_parm, 1); end; done_cmd: {done processing the current command} if not op_done (stat) then begin {command not implemented by programmer} cmd_nimp: {common code to handle unimplemented command} { * The programmer doesn't implement a feature required to perform this * operation. OPT_P points to the operation and OPT is the string to * request the operation from the user's point of view. } sys_msg_parm_vstr (msg_parm[1], opt); sys_message_bomb ('picprg', 'pic_ctrl_unimpl', msg_parm, 1); end; opt_p := opt_p^.next_p; {advance to next operation in the list} end; {back to perform this new operation} { * Done with all the operations specifically requested by the user. * ******************** * * Read back the state of the signals to the extent possible and report their values * on standard output. } { * Show the programmer name if available. } picprg_cmdw_nameget (pr, parm, stat); {try to get user settable programmer name} if not not_implemented(stat) then begin {either got name or hard error ?} sys_error_abort (stat, '', '', nil, 0); {abort on hard error} writeln ('Name = "', parm.str:parm.len, '"'); end; { * Show Vdd voltage. } picprg_cmdw_getvdd (pr, r1, stat); {try to get Vdd voltage} if not sys_error(stat) then begin writeln ('Vdd =', r1:7:3); goto dshow_vdd; end; discard( not_implemented(stat) ); {clear command not implemented error, if any} sys_error_abort (stat, '', '', nil, 0); dshow_vdd: { * Show Vpp voltage. } picprg_cmdw_getvpp (pr, r1, stat); {try to get vpp voltage} if not sys_error(stat) then begin writeln ('Vpp =', r1:7:3); goto dshow_vpp; end; discard( not_implemented(stat) ); {clear command not implemented error, if any} sys_error_abort (stat, '', '', nil, 0); dshow_vpp: { * Disable the command stream timeout so that the current state will persist * until explicitly changed. } picprg_cmdw_ntout (pr, stat); {try to disable the command stream timeout} discard( not_implemented(stat) ); {silently skip it if this is not implemented} { * Reboot the control processor if the name was changed. This is cached * in the operating system in some cases. For example if the programmer * is plugged into the USB, the old name will stay cached in the driver and * programs using the new name will be unable to open it. Rebooting the * control processor is the same as unplugging the replugging the device, * which forces the driver to assume it is a different device and not * keep any cached data. * * This is the last thing this program does, since this could break the I/O * connection depending on how the programmer is connected. } if set_name then begin {new name was set in programmer ?} picprg_cmdw_reboot (pr, stat); {attempt to reboot, ignore errors} end; picprg_close (pr, stat); {disconnect from the programmer} end.
unit DVDInfo; {$WARNINGS OFF} interface USES FileInfo, Windows; type HIFOINFO = Pointer; //void __stdcall PDSSetCssSupport(int nCss);//set css support, 0--no support, other--support procedure PDSSetCssSupport(nCss: Integer); stdcall; //HIFOINFO __stdcall IFOOpen(const wchar_t * pPathFile); //open ifo file, return ifo handle function IFOOpen(pPathFile:PWideChar):HIFOINFO;stdcall; //void __stdcall IFOClose(HIFOINFO hIfoinfo); // close ifo handle procedure IFOClose(hIfoinfo: HIFOINFO ); stdcall; //int __stdcall IFOGetHaveCSSProtect(HIFOINFO hIfoinfo); // wether the disc have css protect -1 mean uncertain, 0 mean not, 1 mean have function GetHaveCSSProtect(hIfoinfo: HIFOINFO): Integer; stdcall; //int __stdcall IFOGetTitleCount(HIFOINFO hIfoinfo);//get title count of ifo function IFOGetTitleCount(hIfoinfo: HIFOINFO): Integer; stdcall; //int __stdcall IFOGetChapterCount(HIFOINFO hIfoinfo, int nTitleIndex);//get chapter count function IFOGetChapterCount(hIfoinfo: HIFOINFO; nTitleIndex: Integer): Integer; stdcall; //double __stdcall IFOGetTitleBeginTime(HIFOINFO hIfoinfo, int nTitleIndex);//get the title begin time function IFOGetTitleBeginTime(hIfoinfo: HIFOINFO; nTitleIndex: Integer): Double; stdcall; //double __stdcall IFOGetTitleLength(HIFOINFO hIfoinfo, int nTitleIndex);//get the title length function IFOGetTitleLength(hIfoinfo: HIFOINFO; nTitleIndex: Integer): Double; stdcall; //double __stdcall IFOGetChapterBeginTime(HIFOINFO hIfoinfo, int nTitleIndex, int nChapterIndex);//get the chapter begintime function IFOGetChapterBeginTime(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nChapterIndex: Integer): Double; stdcall; //double __stdcall IFOGetChapterLength(HIFOINFO hIfoinfo, int nTitleIndex, int nChapterIndex);//get the chapter length function IFOGetChapterLength(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nChapterIndex: Integer): Double; stdcall; //int __stdcall IFOGetTitleAudioTrackCount(HIFOINFO hIfoinfo, int nTitleIndex);//get audio track count function IFOGetTitleAudioTrackCount(hIfoinfo: HIFOINFO; nTitleIndex: Integer):Integer; stdcall; //const wchar_t * __stdcall IFOGetAudioTrackDesc(HIFOINFO hIfoinfo, int nTitleIndex, int nAudioTrackidx);//get audio track description function IFOGetAudioTrackDesc(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nAudioTrackidx: Integer):PWideChar; stdcall; //int __stdcall IFOGetTitleSubTitleCount(HIFOINFO hIfoinfo, int nTitleIndex);//get subtitle count function IFOGetTitleSubTitleCount(hIfoinfo: HIFOINFO; nTitleIndex: Integer):Integer; stdcall; //const wchar_t * __stdcall IFOGetSubTitleDesc(HIFOINFO hIfoinfo, int nTitleIndex, int nSubTitleidx);//get subtitle description function IFOGetSubTitleDesc(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nSubTitleidx: Integer):PWideChar; stdcall; //WORD __stdcall IFOGetAudioTrackLang(HIFOINFO hIfoinfo, int nTitleIndex, int nAudioTrackidx); function IFOGetAudioTrackLang(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nAudioTrackidx: Integer): WORD; stdcall; //const wchar_t * __stdcall IFOGetAudioFormatDesc(HIFOINFO hIfoinfo, int nTitleIndex, int nAudioTrackidx); function IFOGetAudioFormatDesc(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nAudioTrackidx: Integer):PWideChar; stdcall; //int __stdcall IFOGetAudioTrackID(HIFOINFO hIfoinfo, int nTitleIndex, int nAudioTrackidx); function IFOGetAudioTrackID(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nAudioTrackidx: Integer):Integer; stdcall; //int __stdcall IFOGetAudioChannel(HIFOINFO hIfoinfo, int nTitleIndex, int nAudioTrackidx); function IFOGetAudioChannel(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nAudioTrackidx: Integer):Integer; stdcall; //WORD __stdcall IFOGetSubLangCode(HIFOINFO hIfoinfo, int nTitleIndex, int nSubTitleidx); function IFOGetSubLangCode(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nSubTitleidx: Integer):WORD; stdcall; //int __stdcall IFOGetSubTitleTrackID(HIFOINFO hIfoinfo, int nTitleIndex, int nSubTitleidx); function IFOGetSubTitleTrackID(hIfoinfo: HIFOINFO; nTitleIndex: Integer; nSubTitleidx: Integer):Integer; stdcall; //BOOL __stdcall IFOTitleAvailable(HIFOINFO hIfoinfo, int nTitleIndex) function IFOTitleAvailable(hIfoinfo: HIFOINFO; nTitleIndex: Integer):boolean; stdcall; //MEDIA_FILE_INFO* __stdcall IFOGetFileInfo(HIFOINFO hIfoinfo); function IFOGetFileInfo(hIfoinfo: HIFOINFO): PMEDIA_FILE_INFO; stdcall; //int __stdcall ISOGetIFOCount(const wchar_t *pPath); //获得ISO中IFO的数目 function ISOGetIFOCount(pPath: PWideChar): Integer; stdcall; //BOOL _stdcall ISOGetISOVolumeName(const wchar_t *pPath, wchar_t *pVolumeName); //获取ISO 文件的名称 function ISOGetISOVolumeName(pPath, pVolumeName: PWideChar): BOOL; stdcall; implementation const DLLNAME = '.\DecPlugins\fdpDVD.dll'; procedure PDSSetCssSupport ; external DLLNAME index 101; function IFOOpen ; external DLLNAME Name 'IFOOpen'; procedure IFOClose ; external DLLNAME Name 'IFOClose'; function IFOGetTitleCount ; external DLLNAME Name 'IFOGetTitleCount'; function IFOGetChapterCount ; external DLLNAME Name 'IFOGetChapterCount'; function IFOGetTitleBeginTime ; external DLLNAME Name 'IFOGetTitleBeginTime'; function IFOGetTitleLength ; external DLLNAME Name 'IFOGetTitleLength'; function IFOGetChapterBeginTime ; external DLLNAME Name 'IFOGetChapterBeginTime'; function IFOGetChapterLength ; external DLLNAME Name 'IFOGetChapterLength'; function IFOGetTitleAudioTrackCount; external DLLName Name 'IFOGetTitleAudioTrackCount'; function IFOGetAudioTrackDesc ; external DLLName Name 'IFOGetAudioTrackDesc'; function IFOGetTitleSubTitleCount ; External DLLName Name 'IFOGetTitleSubTitleCount'; function IFOGetSubTitleDesc ; External DLLName Name 'IFOGetSubTitleDesc'; function IFOGetAudioTrackLang ; External DLLName Name 'IFOGetAudioTrackLang'; function IFOGetAudioFormatDesc ; External DLLName Name 'IFOGetAudioFormatDesc'; function IFOGetAudioTrackID ; External DLLName Name 'IFOGetAudioTrackID'; function IFOGetAudioChannel ; External DLLName Name 'IFOGetAudioChannel'; function IFOGetSubLangCode ; External DLLName Name 'IFOGetSubLangCode'; function IFOGetSubTitleTrackID ; External DLLName Name 'IFOGetSubTitleTrackID'; function IFOTitleAvailable ; External DLLName Name 'IFOTitleAvailable'; function IFOGetFileInfo ; External DLLName Name 'IFOGetFileInfo'; function ISOGetIFOCount ; External DLLName Name 'ISOGetIFOCount'; function ISOGetISOVolumeName ; External DLLName Name 'ISOGetISOVolumeName'; end.
{ GeoJSON/Geometry/Point Object Test Copyright (c) 2018 Gustavo Carreno <guscarreno@gmail.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. } unit lazGeoJSONTest.GeoJSON.Geometry.Point; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, {testutils,} testregistry, fpjson, lazGeoJSON, lazGeoJSON.Utils, lazGeoJSON.Geometry.Point; type { TTestGeoJSONPoint } TTestGeoJSONPoint= class(TTestCase) private FGeoJSONPoint: TGeoJSONPoint; protected public published procedure TestPointCreate; procedure TestPointCreateJSONWrongObject; procedure TestPointCreateJSONWrongFormedObjectWithEmptyObject; procedure TestPointCreateJSONWrongFormedObjectWithMissingMember; procedure TestPointCreateJSON; procedure TestPointCreateJSONDataWrongObject; procedure TestPointCreateJSONDataWrongFormedObjectWithEmptyObject; procedure TestPointCreateJSONDataWrongFormedObjectWithMissingMember; procedure TestPointCreateJSONData; procedure TestPointCreateJSONObjectWrongFormedObjectWithEmptyObject; procedure TestPointCreateJSONObjectWrongFormedObjectWithMissingMember; procedure TestPointCreateJSONObject; procedure TestPointCreateStreamWrongObject; procedure TestPointCreateStreamWrongFormedObjectWithEmptyObject; procedure TestPointCreateStreamWrongFormedObjectWithMissingMember; procedure TestPointCreateStream; procedure TestPointAsJSON; end; implementation uses lazGeoJSONTest.Common; { TTestGeoJSONPoint } procedure TTestGeoJSONPoint.TestPointCreate; begin FGeoJSONPoint:= TGeoJSONPoint.Create; AssertEquals('GeoJSON Object type gjtPoint', Ord(FGeoJSONPoint.GeoJSONType), Ord(gjtPoint)); FGeoJSONPoint.Free; end; procedure TTestGeoJSONPoint.TestPointCreateJSONWrongObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(cJSONEmptyArray); except on e: EPointWrongObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongObject on empty array', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONDataWrongObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONEmptyArray)); except on e: EPointWrongObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongObject on empty array', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONDataWrongFormedObjectWithEmptyObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONEmptyObject)); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on empty object', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONDataWrongFormedObjectWithMissingMember; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONPointObjectNoPosition)); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on object missing member', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONObjectWrongFormedObjectWithEmptyObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONEmptyObject) as TJSONObject); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on empty object', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONObjectWrongFormedObjectWithMissingMember; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONPointObjectNoPosition) as TJSONObject); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on object missing member', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONObject; begin FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONPointObject) as TJSONObject); AssertEquals('GeoJSON Object type gjtPoint', Ord(FGeoJSONPoint.GeoJSONType), Ord(gjtPoint)); FGeoJSONPoint.Free; end; procedure TTestGeoJSONPoint.TestPointCreateStreamWrongObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(TStringStream.Create(cJSONEmptyArray)); except on e: EPointWrongObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongObject on empty array', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateStreamWrongFormedObjectWithEmptyObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(TStringStream.Create(cJSONEmptyObject)); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on empty object', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateStreamWrongFormedObjectWithMissingMember; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(TStringStream.Create(cJSONPointObjectNoPosition)); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on object missing member', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateStream; begin FGeoJSONPoint:= TGeoJSONPoint.Create(TStringStream.Create(cJSONPointObject)); AssertEquals('GeoJSON Object type gjtPoint', Ord(FGeoJSONPoint.GeoJSONType), Ord(gjtPoint)); FGeoJSONPoint.Free; end; procedure TTestGeoJSONPoint.TestPointCreateJSONWrongFormedObjectWithEmptyObject; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(cJSONEmptyObject); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on empty object', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSONWrongFormedObjectWithMissingMember; var gotException: Boolean; begin gotException:= False; try try FGeoJSONPoint:= TGeoJSONPoint.Create(cJSONPointObjectNoPosition); except on e: EPointWrongFormedObject do begin gotException:= True; end; end; finally FGeoJSONPoint.Free; end; AssertEquals('Got Exception EPointWrongFormedObject on object missing member', True, gotException); end; procedure TTestGeoJSONPoint.TestPointCreateJSON; begin FGeoJSONPoint:= TGeoJSONPoint.Create(cJSONPointObject); AssertEquals('GeoJSON Object type gjtPoint', Ord(FGeoJSONPoint.GeoJSONType), Ord(gjtPoint)); FGeoJSONPoint.Free; end; procedure TTestGeoJSONPoint.TestPointCreateJSONData; begin FGeoJSONPoint:= TGeoJSONPoint.Create(GetJSONData(cJSONPointObject)); AssertEquals('GeoJSON Object type gjtPoint', Ord(FGeoJSONPoint.GeoJSONType), Ord(gjtPoint)); FGeoJSONPoint.Free; end; procedure TTestGeoJSONPoint.TestPointAsJSON; begin FGeoJSONPoint:= TGeoJSONPoint.Create(cJSONPointObject); AssertEquals('Point asJSON I', cJSONPointObject, FGeoJSONPoint.asJSON); FGeoJSONPoint.Free; end; initialization RegisterTest(TTestGeoJSONPoint); end.
// WinRTDimItem.pas // Copyright 1998 BlueWater Systems // // Implementation of classes to keep track of shadow variables. // unit WinRTDimItem; interface uses Windows, WinRTCtl; type tDimItem = class fListNo : integer; fData : pointer; fsize : integer; Constructor create(ListNo : pointer; var data; size : integer); Procedure Get(var buff : tWINRT_CONTROL_array); virtual; Procedure Put(var buff : tWINRT_CONTROL_array); virtual; end; tDimStrItem = class(tDimItem) Constructor create(ListNo : pointer; var s : string; size : integer); Procedure Get(var buff : tWINRT_CONTROL_array); override; Procedure Put(var buff : tWINRT_CONTROL_array); override; end; implementation var DimStrItemsav : tDimStrItem; { ---------------------------------------------------------------------------- } { tDimItem methods } { ---------------------------------------------------------------------------- } // tDimItem.create - constructor for the dimitem // Inputs: ListNo - pseudo pointer to a shadow variable // Data - Pascal variable being shadowed // size - size of the Pascal variable, in bytes // Outputs: none Constructor tDimItem.create(ListNo : pointer; var Data; size : integer); begin inherited create; fListNo := integer(ListNo); fData := @Data; fsize := size end; { create } // tDimItem.Get - copy data from a WINRT_CONTROL_array into the pascal variable // Inputs: buff - the buffer to copy data from // Outputs: none Procedure tDimItem.Get(var buff : tWINRT_CONTROL_array); begin system.move(buff[fListNo].value, fData^, fsize); end; { Get } // tDimItem.Put - copy data from the Pascal variable into a WINRT_CONTROL_array // Inputs: buff - buffer to copy data into // Outputs: none Procedure tDimItem.Put(var buff : tWINRT_CONTROL_array); begin system.move(fData^, buff[fListNo].value, fsize); end; { Put } { --------------------------------------------------------------------------- } { tDimStrItem methods } { --------------------------------------------------------------------------- } // tDimStrItem.create - constructor for the tDimStrItem class // Inputs: ListNo - pseudo pointer to the shadow variable // s - Pascal string to be shadowed // size - length of the string // Outputs: none Constructor tDimStrItem.create(ListNo : pointer; var s : string; size : integer); begin inherited create(ListNo, pointer(s), size); DimStrItemsav := self; end; { create } // tDimStrItem.Get - copy data from a WINRT_CONTROL_array into the pascal variable // Inputs: buff - the buffer to copy data from // Outputs: none Procedure tDimStrItem.Get(var buff : tWINRT_CONTROL_array); var arrayp : pchar; begin arrayp := pchar(@buff[flistNo].value); arrayp[fsize] := #0; string(fdata^) := arrayp; end; { Get } // tDimStrItem.Put - copy data from the Pascal variable into a WINRT_CONTROL_array // Inputs: buff - buffer to copy data into // Outputs: none Procedure tDimStrItem.Put(var buff : tWINRT_CONTROL_array); begin if pointer(fdata^) <> nil then { nothing to move if an empty string } system.move(pointer(fdata^)^, buff[flistNo].value, fsize); end; { Put } end.
{ -------------------------------------------------------------------------------------} { An "application launcher" component for Delphi32. } { Copyright 1996, Patrick Brisacier and Jean-Fabien Connault. All Rights Reserved. } { This component can be freely used and distributed in commercial and private } { environments, provided this notice is not modified in any way. } { -------------------------------------------------------------------------------------} { Feel free to contact us if you have any questions, comments or suggestions at } { cycocrew@aol.com } { -------------------------------------------------------------------------------------} { Date last modified: 08/07/96 } { -------------------------------------------------------------------------------------} { -------------------------------------------------------------------------------------} { TAppExec v1.01 } { -------------------------------------------------------------------------------------} { Description: } { A component that allows you to execute easily applications. } { Properties: } { property ChangeDir: Boolean; } { property ErrNo: Integer; } { property ExeName: String; } { property ExePath: String; } { property ExeParams: TStringList; } { property Wait: Boolean; } { property WindowState: TWindowState; } { Procedures and functions: } { procedure Clear; } { procedure Execute; } { function GetErrorString: string; } { } { See example contained in example.zip file for more details. } { -------------------------------------------------------------------------------------} { Revision History: } { 1.00: + Initial release } { 1.01: + Added support for french and english languages } { -------------------------------------------------------------------------------------} unit appexec; {$IFNDEF WIN32} // Delphi Analizer did not handle this... // ERROR! This unit only available on Win32! {$ENDIF} interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs; type EAppExec = class(Exception); EAppExecChDir = class(EAppExec); EAppExecWinExec = class(EAppExec); TAppExec = class(TComponent) private { Private-déclarations } FErrNo: Integer; FExeName: String; FExePath: String; FExeParams: TStringList; FWindowState: TWindowState; FMode: Word; FChangeDir: Boolean; FWait: Boolean; procedure SetWindowState(AWindowState: TWindowState); procedure SetExeParams(AExeParams: TStringList); procedure SetExePath(AExePath: String); protected { Protected-déclarations } public { Public-déclarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Execute; function GetErrorString: string; procedure Clear; published { Published-déclarations } property ChangeDir: Boolean read FChangeDir write FChangeDir default True; property ErrNo: Integer read FErrNo; property ExeName: String read FExeName write FExeName; property ExeParams: TStringList read FExeParams write SetExeParams; property ExePath: String read FExePath write SetExePath; property Wait:Boolean read FWait write FWait; property WindowState: TWindowState read FWindowState write SetWindowState; end; const { French Messages } { MSG_ERROR_DASH_1 = 'Pas d''exécution'; MSG_ERROR_0 = 'Système dépassé en capacité mémoire, exécutable corrompu, ou réallocations invalides'; MSG_ERROR_2 = 'Fichier non trouvé'; MSG_ERROR_3 = 'Chemin non trouvé'; MSG_ERROR_5 = 'Tentative de liaison dynamique à une tâche, ou erreur de partage, ou erreur de protection réseau'; MSG_ERROR_6 = 'Librairie nécessitant des segments de données séparés pour chaque tâche'; MSG_ERROR_8 = 'Mémoire insuffisante pour démarrer l''application'; MSG_ERROR_10 = 'Version de Windows incorrecte'; MSG_ERROR_11 = 'Exécutable invalide, application non Windows, ou erreur dans l''image du fichier .EXE'; MSG_ERROR_12 = 'Application écrite pour un système d''exploitation différent'; MSG_ERROR_13 = 'Application écrite pour MS-DOS 4.0'; MSG_ERROR_14 = 'Type d''exécutable inconnu'; MSG_ERROR_15 = 'Tentative de chargement d''une application en mode réel (développée pour une version antérieure de Windows)'; MSG_ERROR_16 = 'Tentative de chargement d''une seconde instance d''un exécutable contenant plusieurs segments de données non marqués en lecture seule'; MSG_ERROR_19 = 'Tentative de chargement d''un exécutable compressé. Le fichier doit être décompressé avant de pouvoir être chargé'; MSG_ERROR_20 = 'Fichier Dynamic-link library (DLL) invalide. Une des DLLs requises pour exécuter cette application est corrompue'; MSG_ERROR_21 = 'Application nécessitant des extensions 32-bit'; MSG_ERROR_32_AND_MORE = 'Pas d''erreur'; } { English Messages } MSG_ERROR_DASH_1 = 'No execution'; MSG_ERROR_0 = 'System was out of memory, executable file was corrupt, or relocations were invalid'; MSG_ERROR_2 = 'File was not found'; MSG_ERROR_3 = 'Path was not found'; MSG_ERROR_5 = 'Attempt was made to dynamically link to a task, or there was a sharing or network-protection error'; MSG_ERROR_6 = 'Library required separate data segments for each task'; MSG_ERROR_8 = 'There was insufficient memory to start the application'; MSG_ERROR_10 = 'Windows version was incorrect'; MSG_ERROR_11 = 'Executable file was invalid. Either it was not a Windows application or there was an error in the .EXE image'; MSG_ERROR_12 = 'Application was designed for a different operating system'; MSG_ERROR_13 = 'Application was designed for MS-DOS 4.0'; MSG_ERROR_14 = 'Type of executable file was unknown'; MSG_ERROR_15 = 'Attempt was made to load a real-mode application (developed for an earlier version of Windows)'; MSG_ERROR_16 = 'Attempt to load second instance of an executable containing multiple data segments not marked read-only'; MSG_ERROR_19 = 'Attempt was made to load a compressed executable file. The file must be decompressed before it can be loaded'; MSG_ERROR_20 = 'Dynamic-link library (DLL) file was invalid. One of the DLLs required to run this application was corrupt'; MSG_ERROR_21 = 'Application requires 32-bit extensions'; MSG_ERROR_32_AND_MORE = 'No error'; procedure Register; implementation procedure Register; begin RegisterComponents('Misc', [TAppExec]); end; constructor TAppExec.Create(AOwner: TComponent); begin inherited Create(AOwner); FExeParams := TStringList.Create; FMode := SW_SHOWNORMAL; FErrNo := -1; FChangeDir := True; end; destructor TAppExec.Destroy; begin FExeParams.Free; inherited Destroy; end; procedure TAppExec.Execute; var //InstanceID : THandle; buffer: array[0..511] of Char; bufferParams : array[0..511] of Char; TmpStr: String; i: Integer; StartupInfo:TStartupInfo; ProcessInfo:TProcessInformation; begin { Création de la ligne de commande } TmpStr := FExeName; StrPCopy(buffer,TmpStr); for i := 0 to FExeParams.Count - 1 do TmpStr := TmpStr + ' ' + FExeParams.Strings[i]; StrPCopy(bufferParams, TmpStr); { Changement de répertoire } if FChangeDir and (FExePath <> '') then begin try ChDir(FExePath); except On E:Exception do raise EAppExecChDir.Create(E.Message); end; end; { Execution } FillChar(StartupInfo,Sizeof(StartupInfo),#0); StartupInfo.cb := Sizeof(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := FMode; if not CreateProcessA(buffer, bufferParams, { pointer to command line string } nil, { pointer to process security attributes } nil, { pointer to thread security attributes } false, { handle inheritance flag } CREATE_NEW_CONSOLE or { creation flags } NORMAL_PRIORITY_CLASS, nil, { pointer to new environment block } nil, { pointer to current directory name } StartupInfo, { pointer to STARTUPINFO } ProcessInfo) then begin { pointer to PROCESS_INF } FErrNo := GetLastError(); raise EAppExecWinExec.Create(GetErrorString); end else if FWait then begin WaitforSingleObject(ProcessInfo.hProcess,INFINITE); { GetExitCodeProcess(ProcessInfo.hProcess, ErrNo); } FErrNo := 0; end; end; procedure TAppExec.SetWindowState(AWindowState: TWindowState); const Mode: array[wsNormal..wsMaximized] of Word = (SW_SHOWNORMAL, SW_SHOWMINIMIZED, SW_SHOWMAXIMIZED); begin if FWindowState <> AWindowState then begin FMode := Mode[AWindowState]; FWindowState := AWindowState; end; end; procedure TAppExec.SetExeParams(AExeParams: TStringList); begin FExeParams.Assign(AExeParams); end; procedure TAppExec.SetExePath(AExePath: String); begin if FExePath <> AExePath then begin FExePath := AExePath; if ((FExePath[Length(FExePath)] = '\') and (FExePath <> '\') and (not ((Length(FExePath) = 3) and (FExePath[2] = ':') and (FExePath[3] = '\')) ) ) then FExePath := Copy(FExePath, 1, Length(FExePath) - 1); end; end; procedure TAppExec.Clear; begin FErrNo := -1; FExeName := ''; FExePath := ''; FExeParams.Clear; end; function TAppExec.GetErrorString: string; begin case FErrNo of -1: Result := MSG_ERROR_DASH_1; 0: Result := MSG_ERROR_0; 2: Result := MSG_ERROR_2; 3: Result := MSG_ERROR_3; 5: Result := MSG_ERROR_5; 6: Result := MSG_ERROR_6; 8: Result := MSG_ERROR_8; 10: Result := MSG_ERROR_10; 11: Result := MSG_ERROR_11; 12: Result := MSG_ERROR_12; 13: Result := MSG_ERROR_13; 14: Result := MSG_ERROR_14; 15: Result := MSG_ERROR_15; 16: Result := MSG_ERROR_16; 19: Result := MSG_ERROR_19; 20: Result := MSG_ERROR_20; 21: Result := MSG_ERROR_21; 32..MaxInt: Result := MSG_ERROR_32_AND_MORE; end; end; end.
{ Subroutine STRING_F_BITS16 (S, BITS) * * Convert the low 16 bits in BITS into a 16 character string of ones or * zeroes in S. The string length is truncated to the maximum of S. } module string_f_bits16; define string_f_bits16; %include 'string2.ins.pas'; procedure string_f_bits16 ( {16 digit binary string from 16 bit integer} in out s: univ string_var_arg_t; {output string} in bits: sys_int_min16_t); {input integer, uses low 32 bits} val_param; var i: sys_int_max_t; {integer of right format for convert routine} stat: sys_err_t; {error code} begin i := bits & 16#FFFF; {into format for convert routine} string_f_int_max_base ( {make string from integer} s, {output string} i, {input integer} 2, {number base} 16, {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;
unit UFichaConstrucaoC; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, Mask, ToolEdit, Grids, DBGrids, SMDBGrid, DB, CurrEdit, DBCtrls, RxLookup, DBFilter, DBClient, FMTBcd, Provider, SqlExpr; type TfFichaConstrucaoC = class(TForm) Panel1: TPanel; BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; Label1: TLabel; DateEdit1: TDateEdit; DateEdit2: TDateEdit; Label2: TLabel; SMDBGrid1: TSMDBGrid; StaticText1: TStaticText; BitBtn5: TBitBtn; Label4: TLabel; CurrencyEdit1: TCurrencyEdit; Label5: TLabel; Panel2: TPanel; BitBtn4: TBitBtn; Label3: TLabel; Edit1: TEdit; Edit2: TEdit; sdsPosicao_Ficha: TSQLDataSet; dspPosicao_Ficha: TDataSetProvider; cdsPosicao_Ficha: TClientDataSet; dsPosicao_Ficha: TDataSource; sdsPosicao_FichaID: TIntegerField; sdsPosicao_FichaNOMEPOSICAO: TStringField; sdsPosicao_FichaORDEM: TIntegerField; sdsPosicao_FichaSOMENTEMATERIAL: TStringField; sdsPosicao_FichaINFORMARGRADE: TStringField; sdsPosicao_FichaINFORMAROPCAOMAT: TStringField; cdsPosicao_FichaID: TIntegerField; cdsPosicao_FichaNOMEPOSICAO: TStringField; cdsPosicao_FichaORDEM: TIntegerField; cdsPosicao_FichaSOMENTEMATERIAL: TStringField; cdsPosicao_FichaINFORMARGRADE: TStringField; cdsPosicao_FichaINFORMAROPCAOMAT: TStringField; sdsFichaConstrucao: TSQLDataSet; sdsFichaConstrucaoID: TIntegerField; sdsFichaConstrucaoNOMECONSTRUCAO: TStringField; sdsFichaConstrucaoNOMEFORMA: TStringField; sdsFichaConstrucaoOBS: TMemoField; sdsFichaConstrucaoDATA: TDateField; sdsFichaConstrucaoUSUARIO: TStringField; sdsFichaConstrucaoHRUSUARIO: TTimeField; sdsFichaConstrucaoDTUSUARIO: TDateField; dspFichaConstrucao: TDataSetProvider; cdsFichaConstrucao: TClientDataSet; cdsFichaConstrucaoID: TIntegerField; cdsFichaConstrucaoNOMECONSTRUCAO: TStringField; cdsFichaConstrucaoNOMEFORMA: TStringField; cdsFichaConstrucaoOBS: TMemoField; cdsFichaConstrucaoDATA: TDateField; cdsFichaConstrucaoUSUARIO: TStringField; cdsFichaConstrucaoHRUSUARIO: TTimeField; cdsFichaConstrucaoDTUSUARIO: TDateField; dsFichaConstrucao: TDataSource; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BitBtn3Click(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure SMDBGrid1DblClick(Sender: TObject); procedure BitBtn5Click(Sender: TObject); procedure BitBtn4Click(Sender: TObject); private { Private declarations } procedure Gravar_FichaConstrucao_Pos; public { Public declarations } procedure Monta_FichaConstrucaoLoc(Tipo : String ; ID : Integer); //P=Com Parametros N=Sem Parametros procedure Monta_FichaConstrucao(ID : Integer); //P=Com Parametros N=Sem Parametros procedure Inserir_FichaConstrucao; end; var fFichaConstrucaoC: TfFichaConstrucaoC; implementation uses DateUtils, UDM1, UDMFichaConstrucao, UFichaConstrucao, UDMPosicao_Ficha, uIntegracao, URelFichaConstrucao; {$R *.dfm} procedure TfFichaConstrucaoC.FormClose(Sender: TObject; var Action: TCloseAction); begin if DMFichaConstrucao.Owner.ClassName = Self.ClassName then FreeAndNil(DMFichaConstrucao); if DMPosicao_Ficha.Owner.ClassName = Self.ClassName then FreeAndNil(DMPosicao_Ficha); Action := Cafree; end; procedure TfFichaConstrucaoC.BitBtn3Click(Sender: TObject); begin Monta_FichaConstrucaoLoc('P',0); end; procedure TfFichaConstrucaoC.Monta_FichaConstrucaoLoc(Tipo : String ; ID : Integer); //P=Com Parametros N=Sem Parametros begin cdsFichaConstrucao.Close; sdsFichaConstrucao.CommandText := ' SELECT * FROM FICHACONSTRUCAO '; if ID > 0 then begin sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' WHERE ID = ' + IntToStr(ID); end else if Tipo = 'P' then begin sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' WHERE 0=0 '; if DateEdit1.Date > 0 then sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' AND DATA >= ' + QuotedStr(FormatDateTime('MM/DD/YYYY',DateEdit1.date)); if DateEdit2.Date > 0 then sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' AND DATA <= ' + QuotedStr(FormatDateTime('MM/DD/YYYY',DateEdit2.date)); if Trim(Edit1.Text) <> '' then sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' AND NOMECONSTRUCAO = ' + QuotedStr('%'+Edit1.Text+'%'); if Trim(Edit2.Text) <> '' then sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' AND NOMEFORMA LIKE ' + QuotedStr('%'+Edit2.Text+'%'); sdsFichaConstrucao.CommandText := sdsFichaConstrucao.CommandText + ' ORDER BY DATA, ID '; end else sdsFichaConstrucao.CommandText := ctFichaConstrucao + ' WHERE ID = 0'; cdsFichaConstrucao.Open; end; procedure TfFichaConstrucaoC.Monta_FichaConstrucao(ID : Integer); begin DMFichaConstrucao.cdsFichaConstrucao.Close; DMFichaConstrucao.sdsFichaConstrucao.CommandText := ctFichaConstrucao + ' WHERE ID = ' + IntToStr(ID); DMFichaConstrucao.cdsFichaConstrucao.Open; end; procedure TfFichaConstrucaoC.BitBtn2Click(Sender: TObject); begin if cdsFichaConstrucao.IsEmpty then exit; Monta_FichaConstrucao(cdsFichaConstrucaoID.AsInteger); if DMFichaConstrucao.cdsFichaConstrucao.IsEmpty then exit; if MessageDlg('Deseja excluir este registro?',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit; DMFichaConstrucao.cdsFichaConstrucao.Delete; DMFichaConstrucao.cdsFichaConstrucao.ApplyUpdates(0); end; procedure TfFichaConstrucaoC.BitBtn1Click(Sender: TObject); begin Monta_FichaConstrucao(0); Inserir_FichaConstrucao; Gravar_FichaConstrucao_Pos; fFichaConstrucao := TfFichaConstrucao.Create(Self); fFichaConstrucao.Tag := 0; fFichaConstrucao.ShowModal; end; procedure TfFichaConstrucaoC.FormShow(Sender: TObject); var vData : TDateTime; begin if not Assigned(DMFichaConstrucao) then DMFichaConstrucao := TDMFichaConstrucao.Create(Self); if not Assigned(DMPosicao_Ficha) then DMPosicao_Ficha := TDMPosicao_Ficha.Create(Self); vData := EncodeDate(YearOf(Date),MonthOf(Date),01); DateEdit1.Date := vData; DateEdit2.Date := Date; BitBtn1.Enabled := DM1.tUsuarioInsFichaConstrucao.AsBoolean; BitBtn2.Enabled := DM1.tUsuarioExcFichaConstrucao.AsBoolean; end; procedure TfFichaConstrucaoC.SMDBGrid1DblClick(Sender: TObject); begin if cdsFichaConstrucao.IsEmpty then exit; Monta_FichaConstrucao(cdsFichaConstrucaoID.AsInteger); if DMFichaConstrucao.cdsFichaConstrucao.IsEmpty then exit; if not DM1.tUsuarioAltFichaConstrucao.AsBoolean then begin ShowMessage('Usuário ' + DM1.tUsuarioUsuario.AsString + ' não autorizado a fazer a alteração!'); exit; end; DMFichaConstrucao.cdsFichaConstrucao.Edit; fFichaConstrucao := TfFichaConstrucao.Create(Self); fFichaConstrucao.Tag := 1; fFichaConstrucao.ShowModal; end; procedure TfFichaConstrucaoC.BitBtn5Click(Sender: TObject); begin Close; end; procedure TfFichaConstrucaoC.Inserir_FichaConstrucao; var vNumAux : Integer; begin vNumAux := ProximaSequencia('FICHACONSTRUCAO',0); DMFichaConstrucao.cdsFichaConstrucao.Insert; DMFichaConstrucao.cdsFichaConstrucaoID.AsInteger := vNumAux; DMFichaConstrucao.cdsFichaConstrucaoDATA.AsDateTime := Date; DMFichaConstrucao.cdsFichaConstrucaoUSUARIO.AsString := DM1.tUsuarioUsuario.AsString; DMFichaConstrucao.cdsFichaConstrucaoDTUSUARIO.AsDateTime := Date; DMFichaConstrucao.cdsFichaConstrucaoHRUSUARIO.AsDateTime := Now; DMFichaConstrucao.cdsFichaConstrucaoUSUARIO.AsString := DM1.tUsuarioUsuario.AsString; end; procedure TfFichaConstrucaoC.BitBtn4Click(Sender: TObject); begin if cdsFichaConstrucao.IsEmpty then exit; Monta_FichaConstrucao(cdsFichaConstrucaoID.AsInteger); fRelFichaConstrucao := TfRelFichaConstrucao.Create(Self); fRelFichaConstrucao.RLReport1.Preview; fRelFichaConstrucao.RLReport1.Free; end; procedure TfFichaConstrucaoC.Gravar_FichaConstrucao_Pos; var vItemAux : Integer; begin vItemAux := 0; cdsPosicao_Ficha.Close; cdsPosicao_Ficha.Open; cdsPosicao_Ficha.First; while not cdsPosicao_Ficha.Eof do begin vItemAux := vItemAux + 1; DMFichaConstrucao.cdsFichaConstrucao_Pos.Insert; DMFichaConstrucao.cdsFichaConstrucao_PosID.AsInteger := DMFichaConstrucao.cdsFichaConstrucaoID.AsInteger; DMFichaConstrucao.cdsFichaConstrucao_PosITEM.AsInteger := vItemAux; DMFichaConstrucao.cdsFichaConstrucao_PosNOMEPOSICAO.AsString := cdsPosicao_FichaNomePosicao.AsString; DMFichaConstrucao.cdsFichaConstrucao_PosSOMENTEMATERIAL.AsString := cdsPosicao_FichaSOMENTEMATERIAL.AsString; DMFichaConstrucao.cdsFichaConstrucao_PosINFORMARGRADE.AsString := cdsPosicao_FichaINFORMARGRADE.AsString; DMFichaConstrucao.cdsFichaConstrucao_PosINFORMAROPCAOMAT.AsString := cdsPosicao_FichaINFORMAROPCAOMAT.AsString; DMFichaConstrucao.cdsFichaConstrucao_Pos.Post; cdsPosicao_Ficha.Next; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller relacionado à tabela [LOGSS] 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 LogssController; interface uses Classes, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, LogssVO, Generics.Collections; type TLogssController = class(TController) private class var FDataSet: TClientDataSet; public class procedure VerificarQuantidades; class procedure AtualizarQuantidades; class function Altera(pObjeto: TLogssVO): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses T2TiORM; class procedure TLogssController.VerificarQuantidades; var ObjetoLocal: TLogssVO; Retorno: Boolean; TotalProduto, TotalTTP, TotalR01, TotalR02, TotalR03, TotalR04, TotalR05, TotalR06, TotalR07: Integer; begin try ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TLogssVO>('ID=1', True); TotalProduto := TT2TiORM.SelectCount('PRODUTO'); TotalTTP := TT2TiORM.SelectCount('ECF_TOTAL_TIPO_PAGAMENTO'); TotalR01 := TT2TiORM.SelectCount('R01'); TotalR02 := TT2TiORM.SelectCount('R02'); TotalR03 := TT2TiORM.SelectCount('R03'); TotalR04 := TT2TiORM.SelectCount('ECF_VENDA_CABECALHO'); TotalR05 := TT2TiORM.SelectCount('ECF_VENDA_DETALHE'); TotalR06 := TT2TiORM.SelectCount('R06'); TotalR07 := TT2TiORM.SelectCount('R07'); if (TotalProduto = ObjetoLocal.Produto) and (TotalTTP = ObjetoLocal.Ttp) and (TotalR01 = ObjetoLocal.R01) and (TotalR02 = ObjetoLocal.R02) and (TotalR03 = ObjetoLocal.R03) and (TotalR04 = ObjetoLocal.R04) and (TotalR05 = ObjetoLocal.R05) and (TotalR06 = ObjetoLocal.R06) and (TotalR07 = ObjetoLocal.R07) then Retorno := True else Retorno := False; TratarRetorno(Retorno); finally FreeAndNil(ObjetoLocal); end; end; class procedure TLogssController.AtualizarQuantidades; var ObjetoLocal: TLogssVO; TotalProduto, TotalTTP, TotalR01, TotalR02, TotalR03, TotalR04, TotalR05, TotalR06, TotalR07: Integer; begin try ObjetoLocal := TT2TiORM.ConsultarUmObjeto<TLogssVO>('ID=1', True); TotalProduto := TT2TiORM.SelectCount('PRODUTO'); TotalTTP := TT2TiORM.SelectCount('ECF_TOTAL_TIPO_PAGAMENTO'); TotalR01 := TT2TiORM.SelectCount('R01'); TotalR02 := TT2TiORM.SelectCount('R02'); TotalR03 := TT2TiORM.SelectCount('R03'); TotalR04 := TT2TiORM.SelectCount('ECF_VENDA_CABECALHO'); TotalR05 := TT2TiORM.SelectCount('ECF_VENDA_DETALHE'); TotalR06 := TT2TiORM.SelectCount('R06'); TotalR07 := TT2TiORM.SelectCount('R07'); if not Assigned(ObjetoLocal) then ObjetoLocal := TLogssVO.Create; ObjetoLocal.Produto := TotalProduto; ObjetoLocal.Ttp := TotalTTP; ObjetoLocal.R01 := TotalR01; ObjetoLocal.R02 := TotalR02; ObjetoLocal.R03 := TotalR03; ObjetoLocal.R04 := TotalR04; ObjetoLocal.R05 := TotalR05; ObjetoLocal.R06 := TotalR06; ObjetoLocal.R07 := TotalR07; if ObjetoLocal.Id > 0 then TT2TiORM.Alterar(ObjetoLocal) else TT2TiORM.Inserir(ObjetoLocal); finally FreeAndNil(ObjetoLocal); end; end; class function TLogssController.Altera(pObjeto: TLogssVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TLogssController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TLogssController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TLogssController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TLogssVO>(TObjectList<TLogssVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TLogssController); finalization Classes.UnRegisterClass(TLogssController); end.
program Recursion (input, output); { Some examples of recursion } function Fac(inN : integer) : integer; { Computes the factorial of inN. } begin if inN = 0 then { this is the terminating base-case } Fac := 1 else Fac := inN * Fac(inN - 1) end; { Fac } function FacIter (inN : integer) : integer; { Compute factorial with a function generating an iterative process. } { Yes, this function can be only seen within FacIter, not in the body of the "Recursion" program. } function Iter (inN : integer; inProduct : integer) : integer; { Auxiliary function hiding the state variable "inProduct" from the API of FacIter } begin if (inN > 0) then Iter := Iter (inN-1, inProduct * inN) else Iter := inProduct; end; { Iter } begin FacIter := Iter(inN, 1); end; { FacIter } begin writeln('Oh, remember: Pascal''s Integer can''t handle big numbers. ', 'Fac(7) is the limit, lol'); writeln(Fac(7)); writeln(FacIter(7)); end. { Recursion }
{******************************************************************************* Title: T2Ti ERP Fenix Description: Model relacionado à tabela [FIN_PARCELA_RECEBER] The MIT License Copyright: Copyright (C) 2020 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 FinParcelaReceber; interface uses Generics.Collections, System.SysUtils, FinStatusParcela, FinTipoRecebimento, BancoContaCaixa, FinChequeRecebido, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TFinParcelaReceber = class(TModelBase) private FId: Integer; FIdFinLancamentoReceber: Integer; FIdFinStatusParcela: Integer; FIdFinTipoRecebimento: Integer; FIdBancoContaCaixa: Integer; FIdFinChequeRecebido: Integer; FNumeroParcela: Integer; FDataEmissao: TDateTime; FDataVencimento: TDateTime; FDescontoAte: TDateTime; FValor: Extended; FTaxaJuro: Extended; FTaxaMulta: Extended; FTaxaDesconto: Extended; FValorJuro: Extended; FValorMulta: Extended; FValorDesconto: Extended; FEmitiuBoleto: string; FBoletoNossoNumero: string; FValorRecebido: Extended; FHistorico: string; FFinStatusParcela: TFinStatusParcela; FFinTipoRecebimento: TFinTipoRecebimento; FBancoContaCaixa: TBancoContaCaixa; FFinChequeRecebido: TFinChequeRecebido; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_FIN_LANCAMENTO_RECEBER')] [MVCNameAsAttribute('idFinLancamentoReceber')] property IdFinLancamentoReceber: Integer read FIdFinLancamentoReceber write FIdFinLancamentoReceber; [MVCColumnAttribute('ID_FIN_STATUS_PARCELA')] [MVCNameAsAttribute('idFinStatusParcela')] property IdFinStatusParcela: Integer read FIdFinStatusParcela write FIdFinStatusParcela; [MVCColumnAttribute('ID_FIN_TIPO_RECEBIMENTO')] [MVCNameAsAttribute('idFinTipoRecebimento')] property IdFinTipoRecebimento: Integer read FIdFinTipoRecebimento write FIdFinTipoRecebimento; [MVCColumnAttribute('ID_BANCO_CONTA_CAIXA')] [MVCNameAsAttribute('idBancoContaCaixa')] property IdBancoContaCaixa: Integer read FIdBancoContaCaixa write FIdBancoContaCaixa; [MVCColumnAttribute('ID_FIN_CHEQUE_RECEBIDO')] [MVCNameAsAttribute('idFinChequeRecebido')] property IdFinChequeRecebido: Integer read FIdFinChequeRecebido write FIdFinChequeRecebido; [MVCColumnAttribute('NUMERO_PARCELA')] [MVCNameAsAttribute('numeroParcela')] property NumeroParcela: Integer read FNumeroParcela write FNumeroParcela; [MVCColumnAttribute('DATA_EMISSAO')] [MVCNameAsAttribute('dataEmissao')] property DataEmissao: TDateTime read FDataEmissao write FDataEmissao; [MVCColumnAttribute('DATA_VENCIMENTO')] [MVCNameAsAttribute('dataVencimento')] property DataVencimento: TDateTime read FDataVencimento write FDataVencimento; [MVCColumnAttribute('DESCONTO_ATE')] [MVCNameAsAttribute('descontoAte')] property DescontoAte: TDateTime read FDescontoAte write FDescontoAte; [MVCColumnAttribute('VALOR')] [MVCNameAsAttribute('valor')] property Valor: Extended read FValor write FValor; [MVCColumnAttribute('TAXA_JURO')] [MVCNameAsAttribute('taxaJuro')] property TaxaJuro: Extended read FTaxaJuro write FTaxaJuro; [MVCColumnAttribute('TAXA_MULTA')] [MVCNameAsAttribute('taxaMulta')] property TaxaMulta: Extended read FTaxaMulta write FTaxaMulta; [MVCColumnAttribute('TAXA_DESCONTO')] [MVCNameAsAttribute('taxaDesconto')] property TaxaDesconto: Extended read FTaxaDesconto write FTaxaDesconto; [MVCColumnAttribute('VALOR_JURO')] [MVCNameAsAttribute('valorJuro')] property ValorJuro: Extended read FValorJuro write FValorJuro; [MVCColumnAttribute('VALOR_MULTA')] [MVCNameAsAttribute('valorMulta')] property ValorMulta: Extended read FValorMulta write FValorMulta; [MVCColumnAttribute('VALOR_DESCONTO')] [MVCNameAsAttribute('valorDesconto')] property ValorDesconto: Extended read FValorDesconto write FValorDesconto; [MVCColumnAttribute('EMITIU_BOLETO')] [MVCNameAsAttribute('emitiuBoleto')] property EmitiuBoleto: string read FEmitiuBoleto write FEmitiuBoleto; [MVCColumnAttribute('BOLETO_NOSSO_NUMERO')] [MVCNameAsAttribute('boletoNossoNumero')] property BoletoNossoNumero: string read FBoletoNossoNumero write FBoletoNossoNumero; [MVCColumnAttribute('VALOR_RECEBIDO')] [MVCNameAsAttribute('valorRecebido')] property ValorRecebido: Extended read FValorRecebido write FValorRecebido; [MVCColumnAttribute('HISTORICO')] [MVCNameAsAttribute('historico')] property Historico: string read FHistorico write FHistorico; [MVCNameAsAttribute('finStatusParcela')] property FinStatusParcela: TFinStatusParcela read FFinStatusParcela write FFinStatusParcela; [MVCNameAsAttribute('finTipoRecebimento')] property FinTipoRecebimento: TFinTipoRecebimento read FFinTipoRecebimento write FFinTipoRecebimento; [MVCNameAsAttribute('bancoContaCaixa')] property BancoContaCaixa: TBancoContaCaixa read FBancoContaCaixa write FBancoContaCaixa; [MVCNameAsAttribute('finChequeRecebido')] property FinChequeRecebido: TFinChequeRecebido read FFinChequeRecebido write FFinChequeRecebido; end; implementation { TFinParcelaReceber } constructor TFinParcelaReceber.Create; begin FFinStatusParcela := TFinStatusParcela.Create; FFinTipoRecebimento := TFinTipoRecebimento.Create; FBancoContaCaixa := TBancoContaCaixa.Create; FFinChequeRecebido := TFinChequeRecebido.Create; end; destructor TFinParcelaReceber.Destroy; begin FreeAndNil(FFinStatusParcela); FreeAndNil(FFinTipoRecebimento); FreeAndNil(FBancoContaCaixa); FreeAndNil(FFinChequeRecebido); inherited; end; procedure TFinParcelaReceber.ValidarInsercao; begin inherited; end; procedure TFinParcelaReceber.ValidarAlteracao; begin inherited; end; procedure TFinParcelaReceber.ValidarExclusao; begin inherited; end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.json; interface uses Rtti, SysUtils, Classes, Contnrs, Variants, TypInfo, Generics.Collections, /// ormbr ormbr.mapping.rttiutils, ormbr.types.blob, ormbr.utils, ormbr.rtti.helper, ormbr.objects.helper; type TORMBrJsonOption = (joIgnoreEmptyStrings, joIgnoreEmptyArrays, joDateIsUTC, joDateFormatUnix, joDateFormatISO8601, joDateFormatMongo, joDateFormatParse); TORMBrJsonOptions = set of TORMBrJsonOption; EJSONException = class(Exception); TStringDynamicArray = array of string; TVariantDynamicArray = array of Variant; PJSONVariantData = ^TJSONVariantData; TByteDynArray = array of byte; PByteDynArray = ^TByteDynArray; TJSONVariantKind = (jvUndefined, jvObject, jvArray); TJSONParserKind = (kNone, kNull, kFalse, kTrue, kString, kInteger, kFloat, kObject, kArray); TJSONVariantData = object private function GetListType(LRttiType: TRttiType): TRttiType; protected FVType: TVarType; FVKind: TJSONVariantKind; FVCount: Integer; function GetKind: TJSONVariantKind; function GetCount: Integer; function GetVarData(const AName: string; var ADest: TVarData): Boolean; function GetValue(const AName: string): Variant; function GetValueCopy(const AName: string): Variant; procedure SetValue(const AName: string; const AValue: Variant); function GetItem(AIndex: Integer): Variant; procedure SetItem(AIndex: Integer; const AItem: Variant); public FNames: TStringDynamicArray; FValues: TVariantDynamicArray; procedure Init; overload; procedure Init(const AJson: string); overload; procedure InitFrom(const AValues: TVariantDynamicArray); overload; procedure Clear; function Data(const AName: string): PJSONVariantData; inline; function EnsureData(const APath: string): PJSONVariantData; function AddItem: PJSONVariantData; function NameIndex(const AName: string): Integer; function FromJSON(const AJson: string): Boolean; function ToJSON: string; function ToObject(AObject: TObject): Boolean; function ToNewObject: TObject; procedure AddValue(const AValue: Variant); procedure AddNameValue(const AName: string; const AValue: Variant); procedure SetPath(const APath: string; const AValue: Variant); property Kind: TJSONVariantKind read GetKind; property Count: Integer read GetCount; property Value[const AName: string]: Variant read GetValue write SetValue; default; property ValueCopy[const AName: string]: Variant read GetValueCopy; property Item[AIndex: Integer]: Variant read GetItem write SetItem; end; TJSONParser = object FJson: string; FIndex: Integer; FJsonLength: Integer; procedure Init(const AJson: string; AIndex: Integer); function GetNextChar: Char; inline; function GetNextNonWhiteChar: Char; inline; function CheckNextNonWhiteChar(AChar: Char): Boolean; inline; function GetNextString(out AStr: string): Boolean; overload; function GetNextString: string; overload; inline; function GetNextJSON(out AValue: Variant): TJSONParserKind; function CheckNextIdent(const AExpectedIdent: string): Boolean; function GetNextAlphaPropName(out AFieldName: string): Boolean; function ParseJSONObject(var AData: TJSONVariantData): Boolean; function ParseJSONArray(var AData: TJSONVariantData): Boolean; procedure GetNextStringUnEscape(var AStr: string); end; TJSONVariant = class(TInvokeableVariantType) public procedure Copy(var ADest: TVarData; const ASource: TVarData; const AIndirect: Boolean); override; procedure Clear(var AVarData: TVarData); override; function GetProperty(var ADest: TVarData; const AVarData: TVarData; const AName: string): Boolean; override; function SetProperty(const AVarData: TVarData; const AName: string; const AValue: TVarData): Boolean; override; procedure Cast(var ADest: TVarData; const ASource: TVarData); override; procedure CastTo(var ADest: TVarData; const ASource: TVarData; const AVarType: TVarType); override; end; TJSONObjectORMBr = class private function JSONVariant(const AJson: string): Variant; overload; function JSONVariant(const AValues: TVariantDynamicArray): Variant; overload; function JSONVariantFromConst(const constValues: array of Variant): Variant; function JSONVariantDataSafe(const JSONVariant: Variant; ExpectedKind: TJSONVariantKind = jvUndefined): PJSONVariantData; function GetInstanceProp(AInstance: TObject; AProperty: TRttiProperty): Variant; function JSONToValue(const AJson: string): Variant; function NowToIso8601: string; function JSONToNewObject(const AJson: string): Pointer; procedure RegisterClassForJSON(const AClasses: array of TClass); class function JSONVariantData(const JSONVariant: Variant): PJSONVariantData; class function IdemPropName(const APropName1, APropName2: string): Boolean; inline; class function FindClassForJSON(const AClassName: string): Integer; class function CreateClassForJSON(const AClassName: string): TObject; class function StringToJSON(const AText: string): string; class function ValueToJSON(const AValue: Variant): string; class function DateTimeToJSON(AValue: TDateTime): string; class procedure AppendChar(var AStr: string; AChr: char); class procedure DoubleToJSON(AValue: Double; var AResult: string); class procedure SetInstanceProp(AInstance: TObject; AProperty: TRttiProperty; const AValue: Variant); public function ObjectToJSON(AObject: TObject; AStoreClassName: Boolean = False): string; function JSONToObject(AObject: TObject; const AJson: string): Boolean; overload; function JSONToObject<T: class, constructor>(const AJson: string): T; overload; function JSONToObjectList<T: class, constructor>(const AJson: string): TObjectList<T>; end; var JSONVariantType: TInvokeableVariantType; BASE64DECODE: array of ShortInt; FSettingsUS: TFormatSettings; RegisteredClass: array of record ClassName: string; ClassType: TClass; end; const JSON_BASE64_MAGIC: array [0..2] of byte = ($EF, $BF, $B0); JSON_BASE64_MAGIC_LEN = sizeof(JSON_BASE64_MAGIC) div sizeof(char); BASE64: array [0 .. 63] of char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; JSONVariantDataFake: TJSONVariantData = (); implementation { TJSONObjectORMBr } procedure TJSONObjectORMBr.RegisterClassForJSON(const AClasses: array of TClass); var LFor, LIdx: integer; LName: string; begin for LFor := 0 to High(AClasses) do begin LName := String(AClasses[LFor].ClassName); LIdx := FindClassForJSON(LName); if LIdx>=0 then Continue; LIdx := length(RegisteredClass); SetLength(RegisteredClass,LIdx+1); RegisteredClass[LIdx].ClassName := LName; RegisteredClass[LIdx].ClassType := AClasses[LFor]; end; end; class function TJSONObjectORMBr.IdemPropName(const APropName1, APropName2: string): Boolean; var LLen, LFor: Integer; begin Result := False; LLen := Length(APropName2); if Length(APropName1) <> LLen then Exit; for LFor := 1 to LLen do if (Ord(APropName1[LFor]) xor Ord(APropName2[LFor])) and $DF <> 0 then Exit; Result := True; end; function TJSONObjectORMBr.JSONVariant(const AJson: string): Variant; begin VarClear(Result); TJSONVariantData(Result).FromJSON(AJson); end; function TJSONObjectORMBr.JSONVariant(const AValues: TVariantDynamicArray): Variant; begin VarClear(Result); TJSONVariantData(Result).Init; TJSONVariantData(Result).FVKind := jvArray; TJSONVariantData(Result).FVCount := Length(AValues); TJSONVariantData(Result).FValues := AValues; end; function TJSONObjectORMBr.JSONVariantFromConst(const constValues: array of Variant): Variant; var LFor: Integer; begin VarClear(Result); with TJSONVariantData(Result) do begin Init; FVKind := jvArray; FVCount := Length(FValues); SetLength(FValues, FVCount); for LFor := 0 to FVCount - 1 do FValues[LFor] := constValues[LFor]; end; end; class function TJSONObjectORMBr.JSONVariantData(const JSONVariant: Variant): PJSONVariantData; begin with TVarData(JSONVariant) do begin if VType = JSONVariantType.VarType then Result := @JSONVariant else if VType = varByRef or varVariant then Result := JSONVariantData(PVariant(VPointer)^) else raise EJSONException.CreateFmt('JSONVariantData.Data(%d<>JSONVariant)', [VType]); end; end; function TJSONObjectORMBr.JSONVariantDataSafe(const JSONVariant: Variant; ExpectedKind: TJSONVariantKind = jvUndefined): PJSONVariantData; begin with TVarData(JSONVariant) do begin if VType = JSONVariantType.VarType then if (ExpectedKind = jvUndefined) or (TJSONVariantData(JSONVariant).FVKind = ExpectedKind) then Result := @JSONVariant else Result := @JSONVariantDataFake else if VType = varByRef or varVariant then Result := JSONVariantDataSafe(PVariant(VPointer)^) else Result := @JSONVariantDataFake; end; end; class procedure TJSONObjectORMBr.AppendChar(var AStr: string; AChr: Char); var LLen: Integer; begin LLen := Length(AStr); SetLength(AStr, LLen + 1); PChar(Pointer(AStr))[LLen] := AChr; end; class function TJSONObjectORMBr.StringToJSON(const AText: string): string; var LLen, LFor: Integer; procedure DoEscape; var iChr: Integer; begin Result := '"' + Copy(AText, 1, LFor - 1); for iChr := LFor to LLen do begin case AText[iChr] of #8: Result := Result + '\b'; #9: Result := Result + '\t'; #10: Result := Result + '\n'; #12: Result := Result + '\f'; #13: Result := Result + '\r'; '\': Result := Result + '\\'; '"': Result := Result + '\"'; else if AText[iChr] < ' ' then Result := Result + '\u00' + IntToHex(Ord(AText[iChr]), 2) else AppendChar(Result, AText[iChr]); end; end; AppendChar(Result, '"'); end; begin LLen := Length(AText); for LFor := 1 to LLen do case AText[LFor] of #0 .. #31, '\', '"': begin DoEscape; Exit; end; end; Result := '"' + AText + '"'; end; class procedure TJSONObjectORMBr.DoubleToJSON(AValue: Double; var AResult: string); begin AResult := FloatToStr(AValue, FSettingsUS); end; /// <summary> /// // "YYYY-MM-DD" "Thh:mm:ss" or "YYYY-MM-DDThh:mm:ss" /// </summary> class function TJSONObjectORMBr.DateTimeToJSON(AValue: TDateTime): string; begin Result := '"' + TUtilSingleton.GetInstance.DateTimeToIso8601(AValue) + '"'; end; function TJSONObjectORMBr.NowToIso8601: string; begin Result := TUtilSingleton.GetInstance.DateTimeToIso8601(Now); end; class function TJSONObjectORMBr.ValueToJSON(const AValue: Variant): string; var LInt64: Int64; begin if TVarData(AValue).VType = JSONVariantType.VarType then Result := TJSONVariantData(AValue).ToJSON else if (TVarData(AValue).VType = varByRef or varVariant) then Result := ValueToJSON(PVariant(TVarData(AValue).VPointer)^) else if TVarData(AValue).VType <= varNull then Result := 'null' else if TVarData(AValue).VType = varBoolean then begin if TVarData(AValue).VBoolean then Result := 'true' else Result := 'false'; end else if TVarData(AValue).VType = varDate then Result := DateTimeToJSON(TVarData(AValue).VDouble) else if VarIsOrdinal(AValue) then begin LInt64 := AValue; Result := IntToStr(LInt64); end else if VarIsFloat(AValue) then DoubleToJSON(AValue, Result) else if VarIsStr(AValue) then Result := StringToJSON(AValue) else Result := AValue; end; function TJSONObjectORMBr.JSONToValue(const AJson: string): Variant; var LParser: TJSONParser; begin LParser.Init(AJson, 1); LParser.GetNextJSON(Result); end; function TJSONObjectORMBr.GetInstanceProp(AInstance: TObject; AProperty: TRttiProperty): Variant; var LClass: TObject; begin case AProperty.PropertyType.TypeKind of tkInt64: Result := AProperty.GetNullableValue(AInstance).AsInt64; tkInteger, tkSet: Result := AProperty.GetNullableValue(AInstance).AsInteger; tkUString, tkLString, tkWString, tkString, tkChar, tkWChar: Result := AProperty.GetNullableValue(AInstance).AsString; tkFloat: if AProperty.PropertyType.Handle = TypeInfo(TDateTime) then Result := TUtilSingleton.GetInstance.DateTimeToIso8601(AProperty.GetNullableValue(AInstance).AsExtended) else Result := AProperty.GetNullableValue(AInstance).AsCurrency; tkVariant: Result := AProperty.GetNullableValue(AInstance).AsVariant; tkRecord: begin if AProperty.IsBlob then Result := AProperty.GetNullableValue(AInstance).AsType<TBlob>.ToBytesString else Result := AProperty.GetNullableValue(AInstance).AsVariant; end; tkClass: begin LClass := AProperty.GetNullableValue(AInstance).AsObject; if LClass = nil then Result := null else TJSONVariantData(Result).Init(ObjectToJSON(LClass)); end; tkEnumeration: begin // Mudar o param para receber o tipo Column que tem as info necessárias // Column.FieldType = ftBoolean Result := AProperty.GetNullableValue(AInstance).AsBoolean; end; tkDynArray:; end; end; class procedure TJSONObjectORMBr.SetInstanceProp(AInstance: TObject; AProperty: TRttiProperty; const AValue: Variant); var LClass: TObject; LBlob: TBlob; begin if (AProperty <> nil) and (AInstance <> nil) then begin case AProperty.PropertyType.TypeKind of tkString, tkWString, tkUString, tkWChar, tkLString, tkChar: if TVarData(AValue).VType <= varNull then AProperty.SetValue(AInstance, '') else AProperty.SetValue(AInstance, String(AValue)); tkInteger, tkSet, tkInt64: AProperty.SetValue(AInstance, Integer(AValue)); tkFloat: if TVarData(AValue).VType <= varNull then AProperty.SetValue(AInstance, 0) else if AProperty.PropertyType.Handle = TypeInfo(TDateTime) then AProperty.SetValue(AInstance, TUtilSingleton.GetInstance.Iso8601ToDateTime(AValue)) else if AProperty.PropertyType.Handle = TypeInfo(TTime) then AProperty.SetValue(AInstance, TUtilSingleton.GetInstance.Iso8601ToDateTime(AValue)) else AProperty.SetValue(AInstance, Double(AValue)); tkVariant: AProperty.SetValue(AInstance, TValue.FromVariant(AValue)); tkRecord: begin if AProperty.IsBlob then begin LBlob.ToBytesString(AValue); AProperty.SetValue(AInstance, TValue.From<TBlob>(LBlob)); end else AProperty.SetNullableValue(AInstance, AProperty.PropertyType.Handle, AValue); end; tkClass: begin LClass := AProperty.GetNullableValue(AInstance).AsObject; if LClass <> nil then JSONVariantData(AValue).ToObject(LClass); end; tkEnumeration: begin // if AFieldType in [ftBoolean] then // AProperty.SetValue(AInstance, Boolean(AValue)) // else // if AFieldType in [ftFixedChar, ftString] then // AProperty.SetValue(AInstance, AProperty.GetEnumStringValue(AValue)) // else // if AFieldType in [ftInteger] then // AProperty.SetValue(AInstance, AProperty.GetEnumIntegerValue(AValue)) // else // raise Exception.Create('Invalid type. Type enumerator supported [ftBoolena,ftInteger,ftFixedChar,ftString]'); end; tkDynArray:; end; end; end; function TJSONObjectORMBr.JSONToObjectList<T>(const AJson: string): TObjectList<T>; var LDoc: TJSONVariantData; LItem: TObject; LFor: Integer; begin LDoc.Init(AJson); if (LDoc.FVKind <> jvArray) then Result := nil else begin Result := TObjectList<T>.Create; for LFor := 0 to LDoc.Count - 1 do begin LItem := T.Create; if not JSONVariantData(LDoc.FValues[LFor]).ToObject(LItem) then begin FreeAndNil(Result); Exit; end; Result.Add(LItem); end; end; end; function TJSONObjectORMBr.JSONToObject(AObject: TObject; const AJson: string): Boolean; var LDoc: TJSONVariantData; begin if AObject = nil then Result := False else begin LDoc.Init(AJson); Result := LDoc.ToObject(AObject); end; end; function TJSONObjectORMBr.JSONToObject<T>(const AJson: string): T; begin Result := T.Create; if not JSONToObject(TObject(Result), AJson) then raise Exception.Create('Error Message'); end; function TJSONObjectORMBr.JSONToNewObject(const AJson: string): Pointer; var LDoc: TJSONVariantData; begin LDoc.Init(AJson); Result := LDoc.ToNewObject; end; class function TJSONObjectORMBr.FindClassForJSON(const AClassName: string): Integer; begin for Result := 0 to High(RegisteredClass) do if IdemPropName(RegisteredClass[Result].ClassName, AClassName) then Exit; Result := -1; end; class function TJSONObjectORMBr.CreateClassForJSON(const AClassName: string): TObject; var LFor: Integer; begin LFor := FindClassForJSON(AClassName); if LFor < 0 then Result := nil else Result := RegisteredClass[LFor].ClassType.Create; end; function TJSONObjectORMBr.ObjectToJSON(AObject: TObject; AStoreClassName: Boolean): string; var LTypeInfo: TRttiType; LProperty: TRttiProperty; {$IFDEF DELPHI15_UP} LMethodToArray: TRttiMethod; {$ENDIF DELPHI15_UP} LFor: Integer; LValue: TValue; begin LValue := nil; if AObject = nil then begin Result := 'null'; Exit; end; if AObject.InheritsFrom(TList) then begin if TList(AObject).Count = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to TList(AObject).Count - 1 do Result := Result + ObjectToJSON(TObject(TList(AObject).List[LFor]), AStoreClassName) + ','; Result[Length(Result)] := ']'; end; Exit; end; if AObject.InheritsFrom(TStrings) then begin if TStrings(AObject).Count = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to TStrings(AObject).Count - 1 do Result := Result + StringToJSON(TStrings(AObject).Strings[LFor]) + ','; Result[Length(Result)] := ']'; end; Exit; end; if AObject.InheritsFrom(TCollection) then begin if TCollection(AObject).Count = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to TCollection(AObject).Count - 1 do Result := Result + ObjectToJSON(TCollection(AObject).Items[LFor], AStoreClassName) + ','; Result[Length(Result)] := ']'; end; Exit; end; LTypeInfo := TRttiSingleton.GetInstance.GetRttiType(AObject.ClassType); if LTypeInfo = nil then begin Result := 'null'; Exit; end; if (Pos('TObjectList<', AObject.ClassName) > 0) or (Pos('TList<', AObject.ClassName) > 0) then begin {$IFDEF DELPHI15_UP} LMethodToArray := LTypeInfo.GetMethod('ToArray'); if LMethodToArray <> nil then begin LValue := LMethodToArray.Invoke(AObject, []); Assert(LValue.IsArray); if LValue.GetArrayLength = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to LValue.GetArrayLength -1 do Result := Result + ObjectToJSON(LValue.GetArrayElement(LFor).AsObject, AStoreClassName) + ','; Result[Length(Result)] := ']'; end end; {$ELSE DELPHI15_UP} if TList(AObject).Count = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to TList(AObject).Count -1 do Result := Result + ObjectToJSON(TList(AObject).Items[LFor], AStoreClassName) + ','; Result[Length(Result)] := ']'; end; {$ENDIF DELPHI15_UP} Exit; end; if AStoreClassName then Result := '{"ClassName":"' + string(AObject.ClassName) + '",' else Result := '{'; /// for LProperty in LTypeInfo.GetProperties do begin if LProperty.IsWritable then Result := Result + StringToJSON(LProperty.Name) + ':' + ValueToJSON(GetInstanceProp(AObject, LProperty)) + ','; end; Result[Length(Result)] := '}'; end; { TJSONParser } procedure TJSONParser.Init(const AJson: string; AIndex: Integer); begin FJson := AJson; FJsonLength := Length(FJson); FIndex := AIndex; end; function TJSONParser.GetNextChar: char; begin if FIndex <= FJsonLength then begin Result := FJson[FIndex]; Inc(FIndex); end else Result := #0; end; function TJSONParser.GetNextNonWhiteChar: char; begin if FIndex <= FJsonLength then begin repeat if FJson[FIndex] > ' ' then begin Result := FJson[FIndex]; Inc(FIndex); Exit; end; Inc(FIndex); until FIndex > FJsonLength; Result := #0; end; end; function TJSONParser.CheckNextNonWhiteChar(AChar: Char): Boolean; begin if FIndex <= FJsonLength then begin repeat if FJson[FIndex] > ' ' then begin Result := FJson[FIndex] = aChar; if Result then Inc(FIndex); Exit; end; Inc(FIndex); until FIndex > FJsonLength; Result := False; end; end; procedure TJSONParser.GetNextStringUnEscape(var AStr: string); var LChar: char; LCopy: string; LUnicode, LErr: Integer; begin repeat LChar := GetNextChar; case LChar of #0: Exit; '"': Break; '\': begin LChar := GetNextChar; case LChar of #0 : Exit; 'b': TJSONObjectORMBr.AppendChar(AStr, #08); 't': TJSONObjectORMBr.AppendChar(AStr, #09); 'n': TJSONObjectORMBr.AppendChar(AStr, #$0a); 'f': TJSONObjectORMBr.AppendChar(AStr, #$0c); 'r': TJSONObjectORMBr.AppendChar(AStr, #$0d); 'u': begin LCopy := Copy(FJson, FIndex, 4); if Length(LCopy) <> 4 then Exit; Inc(FIndex, 4); Val('$' + LCopy, LUnicode, LErr); if LErr <> 0 then Exit; TJSONObjectORMBr.AppendChar(AStr, char(LUnicode)); end; else TJSONObjectORMBr.AppendChar(AStr, LChar); end; end; else TJSONObjectORMBr.AppendChar(AStr, LChar); end; until False; end; function TJSONParser.GetNextString(out AStr: string): Boolean; var LFor: Integer; begin for LFor := FIndex to FJsonLength do begin case FJson[LFor] of '"': begin // end of string without escape -> direct copy AStr := Copy(FJson, FIndex, LFor - FIndex); FIndex := LFor + 1; Result := True; Exit; end; '\': begin // need unescaping AStr := Copy(FJson, FIndex, LFor - FIndex); FIndex := LFor; GetNextStringUnEscape(AStr); Result := True; Exit; end; end; end; Result := False; end; function TJSONParser.GetNextString: string; begin if not GetNextString(Result) then Result := ''; end; function TJSONParser.GetNextAlphaPropName(out AFieldName: string): Boolean; var LFor: Integer; begin Result := False; if (FIndex >= FJsonLength) or not (Ord(FJson[FIndex]) in [Ord('A') .. Ord('Z'), Ord('a') .. Ord('z'), Ord('_'), Ord('$')]) then Exit; for LFor := FIndex + 1 to FJsonLength do case Ord(FJson[LFor]) of Ord('0') .. Ord('9'), Ord('A') .. Ord('Z'), Ord('a') .. Ord('z'), Ord('_'):; // allow MongoDB extended syntax, e.g. {age:{$gt:18}} Ord(':'), Ord('='): begin AFieldName := Copy(FJson, FIndex, LFor - FIndex); FIndex := LFor + 1; Result := True; Exit; end; else Exit; end; end; function TJSONParser.GetNextJSON(out AValue: Variant): TJSONParserKind; var LStr: string; LInt64: Int64; LValue: double; LStart, LErr: Integer; begin Result := kNone; case GetNextNonWhiteChar of 'n': if Copy(FJson, FIndex, 3) = 'ull' then begin Inc(FIndex, 3); Result := kNull; AValue := null; end; 'f': if Copy(FJson, FIndex, 4) = 'alse' then begin Inc(FIndex, 4); Result := kFalse; AValue := False; end; 't': if Copy(FJson, FIndex, 3) = 'rue' then begin Inc(FIndex, 3); Result := kTrue; AValue := True; end; '"': if GetNextString(LStr) = True then begin Result := kString; AValue := LStr; end; '{': if ParseJSONObject(TJSONVariantData(AValue)) then Result := kObject; '[': if ParseJSONArray(TJSONVariantData(AValue)) then Result := kArray; '-', '0' .. '9': begin LStart := FIndex - 1; while True do case FJson[FIndex] of '-', '+', '0' .. '9', '.', 'E', 'e': Inc(FIndex); else Break; end; LStr := Copy(FJson, LStart, FIndex - LStart); Val(LStr, LInt64, LErr); if LErr = 0 then begin AValue := LInt64; Result := kInteger; end else begin Val(LStr, LValue, LErr); if LErr <> 0 then Exit; AValue := LValue; Result := kFloat; end; end; end; end; function TJSONParser.CheckNextIdent(const AExpectedIdent: string): Boolean; begin Result := (GetNextNonWhiteChar = '"') and (CompareText(GetNextString, AExpectedIdent) = 0) and (GetNextNonWhiteChar = ':'); end; function TJSONParser.ParseJSONArray(var AData: TJSONVariantData): Boolean; var LItem: Variant; begin Result := False; AData.Init; if not CheckNextNonWhiteChar(']') then begin repeat if GetNextJSON(LItem) = kNone then Exit; AData.AddValue(LItem); case GetNextNonWhiteChar of ',': Continue; ']': Break; else Exit; end; until False; SetLength(AData.FValues, AData.FVCount); end; AData.FVKind := jvArray; Result := True; end; function TJSONParser.ParseJSONObject(var AData: TJSONVariantData): Boolean; var LKey: string; LItem: Variant; begin Result := False; AData.Init; if not CheckNextNonWhiteChar('}') then begin repeat if CheckNextNonWhiteChar('"') then begin if (not GetNextString(LKey)) or (GetNextNonWhiteChar <> ':') then Exit; end else if not GetNextAlphaPropName(LKey) then Exit; if GetNextJSON(LItem) = kNone then Exit; AData.AddNameValue(LKey, LItem); case GetNextNonWhiteChar of ',': Continue; '}': Break; else Exit; end; until False; SetLength(AData.FNames, AData.FVCount); end; SetLength(AData.FValues, AData.FVCount); AData.FVKind := jvObject; Result := True; end; { TJSONVariantData } procedure TJSONVariantData.Init; begin FVType := JSONVariantType.VarType; FVKind := jvUndefined; FVCount := 0; Pointer(FNames) := nil; Pointer(FValues) := nil; end; procedure TJSONVariantData.Init(const AJson: string); begin Init; FromJSON(AJson); if FVType = varNull then FVKind := jvObject else if FVType <> JSONVariantType.VarType then Init; end; procedure TJSONVariantData.InitFrom(const AValues: TVariantDynamicArray); begin Init; FVKind := jvArray; FValues := AValues; FVCount := Length(AValues); end; procedure TJSONVariantData.Clear; begin FNames := nil; FValues := nil; Init; end; procedure TJSONVariantData.AddNameValue(const AName: string; const AValue: Variant); begin if FVKind = jvUndefined then FVKind := jvObject else if FVKind <> jvObject then raise EJSONException.CreateFmt('AddNameValue(%s) over array', [AName]); if FVCount <= Length(FValues) then begin SetLength(FValues, FVCount + FVCount shr 3 + 32); SetLength(FNames, FVCount + FVCount shr 3 + 32); end; FValues[FVCount] := AValue; FNames[FVCount] := AName; Inc(FVCount); end; procedure TJSONVariantData.AddValue(const AValue: Variant); begin if FVKind = jvUndefined then FVKind := jvArray else if FVKind <> jvArray then raise EJSONException.Create('AddValue() over object'); if FVCount <= Length(FValues) then SetLength(FValues, FVCount + FVCount shr 3 + 32); FValues[FVCount] := aValue; Inc(FVCount); end; function TJSONVariantData.FromJSON(const AJson: string): Boolean; var LParser: TJSONParser; begin LParser.Init(AJson, 1); Result := LParser.GetNextJSON(Variant(Self)) in [kObject, kArray]; end; function TJSONVariantData.Data(const AName: string): PJSONVariantData; var LFor: Integer; begin LFor := NameIndex(AName); if (LFor < 0) or (TVarData(FValues[LFor]).VType <> JSONVariantType.VarType) then Result := nil else Result := @FValues[LFor]; end; function TJSONVariantData.GetKind: TJSONVariantKind; begin if (@Self = nil) or (FVType <> JSONVariantType.VarType) then Result := jvUndefined else Result := FVKind; end; function TJSONVariantData.GetCount: Integer; begin if (@Self = nil) or (FVType <> JSONVariantType.VarType) then Result := 0 else Result := FVCount; end; function TJSONVariantData.GetValue(const AName: string): Variant; begin VarClear(Result); if (@Self <> nil) and (FVType = JSONVariantType.VarType) and (FVKind = jvObject) then GetVarData(AName, TVarData(Result)); end; function TJSONVariantData.GetValueCopy(const AName: string): Variant; var LFor: Cardinal; begin VarClear(Result); if (@Self <> nil) and (FVType = JSONVariantType.VarType) and (FVKind = jvObject) then begin LFor := Cardinal(NameIndex(AName)); if LFor < Cardinal(Length(FValues)) then Result := FValues[LFor]; end; end; function TJSONVariantData.GetItem(AIndex: Integer): Variant; begin VarClear(Result); if (@Self <> nil) and (FVType = JSONVariantType.VarType) and (FVKind = jvArray) then if Cardinal(AIndex) < Cardinal(FVCount) then Result := FValues[AIndex]; end; procedure TJSONVariantData.SetItem(AIndex: Integer; const AItem: Variant); begin if (@Self <> nil) and (FVType = JSONVariantType.VarType) and (FVKind = jvArray) then if Cardinal(AIndex) < Cardinal(FVCount) then FValues[AIndex] := AItem; end; function TJSONVariantData.GetVarData(const AName: string; var ADest: TVarData): Boolean; var LFor: Cardinal; begin LFor := Cardinal(NameIndex(AName)); if LFor < Cardinal(Length(FValues)) then begin ADest.VType := varVariant or varByRef; ADest.VPointer := @FValues[LFor]; Result := True; end else Result := False; end; function TJSONVariantData.NameIndex(const AName: string): Integer; begin if (@Self <> nil) and (FVType = JSONVariantType.VarType) and (FNames <> nil) then for Result := 0 to FVCount - 1 do if FNames[Result] = AName then Exit; Result := -1; end; procedure TJSONVariantData.SetPath(const APath: string; const AValue: Variant); var LFor: Integer; begin for LFor := Length(APath) downto 1 do begin if APath[LFor] = '.' then begin EnsureData(Copy(APath, 1, LFor - 1))^.SetValue(Copy(APath, LFor + 1, maxInt), AValue); Exit; end; end; SetValue(APath, AValue); end; function TJSONVariantData.EnsureData(const APath: string): PJSONVariantData; var LFor: Integer; LNew: TJSONVariantData; begin LFor := Pos('.', APath); if LFor = 0 then begin LFor := NameIndex(APath); if LFor < 0 then begin LNew.Init; AddNameValue(APath, Variant(LNew)); Result := @FValues[FVCount - 1]; end else begin if TVarData(FValues[LFor]).VType <> JSONVariantType.VarType then begin VarClear(FValues[LFor]); TJSONVariantData(FValues[LFor]).Init; end; Result := @FValues[LFor]; end; end else Result := EnsureData(Copy(APath, 1, LFor - 1))^.EnsureData(Copy(APath, LFor + 1, maxInt)); end; function TJSONVariantData.AddItem: PJSONVariantData; var LNew: TJSONVariantData; begin LNew.Init; AddValue(Variant(LNew)); Result := @FValues[FVCount - 1]; end; procedure TJSONVariantData.SetValue(const AName: string; const AValue: Variant); var LFor: Integer; begin if @Self = nil then raise EJSONException.Create('Unexpected Value[] access'); if AName = '' then raise EJSONException.Create('Unexpected Value['''']'); LFor := NameIndex(AName); if LFor < 0 then AddNameValue(AName, AValue) else FValues[LFor] := AValue; end; function TJSONVariantData.ToJSON: string; var LFor: Integer; begin case FVKind of jvObject: if FVCount = 0 then Result := '{}' else begin Result := '{'; for LFor := 0 to FVCount - 1 do Result := Result + TJSONObjectORMBr.StringToJSON(FNames[LFor]) + ':' + TJSONObjectORMBr.ValueToJSON(FValues[LFor]) + ','; Result[Length(Result)] := '}'; end; jvArray: if FVCount = 0 then Result := '[]' else begin Result := '['; for LFor := 0 to FVCount - 1 do Result := Result + TJSONObjectORMBr.ValueToJSON(FValues[LFor]) + ','; Result[Length(Result)] := ']'; end; else Result := 'null'; end; end; function TJSONVariantData.ToNewObject: TObject; var LType: TRttiType; LProperty: TRttiProperty; LIdx, LFor: Integer; begin Result := nil; if (Kind <> jvObject) or (Count = 0) then Exit; LIdx := NameIndex('ClassName'); if LIdx < 0 then Exit; Result := TJSONObjectORMBr.CreateClassForJSON(FValues[LIdx]); if Result = nil then Exit; LType := TRttiSingleton.GetInstance.GetRttiType(Result.ClassType); if LType <> nil then begin if LType <> nil then begin for LFor := 0 to Count - 1 do begin if LFor <> LIdx then begin LProperty := LType.GetProperty(FNames[LFor]); if LProperty <> nil then TJSONObjectORMBr.SetInstanceProp(Result, LProperty, FValues[LFor]); end; end; end; end; end; function TJSONVariantData.ToObject(AObject: TObject): Boolean; var LFor: Integer; LItem: TCollectionItem; LListType: TRttiType; LProperty: TRttiProperty; LObjectType: TObject; begin Result := False; if AObject = nil then Exit; case Kind of jvObject: begin AObject.GetType(LListType); if LListType <> nil then begin for LFor := 0 to Count - 1 do begin LProperty := LListType.GetProperty(FNames[LFor]); if LProperty <> nil then TJSONObjectORMBr.SetInstanceProp(AObject, LProperty, FValues[LFor]); end; end; end; jvArray: if AObject.InheritsFrom(TCollection) then begin TCollection(AObject).Clear; for LFor := 0 to Count - 1 do begin LItem := TCollection(AObject).Add; if not TJSONObjectORMBr.JSONVariantData(FValues[LFor]).ToObject(LItem) then Exit; end; end else if AObject.InheritsFrom(TStrings) then try TStrings(AObject).BeginUpdate; TStrings(AObject).Clear; for LFor := 0 to Count - 1 do TStrings(AObject).Add(FValues[LFor]); finally TStrings(AObject).EndUpdate; end else if (Pos('TObjectList<', AObject.ClassName) > 0) or (Pos('TList<', AObject.ClassName) > 0) then begin AObject.GetType(LListType); LListType := GetListType(LListType); if LListType.IsInstance then begin for LFor := 0 to Count - 1 do begin LObjectType := LListType.AsInstance.MetaclassType.Create; if not TJSONObjectORMBr.JSONVariantData(FValues[LFor]).ToObject(LObjectType) then Exit; TRttiSingleton.GetInstance.MethodCall(AObject, 'Add', [LObjectType]); end; end; end else Exit; else Exit; end; Result := True; end; function TJSONVariantData.GetListType(LRttiType: TRttiType): TRttiType; var LTypeName: string; LContext: TRttiContext; begin LContext := TRttiContext.Create; try LTypeName := LRttiType.ToString; LTypeName := StringReplace(LTypeName,'TObjectList<','',[]); LTypeName := StringReplace(LTypeName,'TList<','',[]); LTypeName := StringReplace(LTypeName,'>','',[]); /// Result := LContext.FindType(LTypeName); finally LContext.Free; end; end; { TJSONVariant } procedure TJSONVariant.Cast(var ADest: TVarData; const ASource: TVarData); begin CastTo(ADest, ASource, VarType); end; procedure TJSONVariant.CastTo(var ADest: TVarData; const ASource: TVarData; const AVarType: TVarType); begin if ASource.VType <> VarType then RaiseCastError; Variant(ADest) := TJSONVariantData(ASource).ToJSON; end; procedure TJSONVariant.Clear(var AVarData: TVarData); begin AVarData.VType := varEmpty; Finalize(TJSONVariantData(AVarData).FNames); Finalize(TJSONVariantData(AVarData).FValues); end; procedure TJSONVariant.Copy(var ADest: TVarData; const ASource: TVarData; const AIndirect: Boolean); begin if AIndirect then SimplisticCopy(ADest, ASource, True) else begin VarClear(Variant(ADest)); TJSONVariantData(ADest).Init; TJSONVariantData(ADest) := TJSONVariantData(ASource); end; end; function TJSONVariant.GetProperty(var ADest: TVarData; const AVarData: TVarData; const AName: string): Boolean; begin if not TJSONVariantData(AVarData).GetVarData(AName, ADest) then ADest.VType := varNull; Result := True; end; function TJSONVariant.SetProperty(const AVarData: TVarData; const AName: string; const AValue: TVarData): Boolean; begin TJSONVariantData(AVarData).SetValue(AName, Variant(AValue)); Result := True; end; initialization JSONVariantType := TJSONVariant.Create; {$IFDEF FORMATSETTINGS} FSettingsUS := TFormatSettings.Create('en_US'); {$ELSE FORMATSETTINGS} GetLocaleFormatSettings($0409, FSettingsUS); {$ENDIF FORMATSETTINGS} end.
unit uSnake; {$mode objfpc}{$H+} interface type point = Record x,y:integer; end; type nodeptr = ^snakeNode; snakeNode = Record next: ^snakeNode; place: point; end; qSnake = class(TObject) private tail, head:nodeptr; upv, rightv:integer; size, score, boxh, boxw, frx, fry, frtype, curcolor:integer; public constructor con; procedure grow(base:point); procedure chfreaten(b:point); procedure gennewfr; function getfrtype:integer; function getfrp:point; procedure move; function chCollision():boolean; procedure up; procedure down; procedure left; procedure right; function getsize:integer; function getscore:integer; procedure Create; procedure swcolor; function getccol:integer; procedure update; procedure ttxt; function gettail:nodeptr; function gethead:nodeptr; end; implementation function qSnake.getscore:integer; begin getscore:=score; end; procedure qSnake.ttxt; var n:nodeptr; begin n:=tail; writeln(n^.place.x, ' ', n^.place.y); while (n <> head) do begin n:=n^.next; writeln(n^.place.x, ' ', n^.place.y) ; end; writeln('fr', frtype,' @ ', frx,' ', fry); end; procedure qSnake.update; var b:point; begin b:=tail^.place; move; chfreaten(b); end; function qSnake.getfrtype():integer; begin getfrtype:=frtype; end; function qSnake.gettail:nodeptr; begin gettail:=tail; end; function qSnake.gethead:nodeptr; begin gethead:=head; end; procedure qSnake.chfreaten(b:point); begin if(head^.place.x=frx) and (head^.place.y=fry) then begin if (frtype=1) then begin grow(b); score:=score+1 end else if (frtype=2) then begin score:=score+3; end else begin score:=score+2; swColor; end; gennewfr; end; end; procedure qSnake.gennewfr; begin randomize; frtype:=random(3)+1; frx:=random(boxw)+1; fry:=random(boxh)+1; end; function qSnake.getfrp:point; begin getfrp.x:=frx; getfrp.y:=fry; end; procedure qSnake.swcolor; begin curcolor:=curcolor+1; if curcolor>6 then curcolor:=1; end; function qSnake.getccol:integer; begin getccol:=curcolor; end; procedure qSnake.grow(base:point); var newtail:nodeptr; begin new(newtail); size:=size+1; newtail^.place := base; newtail^.next := tail; tail:=newtail; end; procedure qSnake.move; var n:nodeptr; begin n:= tail; while (n<>head) do begin n^.place := n^.next^.place; n := n^.next; end; head^.place.x := head^.place.x + rightv; head^.place.y := head^.place.y + upv; end; function qSnake.chCollision():boolean; var n:^snakeNode; rval:boolean; begin rval:=false; n:=tail; if(head^.place.x < 1) or (head^.place.y<1) or (head^.place.x>boxw) or (head^.place.y>boxh) then rval:=true else while(n<>head) do begin if((n^.place.x=head^.place.x)and(n^.place.y=head^.place.y)) then begin rval:=true;break; end; n:=n^.next; end; chCollision:=rval; end; procedure qSnake.down(); begin if(upv<>-1) then begin upv:=1; rightv:=0; end; end; procedure qSnake.up(); begin if (upv<>1) then begin upv:=-1; rightv:=0; end; end; procedure qSnake.left(); begin if (rightv<>1) then begin upv:=0; rightv:=-1; end; end; procedure qSnake.right(); begin if (rightv<>-1) then begin upv:=0; rightv:=1; end; end; function qSnake.getsize:longint; begin getsize:=size; end; constructor qSnake.con; begin end; procedure qSnake.Create; var h,m,t:nodeptr; begin boxw:=25; boxh:=25; gennewfr; curcolor:=1; size:= 3; rightv:=1; upv:=0; new(h); h^.place.x:=4; h^.place.y:=2; head:=h; new(m); m^.place.x:=3; m^.place.y:=2; m^.next:=h; new(t); t^.place.x:=2; t^.place.y:=2; t^.next:=m; tail:=t; end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller do lado Cliente relacionado à tabela [VIEW_TRIBUTACAO_ICMS_CUSTOM] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit ViewTributacaoIcmsCustomController; interface uses Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, ViewTributacaoIcmsCustomVO, Generics.Collections; type TViewTributacaoIcmsCustomController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TViewTributacaoIcmsCustomVO>; class function ConsultaObjeto(pFiltro: String): TViewTributacaoIcmsCustomVO; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; end; implementation uses UDataModule, T2TiORM; class procedure TViewTributacaoIcmsCustomController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TViewTributacaoIcmsCustomVO>; begin try Retorno := TT2TiORM.Consultar<TViewTributacaoIcmsCustomVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TViewTributacaoIcmsCustomVO>(Retorno); finally end; end; class function TViewTributacaoIcmsCustomController.ConsultaLista(pFiltro: String): TObjectList<TViewTributacaoIcmsCustomVO>; begin try Result := TT2TiORM.Consultar<TViewTributacaoIcmsCustomVO>(pFiltro, '-1', True); finally end; end; class function TViewTributacaoIcmsCustomController.ConsultaObjeto(pFiltro: String): TViewTributacaoIcmsCustomVO; begin try Result := TT2TiORM.ConsultarUmObjeto<TViewTributacaoIcmsCustomVO>(pFiltro, True); finally end; end; class function TViewTributacaoIcmsCustomController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TViewTributacaoIcmsCustomController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; initialization Classes.RegisterClass(TViewTributacaoIcmsCustomController); finalization Classes.UnRegisterClass(TViewTributacaoIcmsCustomController); end.
Program TreeByFairuza; uses crt; type Tinf=String; pNode=^tNode; {Указатель на узел} tNode=record {Тип запись в котором будет храниться информация} Info:TInf; Left,Right:pNode; {Ссылки на левого и правого сыновей} Index: Integer; end; pRoot=pNode; //Стек pStack=^tStack; {указатель на элемент типа TList} tStack=record Node:pNode; next:pStack; end; //Стек {добавления элеманта в стек} Function isEmptyS(st: pStack):boolean; begin isEmptyS:=(st=nil); end; procedure push(var st:pStack;znach:pNode); var tmp:pStack; begin if (isEmptyS(st)) then //create begin st^.Node:=znach; st^.next:=nil; end else begin new(tmp); tmp^.next:=st; tmp^.Node:=znach; st:=tmp; end; end; Procedure pGet(var st:pStack; var el:pNode); var tmp:pStack; begin el:=st^.Node; //вытаскиваем ссылку. где-то в самой программе нужно dispose tmp:=st; st:=st^.next; dispose(tmp); end; Procedure DestroyS(var st:pStack); var tmp:pStack; begin while st<>nil do begin tmp:=st; st:=st^.next; Dispose(tmp); end; end; Procedure createS(var st:pStack); begin new(st); st^.next:=nil; st:=nil; end; //Дерево Procedure createR(var root:pNode); //создание пустого узла begin new(root); root:=nil; root^.Left:=nil; root^.Right:=nil; end; procedure addToTree (var root:pNode;x:Tinf;i:integer); {Входные параметры - адрес корня дерева и добавл элемент } begin if root=nil then {Если дерево пустое то создаём его корень} begin New(root); {Выделяем память } root^.Info:=x; {Добавляем данные } root^.Index:=i; root^.Left:=nil; {Зануляем указатели на левого } root^.Right:=nil; {и правого сыновей } end else begin if i < root^.Index then {Доб к левому или правому поддереву, это зависит от вводимого элемента} addToTree(root^.Left,x,i) {если меньше корня то в левое поддерево } else addToTree(root^.Right,x,i); {если больше то в правое} end; end; procedure printTree(root:pRoot) ; var Stack:pStack; p:pNode; begin createS(Stack); Stack^.Node:=root; While not isEmptyS(Stack) do begin pGet(Stack,p); While (p<>nil) do begin Write(p^.Info, ' '); p:=p^.Left; if (p^.Right<>nil) then push(Stack,p^.Right); end; end; DestroyS(Stack); end; procedure DeleteTree(var Tree:PNode); //пока рекурсивное удаление begin if Tree <> nil then begin DeleteTree (Tree^.Left); DeleteTree (Tree^.Right); Dispose(Tree); end; end; procedure searchW(root: pRoot;elem:TInf; var found:boolean; var p:pNode{ссылка на элемент}); //ПОИСК в ШИРИНУ var x:pNode; s1,s2:pStack; begin found:=false; createS(s1); createS(s2); push(s2, root); while not isEmptyS(s2){не конец уровней} and not found do begin s1:=s2; while not isEmptyS(s1){не закончились элем уровня} and not found do begin pGet(s1,x); //вытащили ссылку на Node if (x^.Info=elem) then begin found:=true; p:=x; end else begin if (x^.Left<>nil) then push(s2,x^.Left); if (x^.Right<>nil) then push(s2,x^.Right); end; end; end; DestroyS(s1); DestroyS(s2); end; var TreeRoot:pNode; n,i,j:Integer; x:Tinf; found:boolean; p:pNode; begin TreeRoot:=nil; writeln(' Количество элементов в дереве?'); readln(n); writeln(' Дерево поиска'); writeln(' Индекс указывает на место элемента в дереве.'); writeln(' Левее индексы меньше относительно вышестоящих корней, правее соотв-о.'); for j:=1 to n do begin writeln(' Введите индекс и элемент'); readln(i,x); addToTree(TreeRoot,x,i); end; x:='hi'; searchW(TreeRoot,x, found, p); write(found,p^.Info); DeleteTree(TreeRoot); end.
{: Данный модуль срдержит класс, для сопоставления строки шаблону ( подобно регулярным выражениям) По умолчанию * - любой символ и пусто ? - один любой непустой символ $ - Один или более пробелов & - ноль или более пробелов . - аналогично ? но исключая пробел _ - одна цифра # - несколько подряд идущих цифр } unit UMatching; interface //{$define _log_} //{$define _debug_} uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs; const COUNT_META = 9; M_ESCAPE = '\'; // * ? [space] . _ strMatchingKeyType:array[0..COUNT_META-1] of string = ('mktNone','mktKey','mktMetaZ','mktMetaP','mktMetaSpace','mktMetaT','mktMetaNum','mktMetaEms','mktMetaCount'); strMatchingKey:array[0..COUNT_META-1] of string = ('','','*','?','$','.','_','&','#'); type TMatchingKeyType = (mktNone,mktKey,mktMetaZ,mktMetaP,mktMetaSpace,mktMetaT,mktMetaNum,mktMetaEms,mktMetaCount); TMatchingParseRec = class; TMatchingParse = class; TMatching = class; Matching = class(TObject) public class function Matching(aStr, aTemplate: string; aParse: TMatchingParse = nil): Boolean; static; class function Extract(aStr, aTemplate: string;aIndexOfReturnedParam:integer):string;overload; static; class function Extract(aStr:string; aTemplates:array of string;aIndexs:array of integer;aDefault:string = ''):string;overload; static; class function Escape(aStr:string):string;static; class function Loop(aStr:string;aTemplate:string;aIndexResult,aIndexFromLoop:integer;aOut:TStrings):boolean;static; class function Reverse(s:AnsiString):AnsiString;static; end; TMatchingParseRec = class(TObject) public KeyType: TMatchingKeyType; Len: Integer; Pos: Integer; LenStory:integer; Value: string; procedure AssignTo(aTarget: TMatchingParseRec); end; TMatchingParse = class(TObject) private fList: TList; function getCount: Integer; function getItem(Index: Integer): TMatchingParseRec; public constructor Create; virtual; destructor Destroy; override; function Add(aRec: TMatchingParseRec): TMatchingParseRec; virtual; procedure AssignTo(aTarget: TMatchingParse); procedure Clear; procedure Delete(aIndex: Integer = -1); virtual; function Exists(aMatchingStringRec: TMatchingParseRec): Boolean; function IndexOf(aMatchingStringRec: TMatchingParseRec): Integer; function NewItem: TMatchingParseRec; property Count: Integer read getCount; property Item[Index: Integer]: TMatchingParseRec read getItem; default; end; TMatching = class(TObject) private fMeta: array[0..COUNT_META-1] of string; fParse: TMatchingParse; function _Matching(aStr, aTemplate: string): Boolean; function _MatchingLoop(aStr: string; aCurrentKey, aRealPos: integer): Boolean; function GetMetaP: string; procedure SetMetaP(const Value: string); function GetMetaSpace: string; procedure SetMetaSpace(const Value: string); function GetMetaZ: string; procedure SetMetaZ(const Value: string); function GetMetaNum: string; function GetMetaT: string; procedure SetMetaNum(const Value: string); procedure SetMetaT(const Value: string); function GetMetaEms: string; procedure SetMetaEms(const Value: string); public constructor Create; destructor Destroy; override; function Matching(aStr, aTemplate: string): Boolean; function Conf(aStr:string;aParseIndex:integer):string; function ConfTrim(aStr:string;aParseIndex:integer):string; function ConfInt(aStr: string; aParseIndex: integer): integer; function Empty(aStr: string; aParseIndex: integer): boolean; property MetaP: string read GetMetaP write SetMetaP; property MetaSpace: string read GetMetaSpace write SetMetaSpace; property MetaZ: string read GetMetaZ write SetMetaZ; property MetaT: string read GetMetaT write SetMetaT; property MetaNum: string read GetMetaNum write SetMetaNum; property MetaEms: string read GetMetaEms write SetMetaEms; property Parse: TMatchingParse read fParse; end; implementation uses {$ifdef _log_}ULog, {$endif} UStr; { *********************************** Matching *********************************** } class function Matching.Escape(aStr: string): string; var cBuild:TStringBuilder; i: Integer; begin // экранирование ключевых символов в строке cBuild:=TStringBuilder.Create; cBuild.Append(aStr); for i:=0 to Length(strMatchingKey) - 1 do begin if (strMatchingKey[i]<>'') then cBuild.Replace(strMatchingKey[i],M_ESCAPE+strMatchingKey[i]); end; result:=cBuild.ToString; cBuild.Free; end; class function Matching.Extract(aStr, aTemplate: string; aIndexOfReturnedParam: integer): string; var cMatch:TMatching; begin result:=''; cMatch:=TMatching.Create; try if cMatch.Matching(aStr,aTemplate) then result:=cMatch.ConfTrim(aStr,aIndexOfReturnedParam); finally cMatch.Free; end; end; class function Matching.Extract(aStr:string; aTemplates:array of string;aIndexs:array of integer;aDefault:string = ''):string; const cFuncName = 'Extract'; var cMatch:TMatching; cIndex:integer; i: Integer; begin {$ifdef _log_} SLog.Stack(ClassName,cFuncName);{$endif} cMatch:=TMatching.Create; result:=aDefault; try try for i:=0 to length(aTemplates)-1 do begin if i>=Length(aIndexs) then cIndex:=aIndexs[Length(aIndexs)-1] else cIndex:=aIndexs[i]; if cMatch.Matching(aStr,aTemplates[i]) then begin result:=cMatch.ConfTrim(aStr,(cIndex)); exit; end end; except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} end; end; finally cMatch.Free; end; end; class function Matching.Loop(aStr, aTemplate: string; aIndexResult,aIndexFromLoop: integer; aOut: TStrings): boolean; const cFuncName = 'Loop'; var cMatch:TMatching; cOriginal:string; begin // применяем Match к результату обрезанному по aIndexFromLoop // а в aOut сохраняем значение из aIndexResult // В случае отрицательного сопоставления возварщает полную строку в aOut // Удобно для разбора строки на массив // Ex: Loop("1,2,3,6-7,4,","*,*",0,2,cOut) - // res: cOut[0] = "1" // cOut[1] = "2 // cOut[2] = "3" // cOut[3] = "6-7" // cOut[4] = "4" // cOut[5] = "" {$ifdef _log_} SLog.Stack(ClassName,cFuncName);{$endif} cMatch:=TMatching.Create; result:=false; aOut.Clear; cOriginal:=aStr; try try //TO DO while cMatch.Matching(aStr,aTemplate) do begin aOut.Add(cMatch.Conf(aStr,aIndexResult)); aStr:=copy(aStr,cMatch.Parse[aIndexFromLoop].Pos,Length(aStr)); result:=true; end; if result then aOut.Add(aStr) else aOut.Add(cOriginal); except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} aOut.Add(cOriginal); end; end; finally cMatch.Free; end; end; class function Matching.Matching(aStr, aTemplate: string; aParse: TMatchingParse = nil): Boolean; var cMatch: TMatching; const cFuncName = 'Matching'; begin cMatch:=TMatching.Create(); try try result:=cMatch.Matching(aStr,aTemplate); if aParse<>nil then cMatch.Parse.AssignTo(aParse); except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} result:=false; end; end; finally cMatch.Free; end; end; class function Matching.Reverse(s: AnsiString): AnsiString; var i : integer; begin result := ''; for i := 1 to Length( s ) do begin result := s[ i ] + result; end; end; { ****************************** TMatchingParseRec ******************************* } procedure TMatchingParseRec.AssignTo(aTarget: TMatchingParseRec); begin if (aTarget<>nil) then begin aTarget.Len:=Len; aTarget.Pos:=Pos; aTarget.Value:=Value; aTarget.LenStory:=LenStory; aTarget.KeyType:=KeyType; end; end; { ******************************** TMatchingParse ******************************** } constructor TMatchingParse.Create; begin inherited Create; fList:=TList.Create; end; destructor TMatchingParse.Destroy; begin Clear; fList.Free; inherited Destroy; end; function TMatchingParse.Add(aRec: TMatchingParseRec): TMatchingParseRec; begin try result:=aRec; fList.Add(result); except result:=nil; end; end; procedure TMatchingParse.AssignTo(aTarget: TMatchingParse); var i: Integer; begin if (aTarget<>nil) then begin aTarget.Clear; for i:=0 to Count - 1 do Item[i].AssignTo(aTarget.NewItem); end; end; procedure TMatchingParse.Clear; begin Delete(-1); end; procedure TMatchingParse.Delete(aIndex: Integer = -1); var cObj: TMatchingParseRec; begin if aIndex = -1 then begin while fList.Count>0 do Delete(fList.Count-1); end else begin cObj:=TMatchingParseRec(fList.Items[aIndex]); cObj.Free; fList.Delete(aIndex); end; end; function TMatchingParse.Exists(aMatchingStringRec: TMatchingParseRec): Boolean; begin result:=(IndexOf(aMatchingStringRec)<>-1); end; function TMatchingParse.getCount: Integer; begin result:=fList.Count; end; function TMatchingParse.getItem(Index: Integer): TMatchingParseRec; begin result:=TMatchingParseRec(fList.Items[Index]); end; function TMatchingParse.IndexOf(aMatchingStringRec: TMatchingParseRec): Integer; begin result:=fList.IndexOf(aMatchingStringRec); end; function TMatchingParse.NewItem: TMatchingParseRec; begin result:=TMatchingParseRec.Create; Add(result); end; { ********************************** TMatching *********************************** } function TMatching.Conf(aStr: string; aParseIndex: integer): string; var cRec: TMatchingParseRec; begin cRec:=Parse.Item[aParseIndex]; if cRec<>nil then result:=copy(aStr,cRec.Pos,cRec.Len) else result:=''; end; function TMatching.Empty(aStr:string;aParseIndex:integer):boolean; begin result:=(ConfTrim(aStr,aParseIndex) = ''); end; function TMatching.ConfTrim(aStr: string; aParseIndex: integer): string; begin result:=Trim(Conf(aStr,aParseIndex)); end; function TMatching.ConfInt(aStr: string; aParseIndex: integer): integer; begin try result:=StrToInt(ConfTrim(aStr,aParseIndex)); except result:=-3333333; end; end; constructor TMatching.Create; begin inherited Create; fParse:=TMatchingParse.Create; fMeta[integer(mktMetaZ)]:='*'; fMeta[integer(mktMetaP)]:='?'; fMeta[integer(mktMetaSpace)]:='$'; fMeta[integer(mktMetaT)]:='.'; fMeta[integer(mktMetaNum)]:='_'; fMeta[integer(mktMetaEms)]:='&'; fMeta[integer(mktMetaCount)]:='#'; end; destructor TMatching.Destroy; begin fParse.Free; inherited Destroy; end; function TMatching.GetMetaEms: string; begin result:=fMeta[integer(mktMetaEms)]; end; function TMatching.GetMetaNum: string; begin result:=fMeta[integer(mktMetaNum)]; end; function TMatching.GetMetaP: string; begin result:=fMeta[integer(mktMetaP)]; end; function TMatching.GetMetaSpace: string; begin result:=fMeta[integer(mktMetaSpace)]; end; function TMatching.GetMetaT: string; begin result:=fMeta[integer(mktMetaT)]; end; function TMatching.GetMetaZ: string; begin result:=fMeta[integer(mktMetaZ)]; end; function TMatching.Matching(aStr, aTemplate: string): Boolean; begin result:=_Matching(aStr,aTemplate); end; procedure TMatching.SetMetaEms(const Value: string); begin fMeta[integer(mktMetaEms)]:=Value; end; procedure TMatching.SetMetaNum(const Value: string); begin fMeta[integer(mktMetaNum)]:=Value; end; procedure TMatching.SetMetaP(const Value: string); begin fMeta[integer(mktMetaP)]:=Value; end; procedure TMatching.SetMetaSpace(const Value: string); begin fMeta[integer(mktMetaSpace)]:=Value; end; procedure TMatching.SetMetaT(const Value: string); begin fMeta[integer(mktMetaT)]:=Value; end; procedure TMatching.SetMetaZ(const Value: string); begin fMeta[integer(mktMetaZ)]:=Value; end; function TMatching._Matching(aStr, aTemplate: string): Boolean; var cTemplate: string; //cPosZ: Integer; //cPosP: Integer; //cPosS: Integer; cPos: Integer; cRec: TMatchingParseRec; cKeyType: TMatchingKeyType; cTmp: string; arPos:array[1..COUNT_META-1] of integer; cAddToPrev: boolean; cBuilder:TStringBuilder; i: Integer; procedure _set_pos(); var i:integer; begin for i:=1 to COUNT_META-1 do arPos[i]:=StrUtils.PosWithoutShield(fMeta[i],cTemplate); end; function _absent():boolean; var i:integer; begin result:=false; for i:=1 to COUNT_META-1 do if arPos[i]>0 then exit; result:=true; end; procedure _assept(); var i,j:integer; cPosUp,cPosDn:integer; cBool:boolean; begin for i:=1 to COUNT_META -1 do begin cPosUp:=arPos[i]; cBool:=(cPosUp > 0); if (cBool) then begin for j:=1 to COUNT_META-1 do begin if j<>i then begin cPosDn:=arPos[j]; cBool:=((cPosUp<cPosDn) or (cPosDn=0)) and cBool; end; end;//for j end;//if if cBool then begin cPos:=cPosUp; cKeyType:=TMatchingKeyType(i); break; end; end; end; procedure _set_init_len(); begin if (cKeyType = mktMetaP) or (cKeyType = mktMetaT) or (cKeyType = mktMetaNum) or (cKeyType = mktMetaSpace) or (cKeyType = mktMetaCount) then cRec.Len:=1 else cRec.Len:=0; cRec.LenStory:=cRec.Len; end; function _remove_shield(aStr:string):string; var i:integer; begin i:=1; while i<Length(aStr) do begin if (aStr[i] = M_ESCAPE) and (i<Length(aStr)) and (aStr[i+1]<> M_ESCAPE) then delete(aStr,i,1) else inc(i); end; result:=aStr; end; procedure _check_prev(); begin cAddToPrev:=false; if fParse.Count>0 then begin cRec:=fParse.Item[fParse.Count-1]; if fParse.Item[fParse.Count-1].KeyType <> mktKey then cRec:=fParse.NewItem else cAddToPrev:=true; end else cRec:=fParse.NewItem; cRec.KeyType:=mktKey; end; const cFuncName = '_Matching'; begin // aTemplate = World1 * World?World // * - любое колво и ни одного // ? - один лбой символ // разбираем строку fParse.Clear; cBuilder:=TStringBuilder.Create; try try // убираем двойной слеш из экранов cTemplate:=cBuilder.Append(aTemplate).Replace(M_ESCAPE+M_ESCAPE,M_ESCAPE+#191).ToString; //cTemplate:=aTemplate; while Length(cTemplate)>0 do begin _set_pos(); if (_absent()) then begin _check_prev(); cTemplate:=_remove_shield(cTemplate); if cAddToPrev then begin cRec.Value:=cRec.Value+cTemplate; cRec.Len:=cRec.Len+Length(cTemplate); end else begin cRec.Value:=cTemplate; cRec.Len:=Length(cTemplate); end; cRec.LenStory:=cRec.Len; cTemplate:=''; end else begin _assept(); if cPos>1 then begin cTmp:=_remove_shield(copy(cTemplate,1,cPos-1)); _check_prev(); if cAddToPrev then begin cRec.Value:=cRec.Value+cTmp; cRec.Len:=cRec.Len+Length(cTmp); end else begin cRec.Value:=cTmp; cRec.Len:=Length(cTmp); end; cRec.LenStory:=cRec.Len; //cRec.KeyType:=mktKey; //cRec.Value:=cTmp; //cRec.Len:=Length(cTmp); //cKeys.Add(cTmp); cTmp:=copy(cTemplate,cPos,1); if fParse<>nil then begin cRec:=fParse.NewItem; cRec.KeyType:=cKeyType; cRec.Value:=cTmp; _set_init_len(); end; //cKeys.Add(cTmp); end else begin cTmp:=copy(cTemplate,cPos,1); if fParse<>nil then begin cRec:=fParse.NewItem; cRec.KeyType:=cKeyType; cRec.Value:=cTmp; _set_init_len(); end; //cKeys.Add(cTmp); end; cTemplate:=copy(cTemplate,cPos+1,Length(cTemplate)); end; end; for i:=0 to fParse.Count-1 do begin cBuilder.Length:=0; fParse.Item[i].Value:=cBuilder.Append(fParse.Item[i].Value).Replace(#191,M_ESCAPE).ToString; {$ifdef _debug_} ULog.Log('%d Key=%s Value=%s ',[i,strMatchingKeyType[integer(fParse.Item[i].KeyType)],fParse.Item[i].Value],ClassName,cFuncName);{$endif} end; // начинаем проходку result:=_MatchingLoop(aStr,0,1); except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} result:=false; end; end; finally //cKeys.Free; cBuilder.Free; end; end; function TMatching._MatchingLoop(aStr: string; aCurrentKey, aRealPos: integer): Boolean; var cPos: Integer; cRec: TMatchingParseRec; cBuf: string; cTmp:string; cAdd:integer; function IsEnd():boolean; begin result:= (aCurrentKey >= (fParse.Count-1)); end; function _single():boolean; begin result:=(((Length(aStr) = 1) and IsEnd()) or (Length(aStr)>0) and not IsEnd()); end; function _getendnumpos():integer; begin result:=0; if aStr = '' then exit; while StrUtils.CharIsNum(Char(aStr[result+1])) do result:=result+1; end; const cFuncName = '_MatchingLoop'; begin result:=false; try try // получаем текущий ключ //cNext:=_GetNextKey(aCurrentKey,aKeys); result:=false; cRec:=fParse.Item[aCurrentKey]; cRec.Len:=cRec.LenStory; cRec.Pos:=aRealPos; case cRec.KeyType of mktKey: begin cPos:=Pos(cRec.Value,aStr); if cPos = 1 then begin if not IsEnd() then begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); end else result:=(cRec.Value = aStr); end else result:=false; end; mktMetaZ: begin result:=false; cBuf:=aStr; while (not result) do begin if not IsEnd() then begin if (Length(cBuf)>0) then begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); if not result then cRec.Len:=cRec.Len+1; end else exit;// result = false; end else begin cRec.Len:=Length(aStr); result:=true; end; end;//while end; mktMetaEms: begin result:=false; cBuf:=aStr; cRec.Len:=0; while (not result) do begin if IsEnd() then begin result:=(Trim(cBuf) = ''); if result then cRec.Len:=Length(cBuf); exit; end else begin if Length(cBuf) = 0 then exit; cTmp:=copy(aStr,1,cRec.Len); cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); if (Trim(cTmp) = '') then begin result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); if not result then cRec.Len:=cRec.Len+1 else exit; end else exit; end; end;//while end; mktMetaP: begin result:=_single(); if (result) and (not IsEnd()) then begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); end; end; mktMetaT: begin result:=_single() and (aStr[1]<>' '); if (result) and (not IsEnd()) then begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); end; end; mktMetaNum: begin result:=_single() and (StrUtils.CharIsNum(Char(aStr[1]))); if (result) and (not IsEnd())then begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); end; end; mktMetaCount: begin cAdd:=_getendnumpos(); result:=(cAdd>0); cRec.Len:=0; if (result) then begin result :=false; cRec.Len :=cAdd; while (cRec.Len>0) do begin cBuf:=copy(aStr,cRec.Len+1,Length(aStr)); if (Length(cBuf)>0) then begin if (not IsEnd()) then begin result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); if result then break; end else break; end else begin if IsEnd() then begin result:=true; break; end else begin result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); if result then break; end; end; dec(cRec.Len); end; end; end;//mktMetaSpace: mktMetaSpace: begin result:=false; cBuf:=aStr; cRec.Len:=Length(cBuf)-Length(TrimLeft(cBuf)); //result:= (cRec.Len>0); if cRec.Len>0 then while (not result) do begin if IsEnd() then begin result:=(Length(cBuf)=0) or (Trim(cBuf) = ''); if result then cRec.Len:=Length(cBuf); exit; end else begin cBuf:=copy(cBuf,cRec.Len+1,Length(cBuf)); result:=_MatchingLoop(cBuf, aCurrentKey+1,aRealPos+cRec.Len); if not result then cRec.Len:=cRec.Len-1; if (result) or (cRec.Len <0) then exit; end; end;//while end;//mktMetaSpace: end;// case except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} end; end; finally end; end; end.
unit DIFileCache; interface uses Classes, DISQLite3Cache; type TDIFileBlock = record Len: Integer; // Count of data bytes in block. Data: record end; end; PDIFileBlock = ^TDIFileBlock; //------------------------------------------------------------------------------ // TDIFileCache class //------------------------------------------------------------------------------ { Provides buffered access to blocks of a file. } TDIFileCache = class private FBlockSize: Integer; FCache: TDISQLite3Cache; FFileName: AnsiString; FFileStream: TFileStream; FUpdateCount: Integer; public constructor Create(const AFileName: AnsiString; const ABlockSize: Integer); { Reads blocks from file and adds them to the internal cache. Returns a pointer to the last block added to the cache. } function AddBlocksToCache(ABlockIdx, ABlockCount: Integer): PDIFileBlock; procedure BeginUpdate; procedure EndUpdate; { Reads a block from disk into the cache and returns a pointer to the cached block. } function GetBlock(const ABlockIdx: Integer): PDIFileBlock; procedure Invalidate; property BlockSize: Integer read FBlockSize; end; function BlockToHex(const ABlock: PDIFileBlock): AnsiString; function BlockToText(const ABlock: PDIFileBlock): AnsiString; implementation uses SysUtils; //------------------------------------------------------------------------------ // TDIFileCache class //------------------------------------------------------------------------------ constructor TDIFileCache.Create(const AFileName: AnsiString; const ABlockSize: Integer); begin FFileName := AFileName; FBlockSize := ABlockSize; FCache := TDISQLite3Cache.Create(SizeOf(TDIFileBlock) + ABlockSize); FCache.MaxCount := 396; end; //------------------------------------------------------------------------------ function TDIFileCache.AddBlocksToCache(ABlockIdx, ABlockCount: Integer): PDIFileBlock; var Pos: Int64; begin Result := nil; BeginUpdate; try Pos := ABlockIdx * FBlockSize; if FFileStream.Seek(Pos, soFromBeginning) = Pos then repeat Result := FCache.GetItem(ABlockIdx); if not Assigned(Result) then Result := FCache.AddItem(ABlockIdx); Result.Len := FFileStream.Read(Result^.Data, FBlockSize); Inc(ABlockIdx); Dec(ABlockCount); until (Result.Len < FBlockSize) or (ABlockCount = 0); finally EndUpdate; end; end; //------------------------------------------------------------------------------ procedure TDIFileCache.BeginUpdate; begin if FUpdateCount = 0 then FFileStream := TFileStream.Create(FFileName, fmOpenRead or fmShareDenyNone); Inc(FUpdateCount); end; //------------------------------------------------------------------------------ procedure TDIFileCache.EndUpdate; begin if FUpdateCount > 0 then begin Dec(FUpdateCount); if FUpdateCount = 0 then FFileStream.Free; end; end; //------------------------------------------------------------------------------ function TDIFileCache.GetBlock(const ABlockIdx: Integer): PDIFileBlock; begin Result := FCache.GetItem(ABlockIdx); if not Assigned(Result) then Result := AddBlocksToCache(ABlockIdx, 1); end; //------------------------------------------------------------------------------ procedure TDIFileCache.Invalidate; begin FCache.Invalidate; end; //------------------------------------------------------------------------------ // Functions //------------------------------------------------------------------------------ function BlockToHex(const ABlock: PDIFileBlock): AnsiString; var l: Integer; p: ^Byte; begin Result := ''; p := @ABlock^.Data; l := ABlock^.Len; while l > 0 do begin Result := Result + IntToHex(p^, 2) + ' '; Inc(p); Dec(l); end; end; //------------------------------------------------------------------------------ function BlockToText(const ABlock: PDIFileBlock): AnsiString; var l: Integer; p: PAnsiChar; begin l := ABlock.Len; SetString(Result, PAnsiChar(@ABlock^.Data), l); p := Pointer(Result); while l > 0 do begin if p^ < #32 then p^ := '.'; Inc(p); Dec(l); end; end; end.
{ Subroutine STRING_T_INT32H (S,I,STAT) * * Convert the string S to the integer I. S is assumed to be in hexadecimal * notation. STAT is the completion status code. } module string_t_int32h; define string_t_int32h; %include 'string2.ins.pas'; procedure string_t_int32h ( {convert HEX string to 32 bit integer} in s: univ string_var_arg_t; {input string} out i: sys_int_min32_t; {output integer, bits will be right justified} out stat: sys_err_t); {completion status code} var im: sys_int_max_t; {raw integer value} begin string_t_int_max_base ( {convert string to raw integer} s, {input string} 16, {number base of string} [string_ti_unsig_k], {unsigned number, blank is error} im, {raw integer value} stat); if sys_error(stat) then return; if (im & 16#FFFFFFFF) = im then begin {value is within range} i := im; {pass back final value} end else begin {value is out of range} sys_stat_set (string_subsys_k, string_stat_ovfl_i_k, stat); sys_stat_parm_vstr (s, stat); end ; end;
object EditOrderAttackForm: TEditOrderAttackForm Left = 252 Top = 172 BorderStyle = bsSizeToolWin Caption = 'Edit ATTACK Order' ClientHeight = 280 ClientWidth = 322 Color = clBtnFace Constraints.MinHeight = 200 Constraints.MinWidth = 221 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False DesignSize = ( 322 280) PixelsPerInch = 96 TextHeight = 13 object Label2: TLabel Left = 0 Top = 12 Width = 31 Height = 13 Caption = 'Attack' Layout = tlBottom end object Label3: TLabel Left = 0 Top = 36 Width = 35 Height = 13 Caption = 'Faction' end object bnOk: TButton Left = 24 Top = 248 Width = 75 Height = 25 Anchors = [akLeft, akBottom] Caption = '&OK' ModalResult = 1 TabOrder = 4 OnClick = bnOkClick end object bnCancel: TButton Left = 128 Top = 248 Width = 75 Height = 25 Anchors = [akLeft, akBottom] Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 5 OnClick = bnCancelClick end object cbCommented: TCheckBox Left = 129 Top = 226 Width = 79 Height = 17 Anchors = [akLeft, akBottom] Caption = '&Commented' TabOrder = 3 end object cbRepeating: TCheckBox Left = 25 Top = 226 Width = 71 Height = 17 Anchors = [akLeft, akBottom] Caption = '&Repeating' TabOrder = 2 end object cbCanTargets: TComboBox Left = 40 Top = 8 Width = 280 Height = 21 Anchors = [akLeft, akTop, akRight] DropDownCount = 16 ItemHeight = 0 TabOrder = 0 OnChange = cbCanTargetsChange OnDblClick = bnAddClick end object cbFacDiap: TComboBox Left = 40 Top = 32 Width = 280 Height = 21 Style = csDropDownList Anchors = [akLeft, akTop, akRight] ItemHeight = 0 TabOrder = 1 OnChange = cbFacDiapChange OnEnter = cbFacDiapEnter OnKeyPress = cbFacDiapKeyPress end object lbTargets: TListBox Left = 8 Top = 64 Width = 309 Height = 121 Anchors = [akLeft, akTop, akRight, akBottom] ItemHeight = 13 TabOrder = 6 OnDblClick = bnDeleteClick end object bnAdd: TButton Left = 24 Top = 192 Width = 75 Height = 25 Anchors = [akLeft, akBottom] Caption = '&Add' Default = True TabOrder = 7 OnClick = bnAddClick end object bnDelete: TButton Left = 232 Top = 192 Width = 75 Height = 25 Anchors = [akLeft, akBottom] Caption = '&Delete' TabOrder = 8 OnClick = bnDeleteClick end object bnAddAll: TButton Left = 120 Top = 192 Width = 75 Height = 25 Anchors = [akLeft, akBottom] Caption = 'Add A&ll' TabOrder = 9 OnClick = bnAddAllClick end end
begin write('Hello, world!')end.
// Copyright 2018 by John Kouraklis and Contributors. 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 Casbin.Functions; interface uses Casbin.Core.Base.Types, Casbin.Functions.Types, System.Generics.Collections, System.Classes, System.Types, System.Rtti; type TFunctions = class (TBaseInterfacedObject, IFunctions) private fDictionary: TDictionary<string, TCasbinFunc>; fObjDictionary: TDictionary<string, TCasbinObjectFunc>; fList: TStringList; procedure loadBuiltInFunctions; procedure loadCustomFunctions; //PALOFF private {$REGION 'Interface'} procedure registerFunction(const aName: string; const aFunc: TCasbinFunc); overload; procedure registerFunction(const aName: string; const aFunc: TCasbinObjectFunc); overload; function retrieveFunction(const aName: string): TCasbinFunc; function retrieveObjFunction(const aName: string): TCasbinObjectFunc; function list: TStringList; procedure refreshFunctions; {$ENDREGION} public constructor Create; destructor Destroy; override; end; implementation uses System.SysUtils, System.RegularExpressions, System.StrUtils, Casbin.Functions.IPMatch, Casbin.Functions.KeyMatch, Casbin.Functions.KeyMatch2, Casbin.Functions.RegExMatch; constructor TFunctions.Create; begin inherited; fDictionary:=TDictionary<string, TCasbinFunc>.Create; fObjDictionary:=TDictionary<string, TCasbinObjectFunc>.Create; fList:=TStringList.Create; fList.Sorted:=true; loadBuiltInFunctions; loadCustomFunctions; end; destructor TFunctions.Destroy; var item: string; begin for item in fDictionary.Keys do fDictionary.AddOrSetValue(item, nil); for item in fDictionary.Keys do fObjDictionary.AddOrSetValue(item, nil); fDictionary.Free; fObjDictionary.Free; fList.Free; inherited; end; procedure TFunctions.refreshFunctions; begin fDictionary.Clear; loadBuiltInFunctions; loadCustomFunctions; end; procedure TFunctions.registerFunction(const aName: string; const aFunc: TCasbinObjectFunc); begin if Trim(aName)='' then raise Exception.Create('Obj Function to register must have a name'); if not Assigned(aFunc) then raise Exception.Create('Obj Function to register is nil'); if Assigned(aFunc) then fObjDictionary.AddOrSetValue(Trim(aName), aFunc); end; function TFunctions.retrieveFunction(const aName: string): TCasbinFunc; begin if not fDictionary.ContainsKey(Trim(aName)) then raise Exception.Create('Function '+aName+' is not registered'); Result:=fDictionary.Items[Trim(aName)]; end; procedure TFunctions.registerFunction(const aName: string; const aFunc: TCasbinFunc); begin if Trim(aName)='' then raise Exception.Create('Function to register must have a name'); if not Assigned(aFunc) then raise Exception.Create('Function to register is nil'); if Assigned(aFunc) then fDictionary.AddOrSetValue(Trim(aName), aFunc); end; function TFunctions.retrieveObjFunction(const aName: string): TCasbinObjectFunc; begin if not fObjDictionary.ContainsKey(Trim(aName)) then raise Exception.Create('Function '+aName+' is not registered'); Result:=fObjDictionary.Items[Trim(aName)]; end; function TFunctions.list: TStringList; var name: string; begin fList.Clear; for name in fDictionary.Keys do fList.add(name); for name in fObjDictionary.Keys do fList.add(name); Result:=fList; end; procedure TFunctions.loadBuiltInFunctions; begin fDictionary.Add('KeyMatch', KeyMatch); fDictionary.Add('KeyMatch2', KeyMatch2); fDictionary.Add('KeyMatch3', KeyMatch2); fDictionary.Add('RegExMatch', regexMatch); fDictionary.Add('IPMatch', IPMatch); end; procedure TFunctions.loadCustomFunctions; begin // Add call to fDictionary.Add to register a custom function end; end.
unit Interseccion; {$mode objfpc}{$H+} interface uses Classes, SysUtils,Dialogs,math,ParseMath,MetodosC; type t_matrix= array of array of real; Type TInterseccion=class public restaF:String; constructor create(); function executeInnterseccion(f1,g1:string;min,max,h:real):t_matrix; private Parse:TParseMath; function Bolzano(ay,by:Double):Integer; function fB(x:Real):Real; end; implementation constructor TInterseccion.create(); begin parse:=TParseMath.create(); Parse.AddVariable('x',0); end; function TInterseccion.fB(x:Real):Real; begin Parse.Expression:=restaF; Parse.NewValue('x',x); Result:=Parse.Evaluate(); end; function TInterseccion.Bolzano(ay,by:Double):Integer; var test:double; begin if (IsNan(fB(ay))or IsNan(fB(by))) then begin Result:=-1; exit; end; if ((fB(ay)=0) or (fB(by)=0)) then begin Result:=1; exit; end; test:=fB(ay)*fB(by); if test<=0 then begin Result:=1; end else Result:=-1; end; function TInterseccion.executeInnterseccion(f1,g1:string;min,max,h:real):t_matrix; var valor:Real; intVA,intVB:Real; error:Real; //Puntos:TStringList; Puntos:Array[0..20] of Real; i,j,test,x:Integer; y:Real; Bisecccion:TMetodos; begin restaF:=f1+'-('+g1+')'; intVA:=min; intVB:=max; error:=0.0001; Bisecccion:=TMetodos.Create(restaF); i:=0; while intVA<=max+h do begin test:=Bolzano(intVA,intVA+h); { Bisecccion.a:=intVA; Bisecccion.b:=intVA+ht; try valor:=StrToFloat(Bisecccion.biseccion()); Except valor:=-1; end; } if test<>-1 then begin valor:=StrToFloat(Bisecccion.biseccion(intVA,intVA+h,error)); //ShowMessage(':'+floatTostr(valor)); Puntos[i]:=valor; i:=i+1; end; intVA:=intVA+h; end; SetLength(Result,i,2); Parse.Expression:=f1; for j:=0 to i-1 do begin Parse.NewValue('x',Puntos[j]); Result[j][0]:=Puntos[j]; Result[j][1]:=Parse.Evaluate(); end; { for x:=0 to i-1 do begin ShowMessage('x: ->'+FloatToStr(Result[x][0])+' y:->'+FloatToStr(Result[x][1])); end; } end; end.
unit MemoryStreamReader; { Implements the TMemoryStreamReader object. It's basically a memorystream that can not write. It's main purpose is to provide a seperate read pointer for a memorystream object One requirement is that the memorystream object does not get written to while this object exists } {$mode delphi} interface uses Classes, SysUtils; type TMemoryStreamReader=class(TCustomMemoryStream) private protected public constructor create(ms: TCustomMemoryStream); end; implementation constructor TMemoryStreamReader.create(ms: TCustomMemoryStream); begin inherited create; SetPointer(ms.Memory, ms.size); end; end.
unit VSECamera; interface uses OpenGL, avlVectors, avlMath; type TCamera = class private FEye, FCenter: TVector3D; FAngle: TVector2D; procedure UpdateCenter; procedure SetAngle(const Value: TVector2D); procedure SetEye(const Value: TVector3D); procedure SetHeight(const Value: Single); public procedure Apply; procedure Move(Offset: TVector2D; LocalSpace: Boolean = true); overload; procedure Move(Offset, BoundsMin, BoundsMax: TVector2D; LocalSpace: Boolean = true); overload; property Angle: TVector2D read FAngle write SetAngle; property Center: TVector3D read FCenter; property Eye: TVector3D read FEye write SetEye; property Height: Single read FEye.Y write SetHeight; end; const DegToRad = Pi / 180; {var Camera: TCamera;} implementation procedure TCamera.Apply; begin glPushAttrib(GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); gluLookAt(FEye.X, FEye.Y, FEye.Z, FCenter.X, FCenter.Y, FCenter.Z, 0, 1, 0); glPopAttrib; end; procedure TCamera.Move(Offset: TVector2D; LocalSpace: Boolean); var C, S, T: Single; begin if LocalSpace then begin C := Cos(FAngle.X * DegToRad); S := Sin(FAngle.X * DegToRad); with Offset do begin T := C * Y + S * X; X := C * X - S * Y; Y := T; end; end; FEye.X := FEye.X + Offset.X; FEye.Z := FEye.Z + Offset.Y; UpdateCenter; end; procedure TCamera.Move(Offset, BoundsMin, BoundsMax: TVector2D; LocalSpace: Boolean); begin Move(Offset, LocalSpace); FEye.X := Max(BoundsMin.X, Min(FEye.X, BoundsMax.X)); FEye.Z := Max(BoundsMin.Y, Min(FEye.Z, BoundsMax.Y)); UpdateCenter; end; procedure TCamera.UpdateCenter; var Dist: Single; begin Dist := cos(FAngle.Y * DegToRad); FCenter.X := FEye.X + sin(-FAngle.X * DegToRad) * Dist; FCenter.Y := FEye.Y + sin(FAngle.Y * DegToRad); FCenter.Z := FEye.Z + cos(-FAngle.X * DegToRad) * Dist; end; procedure TCamera.SetAngle(const Value: TVector2D); begin FAngle := Value; UpdateCenter; end; procedure TCamera.SetEye(const Value: TVector3D); begin FEye := Value; UpdateCenter; end; procedure TCamera.SetHeight(const Value: Single); begin FEye.Y := Value; UpdateCenter; end; end.
unit UAddGoodForm; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.FMTBcd, Data.DB, Data.SqlExpr, Data.Win.ADODB, UMainDataModule, Vcl.Mask, Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.Buttons; type TAddGoodForm = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; DBEditNameGood: TDBEdit; DBEditSizeGood: TDBEdit; DBEditMaterialGood: TDBEdit; DBEditPurchPr: TDBEdit; DBEditQuantity: TDBEdit; DBEditSellPr: TDBEdit; PanelAddGood: TPanel; dblcTypeGoods: TDBLookupComboBox; bibCancel: TBitBtn; bibClearFields: TBitBtn; bibAddGood: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bibCancelClick(Sender: TObject); procedure bibClearFieldsClick(Sender: TObject); procedure bibAddGoodClick(Sender: TObject); procedure DBEditNameGoodChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var AddGoodForm: TAddGoodForm; implementation uses UMainForm; {$R *.dfm} procedure TAddGoodForm.bibAddGoodClick(Sender: TObject); begin MainDataModule.ADOTableGoods.Post; end; procedure TAddGoodForm.bibCancelClick(Sender: TObject); begin MainDataModule.ADOTableGoods.Cancel; end; procedure TAddGoodForm.bibClearFieldsClick(Sender: TObject); begin DBEditNameGood.Field.Clear; dblcTypeGoods.KeyValue:= -1; DBEditSizeGood.Field.Clear; DBEditMaterialGood.Field.Clear; DBEditQuantity.Field.Clear; DBEditSellPr.Field.Clear; DBEditPurchPr.Field.Clear; end; procedure TAddGoodForm.DBEditNameGoodChange(Sender: TObject); begin // DBEditNameGood.Text:= Utf8ToAnsi(DBEditNameGood.Text); end; procedure TAddGoodForm.FormClose(Sender: TObject; var Action: TCloseAction); begin dblcTypeGoods.Destroy; end; end.
Unit PJSP; Interface Uses Crt, Dos, Graph; Function UpperCase( StrIn : String ) : String; Procedure EscreveEm( X, Y: Byte; StrIn: String ); Function ReadString( X, Y, Tamanho: Integer; Tipo: Char):String; Function ReadNum( X, Y, Tamanho: Integer; Tipo: Char):String; Function ReadInt( x, y, Tamanho: Integer; Tipo: Char):String; Function ReadStringG( X, Y, Tamanho: Integer ):String; Function ReadNumG( X, Y, Tamanho: Integer ):String; Function ReadIntG( x1,y1,x2,y2,nH,nV,Tamanho,Cor,CorF: Word):String; Function ReadIntX( X, Y, Tam: Byte; Car: Char ): String; Function Real_Em_Str( rIn: Real ): String; Function Int_Em_Tam( n: Byte; Valor: Word ): String; Function Str_Em_Tam( n: Byte; StrIn: String ): String; Function Num_Em_Str( Valor: Integer ): String; Function Long_Em_Str( Valor: LongInt; Var L: Byte ): String; Function Str_Em_Num( StrIn: String ): Word; Function Str_Em_Long( StrIn: String ): LongInt; Function Existe_Ficheiro( NomeF: String ) : Boolean; Function Divide_em_Milhares( Valor: String; Virgula: Char ): String; Function Le_Teclado: String; Procedure Data(Var Ds: String; Var Dia,Mes,Ano:Word); Implementation Type po = ^Jan; Jan = Record Atrib : Word; Prox : Po; End; Sp = ^Stack; Stack = Record x1, y1, x2, y2: Byte; Sombra, Borda : Boolean; Pont : Po; Prox : Sp; End; Var Sp1 : Sp; Registos : Registers; Function UpperCase( StrIn : String ): String; Var Aux : String; Loop: Integer; Begin Aux := ''; For Loop := 1 To Length( StrIn ) Do Aux := Aux + UpCase( StrIn[ Loop ] ); UpperCase := Aux; end; Procedure EscreveEm( X, Y: Byte; StrIn: String ); Begin GoToXY( X, Y ); Write( StrIn ); End; { Procedure EscreveEm } Procedure Inicia( X1, Y1, Tam : Integer; Tip : Char); Var V : Integer; Begin For V := 1 To Tam Do Begin GoToXY( X1 - 1 + V , Y1 ); Write( Tip ); End; GoToXY( X1 , Y1 ); End; Function ReadString( X, Y, Tamanho: Integer; Tipo: Char):String; Var C : Char; S : String[ 80 ]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; Loop : Integer; Begin N := 0; Inicia( X, Y, Tamanho, Tipo ); Repeat C := ReadKey; If (C in [' '..'z']) Then Begin If n >= Tamanho Then n := n - 1; GoToXY( X + n , Y ); Write( C ); N := N + 1; Ac[ N ] := C; End; If ( C = Char( 8 ) ) And ( n > 0 ) Then Begin GoToXY( X + N - 1, Y ); Write( Tipo ); GoToXY( X + N - 1, Y ); Ac[ N ] := ' '; N := N - 1; End; Until C= Char( 13 ); S := ''; For N1 := 1 To N Do S := S + Ac[N1]; ReadString := S; For Loop := 1 To Tamanho Do Begin GoToXY( X + Loop - 1, Y ); Write(' '); End; {GoToXY( X + Tamanho - Length( S ), Y ); Write( S );} end; Function ReadNum( x, y, Tamanho: Integer; Tipo: Char):String; Var C : Char; S : String[60]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; Virg, VirgPos : integer; Procedure Recua; begin GoToXY( X + n - 1, Y ); Write( Tipo ); GoToXY( X + n - 1, Y ); Ac[n] := ' '; n := n - 1; end; Procedure Escreve; begin If n >= Tamanho Then n := n - 1; GoToXY( X + n , Y ); Write( C ); n := n + 1; Ac[n] := C; end; begin n := 0; Inicia( X, Y, Tamanho, Tipo); Virg := 0; repeat C := ReadKey; If ( C in ['0'..'9']) Then Escreve; if c = '.' then begin Virg := Virg + 1; If Virg <= 1 Then Begin Escreve; If Virg = 1 Then VirgPos := n; end; end; If ( C = Char(8) ) And ( n > 0 ) Then begin Recua; If n <= VirgPos Then Virg := 0; end; If C = '.' Then Virg := virg + 1; until c= char(13); S := ''; For N1 := 1 To n Do S := S + Ac[N1]; ReadNum := S; n := 0; end; Function ReadInt( x, y, Tamanho: Integer; Tipo: Char):String; Var C : Char; S : String[60]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; Virg, VirgPos : integer; Procedure Recua; begin GoToXY( X + n - 1, Y ); Write( Tipo ); GoToXY( X + n - 1, Y ); Ac[n] := ' '; n := n - 1; end; Procedure Escreve; begin If n >= Tamanho Then n := n - 1; GoToXY( X + n , Y ); Write( C ); n := n + 1; Ac[n] := C; end; begin n := 0; Inicia( X, Y, Tamanho, Tipo); Virg := 0; repeat C := ReadKey; If ( C in ['0'..'9']) Then Escreve; If ( C = Char(8) ) And ( n > 0 ) Then Recua; until c= char(13); S := ''; For N1 := 1 To n Do S := S + Ac[N1]; ReadInt := S; n := 0; end; Function PosX( n, Xi: Integer ): Integer; Var Acum, T, Aux : Integer; Begin If n = 1 Then Aux := Xi Else Begin T := TextWidth( '-' ); Acum := 0; Aux := Xi; Repeat Acum := Acum + 1; Aux := Aux + T; Until Acum = n-1; End; PosX := Aux; End; { Function PosX( n, Xi: Integer ) } Function ReadStringG( X, Y, Tamanho: Integer):String; Var C, uC : Char; S : String[ 80 ]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; Loop : Integer; Cor, CorF: Word; Begin Cor := GetColor; CorF := GetBkColor; For Loop := 1 To Tamanho Do OutTextXY( PosX( Loop, X), Y, '_' ); N := 0; Repeat SetColor( Cor ); C := ReadKey; If (C in [' '..'z']) Then Begin If n >= Tamanho Then Begin n := n - 1; SetColor( CorF ); OutTextXY( PosX( n+1, X), Y, uC ); End; SetColor( CorF ); OutTextXY( PosX( n+1, X), Y, '_' ); SetColor( Cor ); OutTextXY( PosX( n+1, X), Y, C ); N := N + 1; Ac[ N ] := C; End; If ( C = Char( 8 ) ) And ( n > 0 ) Then Begin SetColor( CorF ); OutTextXY( PosX( n, X), Y, Ac[n] ); SetColor( Cor ); Ac[ N ] := ' '; N := N - 1; OutTextXY( PosX( n+1, X), Y, '_' ); End; uC := C; Until C= Char( 13 ); S := ''; SetColor( CorF ); For N1 := 1 To Tamanho Do OutTextXY( PosX( N1, X ), Y, '_' ); For N1 := 1 To N Do Begin OutTextXY( PosX( N1, X ), Y, Ac[N1] ); S := S + Ac[N1]; End; SetColor( Cor ); OutTextXY( X, Y, S ); ReadStringG := S; End; { Function ReadStringG( X, Y, Tamanho: Integer) } Function ReadNumG( x, y, Tamanho: Integer):String; Var C, uC : Char; S : String[60]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; Virg, VirgPos : integer; Cor, CorF: Word; Procedure Recua; Begin SetColor( CorF ); OutTextXY( PosX( n, X ), Y, Ac[n] ); SetColor( Cor ); OutTextXY( PosX( n, X ), Y, '_' ); Ac[n] := ' '; n := n - 1; End; { Procedure Recua } Procedure Escreve; Begin If n >= Tamanho Then Begin n := n - 1; SetColor( CorF ); OutTextXY( PosX( n+1, X), Y, uC ); End; n := n + 1; SetColor( CorF ); OutTextXY( PosX( n, X), Y, '_' ); SetColor( Cor ); OutTextXY( PosX( n, X ), Y, C ); Ac[n] := C; End; { Procedure Escreve } Begin Cor := GetColor; CorF := GetBkColor; SetColor( Cor ); For n := 1 To Tamanho Do OutTextXY( PosX( n, X), Y, '_' ); n := 0; Virg := 0; Repeat C := ReadKey; If ( C in ['0'..'9']) Then Escreve; If c = '.' Then Begin Virg := Virg + 1; If Virg <= 1 Then Begin Escreve; If Virg = 1 Then VirgPos := n; End; End; If ( C = Char(8) ) And ( n > 0 ) Then Begin Recua; If n <= VirgPos Then Virg := 0; End; If C = '.' Then Virg := virg + 1; uC := C; Until c = Char(13); S := ''; SetColor( CorF ); For N1 := 1 To Tamanho Do OutTextXY( PosX( N1, X ), Y, '_' ); For N1 := 1 To N Do Begin OutTextXY( PosX( N1, X ), Y, Ac[N1] ); S := S + Ac[N1]; End; SetColor( Cor ); OutTextXY( X, Y, S ); ReadNumG := S; n := 0; End; { Function ReadNumG } Function ReadIntG( x1,y1,x2,y2,nH,nV,Tamanho,Cor,CorF: Word):String; Var C, uC : Char; S : String[60]; N1, n : Integer; Ac : Array[ 1..80 ] of Char; X,Y: Word; Procedure Recua; Begin SetColor( CorF ); OutTextXY( PosX( n, X ), Y, Ac[n] ); SetColor( Cor ); OutTextXY( PosX( n, X ), Y, '_' ); Ac[n] := ' '; n := n - 1; End; { Procedure Recua } Procedure Escreve; Begin If n >= Tamanho Then Begin n := n - 1; SetColor( CorF ); OutTextXY( PosX( n+1, X), Y, uC ); End; n := n + 1; SetColor( CorF ); OutTextXY( PosX( n, X), Y, '_' ); SetColor( Cor ); OutTextXY( PosX( n, X ), Y, C ); Ac[n] := C; End; { Procedure Escreve } Begin SetFillStyle(SolidFill, CorF); Bar(x1,y1,x2,y2); X:= x1+nH; Y:=y1+nV; {For n := 1 To Tamanho Do OutTextXY( PosX( n, X), Y, '_' );} n := 0; Repeat C := ReadKey; If ( C in ['0'..'9']) Then Escreve; If ( C = Char(8) ) And ( n > 0 ) Then Recua; uC := C; Until c= char(13); S := ''; SetColor( CorF ); For N1 := 1 To Tamanho Do OutTextXY( PosX( N1, X ), Y, '_' ); For N1 := 1 To N Do Begin OutTextXY( PosX( N1, X ), Y, Ac[N1] ); S := S + Ac[N1]; End; SetColor( Cor ); {OutTextXY( X, Y, S );} ReadIntG := S; n := 0; End; { Function ReadIntG } Function ReadIntX( X, Y, Tam: Byte; Car: Char ): String; Var SAux : String; Begin SAux := ReadInt( X, Y, Tam, Car ); While Length( SAux ) < Tam Do SAux := '0' + SAux; GoToXY( X, Y ); WriteLn( SAux ); ReadIntX := SAux; End; { Function ReadIntX } Function Real_Em_Str( rIn: Real ): String; Var TamReal, Ponto: Byte; ParteI, ParteD: LongInt; SAux: String; Begin ParteI := Trunc( Int( rIn )); ParteD := Round( Frac( rIn ) * 100 ); sAux := ''; sAux := Long_Em_Str( ParteI, TamReal ); sAux := sAux + '.' + Long_Em_Str( ParteD, TamReal ); TamReal := Length( sAux ); If TamReal < 5 Then Repeat sAux := ' ' + sAux; Until Length( sAux ) = 5; Real_Em_Str := sAux; End; { Function Real_Em_Str } Function Int_Em_Tam( n: Byte; Valor: Word ): String; Var SAux: String; Begin Str( Valor, SAux ); While Length( SAux ) < n Do SAux := '0' + SAux; Int_Em_Tam := SAux; End;{ Function Int_Em_Tam } Function Str_Em_Tam( n: Byte; StrIn: String ): String; Begin While Length( StrIn ) < n Do StrIn := ' ' + StrIn; Str_Em_Tam := StrIn; End;{ Function Str_Em_Tam } Function Num_Em_Str( Valor: Integer ): String; Var SAux: String; Begin Str( Valor, SAux ); Num_Em_Str := SAux; End;{ Function Num_Em_Str } Function Long_Em_Str( Valor: LongInt; Var L: Byte ): String; Var SAux: String; Begin Str( Valor, SAux ); Long_Em_Str := SAux; L := Length ( sAux ); End;{ Function Long_Em_Str } Function Str_Em_Num( StrIn: String ): Word; Var Aux : Integer; Code : Integer; Begin Val( StrIn, Aux, Code ); If Code = 0 Then Str_Em_Num := Aux Else Str_Em_Num := 0 End; { Function Str_Em_Num } Function Str_Em_Long( StrIn: String ): LongInt; Var Aux : LongInt; Code : Integer; Begin Val( StrIn, Aux, Code ); If Code = 0 Then Str_Em_Long := Aux Else Str_Em_Long := 0 End; { Function Str_Em_Num } Function Existe_Ficheiro( NomeF: String ) : Boolean; Var f: File; Begin {$I-} Assign( f, NomeF ); Reset( f ); Close ( f ); {$I+} Existe_Ficheiro := ( IoResult = 0 ) And ( NomeF <> '' ); End; { Function Existe_Ficheiro } Procedure RepeteEm( X, Y: Byte; StrIn: Char; Vezes: Byte ); Var Loop: Byte; Begin For Loop := 1 To Vezes Do Begin GoToXY( X + Loop - 1, Y ); Write( StrIn ); End; End; { Procedure RepeteEm } Function Divide_em_Milhares( Valor: String; Virgula: Char ): String; Var L : Byte; S1: String; Begin S1 := ''; L := Length( Valor ); If L <= 3 Then Divide_em_Milhares := Valor Else Begin Repeat S1 := Virgula + Copy( Valor, L - 2, 3 ) + S1; Delete( Valor, L - 2, 3 ); L := Length( Valor ); Until L <= 3; Divide_Em_Milhares := Valor + S1; End; End; { Function Divide_em_Milhares } Function Le_Teclado: String; Var Ch : Char; sAux : String; Begin Ch:=ReadKey; case Ch of #0: { Function keys } begin Ch:=ReadKey; case Ch of #59: sAux := 'F1'; #60: sAux := 'F2'; #61: sAux := 'F3'; #62: sAux := 'F4'; #63: sAux := 'F5'; #64: sAux := 'F6'; #65: sAux := 'F7'; #66: sAux := 'F8'; #67: sAux := 'F9'; #68: sAux := 'F10'; #71: sAux := 'HOME'; #79: sAux := 'END'; #72: sAux := 'UP'; { Up } #75: sAux := 'LFT'; { Left } #77: sAux := 'RGT'; { Right } #80: sAux := 'DWN'; { Down } #73: sAux := 'PGUP'; { PgUp } #81: sAux := 'PGDN'; { PgDn } #82: sAux := 'INS'; { Ins } #83: sAux := 'DEL'; { Del } end; end; #8: sAux := 'BS'; { Back Space } #9: sAux := 'TAB'; { Tab } #13: sAux := 'CR'; { Enter } #27: sAux := 'ESC'; { Esc } else sAux := Ch; end; Le_Teclado := sAux; end; { Function Le_Teclado } Procedure Data(Var Ds: String; Var Dia,Mes,Ano:Word); Var nds: Word; Begin GetDate(Ano,Mes,Dia,nds); Case nds Of 0 : Ds:= 'Dom'; 1 : Ds:= 'Seg'; 2 : Ds:= 'Ter'; 3 : Ds:= 'Qua'; 4 : Ds:= 'Qui'; 5 : Ds:= 'Sex'; 6 : Ds:= 'Sab'; End; End; {Procedure Data} Begin Sp1 := Nil; End.
unit ibacortrainschedule_integration; {$mode objfpc}{$H+} interface uses http_lib, fpjson, common, Classes, SysUtils; type { TIbacorTrainScheduleController } TIbacorTrainScheduleController = class private FDateAsString: string; FDestinationStation: string; FStationData: TStringList; FStationName: string; FToken: string; jsonData: TJSONData; function getStationData: boolean; public constructor Create; destructor Destroy; override; function DateKey(AIndex: integer): string; function CityKey(ACityName: string): string; function StationKey(ACityName, AStationName: string): string; function IsValidCity(ACityName: string): boolean; function StationListAsString(ACityName: string): string; function Schedule(ADateKey, AFromKey, ADestinationKey: string): string; function ScheduleStationToStation(ADateKey, AFromKey, ADestinationKey: string): string; published property Token: string read FToken write FToken; property StationData: TStringList read FStationData; property DateAsString: string read FDateAsString; property DestinationStation: string read FDestinationStation; property StationName: string read FStationName; end; implementation const _IBACOR_TRAINSCHEDULE_DATA = 'http://ibacor.com/api/kereta-api?k='; _IBACOR_TRAINSCHEDULE = 'http://ibacor.com/api/kereta-api?k=%s&tanggal=%s&asal=%s&tujuan=%s'; var Response: IHTTPResponse; { TIbacorTrainScheduleController } function TIbacorTrainScheduleController.getStationData: boolean; begin Result := False; if FToken = '' then Exit; with THTTPLib.Create(_IBACOR_TRAINSCHEDULE_DATA + FToken) do begin Response := Get; try if Response.ResultCode = 200 then begin jsonData := GetJSON(Response.ResultText); if jsonGetData(jsonData, 'status') = 'success' then begin FStationData.Text := Response.ResultText; Result := True; end; end; except end; Free; end; end; constructor TIbacorTrainScheduleController.Create; begin FStationData := TStringList.Create; FStationData.Text := ''; end; destructor TIbacorTrainScheduleController.Destroy; begin if Assigned(jsonData) then jsonData.Free; FStationData.Free; end; function TIbacorTrainScheduleController.DateKey(AIndex: integer): string; begin Result := ''; if not Assigned(jsonData) then if not getStationData then exit; FDateAsString := jsonGetData(jsonData, 'data/tanggal[' + i2s(AIndex) + ']/name'); Result := jsonGetData(jsonData, 'data/tanggal[' + i2s(AIndex) + ']/value'); end; function TIbacorTrainScheduleController.CityKey(ACityName: string): string; var i: integer; s: string; begin Result := ''; if not Assigned(jsonData) then if not getStationData then exit; for i := 0 to jsonData.GetPath('data.stasiun').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/kota'); if s = UpperCase(ACityName) then begin FStationName := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/list[0]/name'); Result := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/list[0]/value'); end; end; end; function TIbacorTrainScheduleController.StationKey(ACityName, AStationName: string): string; var i, j: integer; s: string; begin Result := ''; if not Assigned(jsonData) then if not getStationData then exit; ACityName := StringReplace(UpperCase(ACityName), ' ', '', [rfReplaceAll]); AStationName := StringReplace(UpperCase(AStationName), ' ', '', [rfReplaceAll]); try for i := 0 to jsonData.GetPath('data.stasiun').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/kota'); s := StringReplace(s, ' ', '', [rfReplaceAll]); if s = ACityName then begin for j := 0 to jsonData.GetPath('data.stasiun[' + i2s(i) + '].list').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/list[' + i2s(j) + ']/name'); s := StringReplace(s, ' ', '', [rfReplaceAll]); if Pos(AStationName, s) > 0 then begin Result := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/list[' + i2s(j) + ']/value'); end; end; exit; end; end; except end; end; function TIbacorTrainScheduleController.IsValidCity(ACityName: string): boolean; var i: integer; s: string; begin Result := False; if not Assigned(jsonData) then if not getStationData then exit; try for i := 0 to jsonData.GetPath('data.stasiun').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/kota'); if s = UpperCase(ACityName) then begin Result := True; end; end; except end; end; function TIbacorTrainScheduleController.StationListAsString(ACityName: string): string; var i, j: integer; s: string; begin Result := ''; if not Assigned(jsonData) then if not getStationData then exit; ACityName := StringReplace(UpperCase(ACityName), ' ', '', [rfReplaceAll]); Result := ''; try for i := 0 to jsonData.GetPath('data.stasiun').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/kota'); s := StringReplace(s, ' ', '', [rfReplaceAll]); if s = ACityName then begin for j := 0 to jsonData.GetPath('data.stasiun[' + i2s(i) + '].list').Count - 1 do begin s := jsonGetData(jsonData, 'data/stasiun[' + i2s(i) + ']/list[' + i2s(j) + ']/name'); s := StringReplace(s, ' ', '', [rfReplaceAll]); Result := Result + s + #10; end; Result := Trim(Result); exit; end; end; except end; end; function TIbacorTrainScheduleController.Schedule(ADateKey, AFromKey, ADestinationKey: string): string; begin Result := ''; end; function TIbacorTrainScheduleController.ScheduleStationToStation( ADateKey, AFromKey, ADestinationKey: string): string; var urlTarget: string; begin Result := ''; urlTarget := Format(_IBACOR_TRAINSCHEDULE, [FToken, ADateKey, AFromKey, ADestinationKey]); with THTTPLib.Create(urlTarget) do begin Response := Get; try if Response.ResultCode = 200 then begin Result := Response.ResultText; end; except end; Free; end; end; end.
unit UGrowableStackList; interface type { A list that should live on the stack. It can hold a configurable amount of data on the stack. The number of bytes of data it can contain is equal to the size of the TSize type parameter. The TSize type parameter has no other purpose. Once the stack capacity has been reached, the list switches to the heap for any additional items. } TStackList<T: record; TSize: record> = record private type P = ^T; private FStackData: TSize; FStackCapacity: Integer; FHeapData: Pointer; FHeapCapacity: Integer; FCount: Integer; function GetItem(const AIndex: Integer): T; function GetHeapCount: Integer; private procedure Grow; public { Initializes the list. You *must* call this method before using this list. It acts like a constructor. You also *must* call Finalize when you are done with the list. } procedure Initialize; { Finalizes the list. You *must* call this method when you are done with the list. It acts like a destructor and frees any heap memory that may have been allocated. } procedure Finalize; { Clears the list } procedure Clear; { Adds an item to the list. Raises EInvalidOperation if the list is full and the item cannot be added. } procedure Add(const AItem: T); { The number of items in the list. } property Count: Integer read FCount; { The number of items that are stored in heap memory. FOR TESTING ONLY. } property HeapCount: Integer read GetHeapCount; { The items in the list. Raises EArgumentOutOfRangeException if AIndex is invalid. } property Items[const AIndex: Integer]: T read GetItem; default; end; type { Some predefined types that can be used as the TSize type parameter for the TStackList<T, TSize> type. } T128Bytes = record Data: array [0..127] of Byte end; T256Bytes = record Data: array [0..255] of Byte end; T512Bytes = record Data: array [0..511] of Byte end; T1024Bytes = record Data: array [0..1023] of Byte end; implementation uses System.Math, System.Classes, System.SysUtils; { TStackList<T, TSize> } procedure TStackList<T, TSize>.Add(const AItem: T); var Target: P; Index: Integer; begin if (FCount < FStackCapacity) then begin { We can still add this item to the memory stack. } Target := @FStackData; Inc(Target, FCount); end else begin { We need to add this item to heap memory. First calculate the index into heap memory. } Index := FCount - FStackCapacity; { Grow heap memory if needed to accommodate Index } if (Index >= FHeapCapacity) then Grow; Target := FHeapData; Inc(Target, Index); end; Target^ := AItem; Inc(FCount); end; procedure TStackList<T, TSize>.Clear; begin FCount := 0; end; procedure TStackList<T, TSize>.Finalize; begin FreeMem(FHeapData); FHeapData := nil; FHeapCapacity := 0; FCount := 0; end; function TStackList<T, TSize>.GetHeapCount: Integer; begin Result := Max(0, FCount - FStackCapacity); end; function TStackList<T, TSize>.GetItem(const AIndex: Integer): T; var Item: P; begin if (AIndex < 0) or (AIndex >= FCount) then raise EArgumentOutOfRangeException.Create('List index out of range'); if (AIndex < FStackCapacity) then begin Item := @FStackData; Inc(Item, AIndex); end else begin Item := FHeapData; Inc(Item, AIndex - FStackCapacity); end; Result := Item^; end; {$IF (RTLVersion < 33)} procedure TStackList<T, TSize>.Grow; begin { Pre-Rio growth strategy: double collection size } if (FHeapCapacity = 0) then FHeapCapacity := 4 else FHeapCapacity := FHeapCapacity * 2; ReallocMem(FHeapData, FHeapCapacity * SizeOf(T)); end; {$ELSE} procedure TStackList<T, TSize>.Grow; begin { Delphi Rio introduced a user-configurable growth strategy } FHeapCapacity := GrowCollection(FHeapCapacity, FHeapCapacity + 1); ReallocMem(FHeapData, FHeapCapacity * SizeOf(T)); end; {$ENDIF} procedure TStackList<T, TSize>.Initialize; begin if IsManagedType(T) or IsManagedType(TSize) then raise EInvalidOperation.Create('A stack based collection cannot contain managed types'); FStackCapacity := SizeOf(FStackData) div SizeOf(T); FHeapData := nil; FHeapCapacity := 0; FCount := 0; end; end.
unit u_cCategoria; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, u_dtm_conexao, ZAbstractConnection, ZConnection,ZAbstractRODataset, ZAbstractDataset, ZDataset, system.SysUtils; type TCategoria = class private conexaoDb: TZConnection; f_id: integer; f_descricao: String; function getCodigo: integer; function getDescricao: string; procedure setCodigo(const Value: integer); procedure setDescricao(const Value: string); public constructor Create(aConexao:TZConnection); destructor Destroy; override; function inserir:Boolean; function atualizar:Boolean; function apagar(id: integer;descricao: string):Boolean; function selecionar(id: integer):Boolean; published property codigo: integer read getCodigo write setCodigo; property descricao: string read getDescricao write setDescricao; end; implementation { TCategoria } {$REGION 'CRUD'} function TCategoria.apagar(id: integer;descricao: string): Boolean; var qry:TZQuery; begin if MessageDlg('Apagar registro: '+IntToStr(id)+#13+'Descrição: '+descricao,mtConfirmation,[mbYes,mbNo],0) = mrNo then begin result := false; abort; end; try result:= true; qry := TZQuery.Create(nil); qry.Connection := conexaoDb; qry.SQL.Clear; qry.SQL.Add('delete from categoriaid where id=:id'); qry.ParamByName('id').Value := id; try qry.ExecSQL; except result := false; end; finally if(Assigned(qry)) then FreeAndNil(qry); end; end; function TCategoria.atualizar: Boolean; var qry:TZQuery; begin try result:= true; qry := TZQuery.Create(nil); qry.Connection := conexaoDb; qry.SQL.Clear; qry.SQL.Add('update categoriaid set descricao=:descricao where id=:id'); qry.ParamByName('id').Value := self.f_id; qry.ParamByName('descricao').Value := self.f_descricao; try qry.ExecSQL; except result := false; end; finally if(Assigned(qry)) then FreeAndNil(qry); end; end; function TCategoria.inserir: Boolean; var qry:TZQuery; begin try result:= true; qry := TZQuery.Create(nil); qry.Connection := conexaoDb; qry.SQL.Clear; qry.SQL.Add('insert into categoriaid(descricao) values(:descricao);'); qry.ParamByName('descricao').Value := self.f_descricao; try qry.ExecSQL; except result:= false; end; finally if(Assigned(qry)) then FreeAndNil(qry); end; end; function TCategoria.selecionar(id: integer): Boolean; var qry:TZQuery; begin try result:= true; qry := TZQuery.Create(nil); qry.Connection := conexaoDb; qry.SQL.Clear; qry.SQL.Add('select descricao from categoriaid where id = :id;'); qry.ParamByName('id').Value := id; try qry.Open; self.f_id := id; self.f_descricao := qry.FieldByName('descricao').AsString; except result := false; end; finally if(Assigned(qry)) then FreeAndNil(qry); end; end; {$ENDREGION} {$REGION 'CONSTRUCT AND DESTRUCT'} constructor TCategoria.Create(aConexao:TZConnection); begin ConexaoDb := aConexao; end; destructor TCategoria.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'GET AND SET'} // GET function TCategoria.getCodigo: integer; begin result := self.f_id; end; function TCategoria.getDescricao: string; begin result := self.f_descricao; end; // SET procedure TCategoria.setCodigo(const Value: integer); begin self.f_id := value; end; procedure TCategoria.setDescricao(const Value: string); begin self.f_descricao := value; end; {$ENDREGION} end.
unit fImportaClientes; interface uses Generics.Collections, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, AdvObj, BaseGrid, AdvGrid, AdvCGrid, ExtCtrls, Entidades.Cadastro; type TfmImportaClientes = class(TForm) Memo1: TMemo; grid1: TAdvColumnGrid; Button1: TButton; Splitter1: TSplitter; Memo2: TMemo; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private FClientes: TList<TCliente>; FAnimais: TList<TAnimal>; procedure ProcessaIdade; procedure ProcessaSexo; procedure ProcessaData; procedure ProcessaFones; procedure CriaObjetos; function AchaAnimal(A: TAnimal): boolean; procedure MostraObjetos; procedure SalvaObjetos; public end; var fmImportaClientes: TfmImportaClientes; implementation uses dConnection, Aurelius.Drivers.Interfaces, Aurelius.Engine.ObjectManager; {$R *.dfm} procedure TfmImportaClientes.Button1Click(Sender: TObject); var I: Integer; S: string; C: integer; R: integer; begin grid1.RowCount := Memo1.Lines.Count + 1; R := 1; for I := 0 to Memo1.Lines.Count - 1 do begin C := 0; S := Memo1.Lines[I]; while Pos(#9, S) > 0 do begin grid1.Cells[C, R] := Trim(Copy(S, 1, Pos(#9, S) - 1)); Delete(S, 1, Pos(#9, S)); Inc(C); end; grid1.Cells[C, R] := Trim(S); S := grid1.Cells[0, R]; if (S <> '2011') and (S <> '2012') and (S <> '') then Inc(R); end; grid1.RowCount := R; ProcessaIdade; ProcessaSexo; ProcessaData; ProcessaFones; CriaObjetos; MostraObjetos; SalvaObjetos; end; procedure TfmImportaClientes.CriaObjetos; var I: Integer; C: TCliente; A: TAnimal; Cad: TDateTime; begin for I := 1 to grid1.RowCount - 1 do begin A := TAnimal.Create; A.Nome := grid1.Cells[0, I]; Cad := StrToDate(grid1.Cells[7, I]); if grid1.Cells[1, I] <> '' then A.DataNascimento := Cad - StrToInt(grid1.Cells[1, I]) * 30; A.Raca := grid1.Cells[2, I]; if grid1.Cells[3, I] <> '' then A.Sexo := TSexo(grid1.Ints[3, I]); C := TCliente.Create; C.Nome := grid1.Cells[4, I]; C.Rua := grid1.Cells[5, I]; C.Fone := grid1.Cells[6, I]; C.Celular := grid1.Cells[8, I]; C.Fone2 := grid1.Cells[9, I]; C.DataCadastro := StrToDate(grid1.Cells[7, I]); A.Proprietario := C; if AchaAnimal(A) then begin C.Free; A.Free; end else begin FClientes.Add(C); FAnimais.Add(A); end; end; end; function TfmImportaClientes.AchaAnimal(A: TAnimal): boolean; var A2: TAnimal; I: Integer; begin Result := false; for I := 0 to FAnimais.Count - 1 do begin A2 := FAnimais[I]; if SameText(A.Nome, A2.Nome) and SameText(A.Raca, A2.Raca) and SameText(A.Proprietario.Nome, A2.Proprietario.Nome) then begin Result := true; // if (C2.Rua <> C.Rua) or (C2.Fone <> C.Fone) then //// or (C2.Celular <> C.Celular) or (C2.Fone2 <> C.Fone2) then // begin // Memo2.Lines.Add(Format('%s (%s), %s (%s), %s (%s)', // [ // C2.Nome, // C.Nome, // C2.Rua.ValueOrDefault, // C.Rua.ValueOrDefault, // C2.Fone.ValueOrDefault, // C.Fone.ValueOrDefault // ] // )); // end; end; end; end; procedure TfmImportaClientes.FormCreate(Sender: TObject); begin FClientes := TObjectList<TCliente>.Create; FAnimais := TObjectList<TAnimal>.Create; end; procedure TfmImportaClientes.FormDestroy(Sender: TObject); begin FClientes.Free; FAnimais.Free; end; procedure TfmImportaClientes.MostraObjetos; var I: Integer; A: TAnimal; S: string; begin grid1.ClearAll; grid1.RowCount := 2; grid1.RowCount := FAnimais.Count + 1; for I := 1 to FAnimais.Count do begin A := FAnimais[I - 1]; grid1.Cells[0, I] := A.Nome; grid1.Cells[1, I] := A.Raca; grid1.Cells[2, I] := A.Proprietario.Nome; grid1.Cells[3, I] := A.Proprietario.Fone; case A.Sexo of TSexo.Macho: S := 'macho'; TSexo.Femea: S := 'femea'; TSexo.MachoCastrado: S := 'mcastr'; TSexo.FemeaCastrada: S := 'femcas'; end; grid1.Cells[4, I] := S; grid1.Cells[5, I] := DateToStr(A.DataNascimento.ValueOrDefault); grid1.Cells[6, I] := A.Proprietario.Rua; grid1.Cells[7, I] := DatetoStr(A.Proprietario.DataCadastro); end; Memo2.Lines.Add('Total: ' + IntToStr(FAnimais.Count)); end; procedure TfmImportaClientes.ProcessaData; var I: integer; begin for I := 1 to grid1.RowCount - 1 do try StrToDate(grid1.Cells[7, I]); except Memo2.Lines.Add(intToStr(I) + ': ' + grid1.Cells[7, I]); grid1.Row := I - 1; end; end; procedure TfmImportaClientes.ProcessaFones; function ParseaFone(S: string): string; var p: integer; Fone: string; Extra: string; begin if S = '' then Exit(S); p := Length(S); while (S[p] <> '(') and (p > 0) do dec(p); if P > 1 then begin Fone := Copy(S, 1, p - 1); Extra := Trim(Copy(S, p, MaxInt)); end else Fone := S; Fone := Trim(Fone); case Length(Fone) of 8: begin StrToInt(Fone); Fone := '(41) ' + Copy(Fone, 1, 4) + '-' + Copy(Fone, 5, 4); end; 12: begin StrToInt(Copy(Fone, 2, 2)); StrToInt(Copy(Fone, 5, 8)); Fone := Copy(Fone, 1, 4) + ' ' + Copy(Fone, 5, 4) + '-' + Copy(Fone, 9, 4); end; 13: begin StrToInt(Copy(Fone, 2, 2)); StrToInt(Copy(Fone, 6, 8)); Fone := Copy(Fone, 1, 4) + ' ' + Copy(Fone, 6, 4) + '-' + Copy(Fone, 10, 4); end else raise Exception.Create('Fone errado: ' + Fone + ' -> ' + S); end; result := Fone; if Extra <> '' then result := result + ' ' + Extra; end; var S: string; I: Integer; p: integer; begin for I := 1 to grid1.RowCount - 1 do begin S := grid1.Cells[6, I]; p := Pos('/', S); if P <> 0 then begin grid1.Cells[6, I] := Trim(Copy(S, 1, P - 1)); S := Trim(Copy(S, P + 1, MaxInt)); grid1.Cells[8, I] := S; p := Pos('/', S); if P <> 0 then begin grid1.Cells[8, I] := Trim(Copy(S, 1, P - 1)); S := Trim(Copy(S, P + 1, MaxInt)); grid1.Cells[9, I] := S; if Pos('/', S) > 0 then raise Exception.Create('Telefone errado!'); end; end; grid1.Cells[6, I] := ParseaFone(grid1.Cells[6, I]); grid1.Cells[8, I] := ParseaFone(grid1.Cells[8, I]); grid1.Cells[9, I] := ParseaFone(grid1.Cells[9, I]); end; end; procedure TfmImportaClientes.ProcessaIdade; var I: Integer; S: string; Numero: integer; P: integer; Age: integer; begin for I := 1 to grid1.RowCount - 1 do begin S := grid1.Cells[1, I]; if S = '' then Continue; P := Pos(' ', S); if P <> 0 then Numero := StrToInt(Copy(S, 1, P - 1)); S := Lowercase(Copy(S, P + 1, MaxInt)); if (S = 'anos') or (s = 'ano') then Age := Numero * 12 else if (S = 'meses') then Age := Numero else if (S = 'mÍs e meio') then Age := Numero else if (S = 'anos e meio') or (S = 'ano e meio') or (s = 'ano e seis meses') then Age := Numero * 12 + 6 else if (S = 'ano e 10 meses') then Age := Numero * 12 + 10 else if (S = 'ano e 5 meses') then Age := Numero * 12 + 5 else Age := Round(Date - StrToDate(S)) div 30; grid1.Cells[1, I] := IntToStr(Age); end; end; procedure TfmImportaClientes.ProcessaSexo; var I: integer; S: string; Sexo: TSexo; begin for I := 1 to grid1.RowCount - 1 do begin S := Lowercase(Trim(grid1.Cells[3, I])); if S = 'm' then Sexo := TSexo.Macho else if S = 'f' then Sexo := TSexo.Femea else if S = 'm castrado' then Sexo := TSexo.MachoCastrado else if S = 'f castrada' then Sexo := TSexo.FemeaCastrada else if S <> '' then Memo2.Lines.Add(IntToStr(I) + ': ' + S); grid1.Cells[3, I] := IntToStr(Ord(Sexo)); end; end; procedure TfmImportaClientes.SalvaObjetos; var M: TObjectManager; I: Integer; T: IDBTransaction; begin M := dmConnection.CreateManager; try T := M.Connection.BeginTransaction; try I := 0; while FAnimais.Count > 0 do begin M.Save(FAnimais[0]); FClientes.Extract(TCliente(FAnimais[0].Proprietario)); FAnimais.Extract(FAnimais[0]); I := I + 1; end; T.Commit; except T.Rollback; Memo2.Lines.Add(IntToStr(I) + ' -> ' + FANimais[FAnimais.Count - 1].Nome); grid1.Row := I; raise; end; finally M.Free; end; end; end.
{ $HDR$} {**********************************************************************} { Unit archived using Team Coherence } { Team Coherence is Copyright 2002 by Quality Software Components } { } { For further information / comments, visit our WEB site at } { http://www.TeamCoherence.com } {**********************************************************************} {} { $Log: 108528: Main.pas { { Rev 1.0 14/08/2004 12:29:18 ANeillans { Initial Checkin } { Demo Name: SMTP Server Created By: Andy Neillans On: 27/10/2002 Notes: Demonstration of SMTPServer (by use of comments only!!) Read the RFC to understand how to store and manage server data, and therefore be able to use this component effectivly. Version History: 14th Aug 04: Andy Neillans Updated for Indy 10, rewritten IdSMTPServer 12th Sept 03: Andy Neillans Cleanup. Added some basic syntax checking for example. Tested: Indy 10: D5: Untested D6: Untested D7: Untested } unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPServer, IdSMTPServer, StdCtrls, IdMessage, IdEMailAddress, IdCmdTCPServer, IdExplicitTLSClientServerBase; type TForm1 = class(TForm) Memo1: TMemo; Label1: TLabel; Label2: TLabel; Label3: TLabel; ToLabel: TLabel; FromLabel: TLabel; SubjectLabel: TLabel; IdSMTPServer1: TIdSMTPServer; btnServerOn: TButton; btnServerOff: TButton; procedure btnServerOnClick(Sender: TObject); procedure btnServerOffClick(Sender: TObject); procedure IdSMTPServer1MsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream; var LAction: TIdDataReply); procedure IdSMTPServer1RcptTo(ASender: TIdSMTPServerContext; const AAddress: String; var VAction: TIdRCPToReply; var VForward: String); procedure IdSMTPServer1UserLogin(ASender: TIdSMTPServerContext; const AUsername, APassword: String; var VAuthenticated: Boolean); procedure IdSMTPServer1MailFrom(ASender: TIdSMTPServerContext; const AAddress: String; var VAction: TIdMailFromReply); procedure IdSMTPServer1Received(ASender: TIdSMTPServerContext; AReceived: String); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.btnServerOnClick(Sender: TObject); begin btnServerOn.Enabled := False; btnServerOff.Enabled := True; IdSMTPServer1.active := true; end; procedure TForm1.btnServerOffClick(Sender: TObject); begin btnServerOn.Enabled := True; btnServerOff.Enabled := False; IdSMTPServer1.active := false; end; procedure TForm1.IdSMTPServer1MsgReceive(ASender: TIdSMTPServerContext; AMsg: TStream; var LAction: TIdDataReply); var LMsg : TIdMessage; LStream : TFileStream; begin // When a message is received by the server, this event fires. // The message data is made available in the AMsg : TStream. // In this example, we will save it to a temporary file, and the load it using // IdMessage and parse some header elements. LStream := TFileStream.Create(ExtractFilePath(Application.exename) + 'test.eml', fmCreate); Try LStream.CopyFrom(AMsg, 0); Finally FreeAndNil(LStream); End; LMsg := TIdMessage.Create; Try LMsg.LoadFromFile(ExtractFilePath(Application.exename) + 'test.eml', False); ToLabel.Caption := LMsg.Recipients.EMailAddresses; FromLabel.Caption := LMsg.From.Text; SubjectLabel.Caption := LMsg.Subject; Memo1.Lines := LMsg.Body; Finally FreeAndNil(LMsg); End; end; procedure TForm1.IdSMTPServer1RcptTo(ASender: TIdSMTPServerContext; const AAddress: String; var VAction: TIdRCPToReply; var VForward: String); begin // Here we are testing the RCPT TO lines sent to the server. // These commands denote where the e-mail should be sent. // RCPT To address comes in via AAddress. VAction sets the return action to the server. // Here, you would normally do: // Check if the user has relay rights, if the e-mail address is not local // If the e-mail domain is local, does the address exist? // The following actions can be returned to the server: { rAddressOk, //address is okay rRelayDenied, //we do not relay for third-parties rInvalid, //invalid address rWillForward, //not local - we will forward rNoForward, //not local - will not forward - please use rTooManyAddresses, //too many addresses rDisabledPerm, //disabled permentantly - not accepting E-Mail rDisabledTemp //disabled temporarily - not accepting E-Mail } // For now, we will just always allow the rcpt address. VAction := rAddressOk; end; procedure TForm1.IdSMTPServer1UserLogin(ASender: TIdSMTPServerContext; const AUsername, APassword: String; var VAuthenticated: Boolean); begin // This event is fired if a user attempts to login to the server // Normally used to grant relay access to specific users etc. VAuthenticated := True; end; procedure TForm1.IdSMTPServer1MailFrom(ASender: TIdSMTPServerContext; const AAddress: String; var VAction: TIdMailFromReply); begin // Here we are testing the MAIL FROM line sent to the server. // MAIL FROM address comes in via AAddress. VAction sets the return action to the server. // The following actions can be returned to the server: { mAccept, mReject } // For now, we will just always allow the mail from address. VAction := mAccept; end; procedure TForm1.IdSMTPServer1Received(ASender: TIdSMTPServerContext; AReceived: String); begin // This is a new event in the rewrite of IdSMTPServer for Indy 10. // It lets you control the Received: header that is added to the e-mail. // If you do not want a Received here to be added, set AReceived := ''; // Formatting 'keys' are available in the received header -- please check // the IdSMTPServer source for more detail. end; end.
unit DatabaseDefinitionTest; interface uses Classes, SysUtils, TestFramework, DatabaseDefinition, MsXml2; type TDatabaseDefinitionTest = class (TTestCase) protected function CreateDefinitionDescription: IXMLDOMDocument; published procedure TestLoad; end; implementation { TDatabaseDefinitionTest } { Protected declarations } function TDatabaseDefinitionTest.CreateDefinitionDescription: IXMLDOMDocument; function CreateTableNode(Document: IXMLDOMDocument): IXMLDOMNode; var Attr: IXMLDOMAttribute; begin Result := Document.createElement('table'); Attr := Document.createAttribute('name'); Attr.value := 'TEST'; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('filename'); Attr.value := 'TEST.rtm'; Result.attributes.setNamedItem(Attr); end; function CreateFieldNode(Document: IXMLDOMDocument; Name, DataType, Size, Offset, IncludedInSQL, IsPrimaryKey: String): IXMLDOMNode; var Attr: IXMLDOMAttribute; begin Result := Document.createElement('field'); Attr := Document.createAttribute('name'); Attr.value := Name; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('type'); Attr.value := DataType; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('size'); Attr.value := Size; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('offset'); Attr.value := Offset; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('sql'); Attr.value := IncludedInSQL; Result.attributes.setNamedItem(Attr); Attr := Document.createAttribute('primarykey'); Attr.value := IsPrimaryKey; Result.attributes.setNamedItem(Attr); end; var Node: IXMLDOMNode; begin Result := CoDOMDocument.Create; Result.appendChild(Result.createElement('database')); Node := Result.createElement('tables'); Result.selectSingleNode('//database').appendChild(Node); Node := CreateTableNode(Result); Result.selectSingleNode('//database/tables').appendChild(Node); Node := Result.createElement('fields'); Result.selectSingleNode('//database/tables/table').appendChild(Node); Node.appendChild(CreateFieldNode(Result, 'Field1', 'Integer', '4', '1', 'False', 'False')); Node.appendChild(CreateFieldNode(Result, 'Field2', 'Double', '8', '10', 'True', 'True')); end; { Test cases } procedure TDatabaseDefinitionTest.TestLoad; begin with TDatabaseDefinition.Create do try Load(CreateDefinitionDescription.documentElement); CheckEquals(1, Tables.Count, 'Expected one table'); CheckEquals('TEST', Tables[0].Name); CheckEquals('TEST.rtm', Tables[0].FileName); CheckEquals(2, Tables[0].Fields.Count, 'Expected two fields'); CheckEquals('Field1', Tables[0].Fields[0].Name); CheckEquals(Integer(dtInteger), Integer(Tables[0].Fields[0].DataType)); CheckEquals(4, Tables[0].Fields[0].Size); CheckEquals(1, Tables[0].Fields[0].Offset); CheckEquals(False, Tables[0].Fields[0].IncludedInSQL); CheckEquals(False, Tables[0].Fields[0].IsPrimaryKey); CheckEquals('Field1', Tables[0].Fields[0].Name); CheckEquals(Integer(dtDouble), Integer(Tables[0].Fields[1].DataType)); CheckEquals(8, Tables[0].Fields[1].Size); CheckEquals(10, Tables[0].Fields[1].Offset); CheckEquals(True, Tables[0].Fields[1].IncludedInSQL); CheckEquals(True, Tables[0].Fields[1].IsPrimaryKey); finally Free; end; end; initialization RegisterTest(TDatabaseDefinitionTest.Suite); end.
unit MainFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, MyArrayUnit, MyListUnit, MyStackUnit; type TMainForm = class(TForm) Memo1: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Memo2: TMemo; Memo3: TMemo; Button5: TButton; Button6: TButton; Button7: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); private myArray: TMyArray; myList: TMyList; myStack: TMyStack; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure TMainForm.FormCreate(Sender: TObject); begin myArray:=TMyArray.Create; myList:=TMyList.Create; myStack:=TMyStack.Create; end; procedure TMainForm.Button1Click(Sender: TObject); var str: string; begin myArray.Clean; Memo1.Clear; myArray.ReadFile('data.txt'); myArray.ReadFile('data2.txt'); str:='========== Unsorted Array ==========='; repeat begin Memo1.Lines.Add(str); str:=myArray.GetNextStr; end; until str=''; end; procedure TMainForm.Button2Click(Sender: TObject); var str: string; begin myArray.Rewind; Memo1.Clear; myArray.SelectionSort; str:='========== Sorted Array ==========='; repeat begin Memo1.Lines.Add(str); str:=myArray.GetNextStr; end; until str=''; end; procedure TMainForm.Button5Click(Sender: TObject); var p: Person; str: string; begin p.IDStud:='2410213'; p.NameStud:='Муха Олександр Олександрович'; p.DerzZamovl:=FALSE; p.Reiting:=68.9; p.Grupa:=402; myArray.Insert(p); myArray.Rewind; Memo1.Clear; str:='========== Array with Insertion ==========='; repeat begin Memo1.Lines.Add(str); str:=myArray.GetNextStr; end; until str=''; end; procedure TMainForm.Button3Click(Sender: TObject); var str: string; begin myList.Fill(myArray); Memo2.Clear; myList.Rewind; str:='========== Unsorted List ==========='; repeat begin Memo2.Lines.Add(str); str:=myList.GetNextStr; end; until str=''; end; procedure TMainForm.Button4Click(Sender: TObject); var str: string; begin myList.Sort; Memo2.Clear; myList.Rewind; str:='========== Sorted List ==========='; repeat begin Memo2.Lines.Add(str); str:=myList.GetNextStr; end; until str=''; end; procedure TMainForm.Button6Click(Sender: TObject); var p: Person; str: string; begin p:=myArray.GetNext; if p.IDStud='' then begin myArray.Rewind; p:=myArray.GetNext; end; myStack.Push(p); Memo3.Clear; myStack.Rewind; str:='========== Top of Stack ==========='; repeat begin Memo3.Lines.Add(str); str:=myStack.GetNextStr; end; until str=''; end; procedure TMainForm.Button7Click(Sender: TObject); var str: string; begin myStack.Pop; myStack.Rewind; Memo3.Clear; str:='========== Top of Stack ==========='; repeat begin Memo3.Lines.Add(str); str:=myStack.GetNextStr; end; until str=''; end; end.
unit uCefScriptNavBase; interface uses System.Classes, System.SysUtils, System.SyncObjs, // uReLog3, uLoggerInterface, // uCefScriptBase, uCefWebActionBase, uCefWebAction; const NAV_TIMEOUT_DEF = 60; type TCefScriptNavBase = class abstract(TCefScriptBase) private protected FSetIsNav: Boolean; FDoStop: Boolean; FAction: TCefWebAction; procedure Nav(const AUrl: string); function DoStartEvent: Boolean; override; function DoNavEvent(const AWebAction: TCefWebAction): Boolean; virtual; abstract; public constructor Create(const AActionName: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); destructor Destroy; override; procedure AfterConstruction; override; function Wait:TWaitResult; override; procedure Abort; override; end; implementation uses // uStringUtils ; { TCefScriptNavBase } constructor TCefScriptNavBase.Create(const AActionName: string; const ASetAsNav: Boolean; const AParent: TCefScriptBase); begin inherited Create(AActionName, AParent); FSetIsNav := ASetAsNav end; destructor TCefScriptNavBase.Destroy; begin FAction.Free; inherited; end; procedure TCefScriptNavBase.AfterConstruction; begin inherited; FAction := TCefWebAction.Create('wa', FLogger, Chromium, NAV_TIMEOUT_DEF, FAbortEvent, DoNavEvent); end; procedure TCefScriptNavBase.Abort; begin inherited; FAction.Abort(); end; function TCefScriptNavBase.DoStartEvent: Boolean; begin if FSetIsNav then begin FAction.IsNavigate := True; FDoStop := True; end; if FDoStop then begin DoNavStop(); end; Result := FAction.Start() end; procedure TCefScriptNavBase.Nav(const AUrl: string); begin LogInfo('navigate ' + AUrl); //FAction.IsNavigate := True; Chromium.LoadURL(AUrl); end; function TCefScriptNavBase.Wait: TWaitResult; begin Result := FAction.Wait(); FFail := FAction.IsFail; if FAction.ErrorStr <> '' then LogError2(FAction.ErrorStr); end; end.
unit Startup; interface uses System.IniFiles, Logger; var main_ini: TINIFILE; internal_logger: TLogger; isInilessStartOn: boolean; LANG: string; implementation uses sysutils, Forms; var logger_host: string; logger_port: integer; initialization main_ini := TIniFile.Create(GetCurrentDir+'\config.ini'); LANG := 'ITA'; isInilessStartOn := false; if main_ini.readString('CONFIG', 'VALIDATE', '---') <> 'OK' then begin try Application.MessageBox('Ini file non valido. Verrą fatto un tentativo di scaricare il file ini corretto.', 'WARNING', 0); isInilessStartOn := true; internal_logger := TLogger.create(TCP_HOST_LOGGER, TCP_PORT_LOGGER); except Application.MessageBox('INTERNAL ERROR 1: Ini file non valido e logger offline. Chiamare l''assistenza.', 'ERROR', 0); Halt; end; end else begin logger_host := main_ini.readString('LOGGER', 'HOST', '---'); logger_port := StrToInt(main_ini.ReadString('LOGGER', 'PORT', '---')); internal_logger := TLogger.create(logger_host, logger_port); end; finalization freeAndNil(internal_logger); FreeAndNil(main_ini); end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2021, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.BVH.StaticAABBTree; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$ifdef Delphi2009AndUp} {$warn DUPLICATE_CTOR_DTOR off} {$endif} {$undef UseDouble} {$ifdef UseDouble} {$define NonSIMD} {$endif} {-$define NonSIMD} {$ifdef NonSIMD} {$undef SIMD} {$else} {$ifdef cpu386} {$if not (defined(Darwin) or defined(CompileForWithPIC))} {$define SIMD} {$ifend} {$endif} {$ifdef cpux64} {$define SIMD} {$endif} {$endif} {$define NonRecursive} {$ifndef fpc} {$scopedenums on} {$endif} {$warnings off} interface uses SysUtils,Classes,Math, PasVulkan.Types, PasVulkan.Math; type TpvBVHStaticAABBTree=class public type TTreeProxy=record AABB:TpvAABB; UserData:TpvPtrInt; Next:TpvSizeInt; end; PTreeProxy=^TTreeProxy; TTreeProxies=array of TTreeProxy; TTreeNode=record AABB:TpvAABB; Children:array[0..1] of TpvSizeInt; Proxies:TpvSizeInt; end; PTreeNode=^TTreeNode; TTreeNodes=array of TTreeNode; public Proxies:TTreeProxies; ProxiesCount:TpvSizeInt; Nodes:TTreeNodes; NodeCount:TpvSizeInt; Root:TpvSizeInt; constructor Create; destructor Destroy; override; procedure CreateProxy(const aAABB:TpvAABB;const aUserData:TpvPtrInt); procedure Build(const aThreshold:TpvSizeInt=8;const aMaxDepth:TpvSizeInt=64;const aKDTree:boolean=false); end; implementation { TpvBVHStaticAABBTree } constructor TpvBVHStaticAABBTree.Create; begin inherited Create; Proxies:=nil; ProxiesCount:=0; Nodes:=nil; NodeCount:=-1; Root:=-1; end; destructor TpvBVHStaticAABBTree.Destroy; begin SetLength(Proxies,0); SetLength(Nodes,0); inherited Destroy; end; procedure TpvBVHStaticAABBTree.CreateProxy(const aAABB:TpvAABB;const aUserData:TpvPtrInt); var Index:TpvSizeInt; begin Index:=ProxiesCount; inc(ProxiesCount); if ProxiesCount>=length(Proxies) then begin SetLength(Proxies,RoundUpToPowerOfTwo(ProxiesCount)); end; Proxies[Index].AABB:=aAABB; Proxies[Index].UserData:=aUserData; Proxies[Index].Next:=Index-1; end; procedure TpvBVHStaticAABBTree.Build(const aThreshold:TpvSizeInt=8;const aMaxDepth:TpvSizeInt=64;const aKDTree:boolean=false); var Counter,StackPointer,Node,Depth,LeftCount,RightCount,ParentCount,Axis,BestAxis,Proxy,Balance,BestBalance, NextProxy,LeftNode,RightNode,TargetNode:TpvSizeInt; Stack:array of TpvSizeInt; Center:TpvVector3; LeftAABB,RightAABB:TpvAABB; begin SetLength(Proxies,ProxiesCount); if ProxiesCount>0 then begin Stack:=nil; try Root:=0; NodeCount:=1; SetLength(Nodes,Max(NodeCount,ProxiesCount)); Nodes[0].AABB:=Proxies[0].AABB; for Counter:=1 to ProxiesCount-1 do begin Nodes[0].AABB:=Nodes[0].AABB.Combine(Proxies[Counter].AABB); end; for Counter:=0 to ProxiesCount-2 do begin Proxies[Counter].Next:=Counter+1; end; Proxies[ProxiesCount-1].Next:=-1; Nodes[0].Proxies:=0; Nodes[0].Children[0]:=-1; Nodes[0].Children[1]:=-1; SetLength(Stack,16); Stack[0]:=0; Stack[1]:=aMaxDepth; StackPointer:=2; while StackPointer>0 do begin dec(StackPointer,2); Node:=Stack[StackPointer]; Depth:=Stack[StackPointer+1]; if (Node>=0) and (Nodes[Node].Proxies>=0) then begin Proxy:=Nodes[Node].Proxies; Nodes[Node].AABB:=Proxies[Proxy].AABB; Proxy:=Proxies[Proxy].Next; ParentCount:=1; while Proxy>=0 do begin Nodes[Node].AABB:=Nodes[Node].AABB.Combine(Proxies[Proxy].AABB); inc(ParentCount); Proxy:=Proxies[Proxy].Next; end; if (Depth<>0) and ((ParentCount>2) and (ParentCount>=aThreshold)) then begin Center:=(Nodes[Node].AABB.Min+Nodes[Node].AABB.Max)*0.5; BestAxis:=-1; BestBalance:=$7fffffff; for Axis:=0 to 3 do begin LeftCount:=0; RightCount:=0; ParentCount:=0; LeftAABB:=Nodes[Node].AABB; RightAABB:=Nodes[Node].AABB; LeftAABB.Max.xyz[Axis]:=Center.xyz[Axis]; RightAABB.Min.xyz[Axis]:=Center.xyz[Axis]; Proxy:=Nodes[Node].Proxies; if aKDTree then begin while Proxy>=0 do begin if LeftAABB.Contains(Proxies[Proxy].AABB) then begin inc(LeftCount); end else if RightAABB.Contains(Proxies[Proxy].AABB) then begin inc(RightCount); end else begin inc(ParentCount); end; Proxy:=Proxies[Proxy].Next; end; if (LeftCount>0) and (RightCount>0) then begin Balance:=abs(RightCount-LeftCount); if (BestBalance>Balance) and ((LeftCount+RightCount)>=ParentCount) and ((LeftCount+RightCount+ParentCount)>=aThreshold) then begin BestBalance:=Balance; BestAxis:=Axis; end; end; end else begin while Proxy>=0 do begin if ((Proxies[Proxy].AABB.Min+Proxies[Proxy].AABB.Max)*0.5).xyz[Axis]<RightAABB.Min.xyz[Axis] then begin inc(LeftCount); end else begin inc(RightCount); end; Proxy:=Proxies[Proxy].Next; end; if (LeftCount>0) and (RightCount>0) then begin Balance:=abs(RightCount-LeftCount); if BestBalance>Balance then begin BestBalance:=Balance; BestAxis:=Axis; end; end; end; end; if BestAxis>=0 then begin LeftNode:=NodeCount; RightNode:=NodeCount+1; inc(NodeCount,2); if NodeCount>=length(Nodes) then begin SetLength(Nodes,RoundUpToPowerOfTwo(NodeCount)); end; LeftAABB:=Nodes[Node].AABB; RightAABB:=Nodes[Node].AABB; LeftAABB.Max.xyz[BestAxis]:=Center.xyz[BestAxis]; RightAABB.Min.xyz[BestAxis]:=Center.xyz[BestAxis]; Proxy:=Nodes[Node].Proxies; Nodes[LeftNode].Proxies:=-1; Nodes[RightNode].Proxies:=-1; Nodes[Node].Proxies:=-1; if aKDTree then begin while Proxy>=0 do begin NextProxy:=Proxies[Proxy].Next; if LeftAABB.Contains(Proxies[Proxy].AABB) then begin TargetNode:=LeftNode; end else if RightAABB.Contains(Proxies[Proxy].AABB) then begin TargetNode:=RightNode; end else begin TargetNode:=Node; end; Proxies[Proxy].Next:=Nodes[TargetNode].Proxies; Nodes[TargetNode].Proxies:=Proxy; Proxy:=NextProxy; end; end else begin while Proxy>=0 do begin NextProxy:=Proxies[Proxy].Next; if ((Proxies[Proxy].AABB.Min+Proxies[Proxy].AABB.Max)*0.5).xyz[BestAxis]<RightAABB.Min.xyz[BestAxis] then begin TargetNode:=LeftNode; end else begin TargetNode:=RightNode; end; Proxies[Proxy].Next:=Nodes[TargetNode].Proxies; Nodes[TargetNode].Proxies:=Proxy; Proxy:=NextProxy; end; end; Nodes[Node].Children[0]:=LeftNode; Nodes[Node].Children[1]:=RightNode; Nodes[LeftNode].AABB:=LeftAABB; Nodes[LeftNode].Children[0]:=-1; Nodes[LeftNode].Children[1]:=-1; Nodes[RightNode].AABB:=RightAABB; Nodes[RightNode].Children[0]:=-1; Nodes[RightNode].Children[1]:=-1; if (StackPointer+4)>=length(Stack) then begin SetLength(Stack,RoundUpToPowerOfTwo(StackPointer+4)); end; Stack[StackPointer+0]:=LeftNode; Stack[StackPointer+1]:=Max(-1,Depth-1); Stack[StackPointer+2]:=RightNode; Stack[StackPointer+3]:=Max(-1,Depth-1); inc(StackPointer,4); end; end; end; end; SetLength(Nodes,NodeCount); finally Stack:=nil; end; end else begin NodeCount:=0; SetLength(Nodes,0); end; end; end.
{$include kode.inc} unit kode_list; // double-linked list // todo: single? //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type KListNode = class private FPrev : KListNode; FNext : KListNode; public constructor create; property next : KListNode read FNext; property prev : KListNode read FPrev; end; //---------- KList = class private FHead : KListNode; FTail : KListNode; public property head : KListNode read Fhead; property tail : KListNode read FTail; public constructor create; procedure reset; function empty : Boolean; procedure destroyNodes; procedure appendHead(ANode:KListNode); procedure appendTail(ANode:KListNode); procedure removeHead; procedure removeTail; procedure append(ANode:KListNode); procedure remove(ANode:KListNode); //procedure insertBefore(ANode,ANewNode:KListNode); //procedure insertAfter(ANode,ANewNode:KListNode); end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- constructor KListNode.create; begin FPrev := nil; FNext := nil; end; //------------------------------ // //------------------------------ constructor KList.create; begin self.reset; end; //---------- procedure KList.reset; begin // todo: delete nodes ? FHead := nil; FTail := nil; end; //---------- function KList.empty : Boolean; begin if FHead = nil then result := true else result := false; end; //---------- procedure KList.destroyNodes; var node,next : KListNode; begin node := FHead; while Assigned(node) do begin next := node.FNext; node.Destroy; node := next; end; FHead := nil; FTail := nil; end; //---------- procedure KList.appendHead(ANode:KListNode); begin ANode.FPrev := nil; if FTail = nil then begin FTail := ANode; ANode.FNext := nil; end else begin FHead.FPrev := ANode; ANode.FNext := FHead; end; FHead := ANode; end; //---------- procedure KList.appendTail(ANode:KListNode); begin ANode.FNext := nil; if FHead = nil then begin FHead := ANode; ANode.FPrev := nil; end else begin FTail.FNext := ANode; ANode.FPrev := FTail; end; FTail := ANode; end; //---------- procedure KList.removeHead; begin if FHead = FTail then self.reset else begin FHead := FHead.FNext; FHead.FPrev := nil; end; end; //---------- procedure KList.removeTail; begin if FHead = FTail then self.reset else begin FTail := FTail.FPrev; FTail.FNext := nil; end; end; //---------- procedure KList.append(ANode:KListNode); begin appendTail(ANode); end; //---------- procedure KList.remove(ANode:KListNode); begin if ANode = FHead then removeHead else if ANode = FTail then removeTail else begin ANode.FNext.FPrev := ANode.FPrev; ANode.FPrev.FNext := ANode.FNext; end; end; //---------- //procedure KList.insertBefore(ANode,ANewNode:KListNode); //begin //end; //---------- //procedure KList.insertAfter(ANode,ANewNode:KListNode); //begin //end; //---------------------------------------------------------------------- end.
unit uBaseForm; interface uses Forms, SysUtils, System.Classes, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxClasses, cxLookAndFeels, dxSkinsForm, cxGridCustomTableView, cxGridDBTableView, cxGridCustomView, cxGridTableView, cxDBEdit, cxDropDownEdit, cxTextEdit, cxedit, uSysDataBase, uSysUser, uSysConfig; type TStrObj = class(TObject) public FStr: string; end; TBaseForm = class(TForm) procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } procedure GridViewDisplay(); procedure GridViewDisplayDo(GridView: TcxGridDBTableView); procedure GridViewAddOrderColumn(GridView: TcxGridDBTableView); procedure OrderColumnGetDataText(Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); protected procedure InitCxComboBoxWithDicType(cxDBComboBox: TcxCustomComboBox; AType: string); procedure InitCxComboBoxWithSql(cxDBComboBox: TcxCustomComboBox; ASql: string; AField: string); public { Public declarations } FSysDataBase: TSysDataBase; FSysUser: TSysUser; FSysConfig: TSysConfig; FSkin: TdxSkinController; end; implementation procedure TBaseForm.FormCreate(Sender: TObject); begin inherited; FSysDataBase := uSysDataBase.GetSysDataBase; FSysUser := uSysUser.GetSysUser; FSysConfig := uSysConfig.SysConfig; // if not Self.SetQueryDataBase then // raise Exception.Create('Err25: SetQueryConnErr.'); // FSkin := TdxSkinController.Create(Self); FSkin.NativeStyle := False; FSkin.Kind := lfFlat; FSkin.SkinName := FSysConfig.SkinName; FSkin.UseSkins := True; end; procedure TBaseForm.FormShow(Sender: TObject); begin GridViewDisplay; end; procedure TBaseForm.GridViewDisplay; var i: Integer; begin for i := 0 to Self.ComponentCount - 1 do begin if Self.Components[i] is TcxGridDBTableView then begin GridViewDisplayDo(Self.Components[i] as TcxGridDBTableView); end; end; end; procedure TBaseForm.GridViewDisplayDo(GridView: TcxGridDBTableView); var iIndex: Integer; LSql: string; LColumn: TcxGridDBColumn; begin // GridView.OptionsView.DataRowHeight := 30; //delete for: 设置height会导致cell不能自动换行 GridView.OptionsView.HeaderHeight := 35; GridView.OptionsView.CellAutoHeight := True; //设置cell能自动换行 LSql := 'select * from grid_view_config where form = ' + QuotedStr(Self.Name) + ' and grid = ' + QuotedStr(GridView.Name) + ' order by order_no asc'; with FSysDataBase.GetDataSetBySql(LSql) do begin GridView.ClearItems; //清空数据 if IsEmpty then begin (GridView.DataController as IcxCustomGridDataController).DeleteAllItems; //删除所有列 (GridView.DataController as IcxCustomGridDataController).CreateAllItems(false); //创建数据源中的所有列 GridView.ApplyBestFit; //让列宽自适应 .BestFitMaxWidth; for iIndex := 0 to GridView.ColumnCount-1 do begin GridView.Columns[iIndex].HeaderAlignmentHorz := taCenter; LSql := 'insert into grid_view_config(form, grid, field, order_no, value_type, caption, caption_align, width, visible) ' + 'values(''%s'', ''%s'', ''%s'', %d, ''%s'', ''%s'', %d, %d, ''%s'')'; LSql := LSql.Format(LSql, [Self.Name, GridView.Name, GridView.Columns[iIndex].DataBinding.FieldName, iIndex, GridView.Columns[iIndex].DataBinding.ValueType, GridView.Columns[iIndex].Caption, Ord(GridView.Columns[iIndex].HeaderAlignmentHorz), GridView.Columns[iIndex].Width, '1']); FSysDataBase.ExecSQL(LSql); end; end else begin if GridView.Tag = 9 then GridViewAddOrderColumn(GridView); First; while not Eof do begin if 1 = FieldByName('visible').AsInteger then begin LColumn := GridView.CreateColumn; LColumn.DataBinding.FieldName := FieldByName('field').AsString; LColumn.DataBinding.ValueType := FieldByName('value_type').AsString; LColumn.Caption := FieldByName('caption').AsString; LColumn.Width := FieldByName('width').AsInteger; LColumn.HeaderAlignmentHorz := TAlignment(FieldByName('caption_align').AsInteger); // if (nil <> LColumn.Properties) and (nil <> LColumn.Properties.Alignment) then begin // LColumn.Properties.Alignment.Horz := TcxEditHorzAlignment(2);//taCenter; //表格水平方向 // LColumn.Properties.Alignment.Vert := TcxEditVertAlignment(2);// TAlignment(1); //taCenter; // end; // LColumn.Visible := (1 = FieldByName('visible').AsInteger); // if FieldByName('properties').AsString.Equals('Memo') then begin // LColumn.PropertiesClassName := 'TcxMemoProperties'; // end; LColumn.GetProperties.Alignment.Horz := taCenter; end; Next; end; end; end; end; procedure TBaseForm.GridViewAddOrderColumn(GridView: TcxGridDBTableView); var LColumn: TcxGridDBColumn; begin LColumn := GridView.CreateColumn; LColumn.Caption := '序号'; LColumn.Width := 50; LColumn.HeaderAlignmentHorz := taCenter; LColumn.OnGetDataText := OrderColumnGetDataText; LColumn.PropertiesClassName := 'TcxTextEditProperties'; LColumn.Properties.Alignment.Horz := taCenter; end; procedure TBaseForm.OrderColumnGetDataText(Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string); begin AText := IntToStr(ARecordIndex+1); end; procedure TBaseForm.InitCxComboBoxWithDicType(cxDBComboBox: TcxCustomComboBox; AType: string); begin InitCxComboBoxWithSql(cxDBComboBox, 'select * from system_dic where type = ' + QuotedStr(AType) + ' order by order_no asc', 'name'); end; procedure TBaseForm.InitCxComboBoxWithSql(cxDBComboBox: TcxCustomComboBox; ASql: string; AField: string); var LStrObj: TStrObj; begin cxDBComboBox.Properties.Items.Clear; with FSysDataBase.GetDataSetBySql(ASql) do begin First; while not Eof do begin // cxDBComboBox.Properties.Items.Add(FieldByName(AField).AsString); LStrObj := TStrObj.Create; LStrObj.FStr := FieldByName('sys_id').AsString; cxDBComboBox.Properties.Items.AddObject(FieldByName(AField).AsString, LStrObj); Next; end; end; end; end.
{******************************************************************************* Title: T2TiPDV Description: Tela principal do SAT - Caixa. The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije @version 2.0 ******************************************************************************* } unit UCaixa; interface uses Windows, Dialogs, pngimage, ExtCtrls, Classes, Messages, SysUtils, Variants, Generics.Collections, Graphics, Controls, Forms, jpeg, StdCtrls, Buttons, JvLabel, JvValidateEdit, JvgListBox, JvListBox, JvBaseDlg, JvCalc, JvExExtCtrls, JvExtComponent, JvClock, JvExStdCtrls, JvEdit, JvExControls, ACBrBase, TypInfo, Constantes, ACBrBAL, ACBrDevice, ACBrInStore, JvAnimatedImage, JvGIFCtrl, Mask, jvExMask, JvToolEdit, JvBaseEdits, ACBrLCB, inifiles, IndyPeerImpl, AppEvnts, Controller, UBase, Tipos, Biblioteca, DateUtils, ACBrDFeUtil, pcnConversao, pcnConversaoNFe, ACBrSAT, ACBrSATClass; const cAssinatura = 'eije11111111111111111111111111111111111111111111111111111111111'+ '111111111111111111111111111111111111111111111111111111111111111'+ '111111111111111111111111111111111111111111111111111111111111111'+ '111111111111111111111111111111111111111111111111111111111111111'+ '111111111111111111111111111111111111111111111111111111111111111'+ '11111111111111111111111111111' ; type TFCaixa = class(TFBase) panelPrincipal: TPanel; imagePrincipal: TImage; labelDescricaoProduto: TJvLabel; labelTotalGeral: TJvLabel; labelMensagens: TJvLabel; imageProduto: TImage; Bobina: TJvListBox; panelMenuPrincipal: TPanel; imagePanelMenuPrincipal: TImage; labelMenuPrincipal: TJvLabel; listaMenuPrincipal: TJvgListBox; panelMenuOperacoes: TPanel; imagePanelMenuOperacoes: TImage; labelMenuOperacoes: TJvLabel; listaMenuOperacoes: TJvgListBox; panelSubMenu: TPanel; imagePanelSubMenu: TImage; listaSupervisor: TJvgListBox; listaGerente: TJvgListBox; TimerMarketing: TTimer; panelTitulo: TPanel; panelBotoes: TPanel; panelF1: TPanel; labelF1: TLabel; imageF1: TImage; panelF7: TPanel; labelF7: TLabel; imageF7: TImage; panelF2: TPanel; labelF2: TLabel; imageF2: TImage; panelF3: TPanel; labelF3: TLabel; imageF3: TImage; panelF4: TPanel; labelF4: TLabel; imageF4: TImage; panelF5: TPanel; labelF5: TLabel; imageF5: TImage; panelF6: TPanel; labelF6: TLabel; imageF6: TImage; panelF8: TPanel; labelF8: TLabel; imageF8: TImage; panelF9: TPanel; labelF9: TLabel; imageF9: TImage; panelF10: TPanel; labelF10: TLabel; imageF10: TImage; panelF11: TPanel; labelF11: TLabel; imageF11: TImage; panelF12: TPanel; labelF12: TLabel; imageF12: TImage; Calculadora: TJvCalculator; Relogio: TJvClock; labelOperador: TLabel; labelCaixa: TLabel; LabelDescontoAcrescimo: TLabel; EditCodigo: TEdit; ACBrBAL1: TACBrBAL; ACBrInStore1: TACBrInStore; edtNVenda: TLabel; edtNumeroNota: TLabel; EditQuantidade: TJvCalcEdit; EditUnitario: TJvCalcEdit; EditTotalItem: TJvCalcEdit; EditSubTotal: TJvCalcEdit; ACBrLCB1: TACBrLCB; ApplicationEvents1: TApplicationEvents; LabelCliente: TLabel; Timer1: TTimer; MemoXmlSAT: TMemo; procedure RecuperarVenda; procedure GerarXmlSAT; procedure InstanciaVendaAtual; procedure DesmembraCodigoDigitado(CodigoDeBarraOuDescricaoOuIdProduto: String); procedure MensagemDeProdutoNaoEncontrado; procedure FechaMenuOperacoes; procedure TrataExcecao(Sender: TObject; E: Exception); procedure ConfiguraLayout; procedure ExecutaOutrosProcedimentosDeAbertura; procedure CompoeItemParaVenda; procedure ParametrosIniciaisVenda; procedure ConsultaProduto(Codigo: String; Tipo: Integer); procedure ImprimeCabecalhoBobina; procedure ImprimeItemBobina; procedure LocalizaProduto; procedure ConsultaStatusOperacional; procedure AcionaMenuPrincipal; procedure AcionaMenuOperacoes; procedure IdentificaCliente; procedure IdentificaVendedor; procedure ConfiguraConstantes; procedure ConfiguraResolucao; procedure ConfiguraSAT; procedure IniciaMovimento; procedure EncerraMovimento; procedure CancelaVenda; procedure Suprimento; procedure Sangria; procedure DescontoOuAcrescimo; procedure TelaPadrao; procedure IniciaVenda; procedure IniciaEncerramentoVenda; procedure ConcluiEncerramentoVenda; procedure VendeItem; procedure IniciaVendaDeItens; procedure AtualizaTotais; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure listaMenuPrincipalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure listaMenuOperacoesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure listaGerenteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure listaSupervisorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TimerMarketingTimer(Sender: TObject); procedure FormActivate(Sender: TObject); procedure panelF1MouseLeave(Sender: TObject); procedure panelF1MouseEnter(Sender: TObject); procedure panelF7MouseEnter(Sender: TObject); procedure panelF7MouseLeave(Sender: TObject); procedure panelF2MouseEnter(Sender: TObject); procedure panelF2MouseLeave(Sender: TObject); procedure panelF3MouseEnter(Sender: TObject); procedure panelF3MouseLeave(Sender: TObject); procedure panelF4MouseLeave(Sender: TObject); procedure panelF5MouseEnter(Sender: TObject); procedure panelF5MouseLeave(Sender: TObject); procedure panelF6MouseEnter(Sender: TObject); procedure panelF6MouseLeave(Sender: TObject); procedure panelF8MouseEnter(Sender: TObject); procedure panelF8MouseLeave(Sender: TObject); procedure panelF9MouseEnter(Sender: TObject); procedure panelF9MouseLeave(Sender: TObject); procedure panelF10MouseEnter(Sender: TObject); procedure panelF10MouseLeave(Sender: TObject); procedure panelF11MouseEnter(Sender: TObject); procedure panelF11MouseLeave(Sender: TObject); procedure panelF12MouseEnter(Sender: TObject); procedure panelF12MouseLeave(Sender: TObject); procedure panelF4MouseEnter(Sender: TObject); procedure panelF12Click(Sender: TObject); procedure panelF1Click(Sender: TObject); procedure panelF2Click(Sender: TObject); procedure panelF3Click(Sender: TObject); procedure panelF4Click(Sender: TObject); procedure panelF5Click(Sender: TObject); procedure panelF6Click(Sender: TObject); procedure panelF7Click(Sender: TObject); procedure panelF8Click(Sender: TObject); procedure panelF9Click(Sender: TObject); procedure panelF10Click(Sender: TObject); procedure panelF11Click(Sender: TObject); procedure EditCodigoKeyPress(Sender: TObject; var Key: Char); procedure EditQuantidadeKeyPress(Sender: TObject; var Key: Char); procedure EditQuantidadeExit(Sender: TObject); procedure DesabilitaControlesVenda; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure EditCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ConectaComBalanca; procedure ACBrBAL1LePeso(Peso: Double; Resposta: AnsiString); procedure FormShow(Sender: TObject); procedure ACBrLCB1LeCodigo(Sender: TObject); procedure ConectaComLeitorSerial; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Timer1Timer(Sender: TObject); private BalancaLePeso: Boolean; ExtratoResumido: Boolean; procedure ShowHint(Sender: TObject); procedure CancelaItem; { Private declarations } public procedure MenuSetaAcima(Indice: Integer; Lista: TJvgListBox); procedure MenuSetaAbaixo(Indice: Integer; Lista: TJvgListBox); procedure HabilitaControlesVenda; { Public declarations } end; var FCaixa: TFCaixa; ItemCupom: Integer; SubTotal, TotalGeral, Desconto, Acrescimo, ValorICMS: Extended; Filtro: String; MensagemPersistente: String; implementation uses UDataModule, UImportaNumero, UIdentificaCliente, UValorReal, UDescontoAcrescimo, UIniciaMovimento, UDataModuleConexao, UEfetuaPagamento, UEncerraMovimento, UImportaCliente, UImportaProduto, UMovimentoAberto, ULoginGerenteSupervisor, UListaVendas, ProdutoVO, NfcePosicaoComponentesVO, NfceSangriaVO, NfceSuprimentoVO, DAVDetalheVO, NfeCabecalhoVO, DavCabecalhoVO, VendedorVO, UnidadeProdutoVO, NfeConfiguracaoVO, NfeNumeroVO, NfeDetalheVO, UStatusOperacional; var DavCabecalho: TDavCabecalhoVO; VendaDetalhe: TNfeDetalheVO; ObjetoNfeConfiguracaoVO: TNfeConfiguracaoVO; {$R *.dfm} {$REGION 'Procedimentos principais e de infra'} procedure TFCaixa.FormActivate(Sender: TObject); begin FCaixa.Repaint; end; procedure TFCaixa.FormShow(Sender: TObject); begin ConfiguraAmbiente; Application.CreateForm(TFDataModuleConexao, FDataModuleConexao); Application.OnException := TrataExcecao; DesabilitaControlesVenda; Sessao.PopulaObjetosPrincipais; Sessao.MenuAberto := snNao; Sessao.StatusCaixa := scFechado; Application.OnHint := ShowHint; ConfiguraConstantes; ConfiguraLayout; ConfiguraResolucao; ExecutaOutrosProcedimentosDeAbertura; ObjetoNfeConfiguracaoVO := TNfeConfiguracaoVO(TController.BuscarObjeto('NfeConfiguracaoController.TNfeConfiguracaoController', 'ConsultaObjeto', ['ID=1'], 'GET')); ConfiguraSAT; BalancaLePeso := False; end; procedure TFCaixa.FormClose(Sender: TObject; var Action: TCloseAction); begin Sessao.Free; end; procedure TFCaixa.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (Sessao.StatusCaixa <> scVendaEmAndamento) then begin if Application.MessageBox('Tem Certeza Que Deseja Sair do Sistema?', 'Sair do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then begin SetTaskBar(true); Application.Terminate; end else CanClose := False; end else begin Application.MessageBox('Existe uma venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); CanClose := False; end; end; procedure TFCaixa.ExecutaOutrosProcedimentosDeAbertura; begin TelaPadrao; HabilitaControlesVenda; if Sessao.Configuracao.NfceConfiguracaoBalancaVO.Modelo > 0 then begin try ConectaComBalanca; except Application.MessageBox('Balança não conectada ou desligada!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; end; if Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Usa = 'S' then begin try ConectaComLeitorSerial; except Application.MessageBox('Leitor de Código de Barras Serial não conectado ou está desligado!' + #13 + 'Verifique os cabos e reveja as configurações do dispositivo!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; end; end; procedure TFCaixa.ConfiguraLayout; begin panelTitulo.Caption := Sessao.Configuracao.TituloTelaCaixa + ' Build : ' + VersaoExe(Application.ExeName, 'V'); if FileExists(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemTela) then imagePrincipal.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemTela) else Sessao.Configuracao.CaminhoImagensLayout := 'Imagens\imgLayout\'; imagePrincipal.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemTela); imagePanelMenuPrincipal.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemMenu); imagePanelMenuOperacoes.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemMenu); imagePanelSubMenu.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensLayout + Sessao.Configuracao.NfceResolucaoVO.ImagemSubMenu); end; procedure TFCaixa.ConfiguraSAT; begin // EXERCICIO: Crie uma tabela no banco de dados para armazenar as configurações do SAT FDataModule.ACBrSAT.Modelo := satDinamico_cdecl; // TACBrSATModelo( cbxModelo.ItemIndex ) ; FDataModule.ACBrSAT.ArqLOG := 'ACBrSAT.log'; FDataModule.ACBrSAT.NomeDLL := 'C:\SAT\SAT.DLL'; FDataModule.ACBrSAT.Config.ide_numeroCaixa := 1; FDataModule.ACBrSAT.Config.ide_tpAmb := taHomologacao; // TpcnTipoAmbiente( cbxAmbiente.ItemIndex ); FDataModule.ACBrSAT.Config.ide_CNPJ := '11111111111111'; // CNPJ da Software House FDataModule.ACBrSAT.Config.emit_CNPJ := '11111111111111'; // CNPJ do Emitente FDataModule.ACBrSAT.Config.emit_IE := '111.111.111.111'; // IE do Emitente FDataModule.ACBrSAT.Config.emit_IM := '123123'; // IM do Emitente FDataModule.ACBrSAT.Config.emit_cRegTrib := RTSimplesNacional; // TpcnRegTrib( cbxRegTributario.ItemIndex ) ; FDataModule.ACBrSAT.Config.emit_cRegTribISSQN := RTISSMicroempresaMunicipal; // TpcnRegTribISSQN( cbxRegTribISSQN.ItemIndex ) ; FDataModule.ACBrSAT.Config.emit_indRatISSQN := irNao; // TpcnindRatISSQN( cbxIndRatISSQN.ItemIndex ) ; FDataModule.ACBrSAT.Config.PaginaDeCodigo := 0; FDataModule.ACBrSAT.Config.EhUTF8 := False; FDataModule.ACBrSAT.Config.infCFe_versaoDadosEnt := 0.06; FDataModule.ACBrSAT.ConfigArquivos.SalvarCFe := True; FDataModule.ACBrSAT.ConfigArquivos.SalvarCFeCanc := True; FDataModule.ACBrSAT.ConfigArquivos.SalvarEnvio := True; FDataModule.ACBrSAT.ConfigArquivos.SepararPorCNPJ := True; FDataModule.ACBrSAT.ConfigArquivos.SepararPorMes := True; FDataModule.ACBrSAT.CFe.IdentarXML := True; FDataModule.ACBrSAT.CFe.TamanhoIdentacao := 3; // impressão FDataModule.ACBrSATExtratoFortes.LarguraBobina := 302; FDataModule.ACBrSATExtratoFortes.Margens.Topo := 5; FDataModule.ACBrSATExtratoFortes.Margens.Fundo := 5; FDataModule.ACBrSATExtratoFortes.Margens.Esquerda := 4; FDataModule.ACBrSATExtratoFortes.Margens.Direita := 4; FDataModule.ACBrSATExtratoFortes.MostrarPreview := True; // inicializa FDataModule.ACBrSAT.Inicializado := not FDataModule.ACBrSAT.Inicializado; ExtratoResumido := False; end; Procedure TFCaixa.TrataExcecao(Sender: TObject; E: Exception); begin Application.MessageBox(PChar(E.Message), 'Erro do Sistema', MB_OK + MB_ICONERROR); end; procedure TFCaixa.ConfiguraConstantes; begin Constantes.TConstantes.DECIMAIS_QUANTIDADE := Sessao.Configuracao.DecimaisQuantidade; Constantes.TConstantes.DECIMAIS_VALOR := Sessao.Configuracao.DecimaisValor; end; procedure TFCaixa.ConfiguraResolucao; var i, j: Integer; ListaPosicoes: TObjectList<TNfcePosicaoComponentesVO>; PosicaoComponente: TNfcePosicaoComponentesVO; NomeComponente: String; begin ListaPosicoes := Sessao.Configuracao.NfceResolucaoVO.ListaNfcePosicaoComponentesVO; for j := 0 to componentcount - 1 do begin NomeComponente := components[j].Name; for i := 0 to ListaPosicoes.Count - 1 do begin PosicaoComponente := ListaPosicoes.Items[i]; if PosicaoComponente.Nome = NomeComponente then begin (components[j] as TControl).Height := PosicaoComponente.Altura; (components[j] as TControl).Left := PosicaoComponente.Esquerda; (components[j] as TControl).Top := PosicaoComponente.Topo; (components[j] as TControl).Width := PosicaoComponente.Largura; if PosicaoComponente.TamanhoFonte <> 0 then begin if (components[j] is TEdit) then (components[j] as TEdit).Font.Size := PosicaoComponente.TamanhoFonte; if (components[j] is TJvListBox) then (components[j] as TJvListBox).Font.Size := PosicaoComponente.TamanhoFonte; if (components[j] is TJvLabel) then (components[j] as TJvLabel).Font.Size := PosicaoComponente.TamanhoFonte; if (components[j] is TPanel) then (components[j] as TPanel).Font.Size := PosicaoComponente.TamanhoFonte; if (components[j] is TJvCalcEdit) then (components[j] as TJvCalcEdit).Font.Size := PosicaoComponente.TamanhoFonte; end; if (components[j] is TLabel) then (components[j] as TLabel).Caption := PosicaoComponente.Texto; break; end; end; end; FCaixa.Left := 0; FCaixa.Top := 0; FCaixa.Width := Sessao.Configuracao.NfceResolucaoVO.Largura; FCaixa.Height := Sessao.Configuracao.NfceResolucaoVO.Altura; FCaixa.AutoSize := true; end; procedure TFCaixa.ShowHint(Sender: TObject); begin if Application.Hint <> '' then labelMensagens.Caption := Application.Hint else labelMensagens.Caption := MensagemPersistente; end; procedure TFCaixa.TelaPadrao; begin if Assigned(Sessao.VendaAtual) then Sessao.LiberaVendaAtual; if not Assigned(Sessao.Movimento) then begin labelMensagens.Caption := 'CAIXA FECHADO'; IniciaMovimento; // se o caixa estiver fechado abre o iniciaMovimento end else if Sessao.Movimento.StatusMovimento = 'T' then labelMensagens.Caption := 'SAIDA TEMPORÁRIA' else labelMensagens.Caption := 'CAIXA ABERTO'; if Sessao.StatusCaixa = scVendaEmAndamento then labelMensagens.Caption := 'Venda em andamento...'; MensagemPersistente := labelMensagens.Caption; if Assigned(Sessao.Movimento) then begin labelCaixa.Caption := 'Terminal: ' + Sessao.Movimento.NfceCaixaVO.Nome; labelOperador.Caption := 'Operador: ' + Sessao.Movimento.NfceOperadorVO.Login; end; EditQuantidade.Text := '1'; EditCodigo.Text := ''; EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditSubTotal.Text := '0'; labelTotalGeral.Caption := '0,00'; labelDescricaoProduto.Caption := ''; LabelDescontoAcrescimo.Caption := ''; LabelCliente.Caption := ''; edtNVenda.Caption := ''; edtNumeroNota.Caption := ''; SubTotal := 0; TotalGeral := 0; ValorICMS := 0; Desconto := 0; Acrescimo := 0; Bobina.Clear; if Sessao.Configuracao.MarketingAtivo = 'S' then TimerMarketing.Enabled := true else begin if FileExists(Sessao.Configuracao.CaminhoImagensProdutos + 'padrao.png') then imageProduto.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensProdutos + 'padrao.png') else imageProduto.Picture.LoadFromFile('Imagens\imgProdutos\padrao.png') end; end; procedure TFCaixa.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; if Assigned(Sessao.Movimento) then begin Application.CreateForm(TFMovimentoAberto, FMovimentoAberto); FMovimentoAberto.ShowModal; end; end; procedure TFCaixa.TimerMarketingTimer(Sender: TObject); var Aleatorio: Integer; begin if Sessao.StatusCaixa = scAberto then begin Aleatorio := 1 + Random(5); if FileExists(Sessao.Configuracao.CaminhoImagensMarketing + IntToStr(Aleatorio) + '.jpg') then imageProduto.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensMarketing + IntToStr(Aleatorio) + '.jpg') else imageProduto.Picture.LoadFromFile('Imagens\imgMarketing\' + IntToStr(Aleatorio) + '.jpg') end; end; procedure TFCaixa.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // F1 - Identifica Cliente if Key = VK_F1 then IdentificaCliente; // F2 - Menu Principal if Key = VK_F2 then AcionaMenuPrincipal; // F3 - Menu Operações if Key = VK_F3 then AcionaMenuOperacoes; // F4 - Cancelar / Inutilizar if Key = VK_F4 then ConsultaStatusOperacional; // F5 - Recuperar Venda if Key = VK_F5 then RecuperarVenda; // F6 - Localiza Produto if Key = VK_F6 then LocalizaProduto; // F7 - Encerra Venda if Key = VK_F7 then IniciaEncerramentoVenda; // F8 - Cancela Item if Key = VK_F8 then CancelaItem; // F9 - Cancela Venda if Key = VK_F9 then CancelaVenda; // F10 - Concede Desconto if Key = VK_F10 then DescontoOuAcrescimo; // F11 - Identifica Vendedor if Key = VK_F11 then IdentificaVendedor; // F12 - Sai do Caixa if Key = VK_F12 then Close; if (ssctrl in Shift) and CharInSet(chr(Key), ['B', 'b']) then begin if Sessao.Configuracao.NfceConfiguracaoBalancaVO.Modelo > 0 then begin try BalancaLePeso := true; ACBrBAL1.LePeso(Sessao.Configuracao.NfceConfiguracaoBalancaVO.TimeOut); EditCodigo.Text := ''; EditCodigo.SetFocus; except Application.MessageBox('Balança não conectada ou desligada!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; end; end; end; procedure TFCaixa.AcionaMenuPrincipal; begin if Sessao.StatusCaixa <> scVendaEmAndamento then begin if Sessao.MenuAberto = snNao then begin Sessao.MenuAberto := snSim; panelMenuPrincipal.Visible := true; listaMenuPrincipal.SetFocus; listaMenuPrincipal.ItemIndex := 0; DesabilitaControlesVenda; end end else Application.MessageBox('Existe uma venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFCaixa.AcionaMenuOperacoes; begin if Sessao.StatusCaixa <> scVendaEmAndamento then begin if Sessao.MenuAberto = snNao then begin Sessao.MenuAberto := snSim; panelMenuOperacoes.Visible := true; listaMenuOperacoes.SetFocus; listaMenuOperacoes.ItemIndex := 0; DesabilitaControlesVenda; end; end else Application.MessageBox('Existe uma venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFCaixa.ACBrLCB1LeCodigo(Sender: TObject); begin if EditCodigo.Focused then // Para evitar que ponha o codigo no campo quantidade por exemplo begin EditCodigo.Text := ACBrLCB1.UltimoCodigo; // Preenche o Edit com o codigo lido keybd_event(VK_RETURN, 0, 0, 0); // Simula o acionamento da tecla ENTER end; end; procedure TFCaixa.MenuSetaAbaixo(Indice: Integer; Lista: TJvgListBox); begin if Indice = Lista.Count - 1 then labelMensagens.Caption := Lista.Items[Lista.ItemIndex] else labelMensagens.Caption := Lista.Items[Lista.ItemIndex + 1]; end; procedure TFCaixa.MenuSetaAcima(Indice: Integer; Lista: TJvgListBox); begin if Indice = 0 then labelMensagens.Caption := Lista.Items[Lista.ItemIndex] else labelMensagens.Caption := Lista.Items[Lista.ItemIndex - 1]; end; {$ENDREGION} {$REGION 'Procedimentos referentes ao Menu Principal e seus SubMenus'} procedure TFCaixa.listaMenuPrincipalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin panelMenuPrincipal.Visible := False; labelMensagens.Caption := MensagemPersistente; Sessao.MenuAberto := snNao; panelSubMenu.Visible := False; // HabilitaControlesVenda; EditCodigo.SetFocus; end; if Key = VK_UP then MenuSetaAcima(listaMenuPrincipal.ItemIndex, listaMenuPrincipal); if Key = VK_DOWN then MenuSetaAbaixo(listaMenuPrincipal.ItemIndex, listaMenuPrincipal); if Key = VK_RETURN then begin // chama submenu do supervisor if listaMenuPrincipal.ItemIndex = 0 then begin Application.CreateForm(TFLoginGerenteSupervisor, FLoginGerenteSupervisor); try FLoginGerenteSupervisor.GerenteOuSupervisor := 'S'; if (FLoginGerenteSupervisor.ShowModal = MROK) then begin if FLoginGerenteSupervisor.LoginOK then begin panelSubMenu.Visible := true; listaSupervisor.BringToFront; listaSupervisor.SetFocus; listaSupervisor.ItemIndex := 0; end else Application.MessageBox('Supervisor - dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; finally if Assigned(FLoginGerenteSupervisor) then FLoginGerenteSupervisor.Free; end; end; // chama submenu do gerente if listaMenuPrincipal.ItemIndex = 1 then begin Application.CreateForm(TFLoginGerenteSupervisor, FLoginGerenteSupervisor); try FLoginGerenteSupervisor.GerenteOuSupervisor := 'G'; if (FLoginGerenteSupervisor.ShowModal = MROK) then begin if FLoginGerenteSupervisor.LoginOK then begin panelSubMenu.Visible := true; listaGerente.BringToFront; listaGerente.SetFocus; listaGerente.ItemIndex := 0; end else Application.MessageBox('Gerente - dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; finally if Assigned(FLoginGerenteSupervisor) then FLoginGerenteSupervisor.Free; end; end; // saida temporária if listaMenuPrincipal.ItemIndex = 2 then begin if Sessao.StatusCaixa = scAberto then begin if Application.MessageBox('Deseja fechar o caixa temporariamente?', 'Fecha o caixa temporariamente', Mb_YesNo + Mb_IconQuestion) = IdYes then begin Sessao.Movimento.StatusMovimento := 'T'; TController.ExecutarMetodo('NfceMovimentoController.TNfceMovimentoController', 'Altera', [Sessao.Movimento], 'POST', 'Boolean'); Application.CreateForm(TFMovimentoAberto, FMovimentoAberto); FMovimentoAberto.ShowModal; end; end else Application.MessageBox('Status do caixa não permite saída temporária.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; end; end; procedure TFCaixa.listaSupervisorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin panelSubMenu.Visible := False; listaMenuPrincipal.SetFocus; listaMenuPrincipal.ItemIndex := 0; end; if Key = VK_UP then MenuSetaAcima(listaSupervisor.ItemIndex, listaSupervisor); if Key = VK_DOWN then MenuSetaAbaixo(listaSupervisor.ItemIndex, listaSupervisor); if Key = VK_RETURN then begin // inicia movimento if listaSupervisor.ItemIndex = 0 then IniciaMovimento; // encerra movimento if listaSupervisor.ItemIndex = 1 then EncerraMovimento; // suprimento if listaSupervisor.ItemIndex = 3 then Suprimento; // sangria if listaSupervisor.ItemIndex = 4 then Sangria; end; end; procedure TFCaixa.listaGerenteKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin panelSubMenu.Visible := False; listaMenuPrincipal.SetFocus; listaMenuPrincipal.ItemIndex := 0; end; if Key = VK_UP then MenuSetaAcima(listaGerente.ItemIndex, listaGerente); if Key = VK_DOWN then MenuSetaAbaixo(listaGerente.ItemIndex, listaGerente); if Key = VK_RETURN then begin // inicia movimento if listaGerente.ItemIndex = 0 then IniciaMovimento; // encerra movimento if listaGerente.ItemIndex = 1 then EncerraMovimento; // suprimento if listaGerente.ItemIndex = 3 then Suprimento; // sangria if listaGerente.ItemIndex = 4 then Sangria; end; end; procedure TFCaixa.IniciaMovimento; begin try if not Assigned(Sessao.Movimento) then begin Application.CreateForm(TFIniciaMovimento, FIniciaMovimento); FIniciaMovimento.ShowModal; end else begin Application.MessageBox('Já existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) end; finally end; end; procedure TFCaixa.EncerraMovimento; begin if not Assigned(Sessao.Movimento) then Application.MessageBox('Não existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Application.CreateForm(TFEncerraMovimento, FEncerraMovimento); FEncerraMovimento.ShowModal; end; TelaPadrao; end; procedure TFCaixa.Suprimento; var Suprimento: TNfceSuprimentoVO; ValorSuprimento: Extended; begin if not Assigned(Sessao.Movimento) then Application.MessageBox('Não existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Application.CreateForm(TFValorReal, FValorReal); FValorReal.Caption := 'Suprimento'; FValorReal.LabelEntrada.Caption := 'Informe o valor do suprimento:'; try if (FValorReal.ShowModal = MROK) then begin ValorSuprimento := FValorReal.EditEntrada.Value; Suprimento := TNfceSuprimentoVO.Create; Suprimento.IdNfceMovimento := Sessao.Movimento.Id; Suprimento.DataSuprimento := Date; Suprimento.Observacao := FValorReal.MemoObservacao.Text; Suprimento.Valor := ValorSuprimento; TController.ExecutarMetodo('NfceSuprimentoController.TNfceSuprimentoController', 'Insere', [Suprimento], 'PUT', 'Lista'); Sessao.Movimento.TotalSuprimento := Sessao.Movimento.TotalSuprimento + ValorSuprimento; TController.ExecutarMetodo('NfceMovimentoController.TNfceMovimentoController', 'Altera', [Sessao.Movimento], 'POST', 'Boolean'); end; finally end; end; end; procedure TFCaixa.Sangria; var Sangria: TNfceSangriaVO; ValorSangria: Extended; begin if not Assigned(Sessao.Movimento) then Application.MessageBox('Não existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Application.CreateForm(TFValorReal, FValorReal); FValorReal.Caption := 'Sangria'; FValorReal.LabelEntrada.Caption := 'Informe o valor da sangria:'; try if (FValorReal.ShowModal = MROK) then begin ValorSangria := FValorReal.EditEntrada.Value; Sangria := TNfceSangriaVO.Create; Sangria.IdNfceMovimento := Sessao.Movimento.Id; Sangria.DataSangria := Date; Sangria.Observacao := FValorReal.MemoObservacao.Text; Sangria.Valor := ValorSangria; TController.ExecutarMetodo('NfceSangriaController.TNfceSangriaController', 'Insere', [Sangria], 'PUT', 'Lista'); Sessao.Movimento.TotalSangria := Sessao.Movimento.TotalSangria + ValorSangria; TController.ExecutarMetodo('NfceMovimentoController.TNfceMovimentoController', 'Altera', [Sessao.Movimento], 'POST', 'Boolean'); end; finally end; end; end; procedure TFCaixa.DescontoOuAcrescimo; var // 0-Desconto em Dinheiro // 1-Desconto Percentual // 2-Acréscimo em Dinheiro // 3-Acréscimo Percentual // 5-Cancela o Desconto ou Acréscimo Operacao: Integer; Valor: Extended; begin if Sessao.StatusCaixa = scVendaEmAndamento then begin Application.CreateForm(TFLoginGerenteSupervisor, FLoginGerenteSupervisor); try if (FLoginGerenteSupervisor.ShowModal = MROK) then begin if FLoginGerenteSupervisor.LoginOK then begin Application.CreateForm(TFDescontoAcrescimo, FDescontoAcrescimo); FDescontoAcrescimo.Caption := 'Desconto ou Acréscimo'; try if (FDescontoAcrescimo.ShowModal = MROK) then begin Operacao := FDescontoAcrescimo.ComboOperacao.ItemIndex; Valor := FDescontoAcrescimo.EditEntrada.Value; // desconto em valor if Operacao = 0 then begin if Valor >= Sessao.VendaAtual.ValorTotalProdutos then Application.MessageBox('Desconto não pode ser superior ou igual ao valor da venda.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin if Valor <= 0 then Application.MessageBox('Valor zerado ou negativo. Operação não realizada.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Desconto := Desconto + Valor; AtualizaTotais; end; end; end; // if Operacao = 0 then // desconto em taxa if Operacao = 1 then begin if Valor > 99 then Application.MessageBox('Desconto não pode ser superior a 100%.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin if Valor <= 0 then Application.MessageBox('Valor zerado ou negativo. Operação não realizada.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Desconto := Desconto + TruncaValor(SubTotal * (Valor / 100), Constantes.TConstantes.DECIMAIS_VALOR); AtualizaTotais; end; end; end; // if Operacao = 1 then // acrescimo em valor if Operacao = 2 then begin if Valor <= 0 then Application.MessageBox('Valor zerado ou negativo. Operação não realizada.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else if Valor >= Sessao.VendaAtual.ValorTotalProdutos then Application.MessageBox('Valor do acréscimo não pode ser igual ou superior ao valor da venda!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Acrescimo := Acrescimo + Valor; AtualizaTotais; end; end; // if Operacao = 2 then // acrescimo em taxa if Operacao = 3 then begin if Valor <= 0 then Application.MessageBox('Valor zerado ou negativo. Operação não realizada.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else if Valor > 99 then Application.MessageBox('Acréscimo não pode ser superior a 100%!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Acrescimo := Acrescimo + TruncaValor(SubTotal * (Valor / 100), Constantes.TConstantes.DECIMAIS_VALOR); AtualizaTotais; end; end; // if Operacao = 3 then // cancela desconto ou acrescimo if Operacao = 5 then begin Acrescimo := 0; Desconto := 0; AtualizaTotais; end; // if Operacao = 5 then end; finally if Assigned(FDescontoAcrescimo) then FDescontoAcrescimo.Free; end; end else Application.MessageBox('Login - dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; // if (FLoginGerenteSupervisor.ShowModal = MROK) then finally if Assigned(FLoginGerenteSupervisor) then FLoginGerenteSupervisor.Free; end; end else Application.MessageBox('Não existe venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; {$ENDREGION} {$REGION 'Procedimentos referentes ao Menu Operações e seus SubMenus'} procedure TFCaixa.listaMenuOperacoesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin FechaMenuOperacoes; end; if Key = VK_UP then MenuSetaAcima(listaMenuOperacoes.ItemIndex, listaMenuOperacoes); if Key = VK_DOWN then MenuSetaAbaixo(listaMenuOperacoes.ItemIndex, listaMenuOperacoes); if Key = VK_RETURN then begin // Consultar SAT if listaMenuOperacoes.ItemIndex = 0 then begin FDataModule.ACBrSAT.ConsultarSAT; Application.MessageBox(PWideChar(FDataModule.ACBrSAT.Resposta.mensagemRetorno), 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; // Bloquear SAT if listaMenuOperacoes.ItemIndex = 1 then begin FDataModule.ACBrSAT.BloquearSAT; Application.MessageBox(PWideChar(FDataModule.ACBrSAT.Resposta.mensagemRetorno), 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; // Desbloquear SAT if listaMenuOperacoes.ItemIndex = 2 then begin FDataModule.ACBrSAT.DesbloquearSAT; Application.MessageBox(PWideChar(FDataModule.ACBrSAT.Resposta.mensagemRetorno), 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; end; // if Key = VK_RETURN then end; procedure TFCaixa.FechaMenuOperacoes; begin panelMenuOperacoes.Visible := False; labelMensagens.Caption := MensagemPersistente; Sessao.MenuAberto := snNao; HabilitaControlesVenda; EditCodigo.SetFocus; end; {$ENDREGION} {$REGION 'Procedimentos para controle da venda'} procedure TFCaixa.InstanciaVendaAtual; var NfeNumeroVO: TNfeNumeroVO; begin try // instancia venda if not Assigned(Sessao.VendaAtual) then begin Sessao.VendaAtual := TNfeCabecalhoVO.Create; //Pega um número NfeNumeroVO := TNfeNumeroVO(TController.BuscarObjeto('NfeNumeroController.TNfeNumeroController', 'ConsultaObjeto', ['1=1'], 'GET')); //Gera a chave de acesso Sessao.VendaAtual.ChaveAcesso := IntToStr(Sessao.Configuracao.EmpresaVO.CodigoIbgeUf) + FormatDateTime('yy', Now) + FormatDateTime('mm', Now) + Sessao.Configuracao.EmpresaVO.Cnpj + '65' + NfeNumeroVO.Serie + StringOfChar('0', 9 - Length(IntToStr(NfeNumeroVO.Numero))) + IntToStr(NfeNumeroVO.Numero) + '1' + StringOfChar('0', 8 - Length(IntToStr(NfeNumeroVO.Numero))) + IntToStr(NfeNumeroVO.Numero); Sessao.VendaAtual.DigitoChaveAcesso := Modulo11(Sessao.VendaAtual.ChaveAcesso); Sessao.VendaAtual.UfEmitente := Sessao.Configuracao.EmpresaVO.CodigoIbgeUf; Sessao.VendaAtual.CodigoNumerico := StringOfChar('0', 8 - Length(IntToStr(NfeNumeroVO.Numero))) + IntToStr(NfeNumeroVO.Numero); Sessao.VendaAtual.NaturezaOperacao := 'VENDA'; Sessao.VendaAtual.CodigoModelo := '59'; Sessao.VendaAtual.Serie := NfeNumeroVO.Serie; Sessao.VendaAtual.Numero := StringOfChar('0', 9 - Length(IntToStr(NfeNumeroVO.Numero))) + IntToStr(NfeNumeroVO.Numero); Sessao.VendaAtual.DataHoraEmissao := Now; Sessao.VendaAtual.DataHoraEntradaSaida := Now; Sessao.VendaAtual.TipoOperacao := 1; Sessao.VendaAtual.CodigoMunicipio := Sessao.Configuracao.EmpresaVO.CodigoIbgeCidade; Sessao.VendaAtual.FormatoImpressaoDanfe := 4; Sessao.VendaAtual.TipoEmissao := 1; Sessao.VendaAtual.IdEmpresa := Sessao.Configuracao.EmpresaVO.Id; Sessao.VendaAtual.Ambiente := ObjetoNfeConfiguracaoVO.WebserviceAmbiente; Sessao.VendaAtual.FinalidadeEmissao := 1; Sessao.VendaAtual.ProcessoEmissao := ObjetoNfeConfiguracaoVO.ProcessoEmissao; Sessao.VendaAtual.VersaoProcessoEmissao := ObjetoNfeConfiguracaoVO.VersaoProcessoEmissao; Sessao.VendaAtual.ConsumidorPresenca := 1; end; finally FreeAndNil(NfeNumeroVO); end; end; procedure TFCaixa.LocalizaProduto; begin Application.CreateForm(TFImportaProduto, FImportaProduto); FImportaProduto.ShowModal; if (Sessao.StatusCaixa = scVendaEmAndamento) and (trim(EditCodigo.Text) <> '') then begin EditCodigo.SetFocus; IniciaVendaDeItens; end; end; procedure TFCaixa.IdentificaCliente; begin InstanciaVendaAtual; Application.CreateForm(TFIdentificaCliente, FIdentificaCliente); FIdentificaCliente.ShowModal; if Sessao.VendaAtual.NfeDestinatarioVO.CpfCnpj <> '' then begin if Sessao.StatusCaixa = scAberto then begin IniciaVenda; end; LabelCliente.Caption := 'Cliente: ' + Sessao.VendaAtual.NfeDestinatarioVO.Nome + ' - ' + Sessao.VendaAtual.NfeDestinatarioVO.CpfCnpj; LabelCliente.Repaint; end; end; procedure TFCaixa.IdentificaVendedor; var Vendedor: TVendedorVO; begin try if Sessao.StatusCaixa = scVendaEmAndamento then begin Application.CreateForm(TFImportaNumero, FImportaNumero); FImportaNumero.Caption := 'Identifica Vendedor'; FImportaNumero.LabelEntrada.Caption := 'Informe o código do vendedor'; try if (FImportaNumero.ShowModal = MROK) then begin Filtro := 'ID = ' + FImportaNumero.EditEntrada.Text; Vendedor := TVendedorVO(TController.BuscarObjeto('VendedorController.TVendedorController', 'ConsultaObjeto', [Filtro], 'GET')); if Assigned(Vendedor) then Sessao.VendaAtual.IdVendedor := Vendedor.Id else Application.MessageBox('Vendedor: código inválido ou inexistente.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; except end; end else Application.MessageBox('Não existe venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); finally FreeAndNil(Vendedor); end; end; procedure TFCaixa.IniciaVenda; begin Bobina.Items.Text := ''; if not Assigned(Sessao.Movimento) then Application.MessageBox('Não existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin // instancia venda InstanciaVendaAtual; ImprimeCabecalhoBobina; ParametrosIniciaisVenda; Sessao.StatusCaixa := scVendaEmAndamento; labelMensagens.Caption := 'Venda em andamento...'; Sessao.VendaAtual.IdNfceMovimento := Sessao.Movimento.Id; TController.ExecutarMetodo('VendaController.TVendaController', 'Insere', [Sessao.VendaAtual], 'PUT', 'Objeto'); Sessao.LiberaVendaAtual; Sessao.VendaAtual := TNfeCabecalhoVO(TController.ObjetoConsultado); EditCodigo.SetFocus; EditCodigo.SelectAll; edtNVenda.Caption := 'Venda nº ' + IntToStr(Sessao.VendaAtual.Id); edtNumeroNota.Caption := 'Cupom nº ' + Sessao.VendaAtual.Numero; end; end; procedure TFCaixa.ParametrosIniciaisVenda; begin TimerMarketing.Enabled := False; if FileExists(Sessao.Configuracao.CaminhoImagensProdutos + 'padrao.png') then imageProduto.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensProdutos + 'padrao.png') else imageProduto.Picture.LoadFromFile('Imagens\imgProdutos\padrao.png'); ItemCupom := 0; SubTotal := 0; TotalGeral := 0; ValorICMS := 0; end; procedure TFCaixa.ImprimeCabecalhoBobina; begin Bobina.Items.Add(StringOfChar('-', 48)); Bobina.Items.Add(' ** CUPOM ** '); Bobina.Items.Add(StringOfChar('-', 48)); Bobina.Items.Add('ITEM CÓDIGO DESCRIÇÃO '); Bobina.Items.Add('QTD. UN VL.UNIT.(R$) VL.ITEM(R$)'); Bobina.Items.Add(StringOfChar('-', 48)); end; procedure TFCaixa.IniciaVendaDeItens; var Unitario, Quantidade, Total: Extended; begin if not Assigned(Sessao.Movimento) then begin labelMensagens.Caption := 'CAIXA FECHADO'; IniciaMovimento; // se o caixa estiver fechado abre o iniciaMovimento Abort; end; if Sessao.MenuAberto = snNao then begin if Sessao.StatusCaixa = scAberto then begin IniciaVenda; end; if trim(EditCodigo.Text) <> '' then begin VendaDetalhe := TNfeDetalheVO.Create; DesmembraCodigoDigitado(trim(EditCodigo.Text)); Application.ProcessMessages; if Assigned(VendaDetalhe.ProdutoVO) then begin if VendaDetalhe.ProdutoVO.ValorVenda <= 0 then begin Application.MessageBox('Produto não pode ser vendido com valor zerado ou negativo!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditCodigo.SetFocus; EditCodigo.SelectAll; FreeAndNil(VendaDetalhe); Abort; end; labelMensagens.Caption := 'Venda em andamento...'; MensagemPersistente := labelMensagens.Caption; if ACBrInStore1.Peso > 0 then EditQuantidade.Value := ACBrInStore1.Peso; if ACBrInStore1.Total > 0 then EditQuantidade.Text := FormataFloat('Q', (ACBrInStore1.Total / VendaDetalhe.ProdutoVO.ValorVenda)); if (VendaDetalhe.ProdutoVO.UnidadeProdutoVO.PodeFracionar = 'N') and (Frac(StrToFloat(EditQuantidade.Text)) > 0) then begin Application.MessageBox('Produto não pode ser vendido com quantidade fracionada.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditQuantidade.Text := '1'; labelDescricaoProduto.Caption := ''; EditCodigo.Text := ''; EditCodigo.SetFocus; FreeAndNil(VendaDetalhe); end else begin EditUnitario.Text := FormataFloat('V', VendaDetalhe.ProdutoVO.ValorVenda); labelDescricaoProduto.Caption := VendaDetalhe.ProdutoVO.DescricaoPDV; // carrega imagem do produto if FileExists(Sessao.Configuracao.CaminhoImagensProdutos + VendaDetalhe.ProdutoVO.GTIN + '.jpg') then imageProduto.Picture.LoadFromFile(Sessao.Configuracao.CaminhoImagensProdutos + VendaDetalhe.ProdutoVO.GTIN + '.jpg') else imageProduto.Picture.LoadFromFile('Imagens\imgProdutos\padrao.png'); Unitario := EditUnitario.Value; Quantidade := EditQuantidade.Value; Total := TruncaValor(Unitario * Quantidade, Constantes.TConstantes.DECIMAIS_VALOR); EditTotalItem.Text := FormataFloat('V', Total); VendeItem; SubTotal := SubTotal + VendaDetalhe.ValorTotal; TotalGeral := TotalGeral + VendaDetalhe.ValorTotal; ValorICMS := ValorICMS + VendaDetalhe.NfeDetalheImpostoIcmsVO.ValorIcms; AtualizaTotais; EditCodigo.Clear; EditCodigo.SetFocus; EditQuantidade.Text := '1'; Application.ProcessMessages; end; // if (Produto.PodeFracionarUnidade = 'N') and (Frac(StrToFloat(EditQuantidade.Text))>0) then end else begin MensagemDeProdutoNaoEncontrado; end; // if Produto.Id <> 0 then end; // if trim(EditCodigo.Text) <> '' then end; // if Sessao.MenuAberto = 0 then end; procedure TFCaixa.ConsultaProduto(Codigo: String; Tipo: Integer); begin VendaDetalhe.ProdutoVO := TProdutoVO(TController.BuscarObjeto('ProdutoController.TProdutoController', 'ConsultaPorTipo', [Codigo, Tipo], 'GET')); end; procedure TFCaixa.MensagemDeProdutoNaoEncontrado; begin Application.MessageBox('Código não encontrado.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditQuantidade.Text := '1'; labelDescricaoProduto.Caption := ''; EditCodigo.SetFocus; EditCodigo.SelectAll; end; procedure TFCaixa.DesmembraCodigoDigitado(CodigoDeBarraOuDescricaoOuIdProduto: string); var IdentificadorBalanca, vCodDescrId: String; LengthInteiro, LengthCodigo: Integer; begin IdentificadorBalanca := Sessao.Configuracao.NfceConfiguracaoBalancaVO.Identificador; vCodDescrId := CodigoDeBarraOuDescricaoOuIdProduto; LengthInteiro := Length(DevolveInteiro(vCodDescrId)); LengthCodigo := Length(vCodDescrId); ACBrInStore1.ZerarDados; try if (LengthInteiro = LengthCodigo) and (LengthCodigo <= 4) and (BalancaLePeso = true) then begin ConsultaProduto(vCodDescrId, 1); if Assigned(VendaDetalhe.ProdutoVO) then exit; end; finally BalancaLePeso := False; end; if ((LengthInteiro = 13) and (LengthCodigo = 13)) or ((LengthInteiro = 14) and (LengthCodigo = 14)) then begin if (LengthInteiro = 13) and (IdentificadorBalanca = Copy(vCodDescrId, 1, 1)) then begin ACBrInStore1.Codificacao := trim(Sessao.Configuracao.NfceConfiguracaoBalancaVO.TipoConfiguracao); ACBrInStore1.Desmembrar(trim(vCodDescrId)); ConsultaProduto(ACBrInStore1.Codigo, 1); if Assigned(VendaDetalhe.ProdutoVO) then exit else ACBrInStore1.ZerarDados; end; ConsultaProduto(vCodDescrId, 2); if Assigned(VendaDetalhe.ProdutoVO) then exit; end; if LengthInteiro = LengthCodigo then begin ConsultaProduto(Copy(vCodDescrId, 1, 10), 4); if Assigned(VendaDetalhe.ProdutoVO) then exit; end else begin Application.CreateForm(TFImportaProduto, FImportaProduto); FImportaProduto.EditLocaliza.Text := vCodDescrId; FImportaProduto.ShowModal; if (Length(DevolveInteiro(EditCodigo.Text))) = (Length(trim(EditCodigo.Text))) then begin VendaDetalhe.ProdutoVO.Id := 0; ConsultaProduto(trim(EditCodigo.Text), 4); end else begin MensagemDeProdutoNaoEncontrado; Abort; end; end; end; procedure TFCaixa.EditCodigoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_RETURN: if trim(EditCodigo.Text) <> '' then IniciaVendaDeItens; end; end; procedure TFCaixa.EditCodigoKeyPress(Sender: TObject; var Key: Char); var Quantidade: Extended; begin if Key = '.' then Key := FormatSettings.DecimalSeparator; if (Key = #13) and (trim(EditCodigo.Text) = '') then begin Key := #0; Perform(Wm_NextDlgCtl, 0, 0); end; if Key = '*' then begin Key := #0; try Quantidade := StrToFloat(EditCodigo.Text); if (Quantidade <= 0) then begin Application.MessageBox('Quantidade inválida.', 'Erro', MB_OK + MB_ICONERROR); EditCodigo.Text := ''; EditQuantidade.Text := '1'; end else begin EditQuantidade.Text := EditCodigo.Text; EditCodigo.Text := ''; end; except Application.MessageBox('Quantidade inválida.', 'Erro', MB_OK + MB_ICONERROR); EditCodigo.Text := ''; EditQuantidade.Text := '1'; end; end; end; procedure TFCaixa.EditQuantidadeKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; Perform(Wm_NextDlgCtl, 0, 0); end; end; procedure TFCaixa.EditQuantidadeExit(Sender: TObject); begin if (EditQuantidade.Value <= 0) then begin Application.MessageBox('Quantidade inválida.', 'Erro', MB_OK + MB_ICONERROR); EditQuantidade.Value := 1; end; end; procedure TFCaixa.VendeItem; begin try CompoeItemParaVenda; if VendaDetalhe.GTIN = '' then begin Application.MessageBox('Produto com Código ou GTIN Não Definido!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditCodigo.SetFocus; EditCodigo.SelectAll; Dec(ItemCupom); FreeAndNil(VendaDetalhe); Abort; end; if VendaDetalhe.ProdutoVO.DescricaoPDV = '' then begin Application.MessageBox('Produto com Descrição Não Definida!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditCodigo.SetFocus; EditCodigo.SelectAll; Dec(ItemCupom); FreeAndNil(VendaDetalhe); Abort; end; if VendaDetalhe.ProdutoVO.UnidadeProdutoVO.Sigla = '' then begin Application.MessageBox('Produto com Unidade Não Definida!', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); EditUnitario.Text := '0'; EditTotalItem.Text := '0'; EditCodigo.SetFocus; EditCodigo.SelectAll; Dec(ItemCupom); FreeAndNil(VendaDetalhe); Abort; end; // Imposto VendaDetalhe.NfeDetalheImpostoIcmsVO.OrigemMercadoria := 0; //nacional VendaDetalhe.NfeDetalheImpostoIcmsVO.CstIcms := '00'; //nacional VendaDetalhe.NfeDetalheImpostoIcmsVO.ModalidadeBcIcms := 3; //valor da operação VendaDetalhe.NfeDetalheImpostoIcmsVO.AliquotaIcms := VendaDetalhe.ProdutoVO.AliquotaIcmsPaf; VendaDetalhe.NfeDetalheImpostoIcmsVO.BaseCalculoIcms := VendaDetalhe.ValorTotal; VendaDetalhe.NfeDetalheImpostoIcmsVO.ValorIcms := VendaDetalhe.ValorTotal * VendaDetalhe.ProdutoVO.AliquotaIcmsPaf / 100; TController.ExecutarMetodo('VendaController.TVendaController', 'InsereItem', [VendaDetalhe], 'PUT', 'Objeto'); FreeAndNil(VendaDetalhe); VendaDetalhe := TNfeDetalheVO(TController.ObjetoConsultado); Sessao.VendaAtual.ListaNfeDetalheVO.Add(VendaDetalhe); ImprimeItemBobina; Bobina.ItemIndex := Bobina.Items.Count - 1; finally end; end; procedure TFCaixa.CompoeItemParaVenda; begin inc(ItemCupom); VendaDetalhe.NumeroItem := ItemCupom; VendaDetalhe.IdProduto := VendaDetalhe.ProdutoVO.Id; VendaDetalhe.CFOP := Sessao.Configuracao.CFOP; VendaDetalhe.IdNfeCabecalho := Sessao.VendaAtual.Id; VendaDetalhe.CodigoProduto := VendaDetalhe.ProdutoVO.GTIN; VendaDetalhe.GTIN := VendaDetalhe.ProdutoVO.GTIN; VendaDetalhe.NomeProduto := VendaDetalhe.ProdutoVO.Nome; VendaDetalhe.Ncm := VendaDetalhe.ProdutoVO.Ncm; //VendaDetalhe.ExTipi := StrToInt(VendaDetalhe.ProdutoVO.ExTipi); VendaDetalhe.UnidadeComercial := VendaDetalhe.ProdutoVO.UnidadeProdutoVO.Sigla; VendaDetalhe.UnidadeTributavel := VendaDetalhe.ProdutoVO.UnidadeProdutoVO.Sigla; if Sessao.StatusCaixa = scVendaEmAndamento then begin VendaDetalhe.QuantidadeComercial := EditQuantidade.Value; VendaDetalhe.QuantidadeTributavel := EditQuantidade.Value; VendaDetalhe.ValorUnitarioComercial := EditUnitario.Value; VendaDetalhe.ValorUnitarioTributavel := EditUnitario.Value; VendaDetalhe.ValorBrutoProduto := ArredondaTruncaValor('A', VendaDetalhe.QuantidadeComercial * EditUnitario.Value, 2); VendaDetalhe.ValorSubtotal := EditTotalItem.Value; // EXERCICIO: implemente o desconto sobre o valor do item de acordo com a sua necessidade VendaDetalhe.ValorDesconto := 0; VendaDetalhe.ValorTotal := VendaDetalhe.ValorSubtotal - VendaDetalhe.ValorDesconto; end; end; procedure TFCaixa.ImprimeItemBobina; var Quantidade, Unitario, Total, Unidade: String; begin Quantidade := FloatToStrF(VendaDetalhe.QuantidadeComercial, ffNumber, 8, 3); Unitario := FloatToStrF(VendaDetalhe.ValorUnitarioComercial, ffNumber, 13, 2); Total := FloatToStrF(VendaDetalhe.ValorTotal, ffNumber, 14, 2); Bobina.Items.Add(StringOfChar('0', 3 - Length(IntToStr(ItemCupom))) + IntToStr(ItemCupom) + ' ' + VendaDetalhe.GTIN + StringOfChar(' ', 14 - Length(VendaDetalhe.GTIN)) + ' ' + Copy(VendaDetalhe.ProdutoVO.DescricaoPDV, 1, 28)); Unidade := trim(Copy(VendaDetalhe.ProdutoVO.UnidadeProdutoVO.Sigla, 1, 3)); Bobina.Items.Add(StringOfChar(' ', 8 - Length(Quantidade)) + Quantidade + ' ' + StringOfChar(' ', 3 - Length(Unidade)) + Unidade + ' x ' + StringOfChar(' ', 13 - Length(Unitario)) + Unitario + ' ' + StringOfChar(' ', 14 - Length(Total)) + Total); end; procedure TFCaixa.AtualizaTotais; var DescontoAcrescimo: Extended; begin Sessao.VendaAtual.ValorTotalProdutos := SubTotal; Sessao.VendaAtual.ValorDesconto := Desconto; Sessao.VendaAtual.ValorDespesasAcessorias := Acrescimo; Sessao.VendaAtual.ValorTotal := TotalGeral - Desconto + Acrescimo; Sessao.VendaAtual.BaseCalculoIcms := Sessao.VendaAtual.ValorTotal; Sessao.VendaAtual.ValorIcms := ValorICMS; DescontoAcrescimo := Acrescimo - Desconto; if DescontoAcrescimo < 0 then begin LabelDescontoAcrescimo.Caption := 'Desconto: R$ ' + FormatFloat('0.00', -DescontoAcrescimo); LabelDescontoAcrescimo.Font.Color := clRed; Sessao.VendaAtual.ValorDesconto := -DescontoAcrescimo; Sessao.VendaAtual.ValorDespesasAcessorias := 0; end else if DescontoAcrescimo > 0 then begin LabelDescontoAcrescimo.Caption := 'Acréscimo: R$ ' + FormatFloat('0.00', DescontoAcrescimo); LabelDescontoAcrescimo.Font.Color := clBlue; Sessao.VendaAtual.ValorDesconto := 0; Sessao.VendaAtual.ValorDespesasAcessorias := DescontoAcrescimo; end else begin LabelDescontoAcrescimo.Caption := ''; Acrescimo := 0; Desconto := 0; end; EditSubTotal.Text := FormatFloat('0.00', Sessao.VendaAtual.ValorTotalProdutos); labelTotalGeral.Caption := Format('%18.2n', [Sessao.VendaAtual.ValorTotal]); end; procedure TFCaixa.IniciaEncerramentoVenda; begin if Sessao.StatusCaixa = scVendaEmAndamento then begin if Sessao.VendaAtual.ListaNfeDetalheVO.Count > 0 then begin if Sessao.VendaAtual.ValorTotal <= 0 then begin if Application.MessageBox('Não existem itens para o fechamento da venda.' + #13 + #13 + 'Deseja cancelar o procedimento?', 'Cancelar a venda', Mb_YesNo + Mb_IconQuestion) = IdYes then CancelaVenda; Abort; end; Application.CreateForm(TFEfetuaPagamento, FEfetuaPagamento); FEfetuaPagamento.ShowModal; edtNVenda.Caption := ''; edtNumeroNota.Caption := ''; end else Application.MessageBox('A venda não contém itens.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end else Application.MessageBox('Não existe venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFCaixa.ConcluiEncerramentoVenda; var i: Integer; begin try GerarXmlSAT; FDataModule.ACBrSAT.EnviarDadosVenda(MemoXmlSAT.Text); if ExtratoResumido then FDataModule.ACBrSAT.ImprimirExtratoResumido else FDataModule.ACBrSAT.ImprimirExtrato; TController.ExecutarMetodo('VendaController.TVendaController', 'Altera', [Sessao.VendaAtual], 'POST', 'Boolean'); finally FreeAndNil(DavCabecalho); TelaPadrao; end; end; procedure TFCaixa.CancelaVenda; begin if not Assigned(Sessao.Movimento) then Application.MessageBox('Não existe um movimento aberto.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin Application.CreateForm(TFLoginGerenteSupervisor, FLoginGerenteSupervisor); try if (FLoginGerenteSupervisor.ShowModal = MROK) then begin if FLoginGerenteSupervisor.LoginOK then begin if Sessao.StatusCaixa = scVendaEmAndamento then begin if Application.MessageBox('Deseja cancelar a venda atual?', 'Pergunta do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then begin Sessao.StatusCaixa := scAberto; TelaPadrao; end; end else if (Sessao.StatusCaixa = scAberto) then begin if Application.MessageBox('Deseja cancelar o cupom anterior?', 'Pergunta do Sistema', Mb_YesNo + Mb_IconQuestion) = IdYes then begin try // EXERCICIO: Altere os dados da venda no banco e dados. // EXERCICIO: Realize os procedimentos de controle para que o cupom seja cancelado apenas uma vez. FDataModule.ACBrSAT.CancelarUltimaVenda; FDataModule.ACBrSAT.ImprimirExtratoCancelamento; Sessao.StatusCaixa := scAberto; TelaPadrao; except end; end; end; end else Application.MessageBox('Login - dados incorretos.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; finally if Assigned(FLoginGerenteSupervisor) then FLoginGerenteSupervisor.Free; end; end; end; procedure TFCaixa.CancelaItem; var cancela: Integer; begin if Sessao.StatusCaixa = scVendaEmAndamento then begin if Application.MessageBox('Tem certeza que deseja remover o item da nota fiscal?', 'Pergunta do Sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin Application.CreateForm(TFImportaNumero, FImportaNumero); FImportaNumero.Caption := 'Cancelar Item'; FImportaNumero.LabelEntrada.Caption := 'Informe o número do Item'; try if (FImportaNumero.ShowModal = MROK) then begin cancela := FImportaNumero.EditEntrada.AsInteger; if cancela > 0 then begin if cancela <= Sessao.VendaAtual.ListaNfeDetalheVO.Count then begin TController.ExecutarMetodo('VendaController.TVendaController', 'CancelaItemVenda', [Cancela], 'POST', 'Boolean'); Bobina.Items.Add(StringOfChar('*', 48)); Bobina.Items.Add(StringOfChar('0', 3 - Length(IntToStr(cancela))) + IntToStr(cancela) + ' ' + VendaDetalhe.GTIN + StringOfChar(' ', 14 - Length(VendaDetalhe.GTIN)) + ' ' + Copy(VendaDetalhe.ProdutoVO.DescricaoPDV, 1, 28)); Bobina.Items.Add('ITEM CANCELADO'); Bobina.Items.Add(StringOfChar('*', 48)); SubTotal := SubTotal - VendaDetalhe.ValorTotal; TotalGeral := TotalGeral - VendaDetalhe.ValorTotal; ValorICMS := ValorICMS - VendaDetalhe.NfeDetalheImpostoIcmsVO.ValorIcms; // cancela possíveis descontos ou acrescimos Desconto := 0; Acrescimo := 0; Bobina.ItemIndex := Bobina.Items.Count - 1; AtualizaTotais; end else Application.MessageBox('O item solicitado não existe na venda atual.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end else Application.MessageBox('Informe um número de item válido.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; finally if Assigned(FImportaNumero) then FImportaNumero.Free; end; end; end else Application.MessageBox('Não existe venda em andamento.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION); end; procedure TFCaixa.RecuperarVenda; var i: Integer; begin Application.CreateForm(TFListaVendas, FListaVendas); FListaVendas.ShowModal; if FListaVendas.Confirmou then begin Filtro := 'ID = ' + FListaVendas.CDSNFCe.FieldByName('ID').AsString; Sessao.VendaAtual := TNfeCabecalhoVO(TController.BuscarObjeto('VendaController.TVendaController', 'ConsultaObjeto', [Filtro], 'GET')); if Assigned(Sessao.VendaAtual) then begin ImprimeCabecalhoBobina; ParametrosIniciaisVenda; Sessao.StatusCaixa := scRecuperandoVenda; labelMensagens.Caption := 'Venda recuperada em andamento..'; for i := 0 to Sessao.VendaAtual.ListaNfeDetalheVO.Count - 1 do begin VendaDetalhe := Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]; ConsultaProduto(VendaDetalhe.GTIN, 2); CompoeItemParaVenda; ImprimeItemBobina; if VendaDetalhe.NfeDetalheImpostoIcmsVO.Id = 0 then begin // Imposto VendaDetalhe.NfeDetalheImpostoIcmsVO.OrigemMercadoria := 0; //nacional VendaDetalhe.NfeDetalheImpostoIcmsVO.CstIcms := '00'; //nacional VendaDetalhe.NfeDetalheImpostoIcmsVO.ModalidadeBcIcms := 3; //valor da operação VendaDetalhe.NfeDetalheImpostoIcmsVO.AliquotaIcms := VendaDetalhe.ProdutoVO.AliquotaIcmsPaf; VendaDetalhe.NfeDetalheImpostoIcmsVO.BaseCalculoIcms := VendaDetalhe.ValorTotal; VendaDetalhe.NfeDetalheImpostoIcmsVO.ValorIcms := VendaDetalhe.ValorTotal * VendaDetalhe.ProdutoVO.AliquotaIcmsPaf / 100; end; SubTotal := SubTotal + VendaDetalhe.ValorTotal; TotalGeral := TotalGeral + VendaDetalhe.ValorTotal; ValorICMS := ValorICMS + VendaDetalhe.NfeDetalheImpostoIcmsVO.ValorIcms; AtualizaTotais; end; edtNVenda.Caption := 'Venda nº ' + IntToStr(Sessao.VendaAtual.Id); edtNumeroNota.Caption := 'Cupom nº ' + Sessao.VendaAtual.Numero; Bobina.ItemIndex := Bobina.Items.Count - 1; Sessao.StatusCaixa := scVendaEmAndamento; end; end; end; procedure TFCaixa.DesabilitaControlesVenda; begin EditCodigo.Enabled := False; EditQuantidade.Enabled := False; EditUnitario.Enabled := False; EditTotalItem.Enabled := False; EditSubTotal.Enabled := False; Bobina.Enabled := False; panelBotoes.Enabled := False; FCaixa.KeyPreview := False; end; procedure TFCaixa.HabilitaControlesVenda; begin EditCodigo.Enabled := true; EditQuantidade.Enabled := true; EditUnitario.Enabled := true; EditTotalItem.Enabled := true; EditSubTotal.Enabled := true; Bobina.Enabled := true; panelBotoes.Enabled := true; FCaixa.KeyPreview := true; end; {$ENDREGION} {$REGION 'Demais procedimentos para o SAT'} procedure TFCaixa.ConsultaStatusOperacional; begin Application.CreateForm(TFStatusOperacional, FStatusOperacional); FStatusOperacional.ShowModal; end; procedure TFCaixa.GerarXmlSAT; var i: Integer; TotalItem, TotalProdutos, TotalImpostoAproximado: Double; begin try FDataModule.ACBrSAT.InicializaCFe; with FDataModule.ACBrSAT.CFe do begin ide.numeroCaixa := FDataModule.ACBrSAT.Config.ide_numeroCaixa; { Destinatario } Dest.CNPJCPF := Sessao.VendaAtual.NfeDestinatarioVO.CpfCnpj; Dest.xNome := Sessao.VendaAtual.NfeDestinatarioVO.Nome; Entrega.xLgr := Sessao.VendaAtual.NfeDestinatarioVO.Logradouro; Entrega.nro := Sessao.VendaAtual.NfeDestinatarioVO.Numero; Entrega.xCpl := Sessao.VendaAtual.NfeDestinatarioVO.Complemento; Entrega.xBairro := Sessao.VendaAtual.NfeDestinatarioVO.Bairro; Entrega.xMun := Sessao.VendaAtual.NfeDestinatarioVO.NomeMunicipio; Entrega.Uf := Sessao.VendaAtual.NfeDestinatarioVO.Uf; { Detalhe } for i := 0 to Sessao.VendaAtual.ListaNfeDetalheVO.Count - 1 do begin with Det.Add do begin nItem := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).NumeroItem; Prod.cProd := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).Gtin; Prod.cEAN := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).Gtin; Prod.xProd := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).NomeProduto; Prod.Ncm := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).Ncm; Prod.Cfop := IntToStr(TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).Cfop); Prod.indRegra := irTruncamento; Prod.uCom := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).UnidadeComercial; Prod.qCom := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).QuantidadeComercial; Prod.vUnCom := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).ValorUnitarioComercial; Prod.vDesc := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).ValorDesconto; Prod.vOutro := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).ValorOutrasDespesas; infAdProd := TNfeDetalheVO(Sessao.VendaAtual.ListaNfeDetalheVO.Items[i]).InformacoesAdicionais; // definir se vira do cadastro de produtos ou se sera digitada, por exemplo informaçao de lotes { Detalhes -- Impostos } Imposto.ICMS.orig := oeNacional; if FDataModule.ACBrSAT.Config.emit_cRegTrib = RTRegimeNormal then begin Imposto.ICMS.CST := cst00; Imposto.ICMS.pICMS := 18; end else begin Imposto.ICMS.CSOSN := csosn102; end; Imposto.PIS.CST := pis49; Imposto.PIS.vBC := 0; Imposto.PIS.pPIS := 0; Imposto.COFINS.CST := cof49; Imposto.COFINS.vBC := 0; Imposto.COFINS.pCOFINS := 0; // imposto aproximado TotalItem := (Prod.qCom * Prod.vUnCom); Imposto.vItem12741 := TotalItem * 0.12; TotalProdutos := TotalProdutos + TotalItem; TotalImpostoAproximado := TotalImpostoAproximado + Imposto.vItem12741; end; // with Det.Add do end; // for i := 0 to ListaNFeDetalhe.Count - 1 do } Total.DescAcrEntr.vDescSubtot := Sessao.VendaAtual.ValorDesconto; Total.vCFeLei12741 := TotalImpostoAproximado; // EXERCICIO: pegue os pagamentos utilizados na venda e informe para a NFCe with Pagto.Add do begin cMP := mpDinheiro; vMP := Sessao.VendaAtual.ValorTotal; end; InfAdic.infCpl := 'SAT - T2Ti.COM'; end; MemoXmlSAT.Lines.Text := FDataModule.ACBrSAT.CFe.GerarXML(True); except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro ao gerar o SAT.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; end; {$ENDREGION} {$REGION 'Aparência e controle dos painéis com as funções do programa - F1 a F12'} procedure TFCaixa.panelF1MouseEnter(Sender: TObject); begin panelF1.BevelOuter := bvRaised; panelF1.BevelWidth := 2; end; procedure TFCaixa.panelF1MouseLeave(Sender: TObject); begin panelF1.BevelOuter := bvNone; end; procedure TFCaixa.panelF1Click(Sender: TObject); begin IdentificaCliente; end; procedure TFCaixa.panelF2MouseEnter(Sender: TObject); begin panelF2.BevelOuter := bvRaised; panelF2.BevelWidth := 2; end; procedure TFCaixa.panelF2MouseLeave(Sender: TObject); begin panelF2.BevelOuter := bvNone; end; procedure TFCaixa.panelF2Click(Sender: TObject); begin AcionaMenuPrincipal; end; procedure TFCaixa.panelF3MouseEnter(Sender: TObject); begin panelF3.BevelOuter := bvRaised; panelF3.BevelWidth := 2; end; procedure TFCaixa.panelF3MouseLeave(Sender: TObject); begin panelF3.BevelOuter := bvNone; end; procedure TFCaixa.panelF3Click(Sender: TObject); begin AcionaMenuOperacoes; end; procedure TFCaixa.panelF4MouseEnter(Sender: TObject); begin panelF4.BevelOuter := bvRaised; panelF4.BevelWidth := 2; end; procedure TFCaixa.panelF4MouseLeave(Sender: TObject); begin panelF4.BevelOuter := bvNone; end; procedure TFCaixa.panelF4Click(Sender: TObject); begin ConsultaStatusOperacional; end; procedure TFCaixa.panelF5MouseEnter(Sender: TObject); begin panelF5.BevelOuter := bvRaised; panelF5.BevelWidth := 2; end; procedure TFCaixa.panelF5MouseLeave(Sender: TObject); begin panelF5.BevelOuter := bvNone; end; procedure TFCaixa.panelF5Click(Sender: TObject); begin RecuperarVenda; end; procedure TFCaixa.panelF6MouseEnter(Sender: TObject); begin panelF6.BevelOuter := bvRaised; panelF6.BevelWidth := 2; end; procedure TFCaixa.panelF6MouseLeave(Sender: TObject); begin panelF6.BevelOuter := bvNone; end; procedure TFCaixa.panelF6Click(Sender: TObject); begin LocalizaProduto; end; procedure TFCaixa.panelF7MouseEnter(Sender: TObject); begin panelF7.BevelOuter := bvRaised; panelF7.BevelWidth := 2; end; procedure TFCaixa.panelF7MouseLeave(Sender: TObject); begin panelF7.BevelOuter := bvNone; end; procedure TFCaixa.panelF7Click(Sender: TObject); begin IniciaEncerramentoVenda; end; procedure TFCaixa.panelF8MouseEnter(Sender: TObject); begin panelF8.BevelOuter := bvRaised; panelF8.BevelWidth := 2; end; procedure TFCaixa.panelF8MouseLeave(Sender: TObject); begin panelF8.BevelOuter := bvNone; end; procedure TFCaixa.panelF8Click(Sender: TObject); begin CancelaItem; end; procedure TFCaixa.panelF9MouseEnter(Sender: TObject); begin panelF9.BevelOuter := bvRaised; panelF9.BevelWidth := 2; end; procedure TFCaixa.panelF9MouseLeave(Sender: TObject); begin panelF9.BevelOuter := bvNone; end; procedure TFCaixa.panelF9Click(Sender: TObject); begin CancelaVenda; end; procedure TFCaixa.panelF10MouseEnter(Sender: TObject); begin panelF10.BevelOuter := bvRaised; panelF10.BevelWidth := 2; end; procedure TFCaixa.panelF10MouseLeave(Sender: TObject); begin panelF10.BevelOuter := bvNone; end; procedure TFCaixa.panelF10Click(Sender: TObject); begin DescontoOuAcrescimo; end; procedure TFCaixa.panelF11MouseEnter(Sender: TObject); begin panelF11.BevelOuter := bvRaised; panelF11.BevelWidth := 2; end; procedure TFCaixa.panelF11MouseLeave(Sender: TObject); begin panelF11.BevelOuter := bvNone; end; procedure TFCaixa.panelF11Click(Sender: TObject); begin IdentificaVendedor; end; procedure TFCaixa.panelF12MouseEnter(Sender: TObject); begin panelF12.BevelOuter := bvRaised; panelF12.BevelWidth := 2; end; procedure TFCaixa.panelF12MouseLeave(Sender: TObject); begin panelF12.BevelOuter := bvNone; end; procedure TFCaixa.panelF12Click(Sender: TObject); begin Close; end; {$ENDREGION} {$REGION 'Procedimentos para ler peso direto das balanças componente ACBrBal'} procedure TFCaixa.ConectaComBalanca; // novo procedimento balança begin // se houver conecção aberta, Fecha a conecção if ACBrBAL1.Ativo then ACBrBAL1.Desativar; // configura porta de comunicação ACBrBAL1.Modelo := TACBrBALModelo(Sessao.Configuracao.NfceConfiguracaoBalancaVO.Modelo); ACBrBAL1.Device.HandShake := TACBrHandShake(Sessao.Configuracao.NfceConfiguracaoBalancaVO.HandShake); ACBrBAL1.Device.Parity := TACBrSerialParity(Sessao.Configuracao.NfceConfiguracaoBalancaVO.Parity); ACBrBAL1.Device.Stop := TACBrSerialStop(Sessao.Configuracao.NfceConfiguracaoBalancaVO.StopBits); ACBrBAL1.Device.Data := Sessao.Configuracao.NfceConfiguracaoBalancaVO.DataBits; ACBrBAL1.Device.Baud := Sessao.Configuracao.NfceConfiguracaoBalancaVO.BaudRate; ACBrBAL1.Device.Porta := Sessao.Configuracao.NfceConfiguracaoBalancaVO.Porta; // Conecta com a balança ACBrBAL1.Ativar; end; procedure TFCaixa.ConectaComLeitorSerial; begin // se houver conecção aberta, Fecha a conecção if ACBrLCB1.Ativo then ACBrBAL1.Desativar; // configura porta de comunicação ACBrLCB1.Porta := Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Porta; ACBrLCB1.Device.Baud := Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Baud; ACBrLCB1.Sufixo := Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Sufixo; ACBrLCB1.Intervalo := Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Intervalo; ACBrLCB1.Device.Data := Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.DataBits; ACBrLCB1.Device.Parity := TACBrSerialParity(Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.Parity); if Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.HardFlow = 'N' then ACBrLCB1.Device.HardFlow := False else ACBrLCB1.Device.HardFlow := true; if Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.SoftFlow = 'N' then ACBrLCB1.Device.SoftFlow := False else ACBrLCB1.Device.SoftFlow := true; ACBrLCB1.Device.HandShake := TACBrHandShake(Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.HandShake); ACBrLCB1.Device.Stop := TACBrSerialStop(Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.StopBits); if Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.UsarFila = 'S' Then ACBrLCB1.UsarFila := true else ACBrLCB1.UsarFila := False; if Sessao.Configuracao.NfceConfiguracaoLeitorSerVO.ExcluirSufixo = 'S' then ACBrLCB1.ExcluirSufixo := true else ACBrLCB1.ExcluirSufixo := False; ACBrLCB1.Ativar; end; procedure TFCaixa.ACBrBAL1LePeso(Peso: Double; Resposta: AnsiString); var valid: Integer; begin EditCodigo.Text := FormatFloat('##0.000', Peso) + '*'; if Peso > 0 then begin labelMensagens.Caption := 'Leitura da Balança OK !'; EditQuantidade.Text := FormatFloat('##0.000', Peso); EditCodigo.SetFocus; end else begin valid := Trunc(ACBrBAL1.UltimoPesoLido); case valid of 0: labelMensagens.Caption := 'Coloque o produto sobre a Balança!'; -1: labelMensagens.Caption := 'Tente Nova Leitura'; -2: labelMensagens.Caption := 'Peso Negativo !'; -10: labelMensagens.Caption := 'Sobrepeso !'; end; end; end; {$ENDREGION} end.
UNIT RT_Watch; INTERFACE FUNCTION Hex(Value : Byte) : STRING; IMPLEMENTATION USES Crt; VAR OldExit : Pointer; {====================================================================} FUNCTION Hex(Value:byte) : STRING; CONST HexTable : ARRAY[0..15] OF Char=('0','1','2','3','4','5','6','7', '8','9','A','B','C','D','E','F'); VAR HexStr : STRING; BEGIN HexStr[2] := HexTable[Value AND $0F]; HexStr[1] := HexTable[Value AND $F0 DIV 16]; HexStr[0] := #2; Hex := HexStr; END; PROCEDURE RunTimeExitProc; FAR; VAR Message : STRING; BEGIN IF ErrorAddr <> NIL THEN BEGIN ClrScr; TextColor(LightRed); WriteLn(^j^j^j^j'RUNTIME WATCHER v1.0 MJ (C) 2003'); TextColor(Red+Blink); WriteLn('Fehler gefunden...'); TextColor(White); CASE ExitCode OF 2 : Message := 'Datei wurde nicht gefunden'; 3 : Message := 'Verzeichnispfad wurde nicht gefunden'; 4 : Message := 'Zu viele ge”ffnete Dateien'; 5 : Message := 'Ben”tige Dateizugriff'; 6 : Message := 'Falscher Dateizugriff'; 8 : Message := 'Ungengend Speicher'; 12 : Message := 'Ungltiger Dateizugriffscode'; 15 : Message := 'Ungltige Laufwerksangabe'; 16 : Message := 'Datei kann nicht bewegt werden'; 17 : Message := 'Datei kann nicht umbenannt werden'; 100 : Message := 'Lesefehler'; 100 : Message := 'Schreibfehler'; 102 : Message := 'Datei nicht zugewiesen'; 103 : Message := 'Datei nicht ge”ffnet'; 104 : Message := 'Datei nur fr Schreibzugriffe ge”ffnet'; 105 : Message := 'Datei nur fr Lesezugriffe ge”ffnet'; 106 : Message := 'Ungltiges Zahlenformat'; 150 : Message := 'Datentr„ger ist schreibgeschtzt'; 151 : Message := 'Unbekannte Einheit'; 152 : Message := 'Datentr„ger nicht fertig'; 153 : Message := 'Ungekannter Befehl'; 154 : Message := 'CRC Fehler in Daten'; 155 : Message := 'Datentr„ger m”glicherweise besch„digt'; 156 : Message := 'Schreibfehler'; 157 : Message := 'Unbekannter Datentr„ger'; 158 : Message := 'Sektor nicht gefunden'; 159 : Message := 'Papier fehlt im Drucker'; 160 : Message := 'Allgemeiner Schreibfehler'; 161 : Message := 'Allgemeiner Lesefehler'; 162 : Message := 'Allgemeiner Hardware-Fehler'; 200 : Message := 'Division durch Null'; 201 : Message := 'Range check error'; 202 : Message := 'Stack-šberlauf'; 203 : Message := 'Heap-šberlauf'; 204 : Message := 'Ungltiger Zeiger-Ausfhrung'; 205 : Message := 'Kommazahlen-šberlauf'; 206 : Message := 'Kommazahlen-Unterlauf'; 207 : Message := 'Ungltiger Rechen-Operation'; 208 : Message := 'Overlay manager not installed'; 209 : Message := 'Overlay file read error'; 210 : Message := 'Object not initialized'; 211 : Message := 'Call to abstract method'; 212 : Message := 'Stream register error'; 213 : Message := 'Collection index out of range'; 214 : Message := 'Collection overflow error'; END; Writeln('Error: ',ExitCode, ' Segment: ',Hex(Seg(ErrorAddr^)), ' Offset: ',Hex(Ofs(ErrorAddr^)), ' ',Message); ErrorAddr := NIL; ExitCode := 1; END; ExitProc := OldExit; END; BEGIN OldExit := ExitProc; ExitProc := @RunTimeExitProc; END.
unit LastDisassembleData; {$mode delphi} interface uses Classes, SysUtils, commonTypeDefs; type TDisAssemblerValueType=(dvtNone=0, dvtAddress=1, dvtValue=2); TDisassemblerClass=(dcX86, dcArm, dcArm64, dcThumb); TLastDisassembleData=record address: PtrUint; prefix: string; prefixsize: integer; opcode: string; parameters: string; description: string; commentsoverride: string; Bytes: array of byte; SeperatorCount: integer; Seperators: Array [0..5] of integer; //an index in the byte array describing the seperators (prefix/instruction/modrm/sib/extra) modrmValueType: TDisAssemblerValueType; modrmValue: ptrUint; parameterValueType: TDisAssemblerValueType; parameterValue: ptrUint; // ValueType: TValueType; //if it's not unknown the value type will say what type of value it is (e.g for the FP types) datasize: integer; isfloat: boolean; //True if the data it reads/writes is a float (only when sure) isfloat64: boolean; iscloaked: boolean; hasSib: boolean; sibIndex: integer; sibScaler: integer; isjump: boolean; //set for anything that can change eip/rip iscall: boolean; //set if it's a call isret: boolean; //set if it's a ret isrep: boolean; isconditionaljump: boolean; //set if it's only effective when an conditon is met willJumpAccordingToContext: boolean; //only valid if a context was provided with the disassembler and isconditionaljump is true riprelative: integer; //0 or contains the offset where the rip relative part of the code is Disassembler: TDisassemblerClass; //todo: add an isreader/iswriter //and what registers/flags it could potentially access/modify end; PLastDisassembleData=^TLastDisassembleData; implementation end.
{AUTEUR : FRANCKY23012301 - 2008 ------- Gratuit pour une utilisation non commerciale} unit BrowserTracks; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, StdCtrls, Dialogs; type TBrowserTracks = class; TBrTrackCnt = class; {>>TITLE} TBrPanelTitle = class(TCustomControl) private fColorTitle:TColor; fColorSubTitle:TColor; fColorRectTitle:TColor; fTitle:String; fSubTitle:String; Procedure setColorTitle(Value:TColor); Procedure setColorSubTitle(Value:TColor); Procedure setColorRectTitle(Value:TColor); Procedure SetTitle(Value:String); Procedure SetSubTitle(Value:String); protected procedure Paint; override; procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property ColorTitle:TColor Read fColorTitle Write SetColorTitle; Property ColorSubTitle:TColor Read fColorSubTitle Write SetColorSubTitle; Property ColorRectTitle:TColor Read fColorRectTitle Write SetColorRectTitle; Property Title:String Read fTitle Write SetTitle; Property SubTitle:String Read fSubTitle Write SetSubTitle; end; {>>BrCstButton} TBrCstButton = class(TCustomControl) private fColorLine:TColor; fColorTop:TColor; fColorBottom:TColor; fCaption:String; fSwitchActif:Boolean; fPushed:Boolean; Procedure SetColorLine(Value:TColor); Procedure SetColorTop(Value:TColor); Procedure SetColorBottom(Value:TColor); Procedure SetCaption(Value:String); Procedure DrawBorder; Procedure SetPushed(Value:Boolean); protected procedure Paint; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property ColorLine:TColor Read fColorLine Write SetColorLine; Property ColorTop:TColor Read fColorTop Write SetColorTop; Property ColorBottom:TColor Read fColorBottom Write SetColorBottom; Property Pushed:Boolean Read fPushed Write SetPushed; Property SwitchActif:Boolean Read fSwitchActif Write fSwitchActif; Property Tag; Property Enabled; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnClick; Property OnDblClick; Property Caption : String Read fCaption Write SetCaption; Property Font; end; {>>BrPanelTrack} TTrackType=(TtMidi,TtWav); TBrPanelTrack = class(TCustomControl) private fTypeTrack:TTrackType; fIndex:Integer; fActive:Boolean; fEdit:TEdit; fOpenBt:TBrCstButton; fAcquisitionBt:TBrCstButton; fWriteBt:TBrCstButton; fReadBt:TBrCstButton; fSoloBt:TBrCstButton; fMuteBt:TBrCstButton; Procedure SetTypeTrack(Value:TTrackType); Procedure SetIndex(Value:Integer); Procedure SetActive(Value:Boolean); Procedure DrawTypeArea; Procedure DrawTypeLogo; Procedure DrawCircle(X,Y,Width,Height:Integer); Procedure CreateButton(var Button:TBrCstButton;BtLeft,BtTop:Integer; BtName,BtCaption:String; ToSwitch:Boolean); Procedure EditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); protected procedure Paint; override; procedure Resize; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; public Owner : TPersistent; ItemIndex:Integer; constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Edit:TEdit Read fEdit Write fEdit; property OpenBt:TBrCstButton Read fOpenBt Write fOpenBt; property AcquisitionBt:TBrCstButton Read fAcquisitionBt Write fAcquisitionBt; property WriteBt:TBrCstButton Read fWriteBt Write fWriteBt; property ReadBt:TBrCstButton Read fReadBt Write fReadBt; property SoloBt:TBrCstButton Read fSoloBt Write fSoloBt; property MuteBt:TBrCstButton Read fMuteBt Write fMuteBt; Property TypeTrack:TTrackType Read fTypeTrack Write SetTypeTrack Default TtWav; Property TracksIndex:Integer Read fIndex Write SetIndex; Property Active:Boolean Read fActive Write SetActive; end; {>>TRACKS} TBrTrack=class(TCollectionItem) Private fOnChange: TNotifyEvent; fBrPanelTrack:TBrPanelTrack; fCollection : TCollection; protected function GetDisplayName: string; override; procedure AssignTo(Dest : TPersistent); override; procedure Change; virtual; property Collection : TCollection read fCollection write fCollection; public Owner : TPersistent; procedure Assign(Source : TPersistent); override; constructor Create(ACollection: TCollection); override; destructor Destroy; override; Published Property BrPanelTrack:TBrPanelTrack Read fBrPanelTrack Write fBrPanelTrack; property OnChange :TNotifyEvent read fOnChange write fOnChange; end; {>>TRACKSCNT} TBrTrackCnt = class(TOwnedCollection) Private fOwner : TPersistent; protected function GetOwner: TPersistent; override; function GetItem(Index: integer): TBrTrack; procedure SetItem(Index: integer; Value: TBrTrack); public ItemIndex:Integer; constructor Create(AOwner: TBrowserTracks); function Add: TBrTrack; property Items[Index: integer]: TBrTrack Read GetItem Write SetItem; end; {EVENEMENTS} TOpen_Event = procedure(Sender: TObject) of object; TAcquisition_Event = procedure(Sender: TObject) of object; TWrite_Event = procedure(Sender: TObject) of object; TRead_Event = procedure(Sender: TObject) of object; TSolo_Event = procedure(Sender: TObject) of object; TMute_Event = procedure(Sender: TObject) of object; {>>BrowserTracks} TBrowserTracks = class(TCustomControl) private fBrPanelTitle:TBrPanelTitle; fBrTracksCnt:TBrTrackCnt; fOnOpen_Event: TNotifyEvent; fOnAcquisition_Event: TNotifyEvent; fOnWrite_Event: TNotifyEvent; fOnRead_Event: TNotifyEvent; fOnSolo_Event: TNotifyEvent; fOnMute_Event: TNotifyEvent; procedure SetOnOpen_Event(Event : TNotifyEvent); procedure SetOnAcquisition_Event(Event : TNotifyEvent); procedure SetOnWrite_Event(Event : TNotifyEvent); procedure SetOnRead_Event(Event : TNotifyEvent); procedure SetOnSolo_Event(Event : TNotifyEvent); procedure SetOnMute_Event(Event : TNotifyEvent); protected procedure Paint; override; procedure Resize; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property BrPanelTitle:TBrPanelTitle Read fBrPanelTitle Write fBrPanelTitle; Property BrTracksCnt:TBrTrackCnt Read fBrTracksCnt Write fBrTracksCnt; property Open_Event: TNotifyEvent Read fOnOpen_Event Write SetOnOpen_Event; property Acquisition_Event: TNotifyEvent Read fOnAcquisition_Event Write SetOnAcquisition_Event; property Write_Event: TNotifyEvent Read fOnWrite_Event Write SetOnWrite_Event; property Read_Event: TNotifyEvent Read fOnRead_Event Write SetOnRead_Event; property Solo_Event: TNotifyEvent Read fOnSolo_Event Write SetOnSolo_Event; property Mute_Event: TNotifyEvent Read fOnMute_Event Write SetOnMute_Event; Property OnClick; Property OnDblClick; end; procedure Register; implementation procedure Register; begin RegisterComponents('Music_Pro', [TBrowserTracks]); end; {>>TITLE} constructor TBrPanelTitle.Create(AOwner: TComponent); begin inherited Create(AOwner); fColorRectTitle:=$00935F42; Title:='MUSIC PRO'; fColorTitle:=$00C5C5C5; SubTitle:='Browser'; fColorSubTitle:=$0000BB00; DoubleBuffered:=True; end; destructor TBrPanelTitle.Destroy; begin inherited; end; Procedure TBrPanelTitle.setColorTitle(Value:TColor); Begin fColorTitle:=Value; Invalidate; End; Procedure TBrPanelTitle.setColorSubTitle(Value:TColor); Begin fColorSubTitle:=Value; Invalidate; End; Procedure TBrPanelTitle.setColorRectTitle(Value:TColor); Begin fColorRectTitle:=Value; Invalidate; End; Procedure TBrPanelTitle.SetTitle(Value:String); Begin fTitle:=Value; Invalidate; End; Procedure TBrPanelTitle.SetSubTitle(Value:String); Begin fSubTitle:=Value; Invalidate; End; procedure TBrPanelTitle.Resize; Begin Width:=209; If Height<49 Then Height:=49; Invalidate; End; procedure TBrPanelTitle.Paint; Var RectTitle:TRect; WidthString,HeightString,LeftString,TopString:Integer; Begin InHerited; With Canvas Do Begin Brush.Style:=BsClear; With RectTitle Do Begin Left:=1; Right:=Self.Width; Top:=1; Bottom:=49; Brush.Color:=Self.fColorRectTitle; Pen.Color:=ClBlack; Pen.Width:=2; Rectangle(RectTitle); Font.Name:='ARIAL'; Font.Size:=16; Font.Color:=fColorTitle; LeftString:=Round(0.05*Self.Width); TopString:=Pen.Width; TextOut(LeftString,TopString,fTitle); Font.Name:='Comic Sans MS'; Font.Size:=13; Font.Color:=Self.fColorSubTitle; WidthString:=TextWidth(fSubTitle); HeightString:=TextHeight(fSubTitle); LeftString:=Self.Width-WidthString-10; TopString:=Bottom-Pen.Width-HeightString; TextOut(LeftString,TopString,fSubTitle); End; End End; {>>BrCstButton} constructor TBrCstButton.Create(AOwner: TComponent); begin inherited Create(AOwner); fPushed:=False; DoubleBuffered:=True; end; destructor TBrCstButton.Destroy; begin inherited; end; Procedure TBrCstButton.SetColorLine(Value:TColor); begin fColorLine:=Value; Invalidate; end; Procedure TBrCstButton.SetColorTop(Value:TColor); begin Self.fColorTop:=Value; Self.Invalidate; end; Procedure TBrCstButton.SetColorBottom(Value:TColor); begin fColorBottom:=Value; Invalidate; end; Procedure TBrCstButton.SetCaption(Value:String); begin fCaption:=Value; Invalidate; end; Procedure TBrCstButton.SetPushed(Value:Boolean); begin fPushed:=Value; Invalidate; end; procedure TBrCstButton.Paint; Var RectTop,RectBottom : TRect; HeightCaption, WidthCaption:Integer; Begin InHerited; DrawBorder; With Canvas Do Begin Font:=Self.Font; With RectTop Do Begin Top:=6; Bottom:=Self.Height Div 2 ; Left:=6; Right:=Self.Width-6; Brush.Color:=fColorTop; Pen.Color:=fColorTop; Rectangle(RectTop); End; With RectBottom Do Begin Top:=Self.Height Div 2; Bottom:=Self.Height-6; Left:=6; Right:=Self.Width-6; Brush.Color:=fColorBottom; Pen.Color:=fColorBottom; Rectangle(RectBottom ); End; Brush.Color:=fColorLine; Pen.Color:=fColorLine; Pen.Width:=2; MoveTo(5,Height Div 2); LineTo(Width-7,Height Div 2); HeightCaption:=TextHeight(Caption); WidthCaption:=TextWidth(Caption); Brush.Style:=BsClear; TextOut((Width - WidthCaption) Div 2,(Height - HeightCaption) Div 2, Caption); End; End; Procedure TBrCstButton.DrawBorder; Var LeftColor, RightColor:TColor; UpperCorner,LowerCorner:Array [0..2] Of TPoint; Begin If Not fPushed Then Begin LeftColor:=ClWhite; RightColor:=$00657271; End Else Begin LeftColor:=$00657271; RightColor:=ClWhite; End; With Self.Canvas Do Begin Pen.Width:=2; UpperCorner[0]:=Point(Pen.Width,Height-Pen.Width); UpperCorner[1]:=Point(Pen.Width,Pen.Width); UpperCorner[2]:=Point(Width-Pen.Width,Pen.Width); LowerCorner[0]:=Point(Pen.Width,Self.Height-Pen.Width); LowerCorner[1]:=Point(Width-Pen.Width,Height-Pen.Width); LowerCorner[2]:=Point(Width-Pen.Width,Pen.Width); Brush.Color:=LeftColor; Pen.Color:=LeftColor; Polyline(UpperCorner); Brush.Color:=RightColor; Pen.Color:=RightColor; Polyline(LowerCorner); End; End; procedure TBrCstButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); Begin InHerited; If Shift=[SSLeft] Then Begin fPushed:=Not fPushed; Invalidate; If Assigned(Parent) Then (Parent As TBrPanelTrack).MouseDown(Button,Shift,X+Left,Y+Top); End; End; procedure TBrCstButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); Begin InHerited; If Not fSwitchActif Then fPushed:=False; Invalidate; End; {>>BrPanelTrack} constructor TBrPanelTrack.Create(AOwner: TComponent); begin inherited Create(AOwner); fActive:=True; fIndex:=0; ItemIndex:=-1; fEdit:=TEdit.Create(Self); With fEdit Do Begin Parent:=Self; CharCase:=ecUpperCase; Font.Size:=10; Text:='TRACK'; ReadOnly:=True; AutoSelect:=False; Width:=112; Height:=26; Left:=95; Top:=4; Color:=ClBlack; Font.Color:=ClWhite; OnMouseDown:=EditMouseDown; End; fTypeTrack:=TtWav; CreateButton(fOpenBt,66,34,'OpenBt','O', False); CreateButton(fAcquisitionBt,66,1,'AcquisitionBt','A', True); CreateButton(fWriteBt,94,34,'WriteBt','W', False); CreateButton(fReadBt,122,34,'ReadBt','R', True); CreateButton(fSoloBt,178,34,'SoloBt','S', True); CreateButton(fMuteBt,150,34,'MuteBt','M', True); end; Procedure TBrPanelTrack.EditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); Begin Self.MouseDown(Button,Shift,X,Y); End; Procedure TBrPanelTrack.CreateButton(var Button:TBrCstButton;BtLeft,BtTop:Integer; BtName,BtCaption:String; ToSwitch:Boolean); Begin Button:=TBrCstButton.Create(Self); With Button Do Begin Parent:=Self; Name:=BtName; SetSubComponent(True); Width:=28; Height:=28; Left:=BtLeft; Top:=BtTop; Caption:=BtCaption; SwitchActif:=ToSwitch; Font.Size:=14; Font.Style:=[FsBold]; Button.ColorTop:=$00FFE6E1; Button.ColorBottom:=$00E8E8E8; Button.ColorLine:=$0041C9D3; End; End; destructor TBrPanelTrack.Destroy; begin fEdit.Free; fOpenBt.Free; fAcquisitionBt.Free; fWriteBt.Free; fReadBt.Free; fSoloBt.Free; fMuteBt.Free; inherited; end; procedure TBrPanelTrack.Resize; Begin Width:=209; Height:=65; Invalidate; End; Procedure TBrPanelTrack.SetTypeTrack(Value:TTrackType); Begin fTypeTrack:=Value; Invalidate; End; Procedure TBrPanelTrack.SetIndex(Value:Integer); Begin fIndex:=Value; Invalidate; End; Procedure TBrPanelTrack.SetActive(Value:Boolean); Begin fActive:=Value; Invalidate; End; Procedure TBrPanelTrack.DrawTypeArea; Var RectType:TRect; Begin With Canvas Do With RectType Do Begin Left:=0; Right:=65; Top:=0; Bottom:=Self.Height; Pen.Color:=ClBlack; Pen.Width:=1; If fTypeTrack=TtMidi Then Brush.Color:=$0096E1FA Else Brush.Color:=$00ADAE93; Rectangle(RectType); End; End; Procedure TBrPanelTrack.DrawCircle(X,Y,Width,Height:Integer); Var EllipseRect:TRect; Begin With Canvas Do With EllipseRect Do Begin Pen.Width:=1; Pen.Color:=ClBlack; Pen.Width:=1; Left:=X-Width Div 2; Right:=X+Width Div 2; Top:=Y-Height Div 2; Bottom:=Y+Height Div 2; Ellipse(EllipseRect); End; End; Procedure TBrPanelTrack.DrawTypeLogo; Const WavLogo='WAV'; Var Index,LeftLetter,TopLetter:Cardinal; Begin With Self.Canvas Do Begin If fTypeTrack=TtMidi Then Begin DrawCircle(23,23,35,35); Brush.Color:=ClBlack; DrawCircle(23,13,4,4); DrawCircle(13,23,4,4); DrawCircle(33,23,4,4); DrawCircle(15,16,4,4); DrawCircle(31,16,4,4); End Else Begin Brush.Style:=BsClear; Font.Size:=14; LeftLetter:=8; TopLetter:=20; For Index:=1 To 3 Do Begin LeftLetter:=LeftLetter+20*(Index-1); If Index=3 Then LeftLetter:=LeftLetter-25; TopLetter:=TopLetter-5*(Index-1); If Index=3 Then TopLetter:=TopLetter+5; TextOut(LeftLetter,TopLetter,WavLogo[index]); End; End; If fActive Then Brush.Color:=ClLime Else Brush.Color:=ClRed; DrawCircle(23,55,10,10); Brush.Style:=BsClear; TextOut(60-TextWidth(IntToStr(Self.fIndex)),40-TextHeight(IntToStr(Self.fIndex)) Div 2,IntToStr(Self.fIndex)); End; End; procedure TBrPanelTrack.Paint; Var Index:Cardinal; Begin With Canvas Do Begin Pen.Color:=ClBlack; Brush.Color:=$00C9CAB7; Rectangle(Self.ClientRect); DrawTypeArea; Pen.Color:=ClWhite; For Index:=1 To Self.Height Do If Index Mod 5 = 0 Then Begin MoveTo(Pen.Width,Index); LineTo(65-Pen.Width,Index); MoveTo(65,Index); LineTo(Width-Pen.Width,Index); End; DrawTypeLogo; End; End; procedure TBrPanelTrack.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); Begin InHerited; If Assigned(Parent)Then (Parent As TBrowserTracks).MouseDown(Button,Shift,X+Left,Y+Top); End; {>>TRACKS} constructor TBrTrack.Create(ACollection: TCollection); begin fCollection := (ACollection as TBrTrackCnt); inherited Create(ACollection); Owner:=ACollection.Owner; fBrPanelTrack:=TBrPanelTrack.Create(fCollection.Owner As TComponent); With fBrPanelTrack Do Begin Parent:=(fCollection.Owner As TBrowserTracks); SetSubComponent(True); Owner:=ACollection.Owner; With (Owner As TBrowserTracks) Do Begin fAcquisitionBt.OnClick:=fOnAcquisition_Event; fOpenBt.OnClick:=fOnOpen_Event; fReadBt.OnClick:=fOnRead_Event; fWriteBt.OnClick:=fOnWrite_Event; fSoloBt.OnClick:=fOnSolo_Event; fMuteBt.OnClick:=fOnMute_Event; End; End; end; destructor TBrTrack.Destroy; begin fBrPanelTrack.Free; inherited Destroy; end; procedure TBrTrack.AssignTo(Dest: TPersistent); begin if Dest is TBrTrack then with TBrTrack(Dest) do begin fBrPanelTrack:=self.fBrPanelTrack; fCollection:=Self.fCollection; fOnChange := self.fOnChange; Change; end else inherited AssignTo(Dest); end; procedure TBrTrack.Assign(Source : TPersistent); begin if source is TBrTrack then with TBrTrack(Source) do AssignTo(Self) else inherited Assign(source); end; procedure TBrTrack.Change; begin if Assigned(fOnChange) then fOnChange(Self); end; function TBrTrack.GetDisplayName: string; begin result := 'TBrTrack['+IntToStr(Self.Index)+'] '; end; {>>TRACKSCNT} constructor TBrTrackCnt.Create(AOwner: TBrowserTracks); begin fOwner := AOwner; inherited Create(AOwner,TBrTrack); end; function TBrTrackCnt.Add:TBrTrack; begin Result := TBrTrack(inherited Add); end; function TBrTrackCnt.GetItem(Index: integer):TBrTrack; begin Result := TBrTrack(inherited Items[Index]); end; procedure TBrTrackCnt.SetItem(Index: integer; Value:TBrTrack); begin inherited SetItem(Index, Value); end; function TBrTrackCnt.GetOwner: TPersistent; begin Result := fOwner; end; {>>BrowserTracks} constructor TBrowserTracks.Create(AOwner: TComponent); begin inherited Create(AOwner); RegisterClass(TBrPanelTitle); RegisterClass(TBrPanelTrack); fBrPanelTitle:=TBrPanelTitle.Create(Self); With fBrPanelTitle Do Begin Parent:=Self; Top:=0; Left:=0; Width:=209; Height:=49; End; fBrTracksCnt:=TBrTrackCnt.Create(Self); DoubleBuffered:=True; end; destructor TBrowserTracks.Destroy; begin fBrTracksCnt.Free; fBrPanelTitle.Free; inherited; end; procedure TBrowserTracks.Resize; begin inherited; Width:=209; If fBrTracksCnt.Count<=0 Then Height:=49; end; procedure TBrowserTracks.Paint; Var IndexTracks:Integer; begin inherited; If fBrTracksCnt.Count>0 Then Begin For IndexTracks:=0 To fBrTracksCnt.Count-1 Do With fBrTracksCnt.Items[IndexTracks].fBrPanelTrack Do Top:=49+IndexTracks*65; Self.Height:=49+fBrTracksCnt.Count*65; End; end; Procedure TBrowserTracks.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin inherited; fBrTracksCnt.ItemIndex:=-1; If fBrTracksCnt.Count>0 Then fBrTracksCnt.ItemIndex:=(Y-fBrPanelTitle.Height) Div fBrTracksCnt.Items[0].fBrPanelTrack.Height; End; procedure TBrowserTracks.SetOnOpen_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnOpen_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fOpenBt.OnClick:= fOnOpen_Event; End; procedure TBrowserTracks.SetOnAcquisition_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnAcquisition_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fAcquisitionBt.OnClick:= fOnAcquisition_Event; End; procedure TBrowserTracks.SetOnWrite_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnWrite_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fWriteBt.OnClick:= fOnWrite_Event; End; procedure TBrowserTracks.SetOnRead_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnRead_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fReadBt.OnClick:= fOnRead_Event; End; procedure TBrowserTracks.SetOnSolo_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnSolo_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fSoloBt.OnClick:= fOnSolo_Event; End; procedure TBrowserTracks.SetOnMute_Event(Event : TNotifyEvent); Var Index:Cardinal; Begin fOnMute_Event := Event; If fBrTracksCnt.Count>=0 Then For Index:=0 To (fBrTracksCnt.Count-1) Do fBrTracksCnt.Items[Index].BrPanelTrack.fMuteBt.OnClick:= fOnMute_Event; End; end.
unit ServerWinshoeDAYTIME; interface //////////////////////////////////////////////////////////////////////////////// // Author: Ozz Nixon // .. // 5.13.99 Final Version // 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers) //////////////////////////////////////////////////////////////////////////////// uses Classes, ServerWinshoe; Type TWinshoeDAYTIMEListener = class(TWinshoeListener) private FTimeZone:String; protected function DoExecute(Thread: TWinshoeServerThread): boolean; override; public constructor Create(AOwner: TComponent); override; published Property TimeZone:String read FTimeZone write FTimeZone; end; procedure Register; implementation uses GlobalWinshoe, SysUtils, Winshoes; procedure Register; begin RegisterComponents('Winshoes Servers', [TWinshoeDAYTIMEListener]); end; constructor TWinshoeDAYTIMEListener.Create(AOwner: TComponent); begin inherited Create(AOwner); Port := WSPORT_DAYTIME; FTimeZone:='EST'; end; function TWinshoeDAYTIMEListener.DoExecute(Thread: TWinshoeServerThread): boolean; begin result := inherited DoExecute(Thread); if result then exit; with Thread.Connection do begin If Connected then Writeln(FormatDateTime('dddd, mmmm dd, yyyy hh:nn:ss',Now)+'-'+FTimeZone); Disconnect; end; {with} end; {doExecute} end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Utils; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} interface uses SysUtils, Classes, PasVulkan.Types; type TpvSwap<T>=class public class procedure Swap(var aValue,aOtherValue:T); static; inline; end; TpvUntypedSortCompareFunction=function(const a,b:TpvPointer):TpvInt32; TpvIndirectSortCompareFunction=function(const a,b:TpvPointer):TpvInt32; TpvTypedSort<T>=class private type PStackItem=^TStackItem; TStackItem=record Left,Right,Depth:TpvInt32; end; public type TpvTypedSortCompareFunction=function(const a,b:T):TpvInt32; public class procedure IntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32); overload; class procedure IntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32;const pCompareFunc:TpvTypedSortCompareFunction); overload; end; TpvTopologicalSortNodeDependsOnKeys=array of TpvInt32; PpvTopologicalSortNode=^TpvTopologicalSortNode; TpvTopologicalSortNode=record Key:TpvInt32; DependsOnKeys:TpvTopologicalSortNodeDependsOnKeys; end; TpvTopologicalSortNodes=array of TpvTopologicalSortNode; TpvTopologicalSortVisitedBitmap=array of TpvUInt32; TpvTopologicalSortStack=array of TpvInt32; TpvTopologicalSortKeyToNodeIndex=array of TpvInt32; TpvTopologicalSortKeys=array of TpvInt32; TpvTopologicalSort=class private fNodes:TpvTopologicalSortNodes; fCount:TpvInt32; fCountKeys:TpvInt32; {$ifdef UseIndexingForTopologicalSorting} fKeyToNodeIndex:TpvTopologicalSortKeyToNodeIndex; {$endif} fVisitedBitmap:TpvTopologicalSortVisitedBitmap; fVisitedBitmapSize:TpvInt32; fStack:TpvTopologicalSortStack; fSortedKeys:TpvTopologicalSortKeys; fDirty:boolean; fSolveDirty:boolean; fCyclicState:TpvInt32; function GetNode(const aIndex:TpvInt32):TpvTopologicalSortNode; procedure SetNode(const aIndex:TpvInt32;const aNode:TpvTopologicalSortNode); function GetSortedKey(const aIndex:TpvInt32):TpvInt32; procedure SetCount(const aNewCount:TpvInt32); procedure Setup; public constructor Create; destructor Destroy; override; procedure Clear; procedure Add(const aKey:TpvInt32;const aDependsOnKeys:array of TpvInt32); procedure Solve(const aBackwards:boolean=false); function Cyclic:boolean; property Nodes[const aIndex:TpvInt32]:TpvTopologicalSortNode read GetNode write SetNode; property SortedKeys[const aIndex:TpvInt32]:TpvInt32 read GetSortedKey; property Count:TpvInt32 read fCount write SetCount; end; procedure DebugBreakPoint; function DumpExceptionCallStack(e:Exception):string; function CombineTwoUInt32IntoOneUInt64(const a,b:TpvUInt32):TpvUInt64; {$ifdef caninline}inline;{$endif} // Sorts data direct inplace procedure UntypedDirectIntroSort(const pItems:TpvPointer;const pLeft,pRight,pElementSize:TpvInt32;const pCompareFunc:TpvUntypedSortCompareFunction); // Sorts data indirect outplace with an extra TpvPointer array procedure IndirectIntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32;const pCompareFunc:TpvIndirectSortCompareFunction); function MatchPattern(Input,Pattern:PAnsiChar):boolean; function IsPathSeparator(const aChar:AnsiChar):Boolean; function ExpandRelativePath(const aRelativePath:TpvRawByteString;const aBasePath:TpvRawByteString=''):TpvRawByteString; function ConvertPathToRelative(aAbsolutePath,aBasePath:TpvRawByteString):TpvRawByteString; implementation uses PasVulkan.Math, Generics.Defaults; procedure DebugBreakPoint;{$if defined(cpuarm)}assembler; // E7FFDEFE asm .long 0xFEDEFFE7 end; {$elseif defined(cpu386)}assembler; {$ifdef fpc}nostackframe;{$endif} asm db $cc // int3 end; {$elseif defined(cpux86_64)}assembler; {$ifdef fpc}nostackframe;{$endif} asm {$ifndef fpc} .NOFRAME {$endif} db $cc // int3 end; {$else} begin end; {$ifend} function DumpExceptionCallStack(e:Exception):string; const LineEnding={$if defined(Windows) or defined(Win32) or defined(Win64)}#13#10{$else}#10{$ifend}; {$if defined(fpc)} var Index:TpvInt32; Frames:PPointer; {$else} {$ifend} begin result:='Program exception! '+LineEnding+'Stack trace:'+LineEnding+LineEnding; if assigned(e) then begin result:=result+'Exception class: '+e.ClassName+LineEnding+'Message: '+e.Message+LineEnding; end; {$if defined(fpc)} result:=result+BackTraceStrFunc(ExceptAddr); Frames:=ExceptFrames; for Index:=0 to ExceptFrameCount-1 do begin result:=result+LineEnding+BackTraceStrFunc(Frames); inc(Frames); end; {$else} {$ifend} end; class procedure TpvSwap<T>.Swap(var aValue,aOtherValue:T); var Temporary:T; begin Temporary:=aValue; aValue:=aOtherValue; aOtherValue:=Temporary; end; function CombineTwoUInt32IntoOneUInt64(const a,b:TpvUInt32):TpvUInt64; {$ifdef caninline}inline;{$endif} begin result:=(TpvUInt64(a) shl 32) or b; end; procedure MemorySwap(pA,pB:TpvPointer;pSize:TpvInt32); var Temp:TpvInt32; begin while pSize>=SizeOf(TpvInt32) do begin Temp:=TpvUInt32(pA^); TpvUInt32(pA^):=TpvUInt32(pB^); TpvUInt32(pB^):=Temp; inc(TpvPtrUInt(pA),SizeOf(TpvUInt32)); inc(TpvPtrUInt(pB),SizeOf(TpvUInt32)); dec(pSize,SizeOf(TpvUInt32)); end; while pSize>=SizeOf(TpvUInt8) do begin Temp:=TpvUInt8(pA^); TpvUInt8(pA^):=TpvUInt8(pB^); TpvUInt8(pB^):=Temp; inc(TpvPtrUInt(pA),SizeOf(TpvUInt8)); inc(TpvPtrUInt(pB),SizeOf(TpvUInt8)); dec(pSize,SizeOf(TpvUInt8)); end; end; procedure UntypedDirectIntroSort(const pItems:TpvPointer;const pLeft,pRight,pElementSize:TpvInt32;const pCompareFunc:TpvUntypedSortCompareFunction); type PByteArray=^TByteArray; TByteArray=array[0..$3fffffff] of TpvUInt8; PStackItem=^TStackItem; TStackItem=record Left,Right,Depth:TpvInt32; end; var Left,Right,Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:TpvInt32; StackItem:PStackItem; Stack:array[0..31] of TStackItem; begin if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=IntLog2((pRight-pLeft)+1) shl 1; inc(StackItem); while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort iA:=Left; iB:=iA+1; while iB<=Right do begin iC:=iB; while (iA>=Left) and (iC>=Left) and (pCompareFunc(TpvPointer(@PByteArray(pItems)^[iA*pElementSize]),TpvPointer(@PByteArray(pItems)^[iC*pElementSize]))>0) do begin MemorySwap(@PByteArray(pItems)^[iA*pElementSize],@PByteArray(pItems)^[iC*pElementSize],pElementSize); dec(iA); dec(iC); end; iA:=iB; inc(iB); end; end else begin if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; repeat if i>0 then begin dec(i); end else begin dec(Size); if Size>0 then begin MemorySwap(@PByteArray(pItems)^[(Left+Size)*pElementSize],@PByteArray(pItems)^[Left*pElementSize],pElementSize); end else begin break; end; end; Parent:=i; repeat Child:=(Parent*2)+1; if Child<Size then begin if (Child<(Size-1)) and (pCompareFunc(TpvPointer(@PByteArray(pItems)^[(Left+Child)*pElementSize]),TpvPointer(@PByteArray(pItems)^[(Left+Child+1)*pElementSize]))<0) then begin inc(Child); end; if pCompareFunc(TpvPointer(@PByteArray(pItems)^[(Left+Parent)*pElementSize]),TpvPointer(@PByteArray(pItems)^[(Left+Child)*pElementSize]))<0 then begin MemorySwap(@PByteArray(pItems)^[(Left+Parent)*pElementSize],@PByteArray(pItems)^[(Left+Child)*pElementSize],pElementSize); Parent:=Child; continue; end; end; break; until false; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if pCompareFunc(TpvPointer(@PByteArray(pItems)^[Left*pElementSize]),TpvPointer(@PByteArray(pItems)^[Middle*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Left*pElementSize],@PByteArray(pItems)^[Middle*pElementSize],pElementSize); end; if pCompareFunc(TpvPointer(@PByteArray(pItems)^[Left*pElementSize]),TpvPointer(@PByteArray(pItems)^[Right*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Left*pElementSize],@PByteArray(pItems)^[Right*pElementSize],pElementSize); end; if pCompareFunc(TpvPointer(@PByteArray(pItems)^[Middle*pElementSize]),TpvPointer(@PByteArray(pItems)^[Right*pElementSize]))>0 then begin MemorySwap(@PByteArray(pItems)^[Middle*pElementSize],@PByteArray(pItems)^[Right*pElementSize],pElementSize); end; end; Pivot:=Middle; i:=Left; j:=Right; repeat while (i<Right) and (pCompareFunc(TpvPointer(@PByteArray(pItems)^[i*pElementSize]),TpvPointer(@PByteArray(pItems)^[Pivot*pElementSize]))<0) do begin inc(i); end; while (j>=i) and (pCompareFunc(TpvPointer(@PByteArray(pItems)^[j*pElementSize]),TpvPointer(@PByteArray(pItems)^[Pivot*pElementSize]))>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin MemorySwap(@PByteArray(pItems)^[i*pElementSize],@PByteArray(pItems)^[j*pElementSize],pElementSize); if Pivot=i then begin Pivot:=j; end else if Pivot=j then begin Pivot:=i; end; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; procedure IndirectIntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32;const pCompareFunc:TpvIndirectSortCompareFunction); type PPointers=^TPointers; TPointers=array[0..$ffff] of TpvPointer; PStackItem=^TStackItem; TStackItem=record Left,Right,Depth:TpvInt32; end; var Left,Right,Depth,i,j,Middle,Size,Parent,Child:TpvInt32; Pivot,Temp:TpvPointer; StackItem:PStackItem; Stack:array[0..31] of TStackItem; begin if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=IntLog2((pRight-pLeft)+1) shl 1; inc(StackItem); while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort for i:=Left+1 to Right do begin Temp:=PPointers(pItems)^[i]; j:=i-1; if (j>=Left) and (pCompareFunc(PPointers(pItems)^[j],Temp)>0) then begin repeat PPointers(pItems)^[j+1]:=PPointers(pItems)^[j]; dec(j); until not ((j>=Left) and (pCompareFunc(PPointers(pItems)^[j],Temp)>0)); PPointers(pItems)^[j+1]:=Temp; end; end; end else begin if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; Temp:=nil; repeat if i>0 then begin dec(i); Temp:=PPointers(pItems)^[Left+i]; end else begin dec(Size); if Size>0 then begin Temp:=PPointers(pItems)^[Left+Size]; PPointers(pItems)^[Left+Size]:=PPointers(pItems)^[Left]; end else begin break; end; end; Parent:=i; Child:=(i*2)+1; while Child<Size do begin if ((Child+1)<Size) and (pCompareFunc(PPointers(pItems)^[Left+Child+1],PPointers(pItems)^[Left+Child])>0) then begin inc(Child); end; if pCompareFunc(PPointers(pItems)^[Left+Child],Temp)>0 then begin PPointers(pItems)^[Left+Parent]:=PPointers(pItems)^[Left+Child]; Parent:=Child; Child:=(Parent*2)+1; end else begin break; end; end; PPointers(pItems)^[Left+Parent]:=Temp; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if pCompareFunc(PPointers(pItems)^[Left],PPointers(pItems)^[Middle])>0 then begin Temp:=PPointers(pItems)^[Left]; PPointers(pItems)^[Left]:=PPointers(pItems)^[Middle]; PPointers(pItems)^[Middle]:=Temp; end; if pCompareFunc(PPointers(pItems)^[Left],PPointers(pItems)^[Right])>0 then begin Temp:=PPointers(pItems)^[Left]; PPointers(pItems)^[Left]:=PPointers(pItems)^[Right]; PPointers(pItems)^[Right]:=Temp; end; if pCompareFunc(PPointers(pItems)^[Middle],PPointers(pItems)^[Right])>0 then begin Temp:=PPointers(pItems)^[Middle]; PPointers(pItems)^[Middle]:=PPointers(pItems)^[Right]; PPointers(pItems)^[Right]:=Temp; end; end; Pivot:=PPointers(pItems)^[Middle]; i:=Left; j:=Right; repeat while (i<Right) and (pCompareFunc(PPointers(pItems)^[i],Pivot)<0) do begin inc(i); end; while (j>=i) and (pCompareFunc(PPointers(pItems)^[j],Pivot)>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin Temp:=PPointers(pItems)^[i]; PPointers(pItems)^[i]:=PPointers(pItems)^[j]; PPointers(pItems)^[j]:=Temp; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; class procedure TpvTypedSort<T>.IntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32); type PItem=^TItem; TItem=T; PItemArray=^TItemArray; TItemArray=array of TItem; var Left,Right,Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:TpvInt32; StackItem:PStackItem; Stack:array[0..31] of TStackItem; Temp:T; Comparer:IComparer<T>; begin Comparer:=TComparer<T>.Default; if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=IntLog2((pRight-pLeft)+1) shl 1; inc(StackItem); while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort iA:=Left; iB:=iA+1; while iB<=Right do begin iC:=iB; while (iA>=Left) and (iC>=Left) and (Comparer.Compare(PItemArray(pItems)^[iA],PItemArray(pItems)^[iC])>0) do begin Temp:=PItemArray(pItems)^[iA]; PItemArray(pItems)^[iA]:=PItemArray(pItems)^[iC]; PItemArray(pItems)^[iC]:=Temp; dec(iA); dec(iC); end; iA:=iB; inc(iB); end; end else begin if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; repeat if i>0 then begin dec(i); end else begin dec(Size); if Size>0 then begin Temp:=PItemArray(pItems)^[Left+Size]; PItemArray(pItems)^[Left+Size]:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=Temp; end else begin break; end; end; Parent:=i; repeat Child:=(Parent*2)+1; if Child<Size then begin if (Child<(Size-1)) and (Comparer.Compare(PItemArray(pItems)^[Left+Child],PItemArray(pItems)^[Left+Child+1])<0) then begin inc(Child); end; if Comparer.Compare(PItemArray(pItems)^[Left+Parent],PItemArray(pItems)^[Left+Child])<0 then begin Temp:=PItemArray(pItems)^[Left+Parent]; PItemArray(pItems)^[Left+Parent]:=PItemArray(pItems)^[Left+Child]; PItemArray(pItems)^[Left+Child]:=Temp; Parent:=Child; continue; end; end; break; until false; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if Comparer.Compare(PItemArray(pItems)^[Left],PItemArray(pItems)^[Middle])>0 then begin Temp:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=PItemArray(pItems)^[Middle]; PItemArray(pItems)^[Middle]:=Temp; end; if Comparer.Compare(PItemArray(pItems)^[Left],PItemArray(pItems)^[Right])>0 then begin Temp:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=PItemArray(pItems)^[Right]; PItemArray(pItems)^[Right]:=Temp; end; if Comparer.Compare(PItemArray(pItems)^[Middle],PItemArray(pItems)^[Right])>0 then begin Temp:=PItemArray(pItems)^[Middle]; PItemArray(pItems)^[Middle]:=PItemArray(pItems)^[Right]; PItemArray(pItems)^[Right]:=Temp; end; end; Pivot:=Middle; i:=Left; j:=Right; repeat while (i<Right) and (Comparer.Compare(PItemArray(pItems)^[i],PItemArray(pItems)^[Pivot])<0) do begin inc(i); end; while (j>=i) and (Comparer.Compare(PItemArray(pItems)^[j],PItemArray(pItems)^[Pivot])>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin Temp:=PItemArray(pItems)^[i]; PItemArray(pItems)^[i]:=PItemArray(pItems)^[j]; PItemArray(pItems)^[j]:=Temp; if Pivot=i then begin Pivot:=j; end else if Pivot=j then begin Pivot:=i; end; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; class procedure TpvTypedSort<T>.IntroSort(const pItems:TpvPointer;const pLeft,pRight:TpvInt32;const pCompareFunc:TpvTypedSortCompareFunction); type PItem=^TItem; TItem=T; PItemArray=^TItemArray; TItemArray=array[0..65535] of TItem; var Left,Right,Depth,i,j,Middle,Size,Parent,Child,Pivot,iA,iB,iC:TpvInt32; StackItem:PStackItem; Stack:array[0..31] of TStackItem; Temp:T; begin if pLeft<pRight then begin StackItem:=@Stack[0]; StackItem^.Left:=pLeft; StackItem^.Right:=pRight; StackItem^.Depth:=IntLog2((pRight-pLeft)+1) shl 1; inc(StackItem); while TpvPtrUInt(TpvPointer(StackItem))>TpvPtrUInt(TpvPointer(@Stack[0])) do begin dec(StackItem); Left:=StackItem^.Left; Right:=StackItem^.Right; Depth:=StackItem^.Depth; Size:=(Right-Left)+1; if Size<16 then begin // Insertion sort iA:=Left; iB:=iA+1; while iB<=Right do begin iC:=iB; while (iA>=Left) and (iC>=Left) and (pCompareFunc(PItemArray(pItems)^[iA],PItemArray(pItems)^[iC])>0) do begin Temp:=PItemArray(pItems)^[iA]; PItemArray(pItems)^[iA]:=PItemArray(pItems)^[iC]; PItemArray(pItems)^[iC]:=Temp; dec(iA); dec(iC); end; iA:=iB; inc(iB); end; end else begin if (Depth=0) or (TpvPtrUInt(TpvPointer(StackItem))>=TpvPtrUInt(TpvPointer(@Stack[high(Stack)-1]))) then begin // Heap sort i:=Size div 2; repeat if i>0 then begin dec(i); end else begin dec(Size); if Size>0 then begin Temp:=PItemArray(pItems)^[Left+Size]; PItemArray(pItems)^[Left+Size]:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=Temp; end else begin break; end; end; Parent:=i; repeat Child:=(Parent*2)+1; if Child<Size then begin if (Child<(Size-1)) and (pCompareFunc(PItemArray(pItems)^[Left+Child],PItemArray(pItems)^[Left+Child+1])<0) then begin inc(Child); end; if pCompareFunc(PItemArray(pItems)^[Left+Parent],PItemArray(pItems)^[Left+Child])<0 then begin Temp:=PItemArray(pItems)^[Left+Parent]; PItemArray(pItems)^[Left+Parent]:=PItemArray(pItems)^[Left+Child]; PItemArray(pItems)^[Left+Child]:=Temp; Parent:=Child; continue; end; end; break; until false; until false; end else begin // Quick sort width median-of-three optimization Middle:=Left+((Right-Left) shr 1); if (Right-Left)>3 then begin if pCompareFunc(PItemArray(pItems)^[Left],PItemArray(pItems)^[Middle])>0 then begin Temp:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=PItemArray(pItems)^[Middle]; PItemArray(pItems)^[Middle]:=Temp; end; if pCompareFunc(PItemArray(pItems)^[Left],PItemArray(pItems)^[Right])>0 then begin Temp:=PItemArray(pItems)^[Left]; PItemArray(pItems)^[Left]:=PItemArray(pItems)^[Right]; PItemArray(pItems)^[Right]:=Temp; end; if pCompareFunc(PItemArray(pItems)^[Middle],PItemArray(pItems)^[Right])>0 then begin Temp:=PItemArray(pItems)^[Middle]; PItemArray(pItems)^[Middle]:=PItemArray(pItems)^[Right]; PItemArray(pItems)^[Right]:=Temp; end; end; Pivot:=Middle; i:=Left; j:=Right; repeat while (i<Right) and (pCompareFunc(PItemArray(pItems)^[i],PItemArray(pItems)^[Pivot])<0) do begin inc(i); end; while (j>=i) and (pCompareFunc(PItemArray(pItems)^[j],PItemArray(pItems)^[Pivot])>0) do begin dec(j); end; if i>j then begin break; end else begin if i<>j then begin Temp:=PItemArray(pItems)^[i]; PItemArray(pItems)^[i]:=PItemArray(pItems)^[j]; PItemArray(pItems)^[j]:=Temp; if Pivot=i then begin Pivot:=j; end else if Pivot=j then begin Pivot:=i; end; end; inc(i); dec(j); end; until false; if i<Right then begin StackItem^.Left:=i; StackItem^.Right:=Right; StackItem^.Depth:=Depth-1; inc(StackItem); end; if Left<j then begin StackItem^.Left:=Left; StackItem^.Right:=j; StackItem^.Depth:=Depth-1; inc(StackItem); end; end; end; end; end; end; function MatchPattern(Input,Pattern:PAnsiChar):boolean; begin result:=true; while true do begin case Pattern[0] of #0:begin result:=Input[0]=#0; exit; end; '*':begin inc(Pattern); if Pattern[0]=#0 then begin result:=true; exit; end; while Input[0]<>#0 do begin if MatchPattern(Input,Pattern) then begin result:=true; exit; end; inc(Input); end; end; '?':begin if Input[0]=#0 then begin result:=false; exit; end; inc(Input); inc(Pattern); end; '[':begin if Pattern[1] in [#0,'[',']'] then begin result:=false; exit; end; if Pattern[1]='^' then begin inc(Pattern,2); result:=true; while Pattern[0]<>']' do begin if Pattern[1]='-' then begin if (Input[0]>=Pattern[0]) and (Input[0]<=Pattern[2]) then begin result:=false; break; end else begin inc(Pattern,3); end; end else begin if Input[0]=Pattern[0] then begin result:=false; break; end else begin inc(Pattern); end; end; end; end else begin inc(Pattern); result:=false; while Pattern[0]<>']' do begin if Pattern[1]='-' then begin if (Input[0]>=Pattern[0]) and (Input[0]<=Pattern[2]) then begin result:=true; break; end else begin inc(Pattern,3); end; end else begin if Input[0]=Pattern[0] then begin result:=true; break; end else begin inc(Pattern); end; end; end; end; if result then begin inc(Input); while not (Pattern[0] in [']',#0]) do begin inc(Pattern); end; if Pattern[0]=#0 then begin result:=false; exit; end else begin inc(Pattern); end; end else begin exit; end; end; else begin if Input[0]<>Pattern[0] then begin result:=false; break; end; inc(Input); inc(Pattern); end; end; end; end; constructor TpvTopologicalSort.Create; begin inherited Create; fNodes:=nil; fCount:=0; fCountKeys:=0; {$ifdef UseIndexingForTopologicalSorting} fKeyToNodeIndex:=nil; {$endif} fVisitedBitmap:=nil; fVisitedBitmapSize:=0; fStack:=nil; SetLength(fStack,32); fSortedKeys:=nil; fDirty:=true; fSolveDirty:=true; fCyclicState:=-1; end; destructor TpvTopologicalSort.Destroy; begin SetLength(fNodes,0); {$ifdef UseIndexingForTopologicalSorting} SetLength(fKeyToNodeIndex,0); {$endif} SetLength(fVisitedBitmap,0); SetLength(fStack,0); SetLength(fSortedKeys,0); inherited Destroy; end; procedure TpvTopologicalSort.Clear; begin fCount:=0; fDirty:=true; fSolveDirty:=true; fCyclicState:=-1; end; function TpvTopologicalSort.GetNode(const aIndex:TpvInt32):TpvTopologicalSortNode; begin result:=fNodes[aIndex]; end; procedure TpvTopologicalSort.SetNode(const aIndex:TpvInt32;const aNode:TpvTopologicalSortNode); begin fNodes[aIndex]:=aNode; end; function TpvTopologicalSort.GetSortedKey(const aIndex:TpvInt32):TpvInt32; begin result:=fSortedKeys[aIndex]; end; procedure TpvTopologicalSort.SetCount(const aNewCount:TpvInt32); begin fCount:=aNewCount; if length(fNodes)<fCount then begin SetLength(fNodes,fCount*2); end; end; procedure TpvTopologicalSort.Add(const aKey:TpvInt32;const aDependsOnKeys:array of TpvInt32); var Index:TpvInt32; Node:PpvTopologicalSortNode; begin Index:=fCount; SetCount(fCount+1); Node:=@fNodes[Index]; Node^.Key:=aKey; SetLength(Node^.DependsOnKeys,length(aDependsOnKeys)); if length(aDependsOnKeys)>0 then begin Move(aDependsOnKeys[0],Node^.DependsOnKeys[0],length(aDependsOnKeys)*SizeOf(TpvInt32)); end; fDirty:=true; fSolveDirty:=true; fCyclicState:=-1; end; procedure TpvTopologicalSort.Setup; var Index:TpvInt32; Node:PpvTopologicalSortNode; begin if fDirty then begin fCountKeys:=0; for Index:=0 to fCount-1 do begin Node:=@fNodes[Index]; if fCountKeys<=Node^.Key then begin fCountKeys:=Node^.Key+1; end; end; if fCountKeys>0 then begin {$ifdef UseIndexingForTopologicalSorting} if length(fKeyToNodeIndex)<fCountKeys then begin SetLength(fKeyToNodeIndex,fCountKeys); end; FillChar(fKeyToNodeIndex[0],fCountKeys*SizeOf(TpvInt32),#$ff); for Index:=0 to fCount-1 do begin fKeyToNodeIndex[fNodes[Index].Key]:=Index; end; {$endif} fVisitedBitmapSize:=(fCountKeys+31) shr 5; if length(fVisitedBitmap)<fVisitedBitmapSize then begin SetLength(fVisitedBitmap,fVisitedBitmapSize); end; FillChar(fVisitedBitmap[0],fVisitedBitmapSize*SizeOf(TpvUInt32),#0); end; if length(fSortedKeys)<fCount then begin SetLength(fSortedKeys,fCount); end; fDirty:=false; end; end; procedure TpvTopologicalSort.Solve(const aBackwards:boolean=false); var Index,SubIndex,StackPointer,Key,DependsOnKey,CountDependOnKeys,SortIndex:TpvInt32; Node:PpvTopologicalSortNode; begin if fDirty then begin Setup; end; if fSolveDirty then begin if fCountKeys>0 then begin FillChar(fVisitedBitmap[0],fVisitedBitmapSize*SizeOf(TpvUInt32),#0); if aBackwards then begin SortIndex:=0; end else begin SortIndex:=fCount; end; for Index:=0 to fCount-1 do begin Key:=fNodes[Index].Key; if (Key>=0) and (Key<fCountKeys) and ((fVisitedBitmap[Key shr 5] and (TpvUInt32(1) shl (Key and 31)))=0) then begin StackPointer:=0; if length(fStack)<(StackPointer+2) then begin SetLength(fStack,(StackPointer+2)*2); end; fStack[StackPointer]:=Key; inc(StackPointer); while StackPointer>0 do begin dec(StackPointer); Key:=fStack[StackPointer]; if Key<0 then begin Key:=-(Key+1); if aBackwards then begin if SortIndex<fCount then begin fSortedKeys[SortIndex]:=Key; inc(SortIndex); end; end else begin if SortIndex>1 then begin dec(SortIndex); fSortedKeys[SortIndex]:=Key; end; end; end else if (Key<fCountKeys) and ((fVisitedBitmap[Key shr 5] and (TpvUInt32(1) shl (Key and 31)))=0) then begin fVisitedBitmap[Key shr 5]:=fVisitedBitmap[Key shr 5] or (TpvUInt32(1) shl (Key and 31)); {$ifdef UseIndexingForTopologicalSorting} if fKeyToNodeIndex[Key]>=0 then begin Node:=@fNodes[fKeyToNodeIndex[Key]]; end else begin Node:=nil; end; {$else} Node:=nil; for SubIndex:=0 to fCount-1 do begin if fNodes[SubIndex].Key=Key then begin Node:=@fNodes[SubIndex]; break; end; end; {$endif} if assigned(Node) then begin CountDependOnKeys:=length(Node^.DependsOnKeys); if length(fStack)<(StackPointer+CountDependOnKeys+1) then begin SetLength(fStack,(StackPointer+CountDependOnKeys+1)*2); end; fStack[StackPointer]:=-(Key+1); inc(StackPointer); for SubIndex:=CountDependOnKeys-1 downto 0 do begin DependsOnKey:=Node^.DependsOnKeys[SubIndex]; if (DependsOnKey>=0) and (DependsOnKey<fCountKeys) then begin fStack[StackPointer]:=DependsOnKey; inc(StackPointer); end; end; end; end; end; end; end; end; fSolveDirty:=false; end; end; function TpvTopologicalSort.Cyclic:boolean; var Index,SubIndex,StackPointer,Key,DependsOnKey,CountDependOnKeys:TpvInt32; Node:PpvTopologicalSortNode; begin if fCyclicState>=0 then begin result:=fCyclicState<>0; end else begin result:=false; if fDirty then begin Setup; end; if fCountKeys>0 then begin FillChar(fVisitedBitmap[0],fVisitedBitmapSize*SizeOf(TpvUInt32),#0); for Index:=0 to fCount-1 do begin Key:=fNodes[Index].Key; if (Key>=0) and (Key<fCountKeys) then begin StackPointer:=0; if length(fStack)<(StackPointer+2) then begin SetLength(fStack,(StackPointer+2)*2); end; fStack[StackPointer]:=Key; inc(StackPointer); while StackPointer>0 do begin dec(StackPointer); Key:=fStack[StackPointer]; if Key<0 then begin Key:=-(Key+1); fVisitedBitmap[Key shr 5]:=fVisitedBitmap[Key shr 5] and not (TpvUInt32(1) shl (Key and 31)); end else if (fVisitedBitmap[Key shr 5] and (TpvUInt32(1) shl (Key and 31)))=0 then begin fVisitedBitmap[Key shr 5]:=fVisitedBitmap[Key shr 5] or (TpvUInt32(1) shl (Key and 31)); {$ifdef UseIndexingForTopologicalSorting} if fKeyToNodeIndex[Key]>=0 then begin Node:=@fNodes[fKeyToNodeIndex[Key]]; end else begin Node:=nil; end; {$else} Node:=nil; for SubIndex:=0 to fCount-1 do begin if fNodes[SubIndex].Key=Key then begin Node:=@fNodes[SubIndex]; break; end; end; {$endif} if assigned(Node) then begin CountDependOnKeys:=length(Node^.DependsOnKeys); if length(fStack)<(StackPointer+CountDependOnKeys+1) then begin SetLength(fStack,(StackPointer+CountDependOnKeys+1)*2); end; fStack[StackPointer]:=-(Key+1); inc(StackPointer); for SubIndex:=CountDependOnKeys-1 downto 0 do begin DependsOnKey:=Node^.DependsOnKeys[SubIndex]; if (DependsOnKey>=0) and (DependsOnKey<fCountKeys) then begin fStack[StackPointer]:=DependsOnKey; inc(StackPointer); end; end; end; end else begin result:=true; break; end; end; if result then begin break; end; end; end; end; if result then begin fCyclicState:=1; end else begin fCyclicState:=0; end; end; end; function IsPathSeparator(const aChar:AnsiChar):Boolean; begin case aChar of '/','\':begin result:=true; end; else begin result:=false; end; end; end; function ExpandRelativePath(const aRelativePath:TpvRawByteString;const aBasePath:TpvRawByteString=''):TpvRawByteString; var InputIndex,OutputIndex:TpvInt32; InputPath:TpvRawByteString; PathSeparator:AnsiChar; begin if (length(aRelativePath)>0) and (IsPathSeparator(aRelativePath[1]) or ((length(aRelativePath)>1) and (aRelativePath[1] in ['a'..'z','A'..'Z']) and (aRelativePath[2]=':'))) then begin InputPath:=aRelativePath; end else begin if (length(aBasePath)>1) and not IsPathSeparator(aBasePath[length(aBasePath)]) then begin PathSeparator:=#0; for InputIndex:=1 to length(aBasePath) do begin if IsPathSeparator(aBasePath[InputIndex]) then begin PathSeparator:=aBasePath[InputIndex]; break; end; end; if PathSeparator=#0 then begin for InputIndex:=1 to length(aRelativePath) do begin if IsPathSeparator(aRelativePath[InputIndex]) then begin PathSeparator:=aRelativePath[InputIndex]; break; end; end; if PathSeparator=#0 then begin PathSeparator:='/'; end; end; InputPath:=aBasePath+PathSeparator; end else begin InputPath:=aBasePath; end; InputPath:=InputPath+aRelativePath; end; result:=InputPath; InputIndex:=1; OutputIndex:=1; while InputIndex<=length(InputPath) do begin if (((InputIndex+1)<=length(InputPath)) and (InputPath[InputIndex]='.') and IsPathSeparator(InputPath[InputIndex+1])) or ((InputIndex=length(InputPath)) and (InputPath[InputIndex]='.')) then begin inc(InputIndex,2); if OutputIndex=1 then begin inc(OutputIndex,2); end; end else if (((InputIndex+1)<=length(InputPath)) and (InputPath[InputIndex]='.') and (InputPath[InputIndex+1]='.')) and ((((InputIndex+2)<=length(InputPath)) and IsPathSeparator(InputPath[InputIndex+2])) or ((InputIndex+1)=length(InputPath))) then begin inc(InputIndex,3); if OutputIndex=1 then begin inc(OutputIndex,3); end else if OutputIndex>1 then begin dec(OutputIndex,2); while (OutputIndex>0) and not IsPathSeparator(result[OutputIndex]) do begin dec(OutputIndex); end; inc(OutputIndex); end; end else if IsPathSeparator(InputPath[InputIndex]) then begin if (InputIndex=1) and ((InputIndex+1)<=length(InputPath)) and IsPathSeparator(InputPath[InputIndex+1]) and ((length(InputPath)=2) or (((InputIndex+2)<=Length(InputPath)) and not IsPathSeparator(InputPath[InputIndex+2]))) then begin result[OutputIndex]:=InputPath[InputIndex]; result[OutputIndex+1]:=InputPath[InputIndex+1]; inc(InputIndex,2); inc(OutputIndex,2); end else begin if (OutputIndex=1) or ((OutputIndex>1) and not IsPathSeparator(result[OutputIndex-1])) then begin result[OutputIndex]:=InputPath[InputIndex]; inc(OutputIndex); end; inc(InputIndex); end; end else begin while (InputIndex<=length(InputPath)) and not IsPathSeparator(InputPath[InputIndex]) do begin result[OutputIndex]:=InputPath[InputIndex]; inc(InputIndex); inc(OutputIndex); end; if InputIndex<=length(InputPath) then begin result[OutputIndex]:=InputPath[InputIndex]; inc(InputIndex); inc(OutputIndex); end; end; end; SetLength(result,OutputIndex-1); end; function ConvertPathToRelative(aAbsolutePath,aBasePath:TpvRawByteString):TpvRawByteString; var AbsolutePathIndex,BasePathIndex:TpvInt32; PathSeparator:AnsiChar; begin if length(aBasePath)=0 then begin result:=aAbsolutePath; end else begin aAbsolutePath:=ExpandRelativePath(aAbsolutePath); aBasePath:=ExpandRelativePath(aBasePath); PathSeparator:=#0; for BasePathIndex:=1 to length(aBasePath) do begin if IsPathSeparator(aBasePath[BasePathIndex]) then begin PathSeparator:=aBasePath[BasePathIndex]; break; end; end; if PathSeparator=#0 then begin for AbsolutePathIndex:=1 to length(aAbsolutePath) do begin if IsPathSeparator(aAbsolutePath[AbsolutePathIndex]) then begin PathSeparator:=aAbsolutePath[AbsolutePathIndex]; break; end; end; if PathSeparator=#0 then begin PathSeparator:='/'; end; end; if length(aBasePath)>1 then begin if IsPathSeparator(aBasePath[length(aBasePath)]) then begin if (length(aAbsolutePath)>1) and IsPathSeparator(aAbsolutePath[length(aAbsolutePath)]) then begin if (aAbsolutePath=aBasePath) and (aAbsolutePath[1]<>'.') and (aBasePath[1]<>'.') then begin result:='.'+PathSeparator; exit; end; end; end else begin aBasePath:=aBasePath+PathSeparator; end; end; AbsolutePathIndex:=1; BasePathIndex:=1; while (BasePathIndex<=Length(aBasePath)) and (AbsolutePathIndex<=Length(aAbsolutePath)) and ((aBasePath[BasePathIndex]=aAbsolutePath[AbsolutePathIndex]) or (IsPathSeparator(aBasePath[BasePathIndex]) and IsPathSeparator(aAbsolutePath[AbsolutePathIndex]))) do begin inc(AbsolutePathIndex); inc(BasePathIndex); end; if ((BasePathIndex<=length(aBasePath)) and not IsPathSeparator(aBasePath[BasePathIndex])) or ((AbsolutePathIndex<=length(aAbsolutePath)) and not IsPathSeparator(aAbsolutePath[AbsolutePathIndex])) then begin while (BasePathIndex>1) and not IsPathSeparator(aBasePath[BasePathIndex-1]) do begin dec(AbsolutePathIndex); dec(BasePathIndex); end; end; if BasePathIndex<=Length(aBasePath) then begin result:=''; while BasePathIndex<=Length(aBasePath) do begin if IsPathSeparator(aBasePath[BasePathIndex]) then begin result:=result+'..'+PathSeparator; end; inc(BasePathIndex); end; end else begin result:='.'+PathSeparator; end; if AbsolutePathIndex<=length(aAbsolutePath) then begin result:=result+copy(aAbsolutePath,AbsolutePathIndex,(length(aAbsolutePath)-AbsolutePathIndex)+1); end; end; end; end.
unit CableConstants; { ---------------------------------------------------------- Copyright (c) 2008-2015, Electric Power Research Institute, Inc. All rights reserved. ---------------------------------------------------------- } interface Uses Arraydef, Ucmatrix, Ucomplex, LineUnits, LineConstants; TYPE TCableConstants = class(TLineConstants) private function Get_EpsR(i: Integer): Double; function Get_InsLayer(i, units: Integer): Double; function Get_DiaIns(i, units: Integer): Double; function Get_DiaCable(i, units: Integer): Double; procedure Set_EpsR(i: Integer; const Value: Double); procedure Set_InsLayer(i, units: Integer; const Value: Double); procedure Set_DiaIns(i, units: Integer; const Value: Double); procedure Set_DiaCable(i, units: Integer; const Value: Double); protected FEpsR :pDoubleArray; FInsLayer :pDoubleArray; FDiaIns :pDoubleArray; FDiaCable :pDoubleArray; public Function ConductorsInSameSpace(var ErrorMessage:String):Boolean;override; Procedure Kron(Norder:Integer);override; // don't reduce Y, it has zero neutral capacitance Constructor Create(NumConductors:Integer); Destructor Destroy; Override; Property EpsR[i:Integer]:Double Read Get_EpsR Write Set_EpsR; Property InsLayer[i, units:Integer]:Double Read Get_InsLayer Write Set_InsLayer; Property DiaIns[i, units:Integer]:Double Read Get_DiaIns Write Set_DiaIns; Property DiaCable[i, units:Integer]:Double Read Get_DiaCable Write Set_DiaCable; end; implementation uses SysUtils; procedure TCableConstants.Kron(Norder: Integer); Var Ztemp:TCmatrix; FirstTime:Boolean; i, j: Integer; begin Ztemp := FZMatrix; FirstTime := TRUE; If (FFrequency >= 0.0) and (Norder>0) and (Norder<FnumConds) Then Begin If Assigned(FZreduced) Then FZreduced.Free; If Assigned(FYCreduced) Then FYCReduced.Free; While Ztemp.Order > Norder Do Begin FZReduced := Ztemp.Kron(ZTemp.Order ); // Eliminate last row If Not FirstTime Then Ztemp.Free; // Ztemp points to intermediate matrix Ztemp := FZReduced; FirstTime := FALSE; End; // now copy part of FYCmatrix to FYCreduced FYCreduced := TCmatrix.CreateMatrix(Norder); for i:=1 to Norder do for j:=1 to Norder do FYCreduced.SetElement(i,j, FYCmatrix.GetElement(i,j)); End; end; function TCableConstants.ConductorsInSameSpace( var ErrorMessage: String): Boolean; var i,j :Integer; Dij :Double; Ri, Rj : Double; begin Result := FALSE; For i := 1 to FNumConds do Begin if (FY^[i] >= 0.0) then Begin Result := TRUE; ErrorMessage := Format('Cable %d height must be < 0. ', [ i ]); Exit End; End; For i := 1 to FNumConds do Begin if i <= FNumPhases then Ri := FRadius^[i] else Ri := 0.5 * FDiaCable^[i]; for j := i+1 to FNumConds do Begin if j <= FNumPhases then Rj := FRadius^[j] else Rj := 0.5 * FDiaCable^[j]; Dij := Sqrt(SQR(FX^[i] - FX^[j]) + SQR(FY^[i] - FY^[j])); if (Dij < (Ri + Rj)) then Begin Result := TRUE; ErrorMessage := Format('Cable conductors %d and %d occupy the same space.', [i, j ]); Exit; End; End; End; end; function TCableConstants.Get_EpsR(i: Integer): Double; begin Result := FEpsR^[i]; end; function TCableConstants.Get_InsLayer(i, units: Integer): Double; begin Result := FInsLayer^[i] * From_Meters(Units); end; function TCableConstants.Get_DiaIns(i, units: Integer): Double; begin Result := FDiaIns^[i] * From_Meters(Units); end; function TCableConstants.Get_DiaCable(i, units: Integer): Double; begin Result := FDiaCable^[i] * From_Meters(Units); end; procedure TCableConstants.Set_EpsR(i: Integer; const Value: Double); begin If (i>0) and (i<=FNumConds) Then FEpsR^[i] := Value; end; procedure TCableConstants.Set_InsLayer(i, units: Integer; const Value: Double); begin If (i>0) and (i<=FNumConds) Then FInsLayer^[i] := Value * To_Meters(units); end; procedure TCableConstants.Set_DiaIns(i, units: Integer; const Value: Double); begin If (i>0) and (i<=FNumConds) Then FDiaIns^[i] := Value * To_Meters(units); end; procedure TCableConstants.Set_DiaCable(i, units: Integer; const Value: Double); begin If (i>0) and (i<=FNumConds) Then FDiaCable^[i] := Value * To_Meters(units); end; constructor TCableConstants.Create( NumConductors: Integer); begin inherited Create (NumConductors); FEpsR:= Allocmem(Sizeof(FEpsR^[1])*FNumConds); FInsLayer:= Allocmem(Sizeof(FInsLayer^[1])*FNumConds); FDiaIns:= Allocmem(Sizeof(FDiaIns^[1])*FNumConds); FDiaCable:= Allocmem(Sizeof(FDiaCable^[1])*FNumConds); end; destructor TCableConstants.Destroy; begin Reallocmem(FEpsR, 0); Reallocmem(FInsLayer, 0); Reallocmem(FDiaIns, 0); Reallocmem(FDiaCable, 0); inherited; end; initialization end.
unit ImportExport; interface uses AvL, DataNode; type EImport = class(Exception) end; function ImportFile(const FileName: string): TDataNode; procedure ExportFile(const FileName: string; Data: TDataNode); const SImportFilter = 'Notik files|*.nib|All files|*.*'; implementation uses NotesFile; const SNotEnoughData = 'Not enough data'; SNotANIBFile = 'Not a NIB file'; SUnknownFileExtension = 'Unknown file extension'; NIBMagic = $0142494E; function ImportNIB(Source: TStream): TDataNode; function ReadStr: string; var StrLen: Integer; begin if (Source.Read(StrLen, SizeOf(StrLen)) <> SizeOf(StrLen)) or (Source.Size - Source.Position < StrLen) then raise EImport.Create(SNotEnoughData); SetLength(Result, StrLen); Source.Read(Result[1], StrLen); end; function GetLevel(const S: string): Integer; begin for Result := 1 to Length(S) do if S[Result] <> #09 then Exit; end; var i, Level: Integer; Magic: Cardinal; List: TStringList; CurNode: TDataNode; Text: string; begin Result := nil; Source.ReadBuffer(Magic, SizeOf(Magic)); if Magic <> NIBMagic then raise EImport.Create(SNotANIBFile); List := TStringList.Create; try List.Text := ReadStr; Result := TDataNode.Create; Result.Metadata[SMKCreated, ''] := List.Values['flCreate']; Result.Metadata[SMKAuthor, ''] := List.Values['Author']; Result.Metadata[SMKTitle, ''] := List.Values['Name']; List.Text := ReadStr; CurNode := Result; Level := 0; for i := 0 to List.Count - 1 do begin if GetLevel(List[i]) = Level then CurNode := CurNode.Parent else if GetLevel(List[i]) > Level then Level := Level + 1 else begin while GetLevel(List[i]) < Level do begin CurNode := CurNode.Parent; Level := Level - 1; end; CurNode := CurNode.Parent; end; CurNode := CurNode.Children[CurNode.Children.Add(TDataNode.Create)]; CurNode.Name := TrimLeft(List[i]); Text := ReadStr; if Text <> '' then with CurNode.Streams[CurNode.Streams.Add(TDataStream.Create)] do begin Name := SNNodeText; MIMEType := SMTPlainText; //TODO: Apply default compression Data.Write(Text[1], Length(Text)); end; end; finally List.Free; end; end; function ImportFile(const FileName: string): TDataNode; var Source: TFileStream; begin Result := nil; if not FileExists(FileName) then Exit; Source := TFileStream.Create(FileName, fmOpenRead); try if LowerCase(ExtractFileExt(FileName)) = '.nib' then Result := ImportNIB(Source) else raise EImport.Create(SUnknownFileExtension); finally Source.Free; end; end; procedure ExportFile(const FileName: string; Data: TDataNode); begin end; end.
unit ufrmDialogFinalPayment; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmMasterDialog, StdCtrls, ExtCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxMaskEdit, cxSpinEdit, cxTimeEdit, cxTextEdit, cxCurrencyEdit; // tambahan // Ini juga tambahan type // TFormMode = (fmAdd, fmEdit); TfrmDialogFinalPayment = class(TfrmMasterDialog) lbl4: TLabel; edtPOSCode: TEdit; lbl1: TLabel; lbl2: TLabel; edtCashierID: TEdit; lbl3: TLabel; edtFinPay: TcxCurrencyEdit; edtClock: TcxTimeEdit; edtFinPay1: TcxCurrencyEdit; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure footerDialogMasterbtnSaveClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure edtFinPay1Enter(Sender: TObject); private FIsProcessSuccessfull: boolean; // FFormMode: TFormMode; FNominalEdit: Double; FNominalSisa: Double; // procedure SetFormMode(const Value: TFormMode); procedure SetIsProcessSuccessfull(const Value: boolean); public { Public declarations } balanceID: Integer; balanceUnitID: Integer; posCode: String; cashierID: String; totalFinalPayment: Currency; property NominalEdit: Double read FNominalEdit write FNominalEdit; property NominalSisa: Double read FNominalSisa write FNominalSisa; published // property FormMode: TFormMode read FFormMode write SetFormMode; property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull; end; var frmDialogFinalPayment: TfrmDialogFinalPayment; implementation uses uConn, uRetnoUnit, uTSCommonDlg; {$R *.dfm} procedure TfrmDialogFinalPayment.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; end; procedure TfrmDialogFinalPayment.FormDestroy(Sender: TObject); begin inherited; frmDialogFinalPayment := nil; end; //procedure TfrmDialogFinalPayment.SetFormMode(const Value: TFormMode); //begin // FFormMode := Value; //end; procedure TfrmDialogFinalPayment.SetIsProcessSuccessfull( const Value: boolean); begin FIsProcessSuccessfull := Value; end; procedure TfrmDialogFinalPayment.footerDialogMasterbtnSaveClick( Sender: TObject); begin inherited; IsProcessSuccessfull := False; // Dihilangkan untuk pengecekkan nominal inputan final payment dari kasir { if edtFinPay.Value > (NominalEdit + NominalSisa) then begin CommonDlg.ShowError('Nilai final payment tidak boleh melebihi payment cash!'); exit; end; } { with TNewFinalPayment.CreateWithUser(Self,FLoginId,FLoginUnitId) do begin try Self.Enabled := False; UpdateData(0,balanceID, edtFinPay.Value, dialogunit, edtFinPay.Value); if not BeginningBalance.POS.IsActive then begin CommonDlg.ShowError('POS ' + BeginningBalance.POS.Code + ' sudah tidak Active' + #13 + 'Final Payment Tidak Bisa Dilaksanakan'); Exit; end; IsProcessSuccessfull := SaveToDB; if IsProcessSuccessfull then begin cCommitTrans; end else begin cRollbackTrans; CommonDlg.ShowError('Gagal Update Data!! Cek Total droping'); end; finally Free; Self.Enabled := True; end; end; Close; Exit; } end; procedure TfrmDialogFinalPayment.FormShow(Sender: TObject); begin inherited; edtFinPay.Value := 0; edtFinPay.SelectAll; edtPOSCode.Text := posCode; edtCashierID.Text := cashierID; edtFinPay.Value := totalFinalPayment; end; procedure TfrmDialogFinalPayment.edtFinPay1Enter(Sender: TObject); begin inherited; edtFinPay.SelectAll; end; end.
{ Renamer v1.1 created by matortheeternal * CHANGES * - Removed redundant bethesdaFiles listing - it's inherited from mteFunctions.pas. - Renamed the script to "Renamer" - Created user interface - Flexible handling of conditions and functions. * DESCRIPTION * This script can be used to rename items in bulk. } unit UserScript; uses mteFunctions; const vs = 'v1.1'; sConditions = 'True'#13'HasKeyword'#13'HasSubstringInFULL'#13'HasSubstringInEDID'; sFunctions = 'Replace'#13'SnipTextBefore'#13'SnipTextAfter'#13'AddPrefix'#13'AddSuffix'; var slConditions, slFunctions, slCVars, slFVars, slCsv, slKeywords, slRecords: TStringList; frm: TForm; lbl1, lbl2, padding: TLabel; pnlBottom: TPanel; sb: TScrollBox; kb1, kb2: TCheckBox; btnOk, btnCancel, btnPlus, btnMinus, btnSave, btnLoad: TButton; lstCondition, lstCVar, lstFunction, lstFVar: TList; save, eCsv: boolean; SaveDialog: TSaveDialog; OpenDialog: TOpenDialog; //========================================================================= // LoadCVars: Loads condition variable choices into the appropriate combobox procedure LoadCVars(Sender: TObject); var index: integer; t: string; begin if Assigned(Sender) then begin index := lstCondition.IndexOf(Sender); if index = -1 then exit; end else index := Pred(lstCondition.Count); t := TComboBox(lstCondition[index]).Text; if t = 'HasKeyword' then TComboBox(lstCVar[index]).Items.Text := slKeywords.Text else TComboBox(lstCVar[index]).Items.Text := ''; if t = 'True' then TComboBox(lstCVar[index]).Enabled := false else TComboBox(lstCVar[index]).Enabled := true; end; //========================================================================= // AddFunctionEntry: Creates a new function entry procedure AddFunctionEntry(c: integer; cv: string; f: integer; fv: string); var ed: TEdit; cb01, cb02, cb03: TCombBox; begin cb01 := TComboBox.Create(frm); cb01.Parent := sb; cb01.Left := 8; if lstCondition.Count = 0 then cb01.Top := 10 else begin cb01.Top := TComboBox(lstCondition[Pred(lstCondition.Count)]).Top + 30; padding.Top := cb01.Top + 20; end; cb01.Width := 120; cb01.Style := csDropDownList; cb01.Items.Text := sConditions; cb01.ItemIndex := 0; cb01.OnSelect := LoadCVars; lstCondition.Add(cb01); if Assigned(c) then cb01.ItemIndex := c; cb02 := TComboBox.Create(frm); cb02.Parent := sb; cb02.Left := cb01.Left + cb01.Width + 8; cb02.Top := cb01.Top; cb02.Width := 150; cb02.Items.Text := ''; cb02.ItemIndex := 0; lstCVar.Add(cb02); LoadCVars(nil); if Assigned(cv) then cb02.Text := cv; cb03 := TCombobox.Create(frm); cb03.Parent := sb; cb03.Left := cb02.Left + cb02.Width + 8; cb03.Top := cb01.Top; cb03.Style := csDropDownList; cb03.Width := 100; cb03.Items.Text := sFunctions; cb03.ItemIndex := 0; lstFunction.Add(cb03); if Assigned(f) then cb03.ItemIndex := f; ed := TEdit.Create(frm); ed.Parent := sb; ed.Left := cb03.Left + cb03.Width + 8; ed.Top := cb01.Top; ed.Width := 100; lstFVar.Add(ed); if Assigned(fv) then ed.Text := fv; end; //========================================================================= // DelFunctionEntry: deletes a function entry procedure DelFunctionEntry; begin if lstFunction.Count > 0 then begin TComboBox(lstCondition[Pred(lstCondition.Count)]).Free; TComboBox(lstCVar[Pred(lstCVar.Count)]).Free; TComboBox(lstFunction[Pred(lstFunction.Count)]).Free; TEdit(lstFVar[Pred(lstFVar.Count)]).Free; lstCondition.Delete(Pred(lstCondition.Count)); lstFunction.Delete(Pred(lstFunction.Count)); lstCVar.Delete(Pred(lstCVar.Count)); lstFVar.Delete(Pred(lstFVar.Count)); padding.Top := padding.Top - 30; end; end; //========================================================================= // LoadFunctions: Loads functions from a text file procedure LoadFunctions(fn: filename); var slLoad: TStringList; i: integer; s, s1, s2, s3, s4: string; begin // create loading stringlist slLoad := TStringList.Create; // open dialog and load procedure if OpenDialog.Execute then begin slLoad.LoadFromFile(OpenDialog.FileName); // clear current functions while lstFunction.Count > 0 do DelFunctionEntry; // create new functions with data from file for i := 0 to slLoad.Count - 1 do begin s := slLoad[i]; s1 := CopyFromTo(s, 1, ItPos(',', s, 1) - 1); s2 := CopyFromTo(s, ItPos(',', s, 1) + 1, ItPos(',', s, 2) - 1); s3 := CopyFromTo(s, ItPos(',', s, 2) + 1, ItPos(',', s, 3) - 1); s4 := CopyFromTo(s, ItPos(',', s, 3) + 1, Length(s)); AddFunctionEntry(StrToInt(s1), s2, StrToInt(s3), s4); end; end; slLoad.Free; end; //========================================================================= // SaveFunctions: Saves functions to a text file procedure SaveFunctions(fn: filename); var i: integer; s: string; slSave: TStringList; begin // create saving stringlist slSave := TStringList.Create; // save dialog and save procedure if SaveDialog.Execute then begin for i := 0 to lstCondition.Count - 1 do begin if (TComboBox(lstCondition[i]).Text = '') or (TComboBox(lstCVar[i]).Text = '') or (TEdit(lstFVar[i]).Text = '') then Continue; // build line string s := IntToStr(TComboBox(lstCondition[i]).ItemIndex); s := s + ',' + TComboBox(lstCVar[i]).Text; s := s + ',' + IntToStr(TComboBox(lstFunction[i]).ItemIndex); s := s + ',' + TEdit(lstFVar[i]).Text; // add line to slSave slSave.Add(s); end; // save to file slSave.SaveToFile(SaveDialog.FileName); end; slSave.Free; end; //========================================================================= // FunctionManager: manages function entries procedure frm.FunctionManager(Sender: TObject); begin if Sender = btnPlus then begin AddFunctionEntry(nil, nil, nil, nil); end; if (Sender = btnMinus) and (lstCondition.Count > 1) then begin DelFunctionEntry; end; end; //========================================================================= // OptionsForm procedure OptionsForm; var i: integer; begin frm := TForm.Create(nil); try frm.Caption := 'Renamer '+vs; frm.Width := 550; frm.Height := 400; frm.Position := poScreenCenter; frm.BorderStyle := bsDialog; sb := TScrollBox.Create(frm); sb.Parent := frm; sb.Height := 180; sb.Width := frm.Width - 5; sb.Top := 30; padding := TLabel.Create(frm); padding.Parent := sb; padding.Caption := ''; pnlBottom := TPanel.Create(frm); pnlBottom.Parent := frm; pnlBottom.BevelOuter := bvNone; pnlBottom.Align := alBottom; pnlBottom.Height := 160; SaveDialog := TSaveDialog.Create(frm); SaveDialog.Title := 'Save functions'; SaveDialog.Filter := 'Text documents|*.txt'; SaveDialog.DefaultExt := 'txt'; SaveDialog.InitialDir := ProgramPath + 'Edit Scripts\'; btnSave := TButton.Create(frm); btnSave.Parent := pnlBottom; btnSave.Caption := 'S'; btnSave.ShowHint := true; btnSave.Hint := 'Save functions'; btnSave.Width := 25; btnSave.Left := 12; btnSave.Top := 5; btnSave.OnClick := SaveFunctions; OpenDialog := TOpenDialog.Create(frm); OpenDialog.Title := 'Load functions'; OpenDialog.Filter := 'Text documents|*.txt'; OpenDialog.DefaultExt := 'txt'; OpenDialog.InitialDir := ProgramPath + 'Edit Scripts\'; btnLoad := TButton.Create(frm); btnLoad.Parent := pnlBottom; btnLoad.Caption := 'L'; btnLoad.ShowHint := true; btnLoad.Hint := 'Load functions'; btnLoad.Width := 25; btnLoad.Left := btnSave.Left + btnSave.Width + 5; btnLoad.Top := btnSave.Top; btnLoad.OnClick := LoadFunctions; btnPlus := TButton.Create(frm); btnPlus.Parent := pnlBottom; btnPlus.Caption := '+'; btnPlus.ShowHint := true; btnPlus.Hint := 'Add function'; btnPlus.Width := 25; btnPlus.Left := frm.Width - 80; btnPlus.Top := 5; btnPlus.OnClick := FunctionManager; btnMinus := TButton.Create(frm); btnMinus.Parent := pnlBottom; btnMinus.Caption := '-'; btnMinus.ShowHint := true; btnMinus.Hint := 'Remove function'; btnMinus.Width := 25; btnMinus.Left := btnPlus.Left + btnPlus.Width + 5; btnMinus.Top := btnPlus.Top; btnMinus.OnClick := FunctionManager; lbl1 := TLabel.Create(frm); lbl1.Parent := frm; lbl1.Top := 8; lbl1.Left := 8; lbl1.Width := 360; lbl1.Height := 25; lbl1.Caption := 'Specify the functions you want to apply for renaming below: '; lbl2 := TLabel.Create(frm); lbl2.Parent := pnlBottom; lbl2.Top := btnPlus.Top + btnPlus.Height + 20; lbl2.Left := 8; lbl2.AutoSize := False; lbl2.Wordwrap := True; lbl2.Width := 360; lbl2.Caption := 'Other options:'; kb1 := TCheckBox.Create(frm); kb1.Parent := pnlBottom; kb1.Top := lbl2.Top + 20; kb1.Left := 8; kb1.Width := 150; kb1.Caption := ' Save to Records'; kb2 := TCheckBox.Create(frm); kb2.Parent := pnlBottom; kb2.Top := kb1.Top + 20; kb2.Left := 8; kb2.Width := 150; kb2.Caption := ' Export to .csv'; btnOk := TButton.Create(frm); btnOk.Parent := pnlBottom; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := frm.Width div 2 - btnOk.Width - 8; btnOk.Top := kb2.Top + 30; btnCancel := TButton.Create(frm); btnCancel.Parent := pnlBottom; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 16; btnCancel.Top := btnOk.Top; // add default function entry AddFunctionEntry(nil, nil, nil, nil); if frm.ShowModal = mrOk then begin for i := 0 to lstCondition.Count - 1 do begin if (TComboBox(lstCondition[i]).Text = '') or (TComboBox(lstFunction[i]).Text = '') or (TComboBox(lstFVar[i]).Text = '') then Continue; // add form values to stringlists slConditions.Add(TComboBox(lstCondition[i]).Text); slCVars.Add(TComboBox(lstCVar[i]).Text); slFunctions.Add(TComboBox(lstFunction[i]).Text); slFVars.Add(TComboBox(lstFVar[i]).Text); end; // save boolean options if kb1.Checked = cbChecked then save := true; if kb2.Checked = cbChecked then eCsv := true; end; finally frm.Free; end; end; //========================================================================= // Rename: executes a specified name changing function function Rename(name: string; func: string; fvar: string): string; var find, replace: string; begin Result := name; if func = 'Replace' then begin find := CopyFromTo(fvar, 1, Pos(',', fvar) - 1); replace := CopyFromTo(fvar, Pos(',', fvar) + 1, Length(fvar)); Result := StringReplace(name, find, replace, [rfReplaceAll]); end else if (func = 'SnipTextBefore') and (Pos(fvar, name) > 0) then Result := CopyFromTo(name, Pos(fvar, name), Length(name)) else if (func = 'SnipTextAfter') and (Pos(fvar, name) > 0) then Result := CopyFromTo(name, 1, Pos(fvar, name) + Length(fvar) - 1) else if func = 'AddPrefix' then Result := fvar + name else if func = 'AddSuffix' then Result := name + fvar; end; //========================================================================= // initialize stuff function Initialize: integer; var f, group, e: IInterface; i, j: integer; begin // welcome messages AddMessage(#13#10); AddMessage('----------------------------------------------------------'); AddMessage('Renamer '+vs+': renames items.'); AddMessage('----------------------------------------------------------'); AddMessage(''); // create lists slRecords := TStringList.Create; slConditions := TStringList.Create; slFunctions := TStringList.Create; slCVars := TStringList.Create; slFVars := TStringList.Create; slKeywords := TStringList.Create; slKeywords.Sorted := true; slCsv := TStringList.Create; slCsv.Add('Record,EDID,DATA\Value'); lstCondition := TList.Create; lstCVar := TList.Create; lstFunction := TList.Create; lstFVar := TList.Create; // load keywords stringlist for i := 0 to FileCount - 1 do begin f := FileByIndex(i); group := GroupBySignature(f, 'KYWD'); for j := 0 to ElementCount(group) - 1 do begin e := ElementByIndex(group, j); slKeywords.Add(geev(e, 'EDID')); end; end; end; //========================================================================= // process selected records function Process(e: IInterface): integer; var bnam: IInterface; begin if geev(e, 'FULL') = '' then exit; slRecords.AddObject(geev(e, 'FULL'), TObject(e)); end; //========================================================================= // finalize: where all the stuff happens function Finalize: integer; var i, j: integer; rec: IInterface; skip: boolean; name, edid: string; begin // options form OptionsForm; // exit if no functions were assigned if slFunctions.Count = 0 then exit; // loop through COBJ records AddMessage('Renaming items...'); for i := 0 to slRecords.Count - 1 do begin AddMessage(' Processing '+slRecords[i]); rec := ObjectToElement(slRecords.Objects[i]); edid := geev(ObjectToElement(slRecords.Objects[i]), 'EDID'); name := slRecords[i]; for j := 0 to slConditions.Count - 1 do begin if slConditions[j] = 'True' then begin name := Rename(name, slFunctions[j], slFVars[j]); end else if slConditions[j] = 'HasKeyword' then begin if HasKeyword(rec, slCVars[j]) then name := Rename(name, slFunctions[j], slFVars[j]); end else if slConditions[j] = 'HasSubstringInFULL' then begin if Pos(slCVars[j], slRecords[j]) > 0 then name := Rename(name, slFunctions[j], slFVars[j]); end else if slConditions[j] = 'HasSubstringInEDID' then begin if Pos(slCVars[j], edid) > 0 then name := Rename(name, slFunctions[j], slFVars[j]); end; end; if name <> slRecords[i] then AddMessage(' Renamed to: '+name); // save values if save then if (Pos(GetFileName(GetFile(rec)), bethesdaFiles) = 0) then seev(rec, 'FULL', name); // export values if eCsv then slCsv.Add(IntToStr(FormID(rec))+','+geev(rec, 'FULL')+','+name); end; AddMessage(''); if eCsv then slCsv.SaveToFile(ProgramPath + 'Edit Scripts\Renamed items.csv'); end; end.
{ p_40_1.pas - программа "вопрос-ответ" с применением массива } program p_40_1; const cAnswers = 100; { размер массива с ответами } { объявление типа для массива ответов } type tAnswers = array[1..cAnswers] of string; var answers: tAnswers; { объявление массива ответов } fact: integer; { фактическое количество ответов } f: text; { файл с ответами } s: string; { строка с вопросом } { Процедура ввода ответов из файла с подсчетом введенных строк } procedure ReadFromFile(var aFile: text); var i: integer; begin fact := 0; for i:=1 to cAnswers do begin if Eof(aFile) then Break; Readln(aFile, answers[i]); fact := fact + 1; end; end; {----- Главная программа -----} begin Assign(f, 'p_40_1_in.txt'); Reset(f); ReadFromFile(f); Close(f); Randomize; repeat Write('Введите вопрос: '); Readln(s); if s<>'' then Writeln(answers[Random(fact)+1]); until s=''; end.
Unit ZBreak; {################################} {# ZiLEM Z80 Emulator #} {# Breakpoints #} {# Copyright (c) 1994 James Ots #} {# All rights reserved #} {################################} Interface Uses Objects, Views, Drivers, Dialogs, ZEngine, ZGlobals, ZHex, ZConsts, ZInputs, MsgBox; Type PBreakpointItem = ^TBreakpointItem; TBreakpointItem = Object(TObject) PZMem : Pointer; Address : Word; OldCode, PassCount: Byte; Constructor Init(AnAddress : Word; APassCount : Byte; APZMem : Pointer); Destructor Done; virtual; End; PBreakpointCollection = ^TBreakpointCollection; TBreakpointCollection = Object(TCollection) PZMem : Pointer; MyAddress : Word; Constructor Init(APZMem : Pointer); Procedure Create(AnAddress : Word; APassCount : Byte); Function BreakAt(AnAddress : Word; var AResult : Byte) : Boolean; Function GetOld(AnAddress : Word) : Byte; Procedure Kill(AnAddress : Word); Procedure Error(Code, Info : Integer); virtual; Function Exists : Pointer; End; PBreakpointListBox = ^TBreakpointListBox; TBreakpointListBox = Object(TListBox) Function GetText(Item : Integer; MaxLen : Integer) : String; virtual; End; PBreakpointDialog = ^TBreakpointDialog; TBreakpointDialog = Object(TDialog) VScrollBar : PScrollBar; BreakpointListBox : PBreakpointListBox; BreakpointCollection : PBreakpointCollection; Constructor Init(ABreakpointCollection : PBreakpointCollection); Procedure HandleEvent(var Event : TEvent); virtual; End; PAddBreakpointDialog = ^TAddBreakpointDialog; TAddBreakpointDialog = Object(TDialog) BreakpointInputLine : PAddressInputLine; PasscountInputLine : PByteInputLine; BreakpointCollection : PBreakpointCollection; Constructor Init(ABreakpointCollection : PBreakpointCollection; AnAddress : Longint); Procedure HandleEvent(var Event : TEvent); virtual; End; Implementation {*********************************************************************} {*********************************************************************} Function TBreakpointListBox.GetText(Item : Integer; MaxLen : Integer) : String; Var TempStr : String; Info : Record Address, Passcount, OldCode : Longint; End; Begin With Info do Begin Address := Longint(PBreakpointItem(List^.At(Item))^.Address); Passcount := Longint(PBreakpointItem(List^.At(Item))^.Passcount); OldCode := Longint(PBreakpointItem(List^.At(Item))^.OldCode); End; If Pref.Base=0 then FormatStr(TempStr,' $%04x $%02x $%02x ',Info) else FormatStr(TempStr,' %5d %3d %3d ',Info); GetText := TempStr; End; {*********************************************************************} {*********************************************************************} Constructor TBreakpointDialog.Init(ABreakpointCollection : PBreakpointCollection); Var R : TRect; PBreakpointButton : PButton; Info : Record List : Pointer; Item : Word; End; Begin R.Assign(0,0,26,16); Inherited Init(R,'Breakpoints'); Options := Options or ofCentered; BreakpointCollection := ABreakpointCollection; R.Assign(22,3,23,10); VScrollBar := New(PScrollBar,Init(R)); Insert(VScrollBar); R.Assign(3,3,22,10); BreakpointListBox := New(PBreakpointListBox,Init(R,1,VScrollBar)); BreakpointListBox^.HelpCtx := hcBreakpointListBox; Info.List := BreakpointCollection; Info.Item := 0; BreakpointListBox^.SetData(Info); Insert(BreakpointListBox); R.Assign(3,2,20,3); Insert(New(PLabel,Init(R,'~A~ddress Pass Old',BreakpointListBox))); R.Assign(2,11,12,13); PBreakpointButton := New(PButton,Init(R,'O~k~',cmOk,bfDefault)); PBreakpointButton^.HelpCtx := hcOkButton; Insert(PBreakpointButton); R.Assign(14,11,24,13); PBreakpointButton := New(PButton,Init(R,'~A~dd',cmAddBreakpoint, bfDefault)); PBreakpointButton^.HelpCtx := hcAddBreakpointButton; Insert(PBreakpointButton); R.Assign(14,13,24,15); PBreakpointButton := New(PButton,Init(R,'~R~emove',cmRemoveBreakpoint, bfDefault)); PBreakpointButton^.HelpCtx := hcRemoveBreakpointButton; Insert(PBreakpointButton); SelectNext(False); End; Procedure TBreakpointDialog.HandleEvent(var Event : TEvent); Var Info : Record List : PBreakpointCollection; Item : Word; End; Begin If Event.What = evCommand then Case Event.Command of cmAddBreakpoint: Begin Owner^.ExecView(New(PAddBreakpointDialog,Init(BreakpointCollection, 0))); BreakpointListBox^.SetRange(BreakpointCollection^.Count); BreakpointListBox^.DrawView; ClearEvent(Event); End; cmRemoveBreakpoint: Begin BreakpointListBox^.GetData(Info); If BreakpointCollection^.Count > 0 then Begin Info.List^.Free(Info.List^.Items^[Info.Item]); BreakpointListBox^.SetRange(Pred(BreakpointListBox^.Range)); BreakpointListBox^.DrawView; End; ClearEvent(Event); End; End; Inherited HandleEvent(Event); End; {*********************************************************************} {*********************************************************************} Constructor TAddBreakpointDialog.Init(ABreakpointCollection : PBreakpointCollection; AnAddress : Longint); Var R : TRect; ANum : Longint; PBreakpointButton : PButton; Begin R.Assign(0,0,27,11); Inherited Init(R,'Add Breakpoint'); Options := Options or ofCentered; BreakpointCollection := ABreakpointCollection; R.Assign(3,3,13,4); BreakpointInputLine := New(PAddressInputLine,Init(R, hcBreakpointInputLine)); BreakpointInputLine^.SetData(AnAddress); Insert(BreakpointInputLine); R.Assign(2,2,21,3); Insert(New(PLabel,Init(R,'~B~reakpoint address',BreakpointInputLine))); R.Assign(3,6,13,7); PasscountInputLine := New(PByteInputLine,Init(R,hcPasscountInputLine)); ANum := 0; PasscountInputLine^.SetData(ANum); Insert(PasscountInputLine); R.Assign(2,5,21,6); Insert(New(PLabel,Init(R,'~P~asscount',PasscountInputLine))); R.Assign(2,8,12,10); PBreakpointButton := New(PButton,Init(R,'O~k~',cmEnterBreakpoint, bfDefault)); PBreakpointButton^.HelpCtx := hcAddBreakpointButton; Insert(PBreakpointButton); R.Assign(14,8,24,10); PBreakpointButton := New(PButton,Init(R,'~C~ancel',cmCancel,bfNormal)); PBreakpointButton^.HelpCtx := hcCancelButton; Insert(PBreakpointButton); SelectNext(False); End; {of TPasteDialog.Init} Procedure TAddBreakpointDialog.HandleEvent(var Event : TEvent); Var Address, Passcount : Longint; Begin If (Event.What = evCommand) and (Event.Command = cmEnterBreakpoint) and BreakpointInputLine^.Valid(cmOk) and PasscountInputLine^.Valid(cmOk) then Begin BreakpointInputLine^.GetData(Address); PasscountInputLine^.GetData(Passcount); BreakpointCollection^.Create(Address,Passcount); Event.Command := cmOk; End; Inherited HandleEvent(Event); End; {*********************************************************************} {*********************************************************************} Constructor TBreakpointItem.Init(AnAddress : Word; APassCount : Byte; APZMem : Pointer); Begin Inherited Init; PZMem := APZMem; Address := AnAddress; PassCount := APassCount; OldCode := Byte((Ptr(Seg(PZMem^),Ofs(PZmem^)+Address))^); Byte((Ptr(Seg(PZMem^),Ofs(PZmem^)+Address))^) := $76; End; Destructor TBreakpointItem.Done; Begin Inherited Done; If Byte((Ptr(Seg(PZMem^),Ofs(PZmem^)+Address))^) <> $76 then Begin If MessageBox(#3'The halt instruction at this'#13+ #3'breakpoint has been changed.'#13+ #3'Do you want to leave it like this?',nil,mfConfirmation or mfYesButton or mfNoButton) = cmNo then End else Byte((Ptr(Seg(PZMem^),Ofs(PZmem^)+Address))^) := OldCode; End; {*********************************************************************} {*********************************************************************} Function TBreakpointCollection.Exists : Pointer; Var i : Integer; Temp : Pointer; Begin Temp := nil; i := 0; If Count>0 then Repeat If PBreakpointItem(Items^[i])^.Address = MyAddress then Temp := Items^[i]; Inc(i); Until (i >= Count) or (Temp <> nil); Exists := Temp; End; Constructor TBreakpointCollection.Init(APZMem : Pointer); Begin Inherited Init(40,20); PZMem := APZMem; End; Procedure TBreakpointCollection.Create(AnAddress : Word; APassCount : Byte); Begin MyAddress := AnAddress; If Exists <> nil then Error(coBreakpointExists,Integer(AnAddress)) else Insert(New(PBreakpointItem,Init(AnAddress,APassCount,PZMem))); End; Function TBreakpointCollection.BreakAt(AnAddress : Word; var AResult : Byte) : Boolean; Var BreakItem : PBreakpointItem; Begin MyAddress := AnAddress; BreakItem := PBreakpointItem(Exists); If BreakItem = nil then Begin BreakAt := False; AResult := exUserHalt; End else Begin If BreakItem^.PassCount = 1 then BreakAt := True else BreakAt := False; If BreakItem^.PassCount > 1 then Begin Dec(BreakItem^.PassCount); AResult := exOk; End; If BreakItem^.PassCount = 0 then Begin Kill(AnAddress); AResult := exStop; End; End; End; Procedure TBreakpointCollection.Kill(AnAddress : Word); Var BreakItem : PBreakpointItem; Begin MyAddress := AnAddress; BreakItem := PBreakpointItem(Exists); If BreakItem <> nil then Free(BreakItem); End; Function TBreakpointCollection.GetOld(AnAddress : Word) : Byte; Var BreakItem : PBreakpointItem; Begin MyAddress := AnAddress; BreakItem := PBreakpointItem(Exists); If BreakItem <> nil then GetOld := BreakItem^.OldCode; End; Procedure TBreakpointCollection.Error(Code, Info : Integer); Begin If Code = coBreakpointExists then MessageBox(#3'A breakpoint already exists'#13#13+ #3'at this address',nil,mfError or mfOkButton) else Inherited Error(Code, Info); End; End.
unit USnapshot; interface uses Classes, contnrs{, UObservers}; type IUndoRedo = interface ['{596D4B08-CCF2-47E1-A901-F69E4EF800ED}'] function GetHasUndo: boolean; function GetHasRedo: boolean; procedure DoUndo; procedure DoRedo; end; // ISubjectAddSnapshot = interface(ISubject) // ['{BD66D863-E0EE-4113-B287-BEA322FDC480}'] // function GetSheetID: TGuoidString; // procedure SetSheetID(const value: TGuoidString); // property SheetID: TGuoidString read GetSheetID write SetSheetID; // end; TSnapshot = class protected function GetAsString: string; virtual; abstract; procedure SetAsString(const Value: string); virtual; abstract; public function Equals(oWith: TSnapshot): boolean; virtual; property AsString: string read GetAsString write SetAsString; end; TSnapshotList = class(TObjectList) private FCurrentSnapshotIndex: integer; FActive: boolean; function GetCurrentSnapshotIndex: integer; procedure SetCurrentSnapshotIndex(const Value: integer); function GetItems(index: integer): TSnapshot; procedure SetItems(index: integer; const Value: TSnapshot); function GetHasUndo: boolean; function GetHasRedo: boolean; public property Active: boolean read FActive write FActive; property CurrentSnapshotIndex: integer read GetCurrentSnapshotIndex write SetCurrentSnapshotIndex; property Items[index: integer]: TSnapshot read GetItems write SetItems; property HasUndo: boolean read GetHasUndo; property HasRedo: boolean read GetHasRedo; procedure ActionDo(oNewSnapshot: TSnapshot); function ActionUndo: TSnapshot; function ActionRedo: TSnapshot; procedure Clear; override; end; //function GetSubjectAddSnapshot: ISubjectAddSnapshot; implementation uses SysUtils; //type // TSubjectAddSnapshot = class(TSubject, ISubjectAddSnapshot) // private // FSheetID: TGuoidString; // protected // function GetSheetID: TGuoidString; // procedure SetSheetID(const value: TGuoidString); // end; // //var // gl_SubjectAddSnapshot: ISubjectAddSnapshot; // //function GetSubjectAddSnapshot: ISubjectAddSnapshot; //begin // if not Assigned(gl_SubjectAddSnapshot) then // gl_SubjectAddSnapshot := TSubjectAddSnapshot.Create; // Result := gl_SubjectAddSnapshot; //end; // //function MakeOneLine(strLine: string): string; //var // i: integer; //begin // Result := strLine; // for i := 1 to Length(strLine) do // if Result[i] = #$a then // Result[i] := '_'; //end; // { TSnapshotList } procedure TSnapshotList.ActionDo(oNewSnapshot: TSnapshot); begin if FActive then begin if FCurrentSnapshotIndex <> -1 then begin if Items[FCurrentSnapshotIndex].Equals(oNewSnapshot) then begin oNewSnapshot.Free; exit; end; while (FCurrentSnapshotIndex + 1) < Count do begin Delete(FCurrentSnapshotIndex + 1); end; end; FCurrentSnapshotIndex := Add(oNewSnapshot); //gl_DebugSnapshots.Add(MakeOneLine(oNewSnapshot.AsString )); //gl_DebugSnapshots.Add('ActionDo - FCurrentSnapshotIndex=' + IntToStr(FCurrentSnapshotIndex)); //gl_DebugSnapshots.SaveToFile('D:\temp\snapshots.txt'); while Count > 30 do begin Delete(0); dec(FCurrentSnapshotIndex); end; end; end; function TSnapshotList.GetCurrentSnapshotIndex: integer; begin Result := FCurrentSnapshotIndex; end; function TSnapshotList.GetHasRedo: boolean; begin Result := FActive and ((FCurrentSnapshotIndex + 1) < Count); end; function TSnapshotList.GetHasUndo: boolean; begin Result := FActive and (FCurrentSnapshotIndex > 0); end; function TSnapshotList.GetItems(index: integer): TSnapshot; begin Result := inherited Items[index] as TSnapshot; end; function TSnapshotList.ActionRedo: TSnapshot; begin if FActive then begin if HasRedo then begin inc(FCurrentSnapshotIndex); end; Result := Items[FCurrentSnapshotIndex]; end; end; function TSnapshotList.ActionUndo: TSnapshot; begin if FActive then begin if HasUndo then begin dec(FCurrentSnapshotIndex); end; Result := Items[FCurrentSnapshotIndex]; end; end; procedure TSnapshotList.Clear; begin inherited; FCurrentSnapshotIndex := -1; FActive := false; end; procedure TSnapshotList.SetCurrentSnapshotIndex(const Value: integer); begin if (Value >= 0) and (Value < Count) then begin FCurrentSnapshotIndex := Value; end; end; procedure TSnapshotList.SetItems(index: integer; const Value: TSnapshot); begin inherited Items[index] := Value; end; { TSnapshot } function TSnapshot.Equals(oWith: TSnapshot): boolean; begin Result := AsString = oWith.AsString; end; //initialization // gl_DebugSnapshots := TStringList.Create; //finalization // FreeAndNil(gl_DebugSnapshots); { TSubjectAddSnapshot } //function TSubjectAddSnapshot.GetSheetID: TGuoidString; //begin // Result := FSheetID; //end; // //procedure TSubjectAddSnapshot.SetSheetID(const value: TGuoidString); //begin // FSheetID := Value; //end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [FIN_PARCELA_PAGAMENTO] 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 FinParcelaPagamentoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('FIN_PARCELA_PAGAMENTO')] TFinParcelaPagamentoVO = class(TVO) private FID: Integer; FID_FIN_PARCELA_PAGAR: Integer; FID_FIN_CHEQUE_EMITIDO: Integer; FID_FIN_TIPO_PAGAMENTO: Integer; FID_CONTA_CAIXA: Integer; FDATA_PAGAMENTO: TDateTime; FTAXA_JURO: Extended; FTAXA_MULTA: Extended; FTAXA_DESCONTO: Extended; FVALOR_JURO: Extended; FVALOR_MULTA: Extended; FVALOR_DESCONTO: Extended; FVALOR_PAGO: Extended; FHISTORICO: String; //Transientes public [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_FIN_PARCELA_PAGAR', 'Id Fin Parcela Pagar', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFinParcelaPagar: Integer read FID_FIN_PARCELA_PAGAR write FID_FIN_PARCELA_PAGAR; [TColumn('ID_FIN_CHEQUE_EMITIDO', 'Id Fin Cheque Emitido', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFinChequeEmitido: Integer read FID_FIN_CHEQUE_EMITIDO write FID_FIN_CHEQUE_EMITIDO; [TColumn('ID_FIN_TIPO_PAGAMENTO', 'Id Fin Tipo Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFinTipoPagamento: Integer read FID_FIN_TIPO_PAGAMENTO write FID_FIN_TIPO_PAGAMENTO; [TColumn('ID_CONTA_CAIXA', 'Id Conta Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdContaCaixa: Integer read FID_CONTA_CAIXA write FID_CONTA_CAIXA; [TColumn('DATA_PAGAMENTO', 'Data Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataPagamento: TDateTime read FDATA_PAGAMENTO write FDATA_PAGAMENTO; [TColumn('TAXA_JURO', 'Taxa Juro', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaJuro: Extended read FTAXA_JURO write FTAXA_JURO; [TColumn('TAXA_MULTA', 'Taxa Multa', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaMulta: Extended read FTAXA_MULTA write FTAXA_MULTA; [TColumn('TAXA_DESCONTO', 'Taxa Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; [TColumn('VALOR_JURO', 'Valor Juro', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorJuro: Extended read FVALOR_JURO write FVALOR_JURO; [TColumn('VALOR_MULTA', 'Valor Multa', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorMulta: Extended read FVALOR_MULTA write FVALOR_MULTA; [TColumn('VALOR_DESCONTO', 'Valor Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO; [TColumn('VALOR_PAGO', 'Valor Pago', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorPago: Extended read FVALOR_PAGO write FVALOR_PAGO; [TColumn('HISTORICO', 'Historico', 450, [ldGrid, ldLookup, ldCombobox], False)] property Historico: String read FHISTORICO write FHISTORICO; //Transientes end; implementation initialization Classes.RegisterClass(TFinParcelaPagamentoVO); finalization Classes.UnRegisterClass(TFinParcelaPagamentoVO); end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.container.clientdataset; interface uses DB, SysUtils, DBClient, /// ormbr ormbr.session.dataset, ormbr.container.dataset, ormbr.dataset.clientdataset, dbebr.factory.interfaces; type TContainerClientDataSet<M: class, constructor> = class(TContainerDataSet<M>) public constructor Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); overload; constructor Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer); overload; constructor Create(AConnection: IDBConnection; ADataSet: TDataSet; AMasterObject: TObject); overload; constructor Create(AConnection: IDBConnection; ADataSet: TDataSet); overload; destructor Destroy; override; end; implementation { TContainerClientDataSet } constructor TContainerClientDataSet<M>.Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject); begin if ADataSet is TClientDataSet then FDataSetAdapter := TClientDataSetAdapter<M>.Create(AConnection, ADataSet, APageSize, AMasterObject) else raise Exception.Create('Is not TClientDataSet type'); end; constructor TContainerClientDataSet<M>.Create(AConnection: IDBConnection; ADataSet: TDataSet; APageSize: Integer); begin Create(AConnection, ADataSet, APageSize, nil); end; constructor TContainerClientDataSet<M>.Create(AConnection: IDBConnection; ADataSet: TDataSet; AMasterObject: TObject); begin Create(AConnection, ADataSet, -1, AMasterObject); end; constructor TContainerClientDataSet<M>.Create(AConnection: IDBConnection; ADataSet: TDataSet); begin Create(AConnection, ADataSet, -1, nil); end; destructor TContainerClientDataSet<M>.Destroy; begin FDataSetAdapter.Free; inherited; end; end.
unit imglib; interface uses Windows, sysutils, Graphics, ImgList, Vcl.Controls, System.Types; function DisabledImages(AImageList: TCustomImageList): TImageList; implementation function DisabledImages(AImageList: TCustomImageList): TImageList; const MaskColor = 5757; var ImgList: TImageList; ABitmap: TBitmap; i: Integer; function ConvertColor(AColor: TColor): TColor; var PixelColor, NewColor: Integer; begin PixelColor := ColorToRGB(AColor); NewColor := Round((((PixelColor shr 16) + ((PixelColor shr 8) and $00FF) + (PixelColor and $0000FF)) div 3)) div 2 + 96; Result := RGB(NewColor, NewColor, NewColor); end; procedure ConvertColors(ABitmap: TBitmap); var x, y: Integer; begin for x := 0 to ABitmap.Width - 1 do for y := 0 to ABitmap.Height - 1 do begin ABitmap.Canvas.Pixels[x, y] := ConvertColor(ABitmap.Canvas.Pixels[x, y]); end; end; begin ABitmap := TBitmap.Create; try ImgList := TImageList.Create(nil); ImgList.Width := AImageList.Width; ImgList.Height := AImageList.Height; ImgList.Clear; for i := 0 to AImageList.Count - 1 do begin ABitmap.Canvas.Brush.Color := MaskColor; ABitmap.Canvas.FillRect(rect(0, 0, AImageList.Width, AImageList.Height)); AImageList.GetBitmap(i, ABitmap); ConvertColors(ABitmap); ImgList.AddMasked(ABitmap, ConvertColor(MaskColor)); end; Result := ImgList; finally ABitmap.Free; end; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Spin, BZArrayClasses, BZColors, BZGraphic, BZBitmap, BZMath, BZVectorMath, BZGeoTools; type TBZCurvePointType = (cptControls, cptAnchors); { TBZ2DCustomCurve } TBZ2DCustomCurve = Class(TBZFloatPointsContainer) private FCurvePointType : TBZCurvePointType; protected FTolerance : Single; public Constructor Create; override; Constructor Create(APoints : TBZArrayOfFloatPoints; Const aPointType : TBZCurvePointType = cptAnchors); overload; Destructor Destroy; override; function ComputePointAt(t : Single) : TBZFloatPoint; virtual; function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; virtual; function GetLength : Single; virtual; function GetBounds : TBZFloatRect; virtual; // function getTangentAt(t: Single) : TBZFloatPoint; // function getNormalAt(t: Single) : TBZFloatPoint; //function ComputeControlPoints : TBZArrayOfFloatPoints; virtual; function ComputeOptimalSteps(Const aTolerance : Single = 0.1) : Integer; virtual; property CurvePointType : TBZCurvePointType read FCurvePointType write FCurvePointType; property Tolerance : Single read FTolerance write FTolerance; end; { TBZ2DBezierSplineCurve } TBZ2DBezierSplineCurve = Class(TBZ2DCustomCurve) private FControlPoints : TBZArrayOfFloatPoints; protected //function ComputeOptimalSteps(Const aTolerance : Single = 0.1) : Integer; override; function ComputeCoef(n, k : Integer) : Double; public function ComputeOptimalSteps(Const aTolerance : Single = 0.1) : Integer; override; function ComputePointAt(t : Single) : TBZFloatPoint; override; function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; override; end; //TBZCubicSplineType = (cstMonotonic, cstNatural, cstNaturalClamped); //TBZ2DCubicSplineCurve = Class(TBZ2DCustomCurve) //private // FSplineType : TBZCubicSplineType; //protected // //public; // Constructor Create; override; // Constructor Create(APoints : TBZArrayOfFloatPoints; Const aSplineType : TBZCubicSplineType = cptAnchors); overload; // // function ComputePointAt(t : Single) : TBZFloatPoint; override; // function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; override; // // property SplineType : TBZBSplineType read FSplineType write FSplineType; //end; TBZCatmullRomSplineType = (cstCentripetal, cstChordal, cstUniform); { TBZ2DCatmullRomSplineCurve } TBZ2DCatmullRomSplineCurve = Class(TBZ2DCustomCurve) private FSplineType : TBZCatmullRomSplineType; FClosed : Boolean; FTension : Single; protected procedure ComputeCubicCoefs(x0, x1, t0, t1 : Single; var c0, c1, c2, c3 : Single); procedure ComputeUniformCatmullRomCoefs(x0, x1, x2, x3, w : Single; var c0, c1, c2, c3 : Single); procedure ComputeNonUniformCatmullRomCoefs(x0, x1, x2, x3, dt0, dt1, dt2 : Single; var c0, c1, c2, c3 : Single); function ComputeCoef(t, c0, c1, c2, c3 : Single) : Single; public Constructor Create; override; Constructor Create(APoints : TBZArrayOfFloatPoints; Const aSplineType : TBZCatmullRomSplineType = cstUniform); overload; function ComputePointAt(t : Single) : TBZFloatPoint; override; function ComputePolyLinePoints(Const nbStep : Integer = -1) : TBZArrayOfFloatPoints; override; property SplineType : TBZCatmullRomSplineType read FSplineType write FSplineType; property Closed : Boolean read FClosed write FClosed; property Tension : Single read FTension write FTension; end; { TMainForm } TBZPointToolMode = (ptmNone, ptmCreate, ptmMove, ptmDelete); TMainForm = class(TForm) pnlViewer : TPanel; Panel1 : TPanel; Label2 : TLabel; GroupBox1 : TGroupBox; Panel2 : TPanel; GroupBox3 : TGroupBox; Label4 : TLabel; Panel4 : TPanel; Label5 : TLabel; Label6 : TLabel; Panel5 : TPanel; Label7 : TLabel; lblCurveLen : TLabel; Panel6 : TPanel; Label9 : TLabel; Label10 : TLabel; Panel7 : TPanel; Label11 : TLabel; lblNormal : TLabel; Panel8 : TPanel; chkShowTangentAndNormal : TCheckBox; chkShowBoundingBox : TCheckBox; chkShowControlPoint : TCheckBox; chkShowConstructLine : TCheckBox; Panel9 : TPanel; Panel11 : TPanel; Label13 : TLabel; lblOptimalSteps : TLabel; Panel3: TPanel; sbCurveTension: TScrollBar; Label1: TLabel; lblCurveTension: TLabel; Panel10: TPanel; Label12: TLabel; speSteps: TSpinEdit; Label3: TLabel; cbxCurveType: TComboBox; Panel12: TPanel; sbCurvePos: TScrollBar; Label8: TLabel; lblCurveTime: TLabel; procedure FormCreate(Sender : TObject); procedure FormDestroy(Sender : TObject); procedure pnlViewerMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); procedure pnlViewerMouseUp(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); procedure pnlViewerMouseMove(Sender : TObject; Shift : TShiftState; X, Y : Integer); procedure FormShow(Sender : TObject); procedure FormCloseQuery(Sender : TObject; var CanClose : boolean); procedure pnlViewerPaint(Sender : TObject); procedure sbCurveTensionChange(Sender : TObject); procedure sbCurvePosChange(Sender: TObject); private FBuffer : TBZBitmap; FControlPoints, FAnchorPoints : TBZArrayOfFloatPoints; FPointIndex : Integer; FMousePos, FLastMousePos : TBZFloatPoint; FMouseActive : Boolean; FPointToolMode : TBZPointToolMode; FDrag : Byte; FDist : Single; FBezierCurve : TBZ2DBezierSplineCurve; FCatmullRomCurve : TBZ2DCatmullRomSplineCurve; FBezierCurve2 : TBZ2DCurve; procedure CheckSelectedPoint; protected procedure DrawControlPoint(pt : TBZFloatPoint; IsSelected : Boolean); procedure Render; function InPoint(mx, my, px, py, r : Single) : Boolean; public end; var MainForm : TMainForm; implementation {$R *.lfm} Uses Math, BZLogger, BZTypesHelpers; {%region TMainForm } procedure TMainForm.FormCreate(Sender : TObject); begin FBuffer := TBZBitmap.Create(pnlViewer.ClientWidth, pnlViewer.ClientHeight); FControlPoints := TBZArrayOfFloatPoints.Create(16); FAnchorPoints := TBZArrayOfFloatPoints.Create(16); FPointToolMode := ptmNone; FPointIndex := -1; //FBezierCurve := TBZ2DBezierSplineCurve.Create(16); //FBezierCurve.CurvePointType := cptAnchors; FCatmullRomCurve := TBZ2DCatmullRomSplineCurve.Create; FCatmullRomCurve.SplineType := cstUniform; FCatmullRomCurve.Tension := 0.8; FCatmullRomCurve.Closed := True; FBezierCurve := TBZ2DBezierSplineCurve.Create; FBezierCurve2 := TBZ2DCurve.Create(ctBezier); end; procedure TMainForm.FormDestroy(Sender : TObject); begin FreeAndNil(FBezierCurve2); FreeAndNil(FBezierCurve); FreeAndNil(FCatmullRomCurve); FreeAndNil(FAnchorPoints); FreeAndNil(FControlPoints); FreeAndNil(FBuffer); end; procedure TMainForm.pnlViewerMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); begin FMouseActive := True; FMousePos.Create(x,y); if (ssLeft in Shift) then begin if (ssCtrl in Shift) then begin CheckSelectedPoint; if (FPointIndex > - 1) then FPointToolMode := ptmMove; end else begin FPointToolMode := ptmCreate; FMouseActive := False; end; end else if (ssRight in Shift) then begin CheckSelectedPoint; if (FPointIndex > - 1) then FPointToolMode := ptmDelete; FMouseActive := False; end; //if InPoint(FMousePos.X, FMousePos.Y, CurveSpline.Points[0].X, CurveSpline.Points[0].Y, 5) then FDrag := 0 //else if InPoint(FMousePos.X, FMousePos.Y, CurveSpline.Points[1].X, CurveSpline.Points[1].Y, 5) then FDrag := 1 //else if InPoint(FMousePos.X, FMousePos.Y, CurveSpline.Points[2].X, CurveSpline.Points[2].Y, 5) then FDrag := 2 //else if InPoint(FMousePos.X, FMousePos.Y, CurveSpline.Points[3].X, CurveSpline.Points[3].Y, 5) then FDrag := 3; FLastMousePos := FMousePos; Render; pnlViewer.invalidate; end; procedure TMainForm.pnlViewerMouseUp(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer); begin FMouseActive := False; Case FPointToolMode of ptmCreate : begin FAnchorPoints.Add(FMousePos); //FBezierCurve.PointsList.Add(FMousePos); end; ptmDelete : begin if (FPointIndex > -1) then FAnchorPoints.Delete(FPointIndex); end; end; FPointToolMode := ptmNone; FPointIndex := -1; FLastMousePos.Create(x,y); Render; pnlViewer.invalidate; end; procedure TMainForm.pnlViewerMouseMove(Sender : TObject; Shift : TShiftState; X, Y : Integer); Var Delta : TBZFloatPoint; begin FMousePos.Create(x,y); if FMouseActive then begin if (FPointToolMode = ptmMove) then begin Delta := FMousePos - FLastMousePos; FAnchorPoints.Items[FPointIndex] := FAnchorPoints.Items[FPointIndex] + Delta; FLastMousePos := FMousePos; end; end else CheckSelectedPoint; Render; pnlViewer.invalidate; end; procedure TMainForm.FormShow(Sender : TObject); begin //BZThreadTimer1.Enabled := True; Render; end; procedure TMainForm.FormCloseQuery(Sender : TObject; var CanClose : boolean); begin //BZThreadTimer1.Enabled := False; CanClose := True; end; procedure TMainForm.pnlViewerPaint(Sender : TObject); begin FBuffer.DrawToCanvas(pnlViewer.Canvas, pnlViewer.ClientRect); end; procedure TMainForm.sbCurveTensionChange(Sender : TObject); var t : Single; begin t := sbCurveTension.Position / 100; lblCurveTension.Caption := t.ToString(2); FCatmullRomCurve.Tension := t; Render; pnlViewer.Invalidate; end; procedure TMainForm.sbCurvePosChange(Sender: TObject); var t : Single; begin t := sbCurvePos.Position / 100; lblCurveTime.Caption := t.ToString(2); Render; pnlViewer.Invalidate; end; procedure TMainForm.CheckSelectedPoint; Var i : integer; begin FPointIndex := -1; if FAnchorPoints.Count > 0 then begin for i := 0 to (FAnchorPoints.Count - 1) do begin if InPoint(FMousePos.X, FMousePos.Y, FAnchorPoints.Items[i].X, FAnchorPoints.Items[i].Y, 5) then begin FPointIndex := i; Break; end; end; end; lblNormal.Caption := FPointIndex.ToString; end; procedure TMainForm.DrawControlPoint(pt: TBZFloatPoint; IsSelected: Boolean); begin With FBuffer.Canvas do begin //Antialias := True; Brush.Style := bsClear; Pen.Style := ssSolid; Pen.Color := clrGray; Pen.Width := 1; Circle(pt, 5); Circle(pt, 2); if Not(IsSelected) then Pen.Color := clrWhite else Pen.Color := clrAqua; Circle(pt, 3); Circle(pt, 4); Antialias := False; //Brush.Color := clrGreen; //Brush.Color.Alpha := 127; //Circle(pt, 2); end; end; procedure TMainForm.Render; Var i : Integer; //aBezierCurve : TBZArrayOfFloatPoints; t : Single; LSelected : Boolean; {$CODEALIGN VARMIN=16} pSA, pAB, pBE, pt1, pt2, ptC, NormPt : TBZFloatPoint; {$CODEALIGN VARMIN=4} NormalLine : TBZ2DLineTool; PolyPoints, PolyPoints2, PolyPoints3 : TBZArrayOfFloatPoints; begin FBuffer.RenderFilter.DrawGrid(clrBlack, clrGray25, clrGray15, clrRed, clrGreen, 16); Fbuffer.Canvas.Antialias := False; if chkShowControlPoint.Checked then begin for i := 0 to (FAnchorPoints.Count - 1) do begin if FPointIndex = i then LSelected := True else LSelected := False; DrawControlPoint(FAnchorPoints.Items[i], LSelected); end; end; With FBuffer.Canvas do begin if chkShowConstructLine.Checked then begin Pen.Style := ssSolid; Pen.Color := clrYellow; for i := 0 to (FAnchorPoints.Count - 2) do begin Line(FAnchorPoints.Items[i], FAnchorPoints.Items[i + 1]); end; end; //if chkShowBoundingBox.Checked then //begin // Pen.Color := clrTeal; // Brush.Style := bsClear; // Rectangle(CurveSpline.GetBounds); //end; Pen.Style := ssSolid; Pen.Color := clrWhite; Brush.Style := bsClear; //For i := 0 to (aBezierCurve.Count - 2) do //begin // Line(aBezierCurve.Items[i], aBezierCurve.Items[i+1]); //end; Pen.Width := 1; if (FAnchorPoints.Count > 2) then begin Case cbxCurveType.ItemIndex of 0 : begin FBezierCurve2.AssignPoints(FAnchorPoints); FBezierCurve2.CurveType := ctBezier; PolyPoints2 := FBezierCurve2.ComputePolylinePoints; FBezierCurve2.CurveType := ctSmoothBezier; PolyPoints3 := FBezierCurve2.ComputePolylinePoints; FBezierCurve.AssignPoints(FAnchorPoints); //lblOptimalSteps.Caption := FBezierCurve.ComputeOptimalSteps.ToString; PolyPoints := FBezierCurve.ComputePolyLinePoints(speSteps.Value); end; 4, 5, 6 : begin FCatmullRomCurve.AssignPoints(FAnchorPoints); lblOptimalSteps.Caption := FCatmullRomCurve.ComputeOptimalSteps.ToString; PolyPoints := FCatmullRomCurve.ComputePolyLinePoints(speSteps.Value); end; end; MoveTo(PolyPoints.Items[0]); for i := 1 to (PolyPoints.Count - 1) do begin LineTo(PolyPoints.Items[i]); end; FreeAndNil(PolyPoints); MoveTo(PolyPoints2.Items[0]); //DrawControlPoint(PolyPoints2.Items[0], true); for i := 1 to (PolyPoints2.Count - 1) do begin //DrawControlPoint(PolyPoints2.Items[i], true); Pen.Color := clrFuchsia; LineTo(PolyPoints2.Items[i]); end; FreeAndNil(PolyPoints2); MoveTo(PolyPoints3.Items[0]); for i := 1 to (PolyPoints3.Count - 1) do begin Pen.Color := clrAqua; LineTo(PolyPoints3.Items[i]); end; FreeAndNil(PolyPoints3); end; //if chkShowTangentAndNormal.Checked then //begin // //NormPt := CubicBezierA.GetNormalAt(t); // //NormalLine := TBZ2DLineTool.Create; // //NormalLine.SetInfiniteLine(CubicBezierA.ComputePointAt(t), NormPt, 40); // ptC := CubicBezierA.ComputePointAt(t); // NormPt := CubicBezierA.GetNormalAt(t); // Pen.Color := clrBrass; // Pen.Style := ssSolid; // MoveTo(ptC);// - (NormPt * 40)); // LineTo(ptC + (NormPt * 40)); // // ptC := CubicBezierA.ComputePointAt(t); // NormPt := CubicBezierA.GetTangentAt(t); // Pen.Color := clrVioletRed; // MoveTo(ptC); // - (NormPt * 80)); // LineTo(ptC + (NormPt * 80)); // // // //FreeAndNil(NormalLine); // lblNormal.Caption := NormPt.ToString; //end //else lblNormal.Caption := '---'; end; //pt1.Create(80,FBuffer.MaxHeight - 80); //pt2.Create(FBuffer.MaxWidth - 80, 80); //Pen.Color := clrLime; //MoveTo(pt1); //LineTo(pt2); end; function TMainForm.InPoint(mx, my, px, py, r : Single) : Boolean; begin Result := False; if (mX >= px - r) and (mX <= px + r) and (mY >= py - r) and (mY <= py + r) then Result := True; end; {%endregion%} {%region TBZ2DCustomCurve } Constructor TBZ2DCustomCurve.Create; begin inherited Create(64); FCurvePointType := cptAnchors; FTolerance := 0.1; end; Constructor TBZ2DCustomCurve.Create(APoints: TBZArrayOfFloatPoints; Const aPointType: TBZCurvePointType); begin inherited Create(aPoints); FCurvePointType := aPointType; FTolerance := 0.1; end; Destructor TBZ2DCustomCurve.Destroy; begin inherited Destroy; end; function TBZ2DCustomCurve.ComputeOptimalSteps(Const aTolerance: Single): Integer; Var {$CODEALIGN VARMIN=16} P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i : Integer; d : Single; begin d := 0; For i := 0 to (Self.PointsList.Count - 2) do begin P1 := Self.Points[i]; P2 := Self.Points[i+1]; d := d + P1.DistanceSquare(P2); end; d := System.Sqrt(System.Sqrt(d) / aTolerance); if (d < cEpsilon) then d := 1.0; Result := Round(d); end; function TBZ2DCustomCurve.ComputePointAt(t: Single): TBZFloatPoint; begin Result.Create(0,0); end; function TBZ2DCustomCurve.ComputePolyLinePoints(Const nbStep: Integer): TBZArrayOfFloatPoints; begin result := nil; end; function TBZ2DCustomCurve.GetLength: Single; begin Result := 0; end; function TBZ2DCustomCurve.GetBounds: TBZFloatRect; begin Result.Create(0,0,0,0); end; {%endregion%} {%region TBZ2DBezierSplineCurve } function TBZ2DBezierSplineCurve.ComputeOptimalSteps(Const aTolerance: Single): Integer; Var {$CODEALIGN VARMIN=16} P1, P2 : TBZFloatPoint; {$CODEALIGN VARMIN=4} i : Integer; d : Single; begin d := 0; For i := 0 to (Self.PointsList.Count - 2) do begin P1 := Self.Points[i]; P2 := Self.Points[i+1]; d := Max(d, P1.DistanceSquare(P2)); end; d := System.Sqrt(System.Sqrt(d) / aTolerance) * 2; if (d < cEpsilon) then d := 1.0; Result := Round(d); end; function TBZ2DBezierSplineCurve.ComputeCoef(n, k: Integer): Double; Var Coef : Single; i, j : integer; begin Coef := 1; j := n - k + 1; for i := j to n do begin Coef := Coef * i; end; for i := 1 to k do begin Coef := Coef / i; end; Result := Coef; end; function TBZ2DBezierSplineCurve.ComputePointAt(t: Single): TBZFloatPoint; Var i, n : integer; b, nt : Double; begin n := Self.PointsList.Count - 1; Result.Create(0,0); nt := 1 - t; for i := 0 to n do begin b := ComputeCoef(n, i) * BZMath.Pow(nt, (n-i)) * BZMath.Pow(t, i); Result := Result + (Self.Points[i] * b); end; end; function TBZ2DBezierSplineCurve.ComputePolyLinePoints(Const nbStep: Integer): TBZArrayOfFloatPoints; var nbSteps, j : Integer; Delta, aTime : Single; pt : TBZFloatPoint; begin Result := nil; if nbStep <= 0 then nbSteps := ComputeOptimalSteps(FTolerance) else nbSteps := nbStep; Result := TBZArrayOfFloatPoints.Create(nbSteps + 1); if nbSteps > 1 then begin aTime := 0; Delta := 1.0 / nbSteps; for j := 0 to (nbSteps - 1) do begin pt :=ComputePointAt(aTime); Result.Add(pt); aTime := aTime + Delta; end; end else begin Result.Add(Self.Points[0]); Result.Add(Self.Points[(Self.PointsList.Count - 1)]); end; end; //function TBZ2DBezierSplineCurve.ComputeControlPoints: TBZArrayOfFloatPoints; //var // sp, ep, cp1, cp2 : TBZFloatPoint; // n, j : integer; // RightHandSide, pX, pY : TBZSingleList; // t : Single; // // function GetFirstControlPoint( rhs : TBZSingleList) : TBZSingleList; // var // i, k : Integer; // tmp, tmpX : TBZSingleList; // b, v : single; // begin // k := rhs.Count; // b := 2.0; // tmp := TBZSingleList.Create(16); // tmpX := TBZSingleList.Create(16); // v := rhs.Items[0] / b; // tmpX.Add(v); // for i := 1 to (k - 1) do // begin // v := 1 / b; // tmp.Add(v); // if (i < (k - 1)) then b := 4.0 - tmp.Items[i - 1] // else b := 3.5 - tmp.Items[i - 1]; // v := (rhs.Items[i] - tmpX.Items[i - 1]) / b; // tmpX.Add(v); // end; // // for i := 1 to (k - 1) do // begin // v := tmpX.Items[k - i - 1]; // v := v - (tmp.Items[i - 1] * tmpX.Items[i - 1]); // tmpX.Items[k - i - 1] := v; // end; // // FreeAndNil(tmp); // Result := tmpX; // end; // //begin // n := PointsList.Count - 1; // Result := TBZArrayOfFloatPoints.Create(16); // if (n = 1) then // Cas spécial, c'est une simple ligne // begin // sp := Self.Points[0]; // cp1 := ((Self.Points[0] + Self.Points[0]) + Self.Points[1]) / 3; // cp2 := (cp1 - Self.Points[0]); // ep := Self.Points[1]; // Result.Add(sp); // Result.Add(cp1); // Result.Add(cp2); // Result.Add(ep); // Exit; // end; // // RightHandSide := TBZSingleList.Create(16); // t := Self.Points[1].X; // t := t + t; // t := t+ Self.Points[0].X; // RightHandSide.Add(t); // for j := 1 to (n - 1) do // begin // t := Self.Points[j + 1].X; // t := t + t; // t := (4 * Self.Points[j].X) + t; // RightHandSide.Add(t); // end; // t := ((8 * Self.Points[n - 1].X) + Self.Points[n].X) * 0.5; // RightHandSide.Add(t); // pX := GetFirstControlPoint(RightHandSide); // // RightHandSide.Clear; // t := Self.Points[1].Y; // t := t + t; // t := t+ Self.Points[0].Y; // RightHandSide.Add(t); // for j := 1 to (n - 1) do // begin // t := Self.Points[j + 1].Y; // t := t + t; // t := (4 * Self.Points[j].Y) + t; // RightHandSide.Add(t); // end; // t := ((8 * Self.Points[n - 1].Y) + Self.Points[n].Y) * 0.5; // RightHandSide.Add(t); // pY := GetFirstControlPoint(RightHandSide); // // FreeAndNil(RightHandSide); // // for j := 0 to (n - 1) do // begin // sp := Self.Points[j]; // cp1.Create(pX.Items[j], pY.Items[j]); // if (j < (n - 1)) then // begin // cp2.Create((Self.Points[j + 1].X * 2) - pX.Items[j + 1], (Self.Points[j + 1].Y * 2) - pY.Items[j + 1]); // end // else // begin // cp2.Create((Self.Points[n].X + pX.Items[n - 1]) * 0.5, (Self.Points[n].Y + pY.Items[n - 1]) * 0.5); // end; // ep := Self.Points[j + 1]; // Result.Add(sp); // Result.Add(cp1); // Result.Add(cp2); // Result.Add(ep); // end; // //Result.Add(Self.Points[n]); // FreeAndNil(pX); // FreeAndNil(pY); //end; {%endregion%} {%region TBZ2DCatmullRomSplineCurve } Constructor TBZ2DCatmullRomSplineCurve.Create; begin inherited Create; FSplineType := cstUniform; FClosed := False; FTension := 0.5; end; Constructor TBZ2DCatmullRomSplineCurve.Create(APoints: TBZArrayOfFloatPoints; Const aSplineType: TBZCatmullRomSplineType); begin inherited Create(aPoints, cptAnchors); FSplineType := aSplineType; FClosed := False; FTension := 0.5; end; procedure TBZ2DCatmullRomSplineCurve.ComputeCubicCoefs(x0, x1, t0, t1: Single; var c0, c1, c2, c3: Single); begin c0 := x0; c1 := t0; c2 := -3 * x0 + 3 * x1 - 2 * t0 - t1; c3 := 2 * x0 - 2 * x1 + t0 + t1; end; procedure TBZ2DCatmullRomSplineCurve.ComputeUniformCatmullRomCoefs(x0, x1, x2, x3, w: Single; var c0, c1, c2, c3: Single); begin ComputeCubicCoefs( x1, x2, w * ( x2 - x0 ), w * ( x3 - x1 ), c0, c1, c2, c3 ); end; procedure TBZ2DCatmullRomSplineCurve.ComputeNonUniformCatmullRomCoefs(x0, x1, x2, x3, dt0, dt1, dt2: Single; var c0, c1, c2, c3: Single); var t1, t2 : Single; begin t1 := ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1; t2 := ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2; t1 := t1 * dt1; t2 := t2 * dt1; ComputeCubicCoefs( x1, x2, t1, t2, c0, c1, c2, c3 ); end; function TBZ2DCatmullRomSplineCurve.ComputeCoef(t, c0, c1, c2, c3: Single): Single; var t2, t3 : Single; begin t2 := t * t; t3 := t2 * t; result := c0 + c1 * t + c2 * t2 + c3 * t3; end; function TBZ2DCatmullRomSplineCurve.ComputePointAt(t: Single): TBZFloatPoint; var k, pi : Integer; p, weight : Single; tmp, p0, p1, p2, p3 : TBZFloatPoint; dt0, dt1, dt2, powfactor, cx0, cx1, cx2, cx3, cy0, cy1, cy2, cy3 : Single; begin k := Self.PointsList.Count; if FClosed then p := (k * t) else p := (k - 1) * t; pi := Floor(p); Weight := p - pi; if FClosed then begin if (pi <= 0) then pi := pi + ((floor(abs(pi) / k ) + 1 ) * k); end else if (Weight = 0) and (pi = (k - 1)) then begin pi := k - 2; Weight := 1; end; if (FClosed and (pi > 0)) then begin p0 := Self.Points[( pi - 1) mod k]; end else begin tmp := Self.Points[0]; p0 := (tmp - Self.Points[1]) + tmp; end; p1 := Self.Points[(pi mod k)]; p2 := Self.Points[(pi + 1) mod k]; if (FClosed or ((pi + 1) < k)) then begin p3 := Self.Points[(pi + 2) mod k]; end else begin tmp := Self.Points[k - 1]; p0 := (tmp - Self.Points[k - 2]) + tmp; end; Case FSplineType of cstCentripetal, cstChordal : begin if (FSplineType = cstChordal) then powfactor := 0.5 else powfactor := 0.25; dt0 := power( p0.distanceSquare( p1 ), powfactor ); dt1 := power( p1.distanceSquare( p2 ), powfactor ); dt2 := power( p2.distanceSquare( p3 ), powfactor ); // safety check for repeated points if ( dt1 < cEpsilon ) then dt1 := 1.0; if ( dt0 < cEpsilon ) then dt0 := dt1; if ( dt2 < cEpsilon ) then dt2 := dt1; ComputeNonuniformCatmullRomCoefs( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2, cx0, cx1, cx2, cx3 ); ComputeNonuniformCatmullRomCoefs( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2, cy0, cy1, cy2, cy3 ); end; cstUniform: begin ComputeUniformCatmullRomCoefs( p0.x, p1.x, p2.x, p3.x, Ftension, cx0, cx1, cx2, cx3 ); ComputeUniformCatmullRomCoefs( p0.y, p1.y, p2.y, p3.y, Ftension, cy0, cy1, cy2, cy3 ); end; end; Result.x := ComputeCoef(Weight, cx0, cx1, cx2, cx3); Result.y := ComputeCoef(Weight, cy0, cy1, cy2, cy3); end; function TBZ2DCatmullRomSplineCurve.ComputePolyLinePoints(Const nbStep: Integer): TBZArrayOfFloatPoints; var nbSteps, i: Integer; Delta, aTime : Single; pt : TBZFloatPoint; begin if (nbStep <= 0) then nbSteps := Self.ComputeOptimalSteps(Self.Tolerance) else nbSteps := nbStep; if not(FClosed) then begin Self.PointsList.Add(Self.Points[(Self.PointsList.Count - 1)]); end else nbSteps := nbSteps + 1; Result := TBZArrayOfFloatPoints.Create(32); aTime := 0; Delta := 1.0 / nbSteps; for i := 0 to (nbSteps - 1) do begin pt := ComputePointAt(aTime); aTime := aTime + Delta; Result.Add(pt); end; if CLosed then Result.Add(Self.Points[0]); end; {%endregion%} end.
unit NovusStringParser; interface Uses NovusUtilities, NovusStringUtils, NovusParser, Classes, SysUtils, StrUtils; type tNovusStringParser = Class(tNovusParser) private FItems: TStringList; stText : String; stWordCount : Integer; stFindString : String; stFindPosition : Integer; procedure GetWordCount; procedure SetText(const Value: String); Public constructor Create(AText : String); destructor Destroy; override; function Replace(fromStr, toStr : String) : Integer; function FindFirst(search : String) : Integer; function FindNext : Integer; property Text : String read stText write SetText; property WordCount : Integer read stWordCount; property Items: TStringList read FItems write FItems; end; implementation constructor tNovusStringParser.Create(AText: String); begin FItems := TStringList.Create; stText := AText; stFindPosition := 1; stFindString := ''; GetWordCount; end; destructor tNovusStringParser.destroy; begin inherited destroy; end; procedure tNovusStringParser.SetText(const Value: String); begin stText := Value; stFindPosition := 1; GetWordCount; end; function tNovusStringParser.FindFirst(search: String): Integer; begin stFindString := search; stFindPosition := 1; Result := FindNext; end; function tNovusStringParser.FindNext: Integer; var index : Integer; findSize : Integer; begin if Length(stFindString) = 0 then Result := -2 else begin findSize := Length(stFindString); Result := -1; index := stFindPosition; while (index <= Length(stText)) and (Result < 0) do begin if stText[index] = stFindString[1] then begin if AnsiMidStr(stText, index, findSize) = stFindString then Result := index; end; Inc(index); end; stFindPosition := index end; end; function tNovusStringParser.Replace(fromStr, toStr: String): Integer; var fromSize, count, index : Integer; newText : String; matched : Boolean; begin fromSize := Length(fromStr); count := 0; newText := ''; index := 1; while index <= Length(stText) do begin matched := false; if stText[index] = fromStr[1] then begin if AnsiMidStr(stText, index, fromSize) = fromStr then begin Inc(count); newText := newText + toStr; Inc(index, fromSize); matched := true; end; end; if not matched then begin newText := newText + stText[index]; Inc(index); end; end; if count > 0 then stText := newText; Result := count; end; procedure tNovusStringParser.GetWordCount; const LF = #10; TAB = #9; CR = #13; BLANK = #32; SEMICOL = ';'; EQUALS = '='; var lsWord: String; WordSeparatorSet : Set of Char; index : Integer; inWord : Boolean; begin WordSeparatorSet := [LF, TAB, CR, BLANK, SEMICOL]; stWordCount := 0; inWord := false; lsWord := ''; for index := 1 to Length(stText) do begin if stText[index] In WordSeparatorSet then begin if inWord then begin FItems.Add(lsWord); Inc(stWordCount); lsWord := ''; end; inWord := false; end else inWord := true; if InWord then lsWord := lsWord + stText[index]; end; if inWord then begin FItems.Add(lsWord); Inc(stWordCount); end; end; end.
program Ex1_ListaCasamento; type rConvidado = record nome : String; confirmou : String; end; rLista = record Conv : array[0..9] of rConvidado; UltimaPosicao: Integer; end; var ListaDeConvidados : rLista; nOpcao : Integer; lSair : Boolean; procedure MontarMenu; begin clrscr; writeln('1 - Adicionar'); writeln('2 - Remover'); writeln('3 - Mostrar Todos'); writeln('4 - Confirmar Presença: '); writeln('0 - Sair'); write('Escolha uma opção: '); readln(nOpcao); end; procedure LimparLista; begin ListaDeConvidados.UltimaPosicao := -1; end; procedure Adicionar; var nNovaPosicao: Integer; begin clrscr; if (ListaDeConvidados.UltimaPosicao = 9) then writeln('ERRO: Não é possível adicionar mais itens') else begin Inc(ListaDeConvidados.UltimaPosicao); nNovaPosicao := ListaDeConvidados.UltimaPosicao; write('Nome: '); readln(ListaDeConvidados.Conv[nNovaPosicao].nome); write('Confirmou(Sim/Não): '); readln(ListaDeConvidados.Conv[nNovaPosicao].confirmou); writeln('Convidado adicionado!'); end; readkey; end; procedure Remover; var nPosRemover, i: Integer; begin clrscr; if ListaDeConvidados.UltimaPosicao = -1 then writeln('ERRO: A lista está vazia!') else begin write('Qual posição deseja remover?: '); readln(nPosRemover); if nPosRemover > ListaDeConvidados.UltimaPosicao then writeln('ERRO: A posição ', nPosRemover, ' não existe!') else begin if nPosRemover <> ListaDeConvidados.UltimaPosicao then begin for i := nPosRemover to ListaDeConvidados.UltimaPosicao -1 do ListaDeConvidados.Conv[i] := ListaDeConvidados.Conv[i + 1]; end; ListaDeConvidados.UltimaPosicao := ListaDeConvidados.UltimaPosicao - 1; writeln('Convidado removido com sucesso!'); end; end; readkey; end; procedure MostrarLista; var i: Integer; begin clrscr; for i := 0 to ListaDeConvidados.UltimaPosicao do begin writeln(i, ' - Convidado: ', ListaDeConvidados.Conv[i].Nome, ' - Confirmou: ', ListaDeConvidados.Conv[i].confirmou); end; readkey; end; procedure ConfirmarPresenca; var cConfirmou : string; i : integer; lAchou : boolean; begin clrscr; lAchou := false; write('Quem confirmou presença?: '); read(cConfirmou); for i := 0 to ListaDeConvidados.UltimaPosicao do begin if (upcase(cConfirmou) = upcase(ListaDeConvidados.Conv[i].Nome)) then begin ListaDeConvidados.Conv[i].confirmou := 'Sim'; lAchou := true; break; end end; if (lAchou) then writeln('Presença confirmada!') else writeln('ERRO: Convidado não está na lista!'); readkey; end; begin LimparLista; lSair := False; while not lSair do begin MontarMenu; case nOpcao of 1 : Adicionar; 2 : Remover; 3 : MostrarLista; 4 : ConfirmarPresenca; else lSair := True; end; end; end.
unit MatriculaUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGrids, DB, FMTBcd, SqlExpr; type TMatriculasForm = class(TForm) MenuPanel: TPanel; IncluirButton: TButton; AlterarButton: TButton; ExcluirButton: TButton; FecharButton: TButton; DadosPanel: TPanel; PesquisarGroupBox: TGroupBox; AlunoRadioButton: TRadioButton; DisciplinaRadioButton: TRadioButton; ProfessorRadioButton: TRadioButton; PesquisarEdit: TEdit; MatriculaDBGrid: TDBGrid; AlunoDiscProfDataSource: TDataSource; AlunoDiscProfSQLQuery: TSQLQuery; procedure FormActivate(Sender: TObject); procedure AlunoRadioButtonClick(Sender: TObject); procedure PesquisarEditChange(Sender: TObject); procedure IncluirButtonClick(Sender: TObject); procedure AlterarButtonClick(Sender: TObject); procedure ExcluirButtonClick(Sender: TObject); procedure FecharButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MatriculasForm: TMatriculasForm; implementation {$R *.dfm} uses DataModuleunit, MatriculaIncAltUnit; procedure TMatriculasForm.FormActivate(Sender: TObject); begin DataModuleBanco.AlunoDiscProfClientDataSet.IndexFieldNames := 'NOMEALUNO'; AlunoRadioButton.Checked := true; DisciplinaRadioButton.Checked := false; ProfessorRadioButton.Checked := false; PesquisarEdit.SetFocus; end; procedure TMatriculasForm.AlunoRadioButtonClick(Sender: TObject); begin if AlunoRadioButton.Checked then begin DataModuleBanco.AlunoDiscProfClientDataSet.IndexFieldNames := 'NOMEALUNO'; PesquisarEdit.Hint := 'Digite o Nome do Aluno que deseja pesquisar.'; end else if DisciplinaRadioButton.Checked then begin DataModuleBanco.AlunoDiscProfClientDataSet.IndexFieldNames := 'NOMEDISCIPLINA'; PesquisarEdit.Hint := 'Digite o Nome da Disciplina que deseja pesquisar.'; end else begin DataModuleBanco.AlunoDiscProfClientDataSet.IndexFieldNames := 'NOMEPROFESSOR'; PesquisarEdit.Hint := 'Digite o Nome do Professor que deseja pesquisar.'; end; PesquisarEdit.SetFocus; end; procedure TMatriculasForm.PesquisarEditChange(Sender: TObject); begin if trim(PesquisarEdit.Text) <> '' then begin if AlunoRadioButton.Checked then DataModuleBanco.AlunoDiscProfClientDataSet.Locate('NOMEALUNO',trim(PesquisarEdit.Text),[loPartialKey]) else if DisciplinaRadioButton.Checked then DataModuleBanco.DiscProfClientDataSet.Locate('NOMEDISCIPLINA',trim(PesquisarEdit.Text),[loPartialKey]) else DataModuleBanco.DiscProfClientDataSet.Locate('NOMEPROFESSOR',trim(PesquisarEdit.Text),[loPartialKey]) end; end; procedure TMatriculasForm.IncluirButtonClick(Sender: TObject); begin Application.CreateForm(TMatriculaIncAltForm, MatriculaIncAltForm); MatriculaIncAltForm.varAcao := 'Incluir'; MatriculaIncAltForm.ShowModal; MatriculaIncAltForm.Release; end; procedure TMatriculasForm.AlterarButtonClick(Sender: TObject); begin Application.CreateForm(TMatriculaIncAltForm, MatriculaIncAltForm); MatriculaIncAltForm.varAcao := 'Alterar'; MatriculaIncAltForm.ShowModal; MatriculaIncAltForm.Release; end; procedure TMatriculasForm.ExcluirButtonClick(Sender: TObject); begin if Application.MessageBox('Deseja Excluir essa Matricula?','Confirmação',Mb_YesNo + Mb_IconInformation + Mb_DefButton2) = 6 then begin AlunoDiscProfSQLQuery.Close; AlunoDiscProfSQLQuery.SQL.Clear; AlunoDiscProfSQLQuery.SQL.Add('Delete from AlunoDisciplinaProfessor where alunodisciplinaprofessorID=:PalunodisciplinaprofessorID'); AlunoDiscProfSQLQuery.ParamByName('PalunodisciplinaprofessorID').AsInteger := DataModuleBanco.AlunoDiscProfClientDataSetALUNODISCIPLINAPROFESSORID.AsInteger; AlunoDiscProfSQLQuery.ExecSQL; DataModuleBanco.AlunoDiscProfClientDataSet.Refresh; end; end; procedure TMatriculasForm.FecharButtonClick(Sender: TObject); begin Close; end; end.
unit VMan; interface uses Forms, Windows, Graphics; function IsWindowsVista: Boolean; procedure SetVistaFonts(const AForm: TCustomForm); procedure SetVistaContentFonts(const AFont: TFont); procedure SetDesktopIconFonts(const AFont: TFont); procedure ExtendGlass(const AHandle: THandle; const AMargins: TRect); function CompositingEnabled: Boolean; function TaskDialog(const AHandle: THandle; const ATitle, ADescription, AContent: string; const Icon, Buttons: integer): Integer; procedure SetVistaTreeView(const AHandle: THandle); const VistaFont = 'Segoe UI'; VistaContentFont = 'Calibri'; XPContentFont = 'Verdana'; XPFont = 'Tahoma'; TD_ICON_BLANK = 0; TD_ICON_WARNING = 84; TD_ICON_QUESTION = 99; TD_ICON_ERROR = 98; TD_ICON_INFORMATION = 81; TD_ICON_SHIELD_QUESTION = 104; TD_ICON_SHIELD_ERROR = 105; TD_ICON_SHIELD_OK = 106; TD_ICON_SHIELD_WARNING = 107; TD_BUTTON_OK = 1; TD_BUTTON_YES = 2; TD_BUTTON_NO = 4; TD_BUTTON_CANCEL = 8; TD_BUTTON_RETRY = 16; TD_BUTTON_CLOSE = 32; TD_RESULT_OK = 1; TD_RESULT_CANCEL = 2; TD_RESULT_RETRY = 4; TD_RESULT_YES = 6; TD_RESULT_NO = 7; TD_RESULT_CLOSE = 8; var CheckOSVerForFonts: Boolean = True; implementation uses SysUtils, Dialogs, Controls, UxTheme; procedure SetVistaTreeView(const AHandle: THandle); begin if IsWindowsVista then SetWindowTheme(AHandle, 'explorer', nil); end; procedure SetVistaFonts(const AForm: TCustomForm); begin if (IsWindowsVista or not CheckOSVerForFonts) and not SameText(AForm.Font.Name, VistaFont) and (Screen.Fonts.IndexOf(VistaFont) >= 0) then begin AForm.Font.Size := AForm.Font.Size; AForm.Font.Name := VistaFont; end; end; procedure SetVistaContentFonts(const AFont: TFont); begin if (IsWindowsVista or not CheckOSVerForFonts) and not SameText(AFont.Name, VistaContentFont) and (Screen.Fonts.IndexOf(VistaContentFont) >= 0) then begin AFont.Size := AFont.Size + 2; AFont.Name := VistaContentFont; end; end; procedure SetDefaultFonts(const AFont: TFont); begin AFont.Handle := GetStockObject(DEFAULT_GUI_FONT); end; procedure SetDesktopIconFonts(const AFont: TFont); var LogFont: TLogFont; begin if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0) then AFont.Handle := CreateFontIndirect(LogFont) else SetDefaultFonts(AFont); end; function IsWindowsVista: Boolean; var VerInfo: TOSVersioninfo; begin VerInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); GetVersionEx(VerInfo); Result := VerInfo.dwMajorVersion >= 6; end; const dwmapi = 'dwmapi.dll'; DwmIsCompositionEnabledSig = 'DwmIsCompositionEnabled'; DwmExtendFrameIntoClientAreaSig = 'DwmExtendFrameIntoClientArea'; TaskDialogSig = 'TaskDialog'; function CompositingEnabled: Boolean; var DLLHandle: THandle; DwmIsCompositionEnabledProc: function(pfEnabled: PBoolean): HRESULT; stdcall; Enabled: Boolean; begin Result := False; if IsWindowsVista then begin DLLHandle := LoadLibrary(dwmapi); if DLLHandle <> 0 then begin @DwmIsCompositionEnabledProc := GetProcAddress(DLLHandle, DwmIsCompositionEnabledSig); if (@DwmIsCompositionEnabledProc <> nil) then begin DwmIsCompositionEnabledProc(@Enabled); Result := Enabled; end; FreeLibrary(DLLHandle); end; end; end; procedure ExtendGlass(const AHandle: THandle; const AMargins: TRect); type _MARGINS = packed record cxLeftWidth: Integer; cxRightWidth: Integer; cyTopHeight: Integer; cyBottomHeight: Integer; end; PMargins = ^_MARGINS; TMargins = _MARGINS; var DLLHandle: THandle; DwmExtendFrameIntoClientAreaProc: function(destWnd: HWND; const pMarInset: PMargins): HRESULT; stdcall; Margins: TMargins; begin if IsWindowsVista and CompositingEnabled then begin DLLHandle := LoadLibrary(dwmapi); if DLLHandle <> 0 then begin @DwmExtendFrameIntoClientAreaProc := GetProcAddress(DLLHandle, DwmExtendFrameIntoClientAreaSig); if (@DwmExtendFrameIntoClientAreaProc <> nil) then begin ZeroMemory(@Margins, SizeOf(Margins)); Margins.cxLeftWidth := AMargins.Left; Margins.cxRightWidth := AMargins.Right; Margins.cyTopHeight := AMargins.Top; Margins.cyBottomHeight := AMargins.Bottom; DwmExtendFrameIntoClientAreaProc(AHandle, @Margins); end; FreeLibrary(DLLHandle); end; end; end; function TaskDialog(const AHandle: THandle; const ATitle, ADescription, AContent: string; const Icon, Buttons: Integer): Integer; var DLLHandle: THandle; res: integer; S: string; wTitle, wDescription, wContent: array[0..1024] of widechar; Btns: TMsgDlgButtons; DlgType: TMsgDlgType; TaskDialogProc: function(HWND: THandle; hInstance: THandle; cTitle, cDescription, cContent: pwidechar; Buttons: Integer; Icon: integer; ResButton: pinteger): integer; cdecl stdcall; begin Result := 0; if IsWindowsVista then begin DLLHandle := LoadLibrary(comctl32); if DLLHandle >= 32 then begin @TaskDialogProc := GetProcAddress(DLLHandle, TaskDialogSig); if Assigned(TaskDialogProc) then begin StringToWideChar(ATitle, wTitle, SizeOf(wTitle)); StringToWideChar(ADescription, wDescription, SizeOf(wDescription)); S := StringReplace(AContent, #10, '', [rfReplaceAll]); S := StringReplace(S, #13, '', [rfReplaceAll]); StringToWideChar(S, wContent, SizeOf(wContent)); TaskDialogProc(AHandle, 0, wTitle, wDescription, wContent, Buttons, Icon, @res); Result := mrOK; case res of TD_RESULT_CANCEL: Result := mrCancel; TD_RESULT_RETRY: Result := mrRetry; TD_RESULT_YES: Result := mrYes; TD_RESULT_NO: Result := mrNo; TD_RESULT_CLOSE: Result := mrAbort; end; end; FreeLibrary(DLLHandle); end; end else begin Btns := []; if Buttons and TD_BUTTON_OK = TD_BUTTON_OK then Btns := Btns + [MBOK]; if Buttons and TD_BUTTON_YES = TD_BUTTON_YES then Btns := Btns + [MBYES]; if Buttons and TD_BUTTON_NO = TD_BUTTON_NO then Btns := Btns + [MBNO]; if Buttons and TD_BUTTON_CANCEL = TD_BUTTON_CANCEL then Btns := Btns + [MBCANCEL]; if Buttons and TD_BUTTON_RETRY = TD_BUTTON_RETRY then Btns := Btns + [MBRETRY]; if Buttons and TD_BUTTON_CLOSE = TD_BUTTON_CLOSE then Btns := Btns + [MBABORT]; DlgType := mtCustom; case Icon of TD_ICON_WARNING: DlgType := mtWarning; TD_ICON_QUESTION: DlgType := mtConfirmation; TD_ICON_ERROR: DlgType := mtError; TD_ICON_INFORMATION: DlgType := mtInformation; end; Result := MessageDlg(AContent, DlgType, Btns, 0); end; end; end.
unit uMoreEnumerators; interface uses uEnumeratorExample ; type TForInDemoClassReverseEnumerator = class private FString: string; FIndex: integer; protected function GetCurrent: Char; virtual; public constructor Create(aString: string); function MoveNext: Boolean; property Current: Char read GetCurrent; end; TForInDemoClassUpperCaseEnumerator = class(TForInDemoClassEnumerator) protected function GetCurrent: Char; override; end; TReverseEnumeratorProxy = class private FOwner: TForInDemo; public constructor Create(aOwner: TForInDemo); function GetEnumerator: TForInDemoClassReverseEnumerator; end; TUpperCaseEnumeratorProxy = class private FOwner: TForInDemo; public constructor Create(aOwner: TForInDemo); function GetEnumerator: TForInDemoClassUpperCaseEnumerator; end; TForInDemoExtraIterators = class(TForInDemo) private FUpper: TUpperCaseEnumeratorProxy; FReverse: TReverseEnumeratorProxy; public constructor Create(aString: string); property AsUpperCase: TUpperCaseEnumeratorProxy read FUpper; property AsReversed: TReverseEnumeratorProxy read FReverse; end; procedure DoMoreStuff; implementation procedure DoMoreStuff; var C: Char; ForInExtraDemo: TForInDemoExtraIterators; begin ForInExtraDemo := TForInDemoExtraIterators.Create('Greetings'); try for C in ForInExtraDemo.AsUpperCase do begin Write(C, ','); end; WriteLn; for C in ForInExtraDemo.AsReversed do begin Write(c, ','); end; WriteLn; finally ForInExtraDemo.Free; end; end; { TForInDemoExtraIteratorsClass } constructor TForInDemoExtraIterators.Create(aString: string); begin inherited Create(aString); FUpper := TUpperCaseEnumeratorProxy.Create(Self); FReverse := TReverseEnumeratorProxy.Create(Self); end; { TForInDemoClassCapitalEnumerator } function TForInDemoClassUpperCaseEnumerator.GetCurrent: Char; begin Result := UpCase(inherited GetCurrent); end; { TUpperCaseEnumeratorProxy } constructor TUpperCaseEnumeratorProxy.Create(aOwner: TForInDemo); begin inherited Create; FOwner := aOwner end; function TUpperCaseEnumeratorProxy.GetEnumerator: TForInDemoClassUpperCaseEnumerator; begin Result := TForInDemoClassUpperCaseEnumerator.Create(FOwner.TheString); end; { TForInDemoClassReverseEnumerator } constructor TForInDemoClassReverseEnumerator.Create(aString: string); begin inherited Create; FString := aString; FIndex := Length(aString) + 1; end; function TForInDemoClassReverseEnumerator.GetCurrent: Char; begin Result := FString[FIndex]; end; function TForInDemoClassReverseEnumerator.MoveNext: Boolean; begin Dec(FIndex); Result := FIndex > 0; end; { TReverseEnumeratorProxy } constructor TReverseEnumeratorProxy.Create(aOwner: TForInDemo); begin inherited Create; FOwner := aOwner; end; function TReverseEnumeratorProxy.GetEnumerator: TForInDemoClassReverseEnumerator; begin Result := TForInDemoClassReverseEnumerator.Create(FOwner.TheString); end; end.
(* MIT License Copyright (c) 2018 Ondrej Kelle 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. *) //------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- // NOTE: When changing this file, you may need to update the GUID in ByteCodeCacheReleaseFileVersion.h // Please update the GUID when: // * CHAKRA_CORE_VERSION_RELEASE is changed to 1 // * CHAKRA_CORE_VERSION_RELEASE is currently set to 1 and the bytecode changes // See notes below about ReleaseVersioningScheme. unit ChakraCoreVersion; interface // -------------- // VERSION NUMBER // -------------- // ChakraCore version number definitions (used in ChakraCore binary metadata) const CHAKRA_CORE_MAJOR_VERSION = 1; CHAKRA_CORE_MINOR_VERSION = 7; CHAKRA_CORE_PATCH_VERSION = 6; CHAKRA_CORE_VERSION_RELEASE_QFE = 0; // Redundant with PATCH_VERSION. Keep this value set to 0. // ------------- // RELEASE FLAGS // ------------- // NOTE: CHAKRA_CORE_VERSION_PRERELEASE can only be set to 1 when // CHAKRA_CORE_VERSION_RELEASE is set to 1, or there is no effect. // Here are the meanings of the various combinations: // // RELEASE** PRERELEASE // DEVELOPMENT 0 0 // <INVALID> 0 1 # INVALID but identical to DEVELOPMENT // RELEASE** 1 0 # // PRERELEASE 1 1 // ** Release flags are not related to build type (e.g. x64_release) // // Unless otherwise noted, the code affected by these flags lies mostly in bin/CoreCommon.ver // // DEVELOPMENT: // * Uses EngineeringVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) // * Sets file flag VS_FF_PRIVATEBUILD // * Adds "Private" to the file description // // RELEASE** and PRERELEASE (i.e. controlled by CHAKRA_CORE_VERSION_RELEASE flag): // * Uses ReleaseVersioningScheme (see lib/Runtime/ByteCode/ByteCodeSerializer.cpp) // // PRERELEASE (preparing for release but not yet ready to release): // * Sets file flag VS_FF_PRERELEASE // * Adds "Pre-release" to the file description // // RELEASE** (code is ready to release) // * Sets neither of the file flags noted above // * Does not add anything to the file description // ChakraCore RELEASE and PRERELEASE flags CHAKRA_CORE_VERSION_RELEASE = 1; CHAKRA_CORE_VERSION_PRERELEASE = 0; // Chakra RELEASE flag // Mostly redundant with CHAKRA_CORE_VERSION_RELEASE, // but semantically refers to Chakra rather than ChakraCore. CHAKRA_VERSION_RELEASE = 1; implementation end.
{ DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(DBEBr Framework) @created(20 Jul 2016) @author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>) } unit dbebr.driver.sqlite3; interface uses Classes, DB, Variants, SQLiteTable3, Datasnap.DBClient, // DBEBr dbebr.driver.connection, dbebr.factory.interfaces; type // Classe de conexão concreta com dbExpress TDriverSQLite3 = class(TDriverConnection) protected FConnection: TSQLiteDatabase; FScripts: TStrings; public constructor Create(const AConnection: TComponent; const ADriverName: TDriverName); override; destructor Destroy; override; procedure Connect; override; procedure Disconnect; override; procedure ExecuteDirect(const ASQL: string); override; procedure ExecuteDirect(const ASQL: string; const AParams: TParams); override; procedure ExecuteScript(const ASQL: string); override; procedure AddScript(const ASQL: string); override; procedure ExecuteScripts; override; function IsConnected: Boolean; override; function InTransaction: Boolean; override; function CreateQuery: IDBQuery; override; function CreateResultSet(const ASQL: String): IDBResultSet; override; function ExecuteSQL(const ASQL: string): IDBResultSet; override; end; TDriverQuerySQLite3 = class(TDriverQuery) private FSQLQuery: TSQLitePreparedStatement; protected procedure SetCommandText(ACommandText: string); override; function GetCommandText: string; override; public constructor Create(AConnection: TSQLiteDatabase); destructor Destroy; override; procedure ExecuteDirect; override; function ExecuteQuery: IDBResultSet; override; end; TDriverResultSetSQLite3 = class(TDriverResultSetBase) private procedure CreateFieldDefs; protected FConnection: TSQLiteDatabase; FDataSet: ISQLiteTable; FRecordCount: Integer; FFetchingAll: Boolean; FFirstNext: Boolean; FFieldDefs: TFieldDefs; FDataSetInternal: TClientDataSet; public constructor Create(const AConnection: TSQLiteDatabase; const ADataSet: ISQLiteTable); destructor Destroy; override; procedure Close; override; function NotEof: Boolean; override; function RecordCount: Integer; override; function FieldDefs: TFieldDefs; override; function GetFieldValue(const AFieldName: string): Variant; overload; override; function GetFieldValue(const AFieldIndex: Integer): Variant; overload; override; function GetFieldType(const AFieldName: string): TFieldType; override; function GetField(const AFieldName: string): TField; override; end; implementation uses SysUtils; { TDriverSQLite3 } constructor TDriverSQLite3.Create(const AConnection: TComponent; const ADriverName: TDriverName); begin inherited; FConnection := AConnection as TSQLiteDatabase; FConnection.Connected := True; FDriverName := ADriverName; FScripts := TStringList.Create; end; destructor TDriverSQLite3.Destroy; begin FConnection.Connected := False; FConnection := nil; FScripts.Free; inherited; end; procedure TDriverSQLite3.Disconnect; begin inherited; /// <summary> /// Esse driver nativo, por motivo de erro, tem que manter a conexão aberta /// até o final do uso da aplicação. /// O FConnection.Connected := False; é chamado no Destroy; /// </summary> end; procedure TDriverSQLite3.ExecuteDirect(const ASQL: string); begin inherited; FConnection.ExecSQL(ASQL); end; procedure TDriverSQLite3.ExecuteDirect(const ASQL: string; const AParams: TParams); var LExeSQL: ISQLitePreparedStatement; LAffectedRows: Integer; LFor: Integer; begin LExeSQL := TSQLitePreparedStatement.Create(FConnection); /// <summary> /// Tem um Bug no método SetParamVariant(Name, Value) passando parêmetro NAME, /// por isso usei passando o INDEX. /// </summary> LExeSQL.ClearParams; for LFor := 0 to AParams.Count -1 do LExeSQL.SetParamVariant(AParams.Items[LFor].Name, AParams.Items[LFor].Value); LExeSQL.PrepareStatement(ASQL); try LExeSQL.ExecSQL(LAffectedRows); except raise; end; end; procedure TDriverSQLite3.ExecuteScript(const ASQL: string); begin inherited; FConnection.ExecSQL(ASQL); end; procedure TDriverSQLite3.ExecuteScripts; var LFor: Integer; begin inherited; try for LFor := 0 to FScripts.Count -1 do FConnection.ExecSQL(FScripts[LFor]); finally FScripts.Clear; end; end; function TDriverSQLite3.ExecuteSQL(const ASQL: string): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQuerySQLite3.Create(FConnection); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; procedure TDriverSQLite3.AddScript(const ASQL: string); begin inherited; FScripts.Add(ASQL); end; procedure TDriverSQLite3.Connect; begin inherited; FConnection.Connected := True; end; function TDriverSQLite3.InTransaction: Boolean; begin Result := FConnection.IsTransactionOpen; end; function TDriverSQLite3.IsConnected: Boolean; begin inherited; Result := FConnection.Connected; end; function TDriverSQLite3.CreateQuery: IDBQuery; begin Result := TDriverQuerySQLite3.Create(FConnection); end; function TDriverSQLite3.CreateResultSet(const ASQL: String): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQuerySQLite3.Create(FConnection); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; { TDriverDBExpressQuery } constructor TDriverQuerySQLite3.Create(AConnection: TSQLiteDatabase); begin FSQLQuery := TSQLitePreparedStatement.Create(AConnection); end; destructor TDriverQuerySQLite3.Destroy; begin FSQLQuery.Free; inherited; end; function TDriverQuerySQLite3.ExecuteQuery: IDBResultSet; var LStatement: TSQLitePreparedStatement; LResultSet: ISQLiteTable; begin LStatement := TSQLitePreparedStatement.Create(FSQLQuery.DB, FSQLQuery.SQL); try try LResultSet := LStatement.ExecQueryIntf; except raise; end; Result := TDriverResultSetSQLite3.Create(FSQLQuery.DB, LResultSet); if LResultSet.Eof then Result.FetchingAll := True; finally LStatement.Free; end; end; function TDriverQuerySQLite3.GetCommandText: string; begin Result := FSQLQuery.SQL; end; procedure TDriverQuerySQLite3.SetCommandText(ACommandText: string); begin inherited; FSQLQuery.SQL := ACommandText; end; procedure TDriverQuerySQLite3.ExecuteDirect; begin FSQLQuery.ExecSQL; end; procedure TDriverResultSetSQLite3.Close; begin if Assigned(FDataSet) then FDataSet := nil; end; constructor TDriverResultSetSQLite3.Create(const AConnection: TSQLiteDatabase; const ADataSet: ISQLiteTable); var LField: TField; LFor: Integer; begin FConnection := AConnection; FDataSet := ADataSet; FFieldDefs := TFieldDefs.Create(nil); FDataSetInternal := TClientDataSet.Create(nil); LField := nil; for LFor := 0 to FDataSet.FieldCount -1 do begin case FDataSet.Fields[LFor].FieldType of 0: LField := TStringField.Create(FDataSetInternal); 1: LField := TIntegerField.Create(FDataSetInternal); 2: LField := TFloatField.Create(FDataSetInternal); 3: LField := TWideStringField.Create(FDataSetInternal); 4: LField := TBlobField.Create(FDataSetInternal); // 5: 15: LField := TDateField.Create(FDataSetInternal); 16: LField := TDateTimeField.Create(FDataSetInternal); end; LField.FieldName := FDataSet.Fields[LFor].Name; LField.DataSet := FDataSetInternal; LField.FieldKind := fkData; end; FDataSetInternal.CreateDataSet; /// <summary> /// Criar os FieldDefs, pois nesse driver não cria automaticamente. /// </summary> CreateFieldDefs; end; destructor TDriverResultSetSQLite3.Destroy; begin FDataSet := nil; FFieldDefs.Free; FDataSetInternal.Free; inherited; end; function TDriverResultSetSQLite3.FieldDefs: TFieldDefs; begin inherited; Result := FFieldDefs; end; function TDriverResultSetSQLite3.GetFieldValue(const AFieldName: string): Variant; begin inherited; Result := FDataSet.FieldByName[AFieldName].Value; end; function TDriverResultSetSQLite3.GetField(const AFieldName: string): TField; begin inherited; FDataSetInternal.Edit; FDataSetInternal.FieldByName(AFieldName).Value := FDataSet.FieldByName[AFieldName].Value; FDataSetInternal.Post; Result := FDataSetInternal.FieldByName(AFieldName); end; function TDriverResultSetSQLite3.GetFieldType(const AFieldName: string): TFieldType; begin inherited; Result := TFieldType(FDataSet.FindField(AFieldName).FieldType); end; function TDriverResultSetSQLite3.GetFieldValue(const AFieldIndex: Integer): Variant; begin inherited; if Cardinal(AFieldIndex) > FDataSet.FieldCount -1 then Exit(Variants.Null); if FDataSet.Fields[AFieldIndex].IsNull then Result := Variants.Null else Result := FDataSet.Fields[AFieldIndex].Value; end; function TDriverResultSetSQLite3.NotEof: Boolean; begin inherited; if not FFirstNext then FFirstNext := True else FDataSet.Next; Result := not FDataSet.Eof; end; function TDriverResultSetSQLite3.RecordCount: Integer; begin inherited; Result := FDataSet.Row; end; procedure TDriverResultSetSQLite3.CreateFieldDefs; var LFor: Integer; begin FFieldDefs.Clear; for LFor := 0 to FDataSet.FieldCount -1 do begin with FFieldDefs.AddFieldDef do begin Name := FDataSet.Fields[LFor].Name; DataType := TFieldType(FDataSet.Fields[LFor].FieldType); end; end; end; end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Model relacionado à tabela [FIN_CHEQUE_RECEBIDO] The MIT License Copyright: Copyright (C) 2020 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 FinChequeRecebido; interface uses Generics.Collections, System.SysUtils, Pessoa, MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TFinChequeRecebido = class(TModelBase) private FId: Integer; FIdPessoa: Integer; FCpf: string; FCnpj: string; FNome: string; FCodigoBanco: string; FCodigoAgencia: string; FConta: string; FNumero: Integer; FDataEmissao: TDateTime; FBomPara: TDateTime; FDataCompensacao: TDateTime; FValor: Extended; FCustodiaData: TDateTime; FCustodiaTarifa: Extended; FCustodiaComissao: Extended; FDescontoData: TDateTime; FDescontoTarifa: Extended; FDescontoComissao: Extended; FValorRecebido: Extended; FPessoa: TPessoa; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; constructor Create; virtual; destructor Destroy; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FId write FId; [MVCColumnAttribute('ID_PESSOA')] [MVCNameAsAttribute('idPessoa')] property IdPessoa: Integer read FIdPessoa write FIdPessoa; [MVCColumnAttribute('CPF')] [MVCNameAsAttribute('cpf')] property Cpf: string read FCpf write FCpf; [MVCColumnAttribute('CNPJ')] [MVCNameAsAttribute('cnpj')] property Cnpj: string read FCnpj write FCnpj; [MVCColumnAttribute('NOME')] [MVCNameAsAttribute('nome')] property Nome: string read FNome write FNome; [MVCColumnAttribute('CODIGO_BANCO')] [MVCNameAsAttribute('codigoBanco')] property CodigoBanco: string read FCodigoBanco write FCodigoBanco; [MVCColumnAttribute('CODIGO_AGENCIA')] [MVCNameAsAttribute('codigoAgencia')] property CodigoAgencia: string read FCodigoAgencia write FCodigoAgencia; [MVCColumnAttribute('CONTA')] [MVCNameAsAttribute('conta')] property Conta: string read FConta write FConta; [MVCColumnAttribute('NUMERO')] [MVCNameAsAttribute('numero')] property Numero: Integer read FNumero write FNumero; [MVCColumnAttribute('DATA_EMISSAO')] [MVCNameAsAttribute('dataEmissao')] property DataEmissao: TDateTime read FDataEmissao write FDataEmissao; [MVCColumnAttribute('BOM_PARA')] [MVCNameAsAttribute('bomPara')] property BomPara: TDateTime read FBomPara write FBomPara; [MVCColumnAttribute('DATA_COMPENSACAO')] [MVCNameAsAttribute('dataCompensacao')] property DataCompensacao: TDateTime read FDataCompensacao write FDataCompensacao; [MVCColumnAttribute('VALOR')] [MVCNameAsAttribute('valor')] property Valor: Extended read FValor write FValor; [MVCColumnAttribute('CUSTODIA_DATA')] [MVCNameAsAttribute('custodiaData')] property CustodiaData: TDateTime read FCustodiaData write FCustodiaData; [MVCColumnAttribute('CUSTODIA_TARIFA')] [MVCNameAsAttribute('custodiaTarifa')] property CustodiaTarifa: Extended read FCustodiaTarifa write FCustodiaTarifa; [MVCColumnAttribute('CUSTODIA_COMISSAO')] [MVCNameAsAttribute('custodiaComissao')] property CustodiaComissao: Extended read FCustodiaComissao write FCustodiaComissao; [MVCColumnAttribute('DESCONTO_DATA')] [MVCNameAsAttribute('descontoData')] property DescontoData: TDateTime read FDescontoData write FDescontoData; [MVCColumnAttribute('DESCONTO_TARIFA')] [MVCNameAsAttribute('descontoTarifa')] property DescontoTarifa: Extended read FDescontoTarifa write FDescontoTarifa; [MVCColumnAttribute('DESCONTO_COMISSAO')] [MVCNameAsAttribute('descontoComissao')] property DescontoComissao: Extended read FDescontoComissao write FDescontoComissao; [MVCColumnAttribute('VALOR_RECEBIDO')] [MVCNameAsAttribute('valorRecebido')] property ValorRecebido: Extended read FValorRecebido write FValorRecebido; [MVCNameAsAttribute('pessoa')] property Pessoa: TPessoa read FPessoa write FPessoa; end; implementation { TFinChequeRecebido } constructor TFinChequeRecebido.Create; begin FPessoa := TPessoa.Create; end; destructor TFinChequeRecebido.Destroy; begin FreeAndNil(FPessoa); inherited; end; procedure TFinChequeRecebido.ValidarInsercao; begin inherited; end; procedure TFinChequeRecebido.ValidarAlteracao; begin inherited; end; procedure TFinChequeRecebido.ValidarExclusao; begin inherited; end; end.
{***************************************************************************} { } { DMemCached - Copyright (C) 2014 - Víctor de Souza Faria } { } { victor@victorfaria.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DMemcached.MemCached; interface uses IdTCPClient, System.Classes, System.SysUtils, DMemcached.Trasncoder, DMemcached.Message; type IMemCacheClient<T> = interface function Add(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Store(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Replace(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Get(key: String): T; function Delete(key: String): Boolean; function Version: String; procedure Flush; end; TMemcachedClient<T> = class(TInterfacedObject, IMemCacheClient<T>) private FTcpConnection: TIdTCPClient; FTrascoder: ITranscoder<T>; function ExecuteCommand(baseMessage: TMemcachedBaseMessage<T>): TMemcachedBaseMessage<T>; public constructor Create(host: String; port: Integer; trascoder: ITranscoder<T> = nil); destructor Destroy; override; function Add(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Delete(key: String): Boolean; function Store(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Replace(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; function Get(key: String): T; function Version: String; procedure Flush; end; implementation uses IdGlobal, DMemcached.Command; { TMemcached } function TMemcachedClient<T>.Add(key: String; value: T; expire: UInt32 = 0; flags: UInt32 = 0): Boolean; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := TCommand<T>.ExecuteCommand(FTcpConnection, TMemcachedSetMessage<T>.Create(opAdd, key, value, flags, expire, FTrascoder), FTrascoder); Result := ((objResponse.Header as TMemcaheResponseHeader).Status = NoError) and (objResponse.Header.CAS <> 0); end; constructor TMemcachedClient<T>.Create(host: String; port: Integer; trascoder: ITranscoder<T>); var defaultTrasncoder: TTranscoder; begin if trascoder = nil then begin defaultTrasncoder := TTranscoder.Default<T>; if not Assigned(defaultTrasncoder) then begin raise Exception.Create('Invalid Data Type.'); end; FTrascoder := defaultTrasncoder as ITranscoder<T>; end else begin FTrascoder := trascoder; end; FTcpConnection := TIdTCPClient.Create(nil); FTcpConnection.Host := host; FTcpConnection.Port := port; FTcpConnection.Connect; end; function TMemcachedClient<T>.Delete(key: String): Boolean; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := ExecuteCommand(TMemcachedGetMessage<T>.Create(opDelete, key, FTrascoder)); Result := (objResponse.Header as TMemcaheResponseHeader).Status = NoError; end; destructor TMemcachedClient<T>.Destroy; begin FTcpConnection.Disconnect; FTcpConnection.Free; inherited; end; function TMemcachedClient<T>.ExecuteCommand( baseMessage: TMemcachedBaseMessage<T>): TMemcachedBaseMessage<T>; begin Result := TCommand<T>.ExecuteCommand(FTcpConnection, baseMessage, FTrascoder); end; procedure TMemcachedClient<T>.Flush; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := ExecuteCommand(TMemcachedGetMessage<T>.Create(opFlush, '', FTrascoder)); end; function TMemcachedClient<T>.Get(key: String): T; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := ExecuteCommand(TMemcachedGetMessage<T>.Create(opGet, key, FTrascoder)); Result := objResponse.Value; end; function TMemcachedClient<T>.Replace(key: String; value: T; expire, flags: UInt32): Boolean; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := ExecuteCommand(TMemcachedSetMessage<T>.Create(opReplace, key, value, flags, expire, FTrascoder)); Result := ((objResponse.Header as TMemcaheResponseHeader).Status = NoError) and (objResponse.Header.CAS <> 0); end; function TMemcachedClient<T>.Store(key: String; value: T; expire, flags: UInt32): Boolean; var objResponse: TMemcachedBaseMessage<T>; begin objResponse := ExecuteCommand(TMemcachedSetMessage<T>.Create(opSet, key, value, flags, expire, FTrascoder)); Result := ((objResponse.Header as TMemcaheResponseHeader).Status = NoError) and (objResponse.Header.CAS <> 0); end; function TMemcachedClient<T>.Version: String; var objResponse: TMemcachedBaseMessage<AnsiString>; begin objResponse := TCommand<AnsiString>.ExecuteCommand(FTcpConnection, TMemcachedGetMessage<AnsiString>.Create(opVersion, '', TTrasncoderAnsiString.Create), TTrasncoderAnsiString.Create); Result := objResponse.Value; end; end.
unit Facade; interface uses BaseFacades, Registrator, Classes, DBGate, SDFacade, SubdivisionComponent, Straton, Theme, Well, BaseObjects; type TMainFacade = class (TSDFacade) private FFilter: string; FRegistrator: TRegistrator; FSubdivisionComments: TSubdivisionComments; FTectonicBlocks: TTectonicBlocks; FStratons: TStratons; FThemes, FSubdivisionThemes: TThemes; FSelectedWells: TWells; function GetAllTexctonicBlocks: TTectonicBlocks; function GetStratons: TStratons; function GetSubdivisionComments: TSubdivisionComments; function GetThemes: TThemes; function GetSelectedWells: TWells; function GetSubdivisionThemes: TThemes; protected function GetRegistrator: TRegistrator; override; function GetDataPosterByClassType(ADataPosterClass: TDataPosterClass): TDataPoster; override; public // все комменты к разбивкам property AllSubdivisionComments: TSubdivisionComments read GetSubdivisionComments; // все тектонические бловки property AllTectonicBlocks: TTectonicBlocks read GetAllTexctonicBlocks; // темы НИР property AllThemes: TThemes read GetThemes; // темы, по которым уже есть разбивки property SubdivisionThemes: TThemes read GetSubdivisionThemes; procedure RefreshSubdivisionThemes; // стратоны property AllStratons: TStratons read GetStratons; // выбранные скважины property SelectedWells: TWells read GetSelectedWells; // фильтр property Filter: string read FFilter write FFilter; // в конструкторе создаются и настраиваются всякие // необходимые в скором времени вещи constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TConcreteRegistrator = class(TRegistrator) public constructor Create; override; end; implementation uses SysUtils, WellPoster, SubdivisionComponentPoster, StratonPoster; { TMDFacade } constructor TMainFacade.Create(AOwner: TComponent); begin inherited; // настройка соединения с бд //DBGates.ServerClassString := 'RiccServer.CommonServer'; DBGates.AutorizationMethod := amEnum; DBGates.NewAutorizationMode := false; SettingsFileName := 'SR.ini' // обязательно также тип клиента прям здесь указать end; destructor TMainFacade.Destroy; begin FreeAndNil(FTectonicBlocks); FreeAndNil(FSubdivisionComments); FreeAndNil(FStratons); FreeAndNil(FThemes); FreeAndNil(FSelectedWells); FreeAndNil(FSubdivisionThemes); inherited; end; function TMainFacade.GetAllTexctonicBlocks: TTectonicBlocks; begin if not Assigned(FTectonicBlocks) then begin FTectonicBlocks := TTectonicBlocks.Create; FTectonicBlocks.Reload('', true); end; Result := FTectonicBlocks; end; function TMainFacade.GetDataPosterByClassType( ADataPosterClass: TDataPosterClass): TDataPoster; begin Result := inherited GetDataPosterByClassType(ADataPosterClass); if Result is TWellDynamicParametersDataPoster then begin (Result as TWellDynamicParametersDataPoster).AllCategories := AllCategoriesWells; (Result as TWellDynamicParametersDataPoster).AllStates := AllStatesWells; (Result as TWellDynamicParametersDataPoster).AllProfiles := AllProfiles; (Result as TWellDynamicParametersDataPoster).AllFluidTypes := AllFluidTypes; (Result as TWellDynamicParametersDataPoster).AllStratons := AllSimpleStratons; (Result as TWellDynamicParametersDataPoster).AllVersions := AllVersions; end else if (Result is TSubdivisionDataPoster) then begin (Result as TSubdivisionDataPoster).AllThemes := AllThemes; (Result as TSubdivisionDataPoster).AllEmployees := AllEmployees; end else if (Result is TSubdivisionComponentDataPoster) then begin (Result as TSubdivisionComponentDataPoster).AllStratons := AllSimpleStratons; (Result as TSubdivisionComponentDataPoster).AllTectonicBlocks := AllTectonicBlocks; (Result as TSubdivisionComponentDataPoster).AllSubdivisionComments := AllSubdivisionComments; end else if (Result is TStratonDataPoster) then (Result as TStratonDataPoster).AllSimpleStratons := AllSimpleStratons; end; function TMainFacade.GetRegistrator: TRegistrator; begin if not Assigned(FRegistrator) then FRegistrator := TConcreteRegistrator.Create; Result := FRegistrator; end; { TConcreteRegistrator } constructor TConcreteRegistrator.Create; begin inherited; AllowedControlClasses.Add(TStringsRegisteredObject); AllowedControlClasses.Add(TTreeViewRegisteredObject); end; function TMainFacade.GetSelectedWells: TWells; begin if not Assigned(FSelectedWells) then begin FSelectedWells := TWells.Create(); FSelectedWells.OwnsObjects := false; end; Result := FSelectedWells; end; function TMainFacade.GetStratons: TStratons; begin if not Assigned(FStratons) then begin FStratons := TStratons.Create; FStratons.Reload('', true); end; result := FStratons; end; function TMainFacade.GetSubdivisionComments: TSubdivisionComments; begin if not Assigned(FSubdivisionComments) then begin FSubdivisionComments := TSubdivisionComments.Create; FSubdivisionComments.Reload('', true); end; Result := FSubdivisionComments; end; function TMainFacade.GetSubdivisionThemes: TThemes; begin if not Assigned(FSubdivisionThemes) then begin FSubdivisionThemes := TThemes.Create; FSubdivisionThemes.Reload('theme_ID in (select distinct theme_id from tbl_subdivision)', false); end; Result := FSubdivisionThemes; end; function TMainFacade.GetThemes: TThemes; begin if not Assigned(FThemes) then begin FThemes := TThemes.Create; FThemes.Reload('', true); end; Result := FThemes; end; procedure TMainFacade.RefreshSubdivisionThemes; begin FreeAndNil(FSubdivisionThemes); end; end.
var a,n:integer; function gcd(a,b:integer):integer; begin if a=0 then gcd:=b else gcd:=gcd(b mod a,a); end; function phi(n:integer):integer; var i:integer; begin phi:=0; if n=1 then phi:=1 else for i:=1 to n-1 do if gcd(i,n)=1 then inc(phi); end; function powermod(a,pangkat,modulo:integer):integer; var temp:integer; begin if pangkat=0 then powermod:=1 else if pangkat=1 then powermod:=a mod modulo else begin temp:=powermod(a,pangkat div 2,modulo); if pangkat mod 2 = 0 then powermod:=(temp*temp) mod modulo else powermod:=(temp*temp*a) mod modulo; end; end; begin readln(a,n); writeln(powermod(a,phi(n),n)); end.
unit IdKeyDialog; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls; type { TDialog } TDialog = class(TForm) Button1: TButton; IdEdit: TEdit; AccesKeyEdit: TEdit; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); private FAccessKey: string; FDone: boolean; FId: string; procedure SetAccessKey(AValue: string); procedure SetDone(AValue: boolean); procedure SetId(AValue: string); { private declarations } public property AccessKey: string read FAccessKey write SetAccessKey; property Id: string read FId write SetId; property Done: boolean read FDone write SetDone; end; var Dialog: TDialog; implementation {$R *.lfm} { TDialog } procedure TDialog.Button1Click(Sender: TObject); begin AccessKey := AccesKeyEdit.Text; Id := IdEdit.Text; Done := true; AccesKeyEdit.Clear; IdEdit.Clear; Close; end; procedure TDialog.FormShow(Sender: TObject); begin Done := false; end; procedure TDialog.SetAccessKey(AValue: string); begin if FAccessKey = AValue then Exit; FAccessKey := AValue; end; procedure TDialog.SetDone(AValue: boolean); begin if FDone=AValue then Exit; FDone:=AValue; end; procedure TDialog.SetId(AValue: string); begin if FId = AValue then Exit; FId := AValue; end; end.
(* *************************************************************************** This example program converts input bitmap in "./data/fire.bmp" to a "32bpp RGBA" bitmap You can run it like this: ./convert *************************************************************************** *) program convert; uses bitmap; const {$IFDEF LINUX, UNIX, MACOS} DIR_BAR = '/'; {$ELSE} DIR_BAR = '\'; {$ENDIF} INPUT_FILENAME = 'data'+DIR_BAR+'fire.bmp'; var mem0: ^byte; bmp : PBitmap; bmp2: TBitmap; // converted bitmap info: TBitmapInf; begin // get info from bitmap file if not bitmap_get_info_from_file(INPUT_FILENAME, info) then begin WriteLn('Could not load bitmap file.'); halt(-1); end; // check bitmap information if (info.bpp = 32) and (info.pixel_format = PIXEL_FORMAT_RGBA) then begin WriteLn('Bitmap is already 32bpp and RGBA, nothing to be done.'); halt(0); end; // try loading bitmap from file bmp := bitmap_load_from_file(INPUT_FILENAME); if not Assigned(bmp) then begin WriteLn('Error while loading bitmap.'); halt(-1); end; // allocate memory for our 32 bit RGBA bitmap, "pixel_data_size + 4096 bytes" of memory is more than enough mem0 := GetMem(bitmap_raw_size(bmp^.width, bmp^.height, 32) + 4096); // create bitmap: 32bit RGBA bitmap_create(bmp^.width, bmp^.height, 32, BitmapV4, PIXEL_FORMAT_RGBA, mem0); bitmap_get_info(mem0, bmp2); // convert bitmap pixel data to "32 bit RGBA", coverted data gets written in "mem0 + pixels" bitmap_pixel_format(bmp^, PIXEL_FORMAT_RGBA, (bmp2.header+(bmp2.pixels - bmp2.header))^); bitmap_free(bmp); // save converted bitmap to file if bitmap_save_to_file('./data'+DIR_BAR+'converted.bmp', @bmp2) then WriteLn('File saved to: ','./data'+DIR_BAR+'converted.bmp'); FreeMem(mem0); end.
{*******************************************************} { Copyright(c) Lindemberg Cortez. } { All rights reserved } { https://github.com/LinlindembergCz } { Since 01/01/2019 } {*******************************************************} unit EF.Schema.MSSQL; interface uses SysUtils, classes, strUtils, EF.Mapping.Atributes, EF.Mapping.AutoMapper, EF.Drivers.Connection, EF.Schema.Abstract; type TMSSQL = class(TCustomDataBase) private function AlterColumn(Table, Field, Tipo: string; IsNull: boolean): string ;override; public function CreateTable( List: TList; Table: string; Key:TStringList = nil): string ;override; function AlterTable( Table, Field, Tipo: string; IsNull: boolean;ColumnExist: boolean): string ;override; function GetPrimaryKey( Table, Fields: string):string; function CreateForeignKey(AtributoForeignKey: PParamForeignKeys;Table: string): string;override; end; implementation { TMSSQLServer } function TMSSQL.AlterColumn(Table, Field, Tipo: string; IsNull: boolean): string; begin result:= 'Alter table ' + Table + ' Alter Column ' + Field + ' ' + Tipo + ' ' + ifthen(IsNull, '', 'NOT NULL'); end; function TMSSQL.AlterTable(Table, Field, Tipo: string; IsNull: boolean;ColumnExist: boolean): string; begin if ColumnExist then result:= AlterColumn( Table , Field, tipo , IsNull) else result:= 'Alter table ' + Table + ' Add ' + Field + ' ' + Tipo + ' ' + ifthen(IsNull, '', 'NOT NULL') end; function TMSSQL.CreateTable( List: TList; Table: string; Key:TStringList = nil ): string; var J: integer; TableList: TStringList; FieldAutoInc: string; Name, Tipo: string; AutoInc, PrimaryKey, IsNull: boolean; CreateScript , ListKey :TStringList; begin CreateScript := TStringList.Create; ListKey := TStringList.Create; ListKey.delimiter := ','; CreateScript.Clear; CreateScript.Add('Create Table ' + uppercase(Table)); CreateScript.Add('('); FieldAutoInc := ''; try for J := 0 to List.Count - 1 do begin Name := PParamAtributies(List.Items[J]).Name; Tipo := PParamAtributies(List.Items[J]).Tipo; if Tipo ='' then break; AutoInc := PParamAtributies(List.Items[J]).AutoInc; PrimaryKey := PParamAtributies(List.Items[J]).PrimaryKey; IsNull := PParamAtributies(List.Items[J]).IsNull; CreateScript.Add(Name + ' ' + Tipo + ' ' + ifthen(AutoInc, ' IDENTITY(1,1) ', '') + ifthen(IsNull, '', 'NOT NULL') + ifthen(J < List.Count - 1, ',', '')); if PrimaryKey then begin ListKey.Add(Name); if Key <> nil then Key.Add(Name); end; end; if ListKey.Count > 0 then begin CreateScript.Add( GetPrimaryKey(Table,ListKey.DelimitedText) ); result:= CreateScript.Text; end else raise exception.Create('Primary Key is riquered!'); finally CreateScript.Free; ListKey.Free; //Key.Free; end; end; function TMSSQL.GetPrimaryKey(Table, Fields: string): string; begin result:= ', CONSTRAINT [PK_' + Table + '] PRIMARY KEY CLUSTERED([' + Fields + '] ASC) ON [PRIMARY])'; end; function TMSSQL.CreateForeignKey(AtributoForeignKey: PParamForeignKeys; Table: string): string; begin result:= 'ALTER TABLE '+Table + ' ADD CONSTRAINT FK_'+AtributoForeignKey.ForeignKey+ ' FOREIGN KEY ('+AtributoForeignKey.ForeignKey+')'+ ' REFERENCES '+AtributoForeignKey.Name+' (ID) '+ ' ON DELETE '+ ifthen( AtributoForeignKey.OnDelete = rlCascade, ' CASCADE ', ifthen( AtributoForeignKey.OnDelete = rlSetNull, ' SET NULL ', ifthen( AtributoForeignKey.OnDelete = rlRestrict,' RESTRICT ', ' NO ACTION ' )))+ ' ON Update '+ ifthen( AtributoForeignKey.OnUpdate = rlCascade, ' CASCADE ', ifthen( AtributoForeignKey.OnUpdate = rlSetNull, ' SET NULL ', ifthen( AtributoForeignKey.OnUpdate = rlRestrict,' RESTRICT ', ' NO ACTION ' ))); end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela para tratamento dos arquivos de retorno The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (alberteije@gmail.com) @version 2.0 ******************************************************************************* } unit UProcessaRetorno; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, ActnList, RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, LabeledCtrls, ComCtrls, JvExDBGrids, JvDBGrid, JvDBUltimGrid, JvBaseEdits, Mask, JvExMask, JvToolEdit, Biblioteca, PessoaVO, ContaCaixaVO, ACBrBoleto, AdmParametroVO, SessaoUsuario, System.Actions, Controller, Vcl.Imaging.pngimage; type TFProcessaRetorno = class(TForm) PanelCabecalho: TPanel; Bevel1: TBevel; Image1: TImage; Label2: TLabel; ActionToolBarPrincipal: TActionToolBar; ActionManagerLocal: TActionManager; ActionProcessarRetorno: TAction; PageControlItens: TPageControl; tsDados: TTabSheet; PanelDados: TPanel; Bevel2: TBevel; DSRetorno: TDataSource; CDSRetorno: TClientDataSet; Grid: TJvDBUltimGrid; CDSRetornoNOSSO_NUMERO: TStringField; CDSRetornoLOG: TStringField; ActionSair: TAction; procedure ActionProcessarRetornoExecute(Sender: TObject); procedure FormShow(Sender: TObject); procedure ActionSairExecute(Sender: TObject); private { Private declarations } public { Public declarations } end; var FProcessaRetorno: TFProcessaRetorno; PessoaVO: TPessoaVO; ContaCaixaVO: TContaCaixaVO; AdmParametroVO: TAdmParametroVO; implementation uses UDataModule, ULookup, FinParcelaReceberController, FinParcelaReceberVO, FinParcelaRecebimentoVO, FinParcelaRecebimentoController, FinChequeRecebidoVO, AdmParametroController; {$R *.dfm} {$REGION 'Infra'} procedure TFProcessaRetorno.FormShow(Sender: TObject); var Filtro: String; begin Grid.SetFocus; Filtro := 'ID_EMPRESA = ' + IntToStr(TSessaoUsuario.Instance.Empresa.Id); AdmParametroVO := TAdmParametroVO(TController.BuscarObjeto('AdmParametroController.TAdmParametroController', 'ConsultaObjeto', [Filtro], 'GET')); end; {$ENDREGION} {$REGION 'Actions'} procedure TFProcessaRetorno.ActionProcessarRetornoExecute(Sender: TObject); var I: integer; Titulo: TACBrTitulo; ParcelaReceber: TFinParcelaReceberVO; ParcelaRecebimento: TFinParcelaRecebimentoVO; begin if not FDataModule.OpenDialog.Execute then Exit; try FDataModule.ACBrBoleto.Banco.TipoCobranca := cobBancoDoBrasil; FDataModule.ACBrBoleto.LayoutRemessa := c240; FDataModule.ACBrBoleto.LeCedenteRetorno := True; FDataModule.ACBrBoleto.DirArqRetorno := ExtractFileDir(FDataModule.OpenDialog.FileName); FDataModule.ACBrBoleto.NomeArqRetorno := ExtractFileName(FDataModule.OpenDialog.FileName); FDataModule.ACBrBoleto.LerRetorno; for I := 0 to FDataModule.ACBrBoleto.ListadeBoletos.Count - 1 do begin Titulo := FDataModule.ACBrBoleto.ListadeBoletos.Objects[i]; //Verifica se o titulo encontra-se no banco de dados ParcelaReceber := TFinParcelaReceberVO(TController.BuscarObjeto('FinParcelaReceberController.TFinParcelaReceberController', 'ConsultaObjeto', ['BOLETO_NOSSO_NUMERO=' + QuotedStr(Titulo.NossoNumero)], 'GET')); if not Assigned(ParcelaReceber) then begin CDSRetorno.Append; CDSRetornoNOSSO_NUMERO.AsString := Titulo.NossoNumero; CDSRetornoLOG.AsString := 'Nosso Número não localizado no banco de dados.'; CDSRetorno.Post; end else begin ParcelaReceber.IdFinStatusParcela := AdmParametroVO.FinParcelaQuitado; ParcelaRecebimento := TFinParcelaRecebimentoVO.Create; ParcelaRecebimento.IdFinTipoRecebimento := AdmParametroVO.FinTipoRecebimentoEdi; ParcelaRecebimento.IdFinParcelaReceber := ParcelaReceber.Id; ParcelaRecebimento.IdContaCaixa := ParcelaReceber.IdContaCaixa; ParcelaRecebimento.DataRecebimento := Titulo.DataBaixa; ParcelaRecebimento.TaxaMulta := Titulo.PercentualMulta; ParcelaRecebimento.ValorMulta := Titulo.ValorMoraJuros; ParcelaRecebimento.ValorDesconto := Titulo.ValorDesconto; ParcelaRecebimento.Historico := 'RECEBIDO VIA EDI BANCARIO - REFERENCIA: ' + Titulo.Referencia; ParcelaRecebimento.ValorRecebido := Titulo.ValorRecebido; CDSRetorno.Append; CDSRetornoNOSSO_NUMERO.AsString := Titulo.NossoNumero; CDSRetornoLOG.AsString := 'Título processado com sucesso.'; CDSRetorno.Post; TController.ExecutarMetodo('FinParcelaReceberController.TFinParcelaReceberController', 'Altera', [ParcelaReceber], 'POST', 'Boolean'); end; end; finally end; end; procedure TFProcessaRetorno.ActionSairExecute(Sender: TObject); begin Close; end; {$ENDREGION} end.
unit FreeOTFEExplorerfrmPropertiesDlg_File; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FreeOTFEExplorerfrmPropertiesDlg_Base, ExtCtrls, StdCtrls, ComCtrls; type TfrmPropertiesDialog_File = class(TfrmPropertiesDialog_Base) edOpensWith: TLabel; Image1: TImage; Label9: TLabel; Panel1: TPanel; edTimestampCreated: TLabel; Label5: TLabel; Label1: TLabel; edTimestampModified: TLabel; Label11: TLabel; Panel4: TPanel; edTimestampAccessed: TLabel; procedure FormShow(Sender: TObject); procedure pbOKClick(Sender: TObject); private { Private declarations } public PathAndFilename: WideString; end; implementation {$R *.dfm} uses SDUGeneral, SDUGraphics, SDUi18n, SDFilesystem_FAT; procedure TfrmPropertiesDialog_File.FormShow(Sender: TObject); var item: TSDDirItem_FAT; DLLFilename: string; DLLIconIdx: integer; tmpIcon: TIcon; begin inherited; self.Caption := SDUParamSubstitute( _('%1 Properties'), [ExtractFilename(PathAndFilename)] ); SetupCtlSeparatorPanel(Panel1); SetupCtlSeparatorPanel(Panel4); item:= TSDDirItem_FAT.Create(); try if Filesystem.GetItem_FAT(PathAndFilename, item) then begin edFilename.Text := ExtractFilename(PathAndFilename); edFileType.Caption := SDUGetFileType_Description(PathAndFilename); edOpensWith.Caption := ''; edLocation.Caption := ExcludeTrailingPathDelimiter(ExtractFilePath(PathAndFilename)); if (edLocation.Caption = '') then begin // Don't strip off trailing "\" if it's just "\" edLocation.Caption := ExtractFilePath(PathAndFilename); end; edSize.Caption := SDUParamSubstitute( _('%1 (%2 bytes)'), [ SDUFormatAsBytesUnits(item.Size, 2), SDUIntToStrThousands(item.Size) ] ); edTimestampCreated.Caption := DateTimeToStr(TimeStampToDateTime(item.TimestampCreation)); edTimestampModified.Caption := DateTimeToStr(TimeStampToDateTime(item.TimestampLastModified)); edTimestampAccessed.Caption := DateToStr(item.DatestampLastAccess); ckReadOnly.Checked := item.IsReadonly; ckHidden.Checked := item.IsHidden; ckArchive.Checked := item.IsArchive; end; finally item.Free(); end; tmpIcon := TIcon.Create(); try SDUGetFileType_Icon(PathAndFilename, DLLFilename, DLLIconIdx); if (DLLFilename = '') then begin DLLFilename := DLL_SHELL32; DLLIconIdx := DLL_SHELL32_DEFAULT_FILE; end; if SDULoadDLLIcon(DLLFilename, FALSE, DLLIconIdx, tmpIcon) then begin imgFileType.Picture.Assign(tmpIcon) end; finally tmpIcon.Free(); end; end; procedure TfrmPropertiesDialog_File.pbOKClick(Sender: TObject); begin inherited; ModalResult := mrOK; end; END.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ***************************************************************** The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net and KadC library http://kadc.sourceforge.net/ ***************************************************************** } { Description: DHT dht parsing and serialization routines } unit dhtkeywords; interface uses classes,classes2,dhttypes,ares_types,class_cmdlist; procedure DHT_RepublishKeyFiles; procedure DHT_RepublishHashFiles; procedure DHT_clear_keywordsFiles; procedure DHT_clear_hashFilelist; procedure DHT_addFileOntheFly(pfile:precord_file_library); procedure DHT_keywordsFile_SetGlobal(sourceList:TMyList); procedure DHT_get_keywordsFromFile(pfile:precord_file_library; destinationList:tmylist); procedure DHT_extract_keywords(pfile:precord_file_library; list:tnapcmdlist; max:integer); function DHT_GetSerialized_PublishPayload(pfile:precord_file_library):string; function DHT_is_popularKeywords(const keyw:string):boolean; implementation uses vars_global,keywfunc,windows,sysutils,dhtconsts,helper_strings,helper_unicode, helper_urls,helper_mimetypes,const_ares; function DHT_is_popularKeywords(const keyw:string):boolean; begin result:=false; if keyw='the' then result:=true else if keyw='of' then result:=true else if keyw='and' then result:=true else if keyw='mp3' then result:=true else if keyw='mpg' then result:=true else if keyw='mpeg' then result:=true else if keyw='divx' then result:=true else if keyw='xvid' then result:=true else if keyw='vcd' then result:=true else if keyw='svcd' then result:=true else if keyw='track' then result:=true else if keyw='rip' then result:=true else if keyw='dvd' then result:=true else if keyw='cd' then result:=true else if keyw='full' then result:=true else if keyw='iso' then result:=true else if keyw='pc' then result:=true else if keyw='xp' then result:=true else if strtointdef(keyw,$ffffff)<>$ffffff then result:=true; end; function DHT_GetSerialized_PublishPayload(pfile:precord_file_library):string; var keywordstr,info,fname:string; list:TNapCmdList; len:byte; begin list:=TNapCmdList.create; keywordstr:=keywfunc.get_keywordsstr(list,pfile); list.free; fname:=widestrtoutf8str(extract_fnameW(utf8strtowidestr(pfile^.path))); info:=chr(length(pfile^.title))+ chr(TAG_ID_DHT_TITLE)+ pfile^.title+ chr(length(fname))+ chr(TAG_ID_DHT_FILENAME)+ fname; len:=length(pfile^.artist); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_ARTIST)+pfile^.artist; len:=length(pfile^.album); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_ALBUM)+pfile^.album; len:=length(pfile^.category); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_CATEGORY)+pfile^.category; len:=length(pfile^.language); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_LANGUAGE)+pfile^.language; len:=length(pfile^.year); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_DATE)+pfile^.year; len:=length(pfile^.comment); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_COMMENTS)+pfile^.comment; len:=length(pfile^.url); if len>1 then info:=info+chr(len)+chr(TAG_ID_DHT_URL)+pfile^.url; if pfile^.amime=1 then begin len:=length(pfile^.keywords_genre); if len >1 then info:=info+chr(len)+chr(TAG_ID_DHT_KEYWGENRE)+pfile^.keywords_genre; end; if pfile^.param2>0 then info:=info+chr(4)+chr(TAG_ID_DHT_PARAM2)+int_2_dword_string(pfile^.param2); result:=pfile^.hash_sha1+ keywordstr+ chr(helper_mimetypes.clienttype_to_shareservertype(pfile^.amime))+ int_2_Qword_string(pfile^.fsize)+ int_2_dword_string(pfile^.param1)+ int_2_dword_string(pfile^.param3)+ info; end; procedure DHT_extract_keywords(pfile:precord_file_library; list:tnapcmdlist; max:integer); var str:string; j:integer; begin j:=0; if length(pfile^.title)>1 then begin str:=utf8str_to_ascii(pfile^.title); splitToKeywords(str+' ',list,max-j,false); end; if ((j>=max) or (pfile^.amime=0)) then exit; if length(pfile^.artist)>1 then begin str:=utf8str_to_ascii(pfile^.artist); splitToKeywords(str+' ',list,max-j,false); end; if j>=max then exit; if ((pfile^.amime=1) or (pfile^.amime=7) or (pfile^.amime=3)) then begin //audio,image,exe if length(pfile^.album)>1 then begin str:=utf8str_to_ascii(pfile^.album); splitToKeywords(str+' ',list,max-j,false); end; end; end; procedure DHT_get_keywordsFromFile(pfile:precord_file_library; destinationList:tmylist); function DHT_FindKeyword(const keyword:string; crc:word):precord_DHT_keywordFilePublishReq; var i:integer; pkeyw:precord_DHT_keywordFilePublishReq; begin result:=nil; for i:=0 to destinationList.count-1 do begin pkeyw:=destinationList[i]; if pkeyw^.crc=crc then if pkeyw^.keyW=keyword then begin result:=pkeyw; exit; end; end; end; var pKeyw:precord_DHT_keywordFilePublishReq; list:tnapcmdlist; crc:word; keystr:string; begin list:=tnapcmdlist.create; DHT_extract_keywords(pfile,list,MAX_KEYWORDS); // m_DHT_KeywordFiles while (list.count>0) do begin keystr:=list.str(list.count-1); list.delete(list.count-1); crc:=whl(keystr); pkeyw:=DHT_FindKeyword(keystr,crc); if pkeyw<>nil then begin if pkeyw^.fileHashes.indexof(pfile^.hash_sha1)=-1 then pkeyw^.fileHashes.add(pfile^.hash_sha1); end else begin if DHT_is_popularKeywords(keystr) then continue; pkeyW:=AllocMem(sizeof(record_DHT_keywordFilePublishReq)); pkeyw^.keyW:=keystr; pkeyw^.crc:=crc; pkeyw^.fileHashes:=Tmystringlist.create; pkeyw^.fileHashes.add(pfile^.hash_sha1); destinationList.add(pkeyw); end; end; list.free; end; procedure DHT_RepublishHashFiles; var i:integer; pfile:precord_file_library; hashLst:TList; phash:precord_DHT_hashFile; begin DHT_LastPublishHashFiles:=gettickcount; hashLst:=DHT_hashFiles.locklist; // clear any remaining hash yet to be published while (hashlst.count>0) do begin phash:=hashlst[hashlst.count-1]; hashlst.delete(hashlst.count-1); FreeMem(phash,sizeof(record_DHT_hashFile)); end; try for i:=0 to vars_global.lista_shared.count-1 do begin pfile:=vars_global.lista_shared[i]; if not pfile^.shared then continue; if pfile^.previewing then continue; if length(pfile^.hash_sha1)<>20 then continue; if pfile^.amime=ARES_MIME_IMAGE then if pos(STR_ALBUMART,lowercase(pfile^.title))=0 then continue; // generate source hash record phash:=AllocMem(sizeof(record_DHT_hashfile)); move(pfile^.hash_sha1[1],phash^.HashValue[0],20); hashLst.add(phash); end; except end; DHT_hashFiles.Unlocklist; end; procedure DHT_RepublishKeyFiles; var i:integer; pfile:precord_file_library; kwdlst:tlist; pkeyw:precord_DHT_keywordFilePublishReq; TempList:tmylist; begin try if vars_global.threadDHT=nil then exit; except exit; end; DHT_LastPublishKeyFiles:=gettickcount; TempList:=tmylist.create; try for i:=0 to vars_global.lista_shared.count-1 do begin pfile:=vars_global.lista_shared[i]; if not pfile^.shared then continue; if pfile^.previewing then continue; if length(pfile^.hash_sha1)<>20 then continue; if pfile^.amime=ARES_MIME_IMAGE then if pos(STR_ALBUMART,lowercase(pfile^.title))=0 then continue; dhtkeywords.DHT_get_keywordsFromFile(pfile,TempList); // extract keywords (very expensive especially here in main thread) end; kwdlst:=DHT_KeywordFiles.Locklist; // send them to DHT thread // clear old list if anything remains here...should definitely not be the case // unless it's something added right after download while (kwdlst.count>0) do begin pkeyw:=kwdlst[kwdlst.count-1]; kwdlst.delete(kwdlst.count-1); pkeyw^.keyW:=''; pkeyw^.fileHashes.free; FreeMem(pkeyw,sizeof(record_DHT_keywordFilePublishReq)); end; // copy our fresh keywords to be published while (TempList.count>0) do begin pkeyw:=TempList[TempList.count-1]; TempList.delete(TempList.count-1); kwdlst.add(pkeyw); end; DHT_KeywordFiles.Unlocklist; except end; TempList.free; end; // file download completed! publish it on DHT procedure DHT_addFileOntheFly(pfile:precord_file_library); var hashLst:Tlist; phash:precord_DHT_hashFile; kwdlst:tlist; pkeyw:precord_DHT_keywordFilePublishReq; TempList:tmylist; begin if vars_global.threadDHT=nil then exit; // generate source hash record phash:=AllocMem(sizeof(record_DHT_hashfile)); move(pfile^.hash_sha1[1],phash^.HashValue[0],20); hashLst:=DHT_hashFiles.locklist; hashLst.add(phash); DHT_hashFiles.Unlocklist; TempList:=tmylist.create; dhtkeywords.DHT_get_keywordsFromFile(pfile,TempList); // extract keywords kwdlst:=DHT_KeywordFiles.Locklist; // send them to DHT thread while (TempList.count>0) do begin pkeyw:=TempList[TempList.count-1]; TempList.delete(TempList.count-1); kwdlst.add(pkeyw); end; DHT_KeywordFiles.Unlocklist; TempList.free; end; procedure DHT_clear_keywordsFiles; var kwdlst:tlist; pkeyw:precord_DHT_keywordFilePublishReq; begin kwdlst:=DHT_KeywordFiles.Locklist; try while (kwdlst.count>0) do begin pkeyw:=kwdlst[kwdlst.count-1]; kwdlst.delete(kwdlst.count-1); pkeyw^.keyW:=''; pkeyw^.fileHashes.free; FreeMem(pkeyw,sizeof(record_DHT_keywordFilePublishReq)); end; except end; DHT_KeywordFiles.Unlocklist; end; procedure DHT_keywordsFile_SetGlobal(sourceList:TMyList); var kwdlst:tlist; pkeyw:precord_DHT_keywordFilePublishReq; begin kwdlst:=DHT_KeywordFiles.Locklist; try while (sourceList.count>0) do begin pkeyw:=sourceList[sourceList.count-1]; sourceList.delete(sourceList.count-1); kwdlst.add(pkeyw); end; except end; DHT_KeywordFiles.UnLocklist; end; procedure DHT_clear_hashFilelist; var hashLst:Tlist; phash:precord_DHT_hashFile; begin hashLst:=DHT_hashFiles.Locklist; try while (hashlst.count>0) do begin phash:=hashlst[hashlst.count-1]; hashlst.delete(hashlst.count-1); FreeMem(phash,sizeof(record_DHT_hashFile)); end; except end; DHT_hashFiles.UnLocklist; end; end.
unit helper.field; interface uses Data.DB, FMX.Forms, FMX.StdCtrls, FMX.Objects; type TFieldHelper = class helper for TField function AsNumFormatado: string; end; implementation uses System.SysUtils; function TFieldHelper.AsNumFormatado: string; begin if Self.AsString.Trim.IsEmpty then Result := '' else begin try if Frac(Self.AsFloat) = 0.00 then Result := FormatFloat(',#0', Self.AsFloat) else Result:= FormatFloat(',#0.00', Self.AsFloat); except Result := Self.AsString; end; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Grids, StringGridExt, DragDrop, DropTarget, DragDropFile, ComCtrls, StrUtils, Dlgs, Commdlg; type TForm1 = class(TForm) OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; StringGridExt1: TStringGridExt; Edit1: TEdit; BitBtn1: TBitBtn; BitBtn2: TBitBtn; DropFileTarget1: TDropFileTarget; CheckBox1: TCheckBox; procedure DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); procedure BitBtn1Click(Sender: TObject); procedure LoadFile; procedure LoadStringList(xFileName: string); function CheckFileFormat(xFileName: string): Boolean; procedure LoadStringGrid; procedure SaveStringGrid; procedure strtok; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); {トークン抽出} private { Private 宣言 } xInFileName: string; LibFileName: string; CSVFileName: string; LibStringList: TStringList; CSVStringList: TStringList; //---CSV processing--- xtext: string; {対象文字列格納エリア} tokns: string; {区切り文字(列)} stokns: string; {ペア内を無視する時に指定する区切り文字(列)} strflg: Boolean; {指定文字のペアの内の区切り文字は無視} blockflg: Boolean; {区切り文字の連続をまとまりで見る} xitems: TStringList; {抽出された項目が格納されるエリア} //--- public { Public 宣言 } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then begin StringGridExt1.Options := StringGridExt1.Options + [goEditing]; end else begin StringGridExt1.Options := StringGridExt1.Options - [goEditing]; end; end; function TForm1.CheckFileFormat(xFileName: string): Boolean; var xFile: TextFile; xLine: string; xLibString: string; begin Result := False; AssignFile(xFile, xFileName); Reset(xFile); Readln(xFile, xLine); xLibString := Copy(xLine, 1, 16); if xLibString <> 'EESchema-LIBRARY' then begin Result := True; end; CloseFile(xFile); end; procedure TForm1.LoadFile; var xErr: Boolean; xExt: string; begin xExt := ExtractFileExt(xInFileName); if (xExt <> '.lib') and (xExt <> '.csv') then begin xErr := True; end else begin xErr := CheckFileFormat(xInFileName); if xExt = '.lib' then begin LibFileName := xInFileName; end; if xExt = '.csv' then begin CSVFileName := xInFileName; end; end; if xErr then begin ShowMessage('Bad File Format.'); xInFileName := ''; end else begin LoadStringList(xInFileName); end; Edit1.Text := xInFileName; end; procedure TForm1.LoadStringList(xFileName: string); var xExt: string; xFile: TextFile; xLine: string; strOld: string; strNew: string; yLine: string; begin LibStringList.Clear; CSVStringList.Clear; xExt := ExtractFileExt(xFileName); if xExt = '.lib' then begin AssignFile(xFile, xFileName); Reset(xFile); while not Eof(xFile) do begin Readln(xFile, xLine); LibStringList.Add(xLine); strOld := ' '; strNew := ','; yLine := AnsiReplaceStr(xLine, strOld, strNew); CSVStringList.Add(yLine); end; CloseFile(xFile); end; if xExt = '.csv' then begin AssignFile(xFile, xFileName); Reset(xFile); while not Eof(xFile) do begin Readln(xFile, xLine); CSVStringList.Add(xLine); strOld := ','; strNew := ' '; yLine := AnsiReplaceStr(xLine, strOld, strNew); yLine := TrimRight(yLine); LibStringList.Add(yLine); end; CloseFile(xFile); end; end; procedure TForm1.LoadStringGrid; var i, j: Integer; xColCount: Integer; begin xColCount := 1; for j := 0 to StringGridExt1.RowCount - 1 do begin for i := 0 to StringGridExt1.ColCount - 1 do begin StringGridExt1.Cells[i, j] := ''; end; end; StringGridExt1.RowCount := CSVStringList.Count; for j := 0 to StringGridExt1.RowCount - 1 do begin xtext := CSVStringList.Strings[j]; strtok; if xColCount < xitems.Count then begin xColCount := xitems.Count; end; if xitems.Count > 0 then begin for i := 0 to xitems.Count - 1 do begin StringGridExt1.Cells[i, j] := xitems[i]; end; end; end; StringGridExt1.ColCount := xColCount; end; procedure TForm1.SaveStringGrid; var xLine, yLine: string; xDQoat: Boolean; i, j: Integer; begin xDQoat := False; for j := 0 to StringGridExt1.RowCount - 1 do begin xLine := ''; yLine := ''; for i := 0 to StringGridExt1.ColCount - 2 do begin if j > 0 then begin if StringGridExt1.Cells[0, j-1] = 'DEF' then begin xDQoat := True; end; if copy(StringGridExt1.Cells[0, j], 0, 1) <> 'F' then begin xDQoat := False; end; end; if xDQoat and (i = 1) and (copy(StringGridExt1.Cells[i, j], 0, 1) <> '"') then begin xLine := xLine + '"' + StringGridExt1.Cells[i, j] + '"' + ','; yLine := yLine + '"' + StringGridExt1.Cells[i, j] + '"' + ' '; end else begin xLine := xLine + StringGridExt1.Cells[i, j] + ','; yLine := yLine + StringGridExt1.Cells[i, j] + ' '; end; end; xLine := xLine + StringGridExt1.Cells[StringGridExt1.ColCount - 1, j]; CSVStringList.Strings[j] := xLine; yLine := yLine + StringGridExt1.Cells[StringGridExt1.ColCount - 1, j]; yLine := TrimRight(yLine); LibStringList.Strings[j] := yLine; end; end; procedure TForm1.strtok; var xStart: integer; xStop: integer; xLetter: string; work: string; max: integer; flag: boolean; begin xStart := 1; {抽出中の項目の先頭} xStop := 1; {抽出中の項目の終わり} flag := false; {非分割処理は初めは開始していない} max := length(xtext); xitems.clear; {項目消去} if xtext='' then {対象文字列が何もなかったら何もしない} begin exit; end; while xStop <= max do begin xLetter := copy(xtext, xStop, 1); {1文字抜き取る} {非分割文字の処理} if pos(xLetter, stokns) <> 0 then {非分割区切り文字} begin if strflg then begin if flag then {非分割処理中} begin flag := False {非分割処理終了} end else begin flag := True; {非分割処理開始} end; end; inc(xStop); continue; end; {区切り文字の処理} if pos(xLetter, tokns) <> 0 then {区切り文字} begin if strflg and flag then {非分割処理中} begin // {何もしない} end else begin work:=copy(xtext, xStart, xStop-xStart); xitems.add(work); if blockflg then begin {区切り文字が連続している場合,ひと固まりで取り扱う用に次の区切り文字までパスする} inc(xStop); while xStop <= max do begin xLetter := copy(xtext, xStop, 1); {1文字抜き取る} if pos(xLetter, tokns) <> 0 then {区切り文字} begin inc(xStop); end else begin dec(xStop); break; end; end; end; xStart := xStop + 1; {開始位置を最後の項目の次に設定} if xStop >= max then begin xitems.add(''); {トークンで終了していれば空データを登録} end; end; end; inc(xStop); end; {最後の項目の登録処理} if xStart <> xStop then begin work := copy(xtext, xStart, xStop-xStart); xitems.add(work); end; end; procedure TForm1.FormCreate(Sender: TObject); begin LibStringList:=TStringList.Create; CSVStringList:=TStringList.Create; xitems := TStringList.Create; tokns := ','; {デフォルトのトークン} stokns := '"'; {デフォルトの文字列認識トークン} strflg := True; {文字列処理を行う} blockflg := False; {区切り文字を個別に見る} end; procedure TForm1.FormShow(Sender: TObject); begin xInFileName := ''; LibFileName := ''; CSVFileName := ''; end; procedure TForm1.FormDestroy(Sender: TObject); begin LibStringList.Free; CSVStringList.Free; xitems.Free; end; procedure TForm1.BitBtn1Click(Sender: TObject); begin if OpenDialog1.Execute then begin xInFileName := OpenDialog1.FileName; LoadFile; LoadStringGrid; end; end; procedure TForm1.BitBtn2Click(Sender: TObject); var xExt: string; xFileName: string; begin SaveDialog1.FileName := ChangeFileExt(ExtractFileName(Edit1.Text),''); if SaveDialog1.Execute then begin SaveStringGrid; xFileName := SaveDialog1.FileName; xExt := ExtractFileExt(SaveDialog1.FileName); if xExt = '' then begin case SaveDialog1.FilterIndex of 1: xExt := '.lib'; 2: xExt := '.csv'; end; xFileName := xFileName + xExt; end; if xExt = '.lib' then begin LibStringList.SaveToFile(xFileName); end; if xExt = '.csv' then begin CSVStringList.SaveToFile(xFileName); end; end; end; procedure TForm1.DropFileTarget1Drop(Sender: TObject; ShiftState: TShiftState; APoint: TPoint; var Effect: Integer); var xCount : Integer; begin xCount := DropFileTarget1.Files.Count; if xCount <> 1 then begin ShowMessage('Please drop one file only.'); end else begin xInFileName := DropFileTarget1.Files[0]; LoadFile; LoadStringGrid; end; end; end.
Program FLB; Uses DOS; Const { Attribut de fichier Dos } fa=$FFE7; { Attribut de tous fichier, sauf r‚pertoire et volume. } faReadOnly=1; { Lecture seulement } faHidden=2; { Cach‚ } faSysFile=4; { SystŠme } faVolumeID=8; { Volume } faDir=$10; { R‚pertoire } faArchive=$20; { Archive } faAnyFile=$3F; { N'importe qu'elle fichier } faAll=$FFF7; { Tous les fichiers sans exception } { Mode fichier d'accŠs d'un fichier } fmRead=0; { Lecture seulement } fmWrite=1; { Ecriture seulement } fmDef=2; { Lecture et ‚criture } errHdl=$FF; Type FLBEntry=Record Data1:Array[0..5]of Byte; { Donn‚es r‚serv‚??? Possiblement 3 mots... } PosAbs:LongInt; { Position absolue dans le fichier de l'image} { suivit par la police (256+SizeImg). Dans la} { partie de taille de 256 caractŠres, il } { contient une table de 128 mots contenant} { des adresses de chacun des 128 caractŠres} { contenu dans cette police.} Name:Array[0..49]of Char; { Nom de la police de caractŠre } SizeImg:Word; { Taille de l'image } Data2:Array[62..75]of Byte; { Donn‚es r‚serv‚??? } Height:Word; { Hauteur des caractŠres } Data3:Word; { Donn‚es r‚serv‚??? } End; Type Hdl=Byte; Var SysErr:Word; Path:String; K,I,J:Byte;X,Y,TY,Jmp,P,LengthObject,LB,Height:Word; Entry:FLBEntry; Buffer:Array[0..32767]of Byte; Handle,Target:Hdl; Year:Word;Month,Day,DayOfWeek:Byte;LP:Char; {Cette proc‚dure rajoute le caractŠre d‚finit par la variable de param‚trage ®Chr¯ … la chaŒne de caractŠres sp‚cifier par la variable de param‚trage ®S¯. } Procedure IncStr(Var S:String;Chr:Char);Assembler;ASM LES BX,S INC Byte Ptr ES:[BX] ADD BL,ES:[BX] ADC BH,0 MOV AL,Chr MOV ES:[BX],AL END; {Cette fonction ouvre un fichier par la technique des fichiers Handle du systŠme d'exploitation DOS ou compatible et retourne son code lui ‚tant attribu‚. } Function FileOpen(Name:String;Mode:Byte):Hdl; Var SegName,OfsName,I:Word; Begin IncStr(Name,#0); SegName:=Seg(Name[1]); OfsName:=Ofs(Name[1]); ASM MOV AX,3D40h OR AL,Mode PUSH DS MOV DX,OfsName MOV DS,SegName INT 21h POP DS JC @1 XOR BX,BX JMP @2 @1:MOV BX,AX MOV AL,errHdl @2:MOV SysErr,BX MOV @Result,AL END; End; Function FileCreate(Name:String;Attr:Word):Hdl;Assembler;ASM PUSH DS MOV CX,Attr LDS DI,Name MOV BL,DS:[DI] INC DI{Set Name[1]} MOV BH,0 MOV DS:[DI+BX],BH{Name:=Name+#0} MOV DX,DI MOV AH,03Ch INT 021h POP DS JC @1 XOR BX,BX JMP @2 @1:MOV BX,AX MOV AX,errHdl @2:MOV SysErr,BX END; { Cette fonction retourne le r‚pertoire courant du systŠme d'exploitation DOS ou compatible. } Function GetCurrentDir:String; Var Path:String; Begin GetDir(0,Path); GetCurrentDir:=Path End; { Cette fonction retourne un chemin de r‚pertoire de fa‡on … ce qu'il est toujours une barre oblique pour permettre l'addition d'un nom de fichier. } Function SetPath4AddFile(Path:String):String;Begin If Path=''Then Path:=GetCurrentDir; If Path[Length(Path)]<>'\'Then IncStr(Path,'\'); SetPath4AddFile:=Path; End; Function Path2NoExt(Const Path:String):String; Var D:DirStr; N:NameStr; E:ExtStr; Begin FSplit(Path,D,N,E); Path2NoExt:=SetPath4AddFile(D)+N End; BEGIN WriteLn('FLB … RC - D‚compilation de bibliothŠque de polices Version 1.0'); WriteLn(' Tous droits r‚serv‚s par les Chevaliers de Malte'); WriteLn; Path:='\NEWS\NEWS.FLB'; Handle:=FileOpen(Path,fmRead);LP:='A'; If(Handle=errHdl)Then Begin WriteLn('Fichier introuvable!'); Halt(1) End; Target:=FileCreate(Path2NoExt(Path)+LP+'.RC',faArchive); If(Target=errHdl)Then Begin WriteLn('Erreur de cr‚ation de fichier'); Halt(2) End; PutFileTxtLn(Target,'// Source: '+Path); PutFileTxtLn(Target,'// Destination: '+Path2NoExt(Path)+'.RC'); GetDate(Year,Month,Day,DayOfWeek); PutFileTxtLn(Target,'// Date de cr‚ation: '+_CStrDate(Year,Month,Day,DayOfWeek)); PutFileLn(Target); PutFileTxtLn(Target,'NumberIndex=34'); PutFileTxtLn(Target,'FontLibrary=Yes'); For P:=0to 33do Begin If FileSize(Target)>131072Then Begin FileClose(Target); Inc(LP); Target:=FileCreate(Path2NoExt(Path)+LP+'.RC',faArchive); If(Target=errHdl)Then Begin;WriteLn('Erreur de cr‚ation de fichier');Halt(2)End; End; PutFileLn(Target); GetRec(Handle,P,SizeOf(Entry),Entry); WriteLn('Police #',P,' nomm‚ ®',StrPas(@Entry.Name),'¯'); PutFileTxtLn(Target,'Name="'+StrPas(@Entry.Name)+'"'); PutFileTxtLn(Target,'Height='+WordToStr(Entry.Height)); PutFileTxtLn(Target,'ImageBin '+WordToStr(P)); _GetAbsRec(Handle,Entry.PosAbs,SizeOf(Buffer),Buffer); LengthObject:=Buffer[0]+(Buffer[1]shl 8);Height:=Buffer[2]; PutFileTxtLn(Target,' Size: '+WordToStr(LengthObject)+','+WordToStr(Height)); Jmp:=4; For J:=0to Height-1do Begin For I:=0to((LengthObject or 7)shr 3)-1do Begin If I=0Then PutFileTxt(Target,' Bin:'); PutFileTxt(Target,BinByte2Str(Buffer[Jmp])); If I<((LengthObject or 7)shr 3)-1Then PutFileTxt(Target,','); Inc(Jmp); End; PutFileLn(Target); End; PutFileTxtLn(Target,'End'); PutFileLn(Target); _GetAbsRec(Handle,Entry.PosAbs+Entry.SizeImg,SizeOf(Buffer),Buffer); For K:=0to 127do Begin Jmp:=Buffer[K shl 1]+(Buffer[(K shl 1)+1]shl 8); If Jmp<>$FFFFThen Begin If K in[32..126]Then PutFileTxtLn(Target,'Matrix '+WordToStr(K)+' // '+Chr(K)) Else PutFileTxtLn(Target,'Matrix '+WordToStr(K)); LengthObject:=Buffer[256+Jmp+1];Height:=Buffer[256+Jmp+3]; TY:=Entry.Height-Buffer[256+Jmp+2]; PutFileTxtLn(Target,' Size: '+WordToStr(LengthObject)+','+WordToStr(Height)+':'+WordToStr(TY)); Inc(Jmp,256+4); For J:=0to Height-1do Begin LB:=LengthObject; If LB<8Then LB:=0 Else Begin If LB and 7<>7Then Inc(LB); LB:=LB shr 3; End; For I:=0to(LB)do Begin If I=0Then PutFileTxt(Target,' Bin:'); PutFileTxt(Target,BinByte2Str(Buffer[Jmp])); If(I<LB)Then PutFileTxt(Target,','); Inc(Jmp); End; PutFileLn(Target); End; PutFileTxtLn(Target,'End'); PutFileLn(Target); End; End; End; FileClose(Target); FileClose(Handle); END.
unit HJYFactoryIntfObjects; interface Uses Classes, SysUtils, HJYFactoryIntfs; Type TIntfCreatorFunc = procedure(out anInstance: IInterface); // 工厂基类 TBaseFactory = Class(THJYFactory) private FIntfGUID: TGUID; public constructor Create(const IID: TGUID); destructor Destroy; override; function Supports(IID: TGUID): Boolean; override; procedure EnumKeys(Intf: IEnumKey); override; end; // 接口工厂 TInterfaceFactory = Class(TBaseFactory) private FIntfCreatorFunc: TIntfCreatorFunc; public constructor Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); virtual; destructor Destroy; override; procedure CreateInstance(const IID: TGUID; out Obj); override; procedure ReleaseInstance; override; end; // 单例工厂 TSingletonFactory = Class(TInterfaceFactory) private FInstance: IInterface; public constructor Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); override; destructor Destroy; override; procedure CreateInstance(const IID: TGUID; out Obj); override; procedure ReleaseInstance; override; end; // 实例工厂 TObjectFactory = Class(TBaseFactory) private FOwnsObj: Boolean; FInstance: TObject; FRefIntf: IInterface; public constructor Create(IID: TGUID; Instance: TObject; OwnsObj: Boolean = False); destructor Destroy; override; procedure CreateInstance(const IID: TGUID; out Obj); override; procedure ReleaseInstance; override; end; implementation uses HJYFactoryManagers, HJYMessages; { TBaseFactory } constructor TBaseFactory.Create(const IID: TGUID); begin if FactoryManager.Exists(IID) then raise Exception.CreateFmt(Err_IntfExists, [GUIDToString(IID)]); FIntfGUID := IID; FactoryManager.RegisterFactory(Self); end; destructor TBaseFactory.Destroy; begin FactoryManager.UnRegisterFactory(Self); inherited; end; procedure TBaseFactory.EnumKeys(Intf: IEnumKey); begin if Assigned(Intf) then Intf.EnumKey(GUIDToString(FIntfGUID)); end; function TBaseFactory.Supports(IID: TGUID): Boolean; begin Result := IsEqualGUID(IID, FIntfGUID); end; { TIntfaceFactory } constructor TInterfaceFactory.Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); begin Self.FIntfCreatorFunc := IntfCreatorFunc; Inherited Create(IID); end; procedure TInterfaceFactory.CreateInstance(const IID: TGUID; out Obj); var tmpIntf: IInterface; begin Self.FIntfCreatorFunc(tmpIntf); tmpIntf.QueryInterface(IID, Obj); end; destructor TInterfaceFactory.Destroy; begin inherited; end; procedure TInterfaceFactory.ReleaseInstance; begin end; { TSingletonFactory } constructor TSingletonFactory.Create(IID: TGUID; IntfCreatorFunc: TIntfCreatorFunc); begin FInstance := nil; inherited Create(IID, IntfCreatorFunc); end; procedure TSingletonFactory.CreateInstance(const IID: TGUID; out Obj); begin if FInstance = nil then inherited CreateInstance(IID, FInstance); if FInstance.QueryInterface(IID, Obj) <> S_OK then raise Exception.CreateFmt(Err_IntfNotSupport, [GUIDToString(IID)]); end; destructor TSingletonFactory.Destroy; begin inherited; end; procedure TSingletonFactory.ReleaseInstance; var Obj: TComponent; RefIntf: IInterfaceComponentReference; begin if FInstance <> nil then begin if FInstance.QueryInterface(IInterfaceComponentReference, RefIntf) = S_OK then begin Obj := RefIntf.GetComponent; Obj.Free; end; FInstance := nil; end; end; { TObjectFactory } constructor TObjectFactory.Create(IID: TGUID; Instance: TObject; OwnsObj: Boolean); begin if not Instance.GetInterface(IID, FRefIntf) then raise Exception.CreateFmt(Err_ObjNotImpIntf, [Instance.ClassName, GUIDToString(IID)]); if (Instance is TInterfacedObject) then raise Exception.Create(Err_DontUseTInterfacedObject); FOwnsObj := OwnsObj; FInstance := Instance; inherited Create(IID); end; procedure TObjectFactory.CreateInstance(const IID: TGUID; out Obj); begin IInterface(Obj) := FRefIntf; end; destructor TObjectFactory.Destroy; begin inherited; end; procedure TObjectFactory.ReleaseInstance; begin inherited; FRefIntf := nil; if FOwnsObj then FreeAndNil(FInstance); end; end.
unit Grijjy.SymbolTranslator; interface { Tries to translate a C++ symbol name (such as a function signature) to Pascal. Parameters: ASymbol: the C++ symbol to translate. Returns: The symbol translated to Pascal. The returned string is only an approximate translation. This function cannot translate all C++ constructs, so parts of the returned string may be untranslated. However, the result is good enough to be able to look it up in you Pascal source code. } function goCppSymbolToPascal(const ASymbol: String): String; implementation uses System.SysUtils, System.Generics.Collections; type TgoSymbolConverter = class // static private class var FTypeMap: TDictionary<String, String>; FOperatorMap: TDictionary<String, String>; private class function ParseFunctionHeading(var AStr: PChar): String; static; class function ParseQualifiedName(var AStr: PChar): String; overload; static; inline; class function ParseQualifiedName(var AStr: PChar; out AInSystem: Boolean): String; overload; static; class function ParseName(var AStr: PChar): String; static; class function ParseParams(var AStr: PChar): String; static; class function ParseParam(var AStr: PChar): String; static; class function ParseGenericArgs(var AStr: PChar): String; static; class function ParseGenericArg(var AStr: PChar): String; static; class function ParseRemainder(var AStr: PChar): String; static; class procedure SkipWhitespace(var AStr: PChar); static; inline; class function ConvertOperatorName(const AName: String): String; static; class function ConvertStaticArray(const AStr: String): String; static; class function ConvertSet(const AStr: String): String; static; class function ConvertCtorDtor(const AStr: String): String; static; class function ConvertSpecialFunctionName(const AStr: String): String; static; public class constructor Create; class destructor Destroy; public class function CppToPascal(const ASymbol: String): String; static; end; function goCppSymbolToPascal(const ASymbol: String): String; begin Result := TgoSymbolConverter.CppToPascal(ASymbol); end; { TgoSymbolConverter } class function TgoSymbolConverter.ConvertCtorDtor(const AStr: String): String; { Convert constructor and destructor. * Foo.TBar.TBar -> Foo.TBar.Create * Foo.TBar.~TBar -> Foo.TBar.Destroy } var I: Integer; TypeName: String; begin I := AStr.LastIndexOf('.'); if (I < 0) then Exit(AStr); if (I < (AStr.Length - 1)) and (AStr.Chars[I + 1] = '~') then Result := AStr.Substring(0, I) + '.Destroy' else begin TypeName := AStr.Substring(I); Result := AStr.Substring(0, I); if (Result.EndsWith(TypeName)) then Result := Result + '.Create' else Result := AStr; end; end; class function TgoSymbolConverter.ConvertOperatorName( const AName: String): String; begin if (not FOperatorMap.TryGetValue(AName, Result)) then Result := AName; end; class function TgoSymbolConverter.ConvertSet(const AStr: String): String; { Set<XYZ, ...> -> set of XYZ } var I: Integer; begin I := AStr.IndexOf(','); if (I < 0) then Result := AStr else Result := 'set of ' + AStr.Substring(4, I - 4); end; class function TgoSymbolConverter.ConvertSpecialFunctionName( const AStr: String): String; { Convert constructor and destructor. * Foo.Finalization() -> Foo.finalization } begin if (AStr.EndsWith('initialization()')) then Result := AStr.Substring(0, AStr.Length - 16) + 'initialization' else if (AStr.EndsWith('Finalization()')) then Result := AStr.Substring(0, AStr.Length - 14) + 'finalization' else Result := AStr; end; class function TgoSymbolConverter.ConvertStaticArray( const AStr: String): String; { StaticArray<XYZ, N> -> array [0..N-1] of XYZ } var CommaPos, N: Integer; begin CommaPos := AStr.IndexOf(','); if (CommaPos < 0) then Exit(AStr); N := StrToIntDef(AStr.Substring(CommaPos + 1, AStr.Length - CommaPos - 2), 0); if (N = 0) then Exit(AStr); Result := 'array [0..' + IntToStr(N - 1) + '] of ' + AStr.Substring(12, CommaPos - 12); end; class function TgoSymbolConverter.CppToPascal(const ASymbol: String): String; { Symbol -> FunctionHeading ('::' FunctionHeading)* This allows for nested routines. For example: Foo(int)::Bar(float) Translates to Foo(Integer).Bar(Single) Where Bar is a nested routine inside the Foo routine. } var P: PChar; begin P := PChar(ASymbol); if (P^ = #0) then Exit(''); Result := ParseFunctionHeading(P); while (P[0] = ':') and (P[1] = ':') do begin Inc(P, 2); Result := Result + '.' + ParseFunctionHeading(P); end; end; class constructor TgoSymbolConverter.Create; begin FTypeMap := TDictionary<String, String>.Create; { C++ types } FTypeMap.Add('bool', 'Boolean'); FTypeMap.Add('signed char', 'ShortInt'); FTypeMap.Add('unsigned char', 'Byte'); FTypeMap.Add('char', 'Byte'); FTypeMap.Add('wchar_t', 'Char'); FTypeMap.Add('char16_t', 'Char'); FTypeMap.Add('char32_t', 'UCS4Char'); FTypeMap.Add('short', 'SmallInt'); FTypeMap.Add('short int', 'SmallInt'); FTypeMap.Add('signed short', 'SmallInt'); FTypeMap.Add('signed short int', 'SmallInt'); FTypeMap.Add('unsigned short', 'Word'); FTypeMap.Add('unsigned short int', 'Word'); FTypeMap.Add('int', 'Integer'); FTypeMap.Add('signed', 'Integer'); FTypeMap.Add('signed int', 'Integer'); FTypeMap.Add('unsigned', 'Cardinal'); FTypeMap.Add('unsigned int', 'Cardinal'); FTypeMap.Add('long', 'LongInt'); FTypeMap.Add('long int', 'LongInt'); FTypeMap.Add('signed long', 'LongInt'); FTypeMap.Add('signed long int', 'LongInt'); FTypeMap.Add('unsigned long', 'LongWord'); FTypeMap.Add('unsigned long int', 'LongWord'); FTypeMap.Add('long long', 'Int64'); FTypeMap.Add('long long int', 'Int64'); FTypeMap.Add('signed long long', 'Int64'); FTypeMap.Add('signed long long int', 'Int64'); FTypeMap.Add('unsigned long long', 'UInt64'); FTypeMap.Add('unsigned long long int', 'UInt64'); FTypeMap.Add('float', 'Single'); FTypeMap.Add('double', 'Double'); FTypeMap.Add('long double', 'Extended'); { Delphi types } FTypeMap.Add('UnicodeString', 'String'); FOperatorMap := TDictionary<String, String>.Create; FOperatorMap.Add('_op_Implicit', 'operator_Implicit'); FOperatorMap.Add('_op_Explicit', 'operator_Explicit'); FOperatorMap.Add('_op_UnaryNegation', 'operator_Negative'); FOperatorMap.Add('_op_UnaryPlus', 'operator_Positive'); FOperatorMap.Add('_op_Increment', 'operator_Inc'); FOperatorMap.Add('_op_Decrement', 'operator_Dec'); FOperatorMap.Add('_op_LogicalNot', 'operator_LogicalNot'); FOperatorMap.Add('_op_Trunc', 'operator_Trunc'); FOperatorMap.Add('_op_Round', 'operator_Round'); FOperatorMap.Add('_op_In', 'operator_In'); FOperatorMap.Add('_op_Equality', 'operator_Equal'); FOperatorMap.Add('_op_Inequality', 'operator_NotEqual'); FOperatorMap.Add('_op_GreaterThan', 'operator_GreaterThan'); FOperatorMap.Add('_op_GreaterThanOrEqual', 'operator_GreaterThanOrEqual'); FOperatorMap.Add('_op_LessThan', 'operator_LessThan'); FOperatorMap.Add('_op_LessThanOrEqual', 'operator_LessThanOrEqual'); FOperatorMap.Add('_op_Addition', 'operator_Add'); FOperatorMap.Add('_op_Subtraction', 'operator_Subtract'); FOperatorMap.Add('_op_Multiply', 'operator_Multiply'); FOperatorMap.Add('_op_Division', 'operator_Divide'); FOperatorMap.Add('_op_IntDivide', 'operator_IntDivide'); FOperatorMap.Add('_op_Modulus', 'operator_Modulus'); FOperatorMap.Add('_op_LeftShift', 'operator_LeftShift'); FOperatorMap.Add('_op_RightShift', 'operator_RightShift'); FOperatorMap.Add('_op_LogicalAnd', 'operator_LogicalAnd'); FOperatorMap.Add('_op_LogicalOr', 'operator_LogicalOr'); FOperatorMap.Add('_op_ExclusiveOr', 'operator_LogicalXor'); FOperatorMap.Add('_op_BitwiseAnd', 'operator_BitwiseAnd'); FOperatorMap.Add('_op_BitwiseOr', 'operator_BitwiseOr'); FOperatorMap.Add('_op_BitwiseXOR', 'operator_BitwiseXor'); end; class destructor TgoSymbolConverter.Destroy; begin FTypeMap.Free; FOperatorMap.Free; end; class function TgoSymbolConverter.ParseFunctionHeading(var AStr: PChar): String; { FunctionHeading -> QualifiedName '(' Params ')' } begin Result := ParseQualifiedName(AStr); Result := ConvertCtorDtor(Result); if (AStr^ <> '(') then Exit(Result + ParseRemainder(AStr)); Inc(AStr); Result := Result + '(' + ParseParams(AStr); if (AStr^ <> ')') then Result := Result + ParseRemainder(AStr) else begin Inc(AStr); Result := Result + ')'; end; Result := ConvertSpecialFunctionName(Result); end; class function TgoSymbolConverter.ParseGenericArg(var AStr: PChar): String; { GenericArg -> ['(' QualifiedName ')'] Param The QualifiedName can be used in typecasts inside generic arguments, as in: (Foo::Bar)0 } begin if (AStr^ = '(') then begin Inc(AStr); Result := ParseQualifiedName(AStr); { Ignore the typecast } if (AStr^ = ')') then Inc(AStr) else Exit(Result + ParseRemainder(AStr)); end; Result := ParseParam(AStr); end; class function TgoSymbolConverter.ParseGenericArgs(var AStr: PChar): String; { GenericArgs -> GenericArg (',' GenericArg)* } begin Result := ParseGenericArg(AStr); while (AStr^ = ',') do begin Inc(AStr); SkipWhitespace(AStr); Result := Result + ', ' + ParseGenericArg(AStr); end; end; class function TgoSymbolConverter.ParseName(var AStr: PChar): String; { Name -> NameChar+ ['<' GenericArgs '>'] NameChar -> <any character except some delimiters> } var P: PChar; I, J: Integer; begin P := AStr; while True do begin case P^ of #0..#32, '<', '>', '(', ')', ',', ':': Break; else Inc(P); end; end; SetString(Result, AStr, P - AStr); { Rename class operators } if (AStr[0] = '_') and (AStr[1] = 'o') and (AStr[2] = 'p') and (AStr[3] = '_') then Result := ConvertOperatorName(Result); AStr := P; if (AStr^ = '<') then begin { When using generic arguments, the name may end with a discriminator, like "__1". Strip this. } I := Result.IndexOf('__'); if (I > 0) then begin J := I + 2; while (J < Result.Length) and (Result.Chars[J] >= '0') and (Result.Chars[J] <= '9') do Inc(J); if (J = Result.Length) then Result := Result.Substring(0, I); end; Inc(AStr); Result := Result + '<' + ParseGenericArgs(AStr); SkipWhitespace(AStr); if (AStr^ <> '>') then Result := Result + ParseRemainder(AStr) else begin Inc(AStr); Result := Result + '>'; end; end; end; class function TgoSymbolConverter.ParseParam(var AStr: PChar): String; { Param -> QualifiedName+ A parameter can take multiple names in these cases: * The C++ type takes multiple names, like 'signed char' or 'unsigned long long'. * The parameter has qualifiers, like 'const&' } var CppName, Name, Suffix: String; InSystem, IsReference: Boolean; I: Integer; begin CppName := ParseQualifiedName(AStr, InSystem); while (AStr^ <> #0) and (AStr^ <= ' ') do begin SkipWhitespace(AStr); Name := ParseQualifiedName(AStr); if (Name <> '') and (Name <> 'const&') then CppName := CppName + ' ' + Name; end; { Check for references (int&) and pointers (int*, int** etc). Make exception for 'void*' which translates to Pointer. } IsReference := CppName.EndsWith('&'); if IsReference then CppName := CppName.Substring(0, CppName.Length - 1); I := CppName.IndexOf('*'); if (I < 0) then Suffix := '' else if (CppName.StartsWith('void*')) then begin Suffix := CppName.Substring(5); CppName := 'Pointer'; end else begin Suffix := CppName.Substring(I); CppName := CppName.Substring(0, I); end; { Convert (C++) type to Delphi type } if (not FTypeMap.TryGetValue(CppName, Result)) then Result := CppName; { Special cases: * For names in the System namespace: * DynamicArray<XYZ> -> array of XYZ * StaticArray<XYZ, N> -> array [0..N-1] of XYZ * DelphiInterface<XYZ> -> XYZ * Set<XYZ, ...> -> set of XYZ * XYZ& -> var XYZ } if InSystem then begin if (Result.StartsWith('DynamicArray<')) then Result := 'array of ' + Result.Substring(13, Result.Length - 14) else if (Result.StartsWith('StaticArray<')) then Result := ConvertStaticArray(Result) else if (Result.StartsWith('DelphiInterface<')) then Result := Result.Substring(16, Result.Length - 17) else if (Result.StartsWith('Set<')) then Result := ConvertSet(Result); end; if (IsReference) then Result := 'var ' + Result; Result := Result + Suffix; end; class function TgoSymbolConverter.ParseParams(var AStr: PChar): String; { Params -> Param (',' Param)* Convert special case "TVarRec*, Integer" to "array of const" } var PrevIsVarRec: Boolean; Param: String; begin Result := ParseParam(AStr); PrevIsVarRec := (Result = 'TVarRec*'); while (AStr^ = ',') do begin Inc(AStr); SkipWhitespace(AStr); Param := ParseParam(AStr); if (PrevIsVarRec) then begin if (Param = 'Integer') then begin Result := Result.Substring(0, Result.Length - 8); Result := Result + 'array of const'; end else Result := Result + ', ' + Param; PrevIsVarRec := False; end else begin Result := Result + ', ' + Param; PrevIsVarRec := (Param = 'TVarRec*'); end; end; end; class function TgoSymbolConverter.ParseQualifiedName(var AStr: PChar): String; var Dummy: Boolean; begin Result := ParseQualifiedName(AStr, Dummy); end; class function TgoSymbolConverter.ParseQualifiedName(var AStr: PChar; out AInSystem: Boolean): String; { QualifiedName -> Name ('::' Name)* For brevity, we ignore the System namespace in names that start with it. } begin Result := ParseName(AStr); AInSystem := (Result = 'System') and (AStr[0] = ':') and (AStr[1] = ':'); if AInSystem then begin Inc(AStr, 2); Result := ParseName(AStr); end; while (AStr[0] = ':') and (AStr[1] = ':') do begin Inc(AStr, 2); Result := Result + '.' + ParseName(AStr); end; end; class function TgoSymbolConverter.ParseRemainder(var AStr: PChar): String; { Is called when string cannot be parsed. Just returns the remainder of the string as-is. } var P: PChar; begin P := AStr; while (P^ <> #0) do Inc(P); SetString(Result, AStr, P - AStr); AStr := P; end; class procedure TgoSymbolConverter.SkipWhitespace(var AStr: PChar); begin while (AStr^ <> #0) and (AStr^ <= ' ') do Inc(AStr); end; end.
unit Sky; interface uses AvL, avlUtils, OpenGL, oglExtensions, VSECore, VSECamera, VSEPrimitiveModel; type TSky=class(TObject) private FDome: TPriModel; FShift: Single; public constructor Create; destructor Destroy; override; procedure Draw(Camera: TCamera); //Draw sky procedure Update; //Update sky end; implementation constructor TSky.Create; begin inherited Create; FDome:=TPriModel.Create(Core.GetFile('Sky.vpm'), true); end; destructor TSky.Destroy; begin FAN(FDome); inherited Destroy; end; procedure TSky.Draw(Camera: TCamera); begin glPushAttrib(GL_ENABLE_BIT or GL_TRANSFORM_BIT or GL_CURRENT_BIT); if GL_ARB_multitexture then glActiveTextureARB(GL_TEXTURE0_ARB); glMatrixMode(GL_TEXTURE); glPushMatrix; glLoadIdentity; glTranslate(FShift, 0, 0); glMatrixMode(GL_MODELVIEW); glPushMatrix; glLoadIdentity; with Camera.Eye do glTranslate(X, Y, Z); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glColor3f(1.0, 1.0, 1.0); FDome.Draw; glPopMatrix; glMatrixMode(GL_TEXTURE); glPopMatrix; glPopAttrib; end; procedure TSky.Update; begin FShift:=FShift+0.0002; if FShift>1 then FShift:=FShift-1; end; end.
unit PLAT_TreeFuncNodeLink; interface uses Menus, Classes, Comctrls, PLAT_QuickLink; type TTreeFuncNodeLink = class(TQuickLink) private FPopupMenu: TPopupMenu; FMenuItem: TMenuItem; FNodeLevel: Integer; procedure SetMenuItem(const Value: TMenuItem); function FindTreeNode: TTreeNode; overload; function FindTreeNode(szText: string): TTreeNode; overload; procedure RefreshPopupMenu; procedure AddMenuItemsFromNode(mi: TMenuItem; Node: TTreeNode); function FindTreeNode(TreeNode: TTreeNode; szText: string): TTreeNode; overload; procedure MenuItemClick(Sender: TObject); procedure SetNodeLevel(const Value: Integer); public ImageIndex: Integer; constructor Create(NodeText: string); destructor Destroy; override; procedure Execute; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; procedure UpdateLinker(Linker: TObject); override; property MenuItem: TMenuItem read FMenuItem write SetMenuItem; property NodeLevel: Integer read FNodeLevel write SetNodeLevel; end; implementation { TPlatFunctionLink } uses PLAT_Utils, Windows, Forms, Dialogs, Sysutils, Main; procedure TTreeFuncNodeLink.Execute; var pt: TPoint; begin with TFormMain(Application.MainForm).TreeViewFunc do begin Selected := self.FindTreeNode; if Selected = nil then exit; if Selected.Count = 0 then TFormMain(Application.MainForm).FuncTreeClick else begin GetCursorPos(pt); RefreshPopupMenu; FPopupMenu.Popup(pt.x, pt.y); end; end; end; procedure TTreeFuncNodeLink.RefreshPopupMenu; var Node: TTreeNode; begin FPopupMenu.Items.Clear; NOde := FindTreeNode; self.AddMenuItemsFromNode(FPopupMenu.Items, Node); end; procedure TTreeFuncNodeLink.AddMenuItemsFromNode(mi: TMenuItem; Node: TTreeNode); var i: Integer; aMi: TMenuItem; begin mi.Caption := node.Text; for i := 0 to Node.Count - 1 do begin Ami := TMenuItem.Create(Forms.application); AddMenuItemsFromNode(Ami, Node.Item[i]); if AMi.Count = 0 then Ami.OnClick := MenuItemClick; mi.Add(Ami); end; {for i:=0 to Mi.Count-1 do begin if mi[i].Caption='-' then continue; ANode:=TreeViewFunc.Items.AddChild (Node,TrimMenuCaption(mi[i].Caption)); AddMenuItems(mi[i],ANode); end; } end; procedure TTreeFuncNodeLink.LoadFromStream(Stream: TStream); var szData: string; begin TUtils.LoadStringFromStream(Stream, szData); Tutils.LoadStringFromStream(Stream, FCaption); TUtils.LoadStringFromStream(Stream, FDescription); TUtils.LoadStringFromStream(Stream, FPNodeCaption); //加入一个上级结点标题的串 TUtils.LoadStringFromStream(Stream, FPModCode); Stream.Read(FLeft, SizeOf(FLeft)); Stream.Read(FTop, SizeOf(FTop)); Stream.Read(FNodeLevel, SizeOf(FNodeLevel)); //FMenuItem:=FindMenuItem(szData); end; procedure TTreeFuncNodeLink.SaveToStream(Stream: TStream); var i: Integer; szData: string; begin try szData := self.ClassName; TUtils.SaveStringToStream(Stream, szData); //pub start Tutils.SaveStringToStream(Stream, FCaption); TUtils.SaveStringToStream(Stream, FDescription); TUtils.SaveStringToStream(Stream, FPNodeCaption); //加入一个上级结点标题的串 TUtils.SaveStringToStream(Stream, FPModCode); Stream.Write(FLeft, SizeOf(FLeft)); Stream.Write(FTop, SizeOf(FTop)); //pub start Stream.Write(FNodeLevel, SizeOf(FNodeLevel)); except end; end; procedure TTreeFuncNodeLink.SetMenuItem(const Value: TMenuItem); begin FMenuItem := Value; end; constructor TTreeFuncNodeLink.Create(NodeText: string); begin inherited Create(); self.Caption := NodeText; self.ImageIndex := ImageIndex; FPopupMenu := TPopupMenu.Create(Forms.Application); FPopupMenu.AutoHotkeys := maManual; end; destructor TTreeFuncNodeLink.Destroy; begin FpopupMenu.Free; inherited; end; function TTreeFuncNodeLink.FindTreeNode: TTreeNode; var i: Integer; treeNode: TTreeNode; begin Result := nil; for i := 0 to TFormMain(Application.MainForm).TreeViewFunc.Items.Count - 1 do begin TreeNode := TFormMain(Application.MainForm).TreeViewFunc.Items[i]; //为了处理菜单重名的问题而加的处理 Hany an 2006.01.14 if TreeNode.Parent = nil then begin // 崔立国 2011.11.10 先检查当前快捷方式所属模块菜单是否已经初始化,如果没有则先初始化再查找。 if SameText(PTreeRec(TreeNode.Data)^.sModCode, FPModCode) then begin // 崔立国 2011.11.10 先检查当前快捷方式所属模块菜单是否已经初始化,如果没有则先初始化再查找。 TFormMain(Application.MainForm).InitModSubTreeNodeAndMenuBox(TreeNode); if (TreeNode.Text = Caption) and (treeNode.Level = FNodeLevel) then begin Result := Treenode; Break; end else Result := FindTreeNode(TreeNode, Caption); end; end else begin //and (treeNode.Level = FNodeLevel) 暂时屏蔽功能 if (TreeNode.Text = Trim(Caption)) and (FPNodeCaption = TreeNode.Parent.Text) then begin Result := Treenode; Break; end else Result := FindTreeNode(TreeNode, Caption); end; if Result <> nil then break; end; end; function TTreeFuncNodeLink.FindTreeNode(TreeNode: TTreeNode; szText: string): TTreeNode; var i: Integer; AtreeNode: TTreeNode; begin Result := nil; for i := 0 to TreeNode.Count - 1 do begin ATreeNode := TreeNode[i]; // Bryan 20040901 if (ATreeNode.Text = szText) and (not ATreeNode.HasChildren) {and (treeNode.Level = FNodeLevel)} then begin Result := ATreenode; break; end else Result := FindTreeNode(ATreeNode, szText); if Result <> nil then break; end; end; procedure TTreeFuncNodeLink.MenuItemClick(Sender: TObject); var szCaption: string; begin if (Sender is TMenuItem) then begin szCaption := (Sender as TMenuItem).Caption; TFormMain(Application.MainForm).TreeViewFunc.Selected := FindTreeNode(szCaption); TFormMain(Application.MainForm).FuncTreeClick end; end; function TTreeFuncNodeLink.FindTreeNode(szText: string): TTreeNode; var i: integer; var TreeNode: TTreeNode; begin Result := nil; for i := 0 to TFormMain(Application.MainForm).TreeViewFunc.Items.Count - 1 do begin TreeNode := TFormMain(Application.MainForm).TreeViewFunc.Items[i]; if TreeNode.Text = szText then begin Result := Treenode; break; end else Result := FindTreeNode(TreeNode, szText); if Result <> nil then break; end; end; procedure TTreeFuncNodeLink.UpdateLinker(Linker: TObject); begin inherited; end; procedure TTreeFuncNodeLink.SetNodeLevel(const Value: Integer); begin FNodeLevel := Value; end; end.
unit CustomAniResource; interface uses CustomAniFigure; type TCustomAniResource = class( TObject) public procedure Render( Figure : TCustomAniFigure ); virtual; abstract; procedure EnumLightSource( Figure : TCustomAniFigure; Index, X, Y, Z : longint; Intensity : double; Radius : integer ); virtual; procedure Draw( Canvas : PSDL_Surface; X, Y : Integer; Frame : Word ); virtual; abstract; procedure FreeResources; virtual; abstract; end; implementation end.
unit Ruler; // Version: 0.9 // Created: by Aleksey Denisov // Last modifyed: March 31, 1998 // Web page: http://www.geocities.com/CapeCanaveral/8002 // E-mail: alex_den@geocities.com // Status: Freeware interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Math; // possible some modules can be savely removed type TOrientation = (orHoriz, orVert); TCaptionAlign = (caTopLeft, caBottomRight); TNumberAlign = (naCenter, naBottomRight, naTopLeft); TTickAlign = (taBottomRight, taTopLeft); TFontRotation = (fr0, fr90, fr180, fr270); TValRange = class(TPersistent) // is used for setting roll limits private FMinValid: Boolean; FMin: Double; FMaxValid: Boolean; FMax: Double; published property MinValid: Boolean read FMinValid write FMinValid; property Min: Double read FMin write FMin; property MaxValid: Boolean read FMaxValid write FMaxValid; property Max: Double read FMax write FMax; end; TRuler = class(TCustomControl) private FCaption: String; FCaptionAlign: TCaptionAlign; FCaptionIndent1: Integer; FCaptionIndent2: Integer; FColor: TColor; FEnableRepaint: Boolean; FFont: TFont; FFontRotation: TFontRotation; FNumberAlign: TNumberAlign; FNumberIndent: Integer; FOrientation: TOrientation; FRollEnabled: Boolean; FRollLimits: TValRange; FStartValue: Double; FSzBig: Integer; FSzMiddle: Integer; FSzSmall: Integer; FTickAlign: TTickAlign; FTickColor: TColor; FUnitSize: Double; FUnitPrice: Double; FUnitPrecision: Integer; MousePressed: Boolean; MousePos: Integer; protected procedure Paint; override; procedure SetCaption(ACaption: String); procedure SetCaptionAlign(AnAlign: TCaptionAlign); procedure SetCaptionIndent1(AnIndent: Integer); procedure SetCaptionIndent2(AnIndent: Integer); procedure SetColor(AColor: TColor); procedure SetFont(AFont: TFont); procedure SetFontRotation(AFontRot: TFontRotation); procedure SetNumberAlign(ANumAlign: TNumberAlign); procedure SetNumberIndent(AnIndent: Integer); procedure SetOrientation(AnOrientation: TOrientation); procedure SetStartValue(AStartVal: Double); procedure SetSzBig(ASize: Integer); procedure SetSzMiddle(ASize: Integer); procedure SetSzSmall(ASize: Integer); procedure SetTickAlign(ATickAlign: TTickAlign); procedure SetUnitSize(AUnitSize: Double); procedure SetUnitPrice(AUnitPrice: Double); procedure SetUnitPrecision(APrecision: Integer); 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; public constructor Create(AOwner: TComponent); override; published property Align; property Caption: String read FCaption write SetCaption; property CaptionAlign: TCaptionAlign read FCaptionAlign write SetCaptionAlign; property CaptionIndent1: Integer read FCaptionIndent1 write SetCaptionIndent1; property CaptionIndent2: Integer read FCaptionIndent2 write SetCaptionIndent2; property Color: TColor read FColor write SetColor; property Enabled; property EnableRepaint: Boolean read FEnableRepaint write FEnableRepaint; property Font: TFont read FFont write SetFont; property FontRotation: TFontRotation read FFontRotation write SetFontRotation; property Hint; property NumberAlign: TNumberAlign read FNumberAlign write SetNumberAlign; property NumberIndent: Integer read FNumberIndent write SetNumberIndent; property Orientation: TOrientation read FOrientation write SetOrientation; property ParentShowHint; property RollEnabled: Boolean read FRollEnabled write FRollEnabled; property RollLimits: TValRange read FRollLimits write FRollLimits; property StartValue: Double read FStartValue write SetStartValue; property TickAlign: TTickAlign read FTickAlign write SetTickAlign; property TickColor: TColor read FTickColor write FTickColor; property TickSizeBig: Integer read FSzBig write SetSzBig; property TickSizeMiddle: Integer read FSzMiddle write SetSzMiddle; property TickSizeSmall: Integer read FSzSmall write SetSzSmall; property UnitSize: Double read FUnitSize write SetUnitSize; property UnitPrice: Double read FUnitPrice write SetUnitPrice; property UnitPrecision: Integer read FUnitPrecision write SetUnitPrecision; property OnMouseMove; property OnMouseDown; property OnMouseUp; property OnClick; end; procedure Register; implementation constructor TRuler.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csOpaque, csClickEvents, csDoubleClicks]; FColor := clYellow; FOrientation := orHoriz; FFont := TFont.Create; FFont.Name := 'Tahoma'; FFont.Height := -9; Width := 200; Height := 16; FUnitSize := 50; FUnitPrice := 1; FUnitPrecision := 0; FSzBig := 45; FSzMiddle := 35; FSzSmall := 15; FTickColor := clBlack; FNumberIndent := 0; FNumberAlign := naCenter; FRollLimits := TValRange.Create; FRollLimits.Max := 100; FEnableRepaint := True; end; procedure TRuler.Paint; var TickCount: Integer; szBig, szMiddle, szSmall: Integer; Pos, Tenth, D: Double; iPos, Val: Integer; lf: TLogFont; tf: TFont; P0, P1, P2, P3: Integer; S: String; Sw, Sh: Integer; begin D := Ceil(FStartValue * 10) / 10; Pos := (D - FStartValue - 1) * FUnitSize; TickCount := Round((D - Floor(FStartValue)) * 10); Tenth := FUnitSize / 10; Val := Ceil(FStartValue - 1); if FOrientation = orHoriz then begin szBig := FSzBig * Height div 100; szMiddle := FSzMiddle * Height div 100; szSmall := FSzSmall * Height div 100; end else begin szBig := FSzBig * Width div 100; szMiddle := FSzMiddle * Width div 100; szSmall := FSzSmall * Width div 100; end; inherited Paint; with Canvas do begin Pen.Color := FTickColor; Pen.Style := psSolid; Pen.Width := 1; tf := TFont.Create; tf.Assign(FFont); GetObject(tf.Handle, SizeOf(lf), @lf); case FFontRotation of fr0: lf.lfEscapement := 0; fr90: lf.lfEscapement := 900; fr180: lf.lfEscapement := 1800; fr270: lf.lfEscapement := 2700; end; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); Brush.Color := FColor; Brush.Style := bsSolid; FillRect(Rect(0, 0, Width, Height)); Sh := TextHeight('0'); if FOrientation = orHoriz then begin if FTickAlign = taBottomRight then begin P0 := Height-1; P1 := Height-1-szBig; P2 := Height-1-szMiddle; P3 := Height-1-szSmall; end else // TickAlign = taTopRight begin P0 := 0; P1 := szBig; P2 := szMiddle; P3 := szSmall; end; while Pos < Width - 1 do begin iPos := Round(Pos); if TickCount > 9 then TickCount := 0; if TickCount = 0 then begin S := Format('%.*f',[FUnitPrecision, Val*FUnitPrice]); Sw := TextWidth(S); case FNumberAlign of naCenter: case FFontRotation of fr0: TextOut(iPos - Sw div 2, FNumberIndent-1, S); fr90: TextOut(iPos - Sh div 2, FNumberIndent + Sw, S); fr180: TextOut(iPos + Sw div 2, FNumberIndent + Sh, S); fr270: TextOut(iPos + Sh div 2, FNumberIndent, S); end; naBottomRight: case FFontRotation of fr0: TextOut(iPos + 2, FNumberIndent, S); fr90: TextOut(iPos, FNumberIndent + Sw, S); fr180: TextOut(iPos + Sw + 1, FNumberIndent + Sh, S); fr270: TextOut(iPos + Sh + 1, FNumberIndent, S); end; naTopLeft: case FFontRotation of fr0: TextOut(iPos - Sw, FNumberIndent, S); fr90: TextOut(iPos - Sh, FNumberIndent + Sw, S); fr180: TextOut(iPos, FNumberIndent + Sh, S); fr270: TextOut(iPos, FNumberIndent, S); end; end; MoveTo(iPos, P0); LineTo(iPos, P1); Inc(Val); end else if TickCount = 5 then begin MoveTo(iPos, P0); LineTo(iPos, P2); end else begin MoveTo(iPos, P0); LineTo(iPos, P3); end; Inc(TickCount); Pos := Pos + Tenth; end; if FCaption <> '' then begin Sw := TextWidth(FCaption); Brush.Color := Color; if FCaptionAlign = caTopLeft then case FFontRotation of fr0: TextOut(CaptionIndent1, CaptionIndent2, FCaption); fr90: TextOut(CaptionIndent1, CaptionIndent2+Sw, FCaption); fr180: TextOut(CaptionIndent1+Sw, CaptionIndent2+Sh, FCaption); fr270: TextOut(CaptionIndent1+Sh, CaptionIndent2, FCaption); end else case FFontRotation of fr0: TextOut(Width-CaptionIndent1-Sw, CaptionIndent2, FCaption); fr90: TextOut(Width-CaptionIndent1-Sh, CaptionIndent2+Sw, FCaption); fr180: TextOut(Width-CaptionIndent1, CaptionIndent2+Sh, FCaption); fr270: TextOut(Width-CaptionIndent1, CaptionIndent2, FCaption); end end; end else //orVert begin if FTickAlign = taBottomRight then begin P0 := Width-1; P1 := Width-1-szBig; P2 := Width-1-szMiddle; P3 := Width-1-szSmall; end else // TickAlign = taTopRight begin P0 := 0; P1 := szBig; P2 := szMiddle; P3 := szSmall; end; while Pos < Height - 1 do begin iPos := Round(Pos); if TickCount > 9 then TickCount := 0; if TickCount = 0 then begin S := Format('%.*f',[FUnitPrecision, Val*FUnitPrice]); Sw := TextWidth(S); case FNumberAlign of naCenter: case FFontRotation of fr0: TextOut(FNumberIndent+1, iPos - Sh div 2, S); fr90: TextOut(FNumberIndent-1, iPos+Sw div 2+1, S); fr180: TextOut(FNumberIndent + Sw, iPos + Sh div 2+1, S); fr270: TextOut(FNumberIndent + Sh, iPos - Sw div 2 + 1, S); end; naBottomRight: case FFontRotation of fr0: TextOut(FNumberIndent+1, iPos, S); fr90: TextOut(FNumberIndent, iPos+Sw+1, S); fr180: TextOut(FNumberIndent + Sw, iPos + Sh + 1, S); fr270: TextOut(FNumberIndent + Sh, iPos+2, S); end; naTopLeft: case FFontRotation of fr0: TextOut(FNumberIndent, iPos-Sh, S); fr90: TextOut(FNumberIndent, iPos-1, S); fr180: TextOut(FNumberIndent + Sw, iPos, S); fr270: TextOut(FNumberIndent + Sh, iPos+2, S); end; end; MoveTo(P0, iPos); LineTo(P1, iPos); Inc(Val); end else if TickCount = 5 then begin MoveTo(P0, iPos); LineTo(P2, iPos); end else begin MoveTo(P0, iPos); LineTo(P3, iPos); end; Inc(TickCount); Pos := Pos + Tenth; end; if FCaption <> '' then begin Sw := TextWidth(FCaption); Brush.Color := Color; if FCaptionAlign = caTopLeft then case FFontRotation of fr0: TextOut(CaptionIndent2, CaptionIndent1, FCaption); fr90: TextOut(CaptionIndent2, CaptionIndent1+Sw, FCaption); fr180: TextOut(CaptionIndent2+Sw, CaptionIndent1+Sh, FCaption); fr270: TextOut(CaptionIndent2+Sh, CaptionIndent1, FCaption); end else case FFontRotation of fr0: TextOut(CaptionIndent2, Height-CaptionIndent1-Sh, FCaption); fr90: TextOut(CaptionIndent2, Height-CaptionIndent1, FCaption); fr180: TextOut(CaptionIndent2+Sw, Height-CaptionIndent1, FCaption); fr270: TextOut(CaptionIndent2+Sh, Height-CaptionIndent1-Sw, FCaption); end; end; end; tf.Free; end; end; procedure TRuler.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FOrientation = orHoriz then MousePos := X else MousePos := Y; if FRollEnabled then MousePressed := True; end; procedure TRuler.MouseMove(Shift: TShiftState; X, Y: Integer); var d: Integer; OldSV, NewSV: Double; begin if not MousePressed then Exit; if FOrientation = orHoriz then begin d := X - MousePos; MousePos := X; end else begin d := Y - MousePos; MousePos := Y; end; if d <> 0 then begin OldSV := FStartValue; NewSV := FStartValue - d / FUnitSize; if FRollLimits.MinValid then if NewSV < FRollLimits.Min then NewSV := FRollLimits.Min; if FRollLimits.MaxValid then if NewSV > FRollLimits.Max then NewSV := FRollLimits.Max; if NewSV <> OldSV then Invalidate; FStartValue := NewSV; end; if Assigned(OnMouseMove) then OnMouseMove(self, Shift, X, Y); end; procedure TRuler.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if MousePressed and Assigned(OnClick) then OnClick(self); MousePressed := False; end; procedure TRuler.SetCaption(ACaption: String); begin if FCaption = ACaption then Exit; FCaption := ACaption; if FEnableRepaint then Invalidate; end; procedure TRuler.SetCaptionAlign(AnAlign: TCaptionAlign); begin if FCaptionAlign = AnAlign then Exit; FCaptionAlign := AnAlign; if FEnableRepaint then Invalidate; end; procedure TRuler.SetCaptionIndent1(AnIndent: Integer); begin if FCaptionIndent1 = AnIndent then Exit; FCaptionIndent1 := AnIndent; if FEnableRepaint then Invalidate; end; procedure TRuler.SetCaptionIndent2(AnIndent: Integer); begin if FCaptionIndent2 = AnIndent then Exit; FCaptionIndent2 := AnIndent; if FEnableRepaint then Invalidate; end; procedure TRuler.SetColor(AColor: TColor); begin if FColor = AColor then Exit; FColor := AColor; if FEnableRepaint then Invalidate; end; procedure TRuler.SetFont(AFont: TFont); begin FFont.Assign(AFont); if FEnableRepaint then Invalidate; end; procedure TRuler.SetFontRotation(AFontRot: TFontRotation); begin if FFontRotation = AFontRot then Exit; FFontRotation := AFontRot; if FEnableRepaint then Invalidate; end; procedure TRuler.SetNumberAlign(ANumAlign: TNumberAlign); begin if FNumberAlign = ANumAlign then Exit; FNumberAlign := ANumAlign; if FEnableRepaint then Invalidate; end; procedure TRuler.SetNumberIndent(AnIndent: Integer); begin if FNumberIndent = AnIndent then Exit; FNumberIndent := AnIndent; if FEnableRepaint then Invalidate; end; procedure TRuler.SetOrientation(AnOrientation: TOrientation); var t: Integer; begin if FOrientation = AnOrientation then Exit; // do nothing if the same FOrientation := AnOrientation; if (csDesigning in ComponentState) and not (csLoading in ComponentState) then begin t := Height; Height := Width; Width := t; if FOrientation = orHoriz then begin FontRotation := fr0; end else begin FontRotation := fr90; end; end; if FEnableRepaint then Invalidate; end; procedure TRuler.SetStartValue(AStartVal: Double); begin if FStartValue = AStartVal then Exit; // do nothing if the same FStartValue := AStartVal; if FEnableRepaint then Invalidate; end; procedure TRuler.SetSzBig(ASize: Integer); begin if FSzBig = ASize then Exit; FSzBig := ASize; if FEnableRepaint then Invalidate; end; procedure TRuler.SetSzMiddle(ASize: Integer); begin if FSzMiddle = ASize then Exit; FSzMiddle := ASize; if FEnableRepaint then Invalidate; end; procedure TRuler.SetSzSmall(ASize: Integer); begin if FSzSmall = ASize then Exit; FSzSmall := ASize; if FEnableRepaint then Invalidate; end; procedure TRuler.SetTickAlign(ATickAlign: TTickAlign); begin if FTickAlign = ATickAlign then Exit; FTickAlign := ATickAlign; if FEnableRepaint then Invalidate; end; procedure TRuler.SetUnitSize(AUnitSize: Double); begin if FUnitSize = AUnitSize then Exit; FUnitSize := AUnitSize; if FEnableRepaint then Invalidate; end; procedure TRuler.SetUnitPrice(AUnitPrice: Double); begin if FUnitPrice = AUnitPrice then Exit; FUnitPrice := AUnitPrice; if FEnableRepaint then Invalidate; end; procedure TRuler.SetUnitPrecision(APrecision: Integer); begin if FUnitPrecision = APrecision then Exit; if APrecision < 0 then APrecision := 0; FUnitPrecision := APrecision; if FEnableRepaint then Invalidate; end; procedure Register; begin RegisterComponents('Samples', [TRuler]); end; end.
unit uEmployee; interface type TEmployee = class private FName: string; FEmail: string; FPhone: string; public property Name: string read FName write FName; property Email: string read FEmail write FEmail; property Phone: string read FPhone write FPhone; end; implementation end.
Unit F09; interface uses typelist; procedure tambah_buku (var Tbuku:List_Buku); { Prosedur ini menerima inputan berupa buku (id, judul, pengarang, jumlah, tahun terbit, dan kategori buku), dan menambahkan buku tersebut ke sistem perpustakaan. Prosedur ini hanya bisa diakses oleh admin. } implementation procedure tambah_buku (var Tbuku:List_Buku); { Prosedur ini menerima inputan berupa buku (id, judul, pengarang, jumlah, tahun terbit, dan kategori buku), dan menambahkan buku tersebut ke sistem perpustakaan. Prosedur ini hanya bisa diakses oleh admin. } // KAMUS LOKAL var id,jumlah,tahun:integer; judul,penulis,kategori:string; // ALGORITMA begin // Input dari User writeln('Masukkan Informasi buku yang ditambahkan:'); write('Masukkan id buku:'); readln(id); write('Masukkan judul buku:'); readln(judul); write('Masukkan pengarang buku:'); readln(penulis); write('Masukkan jumlah buku:'); readln(jumlah); write('Masukkan tahun terbit buku:'); readln(tahun); write('Masukkan kategori buku:'); readln(kategori); writeln(''); writeln('Buku berhasil ditambahkan ke dalam sistem!'); // Memasukkan input dari user ke array List Buku Tbuku.Neff:=Tbuku.Neff+1; Tbuku.listbuku[Tbuku.Neff].ID_Buku:=id; Tbuku.listbuku[Tbuku.Neff].Judul_Buku:=judul; Tbuku.listbuku[Tbuku.Neff].Author:=penulis; Tbuku.listbuku[Tbuku.Neff].Jumlah_Buku:=jumlah; Tbuku.listbuku[Tbuku.Neff].Tahun_Penerbit:=tahun; Tbuku.listbuku[Tbuku.Neff].Kategori:=kategori; end; end.
unit uOperation; interface uses Classes, Contnrs, uAddress, uClient, uClientContext, uSecurityContext, uClearingContext; type TOperation = class(TPersistent) protected fClient: TClient; fClientContext: TClientContext; fSecurityContext: TSecurityContext; fData : String; fId: String; fType : String; fStatus: String; fStatusMessage: String; fTitle: String; fLegend: String; fDataErrors: String; fSignDocument: String; fDocuments: TStringList; fClearingContext: TClearingContext; public constructor Create; destructor Destroy; override; published property Client: TClient read fClient write fClient; property ClientContext: TClientContext read fClientContext; property SecurityContext: TSecurityContext read fSecurityContext; property Data: String read fData write fData; property Id: String read fId write fId; property OperType : String read fType write fType; property Status: String read fStatus write fStatus; property StatusMessage: String read fStatusMessage write fStatusMessage; property Title: String read fTitle write fTitle; property Legend: String read fLegend write fLegend; property DataErrors: String read fDataErrors write fDataErrors; property SignDocument: String read fSignDocument write fSignDocument; property Documents: TStringList read fDocuments write fDocuments; property ClearingContext: TClearingContext read fClearingContext; end; implementation { TOperation } constructor TOperation.Create; begin fClient := TClient.Create; fClientContext := TClientContext.Create; fSecurityContext := TSecurityContext.Create; fClearingContext := TClearingContext.Create; fDocuments := TStringList.Create; end; destructor TOperation.Destroy; begin fClient.Free; fClientContext.Free; fSecurityContext.Free; fClearingContext.Free; fDocuments.Free; inherited; end; end.
unit Benchmarks.Remove; interface uses Core.Benchmark.Base, Motif; type TBenchmarkRemove = class(TBaseBenchmark) private fMotif: TMotif; public procedure runBenchmark; override; procedure setDown; override; procedure setUp; override; end; implementation uses System.SysUtils, System.Classes; { TBenchmarkRemove } procedure TBenchmarkRemove.runBenchmark; var num: integer; begin inherited; for num:=0 to 999 do fMotif.remove('x: '+IntToStr(num)); end; procedure TBenchmarkRemove.setDown; begin inherited; fMotif.Free; end; procedure TBenchmarkRemove.setUp; var num: integer; begin inherited; fMotif:=TMotif.Create; for num:=0 to 999 do fMotif.add('x: '+IntToStr(num), IntToStr(num)); end; end.
unit Unit_FileClient; {******************************************************************************* Stream Exchange Client Demo Indy 10.5.5 It just shows how to send/receive Record/Buffer. No error handling. Version November 2011 & February 2012 *******************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, StdCtrls, Vcl.ExtCtrls; type TFileExchangeClientForm = class(TForm) CheckBox1: TCheckBox; Button_SendStream: TButton; IdTCPClient1: TIdTCPClient; BuildButton: TButton; aOpenDialog: TOpenDialog; FileNameEdit: TEdit; LoadFileButton: TButton; Memo1: TMemo; procedure CheckBox1Click(Sender: TObject); procedure IdTCPClient1Connected(Sender: TObject); procedure IdTCPClient1Disconnected(Sender: TObject); procedure Button_SendStreamClick(Sender: TObject); procedure BuildButtonClick(Sender: TObject); procedure LoadFileButtonClick(Sender: TObject); private procedure SetClientState(aState: Boolean); { Private declarations } public { Public declarations } end; var FileExchangeClientForm: TFileExchangeClientForm; implementation uses Unit_Indy_Classes, Unit_Indy_Functions, Unit_DelphiCompilerversionDLG; {$R *.dfm} procedure TFileExchangeClientForm.BuildButtonClick(Sender: TObject); begin OKRightDlgDelphi.Show; end; procedure TFileExchangeClientForm.Button_SendStreamClick(Sender: TObject); var LSize: LongInt; begin LSize := 0; Memo1.Lines.Add('Try send stream to server.....'); if (ClientSendFile(IdTCPClient1, FileNameEdit.Text) = False) then begin Memo1.Lines.Add('Cannot send record/buffer to server->' + FileNameEdit.Text); Exit; end else begin Memo1.Lines.Add('send record/buffer to server->' + FileNameEdit.Text); end; SetClientState(false); end; procedure TFileExchangeClientForm.CheckBox1Click(Sender: TObject); begin if (CheckBox1.Checked = True) then begin IdTCPClient1.Host := '127.0.0.1'; IdTCPClient1.Port := 6000; IdTCPClient1.Connect; end else IdTCPClient1.Disconnect; end; procedure TFileExchangeClientForm.SetClientState(aState : Boolean); begin if (aState = True) then begin IdTCPClient1.Connect; CheckBox1.Checked := true; end else begin IdTCPClient1.Disconnect; CheckBox1.Checked := false; end; end; procedure TFileExchangeClientForm.IdTCPClient1Connected(Sender: TObject); begin Memo1.Lines.Add('Client has connected to server'); end; procedure TFileExchangeClientForm.IdTCPClient1Disconnected(Sender: TObject); begin Memo1.Lines.Add('Client has disconnected from server'); end; procedure TFileExchangeClientForm.LoadFileButtonClick(Sender: TObject); begin if aOpenDialog.Execute then begin FileNameEdit.Text := aOpenDialog.FileName; end; end; end.
unit uCliente; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, StdCtrls, Mask; type TClass_cliente = class(TObject) private Codigo : Integer; Nome : String; Endereco : String; Bairro : String; Cidade : String; Telefone : String; Email : String; public constructor Create(); destructor Free(); function GetCodigo : Integer; function GetNome : String; function GetEndereco : String; function GetBairro : String; function GetCidade : String; function GetTelefone : String; function GetEmail : String; procedure SetCodigo (const Value : Integer); procedure SetNome (const Value : String); procedure SetEndereco (const Value : String); procedure SetBairro (const Value : String); procedure SetCidade (const Value : String); procedure SetTelefone (const Value : String); procedure SetEmail (const Value : String); procedure Gravar(); procedure arquivo(); procedure Consultar(); procedure Excluir(); end; var Cliente : TClass_cliente; var Lista : TStringList; var arq : TextFile; var cod : String; var i: integer; implementation uses VarCmplx; { TClass_cliente } procedure TClass_cliente.arquivo(); begin AssignFile(arq,'C:\cadastro\cadastro.txt'); {$I-} Reset(arq); {$I+} if (IOResult <> 0) //arquivo não existe e será criado then Rewrite(arq) else begin CloseFile(arq); //o arquivo existe e será aberto para saídas adicionais //Append(arq); end; end; procedure TClass_cliente.Consultar; begin end; constructor TClass_cliente.Create; begin codigo :=0; Nome := ''; Endereco := ''; Bairro := ''; Cidade := ''; Telefone := ''; Email := ''; end; procedure TClass_cliente.Excluir; begin cod:= IntToStr(Codigo); Lista := TStringList.Create; try Lista.LoadFromFile('C:\cadastro\cadastro.txt'); Lista.BeginUpdate; for i := Lista.Count - 1 downto 0 do begin if Copy(Lista.Strings[i], 1, 3) = cod then ShowMessage(Lista.Text); Lista.Delete(i); end; Lista.EndUpdate; Lista.SaveToFile('C:\cadastro\cadastro.txt'); finally FreeAndNil(Lista); ShowMessage('O Registro ' + ' ' + cod + ' ' + ' foi excluido com sucesso !'); end; end; destructor TClass_cliente.Free; begin end; function TClass_cliente.GetBairro: String; begin Result := bairro; end; function TClass_cliente.GetCidade: String; begin Result := cidade; end; function TClass_cliente.GetCodigo: Integer; begin Result := codigo; end; function TClass_cliente.GetEmail: String; begin Result := email; end; function TClass_cliente.GetEndereco: String; begin Result := endereco; end; function TClass_cliente.GetNome: String; begin Result := nome; end; function TClass_cliente.GetTelefone: String; begin Result := telefone; end; procedure TClass_cliente.Gravar(); begin arquivo(); // Cria-se a TStringList Lista := TStringList.Create; // Carrega as linhas que estão no ficheiro para a TStringList Lista.LoadFromFile('C:\cadastro\cadastro.txt'); Lista.Add( IntToStr(Codigo)+'|'+Nome+'|'+Endereco+'|'+Bairro+'|'+Cidade+'|'+ Telefone+'|'+Email); Lista.SaveToFile('C:\cadastro\cadastro.txt'); Lista.Free; end; procedure TClass_cliente.SetBairro(const Value: String); begin bairro := Value; end; procedure TClass_cliente.SetCidade(const Value: String); begin cidade := Value; end; procedure TClass_cliente.SetCodigo(const Value: Integer); begin codigo := Value; end; procedure TClass_cliente.SetEmail(const Value: String); begin email := Value; end; procedure TClass_cliente.SetEndereco(const Value: String); begin endereco := Value; end; procedure TClass_cliente.SetNome(const Value: String); begin nome := Value; end; procedure TClass_cliente.SetTelefone(const Value: String); begin telefone := Value; end; end.