text
stringlengths
14
6.51M
unit LandClassesHandler; interface uses VoyagerInterfaces, Controls, LandInfo; type TLandClassesHandler = class( TLandClassesInfo, IMetaURLHandler, IURLHandler ) // IMetaURLHandler private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; // IURLHandler private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( URLHandler : IMasterURLHandler ); private fMasterURLHandler : IMasterURLHandler; end; const tidMetaHandlerName_LandClasses = 'LandClassesHandler'; // Events const evnAswerLandClassesHandler = 80; implementation uses Land; // TLandClassesHandler function TLandClassesHandler.getName : string; begin result := tidMetaHandlerName_LandClasses; end; function TLandClassesHandler.getOptions : TURLHandlerOptions; begin result := [hopNonVisual]; end; function TLandClassesHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TLandClassesHandler.Instantiate : IURLHandler; begin result := self; end; function TLandClassesHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin result := urlNotHandled; end; function TLandClassesHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var LandClassesInfo : ILandClassesInfo absolute info; begin if EventId = evnAswerLandClassesHandler then begin LandClassesInfo := self; result := evnHandled; end else result := evnNotHandled; end; function TLandClassesHandler.getControl : TControl; begin result := nil; end; procedure TLandClassesHandler.setMasterURLHandler( URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; end; end.
unit kwTestResolveInputFilePath; {* *Описание:* добавляет к имени файла путь к директории TestSet, где хранятся исходные файлы. *Формат* [code] aFileName test:ResolveInputFilePath [code] где aFileName - имя файля без пути (!). Результат помещается в стек. } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwTestResolveInputFilePath.pas" // Стереотип: "ScriptKeyword" // Элемент модели: "test_ResolveInputFilePath" MUID: (53FC3551023F) // Имя типа: "TkwTestResolveInputFilePath" {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwRegisterableWord , tfwScriptingInterfaces ; type TkwTestResolveInputFilePath = {final} class(TtfwRegisterableWord) {* *Описание:* добавляет к имени файла путь к директории TestSet, где хранятся исходные файлы. *Формат* [code] aFileName test:ResolveInputFilePath [code] где aFileName - имя файля без пути (!). Результат помещается в стек. } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; end;//TkwTestResolveInputFilePath {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses //#UC START# *53FC3551023Fimpl_uses* //#UC END# *53FC3551023Fimpl_uses* ; class function TkwTestResolveInputFilePath.GetWordNameForRegister: AnsiString; begin Result := 'test:ResolveInputFilePath'; end;//TkwTestResolveInputFilePath.GetWordNameForRegister procedure TkwTestResolveInputFilePath.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_53FC3551023F_var* //#UC END# *4DAEEDE10285_53FC3551023F_var* begin //#UC START# *4DAEEDE10285_53FC3551023F_impl* RunnerAssert(aCtx.rEngine.IsTopString, 'Не задано имя файла!', aCtx); aCtx.rEngine.PushString(aCtx.rCaller.ResolveInputFilePath(aCtx.rEngine.PopDelphiString)); //#UC END# *4DAEEDE10285_53FC3551023F_impl* end;//TkwTestResolveInputFilePath.DoDoIt initialization TkwTestResolveInputFilePath.RegisterInEngine; {* Регистрация test_ResolveInputFilePath } {$IfEnd} // NOT Defined(NoScripts) end.
{ OpenAL player for the fpsound library License: The same modified LGPL as the LCL Authors: JiXian Yang Felipe Monteiro de Carvalho } unit fpsound_openal; {$mode objfpc} interface uses Classes, SysUtils, OpenAL_NT, fpsound; type { TOpenALPlayer } TOpenALPlayer = class(TSoundPlayer) private al_device: PALCdevice; al_context: PALCcontext; codec_bs: longword; al_source: TALuint; al_format: integer; al_buffers: TALuint; al_bufsize: longword; al_readbuf: Pointer; al_rate: longword; al_bufcount: integer; public constructor Create; override; destructor Destroy; override; procedure Initialize; override; procedure Finalize; override; procedure Play(ASound: TSoundDocument); override; procedure Pause(ASound: TSoundDocument); override; procedure Stop(ASound: TSoundDocument); override; procedure AdjustToKeyElement(ASound: TSoundDocument; AKeyElement: TSoundKeyElement); procedure alStop; //function alProcess(ASound: TSoundDocument; AKeyElement: TSoundKeyElement): Boolean; function alFillBuffer(ASound: TSoundDocument; AKeyElement: TSoundKeyElement): integer; end; implementation constructor TOpenALPlayer.Create; begin inherited; Initialize; end; destructor TOpenALPlayer.Destroy; begin inherited; Finalize; end; procedure TOpenALPlayer.alStop; begin alSourceStop(al_source); alSourceRewind(al_source); alSourcei(al_source, AL_BUFFER, 0); end; {function TOpenALPlayer.alProcess(ASound: TSoundDocument; AKeyElement: TSoundKeyElement): Boolean; var processed : ALint; buffer : ALuint; sz : Integer; begin alGetSourcei(al_source, AL_BUFFERS_PROCESSED, processed); while (processed > 0) and (processed <= al_bufcount) do begin alSourceUnqueueBuffers(al_source, 1, @buffer); sz := alFillBuffer(ASound, AKeyELement); if sz <= 0 then begin Exit(False); end; alBufferData(buffer, al_format, al_readbuf, sz, al_rate); alSourceQueueBuffers(al_source, 1, @buffer); Dec(processed); end; Result := True; end;} function TOpenALPlayer.alFillBuffer(ASound: TSoundDocument; AKeyElement: TSoundKeyElement): integer; var lCurElement: TSoundElement; lReadCount: integer = 0; lBufferBytePtr: PByte; lBufferWordPtr: PWord; loop: TALInt; aaa: TStringList; begin GetMem(al_readbuf, al_bufsize); Result := 0; lBufferBytePtr := al_readbuf; lBufferWordPtr := al_readbuf; while lReadCount < al_bufsize do begin lCurElement := ASound.GetNextSoundElement(); if lCurElement = nil then Exit; Inc(Result); lReadCount := lReadCount + AKeyElement.BitsPerSample div 8; if AKeyElement.BitsPerSample = 8 then begin lBufferBytePtr^ := Lo((lCurElement as TSoundSample8).ChannelValues[0]); Inc(lBufferBytePtr); end else begin lBufferWordPtr^ := word((lCurElement as TSoundSample16).ChannelValues[0]); Inc(lBufferWordPtr, 2); end; end; //AlutLoadWavFile('T:\fpsound\testsounds\test.wav', al_format, al_readbuf, al_bufsize, al_rate, loop); //alutLoadWAVMemory(ASound.GetSoundDocPtr, al_format, al_readbuf, al_bufsize, al_rate, loop); LoadWavStream(ASound.SoundDocStream, al_format, al_readbuf, al_bufsize, al_rate, loop); aaa := TStringList.Create; aaa.Add(IntToStr(ASound.SoundDocStream.Size)); aaa.SaveToFile(IntToStr(ASound.SoundDocStream.Size) + '.txt'); end; procedure TOpenALPlayer.Initialize; var argv: array of PALbyte; begin if FInitialized then Exit; IsMultiThread := False; if not InitOpenAL then Exception.Create('Initialize OpenAL failed'); { al_device := alcOpenDevice(nil); al_context := alcCreateContext(al_device, nil); alcMakeContextCurrent(al_context); } alutInit(nil, argv); al_bufcount := 1; alGenBuffers(al_bufcount, @al_buffers); alListener3f(AL_POSITION, 0, 0, 0); alListener3f(AL_VELOCITY, 0, 0, 0); alListener3f(AL_ORIENTATION, 0, 0, -1); alGenSources(1, @al_source); alSourcef(al_source, AL_PITCH, 1); alSourcef(al_source, AL_GAIN, 1); alSource3f(al_source, AL_POSITION, 0, 0, 0); alSource3f(al_source, AL_VELOCITY, 0, 0, 0); alSourcei(al_source, AL_LOOPING, AL_FALSE); // alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); FInitialized := True; end; procedure TOpenALPlayer.Finalize; begin // finalize openal alDeleteSources(1, @al_source); alDeleteBuffers(al_bufcount, @al_buffers); AlutExit(); if al_readbuf <> nil then FreeMem(al_readbuf); // alcDestroyContext(al_context); // alcCloseDevice(al_device); FInitialized := False; end; procedure TOpenALPlayer.Play(ASound: TSoundDocument); var queued: integer; done: boolean; lKeyElement: TSoundKeyElement; begin // Initialize; // First adjust to the first key element lKeyElement := ASound.GetFirstSoundElement(); AdjustToKeyElement(ASound, lKeyElement); // Now clean up the source alSourceStop(al_source); alSourceRewind(al_source); // alSourcei(al_source, AL_BUFFER, 0); if al_readbuf <> nil then FreeMem(al_readbuf); // Fill the buffer alFillBuffer(ASound, lKeyElement); alBufferData(al_buffers, al_format, al_readbuf, al_bufsize, al_rate); alSourceQueueBuffers(al_source, 1, @al_buffers); // Play the sound alSourcePlay(al_source); end; procedure TOpenALPlayer.Stop(ASound: TSoundDocument); begin alSourceStop(al_source); end; procedure TOpenALPlayer.Pause(ASound: TSoundDocument); begin alSourcePause(al_source); end; procedure TOpenALPlayer.AdjustToKeyElement(ASound: TSoundDocument; AKeyElement: TSoundKeyElement); begin // initialize codec if AKeyElement.Channels = 1 then begin if AKeyElement.BitsPerSample = 8 then al_format := AL_FORMAT_MONO8 else al_format := AL_FORMAT_MONO16; end else begin if AKeyElement.BitsPerSample = 8 then al_format := AL_FORMAT_STEREO8 else al_format := AL_FORMAT_STEREO16; end; codec_bs := 2 * AKeyElement.Channels; // al_bufsize := 20000 - (20000 mod codec_bs); al_rate := AKeyElement.SampleRate; // WriteLn('Blocksize : ', codec_bs); // WriteLn('Rate : ', wave.fmt.SampleRate); // WriteLn('Channels : ', wave.fmt.Channels); // WriteLn('OpenAL Buffers : ', al_bufcount); // WriteLn('OpenAL Buffer Size : ', al_bufsize); // if al_readbuf <> nil then // FreeMem(al_readbuf); //alProcess(ASound, AKeyElement); end; initialization RegisterSoundPlayer(TOpenALPlayer.Create, spOpenAL); end.
unit NueFiltro; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Grids, Buttons, Mask, ToolEdit, Db, DbTables; type tfEstado = ( tfNuevo, tfEdit ); tcControl = ( tcDate, tcFloat, tcString ); TFiltroDlg = class(TForm) GroupBox1: TGroupBox; lbCampos: TListBox; GroupBox2: TGroupBox; Label5: TLabel; edValor: TEdit; Bevel1: TBevel; bbAdd: TBitBtn; bbElim: TBitBtn; BitBtn4: TBitBtn; BitBtn5: TBitBtn; sg: TStringGrid; rgTipo: TRadioGroup; lbSel: TListBox; procedure FormCreate(Sender: TObject); procedure lbCamposClick(Sender: TObject); procedure bbAddClick(Sender: TObject); procedure bbElimClick(Sender: TObject); procedure BitBtn4Click(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FSelect, FWhere, FFrom, FJoin, FOrder: string; FEstado: tfEstado; FDataSet: TDataSet; FFila: integer; FControl: tcControl; FCampo, FCompara, FValor, FCondic: TStringlist; FLisCampos: TStringlist; FOnCompleto: TNotifyEvent; procedure SetFrom(const Value: string); procedure SetJoin(const Value: string); procedure SetOrder(const Value: string); procedure SetSelect(const Value: string); procedure SetWhere(const Value: string); procedure SetDataSet(const Value: TDataSet); procedure ParseCampos; procedure CargaCampos; function NombreCampo( FNombre: string ): string; function ArmarFila: string; procedure LimpiarValores; procedure SetOnCompleto(const Value: TNotifyEvent); public { Public declarations } property Select: string read FSelect write SetSelect; property Where: string read FWhere write SetWhere; property From: string read FFrom write SetFrom; property Join: string read FJoin write SetJoin; property Order: string read FOrder write SetOrder; property DataSet: TDataSet read FDataSet write SetDataSet; property OnCompleto: TNotifyEvent read FOnCompleto write SetOnCompleto; end; var FiltroDlg: TFiltroDlg; implementation {$R *.DFM} { TFiltroDlg } function StripValor( FCad: string ):string; var nPos: integer; begin repeat nPos := Pos( '''', FCad ); delete( FCad, nPos, 1 ); until nPos = 0; repeat nPos := Pos( '%', FCad ); delete( FCad, nPos, 1 ); until nPos = 0; Result := FCad; end; procedure TFiltroDlg.CargaCampos; var x,l, nPos: integer; FCadena: string; FNombre: string; ACampo: TField; begin lbCampos.Clear; l := Length( FSelect ); FCadena := Copy( FSelect, 7, l); if not Assigned( FLisCampos ) then FLisCampos := TStringList.create; FLisCampos.clear; repeat x := Pos( ',', FCadena ); if x > 0 then begin FLisCampos.Add( Trim( Copy( FCadena,1, x-1 ))); FNombre := NombreCampo( FLisCampos[ FLisCampos.count-1 ] ); ACampo := FDataSet.FindField( FNombre ); if ACampo <> nil then lbCampos.Items.Add( ACampo.DisplayLabel ); nPos := Pos( #32, FLisCampos[ FLisCampos.Count-1 ] ); if nPos > 0 then FLisCampos[ FLisCampos.Count-1 ] := Copy( FLisCampos[ FLisCampos.Count-1 ],1, nPos-1 ); FCadena := Copy( FCadena,x+1, l ); end; until x = 0; if FCadena <> '' then begin FLisCampos.Add( Trim( FCadena )); FNombre := NombreCampo( FLisCampos[ FLisCampos.count-1 ] ); ACampo := FDataSet.FindField( FNombre ); if ACampo <> nil then lbCampos.Items.Add( ACampo.DisplayLabel ); nPos := Pos( #32, FLisCampos[ FLisCampos.Count-1 ] ); if nPos > 0 then FLisCampos[ FLisCampos.Count-1 ] := Copy( FLisCampos[ FLisCampos.Count-1 ],1, nPos-1 ); end; end; procedure TFiltroDlg.ParseCampos; var nPos, nLargo: integer; Query: string; begin Query := UpperCase( TQuery( FDataSet ).SQL.Text ); nLargo := length( Query ); nPos := Pos( 'ORDER BY', Query ); if nPos > 0 then begin FOrder := Copy( Query, nPos, nLargo ); Query := Copy( Query, 1, nPos-1 ); end; nPos := Pos( 'WHERE', Query ); if nPos > 0 then begin FWhere := Copy( Query, nPos+6, nLargo ); Query := Copy( Query, 1, nPos-1 ); end; nPos := Pos( 'INNER JOIN', Query ); if nPos > 0 then begin FJoin := Copy( Query, nPos, nLargo ); Query := Copy( Query, 1, nPos-1 ); end; nPos := Pos( 'FROM', Query ); if nPos > 0 then begin FFrom := Copy( Query, nPos, nLargo ); Query := Copy( Query, 1, nPos-1 ); end; nPos := Pos( 'SELECT', Query ); if nPos > 0 then begin FSelect := Copy( Query, nPos, nLargo-nPos ); Query := Copy( Query, 1, nPos-1 ); end; CargaCampos; end; procedure TFiltroDlg.SetDataSet(const Value: TDataSet); begin FDataSet := Value; if Value <> nil then FreeNotification( FDataSet ); ParseCampos; end; procedure TFiltroDlg.SetFrom(const Value: string); begin FFrom := Value; end; procedure TFiltroDlg.SetJoin(const Value: string); begin FJoin := Value; end; procedure TFiltroDlg.SetOrder(const Value: string); begin FOrder := Value; end; procedure TFiltroDlg.SetSelect(const Value: string); begin FSelect := Value; end; procedure TFiltroDlg.SetWhere(const Value: string); begin FWhere := Value; end; procedure TFiltroDlg.FormCreate(Sender: TObject); begin FCampo := TStringList.create; FCompara := TStringList.create; FValor := TStringList.create; FCondic := TStringList.create; FEstado := tfNuevo; FFila := 0; sg.Cells[ 0, 0 ] := ' Y/O'; sg.cells[ 1, 0 ] := ' Condicion de Consulta'; end; procedure TFiltroDlg.lbCamposClick(Sender: TObject); var FNombre: string; ACampo: TField; begin if lbCampos.ItemIndex > -1 then begin FNombre := NombreCampo( FLisCampos[ lbCampos.ItemIndex ] ); ACampo := FDataSet.FindField( FNombre ); if ( ACampo <> nil ) then begin Case( ACampo.DataType ) of ftDate, ftDateTime: begin edValor.Visible := false; FControl := tcDate; end; ftFloat, ftCurrency, ftBCD, ftSmallint, ftInteger, ftWord: begin edValor.Visible := true; FControl := tcFloat; end else begin edValor.Visible := true; FControl := tcString; end; end; end; end; end; procedure TFiltroDlg.bbAddClick(Sender: TObject); var FTexto: string; begin if ( lbCampos.ItemIndex = -1 ) or ( lbSel.ItemIndex = -1 ) then raise exception.create( 'Error!, por favor seleccione valores de consulta' ); if (( edValor.Visible ) and ( edValor.text = '' )) then raise exception.create( 'Error!, por favor seleccione valores de consulta' ); Inc( FFila ); if FFila+1 = sg.RowCount then sg.RowCount := sg.RowCount + 1; FCampo.Add(''); FCompara.Add( '' ); FValor.Add( '' ); FCondic.Add( '' ); FTexto := ArmarFila; sg.cells[ 1, FFila ] := FTexto; LimpiarValores; end; function TFiltroDlg.ArmarFila: string; begin FCampo[ FFila-1 ] := FLisCampos[ lbCampos.ItemIndex ]; Result := lbCampos.Items[ lbCampos.ItemIndex ] + ' '; Case lbSel.ItemIndex of 0: FCompara[ FFila-1 ] := '>'; 1: FCompara[ FFila-1 ] := '>='; 2: FCompara[ FFila-1 ] := '<'; 3: FCompara[ FFila-1 ] := '<='; 4: FCompara[ FFila-1 ] := 'LIKE'; 5: FCompara[ FFila-1 ] := 'LIKE'; 6: FCompara[ FFila-1 ] := '='; 7: FCompara[ FFila-1 ] := '<>'; end; Result := Result + lbSel.Items[ lbSel.ItemIndex ]; Case FControl of tcDate: begin {Result := Result + '''' + DateToStr( Fecha.date ) + ''''; FValor[ FFila-1 ] := '''' + DateToStr( Fecha.date ) + '''';} end; tcFloat: begin Result := Result + edValor.text; FValor[ FFila-1 ] := edValor.text; end; tcString: begin Result := Result + '''' + edValor.text + ''''; if lbSel.ItemIndex = 4 then FValor[ FFila-1 ] := '''' + edValor.text + '%''' else if lbSel.ItemIndex = 5 then FValor[ FFila-1 ] := '''%' + edValor.text + '%''' else FValor[ FFila-1 ] := '''' + edValor.text + ''''; end; end; if ( FFila > 1 ) then if rgTipo.ItemIndex = 0 then begin sg.cells[ 0, FFila ] := ' Y'; FCondic[ FFila-1 ] := 'AND'; end else begin sg.cells[ 0, FFila ] := ' O'; FCondic[ FFila-1 ] := 'OR'; end; end; procedure TFiltroDlg.bbElimClick(Sender: TObject); var x:integer; begin if ( FFila > 0 ) and ( sg.Row > 0 ) then begin FCampo.Delete( sg.Row-1 ); FCompara.Delete( sg.Row-1 ); FValor.Delete( sg.Row-1 ); FCondic.Delete( sg.Row-1 ); if ( sg.Row-1 = 0 ) and ( FCondic.Count > 0 ) then FCondic[0] := ''; sg.Rows[ sg.Row ].Clear; for x:=sg.Row to sg.RowCount-1-1 do sg.Rows[ x ] := sg.Rows[ x+1 ]; sg.RowCount := sg.RowCount-1; sg.Cells[ 0, 1 ] := ''; Dec( FFila ); end; end; procedure TFiltroDlg.BitBtn4Click(Sender: TObject); var FVieSQL: string; FQuery: string; x: integer; begin try FDataSet.DisableControls; FQuery := ''; for x:=0 to FCampo.Count-1 do FQuery := FQuery + FCondic[ x ] + ' ' + FCampo[ x ] + ' ' + FCompara[ x ] + ' ' + FValor[ x ] + ' '; if FQuery = '' then exit; FWhere := 'WHERE ' + FQuery; FVieSQL := TQuery( FDataSet ).SQL.Text; try FDataSet.Close; TQuery( FDataSet ).SQL.Text := FSelect + FFrom + FJoin + FWhere + FOrder; // ShowMessage( TDataSet( FDataSet ).SQL.Text ); if Assigned( FOnCompleto ) then FOnCompleto( self ); TDataSet( FDataSet ).Open; except ShowMessage( 'Error en consulta. Recuperando vieja consulta' ); TQuery( FDataSet ).SQL.Text := FVieSQL; TDataSet( FDataSet ).Open; end; finally FDataSet.EnableControls; end; end; procedure TFiltroDlg.LimpiarValores; begin edValor.Text := ''; end; procedure TFiltroDlg.FormDestroy(Sender: TObject); begin FCampo.free; FCompara.free; FValor.free; FCondic.free; FLisCampos.free; FiltroDlg := nil; end; function TFiltroDlg.NombreCampo(FNombre: string): string; var FNom: string; nPos: integer; begin FNom := Trim( FNombre ); nPos := Pos( '.', FNom ); if nPos > 0 then FNom := Copy( FNom, nPos+1, length( FNom )); nPos := Pos( #32, FNom ); if nPos > 0 then Result := Copy( FNom, nPos+1, length( FNom )) else Result := FNom; end; procedure TFiltroDlg.SetOnCompleto(const Value: TNotifyEvent); begin FOnCompleto := Value; end; end.
unit prehistoricisle_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,rom_engine,pal_engine, ym_3812,nz80,upd7759,sound_engine; function iniciar_prehisle:boolean; implementation const prehisle_rom:array[0..1] of tipo_roms=( (n:'gt-e2.2h';l:$20000;p:0;crc:$7083245a),(n:'gt-e3.3h';l:$20000;p:$1;crc:$6d8cdf58)); prehisle_char:tipo_roms=(n:'gt15.b15';l:$8000;p:0;crc:$ac652412); prehisle_fondo_rom:tipo_roms=(n:'gt.11';l:$10000;p:0;crc:$b4f0fcf0); prehisle_fondo1:tipo_roms=(n:'pi8914.b14';l:$40000;p:0;crc:$207d6187); prehisle_fondo2:tipo_roms=(n:'pi8916.h16';l:$40000;p:0;crc:$7cffe0f6); prehisle_sound:tipo_roms=(n:'gt1.1';l:$10000;p:0;crc:$80a4c093); prehisle_upd:tipo_roms=(n:'gt4.4';l:$20000;p:0;crc:$85dfb9ec); prehisle_sprites:array[0..1] of tipo_roms=( (n:'pi8910.k14';l:$80000;p:0;crc:$5a101b0b),(n:'gt.5';l:$20000;p:$80000;crc:$3d3ab273)); //Dip prehisle_dip_a:array [0..5] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Level Select';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Bonus Life';number:2;dip:((dip_val:$4;dip_name:'Only Twice'),(dip_val:$0;dip_name:'Allways'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coinage';number:4;dip:((dip_val:$0;dip_name:'A 4C/1C B 1C/4C'),(dip_val:$10;dip_name:'A 3C/1C B 1C/3C'),(dip_val:$20;dip_name:'A 2C/1C B 1C/2C'),(dip_val:$30;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Lives';number:4;dip:((dip_val:$80;dip_name:'2'),(dip_val:$c0;dip_name:'3'),(dip_val:$40;dip_name:'4'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())),()); prehisle_dip_b:array [0..4] of def_dip=( (mask:$3;name:'Difficulty';number:4;dip:((dip_val:$2;dip_name:'Easy'),(dip_val:$3;dip_name:'Standard'),(dip_val:$1;dip_name:'Middle'),(dip_val:$0;dip_name:'Difficult'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Game Mode';number:4;dip:((dip_val:$8;dip_name:'Demo Sounds Off'),(dip_val:$c;dip_name:'Demo Sounds On'),(dip_val:$0;dip_name:'Freeze'),(dip_val:$4;dip_name:'Infinite Lives'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Bonus Life';number:4;dip:((dip_val:$30;dip_name:'100k 200k'),(dip_val:$20;dip_name:'150k 300k'),(dip_val:$10;dip_name:'300k 500k'),(dip_val:$0;dip_name:'None'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$40;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var rom:array[0..$1ffff] of word; ram,back_ram:array[0..$1fff] of word; fondo_rom:array[0..$7fff] of word; video_ram:array[0..$3ff] of word; invert_controls,sound_latch:byte; scroll_x1,scroll_y1,scroll_x2,scroll_y2:word; procedure update_video_prehisle; procedure poner_sprites(prioridad:boolean); var atrib,nchar,color,x,y:word; f:byte; begin for f:=0 to $ff do begin color:=buffer_sprites_w[(f*4)+3] shr 12; if (color<$4)<>prioridad then continue; atrib:=buffer_sprites_w[(f*4)+2]; nchar:=atrib and $1fff; if nchar>$1400 then nchar:=nchar-$1400; x:=buffer_sprites_w[(f*4)+1]; y:=buffer_sprites_w[(f*4)]; put_gfx_sprite(nchar,256+(color shl 4),(atrib and $4000)<>0,(atrib and $8000)<>0,1); actualiza_gfx_sprite(x,y,1,1); end; end; var f,color,pos,x,y,sx,sy,nchar,atrib:word; begin for f:=$0 to $120 do begin x:=f div 17; y:=f mod 17; //background sx:=x+((scroll_x1 and $3FF0) shr 4); sy:=y+((scroll_y1 and $1f0) shr 4); pos:=(sy and $1f)+((sx and $3ff) shl 5); atrib:=fondo_rom[pos]; color:=atrib shr 12; if (gfx[2].buffer[pos] or buffer_color[color+$10]) then begin nchar:=atrib and $7ff; put_gfx_flip(x*16,y*16,nchar,(color shl 4)+768,4,2,(atrib and $800)<>0,false); gfx[2].buffer[pos]:=false; end; //background 2 sx:=x+((scroll_x2 and $FF0) shr 4); sy:=y+((scroll_y2 and $1f0) shr 4); pos:=(sy and $1f)+((sx and $ff) shl 5); atrib:=back_ram[pos]; color:=atrib shr 12; if (gfx[3].buffer[pos] or buffer_color[color+$20]) then begin nchar:=atrib and $7ff; put_gfx_trans_flip(x*16,y*16,nchar,(color shl 4)+512,5,3,false,(atrib and $800)<>0); gfx[3].buffer[pos]:=false; end; end; //foreground for f:=$0 to $3ff do begin atrib:=video_ram[f]; color:=atrib shr 12; if (gfx[0].buffer[f] or buffer_color[color]) then begin x:=f mod 32; y:=f div 32; nchar:=atrib and $3ff; put_gfx_trans(x*8,y*8,nchar,color shl 4,2,0); gfx[0].buffer[f]:=false; end; end; //Mix scroll_x_y(4,1,scroll_x1 and $f,scroll_y1 and $f); poner_sprites(false); scroll_x_y(5,1,scroll_x2 and $f,scroll_y2 and $f); poner_sprites(true); actualiza_trozo(0,0,256,256,2,0,0,256,256,1); actualiza_trozo_final(0,16,256,224,1); fillchar(buffer_color[0],MAX_COLOR_BUFFER,0); end; procedure eventos_prehisle; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $Fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $F7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but2[1] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); if arcade_input.start[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); //COIN if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $Fd) else marcade.in2:=(marcade.in2 or $2); end; end; procedure prehisle_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; case f of 21:marcade.dswb:=marcade.dswb and $7f; 239:begin marcade.dswb:=marcade.dswb or $80; m68000_0.irq[4]:=HOLD_LINE; update_video_prehisle; end; end; end; eventos_prehisle; video_sync; end; end; function prehisle_getword(direccion:dword):word; begin case direccion of $0..$3ffff:prehisle_getword:=rom[direccion shr 1]; $70000..$73fff:prehisle_getword:=ram[(direccion and $3fff) shr 1]; $90000..$907ff:prehisle_getword:=video_ram[(direccion and $7ff) shr 1]; $a0000..$a07ff:prehisle_getword:=buffer_sprites_w[(direccion and $7ff) shr 1]; $b0000..$b3fff:prehisle_getword:=back_ram[(direccion and $3fff) shr 1]; $d0000..$d07ff:prehisle_getword:=buffer_paleta[(direccion and $7ff) shr 1]; $e0010:prehisle_getword:=marcade.in1; //P2 $e0020:prehisle_getword:=marcade.in2; //COIN $e0040:prehisle_getword:=marcade.in0 xor invert_controls; //P1 $e0042:prehisle_getword:=marcade.dswa; $e0044:prehisle_getword:=marcade.dswb; end; end; procedure prehisle_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.r:=pal4bit(tmp_color shr 12); color.g:=pal4bit(tmp_color shr 8); color.b:=pal4bit(tmp_color shr 4); set_pal_color(color,numero); case numero of 0..255:buffer_color[numero shr 4]:=true; 512..767:buffer_color[((numero shr 4) and $f)+$20]:=true; 768..1023:buffer_color[((numero shr 4) and $f)+$10]:=true; end; end; begin case direccion of 0..$3ffff:; //ROM $70000..$73fff:ram[(direccion and $3fff) shr 1]:=valor; $90000..$907ff:if video_ram[(direccion and $7ff) shr 1]<>valor then begin video_ram[(direccion and $7ff) shr 1]:=valor; gfx[0].buffer[(direccion and $7ff) shr 1]:=true; end; $a0000..$a07ff:buffer_sprites_w[(direccion and $7ff) shr 1]:=valor; $b0000..$b3fff:if back_ram[(direccion and $3fff) shr 1]<>valor then begin back_ram[(direccion and $3fff) shr 1]:=valor; gfx[3].buffer[(direccion and $3fff) shr 1]:=true; end; $d0000..$d07ff:if buffer_paleta[(direccion and $7ff) shr 1]<>valor then begin buffer_paleta[(direccion and $7ff) shr 1]:=valor; cambiar_color(valor,(direccion and $7ff) shr 1); end; $f0000:if scroll_y2<>(valor and $1ff) then begin if abs((scroll_y2 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[3].buffer[0],$2000,1); scroll_y2:=(valor and $1ff); end; $f0010:if scroll_x2<>(valor and $fff) then begin if abs((scroll_x2 and $ff0)-(valor and $ff0))>15 then fillchar(gfx[3].buffer[0],$2000,1); scroll_x2:=(valor and $fff); end; $f0020:if scroll_y1<>(valor and $1ff) then begin if abs((scroll_y1 and $1f0)-(valor and $1f0))>15 then fillchar(gfx[2].buffer[0],$8000,1); scroll_y1:=(valor and $1ff); end; $f0030:if scroll_x1<>(valor and $3fff) then begin if abs((scroll_x1 and $3ff0)-(valor and $3ff0))>15 then fillchar(gfx[2].buffer[0],$8000,1); scroll_x1:=(valor and $3fff); end; $f0046:if valor<>0 then invert_controls:=$ff else invert_controls:=0; $f0060:main_screen.flip_main_screen:=(valor and $1)<>0; $f0031..$f0045,$f0047..$f005f,$f0061..$f0069:; $f0070:begin sound_latch:=valor and $ff; z80_0.change_nmi(PULSE_LINE); end; end; end; function prehisle_snd_getbyte(direccion:word):byte; begin if direccion=$f800 then prehisle_snd_getbyte:=sound_latch else prehisle_snd_getbyte:=mem_snd[direccion]; end; procedure prehisle_snd_putbyte(direccion:word;valor:byte); begin if direccion>$efff then mem_snd[direccion]:=valor; end; function prehisle_snd_inbyte(puerto:word):byte; begin if (puerto and $ff)=0 then prehisle_snd_inbyte:=ym3812_0.status; end; procedure prehisle_snd_outbyte(puerto:word;valor:byte); begin case (puerto and $ff) of $00:ym3812_0.control(valor); $20:ym3812_0.write(valor); $40:begin upd7759_0.port_w(valor); upd7759_0.start_w(0); upd7759_0.start_w(1); end; $80:upd7759_0.reset_w(valor and $80); end; end; procedure prehisle_sound_update; begin ym3812_0.update; upd7759_0.update; end; procedure snd_irq(irqstate:byte); begin z80_0.change_irq(irqstate); end; //Main procedure reset_prehisle; begin m68000_0.reset; z80_0.reset; ym3812_0.reset; upd7759_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; invert_controls:=0; scroll_x1:=0; scroll_y1:=0; scroll_x2:=0; scroll_y2:=0; sound_latch:=0; end; function iniciar_prehisle:boolean; const ps_x:array[0..15] of dword=(0,4,8,12,16,20,24,28, 0+64*8,4+64*8,8+64*8,12+64*8,16+64*8,20+64*8,24+64*8,28+64*8); ps_y:array[0..15] of dword=(0*32, 1*32, 2*32, 3*32, 4*32, 5*32, 6*32, 7*32, 8*32, 9*32, 10*32, 11*32, 12*32, 13*32, 14*32, 15*32 ); var ptempb,memoria_temp:pbyte; tempw,f:word; begin llamadas_maquina.bucle_general:=prehisle_principal; llamadas_maquina.reset:=reset_prehisle; iniciar_prehisle:=false; iniciar_audio(false); screen_init(1,512,512,false,true); screen_init(2,256,256,true); //BG2 screen_init(4,272,272); screen_mod_scroll(4,272,256,255,272,256,255); //BG0 screen_init(5,272,272,true); screen_mod_scroll(5,272,256,255,272,256,255); iniciar_video(256,224); //Main CPU getmem(memoria_temp,$100000); m68000_0:=cpu_m68000.create(9000000,$100); m68000_0.change_ram16_calls(prehisle_getword,prehisle_putword); //Sound CPU z80_0:=cpu_z80.create(4000000,$100); z80_0.change_ram_calls(prehisle_snd_getbyte,prehisle_snd_putbyte); z80_0.change_io_calls(prehisle_snd_inbyte,prehisle_snd_outbyte); z80_0.init_sound(prehisle_sound_update); //Sound Chips ym3812_0:=ym3812_chip.create(YM3812_FM,4000000); ym3812_0.change_irq_calls(snd_irq); upd7759_0:=upd7759_chip.create(0.9); //cargar roms if not(roms_load16w(@rom,prehisle_rom)) then exit; //cargar sonido if not(roms_load(@mem_snd,prehisle_sound)) then exit; if not(roms_load(upd7759_0.get_rom_addr,prehisle_upd)) then exit; //convertir chars if not(roms_load(memoria_temp,prehisle_char)) then exit; init_gfx(0,8,8,1024); gfx_set_desc_data(4,0,32*8,0,1,2,3); convert_gfx(0,0,memoria_temp,@ps_x,@ps_y,false,false); gfx[0].trans[15]:=true; //sprites if not(roms_load(memoria_temp,prehisle_sprites)) then exit; init_gfx(1,16,16,$1400); gfx[1].trans[15]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(1,0,memoria_temp,@ps_x,@ps_y,false,false); //fondo 1 if not(roms_load(memoria_temp,prehisle_fondo_rom)) then exit; //Lo transformo en word... ptempb:=memoria_temp; for f:=0 to $7fff do begin tempw:=ptempb^ shl 8; inc(ptempb); tempw:=tempw or ptempb^; inc(ptempb); fondo_rom[f]:=tempw; end; if not(roms_load(memoria_temp,prehisle_fondo1)) then exit; init_gfx(2,16,16,$800); gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(2,0,memoria_temp,@ps_x,@ps_y,false,false); //fondo2 if not(roms_load(memoria_temp,prehisle_fondo2)) then exit; init_gfx(3,16,16,$800); gfx[3].trans[15]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(3,0,memoria_temp,@ps_x,@ps_y,false,false); //DIP marcade.dswa:=$ff; marcade.dswb:=$7f; marcade.dswa_val:=@prehisle_dip_a; marcade.dswb_val:=@prehisle_dip_b; //final freemem(memoria_temp); reset_prehisle; iniciar_prehisle:=true; end; end.
{ Subroutine SST_DTYPE_NEW_SUBRANGE (DTYPE_BASE,ORD_MIN,ORD_MAX,DTYPE_P) * * Create a new subrange data type, if necessary. DTYPE_BASE is the data type * descriptor for the subrange. ORD_MIN and ORD_MAX are the min/max ordinal * values the the new data type is to have within the base data type. * DTYPE_P will be returned pointing to the new subrange data type. It will * point to the base data type if the ordinal value range spans the whole * base data type. } module sst_DTYPE_NEW_SUBRANGE; define sst_dtype_new_subrange; %include 'sst2.ins.pas'; procedure sst_dtype_new_subrange ( {create new subrange data type, if necessary} in dtype_base: sst_dtype_t; {base data type to create subrange of} in ord_min: sys_int_max_t; {minimum ordinal value of subrange} in ord_max: sys_int_max_t; {maximum ordinal value of subrange} out dtype_p: sst_dtype_p_t); {subrange dtype, or base dtype if whole range} var odt_min, odt_max: sys_int_max_t; {ordinal range of base data type} dt_p: sst_dtype_p_t; {points to resolved base data type} range: sys_int_max_t; {number of ordinal values in data type} bits: sys_int_machine_t; {number of bits needed for ordinal range} mask: sys_int_max_t; {for testing whether BITS is high enough} align: sys_int_machine_t; {alignment for this data type} label resolve_dtype; begin dt_p := addr(dtype_base); {init pointer to resolved base data type} resolve_dtype: {back here to try again with next layer dtype} case dt_p^.dtype of {what kind of data type is this ?} sst_dtype_int_k: begin odt_max := rshft(~0, 1); odt_min := ~odt_max; end; sst_dtype_enum_k: begin odt_min := 0; odt_max := dt_p^.enum_last_p^.enum_ordval; end; sst_dtype_bool_k: begin odt_min := 0; odt_max := 1; end; sst_dtype_char_k: begin odt_min := 0; odt_max := 255; end; sst_dtype_range_k: begin odt_min := dt_p^.range_ord_first; odt_max := odt_min + dt_p^.range_n_vals - 1; if (ord_min = odt_min) and (ord_max = odt_max) then begin {exact fit ?} dtype_p := dt_p; return; end; dt_p := dt_p^.range_dtype_p; goto resolve_dtype; end; sst_dtype_copy_k: begin dt_p := dt_p^.copy_dtype_p; goto resolve_dtype; end; otherwise sys_message_bomb ('sst', 'dtype_not_ordinal', nil, 0); end; { * DT_P is pointing to the base data type, and ODT_MIN and ODT_MAX are the * min/max possible ordinal values of that data type. } if (ord_min = odt_min) and (ord_max = odt_max) then begin {no subrange needed ?} dtype_p := dt_p; return; end; { * The requested min/max ordinal value range does not exactly match any of the * data types we know about. Create a new data type. } range := ord_max - ord_min; {unsigned number of values - 1} bits := 0; {init number of bits needed} mask := ~0; {init mask for testing if BITS big enough} while (range & mask) <> 0 do begin {BITS still not big enough ?} bits := bits + 1; {one more bit} mask := lshft(mask, 1); end; {try again with one more bit} align := 1; {init to minimum alignment} mask := sst_config.bits_adr; {init max bits for this alignment} while mask < bits do begin {alignment not enough for number of bits ?} align := align * 2; {try next natural alignment} mask := mask * 2; {update max bits for this alignment} end; {back and check for this alignment enough} sst_dtype_new (dtype_p); {create and init new data type} dtype_p^.dtype := sst_dtype_range_k; dtype_p^.bits_min := bits; dtype_p^.align_nat := align; dtype_p^.align := align; dtype_p^.size_used := (bits + sst_config.bits_adr - 1) div sst_config.bits_adr; dtype_p^.size_align := align; dtype_p^.range_dtype_p := dt_p; dtype_p^.range_first_p := nil; dtype_p^.range_last_p := nil; dtype_p^.range_ord_first := ord_min; dtype_p^.range_n_vals := range + 1; end;
unit Model.Usuarios; interface uses Common.ENum, FireDAC.Comp.Client; type TUsuarios = class private FCodigo: integer; FNome: String; FLogin: String; FEMail: String; FSenha: String; FGrupo: Integer; FPrivilegio: String; FExpira: String; FDiasExpira: Integer; FPrimeiroAcesso: String; FAtivo: String; FDataSenha: TDate; FNivel: Integer; FExecutor: String; FManutencao: TDateTime; FAcao: TAcao; public property Codigo: integer read FCodigo write FCodigo; property Nome: String read FNome write FNome; property Login: String read FLogin write FLogin; property EMail: String read FEMail write FEMail; property Senha: String read FSenha write FSenha; property Grupo: Integer read FGrupo write FGrupo; property Privilegio: String read FPrivilegio write FPrivilegio; property Expira: String read FExpira write FExpira; property DiasExpira: Integer read FDiasExpira write FDiasExpira; property PrimeiroAcesso: String read FPrimeiroAcesso write FPrimeiroAcesso; property Ativo: String read FAtivo write FAtivo; property DataSenha: TDate read FDataSenha write FDataSenha; property Nivel: Integer read FNivel write FNivel; property Executor: String read FExecutor write FExecutor; property Manutencao: TDateTime read FManutencao write FManutencao; property Acao: TAcao read FAcao write FAcao; function GetID: Integer; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function ValidaLogin(sLogin: String; sSenha: String): Boolean; function AlteraSenha(AUsuarios: TUsuarios): Boolean; function LoginExiste(sLogin: String): Boolean; function EMailExiste(sEMail: String): Boolean; function ValidaLoginEMail(sEMail: String; sSenha: String): Boolean; end; implementation { TUsuarios } uses DAO.Usuarios; function TUsuarios.AlteraSenha(AUsuarios: TUsuarios): Boolean; var usuarioDAO : TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create; Result := usuarioDAO.AlteraSenha(AUsuarios); finally usuarioDAO.Free; end; end; function TUsuarios.EMailExiste(sEMail: String): Boolean; var usuarioDAO: TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create; Result := usuarioDAO.EMailExiste(sEMail); finally usuarioDAO.Free; end; end; function TUsuarios.GetID: Integer; var usuarioDAO: TUsuariosDAO; begin try usuarioDAO := TUsuariosDAO.Create(); Result := usuarioDAO.GetId; finally usuarioDAO.Free; end; end; function TUsuarios.Gravar: Boolean; var usuarioDAO : TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create; case FAcao of Common.ENum.tacIncluir: Result := usuarioDAO.Inserir(Self); Common.ENum.tacAlterar: Result := usuarioDAO.Alterar(Self); Common.ENum.tacExcluir: Result := usuarioDAO.Excluir(Self); end; finally usuarioDAO.Free; end; end; function TUsuarios.Localizar(aParam: array of variant): TFDQuery; var usuarioDAO: TUsuariosDAO; begin try usuarioDAO := TUsuariosDAO.Create(); Result := usuarioDAO.Pesquisar(aParam); finally usuarioDAO.Free; end; end; function TUsuarios.LoginExiste(sLogin: String): Boolean; var usuarioDAO: TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create; Result := usuarioDAO.LoginExiste(sLogin); finally usuarioDAO.Free; end; end; function TUsuarios.ValidaLogin(sLogin, sSenha: String): Boolean; var usuarioDAO : TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create(); Result := usuarioDAO.ValidaLogin(sLogin, sSenha); finally usuarioDAO.Free; end; end; function TUsuarios.ValidaLoginEMail(sEMail, sSenha: String): Boolean; var usuarioDAO : TUsuariosDAO; begin try Result := False; usuarioDAO := TUsuariosDAO.Create(); Result := usuarioDAO.ValidaLoginEMail(sEMail, sSenha); finally usuarioDAO.Free; end; end; end.
unit ConnectOptionsFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, GMList, Menus, Buttons, StdCtrls, FramedButton, InternationalizerComponent, ImgList; type TGMConnOptions = class(TForm) ImageList1: TImageList; PopupMenu1: TPopupMenu; MoveDown1: TMenuItem; MoveDown2: TMenuItem; N1: TMenuItem; Priority1: TMenuItem; Highest1: TMenuItem; Normal1: TMenuItem; Ignored1: TMenuItem; N2: TMenuItem; Panel3: TPanel; Panel2: TPanel; GMList: TListView; Panel1: TPanel; bMoveUp: TFramedButton; bMoveDown: TFramedButton; bRemove: TFramedButton; bFavorite: TFramedButton; bNormal: TFramedButton; bIgnored: TFramedButton; Label8: TLabel; bClose: TFramedButton; Panel4: TPanel; Label1: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure GMViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure MoveDown1Click(Sender: TObject); procedure MoveDown2Click(Sender: TObject); procedure Highest1Click(Sender: TObject); procedure Normal1Click(Sender: TObject); procedure Ignored1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GMListClick(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure bCloseClick(Sender: TObject); private fInitialized : boolean; fGameMasterList : TGameMasterList; procedure FillList; procedure FocusItem( Item : TGameMasterListInfo ); public property GameMasters : TGameMasterList write fGameMasterList; end; implementation {$R *.DFM} uses CoolSB; const PriorityToStr : array[low(TGMConnectOptions)..high(TGMConnectOptions)] of string = ( 'Literal426', 'Literal427', 'Literal428' ); const FAVORITE_IMGIDX = 0; NORMAL_IMGIDX = 1; IGNORED_IMGIDX = 2; const GMConnectOptionsToImgIdx : array[TGMConnectOptions] of integer = (FAVORITE_IMGIDX, NORMAL_IMGIDX, IGNORED_IMGIDX); procedure TGMConnOptions.FillList; var i : integer; Item : TListItem; begin if fInitialized then begin if GMList <> nil then begin GMList.Items.Clear; for i := 0 to pred(fGameMasterList.Count) do begin Item := GMList.Items.Add; with Item do begin Data := fGameMasterList.Item[i]; ImageIndex := GMConnectOptionsToImgIdx[fGameMasterList.Item[i].Options]; Caption := fGameMasterList.Item[i].Name; end; end; end; end; end; procedure TGMConnOptions.FocusItem( Item : TGameMasterListInfo ); begin if Item <> nil then begin bFavorite.Enabled := true; bNormal.Enabled := true; bIgnored.Enabled := true; bMoveUp.Enabled := true; bMoveDown.Enabled := true; bRemove.Enabled := true; case Item.Options of GMCO_HIGHPRIORITY : bFavorite.Selected := true; GMCO_NORMALPRIORITY : bNormal.Selected := true; GMCO_IGNORE : bIgnored.Selected := true; end end else begin bFavorite.Enabled := false; bNormal.Enabled := false; bIgnored.Enabled := false; bMoveUp.Enabled := false; bMoveDown.Enabled := false; bRemove.Enabled := false; end; end; procedure TGMConnOptions.GMViewMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Screen : TPoint; begin if (Button = mbRight) and (GMList.Selected <> nil) then begin Screen := ClientToScreen( Point( X, Y ) ); PopupMenu1.Popup( Screen.X, Screen.Y ); end; end; procedure TGMConnOptions.MoveDown1Click(Sender: TObject); var Info : TGameMasterListInfo; Idx : integer; begin if (GMList <> nil) and (GMList.Selected <> nil) then begin Info := TGameMasterListInfo(GMList.Selected.Data); Idx := GMList.Selected.Index; if fGameMasterList.MoveGameMasterUp( Info ) then begin GMList.Items.Clear; FillList; GMList.Selected := GMList.Items[pred(Idx)]; end; end; end; procedure TGMConnOptions.MoveDown2Click(Sender: TObject); var Info : TGameMasterListInfo; Idx : integer; begin if (GMList <> nil) and (GMList.Selected <> nil) then begin Info := TGameMasterListInfo(GMList.Selected.Data); Idx := GMList.Selected.Index; if fGameMasterList.MoveGameMasterDown( Info ) then begin GMList.Items.Clear; FillList; GMList.Selected := GMList.Items[succ(Idx)]; end; end; end; procedure TGMConnOptions.Highest1Click(Sender: TObject); var Info : TGameMasterListInfo; Item : TListItem; NewIdx : integer; begin Item := GMList.Selected; if Item <> nil then begin Info := TGameMasterListInfo(Item.Data); fGameMasterList.ChangeGameMasterProperties( Info, GMCO_HIGHPRIORITY, NewIdx ); GMList.Items.Clear; FillList; GMList.Selected := GMList.Items[NewIdx]; end; end; procedure TGMConnOptions.Normal1Click(Sender: TObject); var Info : TGameMasterListInfo; Item : TListItem; NewIdx : integer; begin Item := GMList.Selected; if Item <> nil then begin Info := TGameMasterListInfo(Item.Data); fGameMasterList.ChangeGameMasterProperties( Info, GMCO_NORMALPRIORITY, NewIdx ); GMList.Items.Clear; FillList; GMList.Selected := GMList.Items[NewIdx]; end; end; procedure TGMConnOptions.Ignored1Click(Sender: TObject); var Info : TGameMasterListInfo; Item : TListItem; NewIdx : integer; begin Item := GMList.Selected; if Item <> nil then begin Info := TGameMasterListInfo(Item.Data); fGameMasterList.ChangeGameMasterProperties( Info, GMCO_IGNORE, NewIdx ); GMList.Items.Clear; FillList; GMList.Selected := GMList.Items[NewIdx]; end; end; procedure TGMConnOptions.FormCreate(Sender: TObject); { var Idx : integer; } begin fGameMasterList := TGameMasterList.Create; { fGameMasterList.AddGameMaster( 'mima', GMCO_IGNORE, Idx ); fGameMasterList.AddGameMaster( 'pepe', GMCO_HIGHPRIORITY, Idx ); fGameMasterList.AddGameMaster( 'taka', GMCO_NORMALPRIORITY, Idx ); fGameMasterList.AddGameMaster( 'yuka', GMCO_NORMALPRIORITY, Idx ); } //FillList; end; procedure TGMConnOptions.GMListClick(Sender: TObject); var Info : TGameMasterListInfo; begin if GMList.Selected <> nil then begin Info := TGameMasterListInfo(GMList.Selected.Data); FocusItem( Info ); end else FocusItem( nil ); end; procedure TGMConnOptions.SpeedButton3Click(Sender: TObject); var Info : TGameMasterListInfo; begin if GMList.Selected <> nil then begin Info := TGameMasterListInfo(GMList.Selected.Data); fGameMasterList.DeleteGameMaster( Info.Name ); GMList.Items.Clear; FillList; end; end; procedure TGMConnOptions.FormShow(Sender: TObject); begin fInitialized := true; FillList; if (GMList <> nil)and (GMList.Selected = nil) then FocusItem( nil ); if InitSkinImage then InitializeCoolSB(GMList.Handle); end; procedure TGMConnOptions.bCloseClick(Sender: TObject); begin ModalResult := mrOk; end; end.
program matrices; type matriz = array [0..4,0..4] of integer; const min : integer = 0; const max : integer = 4; var matrixR : array [0..4, 0..4] of integer; var matrixA : array [0..4,0..4] of integer; var matrixB : array [0..4,0..4] of integer; procedure llenado(var matrixA : matriz ; matrixB : matriz); var i,j : integer; begin for i := min to max - 1 do begin for j := min to max - 1 do begin matrixA[i,j] := j * 3 + i; matrixB[i,j] := (i*i*i) - j * j; end; end; end; procedure printMatrix(var matrix : matriz); var i,j : integer; begin for i := min to max - 1 do begin for j := min to max - 1 do begin write(' | ',matrix[i,j]); end; writeln(' |'); end; end; procedure suma(var matrixA : matriz ; var matrixB : matriz ; var matrixR : matriz); var i,j : integer; begin for i:= min to max - 1 do begin for j := min to max - 1 do begin matrixR[i,j] := matrixA[i,j] + matrixB[i,j]; end; end; end; procedure sumaFilas(var matrix : matriz); var i,j,aux : integer; begin writeln(' R'); for i := min to max - 1 do begin aux := 0; for j := min to max - 1 do begin aux := aux + matrix[i,j]; write(' | ',matrix[i,j]); end; writeln(' | ',aux); end; end; procedure sumaColumnas(var matrix : matriz); var i,j,aux : integer; begin write('R'); for i := min to max - 1 do begin aux := 0; for j := min to max - 1 do begin aux := aux + matrix[j,i]; end; write(' | ',aux); end; writeln(''); end; procedure resta(var matrixA : matriz ; var matrixB : matriz ; var matrixR : matriz); var i,j : integer; begin for i:= min to max - 1 do begin for j := min to max - 1 do begin matrixR[i,j] := matrixA[i,j] - matrixB[i,j]; end; end; end; procedure Mult(var matrixA : matriz; var matrixB : matriz ; var matrixR : matriz); var i,j,k : integer; begin for i:= min to max - 1 do begin for j := min to max - 1 do begin for k := 0 to max - 1 do begin matrixR[i,j] := matrixR[i,j] + matrixA[i,k] * matrixB[k,j]; end; end; end; end; procedure Transpose(var matrix : matriz); var matrixAux : array[0..4,0..4] of integer; var i,j : integer; begin for i := min to max - 1 do begin for j:= min to max - 1 do begin matrixAux[i,j] := matrix[j,i]; end; end; for i := min to max - 1 do begin for j:= min to max - 1 do begin matrix[i,j] := matrixAux[i,j]; end; end; end; procedure minValue(var matrix : matriz); var i,j,iaux,jaux,temp : integer; begin iaux := min; jaux := min; temp := matrix[min,min]; for i := min to max - 1 do begin for j := min to max - 1 do begin if matrix[i,j] < temp then begin temp := matrix[i,j]; iaux := i; jaux := j; end; end; end; writeln('Min -> [',iaux,',',jaux,'] = ',temp); end; procedure maxValue(var matrix : matriz); var i,j,iaux,jaux,temp : integer; begin iaux := min; jaux := min; temp := matrix[min,min]; for i := min to max - 1 do begin for j := min to max - 1 do begin if matrix[i,j] > temp then begin temp := matrix[i,j]; iaux := i; jaux := j; end; end; end; writeln('Max -> [',iaux,',',jaux,'] = ',temp); end; procedure sort(var matrix : matriz); var i,j,x,y,aux : integer; begin for i := min to max - 1 do begin for j := min to max - 1 do begin for x := 0 to i do begin for y := 0 to j do begin if matrix[i,j] < matrix[x,y] then begin aux := matrix[i,j]; matrix[i,j] := matrix[x,y]; matrix[x,y] := aux; end; end; end; end; end; end; procedure clearMat(var matrix : matriz); var i,j : integer; begin for i := min to max - 1 do begin for j := min to max - 1 do begin matrix[i,j] := 0; end; end; end; llenado(matrixA,matrixB); writeln('Matrix A'); printMatrix(matrixA); writeln('Matrix B'); printMatrix(matrixB); writeln('MatR = MatA + MatB'); suma(matrixA,matrixB,matrixR); printMatrix(MatrixR); writeln('MatR = MatA - MatB'); resta(matrixA,matrixB,matrixR); printMatrix(MatrixR); writeln('Clear MatR'); clearMat(matrixR); printMatrix(matrixR); writeln('MatR = MatA * MatB'); mult(matrixa,matrixb,matrixr); printmatrix(matrixr); writeln('Tranpose(MatA)'); transpose(matrixA); printmatrix(matrixa); minValue(matrixR); maxValue(matrixR); writeln('Sort MatA'); sort(matrixR); printmatrix(matrixR); minValue(matrixR); maxValue(matrixR); writeln('Suma Filas y Columnas'); sumaFilas(matrixa); sumacolumnas(matrixa);
{!DOCTOPIC}{ Type » TBox } {!DOCREF} { @method: function TBox.Width(): Int32; @desc: Returns the width of the TBox } function TBox.Width(): Int32; {$IFDEF AeroLib}override;{$ENDIF} begin Result := (Self.X2 - Self.X1 + 1); end; {!DOCREF} { @method: function TBox.Height(): Int32; @desc: Returns the height of the TBox } function TBox.Height(): Int32; {$IFDEF AeroLib}override;{$ENDIF} begin Result := (Self.Y2 - Self.Y1 + 1); end; {!DOCREF} { @method: function TBox.Area(): Integer; @desc: Returns the area the TBox covers } function TBox.Area(): Integer; begin Result := Self.Width() * Self.Height(); end; {!DOCREF} { @method: function TBox.Center(): TPoint; @desc: Returns the center of the TBox } function TBox.Center(): TPoint; begin Result.X := (Self.X1 + Self.X2) div 2; Result.Y := (Self.Y1 + Self.Y2) div 2; end; {!DOCREF} { @method: procedure TBox.Expand(SizeChange: Int32); @desc: Expand (shrink if negative) the TBox by 'sizechange'. } procedure TBox.Expand(const SizeChange: Int32); {$IFDEF SRL6}override;{$ENDIF} begin Self.X1 := Self.X1 - SizeChange; Self.Y1 := Self.Y1 - SizeChange; Self.X2 := Self.X2 + SizeChange; Self.Y2 := Self.Y2 + SizeChange; end; {!DOCREF} { @method: function TBox.Contains(Pt:TPoint): Boolean; @desc: Returns True if the point 'Pt' is inside the TBox. } function TBox.Contains(Pt:TPoint): Boolean; begin Result := (self.x1 <= pt.x) and (pt.x <= self.x2) and (self.y1 <= pt.y) and (pt.y <= self.y2); end; {!DOCREF} { @method: function TBox.Overlaps(Other:TBox): Boolean; @desc: Return True if a this box overlaps the other TBox. } function TBox.Overlaps(Other:TBox): Boolean; begin Result:= (self.x2 > other.x1) and (self.x1 < other.x2) and (self.y1 < other.y2) and (self.y2 > other.y1); end; {!DOCREF} { @method: function TBox.Combine(Other:TBox): TBox; @desc: Combine two boxes - Lazy (does not expand on current) } function TBox.Combine(Other:TBox): TBox; {$IFDEF SRL6}override;{$ENDIF} begin Result := ToBox(Min(Min(Other.X1, Other.X2), Min(Self.X1, Self.X2)), Min(Min(Other.Y1, Other.Y2), Min(Self.Y1, Self.Y2)), Max(Max(Other.X1, Other.X2), Max(Self.X1, Self.X2)), Max(Max(Other.Y1, Other.Y2), Max(Self.Y1, Self.Y2))); end; {!DOCREF} { @method: function TBox.Merge(Other:TBox): TBox; @desc: Merge two boxes (expands on current) } function TBox.Merge(Other:TBox): TBox; begin Self := ToBox(Min(Min(Other.X1, Other.X2), Min(Self.X1, Self.X2)), Min(Min(Other.Y1, Other.Y2), Min(Self.Y1, Self.Y2)), Max(Max(Other.X1, Other.X2), Max(Self.X1, Self.X2)), Max(Max(Other.Y1, Other.Y2), Max(Self.Y1, Self.Y2))); end; {!DOCREF} { @method: function TBox.ToCoords(): TPointArray; @desc: Return a TPA of the corner points (clockwise). } function TBox.ToCoords(): TPointArray; begin Result := [Point(self.x1,self.y1), Point(self.x2,self.y1), Point(self.x2,self.y2), Point(self.x1,self.y2)]; end; {$IFNDEF SRL6} {!DOCREF} { @method: function TBox.Offset(Offs:TPoint): TBox; @desc: Offsets the TBox, returns a new box. } function TBox.Offset(Offs:TPoint): TBox; begin Result := ToBox(self.x1+Offs.x, self.y1+Offs.y, self.x2+Offs.x, self.y2+Offs.y); end; {$ENDIF} {!DOCREF} { @method: function TBox.EQ(Box:TBox): Boolean; @desc: Compares "EQual" } function TBox.EQ(Box:TBox): Boolean; begin Result := (self.x1=box.x1) and (self.y1=box.y1) and (self.x2=box.x2) and (self.y2=box.y2); end; {!DOCREF} { @method: function TBox.LT(Box:TBox): Boolean; @desc: Compares "Less Then" (compares the size) } function TBox.LT(Box:TBox): Boolean; begin Result := ((self.x2-self.x1+1)*(self.y2-self.y1+1) < (box.x2-box.x1+1)*(box.y2-box.y1+1)); end; {!DOCREF} { @method: function TBox.LT(Box:TBox): Boolean; @desc: Compares "Greater Then" (compares the size) } function TBox.GT(Box:TBox): Boolean; begin Result := ((self.x2-self.x1+1)*(self.y2-self.y1+1) > (box.x2-box.x1+1)*(box.y2-box.y1+1)); end;
{!DOCTOPIC}{ Matrix » TIntMatrix } //----------------------------------------------------------------------------- {!DOCREF} { @method: Integer matrix @desc: [hr] } {!DOCREF} { @method: function se.NewMatrix(W,H:Int32; Init:Int32=0): TIntMatrix; @desc: Creates a new matrix. Fills it with `Init`. } function SimbaExt.NewMatrix(W,H:Int32; Init:Int32=0): TIntMatrix; begin if Init = 0 then SetLength(Result, H,W) else Result := exp_NewMatrixEx(W,H, Init); end; {!DOCREF} { @method: procedure TIntMatrix.SetSize(Height,Width:Int32); @desc: Sets the size (width and height) of the matrix. Same as SetLength(Matrix, H,W); } procedure TIntMatrix.SetSize(Height,Width:Int32); begin SetLength(Self, Height,Width); end; {!DOCREF} { @method: function TIntMatrix.Width(): Int32; @desc: Retruns the width of the matrix (safly) } function TIntMatrix.Width(): Int32; begin if Length(Self) > 0 then Result := Length(Self[0]) else Result := 0; end; {!DOCREF} { @method: function TIntMatrix.Height(): Int32; @desc: Retruns the height of the matrix } function TIntMatrix.Height(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function TIntMatrix.Get(const Indices:TPointArray): TIntArray; @desc: Gets all the values at the given indices. If any of the points goes out of bounds, it will simply be ignored. [code=pascal] var Matrix:TIntMatrix; begin Matrix.SetSize(100,100); Matrix[10][10] := 100; Matrix[10][13] := 29; WriteLn( Matrix.Get([Point(10,10),Point(13,10),Point(20,20)])); end; [/code] } function TIntMatrix.Get(const Indices:TPointArray): TIntArray; begin Result := exp_GetValues(Self, Indices); end; {!DOCREF} { @method: procedure TIntMatrix.Put(const TPA:TPointArray; Values:TIntArray); @desc: Adds the points to the matrix with the given values. } procedure TIntMatrix.Put(const TPA:TPointArray; Values:TIntArray); begin exp_PutValues(Self, TPA, Values); end; {!DOCREF} { @method: procedure TIntMatrix.Put(const TPA:TPointArray; Value:Int32); overload; @desc: Adds the points to the matrix with the given value. } procedure TIntMatrix.Put(const TPA:TPointArray; Value:Int32); overload; begin exp_PutValues(Self, TPA, TIntArray([Value])); end; {!DOCREF} { @method: function TIntMatrix.Merge(): TIntArray; @desc: Merges the matrix is to a flat array of the same type. } function TIntMatrix.Merge(): TIntArray; var i,s,wid: Int32; begin S := 0; SetLength(Result, Self.Width()*Self.Height()); Wid := Self.Width(); for i:=0 to High(Self) do begin MemMove(Self[i][0], Result[S], Wid*SizeOf(Int32)); S := S + Wid; end; end; {!DOCREF} { @method: function TIntMatrix.Sum(): Int64; @desc: Returns the sum of the matrix } function TIntMatrix.Sum(): Int64; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Sum(); end; {!DOCREF} { @method: function TIntMatrix.Mean(): Double; @desc: Returns the mean of the matrix } function TIntMatrix.Mean(): Double; var i: Integer; begin for i:=0 to High(Self) do Result := Result + Self[i].Mean(); Result := Result / Length(Self); end; {!DOCREF} { @method: function TIntMatrix.Stdev(): Double; @desc: Returns the standard deviation of the matrix } function TIntMatrix.Stdev(): Double; var x,y,i,W,H:Int32; avg:Single; square:TDoubleArray; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); SetLength(square,Self.Width()*Self.Height()); i := -1; for y:=0 to H do for x:=0 to W do Square[inc(i)] := Sqr(Self[y,x] - avg); Result := Sqrt(square.Mean()); end; {!DOCREF} { @method: function TIntMatrix.Variance(): Double; @desc: Return the sample variance. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of the matrix. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean. } function TIntMatrix.Variance(): Double; var avg:Single; x,y,w,h:Int32; begin W := Self.Width() - 1; H := Self.Height() - 1; avg := Self.Mean(); for y:=0 to H do for x:=0 to W do Result := Result + Sqr(Self[y,x] - avg); Result := Result / ((W+1) * (H+1)); end; {!DOCREF} { @method: function TIntMatrix.Mode(): Int64; @desc: Returns the sample mode of the matrix, which is the most frequently occurring value in the matrix. When there are multiple values occurring equally frequently, mode returns the smallest of those values. } function TIntMatrix.Mode(): Int64; begin Result := Self.Merge().Mode(); end; //---------------------------------------------------------------------------------------------------\\ {!DOCREF} { @method: function TIntMatrix.MatrixFromTPAEx(const TPA:TPointArray; Init, Value:Integer; Align:Boolean): TIntMatrix; @desc: Converts a TPA to a matrix, where each element in the TPA will be given a value, and the rest will be the value of c'init'. Align must be true if you want to fir each point to the start of the matrix. } function SimbaExt.MatrixFromTPAEx(const TPA:TPointArray; Init, Value:Integer; Align:Boolean): TIntMatrix; begin Result := exp_TPAToMatrixEx(TPA,Init,Value,Align); end; {!DOCREF} { @method: function se.MatrixFromTPA(const TPA:TPointArray; Value:Int32; Align:Boolean): TIntMatrix; @desc: Converts a TPA to a matrix, where each element in the TPA will be given a value, and the rest will be 0. Align must be true if you want to fir each point to the start of the matrix. } function SimbaExt.MatrixFromTPA(const TPA:TPointArray; Value:Int32; Align:Boolean): TIntMatrix; begin Result := exp_TPAToMatrix(TPA, Value, Align); end; {!DOCREF} { @method: function se.MatrixFromTIA(const Arr:TIntegerArray; Width,Height:Integer): TIntMatrix; @desc: Converts a TIntArray to a TIntMatrix of the given width, and height. } function SimbaExt.MatrixFromTIA(const Arr:TIntegerArray; Width,Height:Integer): TIntMatrix; begin Result := exp_MatFromTIA(Arr, Width, Height); end; {!DOCREF} { @method: procedure TIntMatrix.Padding(HPad,WPad:Integer); @desc: Adds a padding / border around all edges of the matrix. } procedure TIntMatrix.Padding(HPad,WPad:Integer); begin exp_PadMatrix(Self,HPad,WPad); end; {!DOCREF} { @method: function TIntMatrix.FloodFill(const Start:TPoint; EightWay:Boolean): TPointArray; @desc: Follows a value in the matrix and fills the result with all those indices. } function TIntMatrix.FloodFill(const Start:TPoint; EightWay:Boolean): TPointArray; begin Result := exp_FloodFillMatrix(Self, Start, EightWay); end; {------------| GetArea, GetCols, GetRows |------------} {!DOCREF} { @method: function TIntMatrix.Area(X1,Y1,X2,Y2:Int32): TIntMatrix; @desc: Crops the matrix to the given box and returns that area. } function TIntMatrix.Area(X1,Y1,X2,Y2:Int32): TIntMatrix; begin Result := exp_GetArea(Self, X1,Y1,X2,Y2); end; {!DOCREF} { @method: function TIntMatrix.Cols(FromCol, ToCol:Integer): TIntMatrix; @desc: Returns all the wanted columns as a new matrix. } function TIntMatrix.Cols(FromCol, ToCol:Integer): TIntMatrix; begin Result := exp_GetCols(Self, FromCol, ToCol); end; {!DOCREF} { @method: function TIntMatrix.Rows(FromRow, ToRow:Integer): TIntMatrix; @desc: Returns all the wanted rows as a new matrix. } function TIntMatrix.Rows(FromRow, ToRow:Integer): TIntMatrix; begin Result := exp_GetRows(Self, FromRow, ToRow); end; {------------| FlipMat |------------} {!DOCREF} { @method: function TIntMatrix.Rows(FromRow, ToRow:Integer): TIntMatrix; @desc: Order of the items in the array is flipped, meaning x becomes y, and y becomes x. Example: [code=pascal] var x:TIntMatrix; begin x := [[1,2,3],[1,2,3],[1,2,3]]; WriteLn(x.Flip()); end. [/code] >> `[[1, 1, 1], [2, 2, 2], [3, 3, 3]]` } function TIntMatrix.Flip(): TIntMatrix; begin Result := exp_Flip(Self); end; {------------| Indices |------------} {!DOCREF} { @method: function TIntMatrix.Indices(Value: Integer; const Comparator:TComparator): TPointArray; @desc: Returns all the indices which matches the given value, and comperator. EG: c'TPA := Matrix.Indices(10, __LT__)' would return where all the items which are less then 10 is. } function TIntMatrix.Indices(Value: Integer; const Comparator:TComparator): TPointArray; begin Result := exp_Indices(Self, Value, Comparator); end; {!DOCREF} { @method: function TIntMatrix.Indices(Value: Integer; B:TBox; const Comparator:TComparator): TPointArray; overload; @desc: Returns all the indices which matches the given value, and comperator. EG: c'Matrix.Indices(10, __LT__)' would return all the items which are less then 10. Takes an extra param to only check a cirtain area of the matrix. } function TIntMatrix.Indices(Value: Integer; B:TBox; const Comparator:TComparator): TPointArray; overload; begin Result := exp_Indices(Self, B, Value, Comparator); end; {----------------| ArgMin/Max |----------------} //argmax {!DOCREF} { @method: function TIntMatrix.ArgMax(): TPoint; @desc: ArgMax returns the index of the largest item } function TIntMatrix.ArgMax(): TPoint; begin Result := exp_ArgMax(Self); end; {!DOCREF} { @method: function TIntMatrix.ArgMax(Count:Int32): TPointArray; overload; @desc: Returns the n-largest elements, by index } function TIntMatrix.ArgMax(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, True); end; {!DOCREF} { @method: function TIntMatrix.ArgMax(B:TBox): TPoint; overload; @desc: ArgMax returns the index of the largest item within the given bounds c'B' } function TIntMatrix.ArgMax(B:TBox): TPoint; overload; begin Result := exp_ArgMax(Self, B); end; {!DOCREF} { @method: function TIntMatrix.ArgMin(): TPoint; @desc: ArgMin returns the index of the smallest item } function TIntMatrix.ArgMin(): TPoint; begin Result := exp_ArgMin(Self); end; {!DOCREF} { @method: function TIntMatrix.ArgMin(Count:Int32): TPointArray; overload; @desc: Returns the n-smallest elements, by index } function TIntMatrix.ArgMin(Count:Int32): TPointArray; overload; begin Result := exp_ArgMulti(Self, Count, False); end; {!DOCREF} { @method: function TIntMatrix.ArgMin(B:TBox): TPoint; overload; @desc: ArgMin returns the index of the smallest item within the given bounds c'B' } function TIntMatrix.ArgMin(B:TBox): TPoint; overload; begin Result := exp_ArgMin(Self, B); end; {----------------| VarMin/VarMax |----------------} {!DOCREF} { @method: function TIntMatrix.VarMax(): Int32; @desc: ArgMax returns the largest item } function TIntMatrix.VarMax(): Int32; var tmp:TPoint; begin tmp := exp_ArgMax(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TIntMatrix.VarMax(Count:Int32): TIntArray; overload; @desc: Returns the n-largest elements } function TIntMatrix.VarMax(Count:Int32): TIntArray; overload; begin Result := exp_VarMulti(Self, Count, True); end; {!DOCREF} { @method: function TIntMatrix.VarMax(B:TBox): Int32; overload; @desc: ArgMax returns the largest item within the given bounds `B` } function TIntMatrix.VarMax(B:TBox): Int32; overload; var tmp:TPoint; begin tmp := exp_ArgMax(Self, B); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TIntMatrix.VarMin(): Int32; @desc: ArgMin returns the the smallest item } function TIntMatrix.VarMin(): Int32; var tmp:TPoint; begin tmp := exp_ArgMin(Self); Result := Self[tmp.y, tmp.x]; end; {!DOCREF} { @method: function TIntMatrix.VarMin(Count:Int32): TIntArray; overload; @desc: Returns the n-smallest elements } function TIntMatrix.VarMin(Count:Int32): TIntArray; overload; begin Result := exp_VarMulti(Self, Count, False); end; {!DOCREF} { @method: function TIntMatrix.VarMin(B:TBox): Int32; overload; @desc: VarMin returns the smallest item within the given bounds `B` } function TIntMatrix.VarMin(B:TBox): Int32; overload; var tmp:TPoint; begin tmp := exp_ArgMin(Self, B); Result := Self[tmp.y, tmp.x]; end; {------------| MinMax |------------} {!DOCREF} { @method: procedure TIntMatrix.MinMax(var Min, Max:Integer); @desc: Returns the smallest, and the largest element in the matrix. } procedure TIntMatrix.MinMax(var Min, Max:Integer); begin exp_MinMax(Self, Min, Max); end; {------------| CombineMatrix (Math operations) |------------} {!DOCREF} { @method: function TIntMatrix.Combine(Other:TIntMatrix; OP:Char='+'): TIntMatrix; @desc: Merges the two matrices in to one matrix.. Supports different math-operatrions for combining ['+','-','*','/']. [code=pascal] var Mat:TIntMatrix; begin SetLength(Mat, 3); Mat[0] := [1,1,1]; Mat[1] := [2,2,2]; Mat[2] := [3,3,3]; WriteLn( Mat.Combine(Mat, '*') ); end. [/code] Outputs: >>> `[[1, 1, 1], [4, 4, 4], [9, 9, 9]]` } function TIntMatrix.Combine(Other:TIntMatrix; OP:Char='+'): TIntMatrix; begin Result := exp_CombineMatrix(Self, Other, OP); end; {------------| Normalize (Matrix) |------------} {!DOCREF} { @method: function TIntMatrix.Normalize(Alpha, Beta:Int32): TIntMatrix; @desc: Fits each element of the matrix within the values of Alpha and Beta. } function TIntMatrix.Normalize(Alpha, Beta:Int32): TIntMatrix; begin Result := exp_Normalize(Self, Alpha, Beta); end;
{================================================================================================== File: CoreAudio/AudioHardware.h Contains: API for communicating with audio hardware. Version: Technology: Mac OS X Release: Mac OS X Copyright: (c) 1985-2005 by Apple Computer, Inc., all rights reserved. ==================================================================================================} { Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2006 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit AudioHardware; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes, CFRunLoop, CoreAudioTypes; {$ALIGN POWER} //================================================================================================== //#pragma mark Overview {! @header AudioHardware The audio HAL provides an abstraction through which applications can access audio hardware. To do this, the HAL provides a small set of AudioObjects that provide access to the various pieces of the system. AudioObjects all have a set of properties that describe and manipulate their state. A property is accessed via an ordered triple. The first ordinate is the selector which describes the property. The other two ordinates are the scope and element that identify the particular part of the object in which to look for the selector. The AudioObjectPropertyAddress structure encapsulates the property address. The value of a property is an untyped block of data whose content depends on the specifics of the selector. Some selectors also require the use of a qualifier when querying. The qualifier allows for additional information to be provided to be used in the manipulation of the property. Changing the value of a property is always considered asynchronous. Applications use the routines AudioObjectHasProperty(), AudioObjectIsPropertySettable() and AudioObjectGetPropertyDataSize() to find useful meta-information about the property. Apps use AudioObjectGetPropertyData() and AudioObjectSetPropertyData() to manipulate the value of the property. Apps use AudioObjectAddPropertyListener() and AudioObjectRemovePropertyListener() to register/unregister a function that is to be called when a given property's value changes. The class of an AudioObject determines the basic functionality of the object in terms of what functions will operate on it as well as the set of properties that can be expected to be implemented by the object. The set of available classes for objects is limited to those defined here. There are no other classes. The set of classes is arranged in a hierarchy such that one class inherits the properties/routines of it's super class. The base class for all AudioObjects is the class AudioObject. As such, each AudioObject will provide basic properties such as it's class, it's human readable name, and the other AudioObjects it contains. Other important classes include AudioSystemObject, AudioDevice, and AudioStream. The AudioObjects in the HAL are arranged in a containment hierarchy. The root of the hierarchy is the one and only instance of the AudioSystemObject class. The properties of the AudioSystemObject describe the process global settings such as the various default devices and the notification run loop. The AudioSystemObject also contains all the AudioDevices that are available. Instances of the AudioDevice class encapsulate individual audio devices. An AudioDevice serves as the basic unit of IO. It provides a single IO cycle, a timing source based on it, and all the buffers synchronized to it. The IO cycle presents all the synchronized buffers to the client in the same call out along with time stamps that specify the current time, when the input data was acquired and when the output data will be presented. AudioDevices contain instances of the AudioStream class. An AudioStream represents a single buffer of data for transferring across the user/kernel boundary. As such, AudioStreams are the gatekeepers of format information. Each has it's own format and list of available formats. AudioStreams can provide data in any format, including encoded formats and non-audio formats. If the format is a linear PCM format, the data will always be presented as 32 bit, native endian floating point. All conversions to and from the true physical format of the hardware is handled by the device's driver. Both AudioDevices and AudioStreams can contain instances of the AudioControl class or it's many subclasses. An AudioControl provides properties that describe/manipulate a particular aspect of the object such as gain, mute, data source selection, etc. Many common controls are also also available as properties on the AudioDevice or AudioStream. } //================================================================================================== //#pragma mark Error Constants {! @enum Error Constants @abstract The error constants unique to the HAL. @discussion These are the error constants that are unique to the HAL. Note that the HAL's functions can and will return other codes that are not listed here. While these constants give a general idea of what might have gone wrong during the execution of an API call, if an API call returns anything other than kAudioHardwareNoError it is to be viewed as the same failure regardless of what constant is actually returned. @constant kAudioHardwareNoError The function call completed successfully. @constant kAudioHardwareNotRunningError The function call requires that the hardware be running but it isn't. @constant kAudioHardwareUnspecifiedError The function call failed while doing something that doesn't provide any error messages. @constant kAudioHardwareUnknownPropertyError The AudioObject doesn't know about the property at the given address. @constant kAudioHardwareBadPropertySizeError An improperly sized buffer was provided when accessing the data of a property. @constant kAudioHardwareIllegalOperationError The requested operation couldn't be completed. @constant kAudioHardwareBadObjectError The AudioObjectID passed to the function doesn't map to a valid AudioObject. @constant kAudioHardwareBadDeviceError The AudioDeviceID passed to the function doesn't map to a valid AudioDevice. @constant kAudioHardwareBadStreamError The AudioStreamID passed to the function doesn't map to a valid AudioStream. @constant kAudioHardwareUnsupportedOperationError The AudioObject doesn't support the requested operation. @constant kAudioDeviceUnsupportedFormatError The AudioStream doesn't support the requested format. @constant kAudioDevicePermissionsError The requested operation can't be completed because the process doesn't have permission. } const kAudioHardwareNoError = 0; kAudioHardwareNotRunningError = FourCharCode('stop'); kAudioHardwareUnspecifiedError = FourCharCode('what'); kAudioHardwareUnknownPropertyError = FourCharCode('who?'); kAudioHardwareBadPropertySizeError = FourCharCode('!siz'); kAudioHardwareIllegalOperationError = FourCharCode('nope'); kAudioHardwareBadObjectError = FourCharCode('!obj'); kAudioHardwareBadDeviceError = FourCharCode('!dev'); kAudioHardwareBadStreamError = FourCharCode('!str'); kAudioHardwareUnsupportedOperationError = FourCharCode('unop'); kAudioDeviceUnsupportedFormatError = FourCharCode('!dat'); kAudioDevicePermissionsError = FourCharCode('!hog'); //================================================================================================== //#pragma mark Property Support Types {! @typedef AudioObjectPropertySelector @abstract An AudioObjectPropertySelector is a four char code that identifies, along with the AudioObjectPropertyScope and AudioObjectPropertyElement, a specific piece of information about an AudioObject. @discussion The property selector specifies the general classification of the property such as volume, stream format, latency, etc. Note that each class has a different set of selectors. A subclass inherits it's super class's set of selectors, although it may not implement them all. } type AudioObjectPropertySelector = UInt32; {! @typedef AudioObjectPropertyScope @abstract An AudioObjectPropertyScope is a four char code that identifies, along with the AudioObjectPropertySelector and AudioObjectPropertyElement, a specific piece of information about an AudioObject. @discussion The scope specifies the section of the object in which to look for the property, such as input, output, global, etc. Note that each class has a different set of scopes. A subclass inherits it's superclass's set of scopes. } type AudioObjectPropertyScope = UInt32; {! @typedef AudioObjectPropertyElement @abstract An AudioObjectPropertyElement is an integer that identifies, along with the AudioObjectPropertySelector and AudioObjectPropertyScope, a specific piece of information about an AudioObject. @discussion The element selects one of possibly many items in the section of the object in which to look for the property. Elements are number sequentially where 0 represents the master element. Elements are particular to an instance of a class, meaning that two instances can have different numbers of elements in the same scope. There is no inheritance of elements. } type AudioObjectPropertyElement = UInt32; {! @struct AudioObjectPropertyAddress @abstract An AudioObjectPropertyAddress collects the three parts that identify a specific property together in a struct for easy transmission. @field mSelector The AudioObjectPropertySelector for the property. @field mScope The AudioObjectPropertyScope for the property. @field mElement The AudioObjectPropertyElement for the property. } type AudioObjectPropertyAddress = record mSelector: AudioObjectPropertySelector; mScope: AudioObjectPropertyScope; mElement: AudioObjectPropertyElement; end; AudioObjectPropertyAddressPtr = ^AudioObjectPropertyAddress; //================================================================================================== //#pragma mark Property Support Constants {! @enum Property Wildcard Constants @abstract Constants that are used as wildcards in an AudioObjectPropertyAddress. @discussion Wildcards match any and all values for there associated type. They are especially useful for registering listener procs to receive notifications and for querying an AudioObject's list of AudioControls. @constant kAudioObjectPropertySelectorWildcard The wildcard value for AudioObjectPropertySelectors. @constant kAudioObjectPropertyScopeWildcard The wildcard value for AudioObjectPropertyScopes. @constant kAudioObjectPropertyElementWildcard The wildcard value for AudioObjectPropertyElements. @constant kAudioPropertyWildcardPropertyID A synonym for kAudioObjectPropertySelectorWildcard. @constant kAudioPropertyWildcardSection The wildcard value for the isInput argument of AudioDeviceGetPropertyInfo(), AudioDeviceGetProperty(), and AudioDeviceSetProperty(). @constant kAudioPropertyWildcardChannel A synonym for kAudioObjectPropertyElementWildcard. } const kAudioObjectPropertySelectorWildcard = FourCharCode('****'); kAudioObjectPropertyScopeWildcard = FourCharCode('****'); kAudioObjectPropertyElementWildcard = $FFFFFFFF; kAudioPropertyWildcardPropertyID = kAudioObjectPropertySelectorWildcard; kAudioPropertyWildcardSection = $FF; kAudioPropertyWildcardChannel = kAudioObjectPropertyElementWildcard; //================================================================================================== //#pragma mark AudioObject Types {! @typedef AudioClassID @abstract AudioClassIDs are used to identify the class of an AudioObject. } type AudioClassID = UInt32; {! @typedef AudioObjectID @abstract AudioObject is the base class for all the objects in the HAL. @discussion AudioObjects have properties and can contain other AudioObjects. } type AudioObjectID = UInt32; {! @typedef AudioObjectPropertyListenerProc @abstract Clients register an AudioObjectPropertyListenerProc with an AudioObject in order to receive notifications when the properties of the object change. @discussion Listeners will be called when possibly many properties have changed. Consequently, the implementation of a listener must go through the array of addresses to see what exactly has changed. Note that the array of addresses will always have at least one address in it for which the listener is signed up to receive notifications about but may contain addresses for properties for which the listener is not signed up to receive notifications. @param inObjectID The AudioObject whose properties have changed. @param inNumberAddresses The number of elements in the inAddresses array. @param inAddresses An array of AudioObjectPropertyAddresses indicating which properties changed. @param inClientData A pointer to client data established when the listener proc was registered with the AudioObject. @result The return value is currently unused and should always be 0. } type AudioObjectPropertyListenerProc = function( inObjectID: AudioObjectID; inNumberAddresses: UInt32; {const} inAddresses: {variable-size-array} AudioObjectPropertyAddressPtr; inClientData: UnivPtr ): OSStatus; //================================================================================================== //#pragma mark AudioObject Constants {! @enum AudioObject Class Constants @abstract Various constants related to AudioObjects. @constant kAudioObjectPropertyScopeGlobal The AudioObjectPropertyScope for properties that apply to the object as a whole. All AudioObjects have a global scope and for some it is their only scope. @constant kAudioObjectPropertyElementMaster The AudioObjectPropertyElement value for properties that apply to the master element or to the entire scope. @constant kAudioObjectClassID The AudioClassID that identifies the AudioObject class. @constant kAudioObjectClassIDWildcard The wildcard value for AudioClassIDs. @constant kAudioObjectUnknown The AudioObjectID for a non-existant AudioObject. } const kAudioObjectPropertyScopeGlobal = FourCharCode('glob'); kAudioObjectPropertyElementMaster = 0; kAudioObjectClassID = FourCharCode('aobj'); kAudioObjectClassIDWildcard = FourCharCode('****'); kAudioObjectUnknown = 0; //================================================================================================== //#pragma mark AudioObject Properties {! @enum AudioObject Property Selectors @abstract AudioObjectPropertySelector values that apply to all AudioObjects. @constant kAudioObjectPropertyClass An AudioClassID that identifies the class of the AudioObject. @constant kAudioObjectPropertyOwner An AudioObjectID that identifies the the AudioObject that owns the given AudioObject. Note that all AudioObjects are owned by some other AudioObject. The only exception is the AudioSystemObject, for which the value of this property is kAudioObjectUnknown. @constant kAudioObjectPropertyCreator A CFString that contains the bundle ID of the plug-in that instantiated the object. @constant kAudioObjectPropertyObjectName A CFString that contains the human readable name of the object. The caller is responsible for releasing the returned CFObject. @constant kAudioObjectPropertyManufacturer A CFString that contains the human readable name of the manufacturer of the hardware the AudioObject is a part of. The caller is responsible for releasing the returned CFObject. @constant kAudioObjectPropertyElementName A CFString that contains a human readable name for the given element in the given scope. The caller is responsible for releasing the returned CFObject. @constant kAudioObjectPropertyElementCategoryName A CFString that contains a human readable name for the category of the given element in the given scope. The caller is responsible for releasing the returned CFObject. @constant kAudioObjectPropertyElementNumberName A CFString that contains a human readable name for the number of the given element in the given scope. The caller is responsible for releasing the returned CFObject. @constant kAudioObjectPropertyOwnedObjects An array of AudioObjectIDs that represent all the AudioObjects owned by the given object. The qualifier is an array of AudioClassIDs. If it is non-empty, the returned array of AudioObjectIDs will only refer to objects whose class is in the qualifier array or whose is a subclass of one in the qualifier array. @constant kAudioObjectPropertyListenerAdded An AudioObjectPropertyAddress indicating the address to which a new listener was added. Note that this property is not for applications to use. Rather, this property is for the HAL shell to notify AudioObjects implemented by an AudioPlugIn when a listener is added. @constant kAudioObjectPropertyListenerRemoved An AudioObjectPropertyAddress indicating the address to which a listener was removed. Note that this property is not for applications to use. Rather, this property is for the HAL shell to notify AudioObjects implemented by an AudioPlugIn when a listener is removed. } const kAudioObjectPropertyClass = FourCharCode('clas'); kAudioObjectPropertyOwner = FourCharCode('stdv'); kAudioObjectPropertyCreator = FourCharCode('oplg'); kAudioObjectPropertyName = FourCharCode('lnam'); kAudioObjectPropertyManufacturer = FourCharCode('lmak'); kAudioObjectPropertyElementName = FourCharCode('lchn'); kAudioObjectPropertyElementCategoryName = FourCharCode('lccn'); kAudioObjectPropertyElementNumberName = FourCharCode('lcnn'); kAudioObjectPropertyOwnedObjects = FourCharCode('ownd'); kAudioObjectPropertyListenerAdded = FourCharCode('lisa'); kAudioObjectPropertyListenerRemoved = FourCharCode('lisr'); //================================================================================================== //#pragma mark AudioObject Functions {! @functiongroup AudioObject } {! @function AudioObjectShow @abstract Prints to standard out a textural description of the AudioObject. @param inObjectID The AudioObject to show. } procedure AudioObjectShow( inObjectID: AudioObjectID ); external name '_AudioObjectShow'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectHasProperty @abstract Queries an AudioObject about whether or not it has the given property. @param inObjectID The AudioObject to query. @param inAddress An AudioObjectPropertyAddress indicating which property is being queried. @result A Boolean indicating whether or not the AudioObject has the given property. } function AudioObjectHasProperty( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress ): Boolean; external name '_AudioObjectHasProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectIsPropertySettable @abstract Queries an AudioObject about whether or not the given property can be set using AudioObjectSetPropertyData. @param inObjectID The AudioObject to query. @param inAddress An AudioObjectPropertyAddress indicating which property is being queried. @param outIsSettable A Boolean indicating whether or not the property can be set. @result An OSStatus indicating success or failure. } function AudioObjectIsPropertySettable( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; var outIsSettable: Boolean ): OSStatus; external name '_AudioObjectIsPropertySettable'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectGetPropertyDataSize @abstract Queries an AudioObject to find the size of the data for the given property. @param inObjectID The AudioObject to query. @param inAddress An AudioObjectPropertyAddress indicating which property is being queried. @param inQualifierDataSize A UInt32 indicating the size of the buffer pointed to by inQualifierData. Note that not all properties require qualification, in which case this value will be 0. @param inQualifierData, A buffer of data to be used in determining the data of the property being queried. Note that not all properties require qualification, in which case this value will be NULL. @param outDataSize A UInt32 indicating how many bytes the data for the given property occupies. @result An OSStatus indicating success or failure. } function AudioObjectGetPropertyDataSize( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; inQualifierDataSize: UInt32; inQualifierData: {const} UnivPtr; var outDataSize: UInt32 ): OSStatus; external name '_AudioObjectGetPropertyDataSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectGetPropertyData @abstract Queries an AudioObject to get the data of the given property and places it in the provided buffer. @param inObjectID The AudioObject to query. @param inAddress An AudioObjectPropertyAddress indicating which property is being queried. @param inQualifierDataSize A UInt32 indicating the size of the buffer pointed to by inQualifierData. Note that not all properties require qualification, in which case this value will be 0. @param inQualifierData, A buffer of data to be used in determining the data of the property being queried. Note that not all properties require qualification, in which case this value will be NULL. @param ioDataSize A UInt32 which on entry indicates the size of the buffer pointed to by outData and on exit indicates how much of the buffer was used. @param outData The buffer into which the AudioObject will put the data for the given property. @result An OSStatus indicating success or failure. } function AudioObjectGetPropertyData( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; inQualifierDataSize: UInt32; inQualifierData: {const} UnivPtr; var ioDataSize: UInt32; outData: UnivPtr ): OSStatus; external name '_AudioObjectGetPropertyData'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectSetPropertyData @abstract Tells an AudioObject to change the value of the given property using the provided data. @discussion Note that the value of the property should not be considered changed until the HAL has called the listeners as many properties values are changed asynchronously. @param inObjectID The AudioObject to change. @param inAddress An AudioObjectPropertyAddress indicating which property is being changed. @param inQualifierDataSize A UInt32 indicating the size of the buffer pointed to by inQualifierData. Note that not all properties require qualification, in which case this value will be 0. @param inQualifierData, A buffer of data to be used in determining the data of the property being queried. Note that not all properties require qualification, in which case this value will be NULL. @param inDataSize A UInt32 indicating the size of the buffer pointed to by inData. @param inData The buffer containing the data to be used to change the property's value. @result An OSStatus indicating success or failure. } function AudioObjectSetPropertyData( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; inQualifierDataSize: UInt32; inQualifierData: {const} UnivPtr; inDataSize: UInt32; inData: {const} UnivPtr ): OSStatus; external name '_AudioObjectSetPropertyData'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectAddPropertyListener @abstract Registers the given AudioObjectPropertyListenerProc to receive notifications when the given properties change. @param inObjectID The AudioObject to register the listener with. @param inAddress The AudioObjectPropertyAddresses indicating which property the listener should be notified about. @param inListener The AudioObjectPropertyListenerProc to call. @param inClientData A pointer to client data that is passed to the listener when it is called. @result An OSStatus indicating success or failure. } function AudioObjectAddPropertyListener( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; inListener: AudioObjectPropertyListenerProc; inClientData: UnivPtr ): OSStatus; external name '_AudioObjectAddPropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function AudioObjectRemovePropertyListener @abstract Unregisters the given AudioObjectPropertyListenerProc from receiving notifications when the given properties change. @param inObjectID The AudioObject to unregister the listener from. @param inNumberAddresses The number of elements in the inAddresses array. @param inAddresses The AudioObjectPropertyAddress indicating which property the listener should be removed from. @param inListener The AudioObjectPropertyListenerProc being removed. @param inClientData A pointer to client data that is passed to the listener when it is called. @result An OSStatus indicating success or failure. } function AudioObjectRemovePropertyListener( inObjectID: AudioObjectID; const (*var*) inAddress: AudioObjectPropertyAddress; inListener: AudioObjectPropertyListenerProc; inClientData: UnivPtr ): OSStatus; external name '_AudioObjectRemovePropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) //================================================================================================== //#pragma mark AudioControl Constants {! @enum AudioControl Base Class IDs @abstract The AudioClassIDs that identify the various AudioControl base classes. @constant kAudioControlClassID The AudioClassID that identifies the AudioControl class. @constant kAudioLevelControlClassID The AudioClassID that identifies the AudioLevelControl class which is a subclass of AudioControl. AudioLevelControls manipulate gain/attenuation stages in the hardware. @constant kAudioBooleanControlClassID The AudioClassID that identifies the AudioBooleanControl class which is a subclass of AudioControl. AudioBooleanControls manipulate on/off switches in the hardware. @constant kAudioSelectorControlClassID The AudioClassID that identifies the AudioSelectorControl class which is a subclass of AudioControl. AudioSelectorControls manipulate controls that have multiple, but discreet values. @constant kAudioStereoPanControlClassID The AudioClassID that identifies the AudioStereoPanControl class which is a subclass of AudioControl. AudioStereoPanControls manipulate the pot for panning a mono signal between a left/right pair of outputs. } const kAudioControlClassID = FourCharCode('actl'); kAudioLevelControlClassID = FourCharCode('levl'); kAudioBooleanControlClassID = FourCharCode('togl'); kAudioSelectorControlClassID = FourCharCode('slct'); kAudioStereoPanControlClassID = FourCharCode('span'); {! @enum AudioLevelControl Subclass IDs @abstract The four char codes that identify the various standard subclasses of AudioLevelControl. @constant kAudioVolumeControlClassID An AudioLevelControl for a general gain/attenuation stage. @constant kAudioLFEVolumeControlClassID An AudioLevelControl for an LFE channel that results from bass management such as the iSub. Note that LFE channels that are represented as normal audio channels (in other words, real data is being fed them in an IOProc) will use kAudioVolumeControlClassID to manipulate the level. @constant kAudioBootChimeVolumeControlClassID An AudioLevelControl for the boot chime of the CPU. } const kAudioVolumeControlClassID = FourCharCode('vlme'); kAudioLFEVolumeControlClassID = FourCharCode('subv'); kAudioBootChimeVolumeControlClassID = FourCharCode('pram'); {! @enum AudioBooleanControl Subclass IDs @abstract The four char codes that identify the various standard subclasses of AudioBooleanControl. @constant kAudioMuteControlClassID An AudioBooleanControl where a true value means that mute is enabled making that element inaudible. @constant kAudioSoloControlClassID An AudioBooleanControl where a true value means that solo is enabled making just that element audible and the other elements inaudible. @constant kAudioJackControlClassID An AudioBooleanControl where a true value means something is plugged into that element. @constant kAudioLFEMuteControlClassID An AudioBooleanControl where true means that mute is enabled make that LFE element inaudible. This control is for LFE channels that result from bass management such as the iSub. Note that LFE channels that are represented as normal audio channels (in other words, real data is being fed them in an IOProc) will use kAudioVolumeControlClassID to manipulate mute. @constant kAudioISubOwnerClassID An AudioBooleanControl where true means that the AudioDevice that ultimately owns the control also owns any iSub attached to the CPU. } const kAudioMuteControlClassID = FourCharCode('mute'); kAudioSoloControlClassID = FourCharCode('solo'); kAudioJackControlClassID = FourCharCode('jack'); kAudioLFEMuteControlClassID = FourCharCode('subm'); kAudioISubOwnerControlClassID = FourCharCode('atch'); {! @enum AudioSelectorControl Subclass IDs @abstract The four char codes that identify the various standard subclasses of AudioSelectorControl. @constant kAudioDataSourceControlClassID An AudioSelectorControl that identifies where the data for the element is coming from. @constant kAudioDataDestinationControlClassID An AudioSelectorControl that identifies where the data for the element is going. @constant kAudioClockSourceControlClassID An AudioSelectorControl that identifies where the timing info for the object is coming from. @constant kAudioLineLevelControlClassID An AudioSelectorControl that identifies the nominal line level for the element. Note that this is not a gain stage but rather indicating the voltage standard (if any) used for the element, such as +4dBu, -10dBV, instrument, etc. } const kAudioDataSourceControlClassID = FourCharCode('dsrc'); kAudioDataDestinationControlClassID = FourCharCode('dest'); kAudioClockSourceControlClassID = FourCharCode('clck'); kAudioLineLevelControlClassID = FourCharCode('nlvl'); //================================================================================================== //#pragma mark AudioControl Properties {! @enum AudioControl Properties @abstract AudioObjectPropertySelector values that apply to all AudioControls. @discussion AudioControl is a subclass of AudioObject and has only the single scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioControlPropertyScope The AudioObjectPropertyScope in the owning AudioObject that contains the AudioControl. @constant kAudioControlPropertyElement The AudioObjectPropertyElement in the owning AudioObject that contains the AudioControl. @constant kAudioControlPropertyVariant A UInt32 that identifies the specific variant of an AudioControl. This allows the owning AudioObject to support controls that are of the same basic class (that is, the values of kAudioObjectPropertyClass are the same) but may control a part of the object for which the standard controls do not control. } const kAudioControlPropertyScope = FourCharCode('cscp'); kAudioControlPropertyElement = FourCharCode('celm'); kAudioControlPropertyVariant = FourCharCode('cvar'); {! @enum AudioLevelControl Properties @abstract AudioObjectPropertySelector values that apply to all AudioLevelControls. @discussion AudioLevelControl is a subclass of AudioControl and has only the single scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioLevelControlPropertyScalarValue A Float32 that represents the value of the boot chime volume control. The range is between 0.0 and 1.0 (inclusive). @constant kAudioLevelControlPropertyDecibelValue A Float32 that represents the value of the boot chime volume control in dB. @constant kAudioLevelControlPropertyDecibelRange An AudioValueRange that contains the minimum and maximum dB values the boot chime control can have. @constant kAudioLevelControlPropertyConvertScalarToDecibels A Float32 that on input contains a scalar volume value for the boot chime and on exit contains the equivalent dB value. @constant kAudioLevelControlPropertyConvertDecibelsToScalar A Float32 that on input contains a dB volume value for the boot chime and on exit contains the equivalent scalar value. } const kAudioLevelControlPropertyScalarValue = FourCharCode('lcsv'); kAudioLevelControlPropertyDecibelValue = FourCharCode('lcdv'); kAudioLevelControlPropertyDecibelRange = FourCharCode('lcdr'); kAudioLevelControlPropertyConvertScalarToDecibels = FourCharCode('lcsd'); kAudioLevelControlPropertyConvertDecibelsToScalar = FourCharCode('lcds'); {! @enum AudioBooleanControl Properties @abstract AudioObjectPropertySelector values that apply to all AudioBooleanControls. @discussion AudioBooleanControl is a subclass of AudioControl and has only the single scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioBooleanControlPropertyValue A UInt32 where 0 means false and 1 means true. } const kAudioBooleanControlPropertyValue = FourCharCode('bcvl'); {! @enum AudioSelectorControl Properties @abstract AudioObjectPropertySelector values that apply to all AudioSelectorControls. @discussion AudioSelectorControl is a subclass of AudioControl and has only the single scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioSelectorControlPropertyCurrentItem A UInt32 that is the ID of the item currently selected. @constant kAudioSelectorControlPropertyAvailableItems An array of UInt32s that represent the IDs of all the items available. @constant kAudioSelectorControlPropertyItemName This property translates the given item ID into a human readable name. The qualifier contains the ID of the item to be translated and name is returned as a CFString as the property data. The caller is responsible for releasing the returned CFObject. } const kAudioSelectorControlPropertyCurrentItem = FourCharCode('scci'); kAudioSelectorControlPropertyAvailableItems = FourCharCode('scai'); kAudioSelectorControlPropertyItemName = FourCharCode('scin'); {! @enum AudioClockSourceControl Properties @abstract AudioObjectPropertySelector values that apply only to AudioClockSourceControls. @discussion These properties supplement the regular AudioSelectorControl Properties. @constant kAudioClockSourceControlPropertyItemKind This property returns a UInt32 that identifies the kind of clock source the item ID refers to. The qualifier contains the ID of the item. Values for this property are defined in <IOAudio/audio/IOAudioTypes.h>. } const kAudioClockSourceControlPropertyItemKind = FourCharCode('clkk'); {! @enum AudioStereoPanControl Properties @abstract AudioObjectPropertySelector values that apply to all AudioStereoPanControls. @discussion AudioStereoPanControl is a subclass of AudioControl and has only the single scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioStereoPanControlPropertyValue A Float32 where 0.0 is full left, 1.0 is full right, and 0.5 is center. @constant kAudioStereoPanControlPropertyPanningChannels An array of two UInt32s that indicate which elements of the owning object the signal is being panned between. } const kAudioStereoPanControlPropertyValue = FourCharCode('spcv'); kAudioStereoPanControlPropertyPanningChannels = FourCharCode('spcc'); //================================================================================================== //#pragma mark AudioSystemObject Types {! @typedef AudioHardwarePropertyID @abstract An AudioHardwarePropertyID is a integer that identifies a specific piece of information about the AudioSystemObject. } type AudioHardwarePropertyID = AudioObjectPropertySelector; {! @typedef AudioHardwarePropertyListenerProc @abstract Clients register an AudioHardwarePropertyListenerProc with the AudioSystemObject in order to receive notifications when the properties of the object change. @discussion Note that the same functionality is provided by AudioObjectPropertyListenerProc. @param inPropertyID The AudioHardwarePropertyID of the property that changed. @param inClientData A pointer to client data established when the listener proc was registered with the AudioSystemObject. @result The return value is currently unused and should always be 0. } type AudioHardwarePropertyListenerProc = function( inPropertyID: AudioHardwarePropertyID; inClientData: UnivPtr ): OSStatus; //================================================================================================== //#pragma mark AudioSystemObject Constants {! @enum AudioSystemObject Class Constants @abstract Various constants related to the AudioSystemObject. @constant kAudioSystemObjectClassID The AudioClassID that identifies the AudioSystemObject class. @constant kAudioObjectSystemObject The AudioObjectID that always refers to the one and only instance of the AudioSystemObject. } const kAudioSystemObjectClassID = FourCharCode('asys'); kAudioObjectSystemObject = 1; //================================================================================================== //#pragma mark AudioSystemObject Properties {! @enum AudioSystemObject Properties @abstract AudioObjectPropertySelector values that apply to the AudioSystemObject. @discussion The AudioSystemObject has one scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioHardwarePropertyProcessIsMaster A UInt32 where 1 means that the current process contains the master instance of the HAL. The master instance of the HAL is the only instance in which plug-ins should save/restore their devices' settings. @constant kAudioHardwarePropertyIsInitingOrExiting A UInt32 whose value will be non-zero if the HAL is either in the midst of initializing or in the midst of exiting the process. @constant kAudioHardwarePropertyDevices An array of the AudioDeviceIDs that represent all the devices currently available to the system. @constant kAudioHardwarePropertyDefaultInputDevice The AudioDeviceID of the default input AudioDevice. @constant kAudioHardwarePropertyDefaultOutputDevice The AudioDeviceID of the default output AudioDevice. @constant kAudioHardwarePropertyDefaultOutputDevice The AudioDeviceID of the output AudioDevice to use for system related sound from the alert sound to digital call progress. @constant kAudioHardwarePropertyDeviceForUID Using an AudioValueTranslation structure, this property translates the input CFStringRef containing a UID into the AudioDeviceID that refers to the AudioDevice with that UID. This property will return kAudioDeviceUnknown if the given UID does not match any currently available AudioDevice. @constant kAudioHardwarePropertySleepingIsAllowed A UInt32 where 1 means that the process will allow the CPU to idle sleep even if there is audio IO in progress. A 0 means that the CPU will not be allowed to idle sleep. Note that this property won't affect when the CPU is forced to sleep. @constant kAudioHardwarePropertyUnloadingIsAllowed A UInt32 where 1 means that this process wants the HAL to unload itself after a period of inactivity where there are no IOProcs and no listeners registered with any AudioObject. @constant kAudioHardwarePropertyHogModeIsAllowed A UInt32 where 1 means that this process wants the HAL to automatically take hog mode and 0 means that the HAL should not automatically take hog mode on behalf of the process. Processes that only ever use the default device are the sort of that should set this property's value to 0. @constant kAudioHardwarePropertyRunLoop The CFRunLoopRef the HAL is currently attaching all of it's system notification handlers to. By default, the HAL will create and manage it's own thread for this job. Clients can set this property to tell the HAL to use a thread of the client's choosing. The caller is responsible for releasing the returned CFObject. @constant kAudioHardwarePropertyPlugInForBundleID Using an AudioValueTranslation structure, this property translates the input CFString containing a bundle ID into the AudioObjectID of the AudioPlugIn that corresponds to it. This property will return kAudioObjectUnkown if the given bundle ID doesn't match any AudioPlugIns. } const kAudioHardwarePropertyProcessIsMaster = FourCharCode('mast'); kAudioHardwarePropertyIsInitingOrExiting = FourCharCode('inot'); kAudioHardwarePropertyDevices = FourCharCode('dev#'); kAudioHardwarePropertyDefaultInputDevice = FourCharCode('dIn '); kAudioHardwarePropertyDefaultOutputDevice = FourCharCode('dOut'); kAudioHardwarePropertyDefaultSystemOutputDevice = FourCharCode('sOut'); kAudioHardwarePropertyDeviceForUID = FourCharCode('duid'); kAudioHardwarePropertySleepingIsAllowed = FourCharCode('slep'); kAudioHardwarePropertyUnloadingIsAllowed = FourCharCode('unld'); kAudioHardwarePropertyHogModeIsAllowed = FourCharCode('hogr'); kAudioHardwarePropertyRunLoop = FourCharCode('rnlp'); kAudioHardwarePropertyPlugInForBundleID = FourCharCode('pibi'); {! @enum AudioSystemObject Properties Implemented via AudioControl objects @abstract AudioObjectPropertySelector values for AudioSystemObject properties that are implemented by AudioControl objects. @discussion These properties are also accessible by locating the AudioControl object attached to the AudioSystemObject and using that object to access the properties of the control. @constant kAudioHardwarePropertyBootChimeVolumeScalar A Float32 that represents the value of the boot chime volume control. The range is between 0.0 and 1.0 (inclusive). This property is implemented by an AudioControl object that is a subclass of AudioBootChimeVolumeControl. @constant kAudioHardwarePropertyBootChimeVolumeDecibels A Float32 that represents the value of the boot chime volume control in dB. This property is implemented by an AudioControl object that is a subclass of AudioBootChimeVolumeControl. @constant kAudioHardwarePropertyBootChimeVolumeRangeDecibels An AudioValueRange that contains the minimum and maximum dB values the boot chime control can have. This property is implemented by an AudioControl object that is a subclass of AudioBootChimeVolumeControl. @constant kAudioHardwarePropertyBootChimeVolumeScalarToDecibels A Float32 that on input contains a scalar volume value for the boot chime and on exit contains the equivalent dB value. This property is implemented by an AudioControl object that is a subclass of AudioBootChimeVolumeControl. @constant kAudioHardwarePropertyBootChimeVolumeDecibelsToScalar A Float32 that on input contains a dB volume value for the boot chime and on exit contains the equivalent scalar value. This property is implemented by an AudioControl object that is a subclass of AudioBootChimeVolumeControl. } const kAudioHardwarePropertyBootChimeVolumeScalar = FourCharCode('bbvs'); kAudioHardwarePropertyBootChimeVolumeDecibels = FourCharCode('bbvd'); kAudioHardwarePropertyBootChimeVolumeRangeDecibels = FourCharCode('bbd#'); kAudioHardwarePropertyBootChimeVolumeScalarToDecibels = FourCharCode('bv2d'); kAudioHardwarePropertyBootChimeVolumeDecibelsToScalar = FourCharCode('bd2v'); //================================================================================================== //#pragma mark AudioSystemObject Functions {! @functiongroup AudioSystemObject } {! @function AudioHardwareAddRunLoopSource @abstract Add the given CFRunLoopSource to the the HAL's notification CFRunLoop. @discussion The CFRunLoop the HAL uses for notifications is specified by kAudioHardwarePropertyRunLoop. If kAudioHardwarePropertyRunLoop changes, CFRunLoopSources added with this function will automatically be transferred to the new CFRunLoop. @param inRunLoopSource The CFRunLoopSource to add. @result An OSStatus indicating success or failure. } function AudioHardwareAddRunLoopSource( inRunLoopSource: CFRunLoopSourceRef ): OSStatus; external name '_AudioHardwareAddRunLoopSource'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {! @function AudioHardwareRemoveRunLoopSource @abstract Remove the given CFRunLoopSource from the the HAL's notification CFRunLoop. @discussion The CFRunLoop the HAL uses for notifications is specified by kAudioHardwarePropertyRunLoop. @param inRunLoopSource The CFRunLoopSource to remove. @result An OSStatus indicating success or failure. } function AudioHardwareRemoveRunLoopSource( inRunLoopSource: CFRunLoopSourceRef ): OSStatus; external name '_AudioHardwareRemoveRunLoopSource'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {! @function AudioHardwareUnload @abstract When this routine is called, all IO on all devices within a process will be terminated and all resources capable of being released will be released. This routine essentially returns the HAL to it's uninitialized state. @result An OSStatus indicating success or failure. } function AudioHardwareUnload: OSStatus; external name '_AudioHardwareUnload'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioHardwareGetPropertyInfo @abstract Retrieve information about the given property. @discussion Note that the same functionality is provided by the functions AudioObjectHasProperty(), AudioObjectIsPropertySettable(), and AudioObjectGetPropertyDataSize(). @param inPropertyID The AudioHardwarePropertyID of the property to query. @param outSize A pointer to a UInt32 that receives the size of the property data in bytes on exit. This can be NULL if the size information is not being requested. @param outWritable A pointer to a Boolean that receives indication of whether or not the given property can be set. This can be NULL if the writability is not being requested. @result An OSStatus indicating success or failure. } function AudioHardwareGetPropertyInfo( inPropertyID: AudioHardwarePropertyID; outSize: UInt32Ptr; outWritable: BooleanPtr ): OSStatus; external name '_AudioHardwareGetPropertyInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioHardwareGetProperty @abstract Queries an the AudioSystemObject to get the data of the given property and places it in the provided buffer. @discussion Note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inPropertyID The AudioHardwarePropertyID of the property to query. @param ioDataSize A UInt32 which on entry indicates the size of the buffer pointed to by outData and on exit indicates how much of the buffer was used. @param outData The buffer into which the AudioSystemObject will put the data for the given property. @result An OSStatus indicating success or failure. } function AudioHardwareGetProperty( inPropertyID: AudioHardwarePropertyID; var ioPropertyDataSize: UInt32; outPropertyData: UnivPtr ): OSStatus; external name '_AudioHardwareGetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioHardwareSetProperty @abstract Tells the AudioSystemObject to change the value of the given property using the provided data. @discussion Note that the value of the property should not be considered changed until the HAL has called the listeners as many properties values are changed asynchronously. Also note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inPropertyID The AudioHardwarePropertyID of the property to change. @param inDataSize A UInt32 indicating the size of the buffer pointed to by inData. @param inData The buffer containing the data to be used to change the property's value. @result An OSStatus indicating success or failure. } function AudioHardwareSetProperty( inPropertyID: AudioHardwarePropertyID; inPropertyDataSize: UInt32; inPropertyData: {const} UnivPtr ): OSStatus; external name '_AudioHardwareSetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioHardwareAddPropertyListener @abstract Registers the given AudioHardwarePropertyListenerProc to receive notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectAddPropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inPropertyID The AudioHardwarePropertyID of the property to listen to. @param inProc AudioHardwarePropertyListenerProc to call. @param inClientData A pointer to client data that is passed to the listener when it is called. @result An OSStatus indicating success or failure. } function AudioHardwareAddPropertyListener( inPropertyID: AudioHardwarePropertyID; inProc: AudioHardwarePropertyListenerProc; inClientData: UnivPtr ): OSStatus; external name '_AudioHardwareAddPropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioHardwareRemovePropertyListener @abstract Unregisters the given AudioHardwarePropertyListenerProc from receive notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectRemovePropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inPropertyID The AudioHardwarePropertyID of the property to stop listening to. @param inProc AudioHardwarePropertyListenerProc to unregister. @result An OSStatus indicating success or failure. } function AudioHardwareRemovePropertyListener( inPropertyID: AudioHardwarePropertyID; inProc: AudioHardwarePropertyListenerProc ): OSStatus; external name '_AudioHardwareRemovePropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) //================================================================================================== //#pragma mark AudioPlugIn Constants {! @enum AudioPlugIn Class Constants @abstract Various constants related to AudioPlugIns. @constant kAudioPlugInClassID The AudioClassID that identifies the AudioPlugIn class. } const kAudioPlugInClassID = FourCharCode('aplg'); //================================================================================================== //#pragma mark AudioPlugIn Properties {! @enum AudioPlugIn Properties @abstract AudioObjectPropertySelector values that apply to AudioPlugIns. @discussion AudioPlugIn is a subclass of AudioObject that represents a plug-in loaded by the HAL that conforms to the API in <CoreAudio/AudioHardwarePlugIn.h>. AudioPlugIns have one scope, kAudioObjectPropertyScopeGlobal, and only a master element. @constant kAudioPlugInPropertyBundleID A CFString that contains the bundle identifier for the AudioPlugIn. The caller is responsible for releasing the returned CFObject. @constant kAudioPlugInCreateAggregateDevice This property is used to tell a plug-in to create a new AudioAggregateDevice. It's value is only read. The qualifier data for this property is a CFDictionary containing a description of the AudioAggregateDevice to create. The keys for the CFDictionary are defined in the AudioAggregateDevice Constants section. The value of the property that gets returned is the AudioObjectID of the newly created device. @constant kAudioPlugInDestroyAggregateDevice This property is used to tell a plug-in to destroy an AudioAggregateDevice. Like kAudioPlugInCreateAggregateDevice, this property is read only. The value of the property is the AudioObjectID of the AudioAggregateDevice to destroy. } const kAudioPlugInPropertyBundleID = FourCharCode('piid'); kAudioPlugInCreateAggregateDevice = FourCharCode('cagg'); kAudioPlugInDestroyAggregateDevice = FourCharCode('dagg'); //================================================================================================== //#pragma mark AudioDevice Types {! @typedef AudioDeviceID @abstract AudioDevice is the base class for all objects that represent an audio device. @discussion AudioDevice is a subclass of AudioObject. AudioDevices normally contain AudioStreams and AudioControls, but may contain other things depending on the kind of AudioDevice (e.g. aggregate devices contain other AudioDevices). } type AudioDeviceID = AudioObjectID; {! @typedef AudioDevicePropertyID @abstract An AudioDevicePropertyID is an integer that identifies a specific piece of information about the object. } type AudioDevicePropertyID = AudioObjectPropertySelector; {! @struct AudioHardwareIOProcStreamUsage @abstract This structure describes which streams a given AudioDeviceIOProc will use. It is used in conjunction with kAudioDevicePropertyIOProcStreamUsage. @field mIOProc The IOProc whose stream usage is being specified. @field mNumberStreams The number of streams being specified. @field mStreamIsOn An array of UInt32's whose length is specified by mNumberStreams. Each element of the array corresponds to a stream. A value of 0 means the stream is not to be enabled. Any other value means the stream is to be used. } type AudioHardwareIOProcStreamUsage = record mIOProc: UnivPtr; mNumberStreams: UInt32; mStreamIsOn: array[0..0] of UInt32; end; {! @typedef AudioDeviceIOProc @abstract An AudioDeviceIOProc is called by an AudioDevice to provide input data read from the device and collect output data to be written to the device for the current IO cycle. @param inDevice The AudioDevice doing the IO. @param inNow An AudioTimeStamp that indicates the IO cycle started. Note that this time includes any scheduling latency that may have been incurred waking the thread on which IO is being done. @param inInputData An AudioBufferList containing the input data for the current IO cycle. For streams that are disabled, the AudioBuffer's mData field will be NULL but the mDataByteSize field will still say how much data would have been there if it was enabled. Note that the contents of this structure should never be modified. @param inInputTime An AudioTimeStamp that indicates the time at which the first frame in the data was acquired from the hardware. If the device has no input streams, the time stamp will be zeroed out. @param outOutputData An AudioBufferList in which the output data for the current IO cycle is to be placed. On entry, each AudioBuffer's mDataByteSize field indicates the maximum amount of data that can be placed in the buffer and the buffer's memory has been zeroed out. For formats where the number of bytes per packet can vary (as with AC-3, for example), the client has to fill out on exit each mDataByteSize field in each AudioBuffer with the amount of data that was put in the buffer. Otherwise, the mDataByteSize field should not be changed. For streams that are disabled, the AudioBuffer's mData field will be NULL but the mDataByteSize field will still say how much data would have been there if it was enabled. Except as noted above, the contents of this structure should not other wise be modified. @param inOutputTime An AudioTimeStamp that indicates the time at which the first frame in the data will be passed to the hardware. If the device has no output streams, the time stamp will be zeroed out. @param inClientData A pointer to client data established when the AudioDeviceIOProc was registered with the AudioDevice. @result The return value is currently unused and should always be 0. } type AudioDeviceIOProc = function( inDevice: AudioDeviceID; const (*var*) inNow: AudioTimeStamp; const (*var*) inInputData: AudioBufferList; const (*var*) inInputTime: AudioTimeStamp; var outOutputData: AudioBufferList; const (*var*) inOutputTime: AudioTimeStamp; inClientData: UnivPtr ): OSStatus; {! @typedef AudioDevicePropertyListenerProc @abstract Clients register an AudioDevicePropertyListenerProc with the AudioDevice object in order to receive notifications when the properties of the object change. @discussion Note that the same functionality is provided by AudioObjectPropertyListenerProc. @param inDevice The AudioDevice whose property has changed. @param inChannel The channel of the property that changed where 0 is the master channel. @param isInput Which section of the AudioDevice changed. @param inPropertyID The AudioDevicePropertyID of the property that changed. @param inClientData A pointer to client data established when the listener proc was registered with the object. @result The return value is currently unused and should always be 0. } type AudioDevicePropertyListenerProc = function( inDevice: AudioDeviceID; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; inClientData: UnivPtr ): OSStatus; //================================================================================================== //#pragma mark AudioDevice Constants {! @enum AudioDevice Class Constants @abstract Various constants related to AudioDevices. @constant kAudioDevicePropertyScopeInput The AudioObjectPropertyScope for properties that apply to the input signal paths of the AudioDevice. @constant kAudioDevicePropertyScopeOutput The AudioObjectPropertyScope for properties that apply to the output signal paths of the AudioDevice. @constant kAudioDevicePropertyScopePlayThrough The AudioObjectPropertyScope for properties that apply to the play through signal paths of the AudioDevice. @constant kAudioDeviceClassID The AudioClassID that identifies the AudioDevice class. @constant kAudioDeviceUnknown The AudioObjectID for a nonexistent AudioObject. } const kAudioDevicePropertyScopeInput = FourCharCode('inpt'); kAudioDevicePropertyScopeOutput = FourCharCode('outp'); kAudioDevicePropertyScopePlayThrough = FourCharCode('ptru'); kAudioDeviceClassID = FourCharCode('adev'); kAudioDeviceUnknown = kAudioObjectUnknown; {! @enum StartAtTime/GetNearestStartTime Flags @abstract The flags that can be passed to control the behavior of AudioDeviceStartAtTime() andAudioDeviceGetNearestStartTime(). @constant kAudioDeviceStartTimeIsInputFlag Set to indicate that the requested time refers to an input time. Clear to indicate that it is an output time. @constant kAudioDeviceStartTimeDontConsultDeviceFlag Set to indicate that the device should not be consulted when determining the start time. Clear to indicate that the device should be consulted. This flag cannot be set if kAudioDeviceStartTimeDontConsultHALFlag is set. @constant kAudioDeviceStartTimeDontConsultHALFlag Set to indicate that the HAL should not be consulted when determining the start time. Clear to indicate that the HAL should be consulted. This flag cannot be set if kAudioDeviceStartTimeDontConsultDeviceFlag is set. } const kAudioDeviceStartTimeIsInputFlag = 1 shl 0; kAudioDeviceStartTimeDontConsultDeviceFlag = 1 shl 1; kAudioDeviceStartTimeDontConsultHALFlag = 1 shl 2; //================================================================================================== //#pragma mark AudioDevice Properties {! @enum AudioDevice Properties @abstract AudioObjectPropertySelector values that apply to AudioDevice objects. @discussion AudioDevices have four scopes: kAudioDevicePropertyScopeGlobal, kAudioDevicePropertyScopeInput, kAudioDevicePropertyScopeOutput, and kAudioDevicePropertyScopePlayThrough. They have a master element and an element for each channel in each stream numbered according to the starting channel number of each stream. @constant kAudioDevicePropertyPlugIn An OSStatus that contains any error codes generated by loading the IOAudio driver plug-in for the AudioDevice or kAudioHardwareNoError if the plug-in loaded successfully. This property only exists for IOAudio-based AudioDevices whose driver has specified a plug-in to load. @constant kAudioDevicePropertyConfigurationApplication A CFString that contains the bundle ID for an application that provides a GUI for configuring the AudioDevice. By default, the value of this property is the bundle ID for Audio MIDI Setup. The caller is responsible for releasing the returned CFObject. @constant kAudioDevicePropertyDeviceUID A CFString that contains a persistent identifier for the AudioDevice. An AudioDevice's UID is persistent across boots. The content of the UID string is a black box and may contain information that is unique to a particular instance of an AudioDevice's hardware or unique to the CPU. Therefore they are not suitable for passing between CPUs or for identifying similar models of hardware. @constant kAudioDevicePropertyModelUID A CFString that contains a persistent identifier for the model of an AudioDevice. The identifier is unique such that the identifier from two AudioDevices are equal if and only if the two AudioDevices are the exact same model from the same manufacturer. Further, the identifier has to be the same no matter on what machine the AudioDevice appears. @constant kAudioDevicePropertyTransportType A UInt32 whose value indicates how the AudioDevice is connected to the CPU. Constants for some of the values for this property can be found in <IOKit/audio/IOAudioTypes.h>. @constant kAudioDevicePropertyRelatedDevices An array of AudioDeviceIDs for devices related to the AudioDevice. For IOAudio-based devices, a AudioDevices are related if they share the same IOAudioDevice object. @constant kAudioDevicePropertyClockDomain A UInt32 whose value indicates the clock domain to which this AudioDevice belongs. AudioDevices that have the same value for this property are able to be synchronized in hardware. However, a value of 0 indicates that the clock domain for the device is unspecified and should be assumed to be separate from every other device's clock domain, even if they have the value of 0 as their clock domain as well. @constant kAudioDevicePropertyDeviceIsAlive A UInt32 where a value of 1 means the device is ready and available and 0 means the device is usable and will most likely go away shortly. @constant kAudioDevicePropertyDeviceHasChanged The type of this property is a UInt32, but it's value has no meaning. This property exists so that clients can listen to it and be told when the configuration of the AudioDevice has changed in ways that cannot otherwise be conveyed through other notifications. In response to this notification, clients should re-evaluate everything they need to know about the device, particularly the layout and values of the controls. @constant kAudioDevicePropertyDeviceIsRunning A UInt32 where a value of 0 means the AudioDevice is not performing IO and a value of 1 means that it is. Note that the device can be running even if there are no active IOProcs such as by calling AudioDeviceStart() and passing a NULL IOProc. Note that the notification for this property is usually sent from the AudioDevice's IO thread. @constant kAudioDevicePropertyDeviceIsRunningSomewhere A UInt32 where 1 means that the AudioDevice is running in at least one process on the system and 0 means that it isn't running at all. @constant kAudioDevicePropertyDeviceCanBeDefaultDevice A UInt32 where 1 means that the AudioDevice is a possible selection for kAudioHardwarePropertyDefaultInputDevice or kAudioHardwarePropertyDefaultOutputDevice depending on the scope. @constant kAudioDevicePropertyDeviceCanBeDefaultSystemDevice A UInt32 where 1 means that the AudioDevice is a possible selection for kAudioHardwarePropertyDefaultSystemOutputDevice. @constant kAudioDeviceProcessorOverload A UInt32 where the value has no meaning. This property exists so that clients can be notified when the AudioDevice detects that an IO cycle has run past it's deadline. Note that the notification for this property is usually sent from the AudioDevice's IO thread. @constant kAudioDevicePropertyHogMode A pid_t indicating the process that currently owns exclusive access to the AudioDevice or a value of -1 indicating that the device is currently available to all processes. If the AudioDevice is in a non-mixable mode, the HAL will automatically take hog mode on behalf of the first process to start an IOProc. @constant kAudioDevicePropertyLatency A UInt32 containing the number of frames of latency in the AudioDevice. Note that input and output latency may differ. Further, the AudioDevice's AudioStreams may have additional latency so they should be queried as well. If both the device and the stream say they have latency, then the total latency for the stream is the device latency summed with the stream latency. @constant kAudioDevicePropertyBufferFrameSize A UInt32 whose value indicates the number of frames in the IO buffers. @constant kAudioDevicePropertyBufferFrameSizeRange An AudioValueRange indicating the minimum and maximum values, inclusive, for kAudioDevicePropertyBufferFrameSize. @constant kAudioDevicePropertyUsesVariableBufferFrameSizes A UInt32 that, if implemented by a device, indicates that the sizes of the buffers passed to an IOProc will vary by a small amount. The value of this property will indicate the largest buffer that will be passed and kAudioDevicePropertyBufferFrameSize will indicate the smallest buffer that will get passed to the IOProc. The usage of this property is narrowed to only allow for devices whose buffer sizes vary by small amounts greater than kAudioDevicePropertyBufferFrameSize. It is not intended to be a license for devices to be able to send buffers however they please. Rather, it is intended to allow for hardware whose natural rhythms lead to this necessity. @constant kAudioDevicePropertyStreams An array of AudioStreamIDs that represent the AudioStreams of the AudioDevice. Note that if a notification is received for this property, any cached AudioStreamIDs for the device become invalid and need to be re-fetched. @constant kAudioDevicePropertySafetyOffset A UInt32 whose value indicates the number for frames in ahead (for output) or behind (for input the current hardware position that is safe to do IO. @constant kAudioDevicePropertyIOCycleUsage A Float32 whose range is from 0 to 1. This value indicates how much of the client portion of the IO cycle the process will use. The client portion of the IO cycle is the portion of the cycle in which the device calls the IOProcs so this property does not the apply to the duration of the entire cycle. @constant kAudioDevicePropertyStreamConfiguration This property returns the stream configuration of the device in an AudioBufferList (with the buffer pointers set to NULL) which describes the list of streams and the number of channels in each stream. This corresponds to what will be passed into the IOProc. @constant kAudioDevicePropertyIOProcStreamUsage An AudioHardwareIOProcStreamUsage structure which details the stream usage of a given IO proc. If a stream is marked as not being used, the given IOProc will see a corresponding NULL buffer pointer in the AudioBufferList passed to it's IO proc. Note that the number of streams detailed in the AudioHardwareIOProcStreamUsage must include all the streams of that direction on the device. Also, when getting the value of the property, one must fill out the mIOProc field of the AudioHardwareIOProcStreamUsage with the address of the of the IOProc whose stream usage is to be retrieved. @constant kAudioDevicePropertyPreferredChannelsForStereo An array of two UInt32s, the first for the left channel, the second for the right channel, that indicate the channel numbers to use for stereo IO on the device. The value of this property can be different for input and output and there are no restrictions on the channel numbers that can be used. @constant kAudioDevicePropertyPreferredChannelLayout An AudioChannelLayout that indicates how each channel of the AudioDevice should be used. @constant kAudioDevicePropertyNominalSampleRate A Float64 that indicates the current nominal sample rate of the AudioDevice. @constant kAudioDevicePropertyAvailableNominalSampleRates An array of AudioValueRange structs that indicates the valid ranges for the nominal sample rate of the AudioDevice. @constant kAudioDevicePropertyActualSampleRate A Float64 that indicates the current actual sample rate of the AudioDevice as measured by it's time stamps. } const kAudioDevicePropertyPlugIn = FourCharCode('plug'); kAudioDevicePropertyConfigurationApplication = FourCharCode('capp'); kAudioDevicePropertyDeviceUID = FourCharCode('uid '); kAudioDevicePropertyModelUID = FourCharCode('muid'); kAudioDevicePropertyTransportType = FourCharCode('tran'); kAudioDevicePropertyRelatedDevices = FourCharCode('akin'); kAudioDevicePropertyClockDomain = FourCharCode('clkd'); kAudioDevicePropertyDeviceIsAlive = FourCharCode('livn'); kAudioDevicePropertyDeviceHasChanged = FourCharCode('diff'); kAudioDevicePropertyDeviceIsRunning = FourCharCode('goin'); kAudioDevicePropertyDeviceIsRunningSomewhere = FourCharCode('gone'); kAudioDevicePropertyDeviceCanBeDefaultDevice = FourCharCode('dflt'); kAudioDevicePropertyDeviceCanBeDefaultSystemDevice = FourCharCode('sflt'); kAudioDeviceProcessorOverload = FourCharCode('over'); kAudioDevicePropertyHogMode = FourCharCode('oink'); kAudioDevicePropertyLatency = FourCharCode('ltnc'); kAudioDevicePropertyBufferFrameSize = FourCharCode('fsiz'); kAudioDevicePropertyBufferFrameSizeRange = FourCharCode('fsz#'); kAudioDevicePropertyUsesVariableBufferFrameSizes = FourCharCode('vfsz'); kAudioDevicePropertyStreams = FourCharCode('stm#'); kAudioDevicePropertySafetyOffset = FourCharCode('saft'); kAudioDevicePropertyIOCycleUsage = FourCharCode('ncyc'); kAudioDevicePropertyStreamConfiguration = FourCharCode('slay'); kAudioDevicePropertyIOProcStreamUsage = FourCharCode('suse'); kAudioDevicePropertyPreferredChannelsForStereo = FourCharCode('dch2'); kAudioDevicePropertyPreferredChannelLayout = FourCharCode('srnd'); kAudioDevicePropertyNominalSampleRate = FourCharCode('nsrt'); kAudioDevicePropertyAvailableNominalSampleRates = FourCharCode('nsr#'); kAudioDevicePropertyActualSampleRate = FourCharCode('asrt'); {! @enum AudioDevice Properties Implemented via AudioControl objects @abstract AudioObjectPropertySelector values for AudioDevice properties that are implemented by AudioControl objects. @discussion These properties are also accessible by locating the AudioControl object attached to the AudioDevice and using that object to access the properties of the control. @constant kAudioDevicePropertyJackIsConnected A UInt32 where a value of 0 means that there isn't anything plugged into the jack associated withe given element and scope. This property is implemented by an AudioJackControl, a subclass of AudioBooleanControl. @constant kAudioDevicePropertyVolumeScalar A Float32 that represents the value of the volume control. The range is between 0.0 and 1.0 (inclusive). This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. @constant kAudioDevicePropertyVolumeDecibels A Float32 that represents the value of the volume control in dB. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. @constant kAudioDevicePropertyVolumeRangeDecibels An AudioValueRange that contains the minimum and maximum dB values the control can have. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. @constant kAudioDevicePropertyVolumeScalarToDecibels A Float32 that on input contains a scalar volume value for the and on exit contains the equivalent dB value. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. @constant kAudioDevicePropertyVolumeDecibelsToScalar A Float32 that on input contains a dB volume value for the and on exit contains the equivalent scalar value. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. @constant kAudioDevicePropertyStereoPan A Float32 where 0.0 is full left, 1.0 is full right, and 0.5 is center. This property is implemented by an AudioControl object that is a subclass of AudioStereoPanControl. @constant kAudioDevicePropertyStereoPanChannels An array of two UInt32s that indicate which elements of the owning object the signal is being panned between. This property is implemented by an AudioControl object that is a subclass of AudioStereoPanControl. @constant kAudioDevicePropertyMute A UInt32 where a value of 1 means that mute is enabled making that element inaudible. The property is implemented by an AudioControl object that is a subclass of AudioMuteControl. @constant kAudioDevicePropertySolo A UInt32 where a value of 1 means that just that element is audible and the other elements are inaudible. The property is implemented by an AudioControl object that is a subclass of AudioSoloControl. @constant kAudioDevicePropertyDataSource A UInt32 whose value is the item ID for the currently selected data source. This property is implemented by an AudioControl object that is a subclass of AudioDataSourceControl. @constant kAudioDevicePropertyDataSources An array of UInt32s that are represent all the IDs of all the data sources currently available. This property is implemented by an AudioControl object that is a subclass of AudioDataSourceControl. @constant kAudioDevicePropertyDataSourceNameForIDCFString This property translates the given data source item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 containing the item ID to translated and the output data is a CFString. The caller is responsible for releasing the returned CFObject. This property is implemented by an AudioControl object that is a subclass of AudioDataSourceControl. @constant kAudioDevicePropertyClockSource A UInt32 whose value is the item ID for the currently selected clock source. This property is implemented by an AudioControl object that is a subclass of AudioClockControl. @constant kAudioDevicePropertyClockSources An array of UInt32s that are represent all the IDs of all the clock sources currently available. This property is implemented by an AudioControl object that is a subclass of AudioClockControl. @constant kAudioDevicePropertyClockSourceNameForIDCFString This property translates the given clock source item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 containing the item ID to translated and the output data is a CFString. The caller is responsible for releasing the returned CFObject. This property is implemented by an AudioControl object that is a subclass of AudioClockControl. @constant kAudioDevicePropertyClockSourceKindForID This property returns a UInt32 that identifies the kind of clock source the item ID refers to using an AudioValueTranslation structure. The input data is the UInt32 containing the item ID and the output data is the UInt32. Values for this property are defined in <IOAudio/audio/IOAudioTypes.h>. @constant kAudioDevicePropertyPlayThru A UInt32 where a value of 0 means that play through is off and a value of 1 means that it is on. This property is implemented by an AudioControl object that is a subclass of AudioMuteControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruSolo A UInt32 where a value of 1 means that just that play through element is audible and the other elements are inaudible. The property is implemented by an AudioControl object that is a subclass of AudioSoloControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruVolumeScalar A Float32 that represents the value of the volume control. The range is between 0.0 and 1.0 (inclusive). This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl.Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruVolumeDecibels A Float32 that represents the value of the volume control in dB. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruVolumeRangeDecibels An AudioValueRange that contains the minimum and maximum dB values the control can have. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruVolumeScalarToDecibels A Float32 that on input contains a scalar volume value for the and on exit contains the equivalent dB value. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruVolumeDecibelsToScalar A Float32 that on input contains a dB volume value for the and on exit contains the equivalent scalar value. This property is implemented by an AudioControl object that is a subclass of AudioVolumeControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruStereoPan A Float32 where 0.0 is full left, 1.0 is full right, and 0.5 is center. This property is implemented by an AudioControl object that is a subclass of AudioStereoPanControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruStereoPanChannels An array of two UInt32s that indicate which elements of the owning object the signal is being panned between. This property is implemented by an AudioControl object that is a subclass of AudioStereoPanControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruDestination A UInt32 whose value is the item ID for the currently selected play through data destination. This property is implemented by an AudioControl object that is a subclass of AudioDataDestinationControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruDestinations An array of UInt32s that are represent all the IDs of all the play through data destinations currently available. This property is implemented by an AudioControl object that is a subclass of AudioDataDestinationControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyPlayThruDestinationNameForIDCFString This property translates the given play through data destination item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 containing the item ID to translated and the output data is a CFString. The caller is responsible for releasing the returned CFObject. This property is implemented by an AudioControl object that is a subclass of AudioDataDestinationControl. Further, the control that implements this property is only available through kAudioDevicePropertyScopePlayThrough. @constant kAudioDevicePropertyChannelNominalLineLevel A UInt32 whose value is the item ID for the currently selected nominal line level. This property is implemented by an AudioControl object that is a subclass of AudioLineLevelControl. @constant kAudioDevicePropertyChannelNominalLineLevels An array of UInt32s that represent all the IDs of all the nominal line levels currently available. This property is implemented by an AudioControl object that is a subclass of AudioLineLevelControl. @constant kAudioDevicePropertyChannelNominalLineLevelNameForIDCFString This property translates the given nominal line level item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 containing the item ID to be translated and the output data is a CFString. The caller is responsible for releasing the returned CFObject. This property is implemented by an AudioCOntrol object that is a subclass of AudioLineLevelControl. @constant kAudioDevicePropertyDriverShouldOwniSub A UInt32 where a value of 0 means that the AudioDevice should not claim ownership of any attached iSub and a value of 1 means that it should. Note that this property is only available for built-in devices and for USB Audio devices that use the standard class compliant driver. This property is implemented by an AudioControl object that is a subclass of AudioISubOwnerControl. @constant kAudioDevicePropertySubVolumeScalar A Float32 that represents the value of the LFE volume control. The range is between 0.0 and 1.0 (inclusive). This property is implemented by an AudioControl object that is a subclass of AudioLFEVolumeControl. @constant kAudioDevicePropertySubVolumeDecibels A Float32 that represents the value of the LFE volume control in dB. This property is implemented by an AudioControl object that is a subclass of AudioLFE VolumeControl. @constant kAudioDevicePropertySubVolumeRangeDecibels An AudioValueRange that contains the minimum and maximum dB values the control can have. This property is implemented by an AudioControl object that is a subclass of AudioLFEVolumeControl. @constant kAudioDevicePropertySubVolumeScalarToDecibels A Float32 that on input contains a scalar volume value for the and on exit contains the equivalent dB value. This property is implemented by an AudioControl object that is a subclass of AudioLFEVolumeControl. @constant kAudioDevicePropertySubVolumeDecibelsToScalar A Float32 that on input contains a dB volume value for the and on exit contains the equivalent scalar value. This property is implemented by an AudioControl object that is a subclass of AudioLFEVolumeControl. @constant kAudioDevicePropertySubMute A UInt32 where a value of 1 means that mute is enabled making the LFE on that element inaudible. The property is implemented by an AudioControl object that is a subclass of AudioLFEMuteControl. } const kAudioDevicePropertyJackIsConnected = FourCharCode('jack'); kAudioDevicePropertyVolumeScalar = FourCharCode('volm'); kAudioDevicePropertyVolumeDecibels = FourCharCode('vold'); kAudioDevicePropertyVolumeRangeDecibels = FourCharCode('vdb#'); kAudioDevicePropertyVolumeScalarToDecibels = FourCharCode('v2db'); kAudioDevicePropertyVolumeDecibelsToScalar = FourCharCode('db2v'); kAudioDevicePropertyStereoPan = FourCharCode('span'); kAudioDevicePropertyStereoPanChannels = FourCharCode('spn#'); kAudioDevicePropertyMute = FourCharCode('mute'); kAudioDevicePropertySolo = FourCharCode('solo'); kAudioDevicePropertyDataSource = FourCharCode('ssrc'); kAudioDevicePropertyDataSources = FourCharCode('ssc#'); kAudioDevicePropertyDataSourceNameForIDCFString = FourCharCode('lscn'); kAudioDevicePropertyClockSource = FourCharCode('csrc'); kAudioDevicePropertyClockSources = FourCharCode('csc#'); kAudioDevicePropertyClockSourceNameForIDCFString = FourCharCode('lcsn'); kAudioDevicePropertyClockSourceKindForID = FourCharCode('csck'); kAudioDevicePropertyPlayThru = FourCharCode('thru'); kAudioDevicePropertyPlayThruSolo = FourCharCode('thrs'); kAudioDevicePropertyPlayThruVolumeScalar = FourCharCode('mvsc'); kAudioDevicePropertyPlayThruVolumeDecibels = FourCharCode('mvdb'); kAudioDevicePropertyPlayThruVolumeRangeDecibels = FourCharCode('mvd#'); kAudioDevicePropertyPlayThruVolumeScalarToDecibels = FourCharCode('mv2d'); kAudioDevicePropertyPlayThruVolumeDecibelsToScalar = FourCharCode('mv2s'); kAudioDevicePropertyPlayThruStereoPan = FourCharCode('mspn'); kAudioDevicePropertyPlayThruStereoPanChannels = FourCharCode('msp#'); kAudioDevicePropertyPlayThruDestination = FourCharCode('mdds'); kAudioDevicePropertyPlayThruDestinations = FourCharCode('mdd#'); kAudioDevicePropertyPlayThruDestinationNameForIDCFString = FourCharCode('mddc'); kAudioDevicePropertyChannelNominalLineLevel = FourCharCode('nlvl'); kAudioDevicePropertyChannelNominalLineLevels = FourCharCode('nlv#'); kAudioDevicePropertyChannelNominalLineLevelNameForIDCFString = FourCharCode('lcnl'); kAudioDevicePropertyDriverShouldOwniSub = FourCharCode('isub'); kAudioDevicePropertySubVolumeScalar = FourCharCode('svlm'); kAudioDevicePropertySubVolumeDecibels = FourCharCode('svld'); kAudioDevicePropertySubVolumeRangeDecibels = FourCharCode('svd#'); kAudioDevicePropertySubVolumeScalarToDecibels = FourCharCode('sv2d'); kAudioDevicePropertySubVolumeDecibelsToScalar = FourCharCode('sd2v'); kAudioDevicePropertySubMute = FourCharCode('smut'); {! @enum AudioDevice Properties That Ought To Some Day Be Deprecated @abstract AudioObjectPropertySelector values whose functionality is better provided by other selectors. @discussion These selectors are still provided for backward compatibility. The description of the property will indicate in parentheses the better selectors to use and why. @constant kAudioDevicePropertyDeviceName A C-string that contains the human readable name of the AudioDevice. (kAudioObjectPropertyName: CFStrings are better for localization.) @constant kAudioDevicePropertyDeviceNameCFString A CFStringRef that contains the human readable name of the AudioDevice. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyName: This is just another name for the inherited selector.) @constant kAudioDevicePropertyDeviceManufacturer A C-string that contains the human readable name of the manufacturer of the AudioDevice. (kAudioObjectPropertyManufacturer: CFStrings are better for localization.) @constant kAudioDevicePropertyDeviceManufacturerCFString A CFString that contains the human readable name of the manufacturer of the AudioDevice. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyManufacturer: This is just another name for the inherited selector.) @constant kAudioDevicePropertyRegisterBufferList This property allows clients to register a fully populated AudioBufferList that matches the topology described by kAudioDevicePropertyStreamConfiguration for doing input using AudioDeviceRead(). The AudioBufferList will be registered with the call the AudioDeviceSetProperty() and will be unregistered with the call to AudioDeviceGetProperty(). If this property isn't implemented by the AudioDevice, it implies that the AudioDevice also doesn't support AudioDeviceRead(). (Aggregate devices make AudioDeviceRead() obsolete for the most part.) @constant kAudioDevicePropertyBufferSize A UInt32 containing the size in bytes of the IO buffer for the AudioStream containing the element. (kAudioDevicePropertyBufferFrameSize: with multiple AudioStreams and the requirement that all streams' buffers represent the same amount of time, it doesn't make sense to set the buffer size in bytes since it will be different for each stream.) @constant kAudioDevicePropertyBufferSizeRange An AudioValueRange specifying the minimum and maximum bytes size for the IO buffer for the AudioStream containing the given element. (kAudioDevicePropertyBufferFrameSizeRange: see kAudioDevicePropertyBufferSize.) @constant kAudioDevicePropertyChannelName A CFString that contains a human readable name for the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementName: CFStrings are better for localization.) @constant kAudioDevicePropertyChannelNameCFString A CFString that contains a human readable name for the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementName: This is just another name for the inherited selector.) @constant kAudioDevicePropertyChannelCategoryName A CFString that contains a human readable name for the category of the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementCategoryName: CFStrings are better for localization.) @constant kAudioDevicePropertyChannelCategoryNameCFString A CFString that contains a human readable name for the category of the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementCategoryName: This is just another name for the inherited selector.) @constant kAudioDevicePropertyChannelNumberName A CFString that contains a human readable name for the number of the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementNumberName: CFStrings are better for localization.) @constant kAudioDevicePropertyChannelNumberNameCFString A CFString that contains a human readable name for the number of the given element in the given scope. The caller is responsible for releasing the returned CFObject. (kAudioObjectPropertyElementNumberName: This is just another name for the inherited selector.) @constant kAudioDevicePropertySupportsMixing A UInt32 where a value of 1 means the AudioDevice supports mixing and a value of 0 means that it doesn't and that all IO is performed in each AudioStream's current physical format. This property is changed indirectly by changing to a format that doesn't support mixing, such as AC-3. (The HAL now vends it's format information with a flag indicating the mixability in order to better support devices with streams that are both mixable and non- mixable.) @constant kAudioDevicePropertyStreamFormat An AudioStreamBasicDescription that describes the current data format for the AudioStream that contains the channel referred to by the element number. (kAudioStreamPropertyVirtualFormat: Managing format information is inherently an operation on AudioStreams, rather than AudioDevices. It is confusing for the client to work with formats at the AudioDevice level and has been shown to lead to programming mistakes by clients when working with devices that have multiple streams.) @constant kAudioDevicePropertyStreamFormats An array of AudioStreamBasicDescriptions that describe the available data formats for the AudioStream that contains the channel referred to by the element number. (kAudioStreamPropertyAvailableVirtualFormats: Managing format information is inherently an operation on AudioStreams, rather than AudioDevices. It is confusing for the client to work with formats at the AudioDevice level and has been shown to lead to programming mistakes by clients when working with devices that have multiple streams.) @constant kAudioDevicePropertyStreamFormatSupported An AudioStreamBasicDescription is passed in to query whether or not the format is supported. A kAudioDeviceUnsupportedFormatError will be returned if the format is not supported and kAudioHardwareNoError will be returned if it is supported. AudioStreamBasicDescription fields set to 0 will be ignored in the query, but otherwise values must match exactly. (kAudioStreamPropertyAvailableVirtualFormats: The proper and most robust way to find a format that the AudioStream can support is to get the list of available formats and look through that rather than using this property.) @constant kAudioDevicePropertyStreamFormatMatch An AudioStreamBasicDescription is passed in and the AudioStream will modify it to describe the best match, in the AudioDevice's opinion, for the given format. (kAudioStreamPropertyAvailableVirtualFormats: The proper and most robust way to find a format that the AudioStream can support is to get the list of available formats and look through that rather than using this property.) @constant kAudioDevicePropertyDataSourceNameForID This property translates the given data source item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 holding the item ID to be translated and the output data is a buffer to hold the name as a null terminated c-string. (kAudioDevicePropertyDataSourceNameForIDCFString: CFStrings are better for localization.) @constant kAudioDevicePropertyClockSourceNameForID This property translates the given clock source item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 holding the item ID to be translated and the output data is a buffer to hold the name as a null terminated c-string. (kAudioDevicePropertyClockSourceNameForIDCFString: CFStrings are better for localization.) @constant kAudioDevicePropertyPlayThruDestinationNameForID This property translates the given play through destination item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 holding the item ID to be translated and the output data is a buffer to hold the name as a null terminated c-string. (kAudioDevicePropertyPlayThruDestinationNameForIDCFString: CFStrings are better for localization.) @constant kAudioDevicePropertyChannelNominalLineLevelNameForID This property translates the given nominal line level item ID into a human readable name using an AudioValueTranslation structure. The input data is the UInt32 holding the item ID to be translated and the output data is a buffer to hold the name as a null terminated c-string. (kAudioDevicePropertyChannelNominalLineLevelNameForIDCFString: CFStrings are better for localization.) } const kAudioDevicePropertyDeviceName = FourCharCode('name'); kAudioDevicePropertyDeviceNameCFString = kAudioObjectPropertyName; kAudioDevicePropertyDeviceManufacturer = FourCharCode('makr'); kAudioDevicePropertyDeviceManufacturerCFString = kAudioObjectPropertyManufacturer; kAudioDevicePropertyRegisterBufferList = FourCharCode('rbuf'); kAudioDevicePropertyBufferSize = FourCharCode('bsiz'); kAudioDevicePropertyBufferSizeRange = FourCharCode('bsz#'); kAudioDevicePropertyChannelName = FourCharCode('chnm'); kAudioDevicePropertyChannelNameCFString = kAudioObjectPropertyElementName; kAudioDevicePropertyChannelCategoryName = FourCharCode('ccnm'); kAudioDevicePropertyChannelCategoryNameCFString = kAudioObjectPropertyElementCategoryName; kAudioDevicePropertyChannelNumberName = FourCharCode('cnnm'); kAudioDevicePropertyChannelNumberNameCFString = kAudioObjectPropertyElementNumberName; kAudioDevicePropertySupportsMixing = FourCharCode('mix?'); kAudioDevicePropertyStreamFormat = FourCharCode('sfmt'); kAudioDevicePropertyStreamFormats = FourCharCode('sfm#'); kAudioDevicePropertyStreamFormatSupported = FourCharCode('sfm?'); kAudioDevicePropertyStreamFormatMatch = FourCharCode('sfmm'); kAudioDevicePropertyDataSourceNameForID = FourCharCode('sscn'); kAudioDevicePropertyClockSourceNameForID = FourCharCode('cscn'); kAudioDevicePropertyPlayThruDestinationNameForID = FourCharCode('mddn'); kAudioDevicePropertyChannelNominalLineLevelNameForID = FourCharCode('cnlv'); //================================================================================================== //#pragma mark AudioDevice Functions {! @functiongroup AudioDevice } {! @function AudioDeviceAddIOProc @abstract Registers the given AudioDeviceIOProc with the AudioDevice. @discussion A client may have multiple IOProcs for a given device, but the device is free to only accept as many as it can handle. Note that it is not recommended for clients to have more than a single IOProc registered at a time as this can be wasteful of system resources. Rather, it is recommended that the client do any necessary mixing itself so that only one IOProc is necessary. @param inDevice The AudioDevice to register the IOProc with. @param inProc The AudioDeviceIOProc to register. @param inClientData A pointer to client data that is passed back to the IOProc when it is called. @result An OSStatus indicating success or failure. } function AudioDeviceAddIOProc( inDevice: AudioDeviceID; inProc: AudioDeviceIOProc; inClientData: UnivPtr ): OSStatus; external name '_AudioDeviceAddIOProc'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceRemoveIOProc @abstract Unregisters the given AudioDeviceIOProc from the AudioDevice. @param inDevice The AudioDevice to unregister the IOProc from. @param inProc The AudioDeviceIOProc to unregister. @result An OSStatus indicating success or failure. } function AudioDeviceRemoveIOProc( inDevice: AudioDeviceID; inProc: AudioDeviceIOProc ): OSStatus; external name '_AudioDeviceRemoveIOProc'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceStart @abstract Starts IO for the given AudioDeviceIOProc. @param inDevice The AudioDevice to start the IOProc on. @param inProc The AudioDeviceIOProc to start. Note that this can be NULL, which starts the hardware regardless of whether or not there are any IOProcs registered. This is necessary if any of the AudioDevice's timing services are to be used. A balancing call to AudioDeviceStop with a NULL IOProc is required to stop the hardware. @result An OSStatus indicating success or failure. } function AudioDeviceStart( inDevice: AudioDeviceID; inProc: AudioDeviceIOProc ): OSStatus; external name '_AudioDeviceStart'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceStartAtTime @abstract Starts IO for the given AudioDeviceIOProc and aligns the IO cycle of the AudioDevice with the given time. @param inDevice The AudioDevice to start the IOProc on. @param inProc The AudioDeviceIOProc to start. Note that this can be NULL, which starts the hardware regardless of whether or not there are any IOProcs registered. @param ioRequestedStartTime A pointer to an AudioTimeStamp that, on entry, is the requested time to start the IOProc. On exit, it will be the actual time the IOProc will start. @param inFlags A UInt32 containing flags that modify how this function behaves. @result An OSStatus indicating success or failure. kAudioHardwareUnsupportedOperationError will be returned if the AudioDevice does not support starting at a specific time and inProc and ioRequestedStartTime are not NULL. } function AudioDeviceStartAtTime( inDevice: AudioDeviceID; inProc: AudioDeviceIOProc; ioRequestedStartTime: AudioTimeStampPtr; inFlags: UInt32 ): OSStatus; external name '_AudioDeviceStartAtTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {! @function AudioDeviceStop @abstract Stops IO for the given AudioDeviceIOProc. @param inDevice The AudioDevice to stop the IOProc on. @param inProc The AudioDeviceIOProc to stop. @result An OSStatus indicating success or failure. } function AudioDeviceStop( inDevice: AudioDeviceID; inProc: AudioDeviceIOProc ): OSStatus; external name '_AudioDeviceStop'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceRead @abstract Read some data from an AudioDevice starting at the given time. @discussion With the advent of aggregate devices, the need for AudioDeviceRead has gone away. Consequently, this function is a good candidate for deprecation some day. @param inDevice The AudioDevice to read from. @param inStartTime An AudioTimeStamp indicating the time from which to read the data. In general, the valid range of time (in frames) is from the current time minus the maximum IO buffer size to the current time minus the safety offset. @param outData An AudioBufferList that must be the same size and shape as that returned by kAudioDevicePropertyStreamConfiguration. Further, the AudioBufferList must have been previously registered with the device via kAudioDevicePropertyRegisterBufferList. On exit, the mDataSize fields will be updated with the amount of data read. @result An OSStatus indicating success or failure. kAudioHardwareUnsupportedOperationError will be returned if the AudioDevice does not support direct reading. } function AudioDeviceRead( inDevice: AudioDeviceID; const (*var*) inStartTime: AudioTimeStamp; var outData: AudioBufferList ): OSStatus; external name '_AudioDeviceRead'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioDeviceGetCurrentTime @abstract Retrieves the current time from an AudioDevice. Note that the device has to be running. @param inDevice The AudioDevice to from which to get the time. @param outTime An AudioTimeStamp into which the current time is put. @result An OSStatus indicating success or failure. kAudioHardwareNotRunningError will be returned if the AudioDevice isn't running. } function AudioDeviceGetCurrentTime( inDevice: AudioDeviceID; var outTime: AudioTimeStamp ): OSStatus; external name '_AudioDeviceGetCurrentTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceTranslateTime @abstract Translates the time in the AudioDevice's time base from one representation to another. Note that the device has to be running @param inDevice The AudioDevice whose time base governs the translation. @param inTime An AudioTimeStamp containing the time to be translated. @param outTime An AudioTimeStamp into which the translated time is put. On entry, the mFlags field specifies which representations to translate the input time into. Because not every device supports all time representations, on exit, the mFlags field will indicate which translations were actually done. @result An OSStatus indicating success or failure. kAudioHardwareNotRunningError will be returned if the AudioDevice isn't running. } function AudioDeviceTranslateTime( inDevice: AudioDeviceID; const (*var*) inTime: AudioTimeStamp; var outTime: AudioTimeStamp ): OSStatus; external name '_AudioDeviceTranslateTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceGetNearestStartTime @abstract Query an AudioDevice to get a time equal to or later than the given time that is the best time to start IO. @discussion The time that is returned is dictated by the constraints of the device and the system. For instance, the driver of a device that provides both audio and video data may only allow start times that coincide with the edge of a video frame. Also, if the device already has one or more active IOProcs, the start time will be shifted to the beginning of the next IO cycle so as not to cause discontinuities in the existing IOProcs. Another reason the start time may shift is to allow for aligning the buffer accesses in an optimal fashion. Note that the device must be running to use this function. @param inDevice The AudioDevice to query. @param ioRequestedStartTime A pointer to an AudioTimeStamp that, on entry, is the requested start time. On exit, it will have the a time equal to or later than the requested time, as dictated by the device's constraints. @param inFlags A UInt32 containing flags that modify how this function behaves. @result An OSStatus indicating success or failure. kAudioHardwareNotRunningError will be returned if the AudioDevice isn't running. kAudioHardwareUnsupportedOperationError will be returned if the AudioDevice does not support starting at a specific time. } function AudioDeviceGetNearestStartTime( inDevice: AudioDeviceID; var ioRequestedStartTime: AudioTimeStamp; inFlags: UInt32 ): OSStatus; external name '_AudioDeviceGetNearestStartTime'; (* AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER *) {! @function AudioDeviceGetPropertyInfo @abstract Retrieve information about the given property of an AudioDevice. @discussion Note that the same functionality is provided by the functions AudioObjectHasProperty(), AudioObjectIsPropertySettable(), and AudioObjectGetPropertyDataSize(). @param inDevice The AudioDevice to query. @param inChannel The channel of the property to query where 0 is the master channel. @param isInput Which section of the AudioDevice to query. @param inPropertyID The AudioDevicePropertyID of the property to query. @param outSize A pointer to a UInt32 that receives the size of the property data in bytes on exit. This can be NULL if the size information is not being requested. @param outWritable A pointer to a Boolean that receives indication of whether or not the given property can be set. This can be NULL if the writability is not being requested. @result An OSStatus indicating success or failure. } function AudioDeviceGetPropertyInfo( inDevice: AudioDeviceID; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; outSize: UInt32Ptr; outWritable: BooleanPtr ): OSStatus; external name '_AudioDeviceGetPropertyInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceGetProperty @abstract Queries an the AudioDevice object to get the data of the given property and places it in the provided buffer. @discussion Note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inDevice The AudioDevice to query. @param inChannel The channel of the property to query where 0 is the master channel. @param isInput Which section of the AudioDevice to query. @param inPropertyID The AudioDevicePropertyID of the property to query. @param ioPropertyDataSize A UInt32 which on entry indicates the size of the buffer pointed to by outData and on exit indicates how much of the buffer was used. @param outPropertyData The buffer into which the object will put the data for the given property. @result An OSStatus indicating success or failure. } function AudioDeviceGetProperty( inDevice: AudioDeviceID; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; var ioPropertyDataSize: UInt32; outPropertyData: UnivPtr ): OSStatus; external name '_AudioDeviceGetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceSetProperty @abstract Tells the AudioDevice object to change the value of the given property using the provided data. @discussion Note that the value of the property should not be considered changed until the HAL has called the listeners as many properties values are changed asynchronously. Also note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inDevice The AudioDevice to change. @param inWhen A pointer to an AudioTimeStamp that says when to change the property's value relative to the device's time base. NULL means execute the change immediately. @param inChannel The channel of the property to change where 0 is the master channel. @param isInput Which section of the AudioDevice to change. @param inPropertyID The AudioDevicePropertyID of the property to change. @param inPropertyDataSize A UInt32 indicating the size of the buffer pointed to by inData. @param inPropertyData The buffer containing the data to be used to change the property's value. @result An OSStatus indicating success or failure. } function AudioDeviceSetProperty( inDevice: AudioDeviceID; inWhen: {const} AudioTimeStampPtr; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; inPropertyDataSize: UInt32; inPropertyData: {const} UnivPtr ): OSStatus; external name '_AudioDeviceSetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceAddPropertyListener @abstract Registers the given AudioDevicePropertyListenerProc to receive notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectAddPropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inDevice The AudioDevice with whom to register the listener. @param inChannel The channel of the property to listen to. @param isInput Which section of the AudioDevice to listen to. @param inPropertyID The AudioDevicePropertyID of the property to listen to. @param inProc AudioDevicePropertyListenerProc to call. @param inClientData A pointer to client data that is passed to the listener when it is called. @result An OSStatus indicating success or failure. } function AudioDeviceAddPropertyListener( inDevice: AudioDeviceID; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; inProc: AudioDevicePropertyListenerProc; inClientData: UnivPtr ): OSStatus; external name '_AudioDeviceAddPropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) {! @function AudioDeviceRemovePropertyListener @abstract Unregisters the given AudioDevicePropertyListenerProc from receiving notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectRemovePropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inDevice The AudioDevice with whom to unregister the listener. @param inChannel The channel of the property to unregister from. @param isInput Which section of the AudioDevice to unregister from. @param inPropertyID The AudioDevicePropertyID of the property to stop listening to. @param inProc AudioDevicePropertyListenerProc to unregister. @result An OSStatus indicating success or failure. } function AudioDeviceRemovePropertyListener( inDevice: AudioDeviceID; inChannel: UInt32; isInput: Boolean; inPropertyID: AudioDevicePropertyID; inProc: AudioDevicePropertyListenerProc ): OSStatus; external name '_AudioDeviceRemovePropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER *) //================================================================================================== //#pragma mark AudioStream Types {! @typedef AudioStreamID @abstract AudioStream is the base class for all objects that represent a stream of data on an audio device. @discussion AudioStream is a subclass of AudioObject and can contain AudioControls. } type AudioStreamID = AudioObjectID; {! @struct AudioStreamRangedDescription @abstract This structure allows a specific sample rate range to be associated with an AudioStreamBasicDescription that specifies it's sample rate as kAudioStreamAnyRate. @discussion Note that this structure is only used to desicribe the the available formats for a stream. It is not used for the current format. @field mFormat The AudioStreamBasicDescription that describes the format of the stream. Note that the mSampleRate field of the structure will be the same as the the values in mSampleRateRange when only a single sample rate is supported. It will be kAudioStreamAnyRate when there is a range with more elements. @field mSampleRateRange The AudioValueRange that describes the minimum and maximum sample rate for the stream. If the mSampleRate field of mFormat is kAudioStreamAnyRate the format supports the range of sample rates described by this structure. Otherwise, the minimum will be the same as the maximum which will be the same as the mSampleRate field of mFormat. } type AudioStreamRangedDescription = record mFormat: AudioStreamBasicDescription; mSampleRateRange: AudioValueRange; end; {! @typedef AudioStreamPropertyListenerProc @abstract Clients register an AudioStreamPropertyListenerProc with the AudioStream object in order to receive notifications when the properties of the object change. @discussion Note that the same functionality is provided by AudioObjectPropertyListenerProc. @param inStream The AudioStream whose property has changed. @param inChannel The channel of the property that changed where 0 is the master channel. @param inPropertyID The AudioDevicePropertyID of the property that changed. @param inClientData A pointer to client data established when the listener proc was registered with the object. @result The return value is currently unused and should always be 0. } type AudioStreamPropertyListenerProc = function( inStream: AudioStreamID; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; inClientData: UnivPtr ): OSStatus; //================================================================================================== //#pragma mark AudioStream Constants {! @enum AudioStream Class Constants @abstract Various constants related to AudioStreams. @constant kAudioStreamClassID The AudioClassID that identifies the AudioStream class. @constant kAudioStreamUnknown The AudioObjectID for a nonexistent AudioObject. } const kAudioStreamClassID = FourCharCode('astr'); kAudioStreamUnknown = kAudioObjectUnknown; //================================================================================================== //#pragma mark AudioStream Properties {! @enum AudioStream Properties @abstract AudioObjectPropertySelector values that apply to all AudioStreams. @discussion AudioStream is a subclass of AudioObject and has only the single scope, kAudioObjectPropertyScopeGlobal. They have a master element and an element for each channel in the stream numbered upward from 1. Note that AudioStream objects share AudioControl objects with their owning AudioDevice. Consequently, all the standard AudioControl related property selectors implemented by AudioDevices are also implemented by AudioStreams. The same constants are to be used for such properties. @constant kAudioStreamPropertyDirection A UInt32 where a value of 0 means that this AudioStream is an output stream and a value of 1 means that it is an input stream. @constant kAudioStreamPropertyTerminalType A UInt32 whose value describes the general kind of functionality attached to the AudioStream. Constants that describe some of the values of this property are defined in <IOKit/audio/IOAudioTypes.h> @constant kAudioStreamPropertyStartingChannel A UInt32 that specifies the first element in the owning device that corresponds to element one of this stream. @constant kAudioStreamPropertyLatency A UInt32 containing the number of frames of latency in the AudioStream. Note that the owning AudioDevice may have additional latency so it should be queried as well. If both the device and the stream say they have latency, then the total latency for the stream is the device latency summed with the stream latency. @constant kAudioStreamPropertyVirtualFormat An AudioStreamBasicDescription that describes the current data format for the AudioStream. The virtual format refers to the data format in which all IOProcs for the owning AudioDevice will perform IO transactions. @constant kAudioStreamPropertyAvailableVirtualFormats An array of AudioStreamRangedDescriptions that describe the available data formats for the AudioStream. The virtual format refers to the data format in which all IOProcs for the owning AudioDevice will perform IO transactions. @constant kAudioStreamPropertyPhysicalFormat An AudioStreamBasicDescription that describes the current data format for the AudioStream. The physical format refers to the data format in which the hardware for the owning AudioDevice performs it's IO transactions. @constant kAudioStreamPropertyAvailablePhysicalFormats An array of AudioStreamRangedDescriptions that describe the available data formats for the AudioStream. The physical format refers to the data format in which the hardware for the owning AudioDevice performs it's IO transactions. } const kAudioStreamPropertyDirection = FourCharCode('sdir'); kAudioStreamPropertyTerminalType = FourCharCode('term'); kAudioStreamPropertyStartingChannel = FourCharCode('schn'); kAudioStreamPropertyLatency = kAudioDevicePropertyLatency; kAudioStreamPropertyVirtualFormat = FourCharCode('sfmt'); kAudioStreamPropertyAvailableVirtualFormats = FourCharCode('sfma'); kAudioStreamPropertyPhysicalFormat = FourCharCode('pft '); kAudioStreamPropertyAvailablePhysicalFormats = FourCharCode('pfta'); {! @enum AudioStream Properties That Ought To Some Day Be Deprecated @abstract AudioObjectPropertySelector values whose functionality is better provided by other selectors. @discussion These selectors are still provided for backward compatibility. The description of the property will indicate in parentheses the better selectors to use and why. @constant kAudioStreamPropertyOwningDevice The AudioObjectID of the AudioDevice of which this AudioStream is a part. (kAudioObjectPropertyOwner: This is just another name for the inherited selector.) @constant kAudioStreamPropertyPhysicalFormats An array of AudioStreamBasicDescriptions that describe the available data formats for the AudioStream. The physical format refers to the data format in which the hardware for the owning AudioDevice performs it's IO transactions. (kAudioStreamPropertyAvailablePhysicalFormats: The new name for this property is much clearer for readers of the API to see what is meant and the AudioStreamRangedDescription structure provides better information.) @constant kAudioStreamPropertyPhysicalFormatSupported An AudioStreamBasicDescription is passed in to query whether or not the format is supported. A kAudioDeviceUnsupportedFormatError will be returned if the format is not supported and kAudioHardwareNoError will be returned if it is supported. AudioStreamBasicDescription fields set to 0 will be ignored in the query, but otherwise values must match exactly. The physical format refers to the data format in which the hardware for the owning AudioDevice performs it's IO transactions. (kAudioStreamPropertyAvailablePhysicalFormats: The proper and most robust way to find a format that the AudioStream can support is to get the list of available formats and look through that rather than using this property.) @constant kAudioStreamPropertyPhysicalFormatMatch An AudioStreamBasicDescription is passed in and the AudioStream will modify it to describe the best match, in the AudioDevice's opinion, for the given format. The physical format refers to the data format in which the hardware for the owning AudioDevice performs it's IO transactions. (kAudioStreamPropertyAvailablePhysicalFormats: The proper and most robust way to find a format that the AudioStream can support is to get the list of available formats and look through that rather than using this property.) } const kAudioStreamPropertyOwningDevice = kAudioObjectPropertyOwner; kAudioStreamPropertyPhysicalFormats = FourCharCode('pft#'); kAudioStreamPropertyPhysicalFormatSupported = FourCharCode('pft?'); kAudioStreamPropertyPhysicalFormatMatch = FourCharCode('pftm'); //================================================================================================== //#pragma mark AudioStream Functions {! @functiongroup AudioStream } {! @function AudioStreamGetPropertyInfo @abstract Retrieve information about the given property of an AudioStream. @param inStream The AudioStream to query. @param inChannel The channel of the property to query where 0 is the master channel. @param inPropertyID The AudioDevicePropertyID of the property to query. @param outSize A pointer to a UInt32 that receives the size of the property data in bytes on exit. This can be NULL if the size information is not being requested. @param outWritable A pointer to a Boolean that receives indication of whether or not the given property can be set. This can be NULL if the writability is not being requested. @result An OSStatus indicating success or failure. } function AudioStreamGetPropertyInfo( inStream: AudioStreamID; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; var outSize: UInt32; var outWritable: Boolean ): OSStatus; external name '_AudioStreamGetPropertyInfo'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioStreamGetProperty @abstract Queries an the AudioStream object to get the data of the given property and places it in the provided buffer. @discussion Note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inStream The AudioStream to query. @param inChannel The channel of the property to query where 0 is the master channel. @param inPropertyID The AudioDevicePropertyID of the property to query. @param ioPropertyDataSize A UInt32 which on entry indicates the size of the buffer pointed to by outData and on exit indicates how much of the buffer was used. @param outPropertyData The buffer into which the object will put the data for the given property. @result An OSStatus indicating success or failure. } function AudioStreamGetProperty( inStream: AudioStreamID; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; var ioPropertyDataSize: UInt32; outPropertyData: UnivPtr ): OSStatus; external name '_AudioStreamGetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioStreamSetProperty @abstract Tells the AudioStream object to change the value of the given property using the provided data. @discussion Note that the value of the property should not be considered changed until the HAL has called the listeners as many properties values are changed asynchronously. Also note that the same functionality is provided by the function AudioObjectGetPropertyData(). @param inStream The AudioStream to change. @param inWhen A pointer to an AudioTimeStamp that says when to change the property's value relative to the device's time base. NULL means execute the change immediately. @param inChannel The channel of the property to change where 0 is the master channel. @param inPropertyID The AudioDevicePropertyID of the property to change. @param inPropertyDataSize A UInt32 indicating the size of the buffer pointed to by inData. @param inPropertyData The buffer containing the data to be used to change the property's value. @result An OSStatus indicating success or failure. } function AudioStreamSetProperty( inStream: AudioStreamID; inWhen: AudioTimeStampPtr; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; inPropertyDataSize: UInt32; inPropertyData: {const} UnivPtr ): OSStatus; external name '_AudioStreamSetProperty'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioStreamAddPropertyListener @abstract Registers the given AudioStreamPropertyListenerProc to receive notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectAddPropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inStream The AudioStream with whom to register the listener. @param inChannel The channel of the property to listen to. @param inPropertyID The AudioDevicePropertyID of the property to listen to. @param inProc AudioStreamPropertyListenerProc to call. @param inClientData A pointer to client data that is passed to the listener when it is called. @result An OSStatus indicating success or failure. } function AudioStreamAddPropertyListener( inStream: AudioStreamID; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; inProc: AudioStreamPropertyListenerProc; inClientData: UnivPtr ): OSStatus; external name '_AudioStreamAddPropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) {! @function AudioStreamRemovePropertyListener @abstract Unregisters the given AudioStreamPropertyListenerProc from receiving notifications when the given property changes. @discussion Note that the same functionality is provided by AudioObjectRemovePropertyListener in conjunction with AudioObjectPropertyListenerProc. @param inStream The AudioStream with whom to unregister the listener. @param inChannel The channel of the property to unregister from. @param inPropertyID The AudioDevicePropertyID of the property to stop listening to. @param inProc AudioStreamPropertyListenerProc to unregister. @result An OSStatus indicating success or failure. } function AudioStreamRemovePropertyListener( inStream: AudioStreamID; inChannel: UInt32; inPropertyID: AudioDevicePropertyID; inProc: AudioStreamPropertyListenerProc ): OSStatus; external name '_AudioStreamRemovePropertyListener'; (* AVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER *) //================================================================================================== //#pragma mark AudioAggregateDevice Constants {! @enum AudioAggregateDevice Class Constants @abstract Various constants related to AudioAggregateDevices. @constant kAudioAggregateDeviceClassID The AudioClassID that identifies the AudioAggregateDevice class. @constant kAudioDeviceTransportTypeAggregate The transport type ID (see kAudioDevicePropertyTransportType) for aggregate devices. @constant kAudioDeviceTransportTypeAutoAggregate The transport type ID (see kAudioDevicePropertyTransportType) for automatically generated aggregate devices. } const kAudioAggregateDeviceClassID = FourCharCode('aagg'); kAudioDeviceTransportTypeAggregate = FourCharCode('grup'); kAudioDeviceTransportTypeAutoAggregate = FourCharCode('fgrp'); {! @defined kAudioAggregateDeviceUIDKey @discussion The key used in a CFDictionary that describes the composition of an AudioAggregateDevice. The value for this key is a CFString that contains the UID of the AudioAggregateDevice. } const kAudioAggregateDeviceUIDKey = 'uid'; {! @defined kAudioAggregateDeviceNameKey @discussion The key used in a CFDictionary that describes the composition of an AudioAggregateDevice. The value for this key is a CFString that contains the human readable name of the AudioAggregateDevice. } const kAudioAggregateDeviceNameKey = 'name'; {! @defined kAudioAggregateDeviceSubDeviceListKey @discussion The key used in a CFDictionary that describes the composition of an AudioAggregateDevice. The value for this key is a CFArray of CFDictionaries that describe each sub-device in the AudioAggregateDevice. The keys for this CFDictionary are defined in the AudioSubDevice section. } const kAudioAggregateDeviceSubDeviceListKey = 'subdevices'; {! @defined kAudioAggregateDeviceMasterSubDeviceKey @discussion The key used in a CFDictionary that describes the composition of an AudioAggregateDevice. The value for this key is a CFString that contains the UID for the sub-device that is the master time source for the AudioAggregateDevice. } const kAudioAggregateDeviceMasterSubDeviceKey = 'master'; {! @defined kAudioAggregateDeviceIsPrivateKey @discussion The key used in a CFDictionary that describes the composition of an AudioAggregateDevice. The value for this key is a CFNumber where a value of 0 means that the AudioAggregateDevice is to be published to the entire system and a value of 1 means that the AudioAggregateDevice is private to the process that created it. Note that a private AudioAggregateDevice is not persistent across launches of the process that created it. Note that if this key is not present, it implies that the AudioAggregateDevice is published to the entire system. } const kAudioAggregateDeviceIsPrivateKey = 'private'; //================================================================================================== //#pragma mark AudioAggregateDevice Properties {! @enum AudioAggregateDevice Properties @abstract AudioObjectPropertySelector values that apply to all AudioAggregateDevices. @discussion AudioAggregateDevice is a subclass of AudioDevice. @constant kAudioAggregateDevicePropertyFullSubDeviceList A CFArray of CFStrings that contain the UIDs of all the devices, active or inactive, contained in the AudioAggregateDevice. The order of the items in the array is significant and is used to determine the order of the streams of the AudioAggregateDevice. The caller is responsible for releasing the returned CFObject. @constant kAudioAggregateDevicePropertyActiveSubDeviceList An array of AudioObjectIDs for all the active sub-devices in the aggregate device. @constant kAudioAggregateDevicePropertyComposition A CFDictionary that describes the composition of the AudioAggregateDevice. The keys for this CFDicitionary are defined in the AudioAggregateDevice Constants section. } const kAudioAggregateDevicePropertyFullSubDeviceList = FourCharCode('grup'); kAudioAggregateDevicePropertyActiveSubDeviceList = FourCharCode('agrp'); kAudioAggregateDevicePropertyComposition = FourCharCode('acom'); {! @enum AudioAggregateDevice Properties Implemented via AudioControl objects @abstract AudioObjectPropertySelector values for AudioAggregateDevice properties that are implemented by AudioControl objects. @discussion These properties are also accessible by locating the AudioControl object attached to the AudioAggregateDevice and using that object to access the properties of the control. @constant kAudioAggregateDevicePropertyMasterSubDevice A CFString that contains the UID for the AudioDevice that is currently serving as the master time base of the aggregate device. This property is also implemented by the AudioClockSourceControl on the master element of the global scope of the AudioAggregateDevice. } const kAudioAggregateDevicePropertyMasterSubDevice = FourCharCode('amst'); //================================================================================================== //#pragma mark AudioSubDevice Constants {! @enum AudioSubDevice Class Constants @abstract Various constants related to AudioSubDevices. @constant kAudioSubDeviceClassID The AudioClassID that identifies the AudioSubDevice class. } const kAudioSubDeviceClassID = FourCharCode('asub'); {! @enum AudioSubDevice Clock Drift Compensation Methods @abstract Constants that describe the range of values the property kAudioSubDevicePropertyDriftCompensation. It is a continuous range from kAudioSubDeviceDriftCompensationMinQuality to kAudioSubDeviceDriftCompensationMaxQuality, with some commonly used settings called out. } const kAudioSubDeviceDriftCompensationMinQuality = 0; kAudioSubDeviceDriftCompensationLowQuality = $20; kAudioSubDeviceDriftCompensationMediumQuality = $40; kAudioSubDeviceDriftCompensationHighQuality = $60; kAudioSubDeviceDriftCompensationMaxQuality = $7F; {! @defined kAudioSubDeviceUIDKey @discussion The key used in a CFDictionary that describes the state of an AudioSubDevice. The value for this key is a CFString that contains the UID for the AudioSubDevice. } const kAudioSubDeviceUIDKey = 'uid'; //================================================================================================== //#pragma mark AudioSubDevice Properties {! @enum AudioSubDevice Properties @abstract AudioObjectPropertySelector values that apply to all AudioSubDevices. @discussion AudioSubDevice is a subclass of AudioDevice that is collected together with other sub-devices in an AudioAggregateDevice. AudioSubDevice objects do not implement an IO path nor any AudioDevice properties associated with the IO path. They also don't have any streams. @constant kAudioSubDevicePropertyExtraLatency A Float64 indicating the number of sample frames to add to or subtract from the latency compensation used for this AudioSubDevice. @constant kAudioSubDevicePropertyDriftCompensation A UInt32 where a value of 0 indicates that no drift compensation should be done for this AudioSubDevice and a value of 1 means that it should. @constant kAudioSubDevicePropertyDriftCompensationQuality A UInt32 that controls the trade-off between quality and CPU load in the drift compensation. The range of values is from 0 to 128, where the lower the number, the worse the quality but also the less CPU is used to do the compensation. } const kAudioSubDevicePropertyExtraLatency = FourCharCode('xltc'); kAudioSubDevicePropertyDriftCompensation = FourCharCode('drft'); kAudioSubDevicePropertyDriftCompensationQuality = FourCharCode('drfq'); //================================================================================================== end.
{$MODE OBJFPC} program TilingBricks; uses Math; const InputFile = 'BRICKS.INP'; OutputFile = 'BRICKS.OUT'; maxSize = 200; maxN = maxSize * maxSize div 2; maxM = maxN * 4; maxV = 1000; maxW = maxV * maxV * 2; maxD = maxN * maxW + 1; type THeap = record nItems: Integer; items, pos: array[1..maxN] of Integer; end; TEdge = record x, y: Integer; w: Integer; link: Integer; end; var a: array[1..maxSize, 1..maxSize] of Integer; e: array[1..maxM] of TEdge; head: array[1..maxN] of Integer; m, n, k, nE: Integer; match: array[1..maxN] of Integer; f, g: array[1..maxN] of Int64; trace: array[1..maxN] of Integer; free: array[1..maxN] of Boolean; d: array[1..maxN] of Int64; z: array[1..maxN] of Integer; nz: Integer; Heap: THeap; Res: Int64; fi, fo: TextFile; procedure Enter; var i, j: Integer; begin ReadLn(fi, m, n); m := m shl 1; n := n shl 1; for i := 1 to m do begin for j := 1 to n do Read(fi, a[i, j]); ReadLn(fi); end; end; procedure BuildGraph; const dx: array[1..4] of Integer = (0, 0, 1, -1); dy: array[1..4] of Integer = (1, -1, 0, 0); var i, j, i1, j1, p: Integer; d: Integer; black, white: Integer; map: array[1..maxSize, 1..maxSize] of Integer; begin black := 0; white := 0; for i := 1 to m do for j := 1 to n do if Odd(i + j) then begin Inc(black); map[i, j] := black; end else begin Inc(white); map[i, j]:= white; end; nE := 0; for i := 1 to m do for j := 1 to n do if Odd(i + j) then for d := 1 to 4 do begin i1 := i + dx[d]; j1 := j + dy[d]; if InRange(i1, 1, m) and InRange(j1, 1, n) then begin Inc(nE); e[nE].x := map[i, j]; e[nE].y := map[i1, j1]; e[nE].w := -a[i, j] * a[i1, j1]; end; end; k := m * n div 2; FillDWord(head[1], k, 0); for p := 1 to nE do with e[p] do begin link := head[x]; head[x] := p; end; end; function Update(v: Integer; newD: Int64): Boolean; var p, c: Integer; begin Result := d[v] > newd; if not Result then Exit; with heap do begin d[v] := newd; c := pos[v]; if c = 0 then begin Inc(nItems); c := nItems; end; repeat p := c div 2; if (p = 0) or (d[items[p]] <= newD) then Break; items[c] := items[p]; pos[items[c]] := c; c := p; until False; items[c] := v; pos[v] := c; end; end; function Extract: Integer; var v: Integer; p, c: Integer; begin with heap do begin Result := items[1]; v := items[nitems]; Dec(nitems); p := 1; repeat c := p * 2; if (c < nitems) and (d[items[c + 1]] < d[items[c]]) then Inc(c); if (c > nitems) or (d[v] <= d[items[c]]) then Break; items[p] := items[c]; pos[items[p]] := p; p := c; until False; items[p] := v; pos[v] := p; end; end; function wp(const E: TEdge): Int64; begin with e do Result := w + f[x] - g[y]; end; procedure Init; var i: Integer; begin for i := 1 to k do f[i] := maxw; FillChar(g[1], k * SizeOf(g[1]), 0); FillDWord(match[1], k, 0); with Heap do begin FillDWord(pos[1], k, 0); nItems := 0; end; for i := 1 to k do d[i] := maxD; end; procedure DijkstraInit(s: Integer); var i: Integer; begin heap.nItems := 0; i := head[s]; while i <> 0 do with e[i] do begin Update(y, wp(e[i])); trace[y] := 0; i := link; end; nz := 0; end; procedure DijkstraDestroy; var i: Integer; begin for i := 1 to nz do begin d[z[i]] := maxD; heap.pos[z[i]] := 0; end; with heap do for i := 1 to nItems do begin d[items[i]] := maxD; pos[items[i]] := 0; end; heap.nItems := 0; nz := 0; end; function Dijkstra(s: Integer): Integer; var ux, uy: Integer; i: Integer; begin DijkstraInit(s); repeat uy := Extract; ux := match[uy]; Inc(nz); z[nz] := uy; if ux = 0 then Break; i := head[ux]; while i <> 0 do with e[i] do begin if Update(y, d[uy] + wp(e[i])) then trace[y] := uy; i := link; end; until False; Result := uy; for i := 1 to nz do begin uy := z[i]; ux := match[uy]; if ux <> 0 then begin Inc(f[ux], d[uy] - d[Result]); Inc(g[uy], d[uy] - d[Result]); end; end; Inc(f[s], -d[Result]); DijkstraDestroy; end; procedure Enlarge(s, t: Integer); var next: Integer; begin repeat next := trace[t]; if next = 0 then Break; match[t] := match[next]; t := next; until False; match[t] := s; end; procedure Solve; var s, t, i: Integer; begin for s := 1 to k do begin t := Dijkstra(s); Enlarge(s, t); end; Res := 0; for i := 1 to k do Inc(Res, f[i] - g[i]); end; begin AssignFile(fi, InputFile); Reset(fi); AssignFile(fo, OutputFile); Rewrite(fo); try Enter; BuildGraph; Init; Solve; Write(fo, res); finally CloseFile(fi); CloseFile(fo); end; end. 2 3 1 2 4 7 2 7 1 7 -1 2 3 -2 -1 -4 7 -8 9 -4 -2 0 6 6 1 0
unit l3KeyboardLayoutService; // Модуль: "w:\common\components\rtl\Garant\L3\l3KeyboardLayoutService.pas" // Стереотип: "Service" // Элемент модели: "Tl3KeyboardLayoutService" MUID: (55099A8303E1) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3ProtoObject ; (* Ml3KeyboardLayoutService = interface {* Контракт сервиса Tl3KeyboardLayoutService } procedure TryActivateKeyboardLayout; end;//Ml3KeyboardLayoutService *) type Il3KeyboardLayoutService = interface {* Интерфейс сервиса Tl3KeyboardLayoutService } procedure TryActivateKeyboardLayout; end;//Il3KeyboardLayoutService Tl3KeyboardLayoutService = {final} class(Tl3ProtoObject) private f_Alien: Il3KeyboardLayoutService; {* Внешняя реализация сервиса Il3KeyboardLayoutService } protected procedure pm_SetAlien(const aValue: Il3KeyboardLayoutService); procedure ClearFields; override; public procedure TryActivateKeyboardLayout; class function Instance: Tl3KeyboardLayoutService; {* Метод получения экземпляра синглетона Tl3KeyboardLayoutService } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property Alien: Il3KeyboardLayoutService write pm_SetAlien; {* Внешняя реализация сервиса Il3KeyboardLayoutService } end;//Tl3KeyboardLayoutService implementation uses l3ImplUses , SysUtils , l3Base //#UC START# *55099A8303E1impl_uses* //#UC END# *55099A8303E1impl_uses* ; var g_Tl3KeyboardLayoutService: Tl3KeyboardLayoutService = nil; {* Экземпляр синглетона Tl3KeyboardLayoutService } procedure Tl3KeyboardLayoutServiceFree; {* Метод освобождения экземпляра синглетона Tl3KeyboardLayoutService } begin l3Free(g_Tl3KeyboardLayoutService); end;//Tl3KeyboardLayoutServiceFree procedure Tl3KeyboardLayoutService.pm_SetAlien(const aValue: Il3KeyboardLayoutService); begin Assert((f_Alien = nil) OR (aValue = nil)); f_Alien := aValue; end;//Tl3KeyboardLayoutService.pm_SetAlien procedure Tl3KeyboardLayoutService.TryActivateKeyboardLayout; //#UC START# *55099AAA0207_55099A8303E1_var* //#UC END# *55099AAA0207_55099A8303E1_var* begin //#UC START# *55099AAA0207_55099A8303E1_impl* if (f_Alien <> nil) then f_Alien.TryActivateKeyboardLayout; //#UC END# *55099AAA0207_55099A8303E1_impl* end;//Tl3KeyboardLayoutService.TryActivateKeyboardLayout class function Tl3KeyboardLayoutService.Instance: Tl3KeyboardLayoutService; {* Метод получения экземпляра синглетона Tl3KeyboardLayoutService } begin if (g_Tl3KeyboardLayoutService = nil) then begin l3System.AddExitProc(Tl3KeyboardLayoutServiceFree); g_Tl3KeyboardLayoutService := Create; end; Result := g_Tl3KeyboardLayoutService; end;//Tl3KeyboardLayoutService.Instance class function Tl3KeyboardLayoutService.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_Tl3KeyboardLayoutService <> nil; end;//Tl3KeyboardLayoutService.Exists procedure Tl3KeyboardLayoutService.ClearFields; begin Alien := nil; inherited; end;//Tl3KeyboardLayoutService.ClearFields end.
unit uGeraApuracao; interface uses FireDAC.Comp.Client, System.SysUtils; type TRetornoApuracao = record vlsAPUR_ANO : String; vldAPUR_RECEITABRUTA : Double; vldAPUR_DESPESAS : Double; vldAPUR_LUCROEVIDENCIADO : Double; vldAPUR_PORCENTAGEMISENTA : Double; vldAPUR_VALORISENTO : Double; vldAPUR_VALORTRIBUTADO : Double; vldAPUR_VALORDECLARARIR : Double; vlsAPUR_DECLARA : String; end; type TGeraApuracao = class(TObject) private FConexao : TFDConnection; FQuery : TFDQuery; FAPUR_LUCROEVIDENCIADO: Double; FAPUR_DESPESAS: Double; FAPUR_VALORTRIBUTADO: Double; FAPUR_PORCENTAGEMISENTA: Double; FAPUR_RECEITABRUTA: Double; FAPUR_VALORDECLARARIR: Double; FAPUR_VALORISENTO: Double; FAPUR_ANO: String; FAPUR_DECLARA: String; FpoRetornoApuracao: TRetornoApuracao; procedure SetAPUR_ANO(const Value: String); procedure SetAPUR_DECLARA(const Value: String); procedure SetAPUR_DESPESAS(const Value: Double); procedure SetAPUR_LUCROEVIDENCIADO(const Value: Double); procedure SetAPUR_PORCENTAGEMISENTA(const Value: Double); procedure SetAPUR_RECEITABRUTA(const Value: Double); procedure SetAPUR_VALORDECLARARIR(const Value: Double); procedure SetAPUR_VALORISENTO(const Value: Double); procedure SetAPUR_VALORTRIBUTADO(const Value: Double); procedure SetpoRetornoApuracao(const Value: TRetornoApuracao); public constructor Create(poConexao : TFDConnection); destructor Destroy; override; procedure pcdGravaApuracao; procedure pcdExcluiApuracao; function fncRetornaQtdeAnosApurados: TFDQuery; procedure pcdRetornaValoresApuracaoANO(pdAno:String); published property APUR_ANO : String read FAPUR_ANO write SetAPUR_ANO; property APUR_RECEITABRUTA : Double read FAPUR_RECEITABRUTA write SetAPUR_RECEITABRUTA; property APUR_DESPESAS : Double read FAPUR_DESPESAS write SetAPUR_DESPESAS; property APUR_LUCROEVIDENCIADO : Double read FAPUR_LUCROEVIDENCIADO write SetAPUR_LUCROEVIDENCIADO; property APUR_PORCENTAGEMISENTA : Double read FAPUR_PORCENTAGEMISENTA write SetAPUR_PORCENTAGEMISENTA; property APUR_VALORISENTO : Double read FAPUR_VALORISENTO write SetAPUR_VALORISENTO; property APUR_VALORTRIBUTADO : Double read FAPUR_VALORTRIBUTADO write SetAPUR_VALORTRIBUTADO; property APUR_VALORDECLARARIR : Double read FAPUR_VALORDECLARARIR write SetAPUR_VALORDECLARARIR; property APUR_DECLARA : String read FAPUR_DECLARA write SetAPUR_DECLARA; property poRetornoApuracao : TRetornoApuracao read FpoRetornoApuracao write SetpoRetornoApuracao; end; implementation { TGeraApuracao } constructor TGeraApuracao.Create(poConexao: TFDConnection); begin FConexao := poConexao; FQuery := TFDQuery.Create(nil); FQuery.Connection := FConexao; FQuery.Close; end; destructor TGeraApuracao.Destroy; begin if Assigned(FQuery) then FreeAndNil(FQuery); inherited; end; function TGeraApuracao.fncRetornaQtdeAnosApurados: TFDQuery; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('SELECT APUR_ANO FROM APURACAO ORDER BY APUR_ANO'); FQuery.Open; Result := FQuery; end; procedure TGeraApuracao.pcdExcluiApuracao; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('DELETE FROM APURACAO WHERE APUR_ANO = :APUR_ANO'); FQuery.ParamByName('APUR_ANO').AsString := FAPUR_ANO; FQuery.ExecSQL; end; procedure TGeraApuracao.pcdGravaApuracao; begin FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('INSERT INTO APURACAO (APUR_ANO, APUR_RECEITABRUTA, APUR_DESPESAS, APUR_LUCROEVIDENCIADO,'); FQuery.SQL.Add(' APUR_PORCENTAGEMISENTA, APUR_VALORISENTO, APUR_VALORTRIBUTADO,'); FQuery.SQL.Add(' APUR_VALORDECLARARIR, APUR_DECLARA)'); FQuery.SQL.Add('VALUES (:APUR_ANO, :APUR_RECEITABRUTA, :APUR_DESPESAS, :APUR_LUCROEVIDENCIADO,'); FQuery.SQL.Add(' :APUR_PORCENTAGEMISENTA, :APUR_VALORISENTO, :APUR_VALORTRIBUTADO,'); FQuery.SQL.Add(' :APUR_VALORDECLARARIR, :APUR_DECLARA)'); FQuery.ParamByName('APUR_ANO').AsString := FAPUR_ANO; FQuery.ParamByName('APUR_RECEITABRUTA').AsFloat := FAPUR_RECEITABRUTA; FQuery.ParamByName('APUR_DESPESAS').AsFloat := FAPUR_DESPESAS; FQuery.ParamByName('APUR_LUCROEVIDENCIADO').AsFloat := FAPUR_LUCROEVIDENCIADO; FQuery.ParamByName('APUR_PORCENTAGEMISENTA').AsFloat := FAPUR_PORCENTAGEMISENTA; FQuery.ParamByName('APUR_VALORISENTO').AsFloat := FAPUR_VALORISENTO; FQuery.ParamByName('APUR_VALORTRIBUTADO').AsFloat := FAPUR_VALORTRIBUTADO; FQuery.ParamByName('APUR_VALORDECLARARIR').AsFloat := FAPUR_VALORDECLARARIR; FQuery.ParamByName('APUR_DECLARA').AsString := FAPUR_DECLARA; FQuery.ExecSQL; end; procedure TGeraApuracao.pcdRetornaValoresApuracaoANO(pdAno: String); begin FpoRetornoApuracao.vlsAPUR_ANO := ''; FpoRetornoApuracao.vldAPUR_RECEITABRUTA := 0; FpoRetornoApuracao.vldAPUR_DESPESAS := 0; FpoRetornoApuracao.vldAPUR_LUCROEVIDENCIADO := 0; FpoRetornoApuracao.vldAPUR_PORCENTAGEMISENTA := 0; FpoRetornoApuracao.vldAPUR_VALORISENTO := 0; FpoRetornoApuracao.vldAPUR_VALORTRIBUTADO := 0; FpoRetornoApuracao.vldAPUR_VALORDECLARARIR := 0; FpoRetornoApuracao.vlsAPUR_DECLARA := ''; FQuery.Close; FQuery.SQL.Clear; FQuery.SQL.Add('SELECT APUR_ANO, APUR_RECEITABRUTA, APUR_DESPESAS, APUR_LUCROEVIDENCIADO,'); FQuery.SQL.Add(' APUR_PORCENTAGEMISENTA, APUR_VALORISENTO, APUR_VALORTRIBUTADO,'); FQuery.SQL.Add(' APUR_VALORDECLARARIR, APUR_DECLARA'); FQuery.SQL.Add('FROM APURACAO WHERE APUR_ANO = :APUR_ANO'); FQuery.ParamByName('APUR_ANO').AsString := pdAno; FQuery.Open; FpoRetornoApuracao.vlsAPUR_ANO := FQuery.FieldByName('APUR_ANO').AsString; FpoRetornoApuracao.vldAPUR_RECEITABRUTA := FQuery.FieldByName('APUR_RECEITABRUTA').AsFloat; FpoRetornoApuracao.vldAPUR_DESPESAS := FQuery.FieldByName('APUR_DESPESAS').AsFloat; FpoRetornoApuracao.vldAPUR_LUCROEVIDENCIADO := FQuery.FieldByName('APUR_LUCROEVIDENCIADO').AsFloat; FpoRetornoApuracao.vldAPUR_PORCENTAGEMISENTA := FQuery.FieldByName('APUR_PORCENTAGEMISENTA').AsFloat; FpoRetornoApuracao.vldAPUR_VALORISENTO := FQuery.FieldByName('APUR_VALORISENTO').AsFloat; FpoRetornoApuracao.vldAPUR_VALORTRIBUTADO := FQuery.FieldByName('APUR_VALORTRIBUTADO').AsFloat; FpoRetornoApuracao.vldAPUR_VALORDECLARARIR := FQuery.FieldByName('APUR_VALORDECLARARIR').AsFloat; FpoRetornoApuracao.vlsAPUR_DECLARA := FQuery.FieldByName('APUR_DECLARA').AsString; end; procedure TGeraApuracao.SetAPUR_ANO(const Value: String); begin FAPUR_ANO := Value; end; procedure TGeraApuracao.SetAPUR_DECLARA(const Value: String); begin FAPUR_DECLARA := Value; end; procedure TGeraApuracao.SetAPUR_DESPESAS(const Value: Double); begin FAPUR_DESPESAS := Value; end; procedure TGeraApuracao.SetAPUR_LUCROEVIDENCIADO(const Value: Double); begin FAPUR_LUCROEVIDENCIADO := Value; end; procedure TGeraApuracao.SetAPUR_PORCENTAGEMISENTA(const Value: Double); begin FAPUR_PORCENTAGEMISENTA := Value; end; procedure TGeraApuracao.SetAPUR_RECEITABRUTA(const Value: Double); begin FAPUR_RECEITABRUTA := Value; end; procedure TGeraApuracao.SetAPUR_VALORDECLARARIR(const Value: Double); begin FAPUR_VALORDECLARARIR := Value; end; procedure TGeraApuracao.SetAPUR_VALORISENTO(const Value: Double); begin FAPUR_VALORISENTO := Value; end; procedure TGeraApuracao.SetAPUR_VALORTRIBUTADO(const Value: Double); begin FAPUR_VALORTRIBUTADO := Value; end; procedure TGeraApuracao.SetpoRetornoApuracao(const Value: TRetornoApuracao); begin FpoRetornoApuracao := Value; end; end.
unit ssStrUtil; interface uses SysUtils, Forms, Classes, Types, Math; type TCharset = set of Char; function addLine(s: string; crp: Integer = 0): string; function addNonEmptyLine(lbl, txt: string; crp: Integer = 0): string; function addspaces(s: String; lead,tail: Integer): String; function AnsiUpperCaseEx(const S: String): String; {$IFDEF VER150}function CharInSet(c: AnsiChar; s: TCharSet): Boolean;{$ENDIF} function compareVersionNumbers(v1,v2: String): integer; {$IFNDEF PKG}function DeclineWord(Count: Int64; const Single, pluralOV, pluralA: String): String;{$ENDIF} function DeclineWordList(Count: Integer; const declensions: String): String; function DelChars(const S: String; Chrs: TCharset): String; function ExtractWord(N: Integer; const S: String; const WordDelims: TSysCharSet): String; function FindPart(const HelpWilds, InputStr: String): Integer; function IsWild(InputStr, Wilds: String; IgnoreCase: Boolean): Boolean; function PadLeft(s: string; sp: Integer): string; overload; function PadLeft(sl: TStringList; sp: Integer): string; overload; function PosEx_(const SubStr, S: String; Offset: Cardinal = 1): Integer; function ReplaceStr(const S, Srch, Replace: String): String; function ssStrToFloat(inStr: String; defaultValue: Extended = NaN): Extended; // kills non-number chars beforehand. dieOnError=True for exception raising function WordCount(const S: String; const WordDelims: TSysCharSet): Integer; function WordPosition(const N: Integer; const S: String; const WordDelims: TSysCharSet): Integer; function WordPositionEx(const SS, S: String; const WordDelims: TSysCharSet): Integer; function XorDecode(const Key, Source: String): String; function XorEncode(const Key, Source: String): String; // parses input String into array of strings procedure ExtractWords(const S: String; const WordDelims: TSysCharSet; out wlist: TStringDynArray; skipEmpty: Boolean = False); procedure parseVersionNumber(const v: String; var vp: TIntegerDynArray); //============================================================================================== //============================================================================================== //============================================================================================== implementation uses Controls, xLngDefs, StrUtils; //============================================================================================== function addLine(s: string; crp: Integer = 0): string; begin Result := ifThen( (crp and 2) = 2, #13#10, ''); if s <> '' then Result := Result + s; if (crp and 1) = 1 then Result := Result + #13#10; end; //============================================================================================== function addNonEmptyLine(lbl, txt: string; crp: Integer = 0): string; begin if Trim(txt) <> '' then Result := addLine(lbl + txt, crp); end; //============================================================================================== {$IFDEF VER150} function CharInSet(c: AnsiChar; s: TCharSet): Boolean; begin Result := c in s; end; {$ENDIF} //============================================================================================== function PadLeft(s: string; sp: Integer): string; var rs: String; begin rs := StringOfChar(' ', sp); Result := rs + AnsiReplaceStr(s, #13#10, #13#10 + rs); if AnsiEndsStr(#13#10 + rs, s) then setlength(s, length(s) - sp); // trim spaces past the last crlf end; //============================================================================================== function PadLeft(sl: TStringList; sp: Integer): string; var i: Integer; begin Result := ''; for i := 0 to sl.Count - 1 do Result := Result + PadLeft(sl[i], sp) + #13#10; end; //============================================================================================== function PosEx_(const SubStr, S: String; Offset: Cardinal = 1): Integer; var I,X: Integer; Len, LenSubStr: Integer; begin if False{Offset = 1} then Result := Pos(SubStr, S) else begin I := Offset; LenSubStr := Length(SubStr); Len := Length(S) - LenSubStr + 1; while I <= Len do begin if AnsiUpperCase(S[I]) = AnsiUpperCase(SubStr[1]) then begin X := 1; while (X < LenSubStr) and (AnsiUpperCase(S[I + X]) = AnsiUpperCase(SubStr[X + 1])) do Inc(X); if (X = LenSubStr) then begin Result := I; Exit; end; end; Inc(I); end; Result := 0; end; end; //============================================================================================== function WordPositionEx(const SS, S: String; const WordDelims: TSysCharSet): Integer; var i: Integer; begin Result := -1; for i := 1 to WordCount(S, WordDelims) do if Trim(ExtractWord(i, S, WordDelims)) = SS then begin Result := i; Exit; end; end; {$IFNDEF PKG} //============================================================================================== function DeclineWord(Count: Int64; const Single, pluralOV, pluralA: String): String; var Remainder: Integer; begin Result := ''; if (Count > 10) and (Count < 20) then Remainder := Count else Remainder := Count mod 10; case LangID of lidRUS, lidUKR: begin case Remainder of 0, 5..9, 11..19: Result := Single + pluralOV; 1: Result := Single; 2..4: Result := Single + pluralA; end; end; lidENG: begin if Count = 1 then Result := Single else Result := Single + 's'; end else begin raise Exception.Create('DeclineWord: language conversion is undefined for lang: ' + LangNames[langID]); end end; //case langID end; {$ENDIF} //============================================================================================== function DeclineWordList(Count: Integer; const declensions: String): String; begin if (Count > 9) and (Count < 20) then Result := ExtractWord(11, declensions, [',']) else Result := ExtractWord(Count mod 10, declensions, [',']); end; //============================================================================================== function AnsiUpperCaseEx(const S: String): String; var i: Integer; begin Result := ''; for i := 1 to Length(S) do if CharInSet(S[i], ['і', 'є', 'ї']) then Result := Result + S[i] else Result := Result + AnsiUpperCase(S[i]); end; //============================================================================================== function DelChars(const S: String; Chrs: TCharset): String; var I: Integer; begin Result := S; for I := Length(Result) downto 1 do if CharInSet(Result[I], Chrs) then Delete(Result, I, 1); end; //============================================================================================== function XorDecode(const Key, Source: String): String; var I: Integer; C: Char; begin Result := ''; for I := 0 to Length(Source) div 2 - 1 do begin C := Chr(StrToIntDef('$' + Copy(Source, (I * 2) + 1, 2), Ord(' '))); if Length(Key) > 0 then C := Chr(Byte(Key[1 + (I mod Length(Key))]) xor Byte(C)); Result := Result + C; end; end; //============================================================================================== function XorEncode(const Key, Source: String): String; var I: Integer; C: Byte; begin Result := ''; for I := 1 to Length(Source) do begin if Length(Key) > 0 then C := Byte(Key[1 + ((I - 1) mod Length(Key))]) xor Byte(Source[I]) else C := Byte(Source[I]); Result := Result + AnsiLowerCase(IntToHex(C, 2)); end; end; //============================================================================================== function WordCount(const S: String; const WordDelims: TSysCharSet): Integer; var SLen, I: Cardinal; begin Result := 0; I := 1; SLen := Length(S); while I <= SLen do begin while (I <= SLen) and CharInSet(S[I], WordDelims) do Inc(I); if I <= SLen then Inc(Result); while (I <= SLen) and not CharInSet(S[I], WordDelims) do Inc(I); end; end; //============================================================================================== function FindPart(const HelpWilds, InputStr: String): Integer; var I, J: Integer; Diff: Integer; begin I := Pos('?', HelpWilds); if I = 0 then begin // if no '?' in HelpWilds Result := Pos(HelpWilds, InputStr); Exit; end; // '?' in HelpWilds Diff := Length(InputStr) - Length(HelpWilds); if Diff < 0 then begin Result := 0; Exit; end; // now move HelpWilds over InputStr for I := 0 to Diff do begin for J := 1 to Length(HelpWilds) do begin if (InputStr[I + J] = HelpWilds[J]) or (HelpWilds[J] = '?') then begin if J = Length(HelpWilds) then begin Result := I + 1; Exit; end; end else Break; end; end; Result := 0; end; //============================================================================================== function IsWild(InputStr, Wilds: String; IgnoreCase: Boolean): Boolean; var CWild, CInputWord: Integer; { counter for positions } I, LenHelpWilds: Integer; MaxInputWord, MaxWilds: Integer; { Length of InputStr and Wilds } HelpWilds: String; function SearchNext(var Wilds: String): Integer; // looking for next *, returns position and String until position begin Result := Pos('*', Wilds); if Result > 0 then Wilds := Copy(Wilds, 1, Result - 1); end; begin if Wilds = InputStr then begin Result := True; Exit; end; repeat // delete '**', because '**' = '*' I := Pos('**', Wilds); if I > 0 then Wilds := Copy(Wilds, 1, I - 1) + '*' + Copy(Wilds, I + 2, MaxInt); until I = 0; if Wilds = '*' then begin { for fast end, if Wilds only '*' } Result := True; Exit; end; MaxInputWord := Length(InputStr); MaxWilds := Length(Wilds); if IgnoreCase then begin { upcase all letters } InputStr := AnsiUpperCase(InputStr); Wilds := AnsiUpperCase(Wilds); end; if (MaxWilds = 0) or (MaxInputWord = 0) then begin Result := False; Exit; end; CInputWord := 1; CWild := 1; Result := True; repeat if InputStr[CInputWord] = Wilds[CWild] then begin { equal letters } { goto next letter } Inc(CWild); Inc(CInputWord); Continue; end; if Wilds[CWild] = '?' then begin { equal to '?' } { goto next letter } Inc(CWild); Inc(CInputWord); Continue; end; if Wilds[CWild] = '*' then begin { handling of '*' } HelpWilds := Copy(Wilds, CWild + 1, MaxWilds); I := SearchNext(HelpWilds); LenHelpWilds := Length(HelpWilds); if I = 0 then begin { no '*' in the rest, compare the ends } if HelpWilds = '' then Exit; { '*' is the last letter } { check the rest for equal Length and no '?' } for I := 0 to LenHelpWilds - 1 do begin if (HelpWilds[LenHelpWilds - I] <> InputStr[MaxInputWord - I]) and (HelpWilds[LenHelpWilds - I]<> '?') then begin Result := False; Exit; end; end; Exit; end; { handle all to the next '*' } Inc(CWild, 1 + LenHelpWilds); I := FindPart(HelpWilds, Copy(InputStr, CInputWord, MaxInt)); if I= 0 then begin Result := False; Exit; end; CInputWord := I + LenHelpWilds; Continue; end; Result := False; Exit; until (CInputWord > MaxInputWord) or (CWild > MaxWilds); { no completed evaluation } if CInputWord <= MaxInputWord then Result := False; if (CWild <= MaxWilds) and (Wilds[MaxWilds] <> '*') then Result := False; end; //============================================================================================== function ReplaceStr(const S, Srch, Replace: String): String; var I: Integer; Source: String; begin Source := S; Result := ''; repeat I := Pos(Srch, Source); if I > 0 then begin Result := Result + Copy(Source, 1, I - 1) + Replace; Source := Copy(Source, I + Length(Srch), MaxInt); end else Result := Result + Source; until I <= 0; end; //============================================================================================== function WordPosition(const N: Integer; const S: String; const WordDelims: TSysCharSet): Integer; var Count, I: Integer; begin Count := 0; I := 1; Result := 0; while (I <= Length(S)) and (Count <> N) do begin { skip over delimiters } while (I <= Length(S)) and CharInSet(S[I], WordDelims) do Inc(I); { if we're not beyond end of S, we're at the start of a word } if I <= Length(S) then Inc(Count); { if not finished, find the end of the current word } if Count <> N then while (I <= Length(S)) and not CharInSet(S[I], WordDelims) do Inc(I) else Result := I; end; end; //============================================================================================== function ExtractWord(N: Integer; const S: String; const WordDelims: TSysCharSet): String; var start,I,slen: Integer; begin Result := ''; slen := Length(S); start := WordPosition(N, S, WordDelims); if start <> 0 then begin i := start + 1; while (I <= slen) and not(CharInSet(S[I], WordDelims)) do inc(i); Result := AnsiMidStr(s, start, i - start); end; end; //============================================================================================== // parses input String into array of strings procedure ExtractWords(const S: String; const WordDelims: TSysCharSet; out wlist: TStringDynArray; skipEmpty: Boolean = False); var I,currword,slen,start: Integer; begin if s = '' then Exit; slen := length(s) + 1; // to make last char counted currword := -1; // current word index in wlist start := 1; // current word begin pos for i := 1 to slen do if (i = slen) or (CharInSet(s[i], WordDelims)) then begin // adding new word if not skipEmpty or (skipEmpty and (i > start)) then begin inc(currword); if High(wlist) < currword then setLength(wlist, currword + 1); wlist[currword] := ''; if i > start then wlist[currword] := AnsiMidStr(s, start, i - start); start := i + 1; end; if i = slen then Exit; end; end; //============================================================================================== function addspaces(s: String; lead,tail: Integer): String; begin Result := StringOfChar(' ',lead) + s + StringOfChar(' ',tail); end; //============================================================================================== procedure parseVersionNumber(const v: String; var vp: TIntegerDynArray); var i: Integer; strarr: TStringDynArray; begin ExtractWords(v, ['.', '/', ' ', '_', '-'], strarr); if High(strarr) > 3 then SetLength(strarr, 4); SetLength(vp,4); for i := 0 to 3 do if i > High(strarr) then vp[i] := 0 else try vp[i] := StrToInt(strarr[i]); except if i = 0 then vp[i] := -1 else vp[i] := 0; end; end; //============================================================================================== // NOTE! this func used also in comparing file names function compareVersionNumbers(v1,v2: String): integer; var i: Integer; av1, av2: TIntegerDynArray; begin parseVersionNumber(v1, av1); parseVersionNumber(v2, av2); Result := 0; for i := 0 to 3 do begin if av1[i] < av2[i] then begin Result := -1; Break; end else if av1[i] > av2[i] then begin Result := 1; Break; end; end; //writeln('!D: compareVer: ' + v1 + '(' + IntToStr(av1[0]) + '.' + IntToStr(av1[1]) + '.' + IntToStr(av1[2]) + '.' + IntToStr(av1[3]) + ') <=> ' + v2 + '(' + IntToStr(av2[0]) + '.' + IntToStr(av2[1]) + '.' + IntToStr(av2[2]) + '.' + IntToStr(av2[3]) + ') = ' + IntTostr(Result)); end; //============================================================================================== // kills non-number chars beforehand // Посвящается Мудакам, которые обрабатывают данные не из оригинального датасета, а из ячейки таблицы с пририсованной хуйнёй по бокам. function ssStrToFloat(inStr: String; defaultValue: Extended = NaN): Extended; const errMsg: String = 'ssStrToFloat: crappy input: '; var i,l: Integer; hasDP, hasDigits: Boolean; s: String; begin Result := defaultValue; l := length(inStr); i := 1; while (i <= l) and not (CharInSet(inStr[i], ['0'..'9', '+', '-'])) do inc(i); // skipping head garbage if i > l then if isNaN(defaultValue) then raise Exception.Create(errMsg + inStr) else Exit; if CharInSet(inStr[i], ['+', '-']) then begin s := inStr[i]; inc(i); end else s := ''; hasDP := False; // controls garbage decimal point chars hasdigits := False; // for number sanity check while i <= l do begin if CharInSet(inStr[i], [' ', chr($A0)]) then begin // spaces may be used as thousands separator. $a0 is special grid-dy case inc(i); Continue; end else if CharInSet(inStr[i], [',', '.']) then begin if hasDP // garbage decimal point then if isNaN(defaultValue) then raise Exception.Create(errMsg + inStr) else Exit; hasDP := True; s := s + decimalSeparator; // for we'll always be in correct locale inc(i); Continue; end else if CharInSet(inStr[i], ['0'..'9']) then hasDigits := True else Break; // tail garbage s := s + inStr[i]; inc(i); end; if hasDigits then try Result := StrToFloat(s); except if isNaN(defaultValue) then raise Exception.Create(errMsg + inStr) end; end; end.
unit FrmMain; //uses NLDJoystick created by Albert de Weerd (aka NGLN) //https://www.nldelphi.com/showthread.php?29812-NLDJoystick //http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDJoystick/ interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, NLDJoystick, Vcl.StdCtrls; type TMainForm = class(TForm) JoyPad: TNLDJoystick; tmrJoyenable: TTimer; lblInfo: TLabel; procedure tmrJoyenableTimer(Sender: TObject); procedure JoyPadButtonDown(Sender: TNLDJoystick; const Buttons: TJoyButtons); procedure FormCreate(Sender: TObject); procedure JoyPadMove(Sender: TNLDJoystick; const JoyPos: TJoyRelPos; const Buttons: TJoyButtons); procedure JoyPadPOVChanged(Sender: TNLDJoystick; Degrees: Single); private { Private declarations } FLastJoyButton: Integer; FLastJoyRelPos: TJoyRelPos; FLastPOVDegrees: Single; function ButtonSetLength(Buttons: TJoyButtons): Integer; function ButtonValueFromButtons(Buttons: TJoyButtons): Integer; procedure UpdateLabel; public { Public declarations } end; var MainForm: TMainForm; implementation uses System.Math, Winapi.MMSystem; {$R *.dfm} procedure TMainForm.UpdateLabel; begin if not JoyPad.Active then begin lblInfo.Caption := 'Please Attach a joypad / joystick'; exit; end; if FLastJoyButton = -1 then lblInfo.Caption := 'Please Press a single button only' else if FLastJoyButton = -2 then lblInfo.Caption := 'Please Press a single button only (Multiple detected)' else lblInfo.Caption := 'Last (single) button pressed: ' + IntToStr(FLastJoyButton); if axX in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad X-Axis (Value = ' + IntToStr(Integer(axX)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.X, -2)); if axY in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad Y-Axis (Value = ' + IntToStr(Integer(axY)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.Y, -2)); if axZ in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad Z-Axis (Value = ' + IntToStr(Integer(axZ)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.Z, -2)); if axR in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad R-Axis (Value = ' + IntToStr(Integer(axR)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.R, -2)); if axU in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad U-Axis (Value = ' + IntToStr(Integer(axU)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.U, -2)); if axV in JoyPad.Axises then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad V-Axis (Value = ' + IntToStr(Integer(axV)) + '): ' + FloatToStr(RoundTo(FLastJoyRelPos.V, -2)); if FLastPOVDegrees > 360 then lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad POV Degrees: Centered' else lblInfo.Caption := lblInfo.Caption + #13#10 + 'Joypad POV Degrees: ' + FloatToStr(RoundTo(FLastPOVDegrees, -2)); end; function TMainForm.ButtonValueFromButtons(Buttons: TJoyButtons): Integer; var Button: TJoyButton; begin Result := -1; for Button in Buttons do begin Result := Integer(Button); break; end; end; function TMainForm.ButtonSetLength(Buttons: TJoyButtons): Integer; var Button: TJoyButton; begin Result := 0; for Button in Buttons do inc(Result); end; procedure TMainForm.FormCreate(Sender: TObject); begin FLastJoyButton := -1; end; procedure TMainForm.JoyPadButtonDown(Sender: TNLDJoystick; const Buttons: TJoyButtons); begin if ButtonSetLength(Buttons) <> 1 then FLastJoyButton := -2 else FLastJoyButton := ButtonValueFromButtons(Buttons); UpdateLabel; end; procedure TMainForm.JoyPadMove(Sender: TNLDJoystick; const JoyPos: TJoyRelPos; const Buttons: TJoyButtons); begin FLastJoyRelPos := JoyPos; UpdateLabel; end; procedure TMainForm.JoyPadPOVChanged(Sender: TNLDJoystick; Degrees: Single); begin FLastPOVDegrees := Degrees; end; procedure TMainForm.tmrJoyenableTimer(Sender: TObject); begin if not JoyPad.Active then begin JoyPad.Active := True; if JoyPad.Active then begin tmrJoyenable.Enabled := false; UpdateLabel; end; end else UpdateLabel; end; end.
{ The abstract factory is a class that creates components and returns them to the caller as their abstract types. In this case I chose interfaces over the abstract classes as used in the samples of the book. Any number of concrete classes can implement the factory interface. The consumer in this case does not see the implementation, but just the resultant products. } unit AbstractFactory; interface uses system.generics.collections; type IMaze = interface // definition not important for illustration end; IWall = interface // definition not important for illustration end; IRoom = interface // definition not important for illustration end; IDoor = interface // definition not important for illustration end; IMazeFactory = interface function MakeMaze: IMaze; function MakeWall: IWall; function MakeRoom(ANumber: integer): TArray<IRoom>; function MakeDoor(AFromRoom, AToRoom: IRoom): IDoor; end; // We can pass the factory as a parameter for example // MazeGame.CreateMaze(AFactory); // The game in turn can create the maze in an abstract way. implementation end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.8 7/23/04 6:36:54 PM RLebeau { Added extra exception handling to Open() } { { Rev 1.7 2004.05.20 12:34:30 PM czhower { Removed more non .NET compatible stream read and writes } { { Rev 1.6 2004.02.03 4:17:16 PM czhower { For unit name changes. } { { Rev 1.5 2003.10.17 6:15:54 PM czhower { Upgrades } { { Rev 1.4 2003.10.16 11:24:36 AM czhower { Bug fix } { Rev 1.3 10/15/2003 8:00:10 PM DSiders Added resource string for exception raised in TIdLogFile.SetFilename. } { { Rev 1.2 2003.10.14 1:27:10 PM czhower { Uupdates + Intercept support } { { Rev 1.1 6/16/2003 11:01:06 AM EHill { Throw exception if the filename is set while the log is open. { Expose Open and Close as public instead of protected. } { { Rev 1.0 11/13/2002 07:56:12 AM JPMugaas } unit IdLogFile; { Revision History: 19-Aug-2001 DSiders Fixed bug in Open. Use file mode fmCreate when Filename does *not* exist. 19-Aug-2001 DSiders Added protected method TIdLogFile.LogWriteString. 19-Aug-2001 DSiders Changed implementation of TIdLogFile methods LogStatus, LogReceivedData, and LogSentData to use LogWriteString. 19-Aug-2001 DSiders Added class TIdLogFileEx with the LogFormat method. } interface uses IdLogBase, IdObjs; type TIdLogFile = class(TIdLogBase) protected FFilename: String; FFileStream: TIdStream; // procedure LogFormat(AFormat: string; AArgs: array of const); virtual; procedure LogReceivedData(AText: string; AData: string); override; procedure LogSentData(AText: string; AData: string); override; procedure LogStatus(AText: string); override; procedure LogWriteString(AText: string); virtual; // procedure SetFilename(AFilename: String); public procedure Open; override; procedure Close; override; published property Filename: String read FFilename write SetFilename; end; implementation uses IdGlobal, IdException, IdResourceStringsCore, IdSys, IdBaseComponent; { TIdLogFile } procedure TIdLogFile.Close; begin Sys.FreeAndNil(FFileStream); end; procedure TIdLogFile.LogReceivedData(AText, AData: string); begin LogWriteString(RSLogRecv + AText + ': ' + AData + EOL); {Do not translate} end; procedure TIdLogFile.LogSentData(AText, AData: string); begin LogWriteString(RSLogSent + AText + ': ' + AData + EOL); {Do not translate} end; procedure TIdLogFile.LogStatus(AText: string); begin LogWriteString(RSLogStat + AText + EOL); end; procedure TIdLogFile.Open; begin if not IsDesignTime then begin FFileStream := TAppendFileStream.Create(Filename); end; end; procedure TIdLogFile.LogWriteString(AText: string); begin WriteStringToStream(FFileStream, AText); end; procedure TIdLogFile.LogFormat(AFormat: string; AArgs: array of const); var sPre: string; sMsg: string; sData: string; begin // forces Open to be called prior to Connect if not Active then begin Active := True; end; sPre := ''; {Do not translate} sMsg := ''; {Do not translate} if LogTime then begin sPre := Sys.DateTimeToStr(Sys.Now) + ' ' ; {Do not translate} end; sData := Sys.Format(AFormat, AArgs); if FReplaceCRLF then begin sData := ReplaceCR(sData); end; sMsg := sPre + sData + EOL; LogWriteString(sMsg); end; procedure TIdLogFile.SetFilename(AFilename: String); begin EIdException.IfAssigned(FFileStream, RSLogFileAlreadyOpen); FFilename := AFilename; end; end.
program programadores; procedure leerDatos(var legajo: integer; salario : real); // Salario no se pasa por referencia // Entonces no se actualiza el valor afuera del procedimiento begin writeln(‘Ingrese el nro de legajo y el salario”); read(legajo); read(salario); end; procedure actualizarMaximo( nuevoLegajo :integer; nuevoSalario :real; var maxLegajo :integer ); var maxSalario : real; begin if (nuevoLegajo > maxLegajo) then begin maxLegajo:= nuevoLegajo; maxSalario := nuevoSalario // maxSalario es una variable local al procedimiento y no se devuelve // de ninguna forma, por lo que el algoritmo no funciona end; end; var legajo, maxLegajo, i :integer; salario, maxSalario :real; begin sumaSalarios := 0; // La variable no está declarada for i := 1 to 130 do begin leerDatos(salario, legajo); // Están invertidos los parámetros y no están inicializados actualizarMaximo(legajo, salario, maxLegajo); // maxLegajo no está inicializada sumaSalarios := sumaSalarios + salario; end; writeln(‘En todo el mes se gastan ‘, sumaSalarios, ‘ pesos’); writeln(‘El salario del empleado más nuevo es ‘,maxSalario); end.
unit StringUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TStringUtils } TStringUtils = class class function GetWordAtCursor(const S: string; CursorPos: Integer): string; end; implementation { TStringUtils } class function TStringUtils.GetWordAtCursor(const S: string; CursorPos: Integer): string; var StartPos, EndPos: Integer; begin if (CursorPos = 0) or (CursorPos > Length(S)) then Exit(''); for StartPos := CursorPos downto 1 do if S[StartPos-1] = ' ' then break; for EndPos := CursorPos to Length(S) do if S[EndPos+1] = ' ' then break; Result := Copy(S, StartPos, EndPos - StartPos+1); end; end.
unit VideoLoader; {$WARN SYMBOL_PLATFORM OFF} {$PointerMath ON} interface uses Windows, ActiveX, Classes, ComObj, Video2Matrix_TLB, StdVcl, PrivLoader, SysUtils, Vcl.Graphics; const MAX_THUMB_WIDTH = 320; MAX_THUMB_HEIGHT = 240; BYTES_PER_PIXEL = 3; SUPPORTED_FILETYPES: array [0 .. 5] of string = ('*.mp4', '*.avi', '*.mpg', '*.m4v', '*.mov', '*.wmv'); type TVideoHandle = record loader: TPrivLoader; meta: TVideoMetaData; renderWidth, renderHeight: Integer; matrixW, matrixH: Integer; matrixBitmap, matrixBitmap2: TBitmap; // previewFrames: ^TBitmap; numPreviewFrames: Integer; frameSizeBytes: Integer; frameAccum: Integer; numFramesRendered: Integer; end; PVideoHandle = ^TVideoHandle; TVideoLoader = class(TTypedComObject, IVideoLoader) private mNothing: String; protected function Init: HResult; stdcall; function TryLoad(const videoPath, thumbsPath: WideString; var videoInfo: TVideoInfo; out success: WordBool): HResult; stdcall; // utility procedure to fit a video's dimensions into an arbitrary frame // should be static / not part of this object, but I don't know how to export those yet function FitFrame(origW, origH: Integer; maxW, maxH: Integer; out outW, outH: Integer): HResult; stdcall; function OpenVideo(const filename: WideString; var maxW, maxH: Integer; out outHandle: Integer): HResult; stdcall; function CloseVideo(videoHandle: Integer): HResult; stdcall; function SeekVideo(videoHandle, frame: Integer): HResult; stdcall; function SetMatrixSize(videoHandle, width, height: Integer): HResult; stdcall; function AllocPreviewFrames(videoHandle, maxPreviewFrames: Integer): HResult; stdcall; function FreePreviewFrames(videoHandle: Integer): HResult; stdcall; function RenderPreviewFrame(videoHandle: Integer; out retVal: WordBool): HResult; stdcall; function TotalFrames(videoHandle: Integer; out numFrames: Integer): HResult; stdcall; function GetCachedFrame(videoHandle, frameNum: Integer; var dest: Byte): HResult; stdcall; function GetCachedMatrix(videoHandle, frameNum, cropX, cropY, cropW, cropH: Integer; var dest: Byte; blendFrames: WordBool): HResult; stdcall; function GetFullMatrix(videoHandle, frameNum, cropX, cropY, cropW, cropH: Integer; var dest: Byte): HResult; stdcall; function CurrentFrame(videoHandle: Integer; out retVal: Integer): HResult; stdcall; function GetMatrixWH(videoHandle: Integer; out outW, outH: Integer): HResult; stdcall; end; procedure WriteBitmap(bmp: TBitmap; dest: Pointer); stdcall; procedure FrameToCachedIndex(handle: PVideoHandle; frameNum: Integer; out cachedIndex: Integer; out tween1024: Integer); stdcall; function MixColors(startColor, endColor: TColor; tween1024: Integer): TColor; inline; function Red(color: TColor): byte; inline; function Green(color: TColor): byte; inline; function Blue(color: TColor): byte; inline; implementation uses ComServ; function TVideoLoader.FitFrame(origW, origH: Integer; maxW, maxH: Integer; out outW, outH: Integer): HResult; stdcall; begin // try fitting to width first outW := maxW; outH := (maxW * origH) div origW; if outH > maxH then // nope, was too tall begin outH := maxH; outW := (maxH * origW) div origH; end; result := S_OK; end; function TVideoLoader.Init: HResult; begin // might eventually do initialization here -- but nothing yet result := S_OK; end; function TVideoLoader.TryLoad(const videoPath, thumbsPath: WideString; var videoInfo: TVideoInfo; out success: WordBool): HResult; var loader: TPrivLoader; error: String; metaData: TVideoMetaData; errorFile: TextFile; fnameStr: AnsiString; thumbWidth, thumbHeight: Integer; outBitmap: TBitmap; thumbFname: String; begin loader := TPrivLoader.Create; fnameStr := AnsiString(videoPath); if loader.Open(fnameStr, error, metaData) then begin // make a thumbnail and all that fun stuff with videoInfo do begin isValid := True; { generate thumb and save to file } filename := videoPath; width := metaData.width; height := metaData.height; duration := metaData.duration; avgFrameRate := metaData.avgFrameRate; estNumFrames := loader.TotalFrames; // fit video aspect into min/max size, save in thumbWidth/Height FitFrame(width, height, MAX_THUMB_WIDTH, MAX_THUMB_HEIGHT, thumbWidth, thumbHeight); loader.SetRenderSize(thumbWidth, thumbHeight); outBitmap := TBitmap.Create; outBitmap.PixelFormat := pf24bit; outBitmap.width := thumbWidth; outBitmap.height := thumbHeight; loader.SeekAbs(loader.TotalFrames div 4); // seek to 25% point to skip any intro/fade-in frames loader.NextFrame(); loader.CopyLastFrame(outBitmap); // create thumbs dir if it doesn't exist if not DirectoryExists(thumbsPath) then if not CreateDir(thumbsPath) then raise Exception.Create('unable to create directory for thumbnails'); // save thumb thumbFname := Format('%s\%s-thumb.bmp', [thumbsPath, SysUtils.ExtractFileName(filename)]); outBitmap.SaveToFile(thumbFname); videoInfo.thumbFilename := thumbFname; outBitmap.FreeImage; outBitmap.Free; end; success := True; end else begin // write error AssignFile(errorFile, 'loader_error.txt'); Rewrite(errorFile); WriteLn(errorFile, Format('error was: <<%s>>', [error])); CloseFile(errorFile); videoInfo.isValid := False; success := False; end; loader.Free; result := S_OK; end; function TVideoLoader.OpenVideo(const filename: WideString; var maxW, maxH: Integer; out outHandle: Integer): HResult; var handle: PVideoHandle; err: String; begin New(handle); with handle^ do begin loader := TPrivLoader.Create(); if loader.Open(filename, err, meta) then begin FitFrame(meta.width, meta.height, maxW, maxH, renderWidth, renderHeight); loader.SetRenderSize(renderWidth, renderHeight); // let the client know what the max dimensions really are maxW := renderWidth; maxH := renderHeight; end; previewFrames := nil; end; outHandle := UInt32(handle); result := S_OK; end; function TVideoLoader.CloseVideo(videoHandle: Integer): HResult; var handle: PVideoHandle; begin handle := PVideoHandle(videoHandle); with handle^ do begin if loader <> nil then begin loader.Free; end; if matrixBitmap <> nil then begin matrixBitmap.FreeImage; matrixBitmap.Free; end; if matrixBitmap2 <> nil then begin matrixBitmap2.FreeImage; matrixBitmap2.Free; end; if previewFrames <> nil then begin // generally the client code will do this, but whatever FreePreviewFrames(UInt32(handle)); end; end; Dispose(handle); result := S_OK; end; function TVideoLoader.FreePreviewFrames(videoHandle: Integer): HResult; var i: Integer; begin with PVideoHandle(videoHandle)^ do begin for i := 0 to numPreviewFrames - 1 do begin previewFrames[i].FreeImage; previewFrames[i].Free; end; FreeMem(previewFrames); previewFrames := nil; end; result := S_OK; end; function TVideoLoader.SeekVideo(videoHandle, frame: Integer): HResult; begin PVideoHandle(videoHandle)^.loader.SeekAbs(frame); result := S_OK; end; function TVideoLoader.SetMatrixSize(videoHandle, width, height: Integer): HResult; begin with PVideoHandle(videoHandle)^ do begin matrixW := width; matrixH := height; matrixBitmap := TBitmap.Create; matrixBitmap.PixelFormat := pf24bit; matrixBitmap.width := width; matrixBitmap.height := height; matrixBitmap2 := TBitmap.Create; matrixBitmap2.PixelFormat := pf24bit; matrixBitmap2.width := width; matrixBitmap2.height := height; end; result := S_OK; end; function TVideoLoader.AllocPreviewFrames(videoHandle, maxPreviewFrames: Integer): HResult; var divisor: Integer; i: Integer; begin with PVideoHandle(videoHandle)^ do begin numPreviewFrames := loader.TotalFrames; divisor := 2; while numPreviewFrames > maxPreviewFrames do begin numPreviewFrames := loader.TotalFrames div divisor; Inc(divisor); end; frameSizeBytes := renderWidth * renderHeight * BYTES_PER_PIXEL; previewFrames := GetMemory(SizeOf(TBitmap) * numPreviewFrames); for i := 0 to numPreviewFrames - 1 do begin previewFrames[i] := TBitmap.Create; previewFrames[i].PixelFormat := pf24bit; previewFrames[i].width := renderWidth; previewFrames[i].height := renderHeight; end; numFramesRendered := 0; frameAccum := loader.TotalFrames; // start on the first available frame end; result := S_OK; end; function IntToBool(inValue: Integer): Boolean; begin result := (inValue <> 0); end; function boolToInt(inValue: Boolean): Integer; begin if inValue then result := 1 else result := 0; end; function TVideoLoader.RenderPreviewFrame(videoHandle: Integer; out retVal: WordBool): HResult; begin with PVideoHandle(videoHandle)^ do begin if numFramesRendered >= numPreviewFrames then begin // there might be a bit more video left, but we're already full retVal := False; result := S_OK; exit; end; retVal := loader.NextFrame(); // is this a wanted frame? if frameAccum >= loader.TotalFrames then begin loader.CopyLastFrame(previewFrames[numFramesRendered]); // TODO: fix this to resemble TSeqPreviewForm.RenderSequence frameAccum := frameAccum - loader.TotalFrames; Inc(numFramesRendered); end; Inc(frameAccum, numPreviewFrames); end; result := S_OK; end; function TVideoLoader.TotalFrames(videoHandle: Integer; out numFrames: Integer): HResult; begin with PVideoHandle(videoHandle)^ do begin numFrames := loader.TotalFrames; end; result := S_OK; end; function TVideoLoader.GetCachedFrame(videoHandle, frameNum: Integer; var dest: Byte): HResult; var cachedIndex: Integer; tween1024: Integer; handle: PVideoHandle; begin handle := PVideoHandle(videoHandle); FrameToCachedIndex(handle, frameNum, cachedIndex, tween1024); WriteBitmap(handle^.previewFrames[cachedIndex], @dest); result := S_OK; end; procedure WriteBitmap(bmp: TBitmap; dest: Pointer); stdcall; var y: Integer; destLine: Pointer; begin for y := 0 to bmp.height - 1 do begin destLine := PByte(UInt32(dest) + (y * bmp.width * 3)); Move(bmp.ScanLine[y]^, destLine^, bmp.width * 3); end; end; procedure FrameToCachedIndex(handle: PVideoHandle; frameNum: Integer; out cachedIndex: Integer; out tween1024: Integer); stdcall; var total: Integer; previewFrame, nextPreviewFrame: Integer; begin total := handle.loader.TotalFrames; if (frameNum < 0) or (frameNum >= total) then begin raise Exception.Create('invalid frame number in FrameToCachedIndex'); end; cachedIndex := (frameNum * handle^.numPreviewFrames) div total; previewFrame := (cachedIndex * total) div handle^.numPreviewFrames; nextPreviewFrame := ((cachedIndex + 1) * total) div handle^.numPreviewFrames; tween1024 := ((frameNum - previewFrame) * 1024) div (nextPreviewFrame - previewFrame); // 1/1024th of the range between preview frames end; function TVideoLoader.GetCachedMatrix(videoHandle, frameNum, cropX, cropY, cropW, cropH: Integer; var dest: Byte; blendFrames: WordBool): HResult; var cachedIndex, tween1024: Integer; destRect, cropRect: TRect; srcBitmap: TBitmap; // a, b, mixed: TColor; x, y: Integer; handle: PVideoHandle; begin handle := PVideoHandle(videoHandle); with handle^ do begin destRect.Left := 0; destRect.Top := 0; destRect.Right := matrixW; destRect.Bottom := matrixH; cropRect.Left := cropX; cropRect.Top := cropY; cropRect.Right := cropX + cropW; cropRect.Bottom := cropY + cropH; FrameToCachedIndex(handle, frameNum, cachedIndex, tween1024); // hack! // below is the simple version we can't do // matrixBitmap.Canvas.CopyRect(destRect, previewFrames[cachedIndex].Canvas, cropRect); // accessing the .Canvas of a bitmap creates it, which consumes probably 2x the memory // there doesn't seem to be any way to free the canvas alone and not the whole bitmap // with up to 300 preview frames allocated, that wastes a ton of memory // so here we create a duplicate bitmap -- and this requires modifying it, // or else it just references the original bitmap/canvas, defeating the whole purpose. // anyway, this way we can actually free the canvas by freeing the whole (copied) bitmap srcBitmap := TBitmap.Create; srcBitmap.Assign(previewFrames[cachedIndex]); srcBitmap.Canvas.Pixels[0, 0] := RGB(0, 0, 0); // relatively harmless modification to trigger copy, so we're not in effect allocating the .Canvas on the source previewFrame matrixBitmap.Canvas.CopyRect(destRect, srcBitmap.Canvas, cropRect); if blendFrames and ((cachedIndex + 1) < numPreviewFrames) then begin // handle blending between two separate steps srcBitmap.Assign(previewFrames[cachedIndex + 1]); srcBitmap.Canvas.Pixels[0, 0] := RGB(0, 0, 0); // the silly modification -- see big comment above matrixBitmap2.Canvas.CopyRect(destRect, srcBitmap.Canvas, cropRect); for y := 0 to matrixH - 1 do begin for x := 0 to matrixW - 1 do begin matrixBitmap.Canvas.Pixels[x, y] := MixColors(matrixBitmap.Canvas.Pixels[x, y], matrixBitmap2.Canvas.Pixels[x, y], tween1024); end; end; end; WriteBitmap(matrixBitmap, @dest); srcBitmap.FreeImage; srcBitmap.Free; end; result := S_OK; end; function Red(color: TColor): byte; inline; begin result := (color and $FF); end; function Green(color: TColor): byte; inline; begin result := (color and $FF00) shr 8; end; function Blue(color: TColor): byte; inline; begin result := (color and $FF0000) shr 16; end; function MixColors(startColor, endColor: TColor; tween1024: Integer): TColor; inline; var r1, g1, b1: Integer; r2, g2, b2: Integer; outR, outG, outB: Integer; begin r1 := Red(startColor); r2 := Red(endColor); outR := r1 + ((r2 - r1) * tween1024) div 1024; g1 := Green(startColor); g2 := Green(endColor); outG := g1 + ((g2 - g1) * tween1024) div 1024; b1 := Blue(startColor); b2 := Blue(endColor); outB := b1 + ((b2 - b1) * tween1024) div 1024; result := RGB(outR, outG, outB); end; function TVideoLoader.GetFullMatrix(videoHandle, frameNum, cropX, cropY, cropW, cropH: Integer; var dest: Byte): HResult; var srcBitmap: TBitmap; destRect, cropRect: TRect; handle: PVideoHandle; begin handle := PVideoHandle(videoHandle); with handle^ do begin // problem: we don't want to advance needlessly (calling NextFrame() when not required) // but we also need CurrentFrame() to be initialized somehow while loader.CurrentFrame < frameNum do begin if not loader.NextFrame() then begin // no more frames, do nothing result := S_OK; exit; end; // else keep looping end; srcBitmap := TBitmap.Create; srcBitmap.PixelFormat := pf24bit; srcBitmap.width := renderWidth; srcBitmap.height := renderHeight; loader.CopyLastFrame(srcBitmap); destRect.Left := 0; destRect.Top := 0; destRect.Right := matrixW; destRect.Bottom := matrixH; cropRect.Left := cropX; cropRect.Top := cropY; cropRect.Right := cropX + cropW; cropRect.Bottom := cropY + cropH; matrixBitmap.Canvas.CopyRect(destRect, srcBitmap.Canvas, cropRect); WriteBitmap(matrixBitmap, @dest); srcBitmap.FreeImage; srcBitmap.Free; end; result := S_OK; end; function TVideoLoader.CurrentFrame(videoHandle: Integer; out retVal: Integer): HResult; begin with PVideoHandle(videoHandle)^ do begin retVal := loader.CurrentFrame; end; result := S_OK; end; function TVideoLoader.GetMatrixWH(videoHandle: Integer; out outW, outH: Integer): HResult; begin with PVideoHandle(videoHandle)^ do begin outW := matrixW; outH := matrixH; end; result := S_OK; end; initialization TTypedComObjectFactory.Create(ComServer, TVideoLoader, Class_VideoLoader, ciMultiInstance, tmApartment); end.
namespace Sugar.Xml; interface uses {$IF COOPER} org.w3c.dom, {$ELSEIF ECHOES} System.Xml.Linq, System.Linq, {$ELSEIF TOFFEE} Foundation, {$ENDIF} Sugar, Sugar.IO; type XmlDocument = public class (XmlNode) private {$IF COOPER} class method ParseXml(Content: String; BaseUri: String): not nullable XmlDocument; property Doc: Document read Node as Document; {$ELSEIF ECHOES} property Doc: XDocument read Node as XDocument; {$ELSEIF TOFFEE} property Doc: ^libxml.__struct__xmlDoc read ^libxml.__struct__xmlDoc(Node); method GetDocumentElement: XmlElement; method GetDocumentType: XmlDocumentType; {$ENDIF} method GetElement(Name: String): XmlElement; public {$IF ECHOES} property DocumentElement: XmlElement read iif(Doc.Root = nil, nil, new XmlElement(Doc.Root)); property DocumentType: XmlDocumentType read iif(Doc.DocumentType = nil, nil, new XmlDocumentType(Doc.DocumentType)); {$ELSEIF COOPER} property DocumentElement: XmlElement read iif(Doc.DocumentElement = nil, nil, new XmlElement(Doc.DocumentElement)); property DocumentType: XmlDocumentType read iif(Doc.Doctype = nil, nil, new XmlDocumentType(Doc.Doctype)); {$ELSEIF TOFFEE} property DocumentElement: XmlElement read GetDocumentElement; property DocumentType: XmlDocumentType read GetDocumentType; {$ENDIF} property NodeType: XmlNodeType read XmlNodeType.Document; override; property Element[Name: String]: XmlElement read GetElement; default; method AddChild(Node: XmlNode); method RemoveChild(Node: XmlNode); method ReplaceChild(Node: XmlNode; WithNode: XmlNode); method CreateAttribute(Name: String): XmlAttribute; method CreateAttribute(QualifiedName: String; NamespaceUri: String): XmlAttribute; method CreateXmlNs(Prefix: String; NamespaceUri: String): XmlAttribute; method CreateCDataSection(Data: String): XmlCDataSection; method CreateComment(Data: String): XmlComment; method CreateElement(Name: String): XmlElement; method CreateElement(QualifiedName: String; NamespaceUri: String): XmlElement; method CreateProcessingInstruction(Target, Data: String): XmlProcessingInstruction; method CreateTextNode(Data: String): XmlText; method GetElementsByTagName(Name: String): array of XmlElement; method GetElementsByTagName(LocalName, NamespaceUri: String): array of XmlElement; class method FromFile(aFile: File): not nullable XmlDocument; class method FromBinary(aBinary: Binary): not nullable XmlDocument; class method FromString(aString: String): not nullable XmlDocument; class method CreateDocument: not nullable XmlDocument; method Save(aFile: File); method Save(aFile: File; XmlDeclaration: XmlDocumentDeclaration); method Save(aFile: File; Version: String; Encoding: String; Standalone: Boolean); {$IF TOFFEE}finalizer;{$ENDIF} end; XmlDocumentDeclaration = public class public constructor; empty; constructor(aVersion: String; anEncoding: String; aStandalone: Boolean); property Encoding: String read write; property Standalone: Boolean read write; property StandaloneString: String read iif(Standalone, "yes", "no"); property Version: String read write; end; {$IF WINDOWS_PHONE OR NETFX_CORE} UTF8StringWriter = private class (System.IO.StringWriter) public property Encoding: System.Text.Encoding read System.Text.Encoding.UTF8; override; end; {$ENDIF} implementation {$IF COOPER} method XmlDocument.GetElement(Name: String): XmlElement; begin var Items := GetElementsByTagName(Name); if length(Items) = 0 then exit nil; exit Items[0]; end; method XmlDocument.CreateAttribute(Name: String): XmlAttribute; begin exit new XmlAttribute(Doc.CreateAttribute(Name)); end; method XmlDocument.CreateAttribute(QualifiedName: String; NamespaceUri: String): XmlAttribute; begin exit new XmlAttribute(Doc.CreateAttributeNS(NamespaceUri, QualifiedName)); end; method XmlDocument.CreateXmlNs(Prefix: String; NamespaceUri: String): XmlAttribute; begin SugarArgumentNullException.RaiseIfNil(Prefix, "Prefix"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamesapceUri"); var Attr := Doc.createAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:"+Prefix); Attr.TextContent := NamespaceUri; exit new XmlAttribute(Attr); end; method XmlDocument.CreateCDataSection(Data: String): XmlCDataSection; begin exit new XmlCDataSection(Doc.CreateCDATASection(Data)); end; method XmlDocument.CreateComment(Data: String): XmlComment; begin exit new XmlComment(Doc.CreateComment(Data)); end; method XmlDocument.CreateElement(Name: String): XmlElement; begin exit new XmlElement(Doc.CreateElement(Name)); end; method XmlDocument.CreateElement(QualifiedName: String; NamespaceUri: String): XmlElement; begin exit new XmlElement(Doc.CreateElementNS(NamespaceUri, QualifiedName)); end; method XmlDocument.CreateProcessingInstruction(Target: String; Data: String): XmlProcessingInstruction; begin exit new XmlProcessingInstruction(Doc.CreateProcessingInstruction(Target, Data)); end; method XmlDocument.CreateTextNode(Data: String): XmlText; begin exit new XmlText(Doc.CreateTextNode(Data)); end; method XmlDocument.GetElementsByTagName(Name: String): array of XmlElement; begin if Name = nil then exit []; var items := Doc.GetElementsByTagName(Name); if items = nil then exit []; result := new XmlElement[items.length]; for i: Integer := 0 to items.length-1 do result[i] := new XmlElement(items.Item(i)); end; method XmlDocument.GetElementsByTagName(LocalName: String; NamespaceUri: String): array of XmlElement; begin if Name = nil then exit []; var items := Doc.GetElementsByTagNameNS(NamespaceUri, LocalName); if items = nil then exit []; result := new XmlElement[items.length]; for i: Integer := 0 to items.length-1 do result[i] := new XmlElement(items.Item(i)); end; class method XmlDocument.ParseXml(Content: String; BaseUri: String): not nullable XmlDocument; begin SugarArgumentNullException.RaiseIfNil(Content, "Content"); //java can not ignore insignificant whitespaces, do a manual cleanup Content := java.lang.String(Content).replaceAll(">\s+<", "><"); var Factory := javax.xml.parsers.DocumentBuilderFactory.newInstance; //handle namespaces Factory.NamespaceAware := true; Factory.Validating := false; var Builder := Factory.newDocumentBuilder(); var Input := new org.xml.sax.InputSource(new java.io.StringReader(Content)); if BaseUri <> nil then Input.SystemId := BaseUri; Builder.setEntityResolver(new class org.xml.sax.EntityResolver(resolveEntity := method (publicId: java.lang.String; systemId: java.lang.String): org.xml.sax.InputSource begin if (publicId <> nil) or (systemId <> nil) then exit new org.xml.sax.InputSource(new java.io.ByteArrayInputStream(new SByte[0])) else exit nil; end )); var Document := Builder.parse(Input); //Normalize text content Document.normalize; exit new XmlDocument(Document); end; class method XmlDocument.FromFile(aFile: File): not nullable XmlDocument; begin var Handle := aFile.Open(FileOpenMode.ReadOnly); try var Bin := Handle.Read(Handle.Length); exit ParseXml(new String(Bin.ToArray, Encoding.UTF8), aFile.FullPath); finally Handle.Close; end; end; class method XmlDocument.FromBinary(aBinary: Binary): not nullable XmlDocument; begin exit ParseXml(new String(aBinary.ToArray, Encoding.UTF8), nil); end; class method XmlDocument.FromString(aString: String): not nullable XmlDocument; begin exit ParseXml(aString, nil); end; class method XmlDocument.CreateDocument: not nullable XmlDocument; begin var Factory := javax.xml.parsers.DocumentBuilderFactory.newInstance; Factory.NamespaceAware := true; var Builder := Factory.newDocumentBuilder(); exit new XmlDocument(Builder.newDocument()); end; method XmlDocument.Save(aFile: File); begin Save(aFile, nil); end; method XmlDocument.Save(aFile: File; Version: String; Encoding: String; Standalone: Boolean); begin Save(aFile, new XmlDocumentDeclaration(Version, Encoding, Standalone)); end; method XmlDocument.Save(aFile: File; XmlDeclaration: XmlDocumentDeclaration); begin var Factory := javax.xml.transform.TransformerFactory.newInstance(); var Transformer := Factory.newTransformer(); var Source: javax.xml.transform.dom.DOMSource := new javax.xml.transform.dom.DOMSource(Doc); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.METHOD, "xml"); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "no"); if Doc.Doctype <> nil then begin Transformer.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_PUBLIC, Doc.Doctype.PublicId); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, Doc.Doctype.SystemId); end; if XmlDeclaration <> nil then begin Transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, XmlDeclaration.Encoding); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.VERSION, XmlDeclaration.Version); Transformer.setOutputProperty(javax.xml.transform.OutputKeys.STANDALONE, XmlDeclaration.StandaloneString); Doc.XmlStandalone := XmlDeclaration.Standalone; end; var Stream := new javax.xml.transform.stream.StreamResult(aFile); Transformer.transform(Source, Stream); end; method XmlDocument.AddChild(Node: XmlNode); begin SugarArgumentNullException.RaiseIfNil(Node, "Node"); if not (Node.NodeType in [XmlNodeType.Comment, XmlNodeType.Element, XmlNodeType.ProcessingInstruction]) then raise new SugarInvalidOperationException("Unable to insert node. Only elements, comments and processing instructions allowed."); Doc.appendChild(Node.Node); end; method XmlDocument.RemoveChild(Node: XmlNode); begin Doc.removeChild(Node.Node); end; method XmlDocument.ReplaceChild(Node: XmlNode; WithNode: XmlNode); begin Doc.replaceChild(WithNode.Node, Node.Node); end; {$ELSEIF ECHOES} method XmlDocument.AddChild(Node: XmlNode); begin Doc.Add(Node.Node); end; method XmlDocument.CreateAttribute(Name: String): XmlAttribute; begin var Attr := new XAttribute(System.String(Name), ""); exit new XmlAttribute(Attr); end; method XmlDocument.CreateAttribute(QualifiedName: String; NamespaceUri: String): XmlAttribute; begin var lIndex := QualifiedName.IndexOf(":"); if lIndex <> -1 then QualifiedName := QualifiedName.Substring(lIndex+1, QualifiedName.Length - lIndex - 1); var ns: XNamespace := System.String(NamespaceUri); var Attr := new XAttribute(ns + QualifiedName, ""); exit new XmlAttribute(Attr); end; method XmlDocument.CreateXmlNs(Prefix: String; NamespaceUri: String): XmlAttribute; begin var Attr := new XAttribute(XNamespace.Xmlns + Prefix, NamespaceUri); exit new XmlAttribute(Attr); end; method XmlDocument.CreateCDataSection(Data: String): XmlCDataSection; begin var CData := new XCData(Data); exit new XmlCDataSection(CData); end; method XmlDocument.CreateComment(Data: String): XmlComment; begin var Comment := new XComment(Data); exit new XmlComment(Comment); end; class method XmlDocument.CreateDocument: not nullable XmlDocument; begin var Doc := new XDocument; exit new XmlDocument(Doc); end; method XmlDocument.CreateElement(Name: String): XmlElement; begin var el := new XElement(System.String(Name)); exit new XmlElement(el); end; method XmlDocument.CreateElement(QualifiedName: String; NamespaceUri: String): XmlElement; begin var ns: XNamespace := System.String(NamespaceUri); var el := new XElement(ns + QualifiedName); exit new XmlElement(el); end; method XmlDocument.CreateProcessingInstruction(Target: String; Data: String): XmlProcessingInstruction; begin var pi := new XProcessingInstruction(Target, Data); exit new XmlProcessingInstruction(pi); end; method XmlDocument.CreateTextNode(Data: String): XmlText; begin var text := new XText(Data); exit new XmlText(text); end; method XmlDocument.GetElement(Name: String): XmlElement; begin var Items := GetElementsByTagName(Name); if length(Items) = 0 then exit nil; exit Items[0]; end; method XmlDocument.GetElementsByTagName(LocalName: String; NamespaceUri: String): array of XmlElement; begin if DocumentElement = nil then exit []; exit DocumentElement.GetElementsByTagName(LocalName, NamespaceUri); end; method XmlDocument.GetElementsByTagName(Name: String): array of XmlElement; begin if DocumentElement = nil then exit []; exit DocumentElement.GetElementsByTagName(Name); end; class method XmlDocument.FromFile(aFile: File): not nullable XmlDocument; begin {$IF WINDOWS_PHONE OR NETFX_CORE} var Handle := aFile.Open(FileOpenMode.ReadOnly); try var Content := new String(Handle.Read(Handle.Length).ToArray, Encoding.UTF8); var reader := new System.IO.StringReader(Content); var document := XDocument.Load(reader, LoadOptions.SetBaseUri); exit new XmlDocument(document); finally Handle.Close; end; {$ELSE} var document := XDocument.Load(System.String(aFile), LoadOptions.SetBaseUri); result := new XmlDocument(document); {$ENDIF} end; class method XmlDocument.FromBinary(aBinary: Binary): not nullable XmlDocument; begin var ms := System.IO.MemoryStream(aBinary); var Position := ms.Position; ms.Position := 0; try var document := XDocument.Load(ms, LoadOptions.SetBaseUri); result := new XmlDocument(document); finally ms.Position := Position; end; end; class method XmlDocument.FromString(aString: String): not nullable XmlDocument; begin var document := XDocument.Parse(aString); result := new XmlDocument(document); end; method XmlDocument.RemoveChild(Node: XmlNode); begin (Node.Node as XNode):&Remove; end; method XmlDocument.ReplaceChild(Node: XmlNode; WithNode: XmlNode); begin (Node.Node as XNode):ReplaceWith(WithNode.Node); end; method XmlDocument.Save(aFile: File); begin Save(aFile, nil); end; method XmlDocument.Save(aFile: File; Version: String; Encoding: String; Standalone: Boolean); begin Save(aFile, new XmlDocumentDeclaration(Version, Encoding, Standalone)); end; method XmlDocument.Save(aFile: File; XmlDeclaration: XmlDocumentDeclaration); begin if XmlDeclaration <> nil then Doc.Declaration := new XDeclaration(XmlDeclaration.Version, XmlDeclaration.Encoding, XmlDeclaration.StandaloneString); {$IF WINDOWS_PHONE OR NETFX_CORE} var sb := new StringBuilder; var writer := new UTF8StringWriter(sb); Doc.Save(writer); var Handle := aFile.Open(FileOpenMode.ReadWrite); try Handle.Length := 0; Handle.Write(Encoding.UTF8.GetBytes(sb.ToString)); finally Handle.Close; end; {$ELSEIF ECHOES} Doc.Save(aFile); {$ENDIF} end; {$ELSEIF TOFFEE} method XmlDocument.AddChild(Node: XmlNode); begin SugarArgumentNullException.RaiseIfNil(Node, "Node"); if not (Node.NodeType in [XmlNodeType.Comment, XmlNodeType.Element, XmlNodeType.ProcessingInstruction]) then raise new SugarInvalidOperationException("Unable to insert node. Only elements, comments and processing instructions allowed."); if (DocumentElement <> nil) and (Node.NodeType = XmlNodeType.Element) then raise new SugarInvalidOperationException("Unable to insert node. Root element already exists"); var NewNode := libxml.xmlAddChild(libxml.xmlNodePtr(Doc), libxml.xmlNodePtr(Node.Node)); if NewNode = nil then raise new SugarInvalidOperationException("Unable to insert node {0} to a document", Node.Name); Node.Node := ^libxml.__struct__xmlNode(NewNode); end; method XmlDocument.CreateAttribute(Name: String): XmlAttribute; begin SugarArgumentNullException.RaiseIfNil(Name, "Name"); if libxml.xmlValidateName(XmlChar.FromString(Name), 0) <> 0 then raise new SugarArgumentException("Invalid attribute name {0}", Name); var NewObj := libxml.xmlNewProp(nil, XmlChar.FromString(Name), XmlChar.FromString("")); if NewObj = nil then raise new SugarInvalidOperationException("Unable to create attribute {0}", Name); exit new XmlAttribute(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateAttribute(QualifiedName: String; NamespaceUri: String): XmlAttribute; begin SugarArgumentNullException.RaiseIfNil(QualifiedName, "QualifiedName"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamespaceUri"); var prefix: ^libxml.xmlChar; var local := libxml.xmlSplitQName2(XmlChar.FromString(QualifiedName), var prefix); if local = nil then raise new SugarFormatException("Element name is not qualified name"); //create a new namespace definition var ns := libxml.xmlNewNs(nil, XmlChar.FromString(NamespaceUri), prefix); //create a new property and set reference to a namespace var NewObj := libxml.xmlNewNsProp(nil, ns, local, XmlChar.FromString("")); //This attribute MUST be added to a node, or we end up with namespace not being released if NewObj = nil then exit nil; exit new XmlAttribute(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateXmlNs(Prefix: String; NamespaceUri: String): XmlAttribute; begin SugarArgumentNullException.RaiseIfNil(Prefix, "Prefix"); SugarArgumentNullException.RaiseIfNil(NamespaceUri, "NamespaceUri"); if Prefix.StartsWith("<") or Prefix.StartsWith("&") then raise new SugarArgumentException("Invalid attribute prefix {0}", Prefix); var ns := libxml.xmlNewNs(nil, XmlChar.FromString("http://www.w3.org/2000/xmlns/"), XmlChar.FromString("xmlns")); var NewObj := libxml.xmlNewNsProp(nil, ns, XmlChar.FromString(Prefix), XmlChar.FromString(NamespaceUri)); if NewObj = nil then exit nil; exit new XmlAttribute(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateCDataSection(Data: String): XmlCDataSection; begin var NewObj := libxml.xmlNewCDataBlock(libxml.xmlDocPtr(Doc), XmlChar.FromString(Data), Data.length); if NewObj = nil then exit nil; exit new XmlCDataSection(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateComment(Data: String): XmlComment; begin var NewObj := libxml.xmlNewComment(XmlChar.FromString(Data)); if NewObj = nil then exit nil; exit new XmlComment(^libxml.__struct__xmlNode(NewObj), self); end; class method XmlDocument.CreateDocument: not nullable XmlDocument; begin var NewObj := libxml.xmlNewDoc(XmlChar.FromString("1.0")); result := new XmlDocument(^libxml.__struct__xmlNode(NewObj), nil); result.OwnerDocument := result; end; method XmlDocument.CreateElement(Name: String): XmlElement; begin var NewObj := libxml.xmlNewDocRawNode(libxml.xmlDocPtr(Node), nil, XmlChar.FromString(Name), nil); if NewObj = nil then exit nil; exit new XmlElement(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateElement(QualifiedName: String; NamespaceUri: String): XmlElement; begin var prefix: ^libxml.xmlChar; var local := libxml.xmlSplitQName2(XmlChar.FromString(QualifiedName), var prefix); if local = nil then raise new SugarFormatException("Element name is not qualified name"); var NewObj := libxml.xmlNewDocRawNode(libxml.xmlDocPtr(Node), nil, local, nil); if NewObj = nil then exit nil; var ns := libxml.xmlNewNs(NewObj, XmlChar.FromString(NamespaceUri), prefix); libxml.xmlSetNs(NewObj, ns); exit new XmlElement(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateProcessingInstruction(Target: String; Data: String): XmlProcessingInstruction; begin var NewObj := libxml.xmlNewPI(XmlChar.FromString(Target), XmlChar.FromString(Data)); if NewObj = nil then exit nil; exit new XmlProcessingInstruction(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.CreateTextNode(Data: String): XmlText; begin var NewObj := libxml.xmlNewText(XmlChar.FromString(Data)); if NewObj = nil then exit nil; exit new XmlText(^libxml.__struct__xmlNode(NewObj), self); end; method XmlDocument.GetElement(Name: String): XmlElement; begin var Items := GetElementsByTagName(Name); if length(Items) = 0 then exit nil; exit Items[0]; end; method XmlDocument.GetElementsByTagName(LocalName: String; NamespaceUri: String): array of XmlElement; begin exit new XmlNodeList(self).ElementsByName(LocalName, NamespaceUri); end; method XmlDocument.GetElementsByTagName(Name: String): array of XmlElement; begin exit new XmlNodeList(self).ElementsByName(Name); end; class method XmlDocument.FromFile(aFile: File): not nullable XmlDocument; begin var NewObj := libxml.xmlReadFile(NSString(aFile), "UTF-8", libxml.xmlParserOption.XML_PARSE_NOBLANKS); if NewObj = nil then raise new Exception("Could not parse XML Document"); result := new XmlDocument(^libxml.__struct__xmlNode(NewObj), nil); result.OwnerDocument := result; end; class method XmlDocument.FromBinary(aBinary: Binary): not nullable XmlDocument; begin var NewObj := libxml.xmlReadMemory(^AnsiChar(NSMutableData(aBinary).bytes), aBinary.Length, "", "UTF-8", libxml.xmlParserOption.XML_PARSE_NOBLANKS); if NewObj = nil then raise new Exception("Could not parse XML Document"); result := new XmlDocument(^libxml.__struct__xmlNode(NewObj), nil); result.OwnerDocument := result; end; class method XmlDocument.FromString(aString: String): not nullable XmlDocument; begin var Data := NSString(aString).dataUsingEncoding(NSStringEncoding.NSUTF8StringEncoding); exit FromBinary(Binary(Data)); end; method XmlDocument.RemoveChild(Node: XmlNode); begin SugarArgumentNullException.RaiseIfNil(Node, "Node"); libxml.xmlUnlinkNode(libxml.xmlNodePtr(Node.Node)); libxml.xmlFreeNode(libxml.xmlNodePtr(Node.Node)); end; method XmlDocument.ReplaceChild(Node: XmlNode; WithNode: XmlNode); begin SugarArgumentNullException.RaiseIfNil(Node, "Node"); SugarArgumentNullException.RaiseIfNil(WithNode, "WithNode"); if (Node.NodeType = XmlNodeType.Element) and (WithNode.NodeType <> XmlNodeType.Element) then raise new SugarInvalidOperationException("Unable to replace root node with non element node"); if not (WithNode.NodeType in [XmlNodeType.Comment, XmlNodeType.Element, XmlNodeType.ProcessingInstruction]) then raise new SugarInvalidOperationException("Unable to replace node. Only elements, comments and processing instructions allowed."); if libxml.xmlReplaceNode(libxml.xmlNodePtr(Node.Node), libxml.xmlNodePtr(WithNode.Node)) = nil then raise new SugarInvalidOperationException("Unable to replace node {0} with node {1}", Node.Name, WithNode.Name); end; method XmlDocument.Save(aFile: File); begin Save(aFile, nil); end; method XmlDocument.Save(aFile: File; Version: String; Encoding: String; Standalone: Boolean); begin Save(aFile, new XmlDocumentDeclaration(Version := Version, Encoding := Encoding, Standalone := Standalone)); end; method XmlDocument.Save(aFile: File; XmlDeclaration: XmlDocumentDeclaration); begin if XmlDeclaration <> nil then begin Doc^.standalone := Integer(XmlDeclaration.Standalone); libxml.xmlSaveFormatFileEnc(NSString(aFile), libxml.xmlDocPtr(Node), NSString(XmlDeclaration.Encoding), 1); exit; end; libxml.xmlSaveFormatFile(NSString(aFile), libxml.xmlDocPtr(Node), 1); end; method XmlDocument.GetDocumentElement: XmlElement; begin var Root := libxml.xmlDocGetRootElement(libxml.xmlDocPtr(Doc)); if Root = nil then exit nil; exit new XmlElement(^libxml.__struct__xmlNode(Root), self); end; method XmlDocument.GetDocumentType: XmlDocumentType; begin if Doc^.intSubset = nil then exit nil; exit new XmlDocumentType(^libxml.__struct__xmlNode(Doc^.intSubset), self); end; finalizer XmlDocument; begin if Doc <> nil then libxml.xmlFreeDoc(libxml.xmlDocPtr(Doc)); end; {$ENDIF} { XmlDocumentDeclaration } constructor XmlDocumentDeclaration(aVersion: String; anEncoding: String; aStandalone: Boolean); begin Version := aVersion; Encoding := anEncoding; Standalone := aStandalone; end; end.
unit App; { Based on 005_mandelbrot.cpp example from oglplus (http://oglplus.org/) } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TMandelbrotApp = class(TApplication) private FProgram: TGLProgram; FVerts: TGLBuffer; FCoords: TGLBuffer; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes; { TMandelbrotApp } procedure TMandelbrotApp.Initialize; const RECTANGLE_VERTS: array [0..3] of TVector2 = ( (X: -1; Y: -1), (X: -1; Y: 1), (X: 1; Y: -1), (X: 1; Y: 1)); const RECTANGLE_COORDS: array [0..3] of TVector2 = ( (X: -1.5; Y: -0.5), (X: -1.5; Y: 1.0), (X: 0.5; Y: -0.5), (X: 0.5; Y: 1.0)); const COLOR_MAP: array [0..4] of TVector4 = ( (R: 0.4; G: 0.2; B: 1.0; A: 0.00), (R: 1.0; G: 0.2; B: 0.2; A: 0.30), (R: 1.0; G: 1.0; B: 1.0; A: 0.95), (R: 1.0; G: 1.0; B: 1.0; A: 0.98), (R: 0.1; G: 0.1; B: 0.1; A: 1.00)); var VertexShader, FragmentShader: TGLShader; VertAttr: TGLVertexAttrib; Uniform: TGLUniform; begin VertexShader.New(TGLShaderType.Vertex, 'attribute vec2 Position;'#10+ 'attribute vec2 Coord;'#10+ 'varying vec2 vertCoord;'#10+ 'void main(void)'#10+ '{'#10+ ' vertCoord = Coord;'#10+ ' gl_Position = vec4(Position, 0.0, 1.0);'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision highp float;'#10+ 'varying vec2 vertCoord;'#10+ 'const int nclr = 5;'#10+ 'uniform vec4 clrs[5];'#10+ 'void main(void)'#10+ '{'#10+ ' vec2 z = vec2(0.0, 0.0);'#10+ ' vec2 c = vertCoord;'#10+ ' int i = 0, max = 128;'#10+ ' while ((i != max) && (distance(z, c) < 2.0))'#10+ ' {'#10+ ' vec2 zn = vec2('#10+ ' z.x * z.x - z.y * z.y + c.x,'#10+ ' 2.0 * z.x * z.y + c.y);'#10+ ' z = zn;'#10+ ' ++i;'#10+ ' }'#10+ ' float a = sqrt(float(i) / float(max));'#10+ ' for (i = 0; i != (nclr - 1); ++i)'#10+ ' {'#10+ ' if((a > clrs[i].a) && (a <= clrs[i+1].a))'#10+ ' {'#10+ ' float m = (a - clrs[i].a) / (clrs[i+1].a - clrs[i].a);'#10+ ' gl_FragColor = vec4('#10+ ' mix(clrs[i].rgb, clrs[i+1].rgb, m),'#10+ ' 1.0'#10+ ' );'#10+ ' break;'#10+ ' }'#10+ ' }'#10+ '}'); FragmentShader.Compile; FProgram.New; FProgram.AttachShader(VertexShader); FProgram.AttachShader(FragmentShader); FProgram.Link; VertexShader.Delete; FragmentShader.Delete; FProgram.Use; { Positions } FVerts.New(TGLBufferType.Vertex); FVerts.Bind; FVerts.Data(RECTANGLE_VERTS); VertAttr.Init(FProgram, 'Position'); VertAttr.SetConfig<TVector2>; VertAttr.Enable; { Mandelbrot coordinates } FCoords.New(TGLBufferType.Vertex); FCoords.Bind; FCoords.Data(RECTANGLE_COORDS); VertAttr.Init(FProgram, 'Coord'); VertAttr.SetConfig<TVector2>; VertAttr.Enable; { Color map } Uniform.Init(FProgram, 'clrs'); Uniform.SetValues(COLOR_MAP); gl.Disable(TGLCapability.DepthTest); end; procedure TMandelbrotApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TMandelbrotApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Draw the rectangle } gl.DrawArrays(TGLPrimitiveType.TriangleStrip, 4); end; procedure TMandelbrotApp.Shutdown; begin { Release resources } FCoords.Delete; FVerts.Delete; FProgram.Delete; end; end.
unit eInterestSimulator.Model.PagamentoVariavel; interface uses eInterestSimulator.Model.Interfaces; type TModelAmortizacaoPagamentoVariavel = class(TInterfacedObject, iResultado) private FNumeroParcela: Integer; FValorJuros: Real; FValorAmortizacao: Real; FValorSaldo: Real; FValorPagamento: Real; function NumeroParcela(Value: Integer): iResultado; overload; function NumeroParcela: Integer; overload; function ValorJuros(Value: Real): iResultado; overload; function ValorJuros: Real; overload; function ValorAmortizacao(Value: Real): iResultado; overload; function ValorAmortizacao: Real; overload; function ValorSaldo(Value: Real): iResultado; overload; function ValorSaldo: Real; overload; function ValorPagamento(Value: Real): iResultado; overload; function ValorPagamento: Real; overload; public constructor Create; destructor Destroy; override; class function New: iResultado; end; implementation { TModelAmortizacao } constructor TModelAmortizacaoPagamentoVariavel.Create; begin end; destructor TModelAmortizacaoPagamentoVariavel.Destroy; begin inherited; end; class function TModelAmortizacaoPagamentoVariavel.New: iResultado; begin Result := Self.Create; end; function TModelAmortizacaoPagamentoVariavel.NumeroParcela(Value: Integer) : iResultado; begin Result := Self; FNumeroParcela := Value; end; function TModelAmortizacaoPagamentoVariavel.NumeroParcela: Integer; begin Result := FNumeroParcela; end; function TModelAmortizacaoPagamentoVariavel.ValorAmortizacao(Value: Real) : iResultado; begin Result := Self; FValorAmortizacao := Value; end; function TModelAmortizacaoPagamentoVariavel.ValorAmortizacao: Real; begin Result := FValorAmortizacao; end; function TModelAmortizacaoPagamentoVariavel.ValorJuros(Value: Real): iResultado; begin Result := Self; FValorJuros := Value; end; function TModelAmortizacaoPagamentoVariavel.ValorJuros: Real; begin Result := FValorJuros; end; function TModelAmortizacaoPagamentoVariavel.ValorPagamento: Real; begin Result := FValorPagamento; end; function TModelAmortizacaoPagamentoVariavel.ValorPagamento(Value: Real) : iResultado; begin Result := Self; FValorPagamento := Value; end; function TModelAmortizacaoPagamentoVariavel.ValorSaldo(Value: Real): iResultado; begin Result := Self; FValorSaldo := Value; end; function TModelAmortizacaoPagamentoVariavel.ValorSaldo: Real; begin Result := FValorSaldo; end; end.
// Simple types used in the code formatter // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) // Jens Borrisholt (Jens@borrisholt.dk) - Cleaning up the code, and making it aware of several language features unit GX_CodeFormatterTypes; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, GX_GenericUtils; type ECodeFormatter = class(Exception); type TWordType = (wtLineFeed, wtSpaces, wtHalfComment, wtHalfStarComment, wtHalfOutComment, wtFullComment, wtFullOutComment, wtString, wtErrorString, wtOperator, wtWord, wtNumber, wtHexNumber, wtNothing, wtAsm, wtCompDirective); EFormatException = class(Exception); const Maxline = 1024; // the maximum line length of the Delphi editor NotPrintable = [#1..#8, #10..#14, #16..#19, #22..#31]; { not printable chars } Tab = #9; Space = ' '; MaxCollectionSize = Maxint div (SizeOf(Integer) * 2); type {: determines a word's casing: * rfLowerCase = all lowercase * rfUpperCase = all uppercase * rfFirstUp = first character upper case, all other lowercase * rfUnchanged = do not change anything * rfFirstOccurrence = the first occurrence of the word } TCase = (rfLowerCase, rfUpperCase, rfFirstUp, rfUnchanged, rfFirstOccurrence); TSpace = (spBefore, spAfter); TSpaceSet = set of TSpace; function SpaceSetToInt(_SpaceSet: TSpaceSet): Integer; function IntToSpaceSet(_Value: Integer): TSpaceSet; const spBoth = [spBefore, spAfter]; spNone = []; type TReservedType = (rtNothing, rtReserved, rtOper, rtDirective, rtIf, rtDo, rtWhile, rtOn, rtVar, rtType, rtProcedure, rtAsm, rtTry, rtExcept, rtEnd, rtBegin, rtCase, rtOf, rtLineFeed, rtColon, rtSemiColon, rtThen, rtClass, rtClassDecl, rtProgram, rtRepeat, rtUntil, rtRecord, rtVisibility, rtElse, rtIfElse, rtInterface, rtImplementation, rtLeftBr, rtRightBr, rtLeftHook, rtRightHook, rtMathOper, rtAssignOper, rtMinus, rtPlus, rtLogOper, rtEquals, rtForward, rtDefault, rtInitialization, rtComma, rtUses, rtProcDeclare, rtFuncDirective, rtAbsolute, rtComment, rtRecCase, rtDot, rtCompIf, rtDotDot, rtCompElse, rtCompEndif); const NoReservedTypes = [rtNothing, rtComma, rtColon, rtLineFeed, rtDefault, rtFuncDirective, rtAbsolute, rtComment, rtLeftBr, rtRightBr, rtForward, rtCompIf, rtCompElse, rtCompEndif, rtVisibility]; StandardDirectives = [rtDefault, rtAbsolute, rtVisibility, rtFuncDirective, rtAbsolute, rtForward]; type {: stores all known reserved words in lower case with their associated type, must be ordered perfectly on words!! NOTE: This is for Delphi 2005, there are some words that aren't reserved in earlier Delphi versions, maybe that should be configurable? That could be done by converting this list into a oObjects.TStrCollection which only contains those words that are known for the configured Delphi version. } TReservedWordList = class private FWords: TStringList; public constructor Create; destructor Destroy; override; function FindWord(const _s: string; out _ReservedType: TReservedType): Boolean; procedure Add(const _s: string; _ReservedType: TReservedType); end; var ReservedWordList: TReservedWordList = nil; type {: Holds a special "option" for a tpascal token, some of them is just override a setting or behavior } TTokenOption = (toFeedNewLine); TTokenOptions = set of TTokenOption; {: changes the string case as specified in aCase @param aStr is the input string @param aCase is a TCase specifying the desired case @returns the modified string } function AdjustCase(const _str: TGXUnicodeString; _Case: TCase): TGXUnicodeString; implementation uses GX_CodeFormatterUnicode; function AdjustCase(const _str: TGXUnicodeString; _Case: TCase): TGXUnicodeString; var i: Integer; begin case _Case of rfUpperCase: Result := UpperCase(_str); rfLowerCase: Result := LowerCase(_str); rfFirstUp: begin Result := LowerCase(_str); i := 1; while (Result[i] = Space) or (Result[i] = Tab) do Inc(i); Result[i] := UpCase(Result[i]); end; else // rfUnchanged and rfFirstOccurrence Result := _str; end; end; { TKeywordColl } function SpaceSetToInt(_SpaceSet: TSpaceSet): Integer; begin Result := 0; Move(_SpaceSet, Result, SizeOf(_SpaceSet)); end; function IntToSpaceSet(_Value: Integer): TSpaceSet; begin Result := []; Move(_Value, Result, SizeOf(Result)); end; { TReservedWordList } constructor TReservedWordList.Create; begin inherited Create; FWords := TStringList.Create; FWords.Sorted := True; FWords.Duplicates := dupError; Add('absolute', rtAbsolute); Add('abstract', rtFuncDirective); Add('and', rtOper); Add('array', rtReserved); Add('as', rtOper); Add('asm', rtAsm); Add('assembler', rtFuncDirective); Add('automated', rtVisibility); Add('begin', rtBegin); Add('case', rtCase); Add('cdecl', rtFuncDirective); Add('class', rtClass); Add('const', rtVar); Add('constructor', rtProcedure); Add('contains', rtUses); Add('default', rtDefault); Add('deprecated', rtFuncDirective); Add('destructor', rtProcedure); Add('dispid', rtFuncDirective); Add('dispinterface', rtInterface); Add('div', rtOper); Add('do', rtDo); Add('downto', rtOper); Add('dynamic', rtFuncDirective); Add('else', rtElse); Add('end', rtEnd); Add('except', rtExcept); Add('export', rtFuncDirective); Add('exports', rtUses); Add('external', rtForward); Add('far', rtFuncDirective); Add('file', rtReserved); Add('final', rtDirective); Add('finalization', rtInitialization); Add('finally', rtExcept); Add('for', rtWhile); Add('forward', rtForward); Add('function', rtProcedure); Add('goto', rtReserved); Add('helper', rtReserved); Add('if', rtIf); Add('implementation', rtImplementation); Add('implements', rtFuncDirective); Add('in', rtOper); Add('index', rtFuncDirective); Add('inherited', rtReserved); Add('initialization', rtInitialization); Add('inline', rtFuncDirective); Add('interface', rtInterface); Add('is', rtOper); Add('label', rtVar); Add('library', rtFuncDirective); Add('message', rtFuncDirective); Add('mod', rtOper); Add('name', rtFuncDirective); Add('near', rtFuncDirective); Add('nil', rtReserved); Add('nodefault', rtFuncDirective); Add('not', rtOper); Add('object', rtClass); Add('of', rtOf); Add('on', rtOn); Add('operator', rtProcedure); Add('or', rtOper); Add('out', rtReserved); Add('overload', rtFuncDirective); Add('override', rtFuncDirective); Add('packed', rtReserved); Add('pascal', rtFuncDirective); Add('platform', rtFuncDirective); Add('private', rtVisibility); Add('procedure', rtProcedure); Add('program', rtProgram); Add('property', rtProcedure); Add('protected', rtVisibility); Add('public', rtVisibility); Add('published', rtVisibility); Add('raise', rtReserved); Add('read', rtFuncDirective); Add('readonly', rtFuncDirective); Add('record', rtRecord); Add('reference', rtReserved); Add('register', rtFuncDirective); Add('reintroduce', rtFuncDirective); Add('repeat', rtRepeat); Add('requires', rtUses); Add('resident', rtFuncDirective); Add('resourcestring', rtVar); Add('safecall', rtFuncDirective); Add('set', rtReserved); Add('shl', rtOper); Add('shr', rtOper); Add('static', rtFuncDirective); Add('sealed', rtDirective); Add('stdcall', rtFuncDirective); Add('stored', rtFuncDirective); Add('strict', rtVisibility); Add('string', rtReserved); Add('then', rtThen); Add('threadvar', rtVar); Add('to', rtOper); Add('try', rtTry); Add('type', rtType); Add('unit', rtProgram); Add('until', rtUntil); Add('uses', rtUses); Add('var', rtVar); Add('virtual', rtFuncDirective); Add('while', rtWhile); Add('with', rtWhile); Add('write', rtFuncDirective); Add('writeonly', rtFuncDirective); Add('xor', rtOper); end; destructor TReservedWordList.Destroy; begin FreeAndNil(FWords); inherited; end; procedure TReservedWordList.Add(const _s: string; _ReservedType: TReservedType); begin FWords.AddObject(LowerCase(_s), Pointer(Ord(_ReservedType))); end; function TReservedWordList.FindWord(const _s: string; out _ReservedType: TReservedType): Boolean; var Idx: Integer; begin Result := FWords.Find(LowerCase(_s), Idx); if Result then _ReservedType := TReservedType(Integer(FWords.Objects[Idx])); end; initialization ReservedWordList := TReservedWordList.Create; finalization FreeAndNil(ReservedWordList); end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2017 * } { *********************************************************** } unit tfWindows; {$I TFL.inc} interface uses tfTypes, tfOpenSSL, Windows, SysUtils; // Advapi32.dll, WinCrypt.h const PROV_RSA_FULL = 1; CRYPT_VERIFYCONTEXT = DWORD($F0000000); type HCRYPTPROV = ULONG_PTR; function CryptAcquireContext(var phProv: HCRYPTPROV; pszContainer: LPCTSTR; pszProvider: LPCTSTR; dwProvType: DWORD; dwFlags: DWORD): BOOL; stdcall; function CryptReleaseContext(hProv: HCRYPTPROV; dwFlags: DWORD): BOOL; stdcall; function CryptGenRandom(hProv: HCRYPTPROV; dwLen: DWORD; pbBuffer: LPBYTE): BOOL; stdcall; type TtfLock = record FMutex: THandle; function Acquire: TF_RESULT; function Resease: TF_RESULT; end; // nobody knows is Windows CryptoAPI threadsafe or not; // TForge uses CryptLock to be on the safe side. var CryptLock: TtfLock; function GenRandom(var Buf; BufSize: Cardinal): TF_RESULT; // OpenSSL function TryLoadLibCrypto(const LibName: string = ''): TF_RESULT; implementation type PCipherItem = ^TCipherItem; TCipherItem = record Name: PChar; AlgID: UInt32; Modes: UInt32; end; type TCipherList = array of TCipherItem; function CryptAcquireContext; external advapi32 name {$IFDEF UNICODE}'CryptAcquireContextW'{$ELSE}'CryptAcquireContextA'{$ENDIF}; function CryptReleaseContext; external advapi32 name 'CryptReleaseContext'; function CryptGenRandom; external advapi32 name 'CryptGenRandom'; {$ifdef fpc} function InterlockedCompareExchangePointer(var Target: Pointer; NewValue: Pointer; Comperand: Pointer): Pointer; begin {$ifdef cpu64} Result:= Pointer(InterlockedCompareExchange64(int64(Target), int64(NewValue), int64(Comperand))); {$else cpu64} Result:= Pointer(InterlockedCompareExchange(LongInt(Target), LongInt(NewValue), LongInt(Comperand))); {$endif cpu64} end; {$endif fpc} function GenRandom(var Buf; BufSize: Cardinal): TF_RESULT; var Provider: HCRYPTPROV; begin // TForge uses GenRandom only to get a random seed value, // so large BufSize values aren't needed if BufSize > 256 then begin Result:= TF_E_INVALIDARG; Exit; end; Result:= CryptLock.Acquire; if Result = TF_S_OK then begin if CryptAcquireContext(Provider, nil, nil, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) then begin if not CryptGenRandom(Provider, BufSize, @Buf) then begin Result:= TF_E_FAIL; end; CryptReleaseContext(Provider, 0); end else begin Result:= TF_E_FAIL; end; CryptLock.Resease; end; end; { TtfLock } { Initially FMutex field contains zero; TtfLock does not provide constructor or method to initialize the field because TtfLock instances are designed to be declared as a global variables. =================================================================== On the first lock attempt, FMutex field is initialized by a non-zero value. On collision, each thread attempts to create a mutex and compare-and-swap it into place as the FMutex field. On failure to swap in the FMutex field, the mutex is closed. } function TtfLock.Acquire: TF_RESULT; var Tmp: THandle; begin if FMutex = 0 then begin Tmp:= CreateMutex(nil, False, nil); if InterlockedCompareExchangePointer(Pointer(FMutex), Pointer(Tmp), nil) <> nil then CloseHandle(Tmp); end; if WaitForSingleObject(FMutex, INFINITE) = WAIT_OBJECT_0 then Result:= TF_S_OK else Result:= TF_E_UNEXPECTED; end; function TtfLock.Resease: TF_RESULT; begin ReleaseMutex(FMutex); Result:= TF_S_OK; end; // OpenSSL staff const libCryptoName1 = 'libeay32.dll'; libCryptoName2 = 'libcrypto-1_1.dll'; var LibCryptoLoaded: Boolean = False; function TryLoadLibCrypto(const LibName: string): TF_RESULT; var LibHandle: THandle; // Version: LongWord; function LoadFunction(var Address: Pointer; const Name: string): Boolean; begin Address:= GetProcAddress(LibHandle, PChar(Name)); Result:= Address <> nil; end; // !! ver 1.1.0 replaced 'EVP_CIPHER_CTX_init' by 'EVP_CIPHER_CTX_reset' // from man pages: // # EVP_CIPHER_CTX was made opaque in OpenSSL 1.1.0. As a result, // # EVP_CIPHER_CTX_reset() appeared and EVP_CIPHER_CTX_cleanup() disappeared. // # EVP_CIPHER_CTX_init() remains as an alias for EVP_CIPHER_CTX_reset(). // from evp.h: // # define EVP_CIPHER_CTX_init(c) EVP_CIPHER_CTX_reset(c) // # define EVP_CIPHER_CTX_cleanup(c) EVP_CIPHER_CTX_reset(c) // // I am using 'EVP_CIPHER_CTX_init' and 'EVP_CIPHER_CTX_cleanup' // for compliance with version 1.0.2 // function LoadBrokenABI: Boolean; begin if LoadFunction(@OpenSSL_version_num, 'SSLeay') then begin Result:= LoadFunction(@OpenSSL_version, 'SSLeay_version') and LoadFunction(@EVP_CIPHER_CTX_init, 'EVP_CIPHER_CTX_init') and LoadFunction(@EVP_CIPHER_CTX_cleanup, 'EVP_CIPHER_CTX_cleanup'); end else begin Result:= LoadFunction(@OpenSSL_version_num, 'OpenSSL_version_num') and LoadFunction(@OpenSSL_version, 'OpenSSL_version') and LoadFunction(@EVP_CIPHER_CTX_init, 'EVP_CIPHER_CTX_reset'); @EVP_CIPHER_CTX_cleanup:= @EVP_CIPHER_CTX_init; end; end; begin if LibCryptoLoaded then begin Result:= TF_S_FALSE; Exit; end; if (LibName = '') then begin LibHandle:= LoadLibrary(PChar(libCryptoName1)); if LibHandle = 0 then LibHandle:= LoadLibrary(PChar(libCryptoName2)); end else begin LibHandle:= LoadLibrary(PChar(LibName)); end; if (LibHandle = 0) then begin Result:= TF_E_LOADERROR; Exit; end; if LoadBrokenABI and LoadFunction(@EVP_CIPHER_CTX_new, 'EVP_CIPHER_CTX_new') and LoadFunction(@EVP_CIPHER_CTX_free, 'EVP_CIPHER_CTX_free') and LoadFunction(@EVP_EncryptInit_ex, 'EVP_EncryptInit_ex') and LoadFunction(@EVP_EncryptUpdate, 'EVP_EncryptUpdate') and LoadFunction(@EVP_EncryptFinal_ex, 'EVP_EncryptFinal_ex') and LoadFunction(@EVP_DecryptInit_ex, 'EVP_DecryptInit_ex') and LoadFunction(@EVP_DecryptUpdate, 'EVP_DecryptUpdate') and LoadFunction(@EVP_DecryptFinal_ex, 'EVP_DecryptFinal_ex') and LoadFunction(@EVP_CIPHER_CTX_set_padding, 'EVP_CIPHER_CTX_set_padding') and LoadFunction(@EVP_aes_128_ecb, 'EVP_aes_128_ecb') and LoadFunction(@EVP_aes_128_cbc, 'EVP_aes_128_cbc') and LoadFunction(@EVP_aes_128_cfb, 'EVP_aes_128_cfb128') and LoadFunction(@EVP_aes_128_ofb, 'EVP_aes_128_ofb') and LoadFunction(@EVP_aes_128_ctr, 'EVP_aes_128_ctr') and LoadFunction(@EVP_aes_128_gcm, 'EVP_aes_128_gcm') and LoadFunction(@EVP_aes_192_ecb, 'EVP_aes_192_ecb') and LoadFunction(@EVP_aes_192_cbc, 'EVP_aes_192_cbc') and LoadFunction(@EVP_aes_192_cfb, 'EVP_aes_192_cfb128') and LoadFunction(@EVP_aes_192_ofb, 'EVP_aes_192_ofb') and LoadFunction(@EVP_aes_192_ctr, 'EVP_aes_192_ctr') and LoadFunction(@EVP_aes_192_gcm, 'EVP_aes_192_gcm') and LoadFunction(@EVP_aes_256_ecb, 'EVP_aes_256_ecb') and LoadFunction(@EVP_aes_256_cbc, 'EVP_aes_256_cbc') and LoadFunction(@EVP_aes_256_cfb, 'EVP_aes_256_cfb128') and LoadFunction(@EVP_aes_256_ofb, 'EVP_aes_256_ofb') and LoadFunction(@EVP_aes_256_ctr, 'EVP_aes_256_ctr') and LoadFunction(@EVP_aes_256_gcm, 'EVP_aes_256_gcm') and LoadFunction(@EVP_des_ecb, 'EVP_des_ecb') and LoadFunction(@EVP_des_cbc, 'EVP_des_cbc') then begin LibCryptoLoaded:= True; Result:= TF_S_OK; Exit; end; { 3277 621 00070BC0 EVP_des_cfb1 300 622 00070B90 EVP_des_cfb64 3267 623 00070BD0 EVP_des_cfb8 301 624 00070BB0 EVP_des_ecb 302 625 00071540 EVP_des_ede 303 626 000716A0 EVP_des_ede3 304 627 00071550 EVP_des_ede3_cbc 3280 628 00071580 EVP_des_ede3_cfb1 305 629 00071560 EVP_des_ede3_cfb64 3258 62A 00071590 EVP_des_ede3_cfb8 3236 62B 000716A0 EVP_des_ede3_ecb 306 62C 00071570 EVP_des_ede3_ofb 4737 62D 00071970 EVP_des_ede3_wrap 307 62E 00071510 EVP_des_ede_cbc 308 62F 00071520 EVP_des_ede_cfb64 3231 630 00071540 EVP_des_ede_ecb 309 631 00071530 EVP_des_ede_ofb 310 632 00070BA0 EVP_des_ofb 311 633 00073F20 EVP_desx_cbc } FreeLibrary(LibHandle); Result:= TF_E_LOADERROR; end; end.
unit svInIOCPService; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs, http_objects, iocp_managers, iocp_server; type TInIOCP_HTTP_Service = class(TService) InIOCPServer1: TInIOCPServer; InHttpDataProvider1: TInHttpDataProvider; procedure ServiceCreate(Sender: TObject); procedure ServiceStart(Sender: TService; var Started: Boolean); procedure ServiceStop(Sender: TService; var Stopped: Boolean); procedure InHttpDataProvider1Get(Sender: TObject; Request: THttpRequest; Response: THttpResponse); procedure InHttpDataProvider1Post(Sender: TObject; Request: THttpRequest; Response: THttpResponse); private { Private declarations } FWebSitePath: String; public { Public declarations } function GetServiceController: TServiceController; override; end; var InIOCP_HTTP_Service: TInIOCP_HTTP_Service; implementation uses iocp_varis, iocp_utils, iocp_log, http_base; {$R *.DFM} procedure ServiceController(CtrlCode: DWord); stdcall; begin InIOCP_HTTP_Service.Controller(CtrlCode); end; function TInIOCP_HTTP_Service.GetServiceController: TServiceController; begin Result := ServiceController; end; procedure TInIOCP_HTTP_Service.InHttpDataProvider1Get(Sender: TObject; Request: THttpRequest; Response: THttpResponse); begin // URI要与磁盘的文件对应 if Request.URI = '/' then Response.TransmitFile(FWebSitePath + 'index.htm') else // 调用函数时要单独判断 Response.TransmitFile(FWebSitePath + Request.URI); end; procedure TInIOCP_HTTP_Service.InHttpDataProvider1Post(Sender: TObject; Request: THttpRequest; Response: THttpResponse); begin // Post:已经接收完毕,调用此事件 // 此时:Request.Complete = True if Request.URI = '/ajax/login.htm' then // 动态页面 begin if (Request.Params.AsString['user_name'] <> '') and (Request.Params.AsString['user_password'] <> '') then // 登录成功 begin Response.CreateSession; // 生成 Session! Response.TransmitFile(FWebSitePath + 'ajax\ajax.htm'); end else Response.Redirect('ajax/login.htm'); // 重定位到登录页面 end else begin Response.SetContent('<html><body>In-IOCP HTTP 服务!<br>提交成功!<br>'); Response.AddContent('<a href="' + Request.URI + '">返回</a><br></body></html>'); end; end; procedure TInIOCP_HTTP_Service.ServiceCreate(Sender: TObject); begin iocp_varis.gAppPath := ExtractFilePath(ParamStr(0)); // 程序路径 FWebSitePath := iocp_varis.gAppPath + iocp_utils.AddBackslash(InHttpDataProvider1.RootDirectory); iocp_utils.MyCreateDir(iocp_varis.gAppPath + 'log'); // 建日志目录 end; procedure TInIOCP_HTTP_Service.ServiceStart(Sender: TService; var Started: Boolean); begin iocp_log.TLogThread.InitLog(iocp_varis.gAppPath + 'log'); // 开启日志 InIOCPServer1.Active := True; Started := InIOCPServer1.Active; end; procedure TInIOCP_HTTP_Service.ServiceStop(Sender: TService; var Stopped: Boolean); begin Stopped := True; InIOCPServer1.Active := False; iocp_log.TLogThread.StopLog; end; end.
unit DirectoryServerProtocol; interface type TAccountId = string; const DIR_NOERROR_StillTrial = -1; DIR_NOERROR = 0; DIR_ERROR_Unknown = 1; DIR_ERROR_AccountAlreadyExists = 2; DIR_ERROR_UnexistingAccount = 3; DIR_ERROR_SerialMaxed = 4; DIR_ERROR_InvalidSerial = 5; DIR_ERROR_InvalidAlias = 6; DIR_ERROR_InvalidPassword = 7; DIR_ERROR_AccountBlocked = 8; DIR_ERROR_TrialExpired = 9; type TSerialFamilyId = (famRegular, famTester, famGameMaster, famTutor); var SerialFamilies : array[TSerialFamilyId] of extended; // (0.1233, 0.1233, 0.1233, 0.1233); // (0.3737, 0.1212, 0.5555, 0.9191); function GetFamily( AccountId : TAccountId; out FamilyId : TSerialFamilyId ) : boolean; function IsValidAlias( Alias : string ) : boolean; function GetUserPath( Alias : string ) : string; function GetAliasId( Alias : string ) : string; implementation uses DirectoryServer, SysUtils, GenIdd; function GetFamily( AccountId : TAccountId; out FamilyId : TSerialFamilyId ) : boolean; var EndOfArray : boolean; begin FamilyId := low(FamilyId); repeat result := HeavyIddCheck( AccountId, SerialFamilies[FamilyId] ); EndOfArray := FamilyId = high(FamilyId); if not EndOfArray then inc( FamilyId ); until result or EndOfArray; end; function IsValidAlias( Alias : string ) : boolean; const Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; ValidChars = Alphabet + '0123456789 -_:?!(){}[]<>+=&@#$%^&|;,'; var i : integer; begin Alias := Trim( Alias ); if (Length( Alias ) > 0) and (Pos( UpCase( Alias[1] ), Alphabet ) > 0) then begin i := 2; while (i <= Length( Alias )) and (Pos( UpCase( Alias[i] ), ValidChars ) > 0) do inc( i ); result := i > Length( Alias ); end else result := false; end; function GetAliasId( Alias : string ) : string; var i : integer; begin result := Trim( Alias ); for i := 1 to Length( result ) do if result[i] = ' ' then result[i] := '.' else result[i] := UpCase( result[i] ); end; function GetUserPath( Alias : string ) : string; var aID : string; begin aID := GetAliasID( Alias ); result := 'Root/Users/' + aID[1] + '/' + Alias end; end.
program temperature; var selection : integer; centi, fahren : real; begin writeln('Please select an option: '); writeln('1. For Centigrate to Fahrenheit '); writeln('2. For Fahrenheit to centigrate '); write('>> '); read(selection); case selection of 1: begin write('Enter centigrate: '); read(centi); fahren := (9 / 5) * centi + 32; writeln('Fahrenheit temperature is: ', fahren:6:2); end; 2: begin write('Enter fahrenheit: '); read(fahren); centi := (5 / 9) * (fahren - 32); writeln('Centigrate temperature is: ', centi:6:2); end; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Hashmap * Implements a generic thread safe hash map *********************************************************************************************************************** } Unit TERRA_Hashmap; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Collections; Type HashMapObject = Class(CollectionObject) Protected _Key:TERRAString; Public Property Key:TERRAString Read _Key; End; HashMap = Class(Collection) Protected _Table:Array Of List; _TableSize:Word; Public Constructor Create(TableSize:Word = 1024); // Returns true if insertion was sucessful Function Add(Item:HashMapObject):Boolean;Virtual; // Returns true if deletion was sucessful Function Delete(Item:HashMapObject):Boolean; Virtual; Function ContainsReference(Item:CollectionObject):Boolean; Override; Function ContainsDuplicate(Item:CollectionObject):Boolean; Override; Function GetItemByIndex(Index:Integer):CollectionObject; Override; Function GetItemByKey(Const Key:TERRAString):CollectionObject; Function Search(Visitor:CollectionVisitor; UserData:Pointer = Nil):CollectionObject; Override; Procedure Visit(Visitor:CollectionVisitor; UserData:Pointer = Nil); Override; Function Filter(Visitor:CollectionVisitor; UserData:Pointer = Nil):List; Procedure Clear(); Override; Procedure Reindex(Item:HashMapObject); Function GetIterator:Iterator; Override; Property Items[Const Key:TERRAString]:CollectionObject Read GetItemByKey; Default; End; HashMapIterator = Class(Iterator) Protected _CurrentTable:Integer; _Current:CollectionObject; Function FindNextItem():CollectionObject; Function ObtainNext:CollectionObject; Override; Public Procedure Reset(); Override; End; Implementation Uses TERRA_Log, TERRA_MurmurHash; { HashMap } Constructor HashMap.Create(TableSize:Word); Begin _SortOrder := collection_Unsorted; _ItemCount := 0; _TableSize := TableSize; SetLength(_Table, _TableSize); Self.Init(0, Nil); End; Function HashMap.GetItemByIndex(Index: Integer): CollectionObject; Var I, K, Count:Integer; Begin If (Index<0) Or (Index>=Self.Count) Then Begin Result := Nil; Exit; End; K := 0; For I:=0 To Pred(_TableSize) Do If (Assigned(_Table[I])) Then Begin Count := _Table[I].Count; If (Index>=K) And (Index< K + Count) Then Begin Result := _Table[I].GetItemByIndex(Index - K); Exit; End; Inc(K, Count); End; Result := Nil; End; Function HashMap.Search(Visitor: CollectionVisitor; UserData:Pointer = Nil): CollectionObject; Var I:Integer; Begin Result := Nil; For I:=0 To Pred(_TableSize) Do If Assigned(_Table[I]) Then Begin Result := _Table[I].Search(Visitor, UserData); If Assigned(Result) Then Exit; End; End; Procedure HashMap.Visit(Visitor: CollectionVisitor; UserData:Pointer = Nil); Var I:Integer; Begin For I:=0 To Pred(_TableSize) Do If Assigned(_Table[I]) Then _Table[I].Visit(Visitor, UserData); End; Function HashMap.Filter(Visitor: CollectionVisitor; UserData: Pointer):List; Var It:Iterator; A,B:CollectionObject; Begin Result := List.Create(collection_Unsorted); It := Self.GetIterator(); While It.HasNext Do Begin A := It.Value; If (Visitor(A, UserData)) Then Begin B := CollectionObject(A.ClassType.Create()); B.CopyValue(A); Result.Add(B); End; End; End; Function HashMap.Add(Item:HashMapObject):Boolean; Var Key:HashKey; Begin Result := False; If Item = Nil Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Obtaining an hash for this item...');{$ENDIF} Key := Murmur2(Item.Key); {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Got hash index: '+HexStr(Key));{$ENDIF} Key := Key Mod _TableSize; If Not Assigned(_Table[Key]) Then Begin {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Allocating a new table...');{$ENDIF} _Table[Key] := List.Create(collection_Unsorted); End; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Adding item to table...');{$ENDIF} Result := _Table[Key].Add(Item); Inc(_ItemCount); {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Insertion was ok!');{$ENDIF} End; Function HashMap.Delete(Item:HashMapObject):Boolean; Var Key:HashKey; Begin Result := False; If (Item = Nil) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Obtaining an hash for this item...');{$ENDIF} Key := Murmur2(Item.Key); {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Got hash index: '+HexStr(Key));{$ENDIF} Key := Key Mod _TableSize; If Not Assigned(_Table[Key]) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Removing item from table...');{$ENDIF} Result := (_Table[Key].Delete(Item)); If Result Then Dec(_ItemCount); End; Function HashMap.ContainsReference(Item:CollectionObject):Boolean; Var Key:HashKey; Begin Result := False; If (Item = Nil) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Obtaining an hash for this item...');{$ENDIF} Key := Murmur2(HashMapObject(Item).Key); {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Got hash index: '+HexStr(Key));{$ENDIF} Key := Key Mod _TableSize; If Not Assigned(_Table[Key]) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Searching item in table...');{$ENDIF} Result := (_Table[Key].ContainsReference(Item)); End; Function HashMap.ContainsDuplicate(Item:CollectionObject):Boolean; Var Key:HashKey; Begin Result := False; If (Item = Nil) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Obtaining an hash for this item...');{$ENDIF} Key := Murmur2(HashMapObject(Item).Key); {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Got hash index: '+HexStr(Key));{$ENDIF} Key := Key Mod _TableSize; If Not Assigned(_Table[Key]) Then Exit; {$IFDEF DEBUG}Log(logDebug, 'HashMap', 'Searching item in table...');{$ENDIF} Result := (_Table[Key].ContainsDuplicate(Item)); End; Procedure HashMap.Clear(); Var I:Integer; Begin For I:=0 To Pred(_TableSize) Do If Assigned(_Table[I]) Then Begin Dec(_ItemCount, _Table[I].Count); ReleaseObject(_Table[I]); End; End; Function HashMap.GetItemByKey(const Key: TERRAString): CollectionObject; Var K:HashKey; Index:Integer; P:HashMapObject; Begin K := Murmur2(Key); Index := K Mod _TableSize; Result := Nil; Self.Lock(); If Assigned(_Table[Index]) Then Begin P := HashMapObject(_Table[Index].First); While Assigned(P) Do If (StringEquals(Key, P.Key)) Then Begin Result := P; Break; End Else P := HashMapObject(P.Next); End; Self.Unlock(); End; Function HashMap.GetIterator:Iterator; Var MyIterator:HashMapIterator; Begin MyIterator := HashMapIterator.Create(Self); Result := MyIterator; End; Procedure HashMap.Reindex(Item: HashMapObject); Begin DebugBreak; End; { HashMapIterator } Procedure HashMapIterator.Reset(); Begin Inherited; _CurrentTable := -1; _Current := Nil; End; Function HashMapIterator.FindNextItem():CollectionObject; Var I:Integer; Table:HashMap; Begin Table := HashMap(Self.Collection); For I := Succ(_CurrentTable) To Pred(Table._TableSize) Do If Assigned(Table._Table[I]) Then Begin Result := Table._Table[I].First; _CurrentTable := I; Exit; End; Result := Nil; End; Function HashMapIterator.ObtainNext:CollectionObject; Begin If (_Current = Nil) And (Self.Index<Self.Collection.Count) Then Begin _Current := FindNextItem(); End; If Assigned(_Current) Then Begin Result := _Current; _Current := _Current.Next; End Else Result := Nil; End; End.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 2004.05.20 12:34:32 PM czhower Removed more non .NET compatible stream read and writes Rev 1.4 2004.01.20 10:03:30 PM czhower InitComponent Rev 1.3 2003.10.17 6:15:56 PM czhower Upgrades Rev 1.2 2003.10.17 4:28:54 PM czhower Changed stream names to be consistent with IOHandlerStream Rev 1.1 2003.10.14 1:27:12 PM czhower Uupdates + Intercept support Rev 1.0 11/13/2002 07:56:18 AM JPMugaas } unit IdLogStream; interface {$I IdCompilerDefines.inc} //Put FPC into Delphi mode uses Classes, IdLogBase, IdGlobal; type TIdLogStream = class(TIdLogBase) protected FFreeStreams: Boolean; FReceiveStream: TStream; FSendStream: TStream; // procedure InitComponent; override; procedure LogStatus(const AText: string); override; procedure LogReceivedData(const AText, AData: string); override; procedure LogSentData(const AText, AData: string); override; public procedure Disconnect; override; // property FreeStreams: Boolean read FFreeStreams write FFreeStreams; property ReceiveStream: TStream read FReceiveStream write FReceiveStream; property SendStream: TStream read FSendStream write FSendStream; end; implementation uses SysUtils; // TODO: This was orginally for VCL. For .Net what do we do? Convert back to // 7 bit? Log all? Logging all seems to be a disaster. // Text seems to be best, users are expecting text in this class. But // this write stream will dump unicode out in .net..... // So just convert it again back to 7 bit? How is proper to write // 7 bit to file? Use AnsiString? { TIdLogStream } procedure TIdLogStream.Disconnect; begin inherited Disconnect; if FreeStreams then begin FreeAndNil(FReceiveStream); FreeAndNil(FSendStream); end; end; procedure TIdLogStream.InitComponent; begin inherited InitComponent; FFreeStreams := True; end; procedure TIdLogStream.LogReceivedData(const AText, AData: string); begin if FReceiveStream <> nil then begin WriteStringToStream(FReceiveStream, AData, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); end; end; procedure TIdLogStream.LogSentData(const AText, AData: string); begin if FSendStream <> nil then begin WriteStringToStream(FSendStream, AData, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); end; end; procedure TIdLogStream.LogStatus(const AText: string); begin // We just leave this empty because the AText is not part of the stream and we // do not want to raise an abstract method exception. end; end.
unit wwSimpleMind; interface Uses wwMinds, wwTypes; type TSimpletonMind = class (TwwMind) protected function GetCaption: string; override; function GetEnglishCaption: string; override; function Thinking: TwwDirection; override; end; TLazyMind = class (TSimpletonMind) protected function GetCaption: string; override; function GetEnglishCaption: string; override; function Thinking: TwwDirection; override; end; TGourmetMind = class (TSimpletonMind) protected function GetCaption: string; override; function GetEnglishCaption: string; override; function Thinking: TwwDirection; override; end; implementation Uses Types, wwUtils, wwWorms, WOrmsWorld; { ******************************** TSimpletonMind ******************************** } function TSimpletonMind.GetCaption: string; begin Result:= 'Простак'; end; function TSimpletonMind.GetEnglishCaption: string; begin Result:= 'Simpleton'; end; function TSimpletonMind.Thinking: TwwDirection; var NewHead: TPoint; NewDir, TailDir: TwwDirection; LegalDirs: set of TwwDirection; Num: Integer; l_W: TwwWorm; begin l_W:= Thing as TwwWorm; case l_W.Favorite of ftVertical: begin if l_W.Target.Head.Position.Y <> l_W.Head.Position.Y then begin if l_W.Target.Head.Position.Y - l_W.Head.Position.Y > 0 then NewDir:= dtDown else NewDir:= dtUp; end else begin if l_W.Target.Head.Position.X - l_W.Head.Position.X > 0 then NewDir:= dtRight else NewDir:= dtLeft; end; end; // ftVertical ftHorizontal: begin if l_W.Target.Head.Position.X <> l_W.Head.Position.X then begin if l_W.Target.Head.Position.X-l_W.Head.Position.X > 0 then NewDir:= dtRight else NewDir:= dtLeft; end else begin if l_W.Target.Head.Position.Y-l_W.Head.Position.Y > 0 then NewDir:= dtDown else NewDir:= dtUp; end; end; // ftHorizontal end; { case } MovePoint(l_W.Head.Position, NewDir, NewHead); if not IsFree(NewHead) then begin LegalDirs:= [dtLeft, dtUp, dtRight, dtDown]; TailDir:= dtStop; if l_W.IsMe(NewHead) then begin TailDir:= l_W.ToTail(NewHead); if TailDir <> dtStop then NewDir:= TailDir; end; // isMe MovePoint(l_W.Head.Position, NewDir, NewHead); repeat if not IsFree(NewHead) then begin if not (NewDir in LegalDirs{[dtStop..dtDown]}) then begin Result:= dtStop; break; end; // not (NewDir in [dtStop..dtDown]) Exclude(LegalDirs, NewDir); if ShiftDir(TailDir) = l_W.ToHead(NewHead) then NewDir:= ShiftDirLeft(NewDir) else NewDir:= ShiftDir(NewDir); MovePoint(l_W.Head.Position, NewDir, NewHead); end; // not IsFree until (IsFree(NewHead) or (LegalDirs = [])); if LegalDirs = [] then NewDir:= dtStop; end; Result:= NewDir; end; { ********************************** TLazyMind *********************************** } function TLazyMind.GetCaption: string; begin Result:= 'Ленивый Простак'; end; function TLazyMind.GetEnglishCaption: string; begin Result:= 'Lazy Simpleton' end; function TLazyMind.Thinking: TwwDirection; begin TwwWorm(Thing).Target:= (Thing.World as TWormsField).NearestTarget(Thing.Head.Position); Result:= inherited Thinking; end; { ********************************* TGourmetMind ********************************* } function TGourmetMind.GetCaption: string; begin Result:= 'Простак-гурман' end; function TGourmetMind.GetEnglishCaption: string; begin Result:= 'Gourmet' end; function TGourmetMind.Thinking: TwwDirection; var l_C, l_D: TwwTarget; begin l_C:= (Thing.World as TWormsField).PowerestTarget; l_D:= (Thing.World as TWormsField).NearestTarget(Thing.Head.Position); if l_D.Power = l_C.Power then TwwWorm(Thing).Target:= l_D else TwwWorm(Thing).Target:= l_C; Result := inherited Thinking; end; end.
unit ce_libmaneditor; {$I ce_defines.inc} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, ComCtrls, Buttons, ce_widget, ce_interfaces, ce_project, ce_dmdwrap, ce_common; type { TCELibManEditorWidget } TCELibManEditorWidget = class(TCEWidget, ICEProjectObserver) btnMoveDown: TBitBtn; btnMoveUp: TBitBtn; btnReg: TBitBtn; btnSelFile: TBitBtn; btnAddLib: TBitBtn; btnRemLib: TBitBtn; btnEditAlias: TBitBtn; btnSelfoldOfFiles: TBitBtn; btnSelRoot: TBitBtn; List: TListView; Panel1: TPanel; procedure btnAddLibClick(Sender: TObject); procedure btnEditAliasClick(Sender: TObject); procedure btnRegClick(Sender: TObject); procedure btnRemLibClick(Sender: TObject); procedure btnSelFileClick(Sender: TObject); procedure btnSelfoldOfFilesClick(Sender: TObject); procedure btnSelRootClick(Sender: TObject); procedure btnMoveUpClick(Sender: TObject); procedure btnMoveDownClick(Sender: TObject); procedure ListEdited(Sender: TObject; Item: TListItem; var AValue: string); private fProj: TCEProject; procedure updateRegistrable; procedure projNew(aProject: TCEProject); procedure projChanged(aProject: TCEProject); procedure projClosing(aProject: TCEProject); procedure projFocused(aProject: TCEProject); procedure projCompiling(aProject: TCEProject); // procedure dataToGrid; procedure gridToData; protected procedure DoShow; override; public constructor Create(aOwner: TComponent); override; end; implementation {$R *.lfm} uses ce_libman; const notav: string = '< n/a >'; constructor TCELibManEditorWidget.Create(aOwner: TComponent); var png: TPortableNetworkGraphic; begin inherited; png := TPortableNetworkGraphic.Create; try png.LoadFromLazarusResource('arrow_down'); btnMoveDown.Glyph.Assign(png); png.LoadFromLazarusResource('arrow_up'); btnMoveUp.Glyph.Assign(png); png.LoadFromLazarusResource('book_add'); btnAddLib.Glyph.Assign(png); png.LoadFromLazarusResource('book_delete'); btnRemLib.Glyph.Assign(png); png.LoadFromLazarusResource('book_edit'); btnEditAlias.Glyph.Assign(png); png.LoadFromLazarusResource('folder_brick'); btnSelFile.Glyph.Assign(png); png.LoadFromLazarusResource('bricks'); btnSelfoldOfFiles.Glyph.Assign(png); png.LoadFromLazarusResource('folder_add'); btnSelRoot.Glyph.Assign(png); png.LoadFromLazarusResource('book_link'); btnReg.Glyph.Assign(png); finally png.Free; end; end; procedure TCELibManEditorWidget.updateRegistrable; begin btnReg.Enabled := (fProj <> nil) and (fProj.currentConfiguration.outputOptions.binaryKind = staticlib) and (FileExists(fProj.Filename)) end; procedure TCELibManEditorWidget.projNew(aProject: TCEProject); begin fProj := aProject; end; procedure TCELibManEditorWidget.projChanged(aProject: TCEProject); begin updateRegistrable; end; procedure TCELibManEditorWidget.projClosing(aProject: TCEProject); begin if aProject <> fProj then exit; fProj := nil; updateRegistrable; end; procedure TCELibManEditorWidget.projFocused(aProject: TCEProject); begin fProj := aProject; updateRegistrable; end; procedure TCELibManEditorWidget.projCompiling(aProject: TCEProject); begin end; procedure TCELibManEditorWidget.ListEdited(Sender: TObject; Item: TListItem; var AValue: string); begin gridToData; end; procedure TCELibManEditorWidget.btnAddLibClick(Sender: TObject); var itm: TListItem; begin itm := List.Items.Add; itm.Caption := notav; itm.SubItems.Add(notav); itm.SubItems.Add(notav); SetFocus; itm.Selected := True; end; procedure TCELibManEditorWidget.btnEditAliasClick(Sender: TObject); var al: string; begin if List.Selected = nil then exit; al := List.Selected.Caption; if inputQuery('library alias', '', al) then List.Selected.Caption := al; gridToData; end; procedure TCELibManEditorWidget.btnRegClick(Sender: TObject); var str: TStringList; root: string; lalias: string; i: integer; begin if fProj = nil then exit; // lalias := ExtractFileNameOnly(fProj.Filename); if List.Items.FindCaption(0, lalias, false, false, false) <> nil then begin dlgOkInfo(format('a library item with the alias "%s" already exists, delete it before trying again.', [lalias])); exit; end; // str := TStringList.Create; try for i := 0 to fProj.Sources.Count-1 do str.Add(fProj.getAbsoluteSourceName(i)); root := commonFolder(str); root := ExtractFileDir(root); if root = '' then begin dlgOkInfo('the static library can not be registered because its source files have no common folder'); exit; end; // with List.Items.Add do begin Caption := ExtractFileNameOnly(fProj.Filename); if ExtractFileExt(fProj.outputFilename) <> libExt then SubItems.add(fProj.outputFilename + libExt) else SubItems.add(fProj.outputFilename); SubItems.add(root); if not FileExists(SubItems[0]) then dlgOkInfo('the library file does not exist, maybe the project not been already compiled ?'); Selected:= true; end; SetFocus; gridToData; finally str.free; end; end; procedure TCELibManEditorWidget.btnRemLibClick(Sender: TObject); begin if List.Selected = nil then exit; List.Items.Delete(List.Selected.Index); gridToData; end; procedure TCELibManEditorWidget.btnSelFileClick(Sender: TObject); var ini: string; begin if List.Selected = nil then exit; if List.Selected.SubItems.Count > 0 then ini := List.Selected.SubItems[0] else begin ini := ''; List.Selected.SubItems.Add(ini); end; with TOpenDialog.Create(nil) do try filename := ini; if Execute then begin if not fileExists(filename) then List.Selected.SubItems[0] := extractFilePath(filename) else begin List.Selected.SubItems[0] := filename; if (List.Selected.Caption = '') or (List.Selected.Caption = notav) then List.Selected.Caption := ChangeFileExt(extractFileName(filename), ''); end; end; finally Free; end; gridToData; end; procedure TCELibManEditorWidget.btnSelfoldOfFilesClick(Sender: TObject); var dir, outdir: string; begin if List.Selected = nil then exit; if List.Selected.SubItems.Count > 0 then dir := List.Selected.SubItems[0] else begin dir := ''; List.Selected.SubItems.Add(dir); end; if selectDirectory('folder of static libraries', dir, outdir, True, 0) then List.Selected.SubItems[0] := outdir; gridToData; end; procedure TCELibManEditorWidget.btnSelRootClick(Sender: TObject); var dir, outdir: string; begin if List.Selected = nil then exit; if List.Selected.SubItems.Count > 1 then dir := List.Selected.SubItems[1] else begin dir := ''; while List.Selected.SubItems.Count < 2 do List.Selected.SubItems.Add(dir); end; if selectDirectory('sources root', dir, outdir, True, 0) then List.Selected.SubItems[1] := outdir; gridToData; end; procedure TCELibManEditorWidget.btnMoveUpClick(Sender: TObject); begin if list.Selected = nil then exit; if list.Selected.Index = 0 then exit; // list.Items.Exchange(list.Selected.Index, list.Selected.Index - 1); gridToData; end; procedure TCELibManEditorWidget.btnMoveDownClick(Sender: TObject); begin if list.Selected = nil then exit; if list.Selected.Index = list.Items.Count - 1 then exit; // list.Items.Exchange(list.Selected.Index, list.Selected.Index + 1); gridToData; end; procedure TCELibManEditorWidget.DoShow; begin inherited; dataToGrid; end; procedure TCELibManEditorWidget.dataToGrid; var itm: TLibraryItem; row: TListItem; i: Integer; begin if LibMan = nil then exit; List.BeginUpdate; List.Clear; for i := 0 to LibMan.libraries.Count - 1 do begin itm := TLibraryItem(LibMan.libraries.Items[i]); row := List.Items.Add; row.Caption := itm.libAlias; row.SubItems.Add(itm.libFile); row.SubItems.Add(itm.libSourcePath); end; List.EndUpdate; end; procedure TCELibManEditorWidget.gridToData; var itm: TLibraryItem; row: TListItem; begin if LibMan = nil then exit; LibMan.libraries.BeginUpdate; LibMan.libraries.Clear; for row in List.Items do begin itm := TLibraryItem(LibMan.libraries.Add); itm.libAlias := row.Caption; itm.libFile := row.SubItems.Strings[0]; itm.libSourcePath := row.SubItems.Strings[1]; end; LibMan.libraries.EndUpdate; LibMan.updateDCD; end; end.
unit CsCommon; { $Id: CsCommon.pas,v 1.8 2008/10/01 07:45:40 narry Exp $ } // $Log: CsCommon.pas,v $ // Revision 1.8 2008/10/01 07:45:40 narry // - добавлен путь к образам документов // // Revision 1.7 2008/07/14 07:47:53 narry // - получение путей к базе с сервера (первый шаг, немного в сторону) // // Revision 1.6 2006/11/22 16:23:56 fireton // - подготовка к большому UserID // // Revision 1.5 2006/08/03 13:22:01 narry // - увеличение версии протокола и реакция на ее не совпадение // // Revision 1.4 2006/06/14 12:25:15 narry // - новое: переход на новый механизм рассылки нотификаций // // Revision 1.3 2006/06/08 15:54:40 fireton // - подготовка к переходу на большой User ID // // Revision 1.2 2006/02/08 17:24:29 step // выполнение запросов перенесено из классов-потомков в процедуры объектов // {$I CsDefine.inc} interface uses IdGlobal; type TCsClientId = LongWord; TCsPort = TIdPort; TCsIp = string; // заменить на ченить поприличней TcsError = Integer; TcsLoginExDataEvent = procedure(out aDocBaseVer, aAdminBaseVer: Integer; out aFamilyRoot, aTablePath, aHomePath, aLockpath, aImagesPath: String) of object; implementation end.
unit Controller.Produto; interface uses Horse, Service.Produto, System.JSON, Dataset.Serialize,System.SysUtils; type TControllerProduto = class public class procedure List(Req : THorseRequest; Res : THorseResponse; Next: TProc); class procedure GetById(Req : THorseRequest; Res : THorseResponse; Next: TProc); class procedure Update(Req : THorseRequest; Res : THorseResponse; Next: TProc); class procedure Insert(Req : THorseRequest; Res : THorseResponse; Next: TProc); class procedure Delete(Req : THorseRequest; Res : THorseResponse; Next: TProc); class procedure Registry; end; implementation { TControllerProduto } class procedure TControllerProduto.Delete(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LService : TServiceProduto; LID : Cardinal; begin LService := TServiceProduto.Create(nil); try LID := Req.Params['id'].ToInt64; if LService.GetByID(LID).IsEmpty then raise EHorseException.Create(THTTPStatus.NotFound,'Registro não foi encontrado'); if LService.Delete then Res.Status(THTTPStatus.NoContent) else raise EHorseException.Create(THTTPStatus.NotModified,'Não foi possível deletar!'); finally LService.Free; end; end; class procedure TControllerProduto.GetById(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LService : TServiceProduto; LJson : TJSONArray; IDProduto : Integer; begin LService := TServiceProduto.Create(nil); try IDProduto := Req.Params['id'].ToInt64; if LService.GetByID(IDProduto).IsEmpty then raise EHorseException.Create(THTTPStatus.NotFound,'O registro não foi encontrado!'); LJson := LService.qUpdate.ToJSONArray(); finally LService.Free; end; Res.Send<TJSONArray>(LJson); end; class procedure TControllerProduto.Insert(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LService : TServiceProduto; LBody : TJSONObject; begin LService := TServiceProduto.Create(nil); try LBody := Req.Body<TJSONObject>; if LService.Insert(LBody) then Res.Send<TJSONObject>(LService.qUpdate.ToJSONObject).Status(THTTPStatus.Created) else raise EHorseException.Create(THTTPStatus.NotModified,'Não foi criado'); finally LService.Free; end; end; class procedure TControllerProduto.List(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LService : TServiceProduto; LJson : TJSONArray; begin LService := TServiceProduto.Create(nil); try LJson := LService.List(Req.Query).ToJSONArray(); finally LService.Free; end; Res.Send<TJSONArray>(LJson); end; class procedure TControllerProduto.Update(Req: THorseRequest; Res: THorseResponse; Next: TProc); var LService : TServiceProduto; LBody : TJSONObject; LID : Cardinal; begin LService := TServiceProduto.Create(nil); try LID := Req.Params['id'].ToInt64; if LService.GetByID(LID).IsEmpty then raise EHorseException.Create(THTTPStatus.NotFound,'Registro não foi encontrado'); LBody := Req.Body<TJSONObject>; if LService.Update(LBody) then Res.Status(THTTPStatus.NoContent) else raise EHorseException.Create(THTTPStatus.NotModified,'Não foi modificado'); finally LService.Free; end; end; class procedure TControllerProduto.Registry; begin THorse.Get('/produtos',TControllerProduto.List); THorse.Get('/produtos/:id',TControllerProduto.GetById); THorse.Post('/produtos', TControllerProduto.Insert); THorse.Put('/produtos/:id', TControllerProduto.Update); THorse.Delete('/produtos/:id', TControllerProduto.Delete); end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Colors, FMX.ExtCtrls, FMX.ListBox; type Tmainfrm = class(TForm) recBoard: TPaintBox; ToolBar1: TToolBar; pbdraw: TPopupBox; cbfg: TComboColorBox; cbbg: TComboColorBox; SpeedButton1: TSpeedButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure recBoardGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure recBoardMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure recBoardMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure recBoardMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure recBoardPaint(Sender: TObject; Canvas: TCanvas); procedure pbdrawChange(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private idraw:integer; drawbmp:TBitmap; drawbmprect:TRectF; drawrect:TRectF; pFrom,pTo:TPointF; bdrawing:boolean; procedure StartDrawing(startP:TPointF); procedure EndDrawing(startP:TPointF); procedure DoDraw(Canvas: TCanvas;const drawall:boolean=true); public { Public declarations } procedure FillColor(color:TAlphaColor); end; var mainfrm: Tmainfrm; implementation {$R *.fmx} procedure Tmainfrm.DoDraw(Canvas: TCanvas;const drawall:boolean); var r:TRectF; br:TBrush; str:TStrokeBrush; begin if (drawall) then recBoard.Canvas.DrawBitmap(drawbmp,drawrect,drawrect,1); if (idraw<=0) or(not bdrawing) then exit; br:=TBrush.Create(TBrushKind.bkSolid,cbbg.Color); str:=TStrokeBrush.Create(TBrushKind.bkSolid,cbfg.Color); str.DefaultColor:=cbfg.Color; str.Thickness:=1; r:=TRectF.Create(pFrom,pTo); Canvas.BeginScene(); case idraw of 1:begin Canvas.DrawLine(pFrom,pTo,1,str); end; 2:begin Canvas.FillRect(r,0,0,[TCorner.crTopLeft],1,br); Canvas.DrawRect(r,0,0,[TCorner.crTopLeft],1,str); end; 3:begin Canvas.FillEllipse(r,1,br); Canvas.DrawEllipse(r,1,str); end; 4:begin Canvas.Clear(cbbg.Color); end; end; Canvas.EndScene; br.Free; str.Free; end; procedure Tmainfrm.FillColor(color: TAlphaColor); begin with drawbmp.Canvas do begin BeginScene(); Clear(color); EndScene; end; end; procedure Tmainfrm.FormCreate(Sender: TObject); begin bdrawing:=false; idraw:=0; pFrom := PointF(-1, -1); drawrect:=RectF(0,0,recBoard.Width, recBoard.Height); drawbmprect:=RectF(0,0,recBoard.Width, recBoard.Height); drawbmp := TBitmap.Create(Round(drawbmprect.Width),Round(drawbmprect.Height)); FillColor(cbbg.Color); end; procedure Tmainfrm.FormDestroy(Sender: TObject); begin drawbmp.Free; end; procedure Tmainfrm.pbdrawChange(Sender: TObject); begin if (idraw=pbdraw.ItemIndex) then exit; if (pbdraw.ItemIndex>0) then begin //save context end else begin end; idraw:=pbdraw.ItemIndex; end; procedure Tmainfrm.recBoardGesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin { if ((pFrom.X <> -1) and (pFrom.Y <> -1)) then if (idraw<=0) then exit; if (not bdrawing) then begin if TInteractiveGestureFlag.gfBegin in EventInfo.Flags then StartDrawing(PointF(EventInfo.Location.X, EventInfo.Location.Y)); end else begin if TInteractiveGestureFlag.gfEnd in EventInfo.Flags then begin EndDrawing(PointF(EventInfo.Location.X, EventInfo.Location.Y)); end else begin pTo := PointF(EventInfo.Location.X, EventInfo.Location.Y); recBoard.InvalidateRect(drawrect); end; end; } end; procedure Tmainfrm.recBoardMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if (not bdrawing) then begin StartDrawing(PointF(X, Y)); end; end; procedure Tmainfrm.recBoardMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin if (not bdrawing) then exit; pTo := PointF(X, Y); recBoard.InvalidateRect(drawrect); end; procedure Tmainfrm.recBoardMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin EndDrawing(PointF(X, Y)); end; procedure Tmainfrm.recBoardPaint(Sender: TObject; Canvas: TCanvas); begin DoDraw(Canvas); end; procedure Tmainfrm.SpeedButton1Click(Sender: TObject); begin //drawbmp.SaveToFile(); end; procedure Tmainfrm.StartDrawing(startP: TPointF); begin if (bdrawing) or (idraw<=0) then exit; pFrom := PointF(startP.X, startP.Y); pTo := PointF(startP.X, startP.Y); bdrawing:=true; end; procedure Tmainfrm.EndDrawing(startP: TPointF); begin if (not bdrawing) then exit; pTo := PointF(startP.X,startP.Y); DoDraw(drawbmp.Canvas,false); bdrawing:=false; pFrom := PointF(-1, -1); pTo := PointF(-1, -1); end; end.
unit uSceneLoad; interface uses uScene, Graphics, uGraph; type TSceneLoad = class(TSceneCustom) private FGraph: TGraph; FLogo: TBitmap; FLoadMsg: string; FIsLoad: Boolean; procedure Load; public //** Конструктор. constructor Create; destructor Destroy; override; procedure Draw(); override; procedure Story; function Keys(var Key: Word): Boolean; override; function Enum(): TSceneEnum; override; end; implementation uses Forms, SysUtils, Types, uMain, uIni, uSCR, uGUI, uSceneMenu, uUtils, uGUIBorder; { TSceneLoad } constructor TSceneLoad.Create; begin FIsLoad := False; FLoadMsg := 'Загрузка...'; FGraph := TGraph.Create(Path + 'Data\Images\Screens\'); end; function TSceneLoad.Keys(var Key: Word): Boolean; begin Result := True; end; destructor TSceneLoad.Destroy; begin FGraph.Free; inherited; end; procedure TSceneLoad.Draw; var FTemp: TBitmap; begin if not FIsLoad then Load; FTemp := TBitmap.Create; try FTemp.Assign(FLogo); FTemp.Canvas.Brush.Style := bsClear; FGraph.DrawText(FLoadMsg, FTemp, 400 - (FTemp.Canvas.TextExtent(FLoadMsg).CX div 2), 550, GameFont.FontName, 20, $00103C49, True); SCR.BG.Canvas.Draw(0, 0, FTemp); finally FTemp.Free; end; end; function TSceneLoad.Enum: TSceneEnum; begin Result := scLoad; end; procedure TSceneLoad.Load; begin FIsLoad := True; FLogo := Graphics.TBitmap.Create; FGraph.LoadImage('Load.jpg', FLogo); GUIBorder.Make(FLogo); end; procedure TSceneLoad.Story(); var I, P: Integer; S, G: string; begin for I := 0 to 255 do begin G := Ini.Read(Path + 'Data\Story.ini', IntToStr(I), 'Picture', ''); if (G = '') then Break; S := Ini.Read(Path + 'Data\Story.ini', IntToStr(I), 'Message', ''); P := StrToInt(Ini.Read(Path + 'Data\Story.ini', IntToStr(I), 'Pause', '')); if (P = 0) then Break; FLogo := Graphics.TBitmap.Create; FGraph.LoadImage(G, FLogo); GUIBorder.Make(FLogo); FLoadMsg := Trim(S); fMain.RefreshBox; Sleep(P); end; Create(); end; end.
Program a3test1; { This program gives you a menu interface to manage two collections (c1 and c2). You can insert, delete, join, print and get the size of either collection. Use this to test your code. Make sure you hand in a compiled version of this program. NOTE: There is a new function here called "Peek". This lets you cheat and look at the internal structure of your collection (tree). The output is one line for each node, using a preorder traversal. Each line looks like this: V: <value>, B: <balance>, P: <parent node>, L: <Left child>, R: <Right Child> You can use this function to test your rotations and make sure everything works properly. } uses btadt, a3unit; Procedure Peek(C: Collection); begin If not Is_Empty(C) then begin write('V: ',Get_Root_Value_BT(C),', '); write('B: ',Get_Balance_Field_BT(C),', '); If not Is_Empty_BT(Parent_BT(C)) then write('P: ',Get_Root_Value_BT(Parent_BT(C)),', ') else write('P: NIL, '); If not Is_Empty_BT(LeftChild_BT(C)) then write('L: ',Get_Root_Value_BT(LeftChild_BT(C)),', ') else write('L: NIL, '); If not Is_Empty_BT(RightChild_BT(C)) then write('R: ',Get_Root_Value_BT(RightChild_BT(C)),'.') else write('R: NIL.'); writeln; Peek(LeftChild_BT(C)); Peek(RightChild_BT(C)) end end; var C1,C2: collection; choice: integer; s: collection_element; begin CreateColl(c1); CreateColl(c2); repeat writeln; write('1. Insert into C1, '); writeln('2. Insert into C2,'); write('3. Delete from C1, '); writeln('4. Delete from C2,'); write('5. Join C2 to C1, '); writeln('55. Join C1 to C2.') ; write('6. Get size of C1, '); writeln('7. Get size of C2,'); write('8. Print C1, '); writeln('9. Print C2,'); write('10. Peek at C1, '); write('11. Peek at C2, '); writeln('12. quit'); writeln; readln(choice); case choice of 1: begin Write('String to insert into C1: '); readln(s); Insert(C1, s); end; 2: begin Write('String to insert into C2: '); readln(s); Insert(C2, s); end; 3: begin Write('String to delete from C1: '); readln(s); Delete(C1, s); end; 4: begin Write('String to delete from C2: '); readln(s); Delete(C2, s); end; 5: begin Writeln('Joining C2 to C1, and calling CreateColl(C2) again'); Writeln('Now C1 contains all elements from C1 and C2, and C2 is empty'); Join(C1, C2); CreateColl(C2); end; 55: begin Writeln('Joining C1 to C2, and calling CreateColl(C1) again'); Writeln('Now C2 contains all elements from C1 and C2, and C1 is empty'); Join(C2, C1); CreateColl(C1); end; 6: begin Writeln('C1 has ',Size(C1),' elements'); end; 7: begin Writeln('C2 has ',Size(C2),' elements'); end; 8: begin Writeln('Contents of C1:'); writeln; Print(C1); end; 9: begin Writeln('Contents of C2:'); writeln; Print(C2); end; 10: begin if not is_empty(C1) then Peek(C1) else writeln('C1: Empty collection.') ; end; 11: begin if not is_empty(C2) then Peek(C2) else writeln('C2: Empty collection.') ; end; end; until (choice = 12); destroy(C1); destroy(C2); writeln('C1 and C2 destroyed'); IF MemCheck then writeln('Memory check passed') else writeln('Memory check failed - possible memory leak'); writeln; writeln('Bye Bye...'); end.
unit SessionHelper; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\SessionHelper.pas" // Стереотип: "SimpleClass" // Элемент модели: "SessionHelper" MUID: (47711DA00052) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses ; type SessionHelper = class private constructor Make; reintroduce; virtual; stdcall; protected function GetIsSessionActive: ByteBool; virtual; stdcall; procedure SetIsSessionActive(const aValue: ByteBool); virtual; stdcall; public class function Instance: SessionHelper; {* Метод получения экземпляра синглетона SessionHelper } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property IsSessionActive: ByteBool read GetIsSessionActive write SetIsSessionActive; end;//SessionHelper implementation uses l3ImplUses , SysUtils , l3Base //#UC START# *47711DA00052impl_uses* //#UC END# *47711DA00052impl_uses* ; var g_SessionHelper: SessionHelper = nil; {* Экземпляр синглетона SessionHelper } procedure SessionHelperFree; {* Метод освобождения экземпляра синглетона SessionHelper } begin l3Free(g_SessionHelper); end;//SessionHelperFree function SessionHelper.GetIsSessionActive: ByteBool; //#UC START# *47711DCF03A0_47711DA00052get_var* //#UC END# *47711DCF03A0_47711DA00052get_var* begin //#UC START# *47711DCF03A0_47711DA00052get_impl* !!! Needs to be implemented !!! //#UC END# *47711DCF03A0_47711DA00052get_impl* end;//SessionHelper.GetIsSessionActive procedure SessionHelper.SetIsSessionActive(const aValue: ByteBool); //#UC START# *47711DCF03A0_47711DA00052set_var* //#UC END# *47711DCF03A0_47711DA00052set_var* begin //#UC START# *47711DCF03A0_47711DA00052set_impl* !!! Needs to be implemented !!! //#UC END# *47711DCF03A0_47711DA00052set_impl* end;//SessionHelper.SetIsSessionActive constructor SessionHelper.Make; //#UC START# *477129B00039_47711DA00052_var* //#UC END# *477129B00039_47711DA00052_var* begin //#UC START# *477129B00039_47711DA00052_impl* !!! Needs to be implemented !!! //#UC END# *477129B00039_47711DA00052_impl* end;//SessionHelper.Make class function SessionHelper.Instance: SessionHelper; {* Метод получения экземпляра синглетона SessionHelper } begin if (g_SessionHelper = nil) then begin l3System.AddExitProc(SessionHelperFree); g_SessionHelper := Create; end; Result := g_SessionHelper; end;//SessionHelper.Instance class function SessionHelper.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_SessionHelper <> nil; end;//SessionHelper.Exists end.
Unit mte.utils; {----------------------------------------------------------} { Developed by Muhammad Ajmal p } { ajumalp@gmail.com } { pajmal@hotmail.com } { ajmal@erratums.com } {----------------------------------------------------------} {$mode objfpc}{$H+} Interface Uses base64, Classes, DB, Dialogs, lclintf, sqldb, SysUtils, CheckLst, variants; Type { TMTEUtils } TMTEUtils = Class Public Class Function StreamToBase64(aInputStream: TStream; aReset: Boolean = True): String; Class Function Base64ToStream(Const aBase64: String; aOutStream: TStream; Const aStrict: Boolean = False): Boolean; Overload; Class Function Base64ToStream(Const aBase64: TStrings; aOutStream: TStream; Const aStrict: Boolean = False): Boolean; Overload; Class Function Base64ToFile(Const aBase64, aFile: String): Boolean; Overload; Class Function Base64ToFile(Const aBase64: TStrings; Const aFile: String): Boolean; Overload; Class Function FileToBase64(Const aFile: String): String; Class Function StringToSet(Const aSrc: String): TSysCharSet; Class Function URIParamsEncode(Const aSrc: String): String; Class Function CharRange(Const aMin, aMax: Char): String; Class Function CharRangeAsSet(Const aMin, aMax: Char): TSysCharSet; End; Function StrStartsWith(aContent, aStart: String; aCaseSensitive: Boolean = True): Boolean; Function StrEndsWith(AContent, AEnd: String): Boolean; Function StrLastWord(AContent: String; ASeperator: Char = ' '): String; Function StrWordByIndex(AContent: String; AIndex: Integer; ASeperator: Char = ' '): String; Function StrSubString(AContent: String; AStart, AEnd: Integer): String; Overload; Function StrSubString(AContent: String; AStart: Integer): String; Overload; Function StrSubString(AReverseCnt: Integer; AContent: String): String; Overload; Function RemoveWhiteSpace(Const AValue: String): String; Procedure ShowInfoMsg(Const aMessage: String); Procedure ShowWarnMsg(Const aMessage: String); Procedure ShowErrMsg(Const aMessage: String); Function StringPad(Const aString: String; aLen: Integer; Const aChar: Char; aLeft: Boolean = True): String; Function StrLPad(Const aString: String; aLen: Integer; Const aChar: Char = ' '): String; Function StrRPad(Const aString: String; aLen: Integer; Const aChar: Char = ' '): String; Function IfThen(Const aCondition: Boolean; Const aTrueValue, aFalseValue: Variant): Variant; Procedure AssignParamFromVariant(Const aParam: TParam; Const aVarinat: Variant); Procedure AssignParamFromField(Const aParam: TParam; Const aField: TField); Function FuncEncDecrypt(Const aPassword: String; Const aDecrypt: Boolean = False): String; Function FuncEncrypt(aPassword: String): String; Function FuncEncryptPassword(aPassword: String): String; Function FileToBase64(Const aFileName: String): String; Procedure EFreeAndNil(Var aObj); Procedure SendMail(Const aMailAddress, aSubject, aBody: String); Function GetCheckedItems(Const aCheckListBox: TCheckListBox): String; Procedure SetCheckedItems(Const aCheckListBox: TCheckListBox; aData: String); Implementation Function StrStartsWith(aContent, aStart: String; aCaseSensitive: Boolean): Boolean; Var sStartStr: String; Begin sStartStr := Copy(aContent, 0, Length(aStart)); // returns true if sContent starts with sStart If aCaseSensitive Then Result := sStartStr = aStart Else Result := SameText(sStartStr, aStart); End; Function StrEndsWith(AContent, AEnd: String): Boolean; Var iLen: Integer; Begin // returns true if sContent ends with sEnd iLen := Length(AContent); Result := (Copy(AContent, iLen - (Length(AEnd) - 1), iLen) = AEnd); End; Function StrLastWord(AContent: String; ASeperator: Char = ' '): String; Var varList: TStrings; iCnt: Integer; Begin // return the last word in the string varList := TStringList.Create; Try iCnt := ExtractStrings([ASeperator], [' '], PChar(AContent), varList); Result := varList.Strings[Pred(iCnt)]; Finally varList.Free; End; End; Function StrWordByIndex(AContent: String; AIndex: Integer; ASeperator: Char): String; Var varList: TStringList; Begin // return the nth word in the string varList := TStringList.Create; Try ExtractStrings([aSeperator], [' '], PChar(aContent), varList); If aIndex = -1 Then // If aIndex = -1 // will return all words as TStringList Text Result := varList.Text Else Result := varList.Strings[Pred(aIndex)]; Finally varList.Free; End; End; Function StrSubString(AContent: String; AStart, AEnd: Integer): String; Begin // returns the substring from iStart to iEnd Result := Copy(aContent, aStart, aEnd - (aStart - 1)); End; Function StrSubString(AContent: String; AStart: Integer): String; Begin // returns the substring starting from iStart char index Result := StrSubString(aContent, aStart, Length(aContent)); End; Function StrSubString(AReverseCnt: Integer; AContent: String): String; Begin // returns the substring till the StrLen - iRevCnt Result := StrSubString(aContent, 1, Length(aContent) - aReverseCnt); End; Function RemoveWhiteSpace(Const AValue: String): String; Begin Result := StringReplace(AValue, ' ', '', [rfReplaceAll]); End; Function StringPad(Const aString: String; aLen: Integer; Const aChar: Char; aLeft: Boolean = True): String; Var varPadString: String; iPadLen: Integer; Begin Result := aString; iPadLen := aLen - Length(aString); If iPadLen > 0 Then Begin varPadString := StringOfChar(aChar, iPadLen); If aLeft Then Result := varPadString + aString Else Result := aString + varPadString; End; End; Function StrLPad(Const aString: String; aLen: Integer; Const aChar: Char): String; Begin Result := StringPad(aString, aLen, aChar, True); End; Function StrRPad(Const aString: String; aLen: Integer; Const aChar: Char): String; Begin Result := StringPad(aString, aLen, aChar, False); End; Procedure ShowInfoMsg(Const aMessage: String); Begin MessageDlg(aMessage, mtInformation, [mbOK], 0); End; Procedure ShowWarnMsg(Const aMessage: String); Begin MessageDlg(aMessage, mtWarning, [mbOK], 0); End; Procedure ShowErrMsg(Const aMessage: String); Begin MessageDlg(aMessage, mtError, [mbOK], 0); End; Function IfThen(Const aCondition: Boolean; Const aTrueValue, aFalseValue: Variant): Variant; Begin If ACondition Then Result := ATrueValue Else Result := AFalseValue; End; Procedure AssignParamFromField(Const aParam: TParam; Const aField: TField); Var varStrm: TStream; Begin If aField.IsNull Then Begin aParam.Clear; Exit; End; Case aField.DataType Of ftString: aParam.AsString := aField.AsString; ftSmallint, ftInteger, ftWord: aParam.AsSmallInt := aField.AsInteger; ftBoolean: aParam.AsBoolean := aField.AsBoolean; ftFloat: aParam.AsFloat := aField.AsFloat; ftCurrency: aParam.AsCurrency := aField.AsCurrency; ftBCD: aParam.AsBCD := aField.AsCurrency; ftDate: aParam.AsDate := aField.AsDateTime; ftTime: aParam.AsTime := aField.AsDateTime; ftDateTime: aParam.AsDateTime := aField.AsDateTime; ftBytes: aParam.AsBytes := aField.AsBytes; ftMemo, ftWideString, ftWideMemo: aParam.AsMemo := aField.AsString; ftLargeint: aParam.AsLargeInt := aField.AsLargeInt; ftBlob: Begin varStrm := TMemoryStream.Create; Try TBlobField(aField).SaveToStream(varStrm); aParam.LoadFromStream(varStrm, aField.DataType); Finally varStrm.Free; End; End Else aParam.Value := aField.AsVariant; End; End; Procedure AssignParamFromVariant(Const aParam: TParam; Const aVarinat: Variant); Var varVariantType: TVarType; Begin varVariantType := VarType(aVarinat); Case varVariantType Of varSmallint: aParam.AsSmallInt := VarAsType(aVarinat, varVariantType); varInteger, varSingle, varShortInt: aParam.AsInteger := VarAsType(aVarinat, varVariantType); varDouble: aParam.AsFloat := VarAsType(aVarinat, varVariantType); varCurrency: aParam.AsCurrency := VarAsType(aVarinat, varVariantType); varDate: aParam.AsDateTime := VarToDateTime(aVarinat); varBoolean: aParam.AsBoolean := VarAsType(aVarinat, varVariantType); varWord: aParam.AsWord := VarAsType(aVarinat, varVariantType); varInt64: aParam.AsLargeInt := VarAsType(aVarinat, varVariantType); varString: aParam.AsString := VarToStr(aVarinat); varUString: aParam.AsMemo := VarToStr(aVarinat); Else aParam.Value := aVarinat; End; End; Function FuncEncDecrypt(Const aPassword: String; Const aDecrypt: Boolean): String; Begin If aDecrypt Then Begin Result := DecodeStringBase64(aPassword); Result := StrSubString(Result, 6); Result := StrSubString(3, Result); Result := DecodeStringBase64(Result); End Else Begin Result := EncodeStringBase64(aPassword); Result := 'tfose' + Result + 'yrt'; Result := EncodeStringBase64(Result); End; End; Function FuncEncrypt(aPassword: String): String; Begin aPassword := EncodeStringBase64(aPassword); aPassword := 'tfose' + aPassword + 'yrt'; aPassword := EncodeStringBase64(aPassword); aPassword := StrSubString(aPassword, 3, aPassword.Length - 2); Result := aPassword.ToUpper; End; Function FuncEncryptPassword(aPassword: String): String; Begin aPassword := EncodeStringBase64(aPassword); While StrEndsWith(aPassword, '=') Do aPassword := StrSubString(aPassword, 1, Length(aPassword) - 1); aPassword := EncodeStringBase64(aPassword); While StrEndsWith(aPassword, '=') Do aPassword := StrSubString(aPassword, 1, Length(aPassword) - 1); Result := UpperCase(aPassword); End; Function FileToBase64(Const aFileName: String): String; Begin // base64. End; Procedure EFreeAndNil(Var aObj); Begin If Assigned(TObject(aObj)) Then FreeAndNil(aObj); End; Procedure SendMail(Const aMailAddress, aSubject, aBody: String); Const cMailToFormat = 'mailto:%s?subject=%s&body=%s'; Var sURL, sSubject, sBody: String; Begin sSubject := TMTEUtils.URIParamsEncode(aSubject); sBody := TMTEUtils.URIParamsEncode(aBody); sURL := Format(cMailToFormat, [aMailAddress, sSubject, sBody]); OpenURL(sURL); End; Function GetCheckedItems(Const aCheckListBox: TCheckListBox): String; Var iCntr: Integer; varList: TStringList; Begin varList := TStringList.Create; Try For iCntr := 0 To Pred(aCheckListBox.Items.Count) Do Begin If aCheckListBox.Checked[iCntr] Then varList.Add(aCheckListBox.Items[iCntr]); End; Result := varList.Text; Finally varList.Free; End; End; Procedure SetCheckedItems(Const aCheckListBox: TCheckListBox; aData: String); Var iCntr: Integer; iIndex: Integer; varList: TStringList; Begin varList := TStringList.Create; Try varList.Text := aData; For iCntr := 0 To Pred(aCheckListBox.Items.Count) Do aCheckListBox.Checked[iCntr] := varList.IndexOf(aCheckListBox.Items[iCntr]) >= 0; Finally varList.Free; End; End; { TMTEUtils } Class Function TMTEUtils.StringToSet(Const aSrc: String): TSysCharSet; Var iCntr: Integer; Begin Result := []; For iCntr := 1 To Length(aSrc) Do Result := Result + [aSrc[iCntr]]; End; Class Function TMTEUtils.URIParamsEncode(Const aSrc: String): String; Var i: Integer; Const cUnsafeChars = '*#%<>[]'; {do not localize} Begin Result := ''; {Do not Localize} For i := 1 To Length(aSrc) Do Begin // S.G. 27/11/2002: Changed the parameter encoding: Even in parameters, a space // S.G. 27/11/2002: is much more likely to be meaning "space" than "this is // S.G. 27/11/2002: a new parameter" // S.G. 27/11/2002: ref: Message-ID: <3de30169@newsgroups.borland.com> borland.public.delphi.internet.winsock // S.G. 27/11/2002: Most low-ascii is actually Ok in parameters encoding. If CharInSet(aSrc[i], StringToSet(cUnsafeChars)) Or (Not CharInSet(aSrc[i], CharRangeAsSet(#33, #128))) Then Result := Result + '%' + IntToHex(Ord(aSrc[i]), 2) Else Result := Result + aSrc[i]; End; End; Class Function TMTEUtils.CharRange(Const aMin, aMax: Char): String; Var iCntr: Char; Begin Result := ''; For iCntr := aMin To aMax Do Result := Result + iCntr; End; Class Function TMTEUtils.CharRangeAsSet(Const aMin, aMax: Char): TSysCharSet; Var iCntr: Char; Begin Result := []; For iCntr := aMin To aMax Do Result := Result + [iCntr]; End; Class Function TMTEUtils.StreamToBase64(aInputStream: TStream; aReset: Boolean): String; Var varOutputStrm: TStringStream; varEncoder: TBase64EncodingStream; Begin Result := EmptyStr; varOutputStrm := TStringStream.Create(EmptyStr); varEncoder := TBase64EncodingStream.Create(varOutputStrm); Try If aReset Then aInputStream.Seek(0, 0); varEncoder.CopyFrom(aInputStream, aInputStream.Size); varEncoder.Flush; Result := varOutputStrm.DataString; Finally varEncoder.Free; varOutputStrm.Free; End; End; Class Function TMTEUtils.Base64ToStream(Const aBase64: String; aOutStream: TStream; Const aStrict: Boolean): Boolean; Var varInStrm: TStringStream; varDecoder: TBase64DecodingStream; Begin Result := False; varInStrm := TStringStream.Create(aBase64); Try If aStrict Then varDecoder := TBase64DecodingStream.Create(varInStrm, bdmStrict) Else varDecoder := TBase64DecodingStream.Create(varInStrm, bdmMIME); Try aOutStream.CopyFrom(varDecoder, varDecoder.Size); Result := True; Finally varDecoder.Free; End; Finally varInStrm.Free; End; End; Class Function TMTEUtils.Base64ToStream(Const aBase64: TStrings; aOutStream: TStream; Const aStrict: Boolean): Boolean; Begin Result := TMTEUtils.Base64ToStream(aBase64.Text, aOutStream, aStrict); End; Class Function TMTEUtils.Base64ToFile(Const aBase64, aFile: String): Boolean; Var varOutStrm: TFileStream; Begin Result := False; varOutStrm := TFileStream.Create(aFile, fmCreate Or fmShareExclusive); Try Base64ToStream(aBase64, varOutStrm); Result := True; Finally varOutstrm.Free; End; End; Class Function TMTEUtils.Base64ToFile(Const aBase64: TStrings; Const aFile: String): Boolean; Begin Result := TMTEUtils.Base64ToFile(aBase64.Text, aFile); End; Class Function TMTEUtils.FileToBase64(Const aFile: String): String; Var varInputStrm: TFileStream; Begin If Not FileExists(aFile) Then Exit(EmptyStr); varInputStrm := TFileStream.Create(aFile, fmOpenRead Or fmShareDenyWrite); Try Result := StreamToBase64(varInputStrm); Finally varInputStrm.Free; End; End; End.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA 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 3 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, see <http://www.gnu.org/licenses/>. } unit Util; interface uses Global, SysUtils, windows, Graphics, forms, ComCtrls, cxRichEdit, DB, variants, ora, Classes, VirtualTable, cxListView; function isNVL(value, newValue: variant): variant; function isNull(value:string): string; function isNullorZero(value,DefaultValue:string): boolean; overload; function isNullorZero(value,DefaultValue: integer): boolean; overload; function isNullorZero(value,DefaultValue: Extended): boolean; overload; function ln: string; function Str(s: string): string; function Date(d: string): string; function CompareStr(str1, str2: string): boolean; procedure debug(txt: String); function getFirstWord( text: String ): String; function ExpectResultSet(ASql: String): Boolean; function ExpectScriptSet(ASql: String): Boolean; function GetColumnType(OraFieldName: string): string; function GetColumnValue(OraFieldName, Value: string): string; procedure DrawGradient(Canvas: TCanvas; const ARect: TRect; FromColor, ToColor: TColor; AStepCount: Integer; IsVertical: Boolean = False); procedure CodeColors(Form : TForm; Style :String; RichE : TcxRichedit; InVisible : Boolean); function GetInsertSQLWithData(TableName: string; QTable: TOraQuery; SelectedList: TStringList): string; function GetInsertSQL(TableName: string; FieldList: TFieldDefs): string; function GetUpdateSQL(TableName: string; FieldList: TFieldDefs): string; function GetDeleteSQL(TableName: string; FieldList: TFieldDefs): string; procedure DuplicateCurrentRecord(aDataSet : TDataSet); procedure CopyDataSet(Source: TDataSet; Target: TVirtualTable); procedure FillViewHorizontal(Source: TDataset; ViewName: TcxListView); function BoolToStr(value: boolean; boolType: string): string; function FormatColumnName(ColumnName: string): string; implementation var dbgCounter: Integer = 0; function FormatColumnName(ColumnName: string): string; var str: string; i: integer; begin result := ColumnName; while Pos('_', result) > 0 do result[Pos('_', result)] := ' '; str := AnsiUpperCase(result[1]); i := 1; repeat i:=i+1; if (result[i-1] = ' ') then str := str + AnsiUpperCase(result[i]) else str := str + AnsiLowerCase(result[i]); until length(str) = length(result); result := str; end; function BoolToStr(value: boolean; boolType: string): string; begin if boolType = 'YN' then begin if value then result := 'Yes' else result := 'No'; end; if boolType = 'TF' then begin if value then result := 'True' else result := 'False'; end; end; procedure FillViewHorizontal(Source: TDataset; ViewName: TcxListView); var i: integer; begin ViewName.Items.Clear; Source.First; while not Source.Eof do begin with ViewName.Items.Add do begin Caption := Source.Fields[0].Text; ImageIndex := -1; end; for i := 1 to Source.FieldCount -1 do ViewName.Items[ViewName.Items.count-1].SubItems.Add(Source.Fields[i].Text); Source.Next; end; end; procedure CopyDataSet(Source: TDataSet; Target: TVirtualTable); var i: integer; begin if not Source.Active then exit; Target.close; Target.FieldDefs.Clear; Source.First; for i := 0 to Source.FieldCount - 1 do begin if not (Source.Fields[i].DataType in [ftVarBytes, ftTypedBinary, ftGraphic,ftOraBlob,ftOraClob]) then Target.AddField(Source.Fields[i].FieldName, Source.Fields[i].DataType, Source.Fields[i].Size); end; Target.open; while not Source.Eof do begin Target.Append; for i := 0 to Target.FieldCount - 1 do begin if Target.Fields[i].DataType in [ftString, ftMemo] then Target.Fields[i].AsString := Source.FieldByName(Target.Fields[i].FieldName).AsString else Target.Fields[i].AsVariant := Source.FieldByName(Target.Fields[i].FieldName).AsVariant; end; Target.Post; Source.Next; end; Source.First; end; //CopyDataSet procedure DuplicateCurrentRecord(aDataSet : TDataSet); var Data : array of variant; aRecord : array of TVarRec; i : integer; max : integer; begin max := aDataSet.fields.count -1; // set the lenghth of the arecord array to be the same as the number of // elements in the data array SetLength(arecord,max+1); SetLength(data,max+1); // set the variant type pointers to the data array for i := 0 to max do begin arecord[i].VType := vtVariant; arecord[i].VVariant := @data[i]; end; // Copy the Record to the Array for i := 0 to max do Data[i] := aDataSet.fields[i].value; // finally append the record in one go //aDataSet.AppendRecord(aRecord); aDataSet.InsertRecord(aRecord); end; function GetInsertData(TableName: string; QTable: TOraQuery): string; var i: integer; ins,val: string; FieldData: string; begin with QTable do begin result := 'INSERT INTO '+TableName+ln; for i := 0 to FieldCount -1 do begin if UPPERCASE(Fields[i].FieldName) = 'ROWID' then continue; ins := ins + Fields[i].FieldName; FieldData := ''; if Fields[i].Value = Null then FieldData := 'NULL' else case Fields[i].DataType of ftString, ftWideString: begin FieldData := Fields[i].AsString; FieldData := StringReplace(FieldData,'''','´',[rfReplaceAll]); FieldData := Str(FieldData); end; ftSmallint, ftInteger : FieldData := Fields[i].AsString; ftFloat,ftCurrency: FieldData := Fields[i].AsString; //Trim(Format('%8f', [Fields[i].AsFloat])); ftDate : FieldData := 'to_date('+Str(Fields[i].AsString)+', ''dd.mm.yyyy'')'; ftTime : FieldData := FormatDateTime('hh:mm', Fields[i].AsDateTime); ftDateTime,ftTimeStamp : FieldData := 'to_date('+str(Fields[i].AsString)+', ''dd.mm.yyyy HH:MI:SS AM'')'; ftLargeint : FieldData := Fields[i].AsString; ftMemo,ftBlob, ftTypedBinary, ftGraphic,ftOraBlob,ftOraClob : FieldData := 'NULL'; else FieldData := 'NULL'; end; //case val := val + FieldData; if i <> FieldCount -1 then begin ins := ins + ', '; val := val + ', '; end; end; //for end; //QTable with result := result +' ( '+ins+ ' ) '+ln +'VALUES '+ln +' ( '+val+ ' ); '+ln; end; function GetInsertSQLWithData(TableName: string; QTable: TOraQuery; SelectedList: TStringList): string; var i: integer; begin result := ''; for i := 0 to SelectedList.Count -1 do begin QTable.Locate(QTable.Fields[0].FieldName, SelectedList[i], []); result := result + GetInsertData(TableName, QTable); end; end; //GetInsertSQL function GetInsertSQL(TableName: string; FieldList: TFieldDefs): string; var i: integer; ins,val: string; ADataType: TFieldType; begin result := 'INSERT INTO '+TableName+ln; for i := 0 to FieldList.Count -1 do begin if UPPERCASE(FieldList[i].Name) = 'ROWID' then continue; ins := ins + FieldList[i].Name; ADataType := TFieldType(FieldList[i].DataType); if (ADataType = ftOraBlob) then val := val + ' empty_blob() ' else if (ADataType = ftOraClob) then val := val + ' empty_clob() ' else val := val + ':'+FieldList[i].Name; if i <> FieldList.Count -1 then begin ins := ins + ', '; val := val + ', '; end; end; result := result +' ( '+ins+ ' ) '+ln +'VALUES '+ln +' ( '+val+ ' ) '; end; //GetInsertSQL function GetUpdateSQL(TableName: string; FieldList: TFieldDefs): string; var i: integer; up: string; ADataType: TFieldType; begin result := 'UPDATE '+TableName+ln +'SET '+ln; for i := 0 to FieldList.Count -1 do begin if UPPERCASE(FieldList[i].Name) = 'ROWID' then continue; ADataType := TFieldType(FieldList[i].DataType); if (ADataType = ftOraBlob) then up := up + FieldList[i].Name + ' empty_blob() ' else if (ADataType = ftOraClob) then up := up + FieldList[i].Name + ' empty_clob() ' else up := up + FieldList[i].Name + ' = :'+FieldList[i].Name; if i <> FieldList.Count -1 then up := up + ', '; end; result := result + up + ln +' WHERE ROWID = :OLD_ROWID '+ln; end; //GetUpdateSQL function GetDeleteSQL(TableName: string; FieldList: TFieldDefs): string; begin result := 'DELETE '+TableName+ln +' WHERE ROWID = :OLD_ROWID '+ln; end; //GetDeleteSQL function isNVL(value, newValue: variant): variant; begin if VarIsNull(value) then result := newValue else result := value; end; function isNull(value:string): string; begin if length(value) > 0 then result := value else result := '0'; end; function isNullorZero(value,DefaultValue: string): boolean; overload; begin if (value <> '') and (value <> '0') and( value <> DefaultValue) then result := true else result := false; end; function isNullorZero(value,DefaultValue: integer): boolean; overload; begin if (value <> 0) and( value <> DefaultValue) then result := true else result := false; end; function isNullorZero(value,DefaultValue: Extended): boolean; overload; begin if (value <> 0) and( value <> DefaultValue) then result := true else result := false; end; function ln: string; begin result := #13#10; end; function Str(s: string): string; begin result := #39 + s + #39; end; function Date(d: string): string; begin result := 'to_date('+Str(d)+', ''dd.mm.yyyy'')'; end; function CompareStr(str1, str2: string): boolean; var s1,s2: string; begin s1 := str1; s2 := str2; while Pos(#$D, S1) > 0 do delete(s1, Pos(#$D, S1), 1); while Pos(#$A, S1) > 0 do delete(s1, Pos(#$A, S1), 1); while Pos(#$D, S2) > 0 do delete(s2, Pos(#$D, S2), 1); while Pos(#$A, S2) > 0 do delete(s2, Pos(#$A, S2), 1); result := s1 = s2; end; procedure debug(txt: String); begin if length(txt) = 0 then txt := '(debug: blank output?)'; // Todo: not thread safe. dbgCounter := dbgCounter + 1; txt := Format(APPNAME+': %d %s', [dbgCounter, txt]); OutputDebugString(PChar(txt)); end; function ExpectResultSet(ASql: String): Boolean; const RESULTSET_KEYWORDS : array[0..9] of string[10] = ( //'ANALYZE', 'CALL', 'CHECK', 'DESC', 'DESCRIBE', 'EXECUTE', 'HELP', 'OPTIMIZE', 'REPAIR', 'SELECT', 'SHOW' ); NOTRESULTSET_SENTENCE : string[12] = 'INTO OUTFILE'; var kw : String; i : Integer; begin Result := False; // Find keyword and check existance in const-array of resultset-keywords kw := UpperCase( getFirstWord( ASql ) ); for i := Low(RESULTSET_KEYWORDS) to High(RESULTSET_KEYWORDS) do begin if kw = RESULTSET_KEYWORDS[i] then begin Result := True; break; end; end; if Pos(NOTRESULTSET_SENTENCE, UpperCase(ASql)) > 0 then Result := False; end; function ExpectScriptSet(ASql: String): Boolean; const RESULTSET_KEYWORDS : array[0..3] of string[10] = ( 'DROP', 'ALTER', 'CREATE', 'GRANT' ); NOTRESULTSET_SENTENCE : string[12] = 'INTO OUTFILE'; var kw : String; i : Integer; begin Result := False; kw := UpperCase( getFirstWord( ASql ) ); for i := Low(RESULTSET_KEYWORDS) to High(RESULTSET_KEYWORDS) do begin if kw = RESULTSET_KEYWORDS[i] then begin Result := True; break; end; end; if Pos(NOTRESULTSET_SENTENCE, UpperCase(ASql)) > 0 then Result := False; end; {*** Returns first word of a given text @param string Given text @return string First word-boundary } function getFirstWord( text: String ): String; var i : Integer; wordChars : Set of Char; begin result := ''; text := trim( text ); wordChars := ['a'..'z', 'A'..'Z', '0'..'9', '_', '-']; i := 1; // Find beginning of the first word, ignoring non-alphanumeric chars at the very start // @see bug #1692828 while i < Length(text) do begin if (text[i] in wordChars) then begin // Found beginning of word! break; end; if i = Length(text)-1 then begin // Give up in the very last loop, reset counter // and break. We can't find the start of a word i := 1; break; end; inc(i); end; // Add chars as long as they're alpha-numeric while i < Length(text) do begin if (text[i] in wordChars) then begin result := result + text[i]; end else begin // Stop here because we found a non-alphanumeric char. // This applies to all different whitespaces, brackets, commas etc. break; end; inc(i); end; end; function GetColumnValue(OraFieldName, Value: string): string; begin if Value = 'NULL' then begin result := 'NULL'; exit; end; if OraFieldName = 'BFILE' then result :='NULL'; if OraFieldName = 'BINARY_DOUBLE'then result :='NULL'; if OraFieldName = 'BINARY_FLOAT' then result :='NULL'; if OraFieldName = 'BLOB' then result :='NULL'; if OraFieldName = 'CHAR' then result :=str(Value); if OraFieldName = 'CLOB' then result :='NULL'; if OraFieldName = 'DATE' then result :=Date(Value); if OraFieldName = 'FLOAT' then result :=Value; if OraFieldName = 'LONG' then result :=Value; if OraFieldName = 'LONG RAW' then result :='NULL'; if OraFieldName = 'MLSLABEL' then result :='NULL'; if OraFieldName = 'NCHAR' then result :=str(Value); if OraFieldName = 'NCLOB' then result :='NULL'; if OraFieldName = 'NUMBER' then result :=value; if OraFieldName = 'NVARCHAR2' then result :=str(Value); if OraFieldName = 'RAW' then result :='NULL'; if OraFieldName = 'ROWID' then result :='NULL'; if OraFieldName = 'URITYPE' then result :='NULL'; if OraFieldName = 'UROWID' then result :='NULL'; if OraFieldName = 'VARCHAR2' then result :=str(Value); if OraFieldName = 'CHAR VARYING' then result :=value; if OraFieldName = 'CHARACTER' then result :=str(Value); if OraFieldName = 'CHARACTER VARYING' then result :=value; if OraFieldName = 'DECIMAL' then result :=value; if OraFieldName = 'DOUBLE PRECISION' then result :=value; if OraFieldName = 'INT' then result :=value; if OraFieldName = 'INTEGER' then result :=value; if OraFieldName = 'NATIONAL CHAR' then result :=value; if OraFieldName = 'NATIONAL CHAR VARYING' then result :=value; if OraFieldName = 'NATIONAL CHARACTER' then result :=value; if OraFieldName = 'NATIONAL CHARACTER VARYING'then result :=value; if OraFieldName = 'NCHAR VARYING'then result :=value; if OraFieldName = 'NUMERIC' then result :=value; if OraFieldName = 'REAL' then result :=value; if OraFieldName = 'SMALLINT' then result :=value; if OraFieldName = 'VARCHAR' then result :=str(value); end; function GetColumnType(OraFieldName: string): string; begin if OraFieldName = 'BFILE' then result :='0000'; if OraFieldName = 'BINARY_DOUBLE'then result :='0000'; if OraFieldName = 'BINARY_FLOAT' then result :='0000'; if OraFieldName = 'BLOB' then result :='0000'; if OraFieldName = 'CHAR' then result :='1001'; if OraFieldName = 'CLOB' then result :='0000'; if OraFieldName = 'DATE' then result :='0000'; if OraFieldName = 'FLOAT' then result :='1000'; if OraFieldName = 'LONG' then result :='0000'; if OraFieldName = 'LONG RAW' then result :='0000'; if OraFieldName = 'MLSLABEL' then result :='0000'; if OraFieldName = 'NCHAR' then result :='1000'; if OraFieldName = 'NCLOB' then result :='0000'; if OraFieldName = 'NUMBER' then result :='0110'; if OraFieldName = 'NVARCHAR2' then result :='1000'; if OraFieldName = 'RAW' then result :='1000'; if OraFieldName = 'ROWID' then result :='0000'; if OraFieldName = 'URITYPE' then result :='0000'; if OraFieldName = 'UROWID' then result :='1000'; if OraFieldName = 'VARCHAR2' then result :='1001'; if OraFieldName = 'CHAR VARYING' then result :='1000'; if OraFieldName = 'CHARACTER' then result :='1000'; if OraFieldName = 'CHARACTER VARYING' then result :='1000'; if OraFieldName = 'DECIMAL' then result :='0110'; if OraFieldName = 'DOUBLE PRECISION' then result :='0000'; if OraFieldName = 'INT' then result :='0000'; if OraFieldName = 'INTEGER' then result :='0000'; if OraFieldName = 'NATIONAL CHAR' then result :='1000'; if OraFieldName = 'NATIONAL CHAR VARYING' then result :='1000'; if OraFieldName = 'NATIONAL CHARACTER' then result :='1000'; if OraFieldName = 'NATIONAL CHARACTER VARYING'then result :='1000'; if OraFieldName = 'NCHAR VARYING'then result :='1000'; if OraFieldName = 'NUMERIC' then result :='0110'; if OraFieldName = 'REAL' then result :='0000'; if OraFieldName = 'SMALLINT' then result :='0000'; if OraFieldName = 'VARCHAR' then result :='1000'; end; procedure DrawGradient(Canvas: TCanvas; const ARect: TRect; FromColor, ToColor: TColor; AStepCount: Integer; IsVertical: Boolean = False); var SR: TRect; H, I: Integer; R, G, B: Byte; FromR, ToR, FromG, ToG, FromB, ToB: Byte; begin FromR := GetRValue(FromColor); FromG := GetGValue(FromColor); FromB := GetBValue(FromColor); ToR := GetRValue(ToColor); ToG := GetGValue(ToColor); ToB := GetBValue(ToColor); SR := ARect; with ARect do if IsVertical then H := Bottom - Top else H := Right - Left; for I := 0 to AStepCount - 1 do begin if IsVertical then SR.Bottom := ARect.Top + MulDiv(I + 1, H, AStepCount) else SR.Right := ARect.Left + MulDiv(I + 1, H, AStepCount); with Canvas do begin R := FromR + MulDiv(I, ToR - FromR, AStepCount - 1); G := FromG + MulDiv(I, ToG - FromG, AStepCount - 1); B := FromB + MulDiv(I, ToB - FromB, AStepCount - 1); Brush.Color := RGB(R, G, B); FillRect(SR); end; if IsVertical then SR.Top := SR.Bottom else SR.Left := SR.Right; end; end; procedure CodeColors(Form : TForm; Style : String; RichE : TcxRichedit; InVisible : Boolean); const // ??... CodeC1: array[0..20] of String = ('#','$','(',')','*',',', '.','/',':',';','[',']','{','}','<','>', '-','=','+','''','@'); CodeC3: array[0..28] of String = ( 'BFILE','BINARY_DOUBLE','BINARY_FLOAT','BLOB', 'CHAR','CLOB','DATE','FLOAT', 'LONG','LONG RAW','MLSLABEL','NCHAR','NCLOB','NUMBER','NVARCHAR2','RAW','ROWID', 'URITYPE','UROWID','VARCHAR2','CHAR VARYING','CHARACTER','DECIMAL','INT', 'INTEGER','NUMERIC','REAL','SMALLINT','VARCHAR'); // ???... CodeC2: array[0..68] of String = ('bitmap','partition','local', 'nologging','noparallel','referances','novalidate','sysnonym', 'monitoring','end','range','hash','subpartition', 'forward','function','by','implementation','interface', 'is','nil','or','private','byte','using','to', 'key','grant','unique','foreign','check','grant','alter','constraint', 'primary','null','not','column','on','comment','tablespace', 'index','table','create','from','select', 'modify','default', 'disable', 'row', 'movement', 'nocache', 'nomonitoring', 'values', 'less', 'than', 'add', 'disabled','logging', 'view','as','replace', 'with', 'read', 'only','begin','exception','declare','procedure','function' ); var FoundAt : LongInt; StartPos, ToEnd, i : integer; OldCap,T : String; FontC, BackC, C1, C2 ,C3 ,strC, strC1 : TColor; begin OldCap := Form.Caption; with RichE, RichE.Style, RichE.Properties do begin Font.Name := 'Courier New'; Font.Size := 10; if WordWrap then WordWrap := false; SelectAll; SelAttributes.color := clBlack; SelAttributes.Style := []; SelStart := 0; if InVisible then begin Visible := False; Form.Caption := 'Executing Code Coloring...'; end; end; BackC := clWhite; FontC := clBlack; C1 := clBlack; C2 := clBlack; C3 := clBlack; strC := clBlue; strC1 := clGray; if Style = 'Twilight' then begin BackC := clBlack; FontC := clWhite; C1 := clLime; C2 := clSilver; C3 := clAqua; strC := clYellow; strC1 := clRed; end else if Style = 'Default' then begin BackC := clWhite; FontC := clBlack; C1 := clTeal; C2 := clBlue; C3 := clBlue; strC := clMaroon; strC1 := clSilver; end else if Style = 'Ocean' then begin BackC := $00FFFF80; FontC := clBlack; C1 := clMaroon; C2 := clBlack; C3 := clBlue; strC := clTeal; strC1 := clBlack; end else if Style = 'Classic' then begin BackC := clNavy; FontC := clYellow; C1 := clLime; C2 := clSilver; C3 := clWhite; strC := clAqua; strC1 := clSilver; end else begin with RichE do begin T := '{'+'Style'+' = Invalid Style [Default,Classic,Twilight,Ocean] ONLY! }'; Lines.Insert(0,T); StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText(T, StartPos, ToEnd, [stWholeWord]); SelStart := FoundAt; SelLength := Length(T); SelAttributes.Color := clRed; SelAttributes.Style := [fsBold]; StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText('ONLY!', StartPos, ToEnd, [stWholeWord]); SelStart := FoundAt; SelLength := 4; SelAttributes.Color := clRed; SelAttributes.Style := [fsBold,fsUnderLine]; end; end; //RichE.SelectAll; //RichE.Style.color := BackC; //RichE.SelAttributes.color := FontC; for i := 0 to 100 do begin with RichE do begin StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText(IntToStr(i), StartPos, ToEnd, [stWholeWord]); while (FoundAt <> -1) do begin SelStart := FoundAt; SelLength := Length(IntToStr(i)); SelAttributes.Color := C1; SelAttributes.Style := []; StartPos := FoundAt + Length(IntToStr(i)); FoundAt := FindText(IntToStr(i), StartPos, ToEnd, [stWholeWord]); end; end; end; for i := 0 to High(CodeC1) do begin with RichE do begin StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText(CodeC1[i], StartPos, ToEnd, []); while (FoundAt <> -1) do begin SelStart := FoundAt; SelLength := Length(CodeC1[i]); SelAttributes.Color := C2; StartPos := FoundAt + Length(CodeC1[i]); FoundAt := FindText(CodeC1[i], StartPos, ToEnd, []); end; end; end; for i := 0 to High(CodeC2) do begin with RichE do begin StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText(CodeC2[i], StartPos, ToEnd, [stWholeWord]); while (FoundAt <> -1) do begin SelStart := FoundAt; SelLength := Length(CodeC2[i]); SelAttributes.Color := C3; SelAttributes.Style := []; StartPos := FoundAt + Length(CodeC2[i]); FoundAt := FindText(CodeC2[i], StartPos, ToEnd, [stWholeWord]); end; end; end; for i := 0 to High(CodeC3) do begin with RichE do begin StartPos := 0; ToEnd := Length(Text) - StartPos; FoundAt := FindText(CodeC3[i], StartPos, ToEnd, [stWholeWord]); while (FoundAt <> -1) do begin SelStart := FoundAt; SelLength := Length(CodeC3[i]); SelAttributes.Color := clRed; StartPos := FoundAt + Length(CodeC3[i]); FoundAt := FindText(CodeC3[i], StartPos, ToEnd, [stWholeWord]); end; end; end; Startpos := 0; with RichE do begin FoundAt := FindText('''', StartPos, Length(Text), []); while FoundAt <> -1 do begin SelStart := FoundAt; Startpos := FoundAt+1; FoundAt := FindText('''', StartPos, Length(Text), []); if FoundAt <> -1 then begin SelLength := (FoundAt - selstart)+1; SelAttributes.Style := []; SelAttributes.Color := strC; StartPos := FoundAt+1; FoundAt := FindText('''', StartPos, Length(Text), []); end; end; end; Startpos := 0; with RichE do begin FoundAt := FindText('"', StartPos, Length(Text), []); while FoundAt <> -1 do begin SelStart := FoundAt; Startpos := FoundAt+1; FoundAt := FindText('"', StartPos, Length(Text), []); if FoundAt <> -1 then begin SelLength := (FoundAt - selstart)+1; SelAttributes.Style := []; SelAttributes.Color := strC; StartPos := FoundAt+1; FoundAt := FindText('"', StartPos, Length(Text), []); end; end; end; Startpos := 0; with RichE do begin FoundAt := FindText('{', StartPos, Length(Text), []); while FoundAt <> -1 do begin SelStart := FoundAt; Startpos := FoundAt+1; FoundAt := FindText('}', StartPos, Length(Text), [])+1; if FoundAt <> -1 then begin SelLength := (FoundAt - selstart)+1; SelAttributes.Style := [fsItalic]; SelAttributes.Color := clGreen; StartPos := FoundAt+1; FoundAt := FindText('{', StartPos, Length(Text), []); end; end; end; if InVisible then begin RichE.Visible := True; Form.Caption := OldCap; end; RichE.SelStart := 0; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpIBerApplicationSpecific; {$I ..\Include\CryptoLib.inc} interface uses ClpIDerApplicationSpecific; type IBerApplicationSpecific = interface(IDerApplicationSpecific) ['{C7414497-904B-4CE8-8B5F-E252739F5B5C}'] end; implementation end.
unit INFOXENTITYTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TINFOXENTITYRecord = record PEntId: String[8]; PModCount: String[1]; PName: String[30]; PAddr1: String[30]; PAddr2: String[30]; PAddr3: String[30]; PCitySt: String[25]; Pzip: String[10]; PContact: String[30]; PPhone: String[30]; PCommstat: String[1]; PCommpct: Currency; PAcctId: String[4]; PExpDate: String[10]; PCkHold: String[1]; End; TINFOXENTITYBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TINFOXENTITYRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIINFOXENTITY = (INFOXENTITYPrimaryKey, INFOXENTITYEnt, INFOXENTITYEntName); TINFOXENTITYTable = class( TDBISAMTableAU ) private FDFEntId: TStringField; FDFModCount: TStringField; FDFName: TStringField; FDFAddr1: TStringField; FDFAddr2: TStringField; FDFAddr3: TStringField; FDFCitySt: TStringField; FDFzip: TStringField; FDFContact: TStringField; FDFPhone: TStringField; FDFCommstat: TStringField; FDFCommpct: TCurrencyField; FDFAcctId: TStringField; FDFExpDate: TStringField; FDFCkHold: TStringField; procedure SetPEntId(const Value: String); function GetPEntId:String; procedure SetPModCount(const Value: String); function GetPModCount:String; procedure SetPName(const Value: String); function GetPName:String; procedure SetPAddr1(const Value: String); function GetPAddr1:String; procedure SetPAddr2(const Value: String); function GetPAddr2:String; procedure SetPAddr3(const Value: String); function GetPAddr3:String; procedure SetPCitySt(const Value: String); function GetPCitySt:String; procedure SetPzip(const Value: String); function GetPzip:String; procedure SetPContact(const Value: String); function GetPContact:String; procedure SetPPhone(const Value: String); function GetPPhone:String; procedure SetPCommstat(const Value: String); function GetPCommstat:String; procedure SetPCommpct(const Value: Currency); function GetPCommpct:Currency; procedure SetPAcctId(const Value: String); function GetPAcctId:String; procedure SetPExpDate(const Value: String); function GetPExpDate:String; procedure SetPCkHold(const Value: String); function GetPCkHold:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIINFOXENTITY); function GetEnumIndex: TEIINFOXENTITY; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TINFOXENTITYRecord; procedure StoreDataBuffer(ABuffer:TINFOXENTITYRecord); property DFEntId: TStringField read FDFEntId; property DFModCount: TStringField read FDFModCount; property DFName: TStringField read FDFName; property DFAddr1: TStringField read FDFAddr1; property DFAddr2: TStringField read FDFAddr2; property DFAddr3: TStringField read FDFAddr3; property DFCitySt: TStringField read FDFCitySt; property DFzip: TStringField read FDFzip; property DFContact: TStringField read FDFContact; property DFPhone: TStringField read FDFPhone; property DFCommstat: TStringField read FDFCommstat; property DFCommpct: TCurrencyField read FDFCommpct; property DFAcctId: TStringField read FDFAcctId; property DFExpDate: TStringField read FDFExpDate; property DFCkHold: TStringField read FDFCkHold; property PEntId: String read GetPEntId write SetPEntId; property PModCount: String read GetPModCount write SetPModCount; property PName: String read GetPName write SetPName; property PAddr1: String read GetPAddr1 write SetPAddr1; property PAddr2: String read GetPAddr2 write SetPAddr2; property PAddr3: String read GetPAddr3 write SetPAddr3; property PCitySt: String read GetPCitySt write SetPCitySt; property Pzip: String read GetPzip write SetPzip; property PContact: String read GetPContact write SetPContact; property PPhone: String read GetPPhone write SetPPhone; property PCommstat: String read GetPCommstat write SetPCommstat; property PCommpct: Currency read GetPCommpct write SetPCommpct; property PAcctId: String read GetPAcctId write SetPAcctId; property PExpDate: String read GetPExpDate write SetPExpDate; property PCkHold: String read GetPCkHold write SetPCkHold; published property Active write SetActive; property EnumIndex: TEIINFOXENTITY read GetEnumIndex write SetEnumIndex; end; { TINFOXENTITYTable } procedure Register; implementation function TINFOXENTITYTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TINFOXENTITYTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TINFOXENTITYTable.GenerateNewFieldName } function TINFOXENTITYTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TINFOXENTITYTable.CreateField } procedure TINFOXENTITYTable.CreateFields; begin FDFEntId := CreateField( 'EntId' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TStringField; FDFName := CreateField( 'Name' ) as TStringField; FDFAddr1 := CreateField( 'Addr1' ) as TStringField; FDFAddr2 := CreateField( 'Addr2' ) as TStringField; FDFAddr3 := CreateField( 'Addr3' ) as TStringField; FDFCitySt := CreateField( 'CitySt' ) as TStringField; FDFzip := CreateField( 'zip' ) as TStringField; FDFContact := CreateField( 'Contact' ) as TStringField; FDFPhone := CreateField( 'Phone' ) as TStringField; FDFCommstat := CreateField( 'Commstat' ) as TStringField; FDFCommpct := CreateField( 'Commpct' ) as TCurrencyField; FDFAcctId := CreateField( 'AcctId' ) as TStringField; FDFExpDate := CreateField( 'ExpDate' ) as TStringField; FDFCkHold := CreateField( 'CkHold' ) as TStringField; end; { TINFOXENTITYTable.CreateFields } procedure TINFOXENTITYTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TINFOXENTITYTable.SetActive } procedure TINFOXENTITYTable.SetPEntId(const Value: String); begin DFEntId.Value := Value; end; function TINFOXENTITYTable.GetPEntId:String; begin result := DFEntId.Value; end; procedure TINFOXENTITYTable.SetPModCount(const Value: String); begin DFModCount.Value := Value; end; function TINFOXENTITYTable.GetPModCount:String; begin result := DFModCount.Value; end; procedure TINFOXENTITYTable.SetPName(const Value: String); begin DFName.Value := Value; end; function TINFOXENTITYTable.GetPName:String; begin result := DFName.Value; end; procedure TINFOXENTITYTable.SetPAddr1(const Value: String); begin DFAddr1.Value := Value; end; function TINFOXENTITYTable.GetPAddr1:String; begin result := DFAddr1.Value; end; procedure TINFOXENTITYTable.SetPAddr2(const Value: String); begin DFAddr2.Value := Value; end; function TINFOXENTITYTable.GetPAddr2:String; begin result := DFAddr2.Value; end; procedure TINFOXENTITYTable.SetPAddr3(const Value: String); begin DFAddr3.Value := Value; end; function TINFOXENTITYTable.GetPAddr3:String; begin result := DFAddr3.Value; end; procedure TINFOXENTITYTable.SetPCitySt(const Value: String); begin DFCitySt.Value := Value; end; function TINFOXENTITYTable.GetPCitySt:String; begin result := DFCitySt.Value; end; procedure TINFOXENTITYTable.SetPzip(const Value: String); begin DFzip.Value := Value; end; function TINFOXENTITYTable.GetPzip:String; begin result := DFzip.Value; end; procedure TINFOXENTITYTable.SetPContact(const Value: String); begin DFContact.Value := Value; end; function TINFOXENTITYTable.GetPContact:String; begin result := DFContact.Value; end; procedure TINFOXENTITYTable.SetPPhone(const Value: String); begin DFPhone.Value := Value; end; function TINFOXENTITYTable.GetPPhone:String; begin result := DFPhone.Value; end; procedure TINFOXENTITYTable.SetPCommstat(const Value: String); begin DFCommstat.Value := Value; end; function TINFOXENTITYTable.GetPCommstat:String; begin result := DFCommstat.Value; end; procedure TINFOXENTITYTable.SetPCommpct(const Value: Currency); begin DFCommpct.Value := Value; end; function TINFOXENTITYTable.GetPCommpct:Currency; begin result := DFCommpct.Value; end; procedure TINFOXENTITYTable.SetPAcctId(const Value: String); begin DFAcctId.Value := Value; end; function TINFOXENTITYTable.GetPAcctId:String; begin result := DFAcctId.Value; end; procedure TINFOXENTITYTable.SetPExpDate(const Value: String); begin DFExpDate.Value := Value; end; function TINFOXENTITYTable.GetPExpDate:String; begin result := DFExpDate.Value; end; procedure TINFOXENTITYTable.SetPCkHold(const Value: String); begin DFCkHold.Value := Value; end; function TINFOXENTITYTable.GetPCkHold:String; begin result := DFCkHold.Value; end; procedure TINFOXENTITYTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('EntId, String, 8, N'); Add('ModCount, String, 1, N'); Add('Name, String, 30, N'); Add('Addr1, String, 30, N'); Add('Addr2, String, 30, N'); Add('Addr3, String, 30, N'); Add('CitySt, String, 25, N'); Add('zip, String, 10, N'); Add('Contact, String, 30, N'); Add('Phone, String, 30, N'); Add('Commstat, String, 1, N'); Add('Commpct, Currency, 0, N'); Add('AcctId, String, 4, N'); Add('ExpDate, String, 10, N'); Add('CkHold, String, 1, N'); end; end; procedure TINFOXENTITYTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, EntId, Y, Y, N, N'); Add('Ent, EntId, N, Y, N, Y'); Add('EntName, Name, N, Y, N, N'); end; end; procedure TINFOXENTITYTable.SetEnumIndex(Value: TEIINFOXENTITY); begin case Value of INFOXENTITYPrimaryKey : IndexName := ''; INFOXENTITYEnt : IndexName := 'Ent'; INFOXENTITYEntName : IndexName := 'EntName'; end; end; function TINFOXENTITYTable.GetDataBuffer:TINFOXENTITYRecord; var buf: TINFOXENTITYRecord; begin fillchar(buf, sizeof(buf), 0); buf.PEntId := DFEntId.Value; buf.PModCount := DFModCount.Value; buf.PName := DFName.Value; buf.PAddr1 := DFAddr1.Value; buf.PAddr2 := DFAddr2.Value; buf.PAddr3 := DFAddr3.Value; buf.PCitySt := DFCitySt.Value; buf.Pzip := DFzip.Value; buf.PContact := DFContact.Value; buf.PPhone := DFPhone.Value; buf.PCommstat := DFCommstat.Value; buf.PCommpct := DFCommpct.Value; buf.PAcctId := DFAcctId.Value; buf.PExpDate := DFExpDate.Value; buf.PCkHold := DFCkHold.Value; result := buf; end; procedure TINFOXENTITYTable.StoreDataBuffer(ABuffer:TINFOXENTITYRecord); begin DFEntId.Value := ABuffer.PEntId; DFModCount.Value := ABuffer.PModCount; DFName.Value := ABuffer.PName; DFAddr1.Value := ABuffer.PAddr1; DFAddr2.Value := ABuffer.PAddr2; DFAddr3.Value := ABuffer.PAddr3; DFCitySt.Value := ABuffer.PCitySt; DFzip.Value := ABuffer.Pzip; DFContact.Value := ABuffer.PContact; DFPhone.Value := ABuffer.PPhone; DFCommstat.Value := ABuffer.PCommstat; DFCommpct.Value := ABuffer.PCommpct; DFAcctId.Value := ABuffer.PAcctId; DFExpDate.Value := ABuffer.PExpDate; DFCkHold.Value := ABuffer.PCkHold; end; function TINFOXENTITYTable.GetEnumIndex: TEIINFOXENTITY; var iname : string; begin result := INFOXENTITYPrimaryKey; iname := uppercase(indexname); if iname = '' then result := INFOXENTITYPrimaryKey; if iname = 'ENT' then result := INFOXENTITYEnt; if iname = 'ENTNAME' then result := INFOXENTITYEntName; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TINFOXENTITYTable, TINFOXENTITYBuffer ] ); end; { Register } function TINFOXENTITYBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..15] of string = ('ENTID','MODCOUNT','NAME','ADDR1','ADDR2','ADDR3' ,'CITYST','ZIP','CONTACT','PHONE','COMMSTAT' ,'COMMPCT','ACCTID','EXPDATE','CKHOLD' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 15) and (flist[x] <> s) do inc(x); if x <= 15 then result := x else result := 0; end; function TINFOXENTITYBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftCurrency; 13 : result := ftString; 14 : result := ftString; 15 : result := ftString; end; end; function TINFOXENTITYBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PEntId; 2 : result := @Data.PModCount; 3 : result := @Data.PName; 4 : result := @Data.PAddr1; 5 : result := @Data.PAddr2; 6 : result := @Data.PAddr3; 7 : result := @Data.PCitySt; 8 : result := @Data.Pzip; 9 : result := @Data.PContact; 10 : result := @Data.PPhone; 11 : result := @Data.PCommstat; 12 : result := @Data.PCommpct; 13 : result := @Data.PAcctId; 14 : result := @Data.PExpDate; 15 : result := @Data.PCkHold; end; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StRandom.pas 4.04 *} {*********************************************************} {* SysTools: Classes for random number distributions *} {*********************************************************} {$I StDefine.inc} unit StRandom; interface uses Windows, SysUtils, Classes, StBase; type TStRandomBase = class private protected function rbMarsagliaGamma(aShape : double) : double; function rbMontyPythonNormal : double; public {uniform distributions} function AsFloat : double; virtual; abstract; function AsInt(aUpperLimit : integer) : integer; function AsIntInRange(aLowerLimit : integer; aUpperLimit : integer) : integer; {continuous non-uniform distributions} function AsBeta(aShape1, aShape2 : double) : double; function AsCauchy : double; function AsChiSquared(aFreedom : integer) : double; function AsErlang(aMean : double; aOrder : integer) : double; function AsExponential(aMean : double) : double; function AsF(aFreedom1 : integer; aFreedom2 : integer) : double; function AsGamma(aShape : double; aScale : double) : double; function AsLogNormal(aMean : double; aStdDev : double) : double; function AsNormal(aMean : double; aStdDev : double) : double; function AsT(aFreedom : integer) : double; function AsWeibull(aShape : double; aScale : double) : double; end; TStRandomSystem = class(TStRandomBase) private FSeed : integer; protected procedure rsSetSeed(aValue : integer); public constructor Create(aSeed : integer); function AsFloat : double; override; property Seed : integer read FSeed write rsSetSeed; end; TStRandomCombined = class(TStRandomBase) private FSeed1 : integer; FSeed2 : integer; protected procedure rcSetSeed1(aValue : integer); procedure rcSetSeed2(aValue : integer); public constructor Create(aSeed1, aSeed2 : integer); function AsFloat : double; override; property Seed1 : integer read FSeed1 write rcSetSeed1; property Seed2 : integer read FSeed2 write rcSetSeed2; end; {$IFDEF WIN32} TStRandomMother = class(TStRandomBase) private FNminus4 : integer; FNminus3 : integer; FNminus2 : integer; FNminus1 : integer; FC : integer; protected procedure rsSetSeed(aValue : integer); public constructor Create(aSeed : integer); function AsFloat : double; override; property Seed : integer write rsSetSeed; end; {$ENDIF} implementation uses StConst; var Root2Pi : double; InvRoot2Pi : double; RootLn4 : double; Ln2 : double; MPN_s : double; Ln2MPN_s : double; MPN_sPlus1 : double; Mum1 : integer; Mum2 : integer; Mum3 : integer; Mum4 : integer; {===Helper routines==================================================} function GetRandomSeed : integer; var Hash : integer; SystemTime: TSystemTime; G : integer; begin {start with the tick count} Hash := integer(GetTickCount); {get the current time} GetLocalTime(SystemTime); {hash in the milliseconds} Hash := (Hash shl 4) + SystemTime.wMilliseconds; G := Hash and Integer($F0000000); if (G <> 0) then Hash := (Hash xor (G shr 24)) xor G; {hash in the second} Hash := (Hash shl 4) + SystemTime.wSecond; G := Hash and Integer($F0000000); if (G <> 0) then Hash := (Hash xor (G shr 24)) xor G; {hash in the minute} Hash := (Hash shl 4) + SystemTime.wMinute; G := Hash and Integer($F0000000); if (G <> 0) then Hash := (Hash xor (G shr 24)) xor G; {hash in the hour} Hash := (Hash shl 3) + SystemTime.wHour; G := Hash and Integer($F0000000); if (G <> 0) then Hash := (Hash xor (G shr 24)) xor G; {return the hash} Result := Hash; end; {====================================================================} {===TStRandomBase====================================================} function TStRandomBase.AsBeta(aShape1, aShape2 : double) : double; var R1, R2 : double; begin if not ((aShape1 > 0.0) and (aShape2 > 0.0)) then raise EStPRNGError.Create(stscPRNGBetaShapeS); if (aShape2 = 1.0) then begin repeat R1 := AsFloat; until R1 <> 0.0; Result := exp(ln(R1) / aShape1); end else if (aShape1 = 1.0) then begin repeat R1 := AsFloat; until R1 <> 0.0; Result := 1.0 - exp(ln(R1) / aShape1); end else begin R1 := AsGamma(aShape1, 1.0); R2 := AsGamma(aShape2, 1.0); Result := R1 / (R1 + R2); end; end; {--------} function TStRandomBase.AsCauchy : double; var x : double; y : double; begin repeat repeat x := AsFloat; until (x <> 0.0); y := (AsFloat * 2.0) - 1.0; until sqr(x) + sqr(y) < 1.0; Result := y / x; end; {--------} function TStRandomBase.AsChiSquared(aFreedom : integer) : double; begin if not (aFreedom > 0) then raise EStPRNGError.Create(stscPRNGDegFreedomS); Result := AsGamma(aFreedom * 0.5, 2.0) end; {--------} function TStRandomBase.AsErlang(aMean : double; aOrder : integer) : double; var Product : double; i : integer; begin if not (aMean > 0.0) then raise EStPRNGError.Create(stscPRNGMeanS); if not (aOrder > 0) then raise EStPRNGError.Create(stscPRNGErlangOrderS); if (aOrder < 10) then begin Product := 1.0; for i := 1 to aOrder do Product := Product * AsFloat; Result := -aMean * ln(Product) / aOrder; end else begin Result := AsGamma(aOrder, aMean); end; end; {--------} function TStRandomBase.AsExponential(aMean : double) : double; var R : double; begin if not (aMean > 0.0) then raise EStPRNGError.Create(stscPRNGMeanS); repeat R := AsFloat; until (R <> 0.0); Result := -aMean * ln(R); end; {--------} function TStRandomBase.AsF(aFreedom1 : integer; aFreedom2 : integer) : double; begin Result := (AsChiSquared(aFreedom1) * aFreedom1) / (AsChiSquared(aFreedom2) * aFreedom2); end; {--------} function TStRandomBase.AsGamma(aShape : double; aScale : double) : double; var R : double; begin if not (aShape > 0.0) then raise EStPRNGError.Create(stscPRNGGammaShapeS); if not (aScale > 0.0) then raise EStPRNGError.Create(stscPRNGGammaScaleS); {there are three cases: ..0.0 < shape < 1.0, use Marsaglia's technique of Gamma(shape) = Gamma(shape+1) * uniform^(1/shape)} if (aShape < 1.0) then begin repeat R := AsFloat; until (R <> 0.0); Result := aScale * rbMarsagliaGamma(aShape + 1.0) * exp(ln(R) / aShape); end {..shape = 1.0: this is the same as exponential} else if (aShape = 1.0) then begin repeat R := AsFloat; until (R <> 0.0); Result := aScale * -ln(R); end {..shape > 1.0: use Marsaglia./Tsang algorithm} else begin Result := aScale * rbMarsagliaGamma(aShape); end; end; {--------} function TStRandomBase.AsInt(aUpperLimit : integer) : integer; begin if not (aUpperLimit > 0) then raise EStPRNGError.Create(stscPRNGLimitS); Result := Trunc(AsFloat * aUpperLimit); end; {--------} function TStRandomBase.AsIntInRange(aLowerLimit : integer; aUpperLimit : integer) : integer; begin if not (aLowerLimit < aUpperLimit) then raise EStPRNGError.Create(stscPRNGUpperLimitS); Result := Trunc(AsFloat * (aUpperLimit - aLowerLimit)) + ALowerLimit; end; {--------} function TStRandomBase.AsLogNormal(aMean : double; aStdDev : double) : double; begin Result := exp(AsNormal(aMean, aStdDev)); end; {--------} function TStRandomBase.AsNormal(aMean : double; aStdDev : double) : double; begin if not (aStdDev > 0.0) then raise EStPRNGError.Create(stscPRNGStdDevS); Result := (rbMontyPythonNormal * aStdDev) + aMean; (*** alternative: The Box-Muller transformation var R1, R2 : double; RadiusSqrd : double; begin {get two random numbers that define a point in the unit circle} repeat R1 := (2.0 * aRandGen.AsFloat) - 1.0; R2 := (2.0 * aRandGen.AsFloat) - 1.0; RadiusSqrd := sqr(R1) + sqr(R2); until (RadiusSqrd < 1.0) and (RadiusSqrd > 0.0); {apply Box-Muller transformation} Result := (R1 * sqrt(-2.0 * ln(RadiusSqrd) / RadiusSqrd) * aStdDev) + aMean; ***) end; {--------} function TStRandomBase.AsT(aFreedom : integer) : double; begin if not (aFreedom > 0) then raise EStPRNGError.Create(stscPRNGDegFreedomS); Result := rbMontyPythonNormal / sqrt(AsChiSquared(aFreedom) / aFreedom); end; {--------} function TStRandomBase.AsWeibull(aShape : double; aScale : double) : double; var R : double; begin if not (aShape > 0) then raise EStPRNGError.Create(stscPRNGWeibullShapeS); if not (aScale > 0) then raise EStPRNGError.Create(stscPRNGWeibullScaleS); repeat R := AsFloat; until (R <> 0.0); Result := exp(ln(-ln(R)) / aShape) * aScale; end; {--------} function TStRandomBase.rbMarsagliaGamma(aShape : double) : double; var d : double; c : double; x : double; v : double; u : double; Done : boolean; begin {Notes: implements the Marsaglia/Tsang method of generating random numbers belonging to the gamma distribution: Marsaglia & Tsang, "A Simple Method for Generating Gamma Variables", ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363-372 It is pointless to try and work out what's going on in this routine without reading this paper :-) } d := aShape - (1.0 / 3.0); c := 1.0 / sqrt(9.0 * d); Done := false; v := 0.0; while not Done do begin repeat x := rbMontyPythonNormal; v := 1.0 + (c * x); until (v > 0.0); v := v * v * v; u := AsFloat; Done := u < (1.0 - 0.0331 * sqr(sqr(x))); if not Done then Done := ln(u) < (0.5 * sqr(x)) + d * (1.0 - v + ln(v)) end; Result := d * v; end; {--------} function TStRandomBase.rbMontyPythonNormal : double; var x : double; y : double; v : double; NonZeroRandom : double; begin {Notes: implements the Monty Python method of generating random numbers belonging to the Normal (Gaussian) distribution: Marsaglia & Tsang, "The Monty Python Method for Generating Random Variables", ACM Transactions on Mathematical Software, Vol. 24, No. 3, September 1998, Pages 341-350 It is pointless to try and work out what's going on in this routine without reading this paper :-) Some constants: a = sqrt(ln(4)) b = sqrt(2 * pi) s = a / (b - a) } {step 1: generate a random number x between +/- sqrt(2*Pi) and return it if its absolute value is less than sqrt(ln(4)); note that this exit will happen about 47% of the time} x := ((AsFloat * 2.0) - 1.0) * Root2Pi; if (abs(x) < RootLn4) then begin Result := x; Exit; end; {step 2a: generate another random number y strictly between 0 and 1} repeat y := AsFloat; until (y <> 0.0); {step 2b: the first quadratic pretest avoids ln() calculation calculate v = 2.8658 - |x| * (2.0213 - 0.3605 * |x|) return x if y < v} v := 2.8658 - Abs(x) * (2.0213 - 0.3605 * Abs(x)); if (y < v) then begin Result := x; Exit; end; {step 2c: the second quadratic pretest again avoids ln() calculation return s * (b - x) if y > v + 0.0506} if (y > v + 0.0506) then begin if (x > 0) then Result := MPN_s * (Root2Pi - x) else Result := -MPN_s * (Root2Pi + x); Exit; end; {step 2d: return x if y < f(x) or ln(y) < ln(2) - (0.5 * x * x) } if (ln(y) < (Ln2 - (0.5 * x * x))) then begin Result := x; Exit; end; {step 3: translate x to s * (b - x) and return it if y > g(x) or ln(1 + s - y) < ln(2 * s) - (0.5 * x * x) } if (x > 0) then x := MPN_s * (Root2Pi - x) else x := -MPN_s * (Root2Pi + x); if (ln(MPN_sPlus1 - y) < (Ln2MPN_s - (0.5 * x * x))) then begin Result := x; Exit; end; {step 4: the iterative process} repeat repeat NonZeroRandom := AsFloat; until (NonZeroRandom <> 0.0); x := -ln(NonZeroRandom) * InvRoot2Pi; repeat NonZeroRandom := AsFloat; until (NonZeroRandom <> 0.0); y := -ln(NonZeroRandom); until (y + y) > (x * x); if (NonZeroRandom < 0.5) then Result := -(Root2Pi + x) else Result := Root2Pi + x; end; {====================================================================} {===TStRandomSystem==================================================} constructor TStRandomSystem.Create(aSeed : integer); begin inherited Create; Seed := aSeed; end; {--------} function TStRandomSystem.AsFloat : double; var SaveSeed : integer; begin SaveSeed := RandSeed; RandSeed := FSeed; Result := System.Random; FSeed := RandSeed; RandSeed := SaveSeed; end; {--------} procedure TStRandomSystem.rsSetSeed(aValue : integer); begin if (aValue = 0) then FSeed := GetRandomSeed else FSeed := aValue; end; {====================================================================} {===TStRandomCombined================================================} const m1 = 2147483563; m2 = 2147483399; {--------} constructor TStRandomCombined.Create(aSeed1, aSeed2 : integer); begin inherited Create; Seed1 := aSeed1; if (aSeed1 = 0) and (aSeed2 = 0) then Sleep(10); // a small delay to enable seed to change Seed2 := aSeed2; end; {--------} function TStRandomCombined.AsFloat : double; const a1 = 40014; q1 = 53668; {equals m1 div a1} r1 = 12211; {equals m1 mod a1} a2 = 40692; q2 = 52774; {equals m2 div a2} r2 = 3791; {equals m2 mod a2} OneOverM1 : double = 1.0 / m1; var k : Integer; Z : Integer; begin {advance first PRNG} k := FSeed1 div q1; FSeed1 := (a1 * (FSeed1 - (k * q1))) - (k * r1); if (FSeed1 < 0) then inc(FSeed1, m1); {advance second PRNG} k := FSeed2 div q2; FSeed2 := (a2 * (FSeed2 - (k * q2))) - (k * r2); if (FSeed2 < 0) then inc(FSeed2, m2); {combine the two seeds} Z := FSeed1 - FSeed2; if (Z <= 0) then Z := Z + m1 - 1; Result := Z * OneOverM1; end; {--------} procedure TStRandomCombined.rcSetSeed1(aValue : integer); begin if (aValue = 0) then FSeed1 := GetRandomSeed else FSeed1 := aValue; end; {--------} procedure TStRandomCombined.rcSetSeed2(aValue : integer); begin if (aValue = 0) then FSeed2 := GetRandomSeed else FSeed2 := aValue; end; {====================================================================} {$IFDEF WIN32} {===TStRandomMother==================================================} constructor TStRandomMother.Create(aSeed : integer); begin inherited Create; Seed := aSeed; end; {--------} function TStRandomMother.AsFloat : double; const TwoM31 : double = 1.0 / $7FFFFFFF; begin asm push esi push edi push ebx {get around a compiler bug where it doesn't notice that edx is being changed in the asm code !!! D5 bug} push edx {set ebx to point to self} mov ebx, eax {multiply X(n-4) by 21111111} mov eax, [ebx].TStRandomMother.FNMinus4 mul [Mum1] mov edi, eax mov esi, edx {multiply X(n-3) by 1492 (save it in X(n-4) before though)} mov eax, [ebx].TStRandomMother.FNMinus3 mov [ebx].TStRandomMother.FNMinus4, eax mul [Mum2] add edi, eax adc esi, edx {multiply X(n-2) by 1776 (save it in X(n-3) before though)} mov eax, [ebx].TStRandomMother.FNMinus2 mov [ebx].TStRandomMother.FNMinus3, eax mul [Mum3] add edi, eax adc esi, edx {multiply X(n-1) by 5115 (save it in X(n-2) before though)} mov eax, [ebx].TStRandomMother.FNMinus1 mov [ebx].TStRandomMother.FNMinus2, eax mul [Mum4] add edi, eax adc esi, edx {add in the remainder} add edi, [ebx].TStRandomMother.FC adc esi, 0; {save the lower 32 bits in X(n-1), the upper into the remainder} mov [ebx].TStRandomMother.FNMinus1, edi mov [ebx].TStRandomMother.FC, esi {get around a compiler bug where it doesn't notice that edx was changed in the asm code !!! D5 bug} pop edx pop ebx pop edi pop esi end; Result := (FNMinus1 shr 1) * TwoM31; end; {--------} {$IFOPT Q+} {note: TStRandomMother.rsSetSeed expressly overflows integers (it's equivalent to calculating mod 2^32), so we have to force overflow checks off} {$DEFINE SaveQPlus} {$Q-} {$ENDIF} procedure TStRandomMother.rsSetSeed(aValue : integer); begin if (aValue = 0) then aValue := GetRandomSeed; FNminus4 := aValue; {note: the following code uses the generator Xn := (69069 * Xn-1) mod 2^32 from D.E.Knuth, The Art of Computer Programming, Vol. 2 (second edition), Addison-Wesley, 1981, pp.102} FNminus3 := 69069 * FNminus4; FNminus2 := 69069 * FNminus3; FNminus1 := 69069 * FNminus2; FC := 69069 * FNminus1; end; {$IFDEF SaveQPlus} {$Q+} {$ENDIF} {$ENDIF} {====================================================================} {====================================================================} procedure CalcConstants; begin {for the normal variates} Root2Pi := sqrt(2 * Pi); InvRoot2Pi := 1.0 / Root2Pi; RootLn4 := sqrt(ln(4.0)); Ln2 := ln(2.0); MPN_s := RootLn4 / (Root2Pi - RootLn4); Ln2MPN_s := ln(2.0 * MPN_s); MPN_sPlus1 := MPN_s + 1.0; Mum1 := 2111111111; Mum2 := 1492; Mum3 := 1776; Mum4 := 5115; end; {====================================================================} initialization CalcConstants; end.
unit tcChangedToolBarsList; interface uses l3Interfaces, tcInterfaces, tcItemList ; type TtcChangedToolBarsList = class(TtcItemList, ItcChangedToolBarsList) protected // ItcChangedToolBarsList function pm_GetToolBar(Index: Integer): ItcChangedToolBar; function ItcChangedToolBarsList.Add = ItcChangedToolBarsList_Add; function ItcChangedToolBarsList_Add(const anID: Il3CString): ItcChangedToolBar; procedure AssignToItem(const aSource, aTarget: ItcItem); override; protected procedure AddExisting(const anItem: ItcItem); override; function MakeItem(const anID: Il3CString): ItcItem; override; public class function Make: ItcChangedToolBarsList; end; implementation uses SysUtils, tcChangedToolBar ; { TtcChangedToolBarsList } procedure TtcChangedToolBarsList.AddExisting(const anItem: ItcItem); begin Assert(False); end; procedure TtcChangedToolBarsList.AssignToItem(const aSource, aTarget: ItcItem); begin Assert(False); end; class function TtcChangedToolBarsList.Make: ItcChangedToolBarsList; var l_Instance: TtcChangedToolBarsList; begin l_Instance := Create; try Result := l_Instance; finally FreeAndNil(l_Instance); end; end; function TtcChangedToolBarsList.MakeItem(const anID: Il3CString): ItcItem; begin Result := TtcChangedToolBar.Make(anID); end; function TtcChangedToolBarsList.pm_GetToolBar( Index: Integer): ItcChangedToolBar; begin Result := pm_GetItem(Index) as ItcChangedToolBar; end; function TtcChangedToolBarsList.ItcChangedToolBarsList_Add( const anID: Il3CString): ItcChangedToolBar; begin Result := Add(anID) as ItcChangedToolBar; end; end.
unit InfoRPTRUNTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoRPTRUNRecord = record PLenderNumber: String[8]; PReportID: Integer; PControlStatus: String[10]; PStart: String[20]; PStop: String[20]; PStopStatus: String[10]; PUserID: String[10]; PDescription: String[100]; PReportDate: String[10]; PTitle: String[100]; PFromDate: String[10]; PToDate: String[10]; PReportProcessed: Boolean; PReportFileName: String[12]; PDataIncluded: Integer; PUsingWhichDate: Integer; PSortOrder: Integer; PGroupedby: Integer; PRepro: Integer; POpenClaims: Integer; PStatementDate: Integer; PBeginningWith: Integer; PPrintZero: Integer; PPrintNotes: Integer; PStmtYrMo: String[6]; PFeedback: String[50]; PRptType: Integer; PDestination: String[80]; PSummaryOnlyFlag: Boolean; End; TInfoRPTRUNClass2 = class public PLenderNumber: String[8]; PReportID: Integer; PControlStatus: String[10]; PStart: String[20]; PStop: String[20]; PStopStatus: String[10]; PUserID: String[10]; PDescription: String[100]; PReportDate: String[10]; PTitle: String[100]; PFromDate: String[10]; PToDate: String[10]; PReportProcessed: Boolean; PReportFileName: String[12]; PDataIncluded: Integer; PUsingWhichDate: Integer; PSortOrder: Integer; PGroupedby: Integer; PRepro: Integer; POpenClaims: Integer; PStatementDate: Integer; PBeginningWith: Integer; PPrintZero: Integer; PPrintNotes: Integer; PStmtYrMo: String[6]; PFeedback: String[50]; PRptType: Integer; PDestination: String[80]; PSummaryOnlyFlag: Boolean; End; // function CtoRInfoRPTRUN(AClass:TInfoRPTRUNClass):TInfoRPTRUNRecord; // procedure RtoCInfoRPTRUN(ARecord:TInfoRPTRUNRecord;AClass:TInfoRPTRUNClass); TInfoRPTRUNBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoRPTRUNRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoRPTRUN = (InfoRPTRUNPrimaryKey, InfoRPTRUNLenderReport); TInfoRPTRUNTable = class( TDBISAMTableAU ) private FDFLenderNumber: TStringField; FDFReportID: TAutoIncField; FDFControlStatus: TStringField; FDFStart: TStringField; FDFStop: TStringField; FDFStopStatus: TStringField; FDFUserID: TStringField; FDFDescription: TStringField; FDFReportDate: TStringField; FDFTitle: TStringField; FDFFromDate: TStringField; FDFToDate: TStringField; FDFLenderGroup: TBlobField; FDFCompanyString: TBlobField; FDFLenderString: TBlobField; FDFPrefixString: TBlobField; FDFPolicyString: TBlobField; FDFClaimString: TBlobField; FDFLossCodeString: TBlobField; FDFTranTypeString: TBlobField; FDFSettlementMethodString: TBlobField; FDFAdjusterString: TBlobField; FDFClaimTrackString: TBlobField; FDFTranTrackString: TBlobField; FDFTranStatusString: TBlobField; FDFReportProcessed: TBooleanField; FDFReportFileName: TStringField; FDFDataIncluded: TIntegerField; FDFUsingWhichDate: TIntegerField; FDFSortOrder: TIntegerField; FDFGroupedby: TIntegerField; FDFRepro: TIntegerField; FDFOpenClaims: TIntegerField; FDFStatementDate: TIntegerField; FDFBeginningWith: TIntegerField; FDFPrintZero: TIntegerField; FDFPrintNotes: TIntegerField; FDFStmtYrMo: TStringField; FDFFeedback: TStringField; FDFRptType: TIntegerField; FDFDestination: TStringField; FDFSummaryOnlyFlag: TBooleanField; procedure SetPLenderNumber(const Value: String); function GetPLenderNumber:String; procedure SetPControlStatus(const Value: String); function GetPControlStatus:String; procedure SetPStart(const Value: String); function GetPStart:String; procedure SetPStop(const Value: String); function GetPStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPReportDate(const Value: String); function GetPReportDate:String; procedure SetPTitle(const Value: String); function GetPTitle:String; procedure SetPFromDate(const Value: String); function GetPFromDate:String; procedure SetPToDate(const Value: String); function GetPToDate:String; procedure SetPReportProcessed(const Value: Boolean); function GetPReportProcessed:Boolean; procedure SetPReportFileName(const Value: String); function GetPReportFileName:String; procedure SetPDataIncluded(const Value: Integer); function GetPDataIncluded:Integer; procedure SetPUsingWhichDate(const Value: Integer); function GetPUsingWhichDate:Integer; procedure SetPSortOrder(const Value: Integer); function GetPSortOrder:Integer; procedure SetPGroupedby(const Value: Integer); function GetPGroupedby:Integer; procedure SetPRepro(const Value: Integer); function GetPRepro:Integer; procedure SetPOpenClaims(const Value: Integer); function GetPOpenClaims:Integer; procedure SetPStatementDate(const Value: Integer); function GetPStatementDate:Integer; procedure SetPBeginningWith(const Value: Integer); function GetPBeginningWith:Integer; procedure SetPPrintZero(const Value: Integer); function GetPPrintZero:Integer; procedure SetPPrintNotes(const Value: Integer); function GetPPrintNotes:Integer; procedure SetPStmtYrMo(const Value: String); function GetPStmtYrMo:String; procedure SetPFeedback(const Value: String); function GetPFeedback:String; procedure SetPRptType(const Value: Integer); function GetPRptType:Integer; procedure SetPDestination(const Value: String); function GetPDestination:String; procedure SetPSummaryOnlyFlag(const Value: Boolean); function GetPSummaryOnlyFlag:Boolean; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoRPTRUN); function GetEnumIndex: TEIInfoRPTRUN; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoRPTRUNRecord; procedure StoreDataBuffer(ABuffer:TInfoRPTRUNRecord); property DFLenderNumber: TStringField read FDFLenderNumber; property DFReportID: TAutoIncField read FDFReportID; property DFControlStatus: TStringField read FDFControlStatus; property DFStart: TStringField read FDFStart; property DFStop: TStringField read FDFStop; property DFStopStatus: TStringField read FDFStopStatus; property DFUserID: TStringField read FDFUserID; property DFDescription: TStringField read FDFDescription; property DFReportDate: TStringField read FDFReportDate; property DFTitle: TStringField read FDFTitle; property DFFromDate: TStringField read FDFFromDate; property DFToDate: TStringField read FDFToDate; property DFLenderGroup: TBlobField read FDFLenderGroup; property DFCompanyString: TBlobField read FDFCompanyString; property DFLenderString: TBlobField read FDFLenderString; property DFPrefixString: TBlobField read FDFPrefixString; property DFPolicyString: TBlobField read FDFPolicyString; property DFClaimString: TBlobField read FDFClaimString; property DFLossCodeString: TBlobField read FDFLossCodeString; property DFTranTypeString: TBlobField read FDFTranTypeString; property DFSettlementMethodString: TBlobField read FDFSettlementMethodString; property DFAdjusterString: TBlobField read FDFAdjusterString; property DFClaimTrackString: TBlobField read FDFClaimTrackString; property DFTranTrackString: TBlobField read FDFTranTrackString; property DFTranStatusString: TBlobField read FDFTranStatusString; property DFReportProcessed: TBooleanField read FDFReportProcessed; property DFReportFileName: TStringField read FDFReportFileName; property DFDataIncluded: TIntegerField read FDFDataIncluded; property DFUsingWhichDate: TIntegerField read FDFUsingWhichDate; property DFSortOrder: TIntegerField read FDFSortOrder; property DFGroupedby: TIntegerField read FDFGroupedby; property DFRepro: TIntegerField read FDFRepro; property DFOpenClaims: TIntegerField read FDFOpenClaims; property DFStatementDate: TIntegerField read FDFStatementDate; property DFBeginningWith: TIntegerField read FDFBeginningWith; property DFPrintZero: TIntegerField read FDFPrintZero; property DFPrintNotes: TIntegerField read FDFPrintNotes; property DFStmtYrMo: TStringField read FDFStmtYrMo; property DFFeedback: TStringField read FDFFeedback; property DFRptType: TIntegerField read FDFRptType; property DFDestination: TStringField read FDFDestination; property DFSummaryOnlyFlag: TBooleanField read FDFSummaryOnlyFlag; property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber; property PControlStatus: String read GetPControlStatus write SetPControlStatus; property PStart: String read GetPStart write SetPStart; property PStop: String read GetPStop write SetPStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PUserID: String read GetPUserID write SetPUserID; property PDescription: String read GetPDescription write SetPDescription; property PReportDate: String read GetPReportDate write SetPReportDate; property PTitle: String read GetPTitle write SetPTitle; property PFromDate: String read GetPFromDate write SetPFromDate; property PToDate: String read GetPToDate write SetPToDate; property PReportProcessed: Boolean read GetPReportProcessed write SetPReportProcessed; property PReportFileName: String read GetPReportFileName write SetPReportFileName; property PDataIncluded: Integer read GetPDataIncluded write SetPDataIncluded; property PUsingWhichDate: Integer read GetPUsingWhichDate write SetPUsingWhichDate; property PSortOrder: Integer read GetPSortOrder write SetPSortOrder; property PGroupedby: Integer read GetPGroupedby write SetPGroupedby; property PRepro: Integer read GetPRepro write SetPRepro; property POpenClaims: Integer read GetPOpenClaims write SetPOpenClaims; property PStatementDate: Integer read GetPStatementDate write SetPStatementDate; property PBeginningWith: Integer read GetPBeginningWith write SetPBeginningWith; property PPrintZero: Integer read GetPPrintZero write SetPPrintZero; property PPrintNotes: Integer read GetPPrintNotes write SetPPrintNotes; property PStmtYrMo: String read GetPStmtYrMo write SetPStmtYrMo; property PFeedback: String read GetPFeedback write SetPFeedback; property PRptType: Integer read GetPRptType write SetPRptType; property PDestination: String read GetPDestination write SetPDestination; property PSummaryOnlyFlag: Boolean read GetPSummaryOnlyFlag write SetPSummaryOnlyFlag; published property Active write SetActive; property EnumIndex: TEIInfoRPTRUN read GetEnumIndex write SetEnumIndex; end; { TInfoRPTRUNTable } TInfoRPTRUNQuery = class( TDBISAMQueryAU ) private FDFLenderNumber: TStringField; FDFReportID: TAutoIncField; FDFControlStatus: TStringField; FDFStart: TStringField; FDFStop: TStringField; FDFStopStatus: TStringField; FDFUserID: TStringField; FDFDescription: TStringField; FDFReportDate: TStringField; FDFTitle: TStringField; FDFFromDate: TStringField; FDFToDate: TStringField; FDFLenderGroup: TBlobField; FDFCompanyString: TBlobField; FDFLenderString: TBlobField; FDFPrefixString: TBlobField; FDFPolicyString: TBlobField; FDFClaimString: TBlobField; FDFLossCodeString: TBlobField; FDFTranTypeString: TBlobField; FDFSettlementMethodString: TBlobField; FDFAdjusterString: TBlobField; FDFClaimTrackString: TBlobField; FDFTranTrackString: TBlobField; FDFTranStatusString: TBlobField; FDFReportProcessed: TBooleanField; FDFReportFileName: TStringField; FDFDataIncluded: TIntegerField; FDFUsingWhichDate: TIntegerField; FDFSortOrder: TIntegerField; FDFGroupedby: TIntegerField; FDFRepro: TIntegerField; FDFOpenClaims: TIntegerField; FDFStatementDate: TIntegerField; FDFBeginningWith: TIntegerField; FDFPrintZero: TIntegerField; FDFPrintNotes: TIntegerField; FDFStmtYrMo: TStringField; FDFFeedback: TStringField; FDFRptType: TIntegerField; FDFDestination: TStringField; FDFSummaryOnlyFlag: TBooleanField; procedure SetPLenderNumber(const Value: String); function GetPLenderNumber:String; procedure SetPControlStatus(const Value: String); function GetPControlStatus:String; procedure SetPStart(const Value: String); function GetPStart:String; procedure SetPStop(const Value: String); function GetPStop:String; procedure SetPStopStatus(const Value: String); function GetPStopStatus:String; procedure SetPUserID(const Value: String); function GetPUserID:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPReportDate(const Value: String); function GetPReportDate:String; procedure SetPTitle(const Value: String); function GetPTitle:String; procedure SetPFromDate(const Value: String); function GetPFromDate:String; procedure SetPToDate(const Value: String); function GetPToDate:String; procedure SetPReportProcessed(const Value: Boolean); function GetPReportProcessed:Boolean; procedure SetPReportFileName(const Value: String); function GetPReportFileName:String; procedure SetPDataIncluded(const Value: Integer); function GetPDataIncluded:Integer; procedure SetPUsingWhichDate(const Value: Integer); function GetPUsingWhichDate:Integer; procedure SetPSortOrder(const Value: Integer); function GetPSortOrder:Integer; procedure SetPGroupedby(const Value: Integer); function GetPGroupedby:Integer; procedure SetPRepro(const Value: Integer); function GetPRepro:Integer; procedure SetPOpenClaims(const Value: Integer); function GetPOpenClaims:Integer; procedure SetPStatementDate(const Value: Integer); function GetPStatementDate:Integer; procedure SetPBeginningWith(const Value: Integer); function GetPBeginningWith:Integer; procedure SetPPrintZero(const Value: Integer); function GetPPrintZero:Integer; procedure SetPPrintNotes(const Value: Integer); function GetPPrintNotes:Integer; procedure SetPStmtYrMo(const Value: String); function GetPStmtYrMo:String; procedure SetPFeedback(const Value: String); function GetPFeedback:String; procedure SetPRptType(const Value: Integer); function GetPRptType:Integer; procedure SetPDestination(const Value: String); function GetPDestination:String; procedure SetPSummaryOnlyFlag(const Value: Boolean); function GetPSummaryOnlyFlag:Boolean; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoRPTRUNRecord; procedure StoreDataBuffer(ABuffer:TInfoRPTRUNRecord); property DFLenderNumber: TStringField read FDFLenderNumber; property DFReportID: TAutoIncField read FDFReportID; property DFControlStatus: TStringField read FDFControlStatus; property DFStart: TStringField read FDFStart; property DFStop: TStringField read FDFStop; property DFStopStatus: TStringField read FDFStopStatus; property DFUserID: TStringField read FDFUserID; property DFDescription: TStringField read FDFDescription; property DFReportDate: TStringField read FDFReportDate; property DFTitle: TStringField read FDFTitle; property DFFromDate: TStringField read FDFFromDate; property DFToDate: TStringField read FDFToDate; property DFLenderGroup: TBlobField read FDFLenderGroup; property DFCompanyString: TBlobField read FDFCompanyString; property DFLenderString: TBlobField read FDFLenderString; property DFPrefixString: TBlobField read FDFPrefixString; property DFPolicyString: TBlobField read FDFPolicyString; property DFClaimString: TBlobField read FDFClaimString; property DFLossCodeString: TBlobField read FDFLossCodeString; property DFTranTypeString: TBlobField read FDFTranTypeString; property DFSettlementMethodString: TBlobField read FDFSettlementMethodString; property DFAdjusterString: TBlobField read FDFAdjusterString; property DFClaimTrackString: TBlobField read FDFClaimTrackString; property DFTranTrackString: TBlobField read FDFTranTrackString; property DFTranStatusString: TBlobField read FDFTranStatusString; property DFReportProcessed: TBooleanField read FDFReportProcessed; property DFReportFileName: TStringField read FDFReportFileName; property DFDataIncluded: TIntegerField read FDFDataIncluded; property DFUsingWhichDate: TIntegerField read FDFUsingWhichDate; property DFSortOrder: TIntegerField read FDFSortOrder; property DFGroupedby: TIntegerField read FDFGroupedby; property DFRepro: TIntegerField read FDFRepro; property DFOpenClaims: TIntegerField read FDFOpenClaims; property DFStatementDate: TIntegerField read FDFStatementDate; property DFBeginningWith: TIntegerField read FDFBeginningWith; property DFPrintZero: TIntegerField read FDFPrintZero; property DFPrintNotes: TIntegerField read FDFPrintNotes; property DFStmtYrMo: TStringField read FDFStmtYrMo; property DFFeedback: TStringField read FDFFeedback; property DFRptType: TIntegerField read FDFRptType; property DFDestination: TStringField read FDFDestination; property DFSummaryOnlyFlag: TBooleanField read FDFSummaryOnlyFlag; property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber; property PControlStatus: String read GetPControlStatus write SetPControlStatus; property PStart: String read GetPStart write SetPStart; property PStop: String read GetPStop write SetPStop; property PStopStatus: String read GetPStopStatus write SetPStopStatus; property PUserID: String read GetPUserID write SetPUserID; property PDescription: String read GetPDescription write SetPDescription; property PReportDate: String read GetPReportDate write SetPReportDate; property PTitle: String read GetPTitle write SetPTitle; property PFromDate: String read GetPFromDate write SetPFromDate; property PToDate: String read GetPToDate write SetPToDate; property PReportProcessed: Boolean read GetPReportProcessed write SetPReportProcessed; property PReportFileName: String read GetPReportFileName write SetPReportFileName; property PDataIncluded: Integer read GetPDataIncluded write SetPDataIncluded; property PUsingWhichDate: Integer read GetPUsingWhichDate write SetPUsingWhichDate; property PSortOrder: Integer read GetPSortOrder write SetPSortOrder; property PGroupedby: Integer read GetPGroupedby write SetPGroupedby; property PRepro: Integer read GetPRepro write SetPRepro; property POpenClaims: Integer read GetPOpenClaims write SetPOpenClaims; property PStatementDate: Integer read GetPStatementDate write SetPStatementDate; property PBeginningWith: Integer read GetPBeginningWith write SetPBeginningWith; property PPrintZero: Integer read GetPPrintZero write SetPPrintZero; property PPrintNotes: Integer read GetPPrintNotes write SetPPrintNotes; property PStmtYrMo: String read GetPStmtYrMo write SetPStmtYrMo; property PFeedback: String read GetPFeedback write SetPFeedback; property PRptType: Integer read GetPRptType write SetPRptType; property PDestination: String read GetPDestination write SetPDestination; property PSummaryOnlyFlag: Boolean read GetPSummaryOnlyFlag write SetPSummaryOnlyFlag; published property Active write SetActive; end; { TInfoRPTRUNTable } procedure Register; implementation function TInfoRPTRUNTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoRPTRUNTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoRPTRUNTable.GenerateNewFieldName } function TInfoRPTRUNTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoRPTRUNTable.CreateField } procedure TInfoRPTRUNTable.CreateFields; begin FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField; FDFReportID := CreateField( 'ReportID' ) as TAutoIncField; FDFControlStatus := CreateField( 'ControlStatus' ) as TStringField; FDFStart := CreateField( 'Start' ) as TStringField; FDFStop := CreateField( 'Stop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFReportDate := CreateField( 'ReportDate' ) as TStringField; FDFTitle := CreateField( 'Title' ) as TStringField; FDFFromDate := CreateField( 'FromDate' ) as TStringField; FDFToDate := CreateField( 'ToDate' ) as TStringField; FDFLenderGroup := CreateField( 'LenderGroup' ) as TBlobField; FDFCompanyString := CreateField( 'CompanyString' ) as TBlobField; FDFLenderString := CreateField( 'LenderString' ) as TBlobField; FDFPrefixString := CreateField( 'PrefixString' ) as TBlobField; FDFPolicyString := CreateField( 'PolicyString' ) as TBlobField; FDFClaimString := CreateField( 'ClaimString' ) as TBlobField; FDFLossCodeString := CreateField( 'LossCodeString' ) as TBlobField; FDFTranTypeString := CreateField( 'TranTypeString' ) as TBlobField; FDFSettlementMethodString := CreateField( 'SettlementMethodString' ) as TBlobField; FDFAdjusterString := CreateField( 'AdjusterString' ) as TBlobField; FDFClaimTrackString := CreateField( 'ClaimTrackString' ) as TBlobField; FDFTranTrackString := CreateField( 'TranTrackString' ) as TBlobField; FDFTranStatusString := CreateField( 'TranStatusString' ) as TBlobField; FDFReportProcessed := CreateField( 'ReportProcessed' ) as TBooleanField; FDFReportFileName := CreateField( 'ReportFileName' ) as TStringField; FDFDataIncluded := CreateField( 'DataIncluded' ) as TIntegerField; FDFUsingWhichDate := CreateField( 'UsingWhichDate' ) as TIntegerField; FDFSortOrder := CreateField( 'SortOrder' ) as TIntegerField; FDFGroupedby := CreateField( 'Groupedby' ) as TIntegerField; FDFRepro := CreateField( 'Repro' ) as TIntegerField; FDFOpenClaims := CreateField( 'OpenClaims' ) as TIntegerField; FDFStatementDate := CreateField( 'StatementDate' ) as TIntegerField; FDFBeginningWith := CreateField( 'BeginningWith' ) as TIntegerField; FDFPrintZero := CreateField( 'PrintZero' ) as TIntegerField; FDFPrintNotes := CreateField( 'PrintNotes' ) as TIntegerField; FDFStmtYrMo := CreateField( 'StmtYrMo' ) as TStringField; FDFFeedback := CreateField( 'Feedback' ) as TStringField; FDFRptType := CreateField( 'RptType' ) as TIntegerField; FDFDestination := CreateField( 'Destination' ) as TStringField; FDFSummaryOnlyFlag := CreateField( 'SummaryOnlyFlag' ) as TBooleanField; end; { TInfoRPTRUNTable.CreateFields } procedure TInfoRPTRUNTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoRPTRUNTable.SetActive } procedure TInfoRPTRUNTable.SetPLenderNumber(const Value: String); begin DFLenderNumber.Value := Value; end; function TInfoRPTRUNTable.GetPLenderNumber:String; begin result := DFLenderNumber.Value; end; procedure TInfoRPTRUNTable.SetPControlStatus(const Value: String); begin DFControlStatus.Value := Value; end; function TInfoRPTRUNTable.GetPControlStatus:String; begin result := DFControlStatus.Value; end; procedure TInfoRPTRUNTable.SetPStart(const Value: String); begin DFStart.Value := Value; end; function TInfoRPTRUNTable.GetPStart:String; begin result := DFStart.Value; end; procedure TInfoRPTRUNTable.SetPStop(const Value: String); begin DFStop.Value := Value; end; function TInfoRPTRUNTable.GetPStop:String; begin result := DFStop.Value; end; procedure TInfoRPTRUNTable.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TInfoRPTRUNTable.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TInfoRPTRUNTable.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TInfoRPTRUNTable.GetPUserID:String; begin result := DFUserID.Value; end; procedure TInfoRPTRUNTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoRPTRUNTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoRPTRUNTable.SetPReportDate(const Value: String); begin DFReportDate.Value := Value; end; function TInfoRPTRUNTable.GetPReportDate:String; begin result := DFReportDate.Value; end; procedure TInfoRPTRUNTable.SetPTitle(const Value: String); begin DFTitle.Value := Value; end; function TInfoRPTRUNTable.GetPTitle:String; begin result := DFTitle.Value; end; procedure TInfoRPTRUNTable.SetPFromDate(const Value: String); begin DFFromDate.Value := Value; end; function TInfoRPTRUNTable.GetPFromDate:String; begin result := DFFromDate.Value; end; procedure TInfoRPTRUNTable.SetPToDate(const Value: String); begin DFToDate.Value := Value; end; function TInfoRPTRUNTable.GetPToDate:String; begin result := DFToDate.Value; end; procedure TInfoRPTRUNTable.SetPReportProcessed(const Value: Boolean); begin DFReportProcessed.Value := Value; end; function TInfoRPTRUNTable.GetPReportProcessed:Boolean; begin result := DFReportProcessed.Value; end; procedure TInfoRPTRUNTable.SetPReportFileName(const Value: String); begin DFReportFileName.Value := Value; end; function TInfoRPTRUNTable.GetPReportFileName:String; begin result := DFReportFileName.Value; end; procedure TInfoRPTRUNTable.SetPDataIncluded(const Value: Integer); begin DFDataIncluded.Value := Value; end; function TInfoRPTRUNTable.GetPDataIncluded:Integer; begin result := DFDataIncluded.Value; end; procedure TInfoRPTRUNTable.SetPUsingWhichDate(const Value: Integer); begin DFUsingWhichDate.Value := Value; end; function TInfoRPTRUNTable.GetPUsingWhichDate:Integer; begin result := DFUsingWhichDate.Value; end; procedure TInfoRPTRUNTable.SetPSortOrder(const Value: Integer); begin DFSortOrder.Value := Value; end; function TInfoRPTRUNTable.GetPSortOrder:Integer; begin result := DFSortOrder.Value; end; procedure TInfoRPTRUNTable.SetPGroupedby(const Value: Integer); begin DFGroupedby.Value := Value; end; function TInfoRPTRUNTable.GetPGroupedby:Integer; begin result := DFGroupedby.Value; end; procedure TInfoRPTRUNTable.SetPRepro(const Value: Integer); begin DFRepro.Value := Value; end; function TInfoRPTRUNTable.GetPRepro:Integer; begin result := DFRepro.Value; end; procedure TInfoRPTRUNTable.SetPOpenClaims(const Value: Integer); begin DFOpenClaims.Value := Value; end; function TInfoRPTRUNTable.GetPOpenClaims:Integer; begin result := DFOpenClaims.Value; end; procedure TInfoRPTRUNTable.SetPStatementDate(const Value: Integer); begin DFStatementDate.Value := Value; end; function TInfoRPTRUNTable.GetPStatementDate:Integer; begin result := DFStatementDate.Value; end; procedure TInfoRPTRUNTable.SetPBeginningWith(const Value: Integer); begin DFBeginningWith.Value := Value; end; function TInfoRPTRUNTable.GetPBeginningWith:Integer; begin result := DFBeginningWith.Value; end; procedure TInfoRPTRUNTable.SetPPrintZero(const Value: Integer); begin DFPrintZero.Value := Value; end; function TInfoRPTRUNTable.GetPPrintZero:Integer; begin result := DFPrintZero.Value; end; procedure TInfoRPTRUNTable.SetPPrintNotes(const Value: Integer); begin DFPrintNotes.Value := Value; end; function TInfoRPTRUNTable.GetPPrintNotes:Integer; begin result := DFPrintNotes.Value; end; procedure TInfoRPTRUNTable.SetPStmtYrMo(const Value: String); begin DFStmtYrMo.Value := Value; end; function TInfoRPTRUNTable.GetPStmtYrMo:String; begin result := DFStmtYrMo.Value; end; procedure TInfoRPTRUNTable.SetPFeedback(const Value: String); begin DFFeedback.Value := Value; end; function TInfoRPTRUNTable.GetPFeedback:String; begin result := DFFeedback.Value; end; procedure TInfoRPTRUNTable.SetPRptType(const Value: Integer); begin DFRptType.Value := Value; end; function TInfoRPTRUNTable.GetPRptType:Integer; begin result := DFRptType.Value; end; procedure TInfoRPTRUNTable.SetPDestination(const Value: String); begin DFDestination.Value := Value; end; function TInfoRPTRUNTable.GetPDestination:String; begin result := DFDestination.Value; end; procedure TInfoRPTRUNTable.SetPSummaryOnlyFlag(const Value: Boolean); begin DFSummaryOnlyFlag.Value := Value; end; function TInfoRPTRUNTable.GetPSummaryOnlyFlag:Boolean; begin result := DFSummaryOnlyFlag.Value; end; procedure TInfoRPTRUNTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNumber, String, 8, N'); Add('ReportID, AutoInc, 0, N'); Add('ControlStatus, String, 10, N'); Add('Start, String, 20, N'); Add('Stop, String, 20, N'); Add('StopStatus, String, 10, N'); Add('UserID, String, 10, N'); Add('Description, String, 100, N'); Add('ReportDate, String, 10, N'); Add('Title, String, 100, N'); Add('FromDate, String, 10, N'); Add('ToDate, String, 10, N'); Add('LenderGroup, Blob, 0, N'); Add('CompanyString, Blob, 0, N'); Add('LenderString, Blob, 0, N'); Add('PrefixString, Blob, 0, N'); Add('PolicyString, Blob, 0, N'); Add('ClaimString, Blob, 0, N'); Add('LossCodeString, Blob, 0, N'); Add('TranTypeString, Blob, 0, N'); Add('SettlementMethodString, Blob, 0, N'); Add('AdjusterString, Blob, 0, N'); Add('ClaimTrackString, Blob, 0, N'); Add('TranTrackString, Blob, 0, N'); Add('TranStatusString, Blob, 0, N'); Add('ReportProcessed, Boolean, 0, N'); Add('ReportFileName, String, 12, N'); Add('DataIncluded, Integer, 0, N'); Add('UsingWhichDate, Integer, 0, N'); Add('SortOrder, Integer, 0, N'); Add('Groupedby, Integer, 0, N'); Add('Repro, Integer, 0, N'); Add('OpenClaims, Integer, 0, N'); Add('StatementDate, Integer, 0, N'); Add('BeginningWith, Integer, 0, N'); Add('PrintZero, Integer, 0, N'); Add('PrintNotes, Integer, 0, N'); Add('StmtYrMo, String, 6, N'); Add('Feedback, String, 50, N'); Add('RptType, Integer, 0, N'); Add('Destination, String, 80, N'); Add('SummaryOnlyFlag, Boolean, 0, N'); end; end; procedure TInfoRPTRUNTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, ReportID, Y, Y, N, N'); Add('LenderReport, LenderNumber;RptType;ReportID, N, N, N, Y'); end; end; procedure TInfoRPTRUNTable.SetEnumIndex(Value: TEIInfoRPTRUN); begin case Value of InfoRPTRUNPrimaryKey : IndexName := ''; InfoRPTRUNLenderReport : IndexName := 'LenderReport'; end; end; function TInfoRPTRUNTable.GetDataBuffer:TInfoRPTRUNRecord; var buf: TInfoRPTRUNRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNumber := DFLenderNumber.Value; buf.PReportID := DFReportID.Value; buf.PControlStatus := DFControlStatus.Value; buf.PStart := DFStart.Value; buf.PStop := DFStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PUserID := DFUserID.Value; buf.PDescription := DFDescription.Value; buf.PReportDate := DFReportDate.Value; buf.PTitle := DFTitle.Value; buf.PFromDate := DFFromDate.Value; buf.PToDate := DFToDate.Value; buf.PReportProcessed := DFReportProcessed.Value; buf.PReportFileName := DFReportFileName.Value; buf.PDataIncluded := DFDataIncluded.Value; buf.PUsingWhichDate := DFUsingWhichDate.Value; buf.PSortOrder := DFSortOrder.Value; buf.PGroupedby := DFGroupedby.Value; buf.PRepro := DFRepro.Value; buf.POpenClaims := DFOpenClaims.Value; buf.PStatementDate := DFStatementDate.Value; buf.PBeginningWith := DFBeginningWith.Value; buf.PPrintZero := DFPrintZero.Value; buf.PPrintNotes := DFPrintNotes.Value; buf.PStmtYrMo := DFStmtYrMo.Value; buf.PFeedback := DFFeedback.Value; buf.PRptType := DFRptType.Value; buf.PDestination := DFDestination.Value; buf.PSummaryOnlyFlag := DFSummaryOnlyFlag.Value; result := buf; end; procedure TInfoRPTRUNTable.StoreDataBuffer(ABuffer:TInfoRPTRUNRecord); begin DFLenderNumber.Value := ABuffer.PLenderNumber; DFControlStatus.Value := ABuffer.PControlStatus; DFStart.Value := ABuffer.PStart; DFStop.Value := ABuffer.PStop; DFStopStatus.Value := ABuffer.PStopStatus; DFUserID.Value := ABuffer.PUserID; DFDescription.Value := ABuffer.PDescription; DFReportDate.Value := ABuffer.PReportDate; DFTitle.Value := ABuffer.PTitle; DFFromDate.Value := ABuffer.PFromDate; DFToDate.Value := ABuffer.PToDate; DFReportProcessed.Value := ABuffer.PReportProcessed; DFReportFileName.Value := ABuffer.PReportFileName; DFDataIncluded.Value := ABuffer.PDataIncluded; DFUsingWhichDate.Value := ABuffer.PUsingWhichDate; DFSortOrder.Value := ABuffer.PSortOrder; DFGroupedby.Value := ABuffer.PGroupedby; DFRepro.Value := ABuffer.PRepro; DFOpenClaims.Value := ABuffer.POpenClaims; DFStatementDate.Value := ABuffer.PStatementDate; DFBeginningWith.Value := ABuffer.PBeginningWith; DFPrintZero.Value := ABuffer.PPrintZero; DFPrintNotes.Value := ABuffer.PPrintNotes; DFStmtYrMo.Value := ABuffer.PStmtYrMo; DFFeedback.Value := ABuffer.PFeedback; DFRptType.Value := ABuffer.PRptType; DFDestination.Value := ABuffer.PDestination; DFSummaryOnlyFlag.Value := ABuffer.PSummaryOnlyFlag; end; function TInfoRPTRUNTable.GetEnumIndex: TEIInfoRPTRUN; var iname : string; begin result := InfoRPTRUNPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoRPTRUNPrimaryKey; if iname = 'LENDERREPORT' then result := InfoRPTRUNLenderReport; end; function TInfoRPTRUNQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoRPTRUNQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoRPTRUNQuery.GenerateNewFieldName } function TInfoRPTRUNQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoRPTRUNQuery.CreateField } procedure TInfoRPTRUNQuery.CreateFields; begin FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField; FDFReportID := CreateField( 'ReportID' ) as TAutoIncField; FDFControlStatus := CreateField( 'ControlStatus' ) as TStringField; FDFStart := CreateField( 'Start' ) as TStringField; FDFStop := CreateField( 'Stop' ) as TStringField; FDFStopStatus := CreateField( 'StopStatus' ) as TStringField; FDFUserID := CreateField( 'UserID' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFReportDate := CreateField( 'ReportDate' ) as TStringField; FDFTitle := CreateField( 'Title' ) as TStringField; FDFFromDate := CreateField( 'FromDate' ) as TStringField; FDFToDate := CreateField( 'ToDate' ) as TStringField; FDFLenderGroup := CreateField( 'LenderGroup' ) as TBlobField; FDFCompanyString := CreateField( 'CompanyString' ) as TBlobField; FDFLenderString := CreateField( 'LenderString' ) as TBlobField; FDFPrefixString := CreateField( 'PrefixString' ) as TBlobField; FDFPolicyString := CreateField( 'PolicyString' ) as TBlobField; FDFClaimString := CreateField( 'ClaimString' ) as TBlobField; FDFLossCodeString := CreateField( 'LossCodeString' ) as TBlobField; FDFTranTypeString := CreateField( 'TranTypeString' ) as TBlobField; FDFSettlementMethodString := CreateField( 'SettlementMethodString' ) as TBlobField; FDFAdjusterString := CreateField( 'AdjusterString' ) as TBlobField; FDFClaimTrackString := CreateField( 'ClaimTrackString' ) as TBlobField; FDFTranTrackString := CreateField( 'TranTrackString' ) as TBlobField; FDFTranStatusString := CreateField( 'TranStatusString' ) as TBlobField; FDFReportProcessed := CreateField( 'ReportProcessed' ) as TBooleanField; FDFReportFileName := CreateField( 'ReportFileName' ) as TStringField; FDFDataIncluded := CreateField( 'DataIncluded' ) as TIntegerField; FDFUsingWhichDate := CreateField( 'UsingWhichDate' ) as TIntegerField; FDFSortOrder := CreateField( 'SortOrder' ) as TIntegerField; FDFGroupedby := CreateField( 'Groupedby' ) as TIntegerField; FDFRepro := CreateField( 'Repro' ) as TIntegerField; FDFOpenClaims := CreateField( 'OpenClaims' ) as TIntegerField; FDFStatementDate := CreateField( 'StatementDate' ) as TIntegerField; FDFBeginningWith := CreateField( 'BeginningWith' ) as TIntegerField; FDFPrintZero := CreateField( 'PrintZero' ) as TIntegerField; FDFPrintNotes := CreateField( 'PrintNotes' ) as TIntegerField; FDFStmtYrMo := CreateField( 'StmtYrMo' ) as TStringField; FDFFeedback := CreateField( 'Feedback' ) as TStringField; FDFRptType := CreateField( 'RptType' ) as TIntegerField; FDFDestination := CreateField( 'Destination' ) as TStringField; FDFSummaryOnlyFlag := CreateField( 'SummaryOnlyFlag' ) as TBooleanField; end; { TInfoRPTRUNQuery.CreateFields } procedure TInfoRPTRUNQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoRPTRUNQuery.SetActive } procedure TInfoRPTRUNQuery.SetPLenderNumber(const Value: String); begin DFLenderNumber.Value := Value; end; function TInfoRPTRUNQuery.GetPLenderNumber:String; begin result := DFLenderNumber.Value; end; procedure TInfoRPTRUNQuery.SetPControlStatus(const Value: String); begin DFControlStatus.Value := Value; end; function TInfoRPTRUNQuery.GetPControlStatus:String; begin result := DFControlStatus.Value; end; procedure TInfoRPTRUNQuery.SetPStart(const Value: String); begin DFStart.Value := Value; end; function TInfoRPTRUNQuery.GetPStart:String; begin result := DFStart.Value; end; procedure TInfoRPTRUNQuery.SetPStop(const Value: String); begin DFStop.Value := Value; end; function TInfoRPTRUNQuery.GetPStop:String; begin result := DFStop.Value; end; procedure TInfoRPTRUNQuery.SetPStopStatus(const Value: String); begin DFStopStatus.Value := Value; end; function TInfoRPTRUNQuery.GetPStopStatus:String; begin result := DFStopStatus.Value; end; procedure TInfoRPTRUNQuery.SetPUserID(const Value: String); begin DFUserID.Value := Value; end; function TInfoRPTRUNQuery.GetPUserID:String; begin result := DFUserID.Value; end; procedure TInfoRPTRUNQuery.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoRPTRUNQuery.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoRPTRUNQuery.SetPReportDate(const Value: String); begin DFReportDate.Value := Value; end; function TInfoRPTRUNQuery.GetPReportDate:String; begin result := DFReportDate.Value; end; procedure TInfoRPTRUNQuery.SetPTitle(const Value: String); begin DFTitle.Value := Value; end; function TInfoRPTRUNQuery.GetPTitle:String; begin result := DFTitle.Value; end; procedure TInfoRPTRUNQuery.SetPFromDate(const Value: String); begin DFFromDate.Value := Value; end; function TInfoRPTRUNQuery.GetPFromDate:String; begin result := DFFromDate.Value; end; procedure TInfoRPTRUNQuery.SetPToDate(const Value: String); begin DFToDate.Value := Value; end; function TInfoRPTRUNQuery.GetPToDate:String; begin result := DFToDate.Value; end; procedure TInfoRPTRUNQuery.SetPReportProcessed(const Value: Boolean); begin DFReportProcessed.Value := Value; end; function TInfoRPTRUNQuery.GetPReportProcessed:Boolean; begin result := DFReportProcessed.Value; end; procedure TInfoRPTRUNQuery.SetPReportFileName(const Value: String); begin DFReportFileName.Value := Value; end; function TInfoRPTRUNQuery.GetPReportFileName:String; begin result := DFReportFileName.Value; end; procedure TInfoRPTRUNQuery.SetPDataIncluded(const Value: Integer); begin DFDataIncluded.Value := Value; end; function TInfoRPTRUNQuery.GetPDataIncluded:Integer; begin result := DFDataIncluded.Value; end; procedure TInfoRPTRUNQuery.SetPUsingWhichDate(const Value: Integer); begin DFUsingWhichDate.Value := Value; end; function TInfoRPTRUNQuery.GetPUsingWhichDate:Integer; begin result := DFUsingWhichDate.Value; end; procedure TInfoRPTRUNQuery.SetPSortOrder(const Value: Integer); begin DFSortOrder.Value := Value; end; function TInfoRPTRUNQuery.GetPSortOrder:Integer; begin result := DFSortOrder.Value; end; procedure TInfoRPTRUNQuery.SetPGroupedby(const Value: Integer); begin DFGroupedby.Value := Value; end; function TInfoRPTRUNQuery.GetPGroupedby:Integer; begin result := DFGroupedby.Value; end; procedure TInfoRPTRUNQuery.SetPRepro(const Value: Integer); begin DFRepro.Value := Value; end; function TInfoRPTRUNQuery.GetPRepro:Integer; begin result := DFRepro.Value; end; procedure TInfoRPTRUNQuery.SetPOpenClaims(const Value: Integer); begin DFOpenClaims.Value := Value; end; function TInfoRPTRUNQuery.GetPOpenClaims:Integer; begin result := DFOpenClaims.Value; end; procedure TInfoRPTRUNQuery.SetPStatementDate(const Value: Integer); begin DFStatementDate.Value := Value; end; function TInfoRPTRUNQuery.GetPStatementDate:Integer; begin result := DFStatementDate.Value; end; procedure TInfoRPTRUNQuery.SetPBeginningWith(const Value: Integer); begin DFBeginningWith.Value := Value; end; function TInfoRPTRUNQuery.GetPBeginningWith:Integer; begin result := DFBeginningWith.Value; end; procedure TInfoRPTRUNQuery.SetPPrintZero(const Value: Integer); begin DFPrintZero.Value := Value; end; function TInfoRPTRUNQuery.GetPPrintZero:Integer; begin result := DFPrintZero.Value; end; procedure TInfoRPTRUNQuery.SetPPrintNotes(const Value: Integer); begin DFPrintNotes.Value := Value; end; function TInfoRPTRUNQuery.GetPPrintNotes:Integer; begin result := DFPrintNotes.Value; end; procedure TInfoRPTRUNQuery.SetPStmtYrMo(const Value: String); begin DFStmtYrMo.Value := Value; end; function TInfoRPTRUNQuery.GetPStmtYrMo:String; begin result := DFStmtYrMo.Value; end; procedure TInfoRPTRUNQuery.SetPFeedback(const Value: String); begin DFFeedback.Value := Value; end; function TInfoRPTRUNQuery.GetPFeedback:String; begin result := DFFeedback.Value; end; procedure TInfoRPTRUNQuery.SetPRptType(const Value: Integer); begin DFRptType.Value := Value; end; function TInfoRPTRUNQuery.GetPRptType:Integer; begin result := DFRptType.Value; end; procedure TInfoRPTRUNQuery.SetPDestination(const Value: String); begin DFDestination.Value := Value; end; function TInfoRPTRUNQuery.GetPDestination:String; begin result := DFDestination.Value; end; procedure TInfoRPTRUNQuery.SetPSummaryOnlyFlag(const Value: Boolean); begin DFSummaryOnlyFlag.Value := Value; end; function TInfoRPTRUNQuery.GetPSummaryOnlyFlag:Boolean; begin result := DFSummaryOnlyFlag.Value; end; function TInfoRPTRUNQuery.GetDataBuffer:TInfoRPTRUNRecord; var buf: TInfoRPTRUNRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNumber := DFLenderNumber.Value; buf.PReportID := DFReportID.Value; buf.PControlStatus := DFControlStatus.Value; buf.PStart := DFStart.Value; buf.PStop := DFStop.Value; buf.PStopStatus := DFStopStatus.Value; buf.PUserID := DFUserID.Value; buf.PDescription := DFDescription.Value; buf.PReportDate := DFReportDate.Value; buf.PTitle := DFTitle.Value; buf.PFromDate := DFFromDate.Value; buf.PToDate := DFToDate.Value; buf.PReportProcessed := DFReportProcessed.Value; buf.PReportFileName := DFReportFileName.Value; buf.PDataIncluded := DFDataIncluded.Value; buf.PUsingWhichDate := DFUsingWhichDate.Value; buf.PSortOrder := DFSortOrder.Value; buf.PGroupedby := DFGroupedby.Value; buf.PRepro := DFRepro.Value; buf.POpenClaims := DFOpenClaims.Value; buf.PStatementDate := DFStatementDate.Value; buf.PBeginningWith := DFBeginningWith.Value; buf.PPrintZero := DFPrintZero.Value; buf.PPrintNotes := DFPrintNotes.Value; buf.PStmtYrMo := DFStmtYrMo.Value; buf.PFeedback := DFFeedback.Value; buf.PRptType := DFRptType.Value; buf.PDestination := DFDestination.Value; buf.PSummaryOnlyFlag := DFSummaryOnlyFlag.Value; result := buf; end; procedure TInfoRPTRUNQuery.StoreDataBuffer(ABuffer:TInfoRPTRUNRecord); begin DFLenderNumber.Value := ABuffer.PLenderNumber; DFControlStatus.Value := ABuffer.PControlStatus; DFStart.Value := ABuffer.PStart; DFStop.Value := ABuffer.PStop; DFStopStatus.Value := ABuffer.PStopStatus; DFUserID.Value := ABuffer.PUserID; DFDescription.Value := ABuffer.PDescription; DFReportDate.Value := ABuffer.PReportDate; DFTitle.Value := ABuffer.PTitle; DFFromDate.Value := ABuffer.PFromDate; DFToDate.Value := ABuffer.PToDate; DFReportProcessed.Value := ABuffer.PReportProcessed; DFReportFileName.Value := ABuffer.PReportFileName; DFDataIncluded.Value := ABuffer.PDataIncluded; DFUsingWhichDate.Value := ABuffer.PUsingWhichDate; DFSortOrder.Value := ABuffer.PSortOrder; DFGroupedby.Value := ABuffer.PGroupedby; DFRepro.Value := ABuffer.PRepro; DFOpenClaims.Value := ABuffer.POpenClaims; DFStatementDate.Value := ABuffer.PStatementDate; DFBeginningWith.Value := ABuffer.PBeginningWith; DFPrintZero.Value := ABuffer.PPrintZero; DFPrintNotes.Value := ABuffer.PPrintNotes; DFStmtYrMo.Value := ABuffer.PStmtYrMo; DFFeedback.Value := ABuffer.PFeedback; DFRptType.Value := ABuffer.PRptType; DFDestination.Value := ABuffer.PDestination; DFSummaryOnlyFlag.Value := ABuffer.PSummaryOnlyFlag; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoRPTRUNTable, TInfoRPTRUNQuery, TInfoRPTRUNBuffer ] ); end; { Register } function TInfoRPTRUNBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..29] of string = ('LENDERNUMBER','REPORTID','CONTROLSTATUS','START','STOP','STOPSTATUS' ,'USERID','DESCRIPTION','REPORTDATE','TITLE','FROMDATE' ,'TODATE','REPORTPROCESSED' ,'REPORTFILENAME','DATAINCLUDED','USINGWHICHDATE','SORTORDER','GROUPEDBY' ,'REPRO','OPENCLAIMS','STATEMENTDATE','BEGINNINGWITH','PRINTZERO' ,'PRINTNOTES','STMTYRMO','FEEDBACK','RPTTYPE','DESTINATION' ,'SUMMARYONLYFLAG' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 29) and (flist[x] <> s) do inc(x); if x <= 29 then result := x else result := 0; end; function TInfoRPTRUNBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftAutoInc; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftString; 8 : result := ftString; 9 : result := ftString; 10 : result := ftString; 11 : result := ftString; 12 : result := ftString; 13 : result := ftBoolean; 14 : result := ftString; 15 : result := ftInteger; 16 : result := ftInteger; 17 : result := ftInteger; 18 : result := ftInteger; 19 : result := ftInteger; 20 : result := ftInteger; 21 : result := ftInteger; 22 : result := ftInteger; 23 : result := ftInteger; 24 : result := ftInteger; 25 : result := ftString; 26 : result := ftString; 27 : result := ftInteger; 28 : result := ftString; 29 : result := ftBoolean; end; end; function TInfoRPTRUNBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNumber; 2 : result := @Data.PReportID; 3 : result := @Data.PControlStatus; 4 : result := @Data.PStart; 5 : result := @Data.PStop; 6 : result := @Data.PStopStatus; 7 : result := @Data.PUserID; 8 : result := @Data.PDescription; 9 : result := @Data.PReportDate; 10 : result := @Data.PTitle; 11 : result := @Data.PFromDate; 12 : result := @Data.PToDate; 13 : result := @Data.PReportProcessed; 14 : result := @Data.PReportFileName; 15 : result := @Data.PDataIncluded; 16 : result := @Data.PUsingWhichDate; 17 : result := @Data.PSortOrder; 18 : result := @Data.PGroupedby; 19 : result := @Data.PRepro; 20 : result := @Data.POpenClaims; 21 : result := @Data.PStatementDate; 22 : result := @Data.PBeginningWith; 23 : result := @Data.PPrintZero; 24 : result := @Data.PPrintNotes; 25 : result := @Data.PStmtYrMo; 26 : result := @Data.PFeedback; 27 : result := @Data.PRptType; 28 : result := @Data.PDestination; 29 : result := @Data.PSummaryOnlyFlag; end; end; end.
//////////////////////////////////////////////////////////////////////////////// // TrakceErrors.pas: Error codes definiton //////////////////////////////////////////////////////////////////////////////// { LICENSE: Copyright 2019-2020 Jan Horacek 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. } { DESCRIPTION: This file defines library error codes. It is necessary to keep this file synced with actual library error codes! } unit TrakceErrors; interface uses SysUtils; const TRK_FILE_CANNOT_ACCESS = 1010; TRK_FILE_DEVICE_OPENED = 1011; TRK_ALREADY_OPENNED = 2001; TRK_CANNOT_OPEN_PORT = 2002; TRK_NOT_OPENED = 2011; TRK_UNSUPPORTED_API_VERSION = 4000; type TrkException = class(Exception); ETrkGeneralException = class(TrkException) public constructor Create(); end; ETrkAlreadyOpened = class(TrkException); ETrkCannotOpenPort = class(TrkException); ETrkNotOpened = class(TrkException); ETrkFuncNotAssigned = class(TrkException); ETrkLibNotFound = class(TrkException); ETrkCannotLoadLib = class(TrkException); ETrkNoLibLoaded = class(TrkException); ETrkUnsupportedApiVersion = class(TrkException); ETrkCannotAccessFile = class(TrkException); ETrkDeviceOpened = class(TrkException); implementation constructor ETrkGeneralException.Create(); begin inherited Create('General exception in Trakce library!'); end; end.
unit DataServIntf; interface type ICustomData = interface (IInvokable) ['{890B77BE-661E-4301-8A29-0B8274D27116}'] function GetData: string; stdcall; function SendDelta (Delta: string): Boolean; end; implementation uses InvokeRegistry; initialization InvRegistry.RegisterInterface(TypeInfo(ICustomData)); end.
unit TCPSocket_Lazarus; interface uses Sysutils, RTLConsts, StatusThread, Classes, SyncObjs, sockets; {$M+} const INVALID_SOCKET = -1; SOCKET_ERROR = -1; type TSocket = Longint; TTCPHost = record IP: String; Port: Word; end; TSimpleTCPSocket = class private function GetPeerName: AnsiString; protected FSocket: TSocket; FConnected: Boolean; procedure Error(Source: string); public function ReceiveBuf(var Buf; Size: Word): Integer; {function ReceiveLength: Integer;} function SendBuf(var Buf; Size: Word): Integer; constructor Create(Socket: TSocket = INVALID_SOCKET); procedure Close; destructor Destroy; override; function Accept: TSocket; procedure Bind(Port: Word); function Connect(IP: String; Port: Word): boolean; function RemoteHost: TTCPHost; procedure Listen; function Connected: Boolean; function SelectWrite(Timeout: Word): Boolean; end; TTCPSocket = class(TSimpleTCPSocket) public procedure ReceiveBuf(var Buf; Size: Word); procedure SendBuf(var Buf; Size: Word); end; TSimpleServerClientConnect = procedure(Sender: TObject; newSocket: TSocket) of object; TSimpleServer = class(TSThread) private NewSocket: TSocket; FServerPort: Integer; FServerActive: Boolean; Started: TEvent; procedure DoOnClientConnect; virtual; public ListenSocket: TTCPSocket; OnClientConnect: TSimpleServerClientConnect; property ServerPort: Integer read FServerPort; procedure Execute; override; function Start(Port: Integer): Boolean; procedure Stop; destructor Destroy; override; constructor Create; //ListenSocket, Aktiviert wenn Server aktiv (s. StartServer, StopServer) end; TSimpleServerComponent = class(TComponent) private FOnClientConnect: TSimpleServerClientConnect; procedure SetOnClientConnect(p: TSimpleServerClientConnect); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published SimpleServer: TSimpleServer; property OnClientConnect: TSimpleServerClientConnect read FOnClientConnect write SetOnClientConnect; end; {function GetHostByName(Host: String): in_addr;} procedure Register; implementation procedure Startup; begin //Nothing!!! end; function TSimpleTCPSocket.GetPeerName: AnsiString; var l: Longint; begin Setlength(Result,255); l := 255; if Sockets.GetPeerName(FSocket,PChar(Result)^,l) <> 0 then Error('GetPeerName'); end; function TSimpleTCPSocket.Accept: TSocket; var SAddr: TInetSockAddr; begin FillChar(SAddr,Sizeof(SAddr),0); Result := sockets.accept(FSocket,SAddr,Sizeof(SAddr)); if Result = INVALID_SOCKET then Error('Accept'); end; procedure TSimpleTCPSocket.Bind(Port: Word); var SAddr: TInetSockAddr; begin //vor listen aufzurufen! SAddr.sin_family:=AF_INET; SAddr.sin_port:=htons(Port); SAddr.sin_addr.s_addr:=INADDR_ANY; if not sockets.Bind(FSocket,SAddr,sizeof(SAddr)) then Error('Bind'); end; procedure TSimpleTCPSocket.Close; begin FConnected := False; closesocket(FSocket); end; function TSimpleTCPSocket.Connect(IP: String; Port: Word): boolean; var sockaddr: TInetSockAddr; begin sockaddr.sin_family := AF_INET; sockaddr.sin_port := htons(Port); sockaddr.sin_addr := StrToHostAddr(IP); if sockaddr.sin_addr.S_addr = -1 then sockaddr.sin_addr := Sockets.StrToHostAddr(IP); if not(sockets.connect(FSocket,sockaddr,sizeof(sockaddr))) then Error('Connect') else FConnected := True; Result := FConnected; end; function TSimpleTCPSocket.Connected: Boolean; begin Result := FConnected; if Result then GetPeerName; //-> das müsste ja dann gehen!? (wenn nicht is er nichtmehr verbunden!) end; constructor TSimpleTCPSocket.Create(Socket: TSocket = INVALID_SOCKET); begin inherited Create; Startup; FSocket := Socket; FConnected := False; if FSocket = INVALID_SOCKET then begin FSocket := Sockets.Socket(AF_INET,SOCK_STREAM,0); if FSocket = INVALID_SOCKET then Error('Create'); end else FConnected := True; end; destructor TSimpleTCPSocket.Destroy; begin Close; inherited; end; procedure TSimpleTCPSocket.Error(Source: string); var ErrorCode: Integer; begin ErrorCode := Sockets.SocketError; if ErrorCode <> 0 then begin Close; raise Exception.Create((SysErrorMessage(ErrorCode) + ' (' + inttostr(ErrorCode) + ') API: ' + Source)); end; end; procedure TSimpleTCPSocket.Listen; var r: Integer; begin if not sockets.listen(FSocket,1) then Error('Listen'); end; function TSimpleTCPSocket.ReceiveBuf(var Buf; Size: Word): Integer; begin if not FConnected then raise Exception.Create('API: ReceiveBuf, Socket nicht verbunden!'); Result := sockets.recv(FSocket, Buf, Size, 0); if (Result = SOCKET_ERROR) then Error('ReceiveBuf'); if Result = 0 then Close; end; {function TSimpleTCPSocket.ReceiveLength: Integer; begin Result := 0; if FConnected then if ioctlsocket(FSocket, FIONREAD, Longint(Result)) = SOCKET_ERROR then Error('ReceiveLength'); end; } function TSimpleTCPSocket.RemoteHost: TTCPHost; begin Result.IP := GetPeerName; Result.Port := 0; end; function TSimpleTCPSocket.SelectWrite(Timeout: Word): Boolean; begin Result := True; //Geht mit lazarus nich, also: einfach immer JA! //Weis eh nicht obs das ganze hier gebracht hat!! end; function TSimpleTCPSocket.SendBuf(var Buf; Size: Word): Integer; begin if not FConnected then raise Exception.Create('API: SendBuf, Socket nicht verbunden!'); Result := send(FSocket, Buf, Size, 0); if Result = SOCKET_ERROR then Error('SendBuf'); end; {function GetHostByName(Host: String): in_addr; var hostaddr: PHostEnt; begin hostaddr := winsock.gethostbyname(Pchar(Host)); if hostaddr <> nil then Result := PInAddr(hostaddr^.h_addr^)^ else Result.S_addr := -1; end;} procedure TTCPSocket.ReceiveBuf(var Buf; Size: Word); var ReadPos,ReadCount: Word; ReadPointer: Pointer; begin ReadPos := 0; repeat ReadPointer := Pointer(Cardinal(@Buf) + ReadPos); ReadCount := inherited ReceiveBuf(ReadPointer^,Size-ReadPos); ReadPos := ReadPos + ReadCount; until (not FConnected)or(ReadPos = Size); end; procedure TTCPSocket.SendBuf(var Buf; Size: Word); var SendPos,SendCount: Word; SendPointer: Pointer; begin SendPos := 0; repeat SendPointer := Pointer(Cardinal(@Buf) + SendPos); SendCount := inherited SendBuf(SendPointer^,Size-SendPos); SendPos := SendPos + SendCount; until (not FConnected)or(SendPos = Size); end; procedure TSimpleServer.Stop; begin FServerActive := False; if ListenSocket <> nil then ListenSocket.Close; end; function TSimpleServer.Start(Port: Integer): Boolean; begin if FServerActive then raise Exception.Create('TSimpleServer.Start: Server Already Started!'); FServerPort := Port; FServerActive := True; Started.ResetEvent; Resume; Result := (Started.WaitFor(high(Cardinal)) = wrSignaled)and(FServerActive); end; procedure TSimpleServer.Execute; begin inherited; ReturnValue := STILL_ACTIVE; Status := 'Started...'; while not Terminated do begin if FServerActive then begin ListenSocket := TTCPSocket.Create; try ListenSocket.Bind(FServerPort); ListenSocket.Listen; Started.SetEvent; while (not Terminated)and(FServerActive) do begin Status := 'Listening...'; NewSocket := ListenSocket.Accept; if NewSocket <> INVALID_SOCKET then begin Status := 'Notifying new client'; if Assigned(OnClientConnect) then try Synchronize(@DoOnClientConnect); except on E: Exception do begin Status := 'Exception while notifying new client in ' + Name + ':' + E.Message + ' (' + E.ClassName + ')'; end; end; end; Sleep(100); end; except on E: Exception do begin Status := 'Exception while listening in ' + Name + ':' + E.Message + ' (' + E.ClassName + ') -> Server Paused'; FServerActive := False; Started.SetEvent; end; end; ListenSocket.Free; end //If FServerActive then else begin Status := 'Paused'; Suspend; end; end; Status := 'Stopped'; ReturnValue := 0; end; procedure TSimpleServer.DoOnClientConnect; begin OnClientConnect(Self,NewSocket); end; destructor TSimpleServer.Destroy; begin Terminate; if FServerActive then begin FServerActive := False; ListenSocket.Close; end; Resume; if ReturnValue = STILL_ACTIVE then WaitFor; Started.Free; inherited; end; constructor TSimpleServer.Create; begin inherited Create(False); FServerActive := False; FreeOnTerminate := False; Started := TEvent.Create(nil,True,False,''); end; procedure Register; begin RegisterComponents('nice things', [TSimpleServerComponent]); end; constructor TSimpleServerComponent.Create(AOwner: TComponent); begin inherited; SimpleServer := TSimpleServer.Create; end; destructor TSimpleServerComponent.Destroy; begin SimpleServer.Free; inherited; end; procedure TSimpleServerComponent.SetOnClientConnect( p: TSimpleServerClientConnect); begin SimpleServer.OnClientConnect := p; FOnClientConnect := p; end; end.
unit TTSPENDTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSPENDRecord = record PLenderNum: String[4]; PCifFlag: String[1]; PLoanNum: String[20]; PCollNum: Integer; End; TTTSPENDBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSPENDRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSPEND = (TTSPENDPrimaryKey); TTTSPENDTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFCollNum: TIntegerField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetEnumIndex(Value: TEITTSPEND); function GetEnumIndex: TEITTSPEND; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSPENDRecord; procedure StoreDataBuffer(ABuffer:TTTSPENDRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TIntegerField read FDFCollNum; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: Integer read GetPCollNum write SetPCollNum; published property Active write SetActive; property EnumIndex: TEITTSPEND read GetEnumIndex write SetEnumIndex; end; { TTTSPENDTable } procedure Register; implementation procedure TTTSPENDTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; end; { TTTSPENDTable.CreateFields } procedure TTTSPENDTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSPENDTable.SetActive } procedure TTTSPENDTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSPENDTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSPENDTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSPENDTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSPENDTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSPENDTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSPENDTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSPENDTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSPENDTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('CollNum, Integer, 0, N'); end; end; procedure TTTSPENDTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CifFlag;LoanNum;CollNum, Y, Y, N, N'); end; end; procedure TTTSPENDTable.SetEnumIndex(Value: TEITTSPEND); begin case Value of TTSPENDPrimaryKey : IndexName := ''; end; end; function TTTSPENDTable.GetDataBuffer:TTTSPENDRecord; var buf: TTTSPENDRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCollNum := DFCollNum.Value; result := buf; end; procedure TTTSPENDTable.StoreDataBuffer(ABuffer:TTTSPENDRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFCollNum.Value := ABuffer.PCollNum; end; function TTTSPENDTable.GetEnumIndex: TEITTSPEND; var iname : string; begin result := TTSPENDPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSPENDPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSPENDTable, TTTSPENDBuffer ] ); end; { Register } function TTTSPENDBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..4] of string = ('LENDERNUM','CIFFLAG','LOANNUM','COLLNUM' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 4) and (flist[x] <> s) do inc(x); if x <= 4 then result := x else result := 0; end; function TTTSPENDBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; end; end; function TTTSPENDBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCifFlag; 3 : result := @Data.PLoanNum; 4 : result := @Data.PCollNum; end; end; end.
{ Function SST_TERM_SIMPLE(TERM) * * Returns TRUE if the term is "simple". This means no computes are needed * to evaluate it, other than just to go fetch its value. } module sst_TERM_SIMPLE; define sst_term_simple; %include 'sst2.ins.pas'; function sst_term_simple ( {check for term is simple/complicated} in term: sst_exp_term_t) {term descriptor to check} : boolean; {TRUE if no computes needed to evaluate term} const max_msg_parms = 1; {max parameters we can pass to a message} var ele_p: sst_ele_exp_p_t; {points to current set element descriptor} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin sst_term_simple := false; {init to term is not simple} if {unary operator and term not a constant ?} (term.ttype <> sst_term_const_k) and (term.op1 <> sst_op1_none_k) then return; case term.ttype of {what kind of term is it ?} sst_term_const_k: ; sst_term_var_k: begin case term.var_var_p^.vtype of {what kind of var descriptor is this ?} sst_vtype_var_k: ; sst_vtype_dtype_k: ; sst_vtype_rout_k: ; sst_vtype_const_k: ; sst_vtype_com_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(term.var_var_p^.vtype)); sys_message_bomb ('sst', 'vtype_unexpected', msg_parm, 1); end; end; sst_term_type_k: begin {term is a type-transfer function} sst_term_simple := sst_exp_simple(term.type_exp_p^); {process nested exp} return; end; sst_term_set_k: begin ele_p := term.set_first_p; {set curr set element to first set element} while ele_p <> nil do begin {once for each set element} if not sst_exp_simple(ele_p^.first_p^) then return; if ele_p^.last_p <> nil then begin if not sst_exp_simple(ele_p^.last_p^) then return; end; ele_p := ele_p^.next_p; {advance to next set element descriptor} end; {back and process this next set element} end; sst_term_exp_k: begin sst_term_simple := sst_exp_simple(term.exp_exp_p^); {process nested exp} return; end; sst_term_func_k, sst_term_ifunc_k, sst_term_field_k, sst_term_arele_k: return; otherwise sys_msg_parm_int (msg_parm[1], ord(term.ttype)); syo_error (term.str_h, 'sst', 'term_type_unknown', msg_parm, 1); end; sst_term_simple := true; {we now know that expression is simple} end;
UNIT BinaryTree; INTERFACE TYPE Tree = ^Node; Node = RECORD Word: STRING; //поле ячейки, содержит в себе слово-символы Counter: INTEGER; //счётчик, показывает, кол-во одинаково обработанных Word при вставке в дерево Left, Right: Tree //указатели в бинарном дереве END; PROCEDURE Insert(VAR Pointer: Tree; Word: STRING); { Вставляет слово Word в бинарное дерево } PROCEDURE PrintTree(Pointer: Tree; VAR DataFile: TEXT); { Печатает бинарное дерево в DataFile } IMPLEMENTATION CONST MaxWordAmount = MAXINT; VAR MaxWordLength, WordAmount: INTEGER; PROCEDURE Insert(VAR Pointer: Tree; Word: STRING); { Кладёт слово в бинарное дерево } //Требуется знать устройтсво бинарного дерева!// BEGIN { Insert } IF WordAmount <= MaxWordAmount THEN IF Pointer = NIL THEN BEGIN NEW(Pointer); Pointer^.Word := Word; Pointer^.Counter := 1; Pointer^.Left := NIL; Pointer^.Right := NIL; WordAmount := WordAmount + 1 // END ELSE BEGIN IF Pointer^.Word > Word THEN Insert(Pointer^.Left, Word); IF Pointer^.Word < Word THEN Insert(Pointer^.Right, Word); { Слово уже есть в дереве? Тогда просто увеличить счётчик на 1, без вставки в дерево } IF Pointer^.Word = Word THEN Pointer^.Counter := Pointer^.Counter + 1 END ELSE WRITE('Word amount limit - ', MaxWordAmount, ' - has reached'); END; { Insert } CONST MaxWordSize = 100; PROCEDURE WriteWordStatistic(Pointer: Tree; VAR DataFile: TEXT); { Печатает слово и его счётчик отформатированно, в зависимости от длины слова } VAR BlankSize: INTEGER; BEGIN WRITE(DataFile, Pointer^.Word); IF Length(Pointer^.Word) < MaxWordSize THEN BEGIN BlankSize := MaxWordSize - Length(Pointer^.Word); WHILE BlankSize <> 0 DO BEGIN WRITE(DataFile, ' '); BlankSize := BlankSize - 1 END END ELSE WRITE(DataFile, ' '); WRITELN(DataFile, Pointer^.Counter) END; PROCEDURE PrintTree(Pointer: Tree; VAR DataFile: TEXT); { Печать бинарного дерева } BEGIN { PrintTree } IF Pointer <> NIL THEN BEGIN PrintTree(Pointer^.Left, DataFile); { Pointer^.Word = '' - пробел, если хочешь отобразить кол-во пробелов в тексте - убери условие } IF Pointer^.Word <> '' THEN WriteWordStatistic(Pointer, DataFile); PrintTree(Pointer^.Right, DataFile); END END; { PrintTree } BEGIN { InsertTree } WordAmount := 0 END. { InsertTree }
unit uDM; interface uses SysUtils, Classes, uClassDef, DB, ADODB, Inifiles, Forms, Dialogs; // Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; const ConstIniSectionSetUp = 'SETUP'; ConstIniKeyConnString = 'ConnectionString'; type TDM = class(TDataModule) Con: TADOConnection; qryInsertRange: TADOQuery; qryInsertRangeElement: TADOQuery; qryInsertRangeSubElement: TADOQuery; qryDeleteRange: TADOQuery; qryDeleteRangeElement: TADOQuery; qryDeleteRangeSubElement: TADOQuery; qryGetRange: TADOQuery; qryGetRangeElement: TADOQuery; qryGetRangeSubElement: TADOQuery; procedure DataModuleCreate(Sender: TObject); private { Private declarations } function GetConnectionString:string; function SaveRangeToDB(ARange:TRange):Boolean; function SaveRangeElementToDB(const RangeId:Integer; ARangeElement:TRangeElement):Boolean; function SaveRangeSubElementToDB(const RangeId:Integer; const ElementId:Integer; ARangeSubElement:TRangeElement):Boolean; procedure LoadRangeElementFromDB(ARange: TRange); procedure LoadRangeSubElementFromDB(ARange:TRange; ARangeElement:TRangeElement); public { Public declarations } function ConnectToDB():Boolean; function IsDBConnected():Boolean; procedure SaveToDB(ARangeList:TRangeList); function LoadFromDB():TRangeList; function CleanDB():Boolean; end; var DM: TDM; implementation {$R *.dfm} { TDataModule1 } { TDataModule1 } //Method to Save List of Ranges to Database. //This method calls individual method for Range, RagneElement & RangeSubElement procedure TDM.SaveToDB(ARangeList: TRangeList); var I:Integer; begin CleanDB(); //Clean Existing Data for I:=0 to ARangeList.Count-1 do begin Con.BeginTrans(); if SaveRangeToDB(ARangeList[I]) then Con.CommitTrans() else Con.RollbackTrans(); end; end; //Method to save Individual Ranges to Database. //This method internally calls method to save RangeElement function TDM.SaveRangeToDB(ARange: TRange):Boolean; var I:Integer; SQL:string; begin Result := True; try qryInsertRange.Close(); qryInsertRange.Parameters.ParamByName('RangeID').Value := ARange.Id; qryInsertRange.Parameters.ParamByName('Description').Value := ARange.Description; qryInsertRange.ExecSQL(); for I:=0 to ARange.Elements.Count-1 do begin Result := SaveRangeElementToDB(ARange.Id, ARange.Elements[I]); if (not Result) then Exit; end; except Result := False; end; end; //Method to save Individual RangeElement to Database. //This method internally calls method to save RangeSubElement function TDM.SaveRangeElementToDB(const RangeId:Integer; ARangeElement: TRangeElement):Boolean; var I:Integer; SQL:string; begin Result := True; try qryInsertRangeElement.Close(); qryInsertRangeElement.Parameters.ParamByName('RangeID').Value := RangeId; qryInsertRangeElement.Parameters.ParamByName('ElementID').Value := ARangeElement.Id; qryInsertRangeElement.Parameters.ParamByName('Quantity').Value := ARangeElement.Quantity; qryInsertRangeElement.ExecSQL(); for I:=0 to ARangeElement.SubElements.Count-1 do begin Result := SaveRangeSubElementToDB(RangeId, ARangeElement.Id, ARangeElement.SubElements[I]); if not Result then Exit; end; except Result := False; end; end; //Method to save Individual RangeSubElement to Database. function TDM.SaveRangeSubElementToDB(const RangeId:Integer; const ElementId:Integer; ARangeSubElement: TRangeElement):Boolean; var I:Integer; SQL:string; begin Result := True; try qryInsertRangeSubElement.Close(); qryInsertRangeSubElement.Parameters.ParamByName('RangeID').Value := RangeId; qryInsertRangeSubElement.Parameters.ParamByName('ElementID').Value := ElementId; qryInsertRangeSubElement.Parameters.ParamByName('SubElementID').Value := ARangeSubElement.Id; qryInsertRangeSubElement.ExecSQL(); except Result := False; end; end; //Primary method to load Ranges from database. //This will internally load Range Elements & Range Sub Elements function TDM.LoadFromDB: TRangeList; var Index:Integer; begin Result := TRangeList.Create(); qryGetRange.Close(); qryGetRange.Open(); qryGetRange.First; while not qryGetRange.Eof do begin Index := Result.Add(TRange.Create(qryGetRange.FieldByName('RANGE_ID').AsInteger, qryGetRange.FieldByName('DESCRIPTION').AsString)); LoadRangeElementFromDB(Result[Index]); qryGetRange.Next; end; qryGetRange.Close(); end; procedure TDM.LoadRangeElementFromDB(ARange:TRange); var I:Integer; Element:TRangeElement; begin qryGetRangeElement.Close(); qryGetRangeElement.Parameters.ParamByName('RangeID').Value := ARange.Id; qryGetRangeElement.Open(); qryGetRangeElement.First; while not qryGetRangeElement.Eof do begin ARange.Elements.Add(TRangeElement.Create(qryGetRangeElement.FieldByName('ELEMENT_ID').AsInteger, qryGetRangeElement.FieldByName('QUANTITY').AsInteger)); qryGetRangeElement.Next; end; qryGetRangeElement.Close(); //For Each element load its Sub Elements for I:=0 to ARange.Elements.Count -1 do begin Element:= ARange.Elements[I]; LoadRangeSubElementFromDB(ARange, Element); end; end; procedure TDM.LoadRangeSubElementFromDB(ARange:TRange; ARangeElement:TRangeElement); var I:Integer; Element:TRangeElement; begin qryGetRangeSubElement.Close(); qryGetRangeSubElement.Parameters.ParamByName('RangeID').Value := ARange.Id; qryGetRangeSubElement.Parameters.ParamByName('ElementID').Value := ARangeElement.Id; qryGetRangeSubElement.Open(); qryGetRangeSubElement.First; while not qryGetRangeSubElement.Eof do begin Element := ARange.Elements.ItemById[qryGetRangeSubElement.FieldByName('SubElement_ID').AsInteger]; if ARangeElement.SubElements.ItemById[Element.Id] = nil then ARangeElement.SubElements.Add(Element); qryGetRangeSubElement.Next; end; qryGetRangeSubElement.Close(); //For each Sub Elemenets, load its sub elements if there any recursively. for I:=0 to ARangeElement.SubElements.Count-1 do begin LoadRangeSubElementFromDB(ARange, ARangeElement.SubElements[I]); end; end; function TDM.GetConnectionString: string; var IniFileName:string; Ini:TIniFile; ConnString:string; begin IniFileName := ChangeFileExt(Application.ExeName, '.ini'); if not FileExists(IniFileName) then raise Exception.Create('Ini File ' + QuotedStr(IniFileName) + ' not found!'); Ini := TIniFile.Create(IniFileName); if not (Ini.SectionExists(ConstIniSectionSetUp)) then raise Exception.Create('Connection string not found inside Inifile!'); ConnString := Ini.ReadString(ConstIniSectionSetUp, ConstIniKeyConnString, ''); if (Trim(ConnString)='') then raise Exception.Create('Connection string not found inside Inifile!'); Result := ConnString; end; function TDM.ConnectToDB: Boolean; begin Result := True; if (Con.Connected) then Exit; try Con.Connected := True; except on E:Exception do begin ShowMessage(E.Message); end; end; Result := Con.Connected end; function TDM.IsDBConnected: Boolean; begin Result := Con.Connected; end; function TDM.CleanDB: Boolean; begin qryDeleteRange.ExecSQL(); qryDeleteRangeElement.ExecSQL(); qryDeleteRangeSubElement.ExecSQL(); end; procedure TDM.DataModuleCreate(Sender: TObject); begin Con.ConnectionString := GetConnectionString(); end; end.
unit HGM.Controls.PanelExt; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Types, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, HGM.Common; type TPanelExt = class(TCustomPanel) private FOnPanel:Boolean; FDefaultPaint: Boolean; FOnMouseDown: TMouseEvent; FOnMouseMove: TMouseMoveEvent; FOnMouseUp: TMouseEvent; FMouseCoord:TPoint; FMouseState:TShiftState; FRepaintOnMouseMove: Boolean; procedure SetDefaultPaint(const Value: Boolean); procedure SetRepaintOnMouseMove(const Value: Boolean); public FOnMouseEnter:TNotifyEvent; FOnMouseLeave:TNotifyEvent; FOnPaint:TNotifyEvent; procedure FMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CMMouseEnter(var message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var message: TMessage); message CM_MOUSELEAVE; procedure CMMouseWheel(var Message: TCMMouseWheel); message WM_MOUSEWHEEL; procedure WMNCPaint(var Message: TMessage); message WM_NCPAINT; procedure Paint; override; property Canvas; constructor Create(AOwner: TComponent); override; property OnPanel:Boolean read FOnPanel; property MouseCoord:TPoint read FMouseCoord; property MouseState:TShiftState read FMouseState; published property Caption; property DefaultPaint:Boolean read FDefaultPaint write SetDefaultPaint; property OnMouseEnter:TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave:TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove; property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp; property OnPaint:TNotifyEvent read FOnPaint write FOnPaint; property RepaintOnMouseMove:Boolean read FRepaintOnMouseMove write SetRepaintOnMouseMove default False; property Align; property Alignment; property Anchors; property AutoSize; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property BorderStyle; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property Padding; property ParentBiDiMode; property ParentBackground; property ParentColor; property ParentCtl3D; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ShowCaption; property ShowHint; property TabOrder; property TabStop; property Touch; property VerticalAlignment; property Visible; property StyleElements; property OnAlignInsertBefore; property OnAlignPosition; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnGetSiteInfo; property OnMouseActivate; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; end; TDrawPanel = class(TPanelExt) public FOnPaint:TNotifyEvent; procedure Paint; override; constructor Create(AOwner: TComponent); override; published property OnPaint:TNotifyEvent read FOnPaint write FOnPaint; property RepaintOnMouseMove default True; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnPanel; end; TDragPanel = class(TCustomPanel) private FOnMouseDown:TMouseEvent; procedure FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); overload; procedure SetOnMouseDown(const Value: TMouseEvent); public procedure DoDrag; property DockManager; constructor Create(AOwner: TComponent); override; published property Align; property Alignment; property Anchors; property AutoSize; property BevelEdges; property BevelInner; property BevelKind; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property BorderStyle; property Caption; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DoubleBuffered; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property Padding; property ParentBiDiMode; property ParentBackground; property ParentColor; property ParentCtl3D; property ParentDoubleBuffered; property ParentFont; property ParentShowHint; property PopupMenu; property ShowCaption; property ShowHint; property TabOrder; property TabStop; property Touch; property VerticalAlignment; property Visible; property StyleElements; property OnAlignInsertBefore; property OnAlignPosition; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGesture; property OnGetSiteInfo; property OnMouseActivate; property OnMouseDown:TMouseEvent read FOnMouseDown write SetOnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; end; procedure Register; implementation procedure Register; begin RegisterComponents(PackageName, [TPanelExt]); RegisterComponents(PackageName, [TDrawPanel]); RegisterComponents(PackageName, [TDragPanel]); end; constructor TDrawPanel.Create(AOwner: TComponent); begin inherited; ParentBackground:=False; RepaintOnMouseMove := True; end; procedure TDrawPanel.Paint; begin if Assigned(FOnPaint) then FOnPaint(Self); end; procedure TPanelExt.Paint; begin if Brush.Bitmap <> nil then Canvas.Draw(0, 0, Brush.Bitmap); if Assigned(FOnPaint) then FOnPaint(Self); end; procedure TPanelExt.SetDefaultPaint(const Value: Boolean); begin FDefaultPaint := Value; Paint; end; procedure TPanelExt.SetRepaintOnMouseMove(const Value: Boolean); begin FRepaintOnMouseMove := Value; end; procedure TPanelExt.WMNCPaint(var Message: TMessage); begin if FDefaultPaint then inherited; if Assigned(FOnPaint) then FOnPaint(Self); end; procedure TPanelExt.CMMouseEnter(var message: TMessage); begin FOnPanel:=True; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; procedure TPanelExt.CMMouseLeave(var message: TMessage); begin FOnPanel:=False; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; procedure TPanelExt.CMMouseWheel(var Message: TCMMouseWheel); begin with Message do begin Result := 0; if DoMouseWheel(ShiftState, WheelDelta, SmallPointToPoint(Pos)) then Message.Result := 1 else if Parent <> nil then with TMessage(Message) do Result := Parent.Perform(CM_MOUSEWHEEL, WParam, LParam); end; end; constructor TPanelExt.Create(AOwner: TComponent); begin inherited; inherited OnMouseMove:=FMouseMove; inherited OnMouseDown:=FMouseDown; inherited OnMouseUp:=FMouseUp; end; procedure TPanelExt.FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FMouseState := Shift; if Assigned(FOnMouseDown) then FOnMouseDown(Sender, Button, Shift, X, Y); end; procedure TPanelExt.FMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin FMouseState := Shift; FMouseCoord := Point(X, Y); if Assigned(FOnMouseMove) then FOnMouseMove(Sender, Shift, X, Y); if FRepaintOnMouseMove then Repaint; end; procedure TPanelExt.FMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FMouseState := Shift; if Assigned(FOnMouseUp) then FOnMouseUp(Sender, Button, Shift, X, Y); end; { TDragPanel } constructor TDragPanel.Create(AOwner: TComponent); begin inherited; inherited OnMouseDown:=FMouseDown; end; procedure TDragPanel.DoDrag; begin ReleaseCapture; SendMessage(Self.Parent.Handle, WM_SYSCOMMAND, 61458, 0); end; procedure TDragPanel.FMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin DoDrag; if Assigned(FOnMouseDown) then FOnMouseDown(Sender, Button, Shift, X, Y); end; procedure TDragPanel.SetOnMouseDown(const Value: TMouseEvent); begin FOnMouseDown:=Value; end; end.
unit tdLDAPEnum; interface uses System.Classes, Winapi.Windows, System.SysUtils, System.AnsiStrings, System.TypInfo, System.DateUtils, Winapi.ActiveX, ADC.LDAP, JwaRpcdce, ActiveDs_TLB, MSXML2_TLB, System.SyncObjs, ADC.Types, ADC.DC, ADC.Attributes, ADC.ADObject, ADC.ADObjectList, ADC.Common, ADC.AD; type TLDAPEnum = class(TThread) private FSyncObject: TCriticalSection; FProgressProc: TProgressProc; FExceptionProc: TExceptionProc; FProgressValue: Integer; FExceptionCode: ULONG; FExceptionMsg: string; FLDAP: PLDAP; FLDAPSearchResult: PLDAPMessage; FAttrCatalog: TAttrCatalog; FAttributes: array of PAnsiChar; FOutList: TADObjectList<TADObject>; FObj: TADObject; FDomainDN: AnsiString; FDomainHostName: AnsiString; FMaxPwdAge_Secs: Int64; FMaxPwdAge_Days: Int64; procedure SyncProgress; procedure SyncException; procedure Clear; procedure GetDomainDN(var ADomainDN, AHostName: AnsiString); procedure GetMaxPasswordAge(ABase: AnsiString); function FormatExtDNFlags(iFlagValue: Integer): PLDAPControl; protected destructor Destroy; override; procedure Execute; override; procedure DoProgress(AProgress: Integer); overload; procedure DoProgress; overload; procedure DoException(AMsg: string; ACode: ULONG); public constructor Create(AConnection: PLDAP; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); reintroduce; end; implementation { TLDAPEnum } procedure TLDAPEnum.Clear; var i: Integer; begin if Terminated and (FOutList <> nil) then FOutList.Clear; FLDAP := nil; FProgressProc := nil; FProgressValue := 0; FExceptionProc := nil; FExceptionCode := 0; FExceptionMsg := ''; FAttrCatalog := nil; FDomainDN := ''; FDomainHostName := ''; FMaxPwdAge_Secs := 0; FMaxPwdAge_Days := 0; FOutList := nil; FObj := nil; if FLDAPSearchResult <> nil then ldap_msgfree(FLDAPSearchResult); for i := Low(FAttributes) to High(FAttributes) do System.AnsiStrings.StrDispose(FAttributes[i]); CoUninitialize; if FSyncObject <> nil then begin FSyncObject.Leave; FSyncObject := nil; end; end; constructor TLDAPEnum.Create(AConnection: PLDAP; AAttrCatalog: TAttrCatalog; AOutList: TADObjectList<TADObject>; ASyncObject: TCriticalSection; AProgressProc: TProgressProc; AExceptionProc: TExceptionProc; CreateSuspended: Boolean = False); var i: Integer; begin inherited Create(CreateSuspended); FreeOnTerminate := True; FSyncObject := ASyncObject; FProgressProc := AProgressProc; FExceptionProc := AExceptionProc; if AConnection = nil then begin DoException('No server binding.', 0); Self.Terminate; end else begin FLDAP := AConnection; GetDomainDN(FDomainDN, FDomainHostName); FAttrCatalog := AAttrCatalog; FOutList := AOutList; SetLength(FAttributes, FAttrCatalog.Count + 1); for i := 0 to FAttrCatalog.Count - 1 do FAttributes[i] := System.AnsiStrings.StrNew(PAnsiChar(AnsiString(FAttrCatalog[i]^.Name))); { Заполняем свойства для плавающего окна } i := FAttrCatalog.Count; SetLength(FAttributes, Length(FAttributes) + 3); FAttributes[i] := System.AnsiStrings.StrNew(PansiChar('displayName')); FAttributes[i + 1] := System.AnsiStrings.StrNew(PansiChar('title')); FAttributes[i + 2] := System.AnsiStrings.StrNew(PansiChar('physicalDeliveryOfficeName')); end; end; destructor TLDAPEnum.Destroy; begin inherited; end; procedure TLDAPEnum.DoException(AMsg: string; ACode: ULONG); begin FExceptionCode := ACode; FExceptionMsg := AMsg; Synchronize(SyncException); end; procedure TLDAPEnum.DoProgress; begin FProgressValue := FProgressValue + 1; Synchronize(SyncProgress); end; procedure TLDAPEnum.DoProgress(AProgress: Integer); begin FProgressValue := AProgress; Synchronize(SyncProgress); end; procedure TLDAPEnum.Execute; var returnCode: ULONG; errorCode: ULONG; ldapBase: AnsiString; ldapFilter: AnsiString; ldapCookie: PLDAPBerVal; ldapPage: PLDAPControl; ldapExtDN: PLDAPControl; ldapDeleted: PLDAPControl; ldapControls: array[0..1] of PLDAPControl; ldapServerControls: PPLDAPControl; ldapCount: ULONG; ldapEntry: PLDAPMessage; morePages: Boolean; i: Integer; begin CoInitialize(nil); if FSyncObject <> nil then if not FSyncObject.TryEnter then begin FSyncObject := nil; FOutList := nil; Self.OnTerminate := nil; Self.Terminate; end; if Terminated then begin Clear; Exit; end; FOutList.Clear; try { Из подключения получаем DNS-имя КД } ldapBase := FDomainDN; { Получаем значение атрибута maxPwdAge, которое используем для расчета } { срока действия пароля пользователя в секундах и днях (FMaxPwdAge_Seconds } { и FMaxPwdAge_Days соотв.) а затем используем одно из этих значений в } { процедуре ProcessObjects для расчета даты окончания действия пароля } GetMaxPasswordAge(ldapBase); { Формируем фильтр объектов AD } ldapFilter := '(|' + '(&(objectCategory=person)(objectClass=user))' + '(objectCategory=group)' + '(objectCategory=computer)' + // '(isDeleted=*)' + ')'; ldapExtDN := nil; ldapCookie := nil; DoProgress(0); { Если раскомментировать параметры ниже, то необходимо увеличить } { размер массива параметров ldapControls до необходимого. } { Важно! Массив ldapControls null-terminated, поэтому последний } { элемент должен быть равен nil, т.е. если используется, например, } { 3 параметра, то размер массива 4 ([0..3]) и ldapControls[3] := nil } // New(ldapDeleted); // ldapDeleted^.ldctl_oid := '1.2.840.113556.1.4.417'; { LDAP_SERVER_SHOW_DELETED_OID } // ldapDeleted^.ldctl_iscritical := True; // ldapControls[1] := ldapDeleted; // ldapExtDN := FormatExtDNFlags(1); // ldapControls[2] := ldapExtDN; { Постраничный поиск объектов AD } repeat if Terminated then Break; returnCode := ldap_create_page_control( FLDAP, ADC_SEARCH_PAGESIZE, ldapCookie, 1, ldapPage ); if returnCode <> LDAP_SUCCESS then raise Exception.Create('Failure during ldap_create_page_control: ' + ldap_err2string(returnCode)); ldapControls[0] := ldapPage; returnCode := ldap_search_ext_s( FLDAP, PAnsiChar(ldapBase), LDAP_SCOPE_SUBTREE, PAnsiChar(ldapFilter), PAnsiChar(@FAttributes[0]), 0, @ldapControls, nil, nil, 0, FLDAPSearchResult ); if not (returnCode in [LDAP_SUCCESS, LDAP_PARTIAL_RESULTS]) then raise Exception.Create('Failure during ldap_search_ext_s: ' + ldap_err2string(returnCode)); returnCode := ldap_parse_result( FLDAP^, FLDAPSearchResult, @errorCode, nil, nil, nil, ldapServerControls, False ); if ldapCookie <> nil then begin ber_bvfree(ldapCookie); ldapCookie := nil; end; returnCode := ldap_parse_page_control( FLDAP, ldapServerControls, ldapCount, ldapCookie ); if (ldapCookie <> nil) and (ldapCookie.bv_val <> nil) and (System.SysUtils.StrLen(ldapCookie.bv_val) > 0) then morePages := True else morePages := False; if ldapServerControls <> nil then begin ldap_controls_free(ldapServerControls); ldapServerControls := nil; end; ldapControls[0]:= nil; ldap_control_free(ldapPage); ldapPage := nil; { Обработка объектов } ldapEntry := ldap_first_entry(FLDAP, FLDAPSearchResult); while ldapEntry <> nil do begin if Terminated then Break; FObj := TADObject.Create; FObj.WriteProperties( FLDAP, ldapEntry, FAttrCatalog, string(FDomainHostName), FMaxPwdAge_Secs ); FOutList.Add(FObj); ldapEntry := ldap_next_entry(FLDAP, ldapEntry); DoProgress; end; ldap_msgfree(FLDAPSearchResult); FLDAPSearchResult := nil; until (morePages = False); ber_bvfree(ldapCookie); Dispose(ldapDeleted); Dispose(ldapExtDN); ldapCookie := nil; except on E: Exception do begin DoException(E.Message, returnCode); Clear; end; end; Clear; end; procedure TLDAPEnum.GetDomainDN(var ADomainDN, AHostName: AnsiString); var attr: PAnsiChar; attrArray: array of PAnsiChar; returnCode: ULONG; searchResult: PLDAPMessage; ldapEntry: PLDAPMessage; ldapValue: PPAnsiChar; begin SetLength(attrArray, 3); attrArray[0] := PAnsiChar('defaultNamingContext'); attrArray[1] := PAnsiChar('dnsHostName'); attrArray[2] := nil; returnCode := ldap_search_ext_s( FLDAP, nil, LDAP_SCOPE_BASE, PAnsiChar('(objectclass=*)'), PAnsiChar(@attrArray[0]), 0, nil, nil, nil, 0, searchResult ); if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(FLDAP, searchResult) > 0 ) then begin ldapEntry := ldap_first_entry(FLDAP, searchResult); ldapValue := ldap_get_values(FLDAP, ldapEntry, attrArray[0]); if ldapValue <> nil then ADomainDN := ldapValue^; ldap_value_free(ldapValue); ldapValue := ldap_get_values(FLDAP, ldapEntry, attrArray[1]); if ldapValue <> nil then AHostName := ldapValue^; ldap_value_free(ldapValue); end; if searchResult <> nil then ldap_msgfree(searchResult); end; procedure TLDAPEnum.GetMaxPasswordAge(ABase: AnsiString); const ONE_HUNDRED_NANOSECOND = 0.000000100; SECONDS_IN_DAY = 86400; var attr: PAnsiChar; attrArray: array of PAnsiChar; returnCode: ULONG; searchResult: PLDAPMessage; ldapEntry: PLDAPMessage; ldapBinValues: PPLDAPBerVal; begin SetLength(attrArray, 2); attrArray[0] := PAnsiChar('maxPwdAge'); returnCode := ldap_search_ext_s( FLDAP, PAnsiChar(ABase), LDAP_SCOPE_BASE, PAnsiChar('objectCategory=domain'), PAnsiChar(@attrArray[0]), 0, nil, nil, nil, 0, searchResult ); if (returnCode = LDAP_SUCCESS) and (ldap_count_entries(FLDAP, searchResult) > 0 ) then begin ldapEntry := ldap_first_entry(FLDAP, searchResult); ldapBinValues := ldap_get_values_len(FLDAP, ldapEntry, PAnsiChar('maxPwdAge')); if (ldapBinValues <> nil) and (ldapBinValues^.bv_len > 0) then begin FMaxPwdAge_Secs := Abs(Round(ONE_HUNDRED_NANOSECOND * StrToInt64Def(ldapBinValues^.bv_val, 0))); FMaxPwdAge_Days := Round(FMaxPwdAge_Secs / SECONDS_IN_DAY); end; ldap_value_free_len(ldapBinValues); end; if searchResult <> nil then ldap_msgfree(searchResult); end; function TLDAPEnum.FormatExtDNFlags(iFlagValue: Integer): PLDAPControl; const LDAP_SERVER_EXTENDED_DN_OID = '1.2.840.113556.1.4.529'; var pber: PBerElement; pLControl: PLDAPControl; pldctrl_value: PBERVAL; res: Integer; begin pber := nil; pLControl := nil; pldctrl_value := nil; res := -1; if iFlagValue <> 0 then iFlagValue := 1; pber := ber_alloc_t(LBER_USE_DER); if pber = nil then begin Result := nil; Exit; end; New(pLControl); ZeroMemory(pLControl, SizeOf(LDAPControl)); if pLControl= nil then begin Dispose(pLControl); ber_free(pber, 1); Result := nil end; ber_printf(pber, AnsiString('{i}'), iFlagValue); res := ber_flatten(pber, pldctrl_value); ber_free(pber, 1); if res <> 0 then begin Dispose(pLControl); Result := nil; Exit; end; pLControl.ldctl_oid := PAnsiChar(LDAP_SERVER_EXTENDED_DN_OID); pLControl.ldctl_iscritical := True; New(pLControl.ldctl_value.bv_val); ZeroMemory(pLControl.ldctl_value.bv_val, pldctrl_value.bv_len); CopyMemory( pLControl.ldctl_value.bv_val, pldctrl_value.bv_val, pldctrl_value.bv_len ); pLControl.ldctl_value.bv_len := pldctrl_value.bv_len; ber_bvfree(PLDAPBerVal(pldctrl_value)); Result := pLControl; end; procedure TLDAPEnum.SyncException; begin if Assigned(FExceptionProc) then FExceptionProc(FExceptionMsg, FExceptionCode); end; procedure TLDAPEnum.SyncProgress; begin if Assigned(FProgressProc) then FProgressProc(FObj, FProgressValue); end; end.
unit vtImageListWrapper; {$I vtDefine.inc } interface uses ImgList, l3ImageList ; type TvtImageList = class(Tl3ImageList) protected function DoGetBigSize: Boolean; override; {-} procedure DoSetBigSize(aValue: Boolean); override; {-} public constructor Create(aList: TCustomImageList); override; end; TvtProxyImageList = class(Tl3ImageList) protected function DoGetBigSize: Boolean; override; {-} procedure DoSetBigSize(aValue: Boolean); override; {-} public constructor Create(aList: TCustomImageList); override; end; implementation uses vtPngImgList, vtInterfaces ; { TvtImageList } const g_Sizes: array [Boolean] of TvtPILSize = (ps16x16, ps32x32); constructor TvtImageList.Create(aList: TCustomImageList); begin Assert(aList is TvtPngImageList); inherited Create(aList); end; function TvtImageList.DoGetBigSize: Boolean; begin Result := TvtPngImageList(Hack).CurSize = ps32x32 end; procedure TvtImageList.DoSetBigSize(aValue: Boolean); begin TvtPngImageList(Hack).CurSize := g_Sizes[aValue]; end; { TvtProxyImageList } constructor TvtProxyImageList.Create(aList: TCustomImageList); begin Assert(aList is TvtFixedSizeProxyPngImageList); inherited Create(aList); end; function TvtProxyImageList.DoGetBigSize: Boolean; begin Result := TvtFixedSizeProxyPngImageList(Hack).FixedSize = ps32x32 end; procedure TvtProxyImageList.DoSetBigSize(aValue: Boolean); begin TvtFixedSizeProxyPngImageList(Hack).FixedSize := g_Sizes[aValue]; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type GuidTest = public class (Test) private Data: Guid; GuidString: String := "{5EB4BEC4-5509-4434-9D33-2A9C74CC54EE}"; method AreEqual(Expected, Actual: Guid); method AreNotEqual(Expected, Actual: Guid); public method Setup; override; method CompareTo; method TestEquals; method NewGuid; method Parse; method ParseExceptions; method Empty; method ToByteArray; method TestToString; method ToStringFormat; method Constructors; end; implementation method GuidTest.Setup; begin Data := Guid.Parse(GuidString); end; method GuidTest.AreEqual(Expected: Guid; Actual: Guid); begin Assert.IsTrue(Expected.Equals(Actual)); end; method GuidTest.AreNotEqual(Expected: Guid; Actual: Guid); begin Assert.IsFalse(Expected.Equals(Actual)); end; method GuidTest.CompareTo; begin Assert.AreEqual(Data.CompareTo(Data), 0); var Value := Guid.Parse(GuidString); Assert.AreEqual(Data.CompareTo(Value), 0); Assert.IsTrue(Data.CompareTo(Guid.Empty) <> 0); Value := Guid.Parse("{5EB4BEC4-5509-4434-9D44-2A9C74CC54EE}"); Assert.IsTrue(Data.CompareTo(Value) <> 0); Assert.AreEqual(Guid.Empty.CompareTo(Guid.Empty), 0); end; method GuidTest.TestEquals; begin Assert.IsTrue(Data.Equals(Data)); var Value := Guid.Parse(GuidString); Assert.IsTrue(Data.Equals(Value)); Assert.IsFalse(Data.Equals(Guid.Empty)); Value := Guid.Parse("{5EB4BEC4-5509-4434-9D44-2A9C74CC54EE}"); Assert.IsFalse(Data.Equals(Value)); Assert.IsTrue(Guid.Empty.Equals(Guid.Empty)); end; method GuidTest.NewGuid; begin var Value := Guid.NewGuid; Assert.IsFalse(Value.Equals(Guid.Empty)); end; method GuidTest.Parse; begin AreEqual(Guid.Empty, Guid.Parse("00000000-0000-0000-0000-000000000000")); AreEqual(Guid.Empty, Guid.Parse("{00000000-0000-0000-0000-000000000000}")); AreEqual(Guid.Empty, Guid.Parse("(00000000-0000-0000-0000-000000000000)")); AreEqual(Data, Guid.Parse(GuidString)); AreNotEqual(Guid.Empty, Guid.Parse(GuidString)); AreEqual(Data, Guid.Parse("5EB4BEC4-5509-4434-9D33-2A9C74CC54EE")); AreEqual(Data, Guid.Parse("(5EB4BEC4-5509-4434-9D33-2A9C74CC54EE)")); end; method GuidTest.ParseExceptions; begin Assert.Throws(->Guid.Parse("")); Assert.Throws(->Guid.Parse(nil)); Assert.Throws(->Guid.Parse("String")); Assert.Throws(->Guid.Parse("{5EB4BEC4-5509-4434-9D44-2A9C74CC54EE")); Assert.Throws(->Guid.Parse("5EB4BEC4-5509-4434-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("(5EB4BEC4-5509-4434-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC-5509-4434-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4-55109-4434-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4-5509-44314-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4-5509-4434-9D414-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4-5509-4434-9D44-2A9C744CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4-5509-4434-9D44-2A9C4CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BECJ-5509-4434-9D44-2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4 5509 4434 9D44 2A9C74CC54EE}")); Assert.Throws(->Guid.Parse("{5EB4BEC4550944349D442A9C74CC54EE}")); Assert.Throws(->Guid.Parse("00000000000000000000000000000000")); Assert.Throws(->Guid.Parse("0")); end; method GuidTest.Empty; begin AreEqual(Guid.Parse("{00000000-0000-0000-0000-000000000000}"), Guid.Empty); var Value := Guid.Empty.ToByteArray; for i: Int32 := 0 to length(Value)-1 do Assert.AreEqual(Value[i], 0); end; method GuidTest.ToByteArray; begin var Expected: array of Byte := [94, 180, 190, 196, 85, 9, 68, 52, 157, 51, 42, 156, 116, 204, 84, 238]; var Actual := Data.ToByteArray; Assert.AreEqual(length(Actual), 16); for i: Int32 := 0 to length(Expected)-1 do Assert.AreEqual(Actual[i], Expected[i]); Actual := Guid.Empty.ToByteArray; Assert.AreEqual(length(Actual), 16); for i: Int32 := 0 to length(Expected)-1 do Assert.AreEqual(Actual[i], 0); end; method GuidTest.TestToString; begin //ToString should return string in "default" format Assert.AreEqual(Data.ToString, "5EB4BEC4-5509-4434-9D33-2A9C74CC54EE"); Assert.AreEqual(Data.ToString, Data.ToString(GuidFormat.Default)); end; method GuidTest.ToStringFormat; begin Assert.AreEqual(Data.ToString(GuidFormat.Braces), GuidString); Assert.AreEqual(Data.ToString(GuidFormat.Parentheses), "(5EB4BEC4-5509-4434-9D33-2A9C74CC54EE)"); Assert.AreEqual(Data.ToString(GuidFormat.Default), "5EB4BEC4-5509-4434-9D33-2A9C74CC54EE"); end; method GuidTest.Constructors; begin var Value := new Guid().ToByteArray; for i: Int32 := 0 to length(Value)-1 do Assert.AreEqual(Value[i], 0); var Expected: array of Byte := [94, 180, 190, 196, 85, 9, 68, 52, 157, 51, 42, 156, 116, 204, 84, 238]; var Actual := new Guid(Expected); Assert.IsNotNil(Actual); Assert.IsTrue(Data.Equals(Actual)); end; end.
unit ExtAI_DLL; interface uses Classes, Windows, System.SysUtils, ExtAISharedInterface; type TInitializeDLL = procedure(var aConfig: TDLLpConfig); StdCall; TTerminateDLL = procedure(); StdCall; TCreateExtAI = function(aID, aPort: Word; apIP: PWideChar; aLen: Cardinal): boolean; StdCall; TTerminateExtAI = function(aID: Word): Boolean; StdCall; TGetFirstLog = function(var aLog: PWideChar; var aLength: Cardinal): Boolean; StdCall; TDLLMainCfg = record Author, Description, ExtAIName, Path: UnicodeString; Version: Cardinal; end; // Communication with 1 physical DLL with using exported methods. // Main targets: initialization of 1 physical DLL, creation of ExtAIs and termination of ExtAIs and DLL TExtAI_DLL = class private fDLLConfig: TDLLMainCfg; fLibHandle: THandle; // DLL Procedures fDLLProc_InitDLL: TInitializeDLL; fDLLProc_TerminateDLL: TTerminateDLL; fDLLProc_CreateExtAI: TCreateExtAI; fDLLProc_TerminateExtAI: TTerminateExtAI; fDLLProc_GetFirstLog: TGetFirstLog; function LinkDLL(aDLLPath: String): Boolean; function GetName(): String; public constructor Create(aDLLPath: String); destructor Destroy; override; property Config: TDLLMainCfg read fDLLConfig; property Name: String read GetName; function CreateNewExtAI(aID, aPort: Word; aIP: UnicodeString): Boolean; function TerminateExtAI(aID: Word): Boolean; function GetAILog(var aLog: String): Boolean; end; implementation uses ExtAILog; { TExtAI_DLL } constructor TExtAI_DLL.Create(aDLLPath: String); begin LinkDLL(aDLLPath); gLog.Log('TExtAI_DLL-Create: DLLPath = %s', [aDLLPath]); end; destructor TExtAI_DLL.Destroy; begin gLog.Log('TExtAI_DLL-Destroy: ExtAI name = %s', [fDLLConfig.ExtAIName]); if Assigned(fDLLProc_TerminateDLL) then fDLLProc_TerminateDLL(); FreeLibrary(fLibHandle); Inherited; end; function TExtAI_DLL.LinkDLL(aDLLPath: String): Boolean; var Err: Integer; Cfg: TDLLpConfig; begin Result := False; try // Check if DLL exits if not FileExists(aDLLPath) then begin gLog.Log('TExtAI_DLL-LinkDLL: DLL file was NOT found'); Exit; end; // Load without displaying any pop up error messages fLibHandle := SafeLoadLibrary(aDLLPath, $FFFF); if fLibHandle = 0 then begin gLog.Log('TExtAI_DLL-LinkDLL: library was NOT loaded, error: %d', [GetLastError]); Exit; end; // Check error messages Err := GetLastError(); if Err <> 0 then begin gLog.Log('TExtAI_DLL-LinkDLL: ERROR in the DLL file detected = %d', [Err]); Exit; end; // Connect shared procedures fDLLProc_InitDLL := GetProcAddress(fLibHandle, 'InitializeDLL'); fDLLProc_TerminateDLL := GetProcAddress(fLibHandle, 'TerminateDLL'); fDLLProc_CreateExtAI := GetProcAddress(fLibHandle, 'CreateExtAI'); fDLLProc_TerminateExtAI := GetProcAddress(fLibHandle, 'TerminateExtAI'); fDLLProc_GetFirstLog := GetProcAddress(fLibHandle, 'GetFirstLog'); // Check if procedures are assigned if not Assigned(fDLLProc_InitDLL) or not Assigned(fDLLProc_TerminateDLL) or not Assigned(fDLLProc_CreateExtAI) or not Assigned(fDLLProc_TerminateExtAI) or not Assigned(fDLLProc_GetFirstLog) then begin gLog.Log('TExtAI_DLL-LinkDLL: Exported methods not found'); Exit; end; // Get DLL info fDLLConfig.Path := aDLLPath; fDLLProc_InitDLL(Cfg); fDLLConfig.Version := Cfg.Version; SetLength(fDLLConfig.Author, Cfg.AuthorLen); SetLength(fDLLConfig.Description, Cfg.DescriptionLen); SetLength(fDLLConfig.ExtAIName, Cfg.ExtAINameLen); Move(Cfg.Author^, fDLLConfig.Author[1], Cfg.AuthorLen * SizeOf(fDLLConfig.Author[1])); Move(Cfg.Description^, fDLLConfig.Description[1], Cfg.DescriptionLen * SizeOf(fDLLConfig.Description[1])); Move(Cfg.ExtAIName^, fDLLConfig.ExtAIName[1], Cfg.ExtAINameLen * SizeOf(fDLLConfig.ExtAIName[1])); gLog.Log('TExtAI_DLL-LinkDLL: DLL detected, Name: %s; Version: %d', [fDLLConfig.ExtAIName, fDLLConfig.Version]); Result := True; except // We failed for whatever unknown reason on E: Exception do begin Result := False; // We are not really interested in the Exception message in runtime. Just log it gLog.Log('TExtAI_DLL-LinkDLL: Failed with exception "%s"', [E.Message]); end; end; end; function TExtAI_DLL.CreateNewExtAI(aID, aPort: Word; aIP: UnicodeString): Boolean; begin if not Assigned(fDLLProc_CreateExtAI) then Exit(False); // Connect ExtAI from the main thread - this call creates Overbyte client (new thread) // If Synchronize or critical section is not used then the connection will not be initialized TThread.Synchronize(nil, procedure begin fDLLProc_CreateExtAI(aID, aPort, Addr(aIP[1]), Length(aIP)); end ); Result := True; gLog.Log('TExtAI_DLL-CreateNewExtAI: ID = %d', [aID]); end; function TExtAI_DLL.TerminateExtAI(aID: Word): Boolean; begin if not Assigned(fDLLProc_TerminateExtAI) then Exit(False); // Connect ExtAI from the main thread - this call creates Overbyte client (new thread) // If Synchronize or critical section is not used then the connection will not be initialized TThread.Synchronize(nil, procedure begin fDLLProc_TerminateExtAI(aID); end ); Result := True; gLog.Log('TExtAI_DLL-TerminateExtAI: ID = %d', [aID]); end; function TExtAI_DLL.GetName(): String; begin Result := Format('DLL: %s',[Config.ExtAIName]); end; function TExtAI_DLL.GetAILog(var aLog: String): Boolean; var Length: Cardinal; pLog: PWideChar; begin Result := False; if not Assigned(fDLLProc_GetFirstLog) then Exit(False); if fDLLProc_GetFirstLog(pLog, Length) AND (Length > 0) then begin SetLength(aLog, Length); Move(pLog^, aLog[1], Length * SizeOf(aLog[1])); Result := True; end; end; end.
unit SettingsInterface; interface type ILoggerSettings = interface(IInterface) function GetDataLifeTime: Cardinal; function GetFileName: string; function GetTruncateFileInterval: Cardinal; property DataLifeTime: Cardinal read GetDataLifeTime; property FileName: string read GetFileName; property TruncateFileInterval: Cardinal read GetTruncateFileInterval; end; IMessageThreadSettings = interface(IInterface) function GetIntervals: TArray<Cardinal>; property Intervals: TArray<Cardinal> read GetIntervals; end; ISettings = interface(IInterface) function GetLogger: ILoggerSettings; function GetMessageThread: IMessageThreadSettings; property Logger: ILoggerSettings read GetLogger; property MessageThread: IMessageThreadSettings read GetMessageThread; end; implementation end.
unit ZombieCharacter; interface uses SysUtils, Math, MMsystem, PositionRecord, ZombieAction, ZombieDirection; type {$SCOPEDENUMS ON} TZombieState = (Calm = 0, Alerted, Angry, Ordered); {$SCOPEDENUMS OFF} TZombieCharacter = class protected fStateCheckEveryElapsedSeconds : Double; fSensesCheckEveryElapsedSeconds : Double; fPosition : TPositionRecord; fDirection : TZombieDirection; fState : TZombieState; fAction : TZombieAction; fElapsedSeconds : Double; fTotalElapsedSeconds : Double; fTotalElapsedSecondsLastStateCheck : Double; fTotalElapsedSecondsLastSensesCheck : Double; fSelected : Boolean; fDestination : TPositionRecord; fLastDistanceToDestination : Double; fStateAtDestination : TZombieState; public constructor Create(aPosition : TPositionRecord; aDirection : TZombieDirection = TZombieDirection.Right; aState : TZombieState = TZombieState.Calm; aStateCheckEveryElapsedSeconds : double = 1.3; aSensesCheckEveryElapsedSeconds : double = 0.1); function GetPosition() : TPositionRecord; function GetDirection() : TZombieDirection; function GetState() : TZombieState; function GetAction() : TZombieAction; procedure AddElapsedSeconds(aElapsedSeconds : double); procedure SensesCheck(); //Kollar reaktioner på syn och hörsel procedure StateCheck(); //Styr beteende function GetTotalElapsedSeconds() : double; function GetSelected() : Boolean; procedure SetSelected(aSelected : Boolean); function GetDestination() : TPositionRecord; procedure SetDestination(aDestination : TPositionRecord); procedure SetState(aState : TZombieState); procedure SetStateAtDestination(aState : TZombieState); end; function RandomRangeF(min, max : double):double; implementation function RandomRangeF(min, max : double):double; var float : double; begin float := Random; result := min + float * (max-min); end; { TZombieCharacter } constructor TZombieCharacter.Create(aPosition : TPositionRecord; aDirection : TZombieDirection; aState : TZombieState; aStateCheckEveryElapsedSeconds : double; aSensesCheckEveryElapsedSeconds : double); begin fPosition := aPosition; fDirection := aDirection; fState := aState; fAction := TZombieAction.Stance; fElapsedSeconds := 0; fTotalElapsedSeconds := 0; fTotalElapsedSecondsLastStateCheck := RandomRangeF(0.0,aStateCheckEveryElapsedSeconds); fTotalElapsedSecondsLastSensesCheck :=RandomRangeF(0.0,aSensesCheckEveryElapsedSeconds); fStateCheckEveryElapsedSeconds := aStateCheckEveryElapsedSeconds; fSensesCheckEveryElapsedSeconds := aSensesCheckEveryElapsedSeconds; fSelected := False; AddElapsedSeconds(RandomRangeF(0.0,aStateCheckEveryElapsedSeconds)); end; function TZombieCharacter.GetPosition: TPositionRecord; begin Result := fPosition; end; function TZombieCharacter.GetAction: TZombieAction; begin Result := fAction; end; function TZombieCharacter.GetDestination: TPositionRecord; begin Result := fDestination; end; function TZombieCharacter.GetDirection() : TZombieDirection; begin Result := fDirection; end; function TZombieCharacter.GetSelected: Boolean; begin Result := fSelected; end; function TZombieCharacter.GetState: TZombieState; begin Result := fState; end; function TZombieCharacter.GetTotalElapsedSeconds: double; begin Result := fTotalElapsedSeconds; end; procedure TZombieCharacter.AddElapsedSeconds(aElapsedSeconds: double); begin fElapsedSeconds := aElapsedSeconds; fTotalElapsedSeconds := fTotalElapsedSeconds + aElapsedSeconds; if (fTotalElapsedSeconds - fTotalElapsedSecondsLastSensesCheck) >= (fSensesCheckEveryElapsedSeconds + RandomRangeF(0.0,0.3)) then SensesCheck(); if (fTotalElapsedSeconds - fTotalElapsedSecondsLastStateCheck) >= (fStateCheckEveryElapsedSeconds + RandomRangeF(0.0,1.5)) then StateCheck(); if(fAction = TZombieAction.Lurch) then fPosition.AddFraction( ZombieVectorDirection[Ord(fDirection)].X * 27.0 * aElapsedSeconds,ZombieVectorDirection[Ord(fDirection)].Y * 27.0 * aElapsedSeconds); end; procedure TZombieCharacter.SensesCheck(); var sensesNeedStateCheck : Boolean; begin fTotalElapsedSecondsLastSensesCheck := fTotalElapsedSeconds; sensesNeedStateCheck := False; if sensesNeedStateCheck then fTotalElapsedSecondsLastStateCheck := 0;//Triggers StateCheck end; procedure TZombieCharacter.SetDestination(aDestination: TPositionRecord); begin fDestination := aDestination; end; procedure TZombieCharacter.SetSelected(aSelected: Boolean); begin fSelected := aSelected; end; procedure TZombieCharacter.SetState(aState: TZombieState); begin fState := aState; end; procedure TZombieCharacter.SetStateAtDestination(aState: TZombieState); begin fStateAtDestination := aState; end; procedure TZombieCharacter.StateCheck(); var rand : Integer; distance : Double; begin fTotalElapsedSecondsLastStateCheck := fTotalElapsedSeconds; if fState = TZombieState.Calm then begin rand := RandomRange(0,101); if rand < 17 then fState := TZombieState.Alerted; //Action check if RandomRange(0,101) < 7 then begin if(RandomRange(0,2) = 1) then fDirection := RotateZombieDirectionClockwise(fDirection) else fDirection := RotateZombieDirectionAntiClockwise(fDirection); end; if fAction = TZombieAction.Stance then begin if RandomRange(0,101) < 7 then fAction := TZombieAction.Lurch; end else if fAction = TZombieAction.Lurch then begin if RandomRange(0,101) < 85 then fAction := TZombieAction.Stance; end else begin rand := RandomRange(0,101); if rand < 87 then fAction := TZombieAction.Stance; end; end else if fState = TZombieState.Alerted then begin rand := RandomRange(0,101); if rand < 17 then fState := TZombieState.Calm; if rand < 24 then fState := TZombieState.Angry; //Action check if RandomRange(0,101) < 14 then begin if(RandomRange(0,2) = 1) then fDirection := RotateZombieDirectionClockwise(fDirection) else fDirection := RotateZombieDirectionAntiClockwise(fDirection); end; if fAction = TZombieAction.Stance then begin rand := RandomRange(0,101); if rand < 14 then fAction := TZombieAction.Lurch else if rand < 21 then fAction := TZombieAction.Block; end else if fAction = TZombieAction.Lurch then begin rand := RandomRange(0,101); if rand < 67 then fAction := TZombieAction.Stance else if rand < 87 then fAction := TZombieAction.Block; end else begin rand := RandomRange(0,101); if rand < 67 then fAction := TZombieAction.Stance; end; end else if fState = TZombieState.Angry then begin rand := RandomRange(0,101); if rand < 17 then fState := TZombieState.Alerted; //Action check if RandomRange(0,101) < 35 then begin if(RandomRange(0,2) = 1) then fDirection := RotateZombieDirectionClockwise(fDirection) else fDirection := RotateZombieDirectionAntiClockwise(fDirection); end; if fAction = TZombieAction.Stance then begin rand := RandomRange(0,101); if rand < 77 then fAction := TZombieAction.Block else if rand < 90 then fAction := TZombieAction.Bite; end else if fAction = TZombieAction.Bite then begin rand := RandomRange(0,101); if rand < 57 then fAction := TZombieAction.Slam else if rand < 77 then fAction := TZombieAction.Block else begin if rand < 80 then if FileExists('.\Characters\Zombie\growl.wav') then PlaySound(pchar('.\Characters\Zombie\growl.wav'), 0, SND_ASYNC or SND_FILENAME); end; end else if fAction = TZombieAction.Slam then begin rand := RandomRange(0,101); if rand < 55 then fAction := TZombieAction.Stance else if rand < 77 then fAction := TZombieAction.Lurch else begin if rand < 80 then if FileExists('.\Characters\Zombie\growl.wav') then PlaySound(pchar('.\Characters\Zombie\growl.wav'), 0, SND_ASYNC or SND_FILENAME); end; end else begin rand := RandomRange(0,101); if rand < 67 then fAction := TZombieAction.Stance; end; end else if fState = TZombieState.Ordered then begin fDirection := RotateZombieDirectionTowardsDestination(fDirection,fPosition,fDestination); fAction := TZombieAction.Lurch; if (fPosition.DestinationReached(fDestination,55)) then begin fState := fStateAtDestination; if fState = TZombieState.Angry then fAction := TZombieAction.Slam else fAction := TZombieAction.Stance end; end; end; end.
{$mode objfpc} { Directive for defining classes } {$m+} { Directive for using constructor } program PascalProgram37; uses crt, math; { } { `Abstract` class Example // No lambdas in free Pascal } type ExampleClass = class public function calculate_f(x : double) : double; virtual; abstract; end; { ---------------------------------------------------------------------------- } { ExampleClass1 < ExampleClass } type ExampleClass1 = class(ExampleClass) public function calculate_f(x : double) : double; override; end; function ExampleClass1.calculate_f(x : double) : double; begin calculate_f := power(x - 5, 2); end; { ---------------------------------------------------------------------------- } { ExampleClass2 < ExampleClass } type ExampleClass2 = class(ExampleClass) public function calculate_f(x : double) : double; override; end; function ExampleClass2.calculate_f(x : double) : double; begin calculate_f := 100 * power(x - 0.24, 2); end; { ---------------------------------------------------------------------------- } { class Interval. Represents interval like [3, 7] or [-1, 1] or etc. } type IntervalClass = class private _lower_limit : double; _upper_limit : double; public constructor create(lower_limit, upper_limit : double); function get_lower_limit() : double; function get_upper_limit() : double; end; constructor IntervalClass.create(lower_limit, upper_limit : double); begin _lower_limit := lower_limit; _upper_limit := upper_limit; end; function IntervalClass.get_lower_limit() : double; begin get_lower_limit := _lower_limit; end; function IntervalClass.get_upper_limit() : double; begin get_upper_limit := _upper_limit; end; { ---------------------------------------------------------------------------- } { class Point } type PointClass = class private _x : double; _y : double; public constructor create(x : double; y : double); function get_x() : double; function get_y() : double; end; constructor PointClass.create(x : double; y : double); begin _x := x; _y := y; end; function PointClass.get_x() : double; begin get_x := _x; end; function PointClass.get_y() : double; begin get_y := _y; end; { ---------------------------------------------------------------------------- } { class DSCAlgorithm } type array_of_points_type = array of PointClass; type DSCAlgorithmClass = class private _example : ExampleClass; function find_localized_interval(points : array_of_points_type) : IntervalClass; public const INITIAL_X = 0; const INITIAL_H = 1; constructor create(var example : ExampleClass); function get_example() : ExampleClass; function get_initial_x() : double; function get_initial_h() : double; function apply() : IntervalClass; end; constructor DSCAlgorithmClass.create(var example : ExampleClass); begin _example := example; end; function DSCAlgorithmClass.find_localized_interval(points : array_of_points_type) : IntervalClass; var step : integer; first_index : integer; last_index : integer; point : PointClass; index_of_maximal_y : integer; i : integer; next_index : integer; filtered_points : array[0..2] of PointClass; minimal_x : double; maximal_x : double; begin step := 1; first_index := 0; last_index := length(points) - step; point := points[first_index]; index_of_maximal_y := first_index; for i := first_index + step to last_index do begin if (points[i].get_y() > point.get_y()) then begin point := points[i]; index_of_maximal_y := i; end; end; next_index := first_index; for i := first_index to last_index do begin if (i <> index_of_maximal_y) then begin filtered_points[next_index] := points[i]; next_index := next_index + step; end; end; point := filtered_points[first_index]; minimal_x := filtered_points[first_index].get_x(); for i := first_index to last_index - step do begin if (filtered_points[i].get_x() < point.get_x()) then begin point := filtered_points[i]; minimal_x := filtered_points[i].get_x(); end; end; point := filtered_points[first_index]; maximal_x := filtered_points[first_index].get_x(); for i := first_index to last_index - step do begin if (filtered_points[i].get_x() > point.get_x()) then begin point := filtered_points[i]; maximal_x := filtered_points[i].get_x(); end; end; find_localized_interval := IntervalClass.create(minimal_x, maximal_x); end; function DSCAlgorithmClass.get_example() : ExampleClass; begin get_example := _example; end; function DSCAlgorithmClass.get_initial_x() : double; begin get_initial_x := INITIAL_X; end; function DSCAlgorithmClass.get_initial_h() : double; begin get_initial_h := INITIAL_H; end; function DSCAlgorithmClass.apply() : IntervalClass; var example : ExampleClass; previous_h : double; current_h : double; next_h : double; previous_x : double; current_x : double; next_x : double; previous_f : double; current_f : double; next_f : double; k : integer; one_more_x : double; points : array[0..3] of PointClass; begin example := get_example(); { previous_x := some default value } current_h := get_initial_h(); { next_h := some default value } { previous_x := some default value } current_x := get_initial_x(); next_x := current_x + current_h; { previous_f := some default value } current_f := example.calculate_f(current_x); next_f := example.calculate_f(next_x); k := 0; if (current_f < next_f) then current_h := -current_h; while current_f > next_f do { TODO MAXIMAL_AMOUNT_OF_ITERATIONS } begin next_h := 2 * current_h; previous_x := current_x; current_x := next_x; next_x := next_x + next_h; previous_f := current_f; current_f := next_f; next_f := example.calculate_f(next_x); previous_h := current_f; current_h := next_h; k := k + 1; end; one_more_x := next_x - previous_h / 2; points[0] := PointClass.create(next_x, next_f); points[1] := PointClass.create(current_x, current_f); points[2] := PointClass.create(previous_x, previous_f); points[3] := PointClass.create(one_more_x, example.calculate_f(one_more_x)); apply := find_localized_interval(points); end; { ---------------------------------------------------------------------------- } { class DichotomyMethodClass } type DichotomyMethodClass = class private _example : ExampleClass; _interval : IntervalClass; _delta : double; _epsilon : double; public constructor create( example : ExampleClass; interval : IntervalClass; delta : double; epsilon: double ); function get_example() : ExampleClass; function get_interval() : IntervalClass; function get_delta() : double; function get_epsilon() : double; function apply() : double; end; constructor DichotomyMethodClass.create( example : ExampleClass; interval : IntervalClass; delta : double; epsilon: double ); begin _example := example; _interval := interval; _delta := delta; _epsilon := epsilon; end; function DichotomyMethodClass.get_example() : ExampleClass; begin get_example := _example; end; function DichotomyMethodClass.get_interval() : IntervalClass; begin get_interval := _interval; end; function DichotomyMethodClass.get_delta() : double; begin get_delta := _delta; end; function DichotomyMethodClass.get_epsilon() : double; begin get_epsilon := _epsilon; end; function DichotomyMethodClass.apply() : double; var example : ExampleClass; interval : IntervalClass; delta : double; epsilon : double; current_a : double; current_b : double; next_a : double; next_b : double; x_1 : double; x_2 : double; f_of_x_1 : double; f_of_x_2 : double; begin example := get_example(); interval := get_interval(); delta := get_delta(); epsilon := get_epsilon(); current_a := interval.get_lower_limit(); current_b := interval.get_upper_limit(); repeat x_1 := (current_a + current_b - delta) / 2; x_2 := (current_a + current_b + delta) / 2; f_of_x_1 := example.calculate_f(x_1); f_of_x_2 := example.calculate_f(x_2); if (f_of_x_1 <= f_of_x_2) then begin next_a := current_a; next_b := x_2; end else begin next_b := current_b; next_a := x_1; end; current_a := next_a; current_b := next_b; until abs(next_a - next_b) <= epsilon; apply := (next_a + next_b) / 2; end; { ---------------------------------------------------------------------------- } { Program variables } var delta : double; epsilon : double; example : ExampleClass; dsc_algorithm : DSCAlgorithmClass; interval : IntervalClass; dichotomy_method : DichotomyMethodClass; result : double; { Like main } begin delta := 0.05; epsilon := 0.2; example := ExampleClass1.create(); // delta := 0.05; // epsilon := 0.2; // example := ExampleClass1.create(); dsc_algorithm := DSCAlgorithmClass.create(example); interval := dsc_algorithm.apply(); writeln('Interval: ['); writeln(' ', interval.get_lower_limit(), ','); writeln(' ', interval.get_upper_limit()); writeln(']'); dichotomy_method := DichotomyMethodClass.create(example, interval, delta, epsilon); result := dichotomy_method.apply(); writeln('Result: ', result); readkey; end.
unit WpcExceptions; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TWpcException = class(Exception); TWpcIllegalArgumentException = class(TWpcException); TWpcUseErrorException = class(TWpcException); TWpcEnvironmentDetectorException = class(TWpcException); { TWpcScriptParseException } TWpcScriptParseException = class(TWpcException) public const UNKNOWN_LINE = -1; UNKNOWN_WORD_NUMBER = -2; private FLine : Integer; FWordNumber : Integer; FMessage : String; public property Line : Integer read FLine; property WordNumer : Integer read FWordNumber; property Message : String read FMessage; public constructor Create(ErrMessage: String); constructor Create(ErrMessage : String; ErrLine : Integer); constructor Create(ErrMessage : String; ErrLine : Integer; ErrWordNumber : Integer); end; implementation { TWpcScriptParseException } constructor TWpcScriptParseException.Create(ErrMessage: String); begin FLine := UNKNOWN_LINE; FWordNumber:= UNKNOWN_WORD_NUMBER; FMessage := ErrMessage; end; constructor TWpcScriptParseException.Create(ErrMessage: String; ErrLine: Integer); begin FLine := ErrLine; FWordNumber := UNKNOWN_WORD_NUMBER; FMessage := ErrMessage; end; constructor TWpcScriptParseException.Create(ErrMessage: String; ErrLine: Integer; ErrWordNumber : Integer); begin FLine := ErrLine; FWordNumber := ErrWordNumber; FMessage := ErrMessage; end; end.
unit Samples.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, RESTRequest4D.Request.Intf, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TMyCompletionHandlerWithError = TProc<TObject>; TFrmMain = class(TForm) btnSetMethod: TButton; btnSetBaseURL: TButton; FDMemTable: TFDMemTable; btnSetDatasetAdapter: TButton; btnGetMethod: TButton; btnGetBaseURL: TButton; btnGetResource: TButton; btnGetResourceSuffix: TButton; btnSetResourceSuffix: TButton; btnSetResource: TButton; btnGetDatasetAdapter: TButton; btnGetFullRequestURL: TButton; btnClearParams: TButton; btnAddParam: TButton; Button1: TButton; btnClearBody: TButton; btnAddBodyWithString: TButton; btnAddBodyWithJSONObject: TButton; btnAddBodyWithObject: TButton; btnJWTAuthorizationToken: TButton; btnBasicAuthorization: TButton; btnExecuteRequest: TButton; btnClearBasicAuthentication: TButton; btnGetStatusCode: TButton; btnExecuteAsync: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Button6: TButton; Button7: TButton; Button8: TButton; Button9: TButton; Button10: TButton; Button11: TButton; Button12: TButton; Button13: TButton; Button14: TButton; Button15: TButton; Button16: TButton; Button17: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnSetMethodClick(Sender: TObject); procedure btnSetBaseURLClick(Sender: TObject); procedure btnSetDatasetAdapterClick(Sender: TObject); procedure btnSetResourceClick(Sender: TObject); procedure btnSetResourceSuffixClick(Sender: TObject); procedure btnGetMethodClick(Sender: TObject); procedure btnGetBaseURLClick(Sender: TObject); procedure btnGetResourceClick(Sender: TObject); procedure btnGetResourceSuffixClick(Sender: TObject); procedure btnGetDatasetAdapterClick(Sender: TObject); procedure btnGetFullRequestURLClick(Sender: TObject); procedure btnClearParamsClick(Sender: TObject); procedure btnAddParamClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btnClearBodyClick(Sender: TObject); procedure btnAddBodyWithStringClick(Sender: TObject); procedure btnAddBodyWithJSONObjectClick(Sender: TObject); procedure btnAddBodyWithObjectClick(Sender: TObject); procedure btnExecuteRequestClick(Sender: TObject); procedure btnJWTAuthorizationTokenClick(Sender: TObject); procedure btnBasicAuthorizationClick(Sender: TObject); procedure btnClearBasicAuthenticationClick(Sender: TObject); procedure btnGetStatusCodeClick(Sender: TObject); procedure btnExecuteAsyncClick(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button8Click(Sender: TObject); procedure Button9Click(Sender: TObject); procedure Button10Click(Sender: TObject); procedure Button11Click(Sender: TObject); procedure Button13Click(Sender: TObject); procedure Button12Click(Sender: TObject); procedure Button15Click(Sender: TObject); procedure Button14Click(Sender: TObject); procedure Button16Click(Sender: TObject); procedure Button17Click(Sender: TObject); private FRequest: IRequest; procedure SetRequest(const AValue: IRequest); public property Request: IRequest read FRequest write SetRequest; end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses RESTRequest4D.Request, REST.Types, System.JSON; procedure TFrmMain.btnAddBodyWithJSONObjectClick(Sender: TObject); begin Request.Body.Add(TJSONObject.Create, True); end; procedure TFrmMain.btnAddBodyWithObjectClick(Sender: TObject); begin Request.Body.Add(TObject.Create, True); end; procedure TFrmMain.btnAddBodyWithStringClick(Sender: TObject); begin Request.Body.Add('Any thing'); end; procedure TFrmMain.btnAddParamClick(Sender: TObject); begin Request.Params.Add('country', 'Brazil'); Request.Params.Add('year', 2019); end; procedure TFrmMain.btnBasicAuthorizationClick(Sender: TObject); begin Request.Authentication.SetUsername('sample').SetPassword('123'); end; procedure TFrmMain.btnClearBasicAuthenticationClick(Sender: TObject); begin Request.Authentication.Clear; end; procedure TFrmMain.btnClearBodyClick(Sender: TObject); begin Request.Body.Clear; end; procedure TFrmMain.btnClearParamsClick(Sender: TObject); begin Request.Params.Clear; end; procedure TFrmMain.btnExecuteAsyncClick(Sender: TObject); var LMyCompletionHandlerWithError: TMyCompletionHandlerWithError; begin LMyCompletionHandlerWithError := procedure(AObject: TObject) begin if Assigned(AObject) and (AObject is Exception) then raise Exception(AObject); // or whatever you want! end; Request.ExecuteAsync(nil, True, True, LMyCompletionHandlerWithError); end; procedure TFrmMain.btnExecuteRequestClick(Sender: TObject); begin Request.Execute; end; procedure TFrmMain.btnGetBaseURLClick(Sender: TObject); begin ShowMessage(Request.GetBaseURL); end; procedure TFrmMain.btnGetDatasetAdapterClick(Sender: TObject); var LMemTable: TFDMemTable; begin LMemTable := Request.GetDataSetAdapter as TFDMemTable; end; procedure TFrmMain.btnGetFullRequestURLClick(Sender: TObject); begin ShowMessage(Request.GetFullRequestURL(True)); end; procedure TFrmMain.btnGetMethodClick(Sender: TObject); var LMethod: TRESTRequestMethod; begin LMethod := Request.GetMethod; end; procedure TFrmMain.btnGetResourceClick(Sender: TObject); begin ShowMessage(Request.GetResource); end; procedure TFrmMain.btnGetResourceSuffixClick(Sender: TObject); begin ShowMessage(Request.GetResourceSuffix); end; procedure TFrmMain.btnGetStatusCodeClick(Sender: TObject); var LStatusCode: Integer; begin LStatusCode := Request.Response.GetStatusCode; end; procedure TFrmMain.btnJWTAuthorizationTokenClick(Sender: TObject); begin Request.Headers.Add('Authorization', 'JWT Token', [poDoNotEncode]); end; procedure TFrmMain.btnSetBaseURLClick(Sender: TObject); begin Request.SetBaseURL('http://localhost:8080/datasnap/rest'); end; procedure TFrmMain.btnSetDatasetAdapterClick(Sender: TObject); begin Request.SetDataSetAdapter(FDMemTable); end; procedure TFrmMain.btnSetMethodClick(Sender: TObject); begin Request.SetMethod(rmGET); end; procedure TFrmMain.btnSetResourceClick(Sender: TObject); begin Request.SetResource('servermethods'); end; procedure TFrmMain.btnSetResourceSuffixClick(Sender: TObject); begin Request.SetResourceSuffix('method'); end; procedure TFrmMain.Button10Click(Sender: TObject); var LRaiseException: Boolean; begin LRaiseException := Request.GetRaiseExceptionOn500; end; procedure TFrmMain.Button11Click(Sender: TObject); begin Request.SetRaiseExceptionOn500(False); end; procedure TFrmMain.Button12Click(Sender: TObject); var LContentEncoding: string; begin LContentEncoding := Request.Response.GetContentEncoding; end; procedure TFrmMain.Button13Click(Sender: TObject); var LContentType: string; begin LContentType := Request.Response.GetContentType; end; procedure TFrmMain.Button14Click(Sender: TObject); var LContentLength: Cardinal; begin LContentLength := Request.Response.GetContentLength; end; procedure TFrmMain.Button15Click(Sender: TObject); var LContent: string; begin LContent := Request.Response.GetContent; end; procedure TFrmMain.Button16Click(Sender: TObject); begin Request.SetToken('token'); end; procedure TFrmMain.Button17Click(Sender: TObject); var LToken: string; begin LToken := Request.GetToken; end; procedure TFrmMain.Button1Click(Sender: TObject); begin Request.Headers.Add('Accept-Encoding', 'gzip'); end; procedure TFrmMain.Button2Click(Sender: TObject); var LTimeout: Integer; begin LTimeout := Request.GetTimeout; end; procedure TFrmMain.Button3Click(Sender: TObject); begin Request.SetTimeout(30000); end; procedure TFrmMain.Button4Click(Sender: TObject); var LAccept: string; begin LAccept := Request.GetAccept; end; procedure TFrmMain.Button5Click(Sender: TObject); begin Request.SetAccept(CONTENTTYPE_APPLICATION_JSON); end; procedure TFrmMain.Button6Click(Sender: TObject); var LAcceptCharset: string; begin LAcceptCharset := Request.GetAcceptCharset; end; procedure TFrmMain.Button7Click(Sender: TObject); begin Request.SetAcceptCharset('utf-8'); end; procedure TFrmMain.Button8Click(Sender: TObject); begin Request.SetAcceptEncoding('gzip, deflate'); end; procedure TFrmMain.Button9Click(Sender: TObject); var LAcceptEncoding: string; begin LAcceptEncoding := Request.GetAcceptEncoding; end; procedure TFrmMain.FormCreate(Sender: TObject); begin Request := TRequest.Create; end; procedure TFrmMain.FormDestroy(Sender: TObject); begin Request := nil; end; procedure TFrmMain.SetRequest(const AValue: IRequest); begin FRequest := AValue; end; end.
unit BankGeneralSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; //tidOwner = 'Owner'; tidEstLoan = 'EstLoan'; tidBudget = 'Budget'; tidInterest = 'Interest'; tidTerm = 'Term'; type TBankRequestResult = (brqApproved, brqRejected, brqNotEnoughFunds, brqError); const facStoppedByTycoon = $04; type TBankGeneralSheetHandler = class; TBankGeneralSheetViewer = class(TVisualControl) xfer_Name: TEdit; peBankBudget: TPercentEdit; Label7: TLabel; lbBudget: TLabel; Label12: TLabel; peInterest: TPercentEdit; lbInterest: TLabel; NameLabel: TLabel; Label2: TLabel; peTerm: TPercentEdit; lbTerm: TLabel; eBorrow: TEdit; fbRequest: TFramedButton; btnDemolish: TFramedButton; btnClose: TFramedButton; Label3: TLabel; Label4: TLabel; Shape2: TShape; Label1: TLabel; LoanResult: TPanel; lbBankResult: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure peBankBudgetChange(Sender: TObject); procedure peInterestChange(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure peBankBudgetMoveBar(Sender: TObject); procedure btnDemolishClick(Sender: TObject); procedure fbRequestClick(Sender: TObject); procedure peTermMoveBar(Sender: TObject); procedure peTermChange(Sender: TObject); procedure eBorrowEnter(Sender: TObject); procedure eBorrowKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TBankGeneralSheetHandler; end; TBankGeneralSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TBankGeneralSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; public procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure SetName(str : string); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); end; var BankGeneralSheetViewer: TBankGeneralSheetViewer; function BankGeneralSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, MathUtils, mr_StrUtils, Protocol, SheetUtils, MessageBox, {$IFDEF VER140} Variants, {$ENDIF} Literals; {$R *.DFM} // TBankGeneralSheetHandler procedure TBankGeneralSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; end; function TBankGeneralSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TBankGeneralSheetViewer.Create(Owner); fControl.fHandler := self; //fContainer.ChangeHeight(130); result := fControl; end; function TBankGeneralSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TBankGeneralSheetHandler.RenderProperties(Properties : TStringList); var trouble : string; begin FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] ); if fOwnsFacility then begin fControl.NameLabel.Visible := false; fControl.xfer_Name.Visible := true; fControl.xfer_Name.Enabled := true; end else begin fControl.xfer_Name.Visible := false; fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.NameLabel.Visible := true; end; try if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal4') else fControl.btnClose.Text := GetLiteral('Literal5'); except end; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.fbRequest.Enabled := not fOwnsFacility; fControl.peInterest.Enabled := fOwnsFacility; fControl.peTerm.Enabled := fOwnsFacility; fControl.peBankBudget.Enabled := fOwnsFacility; fControl.eBorrow.Enabled := not fOwnsFacility; if not fOwnsFacility then fControl.eBorrow.Text := Properties.Values[tidEstLoan]; try fControl.peBankBudget.Value := StrToInt(Properties.Values[tidBudget]); except end; try fControl.peInterest.Value := StrToInt(Properties.Values[tidInterest]); except end; try fControl.peTerm.Value := StrToInt(Properties.Values[tidTerm]); except end; end; procedure TBankGeneralSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); //Names.Add(tidOwner); Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TBankGeneralSheetHandler.Clear; begin inherited; fControl.NameLabel.Caption := NA; fControl.xfer_Name.Text := ''; fControl.NameLabel.Caption := ''; fControl.eBorrow.Text := ''; fControl.peBankBudget.Value := 0; fControl.peInterest.Value := 0; fControl.peTerm.Value := 0; fControl.peBankBudget.Enabled := false; fControl.peInterest.Enabled := false; fControl.peTerm.Enabled := false; fControl.eBorrow.Enabled := false; fControl.xfer_Name.Enabled := false; end; procedure TBankGeneralSheetHandler.SetName(str : string); var MSProxy : OleVariant; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and fOwnsFacility and CacheCommon.ValidName(str) then MSProxy.Name := str else Beep; finally fControl.Cursor := crDefault; end; except end; end; procedure TBankGeneralSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; aux : string; MSProxy : OleVariant; EstLoan : string; Budget : integer; Interest : integer; Term : integer; begin Update := parms[1].vInteger; try // Get Cached properties try Prop := fContainer.GetProperties(Names); finally Names.Free; end; // Get Model propeties aux := Prop.Values[tidCurrBlock]; if aux <> '' then fCurrBlock := StrToInt(aux) else fCurrBlock := 0; if (fCurrBlock <> 0) and (Update = fLastUpdate) then begin MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); try EstLoan := MSProxy.RDOEstimateLoan(fContainer.GetClientView.getTycoonId); //EstLoan := realmax(0, EstLoan); // >> except //EstLoan := 10; end; Budget := MSProxy.BudgetPerc; Interest := MSProxy.Interest; Term := MSProxy.Term; //Prop.Values[tidEstLoan] := FormatMoneyStr( '%.0n', [int(EstLoan)] ); Prop.Values[tidEstLoan] := EstLoan; Prop.Values[tidBudget] := IntToStr(Budget); Prop.Values[tidInterest] := IntToStr(Interest); Prop.Values[tidTerm] := IntToStr(Term); end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; except end; end; procedure TBankGeneralSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin if fLastUpdate = parms[1].vInteger then try try RenderProperties(Prop); finally Prop.Free; end; except end; end; // BankGeneralSheetHandlerCreator function BankGeneralSheetHandlerCreator : IPropertySheetHandler; begin result := TBankGeneralSheetHandler.Create; end; procedure TBankGeneralSheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text) else if Key in NotAllowedChars then Key := #0; end; procedure TBankGeneralSheetViewer.peBankBudgetMoveBar(Sender: TObject); begin lbBudget.Caption := IntToStr(peBankBudget.Value) + '%'; end; procedure TBankGeneralSheetViewer.peTermMoveBar(Sender: TObject); begin lbTerm.Caption := IntToStr(peTerm.Value); end; procedure TBankGeneralSheetViewer.peBankBudgetChange(Sender: TObject); var Proxy : OleVariant; wfansw : boolean; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; wfansw := Proxy.WaitForAnswer; Proxy.BindTo(fHandler.fCurrBlock); Proxy.RDOSetLoanPerc(peBankBudget.Value); Proxy.WaitForAnswer := wfansw; except end; end; procedure TBankGeneralSheetViewer.peInterestChange(Sender: TObject); var Proxy : OleVariant; wfansw : boolean; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; Proxy.BindTo(fHandler.fCurrBlock); wfansw := Proxy.WaitForAnswer; Proxy.Interest := peInterest.Value; Proxy.WaitForAnswer := wfansw; except end; end; procedure TBankGeneralSheetViewer.peTermChange(Sender: TObject); var Proxy : OleVariant; wfansw : boolean; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; wfansw := Proxy.WaitForAnswer; Proxy.BindTo(fHandler.fCurrBlock); Proxy.Term := peTerm.Value; Proxy.WaitForAnswer := wfansw; except end; end; procedure TBankGeneralSheetViewer.btnCloseClick(Sender: TObject); begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then if btnClose.Text = GetLiteral('Literal6') then begin fHandler.fContainer.GetMSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal7'); end else begin fHandler.fContainer.GetMSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal8'); end; end; procedure TBankGeneralSheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; s : string; begin s := Format(GetLiteral('Literal497'),[xfer_Name.text]); if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility and (ShowMsgBoxYN(GetLiteral('Literal498'), s, 1, true, true)=mrOk) then try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo('World'); if Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) <> NOERROR then Beep; end; except end; end; procedure TBankGeneralSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TBankGeneralSheetViewer.fbRequestClick(Sender: TObject); var Proxy : OleVariant; Amount : string; Answ : TBankRequestResult; SecId : string; begin if (fHandler.fCurrBlock <> 0) and not fHandler.fOwnsFacility then begin try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo(fHandler.fCurrBlock); Amount := KillSpaces( ReplaceChar( eBorrow.Text, ',', ' ' )); Amount := KillSpaces( ReplaceChar( Amount, '$', ' ' )); SecId := fHandler.fContainer.GetClientView.getSecurityId; if SecId <> '' then Answ := Proxy.RDOAskLoan(StrToInt(SecId), Amount) else Answ := brqError; end else Answ := brqError; except Answ := brqError; end; case Answ of brqApproved : begin lbBankResult.Caption := GetLiteral('Literal9'); LoanResult.Color := clGreen; end; brqRejected : begin lbBankResult.Caption := GetLiteral('Literal10'); LoanResult.Color := clMaroon; end; brqNotEnoughFunds : begin lbBankResult.Caption := GetLiteral('Literal11'); LoanResult.Color := clMaroon; end; brqError : begin lbBankResult.Caption := GetLiteral('Literal12'); LoanResult.Color := clMaroon; end; end; LoanResult.Visible := true; end; end; procedure TBankGeneralSheetViewer.eBorrowEnter(Sender: TObject); begin LoanResult.Visible := false; end; procedure TBankGeneralSheetViewer.eBorrowKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin LoanResult.Visible := false; end; initialization SheetHandlerRegistry.RegisterSheetHandler('BankGeneral', BankGeneralSheetHandlerCreator); end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_Sort * Implements generic quick sort *********************************************************************************************************************** } Unit TERRA_Sort; {$I terra.inc} Interface Type Sort = Class Protected Class Function Partition(Data:Pointer; L, R:Integer):Integer; Class Procedure QuickSort(Data:Pointer; L,R:Integer); Public // should return 1 if A < B // should return -1 if A > B // should return 0 if A = B Class Procedure SetPivot(Data:Pointer; A:Integer); Virtual; Abstract; Class Function Compare(Data:Pointer; A:Integer):Integer; Virtual; Abstract; Class Procedure Swap(Data:Pointer; A,B:Integer); Virtual; Abstract; Class Procedure Sort(Data:Pointer; Count:Integer); End; Implementation { Sort } Class Function Sort.Partition(Data:Pointer; L, R:Integer):Integer; Var I,J:Integer; Begin I := L; J := R; SetPivot(Data, (R + L) Shr 1); While (i <= j) Do Begin While (Compare(Data, I)>0) Do Inc(I); While (Compare(Data, J)<0) Do Dec(J); If (i <= j) Then Begin Swap(Data, I, J); Inc(I); Dec(J); End; End; Result := I; End; Class Procedure Sort.QuickSort(Data:Pointer; L,R:Integer); Var index:Integer; Begin Index := Partition(Data, L, R); If (L < Pred(index)) Then QuickSort(Data, L, Pred(index)); If (index < R) Then QuickSort(Data, Index, R); End; Class procedure Sort.Sort(Data: Pointer; Count: Integer); Begin QuickSort(Data, 0, Pred(Count)); End; End.
unit kwPopEditorRepaintAndCheckWithEtalon; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorRepaintAndCheckWithEtalon.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_RepaintAndCheckWithEtalon // // *Описание:* // Перерисовывает редактор сохраняя данные об отриосванном для тестов. Пересовка вызвается // принудительно. Все отрисованные до этого данные стираются! Создается файл с именем NNN.shapes - // где NNN - номер теста (Внимание! Имя теста дожно начинаться с TK) . Если до этого не // существовало эталона, то он создается. О чем сообщается в конце выполнеия теста. Если эталон уже // существовал, то производится сравнение новой версии файла с эталоном. Если сравнение не прошло, // то об этом будет сообщено (тест будет считаться не прошедшим) и будет вызвана внешняя программа // сравнения файлов. // *Формат:* // {code} // anEditor pop:editor:RepaintCheckWithEtalon // {code} // где anEditor - указатель на редактор, в котором нужно вызвать перерисовку. // *Пример:* // {code} // focused:control:push pop:editor:RepaintCheckWithEtalon // {code} // Вызывает перисовку в редакторе, где находится фокус. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If defined(nsTest) AND not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes, nevTools, nevShapesPaintedSpy ; {$IfEnd} //nsTest AND not NoScripts {$If defined(nsTest) AND not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} _kwCheckWithEtalonCommon_Parent_ = _kwEditorFromStackWord_; {$Include ..\ScriptEngine\kwCheckWithEtalonCommon.imp.pas} TkwPopEditorRepaintAndCheckWithEtalon = class(_kwCheckWithEtalonCommon_) {* *Описание:* Перерисовывает редактор сохраняя данные об отриосванном для тестов. Пересовка вызвается принудительно. Все отрисованные до этого данные стираются! Создается файл с именем NNN.shapes - где NNN - номер теста (Внимание! Имя теста дожно начинаться с TK) . Если до этого не существовало эталона, то он создается. О чем сообщается в конце выполнеия теста. Если эталон уже существовал, то производится сравнение новой версии файла с эталоном. Если сравнение не прошло, то об этом будет сообщено (тест будет считаться не прошедшим) и будет вызвана внешняя программа сравнения файлов. *Формат:* [code] anEditor pop:editor:RepaintCheckWithEtalon [code] где anEditor - указатель на редактор, в котором нужно вызвать перерисовку. *Пример:* [code] focused:control:push pop:editor:RepaintCheckWithEtalon [code] Вызывает перисовку в редакторе, где находится фокус. } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorRepaintAndCheckWithEtalon {$IfEnd} //nsTest AND not NoScripts implementation {$If defined(nsTest) AND not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms, SysUtils, StrUtils ; {$IfEnd} //nsTest AND not NoScripts {$If defined(nsTest) AND not defined(NoScripts)} type _Instance_R_ = TkwPopEditorRepaintAndCheckWithEtalon; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$Include ..\ScriptEngine\kwCheckWithEtalonCommon.imp.pas} // start class TkwPopEditorRepaintAndCheckWithEtalon procedure TkwPopEditorRepaintAndCheckWithEtalon.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4E1B0DEA0240_var* //#UC END# *4F4CB81200CA_4E1B0DEA0240_var* begin //#UC START# *4F4CB81200CA_4E1B0DEA0240_impl* anEditor.View.ClearShapes; ExecuteWithEditor(aCtx, anEditor); //#UC END# *4F4CB81200CA_4E1B0DEA0240_impl* end;//TkwPopEditorRepaintAndCheckWithEtalon.DoWithEditor class function TkwPopEditorRepaintAndCheckWithEtalon.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:RepaintAndCheckWithEtalon'; end;//TkwPopEditorRepaintAndCheckWithEtalon.GetWordNameForRegister {$IfEnd} //nsTest AND not NoScripts initialization {$If defined(nsTest) AND not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //nsTest AND not NoScripts end.
program CBR2; var Zahl1, Zahl2: Integer; procedure Zahlentauschen (var Param1, Param2: Integer); var Hilfsvariable: Integer; begin Hilfsvariable := Param1; Param1 := Param2; Param2 := Hilfsvariable end; begin Zahl1 := 10; Zahl2 := 20; WriteLn ('Vorher : Zahl1 = ', Zahl1, ' Zahl2 = ', Zahl2); Zahlentauschen (Zahl1, Zahl2); WriteLn ('Nachher: Zahl1 = ', Zahl1, ' Zahl2 = ', Zahl2) end.
unit aeTerrain; interface uses windows, types, classes, aeCamera, System.Generics.Collections, aeRenderable, aeMesh, aeSceneNode, aeConst, sysutils, aeLoggingManager, math, aeVectorBuffer, aeIndexBuffer, dglOpenGL; const // target tile size. When quadtree arrived at this size, we stop splitting tree. AE_TERRAIN_TILE_SIZE = 128; // 1 many vertices every x meter AE_TERRAIN_TILE_LOD_RES_HIGH = 2; AE_TERRAIN_TILE_LOD_RES_MID = 8; AE_TERRAIN_TILE_LOD_RES_LOW = 32; type TaeTerrainNeighborType = (AE_TERRAIN_NEIGHBOR_TYPE_TOP, AE_TERRAIN_NEIGHBOR_TYPE_RIGHT, AE_TERRAIN_NEIGHBOR_TYPE_BOTTOM, AE_TERRAIN_NEIGHBOR_TYPE_LEFT); type TaeTerrainTile = class(TaeMesh) public constructor Create(row, column: integer; heightDataCall: TaeTerrainGetHeightCall); // calculate a triangle mesh from the height data... Procedure CalculateTerrainMesh(); procedure SetNeighbor(tile: TaeTerrainTile; ntype: TaeTerrainNeighborType); function GetManhattanDistance(p: TPoint3D): single; function GetDistance(p: TPoint3D): single; procedure SetLOD(lod: TaeMeshLevelOfDetail); private _n_top, _n_right, _n_bottom, _n_left: TaeTerrainTile; _vb_lod: TaeVectorBuffer; _ib_lod_high: TaeIndexBuffer; _ib_lod_mid: TaeIndexBuffer; _ib_lod_low: TaeIndexBuffer; function GenerateLODIndexBuffer(ib: TaeIndexBuffer; tile_size, tile_res: integer): integer; // stich a triangle border around a tile. // function StichTile(tile: TaeTerrainTile): integer; // create a triangle border. // function CreateBorderStrip(gbo: TaeGraphicsBufferObject; neighbor_type: TaeTerrainNeighborType; border_len: integer; border_res_1, border_res_2: word): integer; protected _row, _column: integer; _GetHeightCall: TaeTerrainGetHeightCall; end; type TaeVisableTerrainTiles = record count: integer; tiles: array of TaeTerrainTile; end; type TaeTerrain = class(TaeSceneNode) public Constructor Create(terrain_size: Cardinal; hmap_resolution: integer; hmap_src: TaeTerrainGetHeightCall); procedure SetCamera(cam: TaeCamera); function GetVisableTiles: TaeVisableTerrainTiles; protected // setup basic grid Procedure SetupGrid; // approximate each edge to neighbor so we avoid cracks! private _GetHeightCall: TaeTerrainGetHeightCall; _tiles: TList<TaeTerrainTile>; _terrain_size: Cardinal; // squared _cam: TaeCamera; end; implementation { TaeTerrain } // constructor TaeTerrain.Create(hmap: TaeHeightmap); // begin // self._hmap := hmap; // end; // // procedure TaeTerrain.SetCamera(cam: TaeCamera); // begin // self._cam := cam; // // end; { TaeTerrain } constructor TaeTerrain.Create(terrain_size: Cardinal; hmap_resolution: integer; hmap_src: TaeTerrainGetHeightCall); begin inherited Create('NODE_Terrain_' + IntToStr(terrain_size)); Self._NodeType := AE_SCENENODE_TYPE_TERRAIN; Self._tiles := TList<TaeTerrainTile>.Create; Self._terrain_size := terrain_size * hmap_resolution; // normally 2 Self._GetHeightCall := hmap_src; Self.SetupGrid; AE_LOGGING.AddEntry('TaeTerrain.Create() : Terrain engine started..', AE_LOG_MESSAGE_ENTRY_TYPE_NORMAL); end; function TaeTerrain.GetVisableTiles: TaeVisableTerrainTiles; var i: integer; indx: integer; mhd: single; begin indx := 0; Result.count := Self._tiles.count; SetLength(Result.tiles, Result.count); for i := 0 to Result.count - 1 do begin mhd := Self._tiles[i].GetDistance(Self._cam.getPosition); if (mhd < 5000) then begin if (Self._tiles[i].GetVertexBuffer = nil) then Self._tiles[i].CalculateTerrainMesh; if mhd < 300 then begin Self._tiles[i].SetLOD(AE_MESH_LOD_HIGH); end else if (mhd < 800) then Self._tiles[i].SetLOD(AE_MESH_LOD_MID) else Self._tiles[i].SetLOD(AE_MESH_LOD_LOW); Result.tiles[indx] := Self._tiles[i]; inc(indx); end; end; Result.count := indx; SetLength(Result.tiles, Result.count); end; procedure TaeTerrain.SetCamera(cam: TaeCamera); begin Self._cam := cam; end; procedure TaeTerrain.SetupGrid; var nTiles: integer; y: integer; x: integer; tt: TaeTerrainTile; i: integer; i2: integer; begin nTiles := Self._terrain_size div AE_TERRAIN_TILE_SIZE; for y := 0 to nTiles - 1 do for x := 0 to nTiles - 1 do begin // setup first tt := TaeTerrainTile.Create(x, y, Self._GetHeightCall); Self._tiles.Add(tt); end; // now fix neighbor links ! for y := 0 to nTiles - 1 do for x := 0 to nTiles - 1 do begin i := x + y * nTiles; // set top if (y > 0) then Self._tiles[i].SetNeighbor(Self._tiles[i - nTiles], AE_TERRAIN_NEIGHBOR_TYPE_TOP); // set right if (x < (nTiles - 1)) then Self._tiles[i].SetNeighbor(Self._tiles[i + 1], AE_TERRAIN_NEIGHBOR_TYPE_RIGHT); // set bottom if (y < (nTiles - 1)) then Self._tiles[i].SetNeighbor(Self._tiles[i + nTiles], AE_TERRAIN_NEIGHBOR_TYPE_BOTTOM); // set left if (x > 0) then Self._tiles[i].SetNeighbor(Self._tiles[i - 1], AE_TERRAIN_NEIGHBOR_TYPE_LEFT); end; end; { TaeTerrainTile } procedure TaeTerrainTile.CalculateTerrainMesh; var x: integer; y: integer; tx, ty: single; indx: word; v: TVectorArray; i: integer; numTriangles: integer; i_row, i_col: integer; i_top_left, i_bottom_right: word; begin // create a buffer Self._vb_lod.Clear; numTriangles := (AE_TERRAIN_TILE_SIZE) * (AE_TERRAIN_TILE_SIZE) * 2; Self._vb_lod.PreallocateVectors(numTriangles * 3); // calculate world coordinate offsets // tx/ty is top left coordinate of tile tx := Self._column * AE_TERRAIN_TILE_SIZE; ty := Self._row * AE_TERRAIN_TILE_SIZE; // first we load all vertices into vertex array. for y := 0 to AE_TERRAIN_TILE_SIZE - 1 do begin v[2] := ty + y; for x := 0 to AE_TERRAIN_TILE_SIZE - 1 do begin v[0] := tx + x; v[1] := Self._GetHeightCall(v[0], v[2]); Self._vb_lod.AddVector(v); end; end; Self._vb_lod.Pack; Self.SetVertexBuffer(Self._vb_lod); end; function TaeTerrainTile.GenerateLODIndexBuffer(ib: TaeIndexBuffer; tile_size, tile_res: integer): integer; var neededIndices: word; i_row, i_col: integer; i_top_left, i_bottom_right: word; begin ib.Clear; // calculate needed indices neededIndices := (tile_size div tile_res) * (tile_size div tile_res) * 2 * 3; ib.PreallocateIndices(neededIndices); i_col := 0; i_row := 0; while i_col < (tile_size div tile_res) - 1 do begin while i_row < (tile_size div tile_res) - 1 do begin // top left vertex i_top_left := (i_col * tile_size * tile_res) + (i_row * tile_res); ib.addIndex(i_top_left); // bottom right vertex i_bottom_right := i_top_left + tile_size * tile_res + tile_res; ib.addIndex(i_bottom_right); // top right vertex ib.addIndex(i_top_left + tile_res); // bottom triangle // top left vertex ib.addIndex(i_top_left); // bottom left vertex ib.addIndex(i_top_left + tile_size * tile_res); // bottom right vertex ib.addIndex(i_bottom_right); inc(i_row); end; i_row := 0; inc(i_col); end; ib.Pack; // okay, now for the borders. // Self.StichTile(Self._n_top); // Self.StichTile(Self._n_right); // Self.StichTile(Self._n_bottom); // Self.StichTile(Self._n_left); Result := ib.count; end; { function TaeTerrainTile.StichTile(tile: TaeTerrainTile): integer; begin // the higher quality always reaches down to lower quality. if (tile <> nil) then case Self.GetLOD() of AE_MESH_LOD_HIGH: begin case tile.GetLOD() of AE_MESH_LOD_HIGH: begin end; AE_MESH_LOD_MID: begin end; end; end; AE_MESH_LOD_MID: begin case tile.GetLOD() of AE_MESH_LOD_MID: begin end; AE_MESH_LOD_LOW: begin end; end; end; AE_MESH_LOD_LOW: begin // only have to deal with low quality end; end; end; } constructor TaeTerrainTile.Create(row, column: integer; heightDataCall: TaeTerrainGetHeightCall); begin inherited Create(); Self._row := row; Self._column := column; Self._GetHeightCall := heightDataCall; Self._vb_lod := TaeVectorBuffer.Create; Self._ib_lod_high := TaeIndexBuffer.Create; Self._ib_lod_mid := TaeIndexBuffer.Create; Self._ib_lod_low := TaeIndexBuffer.Create; // we want to delete ram contents, after it has been uploaded to GPU! Self.SetPurgeAfterGPUUpload(True); Self.SetRenderPrimitive(GL_TRIANGLES); end; { function TaeTerrainTile.CreateBorderStrip(gbo: TaeGraphicsBufferObject; neighbor_type: TaeTerrainNeighborType; border_len: integer; border_res_1, border_res_2: word): integer; var largerSide, smallerSide: word; triangleResolution: word; i: integer; indx: integer; begin // find out which of the border sides has more detail (which of the tiles actually) // afterwards, we ´have the lower res side connect to higher res one. largerSide := Max(border_res_1, border_res_2); smallerSide := Min(border_res_1, border_res_2); triangleResolution := largerSide div smallerSide; // now add indices for every triangle that is smallerside. case neighbor_type of AE_TERRAIN_NEIGHBOR_TYPE_TOP: begin // top-bottom... for i := 0 to smallerSide - 1 do begin indx := border_len * i; gbo.addIndex(indx); gbo.addIndex(indx); end; end; AE_TERRAIN_NEIGHBOR_TYPE_RIGHT: ; AE_TERRAIN_NEIGHBOR_TYPE_BOTTOM: ; AE_TERRAIN_NEIGHBOR_TYPE_LEFT: ; end; end; } function TaeTerrainTile.GetDistance(p: TPoint3D): single; var centerPoint: TPoint3D; begin centerPoint.x := (Self._column * AE_TERRAIN_TILE_SIZE) + (AE_TERRAIN_TILE_SIZE div 2); centerPoint.z := (Self._row * AE_TERRAIN_TILE_SIZE) + (AE_TERRAIN_TILE_SIZE div 2); centerPoint.y := Self._GetHeightCall(centerPoint.x, centerPoint.z); Result := p.Distance(centerPoint); end; function TaeTerrainTile.GetManhattanDistance(p: TPoint3D): single; begin // return an approximate distance to the given point. Result := (abs(p.x - Self._row * AE_TERRAIN_TILE_SIZE) + abs(p.z - Self._column * AE_TERRAIN_TILE_SIZE)); end; procedure TaeTerrainTile.SetLOD(lod: TaeMeshLevelOfDetail); begin inherited; case lod of AE_MESH_LOD_HIGH: begin if (Self._ib_lod_high.Empty) then Self.GenerateLODIndexBuffer(Self._ib_lod_high, AE_TERRAIN_TILE_SIZE, AE_TERRAIN_TILE_LOD_RES_HIGH); Self.SetIndexBuffer(Self._ib_lod_high); end; AE_MESH_LOD_MID: begin // now add a middle quality! if (Self._ib_lod_mid.Empty) then Self.GenerateLODIndexBuffer(Self._ib_lod_mid, AE_TERRAIN_TILE_SIZE, AE_TERRAIN_TILE_LOD_RES_MID); Self.SetIndexBuffer(Self._ib_lod_mid); end; AE_MESH_LOD_LOW: begin // now add a low quality! if (Self._ib_lod_low.Empty) then Self.GenerateLODIndexBuffer(Self._ib_lod_low, AE_TERRAIN_TILE_SIZE, AE_TERRAIN_TILE_LOD_RES_LOW); Self.SetIndexBuffer(Self._ib_lod_low); end; end; end; procedure TaeTerrainTile.SetNeighbor(tile: TaeTerrainTile; ntype: TaeTerrainNeighborType); begin case ntype of AE_TERRAIN_NEIGHBOR_TYPE_TOP: Self._n_top := tile; AE_TERRAIN_NEIGHBOR_TYPE_RIGHT: Self._n_right := tile; AE_TERRAIN_NEIGHBOR_TYPE_BOTTOM: Self._n_bottom := tile; AE_TERRAIN_NEIGHBOR_TYPE_LEFT: Self._n_left := tile; end; end; end.
unit AsyncPatcher; interface uses classes, Types, SysUtils, CommandoSettings, UpdateInfo, ExtActns; type TProgressEvent = procedure(AMin, AMax, APosition: Integer) of object; TLogEvent = procedure(AMessage: string) of object; TAsyncPatcher = class(TThread) private FSettings: TCommandoSettings; FUpdates: TUpdateInfo; FSources: TStringList; FUpdateDir: string; FBaseDir: string; FOnLog: TLogEvent; FOnProgress: TProgressEvent; FMessage: string; FPatcherSource: string; FMin: Integer; FMax: Integer; FPosition: Integer; procedure DoLog(AMessage: string); procedure DoProgress(AMin, AMax, APosition: Integer); procedure CallLog(); procedure CallProgress(); procedure WaitIfDesired(); procedure CollectRequiredPatches(); procedure DownloadFiles(); procedure ExtractFiles(); procedure Cleanup(); procedure HandleDownload (Sender: TDownLoadURL; Progress, ProgressMax: Cardinal; StatusCode: TURLDownloadStatus; StatusText: String; var Cancel: Boolean); function HasSelfPatch(): Boolean; procedure SelfPatch(); procedure SelfInstall(); protected procedure Execute(); override; public constructor Create(ASettings: TCommandoSettings; AUpdates: TUpdateInfo); reintroduce; destructor Destroy(); override; property OnProgress: TProgressEvent read FOnProgress write FOnProgress; property OnLog: TLogEvent read FOnLog write FOnLog; end; implementation uses Forms, Windows, VersionCompare, IOUtils, AbBase, AbBrowse, AbZBrows, AbUnzper, PatcherVersion, Process; { TAsyncPatcher } procedure TAsyncPatcher.CallLog; begin if Assigned(FOnLog) then begin FOnLog(FMessage); end; end; procedure TAsyncPatcher.CallProgress; begin if Assigned(FOnProgress) then begin FOnProgress(FMin, FMax, FPosition); end; end; procedure TAsyncPatcher.Cleanup; var LFiles: TStringDynArray; LFile: string; begin if DirectoryExists(FUpdateDir) then begin DoLog('Cleaning Updatefolder...'); LFiles := TDirectory.GetFiles(FUpdateDir); for LFile in LFiles do begin DeleteFile(@LFile[1]); end; RemoveDirectory(@FUpdateDir[1]); end; end; procedure TAsyncPatcher.CollectRequiredPatches; var i: Integer; LVersion: string; begin DoLog('Required Updates:'); for i := 0 to FUpdates.Components.Count - 1 do begin if SameText(FUpdates.Components[i], CPatcherName) then begin LVersion := CPatcherVersion; end else begin LVersion := FSettings.Versions[FUpdates.Components[i]]; end; if NeedsUpdate(LVersion, FUpdates.Versions[i]) then begin DoLog(FUpdates.Components[i] + ' ' + FSettings.Versions[FUpdates.Components[i]] + ' -> ' + FUpdates.Versions[i]); if FSources.IndexOf(FUpdates.Sources[i]) < 0 then begin FSources.Add(FUpdates.Sources[i]); if SameText(FUpdates.Components[i], CPatcherName) then begin FPatcherSource := FUpdates.Sources[i]; end; end; end; end; if FSources.Count = 0 then begin DoLog('<None>'); end; end; constructor TAsyncPatcher.Create(ASettings: TCommandoSettings; AUpdates: TUpdateInfo); begin inherited Create(True); FreeOnTerminate := True; FSources := TStringList.Create(); FSettings := ASettings; FUpdates := AUpdates; FBaseDir := ExtractFilePath(ParamStr(0)); FUpdateDir := FBaseDir + '\updates\'; end; destructor TAsyncPatcher.Destroy; begin FSources.Free; inherited; end; procedure TAsyncPatcher.DoLog(AMessage: string); begin FMessage := AMessage; Synchronize(CallLog); end; procedure TAsyncPatcher.DoProgress(AMin, AMax, APosition: Integer); begin FMin :=AMin; FMax := AMax; FPosition := APosition; Synchronize(CallProgress); end; procedure TAsyncPatcher.DownloadFiles; var LDL: TDownLoadURL; i: Integer; begin DoLog('Downloading files'); ForceDirectories(FUpdateDir); LDL := TDownLoadURL.Create(nil); try LDL.OnDownloadProgress := HandleDownload; if FPatcherSource <> '' then begin DoLog('Downloading patcher...'); LDL.URL := FPatcherSource; LDL.Filename := FUpdateDir + '\' + CPatcherName + '.zip'; LDL.ExecuteTarget(nil); end else begin for i := 0 to FSources.Count - 1 do begin DoLog(IntToStr(i+1) + ' of ' + IntToStr(FSources.Count)); LDL.URL := FSources[i]; LDL.Filename := FUpdateDir + '\' + IntToStr(i) + '.zip'; LDL.ExecuteTarget(nil); end; end; finally LDL.Free; end; end; procedure TAsyncPatcher.Execute; begin inherited; WaitIfDesired(); if FSettings.IsSelfInstall() then begin SelfInstall(); Exit; end; Cleanup(); CollectRequiredPatches(); if FSources.Count > 0 then begin DownloadFiles(); ExtractFiles(); end; if HasSelfPatch() then begin SelfPatch(); Exit; end; Cleanup(); if FileExists(FBaseDir + '\D16IDE.exe') then begin RunProcess(FBaseDir + '\D16IDE.exe', '', False); end; end; procedure TAsyncPatcher.ExtractFiles; var i: Integer; LZip: TAbUnZipper; begin DoLog('Extracting...'); LZip := TAbUnZipper.Create(nil); try if FPatcherSource <> '' then begin LZip.FileName := FUpdateDir + '\' + CPatcherName + '.zip'; LZip.BaseDirectory := FUpdateDir; LZip.ExtractFiles('*'); end else begin for i := 0 to FSources.Count - 1 do begin LZip.FileName := FUpdateDir + '\' + IntToStr(i) + '.zip'; LZip.BaseDirectory := FBaseDir; LZip.ExtractFiles('*'); end; end; finally LZip.Free; end; end; procedure TAsyncPatcher.HandleDownload(Sender: TDownLoadURL; Progress, ProgressMax: Cardinal; StatusCode: TURLDownloadStatus; StatusText: String; var Cancel: Boolean); begin DoProgress(0, ProgressMax, Progress); end; function TAsyncPatcher.HasSelfPatch: Boolean; begin Result := NeedsUpdate(CPatcherVersion, FUpdates.PatcherVersion); end; procedure TAsyncPatcher.SelfInstall; var LTarget: string; begin DoLog('Installing...'); LTarget := FSettings.InstallPath + '\' + CPatcherName + '.exe'; ForceDirectories(FSettings.InstallPath); if CopyFile(@Application.ExeName[1], @LTarget[1], False) then begin FSettings.InstallPath := ''; FSettings.PID := GetCurrentProcessId(); RunProcess(LTarget, FSettings.CommandoLine, False); end else begin raise Exception.Create('Failed to Copy patcher'); end; end; procedure TAsyncPatcher.SelfPatch; begin DoLog('Patching patcher...'); FSettings.InstallPath := FBaseDir; FSettings.PID := GetCurrentProcessId(); RunProcess(FUpdateDir + '\' + CPatcherName + '.exe', FSettings.CommandoLine, False); end; procedure TAsyncPatcher.WaitIfDesired; var LHandle: THandle; begin if FSettings.NeedToWait then begin DoLog('Waiting for host to exit...'); LHandle := OpenProcess(PROCESS_ALL_ACCESS, False, FSettings.PID); if LHandle <> 0 then begin WaitForSingleObject(LHandle, INFINITE); CloseHandle(LHandle); end; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpAesEngine; {$I ..\..\Include\CryptoLib.inc} interface uses SysUtils, ClpIAesEngine, ClpIBlockCipher, ClpICipherParameters, ClpIKeyParameter, ClpCheck, ClpBits, ClpConverters, ClpCryptoLibTypes; resourcestring AESEngineNotInitialised = 'AES Engine not Initialised'; SInputBuffertooShort = 'Input Buffer too Short'; SOutputBuffertooShort = 'Output Buffer too Short'; SInvalidParameterAESInit = 'Invalid Parameter Passed to AES Init - "%s"'; SInvalidKeyLength = 'Key Length not 128/192/256 bits.'; SInvalidOperation = 'Should Never Get Here'; type /// <summary> /// <para> /// an implementation of the AES (Rijndael), from FIPS-197. /// </para> /// <para> /// For further details see: <see href="http://csrc.nist.gov/encryption/aes/" /> /// </para> /// <para> /// This implementation is based on optimizations from Dr. Brian /// Gladman's paper and C code at <see href="http://fp.gladman.plus.com/cryptography_technology/rijndael/" /> /// </para> /// <para> /// This version uses only one 256 word table for each, for a total of /// 2Kbytes, <br />adding 12 rotate operations per round to compute the /// values contained in the other tables from <br />the contents of the /// first. /// </para> /// <para> /// This file contains the middle performance version with 2Kbytes of /// static tables for round precomputation. /// </para> /// </summary> TAesEngine = class sealed(TInterfacedObject, IAesEngine, IBlockCipher) strict private const // multiply four bytes in GF(2^8) by 'x' {02} in parallel // m1 = UInt32($80808080); m2 = UInt32($7F7F7F7F); m3 = UInt32($0000001B); m4 = UInt32($C0C0C0C0); m5 = UInt32($3F3F3F3F); BLOCK_SIZE = Int32(16); var FROUNDS: Int32; FWorkingKey: TCryptoLibMatrixUInt32Array; FC0, FC1, FC2, FC3: UInt32; FforEncryption: Boolean; Fstate: TCryptoLibByteArray; function GetAlgorithmName: String; virtual; function GetIsPartialBlockOkay: Boolean; virtual; function GetBlockSize(): Int32; virtual; /// <summary> /// <para> /// Calculate the necessary round keys /// </para> /// <para> /// The number of calculations depends on key size and block size /// </para> /// <para> /// AES specified a fixed block size of 128 bits and key sizes /// 128/192/256 bits /// </para> /// <para> /// This code is written assuming those are the only possible values /// </para> /// </summary> function GenerateWorkingKey(const key: TCryptoLibByteArray; forEncryption: Boolean): TCryptoLibMatrixUInt32Array; procedure UnPackBlock(const bytes: TCryptoLibByteArray; off: Int32); inline; procedure PackBlock(const bytes: TCryptoLibByteArray; off: Int32); inline; procedure EncryptBlock(const KW: TCryptoLibMatrixUInt32Array); procedure DecryptBlock(const KW: TCryptoLibMatrixUInt32Array); class var Fs, FSi, Frcon: TCryptoLibByteArray; FT0, FTinv0: TCryptoLibUInt32Array; class function Shift(r: UInt32; Shift: Int32): UInt32; static; inline; class function FFmulX(x: UInt32): UInt32; static; inline; class function FFmulX2(x: UInt32): UInt32; static; inline; // The following defines provide alternative definitions of FFmulX that might // give improved performance if a fast 32-bit multiply is not available. // // private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } // private static final int m4 = 0x1b1b1b1b; // private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } class function Inv_Mcol(x: UInt32): UInt32; static; inline; class function SubWord(x: UInt32): UInt32; static; inline; class constructor AesEngine(); public /// <summary> /// initialise an AES cipher. /// </summary> /// <param name="forEncryption"> /// whether or not we are for encryption. /// </param> /// <param name="parameters"> /// the parameters required to set up the cipher. /// </param> /// <exception cref="EArgumentCryptoLibException"> /// if the parameters argument is inappropriate. /// </exception> procedure Init(forEncryption: Boolean; const parameters: ICipherParameters); virtual; function ProcessBlock(const input: TCryptoLibByteArray; inOff: Int32; const output: TCryptoLibByteArray; outOff: Int32): Int32; virtual; procedure Reset(); virtual; property AlgorithmName: String read GetAlgorithmName; property IsPartialBlockOkay: Boolean read GetIsPartialBlockOkay; class procedure Boot; static; end; implementation { TAesEngine } class procedure TAesEngine.Boot; begin // The S box Fs := TCryptoLibByteArray.Create(99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22); // The inverse S-box FSi := TCryptoLibByteArray.Create(82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125); // vector used in calculating key schedule (powers of x in GF(256)) Frcon := TCryptoLibByteArray.Create($01, $02, $04, $08, $10, $20, $40, $80, $1B, $36, $6C, $D8, $AB, $4D, $9A, $2F, $5E, $BC, $63, $C6, $97, $35, $6A, $D4, $B3, $7D, $FA, $EF, $C5, $91); // precomputation tables of calculations for rounds FT0 := TCryptoLibUInt32Array.Create($A56363C6, $847C7CF8, $997777EE, $8D7B7BF6, $0DF2F2FF, $BD6B6BD6, $B16F6FDE, $54C5C591, $50303060, $03010102, $A96767CE, $7D2B2B56, $19FEFEE7, $62D7D7B5, $E6ABAB4D, $9A7676EC, $45CACA8F, $9D82821F, $40C9C989, $877D7DFA, $15FAFAEF, $EB5959B2, $C947478E, $0BF0F0FB, $ECADAD41, $67D4D4B3, $FDA2A25F, $EAAFAF45, $BF9C9C23, $F7A4A453, $967272E4, $5BC0C09B, $C2B7B775, $1CFDFDE1, $AE93933D, $6A26264C, $5A36366C, $413F3F7E, $02F7F7F5, $4FCCCC83, $5C343468, $F4A5A551, $34E5E5D1, $08F1F1F9, $937171E2, $73D8D8AB, $53313162, $3F15152A, $0C040408, $52C7C795, $65232346, $5EC3C39D, $28181830, $A1969637, $0F05050A, $B59A9A2F, $0907070E, $36121224, $9B80801B, $3DE2E2DF, $26EBEBCD, $6927274E, $CDB2B27F, $9F7575EA, $1B090912, $9E83831D, $742C2C58, $2E1A1A34, $2D1B1B36, $B26E6EDC, $EE5A5AB4, $FBA0A05B, $F65252A4, $4D3B3B76, $61D6D6B7, $CEB3B37D, $7B292952, $3EE3E3DD, $712F2F5E, $97848413, $F55353A6, $68D1D1B9, $00000000, $2CEDEDC1, $60202040, $1FFCFCE3, $C8B1B179, $ED5B5BB6, $BE6A6AD4, $46CBCB8D, $D9BEBE67, $4B393972, $DE4A4A94, $D44C4C98, $E85858B0, $4ACFCF85, $6BD0D0BB, $2AEFEFC5, $E5AAAA4F, $16FBFBED, $C5434386, $D74D4D9A, $55333366, $94858511, $CF45458A, $10F9F9E9, $06020204, $817F7FFE, $F05050A0, $443C3C78, $BA9F9F25, $E3A8A84B, $F35151A2, $FEA3A35D, $C0404080, $8A8F8F05, $AD92923F, $BC9D9D21, $48383870, $04F5F5F1, $DFBCBC63, $C1B6B677, $75DADAAF, $63212142, $30101020, $1AFFFFE5, $0EF3F3FD, $6DD2D2BF, $4CCDCD81, $140C0C18, $35131326, $2FECECC3, $E15F5FBE, $A2979735, $CC444488, $3917172E, $57C4C493, $F2A7A755, $827E7EFC, $473D3D7A, $AC6464C8, $E75D5DBA, $2B191932, $957373E6, $A06060C0, $98818119, $D14F4F9E, $7FDCDCA3, $66222244, $7E2A2A54, $AB90903B, $8388880B, $CA46468C, $29EEEEC7, $D3B8B86B, $3C141428, $79DEDEA7, $E25E5EBC, $1D0B0B16, $76DBDBAD, $3BE0E0DB, $56323264, $4E3A3A74, $1E0A0A14, $DB494992, $0A06060C, $6C242448, $E45C5CB8, $5DC2C29F, $6ED3D3BD, $EFACAC43, $A66262C4, $A8919139, $A4959531, $37E4E4D3, $8B7979F2, $32E7E7D5, $43C8C88B, $5937376E, $B76D6DDA, $8C8D8D01, $64D5D5B1, $D24E4E9C, $E0A9A949, $B46C6CD8, $FA5656AC, $07F4F4F3, $25EAEACF, $AF6565CA, $8E7A7AF4, $E9AEAE47, $18080810, $D5BABA6F, $887878F0, $6F25254A, $722E2E5C, $241C1C38, $F1A6A657, $C7B4B473, $51C6C697, $23E8E8CB, $7CDDDDA1, $9C7474E8, $211F1F3E, $DD4B4B96, $DCBDBD61, $868B8B0D, $858A8A0F, $907070E0, $423E3E7C, $C4B5B571, $AA6666CC, $D8484890, $05030306, $01F6F6F7, $120E0E1C, $A36161C2, $5F35356A, $F95757AE, $D0B9B969, $91868617, $58C1C199, $271D1D3A, $B99E9E27, $38E1E1D9, $13F8F8EB, $B398982B, $33111122, $BB6969D2, $70D9D9A9, $898E8E07, $A7949433, $B69B9B2D, $221E1E3C, $92878715, $20E9E9C9, $49CECE87, $FF5555AA, $78282850, $7ADFDFA5, $8F8C8C03, $F8A1A159, $80898909, $170D0D1A, $DABFBF65, $31E6E6D7, $C6424284, $B86868D0, $C3414182, $B0999929, $772D2D5A, $110F0F1E, $CBB0B07B, $FC5454A8, $D6BBBB6D, $3A16162C); FTinv0 := TCryptoLibUInt32Array.Create($50A7F451, $5365417E, $C3A4171A, $965E273A, $CB6BAB3B, $F1459D1F, $AB58FAAC, $9303E34B, $55FA3020, $F66D76AD, $9176CC88, $254C02F5, $FCD7E54F, $D7CB2AC5, $80443526, $8FA362B5, $495AB1DE, $671BBA25, $980EEA45, $E1C0FE5D, $02752FC3, $12F04C81, $A397468D, $C6F9D36B, $E75F8F03, $959C9215, $EB7A6DBF, $DA595295, $2D83BED4, $D3217458, $2969E049, $44C8C98E, $6A89C275, $78798EF4, $6B3E5899, $DD71B927, $B64FE1BE, $17AD88F0, $66AC20C9, $B43ACE7D, $184ADF63, $82311AE5, $60335197, $457F5362, $E07764B1, $84AE6BBB, $1CA081FE, $942B08F9, $58684870, $19FD458F, $876CDE94, $B7F87B52, $23D373AB, $E2024B72, $578F1FE3, $2AAB5566, $0728EBB2, $03C2B52F, $9A7BC586, $A50837D3, $F2872830, $B2A5BF23, $BA6A0302, $5C8216ED, $2B1CCF8A, $92B479A7, $F0F207F3, $A1E2694E, $CDF4DA65, $D5BE0506, $1F6234D1, $8AFEA6C4, $9D532E34, $A055F3A2, $32E18A05, $75EBF6A4, $39EC830B, $AAEF6040, $069F715E, $51106EBD, $F98A213E, $3D06DD96, $AE053EDD, $46BDE64D, $B58D5491, $055DC471, $6FD40604, $FF155060, $24FB9819, $97E9BDD6, $CC434089, $779ED967, $BD42E8B0, $888B8907, $385B19E7, $DBEEC879, $470A7CA1, $E90F427C, $C91E84F8, $00000000, $83868009, $48ED2B32, $AC70111E, $4E725A6C, $FBFF0EFD, $5638850F, $1ED5AE3D, $27392D36, $64D90F0A, $21A65C68, $D1545B9B, $3A2E3624, $B1670A0C, $0FE75793, $D296EEB4, $9E919B1B, $4FC5C080, $A220DC61, $694B775A, $161A121C, $0ABA93E2, $E52AA0C0, $43E0223C, $1D171B12, $0B0D090E, $ADC78BF2, $B9A8B62D, $C8A91E14, $8519F157, $4C0775AF, $BBDD99EE, $FD607FA3, $9F2601F7, $BCF5725C, $C53B6644, $347EFB5B, $7629438B, $DCC623CB, $68FCEDB6, $63F1E4B8, $CADC31D7, $10856342, $40229713, $2011C684, $7D244A85, $F83DBBD2, $1132F9AE, $6DA129C7, $4B2F9E1D, $F330B2DC, $EC52860D, $D0E3C177, $6C16B32B, $99B970A9, $FA489411, $2264E947, $C48CFCA8, $1A3FF0A0, $D82C7D56, $EF903322, $C74E4987, $C1D138D9, $FEA2CA8C, $360BD498, $CF81F5A6, $28DE7AA5, $268EB7DA, $A4BFAD3F, $E49D3A2C, $0D927850, $9BCC5F6A, $62467E54, $C2138DF6, $E8B8D890, $5EF7392E, $F5AFC382, $BE805D9F, $7C93D069, $A92DD56F, $B31225CF, $3B99ACC8, $A77D1810, $6E639CE8, $7BBB3BDB, $097826CD, $F418596E, $01B79AEC, $A89A4F83, $656E95E6, $7EE6FFAA, $08CFBC21, $E6E815EF, $D99BE7BA, $CE366F4A, $D4099FEA, $D67CB029, $AFB2A431, $31233F2A, $3094A5C6, $C066A235, $37BC4E74, $A6CA82FC, $B0D090E0, $15D8A733, $4A9804F1, $F7DAEC41, $0E50CD7F, $2FF69117, $8DD64D76, $4DB0EF43, $544DAACC, $DF0496E4, $E3B5D19E, $1B886A4C, $B81F2CC1, $7F516546, $04EA5E9D, $5D358C01, $737487FA, $2E410BFB, $5A1D67B3, $52D2DB92, $335610E9, $1347D66D, $8C61D79A, $7A0CA137, $8E14F859, $893C13EB, $EE27A9CE, $35C961B7, $EDE51CE1, $3CB1477A, $59DFD29C, $3F73F255, $79CE1418, $BF37C773, $EACDF753, $5BAAFD5F, $146F3DDF, $86DB4478, $81F3AFCA, $3EC468B9, $2C342438, $5F40A3C2, $72C31D16, $0C25E2BC, $8B493C28, $41950DFF, $7101A839, $DEB30C08, $9CE4B4D8, $90C15664, $6184CB7B, $70B632D5, $745C6C48, $4257B8D0); end; class constructor TAesEngine.AesEngine; begin TAesEngine.Boot; end; class function TAesEngine.Shift(r: UInt32; Shift: Int32): UInt32; begin // result := (r shr shift) or (r shl (32 - shift)); result := TBits.RotateRight32(r, Shift); end; class function TAesEngine.SubWord(x: UInt32): UInt32; begin result := UInt32(Fs[x and 255]) or (UInt32(Fs[(x shr 8) and 255]) shl 8) or (UInt32(Fs[(x shr 16) and 255]) shl 16) or (UInt32(Fs[(x shr 24) and 255]) shl 24); end; procedure TAesEngine.DecryptBlock(const KW: TCryptoLibMatrixUInt32Array); var lkw: TCryptoLibUInt32Array; lt0, lt1, lt2, lr0, lr1, lr2, lr3: UInt32; lr: Int32; begin lkw := KW[FROUNDS]; lt0 := FC0 xor lkw[0]; lt1 := FC1 xor lkw[1]; lt2 := FC2 xor lkw[2]; lr3 := FC3 xor lkw[3]; lr := FROUNDS - 1; while (lr > 1) do begin lkw := KW[lr]; System.Dec(lr); lr0 := FTinv0[lt0 and 255] xor Shift(FTinv0[(lr3 shr 8) and 255], 24) xor Shift(FTinv0[(lt2 shr 16) and 255], 16) xor Shift(FTinv0[(lt1 shr 24) and 255], 8) xor lkw[0]; lr1 := FTinv0[lt1 and 255] xor Shift(FTinv0[(lt0 shr 8) and 255], 24) xor Shift(FTinv0[(lr3 shr 16) and 255], 16) xor Shift(FTinv0[(lt2 shr 24) and 255], 8) xor lkw[1]; lr2 := FTinv0[lt2 and 255] xor Shift(FTinv0[(lt1 shr 8) and 255], 24) xor Shift(FTinv0[(lt0 shr 16) and 255], 16) xor Shift(FTinv0[(lr3 shr 24) and 255], 8) xor lkw[2]; lr3 := FTinv0[lr3 and 255] xor Shift(FTinv0[(lt2 shr 8) and 255], 24) xor Shift(FTinv0[(lt1 shr 16) and 255], 16) xor Shift(FTinv0[(lt0 shr 24) and 255], 8) xor lkw[3]; lkw := KW[lr]; System.Dec(lr); lt0 := FTinv0[lr0 and 255] xor Shift(FTinv0[(lr3 shr 8) and 255], 24) xor Shift(FTinv0[(lr2 shr 16) and 255], 16) xor Shift(FTinv0[(lr1 shr 24) and 255], 8) xor lkw[0]; lt1 := FTinv0[lr1 and 255] xor Shift(FTinv0[(lr0 shr 8) and 255], 24) xor Shift(FTinv0[(lr3 shr 16) and 255], 16) xor Shift(FTinv0[(lr2 shr 24) and 255], 8) xor lkw[1]; lt2 := FTinv0[lr2 and 255] xor Shift(FTinv0[(lr1 shr 8) and 255], 24) xor Shift(FTinv0[(lr0 shr 16) and 255], 16) xor Shift(FTinv0[(lr3 shr 24) and 255], 8) xor lkw[2]; lr3 := FTinv0[lr3 and 255] xor Shift(FTinv0[(lr2 shr 8) and 255], 24) xor Shift(FTinv0[(lr1 shr 16) and 255], 16) xor Shift(FTinv0[(lr0 shr 24) and 255], 8) xor lkw[3]; end; lkw := KW[1]; lr0 := FTinv0[lt0 and 255] xor Shift(FTinv0[(lr3 shr 8) and 255], 24) xor Shift(FTinv0[(lt2 shr 16) and 255], 16) xor Shift(FTinv0[(lt1 shr 24) and 255], 8) xor lkw[0]; lr1 := FTinv0[lt1 and 255] xor Shift(FTinv0[(lt0 shr 8) and 255], 24) xor Shift(FTinv0[(lr3 shr 16) and 255], 16) xor Shift(FTinv0[(lt2 shr 24) and 255], 8) xor lkw[1]; lr2 := FTinv0[lt2 and 255] xor Shift(FTinv0[(lt1 shr 8) and 255], 24) xor Shift(FTinv0[(lt0 shr 16) and 255], 16) xor Shift(FTinv0[(lr3 shr 24) and 255], 8) xor lkw[2]; lr3 := FTinv0[lr3 and 255] xor Shift(FTinv0[(lt2 shr 8) and 255], 24) xor Shift(FTinv0[(lt1 shr 16) and 255], 16) xor Shift(FTinv0[(lt0 shr 24) and 255], 8) xor lkw[3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it lkw := KW[0]; FC0 := UInt32(FSi[lr0 and 255]) xor ((UInt32(Fstate[(lr3 shr 8) and 255])) shl 8) xor ((UInt32(Fstate[(lr2 shr 16) and 255])) shl 16) xor ((UInt32(FSi[(lr1 shr 24) and 255])) shl 24) xor lkw[0]; FC1 := UInt32(Fstate[lr1 and 255]) xor ((UInt32(Fstate[(lr0 shr 8) and 255])) shl 8) xor ((UInt32(FSi[(lr3 shr 16) and 255])) shl 16) xor ((UInt32(Fstate[(lr2 shr 24) and 255])) shl 24) xor lkw[1]; FC2 := UInt32(Fstate[lr2 and 255]) xor ((UInt32(FSi[(lr1 shr 8) and 255])) shl 8) xor ((UInt32(FSi[(lr0 shr 16) and 255])) shl 16) xor ((UInt32(Fstate[(lr3 shr 24) and 255])) shl 24) xor lkw[2]; FC3 := UInt32(FSi[lr3 and 255]) xor ((UInt32(Fstate[(lr2 shr 8) and 255])) shl 8) xor ((UInt32(Fstate[(lr1 shr 16) and 255])) shl 16) xor ((UInt32(Fstate[(lr0 shr 24) and 255])) shl 24) xor lkw[3]; end; procedure TAesEngine.EncryptBlock(const KW: TCryptoLibMatrixUInt32Array); var lkw: TCryptoLibUInt32Array; lt0, lt1, lt2, lr0, lr1, lr2, lr3: UInt32; lr: Int32; begin lkw := KW[0]; lt0 := FC0 xor lkw[0]; lt1 := FC1 xor lkw[1]; lt2 := FC2 xor lkw[2]; lr3 := FC3 xor lkw[3]; lr := 1; while (lr < (FROUNDS - 1)) do begin lkw := KW[lr]; System.Inc(lr); lr0 := FT0[lt0 and 255] xor Shift(FT0[(lt1 shr 8) and 255], 24) xor Shift(FT0[(lt2 shr 16) and 255], 16) xor Shift(FT0[(lr3 shr 24) and 255], 8) xor lkw[0]; lr1 := FT0[lt1 and 255] xor Shift(FT0[(lt2 shr 8) and 255], 24) xor Shift(FT0[(lr3 shr 16) and 255], 16) xor Shift(FT0[(lt0 shr 24) and 255], 8) xor lkw[1]; lr2 := FT0[lt2 and 255] xor Shift(FT0[(lr3 shr 8) and 255], 24) xor Shift(FT0[(lt0 shr 16) and 255], 16) xor Shift(FT0[(lt1 shr 24) and 255], 8) xor lkw[2]; lr3 := FT0[lr3 and 255] xor Shift(FT0[(lt0 shr 8) and 255], 24) xor Shift(FT0[(lt1 shr 16) and 255], 16) xor Shift(FT0[(lt2 shr 24) and 255], 8) xor lkw[3]; lkw := KW[lr]; System.Inc(lr); lt0 := FT0[lr0 and 255] xor Shift(FT0[(lr1 shr 8) and 255], 24) xor Shift(FT0[(lr2 shr 16) and 255], 16) xor Shift(FT0[(lr3 shr 24) and 255], 8) xor lkw[0]; lt1 := FT0[lr1 and 255] xor Shift(FT0[(lr2 shr 8) and 255], 24) xor Shift(FT0[(lr3 shr 16) and 255], 16) xor Shift(FT0[(lr0 shr 24) and 255], 8) xor lkw[1]; lt2 := FT0[lr2 and 255] xor Shift(FT0[(lr3 shr 8) and 255], 24) xor Shift(FT0[(lr0 shr 16) and 255], 16) xor Shift(FT0[(lr1 shr 24) and 255], 8) xor lkw[2]; lr3 := FT0[lr3 and 255] xor Shift(FT0[(lr0 shr 8) and 255], 24) xor Shift(FT0[(lr1 shr 16) and 255], 16) xor Shift(FT0[(lr2 shr 24) and 255], 8) xor lkw[3]; end; lkw := KW[lr]; System.Inc(lr); lr0 := FT0[lt0 and 255] xor Shift(FT0[(lt1 shr 8) and 255], 24) xor Shift(FT0[(lt2 shr 16) and 255], 16) xor Shift(FT0[(lr3 shr 24) and 255], 8) xor lkw[0]; lr1 := FT0[lt1 and 255] xor Shift(FT0[(lt2 shr 8) and 255], 24) xor Shift(FT0[(lr3 shr 16) and 255], 16) xor Shift(FT0[(lt0 shr 24) and 255], 8) xor lkw[1]; lr2 := FT0[lt2 and 255] xor Shift(FT0[(lr3 shr 8) and 255], 24) xor Shift(FT0[(lt0 shr 16) and 255], 16) xor Shift(FT0[(lt1 shr 24) and 255], 8) xor lkw[2]; lr3 := FT0[lr3 and 255] xor Shift(FT0[(lt0 shr 8) and 255], 24) xor Shift(FT0[(lt1 shr 16) and 255], 16) xor Shift(FT0[(lt2 shr 24) and 255], 8) xor lkw[3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it lkw := KW[lr]; FC0 := UInt32(Fs[lr0 and 255]) xor ((UInt32(Fs[(lr1 shr 8) and 255])) shl 8) xor ((UInt32(Fstate[(lr2 shr 16) and 255])) shl 16) xor ((UInt32(Fstate[(lr3 shr 24) and 255])) shl 24) xor lkw[0]; FC1 := UInt32(Fstate[lr1 and 255]) xor ((UInt32(Fs[(lr2 shr 8) and 255])) shl 8) xor ((UInt32(Fs[(lr3 shr 16) and 255])) shl 16) xor ((UInt32(Fstate[(lr0 shr 24) and 255])) shl 24) xor lkw[1]; FC2 := UInt32(Fstate[lr2 and 255]) xor ((UInt32(Fs[(lr3 shr 8) and 255])) shl 8) xor ((UInt32(Fs[(lr0 shr 16) and 255])) shl 16) xor ((UInt32(Fs[(lr1 shr 24) and 255])) shl 24) xor lkw[2]; FC3 := UInt32(Fstate[lr3 and 255]) xor ((UInt32(Fstate[(lr0 shr 8) and 255])) shl 8) xor ((UInt32(Fstate[(lr1 shr 16) and 255])) shl 16) xor ((UInt32(Fs[(lr2 shr 24) and 255])) shl 24) xor lkw[3]; end; class function TAesEngine.FFmulX(x: UInt32): UInt32; begin result := ((x and m2) shl 1) xor (((x and m1) shr 7) * m3); end; class function TAesEngine.FFmulX2(x: UInt32): UInt32; var t0, t1: UInt32; begin t0 := (x and m5) shl 2; t1 := (x and m4); t1 := t1 xor (t1 shr 1); result := t0 xor (t1 shr 2) xor (t1 shr 5); end; class function TAesEngine.Inv_Mcol(x: UInt32): UInt32; var t0, t1: UInt32; begin t0 := x; t1 := t0 xor Shift(t0, 8); t0 := t0 xor FFmulX(t1); t1 := t1 xor FFmulX2(t0); t0 := t0 xor (t1 xor Shift(t1, 16)); result := t0; end; function TAesEngine.GenerateWorkingKey(const key: TCryptoLibByteArray; forEncryption: Boolean): TCryptoLibMatrixUInt32Array; var keyLen, KC, i, j: Int32; smallw: TCryptoLibUInt32Array; bigW: TCryptoLibMatrixUInt32Array; u, rcon, t0, t1, t2, t3, t4, t5, t6, t7: UInt32; begin keyLen := System.Length(key); if ((keyLen < 16) or (keyLen > 32) or ((keyLen and 7) <> 0)) then begin raise EArgumentCryptoLibException.CreateRes(@SInvalidKeyLength); end; KC := keyLen shr 2; // KC := keyLen div 4; FROUNDS := KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes System.SetLength(bigW, FROUNDS + 1); // 4 words in a block for i := 0 to FROUNDS do begin System.SetLength(bigW[i], 4); end; case KC of 4: begin t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0); bigW[0][0] := t0; t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4); bigW[0][1] := t1; t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8); bigW[0][2] := t2; t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12); bigW[0][3] := t3; for i := 1 to 10 do begin u := SubWord(Shift(t3, 8)) xor Frcon[i - 1]; t0 := t0 xor u; bigW[i][0] := t0; t1 := t1 xor t0; bigW[i][1] := t1; t2 := t2 xor t1; bigW[i][2] := t2; t3 := t3 xor t2; bigW[i][3] := t3; end; end; 6: begin t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0); bigW[0][0] := t0; t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4); bigW[0][1] := t1; t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8); bigW[0][2] := t2; t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12); bigW[0][3] := t3; t4 := TConverters.ReadBytesAsUInt32LE(PByte(key), 16); bigW[1][0] := t4; t5 := TConverters.ReadBytesAsUInt32LE(PByte(key), 20); bigW[1][1] := t5; rcon := 1; u := SubWord(Shift(t5, 8)) xor rcon; rcon := rcon shl 1; t0 := t0 xor u; bigW[1][2] := t0; t1 := t1 xor t0; bigW[1][3] := t1; t2 := t2 xor t1; bigW[2][0] := t2; t3 := t3 xor t2; bigW[2][1] := t3; t4 := t4 xor t3; bigW[2][2] := t4; t5 := t5 xor t4; bigW[2][3] := t5; i := 3; while i < 12 do begin u := SubWord(Shift(t5, 8)) xor rcon; rcon := rcon shl 1; t0 := t0 xor u; bigW[i][0] := t0; t1 := t1 xor t0; bigW[i][1] := t1; t2 := t2 xor t1; bigW[i][2] := t2; t3 := t3 xor t2; bigW[i][3] := t3; t4 := t4 xor t3; bigW[i + 1][0] := t4; t5 := t5 xor t4; bigW[i + 1][1] := t5; u := SubWord(Shift(t5, 8)) xor rcon; rcon := rcon shl 1; t0 := t0 xor u; bigW[i + 1][2] := t0; t1 := t1 xor t0; bigW[i + 1][3] := t1; t2 := t2 xor t1; bigW[i + 2][0] := t2; t3 := t3 xor t2; bigW[i + 2][1] := t3; t4 := t4 xor t3; bigW[i + 2][2] := t4; t5 := t5 xor t4; bigW[i + 2][3] := t5; System.Inc(i, 3); end; u := SubWord(Shift(t5, 8)) xor rcon; t0 := t0 xor u; bigW[12][0] := t0; t1 := t1 xor t0; bigW[12][1] := t1; t2 := t2 xor t1; bigW[12][2] := t2; t3 := t3 xor t2; bigW[12][3] := t3; end; 8: begin t0 := TConverters.ReadBytesAsUInt32LE(PByte(key), 0); bigW[0][0] := t0; t1 := TConverters.ReadBytesAsUInt32LE(PByte(key), 4); bigW[0][1] := t1; t2 := TConverters.ReadBytesAsUInt32LE(PByte(key), 8); bigW[0][2] := t2; t3 := TConverters.ReadBytesAsUInt32LE(PByte(key), 12); bigW[0][3] := t3; t4 := TConverters.ReadBytesAsUInt32LE(PByte(key), 16); bigW[1][0] := t4; t5 := TConverters.ReadBytesAsUInt32LE(PByte(key), 20); bigW[1][1] := t5; t6 := TConverters.ReadBytesAsUInt32LE(PByte(key), 24); bigW[1][2] := t6; t7 := TConverters.ReadBytesAsUInt32LE(PByte(key), 28); bigW[1][3] := t7; rcon := 1; i := 2; while i < 14 do begin u := SubWord(Shift(t7, 8)) xor rcon; rcon := rcon shl 1; t0 := t0 xor u; bigW[i][0] := t0; t1 := t1 xor t0; bigW[i][1] := t1; t2 := t2 xor t1; bigW[i][2] := t2; t3 := t3 xor t2;; bigW[i][3] := t3; u := SubWord(t3); t4 := t4 xor u; bigW[i + 1][0] := t4; t5 := t5 xor t4; bigW[i + 1][1] := t5; t6 := t6 xor t5; bigW[i + 1][2] := t6; t7 := t7 xor t6; bigW[i + 1][3] := t7; System.Inc(i, 2); end; u := SubWord(Shift(t7, 8)) xor rcon; t0 := t0 xor u; bigW[14][0] := t0; t1 := t1 xor t0; bigW[14][1] := t1; t2 := t2 xor t1; bigW[14][2] := t2; t3 := t3 xor t2;; bigW[14][3] := t3; end else begin raise EInvalidOperationCryptoLibException.CreateRes(@SInvalidOperation); end; end; if (not forEncryption) then begin for j := 1 to System.Pred(FROUNDS) do begin smallw := bigW[j]; for i := 0 to System.Pred(4) do begin smallw[i] := Inv_Mcol(smallw[i]); end; end; end; result := bigW; end; function TAesEngine.GetAlgorithmName: String; begin result := 'AES'; end; function TAesEngine.GetBlockSize: Int32; begin result := BLOCK_SIZE; end; function TAesEngine.GetIsPartialBlockOkay: Boolean; begin result := false; end; procedure TAesEngine.Init(forEncryption: Boolean; const parameters: ICipherParameters); var keyParameter: IKeyParameter; begin if not Supports(parameters, IKeyParameter, keyParameter) then begin raise EArgumentCryptoLibException.CreateResFmt(@SInvalidParameterAESInit, [(parameters as TObject).ToString]); end; FWorkingKey := GenerateWorkingKey(keyParameter.GetKey(), forEncryption); FforEncryption := forEncryption; if forEncryption then begin Fstate := System.Copy(Fs); end else begin Fstate := System.Copy(FSi); end; end; procedure TAesEngine.PackBlock(const bytes: TCryptoLibByteArray; off: Int32); begin TConverters.ReadUInt32AsBytesLE(FC0, bytes, off); TConverters.ReadUInt32AsBytesLE(FC1, bytes, off + 4); TConverters.ReadUInt32AsBytesLE(FC2, bytes, off + 8); TConverters.ReadUInt32AsBytesLE(FC3, bytes, off + 12); end; procedure TAesEngine.UnPackBlock(const bytes: TCryptoLibByteArray; off: Int32); begin FC0 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off); FC1 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 4); FC2 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 8); FC3 := TConverters.ReadBytesAsUInt32LE(PByte(bytes), off + 12); end; function TAesEngine.ProcessBlock(const input: TCryptoLibByteArray; inOff: Int32; const output: TCryptoLibByteArray; outOff: Int32): Int32; begin if (FWorkingKey = Nil) then begin raise EInvalidOperationCryptoLibException.CreateRes (@AESEngineNotInitialised); end; TCheck.DataLength(input, inOff, 16, SInputBuffertooShort); TCheck.OutputLength(output, outOff, 16, SOutputBuffertooShort); UnPackBlock(input, inOff); if (FforEncryption) then begin EncryptBlock(FWorkingKey); end else begin DecryptBlock(FWorkingKey); end; PackBlock(output, outOff); result := BLOCK_SIZE; end; procedure TAesEngine.Reset; begin // nothing to do. end; end.
unit Parsers.Excel.Indexes.Kvartal; interface uses SysUtils, Classes, GsDocument, Parsers.Excel, Parsers.Abstract, StrUtils, GlobalData; type TKvartalIndexRow = class (TExcelRowWrapper) public function IsChapter: Boolean; function IsSubChapters: Boolean; function IsIndexRow: Boolean; function GetIndexValue(Column: Integer; Suffix: Integer): Real; function IndexConvertFloat(StrValue: string): Real; end; TKvartalIndexParser = class (TExcelParser<TGsDocument, TKvartalIndexRow>) private FChapter: TGsAbstractContainer; FSubChapters: array of TGsAbstractContainer; FSuffix: Integer; FLastGroupCaption: string; FCode: Integer; protected function DoGetDocument: TGsDocument; override; procedure DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); override; procedure DoParseRow(AExcelRow: TKvartalIndexRow; ARowIndex: Integer; ADocument: TGsDocument); override; public property Suffix: Integer read FSuffix write FSuffix; end; const SMR = Ord(iaSMR); TER = 1; FER = 0; implementation { TKvartalIndexParser } function TKvartalIndexParser.DoGetDocument: TGsDocument; begin Result := TGsDocument.Create; Result.DocumentType := dtIndex; FChapter := Result.Chapters; end; procedure TKvartalIndexParser.DoParseRow(AExcelRow: TKvartalIndexRow; ARowIndex: Integer; ADocument: TGsDocument); var I: Integer; Index: TGsIndexElement; begin if AExcelRow.ContainsText('(áåç ÍÄÑ)') or AExcelRow.IsEmpty then Exit; if AExcelRow.IsChapter then begin if AnsiStartsText('Èíäåêñû', AExcelRow.FirstValue) then FChapter := TGsDocument.CreateChapterByPriority(FChapter, CP_BRANCH) else FChapter := TGsDocument.CreateChapterByPriority(FChapter, CP_CHAPTER); FChapter.Caption := AExcelRow.FirstValue; SetLength(FSubChapters, 0); end else if AExcelRow.IsSubChapters then begin FCode := 1; SetLength(FSubChapters, AExcelRow.FilledValuesCount); for I := 0 to Length(FSubChapters) - 1 do begin FSubChapters[I] := TGsAbstractContainer.Create(ADocument); FChapter.Add(FSubChapters[I]); FSubChapters[I].Caption := AExcelRow.Values[I + 2]; end; end else if AExcelRow.IsIndexRow then begin if (not AExcelRow.Values[0].IsEmpty) and (not AExcelRow.Values[1].IsEmpty) then FLastGroupCaption := AExcelRow.FirstValue; for I := 0 to Length(FSubChapters) - 1 do begin Index := TGsIndexElement.Create(ADocument); FSubChapters[I].Add(Index); if AExcelRow.Values[1].IsEmpty then Index.Caption := AExcelRow.FirstValue else Index.Caption := FLastGroupCaption + ': ' + AExcelRow.Values[1]; Index.Code := IntToStr(FCode); case FSuffix of FER: Index.Code := 'ÔÅÐ-' + Index.Code; TER: Index.Code := 'ÒÅÐ-' + Index.Code; end; Index.SMR := AExcelRow.GetIndexValue(I + 2, Suffix); end; Inc(FCode); end; end; procedure TKvartalIndexParser.DoParseSheet(AExcelSheet: TExcelSheet; ADocument: TGsDocument); var Prefix: string; begin inherited DoParseSheet(AExcelSheet, ADocument); case Suffix of TER: Prefix := ' èíäåêñû ê ÒÅÐ'; FER: Prefix := ' èíäåêñû ê ÔÅÐ'; else Prefix := ''; end; ADocument.SaveToFile(ChangeFileExt(AExcelSheet.Owner.FileName, Prefix + '.xml')); end; { TKvartalIndexRow } function TKvartalIndexRow.GetIndexValue(Column, Suffix: Integer): Real; var p: Integer; begin p := Pos(' ', Values[Column]); Result := 1; case Suffix of TER: begin if p > 0 then Result := IndexConvertFloat(System.Copy(Values[Column], p+1, 255)) else Result := 1; end; FER: begin if p > 0 then Result := IndexConvertFloat(System.Copy(Values[Column], 1, p-1)) else Result := IndexConvertFloat(Values[Column]); end; end; end; function TKvartalIndexRow.IndexConvertFloat(StrValue: string): Real; begin if StrValue = '-' then StrValue := '1' else if StrValue = '' then StrValue := '1'; Result := ConvertToFloat(StrValue); end; function TKvartalIndexRow.IsChapter: Boolean; begin Result := FilledValuesCount = 1; end; function TKvartalIndexRow.IsIndexRow: Boolean; begin Result := FilledValuesCount > 2; end; function TKvartalIndexRow.IsSubChapters: Boolean; begin Result := FirstValue = Values[2] end; end.
unit l3FrameLinesSpy; {* Сохранение информации по опечатанным линиям (для отрисовки не работает). } // Модуль: "w:\common\components\rtl\Garant\L3\l3FrameLinesSpy.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3FrameLinesSpy" MUID: (4D00B058024F) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3ProtoObject , l3Filer , l3FrameObject , l3InternalInterfaces ; type Tl3FrameLinesSpy = class; Il3FrameLinesLogger = interface ['{E5FD726A-30C8-4738-830E-D410AAE40FCA}'] function OpenLinesLog(const aCanvas: Il3InfoCanvas; aObjID: Integer): AnsiString; procedure CloseLinesLog(const aLogName: AnsiString); function GetPrecision: Integer; end;//Il3FrameLinesLogger Tl3FrameLinesSpy = class(Tl3ProtoObject) {* Сохранение информации по опечатанным линиям (для отрисовки не работает). } private f_Logger: Il3FrameLinesLogger; f_Filer: Tl3CustomFiler; f_Printing: Boolean; f_NeedClear: Boolean; protected procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public class function Exists: Boolean; procedure LogLines(aLines: Tl3FrameObject; const aCanvas: Il3InfoCanvas; anIndex: Integer); procedure SetLogger(const aLogger: Il3FrameLinesLogger; aPrinting: Boolean); procedure RemoveLogger(const aLogger: Il3FrameLinesLogger); class function Instance: Tl3FrameLinesSpy; {* Метод получения экземпляра синглетона Tl3FrameLinesSpy } public property NeedClear: Boolean read f_NeedClear write f_NeedClear; end;//Tl3FrameLinesSpy implementation uses l3ImplUses , l3FrameLine , l3Types , SysUtils , l3Interfaces , l3Base //#UC START# *4D00B058024Fimpl_uses* //#UC END# *4D00B058024Fimpl_uses* ; var g_Tl3FrameLinesSpy: Tl3FrameLinesSpy = nil; {* Экземпляр синглетона Tl3FrameLinesSpy } procedure Tl3FrameLinesSpyFree; {* Метод освобождения экземпляра синглетона Tl3FrameLinesSpy } begin l3Free(g_Tl3FrameLinesSpy); end;//Tl3FrameLinesSpyFree class function Tl3FrameLinesSpy.Exists: Boolean; begin Result := g_Tl3FrameLinesSpy <> nil; end;//Tl3FrameLinesSpy.Exists procedure Tl3FrameLinesSpy.LogLines(aLines: Tl3FrameObject; const aCanvas: Il3InfoCanvas; anIndex: Integer); //#UC START# *4D00BAD501C9_4D00B058024F_var* function MangleCoord(aValue : Integer): Integer; begin with f_Logger do Result := (aValue div GetPrecision) * GetPrecision; end; function LogElement(Data: PObject; Index: Integer): Boolean; var i : Integer; l_LinePart : Tl3LinePart; l_FrameLine : Tl3FrameLine; begin Result := True; l_FrameLine := Tl3FrameLine(Data^); f_Filer.WriteLn('----'); for i := 0 to l_FrameLine.GetBoundsArray.Count - 1 do begin l_LinePart := l_FrameLine.GetBoundsArray.Items[i]; case l_LinePart.rDrawType of lpdDraw: f_Filer.WriteLn('lpdDraw'); lpdSpecialDraw: f_Filer.WriteLn('lpdSpecialDraw'); lpdHidden: f_Filer.WriteLn('lpdHidden'); end; // case l_LinePart.rDrawType of f_Filer.WriteLn(Format('"Начало - Окончание": %d - %d', [MangleCoord(l_LinePart.rStart.LineCoordinate), MangleCoord(l_LinePart.rFinish.LineCoordinate)])); end; // for i := 0 to l_FrameLine.GetBoundsArray.Count - 1 do end; var l_LogName : String; l_ColorArr : Tl3LinesColorArray; l_RightLogging : Boolean; //#UC END# *4D00BAD501C9_4D00B058024F_var* begin //#UC START# *4D00BAD501C9_4D00B058024F_impl* l_RightLogging := not (f_Printing xor aCanvas.Printing); // Или печать или отрисовка! if (f_Logger <> nil) and l_RightLogging and not f_NeedClear then begin l_LogName := f_Logger.OpenLinesLog(aCanvas, anIndex); f_Filer := Tl3CustomDOSFiler.Make(l_LogName, l3_fmWrite); try f_Filer.Open; try l_ColorArr := aLines.GetColorArray; if not aCanvas.Printing then begin f_Filer.WriteLn('----'); f_Filer.WriteLn('Цвета:'); f_Filer.WriteLn(Format('%d %d %d', [l_ColorArr[lpdDraw], l_ColorArr[lpdSpecialDraw], l_ColorArr[lpdHidden]])); end; // if not aCanvas.Printing then f_Filer.WriteLn('----'); f_Filer.WriteLn('Горизонтальные линии:'); aLines.GetLines(False).GetValues.IterateAllF(l3L2IA(@LogElement)); f_Filer.WriteLn('----'); f_Filer.WriteLn('Вертикальные линии:'); aLines.GetLines(True).GetValues.IterateAllF(l3L2IA(@LogElement)); finally f_Filer.Close; end;//try..finally finally FreeAndNil(f_Filer); end;//try..finally f_Logger.CloseLinesLog(l_LogName); end;//f_Logger <> nil //#UC END# *4D00BAD501C9_4D00B058024F_impl* end;//Tl3FrameLinesSpy.LogLines procedure Tl3FrameLinesSpy.SetLogger(const aLogger: Il3FrameLinesLogger; aPrinting: Boolean); //#UC START# *4D00CCAB029E_4D00B058024F_var* //#UC END# *4D00CCAB029E_4D00B058024F_var* begin //#UC START# *4D00CCAB029E_4D00B058024F_impl* Assert(f_Logger = nil); f_NeedClear := False; f_Logger := aLogger; f_Printing := aPrinting; //#UC END# *4D00CCAB029E_4D00B058024F_impl* end;//Tl3FrameLinesSpy.SetLogger procedure Tl3FrameLinesSpy.RemoveLogger(const aLogger: Il3FrameLinesLogger); //#UC START# *4D00CCF000BC_4D00B058024F_var* //#UC END# *4D00CCF000BC_4D00B058024F_var* begin //#UC START# *4D00CCF000BC_4D00B058024F_impl* Assert(f_Logger = aLogger); f_NeedClear := False; f_Logger := nil; f_Printing := False; //#UC END# *4D00CCF000BC_4D00B058024F_impl* end;//Tl3FrameLinesSpy.RemoveLogger class function Tl3FrameLinesSpy.Instance: Tl3FrameLinesSpy; {* Метод получения экземпляра синглетона Tl3FrameLinesSpy } begin if (g_Tl3FrameLinesSpy = nil) then begin l3System.AddExitProc(Tl3FrameLinesSpyFree); g_Tl3FrameLinesSpy := Create; end; Result := g_Tl3FrameLinesSpy; end;//Tl3FrameLinesSpy.Instance procedure Tl3FrameLinesSpy.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4D00B058024F_var* //#UC END# *479731C50290_4D00B058024F_var* begin //#UC START# *479731C50290_4D00B058024F_impl* FreeAndNil(f_Filer); inherited; //#UC END# *479731C50290_4D00B058024F_impl* end;//Tl3FrameLinesSpy.Cleanup procedure Tl3FrameLinesSpy.ClearFields; begin f_Logger := nil; inherited; end;//Tl3FrameLinesSpy.ClearFields end.
unit fmContainerSelection; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, ADC.Types, ADC.DC; type TForm_Container = class(TForm) TreeView_Containers: TTreeView; Button_Cancel: TButton; Button_OK: TButton; Label_Description: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button_CancelClick(Sender: TObject); procedure TreeView_ContainersChange(Sender: TObject; Node: TTreeNode); procedure TreeView_ContainersDeletion(Sender: TObject; Node: TTreeNode); procedure Button_OKClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FCallingForm: TForm; FDC: TDCInfo; FDefaultPath: string; FDescription: string; FSelectedContainer: TADContainer; FOnContainerSelect: TSelectContainerProc; FContainedClass: string; procedure SetCallingForm(const Value: TForm); procedure SetDomainController(const Value: TDCInfo); procedure OpenContainer(APath: string); procedure SetDefaulPath(const Value: string); procedure SetDescription(const Value: string); procedure SetContainedClass(const Value: string); public property CallingForm: TForm write SetCallingForm; property DomainController: TDCInfo read FDC write SetDomainController; property DefaultPath: string write SetDefaulPath; property ContainedClass: string write SetContainedClass; property Description: string read FDescription write SetDescription; property OnContainerSelect: TSelectContainerProc read FOnContainerSelect write FOnContainerSelect; end; var Form_Container: TForm_Container; implementation uses dmDataModule; {$R *.dfm} { TForm_Container } procedure TForm_Container.Button_CancelClick(Sender: TObject); begin Close; end; procedure TForm_Container.Button_OKClick(Sender: TObject); begin if Assigned(FOnContainerSelect) then Self.OnContainerSelect(Self, FSelectedContainer) else Close; end; procedure TForm_Container.FormClose(Sender: TObject; var Action: TCloseAction); begin SetDescription(''); FDefaultPath := ''; FContainedClass := ''; FOnContainerSelect := nil; TreeView_Containers.Items.Clear; Button_OK.Enabled := False; if FCallingForm <> nil then begin FCallingForm.Enabled := True; FCallingForm.Show; FCallingForm := nil; end; end; procedure TForm_Container.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_ESCAPE: begin Close; end; end; end; procedure TForm_Container.OpenContainer(APath: string); function GetNode(ParentNode: TTreeNode; NodeName: string): TTreeNode; var TmpNode: TTreeNode; begin if ParentNode = nil then TmpNode := TreeView_Containers.Items.GetFirstNode else TmpNode := ParentNode.GetFirstChild; while (TmpNode <> nil) and (CompareText(TmpNode.Text, NodeName) <> 0) do TmpNode := TmpNode.GetNextSibling; Result := TmpNode; end; var NodeNames: TStringList; pn: TTreeNode; n: TTreeNode; i: Integer; begin NodeNames := TStringList.Create; NodeNames.StrictDelimiter := True; NodeNames.Delimiter := '/'; NodeNames.DelimitedText := APath; pn := nil; n := nil; for i := 0 to NodeNames.Count - 1 do begin n := GetNode(pn, NodeNames[i]); if n = nil then Break else pn := n; end; NodeNames.Free; if n <> nil then TreeView_Containers.Selected := n; end; procedure TForm_Container.SetCallingForm(const Value: TForm); begin FCallingForm := Value; end; procedure TForm_Container.SetContainedClass(const Value: string); begin FContainedClass := Value; end; procedure TForm_Container.SetDefaulPath(const Value: string); begin FDefaultPath := Value; OpenContainer(Value); end; procedure TForm_Container.SetDescription(const Value: string); begin FDescription := Value; if FDescription.IsEmpty then Label_Description.Caption := 'Укажите контейнер Active Directory.' else Label_Description.Caption := Value; end; procedure TForm_Container.SetDomainController(const Value: TDCInfo); var n: TTreeNode; begin FDC := Value; if FDC <> nil then FDC.BuildTree(TreeView_Containers); if not FDefaultPath.IsEmpty then OpenContainer(FDefaultPath); if not FContainedClass.IsEmpty then for n in TreeView_Containers.Items do if n.Data <> nil then n.Enabled := (n.IsFirstNode) or (PADContainer(n.Data)^.CanContainClass(FContainedClass)); end; procedure TForm_Container.TreeView_ContainersChange(Sender: TObject; Node: TTreeNode); begin FSelectedContainer.Clear; Button_OK.Enabled := Node <> nil; if (Node <> nil) and (Node.Enabled) then begin FSelectedContainer := PADContainer(Node.Data)^; end; end; procedure TForm_Container.TreeView_ContainersDeletion(Sender: TObject; Node: TTreeNode); begin { В узлах дерева хранятся данные типа PADContainerData. Поэтому, } { прежде чем очистить дерево/удалить узел, необходимо освободить } { память занимаемую этими данными } if Node.Data <> nil then Dispose(Node.Data); Node.Data := nil; end; end.
{*******************************************************} { YAGE: Yet Another Global Encoder } { Unit: Main.Exec } { Copyright(c) 2019 Alexey Anisimov } { Contact email: softlight@ya.ru } {*******************************************************} unit Main.Exec; interface uses Winapi.Windows, System.Classes, Helper.Singleton, Helper.Console, Main.Help; type TApp = class(TSingleton) const FOutputFileExt: string = '.xml'; protected constructor Create; override; private FParamList: TStringList; FExitCode: Integer; FStartTime: TDateTime; FStopTime: TDateTime; FElapsedTime: Int64; FInputFile: string; FOutputFile: string; FLog: Boolean; FEncoding: string; FLanguage: string; procedure GetParamList; function SearchParam(const Key: string; var Value: string): Integer; procedure ConvertTextGE(InputText: TStringList; OutputText: TStringList); procedure ConvertTextAZ(InputText: TStringList; OutputText: TStringList); public destructor Destroy; override; property ExitCode: Integer read FExitCode; property StartTime: TDateTime read FStartTime write FStartTime; property StopTime: TDateTime read FStopTime write FStopTime; property ElapsedTime: Int64 read FElapsedTime write FElapsedTime; property InputFile: string read FInputFile; property OutputFile: string read FOutputFile; property Log: Boolean read FLog; property FileLanguage: string read FLanguage; property FileEncoding: string read FEncoding; procedure Init; procedure WriteParams; function CheckParams: Boolean; procedure Execute; procedure Finish; end; function App: TApp; resourcestring // application info rsAppName = 'YAGE'; rsAppDescription = 'Yet Another Global Encoder'; rsAppVer = '1.3'; rsCopyright = 'Copyright (c) 2019 Alexey Anisimov / Email: softlight@ya.ru'; rs_UsageHelp = 'Usage: %s.exe SourceFile [keys]'; // error messages rs_ErrFileNotFound = 'File "%s" not found.'; rs_ErrParamError = 'Value for parameter "%s" = "%s" is invalid.'; rs_ErrInvalidParam = 'Parameter "%s" is invalid.'; implementation uses System.SysUtils, System.DateUtils, System.IOUtils, Common.ShellFileSupport; function App: TApp; begin Result := TApp.GetInstance; end; { TApp } constructor TApp.Create; begin inherited Create; // Init settings here FExitCode := -1; FInputFile := ''; FOutputFile := ''; FParamList := TStringList.Create; end; destructor TApp.Destroy; begin // Save settings here FreeAndNil(FParamList); inherited Destroy; end; procedure TApp.GetParamList; var i, n: Integer; begin FParamList.Clear; n := ParamCount; for i := 0 to n do FParamList.Add(ParamStr(i)); end; function TApp.SearchParam(const Key: string; var Value: string): Integer; var i: Integer; s, skey: string; begin Result := 0; Value := ''; if Key = '' then Exit; if FParamList.Count = 0 then Exit; // Example: "/key:filename.ext" skey := LowerCase('/' + Key); for i := 1 to FParamList.Count do begin s := FParamList.Strings[i - 1]; if Pos(LowerCase(skey), LowerCase(s)) = 1 then begin if Length(s) > Length(skey) then begin Value := Copy(s, Length(skey) + 1, Length(s) - Length(skey)); if Value[1] = ':' then Value := Copy(Value, 2) else Value := ''; Result := i; end else begin Value := ''; Result := i; end; end; if Result <> 0 then Exit; end; end; procedure TApp.WriteParams; begin if not FLog then Exit; WriteAppLog(info, Format('Input file: "%s"', [FInputFile])); WriteAppLog(info, Format('Output file: "%s"', [FOutputFile])); end; function TApp.CheckParams: Boolean; var ParamName: string; ParamValue: string; begin Result := False; if FParamList.Count = 1 then Exit; // check source file FInputFile := PathSearchAndQualify(FParamList[1]); if not FileExists(FInputFile) then raise EFileNotFoundException.Create(Format(rs_ErrFileNotFound, [FInputFile])); // set default values for params FOutputFile := FInputFile; FEncoding := 'utf8'; FLanguage := 'ge'; FLog := False; ParamName := 'log'; if SearchParam(ParamName, ParamValue) > 0 then FLog := True; ParamName := 'lang'; if SearchParam(ParamName, ParamValue) > 0 then begin if (ParamValue <> 'ge') and (ParamValue <> 'az') then raise Exception.Create(Format(rs_ErrParamError, [ParamName, ParamValue])); FLanguage := ParamValue end; ParamName := 'enc'; if SearchParam(ParamName, ParamValue) > 0 then begin if (ParamValue <> 'utf8') and (ParamValue <> 'unicode') then raise Exception.Create(Format(rs_ErrParamError, [ParamName, ParamValue])); FEncoding := ParamValue end; ParamName := 'file'; if SearchParam(ParamName, ParamValue) > 0 then begin FOutputFile := PathSearchAndQualify(System.IOUtils.TPath.GetFileName(ParamValue)); end; if FLog then WriteParams; Result := True; end; procedure TApp.Execute; var InputText:TStringList; OutputText: TStringList; begin InputText := TStringList.Create(); OutputText := TStringList.Create(); try if FEncoding = 'utf8' then InputText.LoadFromFile(FInputFile, TEncoding.UTF8); if FEncoding = 'unicode' then InputText.LoadFromFile(FInputFile, TEncoding.Unicode); if FLanguage = 'ge' then ConvertTextGE(InputText, OutputText); if FLanguage = 'az' then ConvertTextAZ(InputText, OutputText); if FEncoding = 'utf8' then OutputText.SaveToFile(FOutputFile, TEncoding.UTF8); if FEncoding = 'unicode' then OutputText.SaveToFile(FOutputFile, TEncoding.Unicode); except on E: Exception do begin FreeAndNil(OutputText); FreeAndNil(InputText); raise; end; end; FreeAndNil(OutputText); FreeAndNil(InputText); FExitCode := 0; WriteAppLog(ok, 'Done!'); end; procedure TApp.Init; begin GetParamList; Console.Cls(); if FParamList.Count = 1 then begin WriteAppTitle(rsAppName, rsAppDescription, rsAppVer, rsCopyright); WriteAppHelp(rsAppName, rs_UsageHelp); end else WriteAppTitleShort(rsAppName, rsAppVer); end; procedure TApp.Finish; begin Console.SetColor(); end; procedure TApp.ConvertTextGE(InputText: TStringList; OutputText: TStringList); var i: Integer; j: Integer; Line1: string; Line2: string; Letter: Char; CharValue: Cardinal; begin OutputText.Clear; for i := 0 to InputText.Count - 1 do begin Line1 := InputText.Strings[i]; Line2 := ''; for j := 1 to Length(Line1) do begin Letter := Line1[j]; CharValue := Cardinal(Letter); if CharValue >= 127 then begin case CharValue of 247: CharValue := 287; 251: CharValue := 305; 248: CharValue := 351; 255: CharValue := 601; 240: CharValue := 1025; 128: CharValue := 1040; 129: CharValue := 1041; 130: CharValue := 1042; 131: CharValue := 1043; 132: CharValue := 1044; 133: CharValue := 1045; 134: CharValue := 1046; 135: CharValue := 1047; 136: CharValue := 1048; 137: CharValue := 1049; 138: CharValue := 1050; 139: CharValue := 1051; 140: CharValue := 1052; 141: CharValue := 1053; 142: CharValue := 1054; 143: CharValue := 1055; 144: CharValue := 1056; 145: CharValue := 1057; 146: CharValue := 1058; 147: CharValue := 1059; 148: CharValue := 1060; 149: CharValue := 1061; 150: CharValue := 1062; 151: CharValue := 1063; 152: CharValue := 1064; 153: CharValue := 1065; 154: CharValue := 1066; 155: CharValue := 1067; 156: CharValue := 1068; 157: CharValue := 1069; 158: CharValue := 1070; 159: CharValue := 1071; 160: CharValue := 1072; 162: CharValue := 1074; 163: CharValue := 1075; 164: CharValue := 1076; 165: CharValue := 1077; 166: CharValue := 1078; 167: CharValue := 1079; 168: CharValue := 1080; 169: CharValue := 1081; 170: CharValue := 1082; 171: CharValue := 1083; 172: CharValue := 1084; 173: CharValue := 1085; 174: CharValue := 1086; 175: CharValue := 1087; 230: CharValue := 1094; 231: CharValue := 1095; 232: CharValue := 1096; 233: CharValue := 1097; 234: CharValue := 1098; 235: CharValue := 1099; 236: CharValue := 1100; 237: CharValue := 1101; 238: CharValue := 1102; 239: CharValue := 1103; 241: CharValue := 1105; 192: CharValue := 4304; 193: CharValue := 4305; 194: CharValue := 4306; 195: CharValue := 4307; 196: CharValue := 4308; 197: CharValue := 4309; 198: CharValue := 4310; 200: CharValue := 4311; 201: CharValue := 4312; 202: CharValue := 4313; 203: CharValue := 4314; 204: CharValue := 4315; 205: CharValue := 4316; 207: CharValue := 4317; 208: CharValue := 4318; 209: CharValue := 4319; 210: CharValue := 4320; 211: CharValue := 4321; 212: CharValue := 4322; 214: CharValue := 4323; 215: CharValue := 4324; 216: CharValue := 4325; 217: CharValue := 4326; 218: CharValue := 4327; 219: CharValue := 4328; 220: CharValue := 4329; 221: CharValue := 4330; 222: CharValue := 4331; 223: CharValue := 4332; 224: CharValue := 4333; 161: CharValue := 4334; 225: CharValue := 4334; 227: CharValue := 4335; 228: CharValue := 4336; 199: CharValue := 4337; 206: CharValue := 4338; 213: CharValue := 4339; 226: CharValue := 4340; 229: CharValue := 4341; end; Letter := Char(CharValue); end; Line2 := Line2 + Letter; end; OutputText.Add(Line2); end; end; procedure TApp.ConvertTextAZ(InputText: TStringList; OutputText: TStringList); var i: Integer; j: Integer; Line1: string; Line2: string; Letter: Char; CharValue: Cardinal; begin OutputText.Clear; for i := 0 to InputText.Count - 1 do begin Line1 := InputText.Strings[i]; Line2 := ''; for j := 1 to Length(Line1) do begin Letter := Line1[j]; CharValue := Cardinal(Letter); if CharValue >= 127 then begin case CharValue of 215: CharValue := 286; 247: CharValue := 287; 200: CharValue := 304; 251: CharValue := 305; 216: CharValue := 350; 248: CharValue := 351; 223: CharValue := 399; 255: CharValue := 601; 240: CharValue := 1025; 128: CharValue := 1040; 129: CharValue := 1041; 130: CharValue := 1042; 131: CharValue := 1043; 132: CharValue := 1044; 133: CharValue := 1045; 134: CharValue := 1046; 135: CharValue := 1047; 136: CharValue := 1048; 137: CharValue := 1049; 138: CharValue := 1050; 139: CharValue := 1051; 140: CharValue := 1052; 141: CharValue := 1053; 142: CharValue := 1054; 143: CharValue := 1055; 144: CharValue := 1056; 145: CharValue := 1057; 146: CharValue := 1058; 147: CharValue := 1059; 148: CharValue := 1060; 149: CharValue := 1061; 150: CharValue := 1062; 151: CharValue := 1063; 152: CharValue := 1064; 153: CharValue := 1065; 154: CharValue := 1066; 155: CharValue := 1067; 156: CharValue := 1068; 157: CharValue := 1069; 158: CharValue := 1070; 159: CharValue := 1071; 160: CharValue := 1072; 161: CharValue := 1073; 162: CharValue := 1074; 163: CharValue := 1075; 164: CharValue := 1076; 165: CharValue := 1077; 166: CharValue := 1078; 167: CharValue := 1079; 168: CharValue := 1080; 169: CharValue := 1081; 170: CharValue := 1082; 171: CharValue := 1083; 172: CharValue := 1084; 173: CharValue := 1085; 174: CharValue := 1086; 175: CharValue := 1087; 224: CharValue := 1088; 225: CharValue := 1089; 226: CharValue := 1090; 227: CharValue := 1091; 228: CharValue := 1092; 229: CharValue := 1093; 230: CharValue := 1094; 231: CharValue := 1095; 232: CharValue := 1096; 233: CharValue := 1097; 234: CharValue := 1098; 235: CharValue := 1099; 236: CharValue := 1100; 237: CharValue := 1101; 238: CharValue := 1102; 239: CharValue := 1103; 241: CharValue := 1105; end; Letter := Char(CharValue); end; Line2 := Line2 + Letter; end; OutputText.Add(Line2); end; end; end.
// Common useful UI-related classes and routines // // Copyright (C) 2003-2004 Ivan Polyacov, Apus Software (ivan@apus-software.com) // This file is licensed under the terms of BSD-3 license (see license.txt) // This file is a part of the Apus Game Engine (http://apus-software.com/engine/) unit UIScene; interface uses {$IFDEF MSWINDOWS}windows,{$ENDIF}EngineAPI,UIClasses,CrossPlatform,types; const defaultHintStyle:integer=0; // style of hints, can be changed modalShadowColor:cardinal=0; // color of global "under modal" shadow type // Very useful simple scene that contains an UI layer // Almost all game scenes can be instances from this type, however sometimes // it is reasonable to use different scene(s) TUIScene=class(TGameScene) UI:TUIControl; // root UI element: size = render area size frameTime:int64; // time elapsed from the last frame constructor Create(scenename:string='';fullScreen:boolean=true); procedure SetStatus(st:TSceneStatus); override; function Process:boolean; override; procedure Render; override; procedure onResize; override; function GetArea:TRect; override; // screen area occupied by any non-transparent UI elements (i.e. which part of screen can't be ignored) procedure WriteKey(key:cardinal); override; procedure onMouseMove(x,y:integer); override; procedure onMouseBtn(btn:byte;pressed:boolean); override; procedure onMouseWheel(delta:integer); override; // These are markers for drawing scenes background to properly handle alpha channel of the render target to avoid wrong alpha blending // This is important ONLY if you are drawing semi-transparent pixels over the undefined (previous) content procedure BackgroundRenderBegin; virtual; procedure BackgroundRenderEnd; virtual; private lastRenderTime:int64; // prevModal:TUIControl; end; var curHint:TUIHint=nil; // No need to call manually as it is called when any UIScene object is created procedure InitUI; // Установка размера (виртуального) экрана для UI (зачем!?) procedure SetDisplaySize(width,height:integer); // Полезные функции общего применения // ------- // Создать всплывающее окно, прицепить его к указанному предку procedure ShowSimpleHint(msg:string;parent:TUIControl;x,y,time:integer;font:cardinal=0); procedure DumpUIdata; implementation uses SysUtils,MyServis,EventMan,UIRender,EngineTools,CmdProc,console,UDict,publics,geom2d; const statuses:array[TSceneStatus] of string=('frozen','background','active'); var curCursor:integer; initialized:boolean=false; rootWidth,rootHeight,oldRootWidth,oldAreaHeight:integer; // размер области отрисовки LastHandleTime:int64; // параметры хинтов hintRect:tRect; // область, к которой относится хинт // переменные для работы с хинтами элементов hintMode:cardinal; // время (в тиках), до которого длится режим показа хинтов // в этом режиме хинты выпадают гораздо быстрее itemShowHintTime:cardinal; // момент времени, когда элемент должен показать хинт lastHint:string; // текст хинта, соответствующего элементу, над которым была мышь в предыдущем кадре designMode:boolean; // режим "дизайна", в котором можно таскать элементы по экрану правой кнопкой мыши hookedItem:TUIControl; curShadowValue,oldShadowValue,needShadowValue:integer; // 0..255 startShadowChange,shadowChangeDuration:int64; lastShiftState:byte; procedure SetDisplaySize(width,height:integer); begin LogMessage('UIScene.SDS'); oldRootWidth:=rootWidth; oldAreaHeight:=rootHeight; rootWidth:=width; rootHeight:=height; UIClasses.SetDisplaySize(width,height); end; procedure ActivateEventHandler(event:EventStr;tag:TTag); begin EnterCriticalSection(UICritSect); try if tag=0 then SetFocusTo(nil); finally LeaveCriticalSection(UICritSect); end; end; procedure MouseEventHandler(event:EventStr;tag:TTag); var c,c2:TUIControl; e1,e2,e:boolean; x,y:integer; time:int64; st:string; begin event:=UpperCase(copy(event,7,length(event)-6)); EnterCriticalSection(UICritSect); time:=MyTickCount; try // обновить положение курсора если оно устарело if event='UPDATEPOS' then begin Signal('Engine\Cmd\UpdateMousePos'); end; // Движение if event='MOVE' then begin oldMouseX:=curMouseX; oldMouseY:=curMouseY; curMouseX:=SmallInt(tag and $FFFF); curMouseY:=SmallInt((tag shr 16) and $FFFF); if ClipMouse<>cmNo then with clipMouseRect do begin x:=curMouseX; y:=curMouseY; if X<left then x:=left; if X>=right then x:=right-1; if Y<top then y:=top; if Y>=bottom then y:=bottom-1; if (clipMouse in [cmReal,cmLimited]) and ((curMouseX<>x) or (curMouseY<>y)) then begin if clipMouse=cmReal then exit; end; if clipmouse=cmVirtual then begin curMouseX:=x; curMouseY:=y; end; end; if (curMouseX=oldMouseX) and (curMouseY=oldMouseY) then exit; // если мышь покинула прямоугольник хинта - стереть его {$IFNDEF IOS} if (curhint<>nil) and (curhint.visible) and not PtInRect(hintRect,types.Point(curMouseX,curMouseY)) then curhint.Hide; {$ENDIF} if hookedItem<>nil then hookedItem.MoveBy(curMouseX-oldMouseX,curMouseY-oldMouseY); e1:=FindControlAt(oldMouseX,oldMouseY,c); e2:=FindControlAt(curMouseX,curMouseY,c2); if e2 then underMouse:=c2 else undermouse:=nil; if e1 then c.onMouseMove; if e2 and (c2<>c) then c2.onMouseMove; e2:=FindControlAt(curMouseX,curMouseY,c2); // Курсор if e2 and (c2.cursor<>curCursor) then begin if curCursor<>crDefault then begin game.ToggleCursor(curCursor,false); Signal('UI\Cursor\OFF',curCursor); end; curCursor:=c2.cursor; game.ToggleCursor(curCursor,true); Signal('UI\Cursor\ON',curCursor); end; if not e2 and (curCursor<>crDefault) then begin Signal('UI\Cursor\OFF',curCursor); game.ToggleCursor(curCursor,false); curCursor:=crDefault; game.ToggleCursor(curCursor); end; if c<>c2 then begin // мышь перешла границу элемента if c<>nil then Signal('UI\onMouseOut\'+c.ClassName+'\'+c.name); if c2<>nil then Signal('UI\onMouseOver\'+c2.ClassName+'\'+c2.name); end; if (c2<>nil) and (c2.enabled and (c2.hint<>'') or not c2.enabled and (c2.hintIfDisabled<>'')) then begin if c2.enabled then st:=c2.hint else st:=c2.hintIfDisabled; if st<>lastHint then begin if st='' then begin ItemShowHintTime:=0; end else begin // этот элемент должен показать хинт if time<hintMode then ItemShowHintTime:=time+250 else ItemShowHintTime:=time+c2.hintDelay; end; end; lastHint:=st; end else begin ItemShowHintTime:=0; lastHint:=''; end; if clipMouse=cmLimited then begin // запомним скорректированное положение, чтобы не "прыгать" назад curMouseX:=x; curMouseY:=y; end; end; // Нажатие кнопки if copy(event,1,7)='BTNDOWN' then begin c:=nil; e:=FindControlAt(curMouseX,curMouseY,c); if e and (c<>nil) then begin if tag and 1>0 then c.onMouseButtons(1,true); if tag and 2>0 then c.onMouseButtons(2,true); if tag and 4>0 then c.onMouseButtons(3,true); end; if (c<>nil) and (not c.enabled) and (c.handleMouseIfDisabled) then begin if tag and 1>0 then c.onMouseButtons(1,true); if tag and 2>0 then c.onMouseButtons(2,true); if tag and 4>0 then c.onMouseButtons(3,true); end; // Таскание элементов правой кнопкой с Ctrl if (tag and 2>0) and (designmode or (lastShiftState and 2>0)) then hookedItem:=c; // Показать название и св-ва элемента if (tag=4) and (lastShiftState and 2>0) then if c<>nil then begin st:=c.name; c2:=c; while c2.parent<>nil do begin c2:=c2.parent; st:=c2.name+'->'+st; end; ShowSimpleHint(c.ClassName+'('+st+')',c.GetRoot,-1,-1,5000); PutMsg(Format('%s: %.1f,%.1f %.1f,%.1f',[c.name,c.position.x,c.position.y,c.size.x,c.size.y])); if game.shiftstate and 2>0 then // Shift pressed => select item ExecCmd('use '+c.name); end else begin st:='No opaque item here'; FindAnyControlAt(curMouseX,curMouseY,c); if c<>nil then st:=st+'; '+c.ClassName+'('+c.name+')'; ShowSimpleHint(st,nil,-1,-1,500+4000*byte(c<>nil)); end; end; // Отпускание кнопки if copy(event,1,5)='BTNUP' then begin if (hookedItem<>nil) and (tag and 2>0) then begin PutMsg('x='+inttostr(round(hookeditem.position.x))+' y='+inttostr(round(hookeditem.position.y))); hookedItem:=nil; end; if FindControlAt(curMouseX,curMouseY,c) then begin if tag and 1>0 then c.onMouseButtons(1,false); if tag and 2>0 then c.onMouseButtons(2,false); if tag and 4>0 then c.onMouseButtons(3,false); end; end; // Скроллинг if copy(event,1,6)='SCROLL' then if FindControlAt(curMouseX,curMouseY,c) then c.onMouseScroll(tag); finally LeaveCriticalSection(UICritSect); end; end; procedure PrintUIlog; var st:string; begin st:=' mouse clipping: '+inttostr(ord(clipMouse))+' ('+ inttostr(clipMouserect.left)+','+inttostr(clipMouserect.top)+':'+ inttostr(clipMouserect.right)+','+inttostr(clipMouserect.bottom)+')'#13#10; st:=st+' Modal control: '; if modalcontrol<>nil then st:=st+modalcontrol.name else st:=st+'none'; ForceLogMessage('UI state'#13#10+st); end; procedure KbdEventHandler(event:EventStr;tag:TTag); var c:TUIControl; shift:byte; key:integer; begin EnterCriticalSection(UICritSect); try shift:=(tag shr 16) and 255; lastShiftState:=shift; key:=tag and $FF; event:=UpperCase(copy(event,5,length(event)-4)); if event='KEYDOWN' then // Win+Ctrl+S if (key=ord('S')) and (shift=8+2) then PrintUILog; c:=FocusedControl; if (event='KEYDOWN') and (c=nil) then begin {$IFDEF MSWINDOWS} /// TODO ProcessHotKey(MapVirtualKey(key,1),shift); {$ENDIF} end; if c<>nil then begin while c<>nil do begin if not c.enabled then exit; c:=c.parent; end; {$IFDEF MSWINDOWS} /// TODO! if event='KEYDOWN' then if focusedControl.onKey(key,true,shift) then ProcessHotKey(MapVirtualKey(key,1),shift); {$ENDIF} if event='KEYUP' then if not focusedControl.onKey(key,false,shift) then exit; if event='CHAR' then focusedControl.onChar(chr(tag and $FF),tag shr 8); if event='UNICHAR' then focusedControl.onUniChar(WideChar(tag and $FFFF),tag shr 16); end; finally LeaveCriticalSection(UICritSect); end; end; { TUIScene } procedure TUIScene.BackgroundRenderBegin; begin if transpBgnd then painter.SetMode(blMove); end; procedure TUIScene.BackgroundRenderEnd; begin if transpBgnd then painter.SetMode(blAlpha); end; constructor TUIScene.Create; begin InitUI; inherited Create(fullscreen); if sceneName='' then sceneName:=ClassName; name:=scenename; UI:=TUIControl.Create(rootWidth,rootHeight,nil,sceneName); UI.enabled:=false; UI.visible:=false; if not fullscreen then ui.transpMode:=tmTransparent else ui.transpmode:=tmOpaque; if classType=TUIScene then onCreate; if game<>nil then game.AddScene(self); end; function TUIScene.GetArea:TRect; var i:integer; r:TRect; begin result:=Rect(0,0,0,0); // empty if UI=nil then exit; if UI.transpmode<>tmTransparent then result:=Rect(0,0,round(UI.size.x),round(UI.size.y)); for i:=0 to high(UI.children) do with UI.children[i] do if transpmode<>tmTransparent then begin r:=GetPosOnScreen; if IsRectEmpty(result) then result:=r else UnionRect(result,result,r); // именно в таком порядке, иначе - косяк! end; OffsetRect(result,round(UI.position.x),round(UI.position.y)); // actually, UI root shouldn't be displaced, but... end; procedure TUIScene.onMouseBtn(btn: byte; pressed: boolean); begin if (UI<>nil) and (not UI.enabled) then exit; inherited; end; procedure TUIScene.onMouseMove(x, y: integer); begin if (UI<>nil) and (not UI.enabled) then exit; inherited; end; procedure TUIScene.onMouseWheel(delta: integer); begin if (UI<>nil) and (not UI.enabled) then exit; inherited; if (modalcontrol=nil) or (modalcontrol=UI) then begin Signal('UI\'+name+'\MouseWheel',delta); end; end; procedure TUIScene.onResize; begin inherited; rootWidth:=game.renderWidth; rootHeight:=game.renderHeight; if UI<>nil then UI.Resize(rootWidth,rootHeight); end; function TUIScene.Process: boolean; var i,delta:integer; c:TUIControl; time:cardinal; st:string; procedure ProcessControl(c:TUIControl); var j:integer; cnt:integer; list:array[0..255] of TUIControl; begin if c=nil then exit; if c.timer>0 then if c.timer<=delta then begin c.timer:=0; c.onTimer; end else dec(c.timer,delta); cnt:=clamp(length(c.children),0,length(list)); // Can't process more than 255 nested elements if cnt>0 then begin for j:=0 to cnt-1 do list[j]:=c.children[j]; for j:=0 to cnt-1 do ProcessControl(list[j]); end; end; begin result:=true; Signal('Scenes\ProcessScene\'+name); EnterCriticalSection(UICritSect); // отложенное удаление элементов toDelete.Clear; // Размер корневого эл-та - полный экран { if (UI.ClassType=TUIControl) and (UI.x=0) and (UI.y=0) then begin UI.width:=areaWidth; UI.height:=areaHeight; end;} try FindControlAt(curMouseX,curMouseY,underMouse); // Обработка фокуса: если элемент с фокусом невидим или недоступен - убрать с него фокус // Исключение: корневой UI-элемент (при закрытии сцены фокус должен убрать эффект перехода) c:=focusedControl; if c<>nil then begin repeat if not (c.visible and c.enabled) or ((modalcontrol<>nil) and (c.parent=nil) and (c<>modalcontrol)) then begin SetFocusTo(nil); LogMessage(UI.name); break; end; c:=c.parent; until (c=nil) or (c.parent=nil); end; // Обработка захвата: если элемент, захвативший мышь, невидим или недоступен - убрать захват и фокус if hooked<>nil then begin if not (hooked.IsVisible and hooked.IsEnabled) or ((modalcontrol<>nil) and (hooked.GetRoot<>modalControl)) then begin hooked.onLostFocus; hooked:=nil; clipMouse:=cmNo; end; end; if LastHandleTime=0 then begin // первая обработка скипается LastHandleTime:=MyTickCount; exit; end; time:=MyTickCount; delta:=time-LastHandleTime; if UI<>nil then ProcessControl(UI); // обработка хинтов if (itemShowHintTime>LastHandleTime) and (itemShowHintTime<=Time) then begin FindControlAt(game.mouseX,game.mouseY,c); if (c<>nil) then begin if c.enabled then st:=c.hint else st:=c.hintIfDisabled; if st<>'' then begin ShowSimpleHint(st,nil,-1,-1,c.hintDuration); HintRect:=c.globalRect; HintMode:=time+5000; Signal('UI\onHint\'+c.ClassName+'\'+c.name); end; end; end; LastHandleTime:=time; finally LeaveCriticalSection(UICritSect); end; end; // tag: low 8 bit - new shadow value, next 16 bit - duration in ms procedure onSetGlobalShadow(event:eventstr;tag:TTag); begin startShadowChange:=MyTickCount; shadowChangeDuration:=tag shr 8; oldShadowValue:=curShadowValue; needShadowValue:=tag and $FF; end; // tag: low 8 bit - new shadow value, next 16 bit - duration in ms procedure onSetFocus(event:eventstr;tag:TTag); begin delete(event,1,length('UI\SETFOCUS\')); if (event<>'') and (event<>'NIL') then FindControl(event,true).setFocus else SetFocusTo(nil); end; procedure TUIScene.Render; var t:int64; begin t:=MyTickCount; if t>=lastRenderTime then frametime:=t-lastRenderTime else begin frameTime:=1; ForceLogMessage('Kosyak! '+inttostr(t)+' '+inttostr(lastRenderTime)); end; lastRenderTime:=t; UIRender.Frametime:=frametime; Signal('Scenes\'+name+'\BeforeRender'); StartMeasure(11); if UI<>nil then begin Signal('Scenes\'+name+'\BeforeUIRender'); EnterCriticalSection(UICritSect); try try DrawUI(UI); except on e:exception do raise EError.Create('UI.DrawUI '+name+' Err '+e.message); end; finally LeaveCriticalSection(UICritSect); end; Signal('Scenes\'+name+'\AfterUIRender'); end; EndMeasure2(11); end; procedure InitUI; begin if initialized then exit; // асинхронная обработка: сигналы обрабатываются в том же потоке, что и вызываются, // независимо от того из какого потока вызывается ф-ция InitUI SetEventHandler('Mouse',MouseEventHandler,emInstant); SetEventHandler('Kbd',KbdEventHandler,emInstant); SetEventHandler('Engine\ActivateWnd',ActivateEventHandler,emInstant); SetEventHandler('UI\SetGlobalShadow',onSetGlobalShadow,emInstant); SetEventHandler('UI\SetFocus',onSetFocus,emInstant); PublishVar(@rootWidth,'rootWidth',TVarTypeInteger); PublishVar(@rootHeight,'rootHeight',TVarTypeInteger); initialized:=true; end; procedure TUIScene.SetStatus(st: TSceneStatus); begin inherited; ForceLogMessage('Scene '+name+' status changed to '+statuses[st]); // LogMessage('Scene '+name+' status changed to '+statuses[st],5); if (status=ssActive) and (UI=nil) then begin UI:=TUIControl.Create(rootWidth,rootHeight,nil); UI.name:=name; UI.enabled:=false; UI.visible:=false; end; if UI<>nil then begin UI.enabled:=status=ssActive; ui.visible:=ui.enabled; if ui.enabled and (UI is TUIWindow) then UI.SetFocus; end; end; procedure TUIScene.WriteKey(key: cardinal); begin if (UI<>nil) and (not UI.enabled) then exit; inherited; end; procedure ShowSimpleHint; var hint:TUIHint; i:integer; begin LogMessage('ShowHint: '+msg); msg:=translate(msg); if (x=-1) or (y=-1) then begin x:=curMouseX; y:=curMouseY; hintRect:=rect(x-8,y-8,x+8,y+8); end else begin hintRect:=rect(0,0,4000,4000); end; if parent=nil then begin findControlAt(x,y,parent); if parent=nil then begin for i:=0 to high(rootControls) do if RootControls[i].visible then begin parent:=rootControls[i]; break; end; end else parent:=parent.GetRoot; end; if curhint<>nil then begin LogMessage('Free previous hint'); curHint.Free; curHint:=nil; end; hint:=TUIHint.Create(X,Y+10,msg,false,parent); hint.font:=font; hint.style:=defaultHintStyle; hint.timer:=time; hint.order:=10000; // Top curhint:=hint; LogMessage('Hint created '+inttohex(cardinal(hint),8)); end; procedure DumpUIdata; var i:integer; f:text; procedure DumpControl(c:TUIControl;indent:string); var i:integer; begin writeln(f,indent,c.ClassName+':'+c.name+' = '+inttohex(cardinal(c),8)); writeln(f,indent,c.order,' En=',c.enabled,' Vis=',c.visible,' trM=',ord(c.transpmode)); writeln(f,indent,Format('x=%.1f, y=%.1f, w=%.1f, h=%.1f, left=%d, top=%d', [c.position.x,c.position.y,c.size.x,c.size.y,c.globalRect.Left,c.globalRect.Top])); writeln(f); for i:=0 to length(c.children)-1 do DumpControl(c.children[i],indent+'+ '); end; function SceneInfo(s:TGameScene):string; begin if s=nil then exit; result:=Format(' %-20s Z=%-10d status=%-2d type=%-2d eff=%s', [s.name,s.zorder,ord(s.status),byte(s.fullscreen),PtrToStr(s.effect)]); if s is TUIScene then result:=result+Format(' UI=%s (%s)',[TUIScene(s).UI.name, PtrToStr(TUIScene(s).UI)]); end; begin try assign(f,'UIdata.log'); rewrite(f); writeln(f,'Scenes:'); for i:=0 to high(game.scenes) do writeln(f,i:3,SceneInfo(game.scenes[i])); writeln(f,'Topmost scene = ',game.TopmostVisibleScene(false).name); writeln(f,'Topmost fullscreen scene = ',game.TopmostVisibleScene(true).name); writeln(f); writeln(f,'Modal: '+inttohex(cardinal(modalcontrol),8)); writeln(f,'Focused: '+inttohex(cardinal(focusedControl),8)); writeln(f,'Hooked: '+inttohex(cardinal(hooked),8)); writeln(f); for i:=0 to high(rootControls) do DumpControl(rootControls[i],''); close(f); except on e:exception do ForceLogMessage('Error in DumpUI: '+ExceptionMsg(e)); end; end; end.
{Copyright (c) 1982, Charles L. Hedrick Distribution and use of this software is subject to conditions described in the Installation Document.} const {declarations to help using break masks} {Standard Field break mask all control chars, space through comma, dot, slash, colon through question mark, atsign, open bracket through accent grave, and close bracket through tilde} fldb0=777777777760B; fldb1=777754001760B; fldb2=400000000760B; fldb3=400000000760B; {Keyword break set. Same as standard field for now} keyb0=777777777760B; keyb1=777754001760B; keyb2=400000000760B; keyb3=400000000760B; {Username break set. Breaks on everything except dot and alphabetics.} usrb0=777777777760B; usrb1=747544001760B; usrb2=400000000740B; usrb3=400000000760B; {Account mask currently the same as user mask} actb0=777777777760B; actb1=747544001760B; actb2=400000000740B; actb3=400000000760B; {Filespec field - filespec punctuation characters are legal ( :, <, >, ., ;)} filb0=777777777760B; filb1=74544000120B; filb2=400000000240B; filb3=400000000760B; {Read Device Name - like standard field, but allow dollarsign and underscore} devb0=777777777760B; devb1=757754001760B; devb2=400000000740B; devb3=400000000760B; {Read To End Of Line - break on linefeed and carraige return} eolb0=000220000000B; eolb1=000000000000B; eolb2=000000000000B; eolb3=000000000000B; type t=array[0:100]of integer; table=^t; tadrec=packed record year:0..777777B; month:0..777777B; dayofmonth:0..777777B; dayofweek:0..777777B; zoneused:boolean; daylightsavings:boolean; zoneinput:boolean; julianday:boolean; dum:0..377B; zone:0..77B; seconds:0..777777B end; cmmodes=(normal,rescan); brkmsk=array [0..3] of integer; procedure cmini(prompt:string);extern; {Use this procedure first. It will issue the prompt, and set things up for reparsing in case of errors. Beware that if an error occurs in any of the other CM functions, control may be returned to the statement after the CMINI. Effectively this is done with a non-local GOTO. Thus the code between the CMINI and the end of the parse must be designed so that it can be restarted. Also, you must not exit the block in which the CMINI is issued until the entire parse is done. Since control will be returned to the CMINI in case of an error, it would cause serious troubles if that block was no longer active. } procedure cminir(prompt:string);extern; {Special version of CMINI to be used when you want to read a rescanned command from the EXEC. If this is done in a loop, the second time it is done, the program exits.} procedure cmfni(prompt: string; flag:integer); extern; procedure cmfnir(prompt: string; flag:integer); extern; {Special versions of CMINI and CMINIR. The left half of FLAG is set in the .CMFLG word of the COMND JSYS state block. This is needed when you want to set CM%RAI, CM%XIF, or CM%WKF} function cmmode:cmmodes;extern; {Says what "mode" we are running in. At the moment normal or rescan. Rescan means that a CMINIR succeeded in finding valid rescanned data.} procedure cmrscn; extern; {Clears the RSCANF flag saying whether a RSCAN was done by CMINIR so the next time CMINIR is called it will try for a rescaned command again. The old value of RSCANF is returned. } {The following two procedures are used in making up tables of commands and switches. Note that tables and their contents are stored in the heap. So you can use MARK and RELEASE to release them.} function tbmak(size:integer):table;extern; {Issue this one first. It allocates space for a table with the specified number of entries. It returns a table pointer, which is used for the other functions that operate on tables.} procedure tbadd(t:table;value:integer;key:string;bits:integer);extern; {Issue this once for each entry to go in the table. T - the value return by the call to TBMAK that allocated the table. VALUE - This is the value that will be returned when this entry in the table is found. KEY - This string is the name of the table entry. BITS - as documented in the JSYS manual. Normally zero. For example, one entry in a table of terminal types might be tbadd( termtable, 6, 'I400', 0) This entry will be matched by the string 'I400' (or any unique abbreviation), and will return the value 6, presumably the internal code for the I400 terminal.} {WARNING: You must issue these in reverse alphabetical order, i.e. the last entry in the table must be done first. This may be a monitor bug.} {The following procedures are used to parse individual fields in a command. They should be issued in the same order that the user is expected to type the fields.} function cmkey(t:table):integer;extern; {Expects the user to type one of the keywords in the table. It returns the value that was specified by TBADD when the keyword was put in the table. E.g. if the user typed I400, this would return 6 if the table had the entry shown above.} function cmswi(t:table):integer;extern; {Similar to cmkey, except the table is of switches. The slash should not be part of the name in the table. If the user ended the switch with a colon (i.e. you can expect a value after the switch), the negative of the value normally returned will be returned.} procedure cmifi(var f:file);extern; {Expects the user to type an input file name. The argument should be a Pascal file. That file will be preset to use the file specified. E.g. if you say CMIFI(INPUT), you can then use RESET(INPUT) and INPUT will be open on the file that the user specified. This function actually gets a jfn for the file specified by the user. That jfn is then stored in the file's file control block.} procedure cmofi(var f:file);extern; {Expects an output file name.} procedure cmfil(var f:file);extern; {Expects a general file spec. You must set up an extended gtjfn block appropriately to read the file spec. This is done with the gjxxx procedures below. At least gjgen must be used.} function cmnum:integer; extern; {Get a decimal number.} function cmnum8:integer; extern; {Get an octal number.} function cmnux:integer; extern; {Get a decimal number, ends with any non-numeric} function cmnux8:integer; extern; {Get an octal number, ends with any non-numeric} function cmflt:real; extern; {Get a real number} procedure cmnoi(stuff:string);extern; {Puts out a noise word if the user types altmode. Note that the parentheses are not part of the noise word.} procedure cmcfm; extern; {Expects the user to type a carriage return. This would usually be the last call made for parsing a command.} procedure cmcma; extern; {Expects the user to type a comma. If this is for an optional field, you should set CMAUTO(false) first, to prevent an error trap if there isn't one.} procedure cmtok(stuff:string);extern; {Expects the user to type that particular thing. See cmcma.} procedure cmctok(c:char);extern; {like CMTOK, but takes a single character instead of a string.} function cmdir:integer; extern; {Expects a directory name: returns the 36-bit dir. number. To see the text, use CMATOM.} function cmdirw:integer; extern; {as above, but allows wildcards} function cmusr:integer; extern; {Expects a user name: returns a 36-bit user number.(CMATOM for text)} function cmdev:integer; extern; {Expects a device name: returns a device designator (CMATOM for text)} {The following functions parse date and/or time. We have the following method: TAD - both date and time null - returns internal form T - time only N - puts unconverted form into a record D - date only} function cmtad:integer; extern; function cmt:integer; extern; function cmd:integer; extern; procedure cmtadn(var r:tadrec); extern; procedure cmtn(var r:tadrec); extern; procedure cmdn(var r:tadrec); extern; {The following procedures all return strings where you specify, and a count indicating how many characters were actually seen. Any extra characters in the destination array are filled with blanks. If there is not enough space, an error message is given and a reparse triggered.} function cmatom(var s:string):integer; extern; {This returns the contents of the "atom buffer". It is useful when you want to see what the user actually typed for the last field. It not cause any extra parsing, the data comes from the last field parsed.} function cmfld(var s:string):integer; extern; {Field delimited by first non-alphanumeric} function cmtxt(var s:string):integer; extern; {To next end of line} function cmqst(var s:string):integer; extern; {String in double quotes. Quotes not returned.} function cmuqs(var s: string; break_mask: brkmsk; var b: char):integer; extern; {Unquoted string. NOTE: Do NOT use CMBRK to set the break mask for this function. Use the second argument provided for that task. The third argument has the break character that was used returned in it. This doesn't seem to work for some special characters (like escape) also you might want to set the CM%WKF bit in the comnd state block to cause a wakeup on each field while parsing. See CMFIN procedure for how to do that.} function cmact(var s:string):integer; extern; {Account string. Not verified for legality} function cmnod(var s:string):integer; extern; {network node name. Not verified for legality} {The following procedures are used to set up the extended gtjfn block for cmfil. They must be given before the cmfil call. gjgen must always be used, and must be the first one of these to be called, as it clears the rest of the block. These procedures simply set the corresponding words in the gtjfn block, so see the jsys manual for details.} procedure gjgen(flags_and_generation:integer);extern; procedure gjdev(default_device:string);extern; procedure gjdir(default_directory:string);extern; procedure gjnam(default_name:string);extern; procedure gjext(default_extension:string);extern; procedure gjpro(default_protectin:string);extern; procedure gjact(default_account:string);extern; procedure gjjfn(try_to_use_this_jfn:integer);extern; {The following procedures are only needed for more complex parsers. They allow one to turn off various of the features that are normally supplied by default.} procedure cmauto(useauto:Boolean);extern; {Turn on or off automatic error processing. It is turned on by default. When automatic error processing is in effect, if the user does not type what is requested, an error message is issued and the prompt is reissued. At that point he can either type a new command, or type ^H to have the old command repeated up to the point of the error. Thus in the normal mode, the programmer does not need to worry about errors. Reparsing is done until the user types something valid. When automatic error processing has been turned off, no automatic reparsing is done for errors. Instead the procedure that was trying to read the field returns with a null value (if any). The user is expected to check for errors with cmerr. This is useful in the case where there are several valid responses. For example suppose either a keyword or a file is valid. Then you could do cmauto(false); % turn off error handling \ cmifi(input); if cmerr % wasn't a valid file \ then key := cmkey(keytable); In general one should probably turn cmauto back on before trying the last alternative, so that a reparse is done if it isn't valid. Note that even with cmauto false, some automatic reparses are still done if the user backspaces into a previously parsed fields. cmauto only controls what happens on a genuine error. cmini reinitializes cmauto to true.} function cmerr:Boolean; extern; {Returns true if the most recent parse call got an error.} procedure cmagain; extern; {Abort the current parse, reissue the prompt and try again. If cmauto is in effect, this is done automatically whenever there is an error. Note that cmagain does not print an error message. It is assumed that if you want the normal error message, you will turn on cmauto and let everything happen automatically.} procedure cmuerr(s:string); extern; {Print ?, clear the input buffer, print the string supplied, and call cmagain. This is equivalent to the usual error processing, but with a user-supplied error message.} procedure cmerrmsg; extern; {This prints the official error message from the last failure. This followed by cmagain is equivalent to the usual error processing.} function cmeof(trap: boolean):boolean; extern; {This function is used to trap end of file conditions detected by the COMND jsys. If TRAP is TRUE then the next eof will cause a reparse (instead of an illegal instruction trap) and cmeof will return true to indicate that the eof has happened. Use of this is as followes: CMINI('prompt'); IF CMEOF(TRUE) THEN eof_code; normal parsing stuff NOTE: Because a reparse is done when the error is seen, you should place the call to CMEOF just after your call to CMINI (or CMINIR) and before ANY CALLES TO OTHER PROCEDURES IN THIS PACKAGE. If you fail to do this the program will go into an infinite loop. } function cmioj(newjfns: integer):integer; extern; {This function sets .CMIOJ of the COMND state block to NEWJFNS and returns the old value of that word. This is useful for "pushing" the current JFNs.} procedure cmhlp(helptext:string); extern; {Used to supply your own help message when the user types ?. The text given will be used for the next field parsed. To supply a message taking up more than one line, just call cmhlp several times. Each call will add a line to the message. (Thus cmhlp is vaguely like writeln.) Note that the help message stays in effect only for the next field parsed.} procedure cmdef(default:string); extern; {Used to supply a default value for the next field parsed. This default stays in effect only for the next field.} function cmstat:integer; extern; {Returns the address of the COMND state block. Don't write into unless you really know what you're doing.} procedure cmbrk(break_mask: brkmsk); extern; {Used to supply a break mask for use in parsing the next field.} procedure brini(var break_mask: brkmsk; w0, w1, w2, w3: integer); extern; {Used to copy w0 through w3 into BREAK_MASK. Hint use this an the predefined CONSTants (at the beginning of this file) to set up break masks. For example to be able to parse keywords with ^ in them: brini(break,fldb0,fldb1,fldb2,flbd3); brmsk(break,'^',''); ... cmbrk(break); which := cmkey(keyword_table); } procedure brmsk(var break_mask: brkmsk; allow, disallow: string); extern; {Use to make a break mask with the characters, ALLOW, allowed and DISALLOW, disallowed.} {In some cases you may want to allow a choice of several alternatives. To do this, issue CMMULT, to go into "multiple choice mode". Once in this mode, issue CMxxx calls as usual. Instead of being done immediately, these calls store away specifications of the legal alternatives. For those that are functions, the values returned are garbage. Once you have specified all the alternatives, call CMDO. This returns an integer, 1..the number of alternatives, telling you which (if any) succeeded, 0 if none did. For alternatives that return values, you can then do CMINT to get the returned value if it is an integer, or CMREAL if it is real. Alternatives that return values in variables passed by reference will do so, using the variable passed when the original CMxxx was called. (Needless to say, that variable has better still be accessible.)} procedure cmmult; extern; {Enter multiple choice mode. All CMxxx procedures until the next CMDO are interpreted as specifications, rather than done immediately.} function cmdo:integer; extern; {Do a COMND jsys, specifying the alternatives stored up since the last CMMULT. Returns a code indicating which succeeded, or 0 if none did. Since the return value is used to indicate which alternative was found, there is a possible question: how do we get the returned value, if there is one (i.e. if the alternative found is a Pascal function that returns some value)? The answer to this is that the value returned is stored away internally and is available by CMINT or CMREAL, depending upon its type. Note that files and strings are returned through variables passed by reference. They do not need this mechanism, since that will be set automatically. (What happens is that the addresses of all reference variables are stored away when the alternative is first set up, and the appropriate one is set when we find out which alternative is actually there.)} function cmint:integer; extern; {Return a value from the last CMDO, if the alternative that succeeded was an integer} function cmreal:real; extern {Return a value from the last CMDO, if the alternative that succeeded was a real} .
unit UGeCartaCorrecao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UGrPadraoCadastro, ImgList, IBCustomDataSet, IBUpdateSQL, DB, Mask, DBCtrls, StdCtrls, Buttons, ExtCtrls, Grids, DBGrids, ComCtrls, ToolWin, IBQuery, IBTable, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons, JvExMask, JvToolEdit, JvDBControls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, dxSkinsCore, dxSkinMcSkin, dxSkinOffice2007Green, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, System.ImageList; type TfrmGeCartaCorrecao = class(TfrmGrPadraoCadastro) lblNFe: TLabel; dtsEmpresa: TDataSource; lblEmpresa: TLabel; dbEmpresa: TDBLookupComboBox; IbDtstTabelaCCE_NUMERO: TIntegerField; IbDtstTabelaCCE_EMPRESA: TIBStringField; IbDtstTabelaCCE_DATA: TDateField; IbDtstTabelaCCE_HORA: TTimeField; IbDtstTabelaCCE_ENVIADA: TSmallintField; IbDtstTabelaCCE_TEXTO: TMemoField; IbDtstTabelaNFE_SERIE: TIBStringField; IbDtstTabelaNFE_NUMERO: TIntegerField; IbDtstTabelaNFE_MODELO: TSmallintField; IbDtstTabelaNUMERO: TIntegerField; IbDtstTabelaPROTOCOLO: TIBStringField; IbDtstTabelaXML: TMemoField; lblDataHora: TLabel; dbDataHora: TDBEdit; lblNumero: TLabel; dbNumero: TDBEdit; IbDtstTabelaNFE_DESTINATARIO_RAZAO: TIBStringField; IbDtstTabelaNFE_DESTINATARIO_CNPJ: TIBStringField; lblCorrecao: TLabel; dbCorrecao: TDBMemo; lblProtocolo: TLabel; dbProtocolo: TDBEdit; dbEnviada: TDBCheckBox; mmCondicaoUso: TMemo; IbDtstTabelaDataHora: TDateTimeField; IbDtstTabelaNotaFiscalEletronica: TStringField; IbDtstTabelaNFE_DESTINATARIO: TIBStringField; lblCartaPendente: TLabel; Bevel5: TBevel; BtnEnviarCCe: TcxButton; dbNFe: TJvDBComboEdit; fdQryEmpresa: TFDQuery; procedure FormCreate(Sender: TObject); procedure dbNFeButtonClick(Sender: TObject); procedure IbDtstTabelaCalcFields(DataSet: TDataSet); procedure IbDtstTabelaNewRecord(DataSet: TDataSet); procedure IbDtstTabelaBeforeEdit(DataSet: TDataSet); procedure IbDtstTabelaBeforeDelete(DataSet: TDataSet); procedure dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure btbtnSalvarClick(Sender: TObject); procedure pgcGuiasChange(Sender: TObject); procedure BtnEnviarCCeClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure IbDtstTabelaAfterScroll(DataSet: TDataSet); procedure DtSrcTabelaStateChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure btbtnListaClick(Sender: TObject); private { Private declarations } procedure HabilitarDesabilitar_Btns; procedure RecarregarRegistro; procedure RegistrarNovaRotinaSistema; function GetRotinaEnviarCCeID : String; public { Public declarations } property RotinaEnviarCCeID : String read GetRotinaEnviarCCeID; end; (* Tabelas: - TBNFE_CARTA_CORRECAO - TBNFE_ENVIADA - TBVENDAS - TBCLIENTE - TBCOMPRAS - TBFORNECEDOR - TBEMPRESA Views: Procedures: *) var frmGeCartaCorrecao: TfrmGeCartaCorrecao; implementation uses UDMBusiness, UConstantesDGE, UDMNFe, UGeNFEmitida, UDMRecursos; {$R *.dfm} procedure TfrmGeCartaCorrecao.FormCreate(Sender: TObject); begin inherited; WhereAdditional := 'c.cce_empresa = ' + QuotedStr(gUsuarioLogado.Empresa); RotinaID := ROTINA_NFE_CARTA_CORRECAO_ID; ControlFirstEdit := dbEmpresa; DisplayFormatCodigo := '000'; NomeTabela := 'TBNFE_CARTA_CORRECAO'; CampoCodigo := 'CCE_NUMERO'; CampoDescricao := 'PROTOCOLO'; AbrirTabelaAuto := True; UpdateGenerator('GEN_CARTA_CORRECAO'); CarregarLista(fdQryEmpresa); BtnEnviarCCe.Visible := GetEstacaoEmitiNFe(gUsuarioLogado.Empresa) and (gSistema.Codigo in [SISTEMA_GESTAO_COM, SISTEMA_GESTAO_IND, SISTEMA_GESTAO_OPME]); end; procedure TfrmGeCartaCorrecao.FormShow(Sender: TObject); begin inherited; RegistrarNovaRotinaSistema; end; procedure TfrmGeCartaCorrecao.dbNFeButtonClick(Sender: TObject); var iAno , iControle : Integer; sEmpresa , sSerie , sChave : String; iNumero , iModelo : Integer; dEmissao : TDateTime; aDestinatario : TDestinatarioNF; begin iAno := 0; iControle := 0; sEmpresa := IbDtstTabelaCCE_EMPRESA.AsString; if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then if ( SelecionarNFe(Self, sEmpresa, sSerie, sChave, iNumero, iModelo, dEmissao, aDestinatario, iAno, iControle) ) then begin IbDtstTabelaNFE_SERIE.Value := sSerie; IbDtstTabelaNFE_NUMERO.Value := iNumero; IbDtstTabelaNFE_MODELO.Value := iModelo; IbDtstTabelaNFE_DESTINATARIO.Value := FormatFloat('0000000', iNumero) + '-' + sSerie; IbDtstTabelaNFE_DESTINATARIO_RAZAO.Value := aDestinatario.RazaoSocial; IbDtstTabelaNFE_DESTINATARIO_CNPJ.Value := aDestinatario.CpfCnpj; end; end; procedure TfrmGeCartaCorrecao.IbDtstTabelaCalcFields(DataSet: TDataSet); begin IbDtstTabelaDataHora.AsDateTime := StrToDateTime(FormatDateTime('dd/mm/yyyy', IbDtstTabelaCCE_DATA.Value) + ' ' + FormatDateTime('hh:mm:ss', IbDtstTabelaCCE_HORA.Value)); if Trim(IbDtstTabelaNFE_DESTINATARIO.AsString) <> EmptyStr then IbDtstTabelaNotaFiscalEletronica.AsString := IbDtstTabelaNFE_DESTINATARIO.AsString + ' - ' + IbDtstTabelaNFE_DESTINATARIO_RAZAO.AsString + IfThen(StrIsCNPJ(IbDtstTabelaNFE_DESTINATARIO_CNPJ.AsString), ' - CNPJ ' + StrFormatarCnpj(IbDtstTabelaNFE_DESTINATARIO_CNPJ.AsString), ' - CPF ' + StrFormatarCpf (IbDtstTabelaNFE_DESTINATARIO_CNPJ.AsString)); end; procedure TfrmGeCartaCorrecao.IbDtstTabelaNewRecord(DataSet: TDataSet); begin inherited; IbDtstTabelaCCE_EMPRESA.Value := gUsuarioLogado.Empresa; IbDtstTabelaCCE_DATA.Value := GetDateDB; IbDtstTabelaCCE_HORA.Value := GetTimeDB; IbDtstTabelaCCE_ENVIADA.Value := 0; IbDtstTabelaCCE_TEXTO.Clear; IbDtstTabelaXML.Clear; end; procedure TfrmGeCartaCorrecao.IbDtstTabelaBeforeEdit(DataSet: TDataSet); begin if ( IbDtstTabelaCCE_ENVIADA.AsInteger = 1 ) then begin ShowWarning('Esta Carta de Correção já foi enviada para a SEFA e por isso não poderá ser alterada!'); Abort; end; end; procedure TfrmGeCartaCorrecao.IbDtstTabelaBeforeDelete(DataSet: TDataSet); begin if ( IbDtstTabelaCCE_ENVIADA.AsInteger = 1 ) then begin ShowWarning('Esta Carta de Correção já foi enviada para a SEFA e por isso não poderá ser excluída!'); Abort; end else inherited; end; procedure TfrmGeCartaCorrecao.dbgDadosDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; if ( Sender = dbgDados ) then begin // Destacar CC-e não enviada if ( IbDtstTabelaCCE_ENVIADA.AsInteger = 0 ) then dbgDados.Canvas.Font.Color := lblCartaPendente.Font.Color; dbgDados.DefaultDrawDataCell(Rect, dbgDados.Columns[DataCol].Field, State); end; end; procedure TfrmGeCartaCorrecao.HabilitarDesabilitar_Btns; begin if ( pgcGuias.ActivePage = tbsCadastro ) then begin BtnEnviarCCe.Enabled := (IbDtstTabelaCCE_ENVIADA.AsInteger = 0) and (not IbDtstTabela.IsEmpty) and (not (IbDtstTabela.State in [dsEdit, dsInsert])); btbtnLista.Enabled := (IbDtstTabelaCCE_ENVIADA.AsInteger = 1) and (not IbDtstTabela.IsEmpty) and (Trim(IbDtstTabelaPROTOCOLO.AsString) <> EmptyStr); end else begin BtnEnviarCCe.Enabled := False; btbtnLista.Enabled := False; end; end; procedure TfrmGeCartaCorrecao.btbtnListaClick(Sender: TObject); begin inherited; DMNFe.ImprimirCCeACBr(IbDtstTabelaCCE_EMPRESA.AsString, IbDtstTabelaCCE_NUMERO.AsInteger); end; procedure TfrmGeCartaCorrecao.btbtnSalvarClick(Sender: TObject); begin inherited; HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.pgcGuiasChange(Sender: TObject); begin inherited; HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.BtnEnviarCCeClick(Sender: TObject); begin if ( IbDtstTabela.IsEmpty ) then Exit; if not GetPermissaoRotinaInterna(Sender, True) then Abort; RecarregarRegistro; if not DMNFe.GetValidadeCertificado(IbDtstTabelaCCE_EMPRESA.AsString) then Exit; if DMNFe.ConfigurarParamentoNFE(IbDtstTabelaCCE_EMPRESA.AsString) then begin ShowInformation('A emissão da CC-e exige a configuração dos parâmetros da empresa.' + #13 + 'Favor entrar em contrato com suporte.'); Exit; end; if DMNFe.GerarEnviarCCeACBr(IbDtstTabelaCCE_EMPRESA.AsString, IbDtstTabelaCCE_NUMERO.AsInteger, Trim(mmCondicaoUso.Lines.Text)) then begin ExecuteScriptSQL( 'Update TBNFE_CARTA_CORRECAO Set ' + ' CCE_ENVIADA = 1 ' + 'where CCE_EMPRESA = ' + QuotedStr(IbDtstTabelaCCE_EMPRESA.AsString) + ' and CCE_NUMERO = ' + IbDtstTabelaCCE_NUMERO.AsString ); RecarregarRegistro; end; HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.FormActivate(Sender: TObject); begin inherited; HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.IbDtstTabelaAfterScroll(DataSet: TDataSet); begin inherited; HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.DtSrcTabelaStateChange(Sender: TObject); begin inherited; dbEmpresa.ReadOnly := (IbDtstTabela.State = dsEdit); HabilitarDesabilitar_Btns; end; procedure TfrmGeCartaCorrecao.RecarregarRegistro; var sID : String; begin if ( IbDtstTabela.State in [dsEdit, dsInsert] ) then Exit; if IbDtstTabela.IsEmpty then sID := EmptyStr else sID := IbDtstTabelaCCE_NUMERO.AsString; if ( sID <> EmptyStr ) then begin IbDtstTabela.Close; IbDtstTabela.Open; IbDtstTabela.Locate('CCE_NUMERO', sID, []); end; end; procedure TfrmGeCartaCorrecao.RegistrarNovaRotinaSistema; begin if ( Trim(RotinaID) <> EmptyStr ) then begin if BtnEnviarCCe.Visible then SetRotinaSistema(ROTINA_TIPO_FUNCAO, RotinaEnviarCCeID, BtnEnviarCCe.Caption, RotinaID); end; end; function TfrmGeCartaCorrecao.GetRotinaEnviarCCeID: String; begin Result := GetRotinaInternaID(BtnEnviarCCe); end; initialization FormFunction.RegisterForm('frmGeCartaCorrecao', TfrmGeCartaCorrecao); end.
unit xn.list; interface uses System.Generics.Collections, System.Generics.Defaults, xn.Items; type IxnListCustom<T> = interface(IxnItems<T>) ['{D08DE521-118D-4A58-B9D4-34E8211FED75}'] function GetEnumerator: TEnumerator<T>; function Add(aItem: T): Integer; overload; function Remove(aItem: T): Integer; overload; procedure Delete(aIndex: Integer); overload; procedure Clear; function IndexOf(aItem: T): Integer; overload; function Contains(aItem: T): boolean; overload; end; IxnList<T> = interface(IxnListCustom<T>) ['{D4CEE49C-1EEE-40BF-A136-C6B074CFA76B}'] procedure Sort; overload; procedure Sort(const aComparer: IComparer<T>); overload; procedure Sort(const aComparison: TComparison<T>); overload; procedure Insert(aIndex: Integer; aItem: T); end; TxnList<T> = class(TxnItems<T>, IxnList<T>) public constructor Create; overload; override; destructor Destroy; override; function GetEnumerator: TEnumerator<T>; override; function Add(aItem: T): Integer; virtual; function Remove(aItem: T): Integer; virtual; procedure Delete(aIndex: Integer); virtual; procedure Clear; virtual; procedure Sort; overload; virtual; procedure Sort(const aComparer: IComparer<T>); overload; virtual; procedure Sort(const aComparison: TComparison<T>); overload; virtual; function IndexOf(aItem: T): Integer; overload; virtual; function Contains(aItem: T): boolean; overload; virtual; procedure Insert(aIndex: Integer; aItem: T); end; implementation { TxnList<T> } function TxnList<T>.Add(aItem: T): Integer; begin Result := fItems.Add(aItem); end; function TxnList<T>.Remove(aItem: T): Integer; begin Result := fItems.Remove(aItem); end; procedure TxnList<T>.Clear; begin fItems.Clear; end; procedure TxnList<T>.Delete(aIndex: Integer); begin fItems.Delete(aIndex); end; constructor TxnList<T>.Create; begin inherited; end; destructor TxnList<T>.Destroy; begin inherited; end; function TxnList<T>.GetEnumerator: TEnumerator<T>; begin Result := fItems.GetEnumerator; end; function TxnList<T>.Contains(aItem: T): boolean; begin Result := fItems.Contains(aItem) end; function TxnList<T>.IndexOf(aItem: T): Integer; begin Result := fItems.IndexOf(aItem); end; procedure TxnList<T>.Insert(aIndex: Integer; aItem: T); begin fItems.Insert(aIndex, aItem); end; procedure TxnList<T>.Sort; begin fItems.Sort; end; procedure TxnList<T>.Sort(const aComparer: IComparer<T>); begin fItems.Sort(aComparer); end; procedure TxnList<T>.Sort(const aComparison: TComparison<T>); begin fItems.Sort(TComparer<T>.Construct(aComparison)) end; end.
unit FindUnit.Worker; interface uses OtlCommonFU, OtlTaskFU, OtlThreadPoolFU, OtlParallelFU, OtlCollectionsFU, SimpleParser.Lexer.Types, Classes,FindUnit.PasParser, Generics.Collections, FindUnit.IncluderHandlerInc, Log4Pascal; type TOnFinished = procedure(FindUnits: TObjectList<TPasFile>) of object; TParserWorker = class(TObject) private FDirectoriesPath: TStringList; FOnFinished: TOnFinished; FPasFiles: TStringList; FFindUnits: TObjectList<TPasFile>; FIncluder: IIncludeHandler; FParsedItems: Integer; FDcuFiles: TStringList; FParseDcuFile: Boolean; procedure ListPasFiles; procedure ListDcuFiles; procedure RemoveDcuFromExistingPasFiles; procedure GeneratePasFromDcus; procedure ParseFilesParallel; procedure ParseFiles; function GetItemsToParse: Integer; procedure RunTasks; public constructor Create(var DirectoriesPath: TStringList; var Files: TStringList); destructor Destroy; override; procedure Start(CallBack: TOnFinished); overload; function Start: TObjectList<TPasFile>; overload; property ItemsToParse: Integer read GetItemsToParse; property ParsedItems: Integer read FParsedItems; property ParseDcuFile: Boolean read FParseDcuFile write FParseDcuFile; end; implementation uses FindUnit.Utils, SysUtils, Windows, FindUnit.DcuDecompiler; { TParserWorker } constructor TParserWorker.Create(var DirectoriesPath: TStringList; var Files: TStringList); begin FDirectoriesPath := TStringList.Create; if DirectoriesPath <> nil then FDirectoriesPath.Text := TPathConverter.ConvertPathsToFullPath(DirectoriesPath.Text); FreeAndNil(DirectoriesPath); FPasFiles := TStringList.Create; FPasFiles.Sorted := True; FPasFiles.Duplicates := dupIgnore; if Files <> nil then FPasFiles.AddStrings(Files); FreeAndNil(Files); FDcuFiles := TStringList.Create; FDcuFiles.Sorted := True; FDcuFiles.Duplicates := dupIgnore; FFindUnits := TObjectList<TPasFile>.Create; FIncluder := TIncludeHandlerInc.Create(FDirectoriesPath.Text) as IIncludeHandler; end; destructor TParserWorker.Destroy; begin FPasFiles.Free; FDirectoriesPath.Free; // FIncluder.Free; //Weak reference FDcuFiles.Free; inherited; end; function TParserWorker.GetItemsToParse: Integer; begin Result := 0; if (FPasFiles <> nil) then Result := FPasFiles.Count; end; procedure TParserWorker.GeneratePasFromDcus; var DcuDecompiler: TDcuDecompiler; begin if not FParseDcuFile then Exit; DcuDecompiler := TDcuDecompiler.Create; try DcuDecompiler.ProcessFiles(FDcuFiles); finally DcuDecompiler.Free; end; end; procedure TParserWorker.ListDcuFiles; var ResultList: IOmniBlockingCollection; RetunrValue: TObject; DcuFile: TOmniValue; begin if not FParseDcuFile then Exit; FDirectoriesPath.Add(DirRealeaseWin32); ResultList := TOmniBlockingCollection.Create; Parallel.ForEach(0, FDirectoriesPath.Count -1) .Into(ResultList) .Execute( procedure (const index: Integer; var result: TOmniValue) var DcuFiles: TStringList; DcuFile: string; begin try DcuFiles := GetAllDcuFilesFromPath(FDirectoriesPath[index]); try for DcuFile in DcuFiles do ResultList.Add(Trim(DcuFile)); finally DcuFiles.Free; end; except on E: exception do Logger.Error('TParserWorker.ListDcuFiles: ' + e.Message); end; end ); while ResultList.Take(DcuFile) do FDcuFiles.Add(DcuFile.AsString); end; procedure TParserWorker.ListPasFiles; var ResultList: IOmniBlockingCollection; RetunrValue: TObject; PasValue: TOmniValue; begin //DEBUG // FPasFiles.Add('C:\Program Files (x86)\Embarcadero\RAD Studio\8.0\source\rtl\common\Classes.pas'); // Exit; if FPasFiles.Count > 0 then Exit; ResultList := TOmniBlockingCollection.Create; Parallel.ForEach(0, FDirectoriesPath.Count -1) .Into(ResultList) .Execute( procedure (const index: Integer; var result: TOmniValue) var PasFiles: TStringList; PasFile: string; begin try if not DirectoryExists(FDirectoriesPath[index]) then Exit; PasFiles := GetAllPasFilesFromPath(FDirectoriesPath[index]); try for PasFile in PasFiles do ResultList.Add(Trim(PasFile)); finally PasFiles.Free; end; except on E: exception do Logger.Error('TParserWorker.ListPasFiles: ' + e.Message); end; end ); while ResultList.Take(PasValue) do FPasFiles.Add(PasValue.AsString); end; procedure TParserWorker.ParseFiles; var I: Integer; Parser: TPasFileParser; Item: TPasFile; Step: string; begin for I := 0 to FPasFiles.Count -1 do begin try Parser := TPasFileParser.Create(FPasFiles[I]); try Step := 'Parser.SetIncluder(FIncluder)'; Parser.SetIncluder(FIncluder); Step := 'InterlockedIncrement(FParsedItems);'; InterlockedIncrement(FParsedItems); Step := 'Parser.Process'; Item := Parser.Process; if Item <> nil then FFindUnits.Add(Item); except on e: exception do Logger.Error('TParserWorker.ParseFiles[%s]: %s', [Step, e.Message]); end; finally Item := nil; Parser.Free; end; end; end; procedure TParserWorker.ParseFilesParallel; var ResultList: IOmniBlockingCollection; PasValue: TOmniValue; begin ResultList := TOmniBlockingCollection.Create; FParsedItems := 0; Logger.Debug('TParserWorker.ParseFiles: Starting parseing files.'); Parallel.ForEach(0, FPasFiles.Count -1) .Into(ResultList) .Execute( procedure (const index: Integer; var result: TOmniValue) var Parser: TPasFileParser; Item: TPasFile; Step: string; Conter: Integer; begin try Parser := nil; try Step := 'InterlockedIncrement(FParsedItems);'; Conter := InterlockedIncrement(FParsedItems); Step := 'Create'; Parser := TPasFileParser.Create(FPasFiles[index]); Step := 'Parser.SetIncluder(FIncluder)'; Parser.SetIncluder(FIncluder); Step := 'Parser.Process'; Item := Parser.Process; if Item <> nil then ResultList.Add(Item); except on e: exception do Logger.Error('TParserWorker.ParseFiles[%s]: %s', [Step, e.Message]); end; finally Parser.Free; end; end ); Logger.Debug('TParserWorker.ParseFiles: Put results together.'); while ResultList.Take(PasValue) do FFindUnits.Add(TPasFile(PasValue.AsObject)); Logger.Debug('TParserWorker.ParseFiles: Finished.'); end; procedure TParserWorker.RemoveDcuFromExistingPasFiles; var DcuFilesName: TStringList; PasFilesName: TStringList; I: Integer; PasFile: string; DcuFile: string; begin if FDcuFiles.Count = 0 then Exit; PasFilesName := TStringList.Create; PasFilesName.Sorted := True; PasFilesName.Duplicates := dupIgnore; try for I := 0 to FPasFiles.Count -1 do begin PasFile := FPasFiles[i]; PasFile := UpperCase(ExtractFileName(PasFile)); PasFile := StringReplace(PasFile, '.PAS', '', [rfReplaceAll]); PasFilesName.Add(PasFile); end; for I := FDcuFiles.Count -1 downto 0 do begin DcuFile := FDcuFiles[i]; DcuFile:= UpperCase(ExtractFileName(DcuFile)); DcuFile := StringReplace(DcuFile, '.DCU', '', [rfReplaceAll]); if PasFilesName.IndexOf(DcuFile) > -1 then FDcuFiles.Delete(I); end; finally PasFilesName.Free; end; end; function TParserWorker.Start: TObjectList<TPasFile>; begin RunTasks; Result := FFindUnits; end; procedure TParserWorker.RunTasks; var Step: string; procedure OutPutStep(CurStep: string); begin Step := CurStep; Logger.Debug('TParserWorker.RunTasks: ' + CurStep); end; begin try OutPutStep('FIncluder.Process'); TIncludeHandlerInc(FIncluder).Process; OutPutStep('ListPasFiles'); ListPasFiles; OutPutStep('ListDcuFiles'); ListDcuFiles; OutPutStep('RemoveDcuFromExistingPasFiles'); RemoveDcuFromExistingPasFiles; OutPutStep('GeneratePasFromDcus'); GeneratePasFromDcus; OutPutStep('ParseFiles'); ParseFilesParallel; OutPutStep('Finished'); except on E: exception do Logger.Error('TParserWorker.RunTasks[%s]: %s ',[Step, e.Message]); end; end; procedure TParserWorker.Start(CallBack: TOnFinished); begin RunTasks; CallBack(FFindUnits); end; end.
unit FBits; interface uses Windows, Graphics, SysUtils, Controls; const cBitTextOff = 12; //Offset between label coord and text type TBitTyp = ( bbNone, bbBitmap, bbLine, bbOval, bbPoint, bbLabel, bbTrack, bbILIcon //ImageList icon ); TBitInfo = record ID: Integer; Typ: TBitTyp; X1, Y1, X2, Y2: Integer; Data: TObject; DataNotOwn: Boolean; Color: TColor; Color2: TColor; Text: string; Font: string; Size, Size2: Integer; Style: TFontStyles; end; TBitInfoSet = set of ( bbsCoord, //change X1, Y1, X2, Y2 bbsColor, //change Color, Color2 bbsText, //change Text bbsFont, //change Font bbsSizes, //change Size, Size2 bbsStyle //change Style ); const cBitsCount = 1000; //Max bits number type TBits = array[0 .. Pred(cBitsCount)] of TBitInfo; function BitInfo( ATyp: TBitTyp; AX1, AY1, AX2, AY2: Integer; AData: TObject; AColor: TColor; AColor2: TColor; const AText: string; const AFont: string; ASize, ASize2: Integer; AStyle: TFontStyles): TBitInfo; type TBitsObject = class FBits: TBits; FBitsCount: Integer; FBitsLastId: Integer; constructor Create; destructor Destroy; override; //-------- //Adds item(bit) to layers list. //Result is Id >= 0, when item was added, or negative if error occured. function AddBit(const Info: TBitInfo): Integer; //Changes bit info. //Id: Id returned by AddBit. //Info: Info to set. //InfoSet: shows which fields of Info are used (it may be only [bbsCoord]). //Result True if item exists. //Note: Info.Data must not be assigned (currently) function SetBit(Id: Integer; const Info: TBitInfo; InfoSet: TBitInfoSet): Boolean; //Checks is bit index valid (note: not Id, but internal index). function IsBitIndexValid(Index: Integer): Boolean; //Gets internal item index from Id. //Result >= 0 if Id valid, or negative if not valid. function IndexFromId(Id: Integer): Integer; //Gets bit info to Info variable. function GetBit(Id: Integer; var Info: TBitInfo): Boolean; //Deletes bit. function DeleteBit(Id: Integer): Boolean; //Adds track item. Id: Track id (returned by AddBit). P: coordinates. //Result True if item was added. function AddTrackItem(Id: Integer; P: TPoint): Boolean; //Returns number of bits. property BitsCount: Integer read FBitsCount; //-------------- end; implementation uses FTrack; function BitInfo; begin FillChar(Result, SizeOf(Result), 0); with Result do begin Typ := ATyp; X1 := AX1; Y1 := AY1; X2 := AX2; Y2 := AY2; Data := AData; Color := AColor; Color2 := AColor2; Text := AText; Font := AFont; Size := ASize; Size2 := ASize2; Style := AStyle; end; end; procedure ClearBit(var Info: TBitInfo); begin with Info do begin Typ := bbNone; X1 := 0; Y1 := 0; X2 := 0; Y2 := 0; Color := clNone; Color2 := clNone; Text := ''; Font := ''; Size := 0; Size2 := 0; Style := []; if DataNotOwn then Data := nil else if Assigned(Data) then FreeAndNil(Data); end; end; constructor TBitsObject.Create; begin inherited; FBitsCount := 0; FBitsLastId := -1; FillChar(FBits, SizeOf(FBits), 0); end; destructor TBitsObject.Destroy; var i: Integer; begin for i := FBitsCount - 1 downto 0 do ClearBit(FBits[i]); FBitsCount := 0; inherited; end; function TBitsObject.AddBit; begin if FBitsCount >= High(FBits) then begin Result := -1; Exit end; Inc(FBitsCount); Inc(FBitsLastId); Result := FBitsLastId; with FBits[FBitsCount - 1] do begin Id := FBitsLastId; Typ := Info.Typ; X1 := Info.X1; Y1 := Info.Y1; X2 := Info.X2; Y2 := Info.Y2; Data := nil; DataNotOwn := False; case Typ of bbBitmap: begin Assert(Assigned(Info.Data), 'Bitmap not assigned'); Assert(Info.Data is TBitmap, 'Bitmap wrong'); Data := TBitmap.Create; TBitmap(Data).Assign(TBitmap(Info.Data)); end; bbTrack: begin Data := TTrackInfo.Create; end; bbILIcon: begin Assert(Assigned(Info.Data), 'ImageList not assigned'); Assert(Info.Data is TImageList, 'ImageList wrong'); Data := Info.Data; DataNotOwn := True; //Not own object end; end; Color := Info.Color; Color2 := Info.Color2; Text := Info.Text; Font := Info.Font; Size := Info.Size; Size2 := Info.Size2; Style := Info.Style; end; end; //------------------ function TBitsObject.IsBitIndexValid; begin Result := (Index >= 0) and (Index < FBitsCount); end; function TBitsObject.IndexFromId; var i: Integer; begin Result := -1; for i := 0 to FBitsCount - 1 do if FBits[i].ID = Id then begin Result := i; Break end; end; function TBitsObject.GetBit; var Index: Integer; begin Index := IndexFromId(Id); Result := IsBitIndexValid(Index); if Result then with FBits[Index] do begin Info.Typ := Typ; Info.X1 := X1; Info.Y1 := Y1; Info.X2 := X2; Info.Y2 := Y2; Info.Data := Data; Info.Color := Color; Info.Color2 := Color2; Info.Text := Text; Info.Font := Font; Info.Size := Size; Info.Size2 := Size2; Info.Style := Style; end; end; function TBitsObject.SetBit; var Index: Integer; begin Assert(not Assigned(Info.Data), 'Data not assigned'); Index := IndexFromId(Id); Result := IsBitIndexValid(Index); if Result then with FBits[Index] do begin if bbsCoord in InfoSet then begin X1 := Info.X1; Y1 := Info.Y1; X2 := Info.X2; Y2 := Info.Y2; end; if bbsColor in InfoSet then begin Color := Info.Color; Color2 := Info.Color2; end; if bbsText in InfoSet then begin Text := Info.Text; end; if bbsFont in InfoSet then begin Font := Info.Font; end; if bbsSizes in InfoSet then begin Size := Info.Size; Size2 := Info.Size2; end; if bbsStyle in InfoSet then begin Style := Info.Style; end; end; end; function TBitsObject.DeleteBit; var Index, i: Integer; begin Index := IndexFromId(Id); Result := IsBitIndexValid(Index); if Result then begin ClearBit(FBits[Index]); for i := Index to FBitsCount - 2 do Move(FBits[i + 1], FBits[i], SizeOf(TBitInfo)); FillChar(FBits[FBitsCount - 1], SizeOf(TBitInfo), 0); Dec(FBitsCount); end; end; function TBitsObject.AddTrackItem; var Index: Integer; begin Index := IndexFromId(Id); Result := IsBitIndexValid(Index); if Result then with FBits[Index] do begin Assert(Assigned(Data), 'Track not assigned'); Assert(Data is TTrackInfo, 'Track wrong'); with TTrackInfo(Data) do Result := AddItem(P); end; end; end.
{******************************************************************************} { } { Library: Fundamentals TLS } { File name: flcTLSAlgorithmTypes.pas } { File version: 5.03 } { Description: TLS Algorithm Types } { } { Copyright: Copyright (c) 2008-2020, David J Butler } { All rights reserved. } { Redistribution and use in source and binary forms, with } { or without modification, are permitted provided that } { the following conditions are met: } { Redistributions of source code must retain the above } { copyright notice, this list of conditions and the } { following disclaimer. } { THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND } { CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED } { WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED } { WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A } { PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL } { THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, } { INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR } { CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, } { PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF } { USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) } { HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER } { IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING } { NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE } { USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE } { POSSIBILITY OF SUCH DAMAGE. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2008/01/18 0.01 Initial development. } { 2020/05/09 5.02 Create flcTLSAlgorithmTypes unit from flcTLSUtils unit. } { 2020/05/11 5.03 NamedCurve and ECPointFormat enumerations. } { } {******************************************************************************} {$INCLUDE flcTLS.inc} unit flcTLSAlgorithmTypes; interface uses flcStdTypes; { } { CompressionMethod } { } type TTLSCompressionMethod = ( tlscmNull = 0, // Enumerations from handshake tlscmDeflate = 1, tlscmMax = 255 ); PTLSCompressionMethod = ^TTLSCompressionMethod; TTLSCompressionMethods = set of TTLSCompressionMethod; const TLSCompressionMethodSize = Sizeof(TTLSCompressionMethod); { } { HashAlgorithm } { } type TTLSHashAlgorithm = ( tlshaNone = 0, // Enumerations from handshake tlshaMD5 = 1, tlshaSHA1 = 2, tlshaSHA224 = 3, tlshaSHA256 = 4, tlshaSHA384 = 5, tlshaSHA512 = 6, tlshaMax = 255 ); TTLSHashAlgorithms = set of TTLSHashAlgorithm; function HashAlgorithmToStr(const A: TTLSHashAlgorithm): String; { } { SignatureAlgorithm } { } type TTLSSignatureAlgorithm = ( tlssaAnonymous = 0, // Enumerations from handshake tlssaRSA = 1, tlssaDSA = 2, tlssaECDSA = 3, tlssaMax = 255 ); TTLSSignatureAlgorithms = set of TTLSSignatureAlgorithm; { } { SignatureAndHashAlgorithm } { } type TTLSSignatureAndHashAlgorithm = packed record Hash : TTLSHashAlgorithm; Signature : TTLSSignatureAlgorithm; end; PTLSSignatureAndHashAlgorithm = ^TTLSSignatureAndHashAlgorithm; TTLSSignatureAndHashAlgorithmArray = array of TTLSSignatureAndHashAlgorithm; const TLSSignatureAndHashAlgorithmSize = SizeOf(TTLSSignatureAndHashAlgorithm); { } { MACAlgorithm } { Used in TLS record. } { } type TTLSMACAlgorithm = ( tlsmaNone, tlsmaNULL, tlsmaHMAC_MD5, tlsmaHMAC_SHA1, tlsmaHMAC_SHA256, tlsmaHMAC_SHA384, tlsmaHMAC_SHA512 ); TTLSMacAlgorithmInfo = record Name : RawByteString; DigestSize : Integer; Supported : Boolean; // Not used end; PTLSMacAlgorithmInfo = ^TTLSMacAlgorithmInfo; const TLSMACAlgorithmInfo : array[TTLSMACAlgorithm] of TTLSMacAlgorithmInfo = ( ( // None Name : ''; DigestSize : 0; Supported : False; ), ( // NULL Name : 'NULL'; DigestSize : 0; Supported : True; ), ( // HMAC_MD5 Name : 'HMAC-MD5'; DigestSize : 16; Supported : True; ), ( // HMAC_SHA1 Name : 'HMAC-SHA1'; DigestSize : 20; Supported : True; ), ( // HMAC_SHA256 Name : 'HMAC-SHA256'; DigestSize : 32; Supported : True; ), ( // HMAC_SHA384 Name : 'HMAC-SHA384'; DigestSize : 48; Supported : False; ), ( // HMAC_SHA512 Name : 'HMAC-SHA512'; DigestSize : 64; Supported : True; ) ); const TLS_MAC_MAXDIGESTSIZE = 64; { } { KeyExchangeAlgorithm } { } type TTLSKeyExchangeAlgorithm = ( tlskeaNone, tlskeaNULL, tlskeaDHE_DSS, tlskeaDHE_RSA, tlskeaDH_Anon, tlskeaRSA, tlskeaDH_DSS, tlskeaDH_RSA, tlskeaECDHE_ECDSA, tlskeaECDH_ECDSA, tlskeaECDHE_RSA, tlskeaECDH_RSA ); TTLSKeyExchangeMethod = ( tlskemNone, tlskemNULL, tlskemDHE, tlskemDH_Anon, tlskemRSA, tlskemDH, tlskemPSK, tlskemECDH, tlskemECDHE ); TTLSKeyExchangeAuthenticationType = ( tlskeatNone, tlskeatAnon, tlskeatDSS, tlskeatRSA, tlskeatPSK, tlskeatECDSA ); TTLSKeyExchangeAlgorithmInfo = record Name : RawByteString; Method : TTLSKeyExchangeMethod; KeyType : TTLSKeyExchangeAuthenticationType; Supported : Boolean; // Not used end; PTLSKeyExchangeAlgorithmInfo = ^TTLSKeyExchangeAlgorithmInfo; const TLSKeyExchangeAlgorithmInfo: array[TTLSKeyExchangeAlgorithm] of TTLSKeyExchangeAlgorithmInfo = ( ( // None Name : ''; Method : tlskemNone; KeyType : tlskeatNone; Supported : False; ), ( // NULL Name : 'NULL'; Method : tlskemNULL; KeyType : tlskeatNone; Supported : True; ), ( // DHE_DSS Name : 'DHE_DSS'; Method : tlskemDHE; KeyType : tlskeatDSS; Supported : False; ), ( // DHE_RSA Name : 'DHE_RSA'; Method : tlskemDHE; KeyType : tlskeatRSA; Supported : False; ), ( // DH_Anon Name : 'DH_Anon'; Method : tlskemDH_Anon; KeyType : tlskeatNone; Supported : False; ), ( // RSA Name : 'RSA'; Method : tlskemRSA; KeyType : tlskeatRSA; Supported : True; ), ( // DH_DSS Name : 'DH_DSS'; Method : tlskemDH; KeyType : tlskeatDSS; Supported : False; ), ( // DH_RSA Name : 'DH_RSA'; Method : tlskemDH; KeyType : tlskeatRSA; Supported : False; ), ( // ECDHE_ECDSA Name : 'ECDHE_ECDSA'; Method : tlskemECDHE; KeyType : tlskeatECDSA; Supported : False; ), ( // ECDH_ECDSA Name : 'ECDH_ECDSA'; Method : tlskemECDH; KeyType : tlskeatECDSA; Supported : False; ), ( // ECDHE_RSA Name : 'ECDHE_RSA'; Method : tlskemECDHE; KeyType : tlskeatRSA; Supported : False; ), ( // ECDH_RSA Name : 'ECDH_RSA'; Method : tlskemECDH; KeyType : tlskeatRSA; Supported : False; ) ); { } { ClientCertificateType } { } type TTLSClientCertificateType = ( tlscctRsa_sign = 1, tlscctDss_sign = 2, tlscctRsa_fixed_dh = 3, tlscctDss_fixed_dh = 4, tlscctRsa_ephemeral_dh_RESERVED = 5, tlscctDss_ephemeral_dh_RESERVED = 6, tlscctFortezza_dms_RESERVED = 20, tlscctEcdsa_sign = 64, // RFC 8422 tlscctRsa_fixed_ecdh = 65, // RFC 4492, deprecated in RFC 8422 tlscctEcdsa_fixed_ecdh = 66, // RFC 4492, deprecated in RFC 8422 tlscctMax = 255 ); { } { ECCurveType } { } type TTLSECCurveType = ( tlsectExplicit_prime = 1, // RFC 4492, deprecated in RFC 8422 tlsectExplicit_char2 = 2, // RFC 4492, deprecated in RFC 8422 tlsectNamed_curve = 3, // RFC 4492 tlsectMax = 255 ); { } { NamedCurve } { } type TTLSNamedCurve = ( tlsncSect163k1 = 1, // deprecated in RFC 8422 tlsncSect163r1 = 2, // deprecated in RFC 8422 tlsncSect163r2 = 3, // deprecated in RFC 8422 tlsncSect193r1 = 4, // deprecated in RFC 8422 tlsncSect193r2 = 5, // deprecated in RFC 8422 tlsncSect233k1 = 6, // deprecated in RFC 8422 tlsncSect233r1 = 7, // deprecated in RFC 8422 tlsncSect239k1 = 8, // deprecated in RFC 8422 tlsncSect283k1 = 9, // deprecated in RFC 8422 tlsncSect283r1 = 10, // deprecated in RFC 8422 tlsncSect409k1 = 11, // deprecated in RFC 8422 tlsncSect409r1 = 12, // deprecated in RFC 8422 tlsncSect571k1 = 13, // deprecated in RFC 8422 tlsncSect571r1 = 14, // deprecated in RFC 8422 tlsncSecp160k1 = 15, // deprecated in RFC 8422 tlsncSecp160r1 = 16, // deprecated in RFC 8422 tlsncSecp160r2 = 17, // deprecated in RFC 8422 tlsncSecp192k1 = 18, // deprecated in RFC 8422 tlsncSecp192r1 = 19, // deprecated in RFC 8422 tlsncSecp224k1 = 20, // deprecated in RFC 8422 tlsncSecp224r1 = 21, // deprecated in RFC 8422 tlsncSecp256k1 = 22, // deprecated in RFC 8422 tlsncSecp256r1 = 23, tlsncSecp384r1 = 24, tlsncSecp521r1 = 25, tlsncX25519 = 29, // RFC 8422 tlsncX448 = 30, // RFC 8422 tlsncArbitrary_explicit_prime_curves = $FF01, // deprecated in RFC 8422 tlsncArbitrary_explicit_char2_curves = $FF02, // deprecated in RFC 8422 tlsncMax = $FFFF ); { } { ECPointFormat } { } type TTLSECPointFormat = ( tlsepfUncompressed = 0, tlsepfAnsiX962_compressed_prime = 1, tlsepfAnsiX962_compressed_char2 = 2, tlsepfMax = 255 ); { } { Test } { } {$IFDEF TLS_TEST} procedure Test; {$ENDIF} implementation uses { System } SysUtils; { } { HashAlgorithm } { } function HashAlgorithmToStr(const A: TTLSHashAlgorithm): String; begin case A of tlshaNone : Result := 'None'; tlshaMD5 : Result := 'MD5'; tlshaSHA1 : Result := 'SHA1'; tlshaSHA224 : Result := 'SHA224'; tlshaSHA256 : Result := 'SHA256'; tlshaSHA384 : Result := 'SHA384'; tlshaSHA512 : Result := 'SHA512'; else Result := 'Hash#' + IntToStr(Ord(A)); end; end; { } { Test } { } {$IFDEF TLS_TEST} {$ASSERTIONS ON} procedure Test; begin Assert(TLSCompressionMethodSize = 1); end; {$ENDIF} end.
unit NewMessage; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Menus, Placemnt, DialMessages, Utils, DataErrors; type TNewMessageForm = class(TForm) ActionPanel: TPanel; MessageTextMemo: TMemo; MainMenu: TMainMenu; FileMI: TMenuItem; ClearMI: TMenuItem; CharCountLabel: TLabel; FormPlacement: TFormPlacement; SaveMI: TMenuItem; OpenMI: TMenuItem; MessageTextOpenDialog: TOpenDialog; MessageTextSaveDialog: TSaveDialog; CancelButton: TButton; OKButton: TButton; procedure ClearMIClick(Sender: TObject); procedure MessageTextMemoChange(Sender: TObject); procedure SaveMIClick(Sender: TObject); procedure OpenMIClick(Sender: TObject); private { Private declarations } procedure Open; procedure Save; procedure Clear; public { Public declarations } procedure SetMaxMessageLength(const MaxMessageLength: Integer); procedure LoadMessageText(const FileName: string); procedure SaveMessageText(const FileName: string); end; var NewMessageForm: TNewMessageForm; implementation {$R *.dfm} resourcestring rsMessageTooLong = 'Message text exceeds limit!'; procedure TNewMessageForm.ClearMIClick(Sender: TObject); begin Clear; end; procedure TNewMessageForm.MessageTextMemoChange(Sender: TObject); begin CharCountLabel.Caption := IntToStr(Length(MessageTextMemo.Text)); OKButton.Enabled := MessageTextMemo.Text <> EmptyStr; end; procedure TNewMessageForm.SaveMIClick(Sender: TObject); begin Save; end; procedure TNewMessageForm.OpenMIClick(Sender: TObject); begin Open; end; procedure TNewMessageForm.LoadMessageText(const FileName: string); var OldText: string; begin OldText := MessageTextMemo.Text; MessageTextMemo.Lines.LoadFromFile(FileName); if IsError(Length(MessageTextMemo.Text) > MessageTextMemo.MaxLength, rsMessageTooLong) then begin MessageTextMemo.Text := OldText; end; end; procedure TNewMessageForm.SaveMessageText(const FileName: string); begin MessageTextMemo.Lines.SaveToFile(FileName); end; procedure TNewMessageForm.Clear; begin MessageTextMemo.Lines.Clear; CharCountLabel.Caption := '0'; OKButton.Enabled := False; end; procedure TNewMessageForm.Open; begin with MessageTextOpenDialog do begin if Execute then begin LoadMessageText(FileName); end; end; end; procedure TNewMessageForm.Save; begin with MessageTextSaveDialog do begin if Execute then begin SaveMessageText(FileName); end; end; end; procedure TNewMessageForm.SetMaxMessageLength(const MaxMessageLength: Integer); begin MessageTextMemo.MaxLength := MaxMessageLength; end; end.
unit AuthenticationResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, NullableBasicTypesUnit, JSONNullableAttributeUnit; type TPartOfBadAuthenticationResponse = class(TGenericParameters) private [JSONName('status')] FStatus: boolean; [JSONName('session_guid')] [Nullable] FSessionGuid: NullableString; [JSONName('error')] [Nullable] FError: NullableString; public constructor Create; override; property Status: boolean read FStatus write FStatus; property SessionGuid: NullableString read FSessionGuid write FSessionGuid; property Error: NullableString read FError write FError; end; TBadAuthenticationResponse = class(TGenericParameters) // {"session":{"status":false,"error":"Invalid credentials username or password"}} private [JSONName('session')] FSession: TPartOfBadAuthenticationResponse; function GetSessionGuid: NullableString; function GetStatus: boolean; function GetError: NullableString; public property Status: boolean read GetStatus; property SessionGuid: NullableString read GetSessionGuid; property Error: NullableString read GetError; end; TGoodAuthenticationResponse = class(TGenericParameters) {"status":true,"geocoding_service":"http:\/\/validator.route4me.com","session_id":4434046,"session_guid":"38a7a2109334400d672a68aefea83d31","member_id":"387130","api_key":"B46DD4D348B02C249556BF135E800B61","tracking_ttl":60,"geofence_polygon_shape":null,"geofence_polygon_size":0,"geofence_time_onsite_trigger_secs":0,"geofence_minimum_trigger_speed":20,"is_subscription_past_due":null,"visited_departed_enabled":"true","long_press_enabled":"true","account_type_id":"126","account_type_alias":"Enterprise","member_type":"SUB_ACCOUNT_DISPATCHER","max_stops_per_route":"1000","max_routes":"1000","routes_planned":null,"preferred_units":null,"preferred_language":"en","HIDE_ROUTED_ADDRESSES":"FALSE","HIDE_VISITED_ADDRESSES":"FALSE","HIDE_NONFUTURE_ROUTES":"FALSE","READONLY_USER":"FALSE","auto_logout_ts":-1,"last_known_member_payment_device":"web"} private [JSONName('status')] FStatus: boolean; [JSONName('session_id')] FSessionId: integer; [JSONName('session_guid')] FSessionGuid: String; public property Status: boolean read FStatus; property SessionId: integer read FSessionId; property SessionGuid: String read FSessionGuid; end; implementation constructor TPartOfBadAuthenticationResponse.Create; begin inherited; FError := NullableString.Null; FSessionGuid := NullableString.Null; end; function TBadAuthenticationResponse.GetError: NullableString; begin Result := FSession.Error; end; function TBadAuthenticationResponse.GetSessionGuid: NullableString; begin Result := FSession.SessionGuid; end; function TBadAuthenticationResponse.GetStatus: boolean; begin Result := FSession.Status; end; end.
unit Mat.ProjectParser; interface uses System.Generics.Collections, System.Classes, System.SysUtils, System.IOUtils, XMLIntf, XMLDoc, Mat.ProjectUnitParser, Vcl.Forms; type // Class for Project file parsing. TProjectFile = class private FFullPath: string; FTitle: string; FUnits: TUnitStructList; Fversion: string; FIs64Support: boolean; XMLDocument: TXMLDocument; function GetFileName: string; protected function ParseItem(const AStr: string): TUnitStructFile; public constructor Create; destructor Destroy; override; property FullPath: string read FFullPath write FFullPath; property FileName: string read GetFileName; property Title: string read FTitle write FTitle; property Units: TUnitStructList read FUnits write FUnits; property Version: string read Fversion write Fversion; property Is64Support: boolean read FIs64Support write FIs64Support; procedure ParseBlock(const ABlock: string); procedure ParseTitle(const ABlock: string; TT: string); procedure DetectProjectVersion(FileName: string); end; TProjectsList = class(TList<TProjectFile>) protected public procedure ParseDirectory(const ADirectory: string; AIsRecursively: boolean); function ParseFile(const APath: string): TProjectFile; end; implementation uses Mat.Constants, Mat.AnalysisProcessor; { TProjectFile } constructor TProjectFile.Create; begin FUnits := TUnitStructList.Create; end; destructor TProjectFile.Destroy; begin FUnits.Free; inherited; end; function TProjectFile.GetFileName: string; begin Result := TPath.GetFileNameWithoutExtension(FFullPath); end; function TProjectFile.ParseItem(const AStr: string): TUnitStructFile; var LData: string; P: PChar; S: string; Index: integer; Pause: boolean; PauseSpace: boolean; LUnitPath: string; LClassVar: string; function PathCombine(A, B: string): string; var Sl1, Sl2: TStringList; Drive: string; i: integer; begin Drive := ''; Sl1 := TStringList.Create; Sl2 := TStringList.Create; try if A[2] = ':' then begin Drive := A[1]; Sl1.StrictDelimiter := True; Sl1.Delimiter := TPath.DirectorySeparatorChar; Sl1.DelimitedText := A.Substring(2); end else begin Sl1.StrictDelimiter := True; Sl1.DelimitedText := A; end; Sl2.StrictDelimiter := True; Sl2.Delimiter := TPath.DirectorySeparatorChar; Sl2.DelimitedText := B; while (Sl2.Count > 0) and (Sl2[0] = '..') do begin Sl1.Delete(Sl1.Count - 1); Sl2.Delete(0); end; if not Drive.IsEmpty then Result := Drive + ':'; for i := 0 to Sl1.Count - 1 do if not Sl1[i].IsEmpty then Result := Result + TPath.DirectorySeparatorChar + Sl1[i]; for i := 0 to Sl2.Count - 1 do if not Sl2[i].IsEmpty then Result := Result + TPath.DirectorySeparatorChar + Sl2[i]; finally Sl2.Free; Sl1.Free; end; end; begin LData := AStr.Trim + ' '; P := PChar(LData); Result := TUnitStructFile.Create; index := 1; Pause := False; PauseSpace := False; S := ''; while (P^ <> #0) do begin if not Pause then S := S + P^; if P^ = '''' then PauseSpace := not PauseSpace; if S.IsEmpty = False then if (PauseSpace = False) or (P^ = #0) then if ((P^ = ' ') and (S[S.Trim.Length] <> ':')) then begin S := S.Trim; if S.Equals('in') then begin S := ''; end else begin Pause := True; end; end; if Pause and not S.IsEmpty then begin case Index of // 1: Result.UnitFileName := s; 2: begin if S.Trim[1] = '''' then S := S.Substring(1); if S.Trim[S.Trim.Length] = '''' then S := S.Substring(0, S.Trim.Length - 1); if (not S.IsEmpty) and (not((S[1] = '.') and (S[2] = '.'))) then if TPath.HasValidPathChars(S, True) then S := TPath.Combine (TPath.GetDirectoryName(FFullPath), S); if (not S.IsEmpty) and ((S[1] = '.') and (S[2] = '.')) then begin S := PathCombine (TPath.GetDirectoryName(FFullPath), S); end; LUnitPath := S; end; 3: LClassVar := S; end; Pause := False; PauseSpace := False; inc(Index); S := ''; end; inc(P); end; if (LUnitPath.IsEmpty) or (Pos(PAS_EXT, LUnitPath) = 0) or (not TFile.Exists(LUnitPath)) then FreeAndNil(Result) else begin Result := (FAnalysisProcessor.UnitStructList.ParseFile(LUnitPath)); if (not LClassVar.IsEmpty) and (Pos(':', LClassVar) = 0) then Result.FormName := LClassVar; end; end; procedure TProjectFile.ParseTitle(const ABlock: string; TT: string); var S: string; begin S := ABlock.Substring(Pos(TT, ABlock.ToLower) + TT.Length).Trim; if (S[1] = ':') and (S[2] = '=') then S := S.Substring(2).Trim; if S[S.Length] = ';' then S := S.Substring(0, S.Length - 1).Trim; if (S[1] = '''') then S := S.Substring(1, MaxInt); if S[S.Length] = '''' then S := S.Substring(0, S.Length - 1).Trim; FTitle := S; end; procedure TProjectFile.ParseBlock(const ABlock: string); var TempStr: string; P: PChar; LUnitInfo: TUnitStructFile; LWaitParsing: boolean; LStr: string; begin TempStr := ABlock.Trim; if Pos(TempStr, USES_SEARCH_STRING) = 0 then TempStr := TempStr.Substring(4).Trim; P := PChar(TempStr); LStr := ''; while (P^ <> #0) do begin LWaitParsing := (P^ = ',') or (P^ = ';'); if not LWaitParsing then LStr := LStr + P^; if LWaitParsing and (not LStr.IsEmpty) then begin LUnitInfo := ParseItem(LStr); if Assigned(LUnitInfo) then begin FUnits.Add(LUnitInfo); end; LStr := ''; end; inc(P); end; end; { TProjectsList } procedure TProjectsList.ParseDirectory(const ADirectory: string; AIsRecursively: boolean); var LDirectories: TArray<string>; LFiles: TArray<string>; LCurrentPath: string; LPF: TProjectFile; begin if AIsRecursively then begin LDirectories := TDirectory.GetDirectories(ADirectory); for LCurrentPath in LDirectories do ParseDirectory(LCurrentPath, True); end; LFiles := TDirectory.GetFiles(ADirectory, PROJECT_EXT_AST); for LCurrentPath in LFiles do begin LPF := ParseFile(LCurrentPath); Add(LPF); end; end; function TProjectsList.ParseFile(const APath: string): TProjectFile; var LRowUsesList: TStringList; LFileData: TStringList; i: integer; LParsingStarted: boolean; LBlock: string; LIsTitleFound: boolean; begin Result := TProjectFile.Create; LParsingStarted := False; LBlock := ''; LRowUsesList := nil; LFileData := nil; try LFileData := TStringList.Create; LRowUsesList := TStringList.Create; if TFile.Exists(APath) then begin LFileData.LoadFromFile(APath, TEncoding.ANSI); Result.FullPath := APath; LIsTitleFound := False; for i := 0 to Pred(LFileData.Count) do begin if (not LParsingStarted) and (Pos(LFileData[i].Trim.ToLower, USES_SEARCH_STRING) > 0) then LParsingStarted := True; if LParsingStarted then begin LBlock := LBlock + LFileData[i] + CRLF; if LFileData[i].IndexOf(';') > 0 then LParsingStarted := False; end; if (not LParsingStarted) and (not LBlock.IsEmpty) then begin Result.ParseBlock(LBlock); LBlock := ''; end; if not LIsTitleFound then begin if (Pos(PROGRAMM_SEARCH_STRING, LFileData[i].Trim.ToLower) > 0) then if LFileData[i].Trim.ToLower[LFileData[i].Trim.Length] = ';' then begin Result.ParseTitle(LFileData[i], PROGRAMM_SEARCH_STRING); LIsTitleFound := not Result.Title.IsEmpty; end else if (Pos(LIBRARY_SEARCH_STRING, LFileData[i].Trim.ToLower) > 0) then if LFileData[i].Trim.ToLower [LFileData[i].Trim.Length] = ';' then begin Result.ParseTitle(LFileData[i], LIBRARY_SEARCH_STRING); LIsTitleFound := not Result.Title.IsEmpty; end; end; end; end; finally LRowUsesList.Free; LFileData.Free end; end; procedure TProjectFile.DetectProjectVersion(FileName: string); var RootNode: IXMLNode; i: integer; Pprojinfo: IXMLNode; DpojName: string; begin DpojName := FileName + NEW_FILE_FORMAT_ADDICT; if TFile.Exists(DpojName) then begin XMLDocument := TXMLDocument.Create(application); XMLDocument.LoadFromFile(DpojName); XMLDocument.Active := True; Pprojinfo := XMLDocument.DocumentElement.ChildNodes[PG_NODE]; RootNode := XMLDocument.DocumentElement.ChildNodes[PE_NODE].ChildNodes [BP_NODE].ChildNodes[PF_NODE]; Fversion := Pprojinfo.ChildNodes[PV_NODE].NodeValue; for i := 0 to RootNode.ChildNodes.Count - 1 do begin Pprojinfo := RootNode.ChildNodes.Nodes[i]; if RootNode.ChildNodes[i].Attributes[NODE_ATTR] = WIN64_CONST then if RootNode.ChildNodes[i].NodeValue = TRUE_VALUE then FIs64Support := True; end; end; end; end.
unit GMPanel; { ******************************************************************** } { TGMPanel } { ******************************************************************** } { Date : 2006-10-30 } { Coding : Gerard Maheu } { } { } { Comments to : gerard1@mailcity.com } { ******************************************************************** } { Properties : } { Title with or without section } { Shadow, opaque or semi-transparent } { Picture or gradient on background } { Panel semi-transparent } { Panel of differents shapes } { Predefined themes } { ******************************************************************** } { COPYING THE SOFTWARE } { You can freely copy the component provided and re-distribute } { royalty free. } { } { MODIFIED VERSIONS OF THE SOFTWARE } { Feel free to update, revise, modify or improve the component. } { If you do so, PLEASE submit to the author any improvements or } { additions you made for future inclusion in the general distribution } { of the component by the author. } { ******************************************************************** } { MODIFICATIONS : (Please, leave all the above sections.) } { Date : Date of modification } { By : Your name } { Email : } { Description: } { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} { ******************************************************************** } //TODO: avec picture ou gradient, ca branle ! voir pour ajouter un masque // lorsqu'on a une forme autre que rectangle, pour conserver la forme. interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, Math; const CM_NEEDBACK = CM_BASE + 101; NB_PIXELS = 25; // Grandeur minimum pour la section de titre, et // grandeur maximum pour les coins des polygones. type TPanelType = (ptRectangle, ptRoundRect, ptTitleRoundRect, ptOctogone, ptHexagoneLeft, ptHexagoneRight); TTitlePosition = (tpTop, tpLeft, tpBottom); THorizontalAlign = (haCenter, haRight, haLeft, haNone); TVerticalAlign = (vaCenter, vaTop, vaBottom, vaNone); TShadowPosition = (spTopLeft, spTopRight, spBottomLeft, spBottomRight); TPictureStyle = (psTile, psCenter, psStretch); TGradientType = (gtHorizontal, gtVertical); TTransparentType = (gttNone, gttLeft, gttRight, gttUp, gttDown); TThemeType = (ttNote, ttBlue, ttPurple, ttGreen, ttYellow, ttCream, ttRed, ttCustom); TTransparent = class(TPersistent) private FActive: Boolean; FPercent: Integer; FType: TTransparentType; FOnChange: TNotifyEvent; procedure SetTransparentActive(const Value: Boolean); procedure SetTransparentPercent(Value: Integer); procedure SetTransparentType(const Value: TTransparentType); protected procedure ChangeOccured; dynamic; public constructor Create; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Active: Boolean read FActive write SetTransparentActive; property Percent: Integer read FPercent write SetTransparentPercent; property GradientType: TTransparentType read FType write SetTransparentType; end; TTitle = class(TPersistent) private FText : String; // Texte du titre. FFont: TFont; // Police du texte. FTop: Integer; // Position verticale du texte si FVAlign = vaNone. FLeft: Integer; // Position horizontale du texte si FHAlign = haNone. FVAlign: TVerticalAlign; // Alignement vertical du titre. FHAlign: THorizontalAlign; // Alignement horizontal du titre. FSectionVisible : Boolean; // Section de titre visible ou non. FSectionPosition: TTitlePosition; // Position de la section de titre. FSectionSize: Integer; // Dimension de la section de titre. FSectionColor: TColor; // Couleur de fon de la section de titre. FTransparent: TTransparent; FOnChange: TNotifyEvent; procedure SetText(const Value: String); procedure SetFont(const Value: TFont); procedure SetTop(const Value: Integer); procedure SetLeft(const Value: Integer); procedure SetSectionColor(const Value: TColor); procedure SetSectionPosition(const Value: TTitlePosition); procedure SetSectionSize(const Value: Integer); procedure SetSectionVisible(const Value: Boolean); procedure SetVAlign(const Value: TVerticalAlign); procedure SetHAlign(const Value: THorizontalAlign); procedure TitleChange(Sender: TObject); protected procedure ChangeOccured; dynamic; public constructor Create; destructor Destroy; override; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Text : String read FText write SetText; property Font : TFont read FFont write SetFont; property Top : Integer read FTop write SetTop; property Left : Integer read FLeft write SetLeft; property VerticalAlign: TVerticalAlign read FVAlign write SetVAlign; property HorizontalAlign: THorizontalAlign read FHAlign write SetHAlign; property SectionVisible : Boolean read FSectionVisible write SetSectionVisible; property SectionPosition : TTitlePosition read FSectionPosition write SetSectionPosition; property SectionSize : Integer read FSectionSize write SetSectionSize; property SectionColor : TColor read FSectionColor write SetSectionColor; property Transparent: TTransparent read FTransparent write FTransparent; end; TShadow = class(TPersistent) private FVisible : Boolean; // Ombrage visible ou non. FColor : TColor; // Couleur de l'ombre. FDepth : Integer; // Profondeur de l'ombre. FSpace : Integer; // Espace de l'ombre à partir du bord du panneau. FPosition : TShadowPosition; // Position de l'ombre. FTransparency : Integer; // Pourcentage de transparence FOnChange: TNotifyEvent; procedure SetVisible(Value : Boolean); procedure SetColor(Value : TColor); procedure SetDepth(Value : Integer); procedure SetSpace(Value : Integer); procedure SetPosition(Value : TShadowPosition); procedure SetTransparency(Value : Integer); protected procedure ChangeOccured; dynamic; public constructor Create; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Visible : Boolean read FVisible write SetVisible; property Color : TColor read FColor write SetColor; property Depth : Integer read FDepth write SetDepth; property Space : Integer read FSpace write SetSpace; property Position: TShadowPosition read FPosition write SetPosition; property Transparency : Integer read FTransparency write SetTransparency; end; TGMPanelPicture = class(TPersistent) private FPicture: TBitMap; FStyle : TPictureStyle; FTransparent: Boolean; FOnChange: TNotifyEvent; procedure SetPicture(const Value : TBitMap); procedure SetPictureStyle(const Value : TPictureStyle); procedure SetPictureTransparent(const Value : Boolean); protected procedure ChangeOccured; dynamic; public constructor Create; destructor Destroy; override; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Picture: TBitMap read FPicture write SetPicture; property Style: TPictureStyle read FStyle write SetPictureStyle; property Transparent: Boolean read FTransparent write SetPictureTransparent; end; TGradient = class(TPersistent) private FActive: Boolean; FPercent: Integer; FColor_1: TColor; FColor_2: TColor; FColor_3: TColor; FType: TGradientType; FOnChange: TNotifyEvent; procedure SetGradientActive(const Value: Boolean); procedure SetGradientPercent(Value: integer); procedure SetGradientColor_1(const Value: TColor); procedure SetGradientColor_2(const Value: TColor); procedure SetGradientColor_3(const Value: TColor); procedure SetGradientType(const Value: TGradientType); protected procedure ChangeOccured; dynamic; public constructor Create; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Active: Boolean read FActive write SetGradientActive; property Percent: Integer read FPercent write SetGradientPercent; property Color_1: TColor read FColor_1 write SetGradientColor_1; property Color_2: TColor read FColor_2 write SetGradientColor_2; property Color_3: TColor read FColor_3 write SetGradientColor_3; property GradientType: TGradientType read FType write SetGradientType; end; TGMPanel = class(TCustomPanel) private FTitle: TTitle; FShadow: TShadow; FPicture: TGMPanelPicture; FBackBitmap : TBitmap; FGradient : TGradient; FPanelType: TPanelType; FRoundRectDegree: Integer; FTheme: TThemeType; FTransparent: TTransparent; procedure WMEraseBkGnd(var Message: TWMEraseBkGnd); message WM_EraseBkGnd; procedure DrawSection(const Rect: TRect); procedure DrawShadow(var Rect: TRect); procedure DrawPanel(var PanelRect: TRect); procedure DrawTitle(var Rect: TRect); procedure FontChanged(Sender: TObject); procedure TitleChanged(Sender: TObject); procedure ShadowChanged(Sender: TObject); procedure PictureChanged(Sender: TObject); procedure GradientChanged(Sender: TObject); procedure TransparentChange(Sender: TObject); procedure GetBackGround(Parent: TWinControl); procedure WMSIZE(var Message : TMessage); message WM_SIZE; procedure WMMOVE(Var Message : TMessage); message WM_MOVE; procedure CMNEEDBACK(Var Message : TMessage); message CM_NEEDBACK; procedure SetPanelType(const Value: TPanelType); procedure SetRoundRectDegree(const Value: integer); procedure SetTheme(const Value: TThemeType); procedure DoGradient(CL, CT, CW, CH : Integer); procedure DrawGradient(GradientRect: TRect); procedure DrawRectTransparent(TheRect: TRect; TransPercent: Integer; RectColor : TColor; TransparentType: TTransparentType;IsShadow : Boolean); procedure Frame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor; Width: Integer); protected procedure SetParent(AParent: TWinControl); override; procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Invalidate; override; procedure RePaint; override; procedure Refresh; procedure Update; override; published // Rendre published les propriétés qu'on veut. property Align; property Alignment; property Anchors; property AutoSize; property BevelInner; property BevelOuter; property BevelWidth; property BiDiMode; property BorderWidth; property Color; property Constraints; property Ctl3D; property UseDockManager default True; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property FullRepaint; property Font; property Locked; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDockDrop; property OnDockOver; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; property OnUnDock; // Nouvelles propriétés. property Title: TTitle read FTitle write FTitle; property Shadow: TShadow read FShadow write FShadow; property Gradient : TGradient read FGradient write FGradient; property Picture: TGMPanelPicture read FPicture write FPicture; property PanelType: TPanelType read FPanelType write SetPanelType; property RoundRectDegree : Integer read FRoundRectDegree write SetRoundRectDegree; property Theme: TThemeType read FTheme write SetTheme; property Transparent: TTransparent read FTransparent write FTransparent; end; procedure Register; implementation procedure Register; begin RegisterComponents('Additional', [TGMPanel]); end; { -------------------------------------------------------------------- Méthode : DrawBitmapTile. But : -------------------------------------------------------------------- } procedure DrawBitmapTile(B:TBitmap; C:TCanvas; AR:TRect); var PB,PBP : TBitMap; X,Y : integer; begin PB := TBitMap.Create; PBP := TBitMap.Create; PB.Assign(B); PB.Dormant; // Free up GDI resources PB.FreeImage; // Free up Memory. try if not PB.Empty then begin y := AR.Top; while y < AR.Bottom do begin x := AR.Left; while x < AR.Right do begin if x + PB.Width <= AR.Right then begin if y + PB.Height <= AR.Bottom then begin C.Draw(x, y,PB ) end else begin PBP.Assign(B); PBP.Height:=(AR.Bottom-y); C.Draw(x, y,PBP); PBP.Dormant; // Free up GDI resources PBP.FreeImage; // Free up Memory. end; end else begin if y + PB.Height<=AR.Bottom then begin PBP.Assign(B); PBP.Width := (AR.Right-x); C.Draw(x, y,PBP); PBP.Dormant; // Free up GDI resources PBP.FreeImage; // Free up Memory. end else begin PBP.Assign(B); PBP.Width := (AR.Right-x); PBP.Height := (AR.Bottom-y); C.Draw(x, y,PBP); PBP.Dormant; // Free up GDI resources PBP.FreeImage; // Free up Memory. end; end; x := x + PB.Width; end; y := y + PB.Height; end; end; finally PB.Free; PBP.Free; end; end; { -------------------------------------------------------------------- Méthode : DrawBitmapCenter. But : -------------------------------------------------------------------- } procedure DrawBitmapCenter(B:TBitmap; C:TCanvas; AR:TRect); var PB : TBitMap; X,Y : integer; begin PB:=TBitMap.Create; PB.Assign(B); PB.Dormant; // Free up GDI resources PB.FreeImage; // Free up Memory. try if not PB.Empty then begin if PB.Width<(AR.Right-AR.Left) then begin X:=AR.Left+((AR.Right-PB.Width-AR.Left) div 2); end else begin X := AR.Left; PB.Width:=AR.Right-AR.Left; end; if PB.Height<(AR.Bottom-AR.Top) then begin Y:=AR.Top+((AR.Bottom-PB.Height-AR.Top) div 2); end else begin y := AR.Top; PB.Height:=AR.Bottom-AR.Top; end; C.Draw(x, y,PB); end; finally PB.Free; end; end; { -------------------------------------------------------------------- Méthode : DrawBitmapStretch. But : -------------------------------------------------------------------- } procedure DrawBitmapStretch(B:TBitmap; C:TCanvas; AR:TRect); var PB : TBitMap; begin PB:=TBitMap.Create; PB.Assign(B); PB.Dormant; // Free up GDI resources PB.FreeImage; // Free up Memory. try if not PB.Empty then C.StretchDraw(AR,PB); finally PB.Free; end; end; { ******************************************************************** } { ****************************** TGMPanel **************************** } { ******************************************************************** } { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TGMPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csOpaque]; // Panel transparent. FTitle := TTitle.Create; FTitle.Font.OnChange := FontChanged; FTitle.OnChange := TitleChanged; FShadow := TShadow.Create; FShadow.OnChange := ShadowChanged; FPicture := TGMPanelPicture.Create; FPicture.OnChange := PictureChanged; FGradient := TGradient.Create; FGradient.OnChange := GradientChanged; FTransparent := TTransparent.Create; FTransparent.OnChange:= TransparentChange; FTheme := ttCustom; FBackBitmap := TBitmap.Create; FBackBitmap.PixelFormat:=pf24bit; PanelType := ptRectangle; RoundRectDegree := 20; BevelInner := bvNone; BevelOuter := bvNone; BevelWidth := 1; BorderWidth := 0; FullRepaint := True; end; { -------------------------------------------------------------------- Méthode : CreateParams. But : Avoir un panneau transparent. -------------------------------------------------------------------- } procedure TGMPanel.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT; end; { -------------------------------------------------------------------- Méthode : Frame3D. But : -------------------------------------------------------------------- } procedure TGMPanel.Frame3D(Canvas: TCanvas; var Rect: TRect; TopColor, BottomColor: TColor; Width: Integer); procedure DoRect; // Largement inspiré de TCustomPanel.Paint du unit ExtCtrls. var Delta : Integer; // Dimension des coins du polygone. begin Delta := Min(NB_PIXELS, (Rect.Bottom div 4)); // Un maximum de 25 pixels. case FPanelType of ptRectangle : begin Canvas.Pen.Color := TopColor; Canvas.PolyLine([Point(Rect.Left, Rect.Bottom), Point(Rect.Left, Rect.Top), Point(Rect.Right, Rect.Top)]); Canvas.Pen.Color := BottomColor; Canvas.PolyLine([Point(Rect.Right, Rect.Top), Point(Rect.Right, Rect.Bottom), Point(Rect.Left-1, Rect.Bottom)]); end; ptRoundRect : begin Canvas.Pen.Color := TopColor; // Côté gauche. Canvas.MoveTo(Rect.Left, Rect.Bottom - (FRoundRectDegree div 2)); Canvas.LineTo(Rect.Left, Rect.Top + (FRoundRectDegree div 2)); // Coin supérieur gauche. Canvas.Arc(Rect.Left, Rect.Top, Rect.Left+FRoundRectDegree, Rect.Top+FRoundRectDegree, Rect.Left+(FRoundRectDegree div 2), Rect.Top, Rect.Left, Rect.Top+(FRoundRectDegree div 2)); // Côté du haut. Canvas.MoveTo(Rect.Left + (FRoundRectDegree div 2), Rect.Top); Canvas.LineTo(Rect.Right - (FRoundRectDegree div 2), Rect.Top); // Coin supérieur droit. Canvas.Arc(Rect.Right-FRoundRectDegree, Rect.Top, Rect.Right, Rect.Top+FRoundRectDegree, Rect.Right, Rect.Top + (FRoundRectDegree div 2), Rect.Right - (FRoundRectDegree div 2), Rect.Top); Canvas.Pen.Color := BottomColor; // Côté droit. Canvas.MoveTo(Rect.Right, Rect.Top + (FRoundRectDegree div 2)); Canvas.LineTo(Rect.Right, Rect.Bottom - (FRoundRectDegree div 2)); // Coin inférieur droit. Canvas.Arc(Rect.Right-FRoundRectDegree, Rect.Bottom - FRoundRectDegree, Rect.Right, Rect.Bottom, Rect.Right - (FRoundRectDegree div 2), Rect.Bottom, Rect.Right, Rect.Bottom - (FRoundRectDegree div 2)); // Côté du bas. Canvas.MoveTo(Rect.Right - (FRoundRectDegree div 2), Rect.Bottom); Canvas.LineTo(Rect.Left-1 + (FRoundRectDegree div 2), Rect.Bottom); // Coin inférieur gauche. Canvas.Arc(Rect.Left-1, Rect.Bottom - FRoundRectDegree, Rect.Left-1+FRoundRectDegree, Rect.Bottom, Rect.Left-1, Rect.Bottom-(FRoundRectDegree div 2), Rect.Left-1+(FRoundRectDegree div 2), Rect.Bottom ); end; ptTitleRoundRect : begin if FTitle.SectionVisible then begin if FTitle.SectionPosition = tpTop then begin Canvas.Pen.Color := TopColor; // Côté gauche. Canvas.MoveTo(Rect.Left, Rect.Bottom); Canvas.LineTo(Rect.Left, Rect.Top + (FRoundRectDegree div 2)); // Coin supérieur gauche. Canvas.Arc(Rect.Left, Rect.Top, Rect.Left+FRoundRectDegree, Rect.Top+FRoundRectDegree, Rect.Left+(FRoundRectDegree div 2), Rect.Top, Rect.Left, Rect.Top+(FRoundRectDegree div 2)); // Côté du haut. Canvas.MoveTo(Rect.Left + (FRoundRectDegree div 2), Rect.Top); Canvas.LineTo(Rect.Right - (FRoundRectDegree div 2), Rect.Top); Canvas.Pen.Color := BottomColor; // Coin supérieur droit. Canvas.Arc(Rect.Right-FRoundRectDegree, Rect.Top, Rect.Right, Rect.Top+FRoundRectDegree, Rect.Right, Rect.Top + (FRoundRectDegree div 2), Rect.Right - (FRoundRectDegree div 2), Rect.Top); // Côté droit. Canvas.MoveTo(Rect.Right, Rect.Top + (FRoundRectDegree div 2)); Canvas.LineTo(Rect.Right, Rect.Bottom); Canvas.LineTo(Rect.Left-1, Rect.Bottom); end else if FTitle.SectionPosition = tpBottom then begin Canvas.Pen.Color := TopColor; // Coin inférieur gauche. Canvas.Arc(Rect.Left, Rect.Bottom - FRoundRectDegree, Rect.Left+FRoundRectDegree, Rect.Bottom, Rect.Left, Rect.Bottom-(FRoundRectDegree div 2), Rect.Left+(FRoundRectDegree div 2), Rect.Bottom ); // Côté gauche. Canvas.MoveTo(Rect.Left, Rect.Bottom - (FRoundRectDegree div 2)); Canvas.LineTo(Rect.Left, Rect.Top); // Coté du haut. Canvas.LineTo(Rect.Right, Rect.Top); Canvas.Pen.Color := BottomColor; // Côté droit. Canvas.LineTo(Rect.Right, Rect.Bottom - (FRoundRectDegree div 2)); // Coin inférieur droit. Canvas.Arc(Rect.Right-FRoundRectDegree, Rect.Bottom - FRoundRectDegree, Rect.Right, Rect.Bottom, Rect.Right - (FRoundRectDegree div 2), Rect.Bottom, Rect.Right, Rect.Bottom - (FRoundRectDegree div 2)); // Côté du bas. Canvas.MoveTo(Rect.Right - (FRoundRectDegree div 2), Rect.Bottom); Canvas.LineTo(Rect.Left-1 + (FRoundRectDegree div 2), Rect.Bottom); end else // FTitlePosition = tpLeft. begin Canvas.Pen.Color := TopColor; // Coin inférieur gauche. Canvas.Arc(Rect.Left, Rect.Bottom - FRoundRectDegree, Rect.Left+FRoundRectDegree, Rect.Bottom, Rect.Left, Rect.Bottom-(FRoundRectDegree div 2), Rect.Left+(FRoundRectDegree div 2), Rect.Bottom ); // Côté gauche. Canvas.MoveTo(Rect.Left, Rect.Bottom - (FRoundRectDegree div 2)); Canvas.LineTo(Rect.Left, Rect.Top + (FRoundRectDegree div 2)); // Coin supérieur gauche. Canvas.Arc(Rect.Left, Rect.Top, Rect.Left+FRoundRectDegree, Rect.Top+FRoundRectDegree, Rect.Left+(FRoundRectDegree div 2), Rect.Top, Rect.Left, Rect.Top+(FRoundRectDegree div 2)); // Côté du haut. Canvas.MoveTo(Rect.Left + (FRoundRectDegree div 2), Rect.Top); Canvas.LineTo(Rect.Right, Rect.Top); Canvas.Pen.Color := BottomColor; // Côté droit. Canvas.LineTo(Rect.Right, Rect.Bottom); // Côté du bas. Canvas.LineTo(Rect.Left-1 + (FRoundRectDegree div 2), Rect.Bottom); end; end else begin // Pas de section de titre, donc c'est un rectangle ordinaire. Canvas.Pen.Color := TopColor; Canvas.PolyLine([Point(Rect.Left, Rect.Bottom), Point(Rect.Left, Rect.Top), Point(Rect.Right, Rect.Top)]); Canvas.Pen.Color := BottomColor; Canvas.PolyLine([Point(Rect.Right, Rect.Top), Point(Rect.Right, Rect.Bottom), Point(Rect.Left-1, Rect.Bottom)]); end; end; ptOctogone : begin Canvas.Pen.Color := TopColor; Canvas.PolyLine([Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Delta), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom)]); Canvas.Pen.Color := BottomColor; Canvas.PolyLine([Point(Rect.Left-1 + Delta, Rect.Bottom), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right, Rect.Top + Delta), Point(Rect.Right - Delta, Rect.Top)]); end; ptHexagoneLeft : begin Canvas.Pen.Color := TopColor; Canvas.PolyLine([Point(Rect.Right, Rect.Top), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left, Rect.Bottom)]); Canvas.Pen.Color := BottomColor; Canvas.PolyLine([Point(Rect.Left-1, Rect.Bottom), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right, Rect.Top)]); end; ptHexagoneRight : begin Canvas.Pen.Color := TopColor; Canvas.PolyLine([Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left, Rect.Top), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom)]); Canvas.Pen.Color := BottomColor; Canvas.PolyLine([Point(Rect.Left - 1 + Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom), Point(Rect.Right, Rect.Top + Delta), Point(Rect.Right - Delta, Rect.Top)]); end; end; // Case... end; begin Canvas.Pen.Width := 1; Dec(Rect.Bottom); Dec(Rect.Right); while Width > 0 do begin Dec(Width); DoRect; InflateRect(Rect, -1, -1); end; Inc(Rect.Bottom); Inc(Rect.Right); end; { -------------------------------------------------------------------- Méthode : Paint. But : -------------------------------------------------------------------- } procedure TGMPanel.Paint; var Rect: TRect; PictureRect: TRect; PanelRect: TRect; Flags: LongInt; begin Rect := GetClientRect; // Dessiner l'ombre et ajuste les dimensions du Rect en le diminuant // selon la grosseur de l'ombre. if Shadow.Visible then DrawShadow(Rect); PanelRect := Rect; // Mémorise les dimensions sans l'ombre, s'il y a lieu. // Dessiner le panneau. DrawPanel(Rect); // Dessiner le gradient. if FGradient.Active then DrawGradient(Rect); // Dessiner l'image en background. if not FPicture.Picture.Empty then begin PictureRect := Rect; FPicture.Picture.Transparent := FPicture.Transparent; if FTitle.SectionVisible then begin if FTitle.SectionPosition = tpTop then PictureRect.Top := PictureRect.Top + FTitle.SectionSize else if FTitle.SectionPosition = tpBottom then PictureRect.Bottom := PictureRect.Bottom - FTitle.SectionSize else // FTitlePosition = tpLeft. PictureRect.Left := PictureRect.Left + FTitle.SectionSize; end; case FPicture.Style of psTile : DrawBitmapTile(FPicture.Picture, Canvas, PictureRect); psCenter : DrawBitmapCenter(FPicture.Picture, Canvas, PictureRect); psStretch : DrawBitmapStretch(FPicture.Picture, Canvas, PictureRect); end; end; // if not FPicture.Picture.Empty then... if FTransparent.Active then DrawRectTransparent(PanelRect, FTransparent.FPercent, Color, FTransparent.FType, False); // Dessine la section de titre. if Title.SectionVisible then DrawTitle(Rect); // Écrire le titre. if Trim(FTitle.Text) > '' then begin Canvas.Font.Assign(FTitle.Font); Canvas.Brush.Style := bsClear; // Transparent. Canvas.Pen.Style := psClear; // Transparent. if (FTitle.VerticalAlign = vaNone) and (FTitle.HorizontalAlign = haNone) then Canvas.TextOut(FTitle.Left, FTitle.Top, FTitle.Text) else begin Flags := DT_SINGLELINE; case FTitle.VerticalAlign of vaCenter : Flags := Flags or DT_VCENTER; vaTop : Flags := Flags or DT_TOP; vaBottom : Flags := Flags or DT_BOTTOM; vaNone : Rect.Top := FTitle.Top; // FTitle.Top sera utilisé. end; case FTitle.HorizontalAlign of haCenter : Flags := Flags or DT_CENTER; haRight : Flags := Flags or DT_RIGHT; haLeft : Flags := Flags or DT_LEFT; haNone : Rect.Left := FTitle.Left; // FTitle.Left sera utilisé. end; DrawText(Canvas.Handle, PChar(FTitle.Text), -1, Rect, Flags); end; end; end; { -------------------------------------------------------------------- Méthode : WMEraseBkGnd. But : -------------------------------------------------------------------- } procedure TGMPanel.WMEraseBkGnd(var Message: TWMEraseBkGnd); begin Message.Result := 1; end; { -------------------------------------------------------------------- Méthode : SetParent. But : Faire en sorte que le panel soit transparent. Nécessaire pour que ca marche. -------------------------------------------------------------------- } procedure TGMPanel.SetParent(AParent: TWinControl); begin inherited SetParent(AParent); if Parent <> nil then SetWindowLong(Parent.Handle, GWL_STYLE, GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_ClipChildren); end; { -------------------------------------------------------------------- Méthode : RePaint. But : -------------------------------------------------------------------- } procedure TGMPanel.RePaint; begin inherited Repaint; end; { -------------------------------------------------------------------- Méthode : Refresh. But : -------------------------------------------------------------------- } procedure TGMPanel.Refresh; begin inherited Refresh; end; { -------------------------------------------------------------------- Méthode : Update. But : -------------------------------------------------------------------- } procedure TGMPanel.Update; begin inherited Update; end; { -------------------------------------------------------------------- Méthode : Invalidate. But : -------------------------------------------------------------------- } procedure TGMPanel.Invalidate; //var // Rect: TRect; begin // Rect := BoundsRect; // if (Parent <> nil) and Parent.HandleAllocated then // InvalidateRect(Parent.Handle, @Rect, True) // else inherited Invalidate; end; { -------------------------------------------------------------------- Méthode : Destroy. But : -------------------------------------------------------------------- } destructor TGMPanel.Destroy; begin inherited; FTitle.Free; FShadow.Free; FBackBitmap.Free; end; { -------------------------------------------------------------------- Méthode : DoGradient. But : Afficher un gradiant de couleurs sur le panneau. Params. : Section affectée délimitée par CL = Client left, CT = Client top, CW = Client width, CH = Client height. -------------------------------------------------------------------- } procedure TGMPanel.DoGradient(CL, CT, CW, CH: Integer); var H, D0, H1, S, S1, T, R, G, B, R0, G0, B0: Integer; Coefficient : Integer; function EX(A: Integer): Integer; begin Result := A div Coefficient; end; // procedure DWord_Int(C_X: TColor; var Rx, Gx, Bx: Integer); var Y1, Y2, Y3: Integer; begin Y1 := GetRValue(C_X); Y2 := GetGValue(C_X); Y3 := GetBValue(C_X); Rx := Y1 * Coefficient; Gx := Y2 * Coefficient; Bx := Y3 * Coefficient; end; // procedure DO_FILL(X1, X2, X3, X4: Integer); begin with Canvas do begin Brush.Color := RGB((EX(R) + EX(R0 div S * S1)), (EX(G) + EX(G0 div S * S1)), (EX(B) + EX(B0 div S * S1)) ); FillRect(RECT(X1, X2, X3, X4)); end; end; // procedure GPart(CxL, CxT, CxW, CxH, Dx0: Integer); var Sx1: Integer; begin if FGradient.GradientType = gtHorizontal then T := CxW else T := CxH; if T * Coefficient <= Dx0 then H := 1 else H := ((T + EX(Dx0)) - 1) * Coefficient div Dx0; // H := ((T + EX(Dx0))) * Coefficient div Dx0; S := T div H; // get number of steps MAX // now do the FILLING of the AREA H1 := H; // for all - but the last one for Sx1 := 0 to S do begin S1 := Sx1; // so the DO_FILL will see the VAR. if ((Sx1 + 1) * H) > T then // if ((Sx1) * H) > T then H1 := T - (Sx1 * H); if FGradient.GradientType = gtHorizontal then DO_FILL(CxL + (Sx1 * H), CxT, CxL + ((Sx1 * H) + H1), CxT + CxH) else DO_FILL(CxL, CxT + (Sx1 * H), CxL + CxW, CxT + ((Sx1 * H) + H1)); end; end; // function Get_Colors(FCol, TCol: TColor): Boolean; begin Result := False; if FCol = TCol then EXIT; // RED GREEN BLUE DWord_Int(ColorToRGB(FCol), R, G, B); // get MAX difference DWord_Int(ColorToRGB(TCol), R0, G0, B0); R0 := R0 - R; // get Color-Diff RED G0 := G0 - G; // GREEN B0 := B0 - B; // BLUE D0 := ABS(R0); // get Max-Color-Difference if ABS(G0) > D0 then D0 := ABS(G0); if ABS(B0) > D0 then D0 := ABS(B0); Result := TRUE; end; // function XH(I, Proz: Integer): Integer; // PART height begin Result := (I * Proz) div 100; if Result = 0 then Result := 1; end; begin Coefficient := 100; // Up to now - just a few general settings if FGradient.Percent = 100 then begin if Get_Colors(FGradient.Color_1, FGradient.Color_2) then GPart(CL, CT, CW, CH, D0); end else begin if Get_Colors(FGradient.Color_1, FGradient.Color_2) then if FGradient.GradientType = gtHorizontal then GPart(CL, CT, XH(CW, FGradient.Percent), CH, D0) else GPart(CL, CT, CW, XH(CH, FGradient.Percent), D0); if Get_Colors(FGradient.Color_2, FGradient.Color_3) then if FGradient.GradientType = gtHorizontal then GPart(CL + XH(CW, FGradient.Percent), CT, CW - XH(CW, FGradient.Percent), CH, D0) else GPart(CL, CT + XH(CH, FGradient.Percent), CW, CH - XH(CH, FGradient.Percent), D0); end; end; { -------------------------------------------------------------------- Méthode : DrawGradient. But : -------------------------------------------------------------------- } procedure TGMPanel.DrawGradient(GradientRect: TRect); var Dim : Integer; begin if (FTitle.SectionVisible) then begin Dim := FTitle.SectionSize; with GradientRect do begin if FTitle.SectionPosition = tpTop then DoGradient(Left, Top+Dim, Right-Left, Bottom-Dim-Top) else if FTitle.SectionPosition = tpBottom then DoGradient(Left, Top, Right-Left, Bottom-Dim-Top) else // if FTitlePosition = tpLeft DoGradient(Left+Dim, Top, Right-Dim-Left, Bottom-Top); end; // with GradientRect do end else DoGradient(GradientRect.Left, GradientRect.Top, GradientRect.Right-GradientRect.Left, GradientRect.Bottom-GradientRect.Top); end; { -------------------------------------------------------------------- Méthode : DrawPanel. But : Dessine le panneau. Param. : TRect délimitant le panneau. -------------------------------------------------------------------- } procedure TGMPanel.DrawPanel(var PanelRect: TRect); var TopColor, BottomColor: TColor; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin // Bordure 3D. if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, PanelRect, TopColor, BottomColor, BevelWidth); end; Frame3D(Canvas, PanelRect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, PanelRect, TopColor, BottomColor, BevelWidth); end; Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; DrawSection(PanelRect); end; { -------------------------------------------------------------------- Méthode : DrawRectTransparent. But : -------------------------------------------------------------------- } procedure TGMPanel.DrawRectTransparent(TheRect: TRect; TransPercent: Integer; RectColor : TColor; TransparentType: TTransparentType;IsShadow : Boolean); var FForeBitmap : TBitmap; p1,p2 : pByteArray; i,j : Integer; function Bias(PValue, PBias: Double): Double; begin //Invalid values means not bias calculation if (PBias <= 1) and (PBias >= -1) and (PValue >= 0) and (PValue <= 1) then begin // a Bias of 0 is a linear relationship. Let's save some time here if PBias = 0 then begin Result := PValue; exit; end; //PBias ranges from 1 through 0 to -1. Actual bias should be between 0 and 1 if PBias >= 0 then begin //Positive bias Result := Power(PValue, 1 - PBias); end else begin //mirrored positive bias Result := 1 - power(1 - PValue, 1 + PBias); end; end else begin Result := PValue; end; end; function CalculateTransFade(X, Y, Trans : Integer): Integer; var TransFade : Integer; begin case TransparentType of // Bitmap 24 bit (3 bytes par pixel pour R G et B) gttLeft : TransFade := 100 - Round(Bias(((X div 3)/FBackBitmap.Width), (Trans/100)) * (100-Trans)); gttRight: TransFade := 100 - Round(Bias((1 - (X div 3) / FBackBitmap.Width), (Trans/100)) * (100 - Trans)); gttUp : TransFade := 100 - Round(Bias((Y / FBackBitmap.Height), (Trans/100)) * (100 - Trans)); gttDown : TransFade := 100 - Round(Bias((1 - Y / FBackBitmap.Height), (Trans/100)) * (100 - Trans)); else TransFade := Trans; //gttNone end; // case... if TransFade < 0 then Result := 0 else if TransFade > 100 then Result := 100 else Result := TransFade; end; begin FForeBitmap := TBitmap.Create; FForeBitmap.PixelFormat := pf24bit; FForeBitmap.Width := FBackBitmap.Width; FForeBitmap.Height := FBackBitmap.Height; if (IsShadow) then begin FForeBitmap.Canvas.Brush.Color := RectColor; FForeBitmap.Canvas.Brush.Style := bsSolid; FForeBitmap.Canvas.Pen.Style := psClear; FForeBitmap.Canvas.FillRect(TheRect); end else begin // if (FGradient.Active) or not(FPicture.Picture.Empty) then // begin FForeBitmap.Canvas.CopyRect(Rect(0,0,FBackBitmap.Width,FBackBitmap.Height), Canvas, Rect(0,0,FBackBitmap.Width,FBackBitmap.Height)); // end // else // begin // FForeBitmap.Canvas.Brush.Color := RectColor; // FForeBitmap.Canvas.Brush.Style := bsSolid; // FForeBitmap.Canvas.Pen.Style := psClear; // FForeBitmap.Canvas.FillRect(TheRect); // end; end; // Jumelle les deux bitmap pour simuler la transparence. for i := 0 to FBackBitmap.Height-1 do begin p1 := FBackBitmap.ScanLine[i]; p2 := FForeBitmap.ScanLine[i]; for j := 0 to (3 * FBackBitmap.Width)-1 do // bitmap 24 Bit (3 Bytes per pixel pour R G et B) begin p2[j] := p2[j]+ (CalculateTransFade(j, i, TransPercent) * (p1[j]-p2[j]) div 100); end; end; Canvas.Pen.Style := psClear; Canvas.Brush.Bitmap := FForeBitmap; DrawSection(TheRect); FForeBitmap.Free; end; { -------------------------------------------------------------------- Méthode : DrawSection. But : Dessine une section selon le type de panel voulu. Param. : TRect délimitant la section. -------------------------------------------------------------------- } procedure TGMPanel.DrawSection(const Rect: TRect); var Delta : Integer; // Dimension des coins du polygone. begin Delta := Min(NB_PIXELS, (Rect.Bottom div 4)); // Un maximum de 25 pixels. case FPanelType of ptRectangle : Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); ptRoundRect : Canvas.RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, FRoundRectDegree, FRoundRectDegree); ptTitleRoundRect : begin if FTitle.SectionVisible then begin Canvas.RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, FRoundRectDegree, FRoundRectDegree); // Le côté opposé au titre est carré. On couvre donc la partie arrondie qu'on ne veut pas. case FTitle.SectionPosition of tpTop : Canvas.Rectangle(Rect.Left, Rect.Bottom - Delta - 2, Rect.Right, Rect.Bottom); tpBottom : Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Top + Delta + 2); else Canvas.Rectangle(Rect.Right - Delta - 2, Rect.Top, Rect.Right, Rect.Bottom); end; end else Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); end; ptOctogone : Canvas.Polygon([Point(Rect.Left, Delta), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right, Rect.Top + Delta), Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Delta)]); ptHexagoneLeft : Canvas.Polygon([Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left, Rect.Bottom), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right, Rect.Top), Point(Rect.Left + Delta, Rect.Top)]); ptHexagoneRight : Canvas.Polygon([Point(Rect.Left, Rect.Top), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom), Point(Rect.Right, Rect.Top + Delta), Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left, Rect.Top)]); end; end; { -------------------------------------------------------------------- Méthode : DrawShadow. But : Dessine l'ombre. Param. : TRect délimitant le panneau au complet. Retour : TRect est modifié pour obtenir les dimensions disponibles pour le panneau utilisable. -------------------------------------------------------------------- } procedure TGMPanel.DrawShadow(var Rect: TRect); var ShadowRect : TRect; begin Canvas.Brush.Color := Shadow.Color; Canvas.Brush.Style := bsSolid; Canvas.Pen.Color := Shadow.Color; ShadowRect := Rect; case FShadow.Position of spTopLeft : begin ShadowRect.Bottom := ShadowRect.Bottom - Shadow.Space; ShadowRect.Right := ShadowRect.Right - Shadow.Space; end; spTopRight : begin ShadowRect.Bottom := ShadowRect.Bottom - Shadow.Space; ShadowRect.Left := ShadowRect.Left + Shadow.Space; end; spBottomLeft : begin ShadowRect.Top := ShadowRect.Top + Shadow.Space; ShadowRect.Right:= ShadowRect.Right - Shadow.Space; end; spBottomRight : begin ShadowRect.Top := ShadowRect.Top + Shadow.Space; ShadowRect.Left := ShadowRect.Left + Shadow.Space; end; end; if Shadow.Transparency = 0 then begin DrawSection(ShadowRect); end else // Ombre transparente. begin DrawRectTransparent(ShadowRect, Shadow.Transparency, Shadow.Color, gttNone, True) end; // Retire les dimensions de l'ombre, pour le Rect disponible pour // le panneau. case FShadow.Position of spTopLeft : begin Rect.Left := ShadowRect.Left + Shadow.Depth; Rect.Top := ShadowRect.Top + Shadow.Depth; end; spTopRight : begin Rect.Right := ShadowRect.Right - Shadow.Depth; Rect.Top := ShadowRect.Top + Shadow.Depth; end; spBottomLeft : begin Rect.Left := ShadowRect.Left + Shadow.Depth; Rect.Bottom := ShadowRect.Bottom - Shadow.Depth; end; spBottomRight : begin Rect.Right := ShadowRect.Right - Shadow.Depth; Rect.Bottom := ShadowRect.Bottom - Shadow.Depth; end; end; end; { -------------------------------------------------------------------- Méthode : DrawTitle. But : Dessin de la section du titre. -------------------------------------------------------------------- } procedure TGMPanel.DrawTitle(var Rect: TRect); var Delta : Integer; // Dimension des coins du polygone. begin Delta := Min(NB_PIXELS, (Rect.Bottom div 4)); // Un maximum de 25 pixels. // Sépare la section pour le titre. case FTitle.SectionPosition of tpTop : Rect.Bottom := Rect.Top + FTitle.SectionSize + 1; tpLeft: Rect.Right := Rect.Left + FTitle.SectionSize + 1; else Rect.Top := Rect.Bottom - FTitle.SectionSize - 1; end; Canvas.Brush.Color := FTitle.SectionColor; Canvas.Pen.Color := FTitle.SectionColor; case FPanelType of ptRectangle : Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); ptRoundRect : begin Canvas.RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, FRoundRectDegree, FRoundRectDegree); // On veut la base du titre carré. case FTitle.SectionPosition of tpTop : Canvas.Rectangle(Rect.Left, Rect.Top + (FTitle.SectionSize div 2), Rect.Right, Rect.Bottom); tpBottom : Canvas.Rectangle(Rect.Left, Rect.Bottom - FTitle.SectionSize, Rect.Right, Rect.Bottom - (FTitle.SectionSize div 2)); tpLeft : Canvas.Rectangle(Rect.Left + (FTitle.SectionSize div 2), Rect.Top, Rect.Right, Rect.Bottom); end; end; ptTitleRoundRect : begin Canvas.RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, FRoundRectDegree, FRoundRectDegree); // Le côté opposé au titre est carré. On couvre donc la partie arrondie qu'on ne veut pas. case FTitle.SectionPosition of tpTop : Canvas.Rectangle(Rect.Left, Rect.Top + Delta, Rect.Right, Rect.Bottom); tpBottom : Canvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom - 10); else Canvas.Rectangle(Rect.Left + 10, Rect.Top, Rect.Right, Rect.Bottom); end; // On veut la base du titre carré. case FTitle.SectionPosition of tpTop : Canvas.Rectangle(Rect.Left, Rect.Top + (FTitle.SectionSize div 2), Rect.Right, Rect.Bottom); tpBottom : Canvas.Rectangle(Rect.Left, Rect.Bottom - FTitle.SectionSize, Rect.Right, Rect.Bottom - (FTitle.SectionSize div 2)); tpLeft : Canvas.Rectangle(Rect.Left + (FTitle.SectionSize div 2), Rect.Top, Rect.Right, Rect.Bottom); end; end; ptOctogone : case FTitle.SectionPosition of tpTop : // La section de titre arrive plus bas que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, FTitle.SectionSize), Point(Rect.Right, FTitle.SectionSize), Point(Rect.Right, Delta), Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Delta), Point(Rect.Left, FTitle.SectionSize)]); tpBottom : // La section de titre arrive plus haut que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Bottom - FTitle.SectionSize), Point(Rect.Right, Rect.Bottom - FTitle.SectionSize), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left, Rect.Bottom - FTitle.SectionSize)]); tpLeft : if ((Rect.Bottom div 4) = NB_PIXELS) and (FTitle.SectionSize = NB_PIXELS) then // La section de titre arrive vis-à-vis l'angle du panneau. Canvas.Polygon([Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left + Delta, Rect.Bottom)]) else // La section de titre arrive plus à droite que l'angle du panneau. Canvas.Polygon([Point(Rect.Left + FTitle.SectionSize, Rect.Bottom), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left + FTitle.SectionSize, Rect.Top), Point(Rect.Left + FTitle.SectionSize, Rect.Bottom)]); end; // case FTitle.SectionPosition of (ptOctogone) ptHexagoneLeft : case FTitle.SectionPosition of tpTop : // La section de titre arrive plus bas que l'angle du panneau. Canvas.Polygon([Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left, Rect.Top + FTitle.SectionSize), Point(Rect.Right, Rect.Top + FTitle.SectionSize), Point(Rect.Right, Rect.Top), Point(Rect.Left + Delta, Rect.Top)]); tpBottom : // La section de titre arrive plus haut que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Bottom), Point(Rect.Right - Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom - Delta), Point(Rect.Right, Rect.Bottom - FTitle.SectionSize), Point(Rect.Left, Rect.Bottom - FTitle.SectionSize), Point(Rect.Left, Rect.Bottom)]); tpLeft : if ((Rect.Bottom div 4) = NB_PIXELS) and (FTitle.SectionSize = NB_PIXELS) then // La section de titre arrive vis-à-vis l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Bottom), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left, Rect.Bottom)]) else // La section de titre arrive plus à droite que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Bottom), Point(Rect.Left + FTitle.SectionSize, Rect.Bottom), Point(Rect.Left + FTitle.SectionSize, Rect.Top), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top + Delta), Point(Rect.Left, Rect.Bottom)]); end; // case FTitle.SectionPosition of (ptHexagoneLeft) ptHexagoneRight : case FTitle.SectionPosition of tpTop : // La section de titre arrive plus bas que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Top), Point(Rect.Left, Rect.Top + FTitle.SectionSize), Point(Rect.Right, Rect.Top + FTitle.SectionSize), Point(Rect.Right, Rect.Top + Delta), Point(Rect.Right - Delta, Rect.Top), Point(Rect.Left, Rect.Top)]); tpBottom : // La section de titre arrive plus haut que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Bottom - FTitle.SectionSize), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Right, Rect.Bottom), Point(Rect.Right, Rect.Bottom - FTitle.SectionSize), Point(Rect.Left, Rect.Bottom - FTitle.SectionSize)]); tpLeft : if ((Rect.Bottom div 4) = NB_PIXELS) and (FTitle.SectionSize = NB_PIXELS) then // La section de titre arrive vis-à-vis l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Top), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left + Delta, Rect.Top), Point(Rect.Left, Rect.Top)]) else // La section de titre arrive plus à droite que l'angle du panneau. Canvas.Polygon([Point(Rect.Left, Rect.Top), Point(Rect.Left, Rect.Bottom - Delta), Point(Rect.Left + Delta, Rect.Bottom), Point(Rect.Left + FTitle.SectionSize, Rect.Bottom), Point(Rect.Left + FTitle.SectionSize, Rect.Top), Point(Rect.Left, Rect.Top)]); end; // case FTitle.SectionPosition of (ptHexagoneRight) end; // case FPanelType of if FTitle.FTransparent.Active then DrawRectTransparent(Rect, FTitle.FTransparent.FPercent, FTitle.FSectionColor, FTitle.FTransparent.FType, False); end; { -------------------------------------------------------------------- Méthode : FontChanged. But : Forcer à redessiner le panneau lorsque la police est modifiée. -------------------------------------------------------------------- } procedure TGMPanel.FontChanged(Sender: TObject); begin FTheme := ttCustom; Repaint; // Invalidate; end; { -------------------------------------------------------------------- Méthode : WMMOVE. But : -------------------------------------------------------------------- } procedure TGMPanel.WMMOVE(var Message: TMessage); begin inherited; PostMessage(Self.Handle, CM_NEEDBACK, 0, 0); Message.Result := 0; end; { -------------------------------------------------------------------- Méthode : WMSIZE. But : -------------------------------------------------------------------- } procedure TGMPanel.WMSIZE(var Message: TMessage); begin if Assigned(FBackBitmap) then begin FBackBitmap.Width := Width; FBackBitmap.Height := Height; end; PostMessage(Self.Handle, CM_NEEDBACK, 0, 0); end; { -------------------------------------------------------------------- Méthode : CMNEEDBACK. But : Mettre le background dans FBackBitmap. -------------------------------------------------------------------- } procedure TGMPanel.CMNEEDBACK(var Message: TMessage); begin GetBackGround(Self.Parent); end; { -------------------------------------------------------------------- Méthode : GetBackGround. But : -------------------------------------------------------------------- } procedure TGMPanel.GetBackGround(Parent: TWinControl); var ABitmap : TBitmap; // A1 : TBitmap; begin FBackBitmap.Width := Width; FBackBitmap.height := Height; if Assigned(Parent) then begin ABitmap := TBitmap.Create; ABitmap.PixelFormat := pf24bit; ABitmap.Width := -Parent.ClientOrigin.x + ClientOrigin.x + Width; ABitmap.Height := -Parent.ClientOrigin.y + ClientOrigin.y + Height; ABitmap.Canvas.Brush.Color := TCustomForm(Parent).Color; ABitmap.Canvas.FillRect(Rect(0, 0, ABitmap.Width, ABitmap.Height)); SendMessage(Parent.Handle, WM_PAINT, ABitmap.Canvas.Handle, 0); Application.ProcessMessages; // A1 := TBitmap.Create; // A1.PixelFormat := pf24Bit; // A1.width := FBackBitmap.Width; // A1.Height := FBackBitmap.Height; // A1.Canvas.Draw(0, 0, FBackBitmap); FBackBitmap.Canvas.Draw(Parent.ClientOrigin.x - ClientOrigin.x, Parent.ClientOrigin.y - ClientOrigin.y, ABitmap); // ABitmap.Free; Repaint; //Invalidate; // A1.free; end; end; { -------------------------------------------------------------------- Méthode : SetRoundRectDegree. But : -------------------------------------------------------------------- } procedure TGMPanel.SetRoundRectDegree(const Value: integer); begin FRoundRectDegree := Value; FTheme := ttCustom; Repaint; //Invalidate; end; { -------------------------------------------------------------------- Méthode : SetTheme. But : Appliquer le thème sélectionné. -------------------------------------------------------------------- } procedure TGMPanel.SetTheme(const Value: TThemeType); begin FTheme := Value; case FTheme of ttNote: begin Color := $00DDF2F2; // Beige pale. Font.Color := clMaroon; FTitle.SectionColor := $00C0DEDE; // Beige foncé. FTitle.SectionPosition := tpLeft; FTitle.SectionVisible := True; FTitle.SectionSize := 60; FTitle.Font.Color := clOlive; FShadow.Visible := False; end; ttBlue: begin Color := $00E3DED5; FTitle.SectionColor := RGB(0, 128, 192); FShadow.Visible := false; FTitle.Font.Color := clWhite; end; ttPurple: begin Color := $00CBC5C8; FTitle.SectionColor := clPurple; FShadow.Visible := false; FTitle.Font.Color := clWhite; end; ttGreen: begin Color := $00B9CEBB; FTitle.SectionColor := clGreen; FShadow.Visible := false; FTitle.Font.Color := clWhite; end; ttYellow: begin Color := $00BED2D8; FTitle.SectionColor := $00B9FFFF; FTitle.Font.Color := clBlack; FShadow.Visible := false; end; ttCream: begin Color := clWhite; FTitle.SectionColor := $00EFFBFF; FTitle.Font.Color := $00A5703A; FShadow.Visible := false; end; ttRed: begin Color := $00E1DBFD; FTitle.SectionColor := $00CBBFFF; FShadow.Visible := True; FTitle.Font.Color := $005A07AD; FShadow.Depth := 4; FShadow.Space := 10; end; end; Repaint; //Invalidate; // Ré-assigne car les affectations ci-haut remet FTheme = ttCustom. FTheme := Value; end; (* { -------------------------------------------------------------------- Méthode : SetTransparent. But : -------------------------------------------------------------------- } procedure TGMPanel.SetTransparent(const Value: TTransparent); begin FTransparency := Value; // if Value > 0 then // Gradient.Active := False; // Mutuellement exclusif. Repaint; //Invalidate; end; *) { -------------------------------------------------------------------- Méthode : SetPanelType. But : -------------------------------------------------------------------- } procedure TGMPanel.SetPanelType(const Value: TPanelType); begin FPanelType := Value; FTheme := ttCustom; Repaint; //Invalidate; end; { -------------------------------------------------------------------- Méthode : TitleChanged. But : Forcer à redessiner le panneau lorsque le titre est modifié. -------------------------------------------------------------------- } procedure TGMPanel.TitleChanged(Sender: TObject); begin FTheme := ttCustom; Repaint; //Invalidate; end; { -------------------------------------------------------------------- Méthode : ShadowChanged. But : Forcer à redessiner le panneau lorsque l'ombre est modifié. -------------------------------------------------------------------- } procedure TGMPanel.ShadowChanged(Sender: TObject); begin FTheme := ttCustom; Repaint; //Invalidate; end; { -------------------------------------------------------------------- Méthode : PictureChanged. But : Forcer à redessiner le panneau lorsque l'image est modifiée. -------------------------------------------------------------------- } procedure TGMPanel.PictureChanged(Sender: TObject); begin FTheme := ttCustom; Repaint; //Invalidate; end; { -------------------------------------------------------------------- Méthode : TransparentChange. But : -------------------------------------------------------------------- } procedure TGMPanel.TransparentChange(Sender: TObject); begin FTheme := ttCustom; Repaint; end; { -------------------------------------------------------------------- Méthode : GradientChanged. But : -------------------------------------------------------------------- } procedure TGMPanel.GradientChanged(Sender: TObject); begin FTheme := ttCustom; // if Gradient.Active then // Transparency := 0; // Mutuellement exclusif. Repaint; //Invalidate; end; { ******************************************************************** } { ****************************** TShadow ***************************** } { ******************************************************************** } { -------------------------------------------------------------------- Méthode : ChangeOccured. But : Indiquer qu'une modification a été apportée à l'ombre. -------------------------------------------------------------------- } procedure TShadow.ChangeOccured; begin if Assigned(FOnChange) then FOnChange(Self); end; { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TShadow.Create; begin FColor := clGray; FVisible := False; FDepth := 5; FSpace := 5; FTransparency := 0; FPosition := spBottomRight; end; { -------------------------------------------------------------------- Méthode : SetColor. But : -------------------------------------------------------------------- } procedure TShadow.SetColor(Value: TColor); begin FColor := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetDepth. But : -------------------------------------------------------------------- } procedure TShadow.SetDepth(Value: Integer); begin FDepth := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetPosition. But : -------------------------------------------------------------------- } procedure TShadow.SetPosition(Value: TShadowPosition); begin FPosition := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetSpace. But : -------------------------------------------------------------------- } procedure TShadow.SetSpace(Value: Integer); begin FSpace := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetTransparency. But : -------------------------------------------------------------------- } procedure TShadow.SetTransparency(Value: Integer); begin if Value < 0 then FTransparency := 0 else if Value > 100 then FTransparency := 100 else FTransparency := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetVisible. But : -------------------------------------------------------------------- } procedure TShadow.SetVisible(Value: Boolean); begin FVisible := Value; ChangeOccured; end; { ******************************************************************** } { ******************************* TTitle ***************************** } { ******************************************************************** } { -------------------------------------------------------------------- Méthode : ChangeOccured. But : Indiquer qu'une modification a été apportée au titre. -------------------------------------------------------------------- } procedure TTitle.ChangeOccured; begin if Assigned(FOnChange) then FOnChange(Self); end; { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TTitle.Create; begin inherited; // Initialisations. FText := ''; FFont := TFont.Create; FFont.Name := 'Arial'; FFont.Color := clWhite; FTop := 10; FLeft := 10; FSectionVisible := True; FSectionPosition := tpTop; FSectionSize := NB_PIXELS; FSectionColor := clTeal; FVAlign := vaCenter; FHAlign := haCenter; FTransparent := TTransparent.Create; FTransparent.OnChange := TitleChange; end; { -------------------------------------------------------------------- Méthode : Destroy. But : -------------------------------------------------------------------- } destructor TTitle.Destroy; begin inherited; FFont.Free; end; { -------------------------------------------------------------------- Méthode : SetFont. But : -------------------------------------------------------------------- } procedure TTitle.SetFont(const Value: TFont); begin FFont := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetHAlign. But : -------------------------------------------------------------------- } procedure TTitle.SetHAlign(const Value: THorizontalAlign); begin FHAlign := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetVAlign. But : -------------------------------------------------------------------- } procedure TTitle.SetVAlign(const Value: TVerticalAlign); begin FVAlign := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetLeft. But : -------------------------------------------------------------------- } procedure TTitle.SetLeft(const Value: Integer); begin FLeft := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetSectionColor. But : -------------------------------------------------------------------- } procedure TTitle.SetSectionColor(const Value: TColor); begin FSectionColor := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetSectionPosition. But : -------------------------------------------------------------------- } procedure TTitle.SetSectionPosition(const Value: TTitlePosition); begin FSectionPosition := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetSectionSize. But : -------------------------------------------------------------------- } procedure TTitle.SetSectionSize(const Value: Integer); begin if Value < NB_PIXELS then FSectionSize := NB_PIXELS else FSectionSize := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetSectionVisible. But : -------------------------------------------------------------------- } procedure TTitle.SetSectionVisible(const Value: Boolean); begin FSectionVisible := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetText. But : -------------------------------------------------------------------- } procedure TTitle.SetText(const Value: String); begin FText := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetTop. But : -------------------------------------------------------------------- } procedure TTitle.SetTop(const Value: Integer); begin FTop := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : TitleChange. But : -------------------------------------------------------------------- } procedure TTitle.TitleChange(Sender: TObject); begin ChangeOccured; end; { TGMPanelPicture } { -------------------------------------------------------------------- Méthode : ChangeOccured. But : Indiquer qu'une modification a été apportée à l'image. -------------------------------------------------------------------- } procedure TGMPanelPicture.ChangeOccured; begin if Assigned(FOnChange) then FOnChange(Self); end; { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TGMPanelPicture.Create; begin FPicture := TBitmap.Create; FStyle := psTile; FTransparent := False; end; { -------------------------------------------------------------------- Méthode : Destroy. But : -------------------------------------------------------------------- } destructor TGMPanelPicture.Destroy; begin FPicture.Free; inherited; end; { -------------------------------------------------------------------- Méthode : SetPicture. But : -------------------------------------------------------------------- } procedure TGMPanelPicture.SetPicture(const Value: TBitMap); begin if (Value = nil) or (Value.Height = 0) then begin FPicture.Height := 0; FPicture.Width := 0; end else begin Value.Transparent := True; FPicture.Assign(Value); end; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetPictureStyle. But : -------------------------------------------------------------------- } procedure TGMPanelPicture.SetPictureStyle(const Value: TPictureStyle); begin if Value <> FStyle then begin FStyle := Value; ChangeOccured; end; end; { -------------------------------------------------------------------- Méthode : SetPictureTransparent. But : -------------------------------------------------------------------- } procedure TGMPanelPicture.SetPictureTransparent(const Value: Boolean); begin if FTransparent <> Value then begin FTransparent := Value; ChangeOccured; end; end; { TGradient } { -------------------------------------------------------------------- Méthode : ChangeOccured. But : -------------------------------------------------------------------- } procedure TGradient.ChangeOccured; begin if Assigned(FOnChange) then FOnChange(Self); end; { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TGradient.Create; begin FActive := False; FColor_1 := clBtnFace; FColor_2 := clWhite; FColor_3 := clAqua; FType := gtHorizontal; FPercent := 100; end; { -------------------------------------------------------------------- Méthode : SetGradientActive. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientActive(const Value: Boolean); begin FActive := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetGradientColor_1. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientColor_1(const Value: TColor); begin FColor_1 := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetGradientColor_2. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientColor_2(const Value: TColor); begin FColor_2 := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetGradientColor_3. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientColor_3(const Value: TColor); begin FColor_3 := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetGradientPercent. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientPercent(Value: integer); begin if Value < 1 then Value := 1; if Value > 100 then Value := 100; FPercent := Value; ChangeOccured; end; { -------------------------------------------------------------------- Méthode : SetGradientType. But : -------------------------------------------------------------------- } procedure TGradient.SetGradientType(const Value: TGradientType); begin FType := Value; ChangeOccured; end; { ******************************************************************** } { **************************** TTransparent ************************** } { ******************************************************************** } { -------------------------------------------------------------------- Méthode : ChangeOccured. But : -------------------------------------------------------------------- } procedure TTransparent.ChangeOccured; begin if Assigned(FOnChange) then FOnChange(Self); end; { -------------------------------------------------------------------- Méthode : Create. But : -------------------------------------------------------------------- } constructor TTransparent.Create; begin FActive := False; FPercent := 50; FType := gttNone; end; { -------------------------------------------------------------------- Méthode : SetTransparentActive. But : -------------------------------------------------------------------- } procedure TTransparent.SetTransparentActive(const Value: Boolean); begin if FActive <> Value then begin FActive := Value; ChangeOccured; end; end; { -------------------------------------------------------------------- Méthode : SetTransparentPercent. But : -------------------------------------------------------------------- } procedure TTransparent.SetTransparentPercent(Value: Integer); begin if FPercent <> Value then begin FPercent := Value; ChangeOccured; end; end; { -------------------------------------------------------------------- Méthode : SetTransparentType. But : -------------------------------------------------------------------- } procedure TTransparent.SetTransparentType(const Value: TTransparentType); begin if FType <> Value then begin FType := Value; ChangeOccured; end; end; end.
unit D_AttrAlarm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BottomBtnDlg, StdCtrls, Buttons, ExtCtrls, k2Interfaces, k2Tags, DT_Alarm, Mask, vtCombo, vtDateEdit, l3Variant ; type TAttrAlarmDlg = class(TBottomBtnDlg) edtDate: TvtDateEdit; Label1: TLabel; Label2: TLabel; edtComment: TvtSimpleComboEdit; procedure edtCommentDropDown(Sender: TObject); protected function ValidateInputData : Boolean; override; public { Public declarations } end; function GetAttrAlarm(aRec : Tl3Tag; aRecEmpty : Boolean = False) : boolean; implementation {$R *.dfm} uses l3String, l3Date, InsDWin; const sidTooEarlyDate = 'Дата не может быть меньше текущей.'; sidEmptyDate = 'Дата не может быть пустой.'; function TAttrAlarmDlg.ValidateInputData : Boolean; begin if edtDate.IsEmpty then begin FocusAndNote(edtDate,sidEmptyDate); Result := False; end else if edtDate.StDate < CurrentDate then begin FocusAndNote(edtDate,sidTooEarlyDate); Result := False; end else Result := True; end; function GetAttrAlarm(aRec: Tl3Tag; aRecEmpty : Boolean = False) : boolean; begin with TAttrAlarmDlg.Create(nil) do try with aRec do If not aRecEmpty then begin edtDate.StDate := IntA[k2_tiStart]; edtComment.Text := StrA[k2_tiComment]; end; Result := Execute; with aRec do begin AttrW[k2_tiName, nil] := nil; IntA[k2_tiStart] := edtDate.StDate; StrA[k2_tiComment] := edtComment.Text; end; finally Free; end; end; procedure TAttrAlarmDlg.edtCommentDropDown(Sender: TObject); var lInsText : String; begin if GetInsText(lInsText) then edtComment.Text := lInsText; end; end.
unit browse; interface function BrowseURL(const URL: string) : boolean; function BrowseURL_IE( const URL: string ): boolean; implementation uses windows, Registry, ShellAPI; function BrowseURL_IE(const URL: string) : boolean; var Browser: string; begin Result := True; Browser := ''; with TRegistry.Create do try RootKey := HKEY_CLASSES_ROOT; Access := KEY_QUERY_VALUE; if OpenKey('\htmlfile\shell\open\command', False) then Browser := ReadString('') ; CloseKey; finally Free; end; if Browser = '' then begin Result := False; Exit; end; Browser := Copy(Browser, Pos('"', Browser) + 1, Length(Browser)) ; Browser := Copy(Browser, 1, Pos('"', Browser) - 1) ; ShellExecute(0, 'open', PChar(Browser), PChar(URL), nil, SW_SHOW) ; end; function BrowseURL( const URL: string ): boolean; var Browser: string; begin Result := True; ShellExecute(0, 'OPEN', PChar(URL), '', '', SW_SHOWNORMAL); end; //Usage // BrowseURL('http:delphi.about.com') ; end.
unit ssRegUtils; interface uses Registry, Windows; var ssRegUtils_Error: String; function WriteToRegInt(const ARegKey, AValueName: string; AValue: Integer; const root: HKEY = HKEY_CURRENT_USER): boolean; function ReadFromRegInt(const ARegKey, AValueName: string; var AValue: Integer; const root: HKEY = HKEY_CURRENT_USER): boolean; function WriteToRegStr(const ARegKey, AValueName, AValue: string; const root: HKEY = HKEY_CURRENT_USER): boolean; function ReadFromRegStr(const ARegKey, AValueName: string; var AValue: String; const root: HKEY = HKEY_CURRENT_USER): boolean; function WriteToRegDate(const ARegKey, AValueName: string; AValue: TDateTime; const root: HKEY = HKEY_CURRENT_USER): boolean; function ReadFromRegDate(const ARegKey, AValueName: string; var AValue: TDateTime; const root: HKEY = HKEY_CURRENT_USER): boolean; function WriteToRegBool(const ARegKey, AValueName: string; AValue: Boolean; const root: HKEY = HKEY_CURRENT_USER): boolean; function ReadFromRegBool(const ARegKey, AValueName: string; var AValue: Boolean; const root: HKEY = HKEY_CURRENT_USER): boolean; function DropRegKey(const ARegKey: string; const root: HKEY = HKEY_CURRENT_USER): Boolean; function DropRegValue(const ARegKey, AValueName: string; const root: HKEY = HKEY_CURRENT_USER): Boolean; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses StrUtils, SysUtils, Math; var r: TRegistry; //============================================================================================== function DropRegValue(const ARegKey, AValueName: string; const root: HKEY = HKEY_CURRENT_USER): Boolean; begin Result := True; ssRegUtils_Error := ''; with r do try // except Access := KEY_ALL_ACCESS; RootKey := root; if not KeyExists(ARegKey) then Exit; if OpenKey(ARegKey, False) then try if ValueExists(AValueName) then Result := DeleteValue(AValueName) finally CloseKey; end; except on e: Exception do begin ssRegUtils_Error := 'DropRegValue(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '): ' + e.Message; Result := False; end; end; end; //============================================================================================== function DropRegKey(const ARegKey: string; const root: HKEY = HKEY_CURRENT_USER): Boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // except Access := KEY_ALL_ACCESS; RootKey := root; if KeyExists(ARegKey) then Result := DeleteKey(ARegKey) else Result := True; except on e: Exception do ssRegUtils_Error := 'DropRegKey(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '): ' + e.Message; end; end; //============================================================================================== function valueIsValid(key,val: string; t: TRegDataType): Boolean; // internal begin Result := False; if not r.ValueExists(val) then begin ssRegUtils_Error := 'Value not found: ' + Val + ' in ' + Key; Exit; end; if t <> r.GetDataType(Val) then begin ssRegUtils_Error := 'Value of wrong type: ' + Val + ' in ' + Key; Exit; end; Result := True; end; //============================================================================================== function ReadFromRegDate(const ARegKey, AValueName: string; var AValue: TDateTime; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_READ; RootKey := root; if OpenKey(ARegKey, False) then begin if not valueIsValid(ARegKey, AValueName, rdBinary) then Exit; AValue := ReadDateTime(AValueName); Result := True; end; except on e: Exception do begin Result := False; ssRegUtils_Error := 'ReadFromRegDate(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function WriteToRegDate(const ARegKey, AValueName: string; AValue: TDateTime; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_ALL_ACCESS; RootKey := root; if not OpenKey(ARegKey, True) then Exit; WriteDateTime(AValueName, AValue); Result := True; except on e: Exception do begin Result := False; ssRegUtils_Error := 'WriteToRegDate(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function WriteToRegInt(const ARegKey, AValueName: string; AValue: Integer; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_ALL_ACCESS; RootKey := root; if not OpenKey(ARegKey, True) then Exit; WriteInteger(AValueName, AValue); Result := True; except on e: Exception do begin Result := False; ssRegUtils_Error := 'WriteToRegInt(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function ReadFromRegInt(const ARegKey, AValueName: string; var AValue: Integer; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_READ; RootKey := root; if OpenKey(ARegKey, False) then begin if not valueIsValid(ARegKey, AValueName, rdInteger) then Exit; AValue := ReadInteger(AValueName); Result := True; end; except on e: Exception do begin Result := False; ssRegUtils_Error := 'ReadFromRegInt(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function ReadFromRegStr(const ARegKey, AValueName: string; var AValue: string; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_READ; RootKey := root; if OpenKey(ARegKey, False) then begin if not valueIsValid(ARegKey, AValueName, rdString) then Exit; AValue := ReadString(AValueName); Result := True; end; except on e: Exception do begin Result := False; ssRegUtils_Error := 'ReadFromRegStr(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function WriteToRegStr(const ARegKey, AValueName, AValue: string; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := False; ssRegUtils_Error := ''; with r do try // finally try // except Access := KEY_ALL_ACCESS; RootKey := root; if not OpenKey(ARegKey, True) then Exit; WriteString(AValueName, AValue); Result := True; except on e: Exception do begin Result := False; ssRegUtils_Error := 'WriteToRegStr(' + ifThen(root = HKEY_CURRENT_USER, 'HKCU\', 'HKLM\') + ARegKey + '\' + AValueName + '): ' + e.Message; end; end; finally CloseKey; end; end; //============================================================================================== function WriteToRegBool(const ARegKey, AValueName: string; AValue: Boolean; const root: HKEY = HKEY_CURRENT_USER): boolean; begin Result := WriteToRegInt(ARegKey, AValueName, ifThen(AValue, 1, 0), root); end; //============================================================================================== function ReadFromRegBool(const ARegKey, AValueName: string; var AValue: Boolean; const root: HKEY = HKEY_CURRENT_USER): boolean; var v: Integer; begin AValue := False; Result := ReadFromRegInt(ARegKey, AValueName, v, root); if Result then AValue := (v <> 0); end; //============================================================================================== initialization r := TRegistry.Create; r.LazyWrite := False; //============================================================================================== finalization r.Free; end.
unit fGoToLevel; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, cMegaROM, cConfiguration; type TfrmGoToLevel = class(TForm) lstLevels: TListBox; cmdOK: TButton; cmdCancel: TButton; procedure FormShow(Sender: TObject); procedure cmdOKClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; { Private declarations } public Level : Integer; property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmGoToLevel: TfrmGoToLevel; implementation uses uglobal; {$R *.dfm} procedure TfrmGoToLevel.FormShow(Sender: TObject); var i : Integer; begin lstLevels.Items.BeginUpdate; lstLevels.Clear; for i := 0 to _ROMData.Levels.Count -1 do lstLevels.Items.Add(_ROMData.Levels[i].Name); lstLevels.Items.EndUpdate; lstLevels.ItemIndex := _ROMData.CurrentLevel; end; procedure TfrmGoToLevel.cmdOKClick(Sender: TObject); begin Level := lstLevels.ItemIndex; end; end.
unit uDocument; interface uses Classes, SysUtils; type TDocRec = Record ATime: TDateTime; Title: ShortString; End; {TDocument} TDocument = Class private F: File of TDocRec; FFileName: String; public constructor Create(FileName: String); destructor Destroy; override; procedure Add(ATitle: String); procedure ReadAll(var DocList: TStringList); function Find(Keyword: String; var ResulList: TStringList): Boolean; End; implementation { TDocument } procedure TDocument.Add(ATitle: String); var Doc: TDocRec; begin AssignFile(F, FFileName); if FileExists(FFileName) then begin FileMode := 2; Reset(F); Seek(F, FileSize(F)); end else ReWrite(F); Doc.ATime := Now; Doc.Title := ATitle; Write(F, Doc); CloseFile(F); end; constructor TDocument.Create(FileName: String); begin FFileName := FileName; end; destructor TDocument.Destroy; begin inherited Destroy; end; function TDocument.Find(Keyword: String; var ResulList: TStringList): Boolean; var Doc: TDocRec; begin ResulList.Clear; Result := False; AssignFile(F, FFileName); if FileExists(FFileName) then begin Reset(F); while not Eof(F) do begin Read(F, Doc); if Pos(LowerCase(Keyword), LowerCase(Doc.Title)) > 0 then begin ResulList.Add(DateTimeToStr(Doc.ATime) + ' : ' + Doc.Title); Result := True; end; end; end; CloseFile(F); end; procedure TDocument.ReadAll(var DocList: TStringList); var Doc: TDocRec; begin DocList.Clear; AssignFile(F, FFileName); if FileExists(FFileName) then begin Reset(F); while not Eof(F) do begin Read(F, Doc); DocList.Add(DateTimeToStr(Doc.ATime) + ' : ' + Doc.Title); end; CloseFile(F); end; end; end.
{ Reads AvisoCNC G-Code License: The same modified LGPL as the Free Pascal RTL See the file COPYING.modifiedLGPL for more details AUTHORS: Felipe Monteiro de Carvalho Pedro Sol Pegorini L de Lima } unit avisocncgcodereader; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpvectorial; type { Used by tcutils.SeparateString } T10Strings = array[0..9] of shortstring; { TvAvisoCNCGCodeReader } TvAvisoCNCGCodeReader = class(TvCustomVectorialReader) private LastX, LastY, LastZ: Double; function SeparateString(AString: string; ASeparator: Char): T10Strings; procedure ReadString(AStr: string; AData: TvVectorialDocument); function GetCoordinate(AStr: shortstring): Integer; function GetCoordinateValue(AStr: shortstring): Double; public { General reading methods } procedure ReadFromStrings(AStrings: TStrings; AData: TvVectorialDocument); override; end; implementation const { Coordinate constants } INT_COORDINATE_NONE = 0; INT_COORDINATE_X = 1; INT_COORDINATE_Y = 2; INT_COORDINATE_Z = 3; { GCode constants } STR_GCODE_LINEAR_MOVE = 'G01'; STR_GCODE_STEPPER_MOVE = 'S01'; STR_GCODE_2DBEZIER_MOVE = 'B02'; STR_GCODE_3DBEZIER_MOVE = 'B03'; STR_GCODE_DRILL_UP = 'P01'; STR_GCODE_DRILL_DOWN = 'P02'; { TvAvisoCNCGCodeReader } {@@ Reads a string and separates it in substring using ASeparator to delimite them. Limits: Number of substrings: 10 (indexed 0 to 9) Length of each substring: 255 (they are shortstrings) } function TvAvisoCNCGCodeReader.SeparateString(AString: string; ASeparator: Char): T10Strings; var i, CurrentPart: Integer; begin CurrentPart := 0; { Clears the result } for i := 0 to 9 do Result[i] := ''; { Iterates througth the string, filling strings } for i := 1 to Length(AString) do begin if Copy(AString, i, 1) = ASeparator then begin Inc(CurrentPart); { Verifies if the string capacity wasn't exceeded } if CurrentPart > 9 then Exit; end else Result[CurrentPart] := Result[CurrentPart] + Copy(AString, i, 1); end; end; procedure TvAvisoCNCGCodeReader.ReadString(AStr: string; AData: TvVectorialDocument); var AParams: T10Strings; DestX, DestY, DestZ: Double; i: Integer; begin {$ifdef FPVECTORIALDEBUG} WriteLn('TvAvisoCNCGCodeReader.ReadString ', AStr); {$endif} AParams := SeparateString(AStr, ' '); { Format may be: G01 X3 G01 X3 Y4 G01 X3 Y4 Z2 } if AParams[0] = STR_GCODE_DRILL_UP then begin AData.AddLineToPath(LastX, LastY, 0); LastZ := 0; end else if AParams[0] = STR_GCODE_DRILL_DOWN then begin AData.AddLineToPath(LastX, LastY, 50); LastZ := 50; end else if AParams[0] = STR_GCODE_LINEAR_MOVE then begin DestX := LastX; DestY := LastY; DestZ := LastZ; for i := 1 to 3 do begin case GetCoordinate(AParams[i]) of INT_COORDINATE_X: DestX := GetCoordinateValue(AParams[i]); INT_COORDINATE_Y: DestY := GetCoordinateValue(AParams[i]); INT_COORDINATE_Z: DestZ := GetCoordinateValue(AParams[i]); else // error end; end; AData.AddLineToPath(DestX, DestY, DestZ); LastX := DestX; LastY := DestY; LastZ := DestZ; end else if AParams[0] = STR_GCODE_2DBEZIER_MOVE then begin AData.AddBezierToPath( GetCoordinateValue(AParams[1]), GetCoordinateValue(AParams[2]), GetCoordinateValue(AParams[3]), GetCoordinateValue(AParams[4]), GetCoordinateValue(AParams[5]), GetCoordinateValue(AParams[6]) ); LastX := GetCoordinateValue(AParams[5]); LastY := GetCoordinateValue(AParams[6]); end else if AParams[0] = STR_GCODE_3DBEZIER_MOVE then begin AData.AddBezierToPath( GetCoordinateValue(AParams[1]), GetCoordinateValue(AParams[2]), GetCoordinateValue(AParams[3]), GetCoordinateValue(AParams[4]), GetCoordinateValue(AParams[5]), GetCoordinateValue(AParams[6]), GetCoordinateValue(AParams[7]), GetCoordinateValue(AParams[8]), GetCoordinateValue(AParams[9]) ); LastX := GetCoordinateValue(AParams[7]); LastY := GetCoordinateValue(AParams[8]); LastZ := GetCoordinateValue(AParams[9]); end; {else begin Ignore any of these codes: STR_GCODE_STEPPER_MOVE and anything else end;} end; function TvAvisoCNCGCodeReader.GetCoordinate(AStr: shortstring): Integer; begin Result := INT_COORDINATE_NONE; if AStr = '' then Exit else if AStr[1] = 'X' then Result := INT_COORDINATE_X else if AStr[1] = 'Y' then Result := INT_COORDINATE_Y else if AStr[1] = 'Z' then Result := INT_COORDINATE_Z; end; function TvAvisoCNCGCodeReader.GetCoordinateValue(AStr: shortstring): Double; begin Result := 0.0; if Length(AStr) <= 1 then Exit; Result := StrToFloat(Copy(AStr, 2, Length(AStr) - 1)); end; {@@ The information of each separate path is lost in G-Code files Only one path uniting all of them is created when reading G-Code } procedure TvAvisoCNCGCodeReader.ReadFromStrings(AStrings: TStrings; AData: TvVectorialDocument); var i: Integer; begin {$ifdef FPVECTORIALDEBUG} WriteLn('TvAvisoCNCGCodeReader.ReadFromStrings AStrings = ', PtrInt(AStrings), ' AData = ', PtrInt(AData)); {$endif} AData.StartPath(0, 0); for i := 0 to AStrings.Count - 1 do ReadString(AStrings.Strings[i], AData); {$ifdef FPVECTORIALDEBUG} WriteLn('AData.EndPath'); {$endif} AData.EndPath(); end; initialization RegisterVectorialReader(TvAvisoCNCGCodeReader, vfGCodeAvisoCNCPrototipoV5); end.
unit tmsUFlxRowComments; {$INCLUDE ..\FLXCOMPILER.INC} interface uses SysUtils, Classes, {$IFDEF FLX_GENERICS} Generics.Collections, {$ENDIF} Contnrs; type {$IFDEF FLX_GENERICS} TCommentRowPos = class (TList<integer>) public Row: integer; end; {$ELSE} TCommentRowPos= class(TList) private function GetItems(index: integer): integer; procedure SetItems(index: integer; const Value: integer); public Row: integer; procedure Add(const i: integer); property Items[index: integer]: integer read GetItems write SetItems; default; end; {$ENDIF} TRowComments= class(TObjectList) //Items are TCommentRowPos private EmptySlot: TCommentRowPos; function GetItems(aRow: integer): TCommentRowPos; function Find(const aRow: integer; out Index: integer): boolean; public constructor Create; destructor Destroy; override; procedure Add(const aRow, aPos: integer); property Items[aRow: integer]: TCommentRowPos read GetItems; default; procedure Delete(const aRow, aCol: integer); end; implementation { TCommentRowPos } { TRowComments } procedure TRowComments.Add(const aRow, aPos: integer); var i: integer; begin if not Find(aRow, i) then begin; Insert( i, TCommentRowPos.Create); (inherited Items[i] as TCommentRowPos).Row:=aRow; end; (inherited Items[i] as TCommentRowPos).Add(aPos); end; constructor TRowComments.Create; begin inherited Create(True); EmptySlot:= TCommentRowPos.Create; end; destructor TRowComments.Destroy; begin FreeAndNil(EmptySlot); inherited; end; function TRowComments.GetItems(aRow: integer): TCommentRowPos; var i:integer; begin if Find(aRow, i) then Result:= inherited Items[i] as TCommentRowPos else Result:=EmptySlot; end; function TRowComments.Find(const aRow: integer ; out Index: integer): boolean; Var L, H, I, C: Integer; begin Result := False; L := 0; H := Count - 1; while L <= H do begin I := (L + H) shr 1; if (inherited Items[i] as TCommentRowPos).Row < aRow then C:=-1 else if (inherited Items[i] as TCommentRowPos).Row>aRow then C:=1 else C:=0; if C < 0 then L := I + 1 else begin H := I - 1; If C = 0 Then begin Result := True; L := I; end; end; end; Index := L; end; procedure TRowComments.Delete(const aRow, aCol: integer); var i,k:integer; Limit: integer; CRp: TCommentRowPos; begin if Find(aRow, i) then begin CRp:=(inherited Items[i] as TCommentRowPos); Limit:=CRp[aCol]; CRp.Delete(aCol); for i:=0 to Count-1 do begin CRp:=(inherited Items[i] as TCommentRowPos); for k:=0 to CRp.Count-1 do if CRp[k]>Limit then CRp[k]:=CRp[k]-1; end; end; end; {$IFDEF FLX_GENERICS} {$ELSE} { TCommentRowPos } procedure TCommentRowPos.Add(const i: integer); begin inherited Add(Pointer(i)); end; function TCommentRowPos.GetItems(index: integer): integer; begin Result:=Integer(inherited Items[Index]); end; procedure TCommentRowPos.SetItems(index: integer; const Value: integer); begin inherited Items[Index]:=Pointer(Value); end; {$ENDIF} end.
unit Lander; interface uses Windows, Classes, Graphics, GameTypes, LanderTypes; type TLander = class(TInterfacedObject, IGameDocument, ICoordinateConverter) public constructor Create(const Map : IWorldMap); destructor Destroy; override; private // IGameDocument procedure RenderSnapshot(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); function ClipMovement(const view : IGameView; var dx, dy : integer) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; procedure ViewChanged(const view : IGameView); private // ICoordinateConverter function ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; private fMap : IWorldMap; procedure CalculateFirstGrid(const view : IGameView; var x, y : integer; out i, j : integer); private fSpareCache : TGameImage; fShadeCache : TGameImage; fRedShadeCache : TGameImage; fBlackShadeCache : TGameImage; function CheckPoint(const view : IGameView; x, y, i, j : integer) : boolean; procedure DrawGrid(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); end; implementation uses SysUtils, AxlDebug, MathUtils, GDI, ColorTableMgr, NumUtils; const cMaxBuildingHeight = 16; cMaxLandHeight = 3; const cAlpha = 1; // Utils >> function ClipInteger(var i : integer; min, max : integer) : boolean; begin Result := true; if i < min then i := min else if i > max then i := max else Result := false; end; function max(x, y : integer) : integer; begin if x >= y then Result := x else Result := y; end; function min(x, y : integer) : integer; begin if x <= y then Result := x else Result := y; end; // TLander constructor TLander.Create(const Map : IWorldMap); begin inherited Create; fMap := Map; end; destructor TLander.Destroy; begin assert(RefCount = 0); inherited; end; const lightx = -1; lighty = -1; lightz = 1; procedure TLander.RenderSnapshot(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); var u : integer; focus : IGameFocus; Imager : IImager; procedure DrawLand; var obj : TObjInfo; img : TGameImage; i, j : integer; ox, oy : integer; pixel : integer; pixheight : integer; pixrepcnt : integer; x, y : integer; scy : integer; lumN, lumD : integer; rgb : word; rgbQuad : TRGBQuad; function CalcPixelHeight(i, j, ox, oy : integer; out lumN, lumD : integer) : integer; var neighbobj : TObjInfo; x1, x2, x3 : integer; y1, y2, y3 : integer; z1, z2, z3 : integer; nx, ny, nz : integer; // normal vector v1x, v1y, v1z : integer; // triangle-side vectors v2x, v2y, v2z : integer; d : integer; // intersect nmod : single; begin x1 := 2*u; y1 := 0; if fMap.GetGroundInfo(i + 1, j, focus, neighbobj) then z1 := neighbobj.Height else z1 := 0; x2 := 2*u; y2 := 2*u; if fMap.GetGroundInfo(i, j - 1, focus, neighbobj) then z2 := neighbobj.Height else z2 := 0; if ox < 2*u then begin x3 := 0; y3 := u; if fMap.GetGroundInfo(i + 1, j - 1, focus, neighbobj) then z3 := neighbobj.Height else z3 := 0; end else begin x3 := 4*u; y3 := u; z3 := obj.Height; end; v1x := x1 - x3; v1y := y1 - y3; v1z := z1 - z3; v2x := x2 - x3; v2y := y2 - y3; v2z := z2 - z3; nx := v1y*v2z - v1z*v2y; ny := v1z*v2x - v1x*v2z; nz := v1x*v2y - v1y*v2x; d := -nx*x1 - ny*y1 - nz*z1; Result := (-d - nx*ox - ny*oy) div nz; lumN := abs(lightx*nx + lighty*ny + lightz*nz); lumD := abs(nx) + abs(ny) + abs(nz); end; function PackRGBQuad(const RGBQuad : TRGBQuad) : word; const rMask = $7C00; gMask = $03E0; bMask = $001F; var rRight : byte; gRight : byte; bRight : byte; rLeft : byte; gLeft : byte; bLeft : byte; begin rRight := RightShiftCount( rMask ); gRight := RightShiftCount( gMask ); bRight := RightShiftCount( bMask ); rLeft := LeftShiftCount( rMask ); gLeft := LeftShiftCount( gMask ); bLeft := LeftShiftCount( bMask ); with RGBQuad do Result := ( (rgbRed shr rLeft) shl rRight ) or ( (rgbGreen shr gLeft) shl gRight ) or ( (rgbBlue shr bLeft) shl bRight ); end; begin x := ClipRect.Left; y := ClipRect.Bottom + cMaxLandHeight*u; scy := y; while x <= ClipRect.Right do begin while scy >= ClipRect.Top do begin ScreenToMap(view, x, y, i, j); MapToScreen(view, i, j, ox, oy); ox := x - ox; oy := y - (oy - u); if (oy >= 0) and (ox >= 0) and fMap.GetGroundInfo(i, j, focus, Obj) then begin img := Imager.GetLandImage(obj.id); if img <> nil then begin // img.PaletteInfo.RequiredState([tsHiColorTableValid]); repeat pixel := img.Pixel[ox, oy, obj.frame]; pixheight := CalcPixelHeight(i, j, ox, oy , lumN, lumD); rgbQuad := img.PaletteInfo.RGBPalette[pixel]; rgbQuad.rgbRed := (lumN*rgbQuad.rgbRed) div lumD; rgbQuad.rgbGreen := (lumN*rgbQuad.rgbGreen) div lumD; rgbQuad.rgbBlue := (lumN*rgbQuad.rgbBlue) div lumD; rgb := PackRGBQuad(rgbQuad); pixrepcnt := pixheight - (y - scy); if pixrepcnt > 0 then if (pixel <> img.TransparentIndx) and (x < snap.Width) and (scy < snap.Height) then begin repeat if scy >= 0 then pword(snap.PixelAddr[x, scy])^ := rgb{img.PaletteInfo.HiColorTable[pixel]}; dec(scy); dec(pixrepcnt); until pixrepcnt = 0; dec(oy); dec(y); end else begin dec(scy); dec(oy); dec(y); dec(pixrepcnt); end else begin dec(oy); dec(y); end; until (Pixel = img.TransparentIndx) or (oy < 0) or (scy <= ClipRect.Top); end; end else begin dec(y); dec(scy); end; end; y := ClipRect.Bottom + cMaxLandHeight*u; scy := y; inc(x); end; end; begin focus := view.GetFocus; Imager := fMap.GetImager(focus); u := 2 shl view.ZoomLevel; snap.Canvas.Brush.Color := clBlack; snap.Canvas.Brush.Style := bsSolid; snap.Canvas.FillRect(ClipRect); DrawLand; if false // >>>> this comment the next statement out then DrawGrid(view, ClipRect, snap); // >>>> Draw mouse hint end; function TLander.ClipMovement(const view : IGameView; var dx, dy : integer) : boolean; const cMargin = 14; var i, j : integer; x, y : integer; rows : integer; cols : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; x := -dx; y := -dy; ScreenToMap(view, x, y, i, j); {$B+} Result := ClipInteger(i, cMargin, rows + cMargin) or ClipInteger(j, 0, cols); {$B-} if Result then begin MapToScreen(view, i, j, x, y); dx := -x; dy := -y; end; end; function TLander.CreateFocus(const view : IGameView) : IGameFocus; begin Result := fMap.CreateFocus(view); end; procedure TLander.ViewChanged(const view : IGameView); begin fSpareCache := nil; fShadeCache := nil; fRedShadeCache := nil; fBlackShadeCache := nil; end; function TLander.ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; var xx, yy : integer; u : integer; rows : integer; cols : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; u := 2 shl view.ZoomLevel; ScreenToMap(view, x, y + cMaxBuildingHeight*u, i, j); MapToScreen(view, i, j, xx, yy); if i < 0 then begin inc(j, -i); dec(yy, -2*u*i); i := 0; end; if j < 0 then begin inc(i, -j); dec(yy, -2*u*j); j := 0; end; while (i < rows) and (j < cols) and not CheckPoint(view, x, y, i, j) do begin if (xx + 2*u < x) or (j = 0) then begin inc(xx, 2*u); inc(j); end else begin dec(xx, 2*u); inc(i); end; dec(yy, u); end; if Debugging then LogThis(Format('i= %d, j= %d', [i, j])); Result := (i < rows) and (j < cols); end; function TLander.ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; var org : TPoint; aux : integer; u, h : integer; tu : integer; rows : integer; cols : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; org := view.Origin; inc(x, org.x); inc(y, org.y); u := 2 shl view.ZoomLevel; tu := u + u; inc(tu, tu); aux := 2*(u*cols - y); h := aux + tu*succ(rows) - x; if h >= 0 then i := h div tu else i := (h - tu) div tu; h := aux + x; if h >= 0 then j := h div tu else j := (h - tu) div tu; Result := (i >= 0) and (i < rows) and (j >= 0) and (j < cols); end; function TLander.MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; var org : TPoint; u : integer; rows : integer; cols : integer; begin rows := fMap.GetRows; cols := fMap.GetColumns; org := view.Origin; u := 2 shl view.ZoomLevel; x := 2*u*(rows - i + j); y := u*((rows - i) + (cols - j)); dec(x, org.x); dec(y, org.y); Result := (i >= 0) and (i < rows) and (j >= 0) and (j < cols); end; procedure TLander.CalculateFirstGrid(const view : IGameView; var x, y : integer; out i, j : integer); var xb, yb : integer; u : integer; rows : integer; begin rows := fMap.GetRows; u := 2 shl view.ZoomLevel; xb := x; yb := y; ScreenToMap(view, x, y, i, j); MapToScreen(view, i, j, x, y); while (y > yb) or (x > xb) do begin dec(x, 2*u); dec(y, u); inc(i); end; if i >= rows then begin inc(j, succ(i - rows)); inc(x, 4*u*succ(i - rows)); i := pred(rows); end else if j < 0 then begin inc(i, j); inc(x, -4*u*j); j := 0; end; end; function TLander.CheckPoint(const view : IGameView; x, y, i, j : integer) : boolean; begin Result := false; end; procedure TLander.DrawGrid(const view : IGameView; const ClipRect : TRect; snap : TCanvasImage); var x, y : integer; i, j : integer; y1 : integer; u : integer; cols : integer; procedure DrawRank(x, i, j : integer); begin while (x < ClipRect.Right) and (j < cols) and (i >= 0) do begin with snap.Canvas do begin MoveTo(x, y); LineTo(x + 2*u, y + u); LineTo(x + 4*u, y); LineTo(x + 2*u, y - u); LineTo(x, y); end; inc(j); dec(i); inc(x, 4*u); end; // while end; begin cols := fMap.GetColumns; u := 2 shl view.ZoomLevel; x := ClipRect.Left; y := ClipRect.Top; CalculateFirstGrid(view, x, y, i, j); y1 := ClipRect.Bottom + u; snap.Canvas.Pen.Color := clNavy; while (y < y1) and (i >= 0) do begin DrawRank(x, i, j); if (x + 2*u <= ClipRect.Left) or (j = 0) then begin dec(i); inc(x, 2*u); end else begin dec(j); dec(x, 2*u); end; inc(y, u); end; end; end.
unit GX_AutoTodoDone; interface uses SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls; type TfmAutoTodoDone = class(TForm) lblMesssage: TLabel; btnOK: TButton; chkDontShowAgain: TCheckBox; public class function Execute(ATodoCount: Integer): Boolean; end; implementation {$R *.dfm} { TfmAutoTodoDone } class function TfmAutoTodoDone.Execute(ATodoCount: Integer): Boolean; resourcestring DoneMessage = '%d comments have been inserted in empty code blocks.'; var Dialog: TfmAutoTodoDone; begin Dialog := TfmAutoTodoDone.Create(nil); try Dialog.lblMesssage.Caption := Format(DoneMessage, [ATodoCount]); Dialog.ShowModal; Result := Dialog.chkDontShowAgain.Checked; finally FreeAndNil(Dialog); end; end; end.
unit SimpleResult; interface uses DataFileSaver, Data.DB, DBManager; type TSimpleResult = class(TInterfacedObject, IDataSetIterator) private FData: TDataSet; FTableName: String; FIterPointer: Integer; public constructor Create(tableName: String; dbm: TAbsDBManager); function MoveNext(): Boolean; function CurData(): TDataSet; function CurName(): String; function Count(): Integer; procedure MoveFirst; end; implementation { TSimpleResult } function TSimpleResult.Count: Integer; begin result := 1; end; constructor TSimpleResult.Create(tableName: String; dbm: TAbsDBManager); begin FTableName := tableName; FData := dbm.ExecuteQuery( 'select * from ' + tableName + ';' ); MoveFirst; end; function TSimpleResult.CurData: TDataSet; begin result := FData; end; function TSimpleResult.CurName: String; begin result := FTableName; end; procedure TSimpleResult.MoveFirst; begin FIterPointer := -1; end; function TSimpleResult.MoveNext: Boolean; var bRet: Boolean; begin bRet := ( FIterPointer < 0 ); Inc( FIterPointer ); result := bRet; end; end.
unit PlainText; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Editors, EditableObjects; type TPlainTextEditor = class(TInPlaceVisualControl) edValue: TEdit; procedure FormResize(Sender: TObject); procedure edValueChange(Sender: TObject); public procedure UpdateObject; override; public procedure setEditableObject( aEditableObject : TEditableObject; options : integer ); override; end; var PlainTextEditor: TPlainTextEditor; implementation {$R *.DFM} procedure TPlainTextEditor.FormResize(Sender: TObject); begin edValue.SetBounds( 0, 0, ClientWidth, ClientHeight ); end; procedure TPlainTextEditor.UpdateObject; begin fEditableObject.Value := edValue.Text; end; procedure TPlainTextEditor.setEditableObject( aEditableObject : TEditableObject; options : integer ); begin inherited; edValue.Text := fEditableObject.Value; end; procedure TPlainTextEditor.edValueChange(Sender: TObject); begin UpdateObject; end; end.
Program stack; Uses crt; Const max = 4; Type TS = Record Stacks : Array[1..max] Of Integer; top : Integer; End; Var tumpukan : TS; i : Integer; Function iniStack(Var stack : TS) : Boolean; Begin stack.top := 0; iniStack := True; End; Function push(Var stack : TS; data : Integer) : Boolean; Begin If high(stack.stacks) = stack.top Then Begin Writeln(' Tumpukkan Sudah Penuh'); push := False; Exit; End Else Begin Inc(stack.top); stack.stacks[stack.top] := data; push := True; End; For i:= 1 To max Do Begin Write(' Indeks Data Ke-',i,' : ',stack.stacks[i]); Writeln; End; End; Function pop(Var stack : TS) : Integer; Begin If stack.top = 0 Then Begin Writeln(' =>Tumpukkan Kosong!!!'); End Else Begin pop := stack.stacks[stack.top]; stack.stacks[stack.top] := 0; {data yg di pop menjadi 0} Dec(stack.top); End; For i:= 1 To max Do Begin Write(' Indeks Data Ke-',i,' : ',stack.stacks[i]); Writeln; End; End; Label 10,20,30; Var tanya : Char; jawab : Byte; data : integer; Begin Clrscr; Writeln(' ======================================'); Writeln(' || PROGRAM STACK ||'); Writeln(' || ALFA SEAN (20101106067) ||'); iniStack(tumpukan); 10: Repeat Writeln(' ======================================'); Writeln(' 1. Masukkan Data Ke dalam Tumpukkan '); Writeln(' 2. Keluarkan Data Dari Tumpukkan '); Writeln(' 3. Keluar '); Writeln(' ======================================'); Write(' => Masukkan Pilihan Anda : '); Readln(jawab); Case jawab Of 1 : Begin Write(' Masukkan Datanya : '); Readln(data); Writeln(' ======================================'); push(tumpukan,data); End; 2 : Begin Writeln(' ======================================'); pop(tumpukan); End; 3 : 20: Begin Write (' Apakah Anda Yakin Ingin Keluar? (y/n) : '); Readln(tanya); If (tanya = 'y') Or (tanya = 'Y') Then Begin Goto 30; End Else If (tanya = 'n') Or (tanya = 'N') Then Begin Goto 10; End Else Begin Writeln (' => Inputan Salah! '); Goto 20; End; End; Else Writeln(' Inputan Salah!'); End; Readln; Until jawab = 3; 30: End.
UNIT TreeSort; INTERFACE USES ConstAndTypes; PROCEDURE Insert(VAR Ptr: Tree; Data: WordString); {Добавить слово в дерево} PROCEDURE PrintTree(VAR Ptr: Tree; VAR Fout: TEXT); {Распечатать дерево} PROCEDURE CleanTree(VAR Ptr: Tree); {Очистить дерево} IMPLEMENTATION PROCEDURE Insert(VAR Ptr: Tree; Data: WordString); BEGIN {Insert} IF Ptr = NIL THEN BEGIN {Создаем лист со значением Data} NEW(Ptr); Ptr^.SomeWord := Data; Ptr^.CountWord := 1; Ptr^.LLink := NIL; Ptr^.RLink := NIL END ELSE IF Data < Ptr^.SomeWord THEN Insert(Ptr^.LLink, Data) ELSE IF Data > Ptr^.SomeWord THEN Insert(Ptr^.RLink, Data) ELSE {Увеличиваем счетчик слова на 1, если встретили повторно} Ptr^.CountWord := Ptr^.CountWord + 1 END; {Insert} PROCEDURE PrintTree(VAR Ptr: Tree; VAR Fout: TEXT); BEGIN {PrintTree} IF Ptr <> NIL THEN BEGIN {Печатает поддерево слева, вершину, поддерево справа} PrintTree(Ptr^.LLink, Fout); WRITELN(Fout, Ptr^.SomeWord, ' ', Ptr^.CountWord); PrintTree(Ptr^.RLink, Fout) END END; {PrintTree} PROCEDURE CleanTree(VAR Ptr: Tree); BEGIN {CleanTree} IF Ptr <> NIL THEN BEGIN CleanTree(Ptr^.LLink); CleanTree(Ptr^.RLink) END; DISPOSE(Ptr); Ptr := NIL END; {CleanTree} BEGIN {TreeSort} END. {TreeSort}
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clIdnTranslator; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clUtils; type EclIdnError = class(Exception); TclIdnTranslator = class private class function Adapt(ADelta, ANumPoints: Integer; IsFirst: Boolean): Integer; class function IsBasicChar(C: Char): Boolean; class function Digit2CodePoint(ADigit: Integer): Integer; public class function IsBasic(const AInput: string): Boolean; class function GetAsciiText(const AInput: string): string; class function GetAscii(const AInput: string): string; end; resourcestring cIdnBadInput = 'Bad input value for the IDN translator'; cIdnOverflow = 'Input value needs wider integers to translate'; implementation const TMIN: Integer = 1; TMAX: Integer = 26; BASE: Integer = 36; INITIAL_N: Integer = 128; INITIAL_BIAS: Integer = 72; DAMP: Integer = 700; SKEW: Integer = 38; DELIMITER: Char = '-'; ACE_PREFIX: string = 'xn--'; { TclIdnTranslator } class function TclIdnTranslator.Adapt(ADelta, ANumPoints: Integer; IsFirst: Boolean): Integer; var i: Integer; begin if (IsFirst) then begin ADelta := ADelta div DAMP; end else begin ADelta := ADelta div 2; end; ADelta := ADelta + (ADelta div ANumPoints); i := 0; while (ADelta > ((BASE - TMIN) * TMAX) div 2) do begin ADelta := ADelta div (BASE - TMIN); i := i + BASE; end; Result := i + ((BASE - TMIN + 1) * ADelta) div (ADelta + SKEW); end; class function TclIdnTranslator.Digit2CodePoint(ADigit: Integer): Integer; begin if (ADigit < 26) then begin Result := ADigit + Ord('a'); end else if (ADigit < 36) then begin Result := ADigit - 26 + Ord('0'); end else begin raise EclIdnError.Create(cIdnBadInput); end; end; class function TclIdnTranslator.GetAsciiText(const AInput: string): string; var n, b, delta, bias, m, i, h, j, q, k, t: Integer; c: Char; begin n := INITIAL_N; delta := 0; bias := INITIAL_BIAS; Result := ''; b := 0; for i := 1 to Length(AInput) do begin c := AInput[i]; if IsBasicChar(c) then begin Result := Result + c; Inc(b); end; end; if (b < Length(AInput)) then begin Result := ACE_PREFIX + Result; end else begin Exit; end; if (b > 0) then begin Result := Result + DELIMITER; end; h := b; while (h < Length(AInput)) do begin m := MaxInt; for i := 1 to Length(AInput) do begin c := AInput[i]; if (Ord(c) >= n) and (Ord(c) < m) then begin m := Ord(c); end; end; if (m - n) > ((MaxInt - delta) div (h + 1)) then begin raise EclIdnError.Create(cIdnOverflow); end; delta := delta + (m - n) * (h + 1); n := m; for j := 1 to Length(AInput) do begin c := AInput[j]; if (Ord(c) < n) then begin Inc(delta); if (delta = 0) then begin raise EclIdnError.Create(cIdnOverflow); end; end; if (Ord(c) = n) then begin q := delta; k := BASE; while True do begin if (k <= bias) then begin t := TMIN; end else if (k >= bias + TMAX) then begin t := TMAX; end else begin t := k - bias; end; if (q < t) then begin Break; end; Result := Result + Chr(Digit2Codepoint(t + (q - t) mod (BASE - t))); q := (q - t) div (BASE - t); Inc(k, BASE); end; Result := Result + Chr(Digit2Codepoint(q)); bias := Adapt(delta, h + 1, h = b); delta := 0; Inc(h); end; end; Inc(delta); Inc(n); end; end; class function TclIdnTranslator.GetAscii(const AInput: string): string; const cSeparator: array[Boolean] of string = ('', '.'); var list: TStrings; i: Integer; begin list := TStringList.Create(); try SplitText(AInput, list, '.'); Result := ''; for i := 0 to list.Count - 1 do begin Result := Result + cSeparator[i > 0] + GetAsciiText(list[i]); end; finally list.Free(); end; end; class function TclIdnTranslator.IsBasic(const AInput: string): Boolean; var i: Integer; begin Result := True; for i := 1 to Length(AInput) do begin if not IsBasicChar(AInput[i]) then begin Result := False; Exit; end; end; end; class function TclIdnTranslator.IsBasicChar(C: Char): Boolean; begin Result := Ord(C) < $80; end; end.