text
stringlengths
14
6.51M
program Global_Variables; var a, b, c: integer; procedure display; var x, y, z: integer; begin (* local variables *) x := 10; y := 20; z := x + y; (* global variables *) a := 30; b := 40; c := a + b; writeln('Within the procedure display'); writeln('Displaying the global variables a, b, and c'); writeln('value of a = ', a, ' b = ', b, ' and c = ', c); writeln('Displaying the local variables x, y, and z'); writeln('value of x = ', x, ' y = ', y, ' and z = ', z); end; begin a := 100; b := 200; c := 300; writeln('Within the program Global Variables'); writeln('value of a = ', a, ' b = ', b, ' and c = ', c); display(); end.
unit Thread.PopulaApontamentoOperacional; interface uses System.Classes, System.Generics.Collections, System.SysUtils, Vcl.Forms, System.UITypes, Model.RHOperacionalAusencias, DAO.RHOperacionalAusencias, Model.ApontamentoOperacional, DAO.ApontamentoOperacional, clRoteiroEntregador; type Thread_PopulaApontamentoOperacional = class(TThread) private { Private declarations } FData: TDate; FdPos: Double; apontamento: TApontamentoOperacional; apontamentos: TObjectList<TApontamentoOperacional>; apontamentoDAO: TApontamentoOperacionalDAO; ausencia: TRHoperacionalAusencias; ausencias: TObjectList<TRHoperacionalAusencias>; ausenciaDAO: TRHoperacionalAusenciasDAO; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; public property Data: TDate read FData write FData; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure Thread_PopulaApontamentoOperacional.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses View.ApontamentoOperacional, udm; { Thread_PopulaApontamentoOperacional } procedure Thread_PopulaApontamentoOperacional.Execute; var apontamentoTMP: TApontamentoOperacional; ausenciaTMP: TRHoperacionalAusencias; roteiro: TRoteiroEntregador; iTotal : Integer; iPos : Integer; begin { Place thread code here } try Synchronize(IniciaProcesso); Screen.Cursor := crHourGlass; if view_ApontamentoOperacional.tbApontamento.Active then view_ApontamentoOperacional.tbApontamento.Close; view_ApontamentoOperacional.tbApontamento.Open; apontamentoDAO := TApontamentoOperacionalDAO.Create(); apontamentos := apontamentoDAO.FindByData(Self.Data); roteiro := TRoteiroEntregador.Create(); view_ApontamentoOperacional.tbApontamento.IsLoading := True; if apontamentos.Count > 0 then begin iTotal := apontamentos.Count; for apontamentoTMP in apontamentos do begin view_ApontamentoOperacional.tbApontamento.Insert; view_ApontamentoOperacional.tbApontamentoID_OPERACAO.AsInteger := apontamentoTMP.ID; view_ApontamentoOperacional.tbApontamentoCOD_ENTREGADOR.AsInteger := apontamentoTMP.Entregador; view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_ANTIGO.AsString := apontamentoTMP.RoteiroAntigo; view_ApontamentoOperacional.tbApontamentoDAT_OPERACAO.AsDateTime := apontamentoTMP.Data; view_ApontamentoOperacional.tbApontamentoCOD_STATUS_OPERACAO.AsString := apontamentoTMP.StatusOperacao; view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_NOVO.AsString := apontamentoTMP.RoteiroNovo; view_ApontamentoOperacional.tbApontamentoDES_OBSERVACOES.AsString := apontamentoTMP.Obs; view_ApontamentoOperacional.tbApontamentoDOM_PLANILHA.AsString := apontamentoTMP.Planilha; view_ApontamentoOperacional.tbApontamentoID_REFERENCIA.AsInteger := apontamentoTMP.IDReferencia; view_ApontamentoOperacional.tbApontamentoDAT_REFERENCIA.AsDateTime := apontamentoTMP.DataReferencia; view_ApontamentoOperacional.tbApontamentoDES_LOG.AsString := apontamentoTMP.Log; view_ApontamentoOperacional.tbApontamento.Post; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; view_ApontamentoOperacional.dsApontamento.AutoEdit := False; end else begin if roteiro.getObject('S','MOSTRAR') then begin iTotal := dm.qryGetObject.RecordCount; dm.qryGetObject.First; while not dm.qryGetObject.Eof do begin view_ApontamentoOperacional.tbApontamento.Insert; view_ApontamentoOperacional.tbApontamentoID_OPERACAO.AsInteger := 0; view_ApontamentoOperacional.tbApontamentoCOD_ENTREGADOR.AsInteger := dm.qryGetObject.FieldByName('COD_CADASTRO').AsInteger; view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_ANTIGO.AsString := dm.qryGetObject.FieldByName('COD_ROTEIRO_ANTIGO').AsString; view_ApontamentoOperacional.tbApontamentoDAT_OPERACAO.AsDateTime := Self.Data; view_ApontamentoOperacional.tbApontamentoCOD_STATUS_OPERACAO.AsString := 'P'; view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_NOVO.AsString := dm.qryGetObject.FieldByName('COD_ROTEIRO_NOVO').AsString; view_ApontamentoOperacional.tbApontamentoDES_OBSERVACOES.AsString := ''; view_ApontamentoOperacional.tbApontamentoDOM_PLANILHA.AsString := dm.qryGetObject.FieldByName('DOM_MOSTRAR').AsString; view_ApontamentoOperacional.tbApontamentoID_REFERENCIA.AsInteger := 0; view_ApontamentoOperacional.tbApontamentoDAT_REFERENCIA.AsDateTime := 0; view_ApontamentoOperacional.tbApontamentoDES_LOG.AsString := ''; view_ApontamentoOperacional.tbApontamento.Post; dm.qryGetObject.Next; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; dm.qryGetObject.Close; dm.qryGetObject.SQL.Clear; view_ApontamentoOperacional.dsApontamento.AutoEdit := True; end; end; if not view_ApontamentoOperacional.tbApontamento.IsEmpty then view_ApontamentoOperacional.tbApontamento.First; ausenciaDAO := TRHOperacionalAusenciasDAO.Create(); ausencias := ausenciaDAO.FindByData(Self.Data); if view_ApontamentoOperacional.tbAusencias.Active then view_ApontamentoOperacional.tbAusencias.Close; view_ApontamentoOperacional.tbAusencias.Close; for ausenciaTMP in ausencias do begin view_ApontamentoOperacional.tbAusencias.Insert; view_ApontamentoOperacional.tbAusenciasID_AUSENCIA.AsInteger := ausenciaTMP.ID; view_ApontamentoOperacional.tbAusenciasDAT_OPERACAO.AsDateTime := ausenciaTMP.Data; view_ApontamentoOperacional.tbAusenciasCOD_CADASTRO.AsInteger := ausenciaTMP.Cadastro; view_ApontamentoOperacional.tbAusenciasCOD_STATUS_OPERACAO.AsString := ausenciaTMP.StatusOperacao; view_ApontamentoOperacional.tbAusenciasDES_OBSERVACOES.AsString := ausenciaTMP.Obs; view_ApontamentoOperacional.tbAusenciasID_REFERENCIA.AsInteger := ausenciaTMP.IDReferencia; view_ApontamentoOperacional.tbAusenciasDES_LOG.AsString := ausenciaTMP.Log; view_ApontamentoOperacional.tbAusencias.Post; end; finally Synchronize(TerminaProcesso); view_ApontamentoOperacional.tbApontamento.IsLoading := False; apontamentoDAO.Free; ausenciaDAO.Free; roteiro.Free; end; end; procedure Thread_PopulaApontamentoOperacional.IniciaProcesso; begin view_ApontamentoOperacional.pbApontamento.Visible := True; view_ApontamentoOperacional.dsApontamento.Enabled := False; view_ApontamentoOperacional.tbApontamento.IsLoading := True; view_ApontamentoOperacional.pbApontamento.Position := 0; view_ApontamentoOperacional.pbApontamento.Refresh; end; procedure Thread_PopulaApontamentoOperacional.AtualizaProcesso; begin view_ApontamentoOperacional.pbApontamento.Position := FdPos; view_ApontamentoOperacional.pbApontamento.Properties.Text := FormatFloat('0.00%',FdPos); view_ApontamentoOperacional.pbApontamento.Refresh; end; procedure Thread_PopulaApontamentoOperacional.TerminaProcesso; begin view_ApontamentoOperacional.pbApontamento.Position := 0; view_ApontamentoOperacional.pbApontamento.Properties.Text := ''; view_ApontamentoOperacional.pbApontamento.Refresh; view_ApontamentoOperacional.tbApontamento.IsLoading := False; view_ApontamentoOperacional.dsApontamento.Enabled := True; view_ApontamentoOperacional.pbApontamento.Visible := False; end; end.
unit MeasureUnitPoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, MeasureUnits; type TMeasureUnitDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils; { TUnitDataPoster } constructor TMeasureUnitDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_MEASURE_UNIT_DICT'; KeyFieldNames := 'MEASURE_UNIT_ID'; FieldNames := 'MEASURE_UNIT_ID, VCH_MEASURE_UNIT_NAME'; AccessoryFieldNames := 'MEASURE_UNIT_ID, VCH_MEASURE_UNIT_NAME'; AutoFillDates := false; Sort := 'VCH_MEASURE_UNIT_NAME'; end; function TMeasureUnitDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TMeasureUnitDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TMeasureUnit; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin o := AObjects.Add as TMeasureUnit; o.ID := ds.FieldByName('MEASURE_UNIT_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_MEASURE_UNIT_NAME').AsString); ds.Next; end; ds.First; end; end; function TMeasureUnitDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TMeasureUnit; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := TMeasureUnit(AObject); ds.FieldByName('MEASURE_UNIT_ID').AsInteger := o.ID; ds.FieldByName('VCH_MEASURE_UNIT_NAME').AsString := trim (o.Name); ds.Post; o.ID := ds.FieldByName('MEASURE_UNIT_ID').AsInteger; //if o.ID <= 0 then o.ID := (ds as TCommonServerDataSet).CurrentRecordFilterValues[0]; end; end.
unit NewCompany; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DBCtrls, DB, Grids, DBGrids, Mask, DBCtrlsEh, DBLookupEh, DBGridEh, sBitBtn, sLabel, sEdit, sCheckBox, sMaskEdit, sComboBox, sMemo, sDialogs, sSpeedButton, MemDS, DBAccess, Uni, sCustomComboEdit, sSkinProvider, sSkinManager; type TFormNewCompany = class(TForm) BitBtnCancel: TsBitBtn; EditCompany: TsEdit; Label1: TsLabel; Label2: TsLabel; Label4: TsLabel; MEChars: TsMaskEdit; Label5: TsLabel; Label6: TsLabel; CBCompanyNameType: TsComboBox; MemoComment: TsMemo; Label7: TsLabel; Label8: TsLabel; BitBtnSave: TsBitBtn; Label3: TsLabel; EditCity: TsEdit; Label9: TsLabel; CBTrustLevel: TsComboBox; Label10: TsLabel; txtPriceList: TsEdit; btnSelectPrice: TsSpeedButton; SelectPriceDialog: TsOpenDialog; lblBusiness: TsLabel; mmoBusiness: TsMemo; DSCompanyNameType: TUniDataSource; DSTrust: TUniDataSource; QCompanyNameType: TUniQuery; QTrustLevel: TUniQuery; QCompanyNameTypeCNT_ID: TIntegerField; QCompanyNameTypeCNT_NAME: TStringField; QTrustLevelTL_ID: TIntegerField; QTrustLevelTL_LEVEL: TIntegerField; QTrustLevelTL_COLOR: TIntegerField; QTrustLevelTL_NAME: TStringField; sSkinManager1: TsSkinManager; sSkinProvider1: TsSkinProvider; procedure BitBtnCancelClick(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BitBtnSaveClick(Sender: TObject); procedure btnSelectPriceClick(Sender: TObject); private F_LastOperType: string; public procedure SetPosition(L, T: Integer); procedure SetNewCompany(const IsChangeOwner: Boolean); end; var FormNewCompany: TFormNewCompany; implementation {$R *.dfm} uses System.UITypes, DataModule, MainForm, Companies, CommonUnit; const isReloadList: Boolean = True; { TFormCompany } procedure TFormNewCompany.SetPosition(L, T: Integer); begin Left:= L + ShiftLeft; Top:= T + ShiftTop; end; procedure TFormNewCompany.SetNewCompany(const IsChangeOwner: Boolean); begin EditCompany.Clear; EditCity.Clear; txtPriceList.Clear; MemoComment.Clear; mmoBusiness.Clear; MEChars.Text:= IntToStr(FormMain.SearchChars); if (F_LastOperType = '') or (F_LastOperType = 'INS') then begin QCompanyNameType.Close; QCompanyNameType.Open; QCompanyNameType.First; CBCompanyNameType.Clear; while not QCompanyNameType.eof do begin CBCompanyNameType.Items.Add(QCompanyNameType['CNT_NAME']); QCompanyNameType.Next; end; end; CBCompanyNameType.Text:= ''; QTrustlevel.Close; QTrustlevel.Open; QTrustlevel.First; CBTrustlevel.Clear; CBTrustlevel.Text:= QTrustlevel['TL_NAME']; while not QTrustlevel.eof do begin CBTrustLevel.Items.Add(QTrustlevel['TL_NAME']); QTrustLevel.Next; end; end; procedure TFormNewCompany.BitBtnCancelClick(Sender: TObject); begin FocusControl(EditCompany); end; procedure TFormNewCompany.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of // VK_F2: BitBtnSave.Click; VK_Escape: BitBtnCancel.Click; end; // case end; procedure TFormNewCompany.BitBtnSaveClick(Sender: TObject); var SToScreenText, CompanyNamePlusNT: string; Found, TrustLevel: Integer; begin if Length(EditCompany.Text) < 3 then begin MessageDlg('Название компании слишком маленькое, увеличьте его. При необходимости добавьте пробелы ', mtError, [mbOK], 0); ModalResult:= mrNone; Exit; end; //Для поиска имени SToScreenText:= DM.CompanySearchLikeName(ANSIUpperCase(EditCompany.Text), FormMain.SearchChars, False, Found); //Для вставки в БД if Trim(CBCompanyNameType.Text) = '' then CompanyNamePlusNT:= EditCompany.Text else CompanyNamePlusNT:= EditCompany.Text + ', ' + CBCompanyNameType.Text; TrustLevel:= 0; qTrustlevel.Close; qTrustlevel.Open; qTrustlevel.First; while not QTrustlevel.eof do begin if QTrustlevel['TL_NAME'] = CBTrustLevel.Text then begin TrustLevel:= QTrustlevel['TL_ID']; Break; end; QTrustlevel.Next; end; // while if Found > 0 then begin if MessageDlg(SToScreenText + Chr(13) + Chr(10) + 'Подтвердите сохранение', mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin ModalResult:= mrNone; Exit; end; DM.CompanyInsert(CompanyNamePlusNT, EditCity.Text, TrustLevel, MemoComment.text + Chr(13) + Chr(10) + 'Найдены похожие названия', Trim(txtPriceList.Text), UpperCase(Trim(mmoBusiness.Text))); DM.CompanyNTInsertOrUpdate(CBCompanyNameType.Text, F_LastOperType); //F_LastOperType='INS' определяет, что список CBCompanyNameType нужно передернуть //По умолчанию эта строка пустая end else begin DM.CompanyInsert(CompanyNamePlusNT, EditCity.Text, TrustLevel, DeleteLastReturn(MemoComment.Text), Trim(txtPriceList.Text), UpperCase(Trim(mmoBusiness.Text))); DM.CompanyNTInsertOrUpdate(CBCompanyNameType.Text, F_LastOperType); MessageDlg('Название успешно сохранено', mtInformation, [mbOK], 0); end; FocusControl(EditCompany); end; procedure TFormNewCompany.btnSelectPriceClick(Sender: TObject); begin SelectPriceDialog.FileName:= txtPriceList.Text; if SelectPriceDialog.Execute then begin txtPriceList.Text:= SelectPriceDialog.FileName; end; end; end.
unit uFTPServer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPServer, IdCmdTCPServer, IdFTPList, IdExplicitTLSClientServerBase, IdFTPServer, StdCtrls, IdFTPListOutput; type TForm1 = class(TForm) IdFTPServer1: TIdFTPServer; btnClose: TButton; moNotes: TMemo; procedure IdFTPServer1UserLogin(ASender: TIdFTPServerContext; const AUsername, APassword: string; var AAuthenticated: Boolean); procedure IdFTPServer1RemoveDirectory(ASender: TIdFTPServerContext; var VDirectory: string); procedure IdFTPServer1MakeDirectory(ASender: TIdFTPServerContext; var VDirectory: string); procedure IdFTPServer1RetrieveFile(ASender: TIdFTPServerContext; const AFileName: string; var VStream: TStream); procedure IdFTPServer1GetFileSize(ASender: TIdFTPServerContext; const AFilename: string; var VFileSize: Int64); procedure IdFTPServer1StoreFile(ASender: TIdFTPServerContext; const AFileName: string; AAppend: Boolean; var VStream: TStream); procedure IdFTPServer1ListDirectory(ASender: TIdFTPServerContext; const APath: string; ADirectoryListing: TIdFTPListOutput; const ACmd, ASwitches: string); procedure FormCreate(Sender: TObject); procedure IdFTPServer1DeleteFile(ASender: TIdFTPServerContext; const APathName: string); procedure IdFTPServer1ChangeDirectory(ASender: TIdFTPServerContext; var VDirectory: string); procedure btnCloseClick(Sender: TObject); private function ReplaceChars(APath: String): String; function GetSizeOfFile(AFile : String) : Integer; { Private declarations } public { Public declarations } end; var Form1: TForm1; AppDir : String; implementation {$R *.DFM} procedure TForm1.btnCloseClick(Sender: TObject); begin IdFTPServer1.Active := false; close; end; function TForm1.ReplaceChars(APath:String):String; var s:string; begin s := StringReplace(APath, '/', '\', [rfReplaceAll]); s := StringReplace(s, '\\', '\', [rfReplaceAll]); Result := s; end; function TForm1.GetSizeOfFile(AFile : String) : Integer; var FStream : TFileStream; begin Try FStream := TFileStream.Create(AFile, fmOpenRead); Try Result := FStream.Size; Finally FreeAndNil(FStream); End; Except Result := 0; End; end; procedure TForm1.IdFTPServer1ChangeDirectory( ASender: TIdFTPServerContext; var VDirectory: string); begin ASender.CurrentDir := VDirectory; end; procedure TForm1.IdFTPServer1DeleteFile(ASender: TIdFTPServerContext; const APathName: string); begin DeleteFile(ReplaceChars(AppDir+ASender.CurrentDir+'\'+APathname)); end; procedure TForm1.FormCreate(Sender: TObject); begin AppDir := ExtractFilePath(Application.Exename); end; procedure TForm1.IdFTPServer1ListDirectory(ASender: TIdFTPServerContext; const APath: string; ADirectoryListing: TIdFTPListOutput; const ACmd, ASwitches: string); var LFTPItem :TIdFTPListItem; SR : TSearchRec; SRI : Integer; begin ADirectoryListing.DirFormat := doUnix; SRI := FindFirst(AppDir + APath + '\*.*', faAnyFile - faHidden - faSysFile, SR); While SRI = 0 do begin LFTPItem := ADirectoryListing.Add; LFTPItem.FileName := SR.Name; LFTPItem.Size := SR.Size; LFTPItem.ModifiedDate := FileDateToDateTime(SR.Time); if SR.Attr = faDirectory then LFTPItem.ItemType := ditDirectory else LFTPItem.ItemType := ditFile; SRI := FindNext(SR); end; FindClose(SR); SetCurrentDir(AppDir + APath + '\..'); end; procedure TForm1.IdFTPServer1StoreFile(ASender: TIdFTPServerContext; const AFileName: string; AAppend: Boolean; var VStream: TStream); begin if not Aappend then VStream := TFileStream.Create(ReplaceChars(AppDir+AFilename),fmCreate) else VStream := TFileStream.Create(ReplaceChars(AppDir+AFilename),fmOpenWrite) end; procedure TForm1.IdFTPServer1GetFileSize(ASender: TIdFTPServerContext; const AFilename: string; var VFileSize: Int64); Var LFile : String; begin LFile := ReplaceChars( AppDir + AFilename ); try If FileExists(LFile) then VFileSize := GetSizeOfFile(LFile) else VFileSize := 0; except VFileSize := 0; end; end; procedure TForm1.IdFTPServer1RetrieveFile(ASender: TIdFTPServerContext; const AFileName: string; var VStream: TStream); begin VStream := TFileStream.Create(ReplaceChars(AppDir+AFilename),fmOpenRead); end; procedure TForm1.IdFTPServer1MakeDirectory(ASender: TIdFTPServerContext; var VDirectory: string); begin if not ForceDirectories(ReplaceChars(AppDir + VDirectory)) then begin Raise Exception.Create('Unable to create directory'); end; end; procedure TForm1.IdFTPServer1RemoveDirectory(ASender: TIdFTPServerContext; var VDirectory: string); Var LFile : String; begin LFile := ReplaceChars(AppDir + VDirectory); // You should delete the directory here. // TODO end; procedure TForm1.IdFTPServer1UserLogin(ASender: TIdFTPServerContext; const AUsername, APassword: string; var AAuthenticated: Boolean); begin // We just set AAuthenticated to true so any username / password is accepted // You should check them here - AUsername and APassword AAuthenticated := True; end; end.
Unit DateSupport; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses SysUtils, SysConst, DateUtils, Math, System.TimeSpan, StringSupport, MathSupport; Const DATETIME_MIN = -693593; // '1/01/0001' DATETIME_MAX = 2958465; // '31/12/9999' DATETIME_DAY_HOURS = 24; DATETIME_DAY_MINUTES = DATETIME_DAY_HOURS * 60; DATETIME_DAY_SECONDS = DATETIME_DAY_MINUTES * 60; DATETIME_DAY_MILLISECONDS = DATETIME_DAY_SECONDS * 1000; DATETIME_DAY_ONE = 1.0; DATETIME_HOUR_ONE = DATETIME_DAY_ONE / DATETIME_DAY_HOURS; DATETIME_MINUTE_ONE = DATETIME_DAY_ONE / DATETIME_DAY_MINUTES; DATETIME_SECOND_ONE = DATETIME_DAY_ONE / DATETIME_DAY_SECONDS; DATETIME_MILLISECOND_ONE = DATETIME_DAY_ONE / DATETIME_DAY_MILLISECONDS; type TDuration = Int64; // Number of milliseconds. TMonthOfYear = (MonthOfYearJanuary, MonthOfYearFebruary, MonthOfYearMarch, MonthOfYearApril, MonthOfYearMay, MonthOfYearJune, MonthOfYearJuly, MonthOfYearAugust, MonthOfYearSeptember, MonthOfYearOctober, MonthOfYearNovember, MonthOfYearDecember); TMonthDays = Array [TMonthOfYear] Of Word; TDateTimeExPrecision = (dtpYear, dtpMonth, dtpDay, dtpHour, dtpMin, dtpSec, dtpNanoSeconds); TDateTimeExTimezone = (dttzUnknown, dttzUTC, dttzLocal, dttzSpecified); Const codes_TDateTimeExPrecision : Array [TDateTimeExPrecision] of String = ('Year', 'Month', 'Day', 'Hour', 'Min', 'Sec', 'NanoSeconds'); codes_TDateTimeExTimezone : Array [TDateTimeExTimezone] of String = ('Unknown', 'UTC', 'Local', 'Specified'); MONTHOFYEAR_LONG : Array[TMonthOfYear] Of String = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); MONTHOFYEAR_SHORT : Array [TMonthOfYear] Of String = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); MONTHS_DAYS : Array [Boolean{IsLeapYear}] Of TMonthDays = ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31), (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)); type EDateFormatError = class(Exception); TTimeStamp = record year: Smallint; month: Word; day: Word; hour: Word; minute: Word; second: Word; fraction: Cardinal; end; TDateTimeEx = record private Source : String; // for debugging convenience, and also used to mark whether the record has any content year: Smallint; month: Word; day: Word; hour: Word; minute: Word; second: Word; fraction: Cardinal; {@member Precision The precision to which the date and time is specified } FPrecision : TDateTimeExPrecision; FractionPrecision : integer; {@member TimezoneType The type of timezone } TimezoneType : TDateTimeExTimezone; TimeZoneHours : Integer; TimezoneMins : Integer; private procedure clear; procedure check; function checkNoException : boolean; procedure RollUp; function privToString: String; public class function makeNull : TDateTimeEx; static; class function makeUTC : TDateTimeEx; overload; static; class function makeUTC(value : TDateTime) : TDateTimeEx; overload; static; class function makeToday : TDateTimeEx; overload; static; class function makeLocal : TDateTimeEx; overload; static; class function makeLocal(precision : TDateTimeExPrecision) : TDateTimeEx; overload; static; class function makeLocal(value : TDateTime) : TDateTimeEx; overload; static; class function make(value : TDateTime; tz : TDateTimeExTimezone) : TDateTimeEx; static; class function fromHL7(value : String) : TDateTimeEx; static; class function fromXML(value : String) : TDateTimeEx; static; class function fromTS(value : TTimestamp; tz : TDateTimeExTimezone = dttzLocal) : TDateTimeEx; overload; static; class function fromDB(value : String; tz : TDateTimeExTimezone = dttzUTC) : TDateTimeEx; static; // mainly for SQLite support { Read a date (date) given the specified format. The specified format can be any combination of YYYY, YYY, YY, MM, MMM, DD, HH, NN, SS. Use spaces for parts of the date that are just separators. This method can't cope with variable length date representations such as full month names. If the year is < 100, it will be adjusted to a current year (irrespective of the year length YYYY or YY). See ReadDateStrict } class function fromFormat(format, date: String; AllowBlankTimes: Boolean = False; allowNoDay: Boolean = False; allownodate: Boolean = False; noFixYear : boolean = false) : TDateTimeEx; static; { Like ReadDate, but years < 100 will not be corrected as if they are 2 digit year representations } class function fromFormatStrict(format, date: String; AllowBlankTimes: Boolean = False; allowNoDay: Boolean = False; allownodate: Boolean = False) : TDateTimeEx; static; function null : boolean; function notNull : boolean; function DateTime : TDateTime; function TimeStamp : TTimeStamp; function fixPrecision(FPrecision : TDateTimeExPrecision) : TDateTimeEx; function Local : TDateTimeEx; function UTC : TDateTimeEx; function Min : TDateTimeEx; function Max : TDateTimeEx; function AsTz(hr, min : Integer):TDateTimeEx; // this date and time in the specified timezone. function IncrementMonth: TDateTimeEx; function IncrementYear: TDateTimeEx; function IncrementWeek: TDateTimeEx; function IncrementDay: TDateTimeEx; function add(length : TDateTime) : TDateTimeEx; function subtract(length : TDateTime) : TDateTimeEx; function lessPrecision: TDateTimeEx; function equal(other : TDateTimeEx) : Boolean; // returns true if the timezone, FPrecision, and actual instant are the same function sameTime(other : TDateTimeEx) : Boolean; // returns true if the specified instant is the same allowing for specified FPrecision - corrects for timezone function after(other : TDateTimeEx; inclusive : boolean):boolean; function before(other : TDateTimeEx; inclusive : boolean):boolean; function between(min, max : TDateTimeEx; inclusive : boolean):boolean; {@ Valid formatting strings are yyyy 4 digit year yy 2 digit year mmmm long month name mmm short month name mm 2 digit month number (will include leading 0 if needed) m month number (no leading 0) dd 2 digit day number (will include leading 0 if needed) d day number (no leading 0) hh 2 digit hour number nn 2 digit minutes ss 2 digit seconds } function toString(format: String): String; overload; function toString: String; overload; // as human readable function toHL7: String; // as yyyymmddhhnnss.zzz+T function toXML : String; function toDB : String; // as yyyy-mm-dd hh:nn:ss.zzz class function isValidXmlDate(value : String) : Boolean; static; property Precision : TDateTimeExPrecision read FPrecision; end; Function TimeZoneBias : TDateTime; Overload; Function TimeZoneBias(when : TDateTime) : TDateTime; Overload; function TSToDateTime(TS: TTimeStamp): TDateTime; function DateTimeToTS(Value : TDateTime): TTimeStamp; function SameInstant(t1, t2 : TDateTime) : boolean; Function DateTimeMax(Const aA, aB : TDateTime) : TDateTime; Overload; Function DateTimeMin(Const aA, aB : TDateTime) : TDateTime; Overload; Function DateTimeCompare(Const aA, aB : TDateTime) : Integer; Overload; Function DateTimeCompare(Const aA, aB, aThreshold : TDateTime) : Integer; Overload; function DescribePeriod(Period: TDateTime): String; Function DateTimeToXMLDateTimeTimeZoneString(Const aTimestamp, aTimeZone : TDateTime) : String; Implementation uses GuidSupport, EncodeSupport; { TDateTimeEx } function TDateTimeEx.add(length: TDateTime): TDateTimeEx; begin result := makeUTC(dateTime + length); result.FPrecision := FPrecision; result.FractionPrecision := FractionPrecision; result.TimezoneType := TimezoneType; result.TimeZoneHours := TimeZoneHours; result.TimezoneMins := TimezoneMins; end; procedure TDateTimeEx.check; var err : String; begin err := ''; if (year < 1000) or (year > 3000) then err := 'Year is not valid' else if (FPrecision >= dtpMonth) and ((Month > 12) or (Month < 1)) then err := 'Month is not valid' else if (FPrecision >= dtpDay) and ((Day < 1) or (Day >= 32) or (MONTHS_DAYS[IsLeapYear(Year)][TMonthOfYear(Month-1)] < Day)) then err := 'Day is not valid for '+inttostr(Year)+'/'+inttostr(Month) else if (FPrecision >= dtpHour) and (Hour > 23) then err := 'Hour is not valid' else if (FPrecision >= dtpMin) and (Minute > 59) then err := 'Minute is not valid' else if (FPrecision >= dtpSec) and (Second > 59) then err := 'Second is not valid' else if (FPrecision >= dtpNanoSeconds) and (FractionPrecision > 999999999) then err := 'Fraction is not valid' else if (TimezoneType = dttzSpecified) and ((TimezoneHours < -13) or (TimezoneHours > 14)) then err := 'Timezone hours is not valid' else if (TimezoneType = dttzSpecified) and not ((TimezoneMins = 0) or (TimezoneMins = 15) or (TimezoneMins = 30) or (TimezoneMins = 45)) then err := 'Timezone minutes is not valid'; if err <> '' then raise EDateFormatError.Create(err+' ('+privToString+')'); end; function TDateTimeEx.checkNoException: boolean; var err : String; begin err := ''; if (year < 1000) or (year > 3000) then err := 'Year is not valid' else if (FPrecision >= dtpMonth) and ((Month > 12) or (Month < 1)) then err := 'Month is not valid' else if (FPrecision >= dtpDay) and ((Day < 1) or (Day >= 32) or (MONTHS_DAYS[IsLeapYear(Year)][TMonthOfYear(Month-1)] < Day)) then err := 'Day is not valid for '+inttostr(Year)+'/'+inttostr(Month) else if (FPrecision >= dtpHour) and (Hour > 23) then err := 'Hour is not valid' else if (FPrecision >= dtpMin) and (Minute > 59) then err := 'Minute is not valid' else if (FPrecision >= dtpSec) and (Second > 59) then err := 'Second is not valid' else if (FPrecision >= dtpNanoSeconds) and (FractionPrecision > 999999999) then err := 'Fraction is not valid' else if (TimezoneType = dttzSpecified) and ((TimezoneHours < -13) or (TimezoneHours > 14)) then err := 'Timezone hours is not valid' else if (TimezoneType = dttzSpecified) and not ((TimezoneMins = 0) or (TimezoneMins = 15) or (TimezoneMins = 30) or (TimezoneMins = 45)) then err := 'Timezone minutes is not valid'; result := err = ''; end; procedure TDateTimeEx.clear; begin Source := ''; year := 0; month := 0; day := 0; hour := 0; minute := 0; second := 0; fraction := 0; FPrecision := dtpYear; FractionPrecision := 0; TimezoneType := dttzUnknown; TimeZoneHours := 0; TimezoneMins := 0; end; function TDateTimeEx.DateTime: TDateTime; begin check; case FPrecision of dtpYear : Result := EncodeDate(Year, 1, 1); dtpMonth : Result := EncodeDate(Year, Month, 1); dtpDay: Result := EncodeDate(Year, Month, Day); dtpHour : Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, 0, 0, 0); dtpMin : Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, 0, 0); dtpSec : Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, Second, 0); dtpNanoSeconds : Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, Second, Fraction div 1000000); else Result := 0; end; end; procedure FindBlock(ch: Char; const s: String; var start, blength: Integer); begin start := pos(ch, s); if start = 0 then blength := 0 else begin blength := 1; while (start + blength <= length(s)) and (s[start + blength] = ch) do inc(blength); end; end; function UserStrToInt(st, Info: String): Integer; { raise an EHL7UserException } var E: Integer; begin Val(St, Result, E); if E <> 0 then raise EDateFormatError.CreateFmt(SInvalidInteger + ' reading ' + Info, [St]); end; class function TDateTimeEx.make(value: TDateTime; tz: TDateTimeExTimezone): TDateTimeEx; var ms: Word; yr: Word; begin result.clear; DecodeTime(value, result.Hour, result.Minute, result.Second, ms); result.Fraction := ms * 1000000; if result.second > 59 then raise Exception.Create('Fail!'); DecodeDate(value, yr, result.Month, result.Day); result.Year := yr; result.FPrecision := dtpSec; result.FractionPrecision := 0; result.TimezoneType := tz; result.Source := 'makeDT'; end; class function TDateTimeEx.makeLocal(precision: TDateTimeExPrecision): TDateTimeEx; begin result := TDateTimeEx.makeLocal(now).fixPrecision(precision); end; function checkFormat(format : String) : string; begin if (format = 'c') then result := FormatSettings.shortDateFormat+' '+FormatSettings.ShortTimeFormat else if (format = 'cd') then result := FormatSettings.shortDateFormat else if (format = 'ct') then result := FormatSettings.ShortTimeFormat else if (format = 'C') then result := FormatSettings.longDateFormat+' '+FormatSettings.LongTimeFormat else if (format = 'CD') then result := FormatSettings.LongDateFormat else if (format = 'CC') then result := FormatSettings.LongTimeFormat else if (format = 'x') then result := 'yyyy-dd-mmThh:nn:ss' else result := format; end; class function TDateTimeEx.fromDB(value: String; tz : TDateTimeExTimezone = dttzUTC): TDateTimeEx; begin result := fromFormat('yyyy-mm-dd hh:nn:ss.sss', value, true, true, false); result.TimezoneType := tz; end; class function TDateTimeEx.fromFormat(format, date: String; AllowBlankTimes: Boolean = False; allowNoDay: Boolean = False; allownodate: Boolean = False; noFixYear : boolean = false) : TDateTimeEx; var start, length: Integer; s: String; tmp: String; begin result.clear; format := checkFormat(format); Result.year := 0; Result.month := 0; Result.day := 0; Result.hour := 0; Result.minute := 0; Result.second := 0; Result.fraction := 0; FindBlock('y', Format, start, length); tmp := copy(date, start, length); if lowercase(tmp) = 'nown' then exit; if (tmp = '') and AllowNoDate then // we don't bother with the year else begin Result.year := UserStrToInt(tmp, 'Year from "' + date + '"'); if not NoFixYear then begin if Result.year < 100 then if abs(Result.year) > {$IFNDEF VER130}FormatSettings.{$ENDIF}TwoDigitYearCenturyWindow then //abs as result.year is a smallint, twodigityearcenturywindow is a word (range checking) inc(Result.year, 1900) else inc(Result.year, 2000); end; end; FindBlock('m', Format, start, length); s := lowercase(copy(date, start, length)); if AllowNoDate and (tmp = '') then // we don't worry about the month else begin if length > 2 then begin if (s = 'jan') or (s = 'january') then Result.month := 1 else if (s = 'feb') or (s = 'february') then Result.month := 2 else if (s = 'mar') or (s = 'march') then Result.month := 3 else if (s = 'apr') or (s = 'april') then Result.month := 4 else if (s = 'may') then Result.month := 5 else if (s = 'jun') or (s = 'june') then Result.month := 6 else if (s = 'jul') or (s = 'july') then Result.month := 7 else if (s = 'aug') or (s = 'august') then Result.month := 8 else if (s = 'sep') or (s = 'september') then Result.month := 9 else if (s = 'oct') or (s = 'october') then Result.month := 10 else if (s = 'nov') or (s = 'november') then Result.month := 11 else if (s = 'dec') or (s = 'december') then Result.month := 12 else raise EDateFormatError.Create('The Month "' + s + '" is unknown'); end else if s = '' then Result.Month := 1 else Result.month := UserStrToInt(s, 'Month from "' + date + '"'); if (Result.month > 12) or (Result.month < 1) then raise EDateFormatError.Create('invalid month ' + IntToStr(Result.month)); end; FindBlock('d', Format, start, length); tmp := copy(date, start, length); if (AllowNoday or AllowNoDate) and (tmp = '') then // we don't check the day else begin Result.day := UserStrToInt(tmp, 'Day from "' + date + '"'); end; FindBlock('h', Format, start, length); if length <> 0 then if AllowBlankTimes then Result.hour := StrToIntDef(copy(date, start, length), 0) else Result.hour := UserStrToInt(copy(date, start, length), 'Hour from "' + date + '"'); FindBlock('s', Format, start, length); if length <> 0 then if AllowBlankTimes then Result.second := StrToIntDef(copy(date, start, length), 0) else Result.second := UserStrToInt(copy(date, start, length), 'Second from "' + date + '"'); FindBlock('n', Format, start, length); if length <> 0 then if AllowBlankTimes then Result.minute := StrToIntDef(copy(date, start, length), 0) else Result.minute := UserStrToInt(copy(date, start, length), 'Minute from "' + date + '"'); FindBlock('z', Format, start, length); if length <> 0 then if AllowBlankTimes then Result.fraction := StrToIntDef(copy(date, start, length), 0); FindBlock('x', Format, start, length); if length <> 0 then if uppercase(copy(date, start, length)) = 'AM' then begin if Result.hour = 12 then Result.hour := 0 end else inc(Result.hour, 12); if Result.hour = 24 then begin Result.hour := 0; inc(result.day); end; result.RollUp; result.check; if (result.Hour = 0) and (result.Minute = 0) and (result.Second = 0) then result.FPrecision := dtpDay else result.FPrecision := dtpSec; result.FractionPrecision := 0; result.TimezoneType := dttzLocal; result.Source := date; end; class function TDateTimeEx.fromFormatStrict(format, date: String; AllowBlankTimes: Boolean = False; allowNoDay: Boolean = False; allownodate: Boolean = False) : TDateTimeEx; begin result := fromFormat(format, date, AllowBlankTimes, allowNoDay, allownodate, true); end; function TDateTimeEx.IncrementMonth : TDateTimeEx; begin result := self; if result.month = 12 then begin inc(result.year); result.month := 1 end else inc(result.month); if result.day > MONTHS_DAYS[IsLeapYear(result.Year), TMonthOfYear(result.month - 1)] then result.Day := MONTHS_DAYS[IsLeapYear(result.Year), TMonthOfYear(result.month - 1)]; end; function TDateTimeEx.IncrementYear : TDateTimeEx; begin result := self; inc(result.year); end; function vsv(value : String; start, len, min, max : Integer; name : String):Integer; var v : String; begin v := copy(value, start, len); if not StringIsInteger16(v) then exit(-1); result := StrToInt(v); if (result < min) or (result > max) then exit(-1); end; class function TDateTimeEx.isValidXmlDate(value: String): Boolean; var s : String; neg : boolean; res : TDateTimeEx; begin if value = '' then exit(false); res.Source := Value; if pos('Z', value) = length(value) then begin res.TimezoneType := dttzUTC; Delete(value, length(value), 1); end else if (pos('T', value) > 0) and StringContainsAny(copy(Value, pos('T', value)+1, $FF), ['-', '+']) then begin neg := Pos('-', copy(Value, pos('T', value)+1, $FF)) > 0; StringSplitRight(value, ['-', '+'], value, s); if length(s) <> 5 then raise Exception.create('Unable to parse date/time "'+value+'": timezone is illegal length - must be 5'); res.TimezoneHours := vsv(s, 1, 2, 0, 14, 'timezone hours'); res.TimezoneMins := vsv(s, 4, 2, 0, 59, 'timezone minutes'); res.TimezoneType := dttzSpecified; if neg then res.TimezoneHours := -res.TimezoneHours; end; res.FractionPrecision := 0; if Length(value) >=4 then res.Year := vsv(Value, 1, 4, 1800, 2100, 'years'); if Length(value) < 7 then res.FPrecision := dtpYear else begin res.Month := vsv(Value, 6, 2, 1, 12, 'months'); if length(Value) < 10 then res.FPrecision := dtpMonth else begin res.Day := vsv(Value, 9, 2, 1, 31, 'days'); if length(Value) < 13 then res.FPrecision := dtpDay else begin res.Hour := vsv(Value, 12, 2, 0, 23, 'hours'); if length(Value) < 15 then res.FPrecision := dtpHour else begin res.Minute := vsv(Value, 15, 2, 0, 59, 'minutes'); if length(Value) < 18 then res.FPrecision := dtpMin else begin res.Second := vsv(Value, 18, 2, 0, 59, 'seconds'); if length(Value) <= 20 then res.FPrecision := dtpSec else begin s := copy(Value, 21, 6); res.FractionPrecision := length(s); res.fraction := trunc(vsv(Value, 21, 4, 0, 999999, 'fractions') * power(10, 9 - res.FractionPrecision)); res.FPrecision := dtpNanoSeconds; end; end; end; end; end; end; result := res.checkNoException; end; function TDateTimeEx.lessPrecision: TDateTimeEx; begin result := self; if result.FPrecision > dtpYear then result.FPrecision := pred(result.FPrecision); result.RollUp; end; function TDateTimeEx.IncrementWeek : TDateTimeEx; var i: Integer; begin result := self; for i := 1 to 7 do begin inc(result.day); result.rollUp; end; end; function TDateTimeEx.IncrementDay : TDateTimeEx; begin result := self; inc(result.day); result.RollUp; end; function ReplaceSubString(var AStr: String; const ASearchStr, AReplaceStr: String): Boolean; var sStr : String; begin sStr := StringReplace(aStr, ASearchStr, AReplaceStr, [rfReplaceAll, rfIgnoreCase]); result := aStr <> sStr; aStr := sStr; end; function TDateTimeEx.ToString(format: String): String; begin if Source = '' then exit(''); check; format := checkFormat(format); Result := format; if not ReplaceSubString(Result, 'yyyy', StringPadRight(IntToStr(year), '0', 4)) then replaceSubstring(Result, 'yy', copy(IntToStr(year), 3, 2)); if not ReplaceSubString(Result, 'mmmm', copy(MONTHOFYEAR_LONG[TMonthOfYear(month-1)], 1, 4)) then if not ReplaceSubString(Result, 'mmm', MONTHOFYEAR_SHORT[TMonthOfYear(month-1)]) then if not ReplaceSubString(Result, 'mm', StringPadLeft(IntToStr(month), '0', 2)) then ReplaceSubString(Result, 'm', IntToStr(month)); if not ReplaceSubString(Result, 'dd', StringPadLeft(IntToStr(day), '0', 2)) then ReplaceSubString(Result, 'd', IntToStr(day)); ReplaceSubString(Result, 'HH', StringPadLeft(IntToStr(hour), '0', 2)); ReplaceSubString(Result, 'H', IntToStr(hour)); ReplaceSubString(Result, 'hh', StringPadLeft(IntToStr(hour mod 12), '0', 2)); ReplaceSubString(Result, 'h', IntToStr(hour mod 12)); ReplaceSubString(Result, 'nn', StringPadLeft(IntToStr(minute), '0', 2)); ReplaceSubString(Result, 'ss', StringPadLeft(IntToStr(second), '0', 2)); if hour < 12 then ReplaceSubString(Result, 'AMPM', 'AM') else ReplaceSubString(Result, 'AMPM', 'PM'); end; function vs(value : String; start, len, min, max : Integer; name : String):Integer; var v : String; begin v := copy(value, start, len); if not StringIsInteger16(v) then raise exception.create('Unable to parse date/time "'+value+'" at '+name); result := StrToInt(v); if (result < min) or (result > max) then raise exception.create('Value for '+name+' in date/time "'+value+'" is not allowed'); end; class function TDateTimeEx.fromHL7(value: String) : TDateTimeEx; var s : String; neg : boolean; begin if value = '' then exit(makeNull); result.clear; result.Source := Value; if pos('Z', value) = length(value) then begin result.TimezoneType := dttzUTC; Delete(value, length(value), 1); end else if StringContainsAny(Value, ['-', '+']) then begin neg := Pos('-', Value) > 0; StringSplit(value, ['-', '+'], value, s); if length(s) <> 4 then raise Exception.create('Unable to parse date/time "'+value+'": timezone is illegal length - must be 4'); result.TimezoneHours := vs(s, 1, 2, 0, 13, 'timezone hours'); result.TimezoneMins := vs(s, 3, 2, 0, 59, 'timezone minutes'); result.TimezoneType := dttzSpecified; if neg then result.TimezoneHours := -result.TimezoneHours; end; result.FractionPrecision := 0; if Length(value) >=4 then result.Year := vs(Value, 1, 4, 1800, 2100, 'years'); if Length(value) < 6 then result.FPrecision := dtpYear else begin result.Month := vs(Value, 5, 2, 1, 12, 'months'); if length(Value) < 8 then result.FPrecision := dtpMonth else begin result.Day := vs(Value, 7, 2, 1, 31, 'days'); if length(Value) < 10 then result.FPrecision := dtpDay else begin result.Hour := vs(Value, 9, 2, 0, 23, 'hours'); if length(Value) < 12 then result.FPrecision := dtpHour else begin result.Minute := vs(Value, 11, 2, 0, 59, 'minutes'); if length(Value) < 14 then result.FPrecision := dtpMin else begin result.Second := vs(Value, 13, 2, 0, 59, 'seconds'); if length(Value) <= 15 then result.FPrecision := dtpSec else begin s := copy(Value, 16, 4); result.FractionPrecision := length(s); result.fraction := trunc(vs(Value, 16, 4, 0, 9999, 'fractions') * power(10, 9 - result.FractionPrecision)); result.FPrecision := dtpNanoSeconds; end; end; end; end; end; end; result.check; result.source := value; end; class function TDateTimeEx.fromXML(value: String) : TDateTimeEx; var s : String; neg : boolean; begin if value = '' then exit(makeNull); result.clear; result.Source := Value; if pos('Z', value) = length(value) then begin result.TimezoneType := dttzUTC; Delete(value, length(value), 1); end else if (pos('T', value) > 0) and StringContainsAny(copy(Value, pos('T', value)+1, $FF), ['-', '+']) then begin neg := Pos('-', copy(Value, pos('T', value)+1, $FF)) > 0; StringSplitRight(value, ['-', '+'], value, s); if length(s) <> 5 then raise Exception.create('Unable to parse date/time "'+value+'": timezone is illegal length - must be 5'); result.TimezoneHours := vs(s, 1, 2, 0, 14, 'timezone hours'); result.TimezoneMins := vs(s, 4, 2, 0, 59, 'timezone minutes'); result.TimezoneType := dttzSpecified; if neg then result.TimezoneHours := -result.TimezoneHours; end; result.FractionPrecision := 0; if Length(value) >=4 then result.Year := vs(Value, 1, 4, 1800, 2100, 'years'); if Length(value) < 7 then result.FPrecision := dtpYear else begin result.Month := vs(Value, 6, 2, 1, 12, 'months'); if length(Value) < 10 then result.FPrecision := dtpMonth else begin result.Day := vs(Value, 9, 2, 1, 31, 'days'); if length(Value) < 13 then result.FPrecision := dtpDay else begin result.Hour := vs(Value, 12, 2, 0, 23, 'hours'); if length(Value) < 15 then result.FPrecision := dtpHour else begin result.Minute := vs(Value, 15, 2, 0, 59, 'minutes'); if length(Value) < 18 then result.FPrecision := dtpMin else begin result.Second := vs(Value, 18, 2, 0, 59, 'seconds'); if length(Value) <= 20 then result.FPrecision := dtpSec else begin s := copy(Value, 21, 6); result.FractionPrecision := length(s); result.fraction := trunc(vs(Value, 21, 4, 0, 999999, 'fractions') * power(10, 9 - result.FractionPrecision)); result.FPrecision := dtpNanoSeconds; end; end; end; end; end; end; result.check; result.source := value; end; Function sv(i, w : integer):String; begin result := StringPadLeft(inttostr(abs(i)), '0', w); if i < 0 then result := '-'+result; end; function TDateTimeEx.toDB: String; begin case FPrecision of dtpYear: result := sv(Year, 4); dtpMonth: result := sv(Year, 4) + '-'+sv(Month, 2); dtpDay: result := sv(Year, 4) + '-'+sv(Month, 2) + '-'+sv(Day, 2); dtpHour: result := sv(Year, 4) + '-'+sv(Month, 2) + '-'+sv(Day, 2) + ' '+sv(hour, 2); dtpMin: result := sv(Year, 4) + '-'+sv(Month, 2) + '-'+sv(Day, 2) + ' '+sv(hour, 2)+ ':'+sv(Minute, 2); dtpSec: result := sv(Year, 4) + '-'+sv(Month, 2) + '-'+sv(Day, 2) + ' '+sv(hour, 2)+ ':'+sv(Minute, 2)+ ':'+sv(Second, 2); dtpNanoSeconds: result := sv(Year, 4) + '-'+sv(Month, 2) + '-'+sv(Day, 2) + ' '+sv(hour, 2)+ ':'+sv(Minute, 2)+ ':'+sv(Second, 2)+'.'+copy(sv(Fraction, 9), 1, IntegerMax(FractionPrecision, 3)); end; end; function TDateTimeEx.toHL7: String; begin if null then exit(''); case FPrecision of dtpYear: result := sv(Year, 4); dtpMonth: result := sv(Year, 4) + sv(Month, 2); dtpDay: result := sv(Year, 4) + sv(Month, 2) + sv(Day, 2); dtpHour: result := sv(Year, 4) + sv(Month, 2) + sv(Day, 2) + sv(hour, 2); dtpMin: result := sv(Year, 4) + sv(Month, 2) + sv(Day, 2) + sv(hour, 2)+ sv(Minute, 2); dtpSec: result := sv(Year, 4) + sv(Month, 2) + sv(Day, 2) + sv(hour, 2)+ sv(Minute, 2)+ sv(Second, 2); dtpNanoSeconds: result := sv(Year, 4) + sv(Month, 2) + sv(Day, 2) + sv(hour, 2)+ sv(Minute, 2)+ sv(Second, 2)+'.'+copy(sv(Fraction, 9), 1, IntegerMax(FractionPrecision, 3)); end; case TimezoneType of dttzUTC : result := result + 'Z'; dttzSpecified : if TimezoneHours < 0 then result := result + sv(TimezoneHours, 2) + sv(TimezoneMins, 2) else result := result + '+'+sv(TimezoneHours, 2) + sv(TimezoneMins, 2); dttzLocal : if TimeZoneBias > 0 then result := result + '+'+FormatDateTime('hhnn', TimeZoneBias, FormatSettings) else result := result + '-'+FormatDateTime('hhnn', -TimeZoneBias, FormatSettings); {else dttzUnknown - do nothing } end; end; function TDateTimeEx.toXml: String; begin if null then exit(''); case FPrecision of dtpYear: result := sv(Year, 4); dtpMonth: result := sv(Year, 4) + '-' + sv(Month, 2); dtpDay: result := sv(Year, 4) + '-' + sv(Month, 2) + '-' + sv(Day, 2); dtpHour: result := sv(Year, 4) + '-' + sv(Month, 2) + '-' + sv(Day, 2) + 'T' + sv(hour, 2) + ':' + sv(Minute, 2); // note minutes anyway in this case dtpMin: result := sv(Year, 4) + '-' + sv(Month, 2) + '-' + sv(Day, 2) + 'T' + sv(hour, 2) + ':' + sv(Minute, 2); dtpSec: result := sv(Year, 4) + '-' + sv(Month, 2) + '-' + sv(Day, 2) + 'T' + sv(hour, 2) + ':' + sv(Minute, 2)+ ':' + sv(Second, 2); dtpNanoSeconds: result := sv(Year, 4) + '-' + sv(Month, 2) + '-' + sv(Day, 2) + 'T' + sv(hour, 2) + ':' + sv(Minute, 2)+ ':' + sv(Second, 2)+'.'+copy(sv(Fraction, 9), 1, FractionPrecision); end; if (FPrecision > dtpDay) then case TimezoneType of dttzUTC : result := result + 'Z'; dttzSpecified : if TimezoneHours < 0 then result := result + sv(TimezoneHours, 2) + ':'+sv(TimezoneMins, 2) else result := result + '+'+sv(TimezoneHours, 2) + ':'+sv(TimezoneMins, 2); dttzLocal : if TimeZoneBias > 0 then result := result + '+'+FormatDateTime('hh:nn', TimeZoneBias, FormatSettings) else result := result + '-'+FormatDateTime('hh:nn', -TimeZoneBias, FormatSettings); {else dttzUnknown - do nothing } end; end; function TDateTimeEx.Local: TDateTimeEx; var bias : TDateTime; begin if FPrecision >= dtpHour then case TimezoneType of dttzUTC : result := TDateTimeEx.makeLocal(TTimeZone.Local.ToLocalTime(self.DateTime)); dttzSpecified : begin if TimezoneHours < 0 then bias := - (-TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE) else bias := (TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE); result := TDateTimeEx.makeLocal(TTimeZone.Local.ToLocalTime(self.DateTime-bias)); end else result := self; end; result.FPrecision := FPrecision; result.FractionPrecision := FractionPrecision; result.TimezoneType := dttzLocal; end; function TDateTimeEx.Max: TDateTimeEx; begin result := self; case FPrecision of dtpYear: begin inc(result.year); result.Month := 1; result.Day := 1; result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpMonth: begin inc(result.Month); result.Day := 1; result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpDay: begin inc(result.Day); result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpHour: begin inc(result.Hour); result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpMin: begin inc(result.minute); result.Second := 0; result.fraction := 0; end; dtpSec: begin inc(result.Second); result.fraction := 0; end; dtpNanoSeconds: begin inc(result.fraction); end; end; result.RollUp; result.FPrecision := dtpNanoSeconds; result.check; end; function TDateTimeEx.Min: TDateTimeEx; begin result := self; case FPrecision of dtpYear: begin result.Month := 1; result.Day := 1; result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpMonth: begin result.Day := 1; result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpDay: begin result.Hour := 0; result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpHour: begin result.minute := 0; result.Second := 0; result.fraction := 0; end; dtpMin: begin result.Second := 0; result.fraction := 0; end; dtpSec: begin result.fraction := 0; end; dtpNanoSeconds: begin end; end; result.FPrecision := dtpNanoSeconds; end; function TDateTimeEx.notNull: boolean; begin result := Source <> ''; end; function TDateTimeEx.null: boolean; begin result := Source = ''; end; function TDateTimeEx.privToString: String; begin Result := 'yyyymmddhhnnss'; if not ReplaceSubString(Result, 'yyyy', StringPadRight(IntToStr(year), '0', 4)) then replaceSubstring(Result, 'yy', copy(IntToStr(year), 3, 2)); if month <> 0 then begin if not ReplaceSubString(Result, 'mmmm', copy(MONTHOFYEAR_LONG[TMonthOfYear(month-1)], 1, 4)) then if not ReplaceSubString(Result, 'mmm', MONTHOFYEAR_SHORT[TMonthOfYear(month-1)]) then if not ReplaceSubString(Result, 'mm', StringPadLeft(IntToStr(month), '0', 2)) then ReplaceSubString(Result, 'm', IntToStr(month)); if day > 0 then begin if not ReplaceSubString(Result, 'dd', StringPadLeft(IntToStr(day), '0', 2)) then ReplaceSubString(Result, 'd', IntToStr(day)); ReplaceSubString(Result, 'hh', StringPadLeft(IntToStr(hour), '0', 2)); ReplaceSubString(Result, 'nn', StringPadLeft(IntToStr(minute), '0', 2)); ReplaceSubString(Result, 'ss', StringPadLeft(IntToStr(second), '0', 2)); end; end; end; function TDateTimeEx.AsTz(hr, min: Integer): TDateTimeEx; var bias : TDateTime; nbias : TDateTime; begin result := self; if hr < 0 then nbias := - (-Hr * DATETIME_HOUR_ONE) + (min * DATETIME_MINUTE_ONE) else nbias := (Hr * DATETIME_HOUR_ONE) + (min * DATETIME_MINUTE_ONE); bias := timezoneBias; result.TimezoneType := dttzLocal; if FPrecision >= dtpHour then case TimezoneType of dttzUTC : result := TDateTimeEx.makeLocal(self.DateTime+nbias); dttzLocal : result := TDateTimeEx.makeLocal(TTimeZone.Local.ToUniversalTime(self.DateTime-bias)+nbias); dttzSpecified : begin if TimezoneHours < 0 then bias := - (-TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE) else bias := (TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE); result := TDateTimeEx.makeLocal(self.DateTime-bias+nbias); end; else result := self; end; result.FPrecision := FPrecision; result.FractionPrecision := FractionPrecision; result.TimezoneType := dttzSpecified; result.TimezoneHours := hr; result.TimezoneMins := min; end; function TDateTimeEx.UTC: TDateTimeEx; var bias : TDateTime; begin result := self; if FPrecision >= dtpHour then case TimezoneType of dttzLocal : result := TDateTimeEx.makeUTC(TTimeZone.Local.ToUniversalTime(self.DateTime)); dttzSpecified : begin if TimezoneHours < 0 then bias := - (-TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE) else bias := (TimezoneHours * DATETIME_HOUR_ONE) + (TimezoneMins * DATETIME_MINUTE_ONE); result := TDateTimeEx.makeUTC(self.DateTime+bias); end; else end; result.FPrecision := FPrecision; result.FractionPrecision := FractionPrecision; result.TimezoneType := dttzUTC; end; class function TDateTimeEx.makeUTC : TDateTimeEx; begin result := TDateTimeEx.makeUTC(TTimeZone.Local.ToUniversalTime(now)); end; class function TDateTimeEx.makeUTC(value: TDateTime) : TDateTimeEx; begin result := make(value, dttzUTC); end; class function TDateTimeEx.makeLocal : TDateTimeEx; begin result := TDateTimeEx.makeLocal(now); end; class function TDateTimeEx.makeLocal(value: TDateTime) : TDateTimeEx; begin result := make(value, dttzLocal); end; class function TDateTimeEx.makeNull: TDateTimeEx; begin result.clear; result.Source := ''; end; class function TDateTimeEx.makeToday: TDateTimeEx; begin result := TDateTimeEx.makeLocal(trunc(now)); result.FPrecision := dtpDay; end; class function TDateTimeEx.fromTS(value: TTimestamp; tz : TDateTimeExTimezone): TDateTimeEx; begin result.clear; result.Year := value.year; result.month := value.month; result.day := value.day; result.hour := value.hour; result.minute := value.minute; result.second := value.second; result.Fraction := value.fraction; result.FPrecision := dtpNanoSeconds; result.FractionPrecision := 0; result.TimezoneType := tz; result.Source := 'fromTS'; end; function TDateTimeEx.Equal(other: TDateTimeEx): Boolean; var src : TDateTimeEx; begin src := TDateTimeEx(other); result := (year = src.year) and ((FPrecision < dtpMonth) or (month = src.month)) and ((FPrecision < dtpDay) or (day = src.day)) and ((FPrecision < dtpHour) or (hour = src.hour)) and ((FPrecision < dtpMin) or (minute = src.minute)) and ((FPrecision < dtpSec) or (second = src.second)) and ((FPrecision < dtpNanoSeconds) or (fraction = src.fraction)) and (FPrecision = src.FPrecision) and (FractionPrecision = src.FractionPrecision) and (TimezoneType = src.TimezoneType) and (TimeZoneHours = src.TimeZoneHours) and (TimezoneMins = src.TimezoneMins); end; function TDateTimeEx.fixPrecision(FPrecision: TDateTimeExPrecision): TDateTimeEx; begin result := Self; result.FPrecision := FPrecision; end; function TDateTimeEx.SameTime(other: TDateTimeEx): Boolean; begin if (TimezoneType = dttzUnknown) or (other.TimezoneType = dttzUnknown) then result := false // unknown, really else result := sameInstant(UTC.DateTime, other.UTC.DateTime); end; function TDateTimeEx.ToString: String; begin if null then exit(''); Result := DateTimeToStr(DateTime); end; function IsAfterLastMonthDay(y, m, d : integer) : boolean; begin case m of 1: result := d > 31; 2: if IsLeapYear(y) then result := d > 29 else result := d > 28; 3: result := d > 31; 4: result := d > 30; 5: result := d > 31; 6: result := d > 30; 7: result := d > 31; 8: result := d > 31; 9: result := d > 30; 10: result := d > 31; 11: result := d > 30; 12: result := d > 31; else result := false; end; end; procedure TDateTimeEx.RollUp; begin if second >= 60 then begin inc(minute); second := 0; end; if minute >= 60 then begin inc(hour); minute := 0; end; if hour >= 24 then begin inc(day); hour := 0; end; if day > MONTHS_DAYS[IsLeapYear(Year), TMonthOfYear(month - 1)] then begin inc(month); day := 1; end; if month >= 12 then begin inc(year); month := 1; end; if month = 13 then begin inc(year); month := 1; end; end; function TDateTimeEx.subtract(length: TDateTime): TDateTimeEx; begin result := TDateTimeEx.makeUTC(dateTime - length); result.FPrecision := FPrecision; result.FractionPrecision := FractionPrecision; result.TimezoneType := TimezoneType; result.TimeZoneHours := TimeZoneHours; result.TimezoneMins := TimezoneMins; end; function TDateTimeEx.TimeStamp: TTimeStamp; begin FillChar(result, sizeof(result), 0); result.Year := year; if FPrecision >= dtpMonth then result.month := month; if FPrecision >= dtpDay then result.day := day; if FPrecision >= dtpHour then result.hour := hour; if FPrecision >= dtpMin then result.minute := minute; if FPrecision >= dtpSec then result.second := second; if FPrecision >= dtpNanoSeconds then result.Fraction := fraction; end; function TDateTimeEx.after(other : TDateTimeEx; inclusive : boolean) : boolean; var uSelf, uOther : TDateTimeEx; begin uSelf := UTC; uOther := other.UTC; if uSelf.equal(uOther) then exit(inclusive); result := (uSelf.year >= uOther.year) and (uSelf.month >= uOther.month) and (uSelf.day >= uOther.day) and (uSelf.hour >= uOther.hour) and (uSelf.minute >= uOther.minute) and (uSelf.second >= uOther.second) and (uSelf.fraction >= uOther.fraction); end; function TDateTimeEx.before(other : TDateTimeEx; inclusive : boolean):boolean; var uSelf, uOther : TDateTimeEx; begin uSelf := UTC; uOther := other.UTC; if uSelf.equal(uOther) then exit(inclusive); result := (uSelf.year <= uOther.year) and (uSelf.month <= uOther.month) and (uSelf.day <= uOther.day) and (uSelf.hour <= uOther.hour) and (uSelf.minute <= uOther.minute) and (uSelf.second <= uOther.second) and (uSelf.fraction <= uOther.fraction); end; function TDateTimeEx.between(min, max : TDateTimeEx; inclusive : boolean):boolean; begin result := after(min, inclusive) and before(max, inclusive); end; const DATETIME_FORMAT_XML = 'yyyy-mm-dd"T"hh:nn:ss'; Function DateTimeFormat(Const aDateTime : TDateTime; Const sFormat : String) : String; Begin Result := SysUtils.FormatDateTime(sFormat, aDateTime); End; Function TimeZoneBiasToString(Const aTimeZoneBias : TDateTime) : String; Begin // -10:00 etc If aTimeZoneBias < 0 Then Result := DateTimeFormat(-aTimeZoneBias, '"-"hh:nn') Else Result := DateTimeFormat(aTimeZoneBias, '"+"hh:nn'); End; Function DateTimeToXMLTimeZoneString(Const aValue : TDateTime) : String; Begin If aValue = 0 Then Result := TimeZoneBiasToString(TimeZoneBias) Else Result := TimeZoneBiasToString(aValue); End; Function DateTimeToXMLDateTimeString(Const aValue : TDateTime) : String; Begin Result := DateTimeFormat(aValue, DATETIME_FORMAT_XML); End; Function DateTimeToXMLDateTimeTimeZoneString(Const aTimestamp, aTimeZone : TDateTime) : String; Begin Result := DateTimeToXMLDateTimeString(aTimestamp) + 'T' + DateTimeToXMLTimeZoneString(aTimeZone); End; Function TimeZoneBias : TDateTime; begin result := TTimeZone.Local.GetUtcOffset(now).TotalDays; end; Function TimeZoneBias(when : TDateTime) : TDateTime; begin result := TTimeZone.Local.GetUtcOffset(when).TotalDays; end; Function DateTimeCompare(Const aA, aB : TDateTime) : Integer; Begin Result := MathSupport.RealCompare(aA, aB); End; Function DateTimeCompare(Const aA, aB, aThreshold : TDateTime) : Integer; Begin Result := MathSupport.RealCompare(aA, aB, aThreshold); End; Function DateTimeMax(Const aA, aB : TDateTime) : TDateTime; Begin If DateTimeCompare(aA, aB) > 0 Then Result := aA Else Result := aB; End; Function DateTimeMin(Const aA, aB : TDateTime) : TDateTime; Begin If DateTimeCompare(aA, aB) < 0 Then Result := aA Else Result := aB; End; function TSToDateTime(TS: TTimeStamp): TDateTime; begin with TS do Result := EncodeDate(Year, Month, Day) + EncodeTime(Hour, Minute, Second, Fraction div 1000000); end; function DateTimeToTS(Value : TDateTime): TTimeStamp; var DTYear, DTMonth, DTDay, DTHour, DTMinute, DTSecond, DTFraction: Word; begin DecodeDate(Value, DTYear, DTMonth, DTDay); DecodeTime(Value, DTHour, DTMinute, DTSecond, DTFraction); with Result do begin Year := DTYear; Month := DTMonth; Day := DTDay; Hour := DTHour; Minute := DTMinute; Second := DTSecond; Fraction := 0; // DTFraction * 1000000; end; end; const MINUTE_LENGTH = 1 / (24 * 60); SECOND_LENGTH = MINUTE_LENGTH / 60; function DescribePeriod(Period: TDateTime): String; begin if period < 0 then period := -period; if Period < SECOND_LENGTH then Result := IntToStr(trunc(Period * 1000 / SECOND_LENGTH)) + 'ms' else if Period < 180 * SECOND_LENGTH then Result := IntToStr(trunc(Period / SECOND_LENGTH)) + 'sec' else if Period < 180 * MINUTE_LENGTH then Result := IntToStr(trunc(Period / MINUTE_LENGTH)) + 'min' else if Period < 72 * 60 * MINUTE_LENGTH then Result := IntToStr(trunc(Period / (MINUTE_LENGTH * 60))) + 'hr' else Result := IntToStr(trunc(Period)) + ' days'; end; function sameInstant(t1, t2 : TDateTime) : boolean; begin result := abs(t1-t2) < DATETIME_SECOND_ONE; end; End. // DateSupport //
unit MBRTURequestF4314; {$mode objfpc}{$H+} interface uses Classes, SysUtils, MBRTURequestBase, MBRTUMasterDispatcherTypes; type { TMBRTURequestF4314 } TMBRTURequestF4314 = class(TMBRTURequestBase) private FObjectID : Byte; FObjectLen : Byte; FReadDeviceIDCode : Byte; procedure SetObjectID(AValue: Byte); procedure SetObjectLen(AValue: Byte); procedure SetReadDeviceIDCode(AValue: Byte); public constructor Create; override; procedure BuilRequest; override; procedure SetResponce(var AResponce : TMBPacket; AResponceLen : Word); override; property ReadDeviceIDCode : Byte read FReadDeviceIDCode write SetReadDeviceIDCode; property ObjectID : Byte read FObjectID write SetObjectID; property ObjectLen : Byte read FObjectLen write SetObjectLen; end; implementation uses CRC16Func, LoggerItf, MBRTUMasterDispatcherResStr; { TMBRTURequestF4314 } constructor TMBRTURequestF4314.Create; begin inherited Create; MBFunc := 43; FReadDeviceIDCode := $01; FObjectID := $00; FObjectLen := $00; end; procedure TMBRTURequestF4314.SetObjectID(AValue: Byte); begin if FObjectID=AValue then Exit; FObjectID:=AValue; end; procedure TMBRTURequestF4314.SetObjectLen(AValue: Byte); begin if FObjectLen=AValue then Exit; FObjectLen:=AValue; end; procedure TMBRTURequestF4314.SetReadDeviceIDCode(AValue: Byte); begin if FReadDeviceIDCode=AValue then Exit; FReadDeviceIDCode:=AValue; end; procedure TMBRTURequestF4314.BuilRequest; begin SetLength(FRequest,7); FillByte(FRequest[0],Length(FRequest),0); FRequest[0] := DevNum; FRequest[1] := MBFunc; FRequest[2] := $0E; FRequest[3] := FReadDeviceIDCode; FRequest[4] := FObjectID; PWord(@FRequest[5])^ := GetCRC16(@FRequest[0],Length(FRequest)-2); FResponceSize := 0; end; procedure TMBRTURequestF4314.SetResponce(var AResponce: TMBPacket; AResponceLen: Word); begin try // посылаем данные на обработку if IsValidResponce(AResponce, AResponceLen) then CallBackItf.Process4314ResultPackage(MBFunc, $0E, PByteArray(@AResponce[3])^, AResponceLen - 5); except on E : Exception do begin SendLogMessage(llError,rsF4314SetResp,Format(rsErrSendResp,[E.Message])); end; end; end; end.
unit addSignurDevice_f_withBluetooth; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, menu_f, Menus, StdCtrls, Buttons, ExtCtrls, cxLookAndFeelPainters, cxButtons, cxControls, cxContainer, cxListBox, tvc_u, ComCtrls, Grids, DBGrids, cxMaskEdit, cxDropDownEdit, cxTextEdit, cxEdit, cxMemo, Spin, cxSpinEdit, cxDBEdit; type TAddSignurDeviceForm = class(TMenuForm) N3: TMenuItem; Label1: TLabel; Label2: TLabel; cxButton1: TcxButton; btnSave: TcxButton; Label3: TLabel; eksp_header: TcxTextEdit; Theme: TcxComboBox; Author: TcxComboBox; Label5: TLabel; Device_CB: TcxComboBox; PageControl1: TPageControl; TabSheetModem: TTabSheet; TabSheetMOdbus: TTabSheet; Tone_Pulse: TRadioGroup; Label8: TLabel; Access: TcxComboBox; Phone_Number: TcxTextEdit; Label6: TLabel; Label9: TLabel; lbBdr: TLabel; lbParity: TLabel; TabSheet1: TTabSheet; memo: TcxMemo; ModBus_address: TcxSpinEdit; cbBDR: TcxComboBox; cbParity: TcxComboBox; Label4: TLabel; device_Number: TcxMaskEdit; Label_Tone: TLabel; Label_pulse: TLabel; rgAccess: TRadioGroup; TabSheetBlueTooth: TTabSheet; Label7: TLabel; BLUETOOTH_PIN: TcxSpinEdit; // procedure LBClick(Sender: TObject); procedure cxButton1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure ModBusClick(Sender: TObject); procedure ModemClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure modbus_addressPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure Tone_PulseClick(Sender: TObject); procedure rgAccessClick(Sender: TObject); private { Private declarations } public { Public declarations } SignalShapka: TSignalShapka; FilterIndex:integer; ID:integer; end; var AddSignurDeviceForm: TAddSignurDeviceForm; implementation uses config, DM_dm, Main_f; {$R *.dfm} procedure TAddSignurDeviceForm.cxButton1Click(Sender: TObject); begin inherited; close; end; procedure TAddSignurDeviceForm.FormShow(Sender: TObject); begin inherited; dm.GetStringsFromQuery(dm.sql,theme.Properties.Items,'select distinct eksp_theme as theme from eksp where (( eksp_proc = 0 ) or ( eksp_proc >2 ) ) and (id_uplevel=-1) and (hide = 0) ', 'theme'); dm.GetStringsFromQuery(dm.sql,author.Properties.Items,'select distinct eksp_author as author from eksp where (( eksp_proc = 0 ) or ( eksp_proc >2 ) ) and (id_uplevel=-1) and (hide = 0) ', 'author'); dm.GetStringsObjectsFromQuery(dm.sql, device_CB.Properties.Items,'select device_Name, id_Device from devices where not device_type is null ', 'device_name', 'ID_Device'); // Importclick(nil); end; procedure TAddSignurDeviceForm.btnSaveClick(Sender: TObject); var i:integer; begin inherited; if ((rgAccess.itemindex=2) and (ModBus_address.value > 247) or (ModBus_address.value <1)) then begin showmessage('Ошибка ввода адреса ModBus. Адреc должен быть в пределах от 1 до 247'); modalresult:=mrNone; exit; end; if trim(device_number.text)='' then begin showmessage('Вы не задали заводской номер прибора'); modalresult:=mrNone; exit; end; if trim(Device_CB.text)='' then begin showmessage('Задайте тип прибора'); modalresult:=mrNone; exit; end; dm.q.sql.clear; dm.q.sql.add('select count(*) as cnt from eksp where device_number = :device_Number and id_device = :id_device and hide=0'); dm.q.parambyname('device_Number').asinteger:= strtoint(trim(Device_Number.text)); dm.q.parambyname('id_device').asinteger:= integer(Device_CB.Properties.Items.objects[device_CB.itemindex]); dm.q.Open; if dm.q.FieldByName('cnt').asinteger<>0 then begin showmessage('Заводской номер прибора должен быть уникальным для приборов данного типа'); modalresult:=mrNone; exit; end; dm.q.close; if trim(eksp_Header.text)='' then begin if messagedlg('Вы не задали наименование прибора. Предложено наименование на основе типа и номера: '+ device_cb.text+' №'+device_number.text, mtConfirmation, [mbYes, mbNo], 0) = mrNo then begin modalresult:=mrNone; exit; end else eksp_Header.text:=device_cb.text+' №'+device_number.text; end; try dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_THEME').asstring:=theme.text; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_Date').asdatetime:=now; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_Time').asdatetime:=time; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_Header').asstring:=trim(eksp_Header.text); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_Author').asstring:=Author.Text; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_memo').asstring:=memo.text; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_SignalSource').asstring:=''; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('EKSP_SOURCEFILE').asstring:=''; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('ModBus_address').asinteger:=(ModBus_address.value); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('modBus').asinteger:=integer(rgAccess.Itemindex=2); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('BDR').asinteger:=(cbBDR.itemindex); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('ParityControl').asinteger:=(cbParity.itemindex); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('Phone_Number').asstring:=trim(Phone_Number.text); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('modem').asinteger:=integer(rgAccess.Itemindex=1); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('Tone_Pulse').asinteger:=Tone_Pulse.ItemIndex; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('Access').asinteger:=Access.ItemIndex; dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('ID_Device').asinteger:=integer(Device_CB.Properties.Items.objects[device_CB.itemindex]); dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('Device_Number').asinteger:=strtoint(trim(Device_Number.text)); dm.CREATE_EKSP_AND_DEVICEPARAM.ExecProc; Id:=dm.CREATE_EKSP_AND_DEVICEPARAM.ParamByName('ID').asinteger; if rgAccess.ItemIndex =3 then begin dm.q.sql.clear; dm.q.sql.add('update eksp set BlueTooth=1, BlueTooth_pin=:BlueTooth_pin where eksp_nomer = :eksp_nomer '); dm.q.parambyname('eksp_nomer').asinteger:=id; dm.q.parambyname('BlueTooth_pin').asinteger:=BlueTooth_pin.Value; dm.q.ExecSQL; end; dm.q.sql.clear; dm.q.sql.add('insert into signals'); dm.q.sql.add(' ( EKSP_NOMER, EKSP_PARENT, CHANAL_NOMER,'); dm.q.sql.add(' CHANAL_HEADER, DELTX , NAMEX, NAMEY, RAZMX, RAZMY,'); dm.q.sql.add(' MULTX, MULTY, MAXX, MAXY ,'); dm.q.sql.add(' MINX , MINY , DATE_START , TIME_START,'); dm.q.sql.add(' POINTALL,BMAXMINX, BMAXMINY, FILEDAT, REZTYPE,'); dm.q.sql.add(' REZLENGTH , A0 ,A1 , A2 ,A3 ,SIGNALMEMO , SIGNAL_SELECTED ,FILE_SEEK, datetimestart)'); dm.q.sql.add(' values ( :EKSP_NOMER, :EKSP_PARENT, :CHANAL_NOMER,'); dm.q.sql.add(' :CHANAL_HEADER, :DELTX , :NAMEX, :NAMEY, :RAZMX, :RAZMY,'); dm.q.sql.add(' :MULTX, :MULTY, :MAXX, :MAXY ,'); dm.q.sql.add(' :MINX , :MINY , :DATE_START , :TIME_START,'); dm.q.sql.add(' :POINTALL,:BMAXMINX, :BMAXMINY, :FILEDAT, :REZTYPE,'); dm.q.sql.add(' :REZLENGTH , 0 ,1 , 0 ,0 ,:SIGNALMEMO , 1 ,0, :datetimestart)'); dm.q.parambyname('eksp_nomer').asinteger:=ID; dm.q.parambyname('eksp_Parent').asinteger:=ID; dm.q.parambyname('RezType').asinteger:=cRealLong; dm.q.parambyname('RezLength').asinteger:=sizeof(Single); for i:=0 to 1 do begin dm.q.parambyname('Chanal_Nomer').asinteger:=i+1; case i of 0:dm.q.parambyname('Chanal_Header').asstring:='Ah'; 1:dm.q.parambyname('Chanal_Header').asstring:='Ad'; end; case i of 0:dm.q.parambyname('DeltX').asfloat:=3600; 1:dm.q.parambyname('DeltX').asfloat:=3600*24; end; dm.q.parambyname('NameX').asstring:='t'; case i of 0:dm.q.parambyname('NameY').asstring:='Ah'; 1:dm.q.parambyname('NameY').asstring:='Ad'; end; dm.q.parambyname('RazmX').asstring:='сек'; dm.q.parambyname('RazmY').asstring:='куб.м'; dm.q.parambyname('MinX').asfloat:=0; dm.q.parambyname('MinY').asfloat:=0; dm.q.parambyname('MaxX').asfloat:=1; dm.q.parambyname('MaxY').asfloat:=1; dm.q.parambyname('DateTimeStart').asfloat:=now; dm.q.parambyname('Date_Start').asdatetime:=now; dm.q.parambyname('Time_Start').asDatetime:=now; dm.q.parambyname('PointAll').asinteger:=1; dm.q.parambyname('bmaxMinX').asinteger:=integer(false); dm.q.parambyname('bmaxMinY').asinteger:=integer(false); dm.q.parambyname('Filedat').asstring:={dm.ActiveStoragepath + }GetGuidStr+'.sgnr'; dm.q.parambyname('SignalMemo').asstring:=''; dm.q.execSQL; end; dm.CREATE_EKSP_AND_DEVICEPARAM.Transaction.CommitRetaining; except on e:exception do begin showmessage('Ошибка при регистрации. Описание и код ошибки: '+e.message); dm.CREATE_EKSP_AND_DEVICEPARAM.Transaction.RollbackRetaining; modalresult:=mrNone; exit; end; end; end; procedure TAddSignurDeviceForm.ModBusClick(Sender: TObject); begin inherited; { IF MODBUS.Checked THEN begin MODEM.CHECKED:=FALSE;RS232.checked:=false;end; TabsheetModem.TabVisible:=modem.checked; TabsheetModbus.TabVisible:=modbus.checked; if modbus.checked then Pagecontrol1.ActivePage:=TabsheetModbus;} end; procedure TAddSignurDeviceForm.ModemClick(Sender: TObject); begin inherited; { IF MODEM.Checked THEN begin MODBUS.CHECKED:=FALSE; RS232.checked:=false;end; TabsheetModem.TabVisible:=modem.checked; TabsheetModbus.TabVisible:=modbus.checked; if modem.checked then Pagecontrol1.ActivePage:=TabsheetModem; } end; procedure TAddSignurDeviceForm.FormCreate(Sender: TObject); begin inherited; TabsheetModem.TabVisible:=false ; TabsheetModbus.TabVisible:=false; TabsheetBlueTooth.TabVisible:=false; end; procedure TAddSignurDeviceForm.modbus_addressPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; if ((displayvalue > 247) or (displayValue<1)) then errortext:='Ошибка ввода адреса. Адреc должен быть в пределах от 1 до 247'; end; procedure TAddSignurDeviceForm.Tone_PulseClick(Sender: TObject); begin inherited; Label_tone.Visible:=tone_pulse.ItemIndex=1; Label_pulse.Visible:=tone_pulse.ItemIndex=0; end; procedure TAddSignurDeviceForm.rgAccessClick(Sender: TObject); begin inherited; TabsheetModem.TabVisible:=rgAccess.itemindex=1; TabsheetModbus.TabVisible:=rgAccess.itemindex=2; TabsheetBlueTooth.TabVisible:=rgAccess.itemindex=3; case rgAccess.itemindex of 1: Pagecontrol1.ActivePage:=TabsheetModem; 2: Pagecontrol1.ActivePage:=TabsheetModbus; 3: Pagecontrol1.ActivePage:=TabsheetBlueTooth; end; end; end.
unit UDialogFunctions; interface type TDialogFunctions = class published class function OpenDialog(const Title, Filter, DefaultExt: string; var FileName: string): Boolean; class function SaveDialog(const Title, Filter, DefaultExt: string; var FileName: string): Boolean; end; implementation uses Dialogs; { TDialogFunctions } class function TDialogFunctions.OpenDialog(const Title, Filter, DefaultExt: string; var FileName: string): Boolean; var objDialog: TOpenDialog; begin objDialog := TOpenDialog.Create(nil); try objDialog.DefaultExt := DefaultExt; objDialog.FileName := FileName; objDialog.Filter := Filter; objDialog.Title := Title; Result := objDialog.Execute(); if Result then FileName := objDialog.FileName; finally objDialog.Free; end; end; class function TDialogFunctions.SaveDialog(const Title, Filter, DefaultExt: string; var FileName: string): Boolean; var objDialog: TSaveDialog; begin objDialog := TSaveDialog.Create(nil); try objDialog.DefaultExt := DefaultExt; objDialog.FileName := FileName; objDialog.Filter := Filter; objDialog.Title := Title; Result := objDialog.Execute(); if Result then FileName := objDialog.FileName; finally objDialog.Free; end; end; end.
unit test_ucPipe; (* Copyright (c) 2000-2018 HREF Tools Corp. Permission is hereby granted, on 18-Jun-2017, free of charge, to any person obtaining a copy of this file (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) interface {$I hrefdefines.inc} { Master copy of hrefdefines.inc is versioned on Source Forge in the ZaphodsMap project: https://sourceforge.net/p/zaphodsmap/code/HEAD/tree/trunk/ZaphodsMap/Source/hrefdefines.inc } {$Define HAVE_UNICONSOLE} // little utility that writes Ansi, UTF8 and UTF16 uses SysUtils, DUnitX.TestFrameWork, {$IFDEF CodeSite}ZM_CodeSiteInterface,{$ENDIF} ucPipe; type [TestFixture] TTest_ucPipe = class(TObject) private Houses8: UTF8String; Houses16: UnicodeString; FTemp16: TByteArray; FTemp16ByteCount: Integer; procedure AssembleUTF16(var Data: TLittleBuffer; const ByteCount: Integer); public [Setup] procedure SetUp; public [Test] procedure Test_ucPipe_DefaultCodePage; [Test] procedure Test_ucPipe_Pos_Unicode; [Test] procedure Test_ucPipe_Delphi_Raw_CastAs_UTF8; [Test] procedure Test_ucPipe_GetDosOutput_UTF16Directory; public FMiddleDot8: UTf8String; {$IFDEF HAVE_UNICONSOLE} // Requires UniConsole.exe [Test] procedure Test_ucPipe_GetDosOutput_UTF8_UniConsole; [Test] procedure Test_ucPipe_GetDosOutput_UTF16_UniConsole; [Test] procedure Test_ucPipe_GetDosOutput_Bat_UniConsole; {$ENDIF} {$IFDEF MSWINDOWS} public // Ansi Windows Only [Test] procedure Test_ucPipe_Pos_Ansi; {$IFDEF HAVE_UNICONSOLE} // Requires UniConsole.exe [Test] procedure Test_ucPipe_GetDosOutput_Ansi_UniConsole; {$ENDIF} [Test] procedure Test_ucPipe_GetDosOutput_AnsiDirectory; {$ENDIF} end; implementation uses {$IFDEF CodeSite}CodeSiteLogging,{$ENDIF} {$IFDEF MSWINDOWS}Windows,{$ENDIF} // to avoid DCC Hint about inline function Math, WideStrUtils, Character, {$IFDEF MSWINDOWS}ucStringWinAnsi,{$ENDIF} ucLogFil, uFileIO_Helper, uDUnitX_Logging_Helper, uZM_Lingvo_Helper; {$IFDEF MSWINDOWS} type LatinStr = type AnsiString(1252); const cHauserDeu: LatinStr = 'Häuser'; {$ENDIF} const cMiddleDot = #$2E31; { TTest_ucPipe } procedure TTest_ucPipe.AssembleUTF16( var Data: TLittleBuffer; const ByteCount: Integer); begin // This could be done for old-Delphi but not important enough. Move(Data, FTemp16[FTemp16ByteCount], ByteCount); FTemp16ByteCount := FTemp16ByteCount + ByteCount; end; procedure TTest_ucPipe.SetUp; begin FMiddleDot8 := UTF8String(cMiddleDot); Houses8 := Houses_DE_8; Houses16 := Houses_DE; end; procedure TTest_ucPipe.Test_ucPipe_DefaultCodePage; begin Assert.AreEqual(1252, DefaultSystemCodePage, 'Assert.isTrue -codepage on dcc cmd line'); end; procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_AnsiDirectory; var SAnsi: AnsiString; CommandStrAnsi: AnsiString; ErrorCode: Integer; const cDirectoryTest = 'directory_ansi_test.utx'; begin {$WARNINGS OFF} CommandStrAnsi := AnsiString(GetEnvironmentVariable('windir') + AnsiString('\system32\cmd.exe /A /c dir /S')); // NB: /A means Ansi {$WARNINGS OFF} SAnsi := GetDosOutputA(CommandStrAnsi, nil, ErrorCode); Assert.AreEqual(ErrorCode, 0, 'GetDosOutputA non-zero error code'); Assert.isTrue(SAnsi <> ''); StringWriteToFile(cDirectoryTest, SAnsi); Assert.isTrue(Pos('Directory of', SAnsi) > 0, 'The following does not appear to be a Directory listing: ' + SAnsi); DeleteFile(cDirectoryTest); end; procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_UTF16Directory; const cFn = 'Test_ucPipe_GetDosOutput_UTF16Directory'; var APath: string; S16: UnicodeString; ErrorCode: Integer; SRaw: RawByteString; RussianWord: string; n: Integer; InfoMsg: string; const cDirectoryTest = 'directory_test.utx'; begin {$IFDEF CodeSite}CSEnterMethod(Self, cFn);{$ENDIF} FTemp16ByteCount := 0; FTemp16[0] := 0; APath := Unicode_Test_Data_Path; //'..\..\..\..\..\Externals\ZM_TestDataFiles\UniData\'; {$IFDEF CodeSite} CSSend(APath + 'chinese.utx', S(FileExists(APath + 'chinese.utx'))); {$ENDIF} Assert.IsTrue(FileExists(APath + 'chinese.utx'), 'APath required; adjust the TempBuild output to match up with other tests'); // This does not display any Russian filenames on USA Windows 7. SRaw := GetDosOutput(GetEnvironmentVariable('windir') + '\system32\cmd.exe', '/U /c dir ' + //NB: /U Unicode APath, '', AssembleUTF16, ErrorCode); DUnit_Log('SRaw', SRaw); Assert.AreEqual(0, ErrorCode, 't01: ' + SysErrorMessage(ErrorCode)); // NB: SRaw contains garbage because it is really an AnsiString n := FTemp16ByteCount div SizeOf(WideChar); SetLength(S16, n); // This works to turn an array of bytes into a UnicodeString 28-July-2011 Move(FTemp16[0], S16[1], FTemp16ByteCount); Assert.AreNotEqual('', S16, 't02'); DUnit_Log('S16', S16); Assert.isTrue(Pos('Directory of', S16) > 0, 't03: The following does not appear to be a Directory listing: ' + S16); Assert.isTrue(Pos('houses', S16) > 0, 't04: Did not list the file named [houses.utx]: ' + S16); Assert.isTrue(Pos(Houses_DE, S16) > 0, 't05: Did not list the file named [Häuser.utx]: ' + S16); RussianWord := Welcome_in_Russian; // see DUnitX files in ZaphodsMap project RussianWord := StringReplace(RussianWord, ' ', '_', [rfReplaceAll]); { June 2017. Windows 10 Pro insists on capitalizing the first letter of the Russian filename. } Assert.AreNotEqual(0, Length(RussianWord)); RussianWord[Low(RussianWord)] := RussianWord[Low(RussianWord)].ToUpper; InfoMsg := 'Directory output did not list the file named [' + RussianWord + '] in ' + S16; if Pos(RussianWord, S16) = 0 then DUnit_Log('InfoMsg', InfoMsg); Assert.AreNotEqual(0, Pos(RussianWord, S16), 't06: ' + InfoMsg); DeleteFile(cDirectoryTest); {$IFDEF CodeSite}CSExitMethod(Self, cFn);{$ENDIF} end; {$IFDEF HAVE_UNICONSOLE} procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_Ansi_UniConsole; var SAnsi: Latinstr; ErrorCode: Integer; x: Integer; const cTestFile = 'uniconsole_ansi.txt'; begin SAnsi := GetDosOutputA('UniConsole.exe /ansi', nil, ErrorCode); StringWriteToFile(cTestFile, SAnsi); Assert.AreEqual(0, ErrorCode, 'ansi: ' + SysErrorMessage(ErrorCode)); Assert.isTrue(SAnsi <> ''); X := Pos(LatinStr('text:') + cHauserDeu, SAnsi); Assert.isTrue(X > 0, 'text:' + Houses_DE + 'NOT found in: ' + AnsiCodePageToUnicode(SAnsi, 1252)); DeleteFile(cTestFile); end; procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_Bat_UniConsole; const cFn = 'Test_ucPipe_GetDosOutput_Bat_UniConsole'; var SRaw: RawByteString; S8: UTF8String; ErrorCode: Integer; begin {$IFDEF CodeSite}CSEnterMethod(Self, cFn);{$ENDIF} {$IFDEF MSWINDOWS} SRaw := GetDosOutput('run-uniconsole-utf8.bat', '', GetCurrentDir + '\..\..\..\..\..\UniConsole\', nil, ErrorCode); S8 := SRaw; {$IFDEF CodeSite}CSSend('S8', string(S8));{$ENDIF} Assert.AreNotEqual(0, Pos('utf8', S8), string(S8)); {$ENDIF} {$IFDEF CodeSite}CSExitMethod(Self, cFn);{$ENDIF} end; {$ENDIF} {$IFDEF HAVE_UNICONSOLE} procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_UTF8_UniConsole; const cFn = 'Test_ucPipe_GetDosOutput_UTF8_UniConsole'; var S8: UTF8String; SRaw: RawByteString; SUni: UnicodeString; ErrorCode: Integer; x: Integer; const cTestFile = 'uniconsole_utf8.utx'; begin {$IFDEF CodeSite}CSEnterMethod(Self, cFn);{$ENDIF} Assert.IsTrue(FileExists('UniConsole.exe'), 'File does NOT exist in ' + GetCurrentDir + ' : uniconsole.exe'); // NB: much depends on how UniConsole.exe was compiled. SRaw := GetDosOutput('UniConsole.exe', '-utf8', '', nil, ErrorCode); DUnit_Log('SRaw', string(SRaw)); S8 := SRaw; // do not convert. just assign to a UTF8String. DUnit_Log('S8', string(S8)); UTF8StringWriteToFile(cTestFile, S8); Assert.AreEqual(0, ErrorCode, 'utf8: ' + SysErrorMessage(ErrorCode)); Assert.AreNotEqual(UTF8String(''), S8); SUni := string(S8); x := Pos(UnicodeString('text:' + Houses16), SUni); DUnit_Log('x', x.ToString); Assert.AreNotEqual(0, x, 'text:' + Houses16 + ' NOT found in ' + SUni); DeleteFile(cTestFile); {$IFDEF CodeSite}CSExitMethod(Self, cFn);{$ENDIF} end; {$ENDIF} {$IFDEF MSWINDOWS} procedure TTest_ucPipe.Test_ucPipe_Pos_Ansi; var x: Integer; begin x := Pos(cHauserDeu, UnicodeToAnsiCodePage('text:' + Houses_DE + cMiddleDot, 1252)); Assert.isTrue(x > 0, Format('x is %d', [x])); end; {$ENDIF} procedure TTest_ucPipe.Test_ucPipe_Pos_Unicode; var x: Integer; begin x := Pos(Houses16, 'text:' + Houses16); Assert.AreNotEqual(0, x); end; procedure TTest_ucPipe.Test_ucPipe_Delphi_Raw_CastAs_UTF8; {$IFDEF MSWINDOWS} var S8, S8FromAnsi, S8FromRaw: UTF8String; SRaw: RawByteString; SAnsi: AnsiString; begin SAnsi := cHauserDeu; SRaw := cHauserDeu; Assert.AreEqual(RawByteString(SAnsi), SRaw); S8 := AnsiToUTF8Ex(cHauserDeu, 1252); S8FromAnsi := AnsiToUTF8Ex(SAnsi, 1252); Assert.AreEqual(S8, S8FromAnsi, 'Delphi, convert from ansi'); S8FromRaw := AnsiToUTF8Ex(SAnsi, 1252); Assert.AreEqual(S8, S8FromRaw, 'Delphi, convert from raw'); S8FromRaw := UTF8String(SRaw); // should not alter data Assert.isTrue(S8 <> S8FromRaw, 'See S8FromRaw; Delphi cast via UTF8String'); {$ELSE} begin {$ENDIF} end; {$IFDEF HAVE_UNICONSOLE} procedure TTest_ucPipe.Test_ucPipe_GetDosOutput_UTF16_UniConsole; var S16: UnicodeString; SRaw: RawByteString; i: Integer; ErrorCode: Integer; x: Integer; const cTestFile = 'uniconsole_utf16.utx'; begin SRaw := GetDosOutput('UniConsole.exe', '/utf16', '', nil, ErrorCode); Assert.AreEqual(0, ErrorCode, 'utf16: ' + SysErrorMessage(ErrorCode)); Assert.isTrue(SRaw <> ''); for i := 1 to Length(SRaw) do if SRaw[i] <> #0 then S16 := S16 + Char(SRaw[i]); x := Pos('text:' + Houses16, S16); Assert.isTrue(X > 0, 'Not found in ' + S16); DeleteFile(cTestFile); end; {$ENDIF} initialization TDUnitX.RegisterTestFixture(TTest_ucPipe); end.
unit TXAN.App; {$IFDEF FPC} {$mode delphi} {$ENDIF} interface uses SysUtils, Classes, JPL.Strings, JPL.TStr, JPL.Conversion, JPL.Console, JPL.ConsoleApp, JPL.CmdLineParser, JPL.FileSearcher, JPL.TimeLogger, JPL.Files, TXAN.Types; type TApp = class(TJPConsoleApp) private AppParams: TAppParams; FList: TStringList; FStats: TTotalStats; FGithubUrl: string; public procedure Init; procedure Run; procedure Done; procedure RegisterOptions; procedure ProcessOptions; procedure PerfromTasks; procedure ProcessFileList; procedure ProcessFile(const FileName: string; var fs: TFileStats); procedure DisplaySummary; procedure DisplayHelpAndExit(const ExCode: integer); procedure DisplayShortUsageAndTerminate(const Msg: string; const ExCode: integer); procedure DisplayShortUsageAndExit(const Msg: string; const ExCode: integer); procedure DisplayBannerAndExit(const ExCode: integer); procedure DisplayMessageAndExit(const Msg: string; const ExCode: integer); end; implementation {$region ' Init '} procedure TApp.Init; begin //---------------------------------------------------------------------------- AppName := 'TxtAn'; MajorVersion := 1; MinorVersion := 0; Date := EncodeDate(2021, 9, 20); FullNameFormat := '%AppName% %MajorVersion%.%MinorVersion% [%OSShort% %Bits%-bit] (%AppDate%)'; Description := 'The program counts the lines of text in the given text files.'; LicenseName := 'Freeware, OpenSource'; Author := 'Jacek Pazera'; HomePage := 'https://www.pazera-software.com/products/text-analyzer/'; FGithubUrl := 'https://github.com/jackdp/TxtAn'; //HelpPage := HomePage; //----------------------------------------------------------------------------- TryHelpStr := ENDL + 'Try "' + ExeShortName + ' --help for more info.'; ShortUsageStr := ENDL + 'Usage: ' + ExeShortName + ' FILES [-ifsl] [-idsl] [-r=[X]] [-s] [-h] [-V] [--github]' + ENDL + ENDL + 'Mandatory arguments to long options are mandatory for short options too.' + ENDL + 'Options are <color=cyan>case-sensitive</color>. Options in square brackets are optional.' + ENDL + 'All parameters that do not start with the "-" or "/" sign are treated as <color=yellow>file names/masks</color>.' + ENDL + 'Options and input files can be placed in any order, but -- (double dash)' + ENDL + 'indicates the end of parsing options and all subsequent parameters are treated as file names/masks.' + ENDL + ENDL + 'FILES - any combination of file names/masks.'; //------------------------------------------------------------------------------ SetLength(AppParams.FileMasks, 0); AppParams.IgnoreFileSymLinks := True; AppParams.IgnoreDirSymLinks := True; AppParams.RecursionDepth := 50; AppParams.Silent := False; AppParams.ShowSummary := True; FStats.Clear; FList := TStringList.Create; end; {$endregion Init} procedure TApp.Done; begin FList.Free; SetLength(AppParams.FileMasks, 0); end; {$region ' Run '} procedure TApp.Run; begin inherited; RegisterOptions; Cmd.Parse; ProcessOptions; if Terminated then Exit; PerfromTasks; // <----- the main procedure end; {$endregion Run} {$region ' RegisterOptions '} procedure TApp.RegisterOptions; const MAX_LINE_LEN = 120; var Category: string; begin Cmd.CommandLineParsingMode := cpmCustom; Cmd.UsageFormat := cufWget; Cmd.AcceptAllNonOptions := True; // non options = file masks // ------------ Registering command-line options ----------------- Category := 'inout'; Cmd.RegisterOption('ifsl', 'ignore-file-symlinks', cvtNone, False, False, 'Ignore symbolic links to files.', '', Category); Cmd.RegisterOption('idsl', 'ignore-dir-symlinks', cvtNone, False, False, 'Ignore symbolic links to directories.', '', Category); Cmd.RegisterOption( 'r', 'recurse-depth', cvtOptional, False, False, 'Recurse subdirectories. X - recursion depth (def. X = ' + itos(AppParams.RecursionDepth) + ')', 'X', Category ); Cmd.RegisterOption('s', 'silent', cvtNone, False, False, 'Only display a summary (no details).', '', Category); Category := 'info'; Cmd.RegisterOption('h', 'help', cvtNone, False, False, 'Show this help.', '', Category); Cmd.RegisterShortOption('?', cvtNone, False, True, '', '', ''); Cmd.RegisterOption('V', 'version', cvtNone, False, False, 'Show application version.', '', Category); Cmd.RegisterLongOption('github', cvtNone, False, False, 'Opens source code repository on the GitHub.', '', Category); UsageStr := ENDL + 'Input/output:' + ENDL + Cmd.OptionsUsageStr(' ', 'inout', MAX_LINE_LEN, ' ', 30) + ENDL + ENDL + 'Info:' + ENDL + Cmd.OptionsUsageStr(' ', 'info', MAX_LINE_LEN, ' ', 30); end; {$endregion RegisterOptions} {$region ' ProcessOptions '} procedure TApp.ProcessOptions; var i: integer; s: string; xb: Byte; begin // ---------------------------- Invalid options ----------------------------------- if Cmd.ErrorCount > 0 then begin DisplayShortUsageAndExit(Cmd.ErrorsStr, CON_EXIT_CODE_SYNTAX_ERROR); Exit; end; //------------------------------------ Help --------------------------------------- if (ParamCount = 0) or (Cmd.IsLongOptionExists('help')) or (Cmd.IsOptionExists('?')) then begin DisplayHelpAndExit(CON_EXIT_CODE_OK); Exit; end; //---------------------------------- Home ----------------------------------------- //if Cmd.IsLongOptionExists('home') then GoToHomePage; // and continue if Cmd.IsLongOptionExists('github') then begin GoToUrl(FGithubUrl); Exit; end; //------------------------------- Version ------------------------------------------ if Cmd.IsOptionExists('version') then begin DisplayBannerAndExit(CON_EXIT_CODE_OK); Exit; end; // --------------- Silent ----------------- AppParams.Silent := Cmd.IsOptionExists('s'); // -------------- Recursion ----------------- if Cmd.IsOptionExists('r') then begin s := Cmd.GetOptionValue('r', ''); if s <> '' then begin if not TryStrToByte(s, xb) then begin DisplayError('The recursion depth should be an integer between 0 and 255.'); Exit; end; AppParams.RecursionDepth := xb; end; end; // --------------------- Errors ----------------------- if Cmd.ErrorCount > 0 then begin DisplayShortUsageAndTerminate(Cmd.ErrorsStr, CON_EXIT_CODE_SYNTAX_ERROR); Exit; end; // ---------------------- file masks ------------------------- if Cmd.UnknownParamCount > 0 then begin SetLength(AppParams.FileMasks, Cmd.UnknownParamCount); for i := 0 to Cmd.UnknownParamCount - 1 do AppParams.FileMasks[i] := Cmd.UnknownParams[i].ParamStr; end; if Length(AppParams.FileMasks) = 0 then begin DisplayError('At least one file mask was expected!'); Terminate; end; end; {$endregion ProcessOptions} {$region ' Main task '} procedure TApp.PerfromTasks; var i: integer; fs: TJPFileSearcher; Mask: string; begin if Terminated then Exit; if Length(AppParams.FileMasks) = 0 then Exit; TTimeLogger.StartLog; fs := TJPFileSearcher.Create; try fs.FileInfoMode := fimOnlyFileNames; fs.AcceptDirectorySymLinks := not AppParams.IgnoreDirSymLinks; fs.AcceptFileSymLinks := not AppParams.IgnoreFileSymLinks; for i := 0 to High(AppParams.FileMasks) do begin Mask := AppParams.FileMasks[i]; fs.AddInput(Mask, AppParams.RecursionDepth); end; fs.Search; if fs.OutputCount = 0 then begin DisplayHint('No files found'); Exit; end; fs.GetFileList(FList); ProcessFileList; FList.Clear; finally fs.Free; end; TTimeLogger.EndLog; AppParams.ElapsedTimeStr := TTimeLogger.ElapsedTimeStr; if AppParams.ShowSummary then DisplaySummary; end; procedure TApp.ProcessFileList; var i, xFileNo: integer; fName, sCount: string; fs: TFileStats; begin if FList.Count = 0 then Exit; sCount := IntToStrEx(FList.Count); if not AppParams.Silent then Writeln('Files: ' + sCount); xFileNo := 0; for i := 0 to FList.Count - 1 do begin fName := FList[i]; if not FileExists(fName) then Continue; Inc(xFileNo); fs.Clear; if not AppParams.Silent then TConsole.WriteTaggedTextLine( 'Processing file ' + IntToStrEx(i + 1) + ' / ' + sCount + ': <color=yellow>' + fName + '</color>' ); ProcessFile(fName, fs); FStats.AddFileStats(fs); if not AppParams.Silent then begin Writeln('File size: ' + GetFileSizeString(fs.FileSize)); Writeln('Lines: ' + IntToStrEx(fs.Lines)); Writeln('Blank lines: ' + IntToStrEx(fs.BlankLines)); Writeln('Not blank lines: ' + IntToStrEx(fs.NotBlankLines)); Writeln(''); end; end; end; procedure TApp.ProcessFile(const FileName: string; var fs: TFileStats); var sl: TStringList; i: integer; Line: string; begin sl := TStringList.Create; try fs.FileSize := FileSizeInt(FileName); sl.LoadFromFile(FileName); fs.Lines += sl.Count; for i := 0 to sl.Count - 1 do begin Line := sl[i]; // or Trim(sl[i]); if Line = '' then fs.BlankLines += 1 else fs.NotBlankLines += 1; end; finally sl.Free; end; end; procedure TApp.DisplaySummary; begin if FStats.Files = 0 then Exit; Writeln('Command line: ' + CmdLine); Writeln('Processed files: ' + IntToStrEx(FStats.Files)); Writeln('Total size: ' + GetFileSizeString(FStats.TotalSize)); Writeln('Elapsed time: ' + AppParams.ElapsedTimeStr); Writeln('All lines: ' + IntToStrEx(FStats.Lines)); Writeln('All blank lines: ' + IntToStrEx(FStats.BlankLines)); TConsole.WriteTaggedTextLine('All not blank lines:<color=white,darkblue> ' + IntToStrEx(FStats.NotBlankLines) + ' </color>'); end; {$endregion Main task} {$region ' Display... procs '} procedure TApp.DisplayHelpAndExit(const ExCode: integer); begin DisplayBanner; DisplayShortUsage; DisplayUsage; DisplayExtraInfo; ExitCode := ExCode; Terminate; end; procedure TApp.DisplayShortUsageAndTerminate(const Msg: string; const ExCode: integer); begin if Msg <> '' then begin if (ExCode = CON_EXIT_CODE_SYNTAX_ERROR) or (ExCode = CON_EXIT_CODE_ERROR) then DisplayError(Msg) else Writeln(Msg); end; DisplayShortUsage; DisplayTryHelp; ExitCode := ExCode; Terminate; end; procedure TApp.DisplayShortUsageAndExit(const Msg: string; const ExCode: integer); begin if Msg <> '' then Writeln(Msg); DisplayShortUsage; DisplayTryHelp; ExitCode := ExCode; Terminate; end; procedure TApp.DisplayBannerAndExit(const ExCode: integer); begin DisplayBanner; ExitCode := ExCode; Terminate; end; procedure TApp.DisplayMessageAndExit(const Msg: string; const ExCode: integer); begin Writeln(Msg); ExitCode := ExCode; Terminate; end; {$endregion Display... procs} end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Permissions, FMX.DialogService, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, System.Actions, FMX.ActnList, FMX.Objects, FMX.StdActns, FMX.MediaLibrary.Actions, FMX.Platform; type TForm1 = class(TForm) ToolBar1: TToolBar; Button1: TButton; Image1: TImage; ActionList1: TActionList; TakePhotoFromCameraAction1: TTakePhotoFromCameraAction; procedure TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); procedure FormShow(Sender: TObject); private { private 宣言 } public { public 宣言 } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.FormShow(Sender: TObject); begin {$IFDEF ANDROID} PermissionsService.RequestPermissions(['android.permission.CAMERA', 'android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'], procedure(const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>) begin if (Length(AGrantResults) <> 3) or (AGrantResults[0] <> TPermissionStatus.Granted) or (AGrantResults[1] <> TPermissionStatus.Granted) or (AGrantResults[2] <> TPermissionStatus.Granted) then TDialogService.ShowMessage('アプリケーションにカメラへのアクセス、ストレージの読み書きの権限が必要です。') end ); {$ENDIF} end; // 必要な権限がない場合、ユーザーにどのような権限がないのかを通知する procedure TForm1.TakePhotoFromCameraAction1DidFinishTaking(Image: TBitmap); begin Image1.Bitmap.Assign(Image); end; end.
unit un_tarefaParalela; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, SyncObjs; type { Thread } TTarefaParalela = class(TThread) protected {O código que será executado pela Thread. Uma boa prática é efetuar a verificação do valor da propriedade Terminated, pois se o mesmo for True indica que a Thread foi finalizada.} procedure Execute; override; private Controle : TCriticalSection; FProgressBar: TProgressBar; procedure SetCriticalSection(bAtivar: Boolean); public destructor Destroy; override; procedure ConfiguraTask(Barra: TProgressBar; bCreateSuspended: Boolean); procedure SetProgressBar; end; implementation { TTarefaParalela } destructor TTarefaParalela.Destroy; begin inherited; Controle.Free; end; procedure TTarefaParalela.Execute; begin {determinação do nível de prioridade de execução da Thread em questão com relação as outras Threads que fazem parte do processo atual;} Priority := tpNormal; try SetCriticalSection(True); SetProgressBar; finally SetCriticalSection(False); end; end; procedure TTarefaParalela.SetCriticalSection(bAtivar: Boolean); begin if bAtivar then Controle.Acquire else Controle.Release; end; procedure TTarefaParalela.SetProgressBar; var i:Integer; begin for I := 1 to 100 do begin FProgressBar.Position := i; Sleep(25); end; end; procedure TTarefaParalela.ConfiguraTask(Barra: TProgressBar; bCreateSuspended: Boolean); begin FProgressBar := Barra; Controle := TCriticalSection.Create; { Quando definido como True, permite a destruição/liberação da instância de TThread de uma forma automática, dispensando assim o uso do FreeAndNil(), que é utilizado para liberar objetos.} FreeOnTerminate := True; {Faz com que a Thread inicie, caso tenha sido criada em estado de suspensão, efetuando assim o código presente no procedimento Execute;} Resume; end; end.
unit U_ImprimirDados; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.frxClass, FMX.Layouts, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.ListView, FMX.Objects, FMX.ListBox, FMX.TabControl, System.Actions, FMX.ActnList, 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, FMX.frxDBSet, Data.DB, Datasnap.Provider, Datasnap.DBClient, FMX.DateTimeCtrls, FMX.Edit, Classes.Utils.View; type tpImprimir = (Denuncias, Receitas); type tpDadosDenuncia = (Relatorio, Lista); type TfrmImprimirDados = class(TForm) Layout1: TLayout; btnImprimir: TButton; ToolBar1: TToolBar; lblTitulo: TLabel; panelButtonDados: TPanel; TabControl1: TTabControl; tabImprimirMenu: TTabItem; Layout2: TLayout; ActionList1: TActionList; actImprimir: TAction; tabImprimirReceitas: TTabItem; tabImprimirDenuncias: TTabItem; lytImprimirReceitas: TLayout; ListBox1: TListBox; ListBoxItem1: TListBoxItem; Layout3: TLayout; Label1: TLabel; dtedtInicial: TDateEdit; ListBoxItem2: TListBoxItem; Layout4: TLayout; Label2: TLabel; dtedtFinal: TDateEdit; ListBoxItem3: TListBoxItem; Layout5: TLayout; Label3: TLabel; ListBoxItem4: TListBoxItem; Layout6: TLayout; Label4: TLabel; changeTabMenuImprimir: TChangeTabAction; changeTabReceitas: TChangeTabAction; changeTabDenúncias: TChangeTabAction; ListBox2: TListBox; lbxitemImprimirDenuncias: TListBoxItem; lbxitemImprimirReceitas: TListBoxItem; Button1: TButton; actVoltar: TAction; ListBox3: TListBox; ListBoxItem5: TListBoxItem; ListBoxItem6: TListBoxItem; ListBoxItem7: TListBoxItem; ListBoxItem8: TListBoxItem; Layout7: TLayout; Layout8: TLayout; Layout9: TLayout; Layout10: TLayout; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton3: TRadioButton; Label5: TLabel; Layout11: TLayout; Label6: TLabel; Layout12: TLayout; Label7: TLabel; Layout13: TLayout; Label8: TLabel; dtedtFim: TDateEdit; dtedtInicio: TDateEdit; Layout14: TLayout; Label9: TLabel; Layout15: TLayout; rbtnListaDenuncias: TRadioButton; Layout16: TLayout; rbtnRelDenuncias: TRadioButton; lbxitUsuario: TListBoxItem; Edit1: TEdit; ListBoxItem9: TListBoxItem; Edit2: TEdit; procedure actImprimirExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure lbxitemImprimirReceitasClick(Sender: TObject); procedure actVoltarExecute(Sender: TObject); procedure lbxitemImprimirDenunciasClick(Sender: TObject); procedure rbtnRelDenunciasClick(Sender: TObject); procedure rbtnListaDenunciasClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private FImpressao: tpImprimir; FDados: tpDadosDenuncia; FUtils: TUtilsView; procedure SetImpressao(const Value: tpImprimir); procedure SetDados(const Value: tpDadosDenuncia); { Private declarations } public { Public declarations } qryDen, qryRec: TFDQuery; published property Impressao: tpImprimir read FImpressao write SetImpressao; property Dados: tpDadosDenuncia read FDados write SetDados; end; var frmImprimirDados: TfrmImprimirDados; implementation {$R *.fmx} uses U_SISVISA, U_dmSISVISA, Classes.Utils.Consts, U_dmRelReceitas, U_dmRelDenuncias; procedure TfrmImprimirDados.actImprimirExecute(Sender: TObject); begin case Impressao of Denuncias: begin with dmRelDenuncias do begin FUtils.ImprimirRelatorio(TAB_VWDEN, VW_DEN_F6, 'Denuncias', dtedtInicio, dtedtFim, qryDen); case Dados of Relatorio: begin ppRelDenuncias.Print; end; Lista: begin ppListaDenuncias.Print; end; end; end; end; Receitas: begin with dmRelReceitas do begin FUtils.ImprimirRelatorio(TAB_VWRECEITA, VW_REC_F7, 'Receitas', dtedtInicial, dtedtFinal, qryRec); ppRelReceitas.Print; end; end; end; end; procedure TfrmImprimirDados.actVoltarExecute(Sender: TObject); begin changeTabMenuImprimir.ExecuteTarget(Self); panelButtonDados.Visible := False; lblTitulo.Text := IMPRIMIR; end; procedure TfrmImprimirDados.FormCreate(Sender: TObject); begin FUtils := TUtilsView.Create; qryDen := dmRelDenuncias.FDqryRelDenuncias; qryRec := dmRelReceitas.FDqryRelReceitas; TabControl1.TabIndex := 0; TabControl1.TabPosition := TTabPosition.None; rbtnRelDenuncias.IsChecked := True; end; procedure TfrmImprimirDados.FormDestroy(Sender: TObject); begin FUtils.Destroy; end; procedure TfrmImprimirDados.lbxitemImprimirDenunciasClick(Sender: TObject); begin Impressao := Denuncias; changeTabDenúncias.ExecuteTarget(Self); panelButtonDados.Visible := True; lblTitulo.Text := IMPRIMIR + IMPRIME_DEN; end; procedure TfrmImprimirDados.lbxitemImprimirReceitasClick(Sender: TObject); begin Impressao := Receitas; changeTabReceitas.ExecuteTarget(Self); panelButtonDados.Visible := True; lblTitulo.Text := lblTitulo.Text + IMPRIME_REC; end; procedure TfrmImprimirDados.rbtnListaDenunciasClick(Sender: TObject); begin Dados := Lista; end; procedure TfrmImprimirDados.rbtnRelDenunciasClick(Sender: TObject); begin Dados := Relatorio; end; procedure TfrmImprimirDados.SetDados(const Value: tpDadosDenuncia); begin FDados := Value; end; procedure TfrmImprimirDados.SetImpressao(const Value: tpImprimir); begin FImpressao := Value; end; end.
{ Copy landscape data between worldspaces matching cells by grid X,Y coordinates. Worldspaces can be from different plugins and with different masters or none at all. Designed to be used in conjunction with TESAnnwyn to import back modified landscape data into existing mods. For example you exported heightmap or vertex colors with TESAnnwyn from your existing worldspace, modifed it, then imported it using TESAnnwyn into a new plugin, and can apply this script to copy modified data back into your mod. Destination (where to copy) is what you applied this script for: single LAND record, selected cell(s), exterior block(s) or the whole worldspace. Select source worldspace to copy from and what landscape data to copy in options window. } unit CopyLandData; var DestWorld: IInterface; bNormals, bHeightmap, bColors, bLayers: Boolean; CellCount: integer; //=========================================================================== // returns LAND record for CELL record function GetLandscapeForCell(cell: IInterface): IInterface; var cellchild, r: IInterface; i: integer; begin cellchild := FindChildGroup(ChildGroup(cell), 9, cell); // get Temporary group of cell for i := 0 to Pred(ElementCount(cellchild)) do begin r := ElementByIndex(cellchild, i); if Signature(r) = 'LAND' then begin Result := r; Exit; end; end; end; //============================================================================ // get cell record by X,Y grid coordinates from worldspace function GetCellFromWorldspace(Worldspace: IInterface; GridX, GridY: integer): IInterface; var blockidx, subblockidx, cellidx: integer; wrldgrup, block, subblock, cell: IInterface; Grid, GridBlock, GridSubBlock: TwbGridCell; LabelBlock, LabelSubBlock: Cardinal; begin Grid := wbGridCell(GridX, GridY); GridSubBlock := wbSubBlockFromGridCell(Grid); LabelSubBlock := wbGridCellToGroupLabel(GridSubBlock); GridBlock := wbBlockFromSubBlock(GridSubBlock); LabelBlock := wbGridCellToGroupLabel(GridBlock); wrldgrup := ChildGroup(Worldspace); // iterate over Exterior Blocks for blockidx := 0 to Pred(ElementCount(wrldgrup)) do begin block := ElementByIndex(wrldgrup, blockidx); if GroupLabel(block) <> LabelBlock then Continue; // iterate over SubBlocks for subblockidx := 0 to Pred(ElementCount(block)) do begin subblock := ElementByIndex(block, subblockidx); if GroupLabel(subblock) <> LabelSubBlock then Continue; // iterate over Cells for cellidx := 0 to Pred(ElementCount(subblock)) do begin cell := ElementByIndex(subblock, cellidx); if (Signature(cell) <> 'CELL') or GetIsPersistent(cell) then Continue; if (GetElementNativeValues(cell, 'XCLC\X') = Grid.x) and (GetElementNativeValues(cell, 'XCLC\Y') = Grid.y) then begin Result := cell; Exit; end; end; Break; end; Break; end; end; //=========================================================================== procedure FillWorldspaces(lst: TStrings); var sl: TStringList; i, j: integer; f, wrlds, wrld: IInterface; s: string; begin sl := TStringList.Create; for i := 0 to Pred(FileCount) do begin f := FileByIndex(i); wrlds := GroupBySignature(f, 'WRLD'); for j := 0 to Pred(ElementCount(wrlds)) do begin wrld := ElementByIndex(wrlds, j); if ElementType(wrld) <> etMainRecord then Continue; s := EditorID(wrld) + ' in ' + Name(f); sl.AddObject(s, wrld); end; end; sl.Sort; lst.AddStrings(sl); sl.Free; end; //=========================================================================== function OptionsForm: Boolean; var frm: TForm; lbl: TLabel; cmbWorld: TComboBox; clbOptions: TCheckListBox; btnOk, btnCancel: TButton; begin frm := TForm.Create(nil); try frm.Caption := 'Copy landscape data'; frm.Width := 326; frm.Height := 260; frm.Position := poMainFormCenter; frm.BorderStyle := bsDialog; lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := 8; lbl.Top := 8; lbl.Caption := 'From worldspace'; cmbWorld := TComboBox.Create(frm); cmbWorld.Parent := frm; cmbWorld.Left := 8; cmbWorld.Top := 26; cmbWorld.Width := 300; cmbWorld.Style := csDropDownList; FillWorldspaces(cmbWorld.Items); if cmbWorld.Items.Count > 0 then cmbWorld.ItemIndex := 0; clbOptions := TCheckListBox.Create(frm); clbOptions.Parent := frm; clbOptions.Top := 60; clbOptions.Left := 8; clbOptions.Width := 300; clbOptions.Height := 60; clbOptions.Items.Add('Vertex normals'); clbOptions.Items.Add('Vertex heightmap'); clbOptions.Items.Add('Vertex colors'); clbOptions.Items.Add('Texture layers'); lbl := TLabel.Create(frm); lbl.Parent := frm; lbl.Left := 8; lbl.Top := 128; lbl.Width := 300; lbl.Height := 40; lbl.AutoSize := False; lbl.Wordwrap := True; lbl.Caption := 'If you checked Texture layers, then FormIDs of LTEX landscape textures must match in source and destination plugins, otherwise copy will fail'; btnOk := TButton.Create(frm); btnOk.Parent := frm; btnOk.Caption := 'OK'; btnOk.ModalResult := mrOk; btnOk.Left := 150; btnOk.Top := 200; btnCancel := TButton.Create(frm); btnCancel.Parent := frm; btnCancel.Caption := 'Cancel'; btnCancel.ModalResult := mrCancel; btnCancel.Left := btnOk.Left + btnOk.Width + 10; btnCancel.Top := btnOk.Top; if frm.ShowModal <> mrOk then Exit; if cmbWorld.ItemIndex <> -1 then begin DestWorld := ObjectToElement(cmbWorld.Items.Objects[cmbWorld.ItemIndex]); bNormals := clbOptions.Checked[0]; bHeightmap := clbOptions.Checked[1]; bColors := clbOptions.Checked[2]; bLayers := clbOptions.Checked[3]; if bNormals or bHeightmap or bColors or bLayers then Result := True else AddMessage('Nothing to copy'); end; finally frm.Free; end; end; //=========================================================================== function Initialize: integer; begin if not wbSimpleRecords then begin MessageDlg('Simple records must be checked in xEdit options', mtInformation, [mbOk], 0); Result := 1; Exit; end; if not OptionsForm then begin Result := 1; Exit; end; end; //=========================================================================== function Process(e: IInterface): integer; var cell, land: IInterface; begin if Signature(e) <> 'LAND' then Exit; cell := LinksTo(ElementByName(e, 'Cell')); if not Assigned(cell) then Exit; cell := GetCellFromWorldspace(DestWorld, GetElementNativeValues(cell, 'XCLC\X'), GetElementNativeValues(cell, 'XCLC\Y')); land := GetLandscapeForCell(cell); if not Assigned(land) then Exit; if bNormals then ElementAssign(ElementBySignature(e, 'VNML'), LowInteger, ElementBySignature(land, 'VNML'), False); if bHeightmap then ElementAssign(ElementBySignature(e, 'VHGT'), LowInteger, ElementBySignature(land, 'VHGT'), False); if bColors then ElementAssign(ElementBySignature(e, 'VCLR'), LowInteger, ElementBySignature(land, 'VCLR'), False); if bLayers then ElementAssign(ElementByName(e, 'Layers'), LowInteger, ElementByName(land, 'Layers'), False); Inc(CellCount); if CellCount mod 1000 = 0 then AddMessage(Format('%d cell(s) copied', [CellCount])); end; //=========================================================================== function Finalize: integer; begin AddMessage(Format('%d cell(s) copied', [CellCount])); end; end.
// WinRTCtl.pas // Copyright 1998 BlueWater Systems // // Global definitions for the WinRT package // unit WinRTCtl; interface uses sysutils, Windows; const WINRT_MAXIMUM_SECTIONS = 6; LOGICAL_NOT_FLAG = $1000; MATH_SIGNED = $2000; // Dimension type flags DIMENSION_CONSTANT = $1000; DIMENSION_ARRAY = $2000; DIMENSION_GLOBAL = $4000; DIMENSION_EXTERN = $8000; // Array Move flags ARRAY_MOVE_INDIRECT = $8000; // Math MOVE_TO flags MATH_MOVE_TO_PORT = $1000; MATH_MOVE_TO_VALUE = $2000; MATH_MOVE_FROM_VALUE= $4000; FILE_ANY_ACCESS = 0; FILE_READ_ACCESS = 1; FILE_WRITE_ACCESS = 2; METHOD_BUFFERED = 0; METHOD_IN_DIRECT = 1; METHOD_OUT_DIRECT = 2; METHOD_NEITHER = 3; WINRT_DEVICE_TYPE = $8000; IOCTL_WINRT_PROCESS_BUFFER = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($800 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_PROCESS_BUFFER_DIRECT = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($801 shl 2) or METHOD_IN_DIRECT; IOCTL_WINRT_PROCESS_DMA_BUFFER = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($802 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_PROCESS_DMA_BUFFER_DIRECT = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($803 shl 2) or METHOD_IN_DIRECT; IOCTL_WINRT_GET_CONFIG = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($804 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_MAP_MEMORY = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($806 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_UNMAP_MEMORY = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($807 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_AUTOINC_IO = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($808 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_WAIT_INTERRUPT = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($809 shl 2) or METHOD_BUFFERED; IOCTL_WINRT_SET_INTERRUPT = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($80A shl 2) or METHOD_IN_DIRECT; IOCTL_WINRT_SETUP_DMA_BUFFER = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($80C shl 2) or METHOD_BUFFERED; IOCTL_WINRT_FREE_DMA_BUFFER = (Cardinal(WINRT_DEVICE_TYPE) shl 16) or (FILE_ANY_ACCESS shl 14) or ($80D shl 2) or METHOD_BUFFERED; // commands for WINRT_CONTROL_ITEM command buffer // Command naming convention: // data size // B - byte 8 bits, // W - word 16 bits, // L - long 32 bits // port or memory mapped I/O // P - port or I/O mapped // (equivalent to x86 inp() functions) // M - memory mapped // relative or absolute addressing // A - absolute addressing // - no letter is relative addressing // (relative to the // Section0/portAddress in the // registry.) // Example: INP_B port I/O, // relative addressing, // byte // INM_WA memory mapped I/O, // absolute addressing, // word // // // Input & Output commands // port I/O commands // param1 param2 NOP=0; // No operation 0 0 INP_B=1; // input byte port rel byte input INP_W=2; // input word port rel word input INP_L=3; // input long port rel long input OUTP_B=4; // output byte port rel byte to output OUTP_W=5; // output word port rel word to output OUTP_L=6; // output long port rel long to output INP_BA=7; // input byte port abs byte input INP_WA=8; // input word port abs word input INP_LA=9; // input long port abs long input OUTP_BA=10; // output byte port abs byte to output OUTP_WA=11; // output word port abs word to output OUTP_LA=12; // output long port abs long to output // memory mapped I/O commands // param1 param2 INM_B=13; // input byte address rel byte input INM_W=14; // input word address rel word input INM_L=15; // input long address rel long input OUTM_B=16; // output byte address rel byte to output OUTM_W=17; // output word address rel word to output OUTM_L=18; // output long address rel long to output INM_BA=19; // input byte address abs byte input INM_WA=20; // input word address abs word input INM_LA=21; // input long address abs long input OUTM_BA=22; // output byte address abs byte to output OUTM_WA=23; // output word address abs word to output OUTM_LA=24; // output long address abs long to output // // Interrupt commands // param1 param2 INTRP_ID_ALWAYS=25; // identifies interrupt as always ours. // not used not used INTRP_ID_IN=26; // inputs value read by INTRP_ID_xxx commands // not used value read in // Interrupt commands using port I/O // param1 param2 INTRP_ID_IF_SET_PB=27; // identifies interrupt if the port value and'ed // with mask is non-zero (port is byte) // port rel mask for set bits INTRP_ID_IF_NSET_PB=28; // identifies interrupt if the port value and'ed // with mask is zero (port is byte) // port rel mask for not set bits INTRP_ID_IF_SET_PW=29; // identifies interrupt if the port value and'ed // with mask is non-zero (port is word) // port rel mask for set bits INTRP_ID_IF_NSET_PW=30; // identifies interrupt if the port value and'd // with mask is zero (port is word) // port rel mask for not set bits INTRP_ID_IF_SET_PL=31; // identifies interrupt if the port value and'd // with mask is non-zero (port is long) // port rel mask for set bits INTRP_ID_IF_NSET_PL=32; // identifies interrupt if the port value and'd // with mask is zero (port is long) // port rel mask for not set bits INTRP_ID_IF_EQ_PB=33; // identifies interrupt if the port value equals value // port rel value(byte) INTRP_ID_IF_GT_PB=34; // identifies interrupt if the port value > value // port rel value(byte) INTRP_ID_IF_LT_PB=35; // identifies interrupt if the port value < value // port rel value(byte) INTRP_ID_IF_EQ_PW=36; // identifies interrupt if the port value equals value // port rel value(word) INTRP_ID_IF_GT_PW=37; // identifies interrupt if the port value > value // port rel value(word) INTRP_ID_IF_LT_PW=38; // identifies interrupt if the port value < value // port rel value(word) INTRP_ID_IF_EQ_PL=39; // identifies interrupt if the port value equals value // port rel value(long) INTRP_ID_IF_GT_PL=40; // identifies interrupt if the port value > value // port rel value(long) INTRP_ID_IF_LT_PL=41; // identifies interrupt if the port value < value // port rel value(long) INTRP_CLEAR_NOP=42; // clears interrupt with no operation // not used not used INTRP_CLEAR_IN=43; // inputs value read by INTRP_CLEAR_Rxxx commands // not used value read in INTRP_CLEAR_W_PB=44; // clears interrrupt by writing value to port(byte) // port rel byte to output INTRP_CLEAR_W_PW=45; // clears interrrupt by writing value to port(word) // port rel word to output INTRP_CLEAR_W_PL=46; // clears interrrupt by writing value to port(long) // port rel long to output INTRP_CLEAR_R_PB=47; // clears interrrupt by reading port(byte) // port rel byte input INTRP_CLEAR_R_PW=48; // clears interrrupt by reading port(word) // port rel word input INTRP_CLEAR_R_PL=49; // clears interrrupt by reading port(long) // port rel long input INTRP_CLEAR_RMW_SET_PB=50;// clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port rel byte mask INTRP_CLEAR_RMW_SET_PW=51;// clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port rel word mask INTRP_CLEAR_RMW_SET_PL=52;// clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port rel long mask INTRP_CLEAR_RMW_NSET_PB=53;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port rel byte mask INTRP_CLEAR_RMW_NSET_PW=54;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port rel word mask INTRP_CLEAR_RMW_NSET_PL=55;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port rel long mask INTRP_ID_IF_SET_PBA=56; // identifies interrupt if the port value and'ed // with mask is non-zero (port is byte) // port abs mask for set bits INTRP_ID_IF_NSET_PBA=57;// identifies interrupt if the port value and'ed // with mask is zero (port is byte) // port abs mask for not set bits INTRP_ID_IF_SET_PWA=58; // identifies interrupt if the port value and'ed // with mask is non-zero (port is word) // port abs mask for set bits INTRP_ID_IF_NSET_PWA=59;// identifies interrupt if the port value and'd // with mask is zero (port is word) // port abs mask for not set bits INTRP_ID_IF_SET_PLA=60; // identifies interrupt if the port value and'd // with mask is non-zero (port is long) // port abs mask for set bits INTRP_ID_IF_NSET_PLA=61;// identifies interrupt if the port value and'd // with mask is zero (port is long) // port abs mask for not set bits INTRP_ID_IF_EQ_PBA=62; // identifies interrupt if the port value equals value // port abs value(byte) INTRP_ID_IF_GT_PBA=63; // identifies interrupt if the port value > value // port abs value(byte) INTRP_ID_IF_LT_PBA=64; // identifies interrupt if the port value < value // port abs value(byte) INTRP_ID_IF_EQ_PWA=65; // identifies interrupt if the port value equals value // port abs value(word) INTRP_ID_IF_GT_PWA=66; // identifies interrupt if the port value > value // port abs value(word) INTRP_ID_IF_LT_PWA=67; // identifies interrupt if the port value < value // port abs value(word) INTRP_ID_IF_EQ_PLA=68; // identifies interrupt if the port value equals value // port abs value(long) INTRP_ID_IF_GT_PLA=69; // identifies interrupt if the port value > value // port abs value(long) INTRP_ID_IF_LT_PLA=70; // identifies interrupt if the port value < value // port abs value(long) INTRP_CLEAR_W_PBA=71; // clears interrrupt by writing value to port(byte) // port abs byte to output INTRP_CLEAR_W_PWA=72; // clears interrrupt by writing value to port(word) // port abs word to output INTRP_CLEAR_W_PLA=73; // clears interrrupt by writing value to port(long) // port abs long to output INTRP_CLEAR_R_PBA=74; // clears interrrupt by reading port(byte) // port abs byte input INTRP_CLEAR_R_PWA=75; // clears interrrupt by reading port(word) // port abs word input INTRP_CLEAR_R_PLA=76; // clears interrrupt by reading port(long) // port abs long input INTRP_CLEAR_RMW_SET_PBA=77; // clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port abs byte mask INTRP_CLEAR_RMW_SET_PWA=78; // clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port abs word mask INTRP_CLEAR_RMW_SET_PLA=79; // clears interrupt with read modify write operation. // port is input, or'd with value and result is output // port abs long mask INTRP_CLEAR_RMW_NSET_PBA=80;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port abs byte mask INTRP_CLEAR_RMW_NSET_PWA=81;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port abs word mask INTRP_CLEAR_RMW_NSET_PLA=82;// clears interrupt with read modify write operation. // port is input, and'd with value and result is output // port abs long mask // // Interrupt commands // using memory mapped I/O // param1 param2 INTRP_ID_IF_SET_MB=83; // identifies interrupt if the address value and'ed // with mask is non-zero (address is byte) // address rel mask for set bits INTRP_ID_IF_NSET_MB=84;// identifies interrupt if the address value and'ed // with mask is zero (address is byte) // address rel mask for not set bits INTRP_ID_IF_SET_MW=85; // identifies interrupt if the address value and'ed // with mask is non-zero (address is word) // address rel mask for set bits INTRP_ID_IF_NSET_MW=86;// identifies interrupt if the address value and'd // with mask is zero (address is word) // address rel mask for not set bits INTRP_ID_IF_SET_ML=87; // identifies interrupt if the address value and'd // with mask is non-zero (address is long) // address rel mask for set bits INTRP_ID_IF_NSET_ML=88;// identifies interrupt if the address value and'd // with mask is zero (address is long) // address rel mask for not set bits INTRP_ID_IF_EQ_MB=89; // identifies interrupt if the memory value equals value // address rel value(byte) INTRP_ID_IF_GT_MB=90; // identifies interrupt if the memory value > value // address rel value(byte) INTRP_ID_IF_LT_MB=91; // identifies interrupt if the memory value < value // address rel value(byte) INTRP_ID_IF_EQ_MW=92; // identifies interrupt if the memory value equals value // address rel value(word) INTRP_ID_IF_GT_MW=93; // identifies interrupt if the memory value > value // address rel value(word) INTRP_ID_IF_LT_MW=94; // identifies interrupt if the memory value < value // address rel value(word) INTRP_ID_IF_EQ_ML=95; // identifies interrupt if the memory value equals value // address rel value(long) INTRP_ID_IF_GT_ML=96; // identifies interrupt if the memory value > value // address rel value(long) INTRP_ID_IF_LT_ML=97; // identifies interrupt if the memory value < value // address rel value(long) INTRP_CLEAR_W_MB=98; // clears interrrupt by writing value to address(byte) // address rel byte to output INTRP_CLEAR_W_MW=99; // clears interrrupt by writing value to address(word) // address rel word to output INTRP_CLEAR_W_ML=100; // clears interrrupt by writing value to address(long) // address rel long to output INTRP_CLEAR_R_MB=101; // clears interrrupt by reading address(byte) // address rel byte input INTRP_CLEAR_R_MW=102; // clears interrrupt by reading address(word) // address rel word input INTRP_CLEAR_R_ML=103; // clears interrrupt by reading address(long) // address rel long input INTRP_CLEAR_RMW_SET_MB=104; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address rel byte mask INTRP_CLEAR_RMW_SET_MW=105; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address rel word mask INTRP_CLEAR_RMW_SET_ML=106; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address rel long mask INTRP_CLEAR_RMW_NSET_MB=107;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address rel byte mask INTRP_CLEAR_RMW_NSET_MW=108;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address rel word mask INTRP_CLEAR_RMW_NSET_ML=109;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address rel long mask INTRP_ID_IF_SET_MBA=110; // identifies interrupt if the address value and'ed // with mask is non-zero (address is byte) // address abs mask for set bits INTRP_ID_IF_NSET_MBA=111; // identifies interrupt if the address value and'ed // with mask is zero (address is byte) // address abs mask for not set bits INTRP_ID_IF_SET_MWA=112; // identifies interrupt if the address value and'ed // with mask is non-zero (address is word) // address abs mask for set bits INTRP_ID_IF_NSET_MWA=113; // identifies interrupt if the address value and'd // with mask is zero (address is word) // address abs mask for not set bits INTRP_ID_IF_SET_MLA=114; // identifies interrupt if the address value and'd // with mask is non-zero (address is long) // address abs mask for set bits INTRP_ID_IF_NSET_MLA=115; // identifies interrupt if the address value and'd // with mask is zero (address is long) // address abs mask for not set bits INTRP_ID_IF_EQ_MBA=116; // identifies interrupt if the memory value equals value // address abs value(byte) INTRP_ID_IF_GT_MBA=117; // identifies interrupt if the memory value > value // address abs value(byte) INTRP_ID_IF_LT_MBA=118; // identifies interrupt if the memory value < value // address abs value(byte) INTRP_ID_IF_EQ_MWA=119; // identifies interrupt if the memory value equals value // address abs value(word) INTRP_ID_IF_GT_MWA=120; // identifies interrupt if the memory value > value // address abs value(word) INTRP_ID_IF_LT_MWA=121; // identifies interrupt if the memory value < value // address abs value(word) INTRP_ID_IF_EQ_MLA=122; // identifies interrupt if the memory value equals value // address abs value(long) INTRP_ID_IF_GT_MLA=123; // identifies interrupt if the memory value > value // address abs value(long) INTRP_ID_IF_LT_MLA=124; // identifies interrupt if the memory value < value // address abs value(long) INTRP_CLEAR_W_MBA=125; // clears interrrupt by writing value to address(byte) // address abs byte to output INTRP_CLEAR_W_MWA=126; // clears interrrupt by writing value to address(word) // address abs word to output INTRP_CLEAR_W_MLA=127; // clears interrrupt by writing value to address(long) // address abs long to output INTRP_CLEAR_R_MBA=128; // clears interrrupt by reading address(byte) // address abs byte input INTRP_CLEAR_R_MWA=129; // clears interrrupt by reading address(word) // address abs word input INTRP_CLEAR_R_MLA=130; // clears interrrupt by reading address(long) // address abs long input INTRP_CLEAR_RMW_SET_MBA=131; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address abs byte mask INTRP_CLEAR_RMW_SET_MWA=132; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address abs word mask INTRP_CLEAR_RMW_SET_MLA=133; // clears interrupt with read modify write operation. // address is input, or'd with value and result is output // address abs long mask INTRP_CLEAR_RMW_NSET_MBA=134;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address abs byte mask INTRP_CLEAR_RMW_NSET_MWA=135;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address abs word mask INTRP_CLEAR_RMW_NSET_MLA=136;// clears interrupt with read modify write operation. // address is input, and'd with value and result is output // address abs long mask // // Miscellaneous commands // _DELAY=137; // delay thread for count milliseconds (can NOT be used // in a wait for interrupt request) // 0 count in millisecond units _STALL=138; // stall processor for count microseconds (to follow // Microsoft's driver guidelines you should always // keep this value as small as possible and Never greater // than 50 microseconds.) // 0 count in microseconds // Logical and Math items LOGICAL_IF = $10000; // logical If // PortHi - condition type // PortLo - relative jump on not condition // ValueHi - condition var 1 index // ValueLo - condition var 2 index DIM=$10001; // shadow variable dimension // PortHi - data size (1,2,4) plus flags // PortLo - number of entries // Value - data entries JUMP_TO=$10002; // jump to // Port - relative index MATH=$10003; // math operation // PortHi - operation type // PortLo - result index // ValueHi - operation var 1 index // ValueLo - operation var 2 index _WHILE=$10004; // while loop // PortHi - condition type // PortLo - relative jump on not condition // ValueHi - condition var 1 index // ValueLo - condition var 2 index ARRAY_MOVE=$10005; // move array item // PortHi - index of lvalue (plus flags) // PortLo - location of lvalue // ValueHi - index of rvalue (plus flags) // ValueLo - location of rvalue (plus flags) ARRAY_MOVE_TO=$10006; // move array item to port or value // combination of DIM, ARRAY_MOVE, // and MATH [MOVE_TO_PORT | MOVE_TO_VALUE] // PortHi - not used (allocated by backend) // PortLo - not used // ValueHi - index of rvalue (plus flags) // ValueLo - location of rvalue (plus flags) ARRAY_MOVE_FROM=$10007; // MATH_MOVE_FROM_VALUE from temp to array INTERNAL_ELSE=$10008; // reserved INTERNAL_TAG=$10009; // reserved ISR_SETUP=$1000A; // Marks the beginning of the ISR setup code // Port - not used // Value - not used BEGIN_ISR=$1000B; // Marks beginning of ISR // Port - not used // Value - not used BEGIN_DPC=$1000C; // Marks beginning of DPC // Port - not used // Value - not used WINRT_BLOCK_ISR=$1000D; // Mark section for synch with ISR // Port - not used // Value - not used WINRT_RELEASE_ISR=$1000E;// Mark end of section for synch with ISR // Port - not used // Value - not used DMA_START=$1000F; // DMA Start Operation - causes the DMA to be started for slave DMA // Port - TRUE for a transfer from the host to the device // FALSE for a transfer from the device to the host // Value - location and flags of number of bytes rvalue DMA_FLUSH=$10010; // DMA Flush Operation - causes the flush and frees adapter channel // Port - not used // Value - not used WINRT_GLOBAL=$10011; // WinRT Global name // Port - length of name in bytes // Value - not used WINRT_EXTERN=$10012; // WinRT Global name // Port - length of name in bytes // Value - not used SET_EVENT=$10013; // Set an event // Port - Handle to the event returned in the pointer passed // to WinRTCreateEvent // Value - not used SCHEDULE_DPC=$10014; // Schedule a DPC // Port - not used // Value - not used REJECT_INTERRUPT=$10015;// Reject an interrupt from within the ISR // Port - not used // Value - not used STOP_INTERRUPT=$10016; // Remove a repeating interrupt service routine // Port - not used // Value - not used SETUP_TIMER=$10017; // Establish a repeating or one shot timer // Port - Milliseconds // Value - 0 if one shot, non-zero if repeating START_TIMER=$10018; // Start a repeating or one shot timer // Port - not used // Value - not used STOP_TIMER=$10019; // Return from a timer // Port - not used // Value - not used WINRT_TRACE=$1001A; // Print a string to the WinRT Debug Buffer // Port - value to use in print // ValueHi - Bit number in Debug bitmask to AND to determine // whether this string should be printed or not // ValueLo - number of characters in the string that follows // the control item containing this command type pbyte = ^byte; pword = ^word; plong = ^longint; // Configuration item for output from IOCTL_WINRT_GET_CONFIG PWINRT_FULL_CONFIGURATION = ^tWINRT_FULL_CONFIGURATION; tWINRT_FULL_CONFIGURATION = record Reserved : longint; MajorVersion, MinorVersion : word; BusType, BusNumber, PortSections, MemorySections, InterruptVector, InterruptLevel : longint; PortStart : array [0..WINRT_MAXIMUM_SECTIONS-1] of longint; PortLength : array [0..WINRT_MAXIMUM_SECTIONS-1] of longint; MemoryStart : array [0..WINRT_MAXIMUM_SECTIONS-1] of longint; MemoryLength : array [0..WINRT_MAXIMUM_SECTIONS-1] of longint; MemoryStart64 : array [0..(WINRT_MAXIMUM_SECTIONS * 2) - 1] of longint; end; {WINRT_FULL_CONFIGURATION} // Logical conditions for LOGICAL_IF. WHILE and END_ISR statements // and operations for MATH statements tWINRT_LOGIC_MATH = ( EQUAL_TO, NOT_EQUAL_TO, GREATER_THAN, GREATER_THAN_EQUAL, LESS_THAN, LESS_THAN_EQUAL, LOGICAL_AND, LOGICAL_OR, BITWISE_AND, BITWISE_OR, EXCLUSIVE_OR, LOGICAL_NOT, BITWISE_NOT, MOVE_TO, ADD, SUBTRACT, MULTIPLY, DIVIDE, MODULUS ); {WINRT_LOGIC_MATH} // Process buffer item for input to IOCTL_WINRT_PROCESS_BUFFER // and IOCTL_WINRT_WAIT_ON_INTERRUPT PWINRT_CONTROL_ITEM = ^tWINRT_CONTROL_ITEM; tWINRT_CONTROL_ITEM = record WINRT_COMMAND : longint; // command to perform port, // port address value : longint; // input or output data end; PCONTROL_ITEM_ex = ^tCONTROL_ITEM_ex; tCONTROL_ITEM_ex = record WINRT_COMMAND, // command to perform port, // port address value : integer; // input or output data dsize : integer; // size of variable waiting for data end; pWINRT_CONTROL_array = ^tWINRT_CONTROL_array; tWINRT_CONTROL_array = array[0..1000] of tWINRT_CONTROL_ITEM; // Map memory specification for input to IOCTL_WINRT_MAP_MEMORY PWINRT_MEMORY_MAP = ^tWINRT_MEMORY_MAP; tWINRT_MEMORY_MAP = record address : pointer; // physical address to be mapped length : longint; // number of bytes to be mapped (>0) end; // Auto Incrementing I/O buffer item for input to IOCTL_WINRT_AUTOINC_IO. // The output buffer is placed in the union value. PWINRT_AUTOINC_ITEM = ^tWINRT_AUTOINC_ITEM; tWINRT_AUTOINC_ITEM = record command : longint; // command to perform - eg OUTP_B, INP_WA port : longint; // port address case integer of 0:(byteval : byte); 1:(wordval : word); 2:(longval : longint) end; PWINRT_DMA_BUFFER_INFORMATION = ^tWINRT_DMA_BUFFER_INFORMATION; tWINRT_DMA_BUFFER_INFORMATION = record pVirtualAddress : PByteArray; // virtual address of DMA common buffer Length : longint; // length of DMA common buffer LogicalAddressHi, LogicalAddressLo : integer; // logical address of DMA common buffer end; PINTERFACE_TYPE = ^tINTERFACE_TYPE; tINTERFACE_TYPE = ( Internal, Isa, Eisa, MicroChannel, TurboChannel, PCIBus, VMEBus, NuBus, PCMCIABus, CBus, MPIBus, MPSABus, MaximumInterfaceType ); {INTERFACE_TYPE} // tStack keeps the position of the active (not closed) _While or _If/_Else // there is one stack structure for all _While's and another for all _IF/_Else tStack = record data : array[1..8] of integer; // up to 8 pending _While's or _If's allowed sp : integer; end; const NOVALUE = pointer(-1); implementation end.
unit uFormulario; { Exemplo de Flyweight com Delphi Criado por André Luis Celestino: www.andrecelestino.com } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, Buttons, Grids, DBGrids, uFlyweightFactory; type TfFormulario = class(TForm) ClientDataSet: TClientDataSet; ClientDataSetCodigo: TIntegerField; ClientDataSetNome: TStringField; ClientDataSetPais: TStringField; DataSource: TDataSource; DBGrid: TDBGrid; BitBtnExportarComFlyweight: TBitBtn; BitBtnExportarSemFlyweight: TBitBtn; procedure FormCreate(Sender: TObject); procedure BitBtnExportarComFlyweightClick(Sender: TObject); procedure BitBtnExportarSemFlyweightClick(Sender: TObject); end; var fFormulario: TfFormulario; implementation uses ShellAPI, DateUtils, uFlyweight, uConcreteFlyweight; {$R *.dfm} procedure TfFormulario.FormCreate(Sender: TObject); begin // carrega os dados dos leitores a partir de um XML ClientDataSet.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Dados.xml'); end; procedure TfFormulario.BitBtnExportarComFlyweightClick(Sender: TObject); var FlyweightFactory: TFlyweightFactory; Cartao: TCartao; FieldPais: TField; FieldNome: TField; TempoInicio: TDateTime; TempoFim: TDateTime; TempoGasto: smallint; begin // cria o objeto da classe Factory do Flyweight FlyweightFactory := TFlyweightFactory.Create; try // armazena a referência dos Fields // para evitar o uso do FieldByName dentro do loop FieldPais := ClientDataSet.FindField('Pais'); FieldNome := ClientDataSet.FindField('Nome'); // armzena o tempo de início do processamento TempoInicio := Now; // move para o primeiro registro do DataSet ClientDataSet.First; // executa um loop em todos os registros while not ClientDataSet.EOF do begin // chama o método GetCartao para retornar o objeto compartilhado // através do nome do país Cartao := FlyweightFactory.GetCartao(FieldPais.AsString); // altera a proprieade extrínseca, que é o nome do leitor Cartao.NomeLeitor := FieldNome.AsString; // chama o método para exportação do cartão Cartao.Exportar; // move para o próximo registro ClientDataSet.Next; end; // armzena o tempo de fim do processamento TempoFim := Now; // calcula e exibe o tempo gasto TempoGasto := SecondsBetween(TempoFim, TempoInicio); ShowMessage(Format('Tempo gasto com Flyweight: %d segundos', [TempoGasto])); finally // libera o objeto da classe Factory do Flyweight da memória FreeAndNil(FlyweightFactory); end; // abre a pasta com os arquivos criados ShellExecute(Application.Handle, PChar('explore'), PChar(ExtractFilePath(ParamStr(0)) + 'cartoes'), nil, nil, SW_SHOWNORMAL); end; procedure TfFormulario.BitBtnExportarSemFlyweightClick(Sender: TObject); var Cartao: TCartao; FieldPais: TField; FieldNome: TField; TempoInicio: TDateTime; TempoFim: TDateTime; TempoGasto: smallint; begin // armazena a referência dos Fields // para evitar o uso do FieldByName dentro do loop FieldPais := ClientDataSet.FindField('Pais'); FieldNome := ClientDataSet.FindField('Nome'); // armzena o tempo de início do processamento TempoInicio := Now; // move para o primeiro registro do DataSet ClientDataSet.First; // executa um loop em todos os registros while not ClientDataSet.EOF do begin try // cria o objeto de cartão conforme o país do leitor if FieldPais.AsString = 'Espanha' then Cartao := TCartaoEspanha.Create else if FieldPais.AsString = 'EUA' then Cartao := TCartaoEUA.Create else if FieldPais.AsString = 'Brasil' then Cartao := TCartaoBrasil.Create else if FieldPais.AsString = 'Itália' then Cartao := TCartaoItalia.Create; // preenche a propriedade referente ao nome do leitor Cartao.NomeLeitor := FieldNome.AsString; // chama o método para exportação do cartão Cartao.Exportar; finally // libera o objeto de cartão da memória FreeAndNil(Cartao); end; // move para o próximo registro ClientDataSet.Next; end; // armzena o tempo de fim do processamento TempoFim := Now; // calcula e exibe o tempo gasto TempoGasto := SecondsBetween(TempoFim, TempoInicio); ShowMessage(Format('Tempo gasto sem Flyweight: %d segundos', [TempoGasto])); // abre a pasta com os arquivos criados ShellExecute(Application.Handle, PChar('explore'), PChar(ExtractFilePath(ParamStr(0)) + 'cartoes'), nil, nil, SW_SHOWNORMAL); end; end.
unit SparseMatrix; interface uses SysUtils, Row, LinkedList, LinkedListItem, Inf; type TSparseMatrix = class private _rowNumber, _colNumber: integer; _matrix: array of TRow; private function ReadMatrix(rowIndex, colIndex: integer): integer; procedure WriteMatrix(rowIndex, colIndex: integer; value: integer); public constructor Create(rowNumber, colNumber: integer); destructor Destroy(); override; public procedure FillMatrix(FillPercent: extended); function ToString(): string; function Copy(): TSparseMatrix; function Transpose(): TSparseMatrix; function Summarise(matrix_: TSparseMatrix): TSparseMatrix; function Multiplication(matrix_: TSparseMatrix): TSparseMatrix; public property Matrix[rowIndex, colIndex: integer]: integer read ReadMatrix write WriteMatrix; default; property RowNumber: integer read _rowNumber; property ColNumber: integer read _colNumber; end; implementation constructor TSparseMatrix.Create(rowNumber, colNumber: integer); var i: integer; begin inherited Create; _rowNumber := rowNumber; _colNumber := colNumber; SetLength(_matrix, _rowNumber); for i := 0 to _rowNumber - 1 do _matrix[i] := TRow.Create(); end; destructor TSparseMatrix.Destroy(); begin Finalize(_matrix); inherited; end; function TSparseMatrix.ReadMatrix(rowIndex, colIndex: integer): integer; begin result := _matrix[rowIndex - 1].ReadCell(rowIndex, colIndex); end; procedure TSparseMatrix.WriteMatrix(rowIndex, colIndex: integer; value: integer); begin _matrix[rowIndex - 1].WriteCell(value, rowIndex, colIndex); end; procedure TSparseMatrix.FillMatrix(fillPercent: extended); var value: integer; rowIndex, colIndex, numCells, i: integer; begin numCells := round((_rowNumber * _colNumber) * (fillPercent / 100)); for i := 1 to numCells do begin repeat Randomize; rowIndex := Random(_rowNumber) + 1; //от 1 до _rowNumber colIndex := Random(_colNumber) + 1; //от 1 до _colNumber repeat value := Random(199) - 99; //от -99 до 99 until (value <> 0); until (Matrix[rowIndex, colIndex] = 0); Matrix[rowIndex, colIndex] := value; end; for i := 1 to RowNumber do _matrix[i - 1].IsSorted := True; end; function TSparseMatrix.ToString(): string; var i: integer; begin Result := ''; for i := 1 to RowNumber do begin if (_matrix[i - 1].Head <> nil) then Result := Result + IntToStr(i) + '. ' + _matrix[i - 1].ToString + #13#10; end; if (Result = '') then Result := '[nil]' + #13#10; end; function TSparseMatrix.Copy(): TSparseMatrix; // Clone(); var i: integer; newMatrix: TSparseMatrix; item_self: TLinkedListItem; begin if (self <> nil) then begin newMatrix := TSparseMatrix.Create(self.RowNumber, self.ColNumber); for i := 1 to RowNumber do begin item_self := self._matrix[i - 1].Head; while (item_self <> nil) do begin newMatrix[item_self.Inf.Row, item_self.Inf.Col] := item_self.Inf.Value; item_self := item_self.Next; end; end; Result := newMatrix; end else Result := nil; end; function TSparseMatrix.Transpose(): TSparseMatrix; var newMatrix: TSparseMatrix; i: integer; item_self: TLinkedListItem; begin if (self <> nil) then begin newMatrix := TSparseMatrix.Create(self.ColNumber, self.RowNumber); for i := 1 to self.RowNumber do begin item_self := self._matrix[i - 1].Head; while (item_self <> nil) do begin newMatrix[item_self.Inf.Col, item_self.Inf.Row] := item_self.Inf.Value; item_self := item_self.Next; end; end; //сортировка матрицы for i := 1 to newMatrix.RowNumber do if (newMatrix._matrix[i - 1].IsSorted = False) then newMatrix._matrix[i - 1].IsSorted := True; Result := newMatrix; end else Result := nil; end; function TSparseMatrix.Summarise(matrix_: TSparseMatrix): TSparseMatrix; var newMatrix: TSparseMatrix; i: integer; value: integer; item: TLinkedListItem; begin if (self.RowNumber = matrix_.RowNumber) and (self.ColNumber = matrix_.ColNumber) then begin newMatrix := self.Copy(); for i := 1 to newMatrix.RowNumber do begin item := matrix_._matrix[i - 1].Head; while (item <> nil) do begin value := newMatrix[item.Inf.Row, item.Inf.Col] + item.Inf.Value; newMatrix[item.Inf.Row, item.Inf.Col] := value; item := item.Next; end; end; //сортировка матрицы for i := 1 to newMatrix.RowNumber do if (newMatrix._matrix[i - 1].IsSorted = False) then newMatrix._matrix[i - 1].IsSorted := True; Result := newMatrix; end else Result := nil; end; function TSparseMatrix.Multiplication(matrix_: TSparseMatrix): TSparseMatrix; var newMatrix: TSparseMatrix; row, col, i: integer; value: integer; begin if (self.ColNumber = matrix_.RowNumber) then begin newMatrix := TSparseMatrix.Create(self.RowNumber, matrix_.ColNumber); for row := 1 to newMatrix.RowNumber do for col := 1 to newMatrix.ColNumber do begin value := 0; for i := 1 to self.ColNumber do value := value + self[row, i] * matrix_[i, col]; newMatrix[row, col] := value; end; //сортировка матрицы for i := 1 to newMatrix.RowNumber do if (newMatrix._matrix[i - 1].IsSorted = False) then newMatrix._matrix[i - 1].IsSorted := True; Result := newMatrix; end else Result := nil; end; end.
unit NewResourceForm; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, nppforms, FHIRResources, FHIRTypes, FHIRPluginValidator, FHIRProfileUtilities, FHIRParserBase, FHIRParser, FHIRContext; type TResourceNewForm = class(TNppForm) PageControl1: TPageControl; Panel1: TPanel; tbResources: TTabSheet; tbProfiles: TTabSheet; lbResources: TListBox; lbProfiles: TListBox; Label1: TLabel; edtFilter: TEdit; btnCreate: TButton; Button2: TButton; Panel2: TPanel; Label2: TLabel; rbJson: TRadioButton; rbXml: TRadioButton; procedure FormShow(Sender: TObject); procedure edtFilterChange(Sender: TObject); procedure lbResourcesClick(Sender: TObject); procedure btnCreateClick(Sender: TObject); procedure lbProfilesClick(Sender: TObject); private { Private declarations } FContext : TFHIRWorkerContext; procedure loadLists; procedure SetContext(const Value: TFHIRWorkerContext); public { Public declarations } destructor Destroy; override; property Context : TFHIRWorkerContext read FContext write SetContext; end; var ResourceNewForm: TResourceNewForm; implementation {$R *.dfm} Uses FhirPlugin; procedure TResourceNewForm.btnCreateClick(Sender: TObject); var sd : TFhirStructureDefinition; pu : TProfileUtilities; res : TFhirResource; comp : TFHIRComposer; s : TStringStream; begin if PageControl1.ActivePageIndex = 0 then sd := lbResources.items.objects[lbResources.ItemIndex] as TFhirStructureDefinition else sd := lbProfiles.items.objects[lbProfiles.ItemIndex] as TFhirStructureDefinition; pu := TProfileUtilities.create(FContext.Link, nil); try res := pu.populateByProfile(sd); try if rbJson.Checked then comp := TFHIRJsonComposer.Create(FContext.link, 'en') else comp := TFHIRXmlComposer.Create(FContext.link, 'en'); try s := TStringStream.Create; try comp.Compose(s, res, true); Npp.NewFile(s.DataString); finally s.Free; end; finally comp.Free; end; finally res.Free; end; finally pu.Free; end; ModalResult := mrOK; end; destructor TResourceNewForm.Destroy; begin FContext.Free; inherited; end; procedure TResourceNewForm.SetContext(const Value: TFHIRWorkerContext); begin FContext.Free; FContext := Value; end; procedure TResourceNewForm.edtFilterChange(Sender: TObject); begin loadLists; end; procedure TResourceNewForm.FormShow(Sender: TObject); begin LoadLists; end; procedure TResourceNewForm.lbProfilesClick(Sender: TObject); begin btnCreate.Enabled := lbProfiles.ItemIndex > -1; end; procedure TResourceNewForm.lbResourcesClick(Sender: TObject); begin btnCreate.Enabled := lbResources.ItemIndex > -1; end; procedure TResourceNewForm.loadLists; var sd : TFhirStructureDefinition; s : String; begin lbResources.Clear; lbProfiles.Clear; s := edtFilter.Text; s := s.toLower; for sd in TFHIRPluginValidatorContext(FContext).Profiles.ProfilesByURL.Values do if (sd.kind = StructureDefinitionKindResource) and ((edtFilter.Text = '') or sd.name.ToLower.Contains(s)) then if sd.derivation = TypeDerivationRuleSpecialization then lbResources.Items.AddObject(sd.name, sd) else lbProfiles.Items.AddObject(sd.name, sd) end; end.
{********************************************************} { } { Zeos Database Objects } { Abstract Transaction component } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZTransact; interface {$R *.dcr} uses {$IFNDEF LINUX} ExtCtrls, {$ELSE} QExtCtrls, {$ENDIF} SysUtils, DB, Classes, ZToken, ZConnect, ZDirSql, ZSqlTypes, ZSqlScanner; {$INCLUDE ../Zeos.inc} type { Transact options } TZTransactOption = (toHourGlass); TZTransactOptions = set of TZTransactOption; TZMonitor = class; { BatchExecSql event handlers } TOnBeforeBatchExec = procedure (Sender: TObject; var Sql: string) of object; TOnAfterbatchExec = procedure (Sender: TObject; var Res: Integer) of object; TOnBatchError = procedure (Sender: TObject; const E: Exception; var Stop: Boolean) of object; { Abstract transaction component } TZTransact = class(TComponent) protected FConnected: Boolean; FAutoCommit: Boolean; FAutoRecovery: Boolean; FNotifies: TList; FOptions: TZTransactOptions; FDatabase: TZDatabase; FDatabaseType: TDatabaseType; FHandle: TDirTransact; FQuery: TDirQuery; FOnDataChange: TNotifyEvent; FOnApplyUpdates: TNotifyEvent; FOnCommit: TNotifyEvent; FOnRollback: TNotifyEvent; FOnBeforeConnect: TNotifyEvent; FOnAfterConnect: TNotifyEvent; FOnBeforeDisconnect: TNotifyEvent; FOnAfterDisconnect: TNotifyEvent; FVersion: Integer; FBatchCurPos, FBatchCurLen, FBatchCurrentLine: Integer; FOnBeforeBatchExec: TOnBeforeBatchExec; FOnAfterBatchExec: TOnAfterBatchExec; FOnBatchError: TOnBatchError; procedure SetConnected(Value: Boolean); procedure SetDatabase(Value: TZDatabase); function GetTransactSafe: Boolean; procedure SetTransactSafe(Value: Boolean); function GetNotifies(Index: Integer): TObject; function GetNotifyCount: Integer; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure DoDataChange(Sql: string); procedure DoCommit; procedure DoRollback; property AutoRecovery: Boolean read FAutoRecovery write FAutoRecovery; property DatabaseType: TDatabaseType read FDatabaseType; property TransactSafe: Boolean read GetTransactSafe write SetTransactSafe; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Connect; virtual; procedure Disconnect; virtual; function ExecSql(Sql: WideString): LongInt; virtual; function ExecSqlParams(Sql: WideString; Params: TVarRecArray; ParamCount: Integer): LongInt; virtual; function BatchExecSql(Sql: WideString): LongInt; function ExecFunc(Func: WideString): WideString; virtual; procedure Commit; virtual; procedure Rollback; virtual; procedure Recovery(Force: Boolean); virtual; procedure DoApplyUpdates; procedure StartTransaction; procedure AddMonitor(Monitor: TZMonitor); virtual; abstract; procedure DeleteMonitor(Monitor: TZMonitor); virtual; abstract; procedure AddNotify(Notify: TObject); procedure RemoveNotify(Notify: TObject); procedure CloseNotifies; property Database: TZDatabase read FDatabase write SetDatabase; property Connected: Boolean read FConnected write SetConnected; property Handle: TDirTransact read FHandle; property QueryHandle: TDirQuery read FQuery; property Notifies[Index: Integer]: TObject read GetNotifies; property NotifyCount: Integer read GetNotifyCount; published property Options: TZTransactOptions read FOptions write FOptions; property AutoCommit: Boolean read FAutoCommit write FAutoCommit; property Version: Integer read FVersion; property BatchCurPos: Integer read FBatchCurPos; property BatchCurLen: Integer read FBatchCurLen; property BatchCurrentLine: Integer read FBatchCurrentLine; property OnBeforeConnect: TNotifyEvent read FOnBeforeConnect write FOnBeforeConnect; property OnAfterConnect: TNotifyEvent read FOnAfterConnect write FOnAfterConnect; property OnBeforeDisconnect: TNotifyEvent read FOnBeforeDisconnect write FOnBeforeDisconnect; property OnAfterDisconnect: TNotifyEvent read FOnAfterDisconnect write FOnAfterDisconnect; property OnBeforeBatchExec: TOnBeforeBatchExec read FOnBeforeBatchExec write FOnBeforeBatchExec; property OnAfterBatchExec: TOnAfterBatchExec read FOnAfterBatchExec write FOnAfterBatchExec; property OnBatchError: TOnBatchError read FOnBatchError write FOnBatchError; property OnDataChange: TNotifyEvent read FOnDataChange write FOnDataChange; property OnApplyUpdates: TNotifyEvent read FOnApplyUpdates write FOnApplyUpdates; property OnCommit: TNotifyEvent read FOnCommit write FOnCommit; property OnRollback: TNotifyEvent read FOnRollback write FOnRollback; end; { Event on post sql query } TMonitorEvent = procedure(Sql, Result: string) of object; { Abstract component for monitoring outgoing queries } TZMonitor = class (TComponent) private FTransact: TZTransact; FMonitorEvent: TMonitorEvent; procedure SetTransact(const Value: TZTransact); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public destructor Destroy; override; published property Transaction: TZTransact read FTransact write SetTransact; property OnMonitorEvent: TMonitorEvent read FMonitorEvent write FMonitorEvent; end; { Monitors list class } TZMonitorList = class (TList) private function GetMonitor(Index: Integer): TZMonitor; public procedure AddMonitor(Value: TZMonitor); procedure DeleteMonitor(Value: TZMonitor); procedure InvokeEvent(Sql, Result: WideString; Error: Boolean); property Monitors[Index: Integer]: TZMonitor read GetMonitor; end; { Sql statements executing component } TZBatchSql = class(TComponent) private FTransact: TZTransact; FAffectedRows: LongInt; FBeforeExecute: TNotifyEvent; FAfterExecute: TNotifyEvent; FSql: TStringList; procedure SetSql(Value: TStringList); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ExecSql; published property Transaction: TZTransact read FTransact write FTransact; property Sql: TStringList read FSql write SetSql; property RowsAffected: LongInt read FAffectedRows; property OnBeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute; property OnAfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute; end; { Custom Notify event handler type } TZNotifyEvent = procedure (Sender: TObject; Event: string) of object; { Asynchronous notifying} TZNotify = class (TComponent) private FActive: Boolean; FAutoOpen: Boolean; FEventsList: TStringList; FTimer: TTimer; FFirstConnect: Boolean; FBeforeRegister: TZNotifyEvent; FBeforeUnregister: TZNotifyEvent; FAfterRegister: TZNotifyEvent; FAfterUnregister: TZNotifyEvent; FNotifyFired: TZNotifyEvent; protected FTransact: TZTransact; FHandle: TDirNotify; FBackEventsList: TStringList; procedure SetActive(Value: Boolean); function GetInterval: Cardinal; virtual; procedure SetInterval(Value: Cardinal); virtual; procedure SetEventsList(Value: TStringList); virtual; procedure SetTransact(Value: TZTransact); procedure TimerProc(Sender: TObject); virtual; procedure CheckEvents; virtual; procedure EventsChange(Sender: TObject); virtual; procedure EventsChanging(Sender: TObject); virtual; procedure CheckActive; virtual; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open; virtual; procedure Close; virtual; procedure ListenTo(Event: string); procedure DoNotify(Event: string); procedure UnlistenTo(Event: string); property Handle: TDirNotify read FHandle; published property Active: Boolean read FActive write SetActive; property EventsList: TStringList read FEventsList write SetEventsList; property Interval: Cardinal read GetInterval write SetInterval; property OnBeforeRegister: TZNotifyEvent read FBeforeRegister write FBeforeRegister; property OnAfterRegister: TZNotifyEvent read FAfterRegister write FAfterRegister; property OnBeforeUnregister: TZNotifyEvent read FBeforeUnregister write FBeforeUnregister; property OnAfterUnregister: TZNotifyEvent read FAfterUnregister write FAfterUnregister; property OnNotify: TZNotifyEvent read FNotifyFired write FNotifyFired; end; { Custom TThread descendent to allow true asynchronous notify processing } implementation uses ZDbaseConst, ZConvert, ZSqlScript {$IFNDEF NO_GUI}{$IFNDEF LINUX} ,Windows, Controls, Forms {$ELSE} ,QControls, QForms {$ENDIF}{$ENDIF}; {***************** TZTransact implementation *****************} { Class constructor } constructor TZTransact.Create(AOwner: TComponent); begin inherited Create(AOwner); FConnected := False; FAutoCommit := True; FOptions := [toHourGlass]; FVersion := ZDBO_VERSION; FNotifies := TList.Create; FDatabaseType := dtUnknown; end; { Class destructor } destructor TZTransact.Destroy; begin if Connected then Disconnect; CloseNotifies; if Assigned(FDatabase) then FDatabase.RemoveTransaction(Self); FQuery.Free; FHandle.Free; FNotifies.Free; inherited Destroy; end; { Set connected prop } procedure TZTransact.SetConnected(Value: Boolean); begin if Value <> FConnected then if Value then Connect else Disconnect; end; { Set database connection prop } procedure TZTransact.SetDatabase(Value: TZDatabase); begin Disconnect; try if Assigned(FDatabase) then FDatabase.RemoveTransaction(Self); if Assigned(Value) then Value.AddTransaction(Self); finally FDatabase := Value; if Assigned(FDatabase) then begin FHandle.Connect := FDatabase.Handle; FQuery.Connect := FDatabase.Handle; end else begin FHandle.Connect := nil; FQuery.Connect := nil; end; end; end; { Get transaction safe property } function TZTransact.GetTransactSafe: Boolean; begin Result := Handle.TransactSafe; end; { Set transaction safe property} procedure TZTransact.SetTransactSafe(Value: Boolean); begin if Handle.TransactSafe <> Value then begin if Connected then begin if Handle.TransactSafe then Handle.EndTransaction else Handle.StartTransaction; end; Handle.TransactSafe := Value; end; end; { Process notification method } procedure TZTransact.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FDatabase ) and (Operation = opRemove) then begin Disconnect; FDatabase := nil; FHandle.Connect := nil; FQuery.Connect := nil; end; end; { Connect to Sql-database } procedure TZTransact.Connect; {$IFNDEF NO_GUI} var OldCursor: TCursor; {$ENDIF} begin if FConnected then Exit; {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} if not Assigned(FDatabase) then DatabaseError(SConnectNotDefined); if Assigned(OnBeforeConnect) then OnBeforeConnect(Self); FDatabase.Connect; if not FDatabase.Connected then DatabaseError(SConnectError); if not FHandle.Active then begin FHandle.Open; if FHandle.Status <> csOk then DatabaseError(Convert(FHandle.Error, FDatabase.Encoding, etNone)); end; FConnected := FHandle.Active; if Assigned(OnAfterConnect) then OnAfterConnect(Self); finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Disconnect from database } procedure TZTransact.Disconnect; {$IFNDEF NO_GUI} var OldCursor: TCursor; {$ENDIF} begin if not FConnected then Exit; {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} //CloseNotifies; if Assigned(OnBeforeDisconnect) then OnBeforeDisconnect(Self); FConnected := False; FHandle.Close; if FHandle.Status <> csOk then DatabaseError(Convert(FHandle.Error, FDatabase.Encoding, etNone)); finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; if Assigned(OnAfterDisconnect) then OnAfterDisconnect(Self); end; { Call OnDataChange event } procedure TZTransact.DoDataChange(Sql: string); var Token: string; begin if Assigned(FOnDataChange) then begin Token := UpperCase(StrTok(Sql,' '#9#10#13)); if (Token = 'UPDATE') or (Token = 'INSERT') or (Token = 'DELETE') then FOnDataChange(Self); end; end; { Invoke OnApplyUpdates event } procedure TZTransact.DoApplyUpdates; begin if Assigned(FOnApplyUpdates) then FOnApplyUpdates(Self); end; { Invoke OnCommit event } procedure TZTransact.DoCommit; begin if Assigned(FOnCommit) then FOnCommit(Self); end; { Invoke OnRollback event } procedure TZTransact.DoRollback; begin if Assigned(FOnRollback) then FOnRollback(Self); end; { Execute a query } function TZTransact.ExecSql(Sql: WideString): LongInt; var {$IFNDEF NO_GUI} OldCursor: TCursor; {$ENDIF} Error: string; begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FQuery.Sql := Sql; Result := FQuery.Execute; if FQuery.Status <> qsCommandOk then begin Error := Convert(FQuery.Error, FDatabase.Encoding, etNone); Recovery(False); DatabaseError(Error); end else DoDataChange(Sql); if FAutoCommit then Commit; finally FQuery.Sql := ''; {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Execute an sql statement with parameters } function TZTransact.ExecSqlParams(Sql: WideString; Params: TVarRecArray; ParamCount: Integer): LongInt; var {$IFNDEF NO_GUI} OldCursor: TCursor; {$ENDIF} Error: string; begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FQuery.Sql := Sql; Result := FQuery.ExecuteParams(Params, ParamCount); if FQuery.Status <> qsCommandOk then begin Error := Convert(FQuery.Error, FDatabase.Encoding, etNone); Recovery(False); DatabaseError(Error); end else DoDataChange(Sql); if FAutoCommit then Commit; finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Execute a function with params and return a result } function TZTransact.ExecFunc(Func: WideString): WideString; var {$IFNDEF NO_GUI} OldCursor: TCursor; {$ENDIF} Error: string; begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FQuery.Sql := 'SELECT '+Func; FQuery.Open; if FQuery.Status <> qsTuplesOk then begin Error := Convert(FQuery.Error, FDatabase.Encoding, etNone); Recovery(False); DatabaseError(Error); end; Result := FQuery.Field(0); FQuery.Close; if FAutoCommit then Commit; finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Commit transaction } procedure TZTransact.Commit; {$IFNDEF NO_GUI} var OldCursor: TCursor; {$ENDIF} begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FHandle.Commit; if FHandle.Status <> csOk then DatabaseError(Convert(FHandle.Error, FDatabase.Encoding, etNone)); DoCommit; finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Rollback transaction } procedure TZTransact.Rollback; {$IFNDEF NO_GUI} var OldCursor: TCursor; {$ENDIF} begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FHandle.Rollback; if FHandle.Status <> csOk then DatabaseError(Convert(FHandle.Error, FDatabase.Encoding, etNone)); DoRollback; finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; { Execute a multiple queries } function TZTransact.BatchExecSql(Sql: WideString): LongInt; var Text: string; Scanner: TZSqlScanner; Stop: Boolean; begin Scanner := ZSqlScanner.CreateSqlScanner(DatabaseType); Scanner.ShowEOL := True; FBatchCurPos := 0; FBatchCurLen := 0; FBatchCurrentLine := 1; Result := 0; try Scanner.Buffer := Sql; while True do begin Text := Scanner.ExtractStatement(FBatchCurPos, FBatchCurLen, FBatchCurrentLine); if Text='' then Break; try if Assigned(FOnBeforeBatchExec) then FOnBeforeBatchExec(Self, Text); Result := ExecSql(Text); if Assigned(FOnAfterBatchExec) then FOnAfterBatchExec(Self, Result); except on E: EDatabaseError do begin if Assigned(FOnBatchError) then begin Stop := True; FOnBatchError(Self, E, Stop); if Stop then raise; end else raise; end; end; end; finally Scanner.Free; if Assigned(FOnAfterBatchExec) then FOnAfterBatchExec(Self, Result); end; end; { Recovery after error } procedure TZTransact.Recovery(Force: Boolean); begin end; { Open autoactivated datasets } procedure TZTransact.Loaded; begin inherited Loaded; if Assigned(Database) then Database.OpenActiveDatasets; end; { Get notify listener by index } function TZTransact.GetNotifies(Index: Integer): TObject; begin Result := FNotifies[Index]; end; { Get notifies count } function TZTransact.GetNotifyCount: Integer; begin Result := FNotifies.Count; end; { Add new notify listener } procedure TZTransact.AddNotify(Notify: TObject); begin if FNotifies.IndexOf(Notify) >= 0 then Exit; FNotifies.Add(Notify); end; { Delete notify listener from list } procedure TZTransact.RemoveNotify(Notify: TObject); var N: Integer; begin N := FNotifies.IndexOf(Notify); if N >= 0 then try TZNotify(FNotifies[N]).Close; finally FNotifies.Delete(N); end; end; { Close all notify listeners } procedure TZTransact.CloseNotifies; var I: Integer; begin for I := 0 to FNotifies.Count-1 do try TZNotify(FNotifies[I]).Close; except end; end; {*********** TZMonitorList implementation ************} { Get monitor } function TZMonitorList.GetMonitor(Index: Integer): TZMonitor; begin Result := TZMonitor(Items[Index]); end; { Add new monitor } procedure TZMonitorList.AddMonitor(Value: TZMonitor); begin Add(Pointer(Value)); end; { Delete existed monitor } procedure TZMonitorList.DeleteMonitor(Value: TZMonitor); var N: Integer; begin N := IndexOf(Pointer(Value)); if N >= 0 then Delete(N); end; { Invoke SqlEvent in all connected monitors } procedure TZMonitorList.InvokeEvent(Sql, Result: WideString; Error: Boolean); var I: Integer; begin for I := 0 to Count-1 do try if not Error then Result := 'OK.'; if Assigned(Monitors[I].OnMonitorEvent) then Monitors[I].OnMonitorEvent(Sql, Result); except end; end; {*************** TZBatchSql implementation **************} { Class constructor } constructor TZBatchSql.Create(AOwner: TComponent); begin inherited Create(AOwner); FSql := TStringList.Create; end; { Class destructor } destructor TZBatchSql.Destroy; begin FSql.Free; inherited Destroy; end; { Set new sql value } procedure TZBatchSql.SetSql(Value: TStringList); begin FSql.Assign(Value); end; { Process notification messages } procedure TZBatchSql.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FTransact ) and (Operation = opRemove) then FTransact := nil; end; { Execute sql statements } procedure TZBatchSql.ExecSql; begin if Assigned(FTransact) then begin if Assigned(FBeforeExecute) then FBeforeExecute(Self); FTransact.Connected := True; FAffectedRows := FTransact.BatchExecSql(FSql.Text); if Assigned(FAfterExecute) then FAfterExecute(Self); end else DatabaseError(STransactNotDefined); end; {******************** TZMonitor implementation ****************} { Class destructor } destructor TZMonitor.Destroy; begin if Assigned(FTransact) and not (csDestroying in ComponentState) then FTransact.DeleteMonitor(Self); inherited Destroy; end; { Process notification events } procedure TZMonitor.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FTransact) and (Operation = opRemove) then begin if Assigned(FTransact) then FTransact.DeleteMonitor(Self); FTransact := nil; end; end; { Set new transaction } procedure TZMonitor.SetTransact(const Value: TZTransact); begin if FTransact <> Value then begin if Assigned(FTransact) then FTransact.DeleteMonitor(Self); FTransact := Value; if Assigned(FTransact) then FTransact.AddMonitor(Self); end; end; {******************** TZNotify implementation ****************} { TZNotify class constructor } constructor TZNotify.Create(AOwner: TComponent); begin inherited Create(AOwner); FEventsList := TStringList.Create; with FEventsList do begin Duplicates := dupIgnore; OnChange := EventsChange; OnChanging := EventsChanging; end; FBackEventsList := TStringList.Create; FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.Interval := 250; FTimer.OnTimer := TimerProc; FActive := False; FFirstConnect := True; end; { TZNotify destructor } destructor TZNotify.Destroy; begin Close; FEventsList.Free; FBackEventsList.Free; FTimer.Free; FHandle.Free; inherited Destroy; end; { Set check interval } procedure TZNotify.SetInterval(Value: Cardinal); begin FTimer.Interval := Value; end; { Retrieve check interval } function TZNotify.GetInterval; begin Result := FTimer.Interval; end; { Update the events list and sends register events at the server } procedure TZNotify.SetEventsList(Value: TStringList); var I: Integer; begin FEventsList.Assign(Value); for I := 0 to FEventsList.Count -1 do FEventsList[I] := Trim(FEventsList[I]); end; { Activate component } procedure TZNotify.SetActive(Value: Boolean); begin if FActive <> Value then begin if Value then Open else Close; end; end; { Set new transaction object } procedure TZNotify.SetTransact(Value: TZTransact); begin if FTransact <> Value then begin Close; if FTransact <> nil then FTransact.RemoveNotify(Self); FTransact := Value; if FTransact <> nil then FTransact.AddNotify(Self); end; end; { Process notification messages } procedure TZNotify.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FTransact ) and (Operation = opRemove) then SetTransact(nil); end; { Process events list changing } procedure TZNotify.EventsChanging(Sender: TObject); begin if not Active then Exit; FBackEventsList.Text:=FEventsList.Text; end; { Process events list changing } procedure TZNotify.EventsChange(Sender: TObject); var I: Integer; begin if not Active then Exit; with TStringList(FEventsList) do begin OnChange := nil; OnChanging := nil; end; try { Unregistering old events } for I := 0 to FBackEventsList.Count-1 do begin if FEventsList.IndexOf(FBackEventsList[I]) = -1 then begin FHandle.UnListenTo(Trim(FBackEventsList[I])); if FHandle.Status <> nsOK then DatabaseError(SNotifyRegister); end; end; { Registering new events } for I := 0 to FEventsList.Count-1 do begin if FBackEventsList.IndexOf(FEventsList[I])=-1 then begin FHandle.ListenTo(Trim(FEventsList[I])); if FHandle.Status <> nsOK then DatabaseError(SNotifyRegister); end; end; { Restoring change event handlers } finally with TStringList(FEventsList) do begin OnChange := EventsChange; OnChanging := EventsChanging; end; FBackEventsList.Clear; end; end; { Internal procedure that will be called at each timer trigger } procedure TZNotify.TimerProc(Sender: TObject); begin if not Active then FTimer.Enabled := False else CheckEvents; end; { Raise exception if notify isn't active } procedure TZNotify.CheckActive; begin if not Assigned(FTransact) then DatabaseError(STransactNotDefined); if not Active then DatabaseError('TZNotify not in active mode'); if not FTransact.Connected then DatabaseError(SNotConnected); end; { Check autoopen property } procedure TZNotify.Loaded; begin inherited Loaded; if FAutoOpen then begin FAutoOpen := False; Open; end; end; { Start the events listener } procedure TZNotify.Open; var I: Integer; begin if Active then Exit; if not Assigned(FTransact) and (csLoading in ComponentState) then begin FAutoOpen := True; Exit; end; if not Assigned(FTransact) then DatabaseError(STransactNotDefined); if not FTransact.Connected then FTransact.Connect; FHandle.Connect := FTransact.Handle.Connect; FHandle.Transact := FTransact.Handle; { Registering events } for I := 0 to FEventsList.Count-1 do begin FHandle.ListenTo(FEventsList[I]); if FHandle.Status <> nsOk then DatabaseError(FHandle.Error); end; FActive := True; FTimer.Enabled := True; end; { Stop the events listener } procedure TZNotify.Close; var I: Integer; begin if not Active then Exit; FTimer.Enabled := False; { Unregistering events } for I:= 0 to FEventsList.Count-1 do begin FHandle.UnlistenTo(FEventsList[I]); if FHandle.Status <> nsOk then DatabaseError(FHandle.Error); end; FTransact.Disconnect; FActive := False; end; { Listen to a specific event } procedure TZNotify.ListenTo(Event: string); begin if Assigned(FBeforeRegister) then FBeforeRegister(Self, Event); CheckActive; FHandle.ListenTo(Trim(Event)); if FHandle.Status <> nsOk then DatabaseError(FHandle.Error); { Adding event to list } with FEventsList do begin OnChange := nil; OnChanging := nil; if IndexOf(Event) = -1 then Append(Event); OnChange := EventsChange; OnChanging := EventsChanging; end; if Assigned(FAfterRegister) then FAfterRegister(Self, Event); end; { Generate a notify event } procedure TZNotify.DoNotify(Event: string); begin CheckActive; FHandle.DoNotify(Event); if FHandle.Status <> nsOk then DatabaseError(FHandle.Error); end; { Stop listening to a specific event } procedure TZNotify.UnlistenTo(Event: string); begin if Assigned(FBeforeRegister) then FBeforeUnregister(Self, Event); CheckActive; FHandle.UnlistenTo(Trim(Event)); if FHandle.Status <> nsOk then DatabaseError(FHandle.Error); { Removing event from list } with FEventsList do begin OnChange := nil; OnChanging := nil; Delete(IndexOf(Event)); OnChange := EventsChange; OnChanging := EventsChanging; end; if Assigned(FAfterRegister) then FAfterUnregister(Self, Event); end; { Checks for any pending events } procedure TZNotify.CheckEvents; var Notify: string; begin CheckActive; while True do begin Notify := Trim(FHandle.CheckEvents); if FHandle.Status<>nsOK then Exit; if Notify = '' then Break; if FEventsList.IndexOf(Notify) >= 0 then begin if Assigned(FNotifyFired) then FNotifyFired(Self, Notify); end; end; end; {start tranzaction manually} procedure TZTransact.StartTransaction; {$IFNDEF NO_GUI} var OldCursor: TCursor; {$ENDIF} begin if not FConnected then DatabaseError(SNotConnected); {$IFNDEF NO_GUI} OldCursor := Screen.Cursor; {$ENDIF} try {$IFNDEF NO_GUI} if toHourGlass in FOptions then Screen.Cursor := crSqlWait; {$ENDIF} FHandle.StartTransaction; if FHandle.Status <> csOk then DatabaseError(Convert(FHandle.Error, FDatabase.Encoding, etNone)); finally {$IFNDEF NO_GUI} Screen.Cursor := OldCursor; {$ENDIF} end; end; end.
unit frm_EditParents; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Menus, FMUtils, fra_Citations, fra_Memo, LCLType, Spin, ExtCtrls, Buttons; type TenumEditRelation=( eERT_appendParent, eERT_editParent, eERT_appendChild, eERT_editChild); { TfrmEditParents } TfrmEditParents = class(TForm) Ajouter1: TMenuItem; fraMemo1: TfraMemo; idA: TSpinEdit; idB: TSpinEdit; btnParentOK: TBitBtn; btnParentCancel: TBitBtn; fraEdtCitations1: TfraEdtCitations; Label6: TLabel; Label7: TLabel; lblChild: TLabel; MainMenu1: TMainMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; Modifier1: TMenuItem; No: TSpinEdit; pnlDateLeft: TPanel; pnlParentDate: TPanel; pnlParent: TPanel; pnlTop: TPanel; pnlParentBottom: TPanel; NomB: TEdit; NomA: TEdit; P1: TMemo; P2: TMemo; SD: TEdit; lblParent: TLabel; Label4: TLabel; lblDate: TLabel; P: TMemo; SD2: TEdit; Supprimer1: TMenuItem; X: TCheckBox; Y: TComboBox; lblType: TLabel; procedure idAEditingDone(Sender: TObject); procedure idBEditingDone(Sender: TObject); procedure btnParentOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure MenuItem6Click(Sender: TObject); procedure P2DblClick(Sender: TObject); procedure PDblClick(Sender: TObject); procedure PEditingDone(Sender: TObject); procedure SDEditingDone(Sender: TObject); procedure Supprimer1Click(Sender: TObject); procedure ParentsSaveData(Sender:Tobject); procedure YChange(Sender: TObject); private FEditMode: TenumEditRelation; FidEvent: Integer; function GetIdRelation: integer; procedure SetEditMode(AValue: TenumEditRelation); procedure SetIdRelation(AValue: integer); { private declarations } public { public declarations } property EditMode:TenumEditRelation read FEditMode write SetEditMode; property idRelation:integer read GetIdRelation write SetIdRelation; end; var frmEditParents: TfrmEditParents; implementation uses frm_Main, cls_Translation, dm_GenData, frm_Names; { TfrmEditParents } procedure TfrmEditParents.FormShow(Sender: TObject); var lRelType, lidChild, lidParent: LongInt; lPrefered: Boolean; lMemoText, lPhraseText, lSortDate: String; lidRelation: Integer; begin { TODO 20 : Lorsque l'on est dans A ou B, ESC ne fonctionne pas - By design Lazarus} frmStemmaMainForm.SetHistoryToActual(Sender); Caption:=Translation.Items[186]; btnParentOK.Caption:=Translation.Items[152]; btnParentCancel.Caption:=Translation.Items[164]; lblType.Caption:=Translation.Items[166]; lblParent.Caption:=Translation.Items[187]; // Label3.Caption:=Translation.Items[171]; Label4.Caption:=Translation.Items[172]; lblDate.Caption:=Translation.Items[189]; Label6.Caption:=Translation.Items[173]; lblChild.Caption:=Translation.Items[188]; MenuItem1.Caption:=Translation.Items[228]; MenuItem2.Caption:=Translation.Items[224]; MenuItem3.Caption:=Translation.Items[225]; MenuItem4.Caption:=Translation.Items[226]; // Populate le ComboBox dmGenData.GetTypeList(Y.Items,'R',false); fraEdtCitations1.CType:='R'; fraEdtCitations1.OnSaveData:=@ParentsSaveData; // Populate la form // dmGenData.GetCode(code,nocode); if FEditMode in [eERT_appendChild,eERT_appendParent] then begin fraEdtCitations1.Clear; Y.ItemIndex:=0; No.Value:=0; X.Checked:=False; //dmGenData.GetCode(code,nocode); if FEditMode=eERT_appendChild then begin ActiveControl:=idA; Caption:=Translation.Items[41]; idB.Value:=frmStemmaMainForm.iID; NomB.Text:=DecodeName(dmGenData.GetIndividuumName(frmStemmaMainForm.iID),1); idB.ReadOnly :=true; idA.Value:=0; NomA.Text:=''; idA.ReadOnly :=false; end else begin ActiveControl:=idB; Caption:=Translation.Items[42]; idA.Value:=frmStemmaMainForm.iID; NomA.Text:=decodename(dmGenData.GetIndividuumName(frmStemmaMainForm.iID),1); idA.ReadOnly :=true; idB.Value:=0; NomB.Text:=''; idB.ReadOnly :=false; end; fraMemo1.Text:=''; P.Text:=''; SD.Text:=''; SD2.Text:=InterpreteDate('',1);; end else begin idA.ReadOnly :=true; idB.ReadOnly :=true; ActiveControl:=idA; lidRelation := idRelation; dmGenData.GetRelationData(lidRelation, lSortDate, lPhraseText, lMemoText, lPrefered, lidParent, lidChild, lRelType); Y.ItemIndex:=y.Items.IndexOfObject(TObject(ptrint(lRelType))); X.Checked:=lPrefered; idA.Value:=lidChild; idB.Value:=lidParent; NomB.Text:=DecodeName(dmGenData.GetIndividuumName(idb.Value),1); NomA.Text:=DecodeName(dmGenData.GetIndividuumName(ida.Value),1); fraMemo1.Text:=lMemoText; P.Text:=lPhraseText; SD2.Text:=lSortDate; SD.Text:=ConvertDate(lSortDate,1); // Populate le tableau de citations fraEdtCitations1.LinkID:=No.Value; end; P1.Text:=dmGenData.GetTypePhrase(ptrint(Y.Items.Objects[Y.ItemIndex])); if length(P.Text)=0 then begin P.Text:=P1.Text; Label6.Visible:=true; end; P2.Text:=DecodePhrase(idA.Value,'ENFANT',P.Text,'R',No.Value); btnParentOK.Enabled:=(idA.Value>0) and (idB.Value>0); fraEdtCitations1.Enabled:=btnParentOK.Enabled; MenuItem5.Enabled:=btnParentOK.Enabled; end; procedure TfrmEditParents.MenuItem5Click(Sender: TObject); begin btnParentOKClick(Sender); ModalResult:=mrOk; end; procedure TfrmEditParents.MenuItem6Click(Sender: TObject); var lsResult:String; liResult:integer; begin if ActiveControl.name=SD.name then begin lsResult := frmStemmaMainForm.RetreiveFromHistoy('SD'); if lsResult <>'' then begin SD.text:=lsResult; SDEditingDone(Sender); end; end else if activeControl.Name=idA.Name then begin liResult:=frmStemmaMainForm.RetreiveFromHistoyID('A'); if liResult>0 then begin idA.Value:=liResult; idAEditingDone(Sender); end; end else if ActiveControl.Name=P.Name then begin lsResult:=frmStemmaMainForm.RetreiveFromHistoy('P'); if lsResult<>'' then begin P.text:=lsResult; PEditingDone(Sender); end; end else if activeControl.Name=idB.Name then begin liResult:=frmStemmaMainForm.RetreiveFromHistoyID('B'); if liResult>0 then begin idB.Value:=liResult; idBEditingDone(Sender); end; end else if ActiveControl.Name=fraMemo1.edtMemoText.name then begin lsResult:=frmStemmaMainForm.RetreiveFromHistoy('M'); if lsResult<>'' then begin fraMemo1.text:=lsResult; end; end; end; procedure TfrmEditParents.idBEditingDone(Sender: TObject); var lSex: String; begin NomB.Text:=DecodeName(dmGenData.GetIndividuumName(idB.Value),1); P2.Text:=DecodePhrase(idA.Value,'ENFANT',P.Text,'R',No.Value); lSex := dmGenData.GetSexOfInd(idB.Value); if (lSex = '') or ( lSex='?') then btnParentOK.Enabled:=false else btnParentOK.Enabled:=(idA.Value>0) and (idB.Value>0); fraEdtCitations1.Enabled:=btnParentOK.Enabled; MenuItem5.Enabled:=btnParentOK.Enabled; frmStemmaMainForm.AppendHistoryData('B',idB.Value); end; procedure TfrmEditParents.idAEditingDone(Sender: TObject); begin NomA.Text:=DecodeName(dmGenData.GetIndividuumName(idA.Value),1); P2.Text:=DecodePhrase(idA.Value,'ENFANT',P.Text,'R',No.Value); btnParentOK.Enabled:=((StrToInt(idA.Text)>0) and (StrToInt(idB.Text)>0)); fraEdtCitations1.Enabled:=btnParentOK.Enabled; MenuItem5.Enabled:=btnParentOK.Enabled; frmStemmaMainForm.AppendHistoryData('A',idA.Value); end; procedure TfrmEditParents.ParentsSaveData(Sender: Tobject); var lStrTmp,dateev, lMemoText:string; parent1, parent2,no_eve, lidRelation, lidChild, lidParent:integer; prefered, existe, lIsDefaultPhrase, lPrefParExists:boolean; lidType: PtrInt; lSDate, lPhrase: TCaption; begin // Si l'enfant n'idA pas de parent de ce sexe, mettre la relation prefered. prefered:=false; lStrTmp:=''; FidEvent := -1; If dmGenData.IsValidIndividuum(idB.Value) then begin lStrTmp:=dmGenData.GetSexOfInd(idB.Value); dmGenData.Query1.SQL.Text:='SELECT R.no, R.B FROM R JOIN I ON R.B=I.no WHERE I.S=:Sex AND R.X=1 AND R.A=:idIndA'; dmgenData.Query1.ParamByName('Sex').AsString:=lStrTmp; dmgenData.Query1.ParamByName('idIndA').AsInteger:=idA.Value; dmGenData.Query1.Open; prefered:=not dmGenData.Query1.EOF; end; if X.Checked or ((no.Value=0) and prefered) then begin if lStrTmp='F' then lStrTmp:='M' else lStrTmp:='F'; dmGenData.Query1.SQL.Text:='SELECT R.no, R.B, N.N FROM R JOIN I ON R.B=I.no JOIN N on N.I=R.B WHERE I.S=:Sex AND R.X=1 AND N.X=1 AND R.A=:idChild'; dmGendata.Query1.ParamByName('Sex').AsString:=lStrTmp; dmGendata.Query1.ParamByName('idChild').AsInteger:=idA.Value; dmGenData.Query1.Open; lPrefParExists := not dmGenData.Query1.EOF; if lPrefParExists then begin; lStrTmp:=dmGenData.Query1.Fields[2].AsString; parent2:=dmGenData.Query1.Fields[1].AsInteger; end; dmGenData.Query1.close; parent1:=idB.Value; //Done -oJC : Convert to Integer If lPrefParExists then begin // Vérifier qu'il n'y idA pas déjà une union entre ces deux parents dmGenData.Query1.SQL.text:='SELECT COUNT(E.no) FROM E JOIN W ON W.E=E.no JOIN Y on E.Y=Y.no WHERE (W.I=:idParentA OR W.I=:idParentB) AND W.X=1 AND E.X=1 AND Y.Y=''M'' GROUP BY E.no'; dmGendata.Query1.ParamByName('idParentA').AsInteger:=idA.Value; dmGendata.Query1.ParamByName('idParentB').AsInteger:=parent1; dmGenData.Query1.Open; existe:=false; while not dmGenData.Query1.EOF do begin existe:=existe or (dmGenData.Query1.Fields[0].AsInteger=2); dmGenData.Query1.Next; end; if not existe then if Application.MessageBox(Pchar(Translation.Items[300]+ nomB.Text+Translation.Items[299]+ DecodeName(lStrTmp,1)+ Translation.Items[28]),pchar(SConfirmation),MB_YESNO)=IDYES then begin // Unir les parents // Ajouter l'événement mariage dmGenData.Query1.SQL.text:='INSERT INTO E (Y, L, X) VALUES (300, 1, 1)'; dmGenData.Query1.ExecSQL; no_eve:=dmGenData.GetLastIDOfTable('E'); // Ajouter les témoins dmGenData.Query1.SQL.text:='INSERT INTO W (I, E, X, R)'+ ' VALUES (:idParent, :idEvent, 1, ''CONJOINT'')'; dmGenData.Query1.ParamByName('idEvent').AsInteger:=no_eve; dmGenData.Query1.ParamByName('idParent').AsInteger:=parent1; dmGenData.Query1.ExecSQL; dmGenData.Query1.ParamByName('idParent').AsInteger:=parent2; dmGenData.Query1.ExecSQL; // Ajouter les références // noter que l'on doit ajouter les références (frmStemmaMainForm.Code.Text='X') // sur l'événement # frmStemmaMainForm.no.Text dmGenData.PutCode('P',no_eve); FidEvent:=no_Eve; // Sauvegarder les modifications dmGenData.SaveModificationTime(parent1); dmGenData.SaveModificationTime(parent2); // UPDATE DÉCÈS si la date est il y idA 100 ans !!! if (copy(SD2.text,1,1)='1') and not (SD2.text='100000000030000000000') then dateev:=Copy(SD2.text,2,4) else dateev:=FormatDateTime('YYYY',now); if ((StrtoInt(FormatDateTime('YYYY',now))-StrtoInt(dateev))>100) then begin dmGenData.UpdateIndLiving(parent1,'N',sender); dmGenData.UpdateIndLiving(parent2,'N',sender); dmGenData.NamesChanged(frmEditParents); end; dmGenData.EventChanged(frmEditParents); end; end; end; dmGenData.Query1.Close; lIsDefaultPhrase:= Label6.Visible; lidRelation:=no.Value; lidType:=ptrint(Y.items.objects[Y.ItemIndex]); lidChild:=idA.Value; lidParent:=idB.Value; lMemoText:=fraMemo1.text; lSDate:=sd2.text; If lIsDefaultPhrase then lPhrase:='' else lPhrase:=P.text; dmgendata.SaveRelationData(lidRelation,lPhrase, lSDate, lidType, prefered, lidParent, lidChild, lMemoText); if no.text='0' then begin no.text:=InttoStr(dmGenData.GetLastIDOfTable('R')); end; // Sauvegarder les modifications if StrtoInt(idA.Text)>0 then dmGenData.SaveModificationTime(idA.Value); if StrtoInt(idB.Text)>0 then dmGenData.SaveModificationTime(idB.Value); // UPDATE DÉCÈS si la date est il y idA 100 ans !!! if (copy(SD2.text,1,1)='1') and not (SD2.text='100000000030000000000') then dateev:=Copy(SD2.text,2,4) else dateev:=FormatDateTime('YYYY',now); if ((StrtoInt(FormatDateTime('YYYY',now))-StrtoInt(dateev))>100) then begin dmGenData.UpdateIndLiving(idA.Value,'N',Sender); dmGenData.UpdateIndLiving(idB.Value,'N',Sender); If (frmStemmaMainForm.actWinNameAndAttr.Checked) then frmNames.PopulateNom(self); end; end; procedure TfrmEditParents.btnParentOKClick(Sender: TObject); var lidRelation: Integer; lidNewID: Integer; begin ParentsSaveData(Sender); // Donc déplacer ce bloc à la fin de btnParentOK et // exécuter seulement si c'est vraiment une sortie par Button1 ou F10 // dmGenData.GetCode(code,nocode); if FidEvent<>-1 then begin lidRelation:= no.Value; lidNewID:=FidEvent; dmGenData.CopyCitation('R',lidRelation,'E',lidNewID); end; end; procedure TfrmEditParents.P2DblClick(Sender: TObject); begin P.Visible:=true; P2.Visible:=false; end; procedure TfrmEditParents.PDblClick(Sender: TObject); begin P2.Visible:=true; P.Visible:=false; end; procedure TfrmEditParents.PEditingDone(Sender: TObject); begin If length(P.Text)=0 then P.Text:=P1.Text; Label6.Visible:=(P.Text=P1.Text); P2.Text:=DecodePhrase(idA.Value,'ENFANT',P.Text,'R',No.Value); frmStemmaMainForm.AppendHistoryData('P',P.Text); end; procedure TfrmEditParents.SDEditingDone(Sender: TObject); begin SD2.Text:=InterpreteDate(SD.Text,1); SD.Text:=convertDate(SD.Text,1); frmStemmaMainForm.AppendHistoryData('SD',SD2.Text); end; procedure TfrmEditParents.Supprimer1Click(Sender: TObject); begin //If TableauCitations.Row>0 then // if Application.MessageBox(Pchar(Translation.Items[31]+ // TableauCitations.Cells[1,TableauCitations.Row]+Translation.Items[28]),pchar(SConfirmation),MB_YESNO)=IDYES then // begin // dm.Query1.SQL.Text:='DELETE FROM C WHERE no='+TableauCitations.Cells[0,TableauCitations.Row]; // dm.Query1.ExecSQL; // TableauCitations.DeleteRow(TableauCitations.Row); // // Sauvegarder les modifications // if StrtoInt(idA.Text)>0 then dmGenData.SaveModificationTime(idA.Value); // if StrtoInt(idB.Text)>0 then dmGenData.SaveModificationTime(idB.Value); // end; end; procedure TfrmEditParents.YChange(Sender: TObject); begin Y.ItemIndex; P1.Text:=dmGenData.GetTypePhrase(ptrint(Y.Items.Objects[Y.itemindex])); If Label6.Visible and (idA.Value>0) Then begin P.Text:=P1.Text; P2.Text:=DecodePhrase(idA.Value ,'ENFANT',P.Text,'R',No.Value); end else Label6.Visible:=(P.Text=P1.Text); end; procedure TfrmEditParents.SetEditMode(AValue: TenumEditRelation); begin if FEditMode=AValue then Exit; FEditMode:=AValue; end; procedure TfrmEditParents.SetIdRelation(AValue: integer); begin if no.Value=AValue then Exit; no.Value:=AValue; end; function TfrmEditParents.GetIdRelation: integer; begin result := no.Value; end; {$R *.lfm} { TfrmEditParents } end.
{ This unit performs calculus operations via basic numerical methods : integrals, derivatives, and extrema. All functions return real values. The last parameter in each function is a pointer to a "real" function that takes a single "real" parameter: for example, y(x). } Unit Calculus; Interface Function Derivative(x, dx : real; f : pointer) : real; Function Deriv( x, dx : real; f : pointer) : real; Function Integral(a, b, h : real; f : pointer; typ: byte) : real; {Function Integral(a, b, h : real; f : pointer) : real;} Function Length (a, b, h : real; f : pointer) : real; Function Surface(a, b, h : real; f : pointer) : real; Function Volume (a, b, h : real; f : pointer) : real; Procedure CenterTr(a, b, h : real; f : pointer; var xc,yc: real); Function Extremum(x, dx, tolerance : real; f : pointer) : real; Implementation type fofx = function(x : real) : real; { needed for function-evaluating } function derivative(x, dx : real; f : pointer) : real; var y : fofx; begin { Derivative of function at x: delta y over delta x } @y := f; { You supply x & delta x } derivative := (y(x + dx/2) - y(x - dx/2)) / dx; end; function Deriv( x, dx : real; f : pointer) : real; begin Deriv:=sqrt( 1+sqr( derivative(x,dx,f) ) ); end; function integral(a, b, h : real; f : pointer; typ: byte) : real; var x, summation : real; y : fofx; begin { Integrates function from a to b, } @y := f; { by approximating function with } summation := 0; { rectangles of width h. } x := a + h/2; while x < b do begin { Answer is sum of rectangle areas, each area being h*y(x). X is at the middle of the rectangle. } case typ of 0: summation:= summation+h*y(x); 1: summation:= summation+h*Deriv(x,h,f); 2: summation:= summation+h*sqr(y(x)); 3: summation:= summation+h*y(x)*Deriv(x,h,f); 4: summation:= summation+h*x*y(x); 5: summation:= summation+h*x*Deriv(x,h,f); end; x:=x+h; end; integral := summation; end; function Length(a, b, h : real; f : pointer) : real; begin Length:=integral(a,b,h,f,1); end; function Surface(a, b, h : real; f : pointer) : real; begin Surface:=2*pi*integral(a,b,h,f,2); end; function Volume(a, b, h : real; f : pointer) : real; begin Volume:=pi*integral(a,b,h,f,3); end; procedure CenterTr(a, b, h : real; f : pointer; var xc,yc: real); var squ:real; begin squ:=integral(a,b,h,f,0); xc:=integral(a,b,h,f,4)/squ; yc:=0.5*integral(a,b,h,f,2)/squ; end; function extremum(x, dx, tolerance : real; f : pointer) : real; { This function uses DuChez's Method for finding extrema of a function (yes, I seem to have invented it): taking three points, finding the parabola that connects them, and hoping that an extremum of the function is near the vertex of the parabola. If not, at least you have a new "x" to try... X is the initial value to go extremum-hunting at; dx is how far on either side of x to look. "Tolerance" is a parameter: if two consecutive iterations provide x-values within "tolerance" of each other, the answer is the average of the two. } var y : fofx; gotanswer, increasing, decreasing : boolean; oldx : real; itercnt : word; begin @y := f; gotanswer := false; increasing := false; decreasing := false; itercnt := 1; repeat { repeat until you have answer } oldx := x; x := oldx - dx*(y(x+dx) - y(x-dx)) / { this monster is the new value } (2*(y(x+dx) - 2*y(x) + y(x-dx))); { of "x" based DuChez's Method } if abs(x - oldx) <= tolerance then gotanswer := true { within tolerance: got an answer } else if (x > oldx) then begin if decreasing then begin { If "x" is increasing but it } decreasing := false; { had been decreasing, we're } dx := dx/2; { oscillating around the answer. } end; { Cut "dx" in half to home in on } increasing := true; { the extremum. } end else if (x < oldx) then begin if increasing then begin { same thing here, except "x" } increasing := false; { is now decreasing but had } dx := dx/2; { been increasing } end; decreasing := true; end; until gotanswer; extremum := (x + oldx) / 2; { spit out answer } end; end.
{******************************************************************************* Title: T2Ti ERP Description: Controller relacionado à tabela [NFE_FORMA_PAGAMENTO] The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> Albert Eije (T2Ti.COM) @version 1.0 *******************************************************************************} unit NfeFormaPagamentoController; interface uses Classes, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti, Atributos, VO, NfeFormaPagamentoVO, Generics.Collections, Biblioteca; type TNfeFormaPagamentoController = class(TController) private class var FDataSet: TClientDataSet; public class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False); class function ConsultaLista(pFiltro: String): TObjectList<TNfeFormaPagamentoVO>; class procedure Insere(pObjeto: TNfeFormaPagamentoVO); class procedure InsereLista(pListaObjetos: TObjectList<TNfeFormaPagamentoVO>); class function Altera(pObjeto: TNfeFormaPagamentoVO): Boolean; class function Exclui(pId: Integer): Boolean; class function GetDataSet: TClientDataSet; override; class procedure SetDataSet(pDataSet: TClientDataSet); override; class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>); end; implementation uses T2TiORM; class procedure TNfeFormaPagamentoController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean); var Retorno: TObjectList<TNfeFormaPagamentoVO>; begin try Retorno := TT2TiORM.Consultar<TNfeFormaPagamentoVO>(pFiltro, pPagina, pConsultaCompleta); TratarRetorno<TNfeFormaPagamentoVO>(Retorno); finally end; end; class function TNfeFormaPagamentoController.ConsultaLista(pFiltro: String): TObjectList<TNfeFormaPagamentoVO>; begin try Result := TT2TiORM.Consultar<TNfeFormaPagamentoVO>(pFiltro, '-1', True); finally end; end; class procedure TNfeFormaPagamentoController.Insere(pObjeto: TNfeFormaPagamentoVO); var UltimoID: Integer; begin try UltimoID := TT2TiORM.Inserir(pObjeto); Consulta('ID = ' + IntToStr(UltimoID), '0'); finally end; end; class procedure TNfeFormaPagamentoController.InsereLista(pListaObjetos: TObjectList<TNfeFormaPagamentoVO>); var ObjetoEnumerator: TEnumerator<TNfeFormaPagamentoVO>; ItemDaLista: TNfeFormaPagamentoVO; UltimoID: Integer; begin try FormatSettings.DecimalSeparator := '.'; ObjetoEnumerator := pListaObjetos.GetEnumerator; with ObjetoEnumerator do begin while MoveNext do begin ItemDaLista := Current; UltimoID := TT2TiORM.Inserir(ItemDaLista); end; end; finally FormatSettings.DecimalSeparator := ','; FreeAndNil(ObjetoEnumerator); end; end; class function TNfeFormaPagamentoController.Altera(pObjeto: TNfeFormaPagamentoVO): Boolean; begin try Result := TT2TiORM.Alterar(pObjeto); finally end; end; class function TNfeFormaPagamentoController.Exclui(pId: Integer): Boolean; var ObjetoLocal: TNfeFormaPagamentoVO; begin try ObjetoLocal := TNfeFormaPagamentoVO.Create; ObjetoLocal.Id := pId; Result := TT2TiORM.Excluir(ObjetoLocal); finally FreeAndNil(ObjetoLocal); end; end; class function TNfeFormaPagamentoController.GetDataSet: TClientDataSet; begin Result := FDataSet; end; class procedure TNfeFormaPagamentoController.SetDataSet(pDataSet: TClientDataSet); begin FDataSet := pDataSet; end; class procedure TNfeFormaPagamentoController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>); begin try TratarRetorno<TNfeFormaPagamentoVO>(TObjectList<TNfeFormaPagamentoVO>(pListaObjetos)); finally FreeAndNil(pListaObjetos); end; end; initialization Classes.RegisterClass(TNfeFormaPagamentoController); finalization Classes.UnRegisterClass(TNfeFormaPagamentoController); end.
program hmp2obj; uses sysutils, rs_world; function TestPath(s: string): string; begin result := s; if not FileExists(s) then begin writeln('file doesn''t exist: ', s); Halt; end; end; var tex_fname, text_fname, hmp_fname: string; world: TWorld; begin if Paramcount < 2 then begin writeln('not enough files specified'); writeln('usage: hmp2obj hmp text tex'); halt; end; hmp_fname := TestPath(ParamStr(1)); text_fname := TestPath(ParamStr(2)); tex_fname := TestPath(ParamStr(3)); world := TWorld.Create; world.LoadFromFiles(hmp_fname, text_fname, tex_fname); writeln('world loaded'); writeln('tile size: ', world.TileWidth, 'x', world.TileHeight); world.ExportToObj('heightmap.obj'); world.ExportToRaw('heightmap.raw'); writeln('world exported'); world.Free; end.
unit View.MainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, ViewModel.Main, Model.Main, Model.ProSu.Interfaces, Model.Interfaces; type TMainForm = class(TForm) LabelTitle: TLabel; LabelTotalSales: TLabel; LabelTotalSalesFigure: TLabel; ButtonInvoice: TButton; procedure FormCreate(Sender: TObject); procedure ButtonInvoiceClick(Sender: TObject); private { Private declarations } fViewModel: IMainViewModelInterface; fSubscriber: ISubscriberInterface; procedure setViewModel(const newViewModel: IMainViewModelInterface); procedure updateLabels; procedure updateTotalSalesFigure; procedure notificationFromProvider(const notifyClass: INotificationClass); public { Public declarations } property ViewModel: IMainViewModelInterface read fViewModel write setViewModel; end; var MainForm: TMainForm; implementation uses Model.ProSu.Subscriber, View.TestPrintInvoice, Declarations, Model.ProSu.InterfaceActions; {$R *.fmx} { TMainForm } procedure TMainForm.ButtonInvoiceClick(Sender: TObject); var tmpTest: TTestPrintInvoiceForm; begin tmpTest := TTestPrintInvoiceForm.Create(Self); tmpTest.Provider.subscribe(fSubscriber); tmpTest.Show; end; procedure TMainForm.FormCreate(Sender: TObject); begin fSubscriber := TProSuSubscriber.Create; fSubscriber.setUpdateSubscriberMethod(notificationFromProvider); end; procedure TMainForm.notificationFromProvider( const notifyClass: INotificationClass); var tmpNotifClass: TNotificationClass; begin if notifyClass is TNotificationClass then begin tmpNotifClass := notifyClass as TNotificationClass; if actUpdateTotalSalesFigure in tmpNotifClass.actions then LabelTotalSalesFigure.Text := Format('%10.2f', [tmpNotifClass.ActionValue]); end; end; procedure TMainForm.setViewModel(const newViewModel: IMainViewModelInterface); begin fViewModel := newViewModel; if not Assigned(fViewModel) then raise Exception.Create('Main View Model is required'); updateLabels; updateTotalSalesFigure; end; procedure TMainForm.updateLabels; begin LabelTitle.Text := fViewModel.LabelsText.Title; LabelTotalSales.Text := fViewModel.LabelsText.TotalSalesText; LabelTotalSalesFigure.Text := fViewModel.getTotalSalesValue; end; procedure TMainForm.updateTotalSalesFigure; begin ButtonInvoice.Text := fViewModel.LabelsText.IssueButtonCaption; end; end.
unit vk_object; interface uses Windows, ActiveX, SysUtils, Classes, Messages, Variants, Controls, MSXML, StdCtrls, DB, IBDatabase, IBCustomDataSet, IBQuery, IniFiles, Dialogs, XMLUnit; type TMode = ( m_rus_name, //Русское имя (метода или свойства) m_eng_name, //Англ. имя (метода или свойства) m_get_value, //1С читает значение свойства m_set_value, //1С изменяет значение свойства m_n_params, //1С получает число параметров метода (функции) m_execute //Выполнение метода (Функции) ); const XMLExt = '.xml'; // расширение XML-файлов TXTExt = '.txt'; // расширение TXT-файлов type T_vk_object = class(TObject) public C_ID_length, // - C_ID CHECK_DATE_length, // - CHECK_DATE TABEL_length, // - TABEL COST_length, // - COST DISH_NAME_length, // - DISH_NAME WEIGHT_length, // - WEIGHT MA_ID_length, // - MA_ID MENU_DATE_length : integer; // - MENU_DATE g_Value: OleVariant; //Значение свойства или возвращаемое значение функции g_NParams: Integer; //Количество параметров метода (функции) g_Params: PSafeArray; //Массив с параметрами функции g_Event, g_Event_Data: String; //Генерация события // СВОЙСТВА g_fname: String; // function prop1(mode: TMode): String; (*11*) function meth1(mode: TMode): String; function meth2(mode: TMode): String; function meth3(mode: TMode): String; function meth4(mode: TMode): String; function meth5(mode: TMode): String; function meth6(mode: TMode): String; function meth7(mode: TMode): String; function meth8(mode: TMode): String; function meth9(mode: TMode): String; (*12*) Constructor Create; Destructor Destroy; Override; protected g_IconType: Integer; g_Title: String; DB : TIBDatabase; DBt : TIBTransaction; Query : TIBQuery; function GetNParam(lIndex: Integer ): OleVariant; procedure PutNParam(lIndex: Integer; var varPut: OleVariant); function GetParamAsString(lIndex: Integer ): String; function GetParamAsInteger(lIndex: Integer ): Integer; function StrToLength(str: string; l: Integer) : string; procedure CheckXMLExport(C_ID : integer; FileName : string); procedure CheckTxtExport(C_ID : integer; FileName : string); procedure MenuXMLExport(MA_ID : integer; FileName : string); procedure MenuTxtExport(MA_ID : integer; FileName : string); end; implementation ////////////////////////////////////////////////////////////// //Конструктор класса Constructor T_vk_object.Create; begin inherited Create; g_Value:=''; g_NParams:=0; g_Params:=nil; g_Event:=''; g_Event_Data:=''; end; ////////////////////////////////////////////////////////////// //Деструктор класса destructor T_vk_object.Destroy; begin Query.Free; DBt.Free; DB.Free; inherited Destroy; end; // формантирование строки пробелами до нужной длины function T_vk_object.StrToLength(str: string; l: Integer) : string; var ii, lng : integer; buff : AnsiString; begin buff := ''; lng := Length(str); for ii := 1 to l do if ii <= lng then buff := buff + str[ii] else buff := buff + ' '; Result := buff; end; // Экспорт чека в XML procedure T_vk_object.CheckXMLExport(C_ID : integer; FileName : string); const XMLHeader = '<?xml version="1.0" encoding="windows-1251" ?>'#13#10; var i, l, k, CommaCount : integer; XMLStream : TFileStream; XMLFileName, bufstr, bufw, OrderCode : string; begin XMLFileName := FileName; try XMLStream := TFileStream.Create(XMLFileName, fmOpenReadWrite); XMLStream.Position := XMLStream.Size - length(ObjClose); except XMLStream := TFileStream.Create(XMLFileName, fmCreate); XMLStream.Write(XMLHeader,length(XMLHeader)); // открываем корень OpenObject(XMLStream,'CheckHistory'); end; // открываем новый объект OpenObject(XMLStream,'Check'); WriteAttribute(XMLStream,'C_ID',IntToStr(C_ID)); // извлечение чека из БД with Query do begin Close; SQL.Clear; SQL.Add('select * from checks where c_id = ' + IntToStr(C_ID)); Open; end; WriteAttribute(XMLStream,'CHECK_DATE', Query.FieldByName('CHECK_DATE').AsString); WriteAttribute(XMLStream,'TABEL',Query.FieldByName('TABEL').AsString); WriteAttribute(XMLStream,'SUM',Query.FieldByName('COST').AsString); OrderCode := Query.FieldByName('MENU').AsString; // разбор кода заказа CommaCount := 0; // подсчёт разделителей и звёздочек for i := 1 to length(OrderCode) do begin if OrderCode[i] = ',' then inc(CommaCount); end; // основной цикл l := 1; for i := 1 to CommaCount do begin bufstr := ''; bufw := ''; inc(l); repeat bufstr := bufstr + OrderCode[l]; inc(l); // поиск звёздочки if OrderCode[l] = '*' then begin k := l + 1; repeat bufw := bufw + OrderCode[k]; inc(k); until (OrderCode[k] = ',') or (k > length(OrderCode)); l := k; end; until (OrderCode[l] = ',') or (l > length(OrderCode)); OpenObject(XMLStream,'Dish'); WriteAttribute(XMLStream,'ME_ID',bufstr); // извлечение данных о MENU_ENTRY with Query do begin Close; SQL.Clear; SQL.Add('select dishes.dish_name, menu_entries.weight, menu_entries.cost'); SQL.Add('from dishes, menu_entries'); SQL.Add('where (dishes.d_id = menu_entries.d_id) and (menu_entries.me_id = ' + bufstr + ');'); Open; FetchAll; end; WriteAttribute(XMLStream,'DISH_NAME',Query.FieldByName('DISH_NAME').AsString); WriteAttribute(XMLStream,'WEIGHT_NOMINAL',Query.FieldByName('WEIGHT').AsString); WriteAttribute(XMLStream,'COST_NOMINAL',Query.FieldByName('COST').AsString); if bufw <> '' then begin WriteAttribute(XMLStream,'WEIGHT_ORDERED',bufw); WriteAttribute(XMLStream,'COST_ORDERED', IntToStr(round(StrToInt(bufw) / Query.FieldByName('WEIGHT').AsInteger * Query.FieldByName('COST').AsInteger))); end else begin WriteAttribute(XMLStream,'WEIGHT_ORDERED',Query.FieldByName('WEIGHT').AsString); WriteAttribute(XMLStream,'COST_ORDERED',Query.FieldByName('COST').AsString); end; CloseObject(XMLStream); end; // for i // закрываем объект CloseObject(XMLStream); // закрываем корень CloseObject(XMLStream); XMLStream.Free; end; // Экспорт чека в текстовый файл procedure T_vk_object.CheckTxtExport(C_ID : integer; FileName : string); var i, l, k, CommaCount : integer; TXTStream : TFileStream; StrStream : TStringStream; TXTFileName, bufstr, bufw, OrderCode, ExportBase, ExportTail : string; begin TXTFileName := FileName; try TXTStream := TFileStream.Create(FileName, fmOpenReadWrite); TXTStream.Position := TXTStream.Size; except TXTStream := TFileStream.Create(FileName, fmCreate); end; // извлечение чека из БД with Query do begin Close; SQL.Clear; SQL.Add('select * from checks where c_id = ' + IntToStr(C_ID)); Open; end; // формирование начала записи ExportBase := StrToLength(Query.FieldByName('C_ID').AsString,C_ID_length) + StrToLength(FormatDateTime('dd/mm/yyyy',Query.FieldByName('CHECK_DATE').AsVariant),CHECK_DATE_length) + StrToLength(Query.FieldByName('TABEL').AsString,TABEL_length); OrderCode := Query.FieldByName('MENU').AsString; // разбор кода заказа CommaCount := 0; StrStream := TStringStream.Create(''); // подсчёт разделителей и звёздочек for i := 1 to length(OrderCode) do begin if OrderCode[i] = ',' then inc(CommaCount); end; // основной цикл l := 1; for i := 1 to CommaCount do begin bufstr := ''; bufw := ''; inc(l); repeat bufstr := bufstr + OrderCode[l]; inc(l); // поиск звёздочки if OrderCode[l] = '*' then begin k := l + 1; repeat bufw := bufw + OrderCode[k]; inc(k); until (OrderCode[k] = ',') or (k > length(OrderCode)); l := k; end; until (OrderCode[l] = ',') or (l > length(OrderCode)); // извлечение данных о MENU_ENTRY with Query do begin Close; SQL.Clear; SQL.Add('select dishes.dish_name, menu_entries.weight, menu_entries.cost'); SQL.Add('from dishes, menu_entries'); SQL.Add('where (dishes.d_id = menu_entries.d_id) and (menu_entries.me_id = ' + bufstr + ');'); Open; end; // формирование хвоста записи if bufw = '' then begin ExportTail := StrToLength(Query.FieldByName('COST').AsString,COST_length) + StrToLength(Query.FieldByName('DISH_NAME').AsString,DISH_NAME_length) + StrToLength(Query.FieldByName('WEIGHT').AsString, WEIGHT_length) + #13#10; end else begin ExportTail := StrToLength(IntToStr(round(StrToInt(bufw) / Query.FieldByName('WEIGHT').AsInteger * Query.FieldByName('COST').AsInteger)),COST_length) + StrToLength(Query.FieldByName('DISH_NAME').AsString,DISH_NAME_length) + StrToLength(bufw,WEIGHT_length) + #13#10; end; // помещение полной записи в строковый поток StrStream.WriteString(ExportBase + ExportTail); end; // for i // копирование строкового потока в конец потока файла try StrStream.Position := 0; TXTStream.Position := TXTStream.Size; try TXTStream.CopyFrom(StrStream,StrStream.Size); finally TXTStream.Free; end; finally StrStream.Free; end; end; // Экспорт меню в XML procedure T_vk_object.MenuXMLExport(MA_ID : integer; FileName : string); const XMLHeader = '<?xml version="1.0" encoding="windows-1251" ?>'#13#10; var i, l, CommaCount : integer; XMLStream : TFileStream; XMLFileName, bufstr, MenuCode : string; begin XMLFileName := FileName; try XMLStream := TFileStream.Create(XMLFileName, fmOpenReadWrite); XMLStream.Position := XMLStream.Size - length(ObjClose); except XMLStream := TFileStream.Create(XMLFileName, fmCreate); XMLStream.Write(XMLHeader,length(XMLHeader)); // открываем корень OpenObject(XMLStream,'MenuHistory'); end; // открываем новый объект OpenObject(XMLStream,'Menu'); WriteAttribute(XMLStream,'MA_ID',IntToStr(MA_ID)); // извлечение чека из БД with Query do begin Close; SQL.Clear; SQL.Add('select * from menu_archives where ma_id = ' + IntToStr(MA_ID)); Open; end; WriteAttribute(XMLStream,'MENU_DATE', Query.FieldByName('MENU_DATE').AsString); MenuCode := Query.FieldByName('MENU').AsString; // разбор кода меню CommaCount := 0; // подсчёт разделителей for i := 1 to length(MenuCode) do begin if MenuCode[i] = ',' then inc(CommaCount); end; // основной цикл l := 1; for i := 1 to CommaCount do begin bufstr := ''; inc(l); repeat bufstr := bufstr + MenuCode[l]; inc(l); until (MenuCode[l] = ',') or (l > length(MenuCode)); OpenObject(XMLStream,'Dish'); WriteAttribute(XMLStream,'ME_ID',bufstr); // извлечение данных о MENU_ENTRY with Query do begin Close; SQL.Clear; SQL.Add('select dishes.dish_name, menu_entries.weight, menu_entries.cost, menu_entries.on_weight'); SQL.Add('from dishes, menu_entries'); SQL.Add('where (dishes.d_id = menu_entries.d_id) and (menu_entries.me_id = ' + bufstr + ');'); Open; FetchAll; end; WriteAttribute(XMLStream,'DISH_NAME',Query.FieldByName('DISH_NAME').AsString); WriteAttribute(XMLStream,'WEIGHT',Query.FieldByName('WEIGHT').AsString); WriteAttribute(XMLStream,'COST',Query.FieldByName('COST').AsString); WriteAttribute(XMLStream,'ON_WEIGHT',Query.FieldByName('ON_WEIGHT').AsString); CloseObject(XMLStream); end; // for i // закрываем объект CloseObject(XMLStream); // закрываем корень CloseObject(XMLStream); XMLStream.Free; end; // Экспорт меню в текстовый файл procedure T_vk_object.MenuTxtExport(MA_ID : integer; FileName : string); var i, l, CommaCount : integer; TXTStream : TFileStream; StrStream : TStringStream; TXTFileName, bufstr, MenuCode, ExportBase, ExportTail : string; begin TXTFileName := FileName; try TXTStream := TFileStream.Create(FileName, fmOpenReadWrite); TXTStream.Position := TXTStream.Size; except TXTStream := TFileStream.Create(FileName, fmCreate); end; // извлечение чека из БД with Query do begin Close; SQL.Clear; SQL.Add('select * from menu_archives where ma_id = ' + IntToStr(MA_ID)); Open; end; // формирование начала записи ExportBase := StrToLength(Query.FieldByName('Ma_Id').AsString,MA_ID_length) + StrToLength(FormatDateTime('dd/mm/yyyy',Query.FieldByName('MENU_DATE').AsVariant),MENU_DATE_length); MenuCode := Query.FieldByName('MENU').AsString; // разбор кода заказа CommaCount := 0; StrStream := TStringStream.Create(''); // подсчёт разделителей for i := 1 to length(MenuCode) do begin if MenuCode[i] = ',' then inc(CommaCount); end; // основной цикл l := 1; for i := 1 to CommaCount do begin bufstr := ''; inc(l); repeat bufstr := bufstr + MenuCode[l]; inc(l); until (MenuCode[l] = ',') or (l > length(MenuCode)); // извлечение данных о MENU_ENTRY with Query do begin Close; SQL.Clear; SQL.Add('select dishes.dish_name, menu_entries.weight, menu_entries.cost, menu_entries.on_weight'); SQL.Add('from dishes, menu_entries'); SQL.Add('where (dishes.d_id = menu_entries.d_id) and (menu_entries.me_id = ' + bufstr + ');'); Open; FetchAll; end; // формирование хвоста записи ExportTail := StrToLength(Query.FieldByName('COST').AsString,COST_length) + StrToLength(Query.FieldByName('DISH_NAME').AsString,DISH_NAME_length) + StrToLength(Query.FieldByName('WEIGHT').AsString,WEIGHT_length) + #13#10; // помещение полной записи в строковый поток StrStream.WriteString(ExportBase + ExportTail); end; // for i // копирование строкового потока в конец потока файла try StrStream.Position := 0; TXTStream.Position := TXTStream.Size; try TXTStream.CopyFrom(StrStream,StrStream.Size); finally TXTStream.Free; end; finally StrStream.Free; end; end; ///////////////////////////////////////////////////////////////////// function T_vk_object.prop1(mode: TMode): String; begin case mode of m_rus_name: Result:=''; m_eng_name: Result:=''; m_get_value: g_Value:=g_fname; m_set_value: ; end;//case end; (*13*) ///////////////////////////////////////////////////////////////////// // Коннект к базе function T_vk_object.meth1(mode: TMode): String; var s: String; ms: Integer; Config : TIniFile; begin case mode of m_rus_name: Result := 'Инициализация'; m_eng_name: Result := 'Init'; m_n_params: g_NParams := 2; //Количество параметров функции m_execute: begin DB := TIBDatabase.Create(nil); DBt := TIBTransaction.Create(nil); Query := TIBQuery.Create(nil); DB.DatabaseName := GetParamAsString(0); DB.LoginPrompt := false; DB.Params.Add('user_name=sysdba'); DB.Params.Add('PASSWORD=masterkey'); DB.Params.Add('lc_ctype=win1251'); DB.DefaultTransaction := DBt; Query.Database := DB; Query.Transaction := DBt; try DB.Connected := true; DBt.Active := true; except raise Exception.Create('Невозможно соединиться с базой данных.'); end; Config := TIniFile.Create(GetParamAsString(1)); C_ID_length := Config.ReadInteger('TxtFileFormat','C_ID',15); CHECK_DATE_length := Config.ReadInteger('TxtFileFormat','CHECK_DATE',17); TABEL_length := Config.ReadInteger('TxtFileFormat','TABEL',7); COST_length := Config.ReadInteger('TxtFileFormat','COST',7); DISH_NAME_length := Config.ReadInteger('TxtFileFormat','DISH_NAME',51); WEIGHT_length := Config.ReadInteger('TxtFileFormat','WEIGHT',5); MA_ID_length := Config.ReadInteger('TxtFileFormat','MA_ID',15); MENU_DATE_length := Config.ReadInteger('TxtFileFormat','MENU_DATE',17); Config.Free; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение всех чеков в текстовый файл function T_vk_object.meth2(mode: TMode): String; var FileName : String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьВсеЧекиВТекст'; m_eng_name: Result := 'ImportAllChecksToTXT'; m_n_params: g_NParams := 1; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select c_id from checks order by checks.check_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin CheckTxtExport(FieldByName('C_ID').AsInteger,FileName); Next; end; CheckTxtExport(FieldByName('C_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение всех чеков в файл XML function T_vk_object.meth3(mode: TMode): String; var FileName: String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьВсеЧекиВXML'; m_eng_name: Result := 'ImportAllChecksToXML'; m_n_params: g_NParams := 1; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select c_id from checks order by checks.check_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin CheckXMLExport(FieldByName('C_ID').AsInteger,FileName); Next; end; CheckXMLExport(FieldByName('C_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение всего архива меню в текстовый файл function T_vk_object.meth4(mode: TMode): String; var FileName: String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьВсеМенюВТекст'; m_eng_name: Result := 'ImportAllMenuToTXT'; m_n_params: g_NParams := 1; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select MA_ID from menu_archives order by menu_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin MenuTxtExport(FieldByName('MA_ID').AsInteger,FileName); Next; end; MenuTxtExport(FieldByName('MA_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение всего архива меню в файл XML function T_vk_object.meth5(mode: TMode): String; var FileName: String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьВсеМенюВXML'; m_eng_name: Result := 'ImportAllMenuToXML'; m_n_params: g_NParams := 1; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select MA_ID from menu_archives order by menu_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin MenuXMLExport(FieldByName('MA_ID').AsInteger,FileName); Next; end; MenuXMLExport(FieldByName('MA_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение чеков за период времени в текстовый файл function T_vk_object.meth6(mode: TMode): String; var FileName : String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьЧекиВТекст'; m_eng_name: Result := 'ImportChecksToTXT'; m_n_params: g_NParams := 3; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select c_id from checks where check_date between ''' + GetParamAsString(1) + ''' and ''' + GetParamAsString(2) + ''' order by checks.check_date'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin CheckTxtExport(FieldByName('C_ID').AsInteger,FileName); Next; end; CheckTxtExport(FieldByName('C_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение чеков зв период времени в файл XML function T_vk_object.meth7(mode: TMode): String; var FileName : String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьЧекиВXML'; m_eng_name: Result := 'ImportChecksToXML'; m_n_params: g_NParams := 3; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select c_id from checks where check_date between ''' + GetParamAsString(1) + ''' and ''' + GetParamAsString(2) + ''' order by checks.check_date'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin CheckXMLExport(FieldByName('C_ID').AsInteger,FileName); Next; end; CheckXMLExport(FieldByName('C_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение меню из архива за период времени в текстовый файл function T_vk_object.meth8(mode: TMode): String; var FileName: String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьМенюВТекст'; m_eng_name: Result := 'ImportMenuToTXT'; m_n_params: g_NParams := 3; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select MA_ID from menu_archives where menu_date between ''' + GetParamAsString(1) + ''' and ''' + GetParamAsString(2) + ''' order by menu_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin MenuTxtExport(FieldByName('MA_ID').AsInteger,FileName); Next; end; MenuTxtExport(FieldByName('MA_ID').AsInteger,FileName); Free; end; end; end;//case end; ///////////////////////////////////////////////////////////////////// // Извлечение меню из архива за период времени в файл XML function T_vk_object.meth9(mode: TMode): String; var FileName: String; i : integer; tmpQuery : TIBQuery; begin case mode of m_rus_name: Result := 'ИзвлечьМенюВXML'; m_eng_name: Result := 'ImportMenuToXML'; m_n_params: g_NParams := 3; //Количество параметров функции m_execute: begin with tmpQuery do begin FileName := GetParamAsString(0); tmpQuery := TIBQuery.Create(nil); Database := DB; Transaction := DBt; Close; SQL.Clear; SQL.Add('select MA_ID from menu_archives where menu_date between ''' + GetParamAsString(1) + ''' and ''' + GetParamAsString(2) + ''' order by menu_date;'); Open; FetchAll; First; for i := 1 to RecordCount - 1 do begin MenuXMLExport(FieldByName('MA_ID').AsInteger,FileName); Next; end; MenuXMLExport(FieldByName('MA_ID').AsInteger,FileName); Free; end; end; end;//case end; (*14*) //////////////////////////////////////////////////////////////////////// //Функция извлекает параметр из массива g_Params по его индексу function T_vk_object.GetNParam(lIndex: Integer ): OleVariant; var varGet : OleVariant; begin SafeArrayGetElement(g_Params,lIndex,varGet); GetNParam := varGet; end; //////////////////////////////////////////////////////////////////////// //Функция извлекает параметр из массива g_Params по его индексу. //Функция предполагает, что тип значения - строка function T_vk_object.GetParamAsString(lIndex: Integer ): String; var varGet : OleVariant; begin SafeArrayGetElement(g_Params,lIndex,varGet); try Result := varGet; except Raise Exception.Create('Параметр номер ' + IntToStr(lIndex+1) + ' не может быть преобразован в строку.'); end; end; //////////////////////////////////////////////////////////////////////// //Функция извлекает параметр из массива g_Params по его индексу. //Функция предполагает, что тип значения - целое число function T_vk_object.GetParamAsInteger(lIndex: Integer ): Integer; var varGet : OleVariant; begin SafeArrayGetElement(g_Params,lIndex,varGet); try Result := varGet; except Raise Exception.Create('Параметр номер ' + IntToStr(lIndex+1) + ' не может быть преобразован в целое число.'); end; end; //////////////////////////////////////////////////////////////////////// //Функция помещает значение в массив g_Params по указанному индексу procedure T_vk_object.PutNParam(lIndex: Integer; var varPut: OleVariant); begin SafeArrayPutElement(g_Params,lIndex,varPut); end; //////////////////////////////////////////////////////////////////// // Инициализация глобальных переменных initialization CoInitialize(nil); //////////////////////////////////////////////////////////////////// // Уничтожение глобальных переменных finalization CoUninitialize; end.
unit uAcessoView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uCadastroView, 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, System.Actions, Vcl.ActnList, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Mask, Vcl.Grids, Vcl.DBGrids, Vcl.Imaging.pngimage, StrUtils; type TAcessoView = class(TCadastroView) txtidacesso: TDBText; lbldescricao: TLabel; edtacesso: TDBEdit; tblCadastroidacesso: TIntegerField; tblCadastroacesso: TWideStringField; tblCadastrouscadast: TWideStringField; tblCadastrodtcadast: TSQLTimeStampField; tblCadastrousmodifi: TWideStringField; tblCadastrodtmodifi: TSQLTimeStampField; grdAcesso: TDBGrid; dtsAcesso: TDataSource; qryAcesso: TFDQuery; img1: TImage; img2: TImage; qryAcessoativo_flag: TWideStringField; qryAcessoidmenuusuario: TIntegerField; qryAcessoativo: TIntegerField; qryAcessoidmenu: TIntegerField; qryAcessomenu: TWideStringField; qryAcessoidmenuacesso: TIntegerField; qryAcessomenu_acesso: TWideStringField; qryAcessotag: TWideStringField; qryAcessoidusuario: TIntegerField; qryAcessousuario: TWideStringField; qryAcessologin: TWideStringField; qryAcessoidacesso: TIntegerField; qryAcessoacesso: TWideStringField; qryAux: TFDQuery; procedure FormCreate(Sender: TObject); procedure dtsCadastroDataChange(Sender: TObject; Field: TField); procedure grdAcessoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure FormShow(Sender: TObject); procedure qryAcessoativo_flagGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure grdAcessoCellClick(Column: TColumn); procedure grdAcessoDblClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure AjustarGridAcesso(AGrid: TDBGrid; AQuery: TFDQuery); end; var AcessoView: TAcessoView; implementation {$R *.dfm} uses uData, uMainView; procedure TAcessoView.AjustarGridAcesso(AGrid: TDBGrid; AQuery: TFDQuery); //var // I, Col: Integer; begin // Col := 0; // for I := 0 to AGrid.Columns.Count - 1 do // begin // if (AGrid.Columns[I].Index <> 9) and (AGrid.Columns[I].Visible) then // Col := Col + AGrid.Columns[I].Width; // end; AGrid.Columns.Items[0].Title.Caption := 'S/N'; AGrid.Columns[0].Width := 35; // AGrid.Columns[9].Width := AGrid.Width - Col; end; procedure TAcessoView.grdAcessoCellClick(Column: TColumn); var flag, idtag: String; begin inherited; if (not (qryAcesso.IsEmpty)) then begin if Column.FieldName = 'ativo_flag' then begin flag := IfThen(qryAcesso.FieldByName('ativo').AsInteger = 1, '0', '1'); idtag := qryAcesso.FieldByName('idmenuusuario').AsString; qryAux.Close; qryAux.SQL.Clear; qryAux.SQL.Add('UPDATE'); qryAux.SQL.Add(' menu_usuarios'); qryAux.SQL.Add('SET'); qryAux.SQL.Add(' ativo =:ativo,'); qryAux.SQL.Add(' usmodifi =:usmodifi,'); qryAux.SQL.Add(' dtmodifi =:dtmodifi'); qryAux.SQL.Add('where'); qryAux.SQL.Add(' idmenuusuario = :idmenuusuario'); qryAux.ParamByName('ativo').AsInteger := StrToInt(flag); qryAux.ParamByName('usmodifi').AsString := MainView.Usuario.getLogin(); qryAux.ParamByName('dtmodifi').AsDateTime := Now; qryAux.ParamByName('idmenuusuario').AsInteger := StrToInt(idtag); qryAux.ExecSQL; qryAcesso.Refresh; qryAcesso.Locate('idmenuusuario', Variant(idtag), []); end; end; end; procedure TAcessoView.grdAcessoDblClick(Sender: TObject); begin inherited; if grdAcesso.SelectedField <> qryAcesso.FieldByName('ativo_flag') then grdAcessoCellClick(grdAcesso.Columns[0]); end; procedure TAcessoView.grdAcessoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; if Column.Field = qryAcessoativo_flag then begin if qryAcesso.FieldByName('ativo').AsInteger = 1 then grdAcesso.Canvas.Draw(Rect.Left + 10, Rect.Top + 2 , img1.Picture.Graphic) else grdAcesso.Canvas.Draw(Rect.Left + 10, Rect.Top + 2 , img2.Picture.Graphic); grdAcesso.Canvas.Brush.Style := bsClear; grdAcesso.Canvas.TextOut(0, 0, ''); grdAcesso.Canvas.Font.Size := 0; grdAcesso.Canvas.FillRect(Rect); end; end; procedure TAcessoView.dtsCadastroDataChange(Sender: TObject; Field: TField); begin inherited; if (not (tblCadastro.IsEmpty)) then begin qryAcesso.Close; qryAcesso.SQL.Clear; qryAcesso.SQL.Add('SELECT * FROM vw_usuariosacessos WHERE idacesso ='+tblCadastroidacesso.AsString); qryAcesso.Open; grdAcesso.Enabled := not qryAcesso.IsEmpty; end; end; procedure TAcessoView.FormCreate(Sender: TObject); begin Titulo := 'Cadastro de Acessos'; Tabela := 'acessos'; inherited; end; procedure TAcessoView.FormShow(Sender: TObject); begin inherited; qryAcesso.Close; tblCadastro.Next; tblCadastro.Prior; AjustarGridAcesso(grdAcesso, qryAcesso); end; procedure TAcessoView.qryAcessoativo_flagGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin inherited; Text := EmptyStr; end; initialization RegisterClass(TAcessoView); end.
unit ChangePasswordForm; interface uses Classes, Forms, Controls, StdCtrls, Windows, Variants; type TfrmChangePassword = class(TForm) lblOldUserName: TLabel; edtOldUserName: TEdit; lblOldPassword: TLabel; edtOldPassword: TEdit; lblNewPassword: TLabel; edtNewPassword: TEdit; lblConfrimNewPassword: TLabel; edtConfirmNewPassword: TEdit; lblNewUserName: TLabel; edtNewUserName: TEdit; btnOk: TButton; btnCancel: TButton; procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var frmChangePassword: TfrmChangePassword; implementation uses ClientCommon; {$R *.DFM} procedure TfrmChangePassword.btnOkClick(Sender: TObject); var iRes: integer; begin if edtOldUserName.Text = '' then begin MessageBox(Self.Handle, 'Вы не ввели имя пользователя', 'Предупреждение', mb_OK + mb_IconWarning); edtOldUserName.SetFocus(); exit; end; if edtNewUserName.Text = '' then begin MessageBox(Self.Handle, 'Вы не ввели новое имя пользователя', 'Предупреждение', mb_OK + mb_IconWarning); edtNewUserName.SetFocus(); exit; end; if edtNewPassword.Text <> edtConfirmNewPassword.Text then begin MessageBox(Self.Handle, 'Введённые Вами пароли не совпадают!', 'Предупреждение', mb_OK + mb_IconWarning); edtNewPassword.Text:=''; edtConfirmNewPassword.Text:=''; exit; end; if not varIsEmpty(IServer) then begin iRes:= IServer.InsertRow('spd_Change_Login_Password', null, varArrayOf([iClientAppType, edtOldUserName.Text, edtOldPassword.Text, edtNewUserName.Text, edtNewPassword.Text, iEmployeeID])); if iRes < 0 then MessageBox(Self.Handle, 'Не удалось изменить Ваши данные!' + #10 + #13 + 'Проверьте их правильность.', 'Ошибка', mb_OK + mb_IconExclamation) else MessageBox(Self.Handle, 'Ваши данные были успешно изменены', 'Подтверждение', mb_OK + mb_IconInformation); Self.CLose(); end; end; procedure TfrmChangePassword.FormCreate(Sender: TObject); begin if varIsEmpty(IServer) then btnOK.Enabled:= false; end; procedure TfrmChangePassword.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close(); end; end.
unit uSearchIntegration; interface uses Forms, Classes, Dialogs, SysUtils, StrUtils, ToolsApi, fSearchOptions, ActiveX, Controls, uBigFastSearchDFM, Masks, fSearchProgress; const IID_IOTASourceEditor: TGUID = '{F17A7BD1-E07D-11D1-AB0B-00C04FB16FB3}'; IID_IOTAFormEditor: TGUID = '{F17A7BD2-E07D-11D1-AB0B-00C04FB16FB3}'; const ResultGroup = 'Big DFM Search'; procedure Register; type TStartFileEvent = procedure(FileName: string) of object; TSearchItem = class private FFileName: string; FCode: string; FSearch: string; FCallBack: TFoundEvent; FSearchOptions: TSearchOptions; FFindSQLDump: TStrings; public constructor Create(FileName: string; Code: string; Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings = nil); function CreateThread: TThread; end; TSearchThreadList = class private //FList: TList; FQueue: TList; FOnAllThreadsDone: TNotifyEvent; FRunningThread: TThread; FOnStartFile: TStartFileEvent; FIOTAWizard: IOTAWizard; FNoMoreFiles: Boolean; procedure DoThreadTerminated(Sender: TObject); procedure StartNextThread; public constructor Create; virtual; destructor Destroy; override; procedure AddSearch(FileName: String; Code: string; Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings = nil); property OnAllThreadsDone: TNotifyEvent read FOnAllThreadsDone write FOnAllThreadsDone; property OnStartFile: TStartFileEvent read FOnStartFile write FOnStartFile; procedure Cancel; procedure NewSearch; procedure NoMoreFiles; end; type TBigSearchWizard = class(TInterfacedObject, IOTAWizard, IOTAMenuWizard) private FResultCount: Integer; FProgressForm: TFrmSearchProgress; FStartTime: TDateTime; FCancelled: Boolean; FFinished: Boolean; protected function GetGroup(AShowGroup: Boolean; AGroupName: string = ResultGroup): IOTAMessageGroup; procedure BeforeSearch; virtual; procedure AfterSearch; virtual; procedure DoStartFile(FileName: String); virtual; procedure DoAfterSearch(Sender: TObject); virtual; procedure SetResultCount(AResultCount: Integer); procedure SearchOpenFiles(ASearchString: string; SearchOptions: TSearchOptions); virtual; procedure SearchFilesInProject(ASearchString: string; SearchOptions: TSearchOptions); virtual; procedure SearchFilesInFolder(ASearchString: string; AFolder: string; ARecursive: Boolean; SearchOptions: TSearchOptions); virtual; procedure OutputSearchResult(AFile: string; ALine, AColumn: Integer; AText: string); procedure ParseAndOutput(ACode: TStream; AFileName: string; ASearchText: string; SearchOptions: TSearchOptions); overload; procedure ParseAndOutput(ACode: string; AFileName: string; ASearchText: string; SearchOptions: TSearchOptions); overload; procedure DoFoundText(AFileName, AFormClass, AObjectName, APropertyName, AValue: string; ALine: Integer); procedure ClearMessages; procedure DoSearchCancelled(Sender: TObject); public // IOTANotifier procedure AfterSave; procedure BeforeSave; procedure Destroyed; procedure Modified; // IOTAWizard { Expert UI strings } function GetIDString: string; function GetName: string; function GetState: TWizardState; { Launch the AddIn } procedure Execute; // IOTAMenuWizard. Temporary. Add menu item in more flexible way later. function GetMenuText: string; end; implementation procedure Register; begin RegisterPackageWizard(TBigSearchWizard.Create as IOTAWizard); end; var _SearchThreadList: TSearchThreadList; function SearchThreadList: TSearchThreadList; begin if not Assigned(_SearchThreadList) then _SearchThreadList := TSearchThreadList.Create; Result := _SearchThreadList; end; { TBigSearchWizard } procedure TBigSearchWizard.AfterSave; begin // Not needed for wizard end; procedure TBigSearchWizard.AfterSearch; var Msg: string; begin SearchThreadList.OnAllThreadsDone := nil; SearchThreadList.OnStartFile := nil; FreeAndNil(FProgressForm); Msg := ''; if FCancelled then Msg := Msg + 'Search cancelled. '; if FResultCount = 0 then Msg := Msg + 'No results found. ' else Msg := Msg + IntToStr(FResultCount) + ' results found. '; Msg := Msg + 'Duration: ' + FormatDateTime('nn:ss', Now - FStartTime) + '. '; ShowMessage(Msg); SearchThreadList.FIOTAWizard := nil; end; procedure TBigSearchWizard.BeforeSave; begin // Not needed for wizard end; procedure TBigSearchWizard.BeforeSearch; begin ClearMessages; FStartTime := Now; FCancelled := False; FFinished := False; FProgressForm := TFrmSearchProgress.Create(Application); FProgressForm.Hide; FProgressForm.OnCancel := DoSearchCancelled; SearchThreadList.OnAllThreadsDone := DoAfterSearch; SearchThreadList.OnStartFile := DoStartFile; SearchThreadList.FIOTAWizard := Self; end; procedure TBigSearchWizard.ClearMessages; begin (BorlandIDEServices as IOTAMessageServices60).ClearMessageGroup(GetGroup(False)); SetResultCount(0); end; procedure TBigSearchWizard.Destroyed; begin // Clean up end; procedure TBigSearchWizard.DoAfterSearch(Sender: TObject); begin if FCancelled or FFinished then AfterSearch end; procedure TBigSearchWizard.DoFoundText(AFileName, AFormClass, AObjectName, APropertyName, AValue: string; ALine: Integer); begin OutputSearchResult(AFileName, ALine, 0, AFormClass + '.' + AObjectName + '.' + APropertyName + '=' + AValue); Application.ProcessMessages; end; procedure TBigSearchWizard.DoSearchCancelled(Sender: TObject); begin FCancelled := True; SearchThreadList.Cancel; end; procedure TBigSearchWizard.DoStartFile(FileName: String); begin if Assigned(FProgressForm) then FProgressForm.SetFileName(FileName); end; procedure TBigSearchWizard.Execute; begin with TFrmBigSearchOptions.Create(Application) do try if ShowModal = mrOK then begin SearchThreadList.NewSearch; BeforeSearch; try case SearchLocation of slOpenFiles: SearchOpenFiles(SearchString, SearchOptions); slProjectFiles: SearchFilesInProject(SearchString, SearchOptions); slDirectory: SearchFilesInFolder(SearchString, SearchFileMask, SearchRecursive, SearchOptions); end; finally // AfterSearch is triggered by thread manager //AfterSearch; // Tell the queue that there will be no more files. SearchThreadList.NoMoreFiles; end; end; finally Free; end; end; function TBigSearchWizard.GetGroup(AShowGroup: Boolean; AGroupName: string): IOTAMessageGroup; begin Result := (BorlandIDEServices as IOTAMessageServices60).GetGroup(ResultGroup); if Result = nil then Result := (BorlandIDEServices as IOTAMessageServices60).AddMessageGroup(ResultGroup); if AShowGroup then (BorlandIDEServices as IOTAMessageServices60).ShowMessageView(Result); end; function TBigSearchWizard.GetIDString: string; begin Result := 'GolezTrol.BigIDETools.SearchHelper'; end; function TBigSearchWizard.GetMenuText: string; begin Result := 'Big &DFM Search'; end; function TBigSearchWizard.GetName: string; begin Result := 'Big DFM Search'; end; function TBigSearchWizard.GetState: TWizardState; begin Result := [wsEnabled]; end; procedure TBigSearchWizard.Modified; begin // Not needed for wizard end; procedure TBigSearchWizard.OutputSearchResult(AFile: string; ALine, AColumn: Integer; AText: string); var p: Pointer; g: IOTAMessageGroup; begin g := GetGroup(True); // If a matching pas file is found, open that instead to prevent some serious // errors in Delphi 7.. // Skipped it to see how it acts in Delphi 2007. {if SameText(ExtractFileExt(AFile), '.dfm') then if FileExists(ChangeFileExt(AFile, '.pas')) then begin AFile := ChangeFileExt(AFile, '.pas'); ALine := 0; end;} SetResultCount(Succ(FResultCount)); // Ok, that's nasty (BorlandIDEServices as IOTAMessageServices60).AddToolMessage(AFile, AText, ResultGroup, ALine, AColumn, nil, p, g); end; procedure TBigSearchWizard.ParseAndOutput(ACode: TStream; AFileName: string; ASearchText: string; SearchOptions: TSearchOptions); var s: TStringStream; begin // Parse from stream. Actually copies the stream to a string and parses the string. s := TStringStream.Create(''); try s.CopyFrom(ACode, 0); ParseAndOutput(s.DataString, AFileName, ASearchText, SearchOptions); finally s.Free; end; end; procedure TBigSearchWizard.ParseAndOutput(ACode, AFileName, ASearchText: string; SearchOptions: TSearchOptions); var Code: string; s1, s2: TStringStream; begin Application.ProcessMessages; if FCancelled then Abort; Code := ACode; s1 := TStringStream.Create(Code); s2 := TStringStream.Create(''); try // Try and see if the stream contains a binary dfm. If so, convert it to // text. try ObjectResourceToText(s1, s2); // Parsing as binary is OK. s2 contains the text output. Code := s2.DataString; except // Parsing as binary failed. Assume text dfm. end; finally s1.Free; s2.Free; end; // Threading thingy failed (no thread safe queue?) Just do it synchronous. It's fast enough. ScanDFM(Code, AFileName, ASearchText, DoFoundText, SearchOptions); //SearchThreadList.AddSearch(AFileName, Code, ASearchText, DoFoundText, SearchOptions); end; procedure TBigSearchWizard.SearchFilesInFolder(ASearchString, AFolder: string; ARecursive: Boolean; SearchOptions: TSearchOptions); var Folder: string; Mask: string; FileName: string; FolderList: TStringList; FileStream: TFileStream; sr: TSearchRec; res: Integer; begin if not DirectoryExists(AFolder) then begin // Roughly check if a file mask is given. Mask := ExtractFileName(AFolder); Folder := ExtractFilePath(AFolder); if Mask = '' then Mask := '*.dfm'; if not DirectoryExists(Folder) then begin ShowMessageFmt('Folder not found:'#13'%s', [AFolder]); Exit; end; end else begin Folder := IncludeTrailingPathDelimiter(AFolder); Mask := '*.dfm' end; // No recursion, use a Folder stack. FolderList := TStringList.Create; try // Add the first folder to be searched. FolderList.Add(Folder); // Repeat the folder search until the list is empty. while (FolderList.Count > 0) and not FCancelled do begin Folder := FolderList[0]; FolderList.Delete(0); // Search all files. The mask must not be applied to the folders. res := FindFirst(Folder + '*.*', faAnyFile, sr); try while (res = 0) and not FCancelled do begin if ((sr.Attr and faDirectory) = faDirectory) then begin // If recursive searching is on, add folders to the folder stack, // except for '.' and '..'. if (sr.Name <> '.') and (sr.Name <> '..') and ARecursive then FolderList.Add(Folder + sr.Name + PathDelim); end else begin FileName := Folder + sr.Name; // Check if the filename matches the mask. if MatchesMask(sr.Name, Mask) then begin // Load the file from disk and parse it. // Note: files are always loaded from disk. Unsaved changes will // not be shown in the search result! FileStream := TFileStream.Create(FileName, fmOpenRead); try ParseAndOutput(FileStream, FileName, ASearchString, SearchOptions); finally FileStream.Free; end; end; end; res := FindNext(sr); end; finally FindClose(sr); end; end; finally FolderList.Free; FFinished := True; end; end; procedure TBigSearchWizard.SearchFilesInProject(ASearchString: string; SearchOptions: TSearchOptions); var ProjectGroup: IOTAProjectGroup; Project: IOTAProject; Modules: IOTAModuleServices; Module: IOTAModule; ModuleInfo: IOTAModuleInfo; i, j: Integer; FileName: string; FileStream: TFileStream; begin try Modules := (BorlandIDEServices as IOTAModuleServices); // Check if we can find a project group. for i := 0 to Modules.ModuleCount - 1 do begin Module := Modules.Modules[i]; if Supports(Module, IOTAProjectGroup, ProjectGroup) then Break; end; if Assigned(ProjectGroup) then begin // Traverse all projects in the project group. for i := 0 to ProjectGroup.ProjectCount - 1 do begin if FCancelled then Break; Project := ProjectGroup.Projects[i]; // Traverse all modules in the project. for j := 0 to Project.GetModuleCount - 1 do begin if FCancelled then Break; ModuleInfo := Project.GetModule(j); // If the module is a form or a datamodule, try to load and parse it. if (ModuleInfo.ModuleType = omtForm) or (ModuleInfo.ModuleType = omtDatamodule) then begin FileName := ChangeFileExt(ModuleInfo.FileName, '.dfm'); if FileExists(FileName) then begin // Note: Files are loaded from disk. New files, or in memory // changes that have not been saved, are not reflected in the // search result. FileStream := TFileStream.Create(FileName, fmOpenRead); try ParseAndOutput(FileStream, FileName, ASearchString, SearchOptions); finally FileStream.Free; end; end; end; end; end; end; finally FFinished := True; end; end; procedure TBigSearchWizard.SearchOpenFiles(ASearchString: string; SearchOptions: TSearchOptions); var Modules: IOTAModuleServices; Module: IOTAModule; i, j: Integer; FormEditor: IOTAFormEditor; SourceEditor: IOTASourceEditor; Resource: TMemoryStream; ResourceAdapter: IStream; Reader: IOTAEditReader; Source: string; Position, Count: Integer; Buffer: array[0..4096] of AnsiChar; begin try Modules := (BorlandIDEServices as IOTAModuleServices); // Search all open modules. for i := 0 to Modules.ModuleCount - 1 do begin if FCancelled then Break; Module := Modules.Modules[i]; // Search all files/units of the module. for j := 0 to Module.ModuleFileCount - 1 do begin if FCancelled then Break; if Supports(Module.ModuleFileEditors[j], IID_IOTAFormEditor, FormEditor) then begin // If the unit supports a form editor, the form editor is open. The dfm // code is retreived from this form editor. This search acutally searches // the in memory dfm, not the one on disk. Resource := TMemoryStream.Create; ResourceAdapter := TStreamAdapter.Create(Resource, soReference); try FormEditor.GetFormResource(ResourceAdapter); Resource.Position := 0; ParseAndOutput(Resource, FormEditor.FileName, ASearchString, SearchOptions); finally ResourceAdapter := nil; Resource.Free; end; end else if Supports(Module.ModuleFileEditors[j], IID_IOTASourceEditor, SourceEditor) then begin // If the module is a source editor, but the extension is .dfm, assume // this is a dfm source editor (like when you press Alt+F12 on a form) // Read the source from the source editor. This search actually searches // the in memory dfm, not the one on disk. if SameText(ExtractFileExt(Module.FileName), '.dfm') then begin Source := ''; Position := 0; Count := 4096; // A source editor only supports buffered reading through a reader. // Copy all pieces and put them in the source variable. Then parse it. Reader := SourceEditor.CreateReader; repeat Count := Reader.GetText(Position, Buffer, Count); Source := Source + String(Copy(Buffer, 0, Count)); Inc(Position, Count); until Count = 0; Reader := nil; ParseAndOutput(Source, SourceEditor.FileName, ASearchString, SearchOptions); end; end; end; end; finally FFinished := True; end; end; procedure TBigSearchWizard.SetResultCount(AResultCount: Integer); begin // Show the result count in the progress window. if Assigned(FProgressForm) then FProgressForm.SetFound(AResultCount); FResultCount := AResultCount; end; { TSearchThreadList } procedure TSearchThreadList.AddSearch(FileName, Code, Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings); begin // Create a queue item. FQueue.Add(TSearchItem.Create(FileName, Code, Search, CallBack, SearchOptions, FindSQLDump)); StartNextThread; end; procedure TSearchThreadList.Cancel; var i: Integer; begin // If any thread is still running, ignore it. if Assigned(FRunningThread) then TScanDFMThread(FRunningThread).Abandon; FRunningThread := nil; // Clear the queue for i := FQueue.Count - 1 downto 0 do begin TObject(FQueue[i]).Free; FQueue.Delete(i); end; // Notify the wizard we're done if Assigned(FOnAllThreadsDone) then FOnAllThreadsDone(Self); end; constructor TSearchThreadList.Create; begin inherited Create; FQueue := TList.Create; end; destructor TSearchThreadList.Destroy; begin FQueue.Free; inherited; end; procedure TSearchThreadList.DoThreadTerminated(Sender: TObject); begin // If the thread is not the current running thread, ignore it. // Could be a hanging thread from earlier searches, although that shouldn't // trigger this event anymore. if FRunningThread = Sender then begin FRunningThread := nil; StartNextThread; end; end; procedure TSearchThreadList.NewSearch; begin FNoMoreFiles := False; end; procedure TSearchThreadList.NoMoreFiles; begin FNoMoreFiles := True; StartNextThread; // Forces AllThreadsDoneEvent end; procedure TSearchThreadList.StartNextThread; var i: Integer; q: TSearchItem; begin // Only start the next thread when there is no thread active. if FRunningThread = nil then begin while FNoMoreFiles = False do begin // Start the next search, if any, or notify the wizard we're done. if FQueue.Count > 0 then begin // Get the next item from the queue. Notify the wizard of which file it is. // Create and start the thread and remove the item from the queue. i := FQueue.Count - 1; q := TSearchItem(FQueue[i]); FQueue.Delete(i); FRunningThread := q.CreateThread; FRunningThread.OnTerminate := DoThreadTerminated; if Assigned(FOnStartFile) then FOnStartFile(q.FFileName); FRunningThread.Start; q.Free; end else Sleep(1); // Give up thread slice while waiting for more files. end; if Assigned(FOnAllThreadsDone) then FOnAllThreadsDone(Self); end; end; { TSearchItem } constructor TSearchItem.Create(FileName, Code, Search: string; CallBack: TFoundEvent; SearchOptions: TSearchOptions; FindSQLDump: TStrings); begin inherited Create; FFileName := FileName; FCode := Code; FSearch := Search; FCallBack := CallBack; FSearchOptions := SearchOptions; FFindSQLDump := FindSQLDump end; function TSearchItem.CreateThread: TThread; begin Result := TScanDFMThread.Create(FFileName, FCode, FSearch, FCallBack, FSearchOptions, FFindSQLDump); end; initialization finalization _SearchThreadList.Free; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.RandomGenerator; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses {$ifdef windows}Windows,MMSystem,{$endif} {$ifdef unix}dl,BaseUnix,Unix,UnixType,{$endif} SysUtils,Classes,Math,SyncObjs, PasVulkan.Types; type PpvRandomGeneratorPCG32=^TpvRandomGeneratorPCG32; TpvRandomGeneratorPCG32=record State:TpvUInt64; Increment:TpvUInt64; end; PpvRandomGeneratorSplitMix64=^TpvRandomGeneratorSplitMix64; TpvRandomGeneratorSplitMix64=TpvUInt64; PpvRandomGeneratorLCG64=^TpvRandomGeneratorLCG64; TpvRandomGeneratorLCG64=TpvUInt64; PpvRandomGeneratorMWC=^TpvRandomGeneratorMWC; TpvRandomGeneratorMWC=record x:TpvUInt32; y:TpvUInt32; c:TpvUInt32; end; PpvRandomGeneratorXorShift128=^TpvRandomGeneratorXorShift128; TpvRandomGeneratorXorShift128=record x,y,z,w:TpvUInt32; end; PpvRandomGeneratorXorShift128Plus=^TpvRandomGeneratorXorShift128Plus; TpvRandomGeneratorXorShift128Plus=record s:array[0..1] of TpvUInt64; end; PpvRandomGeneratorXorShift1024=^TpvRandomGeneratorXorShift1024; TpvRandomGeneratorXorShift1024=record s:array[0..15] of TpvUInt64; p:TpvInt32; end; PpvRandomGeneratorCMWC4096=^TpvRandomGeneratorCMWC4096; TpvRandomGeneratorCMWC4096=record Q:array[0..4095] of TpvUInt64; QC:TpvUInt64; QJ:TpvUInt64; end; PpvRandomGeneratorState=^TpvRandomGeneratorState; TpvRandomGeneratorState=record LCG64:TpvRandomGeneratorLCG64; XorShift1024:TpvRandomGeneratorXorShift1024; CMWC4096:TpvRandomGeneratorCMWC4096; end; TpvRandomGenerator=class private fState:TpvRandomGeneratorState; fGaussianFloatUseLast:boolean; fGaussianFloatLast:single; fGaussianDoubleUseLast:boolean; fGaussianDoubleLast:double; fCriticalSection:TCriticalSection; public constructor Create; destructor Destroy; override; procedure Reinitialize(FixedSeed:TpvUInt64=TpvUInt64($ffffffffffffffff)); function Get32:TpvUInt32; function Get64:TpvUInt64; function Get(Limit:TpvUInt32):TpvUInt32; function GetFloat:single; // -1.0.0 .. 1.0 function GetFloatAbs:single; // 0.0 .. 1.0 function GetDouble:double; // -1.0.0 .. 1.0 function GetDoubleAbs:Double; // 0.0 .. 1.0 function GetGaussianFloat:single; // -1.0 .. 1.0 function GetGaussianFloatAbs:single; // 0.0 .. 1.0 function GetGaussianDouble:double; // -1.0 .. 1.0 function GetGaussianDoubleAbs:double; // 0.0 .. 1.0 function GetGaussian(Limit:TpvUInt32):TpvUInt32; end; TpvRandomUnique32BitSequence=class private fIndex:TpvUInt32; fIntermediateOffset:TpvUInt32; function PermuteQPR(x:TpvUInt32):TpvUInt32; public constructor Create(const Seed1:TpvUInt32=$b46f23c7;const Seed2:TpvUInt32=$a54c2364); destructor Destroy; override; function Next:TpvUInt32; end; { TpvPCG32 } TpvPCG32=record private const DefaultState=TpvUInt64($853c49e6748fea9b); DefaultStream=TpvUInt64($da3e39cb94b95bdb); Mult=TpvUInt64($5851f42d4c957f2d); private fState:TpvUInt64; fIncrement:TpvUInt64; public procedure Init(const aSeed:TpvUInt64=0); function Get32:TpvUInt32; {$ifdef caninline}inline;{$endif} function Get64:TpvUInt64; {$ifdef caninline}inline;{$endif} function GetBiasedBounded32Bit(const aRange:TpvUInt32):TpvUInt32; {$ifdef caninline}inline;{$endif} function GetUnbiasedBounded32Bit(const aRange:TpvUInt32):TpvUInt32; function GetFloat:single; // -1.0 .. 1.0 function GetFloatAbs:single; // 0.0 .. 1.0 function GetDouble:double; // -1.0 .. 1.0 function GetDoubleAbs:Double; // 0.0 .. 1.0 end; function PCG32Next(var State:TpvRandomGeneratorPCG32):TpvUInt64; {$ifdef caninline}inline;{$endif} function SplitMix64Next(var State:TpvRandomGeneratorSplitMix64):TpvUInt64; {$ifdef caninline}inline;{$endif} function LCG64Next(var State:TpvRandomGeneratorLCG64):TpvUInt64; {$ifdef caninline}inline;{$endif} function XorShift128Next(var State:TpvRandomGeneratorXorShift128):TpvUInt32; {$ifdef caninline}inline;{$endif} function XorShift128PlusNext(var State:TpvRandomGeneratorXorShift128Plus):TpvUInt64; {$ifdef caninline}inline;{$endif} procedure XorShift128PlusJump(var State:TpvRandomGeneratorXorShift128Plus); function XorShift1024Next(var State:TpvRandomGeneratorXorShift1024):TpvUInt64; {$ifdef caninline}inline;{$endif} procedure XorShift1024Jump(var State:TpvRandomGeneratorXorShift1024); function CMWC4096Next(var State:TpvRandomGeneratorCMWC4096):TpvUInt64; {$ifdef caninline}inline;{$endif} implementation {$if defined(fpc) and declared(BSRDWord)} function CLZDWord(Value:TpvUInt32):TpvUInt32; begin if Value=0 then begin result:=0; end else begin result:=31-BSRDWord(Value); end; end; {$elseif defined(cpu386)} function CLZDWord(Value:TpvUInt32):TpvUInt32; assembler; register; {$ifdef fpc}nostackframe;{$endif} asm bsr edx,eax jnz @Done xor edx,edx not edx @Done: mov eax,31 sub eax,edx end; {$elseif defined(cpux64) or defined(cpuamd64)} function CLZDWord(Value:TpvUInt32):TpvUInt32; assembler; register; {$ifdef fpc}nostackframe;{$endif} asm {$ifndef fpc} .NOFRAME {$endif} {$ifdef Windows} bsr ecx,ecx jnz @Done xor ecx,ecx not ecx @Done: mov eax,31 sub eax,ecx {$else} bsr edi,edi jnz @Done xor edi,edi not edi @Done: mov eax,31 sub eax,edi {$endif} end; {$else} function CLZDWord(Value:TpvUInt32):TPasMPInt32; const CLZDebruijn32Multiplicator=TpvUInt32($07c4acdd); CLZDebruijn32Shift=27; CLZDebruijn32Mask=31; CLZDebruijn32Table:array[0..31] of TpvInt32=(31,22,30,21,18,10,29,2,20,17,15,13,9,6,28,1,23,19,11,3,16,14,7,24,12,4,8,25,5,26,27,0); begin if Value=0 then begin result:=32; end else begin Value:=Value or (Value shr 1); Value:=Value or (Value shr 2); Value:=Value or (Value shr 4); Value:=Value or (Value shr 8); Value:=Value or (Value shr 16); result:=CLZDebruijn32Table[((TpvUInt32(Value)*CLZDebruijn32Multiplicator) shr CLZDebruijn32Shift) and CLZDebruijn32Mask]; end; end; {$ifend} function PCG32Next(var State:TpvRandomGeneratorPCG32):TpvUInt64; {$ifdef caninline}inline;{$endif} var OldState:TpvUInt64; XorShifted,Rot:TpvUInt32; begin OldState:=State.State; State.State:=(OldState*TpvUInt64(6364136223846793005))+(State.Increment or 1); XorShifted:=TpvUInt64((OldState shr 18) xor OldState) shr 27; Rot:=OldState shr 59; result:=(XorShifted shr rot) or (TpvUInt64(XorShifted) shl ((-Rot) and 31)); end; function SplitMix64Next(var State:TpvRandomGeneratorSplitMix64):TpvUInt64; {$ifdef caninline}inline;{$endif} var z:TpvUInt64; begin State:=State+{$ifndef fpc}TpvUInt64{$endif}($9e3779b97f4a7c15); z:=State; z:=(z xor (z shr 30))*{$ifndef fpc}TpvUInt64{$endif}($bf58476d1ce4e5b9); z:=(z xor (z shr 27))*{$ifndef fpc}TpvUInt64{$endif}($94d049bb133111eb); result:=z xor (z shr 31); end; function LCG64Next(var State:TpvRandomGeneratorLCG64):TpvUInt64; {$ifdef caninline}inline;{$endif} begin State:=(State*TpvUInt64(2862933555777941757))+TpvUInt64(3037000493); result:=State; end; function XorShift128Next(var State:TpvRandomGeneratorXorShift128):TpvUInt32; {$ifdef caninline}inline;{$endif} var t:TpvUInt32; begin t:=State.x xor (State.x shl 11); State.x:=State.y; State.y:=State.z; State.z:=State.w; State.w:=(State.w xor (State.w shr 19)) xor (t xor (t shr 8)); result:=State.w; end; function XorShift128PlusNext(var State:TpvRandomGeneratorXorShift128Plus):TpvUInt64; {$ifdef caninline}inline;{$endif} var s0,s1:TpvUInt64; begin s1:=State.s[0]; s0:=State.s[1]; State.s[0]:=s0; s1:=s1 xor (s1 shl 23); State.s[1]:=((s1 xor s0) xor (s1 shr 18)) xor (s0 shr 5); result:=State.s[1]+s0; end; procedure XorShift128PlusJump(var State:TpvRandomGeneratorXorShift128Plus); const Jump:array[0..1] of TpvUInt64= (TpvUInt64($8a5cd789635d2dff), TpvUInt64($121fd2155c472f96)); var i,b:TpvInt32; s0,s1:TpvUInt64; begin s0:=0; s1:=0; for i:=0 to 1 do begin for b:=0 to 63 do begin if (Jump[i] and TpvUInt64(TpvUInt64(1) shl b))<>0 then begin s0:=s0 xor State.s[0]; s1:=s1 xor State.s[1]; end; XorShift128PlusNext(State); end; end; State.s[0]:=s0; State.s[1]:=s1; end; function XorShift1024Next(var State:TpvRandomGeneratorXorShift1024):TpvUInt64; {$ifdef caninline}inline;{$endif} var s0,s1:TpvUInt64; begin s0:=State.s[State.p and 15]; State.p:=(State.p+1) and 15; s1:=State.s[State.p]; s1:=s1 xor (s1 shl 31); State.s[State.p]:=((s1 xor s0) xor (s1 shr 11)) xor (s0 shr 30); result:=State.s[State.p]*TpvUInt64(1181783497276652981); end; procedure XorShift1024Jump(var State:TpvRandomGeneratorXorShift1024); const Jump:array[0..15] of TpvUInt64= (TpvUInt64($84242f96eca9c41d), TpvUInt64($a3c65b8776f96855), TpvUInt64($5b34a39f070b5837), TpvUInt64($4489affce4f31a1e), TpvUInt64($2ffeeb0a48316f40), TpvUInt64($dc2d9891fe68c022), TpvUInt64($3659132bb12fea70), TpvUInt64($aac17d8efa43cab8), TpvUInt64($c4cb815590989b13), TpvUInt64($5ee975283d71c93b), TpvUInt64($691548c86c1bd540), TpvUInt64($7910c41d10a1e6a5), TpvUInt64($0b5fc64563b3e2a8), TpvUInt64($047f7684e9fc949d), TpvUInt64($b99181f2d8f685ca), TpvUInt64($284600e3f30e38c3)); var i,b,j:TpvInt32; t:array[0..15] of TpvUInt64; begin for i:=0 to 15 do begin t[i]:=0; end; for i:=0 to 15 do begin for b:=0 to 63 do begin if (Jump[i] and TpvUInt64(TpvUInt64(1) shl b))<>0 then begin for j:=0 to 15 do begin t[j]:=t[j] xor State.s[(j+State.p) and 15]; end; end; XorShift1024Next(State); end; end; for i:=0 to 15 do begin State.s[(i+State.p) and 15]:=t[i]; end; end; function CMWC4096Next(var State:TpvRandomGeneratorCMWC4096):TpvUInt64; {$ifdef caninline}inline;{$endif} var x,t:TpvUInt64; begin State.QJ:=(State.QJ+1) and high(State.Q); x:=State.Q[State.QJ]; t:=(x shl 58)+State.QC; State.QC:=x shr 6; inc(t,x); if x<t then begin inc(State.QC); end; State.Q[State.QJ]:=t; result:=t; end; constructor TpvRandomGenerator.Create; begin inherited Create; fCriticalSection:=TCriticalSection.Create; Reinitialize; end; destructor TpvRandomGenerator.Destroy; begin fCriticalSection.Free; inherited Destroy; end; {$ifdef win32} type HCRYPTPROV=TpvUInt32; const PROV_RSA_FULL=1; CRYPT_VERIFYCONTEXT=$f0000000; CRYPT_SILENT=$00000040; CRYPT_NEWKEYSET=$00000008; function CryptAcquireContext(var phProv:HCRYPTPROV;pszContainer:PAnsiChar;pszProvider:PAnsiChar;dwProvType:TpvUInt32;dwFlags:TpvUInt32):LONGBOOL; stdcall; external advapi32 name 'CryptAcquireContextA'; function CryptReleaseContext(hProv:HCRYPTPROV;dwFlags:DWORD):BOOL; stdcall; external advapi32 name 'CryptReleaseContext'; function CryptGenRandom(hProv:HCRYPTPROV;dwLen:DWORD;pbBuffer:Pointer):BOOL; stdcall; external advapi32 name 'CryptGenRandom'; function CoCreateGuid(var guid:TGUID):HResult; stdcall; external 'ole32.dll'; {$endif} {$ifdef fpc} {$notes off} {$endif} procedure TpvRandomGenerator.Reinitialize(FixedSeed:TpvUInt64=TpvUInt64($ffffffffffffffff)); const N=25; CountStateQWords=(SizeOf(TpvRandomGeneratorState) div SizeOf(TpvUInt64)); type PStateQWords=^TStateQWords; TStateQWords=array[0..CountStateQWords-1] of TpvUInt64; var i,j:TpvInt32; UnixTimeInMilliSeconds:TpvInt64; HashState:TpvUInt64; LCG64:TpvRandomGeneratorLCG64; PCG32:TpvRandomGeneratorPCG32; SplitMix64:TpvRandomGeneratorSplitMix64; {$ifdef unix} f:file of TpvUInt32; ura,urb:TpvUInt32; OLdFileMode:TpvInt32; {$else} {$ifdef win32} lpc,lpf:TpvInt64; pp,p:pwidechar; st:ansistring; {$endif} {$endif} {$ifdef win32} function GenerateRandomBytes(var Buffer;Bytes:Cardinal):boolean; var CryptProv:HCRYPTPROV; begin try if not CryptAcquireContext(CryptProv,nil,nil,PROV_RSA_FULL,CRYPT_VERIFYCONTEXT{ or CRYPT_SILENT}) then begin if not CryptAcquireContext(CryptProv,nil,nil,PROV_RSA_FULL,CRYPT_NEWKEYSET) then begin result:=false; exit; end; end; FillChar(Buffer,Bytes,#0); result:=CryptGenRandom(CryptProv,Bytes,@Buffer); CryptReleaseContext(CryptProv,0); except result:=false; end; end; function GetRandomGUIDGarbage:ansistring; var g:TGUID; begin CoCreateGUID(g); SetLength(result,sizeof(TGUID)); Move(g,result[1],sizeof(TGUID)); end; {$endif} begin fCriticalSection.Enter; try if FixedSeed=TpvUInt64($ffffffffffffffff) then begin UnixTimeInMilliSeconds:=round((SysUtils.Now-25569.0)*86400000.0); {$ifdef nunix} ura:=0; urb:=0; OldFileMode:=FileMode; FileMode:=0; AssignFile(f,'/dev/urandom'); {$i-}System.Reset(f,1);{$i+} if IOResult=0 then begin System.Read(f,ura); System.Read(f,urb); for i:=0 to CountStateDWords-1 do begin System.Read(f,PStateDWords(pointer(@fState))^[i]); end; CloseFile(f); end else begin AssignFile(f,'/dev/random'); {$i-}System.Reset(f,1);{$i+} if IOResult=0 then begin System.Read(f,ura); System.Read(f,urb); for i:=0 to CountStateDWords-1 do begin System.Read(f,PStateDWords(pointer(@fState))^[i]); end; CloseFile(f); end else begin LCG64:=((TpvUInt64(UnixTimeInMilliSeconds) shl 31) or (TpvUInt64(UnixTimeInMilliSeconds) shr 33)) xor TpvUInt64($4c2a9d217a5cde81); for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=LCG64Next(LCG64); end; end; end; FileMode:=OldFileMode; SplitMix64:=TpvUInt64(UnixTimeInMilliSeconds) xor TpvUInt64($7a5cde814c2a9d21); for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=PStateQWords(pointer(@fState))^[i] xor SplitMix64Next(SplitMix64); end; {$else} {$ifdef win32} if not GenerateRandomBytes(fState,SizeOf(TpvRandomGeneratorState)) then begin {$ifdef fpc} LCG64:=GetTickCount64; {$else} LCG64:=GetTickCount; {$endif} LCG64:=LCG64 xor (((TpvUInt64(UnixTimeInMilliSeconds) shl 31) or (TpvUInt64(UnixTimeInMilliSeconds) shr 33)) xor TpvUInt64($4c2a9d217a5cde81)); for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=LCG64Next(LCG64); end; end; begin QueryPerformanceCounter(lpc); QueryPerformanceFrequency(lpf); PCG32.State:=lpc; PCG32.Increment:=lpf; SplitMix64:=(TpvUInt64(GetCurrentProcessId) shl 32) or GetCurrentThreadId; for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=PStateQWords(pointer(@fState))^[i] xor (PCG32Next(PCG32)+SplitMix64Next(SplitMix64)); end; end; i:=0; HashState:=TpvUInt64(4695981039346656037); pp:=GetEnvironmentStringsW; if assigned(pp) then begin p:=pp; while assigned(p) and (p^<>#0) do begin while assigned(p) and (p^<>#0) do begin HashState:=(HashState xor word(p^))*TpvUInt64(1099511628211); PStateQWords(pointer(@fState))^[i]:=PStateQWords(pointer(@fState))^[i] xor HashState; inc(i); if i>=CountStateQWords then begin i:=0; end; inc(p); end; inc(p); end; FreeEnvironmentStringsW(pointer(p)); end; pp:=pointer(GetCommandLineW); if assigned(pp) then begin p:=pp; while assigned(p) and (p^<>#0) do begin HashState:=(HashState xor word(p^))*TpvUInt64(1099511628211); PStateQWords(pointer(@fState))^[i]:=PStateQWords(pointer(@fState))^[i] xor HashState; inc(i); if i>=CountStateQWords then begin i:=0; end; inc(p); end; end; st:=GetRandomGUIDGarbage; for j:=1 to length(st) do begin HashState:=(HashState xor byte(st[j]))*TpvUInt64(1099511628211); PStateQWords(pointer(@fState))^[i]:=PStateQWords(pointer(@fState))^[i] xor HashState; inc(i); if i>=CountStateQWords then begin i:=0; end; end; SetLength(st,0); {$else} SplitMix64:=TpvUInt64(UnixTimeInMilliSeconds) xor TpvUInt64($7a5cde814c2a9d21); for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=SplitMix64Next(SplitMix64); end; {$endif} {$endif} end else begin SplitMix64:=TpvUInt64(FixedSeed) xor TpvUInt64($7a5cde814c2a9d21); for i:=0 to CountStateQWords-1 do begin PStateQWords(pointer(@fState))^[i]:=SplitMix64Next(SplitMix64); end; end; XorShift1024Jump(fState.XorShift1024); fGaussianFloatUseLast:=false; fGaussianFloatLast:=0.0; fGaussianDoubleUseLast:=false; fGaussianDoubleLast:=0.0; finally fCriticalSection.Leave; end; end; {$ifdef fpc} {$notes on} {$endif} function TpvRandomGenerator.Get32:TpvUInt32; begin result:=Get64 shr 32; end; function TpvRandomGenerator.Get64:TpvUInt64; begin fCriticalSection.Enter; try result:=LCG64Next(fState.LCG64)+ XorShift1024Next(fState.XorShift1024)+ CMWC4096Next(fState.CMWC4096); finally fCriticalSection.Leave; end; end; function TpvRandomGenerator.Get(Limit:TpvUInt32):TpvUInt32; begin if (Limit and $ffff0000)=0 then begin result:=((Get32 shr 16)*Limit) shr 16; end else begin result:=(TpvUInt64(Get32)*Limit) shr 32; end; end; function TpvRandomGenerator.GetFloat:single; // -1.0 .. 1.0 var t:TpvUInt32; begin t:=Get32; t:=(((t shr 9) and $7fffff)+((t shr 8) and 1)) or $40000000; result:=single(pointer(@t)^)-3.0; end; function TpvRandomGenerator.GetFloatAbs:single; // 0.0 .. 1.0 var t:TpvUInt32; begin t:=Get32; t:=(((t shr 10) and $3fffff)+((t shr 9) and 1)) or $40000000; result:=single(pointer(@t)^)-2.0; end; function TpvRandomGenerator.GetDouble:double; // -1.0 .. 1.0 var t:TpvUInt64; begin t:=Get64; t:=(((t shr 12) and $fffffffffffff)+((t shr 11) and 1)) or $4000000000000000; result:=double(pointer(@t)^)-3.0; end; function TpvRandomGenerator.GetDoubleAbs:double; // 0.0 .. 1.0 var t:TpvInt64; begin t:=Get64; t:=(((t shr 13) and $7ffffffffffff)+((t shr 12) and 1)) or $4000000000000000; result:=double(pointer(@t)^)-2.0; end; function TpvRandomGenerator.GetGaussianFloat:single; // -1.0 .. 1.0 var x1,x2,w:single; i:TpvUInt32; begin if fGaussianFloatUseLast then begin fGaussianFloatUseLast:=false; result:=fGaussianFloatLast; end else begin i:=0; repeat x1:=GetFloat; x2:=GetFloat; w:=sqr(x1)+sqr(x2); inc(i); until ((i and $80000000)<>0) or (w<1.0); if (i and $80000000)<>0 then begin result:=x1; fGaussianFloatLast:=x2; fGaussianFloatUseLast:=true; end else if abs(w)<1e-18 then begin result:=0.0; end else begin w:=sqrt(((-2.0)*ln(w))/w); result:=x1*w; fGaussianFloatLast:=x2*w; fGaussianFloatUseLast:=true; end; end; if result<-1.0 then begin result:=-1.0; end else if result>1.0 then begin result:=1.0; end; end; function TpvRandomGenerator.GetGaussianFloatAbs:single; // 0.0 .. 1.0 begin result:=(GetGaussianFloat+1.0)*0.5; if result<0.0 then begin result:=0.0; end else if result>1.0 then begin result:=1.0; end; end; function TpvRandomGenerator.GetGaussianDouble:double; // -1.0 .. 1.0 var x1,x2,w:double; i:TpvUInt32; begin if fGaussianDoubleUseLast then begin fGaussianDoubleUseLast:=false; result:=fGaussianDoubleLast; end else begin i:=0; repeat x1:=GetDouble; x2:=GetDouble; w:=sqr(x1)+sqr(x2); inc(i); until ((i and $80000000)<>0) or (w<1.0); if (i and $80000000)<>0 then begin result:=x1; fGaussianDoubleLast:=x2; fGaussianDoubleUseLast:=true; end else if abs(w)<1e-18 then begin result:=0.0; end else begin w:=sqrt(((-2.0)*ln(w))/w); result:=x1*w; fGaussianDoubleLast:=x2*w; fGaussianDoubleUseLast:=true; end; end; if result<-1.0 then begin result:=-1.0; end else if result>1.0 then begin result:=1.0; end; end; function TpvRandomGenerator.GetGaussianDoubleAbs:double; // 0.0 .. 1.0 begin result:=(GetGaussianDouble+1.0)*0.5; if result<0.0 then begin result:=0.0; end else if result>1.0 then begin result:=1.0; end; end; function TpvRandomGenerator.GetGaussian(Limit:TpvUInt32):TpvUInt32; begin result:=round(GetGaussianDoubleAbs*((Limit-1)+0.25)); end; constructor TpvRandomUnique32BitSequence.Create(const Seed1:TpvUInt32=$b46f23c7;const Seed2:TpvUInt32=$a54c2364); begin inherited Create; fIndex:=PermuteQPR(PermuteQPR(Seed1)+$682f0161); fIntermediateOffset:=PermuteQPR(PermuteQPR(Seed2)+$46790905); end; destructor TpvRandomUnique32BitSequence.Destroy; begin inherited Destroy; end; function TpvRandomUnique32BitSequence.PermuteQPR(x:TpvUInt32):TpvUInt32; const Prime=TpvUInt32(4294967291); begin if x>=Prime then begin result:=x; end else begin result:={$ifdef fpc}qword{$else}uint64{$endif}(x*x) mod Prime; if x>(Prime shr 1) then begin result:=Prime-result; end; end; end; function TpvRandomUnique32BitSequence.Next:TpvUInt32; begin result:=PermuteQPR((PermuteQPR(fIndex)+fIntermediateOffset) xor $5bf03635); inc(fIndex); end; { TpvPCG32 } procedure TpvPCG32.Init(const aSeed:TpvUInt64); begin if aSeed=0 then begin fState:=DefaultState; fIncrement:=DefaultStream; end else begin fState:=DefaultState xor (aSeed*362436069); if fState=0 then begin fState:=DefaultState; end; fIncrement:=DefaultStream xor (aSeed*1566083941); inc(fIncrement,1-(fIncrement and 1)); end; end; function TpvPCG32.Get32:TpvUInt32; var OldState:TpvUInt64; {$ifndef fpc} XorShifted,Rotation:TpvUInt32; {$endif} begin OldState:=fState; fState:=(OldState*TpvPCG32.Mult)+fIncrement; {$ifdef fpc} result:=RORDWord(((OldState shr 18) xor OldState) shr 27,OldState shr 59); {$else} XorShifted:=((OldState shr 18) xor OldState) shr 27; Rotation:=OldState shr 59; result:=(XorShifted shr Rotation) or (XorShifted shl ((-Rotation) and 31)); {$endif} end; function TpvPCG32.Get64:TpvUInt64; begin result:=Get32; result:=(result shl 32) or Get32; end; function TpvPCG32.GetBiasedBounded32Bit(const aRange:TpvUInt32):TpvUInt32; var Temporary:TpvUInt64; begin // For avoid compiler code generation bugs, when a compiler is optimizing the 64-bit casting away wrongly, thus, // we use a temporary 64-bit variable for the multiplication and shift operations, so it is sure that the multiplication // and shift operations are done on 64-bit values and not on 32-bit values. Temporary:=TpvUInt64(Get32); Temporary:=Temporary*aRange; result:=Temporary shr 32; end; function TpvPCG32.GetUnbiasedBounded32Bit(const aRange:TpvUInt32):TpvUInt32; var x,l,t:TpvUInt32; m:TpvUInt64; begin if aRange<=1 then begin // For ranges of 0 or 1, just output always zero, but do a dummy Get32 call with discarding its result Get32; result:=0; end else if (aRange and (aRange-1))<>0 then begin // For non-power-of-two ranges: Debiased Integer Multiplication — Lemire's Method x:=Get32; m:=TpvUInt64(x); m:=m*TpvUInt64(aRange); l:=TpvUInt32(m and $ffffffff); if l<aRange then begin t:=-aRange; if t>=aRange then begin dec(t,aRange); if t>=aRange then begin t:=t mod aRange; end; end; while l<t do begin x:=Get32; m:=TpvUInt64(x); m:=m*TpvUInt64(aRange); l:=TpvUInt32(m and $ffffffff); end; end; result:=m shr 32; end else begin // For power-of-two ranges: Bitmask with Rejection (Unbiased) — Apple's Method m:=TpvUInt32($ffffffff); t:=aRange-1; {$if defined(fpc) and declared(BSRDWord)} m:=m shr (31-BSRDWord(t or 1)); {$else} m:=m shr CLZDWord(t or 1); {$ifend} repeat result:=Get32 and m; until result<=t; end; end; function TpvPCG32.GetFloat:single; // -1.0 .. 1.0 var t:TpvUInt32; begin t:=Get32; t:=(((t shr 9) and $7fffff)+((t shr 8) and 1)) or $40000000; result:=single(pointer(@t)^)-3.0; end; function TpvPCG32.GetFloatAbs:single; // 0.0 .. 1.0 var t:TpvUInt32; begin t:=Get32; t:=(((t shr 10) and $3fffff)+((t shr 9) and 1)) or $40000000; result:=single(pointer(@t)^)-2.0; end; function TpvPCG32.GetDouble:double; // -1.0 .. 1.0 var t:TpvUInt64; begin t:=Get64; t:=(((t shr 12) and $fffffffffffff)+((t shr 11) and 1)) or $4000000000000000; result:=double(pointer(@t)^)-3.0; end; function TpvPCG32.GetDoubleAbs:double; // 0.0 .. 1.0 var t:TpvInt64; begin t:=Get64; t:=(((t shr 13) and $7ffffffffffff)+((t shr 12) and 1)) or $4000000000000000; result:=double(pointer(@t)^)-2.0; end; end.
{ p_41_1 - Сортировка массива целых чисел } program p_41_1; const cSize = 10; { размер массива } type tGolds = array[1..cSize] of integer; var golds: tGolds; procedure PrintArray(const aArray: tGolds; aLim: integer); var i: integer; begin for i:=1 to aLim do Write(aArray[i]:5); Writeln; end; procedure BubbleSort(var arg: tGolds); var i, j, t: integer; begin for i:=1 to cSize-1 do for j:=1 to cSize-i do if arg[j]>arg[j+1] then begin t := arg[j]; arg[j] := arg[j+1]; arg[j+1] := t; end; end; var i: integer; begin Randomize; for i:=1 to cSize do golds[i] := 1+Random(1000); Writeln('До сортировки:'); PrintArray(golds, cSize); BubbleSort(golds); Writeln('После сортировки:'); PrintArray(golds, cSize); end.
unit Metrics.UnitMethod; interface uses System.SysUtils, Utils.IntegerArray; type TUnitMethodMetrics = class private fFullUnitName: string; fKind: string; fName: string; fLenght: Integer; fComplexity: Integer; public constructor Create(const aFullUnitName: string; const aKind: string; const aName: string); function SetLenght(aLength: Integer): TUnitMethodMetrics; function SetComplexity(aMaxIndentation: Integer): TUnitMethodMetrics; function ToString(): string; override; function HasName(aName: string): boolean; property FullUnitName: string read fFullUnitName; property Kind: string read fKind; property Name: string read fName; property Lenght: Integer read fLenght; property Complexity: Integer read fComplexity; end; implementation constructor TUnitMethodMetrics.Create(const aFullUnitName: string; const aKind: string; const aName: string); begin self.fFullUnitName := aFullUnitName; self.fKind := aKind; self.fName := aName; end; function TUnitMethodMetrics.SetLenght(aLength: Integer): TUnitMethodMetrics; begin self.fLenght := aLength; Result := self; end; function TUnitMethodMetrics.HasName(aName: string): boolean; begin Result := (Name.ToUpper = aName.ToUpper); end; function TUnitMethodMetrics.SetComplexity(aMaxIndentation: Integer) : TUnitMethodMetrics; begin self.fComplexity := aMaxIndentation; Result := self; end; function TUnitMethodMetrics.ToString: string; begin Result := Format('%s %s = [Lenght: %d] [Level: %d]', [Kind, Name, Lenght, fComplexity]) end; end.
unit Vector4bTimingTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTimingTest, BaseTestCase, native, BZVectorMath, BZProfiler; type { TVector4bTimingTest } TVector4bTimingTest = class(TVectorBaseTimingTest) protected {$CODEALIGN RECORDMIN=4} nbt1, nbt2, nbt3, nbt4: TNativeBZVector4b; abt1, abt2, abt3, abt4: TBZVector4b; {$CODEALIGN RECORDMIN=1} b1, b2, b3, b4, b5, b6, b7, b8: byte; {$CODEALIGN RECORDMIN=4} procedure Setup; override; published procedure TestTimeOpAdd; procedure TestTimeOpAddByte; procedure TestTimeOpSub; procedure TestTimeOpSubByte; procedure TestTimeOpMul; procedure TestTimeOpMulByte; procedure TestTimeOpDiv; procedure TestTimeOpDivByte; procedure TestTimeOpEquality; procedure TestTimeOpNotEquals; procedure TestTimeOpAnd; procedure TestTimeOpAndByte; procedure TestTimeOpOr; procedure TestTimeOpOrByte; procedure TestTimeOpXor; procedure TestTimeOpXorByte; procedure TestTimeDivideBy2; procedure TestTimeOpMin; procedure TestTimeOpMinByte; procedure TestTimeOpMax; procedure TestTimeOpMaxByte; procedure TestTimeOpClamp; procedure TestTimeOpClampByte; procedure TestTimeMulAdd; procedure TestTimeMulDiv; procedure TestTimeShuffle; procedure TestTimeSwizzle; procedure TestTimeCombine; procedure TestTimeCombine2; procedure TestTimeCombine3; procedure TestTimeMinXYZComponent; procedure TestTimeMaxXYZComponent; end; implementation { TVector4bTimingTest } procedure TVector4bTimingTest.Setup; begin inherited Setup; Group := rgVector4b; nbt1.Create(12, 124, 253, 128); nbt2.Create(253, 124, 12, 255); abt1.V := nbt1.V; abt2.V := nbt2.V; b1 := 3; // three small bytes b2 := 4; b3 := 5; // b4 can be used as a result b5 := 245; // three large bytes b6 := 248; b7 := 255; //b8 can be used as a result. end; procedure TVector4bTimingTest.TestTimeOpAdd; begin TestDispName := 'Vector Op Add'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 + nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 + abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpAddByte; begin TestDispName := 'Vector Op Add Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 + b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 + b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpSub; begin TestDispName := 'Vector Op Sub'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 - nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 - abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpSubByte; begin TestDispName := 'Vector Op Sub Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 - b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 - b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMul; begin TestDispName := 'Vector Op Mul'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 * nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 * abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMulByte; begin TestDispName := 'Vector Op Mul Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 * b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 * b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpDiv; begin TestDispName := 'Vector Op Div'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 div nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 div abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpDivByte; begin TestDispName := 'Vector Op Mul Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 div b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 div b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpEquality; begin TestDispName := 'Vector Op Equals'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nb := nbt1 = nbt1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin vb := abt1 = abt1; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpNotEquals; begin TestDispName := 'Vector Op Not Equals'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nb := nbt1 <> nbt1; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin vb := abt1 <> abt1; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpAnd; begin TestDispName := 'Vector Op And'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 and nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 and abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpAndByte; begin TestDispName := 'Vector Op And Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 and b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 and b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpOr; begin TestDispName := 'Vector Op Or'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 or nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 or abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpOrByte; begin TestDispName := 'Vector Op Or Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 or b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 or b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpXor; begin TestDispName := 'Vector Op Xor'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 xor nbt2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 xor abt2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpXorByte; begin TestDispName := 'Vector Op Xor Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1 xor b2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1 xor b2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeDivideBy2; begin TestDispName := 'Vector DivideBy2'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.DivideBy2; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.DivideBy2; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMin; begin TestDispName := 'Vector Op Min'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Min(nbt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Min(abt2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMinByte; begin TestDispName := 'Vector Op Min Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Min(b2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Min(b2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMax; begin TestDispName := 'Vector Op Max'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Max(nbt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Max(abt2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpMaxByte; begin TestDispName := 'Vector Op Max Byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Max(b2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Max(b2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpClamp; begin nbt4 := nbt1.Swizzle(swAGRB); abt4 := abt1.Swizzle(swAGRB); TestDispName := 'Vector Clamp'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.Clamp(nbt2, nbt4); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.Clamp(abt2, abt4); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeOpClampByte; begin TestDispName := 'Vector Clamp byte'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Clamp(b2, b1); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Clamp(b2, b1); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeMulAdd; begin nbt4 := nbt1.Swizzle(swAGRB); abt4 := abt1.Swizzle(swAGRB); TestDispName := 'Vector MulAdd'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.MulAdd(nbt2, nbt4); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.MulAdd(abt2, abt4); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeMulDiv; begin TestDispName := 'Vector MulDiv'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.MulDiv(nbt2, nbt2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.MulDiv(abt2, abt2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeShuffle; begin TestDispName := 'Vector Shuffle'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Shuffle(1,2,3,0); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Shuffle(1,2,3,0); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeSwizzle; begin TestDispName := 'Vector Swizzle'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin nbt3 := nbt1.Swizzle(swZYXW); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin abt3 := abt1.Swizzle(swZYXW); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeCombine; begin TestDispName := 'Vector Combine'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.Combine(nbt2, b1); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.Combine(abt2, b1); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeCombine2; begin TestDispName := 'Vector Combine2'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.Combine2(nbt2, b1, b2); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.Combine2(abt2, b1, b2); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeCombine3; begin nbt4 := nbt1.Swizzle(swAGRB); abt4 := abt1.Swizzle(swAGRB); TestDispName := 'Vector Combine3'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to IterationsQuarter do begin nbt3 := nbt1.Combine3(nbt2, nbt4, b1, b2, b3); end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to IterationsQuarter do begin abt3 := abt1.Combine3(abt2, abt4, b1, b2, b3); end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeMinXYZComponent; begin TestDispName := 'Vector MinXYZComponent'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin b4 := nbt1.MinXYZComponent; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin b4 := abt1.MinXYZComponent; end; GlobalProfiler[1].Stop; end; procedure TVector4bTimingTest.TestTimeMaxXYZComponent; begin TestDispName := 'Vector MaxXYZComponent'; GlobalProfiler[0].Clear; GlobalProfiler[0].Start; for cnt := 1 to Iterations do begin b4 := nbt1.MaxXYZComponent; end; GlobalProfiler[0].Stop; GlobalProfiler[1].Clear; GlobalProfiler[1].Start; For cnt:= 1 to Iterations do begin b4 := abt1.MaxXYZComponent; end; GlobalProfiler[1].Stop; end; initialization RegisterTest(REPORT_GROUP_VECTOR4B, TVector4bTimingTest); end.
unit VSEOpenGLExt; interface uses Windows, OpenGL, oglExtensions, AvL, avlVectors{$IFDEF VSE_LOG}, VSELog{$ENDIF}; type TResolution=record //Resolution info Width, Height: Cardinal; RefreshRate: Cardinal; RefreshRates: array of Cardinal; end; TResolutions=array of TResolution; function gleGoFullscreen(Width, Height, Refresh, Depth: Integer): Boolean; //used internally procedure gleGoBack; //used internally function gleSetPix(DC: HDC; Depth: Cardinal): HGLRC; //used internally procedure gleSetGL; //Set default OpenGL state procedure gleResizeWnd(Width, Height: Integer); //used internally procedure glePushMatrix; //Push Projection & ModelView matrices procedure glePopMatrix; //Pop Projection & ModelView matrices procedure glePerspectiveMatrix(FOV: Single; Width, Height: Integer); //Set perspective projection; FOV: Field of Vision; Width, Height: Viewport size procedure glePerspectiveMatrix2(FOV: Single; Width, Height: Integer; ZNear, ZFar: Single); //Set perspective projection; ZNear, ZFar: Z cutting planes procedure gleOrthoMatrix(Width, Height: Integer); //Set orthogonal projection; Width, Height: projection dimensions procedure gleOrthoMatrix2(Left, Top, Right, Bottom: Double); //Set orthogonal projection; Left, Top, Right, Bottom: projection dimensions function gleError(GLError: Cardinal): string; //Convert OpenGL error code to text procedure gleColor(Color: TColor); //Set current OpenGL color function gleColorTo4f(Color: TColor): TVector4D; //Convert GDI color to OpenGL color function gleGetResolutions: TResolutions; //List available screen resolutions, RefreshRate not used function gleGetCurrentResolution: TResolution; //Returns current resolution, RefreshRates not used function gleScreenTo3D(X, Y: Integer; GetDepth: Boolean=false): TVector3D; //Translates screen coordinates to 3D coordinates; GetDepth: fetch screen depth from framebuffer function gle3DToScreen(X, Y, Z: Double): TPoint; //Translates 3D coordinates to screen coordinates implementation const ENUM_CURRENT_SETTINGS=LongWord(-1); ENUM_REGISTRY_SETTINGS=LongWord(-2); function gleGoFullscreen(Width, Height, Refresh, Depth: Integer): Boolean; var DM: DevMode; begin {$IFDEF VSE_LOG}LogF(llInfo, 'Entering fullscreen. Resolution %dx%d@%d', [Width, Height, Refresh]);{$ENDIF} ZeroMemory(@DM, SizeOf(DM)); DM.dmSize:=SizeOf(DM); DM.dmBitsPerPel:=Depth; DM.dmPelsWidth:=Width; DM.dmPelsHeight:=Height; DM.dmDisplayFrequency:=Refresh; DM.dmFields:=DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT; if Refresh>0 then DM.dmFields:=DM.dmFields or DM_DISPLAYFREQUENCY; Result:=ChangeDisplaySettings(DM, CDS_TEST)=DISP_CHANGE_SUCCESSFUL; if Result then ChangeDisplaySettings(DM, CDS_FULLSCREEN); end; procedure gleGoBack; begin {$IFDEF VSE_LOG}Log(llInfo, 'Leaving fullscreen');{$ENDIF} ChangeDisplaySettings(DevMode(nil^), CDS_FULLSCREEN); end; function gleSetPix(DC: HDC; Depth: Cardinal): HGLRC; var PFD: TPIXELFORMATDESCRIPTOR; PixelFormat: Cardinal; begin Result:=0; {$IFDEF VSE_LOG}Log(llInfo, 'Setting pixel format');{$ENDIF} ZeroMemory(@PFD, SizeOf(TPIXELFORMATDESCRIPTOR)); with PFD do begin nSize:=SizeOf(TPIXELFORMATDESCRIPTOR); nVersion:=1; dwFlags:=PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER or PFD_SWAP_EXCHANGE; iPixelType:=PFD_TYPE_RGBA; cColorBits:=Depth; //if Depth=32 then cAlphaBits:=8; cDepthBits:=24; cStencilBits:=8; iLayerType:=PFD_MAIN_PLANE; end; PixelFormat:=ChoosePixelFormat(DC, @PFD); if PixelFormat=0 then begin {$IFDEF VSE_LOG}Log(llError, 'Unable to find a suitable pixel format');{$ENDIF} Exit; end; if not SetPixelFormat(DC, PixelFormat, @PFD) then begin {$IFDEF VSE_LOG}Log(llError, 'Unable to set the pixel format');{$ENDIF} Exit; end; {$IFDEF VSE_LOG}Log(llInfo, 'Creating rendering context');{$ENDIF} Result:=wglCreateContext(DC); if Result=0 then begin {$IFDEF VSE_LOG}Log(llError, 'Unable to create an OpenGL rendering context');{$ENDIF} Exit; end; {$IFDEF VSE_LOG}Log(llInfo, 'Activating rendering context');{$ENDIF} if not wglMakeCurrent(DC, Result) then begin {$IFDEF VSE_LOG}Log(llError, 'Unable to activate OpenGL rendering context');{$ENDIF} wglDeleteContext(Result); Result:=0; Exit; end; {$IFDEF VSE_LOG}Log(llInfo, 'Reading extensions');{$ENDIF} ReadExtensions; end; procedure gleSetGL; begin glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glEnable(GL_COLOR_MATERIAL); glShadeModel(GL_SMOOTH); glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA); end; procedure gleResizeWnd(Width, Height: Integer); begin if Height=0 then Height:=1; glViewport(0, 0, Width, Height); end; procedure glePushMatrix; begin glPushAttrib(GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix; glMatrixMode(GL_MODELVIEW); glPushMatrix; glPopAttrib; end; procedure glePopMatrix; begin glPushAttrib(GL_TRANSFORM_BIT); glMatrixMode(GL_PROJECTION); glPopMatrix; glMatrixMode(GL_MODELVIEW); glPopMatrix; glPopAttrib; end; procedure glePerspectiveMatrix(FOV: Single; Width, Height: Integer); begin glePerspectiveMatrix2(FOV, Width, Height, 0.1, 10000); end; procedure glePerspectiveMatrix2(FOV: Single; Width, Height: Integer; ZNear, ZFar: Single); begin if Height<1 then Height:=1; glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(FOV, Width/Height, ZNear, ZFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity; end; procedure gleOrthoMatrix(Width, Height: Integer); begin gleOrthoMatrix2(0, 0, Width, Height); end; procedure gleOrthoMatrix2(Left, Top, Right, Bottom: Double); begin glMatrixMode(GL_PROJECTION); glLoadIdentity; glOrtho(Left, Right, Bottom, Top, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity; end; function gleError(GLError: Cardinal): string; begin case GLError of GL_NO_ERROR: Result:='No errors'; GL_INVALID_ENUM: Result:='Invalid enumeration'; GL_INVALID_VALUE: Result:='Invalid value'; GL_INVALID_OPERATION: Result:='Invalid operation'; GL_STACK_OVERFLOW: Result:='Stack overflow'; GL_STACK_UNDERFLOW: Result:='Stack underflow'; GL_OUT_OF_MEMORY: Result:='Out of memory'; else Result:='Unknown error'; end; end; procedure gleColor(Color: TColor); var Clr: packed array[0..3] of Byte absolute Color; begin if Clr[3] = 0 then Clr[3] := $FF; glColor4ub(Clr[0], Clr[1], Clr[2], Clr[3]); end; function gleColorTo4f(Color: TColor): TVector4D; var Clr: packed array[0..3] of Byte absolute Color; begin with Result do begin X:=Clr[0]/255; Y:=Clr[1]/255; Z:=Clr[2]/255; W:=Clr[3]/255; end; end; function gleGetResolutions: TResolutions; procedure AddResolution(Width, Height, Refresh: Cardinal); var i, j: Integer; begin for i:=0 to High(Result) do if (Result[i].Width=Width) and (Result[i].Height=Height) then Break; if Length(Result)=0 then i:=0; if i=Length(Result) then SetLength(Result, i+1); Result[i].Width:=Width; Result[i].Height:=Height; for j:=0 to High(Result[i].RefreshRates) do if Result[i].RefreshRates[j]=Refresh then Exit; SetLength(Result[i].RefreshRates, Length(Result[i].RefreshRates)+1); Result[i].RefreshRates[High(Result[i].RefreshRates)]:=Refresh; end; function Compare(const A, B: TResolution): Boolean; begin Result:=A.Width>B.Width; if A.Width=B.Width then Result:=A.Height>B.Height; end; var i, j, SC: Integer; TmpR: TResolution; TmpF: Cardinal; DM: TDevMode; begin ZeroMemory(@DM, SizeOf(DM)); i:=0; while EnumDisplaySettings(nil, i, DM) do begin if (DM.dmPelsWidth >= 640) and (DM.dmPelsHeight >= 480) and (DM.dmDisplayFrequency <> 1) then AddResolution(DM.dmPelsWidth, DM.dmPelsHeight, DM.dmDisplayFrequency); Inc(i); end; repeat SC:=0; for i:=0 to High(Result)-1 do if Compare(Result[i], Result[i+1]) then begin TmpR:=Result[i]; Result[i]:=Result[i+1]; Result[i+1]:=TmpR; Inc(SC); end; until SC=0; for i:=0 to High(Result) do repeat SC:=0; for j:=0 to High(Result[i].RefreshRates)-1 do if Result[i].RefreshRates[j]>Result[i].RefreshRates[j+1] then begin TmpF:=Result[i].RefreshRates[j]; Result[i].RefreshRates[j]:=Result[i].RefreshRates[j+1]; Result[i].RefreshRates[j+1]:=TmpF; Inc(SC); end; until SC=0; end; function gleGetCurrentResolution: TResolution; var DM: TDevMode; begin ZeroMemory(@DM, SizeOf(DM)); ZeroMemory(@Result, SizeOf(Result)); if not EnumDisplaySettings(nil, ENUM_CURRENT_SETTINGS, DM) then Exit; Result.Width:=DM.dmPelsWidth; Result.Height:=DM.dmPelsHeight; Result.RefreshRate:=DM.dmDisplayFrequency; end; function gleScreenTo3D(X, Y: Integer; GetDepth: Boolean=false): TVector3D; var Viewport: array[0..3] of Integer; ModelViewMatrix, ProjectionMatrix: array[0..15] of Double; Z: Single; OX, OY, OZ: Double; begin glGetDoublev(GL_MODELVIEW_MATRIX, @ModelViewMatrix); glGetDoublev(GL_PROJECTION_MATRIX, @ProjectionMatrix); glGetIntegerv(GL_VIEWPORT, @Viewport); Y:=Viewport[3]-Y-1; if GetDepth then glReadPixels(X, Y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, @Z) else Z:=0; gluUnProject(X, Y, Z, @ModelViewMatrix, @ProjectionMatrix, @Viewport, OX, OY, OZ); Result:=Vector3D(OX, OY, OZ); end; function gle3DToScreen(X, Y, Z: Double): TPoint; var Viewport: array[0..3] of Integer; ModelViewMatrix, ProjectionMatrix: array[0..15] of Double; begin glGetDoublev(GL_MODELVIEW_MATRIX, @ModelViewMatrix); glGetDoublev(GL_PROJECTION_MATRIX, @ProjectionMatrix); glGetIntegerv(GL_VIEWPORT, @Viewport); gluProject(X, Y, Z, @ModelViewMatrix, @ProjectionMatrix, @Viewport, X, Y, Z); Result:=Point(Round(X), Viewport[3]-Round(Y)-1); end; end.
{ Created by BGRA Controls Team Dibo, Circular, lainz (007) and contributors. For detailed information see readme.txt Site: https://sourceforge.net/p/bgra-controls/ Wiki: http://wiki.lazarus.freepascal.org/BGRAControls Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit uPSI_BGRAPascalScript; { This file has been generated by UnitParser v0.7, written by M. Knight and updated by NP. v/d Spek and George Birbilis. Source Code from Carlo Kok has been used to implement various sections of UnitParser. Components of ROPS are used in the construction of UnitParser, code implementing the class wrapper is taken from Carlo Kok's conv utility } interface uses SysUtils ,Classes ,uPSComponent ,uPSRuntime ,uPSCompiler ; type (*----------------------------------------------------------------------------*) TPSImport_BGRAPascalScript = class(TPSPlugin) public procedure CompileImport1(CompExec: TPSScript); override; procedure ExecImport1(CompExec: TPSScript; const {%H-}ri: TPSRuntimeClassImporter); override; end; { compile-time registration functions } procedure SIRegister_bgrapascalscript(CL: TPSPascalCompiler); { run-time registration functions } procedure RIRegister_bgrapascalscript_Routines(S: TPSExec); procedure Register; implementation uses BGRABitmap ,BGRABitmapTypes ,BGRAPascalScript ,Dialogs; procedure Register; begin RegisterComponents('BGRA Controls', [TPSImport_bgrapascalscript]); end; (* === compile-time registration functions === *) (*----------------------------------------------------------------------------*) procedure SIRegister_BGRAPascalScript(CL: TPSPascalCompiler); begin {Types} CL.AddTypeS('TRect','record Left, Top, Right, Bottom: Integer; end;'); CL.AddTypeS('TPoint','record x, y: LongInt; end;'); {Types} CL.AddTypeS('TPointF','record x, y: single; end;'); CL.AddTypeS('TBGRAColor','LongWord'); CL.AddTypeS('TMedianOption','( moNone, moLowSmooth, moMediumSmooth, moHighSmooth )'); CL.AddTypeS('TResampleFilter','( rfBox, rfLinear, rfHalfCosine, rfCosine, rfBicubic, rfMitchell, rfSpline, rfLanczos2, rfLanczos3, rfLanczos4, rfBestQuality )'); CL.AddTypeS('TRadialBlurType','( rbNormal, rbDisk, rbCorona, rbPrecise, rbFast )'); {Utils} CL.AddDelphiFunction('function bgra_GetHighestID: Integer;'); {Color} CL.AddDelphiFunction('function rgb(red,green,blue: byte): TBGRAColor;'); CL.AddDelphiFunction('function rgba(red,green,blue,alpha: byte): TBGRAColor;'); CL.AddDelphiFunction('function getBlue(AColor: TBGRAColor): byte;'); CL.AddDelphiFunction('function getGreen(AColor: TBGRAColor): byte;'); CL.AddDelphiFunction('function getRed(AColor: TBGRAColor): byte;'); CL.AddDelphiFunction('function getAlpha(AColor: TBGRAColor): byte;'); CL.AddDelphiFunction('function setBlue(AColor: TBGRAColor; AValue: byte): TBGRAColor;'); CL.AddDelphiFunction('function setGreen(AColor: TBGRAColor; AValue: byte): TBGRAColor;'); CL.AddDelphiFunction('function setRed(AColor: TBGRAColor; AValue: byte): TBGRAColor;'); CL.AddDelphiFunction('function setAlpha(AColor: TBGRAColor; AValue: byte): TBGRAColor;'); {Constructors} CL.AddDelphiFunction('Procedure bgra_Create( id : Integer)'); CL.AddDelphiFunction('Procedure bgra_CreateWithSize( id : Integer; AWidth, AHeight: integer)'); CL.AddDelphiFunction('Procedure bgra_CreateFromFile( id : Integer; AFilename : string)'); CL.AddDelphiFunction('Procedure bgra_Destroy( id : Integer)'); CL.AddDelphiFunction('Procedure bgra_DestroyAll'); {} CL.AddDelphiFunction('Procedure bgra_Fill( id : Integer; AColor: TBGRAColor)'); CL.AddDelphiFunction('procedure bgra_SetPixel(id: Integer; x,y: integer; AColor: TBGRAColor);'); CL.AddDelphiFunction('function bgra_GetPixel(id: Integer; x,y: integer): TBGRAColor;'); {Loading functions} CL.AddDelphiFunction('procedure bgra_SaveToFile(id: integer; const filename: string);'); {Filters} CL.AddDelphiFunction('procedure bgra_FilterSmartZoom3( id: integer; Option: TMedianOption )'); CL.AddDelphiFunction('procedure bgra_FilterMedian( id: integer; Option: TMedianOption )'); CL.AddDelphiFunction('procedure bgra_FilterSmooth( id: integer )'); CL.AddDelphiFunction('procedure bgra_FilterSharpen( id: integer; Amount: single )'); CL.AddDelphiFunction('procedure bgra_FilterSharpenRect( id: integer; ABounds: TRect; Amount: single )'); CL.AddDelphiFunction('procedure bgra_FilterContour( id: integer )'); CL.AddDelphiFunction('procedure bgra_FilterPixelate( id: integer; pixelSize: integer; useResample: boolean; filter: TResampleFilter )'); CL.AddDelphiFunction('procedure bgra_FilterBlurRadial( id: integer; radius: integer; blurType: TRadialBlurType )'); CL.AddDelphiFunction('procedure bgra_FilterBlurRadialRect( id: integer; ABounds: TRect; radius: integer; blurType: TRadialBlurType )'); CL.AddDelphiFunction('procedure bgra_FilterBlurMotion(id: integer; distance: integer; angle: single; oriented: boolean);'); CL.AddDelphiFunction('procedure bgra_FilterBlurMotionRect(id: integer; ABounds: TRect; distance: integer; angle: single; oriented: boolean);'); CL.AddDelphiFunction('procedure bgra_FilterCustomBlur(id: integer; mask: integer);'); CL.AddDelphiFunction('procedure bgra_FilterCustomBlurRect(id: integer; ABounds: TRect; mask: integer);'); CL.AddDelphiFunction('procedure bgra_FilterEmboss(id: integer; angle: single);'); CL.AddDelphiFunction('procedure bgra_FilterEmbossRect(id: integer; angle: single; ABounds: TRect);'); CL.AddDelphiFunction('procedure bgra_FilterEmbossHighlight(id: integer; FillSelection: boolean);'); CL.AddDelphiFunction('procedure bgra_FilterEmbossHighlightBorder(id: integer; FillSelection: boolean; BorderColor: TBGRAColor); '); CL.AddDelphiFunction('procedure bgra_FilterEmbossHighlightBorderAndOffset(id: integer; FillSelection: boolean; BorderColor: TBGRAColor; Offset: TPoint);'); CL.AddDelphiFunction('procedure bgra_FilterGrayscale(id: integer); '); CL.AddDelphiFunction('procedure bgra_FilterGrayscaleRect(id: integer; ABounds: TRect); '); CL.AddDelphiFunction('procedure bgra_FilterNormalize(id: integer; eachChannel: boolean); '); CL.AddDelphiFunction('procedure bgra_FilterNormalizeRect(id: integer; ABounds: TRect; eachChannel: boolean); '); CL.AddDelphiFunction('procedure bgra_FilterRotate(id: integer; origin: TPointF; angle: single; correctBlur: boolean); '); CL.AddDelphiFunction('procedure bgra_FilterSphere(id: integer); '); CL.AddDelphiFunction('procedure bgra_FilterTwirl(id: integer; ACenter: TPoint; ARadius: single; ATurn: single; AExponent: single);'); CL.AddDelphiFunction('procedure bgra_FilterTwirlRect(id: integer; ABounds: TRect; ACenter: TPoint; ARadius: single; ATurn: single; AExponent: single);'); CL.AddDelphiFunction('procedure bgra_FilterCylinder(id: integer);'); CL.AddDelphiFunction('procedure bgra_FilterPlane(id: integer);'); {Others} CL.AddDelphiFunction('Procedure ShowMessage( const AMessage: string)'); end; (* === run-time registration functions === *) (*----------------------------------------------------------------------------*) procedure RIRegister_BGRAPascalScript_Routines(S: TPSExec); begin {Utils} S.RegisterDelphiFunction(@bgra_GetHighestID, 'bgra_GetHighestID', cdRegister); {Constructors} S.RegisterDelphiFunction(@bgra_Create, 'bgra_Create', cdRegister); S.RegisterDelphiFunction(@bgra_CreateWithSize, 'bgra_CreateWithSize', cdRegister); S.RegisterDelphiFunction(@bgra_CreateFromFile, 'bgra_CreateFromFile', cdRegister); S.RegisterDelphiFunction(@bgra_Destroy, 'bgra_Destroy', cdRegister); S.RegisterDelphiFunction(@bgra_DestroyAll, 'bgra_DestroyAll', cdRegister); {} S.RegisterDelphiFunction(@bgra_Fill, 'bgra_Fill', cdRegister); {Loading functions} S.RegisterDelphiFunction(@bgra_SaveToFile, 'bgra_SaveToFile', cdRegister); {Color} S.RegisterDelphiFunction(@rgb, 'rgb', cdRegister); S.RegisterDelphiFunction(@rgba, 'rgba', cdRegister); S.RegisterDelphiFunction(@getRed, 'getRed', cdRegister); S.RegisterDelphiFunction(@getGreen, 'getGreen', cdRegister); S.RegisterDelphiFunction(@getBlue, 'getBlue', cdRegister); S.RegisterDelphiFunction(@getAlpha, 'getAlpha', cdRegister); S.RegisterDelphiFunction(@setRed, 'setRed', cdRegister); S.RegisterDelphiFunction(@setGreen, 'setGreen', cdRegister); S.RegisterDelphiFunction(@setBlue, 'setBlue', cdRegister); S.RegisterDelphiFunction(@setAlpha, 'setAlpha', cdRegister); S.RegisterDelphiFunction(@bgra_SetPixel, 'bgra_SetPixel', cdRegister); S.RegisterDelphiFunction(@bgra_GetPixel, 'bgra_GetPixel', cdRegister); {Filters} S.RegisterDelphiFunction(@bgra_FilterSmartZoom3,'bgra_FilterSmartZoom3', cdRegister); S.RegisterDelphiFunction(@bgra_FilterMedian,'bgra_FilterMedian', cdRegister); S.RegisterDelphiFunction(@bgra_FilterSmooth,'bgra_FilterSmooth', cdRegister); S.RegisterDelphiFunction(@bgra_FilterSharpen,'bgra_FilterSharpen', cdRegister); S.RegisterDelphiFunction(@bgra_FilterSharpenRect,'bgra_FilterSharpenRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterContour,'bgra_FilterContour', cdRegister); S.RegisterDelphiFunction(@bgra_FilterPixelate,'bgra_FilterPixelate', cdRegister); S.RegisterDelphiFunction(@bgra_FilterBlurRadial,'bgra_FilterBlurRadial', cdRegister); S.RegisterDelphiFunction(@bgra_FilterBlurRadialRect,'bgra_FilterBlurRadialRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterBlurMotion,'bgra_FilterBlurMotion', cdRegister); S.RegisterDelphiFunction(@bgra_FilterBlurMotionRect,'bgra_FilterBlurMotionRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterCustomBlur,'bgra_FilterCustomBlur', cdRegister); S.RegisterDelphiFunction(@bgra_FilterCustomBlurRect,'bgra_FilterCustomBlurRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterEmboss,'bgra_FilterEmboss', cdRegister); S.RegisterDelphiFunction(@bgra_FilterEmbossRect,'bgra_FilterEmbossRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterEmbossHighlight,'bgra_FilterEmbossHighlight', cdRegister); S.RegisterDelphiFunction(@bgra_FilterEmbossHighlightBorder,'bgra_FilterEmbossHighlightBorder', cdRegister); S.RegisterDelphiFunction(@bgra_FilterEmbossHighlightBorderAndOffset,'bgra_FilterEmbossHighlightBorderAndOffset', cdRegister); S.RegisterDelphiFunction(@bgra_FilterGrayscale,'bgra_FilterGrayscale', cdRegister); S.RegisterDelphiFunction(@bgra_FilterGrayscaleRect,'bgra_FilterGrayscaleRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterNormalize,'bgra_FilterNormalize', cdRegister); S.RegisterDelphiFunction(@bgra_FilterNormalizeRect,'bgra_FilterNormalizeRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterRotate,'bgra_FilterRotate', cdRegister); S.RegisterDelphiFunction(@bgra_FilterSphere,'bgra_FilterSphere', cdRegister); S.RegisterDelphiFunction(@bgra_FilterTwirl,'bgra_FilterTwirl', cdRegister); S.RegisterDelphiFunction(@bgra_FilterTwirlRect,'bgra_FilterTwirlRect', cdRegister); S.RegisterDelphiFunction(@bgra_FilterCylinder,'bgra_FilterCylinder', cdRegister); S.RegisterDelphiFunction(@bgra_FilterPlane,'bgra_FilterPlane', cdRegister); {Others} S.RegisterDelphiFunction(@ShowMessage, 'ShowMessage', cdRegister); end; { TPSImport_BGRAPascalScript } (*----------------------------------------------------------------------------*) procedure TPSImport_BGRAPascalScript.CompileImport1(CompExec: TPSScript); begin SIRegister_BGRAPascalScript(CompExec.Comp); end; (*----------------------------------------------------------------------------*) procedure TPSImport_BGRAPascalScript.ExecImport1(CompExec: TPSScript; const ri: TPSRuntimeClassImporter); begin //RIRegister_BGRAPascalScript(ri); RIRegister_BGRAPascalScript_Routines(CompExec.Exec); // comment it if no routines end; (*----------------------------------------------------------------------------*) end.
unit cmpTexturedPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TTextureKind = (tkTile, tkTileLeft, tkTileTop); TTexturedPanel = class(TPanel) private FPicture: TPicture; FBitmap : TBitmap; FTextureKind: TTextureKind; procedure PictureChanged(Sender: TObject); procedure SetPicture(const Value: TPicture); procedure TileRect (rect : TRect); procedure SetTextureKind(const Value: TTextureKind); { Private declarations } protected procedure Paint; override; public constructor Create (AOwner : TComponent); override; destructor Destroy; override; property Bitmap : TBitmap read fBitmap; { Public declarations } published property Picture : TPicture read FPicture write SetPicture; property TExtureKind : TTextureKind read FTextureKind write SetTextureKind; end; implementation { TTexturedPanel } constructor TTexturedPanel.Create(AOwner: TComponent); begin inherited; FPicture := TPicture.Create; FBitmap := TBitmap.Create; FPicture.OnChange := PictureChanged; end; destructor TTexturedPanel.Destroy; begin FBitmap.Free; FPicture.Free; inherited; end; procedure TTexturedPanel.Paint; const Alignments: array[TAlignment] of Longint = (DT_LEFT, DT_RIGHT, DT_CENTER); var Rect: TRect; TopColor, BottomColor: TColor; FontHeight: Integer; Flags: Longint; procedure AdjustColors(Bevel: TPanelBevel); begin TopColor := clBtnHighlight; if Bevel = bvLowered then TopColor := clBtnShadow; BottomColor := clBtnShadow; if Bevel = bvLowered then BottomColor := clBtnHighlight; end; begin Rect := GetClientRect; if BevelOuter <> bvNone then begin AdjustColors(BevelOuter); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; if Assigned (Picture.Graphic) and not Picture.Graphic.Empty then begin if TExtureKind <> tkTile then begin Canvas.Brush.Color := Color; Canvas.FillRect (Rect) end; TileRect (rect); InflateRect (rect, -BorderWidth, -BorderWidth) end else Frame3D(Canvas, Rect, Color, Color, BorderWidth); if BevelInner <> bvNone then begin AdjustColors(BevelInner); Frame3D(Canvas, Rect, TopColor, BottomColor, BevelWidth); end; with Canvas do begin Brush.Color := Color; if not Assigned (Picture.Graphic) or Picture.Graphic.Empty then FillRect(Rect); Brush.Style := bsClear; Font := Self.Font; FontHeight := TextHeight('W'); with Rect do begin Top := ((Bottom + Top) - FontHeight) div 2; Bottom := Top + FontHeight; end; Flags := DT_NOPREFIX or DT_EXPANDTABS or DT_VCENTER or Alignments[Alignment]; Flags := DrawTextBiDiModeFlags(Flags); DrawText(Handle, PChar(Caption), -1, Rect, Flags); end; end; procedure TTexturedPanel.PictureChanged(Sender: TObject); begin FBitmap.Assign (FPicture.Graphic); Invalidate end; procedure TTexturedPanel.SetPicture(const Value: TPicture); begin FPicture.Assign(Value); end; procedure TTexturedPanel.SetTextureKind(const Value: TTextureKind); begin if Value <> FTextureKind then begin FTextureKind := Value; Invalidate end end; procedure TTexturedPanel.TileRect(rect: TRect); var r : TRect; procedure BltRect (rect : TRect); begin BitBlt (Canvas.Handle, rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top, FBitmap.Canvas.Handle, 0, 0, SRCCOPY) end; begin r.Top := rect.Top; repeat r.Left := rect.Left; repeat r.Right := r.Left + FBitmap.Width; r.Bottom := r.Top + FBitmap.Height; if r.Right > rect.Right then r.Right := rect.Right; if r.Bottom > rect.Bottom then r.Bottom := rect.Bottom; BltRect (r); r.Left := r.Right; if textureKind = tkTileLeft then break until r.Right = rect.Right; r.Top := r.Bottom; if textureKind = tkTileTop then break until r.Bottom = rect.Bottom end; end.
{------------------------------------------------------------------------------- | This unit is copyright Cyrille de Brebisson ------------------------------------------------------------------------------- | Version history: | 0.50: source maintained by the autor, version history unknown | - Better support of the completion form when embeded in an MDI | application (thanks to Olivier Deckmyn) | - Added Page up and Page down in the supported keys | - The paint is now done through a bitmat to reduce flickering | 0.51: Stefan van As | - Added Menus unit to the uses clause. | - Added FShortCut, SetShortCut and published ShortCut property | (defaults to Ctrl+Space) and ShortCut handling to EditorKeyDown. -------------------------------------------------------------------------------} unit mwCompletionProposal; interface uses Forms, Classes, StdCtrls, Controls, SysUtils, mwCustomEdit, mwKeyCmds, Windows, Graphics, Menus; type TCompletionProposalPaintItem = Function (Key: String; Canvas: TCanvas; x, y: integer): Boolean of object; TCompletionProposalForm = class (TForm) Protected FCurrentString: String; FOnKeyPress: TKeyPressEvent; FOnKeyDelete: TNotifyEvent; FOnPaintItem: TCompletionProposalPaintItem; FItemList: TStrings; FPosition: Integer; FNbLinesInWindow: Integer; FFontHeight: integer; Scroll: TScrollBar; FOnValidate: TNotifyEvent; FOnCancel: TNotifyEvent; FClSelect: TColor; FAnsi: boolean; procedure SetCurrentString(const Value: String); Procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: char); override; Procedure Paint; override; procedure ScrollGetFocus(Sender: TObject); Procedure Deactivate; override; procedure SelectPrec; procedure SelectNext; procedure ScrollChange(Sender: TObject); procedure SetItemList(const Value: TStrings); procedure SetPosition(const Value: Integer); procedure SetNbLinesInWindow(const Value: Integer); Procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; Procedure StringListChange(Sender: TObject); private Bitmap: TBitmap; // used for drawing fCurrentEditor: TComponent; Public constructor Create(AOwner: Tcomponent); override; destructor destroy; override; Published Property CurrentString: String read FCurrentString write SetCurrentString; Property OnKeyPress: TKeyPressEvent read FOnKeyPress write FOnKeyPress; Property OnKeyDelete: TNotifyEvent read FOnKeyDelete write FOnKeyDelete; Property OnPaintItem: TCompletionProposalPaintItem read FOnPaintItem write FOnPaintItem; Property OnValidate: TNotifyEvent read FOnValidate write FOnValidate; Property OnCancel: TNotifyEvent read FOnCancel write FOnCancel; Property ItemList: TStrings read FItemList write SetItemList; Property Position: Integer read FPosition write SetPosition; Property NbLinesInWindow: Integer read FNbLinesInWindow write SetNbLinesInWindow; Property ClSelect: TColor read FClSelect write FClSelect; Property ffAnsi: boolean read fansi write fansi; Property CurrentEditor: tComponent read fCurrentEditor write fCurrentEditor; end; TCompletionProposal = Class (TComponent) private Form: TCompletionProposalForm; FOnExecute: TNotifyEvent; function GetClSelect: TColor; procedure SetClSelect(const Value: TColor); function GetCurrentString: String; function GetItemList: TStrings; function GetNbLinesInWindow: Integer; function GetOnCancel: TNotifyEvent; function GetOnKeyPress: TKeyPressEvent; function GetOnPaintItem: TCompletionProposalPaintItem; function GetOnValidate: TNotifyEvent; function GetPosition: Integer; procedure SetCurrentString(const Value: String); procedure SetItemList(const Value: TStrings); procedure SetNbLinesInWindow(const Value: Integer); procedure SetOnCancel(const Value: TNotifyEvent); procedure SetOnKeyPress(const Value: TKeyPressEvent); procedure SetOnPaintItem(const Value: TCompletionProposalPaintItem); procedure SetPosition(const Value: Integer); procedure SetOnValidate(const Value: TNotifyEvent); function GetOnKeyDelete: TNotifyEvent; procedure SetOnKeyDelete(const Value: TNotifyEvent); procedure RFAnsi(const Value: boolean); function SFAnsi: boolean; Public Constructor Create(Aowner: TComponent); override; Destructor Destroy; Override; Procedure Execute(s: string; x, y: integer); Property OnKeyPress: TKeyPressEvent read GetOnKeyPress write SetOnKeyPress; Property OnKeyDelete: TNotifyEvent read GetOnKeyDelete write SetOnKeyDelete; Property OnValidate: TNotifyEvent read GetOnValidate write SetOnValidate; Property OnCancel: TNotifyEvent read GetOnCancel write SetOnCancel; Property CurrentString: String read GetCurrentString write SetCurrentString; Published Property OnExecute: TNotifyEvent read FOnExecute Write FOnExecute; Property OnPaintItem: TCompletionProposalPaintItem read GetOnPaintItem write SetOnPaintItem; Property ItemList: TStrings read GetItemList write SetItemList; Property Position: Integer read GetPosition write SetPosition; Property NbLinesInWindow: Integer read GetNbLinesInWindow write SetNbLinesInWindow; Property ClSelect: TColor read GetClSelect Write SetClSelect; Property AnsiStrings: boolean read SFAnsi Write RFAnsi; End; TMwCompletionProposal = class (TCompletionProposal) private FShortCut: TShortCut; fEditors: TList; fEditstuffs: TList; FEndOfTokenChr: string; procedure SetEditor(const Value: TmwCustomEdit); procedure backspace(Senter: TObject); procedure Cancel(Senter: TObject); procedure Validate(Senter: TObject); procedure KeyPress(Sender: TObject; var Key: Char); Procedure EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); Procedure EditorKeyPress(Sender: TObject; var Key: char); Function GetPreviousToken(FEditor: TmwCustomEdit): string; function GetFEditor: TmwCustomEdit; function GetEditor(i: integer): TmwCustomEdit; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetShortCut(Value: TShortCut); public Constructor Create(AOwner: TComponent); override; destructor destroy; override; Property Editors[i: integer]: TmwCustomEdit read GetEditor; Procedure AddEditor(Editor: TmwCustomEdit); Function RemoveEditor(Editor: TmwCustomEdit): boolean; Function EditorsCount: integer; published property ShortCut: TShortCut read FShortCut write SetShortCut; Property Editor: TmwCustomEdit read GetFEditor write SetEditor; Property EndOfTokenChr: string read FEndOfTokenChr write FEndOfTokenChr; end; TmwAutoComplete = class(TComponent) private FShortCut: TShortCut; fEditors: TList; fEditstuffs: TList; fAutoCompleteList: TStrings; FEndOfTokenChr: string; Procedure SetAutoCompleteList(List: TStrings); function GetEditor(i: integer): TmwCustomEdit; function GetEdit: TmwCustomEdit; procedure SetEdit(const Value: TmwCustomEdit); protected procedure SetShortCut(Value: TShortCut); procedure Notification(AComponent: TComponent; Operation: TOperation); override; Procedure EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); virtual; Procedure EditorKeyPress(Sender: TObject; var Key: char); virtual; Function GetPreviousToken(Editor: tmwCustomEdit): string; public Constructor Create(AOwner: TComponent); override; Destructor destroy; override; Procedure Execute(token: string; Editor: TmwCustomEdit); Property Editors[i: integer]: TmwCustomEdit read GetEditor; Procedure AddEditor(Editor: TmwCustomEdit); Function RemoveEditor(Editor: TmwCustomEdit): boolean; Function EditorsCount: integer; published Property AutoCompleteList: TStrings read fAutoCompleteList write SetAutoCompleteList; Property EndOfTokenChr: string read FEndOfTokenChr write FEndOfTokenChr; Property Editor: TmwCustomEdit read GetEdit write SetEdit; property ShortCut: TShortCut read FShortCut write SetShortCut; end; Procedure PretyTextOut(c: TCanvas; x, y: integer; s: String); Procedure register; implementation uses mwLocalStr, mwSupportProcs; { TCompletionProposalForm } constructor TCompletionProposalForm.Create(AOwner: Tcomponent); begin CreateNew(AOwner); FItemList:= TStringList.Create; BorderStyle:= bsNone; width:=262; Scroll:= TScrollBar.Create(self); Scroll.Kind:= sbVertical; Scroll.OnChange:= ScrollChange; Scroll.Parent:= self; Scroll.OnEnter:= ScrollGetFocus; Visible:= false; FFontHeight:= Canvas.TextHeight('Cyrille de Brebisson'); ClSelect:= clAqua; TStringList(FItemList).OnChange:= StringListChange; bitmap:= TBitmap.Create; NbLinesInWindow:= 6; End; procedure TCompletionProposalForm.Deactivate; begin Visible:= False; end; destructor TCompletionProposalForm.destroy; begin bitmap.free; Scroll.Free; FItemList.Free; inherited destroy; end; procedure TCompletionProposalForm.KeyDown(var Key: Word; Shift: TShiftState); var i: integer; begin case key of 13: if Assigned(OnValidate) then OnValidate(Self); 27,32: if Assigned(OnCancel) then OnCancel(Self); // I do not think there is a worst way to do this, but laziness rules :-) 33: for i:=1 to NbLinesInWindow do SelectPrec; 34: for i:=1 to NbLinesInWindow do SelectNext; 38: if ssCtrl in Shift then Position:= 0 else SelectPrec; 40: if ssCtrl in Shift then Position:= ItemList.count-1 else SelectNext; 8: if Shift=[] then Begin if Length(CurrentString)<>0 then begin CurrentString:= copy(CurrentString,1,Length(CurrentString)-1); if Assigned(OnKeyDelete) then OnKeyDelete(Self); end; end; end; paint; end; procedure TCompletionProposalForm.KeyPress(var Key: char); begin case key of // #33..'z': Begin CurrentString:= CurrentString+key; if Assigned(OnKeyPress) then OnKeyPress(self, Key); end; #8: CurrentString:= CurrentString+key; else if Assigned(OnCancel) then OnCancel(Self); end; // case paint; end; procedure TCompletionProposalForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin y:= (y-1) div FFontHeight; Position:= Scroll.Position+y; end; procedure TCompletionProposalForm.Paint; var i: integer; begin // update scrool bar if ItemList.Count-NbLinesInWindow<0 then Scroll.Max:= 0 else Scroll.Max:= ItemList.Count-NbLinesInWindow; Position:= Position; Scroll.LargeChange:= NbLinesInWindow; // draw a rectangle around the window Canvas.Pen.Color:= ClBlack; Canvas.Moveto(0, 0); Canvas.LineTo(Width-1, 0); Canvas.LineTo(Width-1, Height-1); Canvas.LineTo(0, Height-1); Canvas.LineTo(0, 0); with bitmap do begin canvas.pen.color:= color; canvas.brush.color:= color; canvas.Rectangle(0,0,Width,Height); For i:= 0 to min(NbLinesInWindow-1,ItemList.Count-1) do Begin if i+Scroll.Position=Position then Begin Canvas.Brush.Color:= ClSelect; Canvas.Pen.Color:= ClSelect; Canvas.Rectangle(0, FFontHeight*i, width, FFontHeight*(i+1)); Canvas.Pen.Color:= ClBlack; end else Canvas.Brush.Color:= Color; if not Assigned(OnPaintItem) or not OnPaintItem(ItemList[Scroll.Position+i], Canvas, 0, FFontHeight*i) then Canvas.TextOut(0, FFontHeight*i, ItemList[Scroll.Position+i]); end; end; canvas.Draw(1, 1, bitmap); end; procedure TCompletionProposalForm.ScrollChange(Sender: TObject); begin if Position < Scroll.Position then Position:= Scroll.Position else if Position > Scroll.Position+NbLinesInWindow-1 then Position:= Scroll.Position+NbLinesInWindow-1; Paint; end; procedure TCompletionProposalForm.ScrollGetFocus(Sender: TObject); begin ActiveControl:= nil; end; procedure TCompletionProposalForm.SelectNext; begin if Position<ItemList.Count-1 then Position:= Position+1; end; procedure TCompletionProposalForm.SelectPrec; begin if Position>0 then Position:= Position-1; end; procedure TCompletionProposalForm.SetCurrentString(const Value: String); var i: integer; begin FCurrentString := Value; i:= 0; if ffansi then while (i<=ItemList.count-1) and (AnsiCompareText(ItemList[i],Value)<0) do inc(i) else while (i<=ItemList.count-1) and (ItemList[i]<Value) do inc(i); if i<=ItemList.Count-1 then Position:= i; end; procedure TCompletionProposalForm.SetItemList(const Value: TStrings); begin FItemList.Assign(Value); end; procedure TCompletionProposalForm.SetNbLinesInWindow(const Value: Integer); begin FNbLinesInWindow := Value; Height:= fFontHeight * NbLinesInWindow + 2; Scroll.top:= 2; Scroll.left:= ClientWidth-Scroll.Width-2; Scroll.Height:= Height-4; bitmap.Width:= Scroll.left-2; bitmap.height:= Height-2; end; procedure TCompletionProposalForm.SetPosition(const Value: Integer); begin if Value<=ItemList.Count-1 then Begin if FPosition<>Value then Begin FPosition := Value; if Position<Scroll.Position then Scroll.Position:= Position else if Scroll.Position < Position-NbLinesInWindow+1 then Scroll.Position:= Position-NbLinesInWindow+1; invalidate; end; end; end; procedure TCompletionProposalForm.StringListChange(Sender: TObject); begin if ItemList.Count-NbLinesInWindow<0 then Scroll.Max:= 0 else Scroll.Max:= ItemList.Count-NbLinesInWindow; Position:= Position; end; { TCompletionProposal } constructor TCompletionProposal.Create(Aowner: TComponent); begin Inherited Create(AOwner); Form:= TCompletionProposalForm.Create(Self); end; destructor TCompletionProposal.Destroy; begin form.Free; Inherited Destroy; end; procedure TCompletionProposal.Execute(s: string; x, y: integer); begin form.top:= y; form.left:= x; CurrentString:= s; if assigned(OnExecute) then OnExecute(Self); form.Show; end; function TCompletionProposal.GetCurrentString: String; begin result:= Form.CurrentString; end; function TCompletionProposal.GetItemList: TStrings; begin result:= Form.ItemList; end; function TCompletionProposal.GetNbLinesInWindow: Integer; begin Result:= Form.NbLinesInWindow; end; function TCompletionProposal.GetOnCancel: TNotifyEvent; begin Result:= Form.OnCancel; end; function TCompletionProposal.GetOnKeyPress: TKeyPressEvent; begin Result:= Form.OnKeyPress; end; function TCompletionProposal.GetOnPaintItem: TCompletionProposalPaintItem; begin Result:= Form.OnPaintItem; end; function TCompletionProposal.GetOnValidate: TNotifyEvent; begin Result:= Form.OnValidate; end; function TCompletionProposal.GetPosition: Integer; begin Result:= Form.Position; end; procedure TCompletionProposal.SetCurrentString(const Value: String); begin form.CurrentString:= Value; end; procedure TCompletionProposal.SetItemList(const Value: TStrings); begin form.ItemList:= Value; end; procedure TCompletionProposal.SetNbLinesInWindow(const Value: Integer); begin form.NbLinesInWindow:= Value; end; procedure TCompletionProposal.SetOnCancel(const Value: TNotifyEvent); begin form.OnCancel:= Value; end; procedure TCompletionProposal.SetOnKeyPress(const Value: TKeyPressEvent); begin form.OnKeyPress:= Value; end; procedure TCompletionProposal.SetOnPaintItem(const Value: TCompletionProposalPaintItem); begin form.OnPaintItem:= Value; end; procedure TCompletionProposal.SetPosition(const Value: Integer); begin form.Position:= Value; end; procedure TCompletionProposal.SetOnValidate(const Value: TNotifyEvent); begin form.OnValidate:= Value; end; function TCompletionProposal.GetClSelect: TColor; begin Result:= Form.ClSelect; end; procedure TCompletionProposal.SetClSelect(const Value: TColor); begin Form.ClSelect:= Value; end; function TCompletionProposal.GetOnKeyDelete: TNotifyEvent; begin result:= Form.OnKeyDelete; end; procedure TCompletionProposal.SetOnKeyDelete(const Value: TNotifyEvent); begin form.OnKeyDelete:= Value; end; procedure TCompletionProposal.RFAnsi(const Value: boolean); begin form.ffAnsi:= value; end; function TCompletionProposal.SFAnsi: boolean; begin result:= form.ffansi; end; procedure Register; begin RegisterComponents(MWS_ComponentsPage, [TMwCompletionProposal, TmwAutoComplete]); end; Procedure PretyTextOut(c: TCanvas; x, y: integer; s: String); var i: integer; b: TBrush; f: TFont; Begin b:= TBrush.Create; b.Assign(c.Brush); f:= TFont.Create; f.Assign(c.Font); try i:= 1; while i<=Length(s) do case s[i] of #1: Begin C.Font.Color:= ord(s[i+1])+ord(s[i+2])*256+ord(s[i+3])*65536; inc(i, 4); end; #2: Begin C.Brush.Color:= ord(s[i+1])+ord(s[i+2])*256+ord(s[i+3])*65536; inc(i, 4); end; #3: Begin case s[i+1] of 'B': c.Font.Style:= c.Font.Style+[fsBold]; 'b': c.Font.Style:= c.Font.Style-[fsBold]; 'U': c.Font.Style:= c.Font.Style+[fsUnderline]; 'u': c.Font.Style:= c.Font.Style-[fsUnderline]; 'I': c.Font.Style:= c.Font.Style+[fsItalic]; 'i': c.Font.Style:= c.Font.Style-[fsItalic]; end; inc(i, 2); end; else C.TextOut(x, y, s[i]); x:= x+c.TextWidth(s[i]); inc(i); end; except end; c.Font.Assign(f); f.Free; c.Brush.Assign(b); b.Free; end; { TMwCompletionProposal } type TRecordUsedToStoreEachEditorVars = record kp: TKeyPressEvent; kd: TKeyEvent; NoNextKey: boolean; end; PRecordUsedToStoreEachEditorVars = ^TRecordUsedToStoreEachEditorVars; procedure TMwCompletionProposal.backspace(Senter: TObject); begin if (senter as TCompletionProposalForm).CurrentEditor <> nil then ((senter as TCompletionProposalForm).CurrentEditor as TmwCustomEdit).CommandProcessor(ecDeleteLastChar,#0,nil); end; procedure TMwCompletionProposal.Cancel(Senter: TObject); begin if (senter as TCompletionProposalForm).CurrentEditor <> nil then begin if (((senter as TCompletionProposalForm).CurrentEditor as TmwCustomEdit).Owner) is TWinControl then TWinControl(((senter as TCompletionProposalForm).CurrentEditor as TmwCustomEdit).Owner).SetFocus; ((senter as TCompletionProposalForm).CurrentEditor as TmwCustomEdit).SetFocus; end; end; procedure TMwCompletionProposal.Validate(Senter: TObject); begin if (senter as TCompletionProposalForm).CurrentEditor <> nil then with ((senter as TCompletionProposalForm).CurrentEditor as TmwCustomEdit) do Begin BlockBegin:= Point(CaretX - length(CurrentString) , CaretY); BlockEnd:= Point(CaretX, CaretY); SelText:= ItemList[position]; SetFocus; end; end; Procedure TMwCompletionProposal.KeyPress(Sender: TObject; var Key: Char); Begin if (sender as TCompletionProposalForm).CurrentEditor <> nil then with ((sender as TCompletionProposalForm).CurrentEditor as TmwCustomEdit) do CommandProcessor(ecChar, Key, NIL); end; procedure TMwCompletionProposal.SetEditor(const Value: TmwCustomEdit); begin AddEditor(Value); end; procedure TMwCompletionProposal.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (fEditors.indexOf(AComponent)<>-1) then RemoveEditor(AComponent as tmwCustomEdit); end; Constructor TMwCompletionProposal.Create(AOwner: TComponent); begin Inherited Create(AOwner); Form.OnKeyPress:= KeyPress; Form.OnKeyDelete:= backspace; Form.OnValidate:= validate; Form.OnCancel:= Cancel; FEndOfTokenChr:= '()[].'; fEditors:= TList.Create; fEditstuffs:= TList.Create; fShortCut := Menus.ShortCut(Ord(' '), [ssCtrl]); end; procedure TMwCompletionProposal.SetShortCut(Value: TShortCut); begin FShortCut := Value; end; procedure TMwCompletionProposal.EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var p: TPoint; i: integer; ShortCutKey: Word; ShortCutShift: TShiftState; begin ShortCutToKey(FShortCut, ShortCutKey, ShortCutShift); i:= fEditors.indexOf(Sender); if i<>-1 then with sender as TmwCustomEdit do begin if (Shift = ShortCutShift) and (Key = ShortCutKey) then Begin p := ClientToScreen(Point(CaretXPix, CaretYPix+LineHeight)); Form.CurrentEditor:= Sender as TmwCustomEdit; Execute(GetPreviousToken(Sender as TmwCustomEdit), p.x, p.y); Key:= 0; TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey:= true; End; if assigned(TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kd) then TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kd(sender, key, shift); end; end; function TMwCompletionProposal.GetPreviousToken(FEditor: TmwCustomEdit): string; var s: String; i: integer; begin if FEditor <> nil then Begin s:= FEditor.LineText; i:= FEditor.CaretX-1; if i>length(s) then result:= '' else begin while (i>0) and (s[i]>' ') and (pos (s[i], FEndOfTokenChr)=0) do dec(i); result:= copy(s, i+1, FEditor.CaretX-i-1); end; end else result:= ''; end; procedure TMwCompletionProposal.EditorKeyPress(Sender: TObject; var Key: char); var i: integer; begin i:= fEditors.IndexOf(Sender); if i<>-1 then begin if TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey then Begin key:= #0; TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey:= false; end; if assigned(TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kp) then TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kp(sender, key); end; end; destructor TMwCompletionProposal.destroy; begin while fEditors.Count<>0 do RemoveEditor(tmwCustomEdit(fEditors.last)); fEditors.Free; fEditstuffs.free; inherited; end; function TMwCompletionProposal.GetFEditor: TmwCustomEdit; begin if EditorsCount>0 then result:= Editors[0] else result:= nil; end; procedure TMwCompletionProposal.AddEditor(Editor: TmwCustomEdit); var p: PRecordUsedToStoreEachEditorVars; begin if fEditors.IndexOf(Editor)=-1 then Begin fEditors.Add(Editor); new(p); p.kp:=Editor.OnKeyPress; p.kd:=Editor.OnKeyDown; p.NoNextKey:= false; fEditstuffs.add(p); Editor.FreeNotification(self); if not (csDesigning in ComponentState) then Begin Editor.OnKeyDown:= EditorKeyDown; Editor.OnKeyPress:= EditorKeyPress; end; end; end; function TMwCompletionProposal.EditorsCount: integer; begin result:= fEditors.count; end; function TMwCompletionProposal.GetEditor(i: integer): TmwCustomEdit; begin if (i<0) or (i>=EditorsCount) then result:= nil else result:= TmwCustomEdit(fEditors[i]); end; function TMwCompletionProposal.RemoveEditor(Editor: TmwCustomEdit): boolean; var i: integer; begin i:= fEditors.Remove(Editor); result:= i<>-1; if result then begin; dispose(fEditstuffs[i]); fEditstuffs.delete(i); end; end; { TmwAutoComplete } procedure TmwAutoComplete.AddEditor(Editor: TmwCustomEdit); var p: PRecordUsedToStoreEachEditorVars; begin if fEditors.IndexOf(Editor)=-1 then Begin fEditors.Add(Editor); new(p); p.kp:=Editor.OnKeyPress; p.kd:=Editor.OnKeyDown; p.NoNextKey:= false; fEditstuffs.add(p); Editor.FreeNotification(self); if not (csDesigning in ComponentState) then Begin Editor.OnKeyDown:= EditorKeyDown; Editor.OnKeyPress:= EditorKeyPress; end; end; end; constructor TmwAutoComplete.Create(AOwner: TComponent); begin inherited; fEditors:= TList.Create; fEditstuffs:= TList.Create; FEndOfTokenChr:= '()[].'; fAutoCompleteList:= TStringList.Create; fShortCut := Menus.ShortCut(Ord(' '), [ssShift]); end; procedure TmwAutoComplete.SetShortCut(Value: TShortCut); begin FShortCut := Value; end; destructor TmwAutoComplete.destroy; begin while feditors.count<>0 do RemoveEditor(feditors.last); fEditors.free; fEditstuffs.free; fAutoCompleteList.free; Inherited; end; procedure TmwAutoComplete.EditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var i: integer; ShortCutKey: Word; ShortCutShift: TShiftState; begin ShortCutToKey(FShortCut, ShortCutKey, ShortCutShift); i:= fEditors.IndexOf(Sender); if i<>-1 then begin if (Shift = ShortCutShift) and (Key = ShortCutKey) then Begin Execute(GetPreviousToken(Sender as TmwCustomEdit), Sender as TmwCustomEdit); Key:= 0; TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey:= true; End; if assigned(TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kd) then TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kd(sender, key, Shift); end; end; procedure TmwAutoComplete.EditorKeyPress(Sender: TObject; var Key: char); var i: integer; begin i:= fEditors.IndexOf(Sender); if i<>-1 then begin if TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey then Begin key:= #0; TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).NoNextKey:= false; end; if assigned(TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kp) then TRecordUsedToStoreEachEditorVars(fEditstuffs[i]^).kp(sender, key); end; end; function TmwAutoComplete.EditorsCount: integer; begin result:= fEditors.count; end; procedure TmwAutoComplete.Execute(token: string; Editor: TmwCustomEdit); Var Temp: string; i, j, prevspace: integer; StartOfBlock: tpoint; Begin i:= AutoCompleteList.IndexOf(token); if i<>-1 then Begin TRecordUsedToStoreEachEditorVars(fEditstuffs[fEditors.IndexOf(Editor)]^).NoNextKey:= true; for j:= 1 to length(token) do Editor.CommandProcessor(ecDeleteLastChar, ' ', nil); inc(i); StartOfBlock:= Point(-1, -1); PrevSpace:= 0; while (i<AutoCompleteList.Count) and (length(AutoCompleteList[i])>0) and (AutoCompleteList[i][1]='=') do Begin for j:= 0 to PrevSpace-1 do Editor.CommandProcessor(ecDeleteLastChar, ' ', nil); Temp:= AutoCompleteList[i]; PrevSpace:= 0; while (length(temp)>=PrevSpace+2) and (temp[PrevSpace+2]<=' ') do inc(PrevSpace); for j:=2 to length(Temp) do Begin Editor.CommandProcessor(ecChar, Temp[j], nil); if Temp[j]='|' then StartOfBlock:= Editor.CaretXY end; inc(i); if (i<AutoCompleteList.Count) and (length(AutoCompleteList[i])>0) and (AutoCompleteList[i][1]='=') then Editor.CommandProcessor(ecLineBreak, ' ', nil); end; if (StartOfBlock.x<>-1) and (StartOfBlock.y<>-1) then Begin Editor.CaretXY:= StartOfBlock; Editor.CommandProcessor(ecDeleteLastChar, ' ', nil); end; end; end; function TmwAutoComplete.GetEdit: TmwCustomEdit; begin if EditorsCount>0 then result:= Editors[0] else result:= nil; end; function TmwAutoComplete.GetEditor(i: integer): TmwCustomEdit; begin if (i<0) or (i>=EditorsCount) then result:= nil else result:= TmwCustomEdit(fEditors[i]); end; function TmwAutoComplete.GetPreviousToken(Editor: tmwCustomEdit): string; var s: String; i: integer; begin if Editor <> nil then Begin s:= Editor.LineText; i:= Editor.CaretX-1; if i>length(s) then result:= '' else begin while (i>0) and (s[i]>' ') and (pos(s[i], FEndOfTokenChr)=0) do dec(i); result:= copy(s, i+1, Editor.CaretX-i-1); end; end else result:= ''; end; procedure TmwAutoComplete.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (fEditors.indexOf(AComponent)<>-1) then RemoveEditor(AComponent as tmwCustomEdit); end; function TmwAutoComplete.RemoveEditor(Editor: TmwCustomEdit): boolean; var i: integer; begin i:= fEditors.Remove(Editor); result:= i<>-1; if result then begin; dispose(fEditstuffs[i]); fEditstuffs.delete(i); end; end; procedure TmwAutoComplete.SetAutoCompleteList(List: TStrings); begin fAutoCompleteList.Assign(List); end; procedure TmwAutoComplete.SetEdit(const Value: TmwCustomEdit); begin AddEditor(Value); end; end.
unit ssl_sk; interface uses ssl_types; var sk_value: function (_stack: PSTACK_OF; _i: TC_INT): Pointer; cdecl = nil; sk_new_null: function: PSTACK_OF; cdecl = nil; sk_push: function(st: PSTACK_OF; data: Pointer): TC_INT; cdecl = nil; sk_pop_free: procedure(st: PSTACK_OF; func: SK_POP_FREE_PROC); cdecl = nil; sk_free: procedure(_stack: PSTACK_OF); cdecl = nil; function sk_X509_NAME_ENTRY_value(_stack: PSTACK_OF_X509_NAME_ENTRY; i: Integer): PX509_NAME_ENTRY; function sk_X509_EXTENSION_new_null: PSTACK_OF_X509_EXTENSION; function sk_X509_EXTENSION_push(_stak: PSTACK_OF_X509_EXTENSION; data: Pointer): TC_INT; procedure sk_X509_EXTENSION_pop_free(st: PSTACK_OF_X509_EXTENSION; func: SK_POP_FREE_PROC); procedure sk_X509_EXTENSION_free(st: PSTACK_OF_X509_EXTENSION); function sk_X509_new_null: PSTACK_OF_X509; function sk_X509_push(_stak: PSTACK_OF_X509; data: Pointer): TC_INT; procedure SSL_initSk; implementation uses ssl_lib; function sk_X509_NAME_ENTRY_value(_stack: PSTACK_OF_X509_NAME_ENTRY; i: Integer): PX509_NAME_ENTRY; begin Result := sk_value(_stack, i); end; function sk_X509_EXTENSION_new_null: PSTACK_OF_X509_EXTENSION; begin Result := sk_new_null; end; function sk_X509_new_null: PSTACK_OF_X509; begin Result := sk_new_null; end; function sk_X509_EXTENSION_push(_stak: PSTACK_OF_X509_EXTENSION; data: Pointer): TC_INT; begin Result := sk_push(_stak, data); end; function sk_X509_push(_stak: PSTACK_OF_X509; data: Pointer): TC_INT; begin Result := sk_push(_stak, data); end; procedure sk_X509_EXTENSION_pop_free(st: PSTACK_OF_X509_EXTENSION; func: SK_POP_FREE_PROC); begin sk_pop_free(st, func); end; procedure sk_X509_EXTENSION_free(st: PSTACK_OF_X509_EXTENSION); begin sk_free(st); end; procedure SSL_initSk; begin if @sk_value = nil then begin @sk_value := LoadFunctionCLib('sk_value'); @sk_new_null := LoadFunctionCLib('sk_new_null'); @sk_push := LoadFunctionCLib('sk_push'); @sk_pop_free := LoadFunctionCLib('sk_pop_free'); @sk_free := LoadFunctionCLib('sk_free'); end; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 260 of 267 From : Rob Perelman 1:202/1308.0 14 Apr 93 23:23 To : Chris Bratene Subj : Pascal Probs ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ CB> - What's the CHARACTER that is returned when you hit your arrow keys? I' > using a CHAR variable for input and would like to know what the arrow > keys give out as a CHAR. CB> ie. When you hit Return/Enter key it gives out #13 CB> Could you lay out the commands for all 4 arrow keys like so: CB> /-\ up arrow = ?? > | > left arrow = ?? <-- --> right arrow = ?? > | > \_/ > down arrow = ?? Try using this program to figure out how to use it:} Program Ordinal; Uses Crt; Var Letter: Char; I: Integer; Begin TextBackGround(Black); TextColor(LightGray); Clrscr; Repeat Letter:=ReadKey; If Letter=#0 then Begin Letter:=ReadKey; Writeln('Special characters: 0, ',Ord(Letter),' (',Letter,')'); End Else Writeln(Letter,' = ',Ord(Letter)); Until Letter=#27; {Escape} End. This will show you how to use arrow keys, F-keys, and Alt-key (and a few other keys)!
unit Grijjy.ErrorReporting; { Some building blocks for creating an exception logger for iOS, Android or macOS. It traps unhandled exceptions and logs them with a stack trace (aka call stack). It can also trap exceptions on Windows, but it does not create a call stack on this platform. DEVELOPER GUIDE =============== For more information, see these blog articles: * Build your own Error Reporter – Part 1: iOS https://blog.grijjy.com/2017/02/09/build-your-own-error-reporter-part-1-ios/ * Build your own Error Reporter – Part 2: Android https://blog.grijjy.com/2017/02/21/build-your-own-error-reporter-part-2-android/ * Build your own Error Reporter – Part 3: Intel macOS64 To enable exception reporting, you need to do the following: * Let the exception logger capture unhandled FMX exceptions (place this where it is executed early, like the constructor of the main form): Application.OnException := TgoExceptionReporter.ExceptionHandler; * Subscribe to the TgoExceptionReportMessage message to get notified of exception reports: TMessageManager.DefaultManager.SubscribeToMessage( TgoExceptionReportMessage, HandleExceptionReport); * In this message handler, you can handle the report in any way you want. For example: * You can email it to your development team. * You can send it to your cloud backend. * You can show it to the user. However, note that the message may be sent from another thread than the UI thread, so you need to synchronize any UI calls with the main thread. * You can send it to a service like HockeyApp. * etc. However, because the app may be unstable now (depending on the type of exception) it may be safest to just write the report to disk and terminate the app (by calling Halt). Then, the next time the app starts up, and can check for this file and handle the report at that point. * Enable embedding of debug information to receive useful callstacks, by setting these project options (menu option "Project | Options..."): * Compiling | Debugging: * Debug information: Limited debug information * Local symbols: False * Symbol reference info: None * Use debug .dcus: True (in case you want symbol information for standard RTL and FXM units) * Linking | Debug information: True (checked) NOTES FOR ANDROID ----------------- For symbolication to work on Android, you need to set the following linker option: * Go to "Project | Options..." * Select the target "All configurations - Android platform" * Go to the page "Delphi Compiler | Linking" * Set "Options passed to the LD linker" to: --version-script=goExports.vsr Make sure goExports.vsr is available in the search path, or set it using an absolute or relative path, as in: --version-script=..\goExports.vsr If you only want symbolication for your Release (play store) build, then select the target "Release configuration - Android platform" instead (or any other configuration you want). NOTES FOR MACOS --------------- To enable line number information: * Add the following post-build event to a 64-bit macOS configuration: LNG.exe "$(OUTPUTPATH)" Make sure the LNG (Line Number Generator) is in the system path, or use an absolute or relative path. The source code for this tool can be found in the Tools directory. Make sure the "Cancel on error" option is checked. * Deploy the .gol file: * In the Deployment Mananger, add the .gol file (usually found in the OSX64\<config>\ directory). * Set the Remote Path to "Contents\MacOS\" * Make sure you do *NOT* deploy the dSYM file, since this is not needed. Uncheck it in the Deployment Manager. Note: the LNG tool uses the dSYM file to extract line number information. If the tool fails for some reason (for example, because the dSYM is not available), then an error is logged to the Output window in Delphi, and the Delphi compilation will fail. The tool creates a .gol file in the same directory as the executable. } interface uses {$IF Defined(MACOS64) and not Defined(IOS)} Grijjy.LineNumberInfo, {$ENDIF} System.SysUtils, System.Messaging; type { Signature of the TApplication.OnException event } TgoExceptionEvent = procedure(Sender: TObject; E: Exception) of object; type { A single entry in a stack trace } TgoCallStackEntry = record public { The address of the code in the call stack. } CodeAddress: UIntPtr; { The address of the start of the routine in the call stack. The CodeAddress value always lies inside the routine that starts at RoutineAddress. This, the value "CodeAddress - RoutineAddress" is the offset into the routine in the call stack. } RoutineAddress: UIntPtr; { The (base) address of the module where CodeAddress is found. } ModuleAddress: UIntPtr; { The line number (of CodeAddress), or 0 if not available. } LineNumber: Integer; { The name of the routine at CodeAddress, if available. } RoutineName: String; { The name of the module where CodeAddress is found. If CodeAddress is somewhere inside your (Delphi) code, then this will be the name of the executable module (or .so file on Android). } ModuleName: String; public { Clears the entry (sets everything to 0) } procedure Clear; end; type { A call stack (aka stack trace) is just an array of call stack entries. } TgoCallStack = TArray<TgoCallStackEntry>; type { Represents an exception report. When an unhandled exception is encountered, it creates an exception report and broadcasts is using a TgoExceptionReportMessage } IgoExceptionReport = interface ['{A949A858-3B30-4C39-9A18-AD2A86B4BD9F}'] {$REGION 'Internal Declarations'} function _GetExceptionMessage: String; function _GetExceptionLocation: TgoCallStackEntry; function _GetCallStack: TgoCallStack; function _GetReport: String; {$ENDREGION 'Internal Declarations'} { The exception message (the value of the Exception.Message property) } property ExceptionMessage: String read _GetExceptionMessage; { The location (address) of the exception. This is of type TgoCallStackEntry, so it also contains information about where and in which routine the exception happened. } property ExceptionLocation: TgoCallStackEntry read _GetExceptionLocation; { The call stack (aka stack trace) leading up the the exception. This also includes calls into the exception handler itself. } property CallStack: TgoCallStack read _GetCallStack; { A textual version of the exception. Contains the exception messages as well as a textual representation of the call stack. } property Report: String read _GetReport; end; type { A type of TMessage that is used to broadcast exception reports. Subscribe to this message (using TMessageManager.DefaultManager.SubscribeToMessage) to get notified about exception reports. @bold(Important): This message is sent from the thread where the exception occured, which may not always be the UI thread. So don't update the UI from this message, or synchronize it with the main thread. } TgoExceptionReportMessage = class(TMessage) {$REGION 'Internal Declarations'} private FReport: IgoExceptionReport; {$ENDREGION 'Internal Declarations'} public { Used internally to create the message. } constructor Create(const AReport: IgoExceptionReport); { The exception report. } property Report: IgoExceptionReport read FReport; end; type { Main class for reporting exceptions. See the documentation at the top of this unit for usage information. } TgoExceptionReporter = class {$REGION 'Internal Declarations'} private class var FInstance: TgoExceptionReporter; {$IF Defined(MACOS64) and not Defined(IOS)} FLineNumberInfo: TgoLineNumberInfo; class function GetLineNumber(const AAddress: UIntPtr): Integer; static; {$ENDIF} class function GetExceptionHandler: TgoExceptionEvent; static; class function GetMaxCallStackDepth: Integer; static; class procedure SetMaxCallStackDepth(const Value: Integer); static; private FMaxCallStackDepth: Integer; FModuleAddress: UIntPtr; FReportingException: Boolean; private constructor InternalCreate(const ADummy: Integer = 0); procedure ReportException(const AExceptionObject: TObject; const AExceptionAddress: Pointer); private class function GetCallStack(const AStackInfo: Pointer): TgoCallStack; static; class function GetCallStackEntry(var AEntry: TgoCallStackEntry): Boolean; static; private { Global hooks } procedure GlobalHandleException(Sender: TObject; E: Exception); class procedure GlobalExceptionAcquiredHandler(Obj: {$IFDEF AUTOREFCOUNT}TObject{$ELSE}Pointer{$ENDIF}); static; class procedure GlobalExceptHandler(ExceptObject: TObject; ExceptAddr: Pointer); static; class function GlobalGetExceptionStackInfo(P: PExceptionRecord): Pointer; static; class procedure GlobalCleanUpStackInfo(Info: Pointer); static; {$ENDREGION 'Internal Declarations'} public { Don't call the constructor manually. This is a singleton. } constructor Create; { Set to Application.OnException handler event to this value to report unhandled exceptions in the main (UI) thread. For example: Application.OnException := TgoExceptionReporter.ExceptionHandler; } class property ExceptionHandler: TgoExceptionEvent read GetExceptionHandler; { Maximum depth of the call stack that is retrieved when an exception occurs. Defaults to 20. Every time an exception is raised, we retrieve a call stack. This adds a little overhead, but raising exceptions is already an "expensive" operation anyway. You can limit this overhead by decreasing the maximum number of entries in the call stack. You can also increase this number of you want a more detailed call stack. Set to 0 to disable call stacks altogether. } class property MaxCallStackDepth: Integer read GetMaxCallStackDepth write SetMaxCallStackDepth; end; implementation uses System.Classes, {$IF Defined(MACOS) or Defined(ANDROID)} Posix.Dlfcn, Posix.Stdlib, {$ENDIF} Grijjy.SymbolTranslator; {$RANGECHECKS OFF} type TgoExceptionReport = class(TInterfacedObject, IgoExceptionReport) private FCallStack: TgoCallStack; FExceptionLocation: TgoCallStackEntry; FExceptionMessage: String; FReport: String; private function BuildReport: String; class function AddressToString(const AAddress: UIntPtr): String; static; protected { IgoExceptionReport } function _GetExceptionMessage: String; function _GetExceptionLocation: TgoCallStackEntry; function _GetCallStack: TgoCallStack; function _GetReport: String; public constructor Create(const AExceptionMessage: String; const AExceptionLocation: TgoCallStackEntry; const ACallStack: TgoCallStack); end; { TgoExceptionReport } class function TgoExceptionReport.AddressToString( const AAddress: UIntPtr): String; begin {$IFDEF CPU64BITS} Result := '$' + IntToHex(AAddress, 16); {$ELSE} Result := '$' + IntToHex(AAddress, 8); {$ENDIF} end; function TgoExceptionReport.BuildReport: String; var SB: TStringBuilder; Entry: TgoCallStackEntry; begin SB := TStringBuilder.Create; try SB.AppendLine(FExceptionMessage); SB.Append('At address: '); SB.Append(AddressToString(FExceptionLocation.CodeAddress)); if (FExceptionLocation.RoutineName <> '') then begin SB.Append(' ('); SB.Append(FExceptionLocation.RoutineName); SB.Append(' + '); SB.Append(FExceptionLocation.CodeAddress - FExceptionLocation.RoutineAddress); if (FExceptionLocation.LineNumber > 0) then begin SB.Append(', line '); SB.Append(FExceptionLocation.LineNumber) end; SB.AppendLine(')'); end else SB.AppendLine; SB.AppendLine; if (FCallStack <> nil) then begin SB.AppendLine('Call stack:'); for Entry in FCallStack do begin SB.AppendFormat('%-25s %s', [ExtractFilename(Entry.ModuleName), AddressToString(Entry.CodeAddress)]); if (Entry.RoutineName <> '') then begin SB.Append(' '); SB.Append(Entry.RoutineName); SB.Append(' + '); SB.Append(Entry.CodeAddress - Entry.RoutineAddress); if (Entry.LineNumber > 0) then begin SB.Append(', line '); SB.Append(Entry.LineNumber) end; end; SB.AppendLine; end; end; Result := SB.ToString; finally SB.Free; end; end; constructor TgoExceptionReport.Create(const AExceptionMessage: String; const AExceptionLocation: TgoCallStackEntry; const ACallStack: TgoCallStack); begin inherited Create; FExceptionMessage := AExceptionMessage; FExceptionLocation := AExceptionLocation; FCallStack := ACallStack; end; function TgoExceptionReport._GetCallStack: TgoCallStack; begin Result := FCallStack; end; function TgoExceptionReport._GetExceptionLocation: TgoCallStackEntry; begin Result := FExceptionLocation; end; function TgoExceptionReport._GetExceptionMessage: String; begin Result := FExceptionMessage; end; function TgoExceptionReport._GetReport: String; begin if (FReport = '') then FReport := BuildReport; Result := FReport; end; { TgoExceptionReportMessage } constructor TgoExceptionReportMessage.Create(const AReport: IgoExceptionReport); begin inherited Create; FReport := AReport; end; { TgoCallStackEntry } procedure TgoCallStackEntry.Clear; begin CodeAddress := 0; RoutineAddress := 0; ModuleAddress := 0; LineNumber := 0; RoutineName := ''; ModuleName := ''; end; { TgoExceptionReporter } constructor TgoExceptionReporter.Create; begin raise EInvalidOperation.Create('Invalid singleton constructor call'); end; class function TgoExceptionReporter.GetExceptionHandler: TgoExceptionEvent; begin { HandleException is usually called in response to the FMX Application.OnException event, which is called for exceptions that aren't handled in the main thread. This event is only fired for exceptions that occur in the main (UI) thread though. } if Assigned(FInstance) then Result := FInstance.GlobalHandleException else Result := nil; end; class function TgoExceptionReporter.GetMaxCallStackDepth: Integer; begin if Assigned(FInstance) then Result := FInstance.FMaxCallStackDepth else Result := 20; end; class procedure TgoExceptionReporter.GlobalCleanUpStackInfo(Info: Pointer); begin { Free memory allocated by GlobalGetExceptionStackInfo } if (Info <> nil) then FreeMem(Info); end; class procedure TgoExceptionReporter.GlobalExceptHandler(ExceptObject: TObject; ExceptAddr: Pointer); begin if Assigned(FInstance) then FInstance.ReportException(ExceptObject, ExceptAddr); end; class procedure TgoExceptionReporter.GlobalExceptionAcquiredHandler( Obj: {$IFDEF AUTOREFCOUNT}TObject{$ELSE}Pointer{$ENDIF}); begin if Assigned(FInstance) then FInstance.ReportException(Obj, ExceptAddr); end; procedure TgoExceptionReporter.GlobalHandleException(Sender: TObject; E: Exception); begin ReportException(E, ExceptAddr); end; constructor TgoExceptionReporter.InternalCreate(const ADummy: Integer); {$IF Defined(IOS) or Defined(ANDROID)} var Info: dl_info; {$ENDIF} begin inherited Create; FMaxCallStackDepth := 20; { Assign the global ExceptionAcquired procedure to our own implementation (it is nil by default). This procedure gets called for unhandled exceptions that happen in other threads than the main thread. } ExceptionAcquired := @GlobalExceptionAcquiredHandler; { The global ExceptProc method can be called for certain unhandled exception. By default, it calls the ExceptHandler procedure in the System.SysUtils unit, which shows the exception message and terminates the app. We set it to our own implementation. } ExceptProc := @GlobalExceptHandler; { We hook into the global static GetExceptionStackInfoProc and CleanUpStackInfoProc methods of the Exception class to provide a call stack for the exception. These methods are unassigned by default. The Exception.GetExceptionStackInfoProc method gets called soon after the exception is created, before the call stack is unwound. This is the only place where we can get the call stack at the point closest to the exception as possible. The Exception.CleanUpStackInfoProc just frees the memory allocated by GetExceptionStackInfoProc. } Exception.GetExceptionStackInfoProc := GlobalGetExceptionStackInfo; Exception.CleanUpStackInfoProc := GlobalCleanUpStackInfo; {$IF Defined(IOS) or Defined(ANDROID)} { Get address of current module. We use this to see if an entry in the call stack is part of this module. We use the dladdr API as a "trick" to get the address of this method, which is obviously part of this module. } if (dladdr(UIntPtr(@TgoExceptionReporter.InternalCreate), Info) <> 0) then FModuleAddress := UIntPtr(Info.dli_fbase); {$ENDIF} end; procedure TgoExceptionReporter.ReportException(const AExceptionObject: TObject; const AExceptionAddress: Pointer); var E: Exception; ExceptionMessage: String; CallStack: TgoCallStack; ExceptionLocation: TgoCallStackEntry; Report: IgoExceptionReport; I: Integer; begin { Ignore exception that occur while we are already reporting another exception. That can happen when the original exception left the application in such a state that other exceptions would happen (cascading errors). } if (FReportingException) then Exit; FReportingException := True; try CallStack := nil; if (AExceptionObject = nil) then ExceptionMessage := 'Unknown Error' else if (AExceptionObject is EAbort) then Exit // do nothing else if (AExceptionObject is Exception) then begin E := Exception(AExceptionObject); ExceptionMessage := E.Message; if (E.StackInfo <> nil) then begin CallStack := GetCallStack(E.StackInfo); for I := 0 to Length(Callstack) - 1 do begin { If entry in call stack is for this module, then try to translate the routine name to Pascal. } if (CallStack[I].ModuleAddress = FModuleAddress) then CallStack[I].RoutineName := goCppSymbolToPascal(CallStack[I].RoutineName); end; end; end else ExceptionMessage := 'Unknown Error (' + AExceptionObject.ClassName + ')'; ExceptionLocation.Clear; ExceptionLocation.CodeAddress := UIntPtr(AExceptionAddress); GetCallStackEntry(ExceptionLocation); if (ExceptionLocation.ModuleAddress = FModuleAddress) then ExceptionLocation.RoutineName := goCppSymbolToPascal(ExceptionLocation.RoutineName); Report := TgoExceptionReport.Create(ExceptionMessage, ExceptionLocation, CallStack); try TMessageManager.DefaultManager.SendMessage(Self, TgoExceptionReportMessage.Create(Report)); except { Ignore any exceptions in the report message handler. } end; finally FReportingException := False; end; end; class procedure TgoExceptionReporter.SetMaxCallStackDepth(const Value: Integer); begin if Assigned(FInstance) then FInstance.FMaxCallStackDepth := Value; end; {$IF Defined(MACOS)} (*****************************************************************************) (*** iOS/macOS specific ******************************************************) (*****************************************************************************) const libSystem = '/usr/lib/libSystem.dylib'; function backtrace(buffer: PPointer; size: Integer): Integer; external libSystem name 'backtrace'; function cxa_demangle(const mangled_name: MarshaledAString; output_buffer: MarshaledAString; length: NativeInt; out status: Integer): MarshaledAString; cdecl; external libSystem name '__cxa_demangle'; type TCallStack = record { Number of entries in the call stack } Count: Integer; { The entries in the call stack } Stack: array [0..0] of UIntPtr; end; PCallStack = ^TCallStack; class function TgoExceptionReporter.GlobalGetExceptionStackInfo( P: PExceptionRecord): Pointer; var CallStack: PCallStack; begin { Don't call into FInstance here. That would only add another entry to the call stack. Instead, retrieve the entire call stack from within this method. Just return nil if we are already reporting an exception, or call stacks are disabled. } if (FInstance = nil) or (FInstance.FReportingException) or (FInstance.FMaxCallStackDepth <= 0) then Exit(nil); { Allocate a PCallStack record large enough to hold just MaxCallStackDepth entries } GetMem(CallStack, SizeOf(Integer{TCallStack.Count}) + FInstance.FMaxCallStackDepth * SizeOf(Pointer)); { Use backtrace API to retrieve call stack } CallStack.Count := backtrace(@CallStack.Stack, FInstance.FMaxCallStackDepth); Result := CallStack; end; class function TgoExceptionReporter.GetCallStack( const AStackInfo: Pointer): TgoCallStack; var CallStack: PCallStack; I: Integer; begin { Convert TCallStack to TgoCallStack } CallStack := AStackInfo; SetLength(Result, CallStack.Count); for I := 0 to CallStack.Count - 1 do begin Result[I].CodeAddress := CallStack.Stack[I]; GetCallStackEntry(Result[I]); end; end; {$IF Defined(MACOS64) and not Defined(IOS)} class function TgoExceptionReporter.GetLineNumber(const AAddress: UIntPtr): Integer; begin if (FLineNumberInfo = nil) then FLineNumberInfo := TgoLineNumberInfo.Create; Result := FLineNumberInfo.Lookup(AAddress); end; {$ENDIF} {$ELSEIF Defined(ANDROID64)} (*****************************************************************************) (*** Android64 specific ******************************************************) (*****************************************************************************) function cxa_demangle(const mangled_name: MarshaledAString; output_buffer: MarshaledAString; length: NativeInt; out status: Integer): MarshaledAString; cdecl; external 'libc++abi.a' name '__cxa_demangle'; type _PUnwind_Context = Pointer; _Unwind_Ptr = UIntPtr; type _Unwind_Reason_code = Integer; const _URC_NO_REASON = 0; _URC_FOREIGN_EXCEPTION_CAUGHT = 1; _URC_FATAL_PHASE2_ERROR = 2; _URC_FATAL_PHASE1_ERROR = 3; _URC_NORMAL_STOP = 4; _URC_END_OF_STACK = 5; _URC_HANDLER_FOUND = 6; _URC_INSTALL_CONTEXT = 7; _URC_CONTINUE_UNWIND = 8; type _Unwind_Trace_Fn = function(context: _PUnwind_Context; userdata: Pointer): _Unwind_Reason_code; cdecl; const LIB_UNWIND = 'libunwind.a'; procedure _Unwind_Backtrace(fn: _Unwind_Trace_Fn; userdata: Pointer); cdecl; external LIB_UNWIND; function _Unwind_GetIP(context: _PUnwind_Context): _Unwind_Ptr; cdecl; external LIB_UNWIND; type TCallStack = record { Number of entries in the call stack } Count: Integer; { The entries in the call stack } Stack: array [0..0] of UIntPtr; end; PCallStack = ^TCallStack; function UnwindCallback(AContext: _PUnwind_Context; AUserData: Pointer): _Unwind_Reason_code; cdecl; var Callstack: PCallstack; begin Callstack := AUserData; if (TgoExceptionReporter.FInstance = nil) or (Callstack.Count >= TgoExceptionReporter.FInstance.FMaxCallStackDepth) then Exit(_URC_END_OF_STACK); Callstack.Stack[Callstack.Count] := _Unwind_GetIP(AContext); Inc(Callstack.Count); Result := _URC_NO_REASON; end; class function TgoExceptionReporter.GlobalGetExceptionStackInfo( P: PExceptionRecord): Pointer; var CallStack: PCallStack; begin { Don't call into FInstance here. That would only add another entry to the call stack. Instead, retrieve the entire call stack from within this method. Just return nil if we are already reporting an exception, or call stacks are disabled. } if (FInstance = nil) or (FInstance.FReportingException) or (FInstance.FMaxCallStackDepth <= 0) then Exit(nil); { Allocate a PCallStack record large enough to hold just MaxCallStackDepth entries } GetMem(CallStack, SizeOf(Integer{TCallStack.Count}) + FInstance.FMaxCallStackDepth * SizeOf(Pointer)); { Use _Unwind_Backtrace API to retrieve call stack } CallStack.Count := 0; _Unwind_Backtrace(UnwindCallback, Callstack); Result := CallStack; end; class function TgoExceptionReporter.GetCallStack( const AStackInfo: Pointer): TgoCallStack; var CallStack: PCallStack; I: Integer; begin { Convert TCallStack to TgoCallStack } CallStack := AStackInfo; SetLength(Result, CallStack.Count); for I := 0 to CallStack.Count - 1 do begin Result[I].CodeAddress := CallStack.Stack[I]; GetCallStackEntry(Result[I]); end; end; {$ELSEIF Defined(ANDROID)} (*****************************************************************************) (*** Android32 specific ******************************************************) (*****************************************************************************) type TGetFramePointer = function: NativeUInt; cdecl; const { We need a function to get the frame pointer. The address of this frame pointer is stored in register R7. In assembly code, the function would look like this: ldr R0, [R7] // Retrieve frame pointer bx LR // Return to caller The R0 register is used to store the function result. The "bx LR" line means "return to the address stored in the LR register". The LR (Link Return) register is set by the calling routine to the address to return to. We could create a text file with this code, assemble it to a static library, and link that library into this unit. However, since the routine is so small, it assembles to just 8 bytes, which we store in an array here. } GET_FRAME_POINTER_CODE: array [0..7] of Byte = ( $00, $00, $97, $E5, // ldr R0, [R7] $1E, $FF, $2F, $E1); // bx LR var { Now define a variable of a procedural type, that is assigned to the assembled code above } GetFramePointer: TGetFramePointer = @GET_FRAME_POINTER_CODE; function cxa_demangle(const mangled_name: MarshaledAString; output_buffer: MarshaledAString; length: NativeInt; out status: Integer): MarshaledAString; cdecl; external {$IF (RTLVersion < 34)}'libgnustl_static.a'{$ELSE}'libc++abi.a'{$ENDIF} name '__cxa_demangle'; type { For each entry in the call stack, we save 7 values for inspection later. See GlobalGetExceptionStackInfo for explaination. } TStackValues = array [0..6] of UIntPtr; type TCallStack = record { Number of entries in the call stack } Count: Integer; { The entries in the call stack } Stack: array [0..0] of TStackValues; end; PCallStack = ^TCallStack; class function TgoExceptionReporter.GlobalGetExceptionStackInfo( P: PExceptionRecord): Pointer; const { On most Android systems, each thread has a stack of 1MB } MAX_STACK_SIZE = 1024 * 1024; var MaxCallStackDepth, Count: Integer; FramePointer, MinStack, MaxStack: UIntPtr; Address: Pointer; CallStack: PCallStack; begin { Don't call into FInstance here. That would only add another entry to the call stack. Instead, retrieve the entire call stack from within this method. Just return nil if we are already reporting an exception, or call stacks are disabled. } if (FInstance = nil) or (FInstance.FReportingException) or (FInstance.FMaxCallStackDepth <= 0) then Exit(nil); MaxCallStackDepth := FInstance.FMaxCallStackDepth; { Allocate a PCallStack record large enough to hold just MaxCallStackDepth entries } GetMem(CallStack, SizeOf(Integer{TCallStack.Count}) + MaxCallStackDepth * SizeOf(TStackValues)); (*We manually walk the stack to create a stack trace. This is possible since Delphi creates a stack frame for each routine, by starting each routine with a prolog. This prolog is similar to the one used by the iOS ABI (Application Binary Interface, see https://developer.apple.com/library/content/documentation/Xcode/Conceptual/iPhoneOSABIReference/Articles/ARMv7FunctionCallingConventions.html The prolog looks like this: * Push all registers that need saving. Always push the R7 and LR registers. * Set R7 (frame pointer) to the location in the stack where the previous value of R7 was just pushed. A minimal prolog (used in many small functions) looks like this: push {R7, LR} mov R7, SP We are interested in the value of the LR (Link Return) register. This register contains the address to return to after the routine finishes. We can use this address to look up the symbol (routine name). Using the example prolog above, we can get to the LR value and walk the stack like this: 1. Set FramePointer to the value of the R7 register. 2. At this location in the stack, you will find the previous value of the R7 register. Lets call this PreviousFramePointer. 3. At the next location in the stack, we will find the LR register. Add its value to our stack trace so we can use it later to look up the routine name at this address. 4. Set FramePointer to PreviousFramePointer and go back to step 2, until FramePointer is 0 or falls outside of the stack. Unfortunately, Delphi doesn't follow the iOS ABI exactly, and it may push other registers between R7 and LR. For example: push {R4, R5, R6, R7, R8, R9, LR} add R7, SP, #12 Here, it pushed 3 registers (R4-R6) before R7, so in the second line it sets R7 to point 12 bytes into the stack (so it still points to the previous R7, as required). However, it also pushed registers R8 and R9, before it pushes the LR register. This means we cannot assume that the LR register will be directly located after the R7 register in the stack. There may be (up to 6) registers in between. We don't know which one represents LR, so we just store all 7 values after R7, and later try to figure out which one represents LR (in the GetCallStack method). *) FramePointer := GetFramePointer; { The stack grows downwards, so all entries in the call stack leading to this call have addresses greater than FramePointer. We don't know what the start and end address of the stack is for this thread, but we do know that the stack is at most 1MB in size, so we only investigate entries from FramePointer to FramePointer + 1MB. } MinStack := FramePointer; MaxStack := MinStack + MAX_STACK_SIZE; { Now we can walk the stack using the algorithm described above. } Count := 0; while (Count < MaxCallStackDepth) and (FramePointer <> 0) and (FramePointer >= MinStack) and (FramePointer < MaxStack) do begin { The first value at FramePointer contains the previous value of R7. Store the 7 values after that. } Address := Pointer(FramePointer + SizeOf(UIntPtr)); Move(Address^, CallStack.Stack[Count], SizeOf(TStackValues)); Inc(Count); { The FramePointer points to the previous value of R7, which contains the previous FramePointer. } FramePointer := PNativeUInt(FramePointer)^; end; CallStack.Count := Count; Result := CallStack; end; class function TgoExceptionReporter.GetCallStack( const AStackInfo: Pointer): TgoCallStack; var CallStack: PCallStack; I, J: Integer; FoundLR: Boolean; begin { Convert TCallStack to TgoCallStack } CallStack := AStackInfo; SetLength(Result, CallStack.Count); for I := 0 to CallStack.Count - 1 do begin { For each entry in the call stack, we have up to 7 values now that may represent the LR register. Most of the time, it will be the first value. We try to find the correct LR value by passing up to all 7 addresses to the dladdr API (by calling GetCallStackEntry). If the API call succeeds, we assume we found the value of LR. However, this is not fool proof because an address value we pass to dladdr may be a valid code address, but not the LR value we are looking for. Also, the LR value contains the address of the next instruction after the call instruction. Delphi usually uses the BL or BLX instruction to call another routine. These instructions takes 4 bytes, so LR will be set to 4 bytes after the BL(X) instruction (the return address). However, we want to know at what address the call was made, so we need to subtract 4 bytes. There is one final complication here: the lowest bit of the LR register indicates the mode the CPU operates in (ARM or Thumb). We need to clear this bit to get to the actual address, by AND'ing it with "not 1". } FoundLR := False; for J := 0 to Length(CallStack.Stack[I]) - 1 do begin Result[I].CodeAddress := (CallStack.Stack[I, J] and not 1) - 4; if GetCallStackEntry(Result[I]) then begin { Assume we found LR } FoundLR := True; Break; end; end; if (not FoundLR) then { None of the 7 values were valid. Set CodeAddress to 0 to signal we couldn't find LR. } Result[I].CodeAddress := 0; end; end; {$ELSE} (*****************************************************************************) (*** Non iOS/Android *********************************************************) (*****************************************************************************) class function TgoExceptionReporter.GlobalGetExceptionStackInfo( P: PExceptionRecord): Pointer; begin { Call stacks are only supported on iOS, Android and macOS } Result := nil; end; class function TgoExceptionReporter.GetCallStack( const AStackInfo: Pointer): TgoCallStack; begin { Call stacks are only supported on iOS, Android and macOS } Result := nil; end; class function TgoExceptionReporter.GetCallStackEntry( var AEntry: TgoCallStackEntry): Boolean; begin { Call stacks are only supported on iOS, Android and macOS } Result := False; end; {$ENDIF} {$IF Defined(MACOS) or Defined(ANDROID)} class function TgoExceptionReporter.GetCallStackEntry( var AEntry: TgoCallStackEntry): Boolean; var Info: dl_info; Status: Integer; Demangled: MarshaledAString; begin Result := (dladdr(AEntry.CodeAddress, Info) <> 0) and (Info.dli_saddr <> nil); if (Result) then begin AEntry.RoutineAddress := UIntPtr(Info.dli_saddr); AEntry.ModuleAddress := UIntPtr(Info.dli_fbase); Demangled := cxa_demangle(Info.dli_sname, nil, 0, Status); if (Demangled = nil) then AEntry.RoutineName := String(Info.dli_sname) else begin AEntry.RoutineName := String(Demangled); Posix.Stdlib.free(Demangled); end; AEntry.ModuleName := String(Info.dli_fname); {$IF Defined(MACOS64) and not Defined(IOS)} AEntry.LineNumber := GetLineNumber(AEntry.CodeAddress); {$ELSE} AEntry.LineNumber := 0; {$ENDIF} end; end; {$ENDIF} initialization TgoExceptionReporter.FInstance := TgoExceptionReporter.InternalCreate; finalization FreeAndNil(TgoExceptionReporter.FInstance); end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 417 of 441 From : Terry Grant 1:210/20.0 11 Apr 93 08:27 To : All Subj : ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ Hello All! Here is a unit I posted some time ago for use with EMSI Sessions. Hope it helps some of you out. You will require a fossil OR Async Interface for this to compile! -----------------------------------------------------------------------------} Program Emsi; Uses Dos , Crt, Fossil; Type HexString = String[4]; Const FingerPrint = '{EMSI}'; System_Address = '1:210/20.0'; { Your address } Password = 'PASSWORD'; { Session password } Link_Codes = '{8N1}'; { Modem setup } Compatibility_Codes = '{JAN}'; { Janis } Mailer_Product_Code = '{00}'; Mailer_Name = 'MagicMail'; Mailer_Version = '1.00'; Mailer_Serial_Number = '{Alpha}'; EMSI_INQ : String = '**EMSI_INQC816'; EMSI_REQ : String = '**EMSI_REQA77E'; EMSI_ACK : String = '**EMSI_ACKA490'; EMSI_NAK : String = '**EMSI_NAKEEC3'; EMSI_CLI : String = '**EMSI_CLIFA8C'; EMSI_ICI : String = '**EMSI_ICI2D73'; EMSI_HBT : String = '**EMSI_HBTEAEE'; EMSI_IRQ : String = '**EMSI_IRQ8E08'; Var EMSI_DAT : String; { NOTE : EMSI_DAT has no maximum length } Length_EMSI_DAT : HexString; { Expressed in Hexidecimal } Packet : String; Rec_EMSI_DAT : String; { EMSI_DAT sent by the answering system } Len_Rec_EMSI_DAT : Word; Len, CRC : HexString; R : Registers; C : Char; Loop,ComPort,TimeOut,Tries : Byte; Temp : String; Function Up_Case(St : String) : String; Begin For Loop := 1 to Length(St) do St[Loop] := Upcase(St[Loop]); Up_Case := St; End; function Hex(i : Word) : HexString; const hc : array[0..15] of Char = '0123456789ABCDEF'; var l, h : Byte; begin l := Lo(i); h := Hi(i); Hex[0] := #4; { Length of String = 4 } Hex[1] := hc[h shr 4]; Hex[2] := hc[h and $F]; Hex[3] := hc[l shr 4]; Hex[4] := hc[l and $F]; end {Hex} ; Function Power(Base,E : Byte) : Longint; Begin Power := Round(Exp(E * Ln(Base) )); End; Function Hex2Dec(HexStr : String) : Longint; Var I,HexBit : Byte; Temp : Longint; Code : integer; Begin Temp := 0; For I := Length(HexStr) downto 1 do Begin If HexStr[I] in ['A','a','B','b','C','c','D','d','E','e','F','f'] then Val('$' + HexStr[I],HexBit,Code) else Val(HexStr[I],HexBit,Code); Temp := Temp + HexBit * Power(16,Length(HexStr) - I); End; Hex2Dec := Temp; End; Function Bin2Dec(BinStr : String) : Longint; { Maximum is 16 bits, though a requirement for more would be } { easy to accomodate. Leading zeroes are not required. There } { is no error handling - any non-'1's are taken as being zero. } Var I : Byte; Temp : Longint; BinArray : Array[0..15] of char; Begin For I := 0 to 15 do BinArray[I] := '0'; For I := 0 to Pred(Length(BinStr)) do BinArray[I] := BinStr[Length(BinStr) - I]; Temp := 0; For I := 0 to 15 do If BinArray[I] = '1' then inc(Temp,Round(Exp(I * Ln(2)))); Bin2Dec := Temp; End; function CRC16(s:string):word; { By Kevin Cooney } var crc : longint; t,r : byte; begin crc:=0; for t:=1 to length(s) do begin crc:=(crc xor (ord(s[t]) shl 8)); for r:=1 to 8 do if (crc and $8000)>0 then crc:=((crc shl 1) xor $1021) else crc:=(crc shl 1); end; CRC16:=(crc and $FFFF); end; {**** FOSSIL Routines ****} {**** Removed from Code ***} Procedure Hangup; Begin Write2Port('+++'+#13); End; {**** EMSI Handshake Routines ****} Procedure Create_EMSI_DAT; Begin FillChar(EMSI_DAT,255,' '); EMSI_DAT := FingerPrint + '{' + System_Address + '}{'+ Password + '}' + Link_Codes + Compatibility_Codes + Mailer_Product_Code + '{' + Mailer_Name + '}{' + Mailer_Version + '}' + Mailer_Serial_Number; Length_EMSI_DAT := Hex(Length(EMSI_DAT)); End; Function Carrier_Detected : Boolean; Begin TimeOut := 20; { Wait approximately 20 seconds } Repeat Delay(1000); Dec(TimeOut); Until (TimeOut = 0) or (Lo(StatusReq) and $80 = $80); If Timeout = 0 then Carrier_Detected := FALSE else Carrier_Detected := TRUE; End; Function Get_EMSI_REQ : Boolean; Begin Temp := ''; Purge_Input; Repeat C := ReadKeyfromPort; If (C <> #10) and (C <> #13) then Temp := Temp + C; Until Length(Temp) = Length(EMSI_REQ); If Up_Case(Temp) = EMSI_REQ then get_EMSI_REQ := TRUE else get_EMSI_REQ := FALSE; End; Procedure Send_EMSI_DAT; Begin CRC := Hex(CRC16('EMSI_DAT' + Length_EMSI_DAT + EMSI_DAT)); Write2Port('**EMSI_DAT' + Length_EMSI_DAT + EMSI_DAT + CRC); End; Function Get_EMSI_ACK : Boolean; Begin Temp := ''; Repeat C := ReadKeyfromPort; If (C <> #10) and (C <> #13) then Temp := Temp + C; Until Length(Temp) = Length(EMSI_ACK); If Up_Case(Temp) = EMSI_ACK then get_EMSI_ACK := TRUE else get_EMSI_ACK := FALSE; End; Procedure Get_EMSI_DAT; Begin Temp := ''; For Loop := 1 to 10 do { Read in '**EMSI_DAT' } Temp := Temp + ReadKeyfromPort; Delete(Temp,1,2); { Remove the '**' } Len := ''; For Loop := 1 to 4 do { Read in the length } Len := Len + ReadKeyFromPort; Temp := Temp + Len; Len_Rec_EMSI_DAT := Hex2Dec(Len); Packet := ''; For Loop := 1 to Len_Rec_EMSI_DAT do { Read in the packet } Packet := Packet + ReadKeyfromPort; Temp := Temp + Packet; CRC := ''; For Loop := 1 to 4 do { Read in the CRC } CRC := CRC + ReadKeyFromPort; Rec_EMSI_DAT := Packet; Writeln('Rec_EMSI_DAT = ',Rec_EMSI_DAT); If Hex(CRC16(Temp)) <> CRC then Writeln('The recieved EMSI_DAT is corrupt!!!!'); End; Begin { Assumes connection has been made at this point } Tries := 0; Repeat Write2Port(EMSI_INQ); Delay(1000); Inc(Tries); Until (Get_EMSI_REQ = TRUE) or (Tries = 5); If Tries = 5 then Begin Writeln('Host system failed to acknowledge the inquiry sequence.'); Hangup; Halt; End; { Used for debugging } Writeln('Boss has acknowledged receipt of EMSI_INQ'); Send_EMSI_DAT; Tries := 0; Repeat Inc(Tries); Until (Get_EMSI_ACK = True) or (Tries = 5); If Tries = 5 then Begin Writeln('Host system failed to acknowledge the EMSI_DAT packet.'); Hangup; halt; End; Writeln('Boss has acknowledged receipt of EMSI_DAT'); Get_EMSI_DAT; Write2Port(EMSI_ACK); { Normally the file transfers would start at this point } Hangup; End. --------------------------------------------------------------------------- This DOES NOT include all the possibilities in an EMSI Session, And JoHo is Revising most of them right now. When I get further information on the changes I will repost adding the NEW Features.
Program List2_Delete; uses crt; type pComponent = ^tComponent; tComponent = record Info: Char; next: pComponent; end; var input, output: text; firstB1,lastB1, //B1-удаляемое слово. firstT, firstTpr, last:pComponent; //firstT,last-текст. function isEmpty(first: pComponent):boolean; //определение существования элементов в списке. begin isEmpty:= (first = nil); end; procedure add (info:Char; var efirst,elast:pComponent); //добавление элементов в список. var old: pComponent; //стандартное добавление в конец списка. begin old:= elast; new(elast); elast^.Info:= info; elast^.next:= nil; if isEmpty(efirst) then efirst:= elast else old^.next:= elast; end; procedure print(p:pComponent); //Печать списка. begin write(' '); while p<>nil do //Перебор элементов списка. begin write(p^.Info); p:=p^.next; end; writeln(); end; procedure getline(var fi,la:pComponent); var c:Char; begin while not EOLN(input) do //Считываем строку. И сразу заполняем символьный список. begin read(input,c); add(c,fi,la); end; readln(input); end; procedure gettext(var fi,la:pComponent); var c:Char; begin while not EOF(input) do //Считываем текст. И сразу заполняем символьный список. begin read(input,c); add(c,fi,la); end; readln(input); end; Procedure DeleteW(var started{после какого}, ended{последнее удаляемое}: pComponent); //удаление с начального узла до конечного. var c,p: pComponent; begin c:=started^.next; //с какого удалять сохранили started^.next:=ended^.next; while c<>ended do begin p:=c; c:=c^.next; Dispose(p); end; p:=ended; ended:=ended^.next; Dispose(p); end; procedure search(Vf: pComponent;{удаляемое} var T:pComponent{голова текста}); //Поиск и сравнение слов в тексте с тем, которое нужно удалить. var s,startW,tec: pComponent; //prev - элемент, после которого удаляем. var b:boolean; begin startW:=T; tec:=T; while tec<>nil do //Перебор текста begin s:=Vf; //Присваиваем первую компоненту слова, которое удаляем. Нужна для итерации. if tec^.Info=Vf^.Info then //Совпадение первой буквы begin b:=true; //Будет и в дальнейшем тру, если нужное слово найдется. while (tec^.next<>nil) and (s^.next<>nil) and b do begin tec:=tec^.next; s:=s^.next; if (tec^.Info<>s^.Info) then b:=false; //Не совпало. end; if b then DeleteW(startW, tec); // Совпало - удаляем. end else begin startW:=tec; //возможно после какого удаляем. tec:=tec^.next; end; end; end; procedure destroy(var fi:pComponent); //сборка мусора. var c:pComponent; begin while not isEmpty(fi)do //DISPOSE begin c:=fi; fi:=fi^.next; Dispose(c); end; end; begin clrscr; Assign(input, 'input.txt'); //Работа с файлами. Assign(output,'output.txt'); reset(input); rewrite(output); getline(firstB1,lastB1); gettext(firstT,last); new(firstTpr); firstTpr^.Info:=' '; firstTpr^.next:=firstT; print(firstB1); print(firstTpr); search(firstB1,firstTpr); //Начало обработки. print(firstTpr); destroy(firstB1); destroy(firstTpr); close(input); close(output); end.
unit FVectorEditor; interface uses Forms, ComCtrls, StdCtrls, ToolWin, ExtCtrls, Buttons, Graphics, Controls, Classes; type TVectorEditorForm = class(TForm) EDx: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; EDy: TEdit; EDz: TEdit; BBok: TBitBtn; BBcancel: TBitBtn; IMx: TImage; IMy: TImage; IMz: TImage; ToolBar: TToolBar; TBx: TToolButton; TBy: TToolButton; TBz: TToolButton; TBnull: TToolButton; ToolButton5: TToolButton; procedure TBxClick(Sender: TObject); procedure TByClick(Sender: TObject); procedure TBzClick(Sender: TObject); procedure TBnullClick(Sender: TObject); procedure EDxChange(Sender: TObject); procedure EDyChange(Sender: TObject); procedure EDzChange(Sender: TObject); private { Déclarations privées } vx, vy, vz : Single; procedure TestInput(edit : TEdit; imError : TImage; var dest : Single); public { Déclarations publiques } function Execute(var x, y, z : Single) : Boolean; end; function VectorEditorForm : TVectorEditorForm; procedure ReleaseVectorEditorForm; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ {$R *.DFM} uses SysUtils; var vVectorEditorForm : TVectorEditorForm; function VectorEditorForm : TVectorEditorForm; begin if not Assigned(vVectorEditorForm) then vVectorEditorForm:=TVectorEditorForm.Create(nil); Result:=vVectorEditorForm; end; procedure ReleaseVectorEditorForm; begin if Assigned(vVectorEditorForm) then begin vVectorEditorForm.Free; vVectorEditorForm:=nil; end; end; // Execute // function TVectorEditorForm.Execute(var x, y, z : Single) : Boolean; begin // setup dialog fields vx:=x; vy:=y; vz:=z; EDx.Text:=FloatToStr(vx); EDy.Text:=FloatToStr(vy); EDz.Text:=FloatToStr(vz); // show the dialog Result:=(ShowModal=mrOk); if Result then begin x:=vx; y:=vy; z:=vz; end; end; procedure TVectorEditorForm.TestInput(edit : TEdit; imError : TImage; var dest : Single); begin if Visible then begin try dest:=StrToFloat(edit.Text); imError.Visible:=False; except imError.Visible:=True; end; BBOk.Enabled:=not (IMx.Visible or IMy.Visible or IMz.Visible); end; end; procedure TVectorEditorForm.TBxClick(Sender: TObject); begin EDx.Text:='1'; EDy.Text:='0'; EDz.Text:='0'; end; procedure TVectorEditorForm.TByClick(Sender: TObject); begin EDx.Text:='0'; EDy.Text:='1'; EDz.Text:='0'; end; procedure TVectorEditorForm.TBzClick(Sender: TObject); begin EDx.Text:='0'; EDy.Text:='0'; EDz.Text:='1'; end; procedure TVectorEditorForm.TBnullClick(Sender: TObject); begin EDx.Text:='0'; EDy.Text:='0'; EDz.Text:='0'; end; procedure TVectorEditorForm.EDxChange(Sender: TObject); begin TestInput(EDx, IMx, vx); end; procedure TVectorEditorForm.EDyChange(Sender: TObject); begin TestInput(EDy, IMy, vy); end; procedure TVectorEditorForm.EDzChange(Sender: TObject); begin TestInput(EDz, IMz, vz); end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ finalization ReleaseVectorEditorForm; end.
unit UfrmCadastroBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TfrmCadastroBase = class(TForm) pnTopo: TPanel; btnUltimo: TButton; btnAvançar: TButton; btnVoltar: TButton; btnPrimeiro: TButton; btnPesquisa: TButton; btnSalvar: TButton; btnExcluir: TButton; btnEditar: TButton; btnAdicionar: TButton; btnCancelar: TButton; gbCadastro: TGroupBox; fdqConexaoTabela: TFDQuery; dsTabela: TDataSource; btnFechar: TButton; procedure Ativo(); procedure btnAdicionarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnPrimeiroClick(Sender: TObject); procedure btnUltimoClick(Sender: TObject); procedure btnAvançarClick(Sender: TObject); procedure btnVoltarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure btnExcluirClick(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var frmCadastroBase: TfrmCadastroBase; implementation {$R *.dfm} uses UfrmConexao; { TfrmCadastroBase } procedure TfrmCadastroBase.Ativo; begin if btnSalvar.Enabled=false then begin btnAdicionar.Enabled:=false; btnEditar.Enabled:=false; btnExcluir.Enabled:=false; btnAvançar.Enabled:=false; btnVoltar.Enabled:=false; btnPrimeiro.Enabled:=false; btnUltimo.Enabled:=false; btnSalvar.Enabled:=true; btnCancelar.Enabled:=true; gbCadastro.Enabled:=true; end else begin btnAdicionar.Enabled:=true; btnEditar.Enabled:=true; btnExcluir.Enabled:=true; btnAvançar.Enabled:=true; btnVoltar.Enabled:=true; btnPrimeiro.Enabled:=true; btnUltimo.Enabled:=true; btnSalvar.Enabled:=false; btnCancelar.Enabled:=false; gbCadastro.Enabled:=false; end end; procedure TfrmCadastroBase.btnAdicionarClick(Sender: TObject); begin fdqConexaoTabela.Append; Ativo(); end; procedure TfrmCadastroBase.btnAvançarClick(Sender: TObject); begin fdqConexaoTabela.Next; end; procedure TfrmCadastroBase.btnCancelarClick(Sender: TObject); begin fdqConexaoTabela.Cancel; Application.MessageBox('CANCELADO!','Ação cancelada.',MB_OK+MB_ICONEXCLAMATION); Ativo(); end; procedure TfrmCadastroBase.btnEditarClick(Sender: TObject); begin fdqConexaoTabela.Edit; Ativo(); end; procedure TfrmCadastroBase.btnExcluirClick(Sender: TObject); var user:Integer; begin try user:=Application.MessageBox('Deseja realmente Excluir?','Exclusão de cadastro.',MB_YESNO+MB_ICONQUESTION); //6= sim / 7= nao if user=6 then begin fdqConexaoTabela.Delete; Application.MessageBox('Item Excluido!','Exclusão de cadastro.',MB_OK+MB_ICONEXCLAMATION); end else begin Application.MessageBox('CANCELADO!','Exclusão de cadastro cancelada.',MB_OK+MB_ICONEXCLAMATION); end; Except btnExcluir.Enabled:=false; Application.MessageBox('Impossivel excluir cadastro inexistente.','Atenção!',MB_OK+MB_ICONERROR) end; end; procedure TfrmCadastroBase.btnPrimeiroClick(Sender: TObject); begin fdqConexaoTabela.First; end; procedure TfrmCadastroBase.btnSalvarClick(Sender: TObject); begin fdqConexaoTabela.Post; Ativo(); Application.MessageBox('Salvo!','Salvo com sucesso.',MB_OK+MB_ICONEXCLAMATION); end; procedure TfrmCadastroBase.btnUltimoClick(Sender: TObject); begin fdqConexaoTabela.Last; end; procedure TfrmCadastroBase.btnVoltarClick(Sender: TObject); begin fdqConexaoTabela.Prior; end; procedure TfrmCadastroBase.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = #27 then //tem que verificar o keyPreviw begin case application.MessageBox('Deseja realmente fechar o programa?', 'Confirmação', MB_yesno + MB_iconInformation) of mrNo, mrCancel: Application.MessageBox('retomando os testes.','Continuando...'); mrYes: Close; end; end; if (Key = #13) then begin //Key := #0; Perform(Wm_NextDlgCtl,0,0); end; end; procedure TfrmCadastroBase.btnFecharClick(Sender: TObject); begin close; end; end.
unit MVC.FrameBlock; interface uses System.Classes, MVC.ViewBlocks, Vcl.Forms; // ------------ ------------ ------------ ------------ ------------ -------- // {{ Переключиться на UTF-8 }} // TODO: Dodać dokumentację do klasy TFrameBlock // * Uwaga dokumentacja powinna być przetłumaczona na jęz. angielski // ------------ ------------ ------------ ------------ ------------ -------- type TVclFrameClass = class of Vcl.Forms.TFrame; TFrameBlock = class(TViewBlock) private FFrame: TFrame; procedure SetFrame(const Value: TFrame); public procedure BuildAndShow(ViewFrameClass: TVclFrameClass); virtual; property Frame: TFrame read FFrame write SetFrame; end; implementation uses System.SysUtils, Vcl.Controls; procedure TFrameBlock.BuildAndShow(ViewFrameClass: TVclFrameClass); var AContainer: TWinControl; begin if not(self.Owner is Vcl.Controls.TWinControl) then raise Exception.Create ('Invalid Parent Class! Expected TWinControl as Parent.'); AContainer := (self.Owner as TWinControl); Frame := ViewFrameClass.Create(self); Frame.Align := alClient; Frame.Parent := AContainer; end; procedure TFrameBlock.SetFrame(const Value: TFrame); begin FFrame := Value; end; end.
{ Поиск всех возможных маршрутов между двумя точками графа } program all_road; const N=7;{ кол-во вершин графа} var map:array[1..N,1..N] of integer;{ Карта: map[i,j] не 0, если точки i и j соединены } road:array[1..N] of integer;{ Маршрут - номера точек карты } incl:array[1..N] of boolean;{ incl[i]=TRUE, если точка } { с номером i включена в road } start,finish:integer;{ Начальная и конечная точки } i,j:integer; procedure step(s,f,p:integer);{ s - точка, из которой делается шаг} { f - конечная точка маршрута} { p - номер искомой точки маршрута} var c:integer;{ Номер точки, в которую делается очередной шаг } begin if s=f then begin {Точки s и f совпали!} write('Путь: '); for i:=1 to p-1 do write(road[i],' '); writeln; end else begin { Выбираем очередную точку } for c:=1 to N do begin { Проверяем все вершины } if(map[s,c]<>0)and(NOT incl[c]) { Точка соединена с текущей и не включена } { в маршрут} then begin road[p]:=c;{ Добавим вершину в путь } incl[c]:=TRUE;{ Пометим вершину } { как включенную } step(c,f,p+1); incl[c]:=FALSE; road[p]:=0; end; end; end; end;{ конец процедуры step } { Основная программа } begin { Инициализация массивов } for i:=1 to N do road[i]:=0; for i:=1 to N do incl[i]:=FALSE; for i:=1 to N do for j:=1 to N do map[i,j]:=0; { Ввод значений элементов карты } map[1,2]:=1; map[2,1]:=1; map[1,3]:=1; map[3,1]:=1; map[1,4]:=1; map[4,1]:=1; map[3,4]:=1; map[4,3]:=1; map[3,7]:=1; map[7,3]:=1; map[4,6]:=1; map[6,4]:=1; map[5,6]:=1; map[6,5]:=1; map[5,7]:=1; map[7,5]:=1; map[6,7]:=1; map[7,6]:=1; write('Введите через пробел номера начальной и конечной точек -> '); readln(start,finish); road[1]:=start;{ Внесем точку в маршрут } incl[start]:=TRUE;{ Пометим ее как включенную } step(start,finish,2);{Ищем вторую точку маршрута } writeln('Для завершения нажмите <Enter>'); readln; end.
unit ConsoleLogWriter; {$mode objfpc}{$H+} {$INTERFACES CORBA} interface uses Classes, SysUtils, LogWriter, LogItem, JobThread, LogTextFormat, ComponentEnhancer; type { TConsoleLogWriter } TConsoleLogWriter = class(TComponent, ILogWriter, IDemandsLogTextFormat) private fFormat: ILogTextFormat; procedure SetFormat(const aFormat: ILogTextFormat); function GetName: string; function Reverse: TObject; public property Format: ILogTextFormat read fFormat write SetFormat; procedure Write(const aThread: TJobThread; const aItem: PLogItem); end; implementation { TConsoleLogWriter } procedure TConsoleLogWriter.SetFormat(const aFormat: ILogTextFormat); begin fFormat := aFormat; end; function TConsoleLogWriter.GetName: string; begin result := GetClassAndName; end; function TConsoleLogWriter.Reverse: TObject; begin result := self; end; procedure TConsoleLogWriter.Write(const aThread: TJobThread; const aItem: PLogItem); var text: string; begin if IsConsole then begin if not Assigned(Format) then WriteLN('Console Log Writer Error: Format property unassigned.'); text := Format.Format(aItem); WriteLN(text); end; end; end.
/*Mehtode: FindWord();NextWordPos(); (COUNT()); printResult(); */ void countWords(String text, INTEGER n) String words[100] INTEGER iWords[100] INTEGER pos = 0 INTEGER highestPOS = 0 String word = "" while (pos < n) do int i = 0 word = nextWord(text, pos, n) while (words[i] != word) if (i == highestPOS+1) then words[i] = word highestPOS++ else i++ end --if end --while iWords[i]+=1 end --while printResult(words,iWords,highestPOS) end countWords INTEGER nextPos(String text, INTEGER pos, INTEGER n) while((text[pos]==' ')||(text[pos]==',')||(text[pos]=='.')&&(pos < n)) do pos++; end --while end --nextPos String nextWord(String text, INTEGER pos, INTEGER n) String rS = "" while ((text[pos]!=' ')&&(text[pos]!=',')&&(text[pos]!='.')&&(pos < n)) do rS = rS+text[pos] pos++ end --while nextPos(text, pos, n) return rS end --nextWord printResult(INTEGER words[], INTEGER quant[], INTEGER high) for(INTEGER i = 0; i<=high; i++) write("%c: %d",word[i],quant[i]) end --for end --printResult
{ *************************************************************************** } { } { NLDXPSelection - www.nldelphi.com Open Source designtime component } { } { Initiator: Albert de Weerd (aka NGLN) } { License: Free to use, free to modify } { Website: http://www.nldelphi.com/forum/showthread.php?t=19564 } { SVN path: http://svn.nldelphi.com/nldelphi/opensource/ngln/NLDXPSelection } { } { *************************************************************************** } { } { Date: May 17, 2008 } { Version: 2.0.0.0 } { } { *************************************************************************** } unit NLDXPSelection; interface uses Messages, Windows, Graphics, Classes; const DefXPSelColor = clHighLight; WM_XPSELECTIONRESIZE = WM_APP + 13294; WM_XPSELECTIONFINISH = WM_APP + 13295; type TWMXPSelect = packed record Msg: Cardinal; TopLeft: TSmallPoint; BottomRight: TSmallPoint; Unused: LongInt; end; TXPSelectEvent = procedure(Sender: TObject; const SelRect: TRect) of object; TCustomXPSelection = class(TComponent) private FColor: TColor; FOnFinish: TXPSelectEvent; FOnResize: TXPSelectEvent; FSelectionControl: Pointer; procedure SetColor(const Value: TColor); protected property Color: TColor read FColor write SetColor default DefXPSelColor; property OnFinish: TXPSelectEvent read FOnFinish write FOnFinish; property OnResize: TXPSelectEvent read FOnResize write FOnResize; public constructor Create(AOwner: TComponent); override; procedure Start(const MaxBounds: TRect); end; TNLDXPSelection = class(TCustomXPSelection) published property Color; property OnFinish; property OnResize; end; procedure Register; implementation uses Controls, Forms, Math; procedure Register; begin RegisterComponents('NLDelphi', [TNLDXPSelection]); end; { TXPSelectionControl } type TXPSelectionControl = class(TCustomControl) private FBitmap: TBitmap; FBlendFunc: BLENDFUNCTION; FFilter: TBitmap; FForm: TCustomForm; FMaxBounds: TRect; FP1: TPoint; FP2: TPoint; FXPSelection: TCustomXPSelection; procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED; procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; protected procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure RequestAlign; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init(const MaxBounds: TRect); end; procedure TXPSelectionControl.CMColorChanged(var Message: TMessage); begin FFilter.Canvas.Brush.Color := Color; Canvas.Pen.Color := Color; end; constructor TXPSelectionControl.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csCaptureMouse, csOpaque]; FBitmap := TBitmap.Create; FFilter := TBitmap.Create; FBlendFunc.BlendOp := AC_SRC_OVER; FBlendFunc.SourceConstantAlpha := 80; FXPSelection := TCustomXPSelection(AOwner); FForm := TCustomForm(FXPSelection.Owner); Parent := FForm; end; destructor TXPSelectionControl.Destroy; begin FFilter.Free; FBitmap.Free; inherited Destroy; end; procedure TXPSelectionControl.Init(const MaxBounds: TRect); var FormClientRect: TRect; begin if not MouseCapture then begin FP1 := FForm.ScreenToClient(Mouse.CursorPos); FormClientRect := FForm.ClientRect; FMaxBounds.Left := Max(MaxBounds.Left, 0); FMaxBounds.Top := Max(MaxBounds.Top, 0); FMaxBounds.Right := Min(MaxBounds.Right, FormClientRect.Right); FMaxBounds.Bottom := Min(MaxBounds.Bottom, FormClientRect.Right); FFilter.Width := FormClientRect.Right; FFilter.Height := FormClientRect.Bottom; FFilter.Canvas.FillRect(FormClientRect); FBitmap.Width := FormClientRect.Right; FBitmap.Height := FormClientRect.Bottom; FBitmap.Canvas.CopyRect(FormClientRect, FForm.Canvas, FormClientRect); with FBitmap do AlphaBlend(Canvas.Handle, 1, 1, Width - 2, Height - 2, FFilter.Canvas.Handle, 0, 0, Width - 3, Height - 3, FBlendFunc); BringToFront; MouseCapture := True; end; end; procedure TXPSelectionControl.MouseMove(Shift: TShiftState; X, Y: Integer); begin FP2.X := Max(FMaxBounds.Left, Min(Left + X, FMaxBounds.Right)); FP2.Y := Max(FMaxBounds.Top, Min(Top + Y, FMaxBounds.Bottom)); if (Abs(FP1.X - FP2.X) > Mouse.DragThreshold) or (Abs(FP1.Y - FP2.Y) > Mouse.DragThreshold) then Show; if Visible then begin SetBounds(Min(FP1.X, FP2.X), Min(FP1.Y, FP2.Y), Abs(FP1.X - FP2.X), Abs(FP1.Y - FP2.Y)); FForm.Update; if Assigned(FXPSelection.FOnResize) then FXPSelection.FOnResize(FXPSelection, BoundsRect) else PostMessage(FForm.Handle, WM_XPSELECTIONRESIZE, Integer(PointToSmallPoint(BoundsRect.TopLeft)), Integer(PointToSmallPoint(BoundsRect.BottomRight))); end; end; procedure TXPSelectionControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin MouseCapture := False; if Visible then begin Hide; if Assigned(FXPSelection.FOnFinish) then FXPSelection.FOnFinish(FXPSelection, BoundsRect) else PostMessage(FForm.Handle, WM_XPSELECTIONFINISH, Integer(PointToSmallPoint(BoundsRect.TopLeft)), Integer(PointToSmallPoint(BoundsRect.BottomRight))); end; end; procedure TXPSelectionControl.RequestAlign; begin {eat inherited} end; procedure TXPSelectionControl.WMEraseBkgnd(var Msg: TWMEraseBkgnd); begin Msg.Result := 1; end; procedure TXPSelectionControl.WMPaint(var Msg: TWMPaint); begin BitBlt(Canvas.Handle, 1, 1, Width - 2, Height - 2, FBitmap.Canvas.Handle, Left + 1, Top + 1, SRCCOPY); Canvas.LineTo(0, Height - 1); Canvas.LineTo(Width - 1, Height - 1); Canvas.LineTo(Width - 1, 0); Canvas.LineTo(0, 0); Msg.Result := 0; end; { TCustomXPSelection } const SErrInvalidOwnerF = 'XPSelection ''%s'' must be owned by a TCustomForm'; constructor TCustomXPSelection.Create(AOwner: TComponent); begin if AOwner is TCustomForm then begin inherited Create(AOwner); if not (csDesigning in ComponentState) then FSelectionControl := TXPSelectionControl.Create(Self); SetColor(DefXPSelColor); end else raise EComponentError.CreateFmt(SErrInvalidOwnerF, [Name]); end; procedure TCustomXPSelection.SetColor(const Value: TColor); begin if FColor <> Value then begin if Value = clDefault then FColor := DefXPSelColor else FColor := Value; if FSelectionControl <> nil then TXPSelectionControl(FSelectionControl).Color := FColor; end; end; procedure TCustomXPSelection.Start(const MaxBounds: TRect); begin TXPSelectionControl(FSelectionControl).Init(MaxBounds); end; end.
unit uServer; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, Vcl.StdCtrls, IdGlobal, IdException, IdSocketHandle, IdThread, IdSync, Vcl.ExtCtrls, UnitGlobal; type TMyIdNotify = class(TIdNotify) protected procedure DoNotify; override; public mMyData: TMyData; isMyData: Boolean; strMsg: String; end; type TFormServer = class(TForm) Memo1: TMemo; BtnStart: TButton; BtnStop: TButton; BtnBroadcast: TButton; IdTCPServer1: TIdTCPServer; LedtPort: TLabeledEdit; ListBoxClient: TListBox; edtSend: TEdit; btnSend: TButton; btnClearMemo: TButton; procedure IdTCPServer1Execute(AContext: TIdContext); procedure BtnStartClick(Sender: TObject); procedure BtnStopClick(Sender: TObject); procedure IdTCPServer1AfterBind(Sender: TObject); procedure IdTCPServer1BeforeBind(AHandle: TIdSocketHandle); procedure IdTCPServer1BeforeListenerRun(AThread: TIdThread); procedure IdTCPServer1Connect(AContext: TIdContext); procedure IdTCPServer1ContextCreated(AContext: TIdContext); procedure IdTCPServer1Disconnect(AContext: TIdContext); procedure IdTCPServer1Exception(AContext: TIdContext; AException: Exception); procedure IdTCPServer1ListenException(AThread: TIdListenerThread; AException: Exception); procedure IdTCPServer1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); procedure BtnBroadcastClick(Sender: TObject); procedure btnSendClick(Sender: TObject); procedure btnClearMemoClick(Sender: TObject); procedure edtSendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private procedure SendMessage; procedure Multi_cast; { Private declarations } public { Public declarations } procedure StopServer; end; // -------------------------------------------- type TMyContext = class(TIdContext) public UserName: String; Password: String; end; var FormServer: TFormServer; implementation {$R *.dfm} procedure TFormServer.BtnBroadcastClick(Sender: TObject); begin Multi_cast; end; procedure TFormServer.btnClearMemoClick(Sender: TObject); begin Memo1.Lines.Clear; end; procedure TFormServer.btnSendClick(Sender: TObject); var str: TStringBuilder; begin SendMessage; end; procedure TFormServer.BtnStartClick(Sender: TObject); var str: String; begin IdTCPServer1.Bindings.DefaultPort := StrToInt(LedtPort.Text); Memo1.Lines.Add('IdTCPServer.Bindings.DefaultPort' + LedtPort.Text); try IdTCPServer1.Active := True; Memo1.Lines.Add('IdTCPServer1.Active := True;'); except on E: EIdException do Memo1.Lines.Add('== EIdException: ' + E.Message); end; BtnStop.Enabled := True; BtnStart.Enabled := False; end; procedure TFormServer.BtnStopClick(Sender: TObject); begin StopServer; BtnStart.Enabled := True; BtnStop.Enabled := False; end; procedure TFormServer.edtSendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then Multi_cast; end; procedure TFormServer.FormClose(Sender: TObject; var Action: TCloseAction); begin StopServer; end; procedure TFormServer.SendMessage; var List: TList; str: TStringBuilder; begin if ListBoxClient.ItemIndex = -1 then begin Memo1.Lines.Add('請選擇一個 Client'); end else begin try List := IdTCPServer1.Contexts.LockList; if List.Count = 0 then begin exit; end; TIdContext(List[ListBoxClient.ItemIndex]).Connection.IOHandler.WriteLn (edtSend.Text, IndyTextEncoding_UTF8); finally IdTCPServer1.Contexts.UnlockList; end; str := TStringBuilder.Create; str.Append('SendMessage('); str.Append(ListBoxClient.Items[ListBoxClient.ItemIndex]); str.Append('): '); str.Append(edtSend.Text); Memo1.Lines.Add(str.ToString); str.DisposeOf; end; end; procedure TFormServer.Multi_cast; var List: TList; I: Integer; begin List := IdTCPServer1.Contexts.LockList; try if List.Count = 0 then begin Memo1.Lines.Add('沒有Client連線!'); exit; end else Memo1.Lines.Add('Multi_cast:' + edtSend.Text); for I := 0 to List.Count - 1 do begin try TIdContext(List[I]).Connection.IOHandler.WriteLn(edtSend.Text, IndyTextEncoding_UTF8); except on E: EIdException do Memo1.Lines.Add('== EIdException: ' + E.Message); end; end; finally IdTCPServer1.Contexts.UnlockList; end; end; procedure TFormServer.IdTCPServer1AfterBind(Sender: TObject); begin Memo1.Lines.Add('S-AfterBind'); end; procedure TFormServer.IdTCPServer1BeforeBind(AHandle: TIdSocketHandle); begin Memo1.Lines.Add('S-BeforeBind'); end; procedure TFormServer.IdTCPServer1BeforeListenerRun(AThread: TIdThread); begin Memo1.Lines.Add('S-BeforeListenerRun'); end; procedure TFormServer.IdTCPServer1Connect(AContext: TIdContext); var str: String; begin str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString; Memo1.Lines.Add(DateTimeToStr(Now)); Memo1.Lines.Add('S-Connect: ' + str); ListBoxClient.Items.Add(str); // 自動選擇最後新增的 if ListBoxClient.Count > -1 then ListBoxClient.ItemIndex := ListBoxClient.Count - 1; end; procedure TFormServer.IdTCPServer1ContextCreated(AContext: TIdContext); var str: String; begin str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString; Memo1.Lines.Add(DateTimeToStr(Now)); Memo1.Lines.Add('S-ContextCreated ' + str); end; procedure TFormServer.IdTCPServer1Disconnect(AContext: TIdContext); var Index: Integer; str: String; begin str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString; Index := ListBoxClient.Items.IndexOf(str); ListBoxClient.Items.Delete(index); Memo1.Lines.Add(DateTimeToStr(Now)); Memo1.Lines.Add('S-Disconnect: ' + str); end; procedure TFormServer.IdTCPServer1Exception(AContext: TIdContext; AException: Exception); var str: String; begin str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString; Memo1.Lines.Add('IdTCPServer1Exception: ' + str); Memo1.Lines.Add('S-Exception:' + AException.Message); end; procedure TMyIdNotify.DoNotify; begin if isMyData then begin with FormServer.Memo1.Lines do begin Add('ID:' + Inttostr(mMyData.Id)); Add('Name:' + StrPas(mMyData.Name)); Add('Sex:' + mMyData.sex); Add('Age:' + Inttostr(mMyData.age)); Add('UpdateTime:' + DateTimeToStr(mMyData.UpdateTime)); end; end else begin FormServer.Memo1.Lines.Add(strMsg); end; end; // 元件內建的 thread ? procedure TFormServer.IdTCPServer1Execute(AContext: TIdContext); var ReadData: TMyData; buf: TIdBytes; sCmd: Char; sList: TStrings; I, ListCount: Integer; size: Integer; str: String; WasSplit: Boolean; begin // 字 Z 當指令的分割字元 // str := AContext.Connection.IOHandler.ReadLnSplit(WasSplit, 'Z', 5000, -1, // IndyTextEncoding_ASCII); // if not str.IsEmpty then // Memo1.Lines.Add(str); // 直接讀一行 (自動用換行字元區隔) // Memo1.Lines.Add(AContext.Connection.IOHandler.ReadLn(IndyTextEncoding_UTF8)); // 依各別的指令(第一個char),解析不同的資料 sCmd := AContext.Connection.IOHandler.ReadChar; // Tony Test // sCmd := #12; if sCmd = MY_CMD_STRUCT then // 接收結構體 begin AContext.Connection.IOHandler.ReadBytes(buf, SizeOf(ReadData)); BytesToRaw(buf, ReadData, SizeOf(ReadData)); // 因為 FMX 並非 Thread safe,所以要用 TIdNotify.Notify; with TMyIdNotify.Create do begin mMyData := ReadData; isMyData := True; Notify; end; end else if sCmd = MY_CMD_TSTRING then // 接收 TStrings begin ListCount := AContext.Connection.IOHandler.ReadLongInt; sList := TStringList.Create; try AContext.Connection.IOHandler.ReadStrings(sList, ListCount, IndyTextEncoding_UTF8); for I := 0 to sList.Count - 1 do begin // 因為 FMX 並非 Thread safe,所以要用 TIdNotify.Notify; with TMyIdNotify.Create do begin strMsg := sList.Strings[I]; isMyData := False; Notify; end; end; finally sList.Free; end; end else if sCmd = MY_CMD_UTF8 then // 接收 UFT8字串 begin with TMyIdNotify.Create do begin strMsg := AContext.Connection.IOHandler.ReadLn(IndyTextEncoding_UTF8); isMyData := False; Notify; end;; // echo AContext.Connection.IOHandler.WriteLn('收到UTF8 : ', IndyTextEncoding_UTF8); end else begin // 其它的就當作 ASCII 的文字 with TMyIdNotify.Create do begin strMsg := sCmd + AContext.Connection.IOHandler.ReadLn (IndyTextEncoding_ASCII); isMyData := False; Notify; end;; end; AContext.Connection.IOHandler.InputBuffer.Clear; // 清除不能識別的命令 end; procedure TFormServer.IdTCPServer1ListenException(AThread: TIdListenerThread; AException: Exception); begin Memo1.Lines.Add('S-ListenException: ' + AException.Message); end; procedure TFormServer.IdTCPServer1Status(ASender: TObject; const AStatus: TIdStatus; const AStatusText: string); begin Memo1.Lines.Add(DateTimeToStr(Now)); Memo1.Lines.Add('S-Status: ' + AStatusText); end; procedure TFormServer.StopServer; var Index: Integer; Context: TIdContext; begin if IdTCPServer1.Active then begin IdTCPServer1.OnDisconnect := nil; ListBoxClient.Clear; with IdTCPServer1.Contexts.LockList do begin if Count > 0 then begin try for index := 0 to Count - 1 do begin Context := Items[index]; if Context = nil then continue; Context.Connection.IOHandler.WriteBufferClear; Context.Connection.IOHandler.InputBuffer.Clear; Context.Connection.IOHandler.Close; if Context.Connection.Connected then Context.Connection.Disconnect; end; finally IdTCPServer1.Contexts.UnlockList; end; end; end; try IdTCPServer1.Active := False; Memo1.Lines.Add('IdTCPServer1.Active := False'); except on E: EIdException do Memo1.Lines.Add('== EIdException: ' + E.Message); end; end; IdTCPServer1.OnDisconnect := IdTCPServer1Disconnect; end; end.
{$mode TP} {$codepage UTF-8} {$R+,B+,X-} program T_16_44(input, output); uses heaptrc; type TE = integer; list = ^node; node = record elem: TE; next: list end; stack = list; procedure ClearStack(var S: stack); begin S := nil; end; function EmptyStack(S: stack): boolean; begin EmptyStack := S = nil; end; procedure Push(var S: stack; X: TE); var p: list; begin new(p); p^.elem := X; p^.next := S; S := p; end; procedure Pop(var S: stack; var X: TE); var p: list; begin X := S^.elem; p := S; S := S^.next; dispose(p); end; procedure Destroy(var L : list); begin if L^.next <> nil then Destroy(L^.next); dispose(L); end; procedure main; var S: stack; i, j: integer; c: char; begin read(c); ClearStack(S); i := 1; while c <> '.' do begin if c = '(' then Push(S, i); if (c = ')') and not EmptyStack(S) then begin Pop(s, j); write(j, '~', i, ' ') end; i := i + 1; read(c) end; writeln end; begin writeln('Zyanchurin Igor, 110 group, 17-5b'); main end. // A+(45-F(X)*(B-C)). // 8~10 12~16 3~17 // (x-(((x+2)+3)-23-3*(34+2)+2)-a). // 6~10 5~13 20~25 4~28 1~31 // ()()()()(). // 1~2 3~4 5~6 7~8 9~10
unit Unit2; interface uses StdCtrls; type TStr = string; Sel = ^Tsel; Tsel = record Str: TStr; A: Sel; end; TTask = class sp: Sel; constructor Create; procedure Adds(Str: TStr); function GenerateStr(): string; procedure Generate(); procedure Print(ListBox: TListBox); procedure PrintLast(ListBox: TListBox); procedure Task(n: integer); end; implementation constructor TTask.Create; begin inherited Create; sp:= Nil; end; procedure TTask.Adds(Str: TStr); var tmp: Sel; begin New(tmp); tmp^.Str:= Str; tmp^.A:= sp; sp:= tmp; end; function TTask.GenerateStr(): string; var i: word; Str: string; begin Str:= ''; for i:= 1 to 5 do Str:= Str + chr(Random(ord('z')-ord('a')+1)+ord('a')); Result:= Str; end; procedure TTask.Print(ListBox: TListBox); var tmp: Sel; begin ListBox.Clear; tmp:= sp; while tmp <> Nil do begin ListBox.Items.Add(tmp^.Str); tmp:= tmp^.A; end; end; procedure TTask.PrintLast(ListBox: TListBox); var tmp: Sel; begin ListBox.Clear; tmp:= sp; Listbox.Items.Add(tmp^.Str); end; procedure TTask.Generate(); var index: integer; begin sp:= Nil; for index:= 1 to 10 do Adds(GenerateStr); end; procedure TTask.Task(n: integer); var tmp,tmp2: Sel; i: word; begin tmp:= sp; while tmp^.A <> Nil do tmp:= tmp^.A; tmp^.A:= sp; tmp:= sp; while tmp^.A <> tmp do begin for i:= 1 to n-1 do tmp:= tmp^.A; tmp2:= tmp^.A; tmp^.A:= tmp^.A^.A; Dispose(tmp2); end; sp:= tmp; end; end.
{ *************************************************************************** * * * Lazarus DBF Designer * * * * Copyright (C) 2012 Vadim Vitomsky * * * * This source is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This code 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. * * * * A copy of the GNU General Public License is available on the World * * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * * obtain it by writing to the Free Software Foundation, * * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * ***************************************************************************} program dbdesigner; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Forms, Interfaces { add your units here }, umain, useltype, ustruct, uftype, uabout, uindex, translations, urstrrings, sysutils, LCLProc, LazUTF8; {$IFDEF MSWINDOWS} {$R *.res} {$ENDIF} function GetAppName : String; begin Result := 'dbfdesigner'; end; procedure TranslateLCL; var poDidectory, lang, fallbacklang : String; begin poDidectory:=ExtractFilePath(GetAppName)+'languages'; lang:=''; fallbacklang:=''; LazGetLanguageIDs(lang,fallbacklang); translations.TranslateUnitResourceStrings('urstrrings',poDidectory+'dbfdesigner.%.po',lang,fallbacklang); end; begin OnGetApplicationName:=@GetAppName; Application.Initialize; Application.Title:=''; Application.CreateForm(TFormMain, FormMain); Application.CreateForm(TFormSelectDbType, FormSelectDbType); Application.CreateForm(TFormDBSructureDesigner, FormDBSructureDesigner); Application.CreateForm(TFormFT, FormFT); Application.CreateForm(TAboutForm, AboutForm); Application.CreateForm(TIndexForm, IndexForm); Application.Run; end.
//////////////////////////////////////////////// // // GraphUtils.PAS // // Simple unit to // - Load and decode 24bpp PCX files // - Handle "Sprites" (Very basic functions) // // This unit can handle 2 type of sprites: // Non-Transparent and Transparent ones. // // Non-Transparent sprites: // - They have the size XSize and YSize. // - Their picture is taken from // Base_Image+Pic_Num*XSize. // - The Base_Image has the width of // Base_Image_XSize. // - They will be drawn on Dest_Image, which // has Dest_Image_XSize width, at XPos;YPos. // - If the RGB in the sprite data equals to // TRANSPARENT_RGB, the pixel will not be // drawn. // // Transparent Sprites: // - The same as Non-Transparent sprites, // but they can be half-visible or so. // - The Transparency data is taken from // Transp_Base_Image+Pic_Num*XSize. Here there // is another "picture" for the sprite, where // the RGB values are interpreted the following // way: // Take the R value, maximize it in 16. // 16 = Fully show the sprite // ... // 8 = Half visible sprite, half visible background // ... // 0 = Sprite is not visible // //////////////////////////////////////////////// Unit GraphUtils; interface Const TRANSPARENT_RGB=$000000; // Set which RGB means transparency for // sprites! Type Sprite_Data=record //------ When creating sprite, fill the following ones: ------- XSize,YSize:word; // Sprite size Base_Image:pointer; // Where to take sprite datas from Base_Image_XSize:word;// Width of base image (pixel) Dest_Image:pointer; // Where to draw sprites to Dest_Image_XSize:word;// Width of destination (pixel) XPos,YPos:longint; // Sprite position coordinates (in buffer, // not on screen!!) Pic_Num:byte; // Sprite picture number (0-based) Transparent:byte; // 0 = Non transparent, 1=transparent Transp_Base_Image:pointer; // Where to take transparency datas from (same size as Base Image) Enabled:boolean; // Draw or not? //------ Never touch these: ------------------------------------ Background:pointer; // The background of sprite is stored here Used:Boolean; // Is this slot used? end; const MAX_NUM_OF_SPRITES = 64; var Sprites:array [1..MAX_NUM_OF_SPRITES] of Sprite_Data; //Sprite datas // For more information about these functions, check the // implementation part! function Load24bitsPCX( filename:string; var img:pointer): boolean; procedure CopyImage(src,dest:pointer; SrcSize:longint); // Sprite handling routines function Create_Sprite(var handle:byte; sdata:Sprite_Data):boolean; procedure Delete_Sprite(handle:byte); procedure Draw_Sprites; procedure Remove_Sprites; procedure Draw_Sprite(handle:byte); procedure Remove_Sprite(handle:byte); implementation uses use32; var GraphUtils_OldExitProc:pointer; // - - - Load24bitsPCX - - - - - - - - - - - - - - - - - - - - - - - - - - // Function to load 24 bits per pixel PCX images. // Loads the file Filename, uncompresses the image into Img (also allocates // the needed memory, don't forget to freemem it when not needed anymore!), // and sets Width and Height to the dimensions of the loaded image. // function Load24bitsPCX( filename:string; var img:pointer): boolean; type PCXHeaderType=packed record Manufacturer:byte; Version:byte; Encoding:byte; BitsPerPixel:byte; Window:array[1..4] of smallint; HDpi:smallint; VDpi:smallint; Colormap:array[1..3*16] of byte; Reserved:byte; NPlanes:byte; BytesPerLine:smallint; PaletteInfo:smallint; HscreenSize:smallint; VscreenSize:smallint; Filler:array[1..54] of byte; end; var f:file; Header:PCXHeaderType; linesize:longint; count:longint; linebuf,imgypos:pointer; dst:^byte; y:longint; b1,b2:byte; Width,Height:word; filedata:pchar; VirtFilePos:longint; begin result:=false; // Default result is unsuccess // 1st step: Read file into memory assign(f,filename); {$I-} reset(f,1); {$I+} if ioresult<>0 then exit; // Could not open file, exit! getmem(filedata,filesize(f)); // Allocate memory for file if filedata=nil then begin // Exit cleanly if not enough memory close(f); exit; end; blockread(f,filedata^,filesize(f)); // Read all file into memory close(f); // Close file. VirtFilePos:=0; // 2nd step: "Read" PCX header move(filedata[VirtFilePos],Header,sizeof(Header)); inc(VirtFilePos,sizeof(Header)); Width:=Header.Window[3]-Header.Window[1]+1; Height:=Header.Window[4]-Header.Window[2]+1; LineSize:=Header.NPlanes*Header.BytesPerLine; // Get memory for image data (RGB) GetMem(img,Width*Height*3); imgypos:=img; GetMem(linebuf,linesize+4); // 3rd step: Decode PCX planes y:=0; while (y<Height) do // For every line begin dst:=linebuf; // Decode a line into LineBuf count:=0; repeat b1:=byte(filedata[virtfilepos]);inc(virtfilepos); // Get one byte if (b1 and $C0=$C0) then // Is it a lot of bytes? begin b1:=b1 and $3F; // Yes, get number of bytes b2:=byte(filedata[virtfilepos]);inc(virtfilepos); // and the color fillchar(dst^,b1,b2); // Create that much values inc(dst,b1); // Move... inc(count,b1); // ...forward end else begin // It's just one color value! dst^:=b1; // Store... inc(dst); // and move... inc(count); // forward end; until (count>=linesize); // Decode until we decoded one full line // Now we have one line decoded in linebuf, let's store it in image! // Linebuf has the values this way: // RRRRRRRRRRR...RRRRGGGGGGGGG...GGGGBBBB...BBBBBBBBBBBB // We have to make this: // RGBRGBRGBRGBRGBRGB... asm mov esi,linebuf mov edi,imgypos mov ecx,Width @loop: mov ebx,Width mov al,[esi] // Get Red stosb // Store mov al,[esi+ebx] // Get Green stosb // Store mov al,[esi+ebx*2] // Get Blue stosb // Store inc esi dec ecx // Go to next pixel... jnz @loop end; inc(y); inc(longint(imgypos),linesize); end; freemem(linebuf); freemem(filedata); Load24bitsPCX:=true; end; // - - - CopyImage - - - - - - - - - - - - - - - - - - - - - - - - - - - - // This procedure copies Src to Dst, with size SrcSize // The size should be a multiple of 4. // procedure CopyImage(src,dest:pointer; SrcSize:longint);assembler; asm push esi push edi push ecx clc mov edi,dest // Set destination mov esi,src // Set source mov ecx,SrcSize shr ecx,2 // Get number of dwords to copy jz @DontCopy // Don't copy if it's zero repnz movsd // Copy @DontCopy: pop ecx pop edi pop esi end; // - - - Remove_Sprite - - - - - - - - - - - - - - - - - - - - - - - - - - // The procedure removes one sprite from the buffer // procedure Remove_Sprite(handle:byte); var srcPtr,dstPtr:pointer; sXSize,sYSize:word; dXSize,AddToGoDown:word; Dest_Limit:longint; begin if (Handle<1) or (Handle>Max_Num_Of_Sprites) then exit; if (Sprites[Handle].Used=false) or (Sprites[Handle].Enabled=false) then exit; // Copy stored background to the destination buffer! srcPtr:=Sprites[Handle].Background; sXSize:=Sprites[Handle].XSize*3; sYSize:=Sprites[Handle].YSize; dstPtr:=Sprites[Handle].Dest_Image; Dest_Limit:=longint(Sprites[Handle].Dest_Image)+640*480*3-4; dXSize:=Sprites[Handle].Dest_Image_XSize*3; dstPtr:=pointer(longint(dstPtr)+Sprites[Handle].XPos*3+ Sprites[Handle].YPos*dXSize); AddToGoDown:=dXSize-sXSize; asm push esi push edi push ebx push ecx cld mov esi,srcPtr mov edi,dstPtr mov ebx,sYSize @Copy_OneLine: cmp edi,Dest_Limit ja @EndOfLoop mov ecx,sXSize repnz movsb add edi,AddToGoDown dec ebx jnz @Copy_OneLine @EndOfLoop: pop ecx pop ebx pop edi pop esi end; end; // - - - Remove_Sprites - - - - - - - - - - - - - - - - - - - - - - - - - - // The procedure removes all sprites from the buffer // procedure Remove_Sprites; var b:byte; begin for b:=MAX_Num_Of_Sprites downto 1 do if Sprites[b].Used then Remove_Sprite(b); end; // - - - Draw_Sprite - - - - - - - - - - - - - - - - - - - - - - - - - - - // The procedure draws one sprite to the buffer // procedure Draw_Sprite(handle:byte); var srcPtr,dstPtr:pointer; transpptr:pointer; sXSize,sYSize,AddToGoDown:word; dXSize,dYSize:word; AddDestToGoDown,AddSourToGoDown:word; dest_limit:longint; begin if (Handle<1) or (Handle>Max_Num_Of_Sprites) then exit; if (Sprites[Handle].Used=false) or (Sprites[Handle].Enabled=false) then exit; // Store background of sprite! dstPtr:=Sprites[Handle].Background; dXSize:=Sprites[Handle].XSize*3; dYSize:=Sprites[Handle].YSize; sXSize:=Sprites[Handle].Dest_Image_XSize*3; srcPtr:=Sprites[Handle].Dest_Image; Dest_Limit:=longint(Sprites[Handle].Dest_Image)+640*480*3-4; srcPtr:=pointer(longint(srcPtr)+Sprites[Handle].XPos*3+ Sprites[Handle].YPos*sXSize); AddToGoDown:=sXSize-dXSize; asm push esi push edi push ebx push ecx cld mov esi,srcPtr mov edi,dstPtr mov ebx,dYSize @Copy_OneLine2: cmp esi,Dest_Limit ja @EndOfCopy mov ecx,dXSize repnz movsb add esi,AddToGoDown dec ebx jnz @Copy_OneLine2 @EndOfCopy: pop ecx pop ebx pop edi pop esi end; // Now draw sprite transpptr:=pointer(longint(Sprites[Handle].Transp_Base_Image)+ Sprites[Handle].Pic_Num*Sprites[Handle].XSize*3); srcPtr:=pointer(longint(Sprites[Handle].Base_Image)+ Sprites[Handle].Pic_Num*Sprites[Handle].XSize*3); sXSize:=Sprites[Handle].XSize; sYSize:=Sprites[Handle].YSize; dXSize:=Sprites[Handle].Dest_Image_XSize; dstPtr:=Sprites[Handle].Dest_Image; dstPtr:=pointer(longint(dstPtr)+Sprites[Handle].XPos*3+ Sprites[Handle].YPos*dXSize*3); AddDestToGoDown:=(dXSize-sXSize)*3; AddSourToGoDown:=(Sprites[Handle].Base_Image_XSize-sXSize)*3; if Sprites[Handle].Transparent=0 then asm // Draw non-transparent sprites push esi push edi push eax push ebx push ecx cld mov esi,srcPtr mov edi,dstPtr mov ebx,sYSize @Copy_OneLine3: mov ecx,sXSize @More_In_The_Line: cmp edi,Dest_Limit ja @Exit_From_Loop xor eax,eax lodsb shl eax,8 lodsb shl eax,8 lodsb cmp eax,TRANSPARENT_RGB je @Dont_Write mov [edi+2],al mov [edi+1],ah shr eax,16 mov [edi],al @Dont_Write: add edi,3 dec ecx jnz @More_In_The_Line add edi,AddDestToGoDown add esi,AddSourToGoDown dec ebx jnz @Copy_OneLine3 @Exit_From_Loop: pop ecx pop ebx pop eax pop edi pop esi end else asm // Draw transparent sprites push esi push edi push eax push ebx push ecx push edx cld mov esi,srcPtr mov edi,dstPtr mov ebx,sYSize mov edx,TranspPtr @Copy_OneLine3_2: mov ecx,sXSize @More_In_The_Line_2: cmp edi,Dest_Limit ja @Exit_From_Loop_2 push ecx push ebx mov bl,[edx] // BL = Transparency of source shr bl,1 // Sorry, I've fucked up the drawing in PCX, // and it was easier to fix here than to redraw // it. Remove this 'shr bl,1' if you want to get // the results mentioned in header docs. // (This way transparency is from 0 to 32...) cmp bl,16 jbe @BL_OK mov bl,16 @BL_OK: mov bh,16 sub bh,bl // BH = Transparency of background xor eax,eax lodsb // Get source Red mul bl mov cx,ax // Multiply it into CX xor eax,eax mov al,[edi] // Get background Red mul bh add cx,ax // Multiply, and add to CX shr cx,4 // Divide cx by 16 mov [edi],cl // Write the result Red xor eax,eax lodsb // Get source Green mul bl mov cx,ax // Multiply it into CX xor eax,eax mov al,[edi+1] // Get background Green mul bh add cx,ax // Multiply, and add to CX shr cx,4 // Divide cx by 16 mov [edi+1],cl // Write the result Green xor eax,eax lodsb // Get source Blue mul bl mov cx,ax // Multiply it into CX xor eax,eax mov al,[edi+2] // Get background Blue mul bh add cx,ax // Multiply, and add to CX shr cx,4 // Divide cx by 16 mov [edi+2],cl // Write the result Blue add edi,3 add edx,3 pop ebx pop ecx dec ecx jnz @More_In_The_Line_2 add edi,AddDestToGoDown add edx,AddDestToGoDown add esi,AddSourToGoDown dec ebx jnz @Copy_OneLine3_2 @Exit_From_Loop_2: pop edx pop ecx pop ebx pop eax pop edi pop esi end; end; // - - - Draw_Sprites - - - - - - - - - - - - - - - - - - - - - - - - - - - // The procedure draws all sprites to the buffer // procedure Draw_Sprites; var b:byte; begin for b:=1 to MAX_Num_Of_Sprites do if Sprites[b].Used then Draw_Sprite(b); end; // - - - Create_Sprite - - - - - - - - - - - - - - - - - - - - - - - - - - // The function creates a sprite, returns true if successful. // function Create_Sprite(var handle:byte; sdata:Sprite_Data):boolean; var b:byte; begin b:=1; // Find an unused sprite while (b<=MAX_NUM_OF_SPRITES) and (Sprites[b].used) do inc(b); if (b>MAX_Num_Of_Sprites) then begin result:=false; exit; end; Sprites[b]:=sdata; with Sprites[b] do begin Used:=true; getmem(Background,XSize*YSize*3); if Background=NIL then begin result:=false; Used:=false; exit; end; end; Handle:=b; result:=true; end; // - - - Delete_Sprite - - - - - - - - - - - - - - - - - - - - - - - - - - // The procedure deletes a sprite // procedure Delete_Sprite(handle:byte); begin if (Handle<1) or (Handle>Max_Num_Of_Sprites) then exit; if Sprites[Handle].Background<>Nil then begin freemem(Sprites[Handle].Background); Sprites[Handle].Background:=Nil; end; Sprites[Handle].Used:=false; end; //- - - - - Internal routines... - - - - - - - - - - - - - - - - Procedure Init_Sprites; var b:byte; begin for b:=1 to MAX_NUM_OF_SPRITES do with Sprites[b] do begin Used:=false; Background:=Nil; end; end; procedure GraphUtils_NewExitProc; var b:byte; begin exitproc:=GraphUtils_OldExitProc; for b:=1 to MAX_NUM_OF_SPRITES do Delete_Sprite(b); end; begin GraphUtils_OldExitProc:=exitproc; exitproc:=@GraphUtils_NewExitProc; Init_Sprites; end.
unit RRManagerQuickViewFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, RRManagerObjects, RRManagerBaseObjects, ComCtrls, RRManagerBaseGUI, BaseObjects; type // TfrmQuickView = class(TFrame) TfrmQuickView = class(TFrame, IConcreteVisitor) lwProperties: TListView; procedure lwPropertiesInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); procedure lwPropertiesAdvancedCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); procedure lwPropertiesResize(Sender: TObject); private { Private declarations } FActiveObject: TBaseObject; FFakeObject: TObject; protected function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function GetActiveObject: TIDObject; procedure SetActiveObject(const Value: TIDObject); public { Public declarations } procedure VisitWell(AWell: TIDObject); procedure VisitTestInterval(ATestInterval: TIDObject); procedure VisitLicenseZone(ALicenseZone: TIDObject); procedure VisitSlotting(ASlotting: TIDObject); property ActiveObject: TBaseObject read FActiveObject write FActiveObject; procedure VisitVersion(AVersion: TOldVersion); procedure VisitStructure(AStructure: TOldStructure); procedure VisitDiscoveredStructure(ADiscoveredStructure: TOldDiscoveredStructure); procedure VisitPreparedStructure(APreparedStructure: TOldPreparedStructure); procedure VisitDrilledStructure(ADrilledStructure: TOldDrilledStructure); procedure VisitField(AField: TOldField); procedure VisitHorizon(AHorizon: TOldHorizon); procedure VisitSubstructure(ASubstructure: TOldSubstructure); procedure VisitLayer(ALayer: TOldLayer); procedure VisitBed(ABed: TOldBed); procedure VisitAccountVersion(AAccountVersion: TOldAccountVersion); procedure VisitStructureHistoryElement(AHistoryElement: TOldStructureHistoryElement); procedure VisitOldLicenseZone(ALicenseZone: TOldLicenseZone); procedure VisitCollectionWell(AWell: TIDObject); procedure VisitCollectionSample(ACollectionSample: TIDObject); procedure VisitDenudation(ADenudation: TIDObject); procedure VisitWellCandidate(AWellCandidate: TIDObject); procedure Clear; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses RRManagerLoaderCommands, BaseConsts, LicenseZone; {$R *.DFM} type TFakeObject = class end; { TfrmQuickView } procedure TfrmQuickView.VisitBed(ABed: TOldBed); var li: TListItem; actn: TBaseAction; i, j: integer; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.FixVisualization then begin if Assigned(ABed.Substructure) then VisitSubstructure(ABed.Substructure) else VisitStructure(ABed.Structure); li := lwProperties.Items.Add; li.Caption := 'Залежь'; li.Data := FFakeObject; end; li := lwProperties.Items.Add; li.Caption := 'Идентификатор залежи (BedUIN)'; li := lwProperties.Items.Add; li.Caption := IntToStr(ABed.ID); li.Data := ABed; if trim(ABed.BedIndex) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Индекс залежи'; li := lwProperties.Items.Add; li.Caption := ABed.BedIndex; li.Data := ABed; end; if Trim(ABed.Name) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Примечание'; li := lwProperties.Items.Add; li.Caption := ABed.Name; li.Data := ABed; end; if trim(ABed.BedType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип залежи'; li := lwProperties.Items.Add; li.Caption := ABed.BedType; li.Data := ABed; end; if trim(ABed.FluidType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип флюида'; li := lwProperties.Items.Add; li.Caption := ABed.FluidType; li.Data := ABed; end; if trim(ABed.ComplexName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Комплекс'; li := lwProperties.Items.Add; li.Caption := ABed.ComplexName; li.Data := ABed; end; if trim(ABed.CollectorType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип коллектора'; li := lwProperties.Items.Add; li.Caption := ABed.CollectorType; li.Data := ABed; end; if trim(ABed.Age) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Возраст залежи'; li := lwProperties.Items.Add; li.Caption := ABed.Age; li.Data := ABed; end; li := lwProperties.Items.Add; li.Caption := 'Глубина кровли'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ABed.Depth])); li.Data := ABed; actn := TVersionBaseLoadAction.Create(Self); actn.LastCollection := ABed.Versions; actn.LastCollection.NeedsUpdate := true; actn.Execute(ABed); actn.Free; actn := TReserveByVersionBaseLoadAction.Create(Self); for i := 0 to ABed.Versions.Count - 1 do begin actn.LastCollection := ABed.Versions.Items[i].Reserves; actn.LastCollection.NeedsUpdate := true; actn.Execute(ABed.Versions.Items[i]); if ABed.Versions.Items[i].Reserves.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Запасы - ' + ABed.Versions.Items[i].List(loBrief, False, False); li.Data := FFakeObject; for j := 0 to ABed.Versions.Items[i].Reserves.Count - 1 do if ABed.Versions.Items[i].Reserves.Items[j].ReserveValueTypeID = RESERVES_RESERVE_VALUE_TYPE_ID then begin li := lwProperties.Items.Add; with ABed.Versions.Items[i].Reserves.Items[j] do li.Caption := FluidType + '-' + ReserveCategory + '(' + ReserveType + ';' + ReserveKind + ')'; li := lwProperties.Items.Add; li.Caption := Format('%.3f', [ABed.Versions.Items[i].Reserves.Items[j].Value]); li.Data := ABed; end; // те, которые подсчитываются ABed.Versions.Items[i].Reserves.CalculateReserves; for j := 0 to ABed.Versions.Items[i].Reserves.CalculatedReserves.Count - 1 do if ABed.Versions.Items[i].Reserves.CalculatedReserves.Items[j].ReserveValueTypeID = RESERVES_RESERVE_VALUE_TYPE_ID then begin li := lwProperties.Items.Add; with ABed.Versions.Items[i].Reserves.CalculatedReserves.Items[j] do li.Caption := FluidType + '-' + ReserveCategory + '(' + ReserveType + ';' + ReserveKind + ')'; li := lwProperties.Items.Add; li.Caption := Format('%.3f', [ABed.Versions.Items[i].Reserves.CalculatedReserves.Items[j].Value]); li.Data := ABed; end; end; end; actn.Free; ActiveObject := ABed; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitDiscoveredStructure( ADiscoveredStructure: TOldDiscoveredStructure); var li: TListItem; begin lwProperties.Items.BeginUpdate; VisitStructure(ADiscoveredStructure); // типа пустая строка чтобы отделять элементы друг от друга li := lwProperties.Items.Add; li.Caption := 'Выявленная структура'; li.Data := FFakeObject; if AllOpts.Current.ListOption >= loBrief then begin if trim(ADiscoveredStructure.Year) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Год выявления'; li := lwProperties.Items.Add; li.Caption := ADiscoveredStructure.Year; li.Data := ADiscoveredStructure; end; end; if AllOpts.Current.ListOption >= loMedium then begin if trim(ADiscoveredStructure.Method) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Метод выявления'; li := lwProperties.Items.Add; li.Caption := ADiscoveredStructure.Method; li.Data := ADiscoveredStructure; end; end; if AllOpts.Current.ListOption = loFull then begin if trim(ADiscoveredStructure.ReportAuthor) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Автор отчёта'; li := lwProperties.Items.Add; li.Caption := ADiscoveredStructure.ReportAuthor; li.Data := ADiscoveredStructure; end; end; ActiveObject := ADiscoveredStructure; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitDrilledStructure( ADrilledStructure: TOldDrilledStructure); var li: TListItem; begin lwProperties.Items.BeginUpdate; VisitStructure(ADrilledStructure); li := lwProperties.Items.Add; li.Caption := 'Структура в бурении'; li.Data := FFakeObject; if AllOpts.Current.ListOption >= loBrief then begin li := lwProperties.Items.Add; li.Caption := 'Скважин'; li := lwProperties.Items.Add; li.Caption := IntToStr(ADrilledStructure.Wells.Count); li.Data := ADrilledStructure; end; ActiveObject := ADrilledStructure; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitField(AField: TOldField); var li: TListItem; i, j: integer; actn: TBaseAction; begin lwProperties.Items.BeginUpdate; VisitStructure(AField); li := lwProperties.Items.Add; li.Caption := 'Месторождение'; li.Data := FFakeObject; if trim(AField.FieldType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип месторождения'; li := lwProperties.Items.Add; li.Caption := AField.FieldType; li.Data := AField; end; if trim(AField.DevelopingDegree) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Степень освоения'; li := lwProperties.Items.Add; li.Caption := AField.DevelopingDegree; li.Data := AField; end; if AField.LicenseZones.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := '№ лицензии'; li := lwProperties.Items.Add; li.Caption := AField.LicenseZones.List; li.Data := AField; if Trim(AField.LicenseZones.OrganizationList) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Организация-недропользователь'; li := lwProperties.Items.Add; li.Caption := AField.LicenseZones.OrganizationList; li.Data := AField; end; end; actn := TVersionBaseLoadAction.Create(Self); actn.LastCollection := AField.Versions; actn.LastCollection.NeedsUpdate := true; actn.Execute(AField); actn.Free; actn := TFieldReserveByVersionBaseLoadAction.Create(Self); for i := 0 to AField.Versions.Count - 1 do begin actn.LastCollection := AField.Versions.Items[i].Reserves; actn.LastCollection.NeedsUpdate := true; actn.Execute(AField.Versions.Items[i]); if AField.Versions.Items[i].Reserves.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Запасы - ' + AField.Versions.Items[i].List(loBrief, False, False); li.Data := FFakeObject; for j := 0 to AField.Versions.Items[i].Reserves.Count - 1 do if AField.Versions.Items[i].Reserves.Items[j].ReserveValueTypeID = RESERVES_RESERVE_VALUE_TYPE_ID then begin li := lwProperties.Items.Add; with AField.Versions.Items[i].Reserves.Items[j] do li.Caption := FluidType + '-' + ReserveCategory + '(' + ReserveType + ';' + ReserveKind + ')'; li := lwProperties.Items.Add; li.Caption := Format('%.3f', [AField.Versions.Items[i].Reserves.Items[j].Value]); li.Data := AField; end; // те, которые подсчитываются AField.Versions.Items[i].Reserves.CalculateReserves; for j := 0 to AField.Versions.Items[i].Reserves.CalculatedReserves.Count - 1 do if AField.Versions.Items[i].Reserves.CalculatedReserves.Items[j].ReserveValueTypeID = RESERVES_RESERVE_VALUE_TYPE_ID then begin li := lwProperties.Items.Add; with AField.Versions.Items[i].Reserves.CalculatedReserves.Items[j] do li.Caption := FluidType + '-' + ReserveCategory + '(' + ReserveType + ';' + ReserveKind + ')'; li := lwProperties.Items.Add; li.Caption := Format('%.3f', [AField.Versions.Items[i].Reserves.CalculatedReserves.Items[j].Value]); li.Data := AField; end; end; end; actn.Free; ActiveObject := AField; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitHorizon(AHorizon: TOldHorizon); var li: TListItem; s: string; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.FixVisualization then begin VisitStructure(AHorizon.Structure); li := lwProperties.Items.Add; li.Caption := 'Горизонт'; li.Data := FFakeObject; end; if AllOpts.Current.ListOption >= loBrief then begin s := AHorizon.FirstStratum + '(' + AHorizon.FirstStratumPostfix + ')'; if AHorizon.SecondStratum <> '' then s := s + '-' + AHorizon.SecondStratum + AHorizon.SecondStratumPostfix; if trim(s) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Название'; li := lwProperties.Items.Add; li.Caption := s; li.Data := AHorizon; end; if trim(AHorizon.Complex) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Комплекс'; li := lwProperties.Items.Add; li.Caption := AHorizon.Complex; li.Data := AHorizon; end; li := lwProperties.Items.Add; li.Caption := 'Участвует в подсчётах'; li := lwProperties.Items.Add; if AHorizon.Active then li.Caption := 'да' else li.Caption := 'нет'; li.Data := AHorizon; end; if AllOpts.Current.ListOption >= loMedium then begin if trim(AHorizon.Organization) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Организация'; li := lwProperties.Items.Add; li.Caption := AHorizon.Organization; li.Data := AHorizon; end; end; if AllOpts.Current.ListOption = loFull then begin if trim(AHorizon.InvestigationYear) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Год исследования'; li := lwProperties.Items.Add; li.Caption := AHorizon.InvestigationYear; li.Data := AHorizon; end; if trim(AHorizon.Comment) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Описание'; li := lwProperties.Items.Add; li.Caption := AHorizon.Comment; li.Data := AHorizon; end; if AHorizon.FundTypes.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Виды фондов'; li := lwProperties.Items.Add; li.Caption := AHorizon.FundTypes.List(loBrief, false, false); li.Data := AHorizon; end; end; ActiveObject := AHorizon; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitLayer(ALayer: TOldLayer); var li: TListItem; i, j: integer; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.FixVisualization then begin if Assigned(ALayer.Bed) then VisitBed(ALayer.Bed) else if Assigned(ALayer.Substructure) then VisitSubstructure(ALayer.Substructure); li := lwProperties.Items.Add; li.Caption := 'Продуктивный пласт'; li.Data := FFakeObject; end; if AllOpts.Current.ListOption >= loBrief then begin if trim(ALayer.LayerIndex) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Индекс'; li := lwProperties.Items.Add; li.Caption := ALayer.LayerIndex; li.Data := ALayer; end; // тип коллеектора if trim(ALayer.CollectorType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип коллектора'; li := lwProperties.Items.Add; li.Caption := ALayer.CollectorType; li.Data := ALayer; end; if trim(ALayer.RockName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Литология коллектора'; li := lwProperties.Items.Add; li.Caption := ALayer.RockName; li.Data := ALayer; end; // тип ловушки if trim(ALayer.TrapType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип ловушки'; li := lwProperties.Items.Add; li.Caption := ALayer.TrapType; li.Data := ALayer; end; end; if AllOpts.Current.ListOption >= loMedium then begin li := lwProperties.Items.Add; li.Caption := 'Мощность'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.Power])); li.Data := ALayer; li := lwProperties.Items.Add; li.Caption := 'Эффективная мощность'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.EffectivePower])); li.Data := ALayer; li := lwProperties.Items.Add; li.Caption := 'Коэффициент заполнения'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.FillingCoef])); li.Data := ALayer; end; if AllOpts.Current.ListOption = loFull then begin li := lwProperties.Items.Add; li.Caption := 'Высота ловушки'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.TrapHeight])); li.Data := ALayer; li := lwProperties.Items.Add; li.Caption := 'Площадь ловушки'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.TrapArea])); li.Data := ALayer; li := lwProperties.Items.Add; li.Caption := 'Высота залежи'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.BedHeight])); li.Data := ALayer; li := lwProperties.Items.Add; li.Caption := 'Площадь залежи'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ALayer.BedArea])); li.Data := ALayer; end; if AllOpts.Current.ListOption >= loMedium then begin li := lwProperties.Items.Add; li.Caption := 'Ресурсы'; li.Data := FFakeObject; for i := 0 to ALayer.Versions.Count - 1 do with ALayer.Versions.Items[i] do begin for j := 0 to Resources.Count - 1 do begin li := lwProperties.Items.Add; li.Caption := Resources.Items[j].FluidType + ' ' + Resources.Items[j].ResourceCategory + '(' + Resources.Items[j].ResourceType + ')'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.4f', [Resources.Items[j].Value])); li.Data := Resources.Items[j]; end; end; end; ActiveObject := ALayer; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitPreparedStructure( APreparedStructure: TOldPreparedStructure); var li: TListItem; begin lwProperties.Items.BeginUpdate; VisitStructure(APreparedStructure); li := lwProperties.Items.Add; li.Caption := 'Подготовленная структура'; li.Data := FFakeObject; if AllOpts.Current.ListOption >= loBrief then begin if trim(APreparedStructure.Year) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Год подготовки'; li := lwProperties.Items.Add; li.Caption := APreparedStructure.Year; li.Data := APreparedStructure; end; end; if AllOpts.Current.ListOption >= loMedium then begin if trim(APreparedStructure.Method) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Метод подготовки'; li := lwProperties.Items.Add; li.Caption := APreparedStructure.Method; li.Data := APreparedStructure; end; end; if AllOpts.Current.ListOption = loFull then begin if trim(APreparedStructure.ReportAuthor) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Автор отчёта'; li := lwProperties.Items.Add; li.Caption := APreparedStructure.ReportAuthor; li.Data := APreparedStructure; end; end; ActiveObject := APreparedStructure; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitStructure(AStructure: TOldStructure); var li: TListItem; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.ListOption >= loBrief then begin if trim(AStructure.Name) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'ID'; li := lwProperties.Items.Add; li.Caption := IntToStr(AStructure.ID); li.Data := AStructure; end; if trim(AStructure.Name) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Название'; li := lwProperties.Items.Add; li.Caption := AStructure.Name; li.Data := AStructure; end; if trim(AStructure.StructureType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип'; li := lwProperties.Items.Add; li.Caption := AStructure.StructureType; li.Data := AStructure; end; end; if AllOpts.Current.ListOption >= loMedium then begin if trim(AStructure.Organization) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Организация'; li := lwProperties.Items.Add; li.Caption := AStructure.Organization; li.Data := AStructure; end; if trim(AStructure.OwnerOrganization) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Недропользователь'; li := lwProperties.Items.Add; li.Caption := AStructure.OwnerOrganization; li.Data := AStructure; end; if AStructure.PetrolRegions.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'НГР'; li := lwProperties.Items.Add; li.Caption := AStructure.PetrolRegions.List; li.Data := AStructure; end; if AStructure.Districts.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Регион'; li := lwProperties.Items.Add; li.Caption := AStructure.Districts.List; li.Data := AStructure; end; if AStructure.CartoHorizonID > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Горизонт нанесения на карту'; li := lwProperties.Items.Add; li.Caption := AStructure.CartoHorizon.List(AllOpts.Current.ListOption, false, false); li.Data := AStructure; end; end; if AllOpts.Current.ListOption = loFull then begin if AStructure.TectonicStructs.Count > 0 then begin li := lwProperties.Items.Add; li.Caption := 'Тектоническая структура'; li := lwProperties.Items.Add; li.Caption := AStructure.TectonicStructs.List; li.Data := AStructure; end; if trim(AStructure.Area) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Площадь'; li := lwProperties.Items.Add; li.Caption := AStructure.Area; li.Data := AStructure; end; end; ActiveObject := AStructure; lwProperties.Items.EndUpdate; end; procedure TfrmQuickView.VisitSubstructure(ASubstructure: TOldSubstructure); var li: TListItem; sName: string; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.FixVisualization then begin VisitHorizon(ASubstructure.Horizon); li := lwProperties.Items.Add; li.Caption := 'Подструктура'; li.Data := FFakeObject; end; if AllOpts.Current.ListOption >= loBrief then begin if trim(ASubstructure.StructureElementType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип'; li := lwProperties.Items.Add; li.Caption := ASubstructure.StructureElementType; li.Data := ASubstructure; end; // наименование if ASubstructure.RealName <> '' then sName := ASubstructure.RealName else sName := ASubstructure.StructureElement; if trim(sName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Имя'; li := lwProperties.Items.Add; li.Caption := sName; li.Data := ASubstructure; end; // литология if trim(ASubstructure.RockName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Литология коллектора'; li := lwProperties.Items.Add; li.Caption := ASubstructure.RockName; li.Data := ASubstructure; end; // тип коллектора if trim(ASubstructure.CollectorType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип коллектора'; li := lwProperties.Items.Add; li.Caption := ASubstructure.CollectorType; li.Data := ASubstructure; end; // тип залежи if trim(ASubstructure.BedType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип залежи'; li := lwProperties.Items.Add; li.Caption := ASubstructure.BedType; li.Data := ASubstructure; end; end; if AllOpts.Current.ListOption >= loMedium then begin // НГК if trim(ASubstructure.SubComplex) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Подкомплекс'; li := lwProperties.Items.Add; li.Caption := ASubstructure.SubComplex; li.Data := ASubstructure; end; // вероятность существования li := lwProperties.Items.Add; li.Caption := 'Вероятность существования'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.Probability])); li.Data := ASubstructure; // надежность li := lwProperties.Items.Add; li.Caption := 'Надежность'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.Reliability])); li.Data := ASubstructure; // оценка качества if trim(ASubstructure.QualityRange) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Оценка качества'; li := lwProperties.Items.Add; li.Caption := ASubstructure.QualityRange; li.Data := ASubstructure; end; end; if AllOpts.Current.ListOption = loFull then begin li := lwProperties.Items.Add; li.Caption := 'Изогипса'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.ClosingIsogypse])); li.Data := ASubstructure; // перспективная площадь li := lwProperties.Items.Add; li.Caption := 'Персп. площадь'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.PerspectiveArea])); li.Data := ASubstructure; //амплитуда li := lwProperties.Items.Add; li.Caption := 'Амплитуда'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.Amplitude])); li.Data := ASubstructure; li := lwProperties.Items.Add; li.Caption := 'Контр. плотность'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.ControlDensity])); li.Data := ASubstructure; li := lwProperties.Items.Add; li.Caption := 'Ст. ош. карты'; li := lwProperties.Items.Add; li.Caption := Trim(Format('%8.2f', [ASubstructure.MapError])); li.Data := ASubstructure; end; ActiveObject := ASubstructure; lwProperties.Items.EndUpdate; end; function TfrmQuickView._AddRef: Integer; begin Result := 0; end; function TfrmQuickView._Release: Integer; begin Result := 0; end; procedure TfrmQuickView.lwPropertiesInfoTip(Sender: TObject; Item: TListItem; var InfoTip: String); begin if Assigned(Item) then InfoTip := Item.Caption; end; procedure TfrmQuickView.lwPropertiesAdvancedCustomDrawItem( Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean); var r: TRect; begin r := Item.DisplayRect(drBounds); if Item.Index = lwProperties.Items.Count - 1 then begin lwProperties.Canvas.Pen.Color := $00ACB9AF; lwProperties.Canvas.MoveTo(r.Left, r.Bottom); lwProperties.Canvas.LineTo(r.Right, r.Bottom); lwProperties.Canvas.Brush.Color := $00FFFFFF;//$00F7F4E1;//$00F2EDDF;//$00DCF5D6;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB; lwProperties.Canvas.FillRect(r); lwProperties.Canvas.Font.Style := []; lwProperties.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption); end; if not Assigned(Item.Data) then begin DefaultDraw := false; lwProperties.Canvas.Brush.Color := $00EFEFEF;//$00F7F4E1;//$00F2EDDF;//$00DCF5D6;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB; lwProperties.Canvas.FillRect(r); lwProperties.Canvas.Font.Color := $00ACB9AF;//clGray; lwProperties.Canvas.Font.Style := [fsBold]; if (Item.Index < lwProperties.Items.Count - 1) and (TBaseObject(lwProperties.Items[Item.Index + 1].Data) = ActiveObject) then lwProperties.Canvas.Font.Color := lwProperties.Canvas.Font.Color + $00330000; lwProperties.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption); end else begin if (TObject(Item.Data) is TFakeObject) then begin DefaultDraw := false; lwProperties.Canvas.Brush.Color := $00E4EAD7;//$00FBFAF0;//$00DAFCDB;//$00EFFAEB; lwProperties.Canvas.FillRect(r); lwProperties.Canvas.Font.Color := $00ACB9AF;//clGray; lwProperties.Canvas.Font.Style := [fsBold]; if (Item.Index < lwProperties.Items.Count - 2) and (TBaseObject(lwProperties.Items[Item.Index + 2].Data) = ActiveObject) then lwProperties.Canvas.Font.Color := lwProperties.Canvas.Font.Color + $0000AA00; lwProperties.Canvas.TextOut(r.Left + r.Right - lwProperties.Canvas.TextWidth(Item.Caption), r.Top, Item.Caption); end { else if (TBaseObject(Item.Data) = ActiveObject) then begin lwProperties.Canvas.Font.Color := lwProperties.Canvas.Font.Color + $00770033; lwProperties.Canvas.FillRect(r); lwProperties.Canvas.TextOut(r.Left + 2, r.Top, Item.Caption); end;} end; end; procedure TfrmQuickView.Clear; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; lwProperties.Items.EndUpdate; end; constructor TfrmQuickView.Create(AOwner: TComponent); begin inherited; FFakeObject := TFakeObject.Create; end; destructor TfrmQuickView.Destroy; begin FFakeObject.Free; inherited; end; procedure TfrmQuickView.lwPropertiesResize(Sender: TObject); begin lwProperties.Columns[0].Width := lwProperties.Width - 3; end; procedure TfrmQuickView.VisitAccountVersion( AAccountVersion: TOldAccountVersion); begin end; procedure TfrmQuickView.VisitStructureHistoryElement( AHistoryElement: TOldStructureHistoryElement); begin end; procedure TfrmQuickView.VisitVersion(AVersion: TOldVersion); begin { TODO : добавить просмотр информации о версии } end; procedure TfrmQuickView.VisitOldLicenseZone(ALicenseZone: TOldLicenseZone); var li: TListItem; begin lwProperties.Items.BeginUpdate; lwProperties.Items.Clear; if AllOpts.Current.ListOption >= loBrief then begin li := lwProperties.Items.Add; li.Caption := 'ID'; li := lwProperties.Items.Add; li.Caption := IntToStr(ALicenseZone.ID); li.Data := ALicenseZone; if trim(ALicenseZone.LicenseZoneName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Название'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.LicenseZoneName; li.Data := ALicenseZone; end; if trim(ALicenseZone.LicenseZoneNum) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Номер участка'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.LicenseZoneNum; li.Data := ALicenseZone; end; if trim(ALicenseZone.License.LicenseType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Вид лицензии'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.License.LicenseTypeShortName + '(' + ALicenseZone.License.LicenseType + ')'; li.Data := ALicenseZone; end; if trim(ALicenseZone.LicenseZoneState) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Статус участка'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.LicenseZoneState; li.Data := ALicenseZone; end; if ALicenseZone.LicenseZoneStateID = 1 then begin li := lwProperties.Items.Add; li.Caption := 'Дата регистрации лицензии'; li := lwProperties.Items.Add; li.Caption := DateTimeToStr(ALicenseZone.RegistrationStartDate); li.Data := ALicenseZone; li := lwProperties.Items.Add; li.Caption := 'Дата окончания регистрации лицензии'; li := lwProperties.Items.Add; li.Caption := DateTimeToStr(ALicenseZone.RegistrationFinishDate); li.Data := ALicenseZone; end; end; if AllOpts.Current.ListOption >= loMedium then begin if trim(ALicenseZone.License.OwnerOrganizationName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Организация-владелец лицензии'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.License.OwnerOrganizationName; li.Data := ALicenseZone; end; if trim(ALicenseZone.License.DeveloperOrganizationName) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Организация-недропользователь'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.License.DeveloperOrganizationName; li.Data := ALicenseZone; end; if trim(ALicenseZone.License.LicenzeZoneType) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тип участка'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.License.LicenzeZoneType; li.Data := ALicenseZone; end; if trim(ALicenseZone.District) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Регион'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.District; li.Data := ALicenseZone; end; end; if AllOpts.Current.ListOption = loFull then begin if trim(ALicenseZone.TectonicStruct) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'Тектоническая структура'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.TectonicStruct; li.Data := ALicenseZone; end; if trim(ALicenseZone.PetrolRegion) <> '' then begin li := lwProperties.Items.Add; li.Caption := 'НГР'; li := lwProperties.Items.Add; li.Caption := ALicenseZone.PetrolRegion; li.Data := ALicenseZone; end; end; ActiveObject := ALicenseZone; lwProperties.Items.EndUpdate; end; function TfrmQuickView.GetActiveObject: TIDObject; begin Result := FActiveObject; end; procedure TfrmQuickView.SetActiveObject(const Value: TIDObject); begin FActiveObject := Value as TBaseObject; end; procedure TfrmQuickView.VisitSlotting(ASlotting: TIDObject); begin end; procedure TfrmQuickView.VisitTestInterval(ATestInterval: TIDObject); begin end; procedure TfrmQuickView.VisitWell(AWell: TIDObject); begin end; procedure TfrmQuickView.VisitLicenseZone(ALicenseZone: TIDObject); begin VisitOldLicenseZone(ALicenseZone as TOldLicenseZone); end; procedure TfrmQuickView.VisitCollectionSample( ACollectionSample: TIDObject); begin end; procedure TfrmQuickView.VisitCollectionWell(AWell: TIDObject); begin end; procedure TfrmQuickView.VisitDenudation(ADenudation: TIDObject); begin end; procedure TfrmQuickView.VisitWellCandidate(AWellCandidate: TIDObject); begin end; end.
unit MRInfoThemeFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, Buttons, StdCtrls, ExtCtrls, ComCtrls, Theme, BaseObjects; type TfrmInfoTheme = class(TfrmCommonFrame) grp1: TGroupBox; grp2: TGroupBox; mmName: TMemo; grp3: TGroupBox; grp4: TGroupBox; dtmPeriodBegin: TDateTimePicker; grp5: TGroupBox; dtmPeriodFinish: TDateTimePicker; pnl1: TPanel; edtNumber: TLabeledEdit; edtFolder: TLabeledEdit; grp6: TGroupBox; btnSetAuthors: TButton; edtAuthors: TEdit; btnClear: TBitBtn; procedure btnSetAuthorsClick(Sender: TObject); procedure btnClearClick(Sender: TObject); private function GetTheme: TTheme; { Private declarations } protected procedure FillControls(ABaseObject: TIDObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; function GetParentCollection: TIDObjects; override; public property Theme: TTheme read GetTheme; procedure Save(AObject: TIDObject = nil); override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmInfoTheme: TfrmInfoTheme; implementation uses MRInfoPerformer; {$R *.dfm} { TfrmCommonFrame1 } procedure TfrmInfoTheme.ClearControls; begin inherited; edtNumber.Clear; mmName.Clear; edtFolder.Clear; dtmPeriodBegin.Date := Date; dtmPeriodFinish.Date := Date; end; constructor TfrmInfoTheme.Create(AOwner: TComponent); begin inherited; end; destructor TfrmInfoTheme.Destroy; begin inherited; end; procedure TfrmInfoTheme.FillControls(ABaseObject: TIDObject); begin inherited; if Assigned (Theme) then with Theme do begin edtNumber.Text := trim(Number); edtFolder.Text := trim(Folder); mmName.Clear; mmName.Lines.Add(trim(Name)); if Assigned (Performer) then edtAuthors.Text := Performer.Name else edtAuthors.Text := '<не указан>'; if (trim(Number) <> '') then // пересмотреть условие begin dtmPeriodBegin.DateTime := ActualPeriodStart; dtmPeriodFinish.DateTime := ActualPeriodFinish; end else begin dtmPeriodBegin.DateTime := Date; dtmPeriodFinish.DateTime := Date; end; end; end; procedure TfrmInfoTheme.FillParentControls; begin inherited; end; function TfrmInfoTheme.GetParentCollection: TIDObjects; begin end; function TfrmInfoTheme.GetTheme: TTheme; begin end; procedure TfrmInfoTheme.RegisterInspector; begin inherited; end; procedure TfrmInfoTheme.Save(AObject: TIDObject = nil); begin inherited; with Theme do if dtmPeriodBegin.Date <= dtmPeriodFinish.Date then begin Name := trim(mmName.Lines.Text); Number := trim(edtNumber.Text); Folder := trim (edtFolder.Text); ActualPeriodStart := dtmPeriodBegin.Date; ActualPeriodFinish := dtmPeriodFinish.Date; Text := ''; end else MessageBox(0, 'Ошибка', 'Некорректно задан период актуальности темы.', MB_OK + MB_ICONERROR + MB_APPLMODAL); end; procedure TfrmInfoTheme.btnSetAuthorsClick(Sender: TObject); begin inherited; frmSetPerformer := TfrmSetPerformer.Create(Self); if frmSetPerformer.ShowModal = mrOK then begin //Theme.Performer := frmSetPerformer.frmAllEmployees.ActiveAuthor; edtAuthors.Text := Theme.Performer.Name; //GUIAdapter.ChangeMade := true; end; frmSetPerformer.Free; end; procedure TfrmInfoTheme.btnClearClick(Sender: TObject); begin inherited; //Performer := nil; edtAuthors.Text := '<не указан>'; end; end.
unit PushPullTestCase; interface uses TestFramework, Classes, Windows, ZmqIntf; const cBind = 'tcp://*:5555'; cConnect = 'tcp://127.0.0.1:5555'; type TPushPullTestCase = class(TTestCase) private context: IZMQContext; public procedure SetUp; override; procedure TearDown; override; published procedure SendString; procedure SendStringThread; procedure SendStringThreadFirstConnect; end; implementation uses Sysutils ; var ehandle: THandle; { TPushPullTestCase } procedure TPushPullTestCase.SetUp; begin inherited; context := ZMQ.CreateContext; end; procedure TPushPullTestCase.TearDown; begin inherited; context := nil; end; procedure TPushPullTestCase.SendString; var sPush,sPull: PZMQSocket; s: WideString; rc: Integer; begin sPush := context.Socket( stPush ); try sPush.bind( cBind ); sPull := context.Socket( stPull ); try sPull.connect( cConnect ); sPush.SendString( 'Hello' ); rc := sPull.RecvString( s ); CheckEquals( 5*ZMQ_CHAR_SIZE, rc, 'checking result' ); CheckEquals( 'Hello', s, 'checking value' ); finally sPull.Free; end; finally sPush.Free; end; end; procedure PushProc( lcontext: IZMQContext ); var sPush: PZMQSocket; begin WaitForSingleObject( ehandle, INFINITE ); sPush := lcontext.Socket( stPush ); try sPush.bind( cBind ); sPush.SendString( 'Hello' ); finally sPush.Free; end; end; procedure TPushPullTestCase.SendStringThread; var sPull: PZMQSocket; s: WideString; rc: Integer; tid: Cardinal; begin SetEvent( ehandle ); BeginThread( nil, 0, @pushProc, Pointer(context), 0, tid ); sPull := context.Socket( stPull ); try sPull.connect( cConnect ); rc := sPull.RecvString( s ); CheckEquals( 5*ZMQ_CHAR_SIZE, rc, 'checking result' ); CheckEquals( 'Hello', s, 'checking value' ); finally sPull.Free; end; end; // should work, because push blocks until a downstream node // become available. procedure TPushPullTestCase.SendStringThreadFirstConnect; var sPull: PZMQSocket; s: WideString; rc: Integer; tid: Cardinal; begin ResetEvent( ehandle ); BeginThread( nil, 0, @pushProc, Pointer(context), 0, tid ); sPull := context.Socket( stPull ); try sPull.connect( cConnect ); SetEvent( ehandle ); rc := sPull.RecvString( s ); CheckEquals( 5*ZMQ_CHAR_SIZE, rc, 'checking result' ); CheckEquals( 'Hello', s, 'checking value' ); finally sPull.Free; end; end; { try SetEvent( ehandle ); WaitForSingleObject( ehandle, INFINITE ); finally end; } initialization RegisterTest(TPushPullTestCase.Suite); ehandle := CreateEvent( nil, true, true, nil ); finalization CloseHandle( ehandle ); end.
{==============================================================================| | Project : Bauglir Internet Library | |==============================================================================| | Content: Generic connection and server | |==============================================================================| | Copyright (c)2011-2012, Bronislav Klucka | | All rights reserved. | | Source code is licenced under original 4-clause BSD licence: | | http://licence.bauglir.com/bsd4.php | | | | | |==============================================================================| | Requirements: Ararat Synapse (http://www.ararat.cz/synapse/) | |==============================================================================} unit CustomServer2; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$H+} interface uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes, SysUtils, blcksock, // Sockets, ssl_openssl, BClasses, syncobjs; type TCustomServer = class; TCustomConnection = class; {:abstract(Socket used for @link(TCustomConnection)) } TTCPCustomConnectionSocket = class(TTCPBlockSocket) protected fConnection : TCustomConnection; fCurrentStatusReason : THookSocketReason; fCurrentStatusValue : string; fOnSyncStatus : THookSocketStatus; procedure DoOnStatus(Sender: TObject; Reason: THookSocketReason; const Value: String); procedure SyncOnStatus; public constructor Create; destructor Destroy; override; {:Owner (@link(TCustomConnection))} property Connection: TCustomConnection read fConnection; {:Socket status event (synchronized to main thread)} property OnSyncStatus: THookSocketStatus read fOnSyncStatus write fOnSyncStatus; end; {:abstract(Basic connection thread) This object is used from server and client as working thread. When object is server connection: object is created automatically by @link(Parent) server. Thread can be terminated from outside. If server is terminated, all remaining connections are closed. This object is used to communicate with client. Object should not be created directly. } TCustomConnection = class(TBThread) private protected fIndex : integer; fParent : TCustomServer; fSocket : TTCPCustomConnectionSocket; fSSL : boolean; procedure AfterConnectionExecute; virtual; function BeforeExecuteConnection: boolean; virtual; procedure ExecuteConnection; virtual; function GetIsTerminated: boolean; public constructor Create(aSocket: TTCPCustomConnectionSocket); virtual; destructor Destroy; override; {:Thread execute method} procedure Execute; override; {:Thread resume method} procedure Start; {:Thread suspend method} procedure Stop; {:Temination procedure One should call this procedure to terminate thread, it internally calls Terminate, but can be overloaded, and can be used for clean um } procedure TerminateThread; virtual; {:@Connection index. Automatically generated. } property Index: integer read fIndex; {:@True if thread is not terminated and @link(Socket) exists} property IsTerminated: boolean read GetIsTerminated; {:@Connection parent If client connection, this property is always nil, if server connection, this property is @link(TCustomServer) that created this connection } property Parent: TCustomServer read fParent; {:@Connection socket} property Socket: TTCPCustomConnectionSocket read fSocket; {:Whether SSL is used} property SSL: boolean read fSSL write fSSL; end; { TCustomServerConnection TCustomServerConnection = class(TCustomConnection) protected fBroadcastData: TStringList; fBroadcastLock: TCriticalSection; fParent: TCustomServer; //procedure ExecuteConnection; override; procedure SyncConnectionRemove; public constructor Create(aSocket: TTCPCustomServerConnectionSocket; aParent: TCustomServer); reintroduce; virtual; destructor Destroy; override; procedure Execute; override; :Data setup by server's Broadcast method. Connection is responsible to send data the data itself. Connection must delete the data after sending. procedure Broadcast(aData: string); virtual; end; } {:abstract(Class of connections)} // TCustomServerConnections = class of TCustomConnection; {:Event procedural type to hook OnAfterAddConnection in server Use this hook to get informations about connection accepted server that was added } TServerAfterAddConnection = procedure (Server: TCustomServer; aConnection: TCustomConnection) of object; {:Event procedural type to hook OnBeforeAddConnection in server Use this hook to be informed that connection is about to be accepred by server. Use CanAdd parameter (@false) to refuse connection } TServerBeforeAddConnection = procedure (Server: TCustomServer; aConnection: TCustomConnection; var CanAdd: boolean) of object; {:Event procedural type to hook OnAfterRemoveConnection in server Use this hook to get informations about connection removed from server (connection is closed) } TServerAfterRemoveConnection = procedure (Server: TCustomServer; aConnection: TCustomConnection) of object; {:Event procedural type to hook OnAfterRemoveConnection in server Use this hook to get informations about connection removed from server (connection is closed) } TServerBeforeRemoveConnection = procedure (Server: TCustomServer; aConnection: TCustomConnection) of object; {:Event procedural type to hook OnSockedError in server Use this hook to get informations about error on server binding } TServerSocketError = procedure (Server: TCustomServer; Socket: TTCPBlockSocket) of object; {:abstract(Server listening on address and port and spawning @link(TCustomConnection)) Use this object to create server. Object is accepting connections and creating new server connection objects (@link(TCustomConnection)) } TCustomServer = class(TBThread) private protected fBind: string; fPort: string; fCanAddConnection: boolean; fConnections: TList; fConnectionTermLock: TCriticalSection; fCurrentAddConnection: TCustomConnection; fCurrentRemoveConnection: TCustomConnection; fCurrentSocket: TTCPBlockSocket; fIndex: integer; fMaxConnectionsCount: integer; fOnAfterAddConnection: TServerAfterAddConnection; fOnAfterRemoveConnection: TServerAfterRemoveConnection; fOnBeforeAddConnection: TServerBeforeAddConnection; fOnBeforeRemoveConnection: TServerBeforeRemoveConnection; fOnSocketErrot: TServerSocketError; fSSL: boolean; fSSLCertificateFile: string; fSSLKeyPassword: string; fSSLPrivateKeyFile: string; function AddConnection(var aSocket: TTCPCustomConnectionSocket): TCustomConnection; virtual; {:Main function to determine what kind of connection will be used @link(AddConnection) uses this functino to actually create connection thread } function CreateServerConnection(aSocket: TTCPCustomConnectionSocket): TCustomConnection; virtual; procedure DoAfterAddConnection; virtual; procedure DoBeforeAddConnection; procedure DoAfterRemoveConnection; procedure DoBeforeRemoveConnection; procedure DoSocketError; function GetConnection(index: integer): TCustomConnection; function GetConnectionByIndex(index: integer): TCustomConnection; function GetCount: integer; procedure OnConnectionTerminate(Sender: TObject); procedure RemoveConnection(aConnection: TCustomConnection); procedure SyncAfterAddConnection; procedure SyncBeforeAddConnection; procedure SyncAfterRemoveConnection; procedure SyncBeforeRemoveConnection; procedure SyncSocketError; public {:Create new server aBind represents local IP address server will be listening on. IP address may be numeric or symbolic ('192.168.74.50', 'cosi.nekde.cz', 'ff08::1'). You can use for listening 0.0.0.0 for localhost The same for aPort it may be number or mnemonic port ('23', 'telnet'). If port value is '0', system chooses itself and conects unused port in the range 1024 to 4096 (this depending by operating system!). Warning: when you call : Bind('0.0.0.0','0'); then is nothing done! In this case is used implicit system bind instead. } constructor Create(aBind: string; aPort: string); virtual; destructor Destroy; override; procedure Execute; override; {:Temination procedure This method should be called instead of Terminate to terminate thread, it internally calls Terminate, but can be overloaded, and can be used for data clean up } procedure TerminateThread; virtual; { :Method used co send the same data to all server connections. Method only stores data in connection (append to existing data). Connection must send and delete the data itself. } //procedure Broadcast(aData: string); virtual; {: Procedure to stop removing connections from connections list in case there is need to walk through it } procedure LockTermination; {:Thread resume method} procedure Start; {:Thread suspend method} procedure Stop; {:Procedure to resume removing connections. see LockTermination } procedure UnLockTermination; {:Get connection from connection list Index represent index within connection list (not Connection.Index property) } property Connection[index: integer]: TCustomConnection read GetConnection; default; {:Get connection by its Index} property ConnectionByIndex[index: integer]: TCustomConnection read GetConnectionByIndex; {:Valid connections count} property Count: integer read GetCount; {:IP address where server is listening (see aBind in constructor)} property Host: string read fBind; {:Server index. Automatically generated. } property Index: integer read fIndex; {:Maximum number of accepted connections. -1 (default value) represents unlimited number. If limit is reached and new client is trying to connection, it's refused } property MaxConnectionsCount: integer read fMaxConnectionsCount write fMaxConnectionsCount; {:Port where server is listening (see aPort in constructor)} property Port: string read fPort; {:Whether SSL is used} property SSL: boolean read fSSL write fSSL; {:SSL certification file} property SSLCertificateFile: string read fSSLCertificateFile write fSSLCertificateFile; {:SSL key file} property SSLKeyPassword: string read fSSLKeyPassword write fSSLKeyPassword; {:SSL key file} property SSLPrivateKeyFile: string read fSSLPrivateKeyFile write fSSLPrivateKeyFile; {:See @link(TServerAfterAddConnection)} property OnAfterAddConnection: TServerAfterAddConnection read fOnAfterAddConnection write fOnAfterAddConnection; {:See @link(TServerBeforeAddConnection)} property OnBeforeAddConnection: TServerBeforeAddConnection read fOnBeforeAddConnection write fOnBeforeAddConnection; {:See @link(TServerAfterRemoveConnection)} property OnAfterRemoveConnection: TServerAfterRemoveConnection read fOnAfterRemoveConnection write fOnAfterRemoveConnection; {:See @link(TServerBeforeRemoveConnection)} property OnBeforeRemoveConnection: TServerBeforeRemoveConnection read fOnBeforeRemoveConnection write fOnBeforeRemoveConnection; {:See @link(TServerSocketError)} property OnSocketError: TServerSocketError read fOnSocketErrot write fOnSocketErrot; end; implementation uses SynSock {$IFDEF WIN32}, Windows {$ENDIF WIN32}; var fConnectionsIndex: Integer = 0; function getConnectionIndex: integer; begin result := fConnectionsIndex; inc(fConnectionsIndex); end; { TCustomServerConnection procedure TCustomServerConnection.SyncConnectionRemove; begin fParent.OnConnectionTerminate(self); end; constructor TCustomServerConnection.Create(aSocket: TTCPCustomServerConnectionSocket; aParent: TCustomServer); begin fParent := aParent; fIndex := 0; fBroadcastLock := TCriticalSection.Create; fBroadcastData := TStringList.Create; inherited Create(aSocket); end; destructor TCustomServerConnection.Destroy; begin fBroadcastData.Free; fBroadcastLock.free; inherited Destroy; end; procedure TCustomServerConnection.Execute; begin try inherited Execute; if (not fParent.Terminated) then Synchronize(SyncConnectionRemove); //Synchronize(fParent, SyncConnectionRemove); finally end; end; procedure TCustomServerConnection.Broadcast(aData: string); begin if (not IsTerminated) then begin fBroadcastLock.Enter; fBroadcastData.Add(aData); fBroadcastLock.Leave; end; end; { procedure TCustomServerConnection.ExecuteConnection; var s: string; begin while(not IsTerminated) do begin s := fSocket.RecvString(-1); if (fSocket <> nil) then begin if (fSocket.LastError <> 0) then break; if (s <> '') then fSocket.SendString(s + #13#10); if (fSocket.LastError <> 0) then break; end; end; end; } { TCustomServer } procedure TCustomServer.OnConnectionTerminate(Sender: TObject); begin try //OutputDebugString(pChar(Format('srv terminating 1 %d', [TCustomConnection(Sender).Index]))); // fConnectionTermLock.Enter; //OutputDebugString(pChar(Format('srv terminating 2 %d', [TCustomConnection(Sender).Index]))); RemoveConnection(TCustomConnection(Sender)); //OutputDebugString(pChar(Format('srv terminating 3 %d', [TCustomConnection(Sender).Index]))); // fConnectionTermLock.Leave; finally end; //OutputDebugString(pChar(Format('srv terminating e %d', [TCustomConnection(Sender).Index]))); end; procedure TCustomServer.RemoveConnection(aConnection: TCustomConnection); var index: integer; begin index := fConnections.IndexOf(aConnection); if (index <> -1) then begin fCurrentRemoveConnection := aConnection; DoBeforeRemoveConnection; fConnectionTermLock.Enter; //OutputDebugString(pChar(Format('removing %d %d %d', [aConnection.fIndex, index, fConnections.Count]))); fConnections.Extract(aConnection); //fConnections.Delete(index); //OutputDebugString(pChar(Format('removed %d %d %d', [aConnection.fIndex, index, fConnections.Count]))); fConnectionTermLock.Leave; DoAfterRemoveConnection; end; end; procedure TCustomServer.DoAfterAddConnection; begin if (assigned(fOnAfterAddConnection)) then Synchronize(SyncAfterAddConnection); end; procedure TCustomServer.DoBeforeAddConnection; begin if (assigned(fOnBeforeAddConnection)) then Synchronize(SyncBeforeAddConnection); end; procedure TCustomServer.DoAfterRemoveConnection; begin if (assigned(fOnAfterRemoveConnection)) then Synchronize(SyncAfterRemoveConnection); end; procedure TCustomServer.DoBeforeRemoveConnection; begin if (assigned(fOnBeforeRemoveConnection)) then Synchronize(SyncBeforeRemoveConnection); end; procedure TCustomServer.DoSocketError; begin if (assigned(fOnSocketErrot)) then Synchronize(SyncSocketError); end; procedure TCustomServer.SyncAfterAddConnection; begin if (assigned(fOnAfterAddConnection)) then fOnAfterAddConnection(self, fCurrentAddConnection); end; procedure TCustomServer.SyncBeforeAddConnection; begin if (assigned(fOnBeforeAddConnection)) then fOnBeforeAddConnection(self, fCurrentAddConnection, fCanAddConnection); end; procedure TCustomServer.SyncAfterRemoveConnection; begin if (assigned(fOnAfterRemoveConnection)) then fOnAfterRemoveConnection(self, fCurrentRemoveConnection); end; procedure TCustomServer.SyncBeforeRemoveConnection; begin if (assigned(fOnBeforeRemoveConnection)) then fOnBeforeRemoveConnection(self, fCurrentRemoveConnection); end; procedure TCustomServer.SyncSocketError; begin if (assigned(fOnSocketErrot)) then fOnSocketErrot(self, fCurrentSocket); end; procedure TCustomServer.TerminateThread; begin if (terminated) then exit; Terminate; end; constructor TCustomServer.Create(aBind: string; aPort: string); begin fBind := aBind; fPort := aPort; FreeOnTerminate := true; fConnections := TList.Create; fConnectionTermLock := syncobjs.TCriticalSection.Create; fMaxConnectionsCount := -1; fCanAddConnection := true; fCurrentAddConnection := nil; fCurrentRemoveConnection := nil; fCurrentSocket := nil; fIndex := getConnectionIndex; inherited Create(true); end; destructor TCustomServer.Destroy; begin fConnectionTermLock.free; fConnections.free; inherited Destroy; end; function TCustomServer.GetCount: integer; begin result := fConnections.Count; end; { procedure TCustomServer.Broadcast(aData: string); var i: integer; begin fConnectionTermLock.Enter; for i := 0 to fConnections.Count - 1 do begin if (not TCustomConnection(fConnections[i]).IsTerminated) then TCustomServerConnection(fConnections[i]).Broadcast(aData); end; fConnectionTermLock.Leave; end; } function TCustomServer.GetConnection(index: integer): TCustomConnection; begin fConnectionTermLock.Enter; result := nil; if index < fConnections.Count then result := TCustomConnection(fConnections[index]); fConnectionTermLock.Leave; end; function TCustomServer.GetConnectionByIndex(index: integer): TCustomConnection; var i: integer; begin result := nil; fConnectionTermLock.Enter; for i := 0 to fConnections.Count - 1 do begin if (TCustomConnection(fConnections[i]).Index = index) then begin result := TCustomConnection(fConnections[i]); break; end; end; fConnectionTermLock.Leave; end; function TCustomServer.CreateServerConnection(aSocket: TTCPCustomConnectionSocket): TCustomConnection; begin result := nil; end; function TCustomServer.AddConnection(var aSocket: TTCPCustomConnectionSocket): TCustomConnection; begin if ((fMaxConnectionsCount = -1) or (fConnections.count < fMaxConnectionsCount)) then begin result := CreateServerConnection(aSocket); if (result <> nil) then begin result.fParent := self; fCurrentAddConnection := result; fCanAddConnection := true; DoBeforeAddConnection; if (fCanAddConnection) then begin fConnections.add(result); DoAfterAddConnection; result.Resume; end else begin FreeAndNil(result); //aSocket := nil; end; end //else aSocket := nil; end; end; procedure TCustomServer.Execute; var c: TCustomConnection; s: TTCPCustomConnectionSocket; sock: TSocket; i: integer; begin fCurrentSocket := TTCPBlockSocket.Create; with fCurrentSocket do begin CreateSocket; if lastError <> 0 then DoSocketError; SetLinger(true, 10000); if lastError <> 0 then DoSocketError; //EnableReuse(true); // dcm bind(fBind, fPort); if lastError <> 0 then DoSocketError; listen; if lastError <> 0 then DoSocketError; repeat if terminated then break; if canread(1000) then begin if LastError = 0 then begin sock := Accept; if lastError = 0 then begin s := TTCPCustomConnectionSocket.Create; s.Socket := sock; if (fSSL) then begin s.SSL.CertificateFile := fSSLCertificateFile; s.SSL.PrivateKeyFile := fSSLPrivateKeyFile; //s.SSL.SSLType := LT_SSLv3; if (SSLKeyPassword <> '') then s.SSL.KeyPassword := fSSLKeyPassword; s.SSLAcceptConnection; i := s.SSL.LastError; if (i <> 0) then begin FreeAndNil(s); end; end; if (s <> nil) then begin s.GetSins; c := AddConnection(s); if (c = nil) and (s <> nil) then s.Free; end; end else begin DoSocketError; end; end else begin if lastError <> WSAETIMEDOUT then DoSocketError; end; end; until false; end; fOnAfterAddConnection := nil; fOnBeforeAddConnection := nil; fOnAfterRemoveConnection := nil; fOnBeforeRemoveConnection := nil; fOnSocketErrot := nil; //while fConnections.Count > 0 do for i := fConnections.Count - 1 downto 0 do begin c := TCustomConnection(fConnections[i]); try OnConnectionTerminate(c); c.TerminateThread; {$IFDEF WIN32} WaitForSingleObject(c.Handle, 100) {$ELSE WIN32} sleep(100); {$ENDIF WIN32} finally end; end; FreeAndNil(fCurrentSocket); //while fConnections.Count > 0 do sleep(500); end; procedure TCustomServer.LockTermination; begin fConnectionTermLock.Enter; end; procedure TCustomServer.Start; begin Resume; end; procedure TCustomServer.Stop; begin Suspend; end; procedure TCustomServer.UnLockTermination; begin fConnectionTermLock.Leave; end; { TTCPCustomServerConnectionSocket } { TTCPCustomConnectionSocket } destructor TTCPCustomConnectionSocket.Destroy; begin OnStatus := nil; OnSyncStatus := nil; inherited; end; procedure TTCPCustomConnectionSocket.DoOnStatus(Sender: TObject; Reason: THookSocketReason; const Value: String); begin if (fConnection <> nil) and (not fConnection.terminated) and (assigned(fOnSyncStatus)) then begin fCurrentStatusReason := Reason; fCurrentStatusValue := value; fConnection.Synchronize(SyncOnStatus); { if (fCurrentStatusReason = HR_Error) and (LastError = WSAECONNRESET) then fConnection.Terminate; } end; end; procedure TTCPCustomConnectionSocket.SyncOnStatus; begin if (assigned(fOnSyncStatus)) then fOnSyncStatus(self, fCurrentStatusReason, fCurrentStatusValue); end; constructor TTCPCustomConnectionSocket.Create; begin inherited Create; fConnection := nil; OnStatus := DoOnStatus; end; { TCustomConnection } constructor TCustomConnection.Create(aSocket: TTCPCustomConnectionSocket); begin fSocket := aSocket; fSocket.fConnection := self; FreeOnTerminate := true; fIndex := getConnectionIndex; inherited Create(true); end; destructor TCustomConnection.Destroy; begin if (fSocket <> nil) then begin fSocket.OnSyncStatus := nil; fSocket.OnStatus := nil; fSocket.Free; end; inherited Destroy; end; procedure TCustomConnection.Execute; begin if (BeforeExecuteConnection) then begin ExecuteConnection; AfterConnectionExecute; end; if (fParent <> nil) then if (not fParent.Terminated) then fParent.OnConnectionTerminate(self); end; procedure TCustomConnection.Start; begin Resume; end; procedure TCustomConnection.Stop; begin Suspend; end; procedure TCustomConnection.TerminateThread; begin if (terminated) then exit; Socket.OnSyncStatus := nil; Socket.OnStatus := nil; Terminate; end; function TCustomConnection.GetIsTerminated: boolean; begin result := terminated or (fSocket = nil) or (fSocket.Socket = INVALID_SOCKET); end; procedure TCustomConnection.AfterConnectionExecute; begin end; function TCustomConnection.BeforeExecuteConnection: boolean; begin result := true; end; procedure TCustomConnection.ExecuteConnection; begin end; end.
unit USearchServer; interface uses classes, UMyNetPcInfo, UModelUtil, Sockets, UMyTcp, SysUtils, DateUtils, Generics.Collections, IdHTTP, UMyUrl, SyncObjs, UPortMap; type {$Region ' 搜索网络 运行 ' } // 搜索网路 父类 TSearchServerRun = class protected NetworkModeInfo : TNetworkModeInfo; public procedure SetNetworkModeInfo( _NetworkModeInfo : TNetworkModeInfo ); procedure Update;virtual;abstract; class function get( NetworkModeType : string ): TSearchServerRun; function getIsRemoteCompleted : Boolean;virtual; protected procedure ExtractInfo;virtual; end; {$Region ' 局域网 ' } // 搜索 局域网 的服务器 TLanSearchServer = class( TSearchServerRun ) public constructor Create; procedure Update;override; destructor Destroy; override; end; {$EndRegion} {$Region ' Group 网络 ' } // Standard Pc Info TStandardPcInfo = class public PcID, PcName : string; LanIp, LanPort : string; InternetIp, InternetPort : string; public constructor Create( _PcID, _PcName : string ); procedure SetLanSocket( _LanIp, _LanPort : string ); procedure SetInternetSocket( _InternetIp, _InternetPort : string ); end; TStandardPcPair = TPair< string , TStandardPcInfo >; TStandardPcHash = class(TStringDictionary< TStandardPcInfo >); // 发送公司网请求 TFindStandardNetworkHttp = class private CompanyName, Password : string; Cmd : string; public constructor Create( _CompanyName, _Password : string ); procedure SetCmd( _Cmd : string ); function get : string; end; // HearBeat TStandardHearBetThread = class( TThread ) private AccountName, Password : string; LastServerNumber : Integer; public constructor Create; procedure SetAccountInfo( _AccountName, _Password : string ); destructor Destroy; override; protected procedure Execute; override; private procedure SendHeartBeat; procedure CheckAccountPc; end; // 找到 一个 Standard Pc TStandardPcAddHanlde = class private StandardPcInfo : TStandardPcInfo; public constructor Create( _StandardPcInfo : TStandardPcInfo ); procedure Update; private procedure AddNetworkPc; procedure AddPingMsg; end; // 搜索 Account Name 的服务器 TStandSearchServer = class( TSearchServerRun ) private AccountName : string; Password : string; private StandardPcMsg : string; StandardPcHash : TStandardPcHash; private WaitTime : Integer; private IsRemoteCompleted : Boolean; StandardHearBetThread : TStandardHearBetThread; public constructor Create; procedure Update;override; destructor Destroy; override; private function LoginAccount : Boolean; procedure FindStandardPcHash; procedure PingStandardPcHash; procedure LogoutAccount; private procedure PingMyPc; procedure PasswordError; procedure AccountNameNotExit; protected procedure ExtractInfo;override; public function getIsRemoteCompleted : Boolean;override; end; {$EndRegion} {$Region ' 直连网络 ' } // Advace Req Pc Info TAdvancePcInfo = class public PcID : string; PcInfoMsgStr : string; public constructor Create( _PcID, _PcInfoMsgStr : string ); end; TAdvancePcPair = TPair< string , TAdvancePcInfo >; TAdvancePcHash = class(TStringDictionary< TAdvancePcInfo >); // 搜索 Internet Pc 的服务器 TAdvanceSearchServer = class( TSearchServerRun ) private Domain : string; Ip, Port : string; private TcpSocket : TCustomIpClient; private IsRemoteCompleted : Boolean; public constructor Create; procedure Update;override; destructor Destroy; override; private procedure PingMyPc; function FindIp: Boolean; function ConnTargetPc : Boolean; procedure SendInternetPcInfoMsg; procedure RevConnPcInfoMsg; private // 等待重启网络 procedure RestartNetwork; protected procedure ExtractInfo;override; public function getIsRemoteCompleted : Boolean;override; end; {$EndRegion} {$EndRegion} {$Region ' 搜索网络 运行结果处理 ' } {$Region ' Rester Network ' } TFindInternetSocket = class private PortMapping : TPortMapping; InternetIp, InternetPort : string; public constructor Create( _PortMapping : TPortMapping ); procedure Update; private function FindInternetIp: Boolean; procedure FindInternetPort; private function FindRouterInternetIp: Boolean; function FindWebInternetIp: Boolean; procedure SetInternetFace; end; TRestartNetworkHandle = class public procedure Update; private procedure ClearRedirectJob; procedure ClearTransferFace; procedure ClearCsNetwork; procedure ClearNetworkPcInfo; procedure ClearNetworkPcFace; private procedure ClearSearch; procedure ClearRestore; procedure ClearFileTransfer; procedure ClearFileShare; private procedure LostServerFace; end; {$EndRegion} {$Region ' Be Server ' } TNetPcSocket = class public PcID : string; Ip, Port : string; public constructor Create( _PcID : string ); procedure SetSocketInfo( _Ip, _Port : string ); end; TNetPcSocketList = class( TObjectList<TNetPcSocket> ); TBeServerHandle = class private NetPcSocketList : TNetPcSocketList; public constructor Create; procedure Update; destructor Destroy; override; private procedure FindNetPcSocketList; procedure SendBeMasterMsg; end; {$EndRegion} {$Region ' Conn Server ' } TConnServerHandle = class private ServerIp, ServerPort : string; TcpSocket : TCustomIpClient; public constructor Create( _ServerIp, _ServerPort : string ); procedure SetTcpSocket( _TcpSocket : TCustomIpClient ); function get: Boolean; private function ConnServer: Boolean; procedure SendPcOnline; procedure SendMyCloudPcInfo; procedure SendAdvancePcMsg; private procedure ConnServerFace; procedure CheckTransferAndSharePcExist; end; {$EndRegion} {$EndRegion} {$Region ' 等待 Server 线程 ' } // 定时 做 PortMapping TPortMappingThread = class( TThread ) private LanIp, LanPort : string; InternetPort : string; private PortMapping : TPortMapping; public constructor Create( _LanIp, _LanPort : string ); procedure SetPortMapping( _PortMapping : TPortMapping ); destructor Destroy; override; protected procedure Execute; override; end; // 重启网络线程 TRestartNetworkThread = class( TThread ) private StartTime : TDateTime; IsRestart : Boolean; public constructor Create; destructor Destroy; override; protected procedure Execute; override; public procedure RunRestart; procedure ShowRemainTime; procedure StopRestart; private procedure RestartNetwork; end; // 搜索 服务器 TMasterThread = class( TThread ) private IsRestartMaster : Boolean; // 是否重新选择 Master private WaitPingTime : Integer; // 与其他Pc交换信息的时间 WaitServerNotifyTime : Integer; // 等待服务器通知的时间 private PortMapping : TPortMapping; PortMappingThread : TPortMappingThread; // 定时 PortMap public AdvanceLock : TCriticalSection; // 其他 Pc Advance AdvancePcHash : TAdvancePcHash; private SearchServerRun : TSearchServerRun; // 运行网络 RestartNetworkThread : TRestartNetworkThread; // 定时重启网络 public constructor Create; procedure RestartNetwork; procedure SetWaitPingTime( _WaitPingTime : Integer ); procedure RevMaxMaster; procedure RunRestartThread; destructor Destroy; override; protected procedure Execute; override; private procedure ResetNetworkPc; procedure AddPortMaping; procedure RunNetwork; procedure WaitPingMsg; procedure BeServer; procedure WaitServerNotify; function ConnServer: Boolean; procedure StopNetwork; procedure RemovePortMapping; private procedure SetLanMaster; procedure ResetLanMaster; end; {$EndRegion} const Count_SearchServerThread : Integer = 10; MsgType_Ping : string = 'Ping'; MsgType_BackPing : string = 'BackPing'; // Standard Network Http 连接类型 Cmd_Login = 'login'; Cmd_HeartBeat = 'heartbeat'; Cmd_ReadLoginNumber = 'readloginnumber'; Cmd_AddServerNumber = 'addservernumber'; Cmd_ReadServerNumber = 'readservernumber'; Cmd_Logout = 'logout'; // Standard Network Http 参数 HttpReq_CompanyName = 'CompanyName'; HttpReq_Password = 'Password'; HttpReq_PcID = 'PcID'; HttpReq_PcName = 'PcName'; HttpReq_LanIp = 'LanIp'; HttpReq_LanPort = 'LanPort'; HttpReq_InternetIp = 'InternetIp'; HttpReq_InternetPort = 'InternetPort'; HttpReq_CloudIDNumber = 'CloudIDNumber'; // Login 结果 LoginResult_ConnError = 'ConnError'; LoginResult_CompanyNotFind = 'CompanyNotFind'; LoginResult_PasswordError = 'PasswordError'; LoginResult_OK = 'OK'; // Resutl Split Split_Result = '<Result/>'; Split_Pc = '<Pc/>'; Split_PcPro = '<PcPro/>'; PcProCount = 6; PcPro_PcID = 0; PcPro_PcName = 1; PcPro_LanIp = 2; PcPro_LanPort = 3; PcPro_InternetIp = 4; PcPro_InternetPort = 5; // ShowForm_CompanyNameError : string = 'Account name "%s" does not exist.'; // ShowForm_PasswordError : string = 'Password is incorrect.Please input password again.'; // ShowForm_ParseError : string = 'Can not parse "%s" to ip address.'; WaitTime_LAN : Integer = 5; WaitTime_Standard : Integer = 20; WaitTime_Advance : Integer = 30; WaitTime_MyPc : Integer = 2; WaitTime_ServerNofity : Integer = 15; WaitTime_PortMap = 10; // 分钟 AdvanceMsg_NotServer = 'NotServer'; // 非服务器 var MasterThread : TMasterThread; // 等待 Server 线程 implementation uses UNetworkControl, UFormBroadcast, UNetworkFace, UMyUtil, UMyMaster, UMyClient, UMyServer, UBackupInfoFace, USettingInfo, UMyFileSearch, UJobFace, uDebug, UNetPcInfoXml, USearchFileFace, UFileTransferFace, UMyShareControl, UMyShareFace, UMyJobInfo, UChangeInfo, UMainForm; { TSearchServerThread } procedure TMasterThread.AddPortMaping; var FindInternetSocket : TFindInternetSocket; begin FindInternetSocket := TFindInternetSocket.Create( PortMapping ); FindInternetSocket.Update; FindInternetSocket.Free; // 定时 PortMap if PortMapping.IsPortMapable then begin PortMappingThread := TPortMappingThread.Create( PcInfo.LanIp, PcInfo.LanPort ); PortMappingThread.SetPortMapping( PortMapping ); PortMappingThread.Resume; end; end; procedure TMasterThread.BeServer; var BeServerHandle : TBeServerHandle; begin if Terminated or IsRestartMaster then Exit; // 程序结束 // 其他人 成为 Server // 其他人 比较值最大 if Terminated or ( MasterInfo.MasterID <> '' ) or ( MasterInfo.MaxPcID <> PcInfo.PcID ) then Exit; // 成为服务器的处理 BeServerHandle := TBeServerHandle.Create; BeServerHandle.Update; BeServerHandle.Free; end; function TMasterThread.ConnServer: Boolean; var Ip, Port : string; TcpSocket : TCustomIpClient; ConnServerHandle : TConnServerHandle; begin Result := False; if Terminated or IsRestartMaster then Exit; Ip := MasterInfo.MasterIp; Port := MasterInfo.MasterPort; TcpSocket := MyClient.TcpSocket; ConnServerHandle := TConnServerHandle.Create( Ip, Port ); ConnServerHandle.SetTcpSocket( TcpSocket ); Result := ConnServerHandle.get; ConnServerHandle.Free; if Terminated or IsRestartMaster then Result := False; end; constructor TMasterThread.Create; begin inherited Create( True ); AdvanceLock := TCriticalSection.Create; AdvancePcHash := TAdvancePcHash.Create; WaitPingTime := WaitTime_LAN; WaitServerNotifyTime := WaitTime_ServerNofity; IsRestartMaster := True; RestartNetworkThread := TRestartNetworkThread.Create; RestartNetworkThread.Resume; end; procedure TMasterThread.SetLanMaster; begin if MasterInfo.MasterID <> PcInfo.PcID then Exit; end; procedure TMasterThread.SetWaitPingTime(_WaitPingTime: Integer); begin WaitPingTime := _WaitPingTime; end; procedure TMasterThread.StopNetwork; begin SearchServerRun.Free; RestartNetworkThread.StopRestart; MyListener.StopListen; end; destructor TMasterThread.Destroy; begin Terminate; Resume; WaitFor; RestartNetworkThread.Free; AdvancePcHash.Free; AdvanceLock.Free; inherited; end; procedure TMasterThread.Execute; begin PortMapping := TPortMapping.Create; while not Terminated do begin // 初始化 ResetNetworkPc; // 添加 端口映射 Interenet 操作 AddPortMaping; // 运行网络 RunNetwork; // 等待 与其他 Pc 交互信息 WaitPingMsg; // 成为服务器 BeServer; // 等待 Server 通知 WaitServerNotify; // 连接服务器成功, 挂起线程 if ConnServer then begin MyClient.StartHeartBeat; Suspend; MyClient.StopHeartBeat; end; // 停止运行网络 StopNetwork; // 移除 端口映射 RemovePortMapping; end; PortMapping.Free; inherited; end; procedure TMasterThread.RunNetwork; var IsRemoteCompleted : Boolean; PmNetworkOpenChangeInfo : TPmNetworkOpenChangeInfo; PmNetworkReturnLocalNetwork : TPmNetworkReturnLocalNetwork; begin // 开始监听 MyListener.StartListen( PcInfo.LanPort ); // 运行网络 SearchServerRun := TSearchServerRun.get( NetworkModeInfo.getNetworkMode ); SearchServerRun.SetNetworkModeInfo( NetworkModeInfo ); SearchServerRun.Update; IsRemoteCompleted := SearchServerRun.getIsRemoteCompleted; // 可以改变网络 PmNetworkOpenChangeInfo := TPmNetworkOpenChangeInfo.Create; MyNetworkFace.AddChange( PmNetworkOpenChangeInfo ); // 可以重启网路 IsRestartMaster := False; // 远程 登录失败, 返回本地网络 if not IsRemoteCompleted then begin PmNetworkReturnLocalNetwork := TPmNetworkReturnLocalNetwork.Create; MyNetworkFace.AddChange( PmNetworkReturnLocalNetwork ); end; end; procedure TMasterThread.RunRestartThread; begin RestartNetworkThread.RunRestart; end; procedure TMasterThread.RemovePortMapping; begin if PortMapping.IsPortMapable then PortMappingThread.Free; end; procedure TMasterThread.ResetLanMaster; begin if MasterInfo.MasterID <> PcInfo.PcID then Exit; end; procedure TMasterThread.ResetNetworkPc; var RestartNetworkHandle : TRestartNetworkHandle; begin RestartNetworkHandle := TRestartNetworkHandle.Create; RestartNetworkHandle.Update; RestartNetworkHandle.Free; end; procedure TMasterThread.RestartNetwork; var PmNetworkCloseChangeInfo : TPmNetworkCloseChangeInfo; begin PmNetworkCloseChangeInfo := TPmNetworkCloseChangeInfo.Create; MyNetworkFace.AddChange( PmNetworkCloseChangeInfo ); IsRestartMaster := True; Resume; end; procedure TMasterThread.RevMaxMaster; begin WaitServerNotifyTime := WaitServerNotifyTime + WaitServerNotifyTime; end; procedure TMasterThread.WaitPingMsg; var StartTime : TDateTime; Count : Integer; SbMyStatusConningInfo : TSbMyStatusConningInfo; begin Count := 0; StartTime := Now; while not Terminated and ( MasterInfo.MasterID = '' ) and ( SecondsBetween( Now, StartTime ) < WaitPingTime ) and not IsRestartMaster do begin Sleep( 100 ); inc( Count ); if Count = 10 then begin SbMyStatusConningInfo := TSbMyStatusConningInfo.Create; MyNetworkFace.AddChange( SbMyStatusConningInfo ); Count := 0; end; end; end; procedure TMasterThread.WaitServerNotify; var StartTime : TDateTime; Count : Integer; SbMyStatusConningInfo : TSbMyStatusConningInfo; begin Count := 0; StartTime := Now; while not Terminated and ( MasterInfo.MasterID = '' ) and ( SecondsBetween( Now, StartTime ) < WaitServerNotifyTime ) and not IsRestartMaster do begin Sleep( 100 ); inc( Count ); if Count = 10 then begin SbMyStatusConningInfo := TSbMyStatusConningInfo.Create; MyNetworkFace.AddChange( SbMyStatusConningInfo ); Count := 0; end; end; end; { TLanSearchServer } constructor TLanSearchServer.Create; begin // 开启 广播 frmBroadcast.OnRevMsgEvent := MyMasterAccept.RevBroadcastStr; end; destructor TLanSearchServer.Destroy; begin frmBroadcast.OnRevMsgEvent := nil; // 关广播 inherited; end; procedure TLanSearchServer.Update; var SendBroadcastMsg : TSendLanBroadcast; begin // 获取 广播命令 SendBroadcastMsg := TSendLanBroadcast.Create; // 发送 广播命令 MyMasterConn.AddChange( SendBroadcastMsg ); // 设置等待时间 MasterThread.SetWaitPingTime( WaitTime_LAN ); end; { TSearchServerBase } procedure TSearchServerRun.ExtractInfo; begin end; class function TSearchServerRun.get( NetworkModeType: string): TSearchServerRun; begin if NetworkModeType = NetworkMode_LAN then Result := TLanSearchServer.Create else if NetworkModeType = NetworkMode_Standard then Result := TStandSearchServer.Create else if NetworkModeType = NetworkMode_Advance then Result := TAdvanceSearchServer.Create; end; function TSearchServerRun.getIsRemoteCompleted: Boolean; begin Result := True; end; procedure TSearchServerRun.SetNetworkModeInfo( _NetworkModeInfo: TNetworkModeInfo); begin NetworkModeInfo := _NetworkModeInfo; ExtractInfo; end; { TStandSearchServer } procedure TStandSearchServer.AccountNameNotExit; var ErrorStr : string; StandardAccountError : TStandardAccountError; begin ErrorStr := Format( frmMainForm.siLang_frmMainForm.GetText( 'GroupNameError' ), [AccountName] ); MyMessageBox.ShowError( ErrorStr ); StandardAccountError := TStandardAccountError.Create( AccountName ); StandardAccountError.SetPassword( Password ); MyNetworkFace.AddChange( StandardAccountError ); end; constructor TStandSearchServer.Create; begin StandardPcHash := TStandardPcHash.Create; StandardHearBetThread := TStandardHearBetThread.Create; IsRemoteCompleted := True; end; destructor TStandSearchServer.Destroy; begin StandardHearBetThread.Free; StandardPcHash.Free; LogoutAccount; // Logout inherited; end; procedure TStandSearchServer.ExtractInfo; var StandardNetworkMode : TStandardNetworkMode; begin inherited; StandardNetworkMode := ( NetworkModeInfo as TStandardNetworkMode ); AccountName := StandardNetworkMode.AccountName; Password := StandardNetworkMode.Password; StandardHearBetThread.SetAccountInfo( AccountName, Password ); end; procedure TStandSearchServer.FindStandardPcHash; var PcStrList : TStringList; PcProStrList : TStringList; i : Integer; PcID, PcName : string; LanIp, LanPort : string; InternetIp, InternetPort : string; StandardPcInfo : TStandardPcInfo; begin PcStrList := MySplitStr.getList( StandardPcMsg, Split_Pc ); for i := 0 to PcStrList.Count - 1 do begin PcProStrList := MySplitStr.getList( PcStrList[i], Split_PcPro ); if PcProStrList.Count = PcProCount then begin PcID := PcProStrList[ PcPro_PcID ]; PcName := PcProStrList[ PcPro_PcName ]; LanIp := PcProStrList[ PcPro_LanIp ]; LanPort := PcProStrList[ PcPro_LanPort ]; InternetIp := PcProStrList[ PcPro_InternetIp ]; InternetPort := PcProStrList[ PcPro_InternetPort ]; StandardPcInfo := TStandardPcInfo.Create( PcID, PcName ); StandardPcInfo.SetLanSocket( LanIp, LanPort ); StandardPcInfo.SetInternetSocket( InternetIp, InternetPort ); StandardPcHash.AddOrSetValue( PcID, StandardPcInfo ); end; PcProStrList.Free; end; PcStrList.Free; end; function TStandSearchServer.getIsRemoteCompleted: Boolean; begin Result := IsRemoteCompleted; end; function TStandSearchServer.LoginAccount: Boolean; var FindStandardNetworkHttp : TFindStandardNetworkHttp; HttpStr, HttpResult : string; HttpStrList : TStringList; begin Result := False; // 登录 FindStandardNetworkHttp := TFindStandardNetworkHttp.Create( AccountName, Password ); FindStandardNetworkHttp.SetCmd( Cmd_Login ); HttpStr := FindStandardNetworkHttp.get; FindStandardNetworkHttp.Free; // 是否登录远程网络失败 IsRemoteCompleted := False; // 网络连接 断开 if HttpStr = LoginResult_ConnError then else // 帐号不存在 if HttpStr = LoginResult_CompanyNotFind then AccountNameNotExit else // 密码错误 if HttpStr = LoginResult_PasswordError then PasswordError else begin // 登录成功 IsRemoteCompleted := True; HttpStrList := MySplitStr.getList( HttpStr, Split_Result ); if HttpStrList.Count > 0 then HttpResult := HttpStrList[0]; if HttpResult = LoginResult_OK then begin if HttpStrList.Count > 1 then StandardPcMsg := HttpStrList[1]; Result := True; end; HttpStrList.Free; end; end; procedure TStandSearchServer.LogoutAccount; var FindStandardNetworkHttp : TFindStandardNetworkHttp; begin // Logout FindStandardNetworkHttp := TFindStandardNetworkHttp.Create( AccountName, Password ); FindStandardNetworkHttp.SetCmd( Cmd_Logout ); FindStandardNetworkHttp.get; FindStandardNetworkHttp.Free; end; procedure TStandSearchServer.PasswordError; var StandardPasswordError : TStandardPasswordError; begin MyMessageBox.ShowError( frmMainForm.siLang_frmMainForm.GetText( 'GroupPasswordError' ) ); StandardPasswordError := TStandardPasswordError.Create( AccountName ); MyNetworkFace.AddChange( StandardPasswordError ); end; procedure TStandSearchServer.PingMyPc; var LanConnSendPingMsg : TLanConnSendPingMsg; begin LanConnSendPingMsg := TLanConnSendPingMsg.Create; LanConnSendPingMsg.SetRemotePcID( PcInfo.PcID ); LanConnSendPingMsg.SetRemoteLanSocket( PcInfo.LanIp, PcInfo.LanPort ); MyMasterConn.AddChange( LanConnSendPingMsg ); end; procedure TStandSearchServer.PingStandardPcHash; var p : TStandardPcPair; StandardPcAddHanlde : TStandardPcAddHanlde; begin for p in StandardPcHash do begin StandardPcAddHanlde := TStandardPcAddHanlde.Create( p.Value ); StandardPcAddHanlde.Update; StandardPcAddHanlde.Free; end; if StandardPcHash.Count <= 1 then WaitTime := WaitTime_MyPc else WaitTime := WaitTime_Standard; end; procedure TStandSearchServer.Update; begin if LoginAccount then begin FindStandardPcHash; PingStandardPcHash; end else begin WaitTime := WaitTime_MyPc; PingMyPc; end; StandardHearBetThread.Resume; MasterThread.SetWaitPingTime( WaitTime ); end; { TAdvanceSearchServer } function TAdvanceSearchServer.ConnTargetPc: Boolean; var MyTcpConn : TMyTcpConn; NetworkLvAddInfo : TLvNetworkAdd; begin Result := False; MyTcpConn := TMyTcpConn.Create( TcpSocket ); MyTcpConn.SetConnSocket( Ip, Port ); MyTcpConn.SetConnType( ConnType_SearchServer ); if MyTcpConn.Conn then begin if MySocketUtil.RevData( TcpSocket ) <> '' then begin MySocketUtil.SendString( TcpSocket, MasterConn_Advance ); Result := True; end; end; MyTcpConn.Free; // 目标 Pc 离线 if not Result then RestartNetwork; // 启动定时重启 end; constructor TAdvanceSearchServer.Create; begin TcpSocket := TCustomIpClient.Create(nil); IsRemoteCompleted := True; end; destructor TAdvanceSearchServer.Destroy; begin TcpSocket.Free; inherited; end; procedure TAdvanceSearchServer.ExtractInfo; var AdvanceNetworkMode : TAdvanceNetworkMode; begin inherited; AdvanceNetworkMode := ( NetworkModeInfo as TAdvanceNetworkMode ); Domain := AdvanceNetworkMode.InternetName; Port := AdvanceNetworkMode.Port; end; function TAdvanceSearchServer.FindIp: Boolean; var AdvanceDnsError : TAdvanceDnsError; ErrorStr : string; begin Result := True; if MyParseHost.IsIpStr( Domain ) then begin Ip := Domain; Exit; end; if MyParseHost.HostToIP( Domain, Ip ) then Exit; // 显示 解析域名失败 ErrorStr := Format( frmMainForm.siLang_frmMainForm.GetText( 'ParseError' ), [Domain] ); MyMessageBox.ShowError( ErrorStr ); AdvanceDnsError := TAdvanceDnsError.Create( Domain, Port ); MyNetworkFace.AddChange( AdvanceDnsError ); IsRemoteCompleted := False; Result := False; end; function TAdvanceSearchServer.getIsRemoteCompleted: Boolean; begin Result := IsRemoteCompleted; end; procedure TAdvanceSearchServer.PingMyPc; var LanConnSendPingMsg : TLanConnSendPingMsg; begin LanConnSendPingMsg := TLanConnSendPingMsg.Create; LanConnSendPingMsg.SetRemotePcID( PcInfo.PcID ); LanConnSendPingMsg.SetRemoteLanSocket( PcInfo.LanIp, PcInfo.LanPort ); MyMasterConn.AddChange( LanConnSendPingMsg ); end; procedure TAdvanceSearchServer.RestartNetwork; var NetworkLvAddInfo : TLvNetworkAdd; begin // 界面显示 离线机器 NetworkLvAddInfo := TLvNetworkAdd.Create( Domain ); NetworkLvAddInfo.SetPcName( Domain ); MyNetworkFace.AddChange( NetworkLvAddInfo ); MasterThread.RunRestartThread; end; procedure TAdvanceSearchServer.RevConnPcInfoMsg; var MsgStr : string; InternetPcInfoMsg : TInternetPcInfoMsg; NetPcAddHandle : TNetPcAddHandle; InternetConnSendPingMsg : TInternetConnSendPingMsg; begin // 接受命令 并 解释 MsgStr := MySocketUtil.RevString( TcpSocket ); // 非服务器 if ( MsgStr = '' ) or ( MsgStr = AdvanceMsg_NotServer ) then Exit; InternetPcInfoMsg := TInternetPcInfoMsg.Create; InternetPcInfoMsg.SetMsgStr( MsgStr ); // 添加 Pc NetPcAddHandle := TNetPcAddHandle.Create( InternetPcInfoMsg.PcID ); NetPcAddHandle.SetPcName( InternetPcInfoMsg.PcName ); NetPcAddHandle.Update; NetPcAddHandle.Free; // 发送 Ping 命令 InternetConnSendPingMsg := TInternetConnSendPingMsg.Create; InternetConnSendPingMsg.SetRemotePcID( InternetPcInfoMsg.PcID ); InternetConnSendPingMsg.SetRemoteLanSocket( InternetPcInfoMsg.Ip, InternetPcInfoMsg.Port ); InternetConnSendPingMsg.SetRemoteInternetSocket( InternetPcInfoMsg.InternetIp, InternetPcInfoMsg.InternetPort ); MyMasterConn.AddChange( InternetConnSendPingMsg ); InternetPcInfoMsg.Free; end; procedure TAdvanceSearchServer.SendInternetPcInfoMsg; var MsgStr : string; InternetPcInfoMsg : TInternetPcInfoMsg; begin InternetPcInfoMsg := TInternetPcInfoMsg.Create; InternetPcInfoMsg.SetPcID( PcInfo.PcID ); InternetPcInfoMsg.SetPcName( PcInfo.PcName ); InternetPcInfoMsg.SetSocketInfo( PcInfo.LanIp, PcInfo.LanPort ); InternetPcInfoMsg.SetnternetSocketInfo( PcInfo.InternetIp, PcInfo.InternetPort ); InternetPcInfoMsg.SetCloudIDNumMD5( CloudSafeSettingInfo.getCloudIDNumMD5 ); MsgStr := InternetPcInfoMsg.getMsgStr; InternetPcInfoMsg.Free; MySocketUtil.SendString( TcpSocket, MsgStr ); end; procedure TAdvanceSearchServer.Update; var WatiTime : Integer; begin PingMyPc; if FindIp and ConnTargetPc then begin SendInternetPcInfoMsg; RevConnPcInfoMsg; WatiTime := WaitTime_Advance; end else WatiTime := WaitTime_MyPc; MasterThread.SetWaitPingTime( WatiTime ); end; { TBeServerHandle } constructor TBeServerHandle.Create; begin NetPcSocketList := TNetPcSocketList.Create; end; destructor TBeServerHandle.Destroy; begin NetPcSocketList.Free; inherited; end; procedure TBeServerHandle.FindNetPcSocketList; var NetPcInfoHash : TNetPcInfoHash; p : TNetPcInfoPair; PcID, Ip, Port : string; NewNetPcSocket : TNetPcSocket; begin MyNetPcInfo.EnterData; NetPcInfoHash := MyNetPcInfo.NetPcInfoHash; for p in NetPcInfoHash do begin if not p.Value.IsActivate then Continue; PcID := p.Value.PcID; Ip := p.Value.Ip; Port := p.Value.Port; NewNetPcSocket := TNetPcSocket.Create( PcID ); NewNetPcSocket.SetSocketInfo( Ip, Port ); NetPcSocketList.Add( NewNetPcSocket ); end; MyNetPcInfo.LeaveData; end; procedure TBeServerHandle.SendBeMasterMsg; var i : Integer; PcID, Ip, Port : string; ConnSendBeMasterMsg : TConnSendBeMasterMsg; begin for i := 0 to NetPcSocketList.Count - 1 do begin PcID := NetPcSocketList[i].PcID; Ip := NetPcSocketList[i].Ip; Port := NetPcSocketList[i].Port; // BeMaster 命令 ConnSendBeMasterMsg := TConnSendBeMasterMsg.Create; ConnSendBeMasterMsg.SetRemotePcID( PcID ); ConnSendBeMasterMsg.SetRemoteSocketInfo( Ip, Port ); MyMasterConn.AddChange( ConnSendBeMasterMsg ); end; end; procedure TBeServerHandle.Update; begin FindNetPcSocketList; SendBeMasterMsg; end; { TNetPcSocket } constructor TNetPcSocket.Create(_PcID: string); begin PcID := _PcID; end; procedure TNetPcSocket.SetSocketInfo(_Ip, _Port : string); begin Ip := _Ip; Port := _Port; end; { TConnServerHandle } procedure TConnServerHandle.CheckTransferAndSharePcExist; var VstShareFileCheckExistShare : TVstShareFileCheckExistShare; begin VstShareFileCheckExistShare := TVstShareFileCheckExistShare.Create; MyFaceChange.AddChange( VstShareFileCheckExistShare ); end; function TConnServerHandle.ConnServer: Boolean; var MyTcpConn : TMyTcpConn; begin MyTcpConn := TMyTcpConn.Create( TcpSocket ); MyTcpConn.SetConnSocket( ServerIp, ServerPort ); MyTcpConn.SetConnType( ConnType_Server ); Result := MyTcpConn.Conn; MyTcpConn.Free; end; procedure TConnServerHandle.ConnServerFace; var SbMyStatusConnInfo : TSbMyStatusConnInfo; ConnServerSearchFace : TConnServerSearchFace; begin SbMyStatusConnInfo := TSbMyStatusConnInfo.Create; MyNetworkFace.AddChange( SbMyStatusConnInfo ); ConnServerSearchFace := TConnServerSearchFace.Create; MySearchFileFace.AddChange( ConnServerSearchFace ); end; constructor TConnServerHandle.Create(_ServerIp, _ServerPort: string); begin ServerIp := _ServerIp; ServerPort := _ServerPort; end; procedure TConnServerHandle.SendAdvancePcMsg; var AdvacePcHash : TAdvancePcHash; p : TAdvancePcPair; begin MasterThread.AdvanceLock.Enter; AdvacePcHash := MasterThread.AdvancePcHash; for p in AdvacePcHash do MyClient.SendMsgToAll( p.Value.PcInfoMsgStr ); AdvacePcHash.Clear; MasterThread.AdvanceLock.Leave; end; procedure TConnServerHandle.SendMyCloudPcInfo; var ClientSendRefreshPcInfo : TClientSendRefreshPcInfo; begin // 发送 云信息 给 Server ClientSendRefreshPcInfo := TClientSendRefreshPcInfo.Create( MasterInfo.MasterID ); MyClient.AddChange( ClientSendRefreshPcInfo ); end; procedure TConnServerHandle.SendPcOnline; var PcOnlineMsg : TPcOnlineMsg; MsgStr : string; begin // 上线信息 PcOnlineMsg := TPcOnlineMsg.Create; PcOnlineMsg.SetPcID( PcInfo.PcID ); // 上线时间 MsgStr := PcCloudMsgUtil.getOnlineTimeMsg; PcOnlineMsg.SetPcCloudOnlineMsgStr( MsgStr ); // Pc 基本信息 MsgStr := PcCloudMsgUtil.getBaseMsg; PcOnlineMsg.SetPcCloudBaseMsgStr( MsgStr ); // 云空间信息 MsgStr := PcCloudMsgUtil.getSpaceMsg; PcOnlineMsg.SetPcCloudSpaceMsgStr( MsgStr ); // 云配置信息 MsgStr := PcCloudMsgUtil.getConfigMsg; PcOnlineMsg.SetPcCloudConfigMsgStr( MsgStr ); // 备份路径信息 MsgStr := PcCloudMsgUtil.getBackupPathMsg; PcOnlineMsg.SetPcCloudBackupPathMsgStr( MsgStr ); // 发送池 MyClient.SendMsgToAll( PcOnlineMsg ); end; procedure TConnServerHandle.SetTcpSocket(_TcpSocket: TCustomIpClient); begin TcpSocket := _TcpSocket; end; function TConnServerHandle.get: Boolean; begin if ConnServer then begin ConnServerFace; // 刷新备份界面 MySocketUtil.SendString( TcpSocket, PcInfo.PcID ); // 发送 Pc 标识 MyClient.RunRevMsg; // 启动客户端 接收线程 SendPcOnline; // 发送 Pc 上线消息 SendMyCloudPcInfo; // 发送本地云信息 SendAdvancePcMsg; // 连接 本机的 Advance 处理 CheckTransferAndSharePcExist; // 检测是否存在共享目录Pc Result := True; end else Result := False; end; { TRestartNetworkHandle } procedure TRestartNetworkHandle.ClearCsNetwork; begin MyClient.ClientRestart; MyServer.RestartServer; end; procedure TRestartNetworkHandle.ClearFileShare; var ShareDownServerOfflineHandle : TShareDownServerOfflineHandle; ShareHistoryServerOfflineHandle : TShareHistoryServerOfflineHandle; ShareFavorityServerOfflineHandle : TShareFavorityServerOfflineHandle; begin // Share Down ShareDownServerOfflineHandle := TShareDownServerOfflineHandle.Create; ShareDownServerOfflineHandle.Update; ShareDownServerOfflineHandle.Free; // Share History ShareHistoryServerOfflineHandle := TShareHistoryServerOfflineHandle.Create; ShareHistoryServerOfflineHandle.Update; ShareHistoryServerOfflineHandle.Free; // Share Favority ShareFavorityServerOfflineHandle := TShareFavorityServerOfflineHandle.Create; ShareFavorityServerOfflineHandle.Update; ShareFavorityServerOfflineHandle.Free; end; procedure TRestartNetworkHandle.ClearFileTransfer; var VstMyFileAllPcOfflineInfo : TVstMyFileAllPcOfflineInfo; LvFileReceiveSetAllPcOfflineInfo : TLvFileReceiveSetAllPcOfflineInfo; begin // 发送 离线 VstMyFileAllPcOfflineInfo := TVstMyFileAllPcOfflineInfo.Create; MyFaceChange.AddChange( VstMyFileAllPcOfflineInfo ); // 接收 离线 LvFileReceiveSetAllPcOfflineInfo := TLvFileReceiveSetAllPcOfflineInfo.Create; MyFaceChange.AddChange( LvFileReceiveSetAllPcOfflineInfo ); end; procedure TRestartNetworkHandle.ClearNetworkPcFace; var SbMyStatusNotConnInfo : TSbMyStatusNotConnInfo; NetworkServerOfflineFace : TNetworkServerOfflineFace; begin SbMyStatusNotConnInfo := TSbMyStatusNotConnInfo.Create; MyNetworkFace.AddChange( SbMyStatusNotConnInfo ); NetworkServerOfflineFace := TNetworkServerOfflineFace.Create; NetworkServerOfflineFace.Update; NetworkServerOfflineFace.Free; end; procedure TRestartNetworkHandle.ClearNetworkPcInfo; var NetworkPcResetHandle : TNetworkPcResetHandle; begin // 重置 Pc 信息 NetworkPcResetHandle := TNetworkPcResetHandle.Create; NetworkPcResetHandle.Update; NetworkPcResetHandle.Free; // 重置 Master 信息 MasterInfo.ResetMaster; end; procedure TRestartNetworkHandle.ClearRedirectJob; var RedirectJobPcOfflineInfo : TRedirectJobPcOfflineInfo; begin RedirectJobPcOfflineInfo := TRedirectJobPcOfflineInfo.Create( '' ); MyJobInfo.AddChange( RedirectJobPcOfflineInfo ); end; procedure TRestartNetworkHandle.ClearRestore; var AllPcRestoreFileSearchCompleteInfo : TAllPcRestoreFileSearchCompleteInfo; AllPcRestoreFileSearchCancelInfo : TAllPcRestoreFileSearchCancelInfo; begin // Restore Req AllPcRestoreFileSearchCompleteInfo := TAllPcRestoreFileSearchCompleteInfo.Create; MyFileRestoreReq.AddChange( AllPcRestoreFileSearchCompleteInfo ); // Restore Scan AllPcRestoreFileSearchCancelInfo := TAllPcRestoreFileSearchCancelInfo.Create; MyFileRestoreScan.AddChange( AllPcRestoreFileSearchCancelInfo ); end; procedure TRestartNetworkHandle.ClearSearch; var AllPcFileSearchCompleteInfo : TAllPcFileSearchCompleteInfo; AllPcFileSearchCancelInfo : TAllPcFileSearchCancelInfo; begin // Search Req AllPcFileSearchCompleteInfo := TAllPcFileSearchCompleteInfo.Create; MyFileSearchReq.AddChange( AllPcFileSearchCompleteInfo ); // Search Scan AllPcFileSearchCancelInfo := TAllPcFileSearchCancelInfo.Create; MyFileSearchScan.AddChange( AllPcFileSearchCancelInfo ); end; procedure TRestartNetworkHandle.ClearTransferFace; var VirTransferPcOfflineHandle : TVirTransferPcOfflineHandle; begin if MasterInfo.MasterID = '' then Exit; VirTransferPcOfflineHandle := TVirTransferPcOfflineHandle.Create; VirTransferPcOfflineHandle.SetPcID( '' ); VirTransferPcOfflineHandle.Update; VirTransferPcOfflineHandle.Free; end; procedure TRestartNetworkHandle.LostServerFace; var LostServerSearchFace : TLostServerSearchFace; begin LostServerSearchFace := TLostServerSearchFace.Create; MySearchFileFace.AddChange( LostServerSearchFace ); end; procedure TRestartNetworkHandle.Update; begin ClearRedirectJob; ClearTransferFace; // Transfer Face ClearCsNetwork; // 断开 C/S 网络 ClearNetworkPcInfo; // 清除 Pc 连接信息 ClearNetworkPcFace; // 清空 网络 界面 ClearSearch; // 清空搜索 ClearRestore; // 清空恢复 ClearFileTransfer; // 传输离线 ClearFileShare; // 共享离线 // 禁止备份 LostServerFace; end; { TFindInternetSocket } constructor TFindInternetSocket.Create(_PortMapping: TPortMapping); begin PortMapping := _PortMapping; end; function TFindInternetSocket.FindInternetIp: Boolean; begin // 从 路由/网站 获取 Internet IP if PortMapping.IsPortMapable then Result := FindRouterInternetIp else Result := FindWebInternetIp; end; procedure TFindInternetSocket.FindInternetPort; begin if not PortMapping.IsPortMapable then InternetPort := PcInfo.LanPort else InternetPort := MyUpnpUtil.getUpnpPort( PcInfo.LanIp ); end; function TFindInternetSocket.FindRouterInternetIp: Boolean; begin InternetIp := PortMapping.getInternetIp; Result := InternetIp <> ''; end; function TFindInternetSocket.FindWebInternetIp: Boolean; var getIpHttp : TIdHTTP; httpStr : string; HttpList : TStringList; begin getIpHttp := TIdHTTP.Create(nil); getIpHttp.ConnectTimeout := 5000; getIpHttp.ReadTimeout := 5000; try httpStr := getIpHttp.Get( MyUrl.getIp ); HttpList := TStringList.Create; HttpList.Text := httpStr; InternetIp := HttpList[0]; HttpList.Free; Result := True; except Result := False; end; getIpHttp.Free; end; procedure TFindInternetSocket.SetInternetFace; var ShowIp, ShowPort : string; InternetSocketChangeInfo : TInternetSocketChangeInfo; begin // 可能本机未联网 if InternetIp = '' then begin ShowIp := Sign_NA; ShowPort := Sign_NA; end else begin ShowIp := InternetIp; ShowPort := InternetPort; end; // 显示到 Setting 界面 InternetSocketChangeInfo := TInternetSocketChangeInfo.Create( ShowIp, ShowPort ); MyNetworkFace.AddChange( InternetSocketChangeInfo ); end; procedure TFindInternetSocket.Update; var IsConnInternet : Boolean; begin InternetIp := ''; InternetPort := ''; IsConnInternet := False; if FindInternetIp then begin FindInternetPort; IsConnInternet := True; end; PcInfo.SetInternetInfo( InternetIp, InternetPort ); PcInfo.SetIsConnInternet( IsConnInternet ); SetInternetFace; end; { TAdvancePcInfo } constructor TAdvancePcInfo.Create(_PcID, _PcInfoMsgStr: string); begin PcID := _PcID; PcInfoMsgStr := _PcInfoMsgStr; end; { TStandardPcInfo } constructor TStandardPcInfo.Create(_PcID, _PcName: string); begin PcID := _PcID; PcName := _PcName; end; procedure TStandardPcInfo.SetInternetSocket(_InternetIp, _InternetPort: string); begin InternetIp := _InternetIp; InternetPort := _InternetPort; end; procedure TStandardPcInfo.SetLanSocket(_LanIp, _LanPort: string); begin LanIp := _LanIp; LanPort := _LanPort; end; { TFindStandardNetworkHttp } constructor TFindStandardNetworkHttp.Create(_CompanyName, _Password: string); begin CompanyName := _CompanyName; Password := _Password; end; function TFindStandardNetworkHttp.get: string; var PcID, PcName : string; LanIp, LanPort : string; InternetIp, InternetPort : string; CloudIDNumber : string; params : TStringlist; idhttp : TIdHTTP; begin // 本机信息 PcID := PcInfo.PcID; PcName := PcInfo.PcName; LanIp := PcInfo.LanIP; LanPort := PcInfo.LanPort; InternetIp := PcInfo.InternetIp; InternetPort := PcInfo.InternetPort; CloudIDNumber := CloudSafeSettingInfo.getCloudIDNumMD5; CloudIDNumber := MyEncrypt.EncodeMD5String( CloudIDNumber ); // 登录并获取在线 Pc 信息 params := TStringList.Create; params.Add( HttpReq_CompanyName + '=' + CompanyName ); params.Add( HttpReq_Password + '=' + Password ); params.Add( HttpReq_PcID + '=' + PcID ); params.Add( HttpReq_PcName + '=' + PcName ); params.Add( HttpReq_LanIp + '=' + LanIp ); params.Add( HttpReq_LanPort + '=' + LanPort ); params.Add( HttpReq_InternetIp + '=' + InternetIp ); params.Add( HttpReq_InternetPort + '=' + InternetPort ); params.Add( HttpReq_CloudIDNumber + '=' + CloudIDNumber ); idhttp := TIdHTTP.Create(nil); try Result := idhttp.Post( MyUrl.getGroupPcList + '?cmd=' + Cmd, params ); except Result := LoginResult_ConnError; end; idhttp.Free; params.free; end; procedure TFindStandardNetworkHttp.SetCmd(_Cmd: string); begin Cmd := _Cmd; end; { TStandardHearBetThread } procedure TStandardHearBetThread.CheckAccountPc; var Cmd : string; ServerNumber : Integer; FindStandardNetworkHttp : TFindStandardNetworkHttp; begin // 本机 非 Server if MasterInfo.MasterID <> PcInfo.PcID then Exit; // 已连接 if MyNetPcInfoReadUtil.ReadActivePcCount > 1 then Exit; // 是否第一次 if LastServerNumber = -1 then Cmd := Cmd_AddServerNumber else Cmd := Cmd_ReadServerNumber; // Login Number FindStandardNetworkHttp := TFindStandardNetworkHttp.Create( AccountName, Password ); FindStandardNetworkHttp.SetCmd( Cmd ); ServerNumber := StrToIntDef( FindStandardNetworkHttp.get, 0 ); FindStandardNetworkHttp.Free; // 第一次 if LastServerNumber = -1 then begin LastServerNumber := ServerNumber; Exit; end; // 与上次想相同 if LastServerNumber = ServerNumber then Exit; // 重启网络 MasterThread.RestartNetwork; end; constructor TStandardHearBetThread.Create; begin inherited Create( True ); LastServerNumber := -1; end; destructor TStandardHearBetThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TStandardHearBetThread.Execute; var StartHearBeat, StartCheckAccount : TDateTime; begin StartHearBeat := Now; StartCheckAccount := 0; while not Terminated do begin // 5 分钟 发送一次心跳 if MinutesBetween( Now, StartHearBeat ) >= 5 then begin SendHeartBeat; StartHearBeat := Now; end; // 10 秒钟 检测一次帐号 if ( SecondsBetween( Now, StartCheckAccount ) >= 10 ) or ( LastServerNumber = -1 ) then begin CheckAccountPc; StartCheckAccount := Now; end; if Terminated then Break; Sleep(100); end; inherited; end; procedure TStandardHearBetThread.SendHeartBeat; var FindStandardNetworkHttp : TFindStandardNetworkHttp; begin // 心跳 FindStandardNetworkHttp := TFindStandardNetworkHttp.Create( AccountName, Password ); FindStandardNetworkHttp.SetCmd( Cmd_HeartBeat ); FindStandardNetworkHttp.get; FindStandardNetworkHttp.Free; end; procedure TStandardHearBetThread.SetAccountInfo(_AccountName, _Password: string); begin AccountName := _AccountName; Password := _Password; end; { TStandardPcAddHanlde } procedure TStandardPcAddHanlde.AddNetworkPc; var NetPcAddHandle : TNetPcAddHandle; begin NetPcAddHandle := TNetPcAddHandle.Create( StandardPcInfo.PcID ); NetPcAddHandle.SetPcName( StandardPcInfo.PcName ); NetPcAddHandle.Update; NetPcAddHandle.Free; end; procedure TStandardPcAddHanlde.AddPingMsg; var InternetConnSendPingMsg : TInternetConnSendPingMsg; begin InternetConnSendPingMsg := TInternetConnSendPingMsg.Create; InternetConnSendPingMsg.SetRemotePcID( StandardPcInfo.PcID ); InternetConnSendPingMsg.SetRemoteLanSocket( StandardPcInfo.LanIp, StandardPcInfo.LanPort ); InternetConnSendPingMsg.SetRemoteInternetSocket( StandardPcInfo.InternetIp, StandardPcInfo.InternetPort ); MyMasterConn.AddChange( InternetConnSendPingMsg ); end; constructor TStandardPcAddHanlde.Create(_StandardPcInfo: TStandardPcInfo); begin StandardPcInfo := _StandardPcInfo; end; procedure TStandardPcAddHanlde.Update; begin AddNetworkPc; AddPingMsg; end; { TPortMappingThread } constructor TPortMappingThread.Create( _LanIp, _LanPort : string ); begin inherited Create( True ); LanIp := _LanIp; LanPort := _LanPort; InternetPort := MyUpnpUtil.getUpnpPort( LanIp ); end; destructor TPortMappingThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TPortMappingThread.Execute; var StartTime : TDateTime; begin while not Terminated do begin PortMapping.AddMapping( LanIp, LanPort, InternetPort ); StartTime := Now; while ( not Terminated ) and ( MinutesBetween( Now, StartTime ) < WaitTime_PortMap ) do Sleep(100); end; PortMapping.RemoveMapping( InternetPort ); inherited; end; procedure TPortMappingThread.SetPortMapping(_PortMapping: TPortMapping); begin PortMapping := _PortMapping; end; { TRestartNetworkThread } constructor TRestartNetworkThread.Create; begin inherited Create( True ); IsRestart := False; end; destructor TRestartNetworkThread.Destroy; begin Terminate; Resume; WaitFor; inherited; end; procedure TRestartNetworkThread.Execute; var LastShowTime : TDateTime; begin while not Terminated do begin LastShowTime := Now; while ( not Terminated ) and ( SecondsBetween( Now, LastShowTime ) < 1 ) do Sleep(100); if Terminated then Break; ShowRemainTime; end; inherited; end; procedure TRestartNetworkThread.RestartNetwork; begin MyNetworkControl.RestartNetwork; end; procedure TRestartNetworkThread.RunRestart; var PlNetworkConnShowInfo : TPlNetworkConnShowInfo; begin // 显示 PlNetworkConnShowInfo := TPlNetworkConnShowInfo.Create; MyNetworkFace.AddChange( PlNetworkConnShowInfo ); // 开始时间 StartTime := Now; IsRestart := True; // 显示剩余时间 ShowRemainTime; end; procedure TRestartNetworkThread.ShowRemainTime; var RemainTime : Integer; PlNetworkConnRemainInfo : TPlNetworkConnRemainInfo; begin if not IsRestart then Exit; RemainTime := 300 - SecondsBetween( Now, StartTime ); PlNetworkConnRemainInfo := TPlNetworkConnRemainInfo.Create( RemainTime ); MyNetworkFace.AddChange( PlNetworkConnRemainInfo ); // 重启网络 if RemainTime <= 0 then Synchronize( RestartNetwork ); end; procedure TRestartNetworkThread.StopRestart; var PlNetworkConnHideInfo : TPlNetworkConnHideInfo; begin // 隐藏 PlNetworkConnHideInfo := TPlNetworkConnHideInfo.Create; MyNetworkFace.AddChange( PlNetworkConnHideInfo ); IsRestart := False; end; end.
{----------------------------------------------------------------------------- Unit Name: RbProgressBar Purpose: gradient Progress bar Author/Copyright: NathanaŽl VERON - r.b.a.g@free.fr - http://r.b.a.g.free.fr Feel free to modify and improve source code, mail me (r.b.a.g@free.fr) if you make any big fix or improvement that can be included in the next versions. If you use the RbControls in your project please mention it or make a link to my website. =============================================== /* 13/11/2003 */ Modifications for D5 compatibility thx to Pierre Castelain -> www.micropage.fr.st /* 10/01/2004 */ Bug correction when setting negative min value -----------------------------------------------------------------------------} unit RbProgressBar; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, RbDrawCore, Buttons, Forms, ComCtrls; type TRbProgressBar = class(TRbCustomControl) private FGrBitmap: TBitmap; FDefaultFrom : TColor; FDefaultTo : TColor; FMax : integer; FMin : integer; FPosition: integer; FStep : integer; FBorderLines: TBorderLines; FBorderColor : TColor; FGradientType : TGradientType; FOrientation : TProgressBarOrientation; FShowText : boolean; FPercent : integer; FBorderWidth: integer; procedure SetBorderLines(const Value: TBorderLines); procedure SetBorderColor(const Value: TColor); procedure SetDefaultFrom(const Value: TColor); procedure SetDefaultTo(const Value: TColor); procedure SetGradientType(const Value: TGradientType); procedure SetMax(const Value: integer); procedure SetMin(const Value: integer); procedure SetOrientation(const Value: TProgressBarOrientation); procedure SetPosition(const Value: integer); procedure SetShowText(const Value: boolean); procedure SetStep(const Value: integer); procedure SetBorderWidth(const Value: integer); protected procedure Paint; override; procedure UpdateGradients; override; procedure EventResized; override; public property Percent: integer read FPercent; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure StepIt; published property Caption; property DefaultFrom: TColor read FDefaultFrom write SetDefaultFrom; property DefaultTo: TColor read FDefaultTo write SetDefaultTo; property Max : integer read FMax write SetMax; property Min : integer read FMin write SetMin; property Position : integer read FPosition write SetPosition; property Step : integer read FStep write SetStep; property BorderLines : TBorderLines read FBorderLines write SetBorderLines; property BorderColor : TColor read FBorderColor write SetBorderColor; property BorderWidth: integer read FBorderWidth write SetBorderWidth; property GradientType : TGradientType read FGradientType write SetGradientType; property Orientation : TProgressBarOrientation read FOrientation write SetOrientation; property ShowText : boolean read FShowText write SetShowText; end; procedure Register; implementation procedure Register; begin RegisterComponents('RbControls', [TRbProgressBar]); end; {--------------------------------------------- TRbProgressBar ---------------------------------------------} constructor TRbProgressBar.Create(AOwner: TComponent); begin inherited; FGrBitmap := TBitmap.Create; FGrBitmap.PixelFormat := pf24bit; ControlStyle := ControlStyle - [csSetCaption]; FDefaultFrom := $00B6977E; FDefaultTo := $00E0D2C9; FMax := 100; FMin := 0; FPosition := 0; FStep := 1; FBorderLines := [blTop, blBottom, blLeft, blRight]; FBorderColor := clGray; FGradientType := gtVertical; FOrientation := pbHorizontal; FShowText := true; TextShadow := false; FPercent := 0; FBorderWidth := 1; Caption := ''; Width := 150; Height := 16; end; destructor TRbProgressBar.Destroy; begin FGrBitmap.Free; inherited; end; procedure TRbProgressBar.EventResized; begin inherited; UpdateGradients; end; procedure TRbProgressBar.Paint; var R: TRect; BW : integer; Txt: string; begin inherited; R := Canvas.ClipRect; //Calculate the extend of the rect if Orientation = pbHorizontal then R.Right := (R.Right - R.Left) * Percent div 100 else R.Top := (R.Bottom - R.Top) * (100 - Percent) div 100; if BorderLines = [] then BW := 0 else BW := -1; InflateRect(R, BW - BorderWidth, BW - BorderWidth); if Percent > 0 then Canvas.CopyRect(R, FGrBitmap.Canvas, R); //Draw Percent R := Canvas.ClipRect; if ShowText or ShowCaption then begin SetBkMode(Canvas.Handle, TRANSPARENT); Canvas.Font.Assign(Font); if ShowText then Txt := IntToStr(Percent) + '%'; if (Caption <> '') and ShowCaption then if ShowText then Txt := Caption + ' ' + Txt else Txt := Caption; DoDrawText(Canvas, Txt, Font, true, false, R, DT_CENTER or DT_VCENTER or DT_SINGLELINE, TextShadow, clWhite); end; //Draw border lines Canvas.Pen.Color := BorderColor; if blTop in BorderLines then begin Canvas.MoveTo(0, 0); Canvas.LineTo(R.Right, R.Top); end; if blBottom in BorderLines then begin Canvas.MoveTo(0, R.Bottom - 1); Canvas.LineTo(R.Right, R.Bottom - 1); end; if blLeft in BorderLines then begin Canvas.MoveTo(0, 0); Canvas.LineTo(R.Left, R.Bottom); end; if blRight in BorderLines then begin Canvas.MoveTo(R.Right - 1, R.Top); Canvas.LineTo(R.Right - 1, R.Bottom); end; end; procedure TRbProgressBar.SetBorderLines(const Value: TBorderLines); begin if FBorderLines <> Value then begin FBorderLines := Value; Invalidate; end; end; procedure TRbProgressBar.SetBorderColor(const Value: TColor); begin if FBorderColor <> Value then begin FBorderColor := Value; Invalidate; end; end; procedure TRbProgressBar.SetBorderWidth(const Value: integer); begin if (FBorderWidth <> Value) and (Value >= 0) and (Value < Height div 2) then begin FBorderWidth := Value; Invalidate; end; end; procedure TRbProgressBar.SetDefaultFrom(const Value: TColor); begin if FDefaultFrom <> Value then begin FDefaultFrom := Value; UpdateGradients; end; end; procedure TRbProgressBar.SetDefaultTo(const Value: TColor); begin if FDefaultTo <> Value then begin FDefaultTo := Value; UpdateGradients; end; end; procedure TRbProgressBar.SetGradientType(const Value: TGradientType); begin if FGradientType <> Value then begin FGradientType := Value; UpdateGradients; end; end; procedure TRbProgressBar.SetMax(const Value: integer); begin if ((FMax <> Value) and (Value > FMin)) or (csLoading in ComponentState) then begin FMax := Value; if Position > Max then Position := Max; SetPosition(Position); Invalidate; end; end; procedure TRbProgressBar.SetMin(const Value: integer); begin if ((FMin <> Value) and (Value < FMax)) or (csLoading in ComponentState) then begin FMin := Value; if Position < Min then Position := Min; SetPosition(Position); Invalidate; end; end; procedure TRbProgressBar.SetOrientation( const Value: TProgressBarOrientation); begin if FOrientation <> Value then begin FOrientation := Value; Invalidate; end; end; procedure TRbProgressBar.SetPosition(const Value: integer); begin FPosition := Value; if FPosition < Min then Position := Min; if FPosition > Max then Position := Max; if Min <> Max then FPercent := Round(Abs((Position - Min) / (Max - Min)) * 100) else FPercent := 0; Invalidate; end; procedure TRbProgressBar.SetShowText(const Value: boolean); begin if FShowText <> Value then begin FShowText := Value; Invalidate; end; end; procedure TRbProgressBar.SetStep(const Value: integer); begin FStep := Value; end; procedure TRbProgressBar.StepIt; begin Position := Position + Step; end; procedure TRbProgressBar.UpdateGradients; begin FGrBitmap.Width := Width; FGrBitmap.Height := Height; DoBitmapGradient(FGrBitmap, FGrBitmap.Canvas.ClipRect, DefaultFrom, DefaultTo, GradientType, 0); Invalidate; end; end.
unit uFrmModal; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmRoot, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, ActnList, StdCtrls, cxButtons, ExtCtrls, HJYConsts, superobject, cxControls, DB; type // 用来处理保存完数据后的刷新操作, // 如:管理窗体调用明细编辑窗体时,明细窗体保存后触发的操作,有管理窗体传入 TAfterSave = procedure(ALocate: Boolean = False; AValue: string = '') of object; TFrmModal = class(TFrmRoot) pnlClient: TPanel; pnlBottom: TPanel; btnOk: TcxButton; btnCancel: TcxButton; bvl1: TBevel; actlst1: TActionList; actExit: TAction; procedure actExitExecute(Sender: TObject); private FDataSet: TDataSet; FOperKind: TOperKind; FOnAfterSave: TAfterSave; protected FKeyId: string; procedure SetOperKind(const AOperKind: TOperKind); virtual; procedure SetDataSet(const ADataSet: TDataSet); virtual; function IsEditMode: Boolean; virtual; public property OperKind: TOperKind read FOperKind write SetOperKind; property DataSet: TDataSet read FDataSet write SetDataSet; property OnAfterSave: TAfterSave read FOnAfterSave write FOnAfterSave; public class function Execute(AOperKind: TOperKind; ADataSet: TDataSet = nil; AfterSave: TAfterSave = nil): Boolean; end; var FrmModal: TFrmModal; implementation {$R *.dfm} uses HJYDataProviders; procedure TFrmModal.actExitExecute(Sender: TObject); begin Close; end; class function TFrmModal.Execute(AOperKind: TOperKind; ADataSet: TDataSet; AfterSave: TAfterSave): Boolean; begin with Self.Create(nil) do try OperKind := AOperKind; DataSet := ADataSet; OnAfterSave := AfterSave; Result := ShowModal = mrOk; finally Free; end; end; function TFrmModal.IsEditMode: Boolean; begin Result := FOperKind = okUpdate; end; procedure TFrmModal.SetDataSet(const ADataSet: TDataSet); begin FDataSet := ADataSet; end; procedure TFrmModal.SetOperKind(const AOperKind: TOperKind); begin FOperKind := AOperKind; end; end.
unit DetailFrameUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StorageUnit; type { TDetailFrame } TDetailFrame = class(TFrame, IRememberable) private procedure CMFontChanged(var Msg: TMessage); message CM_FONTCHANGED; protected { IRememberable } procedure SaveState(Storage: TStorage; const SectionName, Prefix: string); procedure LoadState(Storage: TStorage; const SectionName, Prefix: string); protected FSavedActiveControl: TWinControl; FID: Integer; procedure SetTitle(const Title: string); procedure FontChanged; virtual; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure CloseFrame; procedure Initialize(AID: Integer); virtual; property ID: Integer read FID; end; implementation {$R *.dfm} { TDetailFrame } procedure TDetailFrame.AfterConstruction; begin inherited AfterConstruction; // if Owner.Owner <> nil then StorageUnit.LoadState(Self, Owner.Owner.Name, 'FRAME#'+Name); end; procedure TDetailFrame.BeforeDestruction; begin // if Owner.Owner <> nil then StorageUnit.SaveState(Self, Owner.Owner.Name, 'FRAME#'+Name); inherited BeforeDestruction; end; procedure TDetailFrame.Initialize(AID: Integer); begin FID := AID; end; { IRememberable } procedure TDetailFrame.SaveState(Storage: TStorage; const SectionName, Prefix: string); begin // SaveChildState(Self, SectionName, Prefix + Name + '.'); end; procedure TDetailFrame.LoadState(Storage: TStorage; const SectionName, Prefix: string); begin // LoadChildState(Self, SectionName, Prefix + Name + '.'); end; type TXWinControl = class(TWinControl) end; procedure TDetailFrame.SetTitle(const Title: string); begin TXWinControl(Parent).Text := Title; end; procedure TDetailFrame.CloseFrame; begin if Parent <> nil then PostMessage(Parent.Handle, CM_RELEASE, 0, 0); end; procedure TDetailFrame.CMFontChanged(var Msg: TMessage); begin inherited; if not (csLoading in ComponentState) and HandleAllocated then FontChanged; end; procedure TDetailFrame.FontChanged; begin { do nothing } end; end.
unit wsADO; {$I wsdefs.inc} interface uses SysUtils,DBClient, Classes, Dialogs, {$IFDEF DELPHI6_LVL} Variants, {$ENDIF} wsDB, DB, ADODB; type TWorkflowADODB = class(TCustomWorkflowDB) private FConnection: TADOConnection; procedure SetConnection(const Value: TADOConnection); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function DoCreateQuery(SQL: string): TDataset; override; procedure DoExecuteQuery(Dataset: TDataset); override; procedure DoAssignSQLParams(Dataset: TDataset; AParams: TParams); override; function BlobFieldToString(AField: TField): string; override; public constructor Create(AOwner: TComponent); override; published property Connection: TADOConnection read FConnection write SetConnection; end; procedure Register; implementation uses wsRes, ServerMethodsUnit1; function Max(A, B: Integer): Integer; begin if A > B then Result := A else Result := B; end; { TWorkflowADODB } constructor TWorkflowADODB.Create(AOwner: TComponent); begin inherited Create(AOwner); DestroyQueries := true; end; function TWorkflowADODB.BlobFieldToString(AField: TField): string; var BlobField: TBlobField; StrStream: TStringStream; c: integer; IsOleStr: boolean; s: string; begin if AField is TBlobField then begin BlobField := TBlobField(AField); StrStream := TStringStream.Create(''); try BlobField.SaveToStream(StrStream); StrStream.Position := 0; s := StrStream.ReadString(StrStream.Size); finally StrStream.Free; end; end else s := AField.AsString; {workaround to "tell" if the string is an Ole string} IsOleStr := true; c := 2; while c < length(s) do begin if s[c] <> chr(0) then begin IsOleStr := false; break; end; c := c + 2; end; {remove #0 characters} if IsOleStr then begin result := ''; for c := 1 to Length(s) do if Odd(c) then result := result + s[c]; end else result := s; end; procedure TWorkflowADODB.DoExecuteQuery(Dataset: TDataset); begin try TClientDataSet(Dataset).Execute; Except end; end; function TWorkflowADODB.DoCreateQuery(SQL: string): TDataset; var Q: TClientDataSet; sm:ServerMethodsUnit1.Tsm; begin { Q := TADOQuery.Create(nil); Q.Connection := FConnection; Q.Parameters.Clear; Q.SQL.Text := SQL;} result :=SM.GeraDS(SQL,'','D'); end; procedure TWorkflowADODB.DoAssignSQLParams(Dataset: TDataset; AParams: TParams); var Q: TClientDataSet; c: integer; AParam: TParam; begin try Q := TClientDataSet(Dataset); // Q.Parameters.ParseSQL(Q.SQL.Text, true); //Q.Parameters.Assign(Params); for c := 0 to Q.Params.Count - 1 do begin AParam := AParams.FindParam(Q.Params[c].Name); if AParam = nil then begin wsDBError(Format(_str(SErrorParamNotFound), [Q.Params[c].Name])); end; Q.Params[c].DataType := AParam.DataType; // Q.Params[c]. := pdInput; Q.Params[c].Value := AParam.Value; if Q.Params[c].DataType in [ftString] then Q.Params[c].Size := Max(1, Length(VarToSTr(Q.Params[c].Value))); end; Except end; end; procedure TWorkflowADODB.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (AComponent = FConnection) then FConnection := nil; inherited Notification(AComponent, Operation); end; procedure TWorkflowADODB.SetConnection(const Value: TADOConnection); begin if (FConnection <> Value) then begin FConnection := Value; if Value <> nil then Value.FreeNotification(Self); end; end; procedure Register; begin RegisterComponents('Workflow Studio', [TWorkflowADODB]); end; end.
unit IdHTTPCUS; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IdHTTP; type { TIdHTTPCUS } TIdHTTPCUS = class(TIdHTTP) public function Delete(AURL: string): string; overload; procedure Delete(AURL: string; AResponseContent: TStream); overload; end; implementation { TIdHTTPCUS } function TIdHTTPCUS.Delete(AURL: string): string; var LResponse: TStringStream; begin LResponse := TStringStream.Create(''); {do not localize} try Delete(AURL, LResponse); finally Result := LResponse.DataString; FreeAndNil(LResponse); end; end; procedure TIdHTTPCUS.Delete(AURL: string; AResponseContent: TStream); begin Assert(AResponseContent <> nil); DoRequest(Id_HTTPMethodDelete, AURL, nil, AResponseContent, []); end; end.
unit SeismPlanFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Ex_Grid, LicenseZone, GRRObligation, ObligationToolsFrame; type TfrmSeismPlan = class(TFrame) frmObligationTools1: TfrmObligationTools; procedure grdvwSeismPlanGetCellText(Sender: TObject; Cell: TGridCell; var Value: String); procedure grdvwSeismPlanGetCellColors(Sender: TObject; Cell: TGridCell; Canvas: TCanvas); procedure grdvwSeismPlanEditAcceptKey(Sender: TObject; Cell: TGridCell; Key: Char; var Accept: Boolean); procedure grdvwSeismPlanSetEditText(Sender: TObject; Cell: TGridCell; var Value: String); procedure grdvwSeismPlanEditCloseUp(Sender: TObject; Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean); procedure grdvwSeismPlanChange(Sender: TObject; Cell: TGridCell; Selected: Boolean); private { Private declarations } FLicenseZone: TLicenseZone; FSaved: Boolean; procedure SetLicenseZone(const Value: TLicenseZone); procedure LoadSeismicObligations; function GetCurrentObligation: TObligation; procedure ObligationsChanged(Sender: TObject); public { Public declarations } property Saved: Boolean read FSaved; property LicenseZone: TLicenseZone read FLicenseZone write SetLicenseZone; property CurrentObligation: TObligation read GetCurrentObligation; procedure RefreshSeismicObligations; procedure Save; procedure Cancel; constructor Create(AOwner: TComponent); override; end; implementation uses Facade, BaseObjects, BaseConsts; {$R *.dfm} { TfrmSeismPlan } procedure TfrmSeismPlan.Cancel; begin LicenseZone.License.ClearSeismicObligations; end; constructor TfrmSeismPlan.Create(AOwner: TComponent); begin inherited; FSaved := true; frmObligationTools1.OnObligationAdded := ObligationsChanged; frmObligationTools1.OnObligationRemoved := ObligationsChanged; end; function TfrmSeismPlan.GetCurrentObligation: TObligation; begin try Result := FLicenseZone.AllSeismicObligations.Items[grdvwSeismPlan.Row] except Result := nil; end; end; procedure TfrmSeismPlan.LoadSeismicObligations; begin TMainFacade.GetInstance.AllSeisWorkTypes.MakeList(grdvwSeismPlan.Columns[0].PickList, False, true); frmObligationTools1.Obligations := FLicenseZone.License.AllSeismicObligations; RefreshSeismicObligations; end; procedure TfrmSeismPlan.ObligationsChanged(Sender: TObject); begin grdvwSeismPlan.Rows.Count := LicenseZone.License.AllSeismicObligations.Count; FSaved := false; grdvwSeismPlan.Refresh; end; procedure TfrmSeismPlan.Save; begin LicenseZone.License.AllSeismicObligations.Update(nil); end; procedure TfrmSeismPlan.SetLicenseZone(const Value: TLicenseZone); begin if FLicenseZone <> Value then begin FLicenseZone := Value; LoadSeismicObligations; FSaved := True; end; end; procedure TfrmSeismPlan.grdvwSeismPlanGetCellText(Sender: TObject; Cell: TGridCell; var Value: String); begin with LicenseZone.AllSeismicObligations.Items[Cell.Row] do case Cell.Col of 0: if Assigned(SeisWorkType) then Value := SeisWorkType.List(loBrief); 1: Value := FloatToStr(Volume); 2: begin if Assigned(SeisWorkType) then case SeisWorkType.ID of SEISWORK_TYPE_2D: Value := 'ïîã. ì'; SEISWORK_TYPE_3D: Value := 'êâ. êì' else Value := ''; end; end; 3: if StartDate <> 0 then Value := DateToStr(StartDate) else Value := ''; 4: if FinishDate <> 0 then Value := DateToStr(FinishDate) else Value := ''; 5: Value := Comment; 6: Value := DoneString; end; end; procedure TfrmSeismPlan.grdvwSeismPlanGetCellColors(Sender: TObject; Cell: TGridCell; Canvas: TCanvas); var o: TObligation; begin o := LicenseZone.License.AllSeismicObligations.Items[Cell.Row]; if (o.FinishDate > 0) and (o.FinishDate <= TMainFacade.GetInstance.ActiveVersion.VersionFinishDate) then begin if o.Done then Canvas.Brush.Color := $00C8F9E3 else Canvas.Brush.Color := $00DFE7FF; end else if o.Done then Canvas.Brush.Color := $00C8F9E3 end; procedure TfrmSeismPlan.grdvwSeismPlanEditAcceptKey(Sender: TObject; Cell: TGridCell; Key: Char; var Accept: Boolean); begin Accept := not(Cell.Col in [2, 6]); if Accept then begin // well number if (Cell.Col in [1, 3, 4]) then Accept := (Pos(Key, '0123456789.') > 0); end; end; procedure TfrmSeismPlan.grdvwSeismPlanSetEditText(Sender: TObject; Cell: TGridCell; var Value: String); begin Value := trim(Value); case Cell.Col of 1: begin if Value <> '' then LicenseZone.License.AllSeismicObligations.Items[Cell.Row].Volume := StrToFloat(Value) else LicenseZone.License.AllSeismicObligations.Items[Cell.Row].StartDate := 0; FSaved := false; end; 3: begin if Value <> '' then LicenseZone.License.AllSeismicObligations.Items[Cell.Row].StartDate := StrToDateTime(Value) else LicenseZone.License.AllSeismicObligations.Items[Cell.Row].StartDate := 0; grdvwSeismPlan.Refresh; FSaved := false; end; 4: begin if Value <> '' then LicenseZone.License.AllSeismicObligations.Items[Cell.Row].FinishDate := StrToDateTime(Value) else LicenseZone.License.AllSeismicObligations.Items[Cell.Row].FinishDate := 0; FSaved := false; grdvwSeismPlan.Refresh; end; 5: begin LicenseZone.License.AllSeismicObligations.Items[Cell.Row].Comment := Value; FSaved := false; end; end; end; procedure TfrmSeismPlan.grdvwSeismPlanEditCloseUp(Sender: TObject; Cell: TGridCell; ItemIndex: Integer; var Accept: Boolean); begin if ItemIndex > -1 then begin if Cell.Col = 0 then begin LicenseZone.License.AllSeismicObligations.Items[Cell.Row].SeisWorkType := TMainFacade.GetInstance.AllSeisWorkTypes.Items[ItemIndex]; FSaved := false; end; end; end; procedure TfrmSeismPlan.grdvwSeismPlanChange(Sender: TObject; Cell: TGridCell; Selected: Boolean); begin frmObligationTools1.SelectedObligation := CurrentObligation; end; procedure TfrmSeismPlan.RefreshSeismicObligations; begin grdvwSeismPlan.Rows.Count := FLicenseZone.License.AllSeismicObligations.Count; grdvwSeismPlan.Refresh; end; end.
{$reference 'System.Windows.Forms.dll'} uses System.Windows.Forms; function genlaw(s: string): string; begin var sb := new StringBuilder(); var underlvl := $'_{s.Where(x -> char.IsUpper(x)).JoinToString().ToLower}l'; sb.AppendLine($' #region {s}Law'); sb.AppendLine($' public enum {s}Law'); sb.AppendLine( ' {'); sb.AppendLine($' All,'); sb.AppendLine( ' }'); sb.AppendLine(); sb.AppendLine($' public const {s}Law Default{s}RandomLaw = {s}Law.All;'); sb.AppendLine($' static Dictionary<{s}Law, RandomationLaw<{s}>.PercentLaw> {s.ToLower}law = new Dictionary<{s}Law, RandomationLaw<{s}>.PercentLaw>();'); sb.AppendLine($' private static {s}Law {underlvl} = Default{s}RandomLaw;'); sb.AppendLine($' public static {s}Law Current{s}RandomLaw'); sb.AppendLine( ' {'); sb.AppendLine($' get => {underlvl};'); sb.AppendLine($' set => {underlvl} = value;'); sb.AppendLine( ' }'); sb.AppendLine($' internal static Enum RandomLaw_{s}(Random rnd) => {s.ToLower}law[{underlvl}].Get(rnd.NextDouble());'); sb.AppendLine($' #endregion'); Result := sb.ToString(); end; function genxml(s: string): string; begin var sb := new StringBuilder(); sb.AppendLine($' <{s}RandomLaws>'); sb.AppendLine($' <{s}RandomLaw law="All">'); sb.AppendLine($' <{s}Percent chance="0.1" value="Child"/>'); sb.AppendLine($' </{s}RandomLaw>'); sb.AppendLine($' </{s}RandomLaws>'); Result := sb.ToString(); end; function genxmlread(s: string): string; begin var sb := new StringBuilder(); sb.AppendLine($' case "{s}RandomLaws":'); sb.AppendLine( ' {'); sb.AppendLine($' foreach (XmlElement rndlaw in rndlaws)'); sb.AppendLine( ' {'); sb.AppendLine($' var value = rndlaw.GetAttribute("law").ToEnum<{s}Law>();'); sb.AppendLine($' var x = new RandomationLaw<{s}>.PercentLaw();'); sb.AppendLine($' foreach (XmlElement val in rndlaw)'); sb.AppendLine( ' {'); sb.AppendLine($' x.Add((val.GetAttribute("chance").ToDouble(), val.GetAttribute("value").ToEnum<{s}>()));'); sb.AppendLine( ' }'); sb.AppendLine($' x.Init();'); sb.AppendLine($' {s.ToLower}law.Add(value, x);'); sb.AppendLine( ' }'); sb.AppendLine( ' }'); sb.AppendLine($' break;'); Result := sb.ToString(); end; begin var s := 'EyesColor'; Println('Defaults.cs {class Defaults}:'); Println('----------------------------------------------------------------'); Println(genlaw(s)); Println('----------------------------------------------------------------'); Println('Defaults.cs {void ReadXmlFile}:'); Println('----------------------------------------------------------------'); Println(genxmlread(s)); Println('----------------------------------------------------------------'); Println('Defaultx.xml:'); Println('----------------------------------------------------------------'); Println(genxml(s)); Println('----------------------------------------------------------------'); Println('RandomationLaw.cs {RandomationLawHelper}:'); Println('----------------------------------------------------------------'); Println($'add(CachedEnum<Archetypes.{s}>.Type, Defaults.RandomLaw_{s});'); Println('----------------------------------------------------------------'); end.
(* MIT License Copyright (c) 2016 Ean Smith Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *) (******************************************************************************* Purpose: Sample project for lazarus demonstrating a use case for the POS library ---------------------------------------------------- dd.mm.yy - initials - note ---------------------------------------------------- 09.19.16 - ems - created *******************************************************************************) unit uMain_Sample_1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, WIZ.POS; type { TMain } { TTestStuff } TTestStuff = class(TCustomStuff) strict private //a buffer to hold some text FTestBuffer : TStringList; protected function DoClassify(out Error: String): Boolean; override; public procedure AddSomeTestText(Const ATest:String); constructor Create; override; destructor Destroy; override; end; TMain = class(TForm) Btn_Add: TButton; Btn_Classify: TButton; Mem_Add: TMemo; Mem_Classify: TMemo; procedure Btn_AddClick(Sender: TObject); procedure Btn_ClassifyClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { private declarations } FTestStuff : TTestStuff; public { public declarations } end; var Main: TMain; implementation {$R *.lfm} { TMain } procedure TMain.Btn_AddClick(Sender: TObject); var I:Integer; begin for I := 0 to Pred(Mem_Add.Lines.Count) do FTestStuff.AddSomeTestText(Mem_Add.Lines[i]); end; procedure TMain.Btn_ClassifyClick(Sender: TObject); var LError: String; begin if not FTestStuff.Classify(LError) then Mem_Classify.Text:=LError else Mem_Classify.Text:=BoolToStr(FTestStuff.IsClassified,True); end; procedure TMain.FormCreate(Sender: TObject); begin FTestStuff:=TTestStuff.Create; end; procedure TMain.FormDestroy(Sender: TObject); begin FTestStuff.Free; end; { TTestStuff } function TTestStuff.DoClassify(out Error: String): Boolean; begin Result:=False; if FTestBuffer.Count<1 then Begin Error:='the buffer has no text to classify with'; Exit; end; while FTestBuffer.Count>0 do Begin if not AddAttribute(FTestBuffer[0],Error) then Exit; FTestBuffer.Delete(0); end; Result:=True; end; procedure TTestStuff.AddSomeTestText(const ATest: String); begin IsClassified:=False; FTestBuffer.Add(ATest); end; constructor TTestStuff.Create; begin inherited Create; FTestBuffer:=TStringList.Create; end; destructor TTestStuff.Destroy; begin FTestBuffer.Free; inherited Destroy; end; end.
{***************************************************************************} { } { Модуль: Шаблон динамических массивов } { Описание: Для организации стека,польской записи,массива данных} { Автор: Зверинцев Дмитрий } { } {***************************************************************************} unit DynArray; interface type TArray<T> = class strict private arr: array of T; arr_len:integer; function GetT(i: integer): T; procedure SetT(i: integer; const Value: T); public procedure Add(const Value:T); procedure Del; procedure SetLen(length:integer); procedure Insert(element:T;pos:integer); property Element[i:integer]:T read GetT write SetT;default; property Len:integer read arr_len; constructor Create(); destructor Destroy;override; end; implementation procedure TArray<T>.Add(const Value: T); begin inc(arr_len); SetLength(arr,arr_len); arr[arr_len-1]:=Value end; constructor TArray<T>.Create; begin arr_len:=0; arr:=nil; end; procedure TArray<T>.Del; begin dec(arr_len); SetLength(arr,arr_len) end; destructor TArray<T>.Destroy; begin arr_len:=0; arr:=nil; end; procedure TArray<T>.Insert(element:T;pos:integer); var i:integer; tmp:array of T; begin SetLength(tmp,arr_len); for i:=0 to arr_len-1 do tmp[i]:=arr[i]; SetLength(arr,arr_len+1);inc(arr_len); arr[pos]:=element; i:=0; while (i <= (arr_len-1)) do begin if (i>pos)then arr[i]:=tmp[i-1]; inc(i) end; end; function TArray<T>.GetT(i: integer): T; begin result:=arr[i]; end; procedure TArray<T>.SetT(i: integer; const Value: T); begin arr[i]:=Value; end; procedure TArray<T>.SetLen(length: integer); begin SetLength(arr,length); arr_len:=length; end; end. {type TArray = class private type val = integer; pval = ^val; private arr: pointer; arr_len:integer; function GetT(i: integer): val;inline; procedure SetT(i: integer; const Value: val);inline; public procedure SetLen(length:integer); property Element[i:integer]:val read GetT write SetT;default; property Len:integer read arr_len; constructor Create(); destructor Destroy;override; end; } { constructor TArray.Create; begin inherited; arr_len:=0; arr:=nil; end; destructor TArray.Destroy; begin FreeMem(arr,arr_len*sizeof(val)); inherited; end; function TArray.GetT(i: integer): val; begin result:=pval(integer(arr)+(i*sizeof(val)))^; end; procedure TArray.SetT(i: integer; const Value: val); begin pval(integer(arr)+(i*sizeof(val)))^:=Value; end; procedure TArray.SetLen(length: integer); var t:pointer; begin if (length=arr_len)then exit; if length<=0 then begin FreeMem(arr,arr_len*sizeof(val)); arr_len:=0;arr:=nil; exit end else begin GetMem(t,length*sizeof(val)); if ((length>0)and(length>arr_len))and(arr_len>0) then Move(arr^,t^,arr_len*sizeof(val)) else if ((length>0)and (length<arr_len))and(arr_len>0) then Move(arr^,t^,length*sizeof(val)); if arr<>nil then FreeMem(arr,arr_len*sizeof(val)); arr:=t; arr_len:=length; end end; }
unit dao.Versao; interface uses UConstantes, classes.ScriptDDL, model.Versao, System.StrUtils, System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FireDAC.Comp.Client, FireDAC.Comp.DataSet; type TVersaoDao = class(TObject) strict private class var aInstance : TVersaoDao; private aDDL : TScriptDDL; aModel : TVersao; constructor Create(); public property Model : TVersao read aModel write aModel; procedure Load(); procedure Delete(); procedure Insert(); class function GetInstance : TVersaoDao; end; implementation uses UDM; { TVersaoDao } constructor TVersaoDao.Create; begin inherited Create; aDDL := TScriptDDL.GetInstance; aModel := TVersao.GetInstance; end; procedure TVersaoDao.Delete(); var aSQL : TStringList; aRetorno : Boolean; begin aRetorno := False; aSQL := TStringList.Create; try aSQL.BeginUpdate; aSQL.Add('Delete from ' + aDDL.getTableNameVersao); aSQL.EndUpdate; with DM, qrySQL do begin qrySQL.Close; qrySQL.SQL.Text := aSQL.Text; qrySQL.ExecSQL; end; finally aSQL.Free; end; end; class function TVersaoDao.GetInstance: TVersaoDao; begin if not Assigned(aInstance) then aInstance := TVersaoDao.Create(); Result := aInstance; end; procedure TVersaoDao.Insert(); var aSQL : TStringList; begin aSQL := TStringList.Create; try aSQL.BeginUpdate; aSQL.Add('Insert Into ' + aDDL.getTableNameVersao + '('); aSQL.Add(' cd_versao '); aSQL.Add(' , ds_versao '); aSQL.Add(' , dt_versao '); aSQL.Add(') values ( '); aSQL.Add(' :cd_versao '); aSQL.Add(' , :ds_versao '); aSQL.Add(' , :dt_versao '); aSQL.Add(')'); aSQL.EndUpdate; with DM, qrySQL do begin qrySQL.Close; qrySQL.SQL.Text := aSQL.Text; if (aModel.Codigo = 0) then begin aModel.Codigo := VERSION_CODE; aModel.Descricao := VERSION_NAME; end; ParamByName('cd_versao').AsInteger := aModel.Codigo; ParamByName('ds_versao').AsString := aModel.Descricao; ParamByName('dt_versao').AsDateTime := aModel.Data; ExecSQL; end; finally aSQL.Free; end; end; procedure TVersaoDao.Load; var aSQL : TStringList; aRetorno : Boolean; begin aRetorno := False; aSQL := TStringList.Create; try aSQL.BeginUpdate; aSQL.Add('Select * '); aSQL.Add('from ' + aDDL.getTableNameVersao); aSQL.EndUpdate; with DM, qrySQL do begin qrySQL.Close; qrySQL.SQL.Text := aSQL.Text; if qrySQL.OpenOrExecute then begin aRetorno := (qrySQL.RecordCount > 0); if aRetorno then begin Model.Codigo := FieldByName('cd_versao').AsInteger; Model.Descricao := FieldByName('ds_versao').AsString; Model.Data := FieldByName('dt_versao').AsDateTime; end else begin Model.Codigo := 0; Model.Descricao := EmptyStr; Model.Data := Date; end; end; qrySQL.Close; end; finally aSQL.Free; end; end; end.
unit BaseComponentTest; interface uses TestFramework, BaseComponent, BaseObjects, Classes; type TBaseComponentImplementorTest = class(TTestCase) protected FTestingComp: TBaseComponentImplementor ; procedure Setup; override; procedure TearDown; override; public property TestingComp: TBaseComponentImplementor read FTestingComp; published procedure TestFill; virtual; end; TRecordingComponentImplementorTest = class(TBaseComponentImplementorTest) private FCurrentObject: TIDObject; protected FPoster: TDataPoster; function CallAddition: TIDObject; virtual; function CallUpdate: TIDObject; virtual; procedure CheckValidMaterialization(AObject: TIDObject); virtual; public property Poster: TDataPoster read FPoster; procedure TestAdd; virtual; procedure TestUpdate; virtual; procedure TestDelete; virtual; published property CurrentObject: TIDObject read FCurrentObject; procedure TestRecordingCycle; virtual; procedure TestFill; override; end; TGUIRecordingComponentImplementorTest = class(TRecordingComponentImplementorTest) public function GetListIndexByObject(AObject: TIDObject): integer; virtual; function GetListCount: integer; virtual; function GetObjectByIndex(AIndex: integer): TObject; virtual; public procedure TestAdd; override; procedure TestUpdate; override; procedure TestDelete; override; procedure TestFill; override; published end; implementation uses SysUtils, DB, Facade, DBGate; { TBaseComponentImplementorTest } procedure TBaseComponentImplementorTest.Setup; begin inherited; end; procedure TBaseComponentImplementorTest.TearDown; begin inherited; end; procedure TBaseComponentImplementorTest.TestFill; begin Check(False, 'Тест не реализован'); end; { TRecordingComponentImplementorTest } function TRecordingComponentImplementorTest.CallAddition: TIDObject; begin Result := nil; end; function TRecordingComponentImplementorTest.CallUpdate: TIDObject; begin Result := nil; end; procedure TRecordingComponentImplementorTest.CheckValidMaterialization(AObject: TIDObject); var iRecordCount: integer; begin // проверяем, записались ли все поля iRecordCount := Poster.GetFromDB(Poster.KeyFieldNames + ' = ' + IntToStr(AObject.ID), nil); Check(iRecordCount = 1, 'Ошибка добавления/редакции. Не найдено строки, соответствующей введенному объекту'); end; procedure TRecordingComponentImplementorTest.TestAdd; var iInputObjectCount, iRecordCount: integer; ds: TDataSet; begin Check(Assigned(TestingComp), 'Ошибка добавления. Для теста не задан тестируемый компонент, задайте непустое значение свойства TestingComp'); Check(Assigned(Poster), 'Ошибка добавления. Не задан материализатор для компонента, задайте непустое значение свойства Poster'); // восстанавливаем материализатор в состоянии, соответствующем коллекции Poster.RestoreState(IBaseComponent(TestingComp).InputObjects.PosterState); iInputObjectCount := IBaseComponent(TestingComp).InputObjects.Count; ds := TMainFacade.GetInstance.DBGates.ItemByPoster[Poster as TImplementedDataPoster]; iRecordCount := ds.RecordCount; FCurrentObject := CallAddition; Check(Assigned(FCurrentObject), 'Ошибка добавления. Объект не был возвращен для дальнейшей работы'); Check(ds.RecordCount - iRecordCount = 1, 'Ошибка добавления. В базу данных не была добавлена строка, соответсвтующая элементу'); Check(FCurrentObject.ID > 0, 'Ошибка добавления. Объект не получил верного идентификатора'); Check(IBaseComponent(TestingComp).InputObjects.Count - iInputObjectCount = 1, 'Ошибка добавления. Во входную коллекцию не добавлен элемент'); CheckValidMaterialization(FCurrentObject); end; procedure TRecordingComponentImplementorTest.TestDelete; var iInputObjectCount, iRecordCount, iID: integer; ds: TDataSet; begin // проверяем предусловия Check(Assigned(CurrentObject), 'Ошибка удаления. Не задан удаляемый объект'); Check(Assigned(TestingComp), 'Ошибка удаления. Для теста не задан тестируемый компонент, задайте непустое значение свойства TestingComp'); Check(Assigned(Poster), 'Ошибка удаления. Не задан материализатор для компонента, задайте непустое значение свойства Poster'); // восстанавливаем материализатор в состоянии, соответствующем коллекции Poster.RestoreState(IBaseComponent(TestingComp).InputObjects.PosterState); // запоминаем начальное состояние iInputObjectCount := IBaseComponent(TestingComp).InputObjects.Count; ds := TMainFacade.GetInstance.DBGates.ItemByPoster[Poster as TImplementedDataPoster]; iRecordCount := ds.RecordCount; iID := CurrentObject.ID; // удаляем IBaseComponent(TestingComp).InputObjects.Remove(CurrentObject); // проверяем - удалено ли Check(iRecordCount - ds.RecordCount = 1, 'Ошибка удаления. Строка, соответствующая элементу не была удалена из БД'); Check(IBaseComponent(TestingComp).InputObjects.Count - iInputObjectCount = -1, 'Ошибка удаления. Элемент не удален из входной коллекции'); Check(not Assigned(IBaseComponent(TestingComp).InputObjects.ItemsByID[iID]), 'Ошибка удаления. Элемент с идентификатором, совпадающим с идентификатором удаленного элемента по прежнему присутствует в коллекции'); end; procedure TRecordingComponentImplementorTest.TestFill; begin Check(Assigned(TestingComp), 'Ошибка заполнения входной коллекции. Для теста не задан тестируемый компонент, задайте непустое значение свойства TestingComp'); Check(Assigned(Poster), 'Ошибка заполнения входной коллекции. Не задан материализатор для компонента, задайте непустое значение свойства Poster'); Check(IBaseComponent(TestingComp).InputObjects.Count > 0, 'Ошибка заполнения входной коллекции. Нет загруженных объектов'); end; procedure TRecordingComponentImplementorTest.TestRecordingCycle; begin TestAdd; TestUpdate; TestDelete; end; procedure TRecordingComponentImplementorTest.TestUpdate; var iInputObjectCount, iRecordCount: integer; ds: TDataSet; begin Check(Assigned(TestingComp), 'Ошибка редакции. Для теста не задан тестируемый компонент, задайте непустое значение свойства TestingComp'); Check(Assigned(Poster), 'Ошибка редакции. Не задан материализатор для компонента, задайте непустое значение свойства Poster'); // восстанавливаем материализатор в состоянии, соответствующем коллекции Poster.RestoreState(IBaseComponent(TestingComp).InputObjects.PosterState); // запоминаем исходное состояние iInputObjectCount := IBaseComponent(TestingComp).InputObjects.Count; ds := TMainFacade.GetInstance.DBGates.ItemByPoster[Poster as TImplementedDataPoster]; iRecordCount := ds.RecordCount; FCurrentObject := CallUpdate; Check(Assigned(FCurrentObject), 'Ошибка редакции. Объект не был возвращен для дальнейшей работы'); Check(iRecordCount - ds.RecordCount = 0, 'Ошибка редакции. Количество строк в наборе данных изменилось после редакции.'); Check(FCurrentObject.ID > 0, 'Ошибка редакции. Объект не получил верного идентификатора'); Check(IBaseComponent(TestingComp).InputObjects.Count - iInputObjectCount = 0, 'Ошибка редакции. Количество элементов в списк изменилось после редакции'); CheckValidMaterialization(FCurrentObject); end; { TGUIRecordingComponentImplementorTest } function TGUIRecordingComponentImplementorTest.GetListCount: integer; begin Result := -1; Assert(False, 'Метод GetListCount не реализован'); end; function TGUIRecordingComponentImplementorTest.GetListIndexByObject( AObject: TIDObject): integer; begin Result := -1; Assert(False, 'Метод GetListIndexByObject не реализован'); end; function TGUIRecordingComponentImplementorTest.GetObjectByIndex( AIndex: integer): TObject; begin Result := nil; Assert(False, 'Метод GetObjectByIndex не реализован'); end; procedure TGUIRecordingComponentImplementorTest.TestAdd; begin inherited; Check(IBaseComponent(TestingComp).InputObjects.Count = GetListCount, 'Ошибка добавления. Не все элементы отображены в пользовательском интерфейсе после загрузки'); Check(GetListIndexByObject(CurrentObject) > -1, 'Ошибка добавления. Последний добавленный элемент не отображен в пользовательском интерфейсе'); end; procedure TGUIRecordingComponentImplementorTest.TestDelete; var iIndex: integer; o1, o2: TObject; begin iIndex := GetListIndexByObject(CurrentObject); Check(iIndex > -1, 'Ошибка удаления. Удаляемый элемент отсутствует в интерфейсе'); o1 := GetObjectByIndex(iIndex); inherited; Check(IBaseComponent(TestingComp).InputObjects.Count - GetListCount = 0, 'Ошибка удаления. Элемент интерфейса, соответствующий удаляемому объекту - не удален'); try o2 := GetObjectByIndex(iIndex); except o2 := nil; end; Check(o1 <> o2, 'Ошибка удаления. Последний удаленный элемент по-прежнему отображается в пользовательском интерфейсе'); end; procedure TGUIRecordingComponentImplementorTest.TestFill; begin inherited; Check(IBaseComponent(TestingComp).InputObjects.Count = GetListCount, 'Не все элементы отображены в пользовательском интерфейсе после загрузки'); end; procedure TGUIRecordingComponentImplementorTest.TestUpdate; begin inherited; Check(IBaseComponent(TestingComp).InputObjects.Count = GetListCount, 'Ошибка редакции. Не все элементы отображены в пользовательском интерфейсе после редакции элемента'); Check(GetListIndexByObject(CurrentObject) > -1, 'Ошибка редакции. Последний отредактированный элемент не отображен в пользовательском интерфейсе'); end; end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.SDL2; {$ifdef fpc} {$mode delphi} {$packrecords c} {$ifdef cpu386} {$asmmode intel} {$endif} {$ifdef cpuamd64} {$asmmode intel} {$endif} {$else} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$if defined(Win32) or defined(Win64)} {$define Windows} {$ifend} {$ifdef linux} {$define unix} {$endif} {$ifdef freebsd} {$define unix} {$endif} {$ifdef darwin} {$define unix} {$endif} {$ifdef haiku} {$define unix} {$endif} {$ifdef unix} {$ifndef darwin} {$linklib c} {$endif} {$ifdef haiku} {$linklib root} {$else} {$ifndef android} {$linklib pthread} {$endif} {$endif} {$endif} {$ifdef staticlink} {$ifdef fpc} {$ifdef linux} {$linklib m} {$endif} {$ifdef win32} {$linklib SDL2} {$linklib SDL2main} {$linklib winmm} {$linklib kernel32} {$linklib gdi32} {$linklib user32} {$linklib imm32} {$linklib ole32} {$linklib oleaut32} {$linklib msvcrt} {$linklib version} {$linklib uuid} {$linklib shell32} {$linklib dinput8} {$linklib dxerr8} {$linklib dxguid} {$linklib moldname} {$endif} {$ifdef win64} {$linklib SDL2} {$linklib SDL2main} {$linklib winmm} {$linklib kernel32} {$linklib gdi32} {$linklib user32} {$linklib imm32} {$linklib ole32} {$linklib oleaut32} {$linklib msvcrt} {$linklib version} {$linklib uuid} {$linklib shell32} {$linklib dinput8} {$linklib dxerr8} {$linklib dxguid} {$linklib moldname} {$endif} {$endif} {$endif} interface uses {$if defined(Windows)} Windows, {$elseif defined(Unix)} BaseUnix, Unix, UnixType, dl, {$if not (defined(GP2X) or defined(Darwin) or defined(SkyOS) or defined(Android))} x, xlib, {$ifend} {$ifend} {$ifdef staticlink} PasVulkan.StaticLinking, {$endif} {$ifdef Android} PasVulkan.Android, {$endif} Vulkan, SysUtils,Classes; const SDL2LibName={$if defined(Win32)} 'sdl2.dll' {$elseif defined(Win64)} 'sdl264.dll' {$elseif defined(Darwin)} 'SDL2' {$else} 'libSDL2.so' {$ifend}; SDL_MAJOR_VERSION=2; SDL_MINOR_VERSION=0; SDL_PATCHLEVEL=5; SDL_FALSE=0; SDL_TRUE=1; SDL_INIT_TIMER=$00000001; SDL_INIT_AUDIO=$00000010; SDL_INIT_VIDEO=$00000020; SDL_INIT_JOYSTICK=$00000200; SDL_INIT_HAPTIC=$00001000; SDL_INIT_GAMECONTROLLER=$00002000; SDL_INIT_EVENTS=$000041000; SDL_INIT_NOPARACHUTE=$00100000; SDL_INIT_EVERYTHING=$0000FFFF; SDL_ALLEVENTS=$FFFFFFFF; SDL_APPINPUTFOCUS=$02; SDL_BUTTON_WHEELUP=4; SDL_BUTTON_WHEELDOWN=5; // SDL_Event types SDL_FIRSTEVENT=0; SDL_QUITEV=$100; SDL_APP_TERMINATING=$101; SDL_APP_LOWMEMORY=$102; SDL_APP_WILLENTERBACKGROUND=$103; SDL_APP_DIDENTERBACKGROUND=$104; SDL_APP_WILLENTERFOREGROUND=$105; SDL_APP_DIDENTERFOREGROUND=$106; SDL_DISPLAYEVENT=$150; SDL_WINDOWEVENT=$200; SDL_SYSWMEVENT=$201; SDL_KEYDOWN=$300; SDL_KEYUP=$301; SDL_TEXTEDITING=$302; SDL_TEXTINPUT=$303; SDL_MOUSEMOTION=$400; SDL_MOUSEBUTTONDOWN=$401; SDL_MOUSEBUTTONUP=$402; SDL_MOUSEWHEEL=$403; SDL_INPUTMOTION=$500; SDL_INPUTBUTTONDOWN=$501; SDL_INPUTBUTTONUP=$502; SDL_INPUTWHEEL=$503; SDL_INPUTPROXIMITYIN=$504; SDL_INPUTPROXIMITYOUT=$505; SDL_JOYAXISMOTION=$600; SDL_JOYBALLMOTION=$601; SDL_JOYHATMOTION=$602; SDL_JOYBUTTONDOWN=$603; SDL_JOYBUTTONUP=$604; SDL_JOYDEVICEADDED=$605; SDL_JOYDEVICEREMOVED=$606; SDL_CONTROLLERAXISMOTION=$650; SDL_CONTROLLERBUTTONDOWN=$651; SDL_CONTROLLERBUTTONUP=$652; SDL_CONTROLLERDEVICEADDED=$653; SDL_CONTROLLERDEVICEREMOVED=$654; SDL_CONTROLLERDEVICEREMAPPED=$655; SDL_FINGERDOWN=$700; SDL_FINGERUP=$701; SDL_FINGERMOTION=$702; SDL_DOLLARGESTURE=$800; SDL_DOLLARRECORD=$801; SDL_MULTIGESTURE=$802; SDL_CLIPBOARDUPDATE=$900; SDL_DROPFILE=$1000; SDL_DROPTEXT=$1001; SDL_DROPBEGIN=$1002; SDL_DROPCOMPLETE=$1003; SDL_AUDIODEVICEADDED=$1100; SDL_AUDIODEVICEREMOVED=$1101; SDL_SENSORUPDATE=$1200; SDL_RENDER_TARGETS_RESET=$2000; SDL_RENDER_DEVICE_RESET=$2001; SDL_USEREVENT=$8000; SDL_LASTEVENT=$ffff; // no compatibility events $7000 // SDL_Surface flags SDL_SWSURFACE=$00000000; //*< Not used */ SDL_PREALLOC=$00000001; //*< Surface uses preallocated memory */ SDL_RLEACCEL=$00000002; //*< Surface is RLE encoded */ SDL_DONTFREE=$00000004; //*< Surface is referenced internally */ SDL_SRCALPHA=$00010000; SDL_SRCCOLORKEY=$00020000; SDL_ANYFORMAT=$00100000; SDL_HWPALETTE=$00200000; SDL_DOUBLEBUF=$00400000; SDL_FULLSCREEN=$00800000; SDL_RESIZABLE=$01000000; SDL_NOFRAME=$02000000; SDL_OPENGL=$04000000; SDL_HWSURFACE=$08000001; //*< Not used */ SDL_ASYNCBLIT=$08000000; //*< Not used */ SDL_RLEACCELOK=$08000000; //*< Not used */ SDL_HWACCEL=$08000000; //*< Not used */ // SDL_Renderer flags SDL_RENDERER_SOFTWARE=$00000001; //*< The renderer is a software fallback */ SDL_RENDERER_ACCELERATED=$00000002; //*< The renderer uses hardware acceleration */ SDL_RENDERER_PRESENTVSYNC=$00000004; // SDL_WindowFlags (enum) SDL_WINDOW_FULLSCREEN=$00000001; //*< fullscreen window, implies borderless */ SDL_WINDOW_OPENGL=$00000002; //*< window usable with OpenGL context */ SDL_WINDOW_SHOWN=$00000004; //*< window is visible */ SDL_WINDOW_HIDDEN=$00000008; //*< window is not visible */ SDL_WINDOW_BORDERLESS=$00000010; //*< no window decoration */ SDL_WINDOW_RESIZABLE=$00000020; //*< window can be resized */ SDL_WINDOW_MINIMIZED=$00000040; //*< window is minimized */ SDL_WINDOW_MAXIMIZED=$00000080; //*< window is maximized */ SDL_WINDOW_INPUT_GRABBED=$00000100; //*< window has grabbed input focus */ SDL_WINDOW_INPUT_FOCUS=$00000200; //*< window has input focus */ SDL_WINDOW_MOUSE_FOCUS=$00000400; //*< window has mouse focus */ SDL_WINDOW_FOREIGN=$00000800; //*< window not created by SDL */ SDL_WINDOW_FULLSCREEN_DESKTOP=SDL_WINDOW_FULLSCREEN or $00001000; //*< fake fullscreen window, that takes the size of the desktop */ SDL_WINDOW_ALLOW_HIGHDPI=$00002000; //**< window should be created in high-DPI mode if supported */ SDL_WINDOW_MOUSE_CAPTURE=$00004000; //**< window has mouse captured (unrelated to INPUT_GRABBED) */ SDL_WINDOW_ALWAYS_ON_TOP=$00008000; //**< window should always be above others */ SDL_WINDOW_SKIP_TASKBAR=$00010000; //**< window should not be added to the taskbar */ SDL_WINDOW_UTILITY=$00020000; //**< window should be treated as a utility window */ SDL_WINDOW_TOOLTIP=$00040000; //**< window should be treated as a tooltip */ SDL_WINDOW_POPUP_MENU=$00080000; //**< window should be treated as a popup menu */ {$if defined(Android) and not defined(PasVulkanUseSDL2WithVulkanSupport)} // In the case if PasVulkan uses on Android still a self-patched SDL 2.0.5 version SDL_WINDOW_VULKAN=$00100000; //**< window usable with Vulkan */ {$else} // SDL 2.0.6 SDL_WINDOW_VULKAN=$10000000; //**< window usable with Vulkan */ {$ifend} SDL_WINDOWPOS_CENTERED_MASK=$2FFF0000; // SDL_WindowEventID (enum) SDL_WINDOWEVENT_NONE=0; //*< Never used SDL_WINDOWEVENT_SHOWN=1; //*< Window has been shown SDL_WINDOWEVENT_HIDDEN=2; //*< Window has been hidden SDL_WINDOWEVENT_EXPOSED=3; //*< Window has been exposed and should be redrawn SDL_WINDOWEVENT_MOVED=4; //*< Window has been moved to data1, data2 SDL_WINDOWEVENT_RESIZED=5; //*< Window size changed to data1xdata2 SDL_WINDOWEVENT_SIZE_CHANGED=6; //*< The window size has changed, [...] */ SDL_WINDOWEVENT_MINIMIZED=7; //*< Window has been minimized SDL_WINDOWEVENT_MAXIMIZED=8; //*< Window has been maximized SDL_WINDOWEVENT_RESTORED=9; //*< Window has been restored to normal size and position SDL_WINDOWEVENT_ENTER=10; //*< Window has gained mouse focus SDL_WINDOWEVENT_LEAVE=11; //*< Window has lost mouse focus SDL_WINDOWEVENT_FOCUS_GAINED=12; //*< Window has gained keyboard focus SDL_WINDOWEVENT_FOCUS_LOST=13; //*< Window has lost keyboard focus SDL_WINDOWEVENT_CLOSE=14; //*< The window manager requests that the window be closed */ SDL_BLENDMODE_NONE=$00000000; // **< No blending SDL_BLENDMODE_BLEND=$00000001; // **< dst = (src * A) + (dst * (1-A)) SDL_BLENDMODE_ADD=$00000002; // **< dst = (src * A) + dst SDL_BLENDMODE_MOD=$00000004; // **< dst = src * dst SDL_DISPLAYEVENT_NONE=0; // Never used SDL_DISPLAYEVENT_ORIENTATION=1; // Display orientation has changed to data1 SDL_ORIENTATION_UNKNOWN=0; // The display orientation can't be determined SDL_ORIENTATION_LANDSCAPE=1; // The display is in landscape mode, with the right side up, relative to portrait mode SDL_ORIENTATION_LANDSCAPE_FLIPPED=2; // The display is in landscape mode, with the left side up, relative to portrait mode SDL_ORIENTATION_PORTRAIT=3; // The display is in portrait mode SDL_ORIENTATION_PORTRAIT_FLIPPED=4; // The display is in portrait mode, upside dowm {$ifdef fpc_big_endian} RMask=$FF000000; GMask=$00FF0000; BMask=$0000FF00; AMask=$000000FF; RShift=24; GShift=16; BShift=8; AShift=0; {$else} RMask=$000000FF; GMask=$0000FF00; BMask=$00FF0000; AMask=$FF000000; RShift=0; GShift=8; BShift=16; AShift=24; {$endif} // SDL_mixer MIX_MAX_VOLUME=128; MIX_INIT_FLAC=$00000001; MIX_INIT_MOD=$00000002; MIX_INIT_MP3=$00000004; MIX_INIT_OGG=$00000008; // SDL_TTF TTF_STYLE_NORMAL=0; TTF_STYLE_BOLD=1; TTF_STYLE_ITALIC=2; // SDL Joystick SDL_HAT_CENTERED=$00; SDL_HAT_UP=$01; SDL_HAT_RIGHT=$02; SDL_HAT_DOWN=$04; SDL_HAT_LEFT=$08; SDL_HAT_RIGHTUP=SDL_HAT_RIGHT or SDL_HAT_UP; SDL_HAT_RIGHTDOWN=SDL_HAT_RIGHT or SDL_HAT_DOWN; SDL_HAT_LEFTUP=SDL_HAT_LEFT or SDL_HAT_UP; SDL_HAT_LEFTDOWN=SDL_HAT_LEFT or SDL_HAT_DOWN; // SDL_image IMG_INIT_JPG=$00000001; IMG_INIT_PNG=$00000002; IMG_INIT_TIF=$00000004; // SDL_EventMask type definition // Enumeration of valid key mods (possibly OR'd together) KMOD_NONE=$0000; KMOD_LSHIFT=$0001; KMOD_RSHIFT=$0002; KMOD_LCTRL=$0040; KMOD_RCTRL=$0080; KMOD_LALT=$0100; KMOD_RALT=$0200; KMOD_LMETA=$0400; KMOD_RMETA=$0800; KMOD_NUM=$1000; KMOD_CAPS=$2000; KMOD_MODE=$4000; KMOD_RESERVED=$8000; KMOD_CTRL=(KMOD_LCTRL or KMOD_RCTRL); KMOD_SHIFT=(KMOD_LSHIFT or KMOD_RSHIFT); KMOD_ALT=(KMOD_LALT or KMOD_RALT); KMOD_META=(KMOD_LMETA or KMOD_RMETA); SDL_SCANCODE_UNKNOWN=0; SDL_SCANCODE_A=4; SDL_SCANCODE_B=5; SDL_SCANCODE_C=6; SDL_SCANCODE_D=7; SDL_SCANCODE_E=8; SDL_SCANCODE_F=9; SDL_SCANCODE_G=10; SDL_SCANCODE_H=11; SDL_SCANCODE_I=12; SDL_SCANCODE_J=13; SDL_SCANCODE_K=14; SDL_SCANCODE_L=15; SDL_SCANCODE_M=16; SDL_SCANCODE_N=17; SDL_SCANCODE_O=18; SDL_SCANCODE_P=19; SDL_SCANCODE_Q=20; SDL_SCANCODE_R=21; SDL_SCANCODE_S=22; SDL_SCANCODE_T=23; SDL_SCANCODE_U=24; SDL_SCANCODE_V=25; SDL_SCANCODE_W=26; SDL_SCANCODE_X=27; SDL_SCANCODE_Y=28; SDL_SCANCODE_Z=29; SDL_SCANCODE_1=30; SDL_SCANCODE_2=31; SDL_SCANCODE_3=32; SDL_SCANCODE_4=33; SDL_SCANCODE_5=34; SDL_SCANCODE_6=35; SDL_SCANCODE_7=36; SDL_SCANCODE_8=37; SDL_SCANCODE_9=38; SDL_SCANCODE_0=39; SDL_SCANCODE_RETURN=40; SDL_SCANCODE_ESCAPE=41; SDL_SCANCODE_BACKSPACE=42; SDL_SCANCODE_TAB=43; SDL_SCANCODE_SPACE=44; SDL_SCANCODE_MINUS=45; SDL_SCANCODE_EQUALS=46; SDL_SCANCODE_LEFTBRACKET=47; SDL_SCANCODE_RIGHTBRACKET=48; SDL_SCANCODE_BACKSLASH=49; SDL_SCANCODE_NONUSHASH=50; SDL_SCANCODE_SEMICOLON=51; SDL_SCANCODE_APOSTROPHE=52; SDL_SCANCODE_GRAVE=53; SDL_SCANCODE_COMMA=54; SDL_SCANCODE_PERIOD=55; SDL_SCANCODE_SLASH=56; SDL_SCANCODE_CAPSLOCK=57; SDL_SCANCODE_F1=58; SDL_SCANCODE_F2=59; SDL_SCANCODE_F3=60; SDL_SCANCODE_F4=61; SDL_SCANCODE_F5=62; SDL_SCANCODE_F6=63; SDL_SCANCODE_F7=64; SDL_SCANCODE_F8=65; SDL_SCANCODE_F9=66; SDL_SCANCODE_F10=67; SDL_SCANCODE_F11=68; SDL_SCANCODE_F12=69; SDL_SCANCODE_PRINTSCREEN=70; SDL_SCANCODE_SCROLLLOCK=71; SDL_SCANCODE_PAUSE=72; SDL_SCANCODE_INSERT=73; SDL_SCANCODE_HOME=74; SDL_SCANCODE_PAGEUP=75; SDL_SCANCODE_DELETE=76; SDL_SCANCODE_END=77; SDL_SCANCODE_PAGEDOWN=78; SDL_SCANCODE_RIGHT=79; SDL_SCANCODE_LEFT=80; SDL_SCANCODE_DOWN=81; SDL_SCANCODE_UP=82; SDL_SCANCODE_NUMLOCKCLEAR=83; SDL_SCANCODE_KP_DIVIDE=84; SDL_SCANCODE_KP_MULTIPLY=85; SDL_SCANCODE_KP_MINUS=86; SDL_SCANCODE_KP_PLUS=87; SDL_SCANCODE_KP_ENTER=88; SDL_SCANCODE_KP_1=89; SDL_SCANCODE_KP_2=90; SDL_SCANCODE_KP_3=91; SDL_SCANCODE_KP_4=92; SDL_SCANCODE_KP_5=93; SDL_SCANCODE_KP_6=94; SDL_SCANCODE_KP_7=95; SDL_SCANCODE_KP_8=96; SDL_SCANCODE_KP_9=97; SDL_SCANCODE_KP_0=98; SDL_SCANCODE_KP_PERIOD=99; SDL_SCANCODE_NONUSBACKSLASH=100; SDL_SCANCODE_APPLICATION=101; SDL_SCANCODE_POWER=102; SDL_SCANCODE_KP_EQUALS=103; SDL_SCANCODE_F13=104; SDL_SCANCODE_F14=105; SDL_SCANCODE_F15=106; SDL_SCANCODE_F16=107; SDL_SCANCODE_F17=108; SDL_SCANCODE_F18=109; SDL_SCANCODE_F19=110; SDL_SCANCODE_F20=111; SDL_SCANCODE_F21=112; SDL_SCANCODE_F22=113; SDL_SCANCODE_F23=114; SDL_SCANCODE_F24=115; SDL_SCANCODE_EXECUTE=116; SDL_SCANCODE_HELP=117; SDL_SCANCODE_MENU=118; SDL_SCANCODE_SELECT=119; SDL_SCANCODE_STOP=120; SDL_SCANCODE_AGAIN=121; SDL_SCANCODE_UNDO=122; SDL_SCANCODE_CUT=123; SDL_SCANCODE_COPY=124; SDL_SCANCODE_PASTE=125; SDL_SCANCODE_FIND=126; SDL_SCANCODE_MUTE=127; SDL_SCANCODE_VOLUMEUP=128; SDL_SCANCODE_VOLUMEDOWN=129; SDL_SCANCODE_LOCKINGCAPSLOCK=130; SDL_SCANCODE_LOCKINGNUMLOCK=131; SDL_SCANCODE_LOCKINGSCROLLLOCK=132; SDL_SCANCODE_KP_COMMA=133; SDL_SCANCODE_KP_EQUALSAS400=134; SDL_SCANCODE_INTERNATIONAL1=135; SDL_SCANCODE_INTERNATIONAL2=136; SDL_SCANCODE_INTERNATIONAL3=137; SDL_SCANCODE_INTERNATIONAL4=138; SDL_SCANCODE_INTERNATIONAL5=139; SDL_SCANCODE_INTERNATIONAL6=140; SDL_SCANCODE_INTERNATIONAL7=141; SDL_SCANCODE_INTERNATIONAL8=142; SDL_SCANCODE_INTERNATIONAL9=143; SDL_SCANCODE_LANG1=144; SDL_SCANCODE_LANG2=145; SDL_SCANCODE_LANG3=146; SDL_SCANCODE_LANG4=147; SDL_SCANCODE_LANG5=148; SDL_SCANCODE_LANG6=149; SDL_SCANCODE_LANG7=150; SDL_SCANCODE_LANG8=151; SDL_SCANCODE_LANG9=152; SDL_SCANCODE_ALTERASE=153; SDL_SCANCODE_SYSREQ=154; SDL_SCANCODE_CANCEL=155; SDL_SCANCODE_CLEAR=156; SDL_SCANCODE_PRIOR=157; SDL_SCANCODE_RETURN2=158; SDL_SCANCODE_SEPARATOR=159; SDL_SCANCODE_OUT=160; SDL_SCANCODE_OPER=161; SDL_SCANCODE_CLEARAGAIN=162; SDL_SCANCODE_CRSEL=163; SDL_SCANCODE_EXSEL=164; SDL_SCANCODE_KP_00=176; SDL_SCANCODE_KP_000=177; SDL_SCANCODE_THOUSANDSSEPARATOR=178; SDL_SCANCODE_DECIMALSEPARATOR=179; SDL_SCANCODE_CURRENCYUNIT=180; SDL_SCANCODE_CURRENCYSUBUNIT=181; SDL_SCANCODE_KP_LEFTPAREN=182; SDL_SCANCODE_KP_RIGHTPAREN=183; SDL_SCANCODE_KP_LEFTBRACE=184; SDL_SCANCODE_KP_RIGHTBRACE=185; SDL_SCANCODE_KP_TAB=186; SDL_SCANCODE_KP_BACKSPACE=187; SDL_SCANCODE_KP_A=188; SDL_SCANCODE_KP_B=189; SDL_SCANCODE_KP_C=190; SDL_SCANCODE_KP_D=191; SDL_SCANCODE_KP_E=192; SDL_SCANCODE_KP_F=193; SDL_SCANCODE_KP_XOR=194; SDL_SCANCODE_KP_POWER=195; SDL_SCANCODE_KP_PERCENT=196; SDL_SCANCODE_KP_LESS=197; SDL_SCANCODE_KP_GREATER=198; SDL_SCANCODE_KP_AMPERSAND=199; SDL_SCANCODE_KP_DBLAMPERSAND=200; SDL_SCANCODE_KP_VERTICALBAR=201; SDL_SCANCODE_KP_DBLVERTICALBAR=202; SDL_SCANCODE_KP_COLON=203; SDL_SCANCODE_KP_HASH=204; SDL_SCANCODE_KP_SPACE=205; SDL_SCANCODE_KP_AT=206; SDL_SCANCODE_KP_EXCLAM=207; SDL_SCANCODE_KP_MEMSTORE=208; SDL_SCANCODE_KP_MEMRECALL=209; SDL_SCANCODE_KP_MEMCLEAR=210; SDL_SCANCODE_KP_MEMADD=211; SDL_SCANCODE_KP_MEMSUBTRACT=212; SDL_SCANCODE_KP_MEMMULTIPLY=213; SDL_SCANCODE_KP_MEMDIVIDE=214; SDL_SCANCODE_KP_PLUSMINUS=215; SDL_SCANCODE_KP_CLEAR=216; SDL_SCANCODE_KP_CLEARENTRY=217; SDL_SCANCODE_KP_BINARY=218; SDL_SCANCODE_KP_OCTAL=219; SDL_SCANCODE_KP_DECIMAL=220; SDL_SCANCODE_KP_HEXADECIMAL=221; SDL_SCANCODE_LCTRL=224; SDL_SCANCODE_LSHIFT=225; SDL_SCANCODE_LALT=226; SDL_SCANCODE_LGUI=227; SDL_SCANCODE_RCTRL=228; SDL_SCANCODE_RSHIFT=229; SDL_SCANCODE_RALT=230; SDL_SCANCODE_RGUI=231; SDL_SCANCODE_MODE=257; SDL_SCANCODE_AUDIONEXT=258; SDL_SCANCODE_AUDIOPREV=259; SDL_SCANCODE_AUDIOSTOP=260; SDL_SCANCODE_AUDIOPLAY=261; SDL_SCANCODE_AUDIOMUTE=262; SDL_SCANCODE_MEDIASELECT=263; SDL_SCANCODE_WWW=264; SDL_SCANCODE_MAIL=265; SDL_SCANCODE_CALCULATOR=266; SDL_SCANCODE_COMPUTER=267; SDL_SCANCODE_AC_SEARCH=268; SDL_SCANCODE_AC_HOME=269; SDL_SCANCODE_AC_BACK=270; SDL_SCANCODE_AC_FORWARD=271; SDL_SCANCODE_AC_STOP=272; SDL_SCANCODE_AC_REFRESH=273; SDL_SCANCODE_AC_BOOKMARKS=274; SDL_SCANCODE_BRIGHTNESSDOWN=275; SDL_SCANCODE_BRIGHTNESSUP=276; SDL_SCANCODE_DISPLAYSWITCH=277; SDL_SCANCODE_KBDILLUMTOGGLE=278; SDL_SCANCODE_KBDILLUMDOWN=279; SDL_SCANCODE_KBDILLUMUP=280; SDL_SCANCODE_EJECT=281; SDL_SCANCODE_SLEEP=282; SDL_NUM_SCANCODES=512; SDLK_UNKNOWN=0; SDLK_RETURN=13; SDLK_ESCAPE=27; SDLK_BACKSPACE=8; SDLK_TAB=9; SDLK_SPACE=32; SDLK_EXCLAIM=ord('!'); SDLK_QUOTEDBL=ord('"'); SDLK_HASH=ord('#'); SDLK_PERCENT=ord('%'); SDLK_DOLLAR=ord('$'); SDLK_AMPERSAND=ord('&'); SDLK_QUOTE=ord(''''); SDLK_LEFTPAREN=ord('('); SDLK_RIGHTPAREN=ord(')'); SDLK_ASTERISK=ord('*'); SDLK_PLUS=ord('+'); SDLK_COMMA=ord(','); SDLK_MINUS=ord('-'); SDLK_PERIOD=ord('.'); SDLK_SLASH=ord('/'); SDLK_0=ord('0'); SDLK_1=ord('1'); SDLK_2=ord('2'); SDLK_3=ord('3'); SDLK_4=ord('4'); SDLK_5=ord('5'); SDLK_6=ord('6'); SDLK_7=ord('7'); SDLK_8=ord('8'); SDLK_9=ord('9'); SDLK_COLON=ord(':'); SDLK_SEMICOLON=ord(';'); SDLK_LESS=ord('<'); SDLK_EQUALS=ord('='); SDLK_GREATER=ord('>'); SDLK_QUESTION=ord('?'); SDLK_AT=ord('@'); SDLK_LEFTBRACKET=ord('['); SDLK_BACKSLASH=ord('\'); SDLK_RIGHTBRACKET=ord(']'); SDLK_CARET=ord('^'); SDLK_UNDERSCORE=ord('_'); SDLK_BACKQUOTE=ord('`'); SDLK_a=ord('a'); SDLK_b=ord('b'); SDLK_c=ord('c'); SDLK_d=ord('d'); SDLK_e=ord('e'); SDLK_f=ord('f'); SDLK_g=ord('g'); SDLK_h=ord('h'); SDLK_i=ord('i'); SDLK_j=ord('j'); SDLK_k=ord('k'); SDLK_l=ord('l'); SDLK_m=ord('m'); SDLK_n=ord('n'); SDLK_o=ord('o'); SDLK_p=ord('p'); SDLK_q=ord('q'); SDLK_r=ord('r'); SDLK_s=ord('s'); SDLK_t=ord('t'); SDLK_u=ord('u'); SDLK_v=ord('v'); SDLK_w=ord('w'); SDLK_x=ord('x'); SDLK_y=ord('y'); SDLK_z=ord('z'); SDL_SCANCODE_TO_KEYCODE=1 shl 30; SDLK_CAPSLOCK=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CAPSLOCK); SDLK_F1=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F1); SDLK_F2=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F2); SDLK_F3=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F3); SDLK_F4=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F4); SDLK_F5=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F5); SDLK_F6=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F6); SDLK_F7=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F7); SDLK_F8=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F8); SDLK_F9=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F9); SDLK_F10=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F10); SDLK_F11=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F11); SDLK_F12=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F12); SDLK_PRINTSCREEN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PRINTSCREEN); SDLK_SCROLLLOCK=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SCROLLLOCK); SDLK_SCROLLOCK=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SCROLLLOCK); SDLK_PAUSE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PAUSE); SDLK_INSERT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_INSERT); SDLK_HOME=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_HOME); SDLK_PAGEUP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PAGEUP); SDLK_DELETE=127; //'\177'; SDLK_END=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_END); SDLK_PAGEDOWN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PAGEDOWN); SDLK_RIGHT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RIGHT); SDLK_LEFT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_LEFT); SDLK_DOWN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_DOWN); SDLK_UP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_UP); SDLK_NUMLOCK=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_NUMLOCKCLEAR); SDLK_NUMLOCKCLEAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_NUMLOCKCLEAR); SDLK_KP_DIVIDE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_DIVIDE); SDLK_KP_MULTIPLY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MULTIPLY); SDLK_KP_MINUS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MINUS); SDLK_KP_PLUS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_PLUS); SDLK_KP_ENTER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_ENTER); SDLK_KP_1=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_1); SDLK_KP_2=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_2); SDLK_KP_3=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_3); SDLK_KP_4=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_4); SDLK_KP_5=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_5); SDLK_KP_6=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_6); SDLK_KP_7=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_7); SDLK_KP_8=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_8); SDLK_KP_9=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_9); SDLK_KP_0=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_0); SDLK_KP1=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_1); SDLK_KP2=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_2); SDLK_KP3=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_3); SDLK_KP4=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_4); SDLK_KP5=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_5); SDLK_KP6=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_6); SDLK_KP7=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_7); SDLK_KP8=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_8); SDLK_KP9=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_9); SDLK_KP0=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_0); SDLK_KP_PERIOD=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_PERIOD); SDLK_APPLICATION=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_APPLICATION); SDLK_POWER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_POWER); SDLK_KP_EQUALS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_EQUALS); SDLK_F13=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F13); SDLK_F14=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F14); SDLK_F15=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F15); SDLK_F16=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F16); SDLK_F17=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F17); SDLK_F18=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F18); SDLK_F19=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F19); SDLK_F20=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F20); SDLK_F21=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F21); SDLK_F22=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F22); SDLK_F23=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F23); SDLK_F24=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_F24); SDLK_EXECUTE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_EXECUTE); SDLK_HELP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_HELP); SDLK_MENU=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_MENU); SDLK_SELECT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SELECT); SDLK_STOP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_STOP); SDLK_AGAIN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AGAIN); SDLK_UNDO=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_UNDO); SDLK_CUT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CUT); SDLK_COPY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_COPY); SDLK_PASTE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PASTE); SDLK_FIND=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_FIND); SDLK_MUTE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_MUTE); SDLK_VOLUMEUP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_VOLUMEUP); SDLK_VOLUMEDOWN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_VOLUMEDOWN); SDLK_KP_COMMA=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_COMMA); SDLK_KP_EQUALSAS400=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_EQUALSAS400); SDLK_ALTERASE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_ALTERASE); SDLK_SYSREQ=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SYSREQ); SDLK_CANCEL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CANCEL); SDLK_CLEAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CLEAR); SDLK_PRIOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_PRIOR); SDLK_RETURN2=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RETURN2); SDLK_SEPARATOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SEPARATOR); SDLK_OUT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_OUT); SDLK_OPER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_OPER); SDLK_CLEARAGAIN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CLEARAGAIN); SDLK_CRSEL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CRSEL); SDLK_EXSEL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_EXSEL); SDLK_KP_00=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_00); SDLK_KP_000=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_000); SDLK_THOUSANDSSEPARATOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_THOUSANDSSEPARATOR); SDLK_DECIMALSEPARATOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_DECIMALSEPARATOR); SDLK_CURRENCYUNIT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CURRENCYUNIT); SDLK_CURRENCYSUBUNIT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CURRENCYSUBUNIT); SDLK_KP_LEFTPAREN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_LEFTPAREN); SDLK_KP_RIGHTPAREN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_RIGHTPAREN); SDLK_KP_LEFTBRACE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_LEFTBRACE); SDLK_KP_RIGHTBRACE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_RIGHTBRACE); SDLK_KP_TAB=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_TAB); SDLK_KP_BACKSPACE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_BACKSPACE); SDLK_KP_A=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_A); SDLK_KP_B=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_B); SDLK_KP_C=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_C); SDLK_KP_D=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_D); SDLK_KP_E=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_E); SDLK_KP_F=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_F); SDLK_KP_XOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_XOR); SDLK_KP_POWER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_POWER); SDLK_KP_PERCENT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_PERCENT); SDLK_KP_LESS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_LESS); SDLK_KP_GREATER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_GREATER); SDLK_KP_AMPERSAND=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_AMPERSAND); SDLK_KP_DBLAMPERSAND=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_DBLAMPERSAND); SDLK_KP_VERTICALBAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_VERTICALBAR); SDLK_KP_DBLVERTICALBAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_DBLVERTICALBAR); SDLK_KP_COLON=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_COLON); SDLK_KP_HASH=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_HASH); SDLK_KP_SPACE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_SPACE); SDLK_KP_AT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_AT); SDLK_KP_EXCLAM=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_EXCLAM); SDLK_KP_MEMSTORE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMSTORE); SDLK_KP_MEMRECALL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMRECALL); SDLK_KP_MEMCLEAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMCLEAR); SDLK_KP_MEMADD=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMADD); SDLK_KP_MEMSUBTRACT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMSUBTRACT); SDLK_KP_MEMMULTIPLY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMMULTIPLY); SDLK_KP_MEMDIVIDE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_MEMDIVIDE); SDLK_KP_PLUSMINUS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_PLUSMINUS); SDLK_KP_CLEAR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_CLEAR); SDLK_KP_CLEARENTRY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_CLEARENTRY); SDLK_KP_BINARY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_BINARY); SDLK_KP_OCTAL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_OCTAL); SDLK_KP_DECIMAL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_DECIMAL); SDLK_KP_HEXADECIMAL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KP_HEXADECIMAL); SDLK_LCTRL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_LCTRL); SDLK_LSHIFT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_LSHIFT); SDLK_LALT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_LALT); SDLK_LGUI=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_LGUI); SDLK_RCTRL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RCTRL); SDLK_RSHIFT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RSHIFT); SDLK_RALT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RALT); SDLK_RGUI=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_RGUI); SDLK_MODE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_MODE); SDLK_AUDIONEXT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AUDIONEXT); SDLK_AUDIOPREV=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AUDIOPREV); SDLK_AUDIOSTOP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AUDIOSTOP); SDLK_AUDIOPLAY=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AUDIOPLAY); SDLK_AUDIOMUTE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AUDIOMUTE); SDLK_MEDIASELECT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_MEDIASELECT); SDLK_WWW=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_WWW); SDLK_MAIL=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_MAIL); SDLK_CALCULATOR=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_CALCULATOR); SDLK_COMPUTER=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_COMPUTER); SDLK_AC_SEARCH=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_SEARCH); SDLK_AC_HOME=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_HOME); SDLK_AC_BACK=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_BACK); SDLK_AC_FORWARD=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_FORWARD); SDLK_AC_STOP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_STOP); SDLK_AC_REFRESH=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_REFRESH); SDLK_AC_BOOKMARKS=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_AC_BOOKMARKS); SDLK_BRIGHTNESSDOWN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_BRIGHTNESSDOWN); SDLK_BRIGHTNESSUP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_BRIGHTNESSUP); SDLK_DISPLAYSWITCH=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_DISPLAYSWITCH); SDLK_KBDILLUMTOGGLE=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KBDILLUMTOGGLE); SDLK_KBDILLUMDOWN=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KBDILLUMDOWN); SDLK_KBDILLUMUP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_KBDILLUMUP); SDLK_EJECT=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_EJECT); SDLK_SLEEP=SDL_SCANCODE_TO_KEYCODE or (SDL_SCANCODE_SLEEP); SDL_BUTTON_LEFT=1; SDL_BUTTON_MIDDLE=2; SDL_BUTTON_RIGHT=3; SDL_BUTTON_X1=6; SDL_BUTTON_X2=7; SDL_QUERY=-1; SDL_IGNORE=0; SDL_DISABLE=0; SDL_ENABLE=1; SDL_AUDIO_MASK_BITSIZE=$ff; SDL_AUDIO_MASK_DATATYPE=1 shl 8; SDL_AUDIO_MASK_ENDIAN=1 shl 12; SDL_AUDIO_MASK_SIGNED=1 shl 15; AUDIO_U8=$0008; // Unsigned 8-bit samples AUDIO_S8=$8008; // Signed 8-bit samples AUDIO_U16LSB=$0010; // Unsigned 16-bit samples AUDIO_S16LSB=$8010; // Signed 16-bit samples AUDIO_S32LSB=$8020; AUDIO_F32LSB=$8120; AUDIO_U16MSB=$1010; // As above, but big-endian uint8 order AUDIO_S16MSB=$9010; // As above, but big-endian uint8 order AUDIO_S32MSB=$9020; AUDIO_F32MSB=$9120; AUDIO_U16=AUDIO_U16LSB; AUDIO_S16=AUDIO_S16LSB; AUDIO_S32=AUDIO_S32LSB; AUDIO_F32=AUDIO_F32LSB; SDL_AUDIO_ALLOW_FREQUENCY_CHANGE=$00000001; SDL_AUDIO_ALLOW_FORMAT_CHANGE=$00000002; SDL_AUDIO_ALLOW_CHANNELS_CHANGE=$00000004; SDL_AUDIO_ALLOW_ANY_CHANGE=SDL_AUDIO_ALLOW_FREQUENCY_CHANGE or SDL_AUDIO_ALLOW_FORMAT_CHANGE or SDL_AUDIO_ALLOW_CHANNELS_CHANGE; SDL_SYSWM_UNKNOWN=0; SDL_SYSWM_WINDOWS=1; SDL_SYSWM_X11=2; SDL_SYSWM_DIRECTFB=3; SDL_SYSWM_COCOA=4; SDL_SYSWM_UIKIT=5; SDL_SYSWM_WAYLAND=6; SDL_SYSWM_MIR=7; SDL_SYSWM_WINRT=8; SDL_SYSWM_ANDROID=9; SDL_SYSWM_VIVANTE=10; SDL_ALPHA_OPAQUE = 255; SDL_ALPHA_TRANSPARENT = 0; {** Pixel type. *} SDL_PIXELTYPE_UNKNOWN = 0; SDL_PIXELTYPE_INDEX1 = 1; SDL_PIXELTYPE_INDEX4 = 2; SDL_PIXELTYPE_INDEX8 = 3; SDL_PIXELTYPE_PACKED8 = 4; SDL_PIXELTYPE_PACKED16 = 5; SDL_PIXELTYPE_PACKED32 = 6; SDL_PIXELTYPE_ARRAYU8 = 7; SDL_PIXELTYPE_ARRAYU16 = 8; SDL_PIXELTYPE_ARRAYU32 = 9; SDL_PIXELTYPE_ARRAYF16 = 10; SDL_PIXELTYPE_ARRAYF32 = 11; {** Bitmap pixel order, high bit -> low bit. *} SDL_BITMAPORDER_NONE = 0; SDL_BITMAPORDER_4321 = 1; SDL_BITMAPORDER_1234 = 2; {** Packed component order, high bit -> low bit. *} SDL_PACKEDORDER_NONE = 0; SDL_PACKEDORDER_XRGB = 1; SDL_PACKEDORDER_RGBX = 2; SDL_PACKEDORDER_ARGB = 3; SDL_PACKEDORDER_RGBA = 4; SDL_PACKEDORDER_XBGR = 5; SDL_PACKEDORDER_BGRX = 6; SDL_PACKEDORDER_ABGR = 7; SDL_PACKEDORDER_BGRA = 8; {** Array component order, low byte -> high byte. *} SDL_ARRAYORDER_NONE = 0; SDL_ARRAYORDER_RGB = 1; SDL_ARRAYORDER_RGBA = 2; SDL_ARRAYORDER_ARGB = 3; SDL_ARRAYORDER_BGR = 4; SDL_ARRAYORDER_BGRA = 5; SDL_ARRAYORDER_ABGR = 6; {** Packed component layout. *} SDL_PACKEDLAYOUT_NONE = 0; SDL_PACKEDLAYOUT_332 = 1; SDL_PACKEDLAYOUT_4444 = 2; SDL_PACKEDLAYOUT_1555 = 3; SDL_PACKEDLAYOUT_5551 = 4; SDL_PACKEDLAYOUT_565 = 5; SDL_PACKEDLAYOUT_8888 = 6; SDL_PACKEDLAYOUT_2101010 = 7; SDL_PACKEDLAYOUT_1010102 = 8; SDL_PIXELFORMAT_UNKNOWN=0; SDL_PIXELFORMAT_INDEX1LSB=(1 shl 28) or (SDL_PIXELTYPE_INDEX1 shl 24) or (SDL_BITMAPORDER_4321 shl 20) or (0 shl 16) or (1 shl 8) or (0 shl 0); SDL_PIXELFORMAT_INDEX1MSB=(1 shl 28) or (SDL_PIXELTYPE_INDEX1 shl 24) or (SDL_BITMAPORDER_1234 shl 20) or (0 shl 16) or (1 shl 8) or (0 shl 0); SDL_PIXELFORMAT_INDEX4LSB=(1 shl 28) or (SDL_PIXELTYPE_INDEX4 shl 24) or (SDL_BITMAPORDER_4321 shl 20) or (0 shl 16) or (4 shl 8) or (0 shl 0); SDL_PIXELFORMAT_INDEX4MSB=(1 shl 28) or (SDL_PIXELTYPE_INDEX4 shl 24) or (SDL_BITMAPORDER_1234 shl 20) or (0 shl 16) or (4 shl 8) or (0 shl 0); SDL_PIXELFORMAT_INDEX8=(1 shl 28) or (SDL_PIXELTYPE_PACKED8 shl 24) or (0 shl 20) or (0 shl 16) or (8 shl 8) or (1 shl 0); SDL_PIXELFORMAT_RGB332=(1 shl 28) or (SDL_PIXELTYPE_PACKED8 shl 24) or (SDL_PACKEDORDER_XRGB shl 20) or (SDL_PACKEDLAYOUT_332 shl 16) or (8 shl 8) or (1 shl 0); SDL_PIXELFORMAT_RGB444=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_XRGB shl 20) or (SDL_PACKEDLAYOUT_4444 shl 16) or (12 shl 8) or (2 shl 0); SDL_PIXELFORMAT_RGB555=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_XRGB shl 20) or (SDL_PACKEDLAYOUT_1555 shl 16) or (15 shl 8) or (2 shl 0); SDL_PIXELFORMAT_BGR555=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_XBGR shl 20) or (SDL_PACKEDLAYOUT_1555 shl 16) or (15 shl 8) or (2 shl 0); SDL_PIXELFORMAT_ARGB4444=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_ARGB shl 20) or (SDL_PACKEDLAYOUT_4444 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_RGBA4444=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_RGBA shl 20) or (SDL_PACKEDLAYOUT_4444 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_ABGR4444=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_ABGR shl 20) or (SDL_PACKEDLAYOUT_4444 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_BGRA4444=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_BGRA shl 20) or (SDL_PACKEDLAYOUT_4444 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_ARGB1555=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_ARGB shl 20) or (SDL_PACKEDLAYOUT_1555 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_RGBA5551=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_RGBA shl 20) or (SDL_PACKEDLAYOUT_5551 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_ABGR1555=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_ABGR shl 20) or (SDL_PACKEDLAYOUT_1555 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_BGRA5551=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_BGRA shl 20) or (SDL_PACKEDLAYOUT_5551 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_RGB565=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_XRGB shl 20) or (SDL_PACKEDLAYOUT_565 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_BGR565=(1 shl 28) or (SDL_PIXELTYPE_PACKED16 shl 24) or (SDL_PACKEDORDER_XBGR shl 20) or (SDL_PACKEDLAYOUT_1555 shl 16) or (16 shl 8) or (2 shl 0); SDL_PIXELFORMAT_RGB24=(1 shl 28) or (SDL_PIXELTYPE_ARRAYU8 shl 24) or (SDL_ARRAYORDER_RGB shl 20) or (0 shl 16) or (24 shl 8) or (3 shl 0); SDL_PIXELFORMAT_BGR24=(1 shl 28) or (SDL_PIXELTYPE_ARRAYU8 shl 24) or (SDL_ARRAYORDER_BGR shl 20) or (0 shl 16) or (24 shl 8) or (3 shl 0); SDL_PIXELFORMAT_RGB888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_XRGB shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (24 shl 8) or (4 shl 0); SDL_PIXELFORMAT_RGBX8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_RGBX shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (24 shl 8) or (4 shl 0); SDL_PIXELFORMAT_BGR888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_XBGR shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (24 shl 8) or (4 shl 0); SDL_PIXELFORMAT_BGRX8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_BGRX shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (24 shl 8) or (4 shl 0); SDL_PIXELFORMAT_ARGB8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_ARGB shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (32 shl 8) or (4 shl 0); SDL_PIXELFORMAT_RGBA8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_RGBA shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (32 shl 8) or (4 shl 0); SDL_PIXELFORMAT_ABGR8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_ABGR shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (32 shl 8) or (4 shl 0); SDL_PIXELFORMAT_BGRA8888=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_RGBX shl 20) or (SDL_PACKEDLAYOUT_8888 shl 16) or (32 shl 8) or (4 shl 0); SDL_PIXELFORMAT_ARGB2101010=(1 shl 28) or (SDL_PIXELTYPE_PACKED32 shl 24) or (SDL_PACKEDORDER_ARGB shl 20) or (SDL_PACKEDLAYOUT_2101010 shl 16) or (32 shl 8) or (4 shl 0); SDL_PIXELFORMAT_YV12=(ord('Y') shl 0) or (ord('V') shl 8) or (ord('1') shl 16) or (ord('2') shl 24); SDL_PIXELFORMAT_IYUV=(ord('I') shl 0) or (ord('Y') shl 8) or (ord('U') shl 16) or (ord('V') shl 24); SDL_PIXELFORMAT_YUY2=(ord('Y') shl 0) or (ord('U') shl 8) or (ord('Y') shl 16) or (ord('2') shl 24); SDL_PIXELFORMAT_UYVY=(ord('U') shl 0) or (ord('Y') shl 8) or (ord('U') shl 16) or (ord('V') shl 24); SDL_PIXELFORMAT_NV12=(ord('N') shl 0) or (ord('V') shl 8) or (ord('1') shl 16) or (ord('2') shl 24); SDL_PIXELFORMAT_NV21=(ord('N') shl 0) or (ord('V') shl 8) or (ord('2') shl 16) or (ord('1') shl 24); {$ifdef fpc_big_endian} SDL_PIXELFORMAT_RGBA32=SDL_PIXELFORMAT_RGBA8888; SDL_PIXELFORMAT_ARGB32=SDL_PIXELFORMAT_ARGB8888; SDL_PIXELFORMAT_BGRA32=SDL_PIXELFORMAT_BGRA8888; SDL_PIXELFORMAT_ABGR32=SDL_PIXELFORMAT_ABGR8888; {$else} SDL_PIXELFORMAT_RGBA32=SDL_PIXELFORMAT_ABGR8888; SDL_PIXELFORMAT_ARGB32=SDL_PIXELFORMAT_BGRA8888; SDL_PIXELFORMAT_BGRA32=SDL_PIXELFORMAT_ARGB8888; SDL_PIXELFORMAT_ABGR32=SDL_PIXELFORMAT_RGBA8888; {$endif} SDL_TEXTUREACCESS_STATIC=0; SDL_TEXTUREACCESS_STREAMING=1; SDL_TEXTUREACCESS_TARGET=2; // SDL_GLprofile (enum) SDL_GL_CONTEXT_PROFILE_CORE=1; SDL_GL_CONTEXT_PROFILE_COMPATIBILITY=2; SDL_GL_CONTEXT_PROFILE_ES=4; // SDL_GLcontextFlag (enum) SDL_GL_CONTEXT_DEBUG_FLAG=1; SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG=2; SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG=4; SDL_GL_CONTEXT_RESET_ISOLATION_FLAG=8; SDL_CONTROLLER_BINDTYPE_NONE=0; SDL_CONTROLLER_BINDTYPE_BUTTON=1; SDL_CONTROLLER_BINDTYPE_AXIS=2; SDL_CONTROLLER_BINDTYPE_HAT=3; SDL_CONTROLLER_AXIS_INVALID=-1; SDL_CONTROLLER_AXIS_LEFTX=0; SDL_CONTROLLER_AXIS_LEFTY=1; SDL_CONTROLLER_AXIS_RIGHTX=2; SDL_CONTROLLER_AXIS_RIGHTY=3; SDL_CONTROLLER_AXIS_TRIGGERLEFT=4; SDL_CONTROLLER_AXIS_TRIGGERRIGHT=5; SDL_CONTROLLER_AXIS_MAX=6; SDL_CONTROLLER_BUTTON_INVALID=-1; SDL_CONTROLLER_BUTTON_A=0; SDL_CONTROLLER_BUTTON_B=1; SDL_CONTROLLER_BUTTON_X=2; SDL_CONTROLLER_BUTTON_Y=3; SDL_CONTROLLER_BUTTON_BACK=4; SDL_CONTROLLER_BUTTON_GUIDE=5; SDL_CONTROLLER_BUTTON_START=6; SDL_CONTROLLER_BUTTON_LEFTSTICK=7; SDL_CONTROLLER_BUTTON_RIGHTSTICK=8; SDL_CONTROLLER_BUTTON_LEFTSHOULDER=9; SDL_CONTROLLER_BUTTON_RIGHTSHOULDER=10; SDL_CONTROLLER_BUTTON_DPAD_UP=11; SDL_CONTROLLER_BUTTON_DPAD_DOWN=12; SDL_CONTROLLER_BUTTON_DPAD_LEFT=13; SDL_CONTROLLER_BUTTON_DPAD_RIGHT=14; SDL_CONTROLLER_BUTTON_MAX=15; SDL_LOG_CATEGORY_APPLICATION=0; SDL_LOG_CATEGORY_ERROR=1; SDL_LOG_CATEGORY_ASSERT=2; SDL_LOG_CATEGORY_SYSTEM=3; SDL_LOG_CATEGORY_AUDIO=4; SDL_LOG_CATEGORY_VIDEO=5; SDL_LOG_CATEGORY_RENDER=6; SDL_LOG_CATEGORY_INPUT=7; SDL_LOG_CATEGORY_TEST=8; SDL_LOG_CATEGORY_RESERVED1=9; SDL_LOG_CATEGORY_RESERVED2=10; SDL_LOG_CATEGORY_RESERVED3=11; SDL_LOG_CATEGORY_RESERVED4=12; SDL_LOG_CATEGORY_RESERVED5=13; SDL_LOG_CATEGORY_RESERVED6=14; SDL_LOG_CATEGORY_RESERVED7=15; SDL_LOG_CATEGORY_RESERVED8=16; SDL_LOG_CATEGORY_RESERVED9=17; SDL_LOG_CATEGORY_RESERVED10=18; SDL_LOG_CATEGORY_CUSTOM=19; SDL_HINT_FRAMEBUFFER_ACCELERATION='SDL_FRAMEBUFFER_ACCELERATION'; SDL_HINT_RENDER_DRIVER='SDL_RENDER_DRIVER'; SDL_HINT_RENDER_OPENGL_SHADERS='SDL_RENDER_OPENGL_SHADERS'; SDL_HINT_RENDER_DIRECT3D_THREADSAFE='SDL_RENDER_DIRECT3D_THREADSAFE'; SDL_HINT_RENDER_DIRECT3D11_DEBUG='SDL_RENDER_DIRECT3D11_DEBUG'; SDL_HINT_RENDER_SCALE_QUALITY='SDL_RENDER_SCALE_QUALITY'; SDL_HINT_RENDER_VSYNC='SDL_RENDER_VSYNC'; SDL_HINT_VIDEO_ALLOW_SCREENSAVER='SDL_VIDEO_ALLOW_SCREENSAVER'; SDL_HINT_VIDEO_X11_XVIDMODE='SDL_VIDEO_X11_XVIDMODE'; SDL_HINT_VIDEO_X11_XINERAMA='SDL_VIDEO_X11_XINERAMA'; SDL_HINT_VIDEO_X11_XRANDR='SDL_VIDEO_X11_XRANDR'; SDL_HINT_VIDEO_X11_NET_WM_PING='SDL_VIDEO_X11_NET_WM_PING'; SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN='SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN'; SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP='SDL_WINDOWS_ENABLE_MESSAGELOOP'; SDL_HINT_GRAB_KEYBOARD='SDL_GRAB_KEYBOARD'; SDL_HINT_MOUSE_RELATIVE_MODE_WARP='SDL_MOUSE_RELATIVE_MODE_WARP'; SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH='SDL_MOUSE_FOCUS_CLICKTHROUGH'; SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS='SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS'; SDL_HINT_IDLE_TIMER_DISABLED='SDL_IOS_IDLE_TIMER_DISABLED'; SDL_HINT_ORIENTATIONS='SDL_IOS_ORIENTATIONS'; SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS='SDL_APPLE_TV_CONTROLLER_UI_EVENTS'; SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION='SDL_APPLE_TV_REMOTE_ALLOW_ROTATION'; SDL_HINT_ACCELEROMETER_AS_JOYSTICK='SDL_ACCELEROMETER_AS_JOYSTICK'; SDL_HINT_XINPUT_ENABLED='SDL_XINPUT_ENABLED'; SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING='SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING'; SDL_HINT_GAMECONTROLLERCONFIG='SDL_GAMECONTROLLERCONFIG'; SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS='SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS'; SDL_HINT_ALLOW_TOPMOST='SDL_ALLOW_TOPMOST'; SDL_HINT_TIMER_RESOLUTION='SDL_TIMER_RESOLUTION'; SDL_HINT_THREAD_STACK_SIZE='SDL_THREAD_STACK_SIZE'; SDL_HINT_VIDEO_HIGHDPI_DISABLED='SDL_VIDEO_HIGHDPI_DISABLED'; SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK='SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK'; SDL_HINT_VIDEO_WIN_D3DCOMPILER='SDL_VIDEO_WIN_D3DCOMPILER'; SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT='SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT'; SDL_HINT_WINRT_PRIVACY_POLICY_URL='SDL_WINRT_PRIVACY_POLICY_URL'; SDL_HINT_WINRT_PRIVACY_POLICY_LABEL='SDL_WINRT_PRIVACY_POLICY_LABEL'; SDL_HINT_WINRT_HANDLE_BACK_BUTTON='SDL_WINRT_HANDLE_BACK_BUTTON'; SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES='SDL_VIDEO_MAC_FULLSCREEN_SPACES'; SDL_HINT_MAC_BACKGROUND_APP='SDL_MAC_BACKGROUND_APP'; SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION='SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION'; SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION='SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION'; SDL_HINT_IME_INTERNAL_EDITING='SDL_IME_INTERNAL_EDITING'; SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH='SDL_ANDROID_SEPARATE_MOUSE_AND_TOUCH'; SDL_HINT_MOUSE_TOUCH_EVENTS='SDL_MOUSE_TOUCH_EVENTS'; SDL_HINT_TOUCH_MOUSE_EVENTS='SDL_TOUCH_MOUSE_EVENTS'; SDL_HINT_ANDROID_BLOCK_ON_PAUSE='SDL_ANDROID_BLOCK_ON_PAUSE'; SDL_HINT_ANDROID_TRAP_BACK_BUTTON='SDL_ANDROID_TRAP_BACK_BUTTON'; SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT='SDL_EMSCRIPTEN_KEYBOARD_ELEMENT'; SDL_HINT_NO_SIGNAL_HANDLERS='SDL_NO_SIGNAL_HANDLERS'; SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4='SDL_WINDOWS_NO_CLOSE_ON_ALT_F4'; SDL_HINT_BMP_SAVE_LEGACY_FORMAT='SDL_BMP_SAVE_LEGACY_FORMAT'; SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING='SDL_WINDOWS_DISABLE_THREAD_NAMING'; SDL_HINT_RPI_VIDEO_LAYER='SDL_RPI_VIDEO_LAYER'; SDL_HINT_AUDIO_RESAMPLING_MODE='SDL_AUDIO_RESAMPLING_MODE'; SDL_HINT_WINRT_REMEMBER_WINDOW_FULLSCREEN_PREFERENCE='SDL_WINRT_REMEMBER_WINDOW_FULLSCREEN_PREFERENCE'; SDL_HINT_ANDROID_HIDE_SYSTEM_BARS='SDL_ANDROID_HIDE_SYSTEM_BARS'; SDL_HINT_MOUSE_NORMAL_SPEED_SCALE='SDL_MOUSE_NORMAL_SPEED_SCALE'; SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE='SDL_MOUSE_RELATIVE_SPEED_SCALE'; SDL_MESSAGEBOX_ERROR=$00000010; //**< error dialog */ SDL_MESSAGEBOX_WARNING=$00000020; //**< warning dialog */ SDL_MESSAGEBOX_INFORMATION=$00000040; //**< informational dialog */ SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT=$00000001; SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT=$00000002; SDL_MESSAGEBOX_COLOR_BACKGROUND=0; SDL_MESSAGEBOX_COLOR_TEXT=1; SDL_MESSAGEBOX_COLOR_BUTTON_BORDER=2; SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND=3; SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED=4; SDL_RWOPS_UNKNOWN=0; SDL_RWOPS_WINFILE=1; SDL_RWOPS_STDFILE=2; SDL_RWOPS_JNIFILE=3; SDL_RWOPS_MEMORY=4; SDL_RWOPS_MEMORY_RO=5; type PSDLInt8=^TSDLInt8; TSDLInt8={$ifdef fpc}Int8{$else}ShortInt{$endif}; PSDLUInt8=^TSDLUInt8; TSDLUInt8={$ifdef fpc}UInt8{$else}Byte{$endif}; PSDLInt16=^TSDLInt16; TSDLInt16={$ifdef fpc}Int16{$else}SmallInt{$endif}; PSDLUInt16=^TSDLUInt16; TSDLUInt16={$ifdef fpc}UInt16{$else}Word{$endif}; PSDLInt32=^TSDLInt32; TSDLInt32={$ifdef fpc}Int32{$else}LongInt{$endif}; PSDLUInt32=^TSDLUInt32; TSDLUInt32={$ifdef fpc}UInt32{$else}LongWord{$endif}; PSDLSizeInt=^TSDLSizeInt; TSDLSizeInt={$ifdef fpc}SizeInt{$else}NativeInt{$endif}; PSDLSizeUInt=^TSDLSizeUInt; TSDLSizeUInt={$ifdef fpc}SizeUInt{$else}NativeUInt{$endif}; PSDLInt64=^TSDLInt64; TSDLInt64=Int64; PSDLUInt64=^TSDLUInt64; TSDLUInt64=UInt64; PSDLFloat=^TSDLFloat; TSDLFloat=Single; PSDLDouble=^TSDLDouble; TSDLDouble=Double; PSDL_Window=pointer; PSDL_Renderer=pointer; PSDL_Texture=pointer; PSDL_GLContext=pointer; PSDL_HintPriority=^TSDL_HintPriority; TSDL_HintPriority= ( SDL_HINT_DEFAULT, SDL_HINT_NORMAL, SDL_HINT_OVERRIDE ); PSDL_GameControllerBindType=^TSDL_GameControllerBindType; TSDL_GameControllerBindType=TSDLInt32; PSDL_GameControllerBind=^TSDL_GameControllerBind; TSDL_GameControllerBind=record case BindType:TSDL_GameControllerBindType of SDL_CONTROLLER_BINDTYPE_BUTTON:( Button:TSDLInt32; ); SDL_CONTROLLER_BINDTYPE_AXIS:( Axis:TSDLInt32; ); SDL_CONTROLLER_BINDTYPE_HAT:( Hat:TSDLInt32; HatMask:TSDLInt32; ); end; PSDL_GameControllerAxis=^TSDL_GameControllerAxis; TSDL_GameControllerAxis=TSDLInt32; PSDL_GameControllerButton=^TSDL_GameControllerButton; TSDL_GameControllerButton=TSDLInt32; PSDL_AudioDeviceID=^TSDL_AudioDeviceID; TSDL_AudioDeviceID=TSDLUInt32; PSDL_BlendMode=^TSDL_BlendMode; TSDL_BlendMode=TSDLUInt32; PSDL_DisplayEventID=^TSDL_DisplayEventID; TSDL_DisplayEventID=TSDLUInt32; PSDL_DisplayOrientation=^TSDL_DisplayOrientation; TSDL_DisplayOrientation=TSDLUInt32; PSDL_RendererFlip=^TSDL_RendererFlip; TSDL_RendererFlip= ( SDL_FLIP_NONE=0, SDL_FLIP_HORIZONTAL=1, SDL_FLIP_VERTICAL=2 ); PSDL_RendererInfo=^TSDL_RendererInfo; TSDL_RendererInfo=record name:PAnsiChar; flags:TSDLUInt32; num_texture_formats:TSDLUInt32; texture_formats:array[0..15] of TSDLUInt32; max_texture_width:TSDLInt32; max_texture_height:TSDLInt32; end; PSDL_AudioStatus=^TSDL_AudioStatus; TSDL_AudioStatus=( SDL_AUDIO_STOPPED=0, SDL_AUDIO_PLAYING=1, SDL_AUDIO_PAUSED=2 ); PSDL_AudioFormat=^TSDL_AudioFormat; TSDL_AudioFormat=TSDLUInt16; TSDL_AudioSpecCallback=procedure(userdata:pointer;stream:PSDLUInt8;len:TSDLInt32); cdecl; PSDL_AudioSpec=^TSDL_AudioSpec; TSDL_AudioSpec=record freq:TSDLInt32; // DSP frequency -- samples per second format:TSDL_AudioFormat; // Audio data format channels:TSDLUInt8; // Number of channels:1 mono, 2 stereo silence:TSDLUInt8; // Audio buffer silence value (calculated) samples:TSDLUInt16; // Audio buffer size in samples padding:TSDLUInt16; // Necessary for some compile environments size:TSDLUInt32; // Audio buffer size in bytes (calculated) callback:TSDL_AudioSpecCallback; userdata:Pointer; end; PSDL_AudioCVT=^TSDL_AudioCVT; TSDL_AudioFilter=procedure(cvt:PSDL_AudioCVT;format:TSDL_AudioFormat); cdecl; TSDL_AudioCVT=record needed:TSDLInt32; src_format:TSDL_AudioFormat; dst_format:TSDL_AudioFormat; rate_incr:TSDLDouble; Buf:PSDLUInt8; len:TSDLInt32; len_cvt:TSDLInt32; len_mult:TSDLInt32; len_ratio:TSDLDouble; filters:array[0..9] of TSDL_AudioFilter; filter_index:TSDLInt32; end; PSDL_Rect=^TSDL_Rect; TSDL_Rect=record x,y,w,h:TSDLInt32; end; PSDL_Point=^TSDL_Point; TSDL_Point=record X,Y:TSDLInt32; end; PSDL_Color=^TSDL_Color; TSDL_Color=record case TSDLUInt8 of 0:( r:TSDLUInt8; g:TSDLUInt8; b:TSDLUInt8; a:TSDLUInt8; ); 1:( r_:TSDLUInt8; g_:TSDLUInt8; b_:TSDLUInt8; unused:TSDLUInt8; ); 2:( value:TSDLUInt32; ); end; PSDL_Colour=^TSDL_Colour; TSDL_Colour=TSDL_Color; PSDL_Palette=^TSDL_Palette; TSDL_Palette=record ncolors:TSDLInt32; colors:PSDL_Color; version:TSDLUInt32; refcount:TSDLInt32; end; PSDL_PixelFormat=^TSDL_PixelFormat; TSDL_PixelFormat=record format:TSDLUInt32; palette:PSDL_Palette; BitsPerPixel:TSDLUInt8; BytesPerPixel:TSDLUInt8; padding:array[0..1] of TSDLUInt8; RMask:TSDLUInt32; GMask:TSDLUInt32; BMask:TSDLUInt32; AMask:TSDLUInt32; Rloss:TSDLUInt8; Gloss:TSDLUInt8; Bloss:TSDLUInt8; Aloss:TSDLUInt8; Rshift:TSDLUInt8; Gshift:TSDLUInt8; Bshift:TSDLUInt8; Ashift:TSDLUInt8; refcount:TSDLInt32; next:PSDL_PixelFormat; end; SDL_eventaction=(SDL_ADDEVENT=0,SDL_PEEPEVENT,SDL_GETEVENT); PSDL_Surface=^TSDL_Surface; TSDL_Surface=record flags:TSDLUInt32; format:PSDL_PixelFormat; w,h:TSDLInt32; pitch:TSDLInt32; pixels:Pointer; offset:TSDLInt32; userdata:Pointer; locked:TSDLInt32; lock_data:Pointer; clip_rect:TSDL_Rect; map:Pointer; refcount:TSDLInt32; end; PSDL_RWops=^TSDL_RWops; TSeek=function(context:PSDL_RWops;offset:TSDLInt32;whence:TSDLInt32):TSDLInt32; cdecl; TRead=function(context:PSDL_RWops;Ptr:Pointer;size:TSDLInt32;maxnum:TSDLInt32):TSDLInt32; cdecl; TWrite=function(context:PSDL_RWops;Ptr:Pointer;size:TSDLInt32;num:TSDLInt32):TSDLInt32; cdecl; TClose=function(context:PSDL_RWops):TSDLInt32; cdecl; TStdio=record autoclose:boolean; fp:pointer; end; TMem=record base:PSDLUInt8; here:PSDLUInt8; stop:PSDLUInt8; end; TUnknown=record data1:pointer; end; TSDL_RWops=record seek:TSeek; read:TRead; write:TWrite; close:TClose; type_:TSDLUInt32; case TSDLUInt8 of 0:(stdio:TStdio); 1:(mem:TMem); 2:(unknown:TUnknown); 3:( AndroidIO:record fileNameRef:Pointer; inputStreamRef:Pointer; readableByteChannelRef:Pointer; readMethod:Pointer; assetFileDescriptorRef:Pointer; position:TSDLInt32; size:TSDLInt32; offset:TSDLInt32; fd:TSDLInt32; end; ); 4:( WindowsIO:record Append:TSDLUInt8; h:Pointer; Buffer:record Data:Pointer; Size:TSDLSizeUInt; Left:TSDLSizeUInt; end; end; ); end; PSDL_version=^TSDL_version; TSDL_version=record major:TSDLUInt8; minor:TSDLUInt8; patch:TSDLUInt8; end; TSDL_SysWm=TSDLInt32; {$if defined(Windows)} // The Windows custom event structure PSDL_SysWMmsg=^TSDL_SysWMmsg; TSDL_SysWMmsg=record version:TSDL_version; subsystem:TSDL_SysWm; h_wnd:HWND; // The window for the message msg:UInt; // The type of message w_Param:WPARAM; // TSDLUInt16 message parameter lParam:LPARAM; // LONG message parameter end; {$elseif defined(Unix)} // The Unix custom event structure PSDL_SysWMmsg=^TSDL_SysWMmsg; TSDL_SysWMmsg=record version:TSDL_version; subsystem:TSDL_SysWm; {$if not (defined(GP2X) or defined(Darwin) or defined(SkyOS) or defined(Android))} event:TXEvent; {$ifend} end; {$else} // The generic custom event structure PSDL_SysWMmsg=^TSDL_SysWMmsg; TSDL_SysWMmsg=record version:TSDL_version; data:TSDLInt32; end; {$ifend} {$if defined(Windows)} // The Windows custom window manager information structure PSDL_SysWMinfo=^TSDL_SysWMinfo; TSDL_SysWMinfo=record version:TSDL_version; subsystem:TSDL_SysWm; window:HWnd; // The display window hdc_:Hdc; hinstance:HModule; end; {$elseif defined(Android)} // The Windows custom window manager information structure PSDL_SysWMinfo=^TSDL_SysWMinfo; TSDL_SysWMinfo=record version:TSDL_version; subsystem:TSDL_SysWm; window:PANativeWindow; // The display window EGLsurface:pointer; end; {$elseif defined(Unix)} // The Unix custom window manager information structure {$if not (defined(GP2X) or defined(Darwin) or defined(SkyOS) or defined(Android))} TSDL_SysWMinfoX11=record display:PDisplay; // The X11 display window:TWindow ; // The X11 display window */ lock_func:Pointer; unlock_func:Pointer; fswindow:TWindow ; // The X11 fullscreen window */ wmwindow:TWindow ; // The X11 managed input window */ end; TSDL_SysWMinfoWayland=record display:pointer; surface:pointer; shell_surface:pointer; end; TSDL_SysWMinfoMIR=record connection:pointer; surface:pointer; end; {$ifend} PSDL_SysWMinfo=^TSDL_SysWMinfo; TSDL_SysWMinfo=record version:TSDL_version ; subsystem:TSDL_SysWm; {$if not (defined(GP2X) or defined(Darwin) or defined(SkyOS) or defined(Android))} case TSDL_SysWm of 0:( X11:TSDL_SysWMinfoX11; ); 1:( Wayland:TSDL_SysWMinfoWayland; ); 2:( Mir:TSDL_SysWMinfoMir; ); {$ifend} end; {$else} // The generic custom window manager information structure PSDL_SysWMinfo=^TSDL_SysWMinfo; TSDL_SysWMinfo=record version:TSDL_version; subsystem:TSDL_SysWm; data:TSDLInt32; end; {$ifend} // SDL_Event type definition TSDL_KeySym=record scancode:TSDLInt32; sym:TSDLInt32; modifier:TSDLUInt16; unicode:TSDLUInt32; end; TSDL_DisplayEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; event:TSDLUInt8; padding1,padding2,padding3:TSDLUInt8; data1:TSDLInt32; end; TSDL_WindowEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; event:TSDLUInt8; padding1,padding2,padding3:TSDLUInt8; data1,data2:TSDLInt32; end; // available in sdl12 but not exposed TSDL_TextEditingEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; text:array[0..31] of TSDLUInt8; start,lenght:TSDLInt32; end; // available in sdl12 but not exposed TSDL_TextInputEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; text:array[0..31] of TSDLUInt8; end; TSDL_TouchFingerEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; touchId:int64; fingerId:int64; x:single; y:single; dx:single; dy:single; pressure:single; end; TSDL_MultiGestureEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowId:TSDLUInt32; touchId:int64; dTheta,dDist,x,y:Single; numFingers,padding:TSDLUInt16; end; TSDL_DollarGestureEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowId:TSDLUInt32; touchId:int64; gesturedId:int64; numFingers:TSDLUInt32; error:Single; end; TSDL_SysWMEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; msg:PSDL_SysWMmsg; end; TSDL_DropEvent=record type_:TSDLUInt32; TimeStamp:TSDLUInt32; FileName:pansichar; end; TSDL_KeyboardEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; state, repeat_, padding2, padding3:TSDLUInt8; keysym:TSDL_KeySym; end; TSDL_MouseMotionEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; which:TSDLUInt32; state:TSDLUInt32; x:TSDLInt32; y:TSDLInt32; xrel:TSDLInt32; yrel:TSDLInt32; end; TSDL_MouseButtonEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt32; windowID:TSDLUInt32; button:TSDLUInt8; state:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; x:TSDLInt32; y:TSDLInt32; end; TSDL_MouseWheelEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; which:TSDLUInt32; x:TSDLInt32; y:TSDLInt32; Direction:TSDLInt32; end; TSDL_JoyAxisEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt8; axis:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; padding3:TSDLUInt8; value:TSDLInt16; padding4:TSDLUInt16; end; TSDL_JoyBallEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt8; ball:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; padding3:TSDLUInt8; xrel:TSDLInt16; yrel:TSDLInt16; end; TSDL_JoyHatEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt8; hat:TSDLUInt8; value:TSDLUInt8; padding1:TSDLUInt8; end; TSDL_JoyButtonEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt8; button:TSDLUInt8; state:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; end; TSDL_JoyDeviceEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLInt32; padding1:TSDLUInt8; end; TSDL_ControllerAxisEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLUInt8; axis:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; padding3:TSDLUInt8; value:TSDLInt16; padding4:TSDLUInt16; end; TSDL_ControllerButtonEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; button:TSDLUInt8; state:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; end; TSDL_ControllerDeviceEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLInt32; end; TSDL_AudioDeviceEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLInt32; iscapture:TSDLUInt8; padding1:TSDLUInt8; padding2:TSDLUInt8; padding3:TSDLUInt8; end; TSDL_SensorEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; which:TSDLInt32; Data:array[0..5] of TSDLFloat; end; TSDL_QuitEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; end; TSDL_UserEvent=record type_:TSDLUInt32; timeStamp:TSDLUInt32; windowID:TSDLUInt32; code:TSDLInt32; data1,data2:Pointer; end; PSDL_Event=^TSDL_Event; TSDL_Event=record case TSDLInt32 of SDL_FIRSTEVENT:(type_:TSDLInt32); SDL_DISPLAYEVENT:(display:TSDL_DisplayEvent); SDL_WINDOWEVENT:(window:TSDL_WindowEvent); SDL_KEYDOWN, SDL_KEYUP:(key:TSDL_KeyboardEvent); SDL_TEXTEDITING:(edit:TSDL_TextEditingEvent); SDL_TEXTINPUT:(tedit:TSDL_TextInputEvent); SDL_MOUSEMOTION:(motion:TSDL_MouseMotionEvent); SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP:(button:TSDL_MouseButtonEvent); SDL_MOUSEWHEEL:(wheel:TSDL_MouseWheelEvent); SDL_JOYAXISMOTION:(jaxis:TSDL_JoyAxisEvent); SDL_JOYBALLMOTION:(jball:TSDL_JoyBallEvent); SDL_JOYHATMOTION:(jhat:TSDL_JoyHatEvent); SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:(jbutton:TSDL_JoyButtonEvent); SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED:(jdevice:TSDL_JoyDeviceEvent); SDL_CONTROLLERAXISMOTION:(caxis:TSDL_ControllerAxisEvent); SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP:(cbutton:TSDL_ControllerButtonEvent); SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED:(cdevice:TSDL_ControllerDeviceEvent); SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED:(adevice:TSDL_AudioDeviceEvent); SDL_SENSORUPDATE:(sensor:TSDL_SensorEvent); SDL_QUITEV:(quit:TSDL_QuitEvent); SDL_USEREVENT:(user:TSDL_UserEvent); SDL_SYSWMEVENT:(syswm:TSDL_SysWMEvent); SDL_FINGERDOWN, SDL_FINGERUP, SDL_FINGERMOTION:(tfinger:TSDL_TouchFingerEvent); SDL_MULTIGESTURE:(mgesture:TSDL_MultiGestureEvent); SDL_DOLLARGESTURE:(dgesture:TSDL_DollarGestureEvent); SDL_DROPFILE:(drop:TSDL_DropEvent); TSDLInt32(SDL_ALLEVENTS):(foo:shortstring); end; TSDL_EventFilter=function(event:PSDL_Event):TSDLInt32; cdecl; PSDL_MessageBoxColor=^TSDL_MessageBoxColor; TSDL_MessageBoxColor=record r,g,b:TSDLUInt8; end; PSDL_MessageBoxColorScheme=^TSDL_MessageBoxColorScheme; TSDL_MessageBoxColorScheme=record colors:array[0..4] of TSDL_MessageBoxColor; end; PSDL_MessageBoxButtonData=^TSDL_MessageBoxButtonData; TSDL_MessageBoxButtonData=record flags:TSDLUInt32; buttonid:TSDLInt32; text:PAnsiChar; end; PSDL_MessageBoxData=^TSDL_MessageBoxData; TSDL_MessageBoxData=record flags:TSDLUInt32; window:PSDL_Window; title:PAnsiChar; message:PAnsiChar; numbuttons:TSDLInt32; buttons:PSDL_MessageBoxButtonData; colorScheme:PSDL_MessageBoxColorScheme; end; PSDLUInt8Array=^TSDLUInt8Array; TSDLUInt8Array=array[0..65535] of TSDLUInt8; PSDLUInt32Array=^TSDLUInt32Array; TSDLUInt32Array=array[0..16383] of TSDLUInt32; PSDL_Thread=Pointer; PSDL_mutex=Pointer; TSDL_GLattr= ( SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_RETAINED_BACKING, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_EGL, SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_SHARE_WITH_CURRENT_CONTEXT, SDL_GL_FRAMEBUFFER_SRGB_CAPABLE ); { TSDL_ArrayByteOrder= // array component order, low TSDLUInt8 -> high TSDLUInt8 ( SDL_ARRAYORDER_NONE, SDL_ARRAYORDER_RGB, SDL_ARRAYORDER_RGBA, SDL_ARRAYORDER_ARGB, SDL_ARRAYORDER_BGR, SDL_ARRAYORDER_BGRA, SDL_ARRAYORDER_ABGR );} TSDL_PixelFormatEnum=TSDLInt32; // Joystick/Controller support PSDL_Joystick=^TSDL_Joystick; TSDL_Joystick=record end; PSDL_GameController=^TSDL_GameController; TSDL_GameController=record end; PSDL_DisplayMode=^TSDL_DisplayMode; TSDL_DisplayMode=record format:TSDLUInt32; w:TSDLInt32; h:TSDLInt32; refrsh_rate:TSDLInt32; driverdata:pointer; end; PSDL_LogCategory=^TSDL_LogCategory; TSDL_LogCategory=TSDLInt32; TSDL_LogPriority= ( SDL_LOG_PRIORITY_VERBOSE=1, SDL_LOG_PRIORITY_DEBUG, SDL_LOG_PRIORITY_INFO, SDL_LOG_PRIORITY_WARN, SDL_LOG_PRIORITY_ERROR, SDL_LOG_PRIORITY_CRITICAL, SDL_NUM_LOG_PRIORITIES ); PSDL_LogOutputCallback=^TSDL_LogOutputCallback; TSDL_LogOutputCallback=procedure(UserData:pointer;category:TSDLInt32;priority:TSDL_LogPriority;message:PAnsiChar); cdecl; TSDL_HintCallback=procedure(userdata:pointer;name,oldValue,newValue:PAnsiChar); cdecl; {$ifdef android} procedure SDL_Android_Init(Env:PJNIEnv;cls:JClass); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$endif} procedure SDL_SetMainReady(); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_Init(flags:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_InitSubSystem(flags:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_Quit; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_Delay(msec:TSDLUInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetTicks:TSDLUInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetPerformanceCounter:uint64; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetPerformanceFrequency:uint64; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_LockSurface(Surface:PSDL_Surface):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_UnlockSurface(Surface:PSDL_Surface); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_LockTexture(Texture:PSDL_Texture;rect:PSDL_Rect;const Pixels,Pitch:pointer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_UnlockTexture(Texture:PSDL_Texture); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_QueryTexture(Texture:PSDL_Texture;format:PSDLUInt32;access,w,h:PSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_BindTexture(Texture:PSDL_Texture;texW,texH:PSDLFloat):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_UnbindTexture(Texture:PSDL_Texture):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetTextureAlphaMod(Texture:PSDL_Texture;alpha:PSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_UpdateTexture(Texture:PSDL_Texture;rect:PSDL_Rect;format:TSDLUInt32;pixels:Pointer;pitch:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_UpdateYUVTexture(Texture:PSDL_Texture;rect:PSDL_Rect;Yplane:Pointer;Ypitch:TSDLInt32;Uplane:Pointer;Upitch:TSDLInt32;Vplane:Pointer;Vpitch:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetTextureAlphaMod(Texture:PSDL_Texture;alpha:TSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetTextureColorMod(Texture:PSDL_Texture;r,g,b:PSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetTextureColorMod(Texture:PSDL_Texture;r,g,b:TSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetTextureBlendMode(Texture:PSDL_Texture;blend_mode:PSDL_BlendMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetTextureBlendMode(Texture:PSDL_Texture;blend_mode:TSDL_BlendMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetError:pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetVideoMode(width,height,bpp:TSDLInt32;flags:TSDLUInt32):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateRGBSurface(flags:TSDLUInt32;Width,Height,Depth:TSDLInt32;RMask,GMask,BMask,AMask:TSDLUInt32):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateRGBSurfaceFrom(pixels:Pointer;width,height,depth,pitch:TSDLInt32;RMask,GMask,BMask,AMask:TSDLUInt32):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateRGBSurfaceWithFormat(flags:TSDLUInt32;width,height,depth:TSDLInt32;format:TSDLUInt32):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_FreeSurface(Surface:PSDL_Surface); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetColorKey(surface:PSDL_Surface;flag,key:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetAlpha(surface:PSDL_Surface;flag,key:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_ConvertSurface(src:PSDL_Surface;fmt:PSDL_PixelFormat;flags:TSDLInt32):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_UpperBlit(src:PSDL_Surface;srcrect:PSDL_Rect;dst:PSDL_Surface;dstrect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_FillRect(dst:PSDL_Surface;dstrect:PSDL_Rect;color:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_UpdateRect(Screen:PSDL_Surface;x,y:TSDLInt32;w,h:TSDLUInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_Flip(Screen:PSDL_Surface):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GetRGB(pixel:TSDLUInt32;fmt:PSDL_PixelFormat;r,g,b:PSDLUInt8); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GetRGBA(pixel:TSDLUInt32;fmt:PSDL_PixelFormat;r,g,b,a:PSDLUInt8); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_MapRGB(format:PSDL_PixelFormat;r,g,b:TSDLUInt8):TSDLUInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_MapRGBA(format:PSDL_PixelFormat;r,g,b,a:TSDLUInt8):TSDLUInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_DisplayFormat(Surface:PSDL_Surface):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_DisplayFormatAlpha(Surface:PSDL_Surface):PSDL_Surface; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RWFromFile(filename,mode:pansichar):PSDL_RWops; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RWFromMem(mem:Pointer;size:TSDLInt32):PSDL_RWops; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RWFromConstMem(mem:Pointer;size:TSDLInt32):PSDL_RWops; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SaveBMP_RW(surface:PSDL_Surface;dst:PSDL_RWops;freedst:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_AllocRW:PSDL_RWops; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_FreeRW(rw:PSDL_RWops); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetClipboardText:PAnsiChar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetClipboardText(const Text:PAnsiChar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_HasClipboardText:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetWindowTitle(window:PSDL_Window;title:pansichar); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetWindowFullscreen(window:PSDL_Window;fullscreen:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetWindowSize(window:PSDL_Window;x,y:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetWindowPosition(window:PSDL_Window;x,y:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetWindowResizable(window:PSDL_Window;b:boolean); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetWindowBordered(window:PSDL_Window;b:boolean); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetWindowFlags(window:PSDL_Window):TSDLUInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GetWindowSize(window:PSDL_Window;var x,y:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GetWindowPosition(window:PSDL_Window;var x,y:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateWindow(title:pansichar;x,y,w,h:TSDLInt32;flags:TSDLUInt32):PSDL_Window; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateRenderer(window:PSDL_Window;index:TSDLInt32;flags:TSDLUInt32):PSDL_Renderer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateTexture(renderer:PSDL_Texture;format:TSDLUInt32;access,w,h:TSDLInt32):PSDL_Texture; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_DestroyWindow(window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_DestroyRenderer(renderer:PSDL_Renderer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_DestroyTexture(texture:PSDL_Texture):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_MinimizeWindow(window:PSDL_Window); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_MaximizeWindow(window:PSDL_Window); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_RestoreWindow(window:PSDL_Window); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_MakeCurrent(window:PSDL_Window;context:PSDL_GLContext):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_CreateContext(window:PSDL_Window):PSDL_GLContext; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GL_DeleteContext(context:PSDL_GLContext); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_SwapWindow(window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_GetDrawableSize(window:PSDL_Window;w,h:PSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_SetSwapInterval(interval:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_VideoQuit; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumVideoDisplays:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumVideoDrivers:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetVideoDriver(Index:TSDLInt32):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetCurrentVideoDriver:pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_VideoInit(drivername:pansichar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_ShowWindow(window:PSDL_Window); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumRenderDrivers:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetRenderDrawBlendMode(renderer:PSDL_Renderer;blendMode:TSDL_BlendMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRenderDrawBlendMode(renderer:PSDL_Renderer;blendMode:PSDL_BlendMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetRenderDrawColor(renderer:PSDL_Renderer;r,g,b,a:TSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRenderDrawColor(renderer:PSDL_Renderer;r,g,b,a:PSDLUInt8):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRenderer(window:PSDL_Window):PSDL_Renderer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRendererTarget(renderer:PSDL_Renderer):PSDL_Texture; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRendererDriverInfo(index:TSDLInt32;info:PSDL_RendererInfo):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRendererInfo(renderer:PSDL_Renderer;info:PSDL_RendererInfo):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRendererOutputSize(renderer:PSDL_Renderer;w,h:PSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderFillRect(renderer:PSDL_Renderer;rect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderFillRects(renderer:PSDL_Renderer;rects:PSDL_Rect;Count:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawLine(renderer:PSDL_Renderer;x1,y1,x2,y2:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawLines(renderer:PSDL_Renderer;points:PSDL_Point;count:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawPoint(renderer:PSDL_Renderer;x,y:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawPoints(renderer:PSDL_Renderer;points:PSDL_Point;count:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawRect(renderer:PSDL_Renderer;rect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderDrawRects(renderer:PSDL_Renderer;rects:PSDL_Rect;count:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderClear(renderer:PSDL_Renderer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderCopy(renderer:PSDL_Renderer;texture:PSDL_Texture;srcrect,dstrect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderCopyEx(renderer:PSDL_Renderer;texture:PSDL_Texture;srcrect,dstrect:PSDL_Rect;angle:TSDLDouble;center:PSDL_Point;flip:TSDL_RendererFlip):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_RenderPresent(renderer:PSDL_Renderer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderReadPixels(renderer:PSDL_Renderer;rect:PSDL_Rect;format:TSDLUInt32;pixels:Pointer;pitch:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderSetViewport(window:PSDL_Window;rect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_RenderGetClipRect(renderer:PSDL_Renderer;rect:PSDL_Rect); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderGetIntegerScale(renderer:PSDL_Renderer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderGetLogicalSize(renderer:PSDL_Renderer;w,h:PSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderGetScale(renderer:PSDL_Renderer;scaleX,scaleY:PSDLFloat):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderGetViewport(renderer:PSDL_Renderer;rect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderIsClipEnabled(renderer:PSDL_Renderer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderSetClipRect(renderer:PSDL_Renderer;rect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderSetIntegerScale(renderer:PSDL_Renderer;enable:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderSetLogicalSize(renderer:PSDL_Renderer;w,h:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderSetScale(renderer:PSDL_Renderer;scaleX,scaleY:TSDLFloat):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RenderTargetSupported(renderer:PSDL_Renderer):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetRenderTarget(renderer:PSDL_Renderer;texture:PSDL_Texture):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRelativeMouseMode:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetRelativeMouseMode(enabled:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRelativeMouseState(x,y:PLongInt):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_PixelFormatEnumToMasks(format:{TSDL_ArrayByteOrder}TSDLInt32;bpp:PLongInt;Rmask,Gmask,Bmask,Amask:PLongInt):Boolean; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_WarpMouseInWindow(window:PSDL_Window;x,y:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_StartTextInput; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_StopTextInput; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_PeepEvents(event:PSDL_Event; numevents:TSDLInt32;action:SDL_eventaction;minType,maxType:TSDLUInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateThread(fn:Pointer;name:pansichar;data:Pointer):PSDL_Thread; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetMouseState(x,y:PLongInt):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetKeyName(key:TSDLUInt32):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_PumpEvents; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_PushEvent(event:PSDL_Event):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_PollEvent(event:PSDL_Event):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_WaitEvent(event:PSDL_Event):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_SetEventFilter(filter:TSDL_EventFilter); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_ShowCursor(toggle:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_malloc(Size:TSDLInt32):pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_realloc(mem:pointer;Size:TSDLInt32):pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_free(mem:pointer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_EventState(type_:TSDLUInt32;state:TSDLInt32):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_WM_SetIcon(icon:PSDL_Surface;mask:TSDLUInt8); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_WM_SetCaption(title:pansichar;icon:pansichar); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_WM_ToggleFullScreen(surface:PSDL_Surface):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_WaitThread(thread:PSDL_Thread;status:PLongInt); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_CreateMutex:PSDL_mutex; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_DestroyMutex(mutex:PSDL_mutex); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_LockMutex(mutex:PSDL_mutex):TSDLInt32; cdecl; external SDL2LibName name 'SDL_mutexP'; function SDL_UnlockMutex(mutex:PSDL_mutex):TSDLInt32; cdecl; external SDL2LibName name 'SDL_mutexV'; function SDL_GL_GetAttribute(attr:TSDL_GLAttr;var value:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_SetAttribute(attr:TSDL_GLattr;value:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GL_SwapBuffers(); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_NumJoysticks:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickName(joy:PSDL_Joystick):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickInstanceID(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickOpen(idx:TSDLInt32):PSDL_Joystick; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickOpened(idx:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickIndex(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickNumAxes(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickNumBalls(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickNumHats(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickNumButtons(joy:PSDL_Joystick):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_JoystickUpdate; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickEventState(state:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetGUID(joy:PSDL_Joystick):TGUID; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetDeviceGUID(joy:PSDL_Joystick):TGUID; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetAxis(joy:PSDL_Joystick;axis:TSDLInt32):TSDLInt16; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetBall(joy:PSDL_Joystick;ball:TSDLInt32;dx:PInteger;dy:PInteger):Word; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetHat(joy:PSDL_Joystick;hat:TSDLInt32):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_JoystickGetButton(joy:PSDL_Joystick;button:TSDLInt32):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_JoystickClose(joy:PSDL_Joystick); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_IsGameController(idx:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerOpen(idx:TSDLInt32):PSDL_GameController; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GameControllerClose(gamecontroller:PSDL_GameController); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_GameControllerUpdate; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerAddMapping(mappingString:pansichar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerAddMappingsFromFile(filename:pansichar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerAddMappingsFromRW(rw:pointer;freerw:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerEventState(state:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetAttached(gamecontroller:PSDL_GameController):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetAxis(gamecontroller:PSDL_GameController;axis:TSDL_GameControllerAxis):TSDLInt16; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetAxisFromString(pchString:pansichar):TSDL_GameControllerAxis; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetBindForAxis(gamecontroller:PSDL_GameController;axis:TSDL_GameControllerAxis):TSDL_GameControllerBindType; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetBindForButton(gamecontroller:PSDL_GameController;button:TSDL_GameControllerButton):TSDL_GameControllerBindType; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetButton(gamecontroller:PSDL_GameController;button:TSDL_GameControllerButton):TSDLUInt8; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetButtonFromString(pchString:pansichar):TSDL_GameControllerButton; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetJoystick(gamecontroller:PSDL_GameController):PSDL_Joystick; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetStringForAxis(axis:TSDL_GameControllerAxis):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerGetStringForButton(button:TSDL_GameControllerButton):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerMapping(gamecontroller:PSDL_GameController):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerMappingForGUID(const guid:TGUID):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerName(gamecontroller:PSDL_GameController):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GameControllerNameForIndex(idx:TSDLInt32):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_LoadLibrary(filename:pansichar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GL_GetProcAddress(procname:pansichar):Pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetModState:TSDLUInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_AudioInit(const aDriverName:PAnsiChar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_AudioQuit; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_BuildAudioCVT(cvt:PSDL_AudioCVT;src_format:TSDL_AudioFormat;src_channels:TSDLUInt8;src_rate:TSDLInt32;dst_format:TSDL_AudioFormat;dst_channels:TSDLUInt8;dst_rate:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LockAudio; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_UnlockAudio; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LockAudioDevice(dev:TSDL_AudioDeviceID); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_UnlockAudioDevice(dev:TSDL_AudioDeviceID); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_CloseAudio; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_CloseAudioDevice(dev:TSDL_AudioDeviceID); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetCurrentAudioDriver:PAnsiChar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetAudioDriver(index:TSDLInt32):PAnsiChar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumAudioDrivers:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumAudioDevices(iscapture:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetAudioDeviceName(index,iscapture:TSDLInt32):PAnsiChar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_OpenAudio(desired,obtained:PSDL_AudioSpec):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_OpenAudioDevice(device:PAnsiChar;iscapture:TSDLInt32;desired,obtained:PSDL_AudioSpec;allowed_changes:TSDLInt32):TSDL_AudioDeviceID; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetAudioStatus:TSDL_AudioStatus; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetAudioDeviceStatus(dev:TSDL_AudioDeviceID):TSDL_AudioStatus; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_PauseAudio(pause_on:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_PauseAudioDevice(dev:TSDL_AudioDeviceID;pause_on:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_FreeWAV(audio_buf:PSDLUInt8); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_LoadWAV_RW(src:PSDL_RWops;freesrc:TSDLInt32;spec:PSDL_AudioSpec;audio_buf:PSDLUInt8;audio_len:PSDLUInt32):PSDL_AudioSpec; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_ConvertAudio(cvt:PSDL_AudioCVT); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_MixAudio(dst,src:PSDLUInt8;len:TSDLUInt32;volume:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_MixAudioFormat(dst,src:PSDLUInt8;format:TSDL_AudioFormat;len:TSDLUInt32;volume:TSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; //function SDL_BlitSurface(src:PSDL_Surface;srcrect:PSDL_Rect;dst:PSDL_Surface;dstrect:PSDL_Rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$ifdef Windows} function SDL_putenv(const text:pansichar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_getenv(const text:pansichar):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$endif} //procedure SDL_WarpMouse(x,y:Word); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetKeyboardState(numkeys:PLongInt):PByteArray; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_AllocFormat(format:TSDLUInt32):PSDL_PixelFormat; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_FreeFormat(pixelformat:PSDL_PixelFormat); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; //function SDL_VideoDriverName(namebuf:pansichar;maxlen:TSDLInt32):pansichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_BUTTON(Button:TSDLInt32):TSDLInt32; function SDL_GetClosestDisplayMode(displayIndex:TSDLInt32;mode,closest:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetCurrentDisplayMode(displayIndex:TSDLInt32;mode:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetDesktopDisplayMode(displayIndex:TSDLInt32;mode:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetDisplayBounds(displayIndex:TSDLInt32;rect:PSDL_rect):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetDisplayMode(displayIndex,modeIndex:TSDLInt32;mode:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetNumDisplayModes(displayIndex:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetWindowDisplayIndex(window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetWindowDisplayMode(window:PSDL_Window;mode:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetWindowDisplayMode(window:PSDL_Window;mode:PSDL_DisplayMode):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetWindowWMInfo(window:PSDL_Window;info:PSDL_SysWMinfo):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetWindowInputFocus(window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_RaiseWindow(window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_DisableScreenSaver; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_EnableScreenSaver; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_IsScreenSaverEnabled:TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetScancodeFromKey(KeyCode:TSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogSetAllPriority(priority:TSDL_LogPriority); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogSetPriority(category:TSDL_LogCategory;priority:TSDL_LogPriority); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_LogGetPriority(category:TSDL_LogCategory):TSDL_LogPriority; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogResetPriorities; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_Log(const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogVerbose(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogDebug(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogInfo(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogWarn(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogError(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogCritical(category:TSDL_LogCategory;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogMessage(category:TSDL_LogCategory;priority:TSDL_LogPriority;const fmt:PAnsiChar); cdecl; varargs; external {$ifndef staticlink}SDL2LibName{$endif}; //procedure SDL_LogMessageV(category:TSDL_LogCategory;priority:TSDL_LogPriority;const fmt:PAnsiChar;ap:TVA_List); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogGetOutputFunction(LogCallback:PSDL_LogOutputCallback;UserData:PPointer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_LogSetOutputFunction(LogCallback:TSDL_LogOutputCallback;UserData:pointer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_ShowMessageBox(const messageboxdata:PSDL_MessageBoxData;const buttonid:PSDLInt32):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_ShowSimpleMessageBox(flags:TSDLUInt32;title,message_:PAnsiChar;window:PSDL_Window):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetHintWithPriority(name,value:PAnsiChar;priority:TSDL_HintPriority):boolean; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_SetHint(name,value:PAnsichar):boolean; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetHint(name:PAnsichar):PAnsichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetHintBoolean(name:PAnsichar;default_value:boolean):PAnsichar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_AddHintCallback(name:PAnsichar;callback:TSDL_HintCallback;userdata:pointer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_DelHintCallback(name:PAnsichar;callback:TSDL_HintCallback;userdata:pointer); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_ClearHints; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$if defined(Android)} function SDL_AndroidGetJNIEnv:pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_AndroidGetActivity:pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$ifend} {$if defined(PasVulkanUseSDL2WithVulkanSupport)} {$if defined(PasVulkanUseSDL2WithStaticVulkanSupport)} function SDL_Vulkan_LoadLibrary(path:PAnsiChar):TSDLInt32; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_Vulkan_GetVkGetInstanceProcAddr:pointer; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_Vulkan_UnloadLibrary; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_Vulkan_GetInstanceExtensions(window:PSDL_Window;pCount:PSDLUInt32;names:pointer{PPAnsiChar}):boolean; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_Vulkan_CreateSurface(window:PSDL_Window;instance_:TVkInstance;surface:PVkSurfaceKHR):boolean; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_Vulkan_GetDrawableSize(window:PSDL_Window;w,h:PSDLInt32); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; {$else} type TSDL_Vulkan_LoadLibrary=function(path:PAnsiChar):TSDLInt32; cdecl; TSDL_Vulkan_GetVkGetInstanceProcAddr=function:pointer; cdecl; TSDL_Vulkan_UnloadLibrary=procedure; cdecl; TSDL_Vulkan_GetInstanceExtensions=function(window:PSDL_Window;pCount:PSDLUInt32;names:pointer{PPAnsiChar}):boolean; cdecl; TSDL_Vulkan_CreateSurface=function(window:PSDL_Window;instance_:TVkInstance;surface:PVkSurfaceKHR):boolean; cdecl; TSDL_Vulkan_GetDrawableSize=procedure(window:PSDL_Window;w,h:PSDLInt32); cdecl; var SDL_Vulkan_LoadLibrary:TSDL_Vulkan_LoadLibrary=nil; SDL_Vulkan_GetVkGetInstanceProcAddr:TSDL_Vulkan_GetVkGetInstanceProcAddr=nil; SDL_Vulkan_UnloadLibrary:TSDL_Vulkan_UnloadLibrary=nil; SDL_Vulkan_GetInstanceExtensions:TSDL_Vulkan_GetInstanceExtensions=nil; SDL_Vulkan_CreateSurface:TSDL_Vulkan_CreateSurface=nil; SDL_Vulkan_GetDrawableSize:TSDL_Vulkan_GetDrawableSize=nil; {$define PasVulkanUseDynamicSDL2} {$ifend} {$ifend} {$ifdef PasVulkanUseDynamicSDL2} var SDL_Library:pointer=nil; {$endif} procedure SDL_GetVersion(out Version:TSDL_Version); cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; function SDL_GetRevision:PAnsiChar; cdecl; external {$ifndef staticlink}SDL2LibName{$endif}; procedure SDL_VERSION(out Version:TSDL_Version); implementation {$ifdef PasVulkanUseDynamicSDL2} function sdl2LoadLibrary(const LibraryName:string):pointer; {$ifdef CAN_INLINE}inline;{$endif} begin {$ifdef Windows} result:={%H-}pointer(LoadLibrary(PChar(LibraryName))); {$else} {$ifdef Unix} result:=dlopen(PChar(LibraryName),RTLD_NOW or RTLD_LAZY); {$else} result:=nil; {$endif} {$endif} end; function sdl2FreeLibrary(LibraryHandle:pointer):boolean; {$ifdef CAN_INLINE}inline;{$endif} begin result:=assigned(LibraryHandle); if result then begin {$ifdef Windows} result:=FreeLibrary({%H-}HMODULE(LibraryHandle)); {$else} {$ifdef Unix} result:=dlclose(LibraryHandle)=0; {$else} result:=false; {$endif} {$endif} end; end; function sdl2GetProcAddress(LibraryHandle:pointer;const ProcName:string):pointer; {$ifdef CAN_INLINE}inline;{$endif} begin {$ifdef Windows} result:=GetProcAddress({%H-}HMODULE(LibraryHandle),PChar(ProcName)); {$else} {$ifdef Unix} result:=dlsym(LibraryHandle,PChar(ProcName)); {$else} result:=nil; {$endif} {$endif} end; function LoadSDL2Library(const LibraryName:string=SDL2LibName):boolean; begin SDL_Library:=sdl2LoadLibrary(LibraryName); result:=assigned(SDL_Library); if result then begin SDL_Vulkan_LoadLibrary:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_LoadLibrary'); SDL_Vulkan_GetVkGetInstanceProcAddr:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_GetVkGetInstanceProcAddr'); SDL_Vulkan_UnloadLibrary:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_UnloadLibrary'); SDL_Vulkan_GetInstanceExtensions:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_GetInstanceExtensions'); SDL_Vulkan_CreateSurface:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_CreateSurface'); SDL_Vulkan_GetDrawableSize:=sdl2GetProcAddress(SDL_Library,'SDL_Vulkan_GetDrawableSize'); end; end; {$endif} function SDL_BUTTON(Button:TSDLInt32):TSDLInt32; begin result:=1 shl (Button-1); end; procedure SDL_VERSION(out Version:TSDL_Version); begin Version.major:=SDL_MAJOR_VERSION; Version.minor:=SDL_MINOR_VERSION; Version.patch:=SDL_PATCHLEVEL; end; {$ifdef PasVulkanUseDynamicSDL2} initialization LoadSDL2Library; finalization if assigned(SDL_Library) then begin sdl2FreeLibrary(SDL_Library); end; {$endif} end.
unit DAO.TipoOcorrenciaJornal; interface uses DAO.Base, Generics.Collections, System.Classes, Model.TipoOcorrenciaJornal; type TTipoOcorrenciaJornalDAO = class(TDAO) public function Insert(aTipos: TTipoOcorrenciaJornal): Boolean; function Update(aTipos: TTipoOcorrenciaJornal): Boolean; function Delete(sCodigo: String): Boolean; function FindByCodigo(iCodigo: Integer): TObjectList<TTipoOcorrenciaJornal>; function FindByDescricao(sDescricao: String): TObjectList<TTipoOcorrenciaJornal>; function FindField(sCampo: String; sCodigo: String): String; end; const TABLENAME = 'jor_tipo_ocorrencia'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TTipoOcorrenciaJornalDAO.Insert(aTipos: TTipoOcorrenciaJornal): Boolean; var sSQL : System.string; begin Result := False; sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(COD_COD_TIPO_OCORRENCIA, DES_TIPO_OCORRENCIA) ' + 'VALUES ' + '(:CODIGO, :DESCRICAO);'; Connection.ExecSQL(sSQL,[aTipos.Codigo, aTipos.Descricao],[ftInteger, ftString]); Result := True; end; function TTipoOcorrenciaJornalDAO.Update(aTipos: TTipoOcorrenciaJornal): Boolean; var sSQL : System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' SET '+ 'DES_TIPO_OCORRENCIA = :DESCRICAO ' + 'WHERE ' + 'COD_TIPO_OCORRENCIA = pCOD_TIPO_OCORRENCIA'; Connection.ExecSQL(sSQL,[aTipos.Descricao, aTipos.Codigo], [ftString, ftInteger]); Result := True; end; function TTipoOcorrenciaJornalDAO.Delete(sCodigo: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' WHERE COD_TIPO_OCORRENCIA = :CODIGO;'; Connection.ExecSQL(sSQL,[sCodigo],[ftString]); Result := True; end; function TTipoOcorrenciaJornalDAO.FindByCodigo(iCodigo: Integer): TObjectList<TTipoOcorrenciaJornal>; var FDQuery: TFDQuery; produtos: TObjectList<TTipoOcorrenciaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_TIPO_OCORRENCIA = :CODIGO'); FDQuery.ParamByName('CODIGO').AsInteger := iCodigo; FDQuery.Open(); produtos := TObjectList<TTipoOcorrenciaJornal>.Create(); while not FDQuery.Eof do begin produtos.Add(TTipoOcorrenciaJornal.Create(FDQuery.FieldByName('COD_TIPO_OCORRENCIA').AsInteger, FDQuery.FieldByName('DES_TIPO_OCORRENCIA').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := produtos; end; function TTipoOcorrenciaJornalDAO.FindByDescricao(sDescricao: string): TObjectList<TTipoOcorrenciaJornal>; var FDQuery: TFDQuery; modalidades: TObjectList<TTipoOcorrenciaJornal>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sDescricao.IsEmpty then begin FDQuery.SQL.Add('WHERE DES_TIPO_OCORRENCIA LIKE :DESCRICAO'); FDQuery.ParamByName('DESCRICAO').AsString := '%' + sDescricao + '%'; end; FDQuery.Open(); modalidades := TObjectList<TTipoOcorrenciaJornal>.Create(); while not FDQuery.Eof do begin modalidades.Add(TTipoOcorrenciaJornal.Create(FDQuery.FieldByName('COD_TIPO_OCORRENCIA').AsInteger, FDQuery.FieldByName('DES_TIPO_OCORRENCIA').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := modalidades; end; function TTipoOcorrenciaJornalDAO.FindField(sCampo: string; sCodigo: string): String; var FDQuery: TFDQuery; begin Result := ''; FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME + ' WHERE COD_TIPO_OCORRENCIA = :CODIGO'); FDQuery.ParamByName('CODIGO').AsString := sCodigo; FDQuery.Open(); if FDQuery.IsEmpty then begin Exit; end; Result := FDQuery.FieldByName(sCampo).AsString; finally FDQuery.Free; end; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 114 of 150 From : Sean Palmer 1:104/123.0 08 Apr 93 15:35 To : All Subj : G:Sync Unit ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ} { Sync unit v1.0 } { 04/06/93 } { Minimal support for cpu-independent timing, Turbo Pascal 6.0} { Copyright (c) 1993 Sean L. Palmer } { Released to the Public Domain } { You may distribute this freely and incorporate it with no royalties. } { Please credit me if your program uses these routines! } { If you really like them or learn something neat from me then I'd } { appreciate a small ($1 to $5) donation. } { Or contact me if you need something programmed or like my work... } { I probably have the wierdest indenting style for pascal ever! 8) } { And, by God my stuff is optimized!! } { Sean L. Palmer (aka Ghost)} { 2237 Lincoln St. } { Longmont, CO 80501 } { (303) 651-7862 } { also on FIDO, or at palmers@spot.colorado.edu } unit sync; {$A-,B-,D-,E-,F-,G-,I-,L-,N-,O-,R-,S-,V-,X-} interface var ticks:word absolute $40:$6C; {ticks happen 18.2 times/second} procedure tick; {pauses until next tick} function ticked:boolean; {true if tick occurred since last check} procedure waitTicks(n:word); {pauses for specified number of ticks} implementation var curTick:word; procedure tick;begin curTick:=succ(ticks);repeat until ticks=curTick;end; function ticked:boolean;begin if curTick<>ticks then begin curTick:=ticks; ticked:=true; end else ticked:=false; end; procedure waitTicks(n:word);begin curTick:=ticks+n; {will wrap} repeat until ticks=curTick; end; begin curTick:=ticks; end. ___ Blue Wave/QWK v2.12 --- Maximus 2.01wb * Origin: >>> Sun Mountain BBS <<< (303)-665-6922 (1:104/123)
unit Marvin.AulaMulticamada.REST.Server.Metodos; interface uses { marvin } uMRVClasses, Marvin.System.Classes.Ambiente, Marvin.System.Classes.Ambiente.Usuario, Marvin.AulaMulticamada.Fachada, Marvin.AulaMulticamada.Fachada.Singleton, Marvin.AulaMulticamada.Listas.TipoCliente, Marvin.AulaMulticamada.Classes.TipoCliente, Marvin.AulaMulticamada.Listas.Cliente, Marvin.AulaMulticamada.Classes.Cliente, { embarcadero } System.SysUtils, System.Classes, System.Json, Datasnap.DSServer, Datasnap.DSAuth; type {$METHODINFO ON} TAulaMulticamadaServerMetodos = class(TComponent) private FFachada: TMRVFachadaAulaMulticamada; FAmbiente: TMRVAmbiente; FAmbienteUsuario: TMRVAmbienteUsuario; { métodos de apoio } function GetException(const AException: Exception; const ADescricaoOperacao: string): TJSONValue; function GetResult(const ADado: TMRVDadosBase; const ADescricaoOperacao: string): TJSONValue; function GetResults(const ALista: TMRVListaBase; const ADescricaoOperacao: string): TJSONValue; protected procedure DoInicializarFachada; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { funções de testes } function EchoString(Value: string): string; function ReverseString(Value: string): string; { tipos de cliente } function TipoCliente(const AObjectId: Integer): TJSONValue; function GetTipoCliente(const AObjectId: Integer): TJSONValue; function GetTiposCliente: TJSONValue; function UpdateTipoCliente(const ATipoCliente: TMRVTipoCliente): TJSONValue; function AcceptTipoCliente(const ATipoCliente: TMRVTipoCliente): TJSONValue; function CancelTipoCliente(const AObjectId: Integer): TJSONValue; { cliente } function Cliente(const AObjectId: Integer): TJSONValue; function GetCliente(const AObjectId: Integer): TJSONValue; function GetClientes: TJSONValue; function UpdateCliente(const ACliente: TMRVCliente): TJSONValue; function AcceptCliente(const ACliente: TMRVCliente): TJSONValue; function CancelCliente(const AObjectId: Integer): TJSONValue; end; {$METHODINFO OFF} implementation uses uMRVSerializador, System.StrUtils; constructor TAulaMulticamadaServerMetodos.Create(AOwner: TComponent); begin inherited Create(AOwner); FAmbienteUsuario := nil; FAmbiente := nil; { recupera a fachada } FFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; { verifica as conexões } if not FFachada.IsConnected then begin FAmbienteUsuario := TMRVAmbienteUsuario.Create; FAmbiente := TMRVAmbiente.Create; { inicializa a fachada } Self.DoInicializarFachada; end; end; destructor TAulaMulticamadaServerMetodos.Destroy; begin if Assigned(FAmbienteUsuario) then begin FreeAndNil(FAmbienteUsuario); end; if Assigned(FAmbiente) then begin FreeAndNil(FAmbiente); end; FFachada := nil; inherited; end; procedure TAulaMulticamadaServerMetodos.DoInicializarFachada; var LServidor, LBancoDados, LBaseDados: string; begin FAmbiente.Descricao := 'init'; { variáveis } { teste local } LServidor := 'NOTE-HP-MVB'; LBancoDados := 'SQLEXPRESS'; LBaseDados := 'AULAS'; { passa os dados para o objeto } FAmbiente.Servidor := LServidor; FAmbiente.BancoDados := LBancoDados; FAmbiente.BaseDados := LBaseDados; { inicializa a fachada } FFachada.Init(FAmbienteUsuario, FAmbiente); end; function TAulaMulticamadaServerMetodos.EchoString(Value: string): string; begin Result := Value; end; function TAulaMulticamadaServerMetodos.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; function TAulaMulticamadaServerMetodos.GetException(const AException: Exception; const ADescricaoOperacao: string): TJSONValue; var LJSONInfo: TJSONObject; begin { instancia o retorno } Result := TJSONObject.Create; { inicializa as informações da exceção } LJSONInfo := TJSONObject.Create; try { informa a classe da exceção } LJSONInfo.AddPair('type', AException.ClassName); LJSONInfo.AddPair('message', AException.Message); LJSONInfo.AddPair('descricaooperacao', ADescricaoOperacao); { informa que é uma exceção } TJSONObject(Result).AddPair('RaiseExceptionServerMethods', LJSONInfo.ToString); finally LJSONInfo.Free; end; end; function TAulaMulticamadaServerMetodos.GetResult(const ADado: TMRVDadosBase; const ADescricaoOperacao: string): TJSONValue; var LObjeto: TJSONValue; LSerializador: TMRVSerializador; LTexto: string; begin { cria o serializador } LSerializador := TMRVSerializador.Create; try LSerializador.TipoSerializacao := TMRVTipoSerializacao.tsJSON; LSerializador.Direcao := TMRVDirecaoSerializacao.dsObjetoToTexto; LSerializador.Objeto := (ADado as TMRVDadosBase); LSerializador.Serializar; LTexto := LSerializador.Texto; finally LSerializador.Free; end; LObjeto := TJSONObject.ParseJSONValue(LTexto); { retorna o objeto JSON } Result := LObjeto; end; function TAulaMulticamadaServerMetodos.GetResults(const ALista: TMRVListaBase; const ADescricaoOperacao: string): TJSONValue; var LObjeto: TJSONValue; LSerializador: TMRVSerializador; LTexto: string; begin { cria o serializador } LSerializador := TMRVSerializador.Create; try LSerializador.TipoSerializacao := TMRVTipoSerializacao.tsJSON; LSerializador.Direcao := TMRVDirecaoSerializacao.dsListaToTexto; LSerializador.Lista := (ALista as TMRVListaBase); LSerializador.Serializar; LTexto := LSerializador.Texto; finally LSerializador.Free; end; LObjeto := TJSONObject.ParseJSONValue(LTexto); { retorna o objeto JSON } Result := LObjeto; end; function TAulaMulticamadaServerMetodos.AcceptCliente(const ACliente: TMRVCliente): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { manda a fachada inserir } LFachada.ClientesInserir(ACliente); { retorna o resultado } Result := Self.GetResult(ACliente, 'AcceptCliente'); except on E: Exception do begin Result := Self.GetException(E, 'AcceptCliente'); end; end; end; function TAulaMulticamadaServerMetodos.AcceptTipoCliente(const ATipoCliente: TMRVTipoCliente): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { manda a fachada inserir } LFachada.TipoClientesInserir(ATipoCliente); { retorna o resultado } Result := Self.GetResult(ATipoCliente, 'AcceptTipoCliente'); except on E: Exception do begin Result := Self.GetException(E, 'AcceptTipoCliente'); end; end; end; function TAulaMulticamadaServerMetodos.CancelCliente(const AObjectId: Integer): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; LCliente: TMRVCliente; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { prepara a informação } LCliente := TMRVCliente.Create; try LCliente.ClienteId := AObjectId; LFachada.ClientesExcluir(LCliente); finally LCliente.Free; end; Result := TJSONObject.Create(TJSONPair.Create('OP', 'CancelCliente')); TJSONObject(Result).AddPair('Mensagem', Format( 'Cliente com Id [%d] excluído com sucesso.', [AObjectId])); except on E: Exception do begin Result := Self.GetException(E, 'CancelCliente'); end; end; end; function TAulaMulticamadaServerMetodos.CancelTipoCliente(const AObjectId: Integer): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; LTipoCliente: TMRVTipoCliente; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { prepara a informação } LTipoCliente := TMRVTipoCliente.Create; try LTipoCliente.TipoClienteId := AObjectId; LFachada.TipoClientesExcluir(LTipoCliente); finally LTipoCliente.Free; end; Result := TJSONObject.Create(TJSONPair.Create('OP', 'CancelTipoCliente')); TJSONObject(Result).AddPair('Mensagem', Format('Tipo de Cliente com Id [%d] excluído com sucesso.', [AObjectId])); except on E: Exception do begin Result := Self.GetException(E, 'CancelTipoCliente'); end; end; end; function TAulaMulticamadaServerMetodos.Cliente(const AObjectId: Integer): TJSONValue; var LResult: TJSONValue; begin LResult := nil; { recupera o cliente informado } if AObjectId <> 0 then begin LResult := Self.GetCliente(AObjectId); end { recupera lista de clientes } else begin LResult := Self.GetClientes; end; { prepara o retorno } Result := LResult; end; function TAulaMulticamadaServerMetodos.GetCliente(const AObjectId: Integer): TJSONValue; var LFacade: TMRVFachadaAulaMulticamada; LCliente: TMRVCliente; begin { manda a fachada procurar cliente } LFacade := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try LCliente := TMRVCliente.Create; try LCliente.Clienteid := AObjectId; LFacade.ClientesProcurarItem(LCliente, LCliente); Result := Self.GetResult(LCliente, 'GetCliente'); finally LCliente.Free; end; except on E: Exception do begin Result := Self.GetException(E, 'GetCliente'); end; end; end; function TAulaMulticamadaServerMetodos.GetClientes: TJSONValue; var LFacade: TMRVFachadaAulaMulticamada; LCliente: TMRVCliente; LListaCliente: TMRVListaCliente; LSearchOption: TMRVSearchOption; begin LFacade := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { instancia os parâmetros } LCliente := TMRVCliente.Create; try LListaCliente := TMRVListaCliente.Create; try { define o objeto de pesquisa } LSearchOption := TMRVSearchOption.Create(LCliente); try LCliente.Clienteid := 0; { manda a fachada recuperar os clientes cadastrados } LFacade.ClientesProcurarItens(LCliente, LListaCliente, LSearchOption); { transforma para o formato JSON } Result := Self.GetResults(LListaCliente, 'GetClientes'); finally LSearchOption.Free; end; finally LListaCliente.Free; end; finally LCliente.Free; end; except on E: Exception do begin Result := Self.GetException(E, 'GetClientes'); end; end; end; function TAulaMulticamadaServerMetodos.TipoCliente(const AObjectId: Integer): TJSONValue; var LResult: TJSONValue; begin LResult := nil; { chama o método da fachada } { recupera o TipoCliente informado } if AObjectId <> 0 then begin LResult := Self.GetTipoCliente(AObjectId); end { recupera lista de TipoClientes } else begin LResult := Self.GetTiposCliente; end; { prepara o retorno } Result := LResult; end; function TAulaMulticamadaServerMetodos.GetTipoCliente(const AObjectId: Integer): TJSONValue; var LFacade: TMRVFachadaAulaMulticamada; LTipoCliente: TMRVTipoCliente; begin { manda a fachada procurar pelo tipo de cliente } LFacade := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try LTipoCliente := TMRVTipoCliente.Create; try LTipoCliente.TipoClienteid := AObjectId; LFacade.TipoClientesProcurarItem(LTipoCliente, LTipoCliente); Result := Self.GetResult(LTipoCliente, 'GetTipoCliente'); finally LTipoCliente.Free; end; except on E: Exception do begin Result := Self.GetException(E, 'GetTipoCliente'); end; end; end; function TAulaMulticamadaServerMetodos.GetTiposCliente: TJSONValue; var LFacade: TMRVFachadaAulaMulticamada; LTipoCliente: TMRVTipoCliente; LListaTipoCliente: TMRVListaTipoCliente; LSearchOption: TMRVSearchOption; begin LFacade := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { instancia os parâmetros } LTipoCliente := TMRVTipoCliente.Create; try LListaTipoCliente := TMRVListaTipoCliente.Create; try { define o objeto de pesquisa } LSearchOption := TMRVSearchOption.Create(LTipoCliente); try LTipoCliente.TipoClienteid := 0; { manda a fachada recuperar os TipoClientes cadastrados } LFacade.TipoClientesProcurarItens(LTipoCliente, LListaTipoCliente, LSearchOption); { transforma para o formato JSON } Result := Self.GetResults(LListaTipoCliente, 'GetTipoClientes'); finally LSearchOption.Free; end; finally LListaTipoCliente.Free; end; finally LTipoCliente.Free; end; except on E: Exception do begin Result := Self.GetException(E, 'GetTiposCliente'); end; end; end; function TAulaMulticamadaServerMetodos.UpdateCliente(const ACliente: TMRVCliente): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { manda a fachada inserir } LFachada.ClientesAlterar(ACliente); { retorna o resultado } Result := Self.GetResult(ACliente, 'UpdateCliente'); except on E: Exception do begin Result := Self.GetException(E, 'UpdateCliente'); end; end; end; function TAulaMulticamadaServerMetodos.UpdateTipoCliente(const ATipoCliente: TMRVTipoCliente): TJSONValue; var LFachada: TMRVFachadaAulaMulticamada; begin { recupera a instância da fachada } LFachada := TMRVAulaMulticamadasFacadeSingletonSealed.Instancia; try { manda a fachada inserir } LFachada.TipoClientesAlterar(ATipoCliente); { retorna o resultado } Result := Self.GetResult(ATipoCliente, 'UpdateTipoCliente'); except on E: Exception do begin Result := Self.GetException(E, 'UpdateTipoCliente'); end; end; end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 430 of 473 From : Erik Johnson 1:104/28.0 13 Apr 93 19:52 To : David Jirku Subj : FAST MATH ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ > I was just wondering how to speed up some math-intensive > routines I've got here. For example, I've got a function > that returns the distance between two objects: > > Function Dist(X1,Y1,X2,Y2 : Integer) : Real; > > BEGIN > Dist := Round(Sqrt(Sqr(X1-X2)+Sqr(Y1-Y2))); > END; > > This is way to slow. I know assembly can speed it up, but > I know nothing about asm. so theres the problem. Please > help me out, any and all source/suggestions welcome! X1, Y1, X2, Y2 are all integers. Integer math is faster than Real (just about anything is). Sqr and Sqrt are not Integer functions. Try for fun... } Function Dist( X1, Y1, X2, Y2 : Integer ) : Real; VAR XTemp, YTemp : INTEGER; {the allocation of these takes time. If you don't want that time taken, make them global with care} BEGIN XTemp := X1 - X2; YTemp := Y1 - Y2; Dist := Round( Sqrt( XTemp*XTemp + YTemp*YTemp )); END; If you have a math coprocessor or a 486dx, try using DOUBLE instead of REAL, and make sure your compiler is set to compile for 287 (or 387).
{ ID: ndchiph1 PROG: money LANG: PASCAL } uses math; const MAX_N = 10000; MAX_V = 25; { var fi,fo: text; f: array[0..MAX_N,1..MAX_V] of int64; c: array[1..MAX_V] of longint; v,n: longint; procedure input; var i: longint; begin readln(fi,v,n); for i:= 1 to v do read(fi,c[i]); end; procedure process; var i,j,k: longint; begin fillchar(f,sizeof(f),0); for i:= 1 to v do f[0,i]:= 1; for i:= 1 to n do begin for j:= 1 to v do begin for k:= j downto 1 do if (c[k] <= i) then inc(f[i,j],f[i-c[k],k]); end; end; writeln(fo,f[n,v]); end; } var fi,fo: text; f: array[0..MAX_N] of int64; v,n: longint; procedure process; var i,j,c: longint; begin readln(fi,v,n); fillchar(f,sizeof(f),0); f[0]:= 1; for i:= 1 to v do begin read(fi,c); for j:= c to n do inc(f[j],f[j-c]); end; writeln(fo,f[n]); end; begin assign(fi,'money.in'); reset(fi); assign(fo,'money.out'); rewrite(fo); // //input; process; // close(fi); close(fo); end.
unit KDictOptions; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, ExtCtrls; type TfrmDictOptions = class(TFrame) GroupBox1: TGroupBox; lstShowingDicts: TCheckListBox; Panel1: TPanel; ckAll: TCheckBox; ckNonAll: TCheckBox; procedure ckAllClick(Sender: TObject); procedure ckNonAllClick(Sender: TObject); private { Private declarations } procedure CheckAll (AValue: boolean); public { Public declarations } constructor Create(AOnwer: TComponent); override; destructor Destroy; override; end; implementation uses Facade; {$R *.dfm} { TfrmDictOptions } constructor TfrmDictOptions.Create(AOnwer: TComponent); begin inherited; (TMainFacade.GetInstance as TMainFacade).Dicts.MakeList(lstShowingDicts.Items); end; destructor TfrmDictOptions.Destroy; begin inherited; end; procedure TfrmDictOptions.ckAllClick(Sender: TObject); begin if ckAll.Checked then CheckAll(true); end; procedure TfrmDictOptions.ckNonAllClick(Sender: TObject); begin if ckNonAll.Checked then CheckAll(false); end; procedure TfrmDictOptions.CheckAll(AValue: boolean); var i: integer; begin ckAll.Checked := AValue; ckNonAll.Checked := not AValue; for i := 0 to lstShowingDicts.Count - 1 do lstShowingDicts.Checked[i] := AValue; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFE_CABECALHO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfeCabecalhoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, TributOperacaoFiscalVO, NfeEmitenteVO, NfeDestinatarioVO, NfeLocalRetiradaVO, NfeLocalEntregaVO, NfeAcessoXmlVO, NfeTransporteVO, NfeFaturaVO, NfeCanaVO, EmpresaVO, NfeReferenciadaVO, NfeNfReferenciadaVO, NfeCteReferenciadoVO, NfeProdRuralReferenciadaVO, NfeCupomFiscalReferenciadoVO, NfeDetalheVO, NfeDuplicataVO, NfeFormaPagamentoVO, NfeProcessoReferenciadoVO, FiscalNotaFiscalEntradaVO; type [TEntity] [TTable('NFE_CABECALHO')] TNfeCabecalhoVO = class(TVO) private FID: Integer; FID_VENDEDOR: Integer; FID_NFCE_MOVIMENTO: Integer; FID_TRIBUT_OPERACAO_FISCAL: Integer; FID_VENDA_CABECALHO: Integer; FID_EMPRESA: Integer; FID_FORNECEDOR: Integer; FID_CLIENTE: Integer; FUF_EMITENTE: Integer; FCODIGO_NUMERICO: String; FNATUREZA_OPERACAO: String; FINDICADOR_FORMA_PAGAMENTO: Integer; FCODIGO_MODELO: String; FSERIE: String; FNUMERO: String; FDATA_HORA_EMISSAO: TDateTime; FDATA_HORA_ENTRADA_SAIDA: TDateTime; FTIPO_OPERACAO: Integer; FLOCAL_DESTINO: Integer; FCODIGO_MUNICIPIO: Integer; FFORMATO_IMPRESSAO_DANFE: Integer; FTIPO_EMISSAO: Integer; FCHAVE_ACESSO: String; FDIGITO_CHAVE_ACESSO: String; FAMBIENTE: Integer; FFINALIDADE_EMISSAO: Integer; FCONSUMIDOR_OPERACAO: Integer; FCONSUMIDOR_PRESENCA: Integer; FPROCESSO_EMISSAO: Integer; FVERSAO_PROCESSO_EMISSAO: String; FDATA_ENTRADA_CONTINGENCIA: TDateTime; FJUSTIFICATIVA_CONTINGENCIA: String; FBASE_CALCULO_ICMS: Extended; FVALOR_ICMS: Extended; FVALOR_ICMS_DESONERADO: Extended; FBASE_CALCULO_ICMS_ST: Extended; FVALOR_ICMS_ST: Extended; FVALOR_TOTAL_PRODUTOS: Extended; FVALOR_FRETE: Extended; FVALOR_SEGURO: Extended; FVALOR_DESCONTO: Extended; FVALOR_IMPOSTO_IMPORTACAO: Extended; FVALOR_IPI: Extended; FVALOR_PIS: Extended; FVALOR_COFINS: Extended; FVALOR_DESPESAS_ACESSORIAS: Extended; FVALOR_TOTAL: Extended; FVALOR_SERVICOS: Extended; FBASE_CALCULO_ISSQN: Extended; FVALOR_ISSQN: Extended; FVALOR_PIS_ISSQN: Extended; FVALOR_COFINS_ISSQN: Extended; FDATA_PRESTACAO_SERVICO: TDateTime; FVALOR_DEDUCAO_ISSQN: Extended; FOUTRAS_RETENCOES_ISSQN: Extended; FDESCONTO_INCONDICIONADO_ISSQN: Extended; FDESCONTO_CONDICIONADO_ISSQN: Extended; FTOTAL_RETENCAO_ISSQN: Extended; FREGIME_ESPECIAL_TRIBUTACAO: Integer; FVALOR_RETIDO_PIS: Extended; FVALOR_RETIDO_COFINS: Extended; FVALOR_RETIDO_CSLL: Extended; FBASE_CALCULO_IRRF: Extended; FVALOR_RETIDO_IRRF: Extended; FBASE_CALCULO_PREVIDENCIA: Extended; FVALOR_RETIDO_PREVIDENCIA: Extended; FTROCO: Extended; FCOMEX_UF_EMBARQUE: String; FCOMEX_LOCAL_EMBARQUE: String; FCOMEX_LOCAL_DESPACHO: String; FCOMPRA_NOTA_EMPENHO: String; FCOMPRA_PEDIDO: String; FCOMPRA_CONTRATO: String; FINFORMACOES_ADD_FISCO: String; FINFORMACOES_ADD_CONTRIBUINTE: String; FSTATUS_NOTA: Integer; FEmpresaVO: TEmpresaVO; FTributOperacaoFiscalVO: TTributOperacaoFiscalVO; FFiscalNotaFiscalEntradaVO: TFiscalNotaFiscalEntradaVO; //1:1 // Grupo C FNfeEmitenteVO: TNfeEmitenteVO; //1:1 // Grupo E FNfeDestinatarioVO: TNfeDestinatarioVO; //0:1 // Grupo F FNfeLocalRetiradaVO: TNfeLocalRetiradaVO; //0:1 // Grupo G FNfeLocalEntregaVO: TNfeLocalEntregaVO; //0:1 // Grupo X FNfeTransporteVO: TNfeTransporteVO; //1:1 // Grupo Y - Y02 FNfeFaturaVO: TNfeFaturaVO; //0:1 // Grupo ZC FNfeCanaVO: TNfeCanaVO; //0:1 // Grupo BA FListaNfeReferenciadaVO: TObjectList<TNfeReferenciadaVO>; //0:500 FListaNfeNfReferenciadaVO: TObjectList<TNfeNfReferenciadaVO>; //0:500 FListaNfeCteReferenciadoVO: TObjectList<TNfeCteReferenciadoVO>; //0:500 FListaNfeProdRuralReferenciadaVO: TObjectList<TNfeProdRuralReferenciadaVO>; //0:500 FListaNfeCupomFiscalReferenciadoVO: TObjectList<TNfeCupomFiscalReferenciadoVO>; //0:500 // Grupo GA FListaNfeAcessoXmlVO: TObjectList<TNfeAcessoXmlVO>; //0:10 // Grupo I FListaNfeDetalheVO: TObjectList<TNfeDetalheVO>; //1:990 // Grupo Y - Y07 FListaNfeDuplicataVO: TObjectList<TNfeDuplicataVO>; //0:120 // Grupo YA [usado apenas na NFC-e] FListaNfeFormaPagamentoVO: TObjectList<TNfeFormaPagamentoVO>; //0:100 // Grupo Z - Z10 FListaNfeProcessoReferenciadoVO: TObjectList<TNfeProcessoReferenciadoVO>; //0:100 public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('NUMERO', 'Numero', 80, [ldGrid, ldLookup, ldCombobox], False)] property Numero: String read FNUMERO write FNUMERO; [TColumn('SERIE', 'Serie', 24, [ldGrid, ldLookup, ldCombobox], False)] property Serie: String read FSERIE write FSERIE; [TColumn('DATA_HORA_EMISSAO', 'Data Hora Emissao', 120, [ldGrid, ldLookup, ldCombobox], False)] property DataHoraEmissao: TDateTime read FDATA_HORA_EMISSAO write FDATA_HORA_EMISSAO; [TColumn('NATUREZA_OPERACAO', 'Natureza Operacao', 450, [ldGrid, ldLookup, ldCombobox], False)] property NaturezaOperacao: String read FNATUREZA_OPERACAO write FNATUREZA_OPERACAO; [TColumn('CHAVE_ACESSO', 'Chave Acesso', 352, [ldGrid, ldLookup, ldCombobox], False)] property ChaveAcesso: String read FCHAVE_ACESSO write FCHAVE_ACESSO; [TColumn('DIGITO_CHAVE_ACESSO', 'Digito Chave Acesso', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property DigitoChaveAcesso: String read FDIGITO_CHAVE_ACESSO write FDIGITO_CHAVE_ACESSO; [TColumn('ID_NFCE_MOVIMENTO', 'Id Movimento', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfceMovimento: Integer read FID_NFCE_MOVIMENTO write FID_NFCE_MOVIMENTO; [TColumn('ID_VENDEDOR', 'Id Vendedor', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendedor: Integer read FID_VENDEDOR write FID_VENDEDOR; [TColumn('ID_TRIBUT_OPERACAO_FISCAL', 'Id Tribut Operacao Fiscal', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdTributOperacaoFiscal: Integer read FID_TRIBUT_OPERACAO_FISCAL write FID_TRIBUT_OPERACAO_FISCAL; [TColumn('ID_VENDA_CABECALHO', 'Id Venda Cabecalho', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdVendaCabecalho: Integer read FID_VENDA_CABECALHO write FID_VENDA_CABECALHO; [TColumn('ID_EMPRESA', 'Id Empresa', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA; [TColumn('ID_FORNECEDOR', 'Id Fornecedor', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdFornecedor: Integer read FID_FORNECEDOR write FID_FORNECEDOR; [TColumn('ID_CLIENTE', 'Id Cliente', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE; [TColumn('UF_EMITENTE', 'Uf Emitente', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property UfEmitente: Integer read FUF_EMITENTE write FUF_EMITENTE; [TColumn('CODIGO_NUMERICO', 'Codigo Numerico', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CodigoNumerico: String read FCODIGO_NUMERICO write FCODIGO_NUMERICO; [TColumn('INDICADOR_FORMA_PAGAMENTO', 'Indicador Forma Pagamento', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IndicadorFormaPagamento: Integer read FINDICADOR_FORMA_PAGAMENTO write FINDICADOR_FORMA_PAGAMENTO; [TColumn('CODIGO_MODELO', 'Codigo Modelo', 16, [ldGrid, ldLookup, ldCombobox], False)] property CodigoModelo: String read FCODIGO_MODELO write FCODIGO_MODELO; [TColumn('DATA_HORA_ENTRADA_SAIDA', 'Data Hora Entrada Saida', 272, [ldGrid, ldLookup, ldCombobox], False)] property DataHoraEntradaSaida: TDateTime read FDATA_HORA_ENTRADA_SAIDA write FDATA_HORA_ENTRADA_SAIDA; [TColumn('TIPO_OPERACAO', 'Tipo Operacao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TipoOperacao: Integer read FTIPO_OPERACAO write FTIPO_OPERACAO; [TColumn('LOCAL_DESTINO', 'Local Destino', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property LocalDestino: Integer read FLOCAL_DESTINO write FLOCAL_DESTINO; [TColumn('CODIGO_MUNICIPIO', 'Codigo Municipio', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property CodigoMunicipio: Integer read FCODIGO_MUNICIPIO write FCODIGO_MUNICIPIO; [TColumn('FORMATO_IMPRESSAO_DANFE', 'Formato Impressao Danfe', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property FormatoImpressaoDanfe: Integer read FFORMATO_IMPRESSAO_DANFE write FFORMATO_IMPRESSAO_DANFE; [TColumn('TIPO_EMISSAO', 'Tipo Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property TipoEmissao: Integer read FTIPO_EMISSAO write FTIPO_EMISSAO; [TColumn('AMBIENTE', 'Ambiente', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Ambiente: Integer read FAMBIENTE write FAMBIENTE; [TColumn('FINALIDADE_EMISSAO', 'Finalidade Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property FinalidadeEmissao: Integer read FFINALIDADE_EMISSAO write FFINALIDADE_EMISSAO; [TColumn('CONSUMIDOR_OPERACAO', 'Consumidor Operacao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ConsumidorOperacao: Integer read FCONSUMIDOR_OPERACAO write FCONSUMIDOR_OPERACAO; [TColumn('CONSUMIDOR_PRESENCA', 'Consumidor Presenca', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ConsumidorPresenca: Integer read FCONSUMIDOR_PRESENCA write FCONSUMIDOR_PRESENCA; [TColumn('PROCESSO_EMISSAO', 'Processo Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ProcessoEmissao: Integer read FPROCESSO_EMISSAO write FPROCESSO_EMISSAO; [TColumn('VERSAO_PROCESSO_EMISSAO', 'Versao Processo Emissao', 160, [ldGrid, ldLookup, ldCombobox], False)] property VersaoProcessoEmissao: String read FVERSAO_PROCESSO_EMISSAO write FVERSAO_PROCESSO_EMISSAO; [TColumn('DATA_ENTRADA_CONTINGENCIA', 'Data Entrada Contingencia', 272, [ldGrid, ldLookup, ldCombobox], False)] property DataEntradaContingencia: TDateTime read FDATA_ENTRADA_CONTINGENCIA write FDATA_ENTRADA_CONTINGENCIA; [TColumn('JUSTIFICATIVA_CONTINGENCIA', 'Justificativa Contingencia', 450, [ldGrid, ldLookup, ldCombobox], False)] property JustificativaContingencia: String read FJUSTIFICATIVA_CONTINGENCIA write FJUSTIFICATIVA_CONTINGENCIA; [TColumn('BASE_CALCULO_ICMS', 'Base Calculo Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIcms: Extended read FBASE_CALCULO_ICMS write FBASE_CALCULO_ICMS; [TColumn('VALOR_ICMS', 'Valor Icms', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcms: Extended read FVALOR_ICMS write FVALOR_ICMS; [TColumn('VALOR_ICMS_DESONERADO', 'Valor Icms Desonerado', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcmsDesonerado: Extended read FVALOR_ICMS_DESONERADO write FVALOR_ICMS_DESONERADO; [TColumn('BASE_CALCULO_ICMS_ST', 'Base Calculo Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIcmsSt: Extended read FBASE_CALCULO_ICMS_ST write FBASE_CALCULO_ICMS_ST; [TColumn('VALOR_ICMS_ST', 'Valor Icms St', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIcmsSt: Extended read FVALOR_ICMS_ST write FVALOR_ICMS_ST; [TColumn('VALOR_TOTAL_PRODUTOS', 'Valor Total Produtos', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotalProdutos: Extended read FVALOR_TOTAL_PRODUTOS write FVALOR_TOTAL_PRODUTOS; [TColumn('VALOR_FRETE', 'Valor Frete', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorFrete: Extended read FVALOR_FRETE write FVALOR_FRETE; [TColumn('VALOR_SEGURO', 'Valor Seguro', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorSeguro: Extended read FVALOR_SEGURO write FVALOR_SEGURO; [TColumn('VALOR_DESCONTO', 'Valor Desconto', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDesconto: Extended read FVALOR_DESCONTO write FVALOR_DESCONTO; [TColumn('VALOR_IMPOSTO_IMPORTACAO', 'Valor Imposto Importacao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorImpostoImportacao: Extended read FVALOR_IMPOSTO_IMPORTACAO write FVALOR_IMPOSTO_IMPORTACAO; [TColumn('VALOR_IPI', 'Valor Ipi', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIpi: Extended read FVALOR_IPI write FVALOR_IPI; [TColumn('VALOR_PIS', 'Valor Pis', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorPis: Extended read FVALOR_PIS write FVALOR_PIS; [TColumn('VALOR_COFINS', 'Valor Cofins', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorCofins: Extended read FVALOR_COFINS write FVALOR_COFINS; [TColumn('VALOR_DESPESAS_ACESSORIAS', 'Valor Despesas Acessorias', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDespesasAcessorias: Extended read FVALOR_DESPESAS_ACESSORIAS write FVALOR_DESPESAS_ACESSORIAS; [TColumn('VALOR_TOTAL', 'Valor Total', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; [TColumn('VALOR_SERVICOS', 'Valor Servicos', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorServicos: Extended read FVALOR_SERVICOS write FVALOR_SERVICOS; [TColumn('BASE_CALCULO_ISSQN', 'Base Calculo Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIssqn: Extended read FBASE_CALCULO_ISSQN write FBASE_CALCULO_ISSQN; [TColumn('VALOR_ISSQN', 'Valor Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIssqn: Extended read FVALOR_ISSQN write FVALOR_ISSQN; [TColumn('VALOR_PIS_ISSQN', 'Valor Pis Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorPisIssqn: Extended read FVALOR_PIS_ISSQN write FVALOR_PIS_ISSQN; [TColumn('VALOR_COFINS_ISSQN', 'Valor Cofins Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorCofinsIssqn: Extended read FVALOR_COFINS_ISSQN write FVALOR_COFINS_ISSQN; [TColumn('DATA_PRESTACAO_SERVICO', 'Data Prestacao Servico', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataPrestacaoServico: TDateTime read FDATA_PRESTACAO_SERVICO write FDATA_PRESTACAO_SERVICO; [TColumn('VALOR_DEDUCAO_ISSQN', 'Valor Deducao Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDeducaoIssqn: Extended read FVALOR_DEDUCAO_ISSQN write FVALOR_DEDUCAO_ISSQN; [TColumn('OUTRAS_RETENCOES_ISSQN', 'Outras Retencoes Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property OutrasRetencoesIssqn: Extended read FOUTRAS_RETENCOES_ISSQN write FOUTRAS_RETENCOES_ISSQN; [TColumn('DESCONTO_INCONDICIONADO_ISSQN', 'Desconto Incondicionado Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property DescontoIncondicionadoIssqn: Extended read FDESCONTO_INCONDICIONADO_ISSQN write FDESCONTO_INCONDICIONADO_ISSQN; [TColumn('DESCONTO_CONDICIONADO_ISSQN', 'Desconto Condicionado Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property DescontoCondicionadoIssqn: Extended read FDESCONTO_CONDICIONADO_ISSQN write FDESCONTO_CONDICIONADO_ISSQN; [TColumn('TOTAL_RETENCAO_ISSQN', 'Total Retencao Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TotalRetencaoIssqn: Extended read FTOTAL_RETENCAO_ISSQN write FTOTAL_RETENCAO_ISSQN; [TColumn('REGIME_ESPECIAL_TRIBUTACAO', 'Regime Especial Tributacao', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property RegimeEspecialTributacao: Integer read FREGIME_ESPECIAL_TRIBUTACAO write FREGIME_ESPECIAL_TRIBUTACAO; [TColumn('VALOR_RETIDO_PIS', 'Valor Retido Pis', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetidoPis: Extended read FVALOR_RETIDO_PIS write FVALOR_RETIDO_PIS; [TColumn('VALOR_RETIDO_COFINS', 'Valor Retido Cofins', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetidoCofins: Extended read FVALOR_RETIDO_COFINS write FVALOR_RETIDO_COFINS; [TColumn('VALOR_RETIDO_CSLL', 'Valor Retido Csll', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetidoCsll: Extended read FVALOR_RETIDO_CSLL write FVALOR_RETIDO_CSLL; [TColumn('BASE_CALCULO_IRRF', 'Base Calculo Irrf', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIrrf: Extended read FBASE_CALCULO_IRRF write FBASE_CALCULO_IRRF; [TColumn('VALOR_RETIDO_IRRF', 'Valor Retido Irrf', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetidoIrrf: Extended read FVALOR_RETIDO_IRRF write FVALOR_RETIDO_IRRF; [TColumn('BASE_CALCULO_PREVIDENCIA', 'Base Calculo Previdencia', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoPrevidencia: Extended read FBASE_CALCULO_PREVIDENCIA write FBASE_CALCULO_PREVIDENCIA; [TColumn('VALOR_RETIDO_PREVIDENCIA', 'Valor Retido Previdencia', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetidoPrevidencia: Extended read FVALOR_RETIDO_PREVIDENCIA write FVALOR_RETIDO_PREVIDENCIA; [TColumn('COMEX_UF_EMBARQUE', 'Comex Uf Embarque', 16, [ldGrid, ldLookup, ldCombobox], False)] property ComexUfEmbarque: String read FCOMEX_UF_EMBARQUE write FCOMEX_UF_EMBARQUE; [TColumn('COMEX_LOCAL_EMBARQUE', 'Comex Local Embarque', 450, [ldGrid, ldLookup, ldCombobox], False)] property ComexLocalEmbarque: String read FCOMEX_LOCAL_EMBARQUE write FCOMEX_LOCAL_EMBARQUE; [TColumn('COMEX_LOCAL_DESPACHO', 'Comex Local Despacho', 450, [ldGrid, ldLookup, ldCombobox], False)] property ComexLocalDespacho: String read FCOMEX_LOCAL_DESPACHO write FCOMEX_LOCAL_DESPACHO; [TColumn('COMPRA_NOTA_EMPENHO', 'Compra Nota Empenho', 176, [ldGrid, ldLookup, ldCombobox], False)] property CompraNotaEmpenho: String read FCOMPRA_NOTA_EMPENHO write FCOMPRA_NOTA_EMPENHO; [TColumn('COMPRA_PEDIDO', 'Compra Pedido', 450, [ldGrid, ldLookup, ldCombobox], False)] property CompraPedido: String read FCOMPRA_PEDIDO write FCOMPRA_PEDIDO; [TColumn('COMPRA_CONTRATO', 'Compra Contrato', 450, [ldGrid, ldLookup, ldCombobox], False)] property CompraContrato: String read FCOMPRA_CONTRATO write FCOMPRA_CONTRATO; [TColumn('INFORMACOES_ADD_FISCO', 'Informacoes Add Fisco', 450, [ldGrid, ldLookup, ldCombobox], False)] property InformacoesAddFisco: String read FINFORMACOES_ADD_FISCO write FINFORMACOES_ADD_FISCO; [TColumn('INFORMACOES_ADD_CONTRIBUINTE', 'Informacoes Add Contribuinte', 450, [ldGrid, ldLookup, ldCombobox], False)] property InformacoesAddContribuinte: String read FINFORMACOES_ADD_CONTRIBUINTE write FINFORMACOES_ADD_CONTRIBUINTE; [TColumn('STATUS_NOTA', 'Status Nota', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property StatusNota: Integer read FSTATUS_NOTA write FSTATUS_NOTA; [TColumn('TROCO', 'Troco', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Troco: Extended read FTROCO write FTROCO; [TAssociation('ID', 'ID_EMPRESA')] property EmpresaVO: TEmpresaVO read FEmpresaVO write FEmpresaVO; [TAssociation('ID', 'ID_TRIBUT_OPERACAO_FISCAL')] property TributOperacaoFiscalVO: TTributOperacaoFiscalVO read FTributOperacaoFiscalVO write FTributOperacaoFiscalVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property FiscalNotaFiscalEntradaVO: TFiscalNotaFiscalEntradaVO read FFiscalNotaFiscalEntradaVO write FFiscalNotaFiscalEntradaVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeEmitenteVO: TNfeEmitenteVO read FNfeEmitenteVO write FNfeEmitenteVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeDestinatarioVO: TNfeDestinatarioVO read FNfeDestinatarioVO write FNfeDestinatarioVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeLocalRetiradaVO: TNfeLocalRetiradaVO read FNfeLocalRetiradaVO write FNfeLocalRetiradaVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeLocalEntregaVO: TNfeLocalEntregaVO read FNfeLocalEntregaVO write FNfeLocalEntregaVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeTransporteVO: TNfeTransporteVO read FNfeTransporteVO write FNfeTransporteVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeFaturaVO: TNfeFaturaVO read FNfeFaturaVO write FNfeFaturaVO; [TAssociation('ID_NFE_CABECALHO', 'ID')] property NfeCanaVO: TNfeCanaVO read FNfeCanaVO write FNfeCanaVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeReferenciadaVO: TObjectList<TNfeReferenciadaVO> read FListaNfeReferenciadaVO write FListaNfeReferenciadaVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeNfReferenciadaVO: TObjectList<TNfeNfReferenciadaVO> read FListaNfeNfReferenciadaVO write FListaNfeNfReferenciadaVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeCteReferenciadoVO: TObjectList<TNfeCteReferenciadoVO> read FListaNfeCteReferenciadoVO write FListaNfeCteReferenciadoVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeProdRuralReferenciadaVO: TObjectList<TNfeProdRuralReferenciadaVO> read FListaNfeProdRuralReferenciadaVO write FListaNfeProdRuralReferenciadaVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeCupomFiscalReferenciadoVO: TObjectList<TNfeCupomFiscalReferenciadoVO> read FListaNfeCupomFiscalReferenciadoVO write FListaNfeCupomFiscalReferenciadoVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeAcessoXmlVO: TObjectList<TNfeAcessoXmlVO> read FListaNfeAcessoXmlVO write FListaNfeAcessoXmlVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeDetalheVO: TObjectList<TNFeDetalheVO> read FListaNfeDetalheVO write FListaNfeDetalheVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeDuplicataVO: TObjectList<TNfeDuplicataVO> read FListaNfeDuplicataVO write FListaNfeDuplicataVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeFormaPagamentoVO: TObjectList<TNfeFormaPagamentoVO> read FListaNfeFormaPagamentoVO write FListaNfeFormaPagamentoVO; [TManyValuedAssociation('ID_NFE_CABECALHO', 'ID')] property ListaNfeProcessoReferenciadoVO: TObjectList<TNfeProcessoReferenciadoVO> read FListaNfeProcessoReferenciadoVO write FListaNfeProcessoReferenciadoVO; end; implementation constructor TNfeCabecalhoVO.Create; begin inherited; FEmpresaVO := TEmpresaVO.Create; FTributOperacaoFiscalVO := TTributOperacaoFiscalVO.Create; FFiscalNotaFiscalEntradaVO := TFiscalNotaFiscalEntradaVO.Create; FNfeEmitenteVO := TNfeEmitenteVO.Create; FNfeDestinatarioVO := TNfeDestinatarioVO.Create; FNfeLocalRetiradaVO := TNfeLocalRetiradaVO.Create; FNfeLocalEntregaVO := TNfeLocalEntregaVO.Create; FNfeTransporteVO := TNfeTransporteVO.Create; FNfeFaturaVO := TNfeFaturaVO.Create; FNfeCanaVO := TNfeCanaVO.Create; FListaNfeReferenciadaVO := TObjectList<TNfeReferenciadaVO>.Create; FListaNfeNfReferenciadaVO := TObjectList<TNfeNfReferenciadaVO>.Create; FListaNfeCteReferenciadoVO := TObjectList<TNfeCteReferenciadoVO>.Create; FListaNfeProdRuralReferenciadaVO := TObjectList<TNfeProdRuralReferenciadaVO>.Create; FListaNfeCupomFiscalReferenciadoVO := TObjectList<TNfeCupomFiscalReferenciadoVO>.Create; FListaNfeAcessoXmlVO := TObjectList<TNfeAcessoXmlVO>.Create; FListaNfeDetalheVO := TObjectList<TNfeDetalheVO>.Create; FListaNfeDuplicataVO := TObjectList<TNfeDuplicataVO>.Create; FListaNfeFormaPagamentoVO := TObjectList<TNfeFormaPagamentoVO>.Create; FListaNfeProcessoReferenciadoVO := TObjectList<TNfeProcessoReferenciadoVO>.Create; end; destructor TNfeCabecalhoVO.Destroy; begin FreeAndNil(FEmpresaVO); FreeAndNil(FTributOperacaoFiscalVO); FreeAndNil(FFiscalNotaFiscalEntradaVO); FreeAndNil(FNfeEmitenteVO); FreeAndNil(FNfeDestinatarioVO); FreeAndNil(FNfeLocalRetiradaVO); FreeAndNil(FNfeLocalEntregaVO); FreeAndNil(FNfeTransporteVO); FreeAndNil(FNfeFaturaVO); FreeAndNil(FNfeCanaVO); FreeAndNil(FListaNfeReferenciadaVO); FreeAndNil(FListaNfeNfReferenciadaVO); FreeAndNil(FListaNfeCteReferenciadoVO); FreeAndNil(FListaNfeProdRuralReferenciadaVO); FreeAndNil(FListaNfeCupomFiscalReferenciadoVO); FreeAndNil(FListaNfeAcessoXmlVO); FreeAndNil(FListaNfeDetalheVO); FreeAndNil(FListaNfeDuplicataVO); FreeAndNil(FListaNfeFormaPagamentoVO); FreeAndNil(FListaNfeProcessoReferenciadoVO); inherited; end; initialization Classes.RegisterClass(TNfeCabecalhoVO); finalization Classes.UnRegisterClass(TNfeCabecalhoVO); end.
{ Procedure STRING_VSTRING (S, IN_STR, IN_LEN) * * Convert a Pascal, C, or FORTRAN string into the variable length string S. * IN_STR is the raw input string. It must be either null terminated (as * built-in strings are in C) or padded with blanks (as built-in strings are * in Pascal and FORTRAN. IN_LEN is storage length of IN_STR. This is how * far out blanks must extend if the string contains no null terminator. * * If IN_LEN is negative, then the input string MUST be null-terminated. * This indicates that the string length is not known. } module string_vstring; define string_vstring; %include 'string2.ins.pas'; procedure string_vstring ( {make var string from Pascal, C or FTN string} in out s: univ string_var_arg_t; {var string to fill in} in in_str: univ string; {source string characters} in in_len: string_index_t); {storage length of IN_STR} val_param; var i: sys_int_machine_t; {loop counter} limit: sys_int_machine_t; {end of string search limit} blanks_pending: sys_int_machine_t; {number of blanks read but not copied yet} begin s.len := 0; {init output string to empty} if s.len >= s.max then return; {output string already full ?} if in_len < 0 {determine input string scanning limit} then limit := lastof(limit) else limit := in_len; i := 1; {init index to first input string character} blanks_pending := 0; {init to no pending blanks exist} while i <= limit do begin {once for each character up to the limit} if in_str[i] = ' ' then begin {this input character is another blank} blanks_pending := blanks_pending + 1; {count one more pending blank} end else begin {this input char is non-blank} while blanks_pending > 0 do begin s.len := s.len + 1; {one more character in output string} s.str[s.len] := ' '; {write this output string character} if s.len >= s.max then return; {output string completely full ?} blanks_pending := blanks_pending - 1; {one less unwritten blank} end; if ord(in_str[i]) = 0 then return; {hit null terminating character ?} s.len := s.len + 1; {one more character in output string} s.str[s.len] := in_str[i]; {copy input string char to output string} if s.len >= s.max then return; {output string completely full ?} end ; i := i + 1; {advance to next input string character} end; {back and process this new input string char} end;
unit ChangePrice; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DBCtrls, DB, Grids, DBGrids, Mask, ZAbstractRODataset, ZDataset, DBCtrlsEh, DBLookupEh, DBGridEh, ZAbstractDataset, StrUtils, sTreeView, sEdit, sBitBtn, sLabel, MemDS, DBAccess, Uni; type TFormPriceChange = class(TForm) BitBtnCancel: TsBitBtn; Label1: TsLabel; Label4: TsLabel; DSPrice: TDataSource; BitBtnSave: TsBitBtn; Label2: TsLabel; Label3: TsLabel; edtPrice: TsEdit; edtNewPrice: TsEdit; edtRest: TsEdit; edtNewRest: TsEdit; QPrice: TUniQuery; QRestField: TUniQuery; QPricePL_ID: TIntegerField; QPricePL_PRICE: TFloatField; QPriceREST: TStringField; QRestFieldGS_FIELD: TStringField; QRestFieldGS_ORDERBY: TIntegerField; QUpdatePrice: TUniSQL; procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BitBtnSaveClick(Sender: TObject); private F_ID:Integer; F_RestName:string; public procedure SetPosition(L, T: Integer); procedure SetNewPrice(PL_ID, PL_TREEID:integer); end; var FormPriceChange: TFormPriceChange; implementation {$R *.dfm} uses DataModule, MainForm, CommonUnit, System.UITypes; const isReloadList: Boolean = True; { TFormCompany } procedure TFormPriceChange.SetPosition(L, T: Integer); begin Left:= L + ShiftLeft; Top:= T + ShiftTop; end; procedure TFormPriceChange.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of // VK_F2: BitBtnSave.Click; VK_Return: BitBtnSave.Click; VK_Escape: BitBtnCancel.Click; end; // case end; procedure TFormPriceChange.SetNewPrice(PL_ID, PL_TREEID:Integer); begin F_ID:=PL_ID; EdtPrice.Clear; EdtNewPrice.Clear; EdtRest.Clear; EdtNewRest.Clear; QRestField.Close; QRestField.ParamByName('TREEID').AsInteger:= PL_TREEID; QRestField.Open; if VarIsNull(QRestField['GS_FIELD']) then F_RestName:='0' else F_RestName:=QRestField['GS_FIELD']; QPrice.Close; QPrice.SQL.Text:='select PL_ID, PL_PRICE, '+F_RestName+' REST from price_lines pl where pl_id = :id'; QPrice.ParamByName('ID').AsInteger:= F_ID; QPrice.Open; EdtPrice.Text:=FloatToStr(0.01*Round(100*QPrice['PL_PRICE'])); EdtNewPrice.Text:=FloatToStr(0.01*Round(100*QPrice['PL_PRICE'])); if VarIsNull(QPrice['REST']) then begin EdtRest.Text:=''; EdtNewRest.Text:='0'; end else begin EdtRest.Text:=QPrice['REST']; EdtNewRest.Text:=QPrice['REST']; end; end; procedure TFormPriceChange.BitBtnSaveClick(Sender: TObject); begin if (edtNewPrice.Text<>edtPrice.Text) or (edtNewRest.Text<>edtRest.Text) then begin if Pos(',',edtNewPrice.Text)>0 then edtNewPrice.Text:=AnsiReplaceStr(edtNewPrice.Text,',',FormatSettings.DecimalSeparator); if Pos('.',edtNewPrice.Text)>0 then edtNewPrice.Text:=AnsiReplaceStr(edtNewPrice.Text,'.',FormatSettings.DecimalSeparator); if Pos(',',edtNewrest.Text)>0 then edtNewrest.Text:=AnsiReplaceStr(edtNewRest.Text,',',FormatSettings.DecimalSeparator); if Pos('.',edtNewRest.Text)>0 then edtNewRest.Text:=AnsiReplaceStr(edtNewRest.Text,'.',FormatSettings.DecimalSeparator); QUpdatePrice.ParamByName('ID').AsInteger:=F_ID; if F_RestName='0' then QUpdatePrice.SQL.Text:='UPDATE PRICE_LINES SET PL_PRICE=:PRICE WHERE PL_ID=:ID' else begin QUpdatePrice.SQL.Text:='UPDATE PRICE_LINES SET PL_PRICE=:PRICE, '+F_Restname+'=:RESTVALUE WHERE PL_ID=:ID'; QUpdatePrice.ParamByName('RESTVALUE').AsString:=edtNewRest.Text; end; QUpdatePrice.ParamByName('PRICE').AsFloat:=StrToFloat(edtNewPrice.Text); QUpdatePrice.Prepare; QUpdatePrice.Execute; end; end; end.
unit AlphaHintWindow; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TAlphaHintWindow = class(THintWindow) private procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWindowHandle(const Params: TCreateParams); override; public constructor Create(AOwner: TComponent); override; procedure ActivateHint(Rect: TRect; const AHint: string); override; end; implementation { TAlphaHintWindow } constructor TAlphaHintWindow.Create(AOwner: TComponent); begin inherited Create(AOwner); // window might be updated quite frequently, so enable double buffer DoubleBuffered := True; end; procedure TAlphaHintWindow.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); // include the layered window style (for alpha blending) Params.ExStyle := Params.ExStyle or WS_EX_LAYERED; end; procedure TAlphaHintWindow.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); // value of 220 here is the alpha (the same as form's AlphaBlendValue) SetLayeredWindowAttributes(Handle, ColorToRGB(clNone), 220, LWA_ALPHA); end; procedure TAlphaHintWindow.ActivateHint(Rect: TRect; const AHint: string); var Monitor: TMonitor; begin // from here was just stripped the animation part and fixed one bug // (setting a hint window top position when going off screen; it is // at least in Delphi 2009 with the most recent updates) Caption := AHint; Inc(Rect.Bottom, 4); UpdateBoundsRect(Rect); Monitor := Screen.MonitorFromPoint(Point(Rect.Left, Rect.Top)); if Width > Monitor.Width then Width := Monitor.Width; if Height > Monitor.Height then Height := Monitor.Height; if Rect.Top + Height > Monitor.Top + Monitor.Height then Rect.Top := (Monitor.Top + Monitor.Height) - Height; if Rect.Left + Width > Monitor.Left + Monitor.Width then Rect.Left := (Monitor.Left + Monitor.Width) - Width; if Rect.Left < Monitor.Left then Rect.Left := Monitor.Left; if Rect.Top < Monitor.Top then Rect.Top := Monitor.Top; ParentWindow := Application.Handle; SetWindowPos(Handle, HWND_TOPMOST, Rect.Left, Rect.Top, Width, Height, SWP_NOACTIVATE); ShowWindow(Handle, SW_SHOWNOACTIVATE); Invalidate; end; procedure TAlphaHintWindow.CMTextChanged(var Message: TMessage); begin // do exactly nothing, because we're adjusting the size by ourselves // and the ancestor would just autosize the window by the text; text // or if you want Caption, is updated only by calling ActivateHint end; end.
unit Stimset; { ============================================================= CHART - Set stimulator parameters module (c) J. Dempster, University of Strathclyde 1996-98 23/8/98 ... OK and Cancel buttons changed to ordinary buttons 6/2/01 .... Spin buttons removed and Validated edit boxes added 18/5/03 ... Pulse amplitude can now be set 23.07.13 ... 0.0 settings now replaced with defaults 03.12.13 ... On and Off voltages now defined =============================================================} interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, ExtCtrls, Spin, Shared, SysUtils, ValEdit, ValidatedEdit ; type TStimulatorDlg = class(TForm) bOK: TButton; bCancel: TButton; GroupBox1: TGroupBox; Label4: TLabel; edPulseVOn: TValidatedEdit; Label5: TLabel; edPulseVOff: TValidatedEdit; GroupBox2: TGroupBox; Period: TLabel; edRepeatPeriod: TValidatedEdit; Label2: TLabel; edNumStimuli: TValidatedEdit; Label1: TLabel; edPulseFrequency: TValidatedEdit; Label3: TLabel; edPulseWidth: TValidatedEdit; procedure FormActivate(Sender: TObject); procedure bOKClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var StimulatorDlg: TStimulatorDlg; implementation {$R *.DFM} uses Main ; procedure TStimulatorDlg.FormActivate(Sender: TObject); begin if MainFrm.Stimulator.GroupInterval <= 0.0 then MainFrm.Stimulator.GroupInterval := 1.0 ; EdRepeatPeriod.Value := MainFrm.Stimulator.GroupInterval ; EdNumStimuli.Value := MainFrm.Stimulator.PulsesPergroup ; if MainFrm.Stimulator.PulseFrequency <= 0.0 then MainFrm.Stimulator.PulseFrequency := 1.0 ; EdPulseFrequency.Value := MainFrm.Stimulator.PulseFrequency ; if MainFrm.Stimulator.PulseWidth <= 0.0 then MainFrm.Stimulator.PulseWidth := 0.1 ; EdPulseWidth.Value := MainFrm.Stimulator.PulseWidth ; edPulseVOn.Value := MainFrm.Stimulator.PulseVOn ; edPulseVOff.Value := MainFrm.Stimulator.PulseVOff ; end; procedure TStimulatorDlg.bOKClick(Sender: TObject); begin MainFrm.Stimulator.GroupInterval := EdRepeatPeriod.Value ; if MainFrm.Stimulator.GroupInterval <= 0.0 then MainFrm.Stimulator.GroupInterval := 1.0 ; MainFrm.Stimulator.RepeatPeriodmsec := Trunc( MainFrm.Stimulator.GroupInterval * 1000. ) ; MainFrm.Stimulator.PulsesPerGroup := Round(EdNumStimuli.Value); MainFrm.Stimulator.PulseFrequency := EdPulseFrequency.Value ; if MainFrm.Stimulator.PulseFrequency <= 0.0 then MainFrm.Stimulator.PulseFrequency := 1.0 ; MainFrm.Stimulator.PulseWidth := EdPulseWidth.Value ; if MainFrm.Stimulator.PulseWidth <= 0.0 then MainFrm.Stimulator.PulseWidth := 0.1 ; MainFrm.Stimulator.PulseVOn := edPulseVOn.Value ; MainFrm.Stimulator.PulseVOff := edPulseVOff.Value ; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Menus, StdCtrls, ComCtrls, BZMath, BZVectorMath, BZColors, BZGraphic, BZBitmap, BZGeoTools; type { TMainForm } TMainForm = class(TForm) Button1 : TButton; Memo1 : TMemo; pnlView : TPanel; tbTolerance : TTrackBar; procedure Button1Click(Sender : TObject); procedure FormClose(Sender : TObject; var CloseAction : TCloseAction); procedure FormCreate(Sender : TObject); procedure pnlViewPaint(Sender : TObject); procedure tbToleranceChange(Sender : TObject); private FArrayOfPoints : TBZArrayOfFloatPoints; FDisplayBuffer : TBZBitmap; FRDPPoints : TBZArrayOfFloatPoints; FDistPoints : TBZArrayOfFloatPoints; protected procedure SimplifyDist(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); procedure Internal_RamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; StartIndex, EndIndex : Integer; Var KeepPoints : Array of Boolean); procedure SimplifyRamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); public procedure GenPolyLine; procedure RenderPolyLine; procedure RenderPolyLineSimplyfied; end; var MainForm : TMainForm; implementation {$R *.lfm} uses BZTypesHelpers; { TMainForm } procedure TMainForm.FormCreate(Sender : TObject); begin FDisplayBuffer := TBZBitmap.Create(pnlView.Width, pnlView.Height); FDisplayBuffer.Clear(clrBlack); FArrayOfPoints := TBZArrayOfFloatPoints.Create(1024); Randomize; GenPolyLine; RenderPolyLine; end; procedure TMainForm.pnlViewPaint(Sender : TObject); begin FDisplayBuffer.DrawToCanvas(pnlView.Canvas, pnlView.ClientRect); end; procedure TMainForm.tbToleranceChange(Sender : TObject); begin Button1Click(Self); end; procedure TMainForm.SimplifyDist(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); Var KeepPoints : Array of Boolean; i, j, k : Integer; //SqTolerance : Single; {$CODEALIGN VARMIN=16} PrevPoint, CurrentPoint : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin //SqTolerance := Tolerance* Tolerance; k := InPts.Count; SetLength(KeepPoints{%H-}, k); KeepPoints[0] := True; KeepPoints[k-1] := True; For i := 2 to k-2 do KeepPoints[i] := False; PrevPoint := InPts.Items[0]; j := 1; For i := 1 to k-1 do begin CurrentPoint := InPts.Items[i]; //if (CurrentPoint.DistanceSquare(PrevPoint) > SqTolerance) then if (CurrentPoint.Distance(PrevPoint) > Tolerance) then begin KeepPoints[i] := True; PrevPoint := CurrentPoint; Inc(j); end; end; OutPts := TBZArrayofFloatPoints.Create(j); For i := 0 to k - 1 do begin if KeepPoints[i] then begin OutPts.Add(InPts.Items[i]); end; end; end; procedure TMainForm.Internal_RamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; StartIndex, EndIndex : Integer; var KeepPoints : array of Boolean); Var {$CODEALIGN VARMIN=16} p1, p2, p : TBZFloatPoint; {$CODEALIGN VARMIN=4} aLine : TBZ2DLineTool; i, MaxIndex : Integer; MaxDist, Dist : Single; begin MaxIndex := 0; MaxDist := -1.0; p1 := InPts.Items[StartIndex]; p2 := InPts.Items[EndIndex]; aLine := TBZ2DLineTool.Create; aLine.StartPoint := p1; aLine.EndPoint := p2; for i := StartIndex + 1 to EndIndex - 1 do begin p := InPts.Items[i]; Dist := aLine.DistanceSegmentToPoint(p); if Dist > MaxDist then begin MaxIndex := i; MaxDist := Dist; end; end; FreeAndNil(aLine); if MaxDist > Tolerance then begin KeepPoints[MaxIndex] := True; if (MaxIndex - StartIndex) > 1 then Internal_RamerDouglasPeucker(InPts, Tolerance, StartIndex, MaxIndex, KeepPoints); if (EndIndex - MaxIndex) > 1 then Internal_RamerDouglasPeucker(InPts, Tolerance, MaxIndex, EndIndex, KeepPoints); end; end; procedure TMainForm.SimplifyRamerDouglasPeucker(InPts : TBZArrayOfFloatPoints; Tolerance : Single; out OutPts : TBZArrayOfFloatPoints); Var KeepPoints : Array of Boolean; i, j, k : Integer; //SqTolerance : Single; begin //SqTolerance := Tolerance * Tolerance; k := InPts.Count; SetLength(KeepPoints{%H-}, k); KeepPoints[0] := True; KeepPoints[k-1] := True; For i := 2 to k-2 do KeepPoints[i] := False; Internal_RamerDouglasPeucker(InPts, Tolerance, 0, k, KeepPoints); j := 0; for i:= 0 to k - 1 do begin if KeepPoints[i] then Inc(j); end; OutPts := TBZArrayOfFloatPoints.Create(j); for i := 0 to k-1 do begin if KeepPoints[i] then begin OutPts.Add(InPts.Items[i]); end; end; end; procedure TMainForm.FormClose(Sender : TObject; var CloseAction : TCloseAction); begin FreeAndNil(FArrayOfPoints); if Assigned(FDistPoints) then FreeAndNil(FDistPoints); if Assigned(FRDPPoints) then FreeAndNil(FRDPPoints); FreeAndNil(FDisplayBuffer); end; procedure TMainForm.Button1Click(Sender : TObject); begin FDisplayBuffer.Clear(clrBlack); if Assigned(FDistPoints) then FreeAndNil(FDistPoints); if Assigned(FRDPPoints) then FreeAndNil(FRDPPoints); SimplifyDist(FArrayOfPoints, tbTolerance.Position, FDistPoints); //SimplifyRamerDouglasPeucker(FArrayOfPoints, tbTolerance.Position, FRDPPoints); SimplifyRamerDouglasPeucker(FDistPoints, tbTolerance.Position, FRDPPoints); RenderPolyLine; RenderPolyLineSimplyfied; pnlView.Invalidate; end; procedure TMainForm.GenPolyLine; Var x, i : Integer; {$CODEALIGN VARMIN=16} NewPt : TBZFloatPoint; {$CODEALIGN VARMIN=4} begin x := 0; While x < FDisplayBuffer.MaxWidth do //For x := 0 to FDisplayBuffer.MaxWidth do begin i := Integer.RandomRange(20,FDisplayBuffer.MaxHeight - 20); NewPt.Create(x, i); FArrayOfPoints.Add(NewPt); inc(x,3); end; end; procedure TMainForm.RenderPolyLine; begin With FDisplayBuffer.Canvas do begin Pen.Style := ssSolid; Pen.Color := clrBlue; PolyLine(FArrayOfPoints); end; // pnlView.Invalidate; end; procedure TMainForm.RenderPolyLineSimplyfied; begin With FDisplayBuffer.Canvas do begin Pen.Style := ssSolid; //Pen.Color := clrYellow; //PolyLine(FDistPoints); Pen.Color := clrFuchsia; PolyLine(FRDPPoints); end; // pnlView.Invalidate; end; end.
unit StratonPoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, Straton; type TTaxonomyTypeDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TStratTaxonomyDataPoster = class(TImplementedDataPoster) private FAllTaxonomyTypes: TTaxonomyTypes; procedure SetAllTaxonomyTypes(const Value: TTaxonomyTypes); public property AllTaxonomyTypes: TTaxonomyTypes read FAllTaxonomyTypes write SetAllTaxonomyTypes; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TSimpleStratonDataPoster = class(TImplementedDataPoster) private FAllStratTaxonomies: TStratTaxonomies; procedure SetAllStratTaxonomies(const Value: TStratTaxonomies); public property AllStratTaxonomies: TStratTaxonomies read FAllStratTaxonomies write SetAllStratTaxonomies; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TStratigraphicSchemeDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TStratotypeRegionDataPoster = class(TImplementedDataPoster) private FAllSimpleStratons: TSimpleStratons; procedure SetAllSimpleStratons(const Value: TSimpleStratons); public property AllSimpleStratons: TSimpleStratons read FAllSimpleStratons write SetAllSimpleStratons; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TStratonDataPoster = class(TImplementedDataPoster) private FAllStratigraphicSchemes: TStratigraphicSchemes; FAllStratotyRegions: TStratotypeRegions; FAllSimpleStratons: TSimpleStratons; procedure SetAllSimplStratons(const Value: TSimpleStratons); procedure SetAllStratigraphicSchemes(const Value: TStratigraphicSchemes); procedure SetAllStratotyRegions(const Value: TStratotypeRegions); public property AllStratigraphicSchemes: TStratigraphicSchemes read FAllStratigraphicSchemes write SetAllStratigraphicSchemes; property AllStratotypeRegions: TStratotypeRegions read FAllStratotyRegions write SetAllStratotyRegions; property AllSimpleStratons: TSimpleStratons read FAllSimpleStratons write SetAllSimplStratons; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils, SDFacade; var flag: Boolean; { TSimpleStratonDataPoster } constructor TSimpleStratonDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_STRATIGRAPHY_NAME_DICT'; //DataDeletionString := ''; //DataPostString := ''; KeyFieldNames := 'STRATON_ID'; FieldNames := 'STRATON_ID, TAXONOMY_UNIT_ID, VCH_STRATON_INDEX, VCH_STRATON_DEFINITION, VCH_COLOR, VCH_DECORATED_STRATON_INDEX'; AccessoryFieldNames := 'STRATON_ID, TAXONOMY_UNIT_ID, VCH_STRATON_INDEX, VCH_STRATON_DEFINITION, VCH_COLOR, VCH_DECORATED_STRATON_INDEX'; AutoFillDates := false; Sort := 'VCH_STRATON_INDEX'; end; function TSimpleStratonDataPoster.DeleteFromDB( AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TSimpleStratonDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TSimpleStraton; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TSimpleStraton; o.ID := ds.FieldByName('STRATON_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_STRATON_INDEX').AsString); o.DecoratedIndex := ds.FieldByName('VCH_DECORATED_STRATON_INDEX').AsString; o.Definition := ds.FieldByName('VCH_STRATON_DEFINITION').AsString; o.Color := ds.FieldByName('VCH_COLOR').AsString; o.Taxonomy := (TMainFacade.GetInstance as TMainFacade).AllStratTaxonomies.ItemsByID[ds.FieldByName('TAXONOMY_UNIT_ID').AsInteger] as TStratTaxonomy; ds.Next; end; ds.First; end; end; function TSimpleStratonDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; o: TSimpleStraton; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); o := AObject as TSimpleStraton; ds.FieldByName('STRATON_ID').Value := o.ID; ds.FieldByName('VCH_STRATON_INDEX').Value := o.Name; ds.FieldByName('VCH_DECORATED_STRATON_INDEX').Value := o.DecoratedIndex; ds.FieldByName('VCH_STRATON_DEFINITION').Value := o.Definition; ds.FieldByName('VCH_COLOR').Value := o.Color; ds.FieldByName('TAXONOMY_UNIT_ID').Value := o.Taxonomy.ID; ds.Post; o.ID := ds.FieldByName('STRATON_ID').AsInteger; end; procedure TSimpleStratonDataPoster.SetAllStratTaxonomies( const Value: TStratTaxonomies); begin if FAllStratTaxonomies <> Value then FAllStratTaxonomies := Value; end; { TStratTaxonomyDataPoster } constructor TStratTaxonomyDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_TAXONOMY_DICT'; KeyFieldNames := 'TAXONOMY_UNIT_ID'; FieldNames := 'TAXONOMY_UNIT_ID, VCH_TAXONOMY_UNIT_NAME, TAXONOMY_UNIT_TYPE_ID, NUM_RANGE'; AccessoryFieldNames := 'TAXONOMY_UNIT_ID, VCH_TAXONOMY_UNIT_NAME, TAXONOMY_UNIT_TYPE_ID, NUM_RANGE'; AutoFillDates := false; Sort := 'VCH_TAXONOMY_UNIT_NAME'; end; function TStratTaxonomyDataPoster.DeleteFromDB( AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TStratTaxonomyDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TStratTaxonomy; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TStratTaxonomy; o.ID := ds.FieldByName('TAXONOMY_UNIT_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_TAXONOMY_UNIT_NAME').AsString); o.TaxonomyType := (TMainFacade.GetInstance as TMainFacade).AllStratTaxonomyTypes.ItemsByID[ds.FieldByName('TAXONOMY_UNIT_TYPE_ID').AsInteger] as TTaxonomyType; o.Range := ds.FieldByName('NUM_RANGE').AsInteger; ds.Next; end; ds.First; end; end; function TStratTaxonomyDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; a: TStratTaxonomy; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); a := AObject as TStratTaxonomy; ds.FieldByName('TAXONOMY_UNIT_ID').Value := a.ID; ds.FieldByName('VCH_TAXONOMY_UNIT_NAME').Value := trim(a.Name); ds.FieldByName('TAXONOMY_UNIT_TYPE_ID').Value := a.TaxonomyType.ID; ds.FieldByName('NUM_RANGE').Value := a.Range; ds.Post; a.ID := ds.FieldByName('TAXONOMY_UNIT_ID').AsInteger; end; procedure TStratTaxonomyDataPoster.SetAllTaxonomyTypes( const Value: TTaxonomyTypes); begin if FAllTaxonomyTypes <> Value then FAllTaxonomyTypes := Value; end; { TStratonDataPoster } constructor TStratonDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_STRATON_PROPERTIES'; // DataPostString := 'TBL_STRATON_PROPERTIES'; // DataDeletionString := 'TBL_STRATON_PROPERTIES'; KeyFieldNames := 'STRATON_REGION_ID'; FieldNames := 'STRATON_REGION_ID, SCHEME_ID, REGION_ID, STRATON_ID, NUM_AGE_OF_BASE, ' + 'NUM_AGE_OF_TOP, VCH_STRATON_DEF_SYNONYM, VCH_SYNONYM_AUTHOR, NUM_DOUBTFUL_BASE, NUM_DOUBTFUL_AGES, NUM_NOT_AFFIRMED, VCH_BASE9_VOLUME, VCH_TOP9_VOLUME, BASE_STRATON_REGION_ID, TOP_STRATON_REGION_ID'; AccessoryFieldNames := 'STRATON_REGION_ID, SCHEME_ID, REGION_ID, STRATON_ID, NUM_AGE_OF_BASE' + ' NUM_AGE_OF_TOP, VCH_STRATON_DEF_SYNONYM, VCH_SYNONYM_AUTHOR, NUM_DOUBTFUL_BASE, NUM_DOUBTFUL_AGES, NUM_NOT_AFFIRMED, VCH_BASE9_VOLUME, VCH_TOP9_VOLUME, BASE_STRATON_REGION_ID, TOP_STRATON_REGION_ID'; AutoFillDates := false; Sort := 'NUM_AGE_OF_BASE'; end; function TStratonDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TStratonDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TStraton; begin Assert(Assigned(AllSimpleStratons)); Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if flag = false then if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TStraton; // AObjects.Add(Found, False, False) - это для ChildStratonPoster - после того как мы нашли Found по Straton_Region_ID o.Name := (AllSimpleStratons.ItemsByID[ds.FieldByName('STRATON_ID').AsInteger] as TSimpleStraton).Name; o.ID := ds.FieldByName('STRATON_REGION_ID').AsInteger; o.Straton := AllSimpleStratons.ItemsByID[ds.FieldByName('STRATON_ID').AsInteger] as TSimpleStraton; o.BaseStraton := TEmptyStraton.Create(ds.FieldByName('BASE_STRATON_REGION_ID').AsInteger); o.TopStraton := TEmptyStraton.Create(ds.FieldByName('TOP_STRATON_REGION_ID').AsInteger); if Assigned(AllStratigraphicSchemes) then o.Scheme := AllStratigraphicSchemes.ItemsByID[ds.FieldByName('SCHEME_ID').AsInteger] as TStratigraphicScheme; if Assigned(AllStratotypeRegions) then o.Region := AllStratotypeRegions.ItemsByID[ds.FieldByName('REGION_ID').AsInteger] as TStratotypeRegion; o.AgeOfBase := ds.FieldByName('NUM_AGE_OF_BASE').AsFloat; o.AgeOfTop := ds.FieldByName('NUM_AGE_OF_TOP').AsFloat; o.StratonDefSynonym := ds.FieldByName('VCH_STRATON_DEF_SYNONYM').AsString; o.SynonymAuthor := ds.FieldByName('VCH_SYNONYM_AUTHOR').AsString; o.DoubtfulBase := ds.FieldByName('NUM_DOUBTFUL_BASE').AsInteger; o.DoubtfulAges := ds.FieldByName('NUM_DOUBTFUL_AGES').AsInteger; o.NotAffirmed := ds.FieldByName('NUM_NOT_AFFIRMED').AsInteger; o.Base9Volume := ds.FieldByName('VCH_BASE9_VOLUME').AsString; o.Top9Volume := ds.FieldByName('VCH_TOP9_VOLUME').AsString; ds.Next; end; ds.First; end; flag := False; end; function TStratonDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; a: TStraton; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); a := AObject as TStraton; ds.FieldByName('STRATON_REGION_ID').Value := a.ID; ds.FieldByName('STRATON_ID').Value := a.Straton.ID; ds.FieldByName('BASE_STRATON_REGION_ID').Value := a.BaseStraton.ID; ds.FieldByName('TOP_STRATON_REGION_ID').Value := a.TopStraton.ID; ds.FieldByName('SCHEME_ID').Value := a.Scheme.ID; ds.FieldByName('REGION_ID').Value := a.Region.ID; ds.FieldByName('NUM_AGE_OF_BASE').Value := a.AgeOfBase; ds.FieldByName('NUM_AGE_OF_TOP').Value := a.AgeOfTop; ds.FieldByName('VCH_STRATON_DEF_SYNONYM').Value := a.StratonDefSynonym; ds.FieldByName('VCH_SYNONYM_AUTHOR').Value := a.SynonymAuthor; ds.FieldByName('NUM_DOUBTFUL_BASE').Value := a.DoubtfulBase; ds.FieldByName('NUM_DOUBTFUL_AGES').Value := a.DoubtfulAges; ds.FieldByName('NUM_NOT_AFFIRMED').Value := a.NotAffirmed; ds.FieldByName('VCH_BASE9_VOLUME').Value := a.Base9Volume; ds.FieldByName('VCH_TOP9_VOLUME').Value := a.Top9Volume; ds.Post; a.ID := ds.FieldByName('STRATON_REGION_ID').AsInteger; end; procedure TStratonDataPoster.SetAllSimplStratons( const Value: TSimpleStratons); begin if FAllSimpleStratons <> Value then FAllSimpleStratons := Value; end; procedure TStratonDataPoster.SetAllStratigraphicSchemes( const Value: TStratigraphicSchemes); begin if FAllStratigraphicSchemes <> Value then FAllStratigraphicSchemes := Value; end; procedure TStratonDataPoster.SetAllStratotyRegions( const Value: TStratotypeRegions); begin if FAllStratotyRegions <> Value then FAllStratotyRegions := Value; end; {procedure TStratonDataPoster.SetAllTaxonomies( const Value: TStratTaxonomies); begin if FAllTaxonomies <> Value then FAllTaxonomies := Value; end; } { procedure TStratonDataPoster.SetAllTaxonomyTypes( const Value: TTaxonomyTypes); begin if FAllTaxonomyTypes <> Value then FAllTaxonomyTypes := Value; end; } constructor TTaxonomyTypeDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_TAXONOMY_TYPE_DICT'; KeyFieldNames := 'TAXONOMY_UNIT_TYPE_ID'; FieldNames := 'TAXONOMY_UNIT_TYPE_ID, VCH_TAXONOMY_UNIT_TYPE_NAME, NUM_DIVISION_ASPECT'; AccessoryFieldNames := 'TAXONOMY_UNIT_TYPE_ID, VCH_TAXONOMY_UNIT_TYPE_NAME, NUM_DIVISION_ASPECT'; AutoFillDates := false; Sort := 'VCH_TAXONOMY_UNIT_TYPE_NAME'; end; function TTaxonomyTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TTaxonomyTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TTaxonomyType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TTaxonomyType; o.ID := ds.FieldByName('TAXONOMY_UNIT_TYPE_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_TAXONOMY_UNIT_TYPE_NAME').AsString); o.DivisionAspect := ds.FieldByName('NUM_DIVISION_ASPECT').AsInteger; ds.Next; end; ds.First; end; end; function TTaxonomyTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; a: TTaxonomyType; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); a := AObject as TTaxonomyType; ds.FieldByName('TAXONOMY_UNIT_TYPE_ID').Value := a.ID; ds.FieldByName('VCH_TAXONOMY_UNIT_TYPE_NAME').Value := trim(a.Name); ds.FieldByName('NUM_DIVISION_ASPECT').Value := a.DivisionAspect; ds.Post; a.ID := ds.FieldByName('TAXONOMY_UNIT_TYPE_ID').AsInteger; end; { TStratigraphicSchemeDataPoster } constructor TStratigraphicSchemeDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_STRATIGRAPHIC_SCHEME_DICT'; KeyFieldNames := 'SCHEME_ID'; FieldNames := 'SCHEME_ID, VCH_SCHEME_NAME, NUM_AFFIRMATION_YEAR, VCH_DESCRIPTION'; AccessoryFieldNames := 'SCHEME_ID, VCH_SCHEME_NAME, NUM_AFFIRMATION_YEAR, VCH_DESCRIPTION'; AutoFillDates := false; Sort := 'SCHEME_ID'; end; function TStratigraphicSchemeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TStratigraphicSchemeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TStratigraphicScheme; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TStratigraphicScheme; o.ID := ds.FieldByName('SCHEME_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_SCHEME_NAME').AsString); o.AffirmationYear := ds.FieldByName('NUM_AFFIRMATION_YEAR').AsInteger; o.Description := trim(ds.FieldByName('VCH_DESCRIPTION').AsString); ds.Next; end; ds.First; end; end; function TStratigraphicSchemeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; a: TStratigraphicScheme; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); a := AObject as TStratigraphicScheme; ds.FieldByName('SCHEME_ID').Value := a.ID; ds.FieldByName('VCH_SCHEME_NAME').Value := trim(a.Name); ds.FieldByName('NUM_AFFIRMATION_YEAR').Value := a.AffirmationYear; ds.FieldByName('VCH_DESCRIPTION').Value := trim(a.Description);; ds.Post; a.ID := ds.FieldByName('SCHEME_ID').AsInteger; end; { TStratotypeRegionDataPoster } constructor TStratotypeRegionDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_STRATOTYPE_REGION_DICT'; KeyFieldNames := 'REGION_ID'; FieldNames := 'REGION_ID, STRATON_ID, VCH_REGION_NAME'; AccessoryFieldNames := 'REGION_ID, STRATON_ID, VCH_REGION_NAME'; AutoFillDates := false; Sort := 'REGION_ID'; end; function TStratotypeRegionDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TStratotypeRegionDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; o: TStratotypeRegion; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; if Assigned(AObjects) then while not ds.Eof do begin o := AObjects.Add as TStratotypeRegion; o.ID := ds.FieldByName('REGION_ID').AsInteger; o.Name := trim(ds.FieldByName('VCH_REGION_NAME').AsString); o.Straton := (TMainFacade.GetInstance as TMainFacade).AllSimpleStratons.ItemsByID[ds.FieldByName('STRATON_ID').AsInteger] as TSimpleStraton; ds.Next; end; ds.First; end; end; function TStratotypeRegionDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; a: TStratotypeRegion; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); a := AObject as TStratotypeRegion; ds.FieldByName('REGION_ID').Value := a.ID; ds.FieldByName('VCH_REGION_NAME').Value := trim(a.Name); ds.FieldByName('STRATON_ID').Value := a.Straton.ID; ds.Post; a.ID := ds.FieldByName('REGION_ID').AsInteger; end; procedure TStratotypeRegionDataPoster.SetAllSimpleStratons( const Value: TSimpleStratons); begin if FAllSimpleStratons <> Value then FAllSimpleStratons := Value; end; end.
unit Services.Utils; interface uses System.SysUtils, System.StrUtils, FMX.Objects, FMX.Graphics, Soap.EncdDecd; type TServicesUtils = class private public class procedure ResourceImage( aResourceName : String; aImage : TImage); class function Base64FromBitmap(aBitmap : TBitmap) : String; class function BitmapFromBase64(const aBase64 : String) : TBitmap; class function MonthName(aData : TDateTime) : String; class function StrToCurrency(Value : String) : Currency; end; implementation uses System.Classes , System.Types , System.DateUtils //, System.Hash , IdCoderMIME , IdHashMessageDigest; { TServicesUtils } class function TServicesUtils.Base64FromBitmap(aBitmap: TBitmap): String; var aRestorno : String; aInput : TBytesStream; aOutput : TStringStream; begin aRestorno := EmptyStr; try if Assigned(aBitmap) then begin aInput := TBytesStream.Create; aBitmap.SaveToStream(aInput); aInput.Position := 0; aOutput := TStringStream.Create('', TEncoding.ASCII); Soap.EncdDecd.EncodeStream(aInput, aOutput); aRestorno := aOutput.DataString; end; finally if Assigned(aInput) then aInput.DisposeOf; if Assigned(aOutput) then aOutput.DisposeOf; Result := aRestorno; end; end; class function TServicesUtils.BitmapFromBase64(const aBase64: String): TBitmap; var aRestorno : TBitmap; aInput : TStringStream; aOutput : TBytesStream; begin aRestorno := nil; aInput := TStringStream.Create(aBase64, TEncoding.ASCII); aOutput := TBytesStream.Create; try if not aBase64.Trim.IsEmpty then begin Soap.EncdDecd.DecodeStream(aInput, aOutput); aOutput.Position := 0; aRestorno := TBitmap.Create; aRestorno.LoadFromStream(aOutput); end; finally if Assigned(aOutput) then aOutput.DisposeOf; if Assigned(aInput) then aInput.DisposeOf; Result := aRestorno; end; end; class function TServicesUtils.MonthName(aData: TDateTime): String; var aRetorno : String; begin aRetorno := EmptyStr; case MonthOf(aData) of 1 : aRetorno := 'Janeiro'; 2 : aRetorno := 'Fevereiro'; 3 : aRetorno := 'Março'; 4 : aRetorno := 'Abril'; 5 : aRetorno := 'Maio'; 6 : aRetorno := 'Junho'; 7 : aRetorno := 'Julho'; 8 : aRetorno := 'Agosto'; 9 : aRetorno := 'Setembro'; 10 : aRetorno := 'Outubro'; 11 : aRetorno := 'Novembro'; 12 : aRetorno := 'Dezembro'; end; Result := aRetorno; end; class procedure TServicesUtils.ResourceImage(aResourceName: String; aImage: TImage); var Resource : TResourceStream; begin Resource := TResourceStream.Create(HInstance, aResourceName, RT_RCDATA); try aImage.Bitmap.LoadFromStream(Resource); finally Resource.DisposeOf; end; end; class function TServicesUtils.StrToCurrency(Value: String): Currency; begin Result := StrToCurrDef(Value.Trim.Replace('.', '').Replace(',', ''), 0) / 100.0; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ColorBox, Contnrs; type { TForm1 } TForm1 = class(TForm) Button1: TButton; ColorBox1: TColorBox; Edit1: TEdit; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { private declarations } thList: TObjectList; procedure GarbageCollection; public { public declarations } end; var Form1: TForm1; implementation uses synsock, blcksock, synautil, HTTPSend; {$R *.lfm} type { TSockThread } TSockThread = class(TThread) private HTTP: THTTPSend; LogData: string; URI: string; procedure AddLog; procedure BeginSock; procedure EndSock; public DoneFlag: boolean; constructor Create(const auri: string); destructor Destroy; override; procedure Execute; override; end; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin Edit1.Text := 'www.yahoo.com, w.y.c, www.google.com, www.google.com:8080'; Memo1.Lines.Clear; thList := TObjectList.Create(False); end; procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin Hide; // Because FormDestroy() may take time. end; procedure TForm1.FormDestroy(Sender: TObject); var i: integer; SockThread: TSockThread; begin for i := 0 to thList.Count - 1 do begin SockThread := TSockThread(thList[i]); SockThread.HTTP.Sock.AbortSocket; SockThread.Terminate; SockThread.WaitFor; // It may take time. SockThread.Free; end; thList.Free; end; procedure TForm1.GarbageCollection; var i: integer; th: TSockThread; begin i := 0; while i < thList.Count do begin th := TSockThread(thList[i]); if th.DoneFlag then begin th.Free; thList.Delete(i); end else Inc(i); end; end; procedure TForm1.Button1Click(Sender: TObject); var i: integer; th: TSockThread; begin if Button1.Caption = 'Go' then begin Memo1.Lines.Clear; Button1.Caption := 'Abort'; GarbageCollection; thList.Add(TSockThread.Create(Edit1.Text)); Memo1.Lines.Add('Thread Count: ' + IntToStr(thList.Count)); end else begin for i := 0 to thList.Count - 1 do begin th := TSockThread(thList[i]); th.HTTP.Sock.AbortSocket; th.Terminate; end; Button1.Caption := 'Go'; end; end; { TSockThread } constructor TSockThread.Create(const auri: string); begin HTTP := THTTPSend.Create; URI := auri; FreeOnTerminate := False; Priority := tpNormal; inherited Create(False); end; destructor TSockThread.Destroy; begin HTTP.Free; inherited Destroy; end; procedure TSockThread.Execute; var s: string; begin DoneFlag := False; Synchronize(@BeginSock); try while not Terminated do begin s := Trim(Fetch(URI, ',')); if s = '' then begin LogData := 'Finished.' + CRLF; Synchronize(@AddLog); Break; end; LogData := StringOfChar('=', 80) + CRLF + s; Synchronize(@AddLog); HTTP.Timeout := 60 * 1000; HTTP.HTTPMethod('GET', s); if Terminated then Break; if HTTP.Sock.LastError = 0 then begin LogData := LogData + HTTP.Headers.Text + CRLF; end else LogData := LogData + 'ERROR: ' + HTTP.Sock.LastErrorDesc + CRLF; LogData := LogData + StringOfChar('=', 80); Synchronize(@AddLog); end; finally Synchronize(@EndSock); DoneFlag := True; end; end; procedure TSockThread.AddLog; begin Form1.Memo1.Lines.BeginUpdate; try Form1.Memo1.Lines.Text := Form1.Memo1.Lines.Text + LogData + CRLF; finally Form1.Memo1.Lines.EndUpdate; end; LogData := ''; end; procedure TSockThread.BeginSock; begin Form1.ColorBox1.Selected := clRed; end; procedure TSockThread.EndSock; var i: integer; b, b1, b2: boolean; SockThread: TSockThread; begin b1 := False; b2 := False; for i := 0 to Form1.thList.Count - 1 do begin SockThread := TSockThread(Form1.thList[i]); b := (SockThread <> Self) and not SockThread.DoneFlag; b1 := b1 or b; b2 := b2 or (b and not SockThread.Terminated); end; if not b1 then Form1.ColorBox1.Selected := clGreen; if not b2 then Form1.Button1.Caption := 'Go'; end; end.
unit FindText; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; const diForward = 0; diBackward = 1; scGlobal = 0; scSelected_Text = 1; orFrom_Cursor = 0; orEntire_Scope = 1; type TFind = class(TForm) Label1: TLabel; Text: TComboBox; Options: TGroupBox; Direction: TRadioGroup; Scope: TRadioGroup; Origin: TRadioGroup; MatchCase: TCheckBox; WholeWords: TCheckBox; Ok: TButton; Cancel: TButton; procedure OkClick(Sender: TObject); procedure CancelClick(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Find: TFind; implementation {$R *.DFM} procedure TFind.OkClick(Sender: TObject); begin ModalResult := mrOk; end; procedure TFind.CancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFind.FormActivate(Sender: TObject); begin OK.SetFocus; end; end.
function ValidateUrl(url: string): boolean; var isHttps : boolean; begin url := Uppercase(url); if Length(url) >= 5 then begin isHttps := url[5] = 'S'; end; if isHttps then begin Result := (Length(url) > 8) and (url[1] = 'H') and (url[2] = 'T') and (url[3] = 'T') and (url[4] = 'P') and (url[6] = ':') and (url[7] = '/') and (url[8] = '/'); end else begin Result := (Length(url) > 7) and (url[1] = 'H') and (url[2] = 'T') and (url[3] = 'T') and (url[4] = 'P') and (url[5] = ':') and (url[6] = '/') and (url[7] = '/'); end; end;
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } {$INCLUDE ..\ormbr.inc} unit ormbr.manager.objectset; interface uses Rtti, SysUtils, Variants, Generics.Collections, // ORMBr {$IFDEF DRIVERRESTFUL} ormbr.restobjectset.adapter, ormbr.client.interfaces, {$ELSE} ormbr.objectset.adapter, dbebr.factory.interfaces, {$ENDIF} ormbr.objectset.base.adapter; type TRepository = class private FObjectSet: TObject; FNestedList: TObjectList<TObject>; public constructor Create; destructor Destroy; override; property ObjectSet: TObject read FObjectSet write FObjectSet; property NestedList: TObjectList<TObject> read FNestedList write FNestedList; end; // Lista de Container TRepositoryList = TObjectDictionary<string, TRepository>; IMOConnection = {$IFDEF DRIVERRESTFUL}IRESTConnection{$ELSE}IDBConnection{$ENDIF}; // TManagerObjectSet TManagerObjectSet = class private FConnection: IMOConnection; FRepository: TRepositoryList; FCurrentIndex: Integer; FSelectedObject: TObject; FOwnerNestedList: Boolean; function Resolver<T: class, constructor>: TObjectSetBaseAdapter<T>; procedure ListChanged<T: class, constructor>(Sender: TObject; const Item: T; Action: TCollectionNotification); procedure SelectNestedListItem<T: class>; procedure LoadLazy<T: class, constructor>(const AOwner, AObject: TObject); overload; public constructor Create(const AConnection: IMOConnection); destructor Destroy; override; function AddAdapter<T: class, constructor>(const APageSize: Integer = -1): TManagerObjectSet; function NestedList<T: class>: TObjectList<T>; // ObjectSet function Find<T: class, constructor>: TObjectList<T>; overload; function Find<T: class, constructor>(const AID: Variant): T; overload; function FindWhere<T: class, constructor>(const AWhere: string; const AOrderBy: string = ''): TObjectList<T>; {$IFDEF DRIVERRESTFUL} function Find<T: class, constructor>(const AMethodName: String; const AParams: array of string): TObjectList<T>; overload; {$ENDIF} function ModifiedFields<T: class, constructor>: TDictionary<string, TDictionary<string, string>>; function ExistSequence<T: class, constructor>: Boolean; procedure LoadLazy<T: class, constructor>(const AObject: TObject); overload; // Métodos para serem usados com a propriedade OwnerNestedList := False; function Insert<T: class, constructor>(const AObject: T): Integer; overload; procedure Modify<T: class, constructor>(const AObject: T); overload; procedure Update<T: class, constructor>(const AObject: T); overload; procedure Delete<T: class, constructor>(const AObject: T); overload; procedure NextPacket<T: class, constructor>(var AObjectList: TObjectList<T>); overload; procedure New<T: class, constructor>(var AObject: T); overload; // Métodos para serem usados com a propriedade OwnerNestedList := True; function Current<T: class, constructor>: T; overload; function Current<T: class, constructor>(const AIndex: Integer): T; overload; function New<T: class, constructor>: Integer; overload; function Insert<T: class, constructor>: Integer; overload; procedure Modify<T: class, constructor>; overload; procedure Update<T: class, constructor>; overload; procedure Delete<T: class, constructor>; overload; procedure NextPacket<T: class, constructor>; overload; function First<T: class, constructor>: Integer; function Next<T: class, constructor>: Integer; function Prior<T: class, constructor>: Integer; function Last<T: class, constructor>: Integer; function Eof<T: class>: Boolean; function Bof<T: class>: Boolean; property OwnerNestedList: Boolean read FOwnerNestedList write FOwnerNestedList; end; implementation { TManagerObjectSet } function TManagerObjectSet.Bof<T>: Boolean; begin Result := False; if not FOwnerNestedList then Exit; Result := (FCurrentIndex = FRepository.Items[T.ClassName].NestedList.Count -1); end; constructor TManagerObjectSet.Create(const AConnection: IMOConnection); begin FConnection := AConnection; FRepository := TRepositoryList.Create([doOwnsValues]); FCurrentIndex := 0; FOwnerNestedList := False; end; function TManagerObjectSet.Current<T>(const AIndex: Integer): T; begin Result := nil; if not FOwnerNestedList then Exit; FCurrentIndex := AIndex; Result := Current<T>; end; function TManagerObjectSet.Current<T>: T; begin Result := nil; if not FOwnerNestedList then Exit; SelectNestedListItem<T>; Result := T(FRepository.Items[T.ClassName].NestedList.Items[FCurrentIndex]); end; procedure TManagerObjectSet.Delete<T>(const AObject: T); begin Resolver<T>.Delete(AObject); end; destructor TManagerObjectSet.Destroy; begin FRepository.Free; inherited; end; function TManagerObjectSet.NestedList<T>: TObjectList<T>; var LClassName: String; begin Result := nil; if not FOwnerNestedList then raise Exception.Create('Enable the OwnerNestedList property'); LClassName := TClass(T).ClassName; if FRepository.ContainsKey(LClassName) then Result := TObjectList<T>(FRepository.Items[LClassName].NestedList); end; function TManagerObjectSet.New<T>: Integer; var LNewObject: T; LObjectList: TObjectList<T>; begin Result := -1; if not FOwnerNestedList then Exit; if not Assigned(FRepository.Items[TClass(T).ClassName].NestedList) then begin LObjectList := TObjectList<T>.Create; LObjectList.OnNotify := ListChanged<T>; FRepository.Items[TClass(T).ClassName].NestedList := TObjectList<TObject>(LObjectList); FCurrentIndex := 0; end; Resolver<T>.New(LNewObject); FRepository.Items[TClass(T).ClassName].NestedList.Add(LNewObject); FCurrentIndex := FRepository.Items[TClass(T).ClassName].NestedList.Count -1; Result := FCurrentIndex; end; procedure TManagerObjectSet.New<T>(var AObject: T); begin AObject := nil; Resolver<T>.New(AObject); end; procedure TManagerObjectSet.Delete<T>; begin if not FOwnerNestedList then Exit; SelectNestedListItem<T>; Resolver<T>.Delete(FSelectedObject); FRepository.Items[TClass(T).ClassName].NestedList.Delete(FCurrentIndex); end; function TManagerObjectSet.Eof<T>: Boolean; begin Result := False; if not FOwnerNestedList then Exit; Result := (FCurrentIndex +1 > FRepository.Items[T.ClassName].NestedList.Count -1); end; function TManagerObjectSet.ExistSequence<T>: Boolean; begin Result := Resolver<T>.ExistSequence; end; function TManagerObjectSet.Find<T>(const AID: Variant): T; begin if TVarData(AID).VType = varInteger then Result := Resolver<T>.Find(Integer(AID)) else if TVarData(AID).VType = varString then Result := Resolver<T>.Find(VarToStr(AID)); FCurrentIndex := 0; end; function TManagerObjectSet.AddAdapter<T>(const APageSize: Integer): TManagerObjectSet; var LObjectetAdapter: TObjectSetBaseAdapter<T>; LClassName: String; LRepository: TRepository; begin Result := Self; LClassName := TClass(T).ClassName; if FRepository.ContainsKey(LClassName) then Exit; {$IFDEF DRIVERRESTFUL} LObjectetAdapter := TRESTObjectSetAdapter<T>.Create(FConnection, APageSize); {$ELSE} LObjectetAdapter := TObjectSetAdapter<T>.Create(FConnection, APageSize); {$ENDIF} // Adiciona o container ao repositório de containers LRepository := TRepository.Create; LRepository.ObjectSet := LObjectetAdapter; FRepository.Add(LClassName, LRepository); end; function TManagerObjectSet.Find<T>: TObjectList<T>; var LObjectList: TObjectList<T>; begin Result := nil; if not FOwnerNestedList then begin Result := Resolver<T>.Find; Exit; end; LObjectList := Resolver<T>.Find; LObjectList.OnNotify := ListChanged<T>; // Lista de objetos FRepository.Items[TClass(T).ClassName].NestedList.Free; FRepository.Items[TClass(T).ClassName].NestedList := TObjectList<TObject>(LObjectList); FCurrentIndex := 0; end; function TManagerObjectSet.Resolver<T>: TObjectSetBaseAdapter<T>; var LClassName: String; begin Result := nil; LClassName := TClass(T).ClassName; if not FRepository.ContainsKey(LClassName) then raise Exception.Create('Use the AddAdapter<T> method to add the class to manager'); Result := TObjectSetBaseAdapter<T>(FRepository.Items[LClassName].ObjectSet); end; procedure TManagerObjectSet.SelectNestedListItem<T>; begin FSelectedObject := FRepository.Items[TClass(T).ClassName].NestedList.Items[FCurrentIndex]; end; procedure TManagerObjectSet.Update<T>; begin if not FOwnerNestedList then Exit; SelectNestedListItem<T>; Resolver<T>.Update(FSelectedObject); end; procedure TManagerObjectSet.Update<T>(const AObject: T); begin Resolver<T>.Update(AObject); end; function TManagerObjectSet.FindWhere<T>(const AWhere, AOrderBy: string): TObjectList<T>; var LObjectList: TObjectList<T>; begin Result := nil; if not FOwnerNestedList then begin Result := Resolver<T>.FindWhere(AWhere, AOrderBy); Exit; end; LObjectList := Resolver<T>.FindWhere(AWhere, AOrderBy); LObjectList.OnNotify := ListChanged<T>; // Lista de objetos FRepository.Items[TClass(T).ClassName].NestedList.Free; FRepository.Items[TClass(T).ClassName].NestedList := TObjectList<TObject>(LObjectList); FCurrentIndex := 0; end; function TManagerObjectSet.First<T>: Integer; begin Result := -1; if not FOwnerNestedList then Exit; FCurrentIndex := 0; Result := FCurrentIndex; end; function TManagerObjectSet.Insert<T>: Integer; begin Result := -1; if not FOwnerNestedList then Exit; Resolver<T>.Insert(FSelectedObject); Result := FCurrentIndex; end; function TManagerObjectSet.Insert<T>(const AObject: T): Integer; begin Result := FCurrentIndex; Resolver<T>.Insert(AObject); if not FOwnerNestedList then Exit; FRepository.Items[TClass(T).ClassName].NestedList.Add(AObject); FCurrentIndex := FRepository.Items[TClass(T).ClassName].NestedList.Count -1; end; function TManagerObjectSet.Last<T>: Integer; begin Result := -1; if not FOwnerNestedList then Exit; FCurrentIndex := FRepository.Items[TClass(T).ClassName].NestedList.Count -1; Result := FCurrentIndex; end; procedure TManagerObjectSet.ListChanged<T>(Sender: TObject; const Item: T; Action: TCollectionNotification); var LClassName: String; begin if Action = cnAdded then // After begin FCurrentIndex := FRepository.Items[TClass(T).ClassName].NestedList.Count -1; end else if Action = cnRemoved then // After begin LClassName := TClass(T).ClassName; if not FRepository.ContainsKey(LClassName) then Exit; if FRepository.Items[LClassName].NestedList.Count = 0 then Dec(FCurrentIndex); if FRepository.Items[LClassName].NestedList.Count > 1 then Dec(FCurrentIndex); end else if Action = cnExtracted then // After begin end; end; procedure TManagerObjectSet.LoadLazy<T>(const AObject: TObject); begin Resolver<T>.LoadLazy(TObjectSetBaseAdapter<T>(FRepository.Items[T.ClassName].ObjectSet), AObject); end; procedure TManagerObjectSet.LoadLazy<T>(const AOwner, AObject: TObject); begin Resolver<T>.LoadLazy(AOwner, AObject); end; function TManagerObjectSet.ModifiedFields<T>: TDictionary<string, TDictionary<string, string>>; begin Result := Resolver<T>.ModifiedFields; end; procedure TManagerObjectSet.Modify<T>; begin if not FOwnerNestedList then Exit; SelectNestedListItem<T>; Resolver<T>.Modify(FSelectedObject); end; procedure TManagerObjectSet.Modify<T>(const AObject: T); begin Resolver<T>.Modify(AObject); end; function TManagerObjectSet.Next<T>: Integer; begin Result := -1; if not FOwnerNestedList then Exit; if FCurrentIndex < FRepository.Items[TClass(T).ClassName].NestedList.Count -1 then Inc(FCurrentIndex); Result := FCurrentIndex; end; procedure TManagerObjectSet.NextPacket<T>(var AObjectList: TObjectList<T>); begin Resolver<T>.NextPacket(AObjectList); end; procedure TManagerObjectSet.NextPacket<T>; var LObjectList: TObjectList<T>; begin if not FOwnerNestedList then Exit; LObjectList := TObjectList<T>(FRepository.Items[TClass(T).ClassName].NestedList); Resolver<T>.NextPacket(LObjectList); end; function TManagerObjectSet.Prior<T>: Integer; begin Result := -1; if not FOwnerNestedList then Exit; if FCurrentIndex > FRepository.Items[TClass(T).ClassName].NestedList.Count -1 then Dec(FCurrentIndex); Result := FCurrentIndex; end; {$IFDEF DRIVERRESTFUL} function TManagerObjectSet.Find<T>(const AMethodName: String; const AParams: array of string): TObjectList<T>; var LObjectList: TObjectList<T>; begin Result := nil; if not FOwnerNestedList then begin Result := Resolver<T>.Find(AMethodName, AParams); Exit; end; LObjectList := Resolver<T>.Find(AMethodName, AParams); LObjectList.OnNotify := ListChanged<T>; // Lista de objetos FRepository.Items[TClass(T).ClassName].NestedList.Free; FRepository.Items[TClass(T).ClassName].NestedList := TObjectList<TObject>(LObjectList); end; {$ENDIF} { TRepository } constructor TRepository.Create; begin end; destructor TRepository.Destroy; begin if Assigned(FObjectSet) then FObjectSet.Free; if Assigned(FNestedList) then FNestedList.Free; inherited; end; end.
unit ViewModel.ViewModel.Standard; interface uses cwCollections , ViewModel , DataModel ; type TViewModel = class( TInterfacedObject, IViewModel ) private fDataModel: IDataModel; strict private procedure CleanUp; procedure UpdateUserPing( const UserID: string ); function getPublicGames: string; function CreateGame( const json: string ): string; function JoinGame( const json: string ): string; function getUsers( const AuthToken: string ): string; function setGameState( AuthToken: string; const json: string ): string; function getCurrentGame( AuthToken : String) : IGameData; function getCurrentTurn( AuthToken: string ): string; function setCurrentTurn( AuthToken: string;Const json : String ): string; private function ListToJSON( const value: IList<IGameDataObject> ): string; procedure ValidateUserCount(const GameData: IGameData); public constructor Create( DataModel: IDataModel ); reintroduce; end; implementation uses StrUtils , SysUtils , cwCollections.Standard , DataModel.Standard , System.JSON , REST.JSON ; { TViewModel } procedure TViewModel.CleanUp; begin fDataModel.CleanUp; end; constructor TViewModel.Create(DataModel: IDataModel); begin inherited Create; fDataModel := DataModel; end; procedure TViewModel.ValidateUserCount( const GameData: IGameData ); begin if GameData.MaxUser<GameData.MinUser then begin GameData.MinUser := GameData.MaxUser; end; if GameData.MinUser>GameData.MaxUser then begin GameData.MaxUser := GameData.MinUser; end; if GameData.MinUser<cMinUserCount then begin raise Exception.Create('Minimum users required is '+IntToStr(cMinUserCount)+' or greater.'); end; if GameData.MaxUser>cMaxUserCount then begin raise Exception.Create('The maximum number of users permitted in a game is '+IntToStr(cMaxUserCount)+'.'); end; end; function TViewModel.CreateGame(const json: string): string; var NewGame: IGameData; NewSessionID: TGUID; idx: nativeuint; begin NewGame := TJSON.JsonToObject<TGameData>(json); CreateGUID(NewSessionID); NewGame.SessionID := GUIDToString(NewSessionID); if NewGame.SessionPassword=cGeneratePasswordFlag then begin NewGame.SessionPassword := cNullString; for idx := 0 to pred(cPasswordLen) do begin NewGame.SessionPassword := NewGame.SessionPassword + chr( cStartPasswordChar+Random(cPasswordCharRange) ); end; end; NewGame.GameState := gsGreenRoom; //- Load and validate min/max user ValidateUserCount(NewGame); //- Return game fDataModel.CreateGame(NewGame); Result := NewGame.ToJSON; end; function TViewModel.getCurrentGame(AuthToken: String): IGameData; begin Result := fDataModel.GetGameByUserID(AuthToken); end; function TViewModel.getCurrentTurn(AuthToken: string): string; var Turn: ITurnData; begin Turn := fDataModel.getCurrentTurn( AuthToken ); Result := Turn.ToJSON; end; function TViewModel.getPublicGames: string; var PublicGames: IList<IGameData>; begin PublicGames := fDataModel.getGames; Result := ListToJSON(PublicGames as IList<IGameDataObject>); end; function TViewModel.getUsers(const AuthToken: string): string; var UserList: IList<IUserData>; begin UserList := fDataModel.getUsers( AuthToken ); UserList.ForEach( procedure ( const Item: IUserData ) begin if Item.UserID<>AuthToken then begin Item.UserID := ''; end; end ); Result := ListToJSON(UserList as IList<IGameDataObject>); end; function TViewModel.JoinGame(const json: string): string; var NewUser: IUserData; NewUserID: TGUID; SelectedGame: IGameData; begin NewUser := TJSON.JsonToObject<TUserData>(json); CreateGUID(NewUserID); NewUser.UserID := GuidToString(NewUserID); //- Look up the requested game SelectedGame := fDataModel.FindGameByID(NewUser.GameID); if not assigned(SelectedGame) then begin raise Exception.Create('Requested game not found.'); end; fDataModel.CreateUser( NewUser ); Result := NewUser.ToJSON; end; function TViewModel.ListToJSON(const value: IList<IGameDataObject>): string; var _Result: string; begin Result := '[]'; _Result := ''; if Value.Count=0 then begin exit; end; try _Result := '['; Value.ForEach( procedure( const item: IGameDataObject ) begin _Result := _Result + Item.ToJSON; _Result := _Result + ','; end ); _Result := LeftStr(_Result,pred(Length(_Result))); _Result := _Result + ']'; finally Result := _Result; end; end; function TViewModel.setCurrentTurn(AuthToken: string; const json: String): string; var TurnData : ITurnData; begin TurnData := TTurnData.FromJSON(JSON); Result := fDataModel.setCurrentTurn(AuthToken,TurnData); end; function TViewModel.setGameState(AuthToken: string; const json: string): string; var GameData: IGameData; begin GameData := TJSON.JsonToObject<TGameData>(json); Result := fDataModel.setGameState(AuthToken,GameData); end; procedure TViewModel.UpdateUserPing(const UserID: string); begin fDataModel.UpdateUserPing(UserID); end; end.
{ Created by BGRA Controls Team Dibo, Circular, lainz (007) and contributors. For detailed information see readme.txt Site: https://sourceforge.net/p/bgra-controls/ Wiki: http://wiki.lazarus.freepascal.org/BGRAControls Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit BCGameGrid; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, BCBaseCtrls, BGRABitmap, BGRABitmapTypes, LCLProc, Types; type TOnRenderControl = procedure(Sender: TObject; Bitmap: TBGRABitmap; r: TRect; n, x, y: integer) of object; TOnClickControl = procedure(Sender: TObject; n, x, y: integer) of object; { TBCCustomGrid } TBCCustomGrid = class(TBCGraphicControl) private FBGRA: TBGRABitmap; FGridWidth: integer; FGridHeight: integer; FBlockWidth: integer; FBlockHeight: integer; FOnRenderControl: TOnRenderControl; FOnClickControl: TOnClickControl; private procedure SetFBlockHeight(AValue: integer); procedure SetFBlockWidth(AValue: integer); procedure SetFGridHeight(AValue: integer); procedure SetFGridWidth(AValue: integer); { Private declarations } protected { Protected declarations } procedure Click; override; procedure DrawControl; override; procedure RenderControl; override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure RenderAndDrawControl; property GridWidth: integer read FGridWidth write SetFGridWidth; property GridHeight: integer read FGridHeight write SetFGridHeight; property BlockWidth: integer read FBlockWidth write SetFBlockWidth; property BlockHeight: integer read FBlockHeight write SetFBlockHeight; property OnRenderControl: TOnRenderControl read FOnRenderControl write FOnRenderControl; property OnClickControl: TOnClickControl read FOnClickControl write FOnClickControl; published { Published declarations } end; TBCGameGrid = class(TBCCustomGrid) published property GridWidth; property GridHeight; property BlockWidth; property BlockHeight; // Support 'n, x, y' property OnRenderControl; property OnClickControl; // 'Classic' events, to be changed... property OnMouseDown; property OnMouseMove; property OnMouseUp; // Ok... property OnMouseEnter; property OnMouseLeave; property OnMouseWheel; property OnMouseWheelDown; property OnMouseWheelUp; end; procedure Register; implementation procedure Register; begin {$I icons\bcgamegrid_icon.lrs} RegisterComponents('BGRA Controls', [TBCGameGrid]); end; { TBCCustomGrid } procedure TBCCustomGrid.SetFBlockHeight(AValue: integer); begin if FBlockHeight = AValue then Exit; if AValue < 1 then FBlockHeight := 1 else FBlockHeight := AValue; RenderAndDrawControl; end; procedure TBCCustomGrid.SetFBlockWidth(AValue: integer); begin if FBlockWidth = AValue then Exit; if AValue < 1 then FBlockWidth := 1 else FBlockWidth := AValue; RenderAndDrawControl; end; procedure TBCCustomGrid.SetFGridHeight(AValue: integer); begin if FGridHeight = AValue then Exit; if AValue < 1 then FGridHeight := 1 else FGridHeight := AValue; RenderAndDrawControl; end; procedure TBCCustomGrid.SetFGridWidth(AValue: integer); begin if FGridWidth = AValue then Exit; if AValue < 1 then FGridWidth := 1 else FGridWidth := AValue; RenderAndDrawControl; end; procedure TBCCustomGrid.Click; var n, x, y: integer; r: TRect; var pos: TPoint; begin if (BlockWidth <= 0) or (BlockHeight <= 0) or (GridWidth <= 0) or (GridHeight <= 0) then Exit; pos := ScreenToClient(Mouse.CursorPos); n := 0; for y := 0 to GridHeight - 1 do begin for x := 0 to GridWidth - 1 do begin r.Left := BlockWidth * x; r.Top := BlockHeight * y; r.Right := r.Left + BlockWidth; r.Bottom := r.Top + BlockHeight; if (pos.x >= r.Left) and (pos.x <= r.Right) and (pos.y >= r.Top) and (pos.y <= r.Bottom) then begin //DebugLn(['TControl.Click ',DbgSName(Self)]); if Assigned(FOnClickControl) and (Action <> nil) and (not CompareMethods(TMethod(Action.OnExecute), TMethod(FOnClickControl))) then // the OnClick is set and differs from the Action => call the OnClick FOnClickControl(Self, n, x, y) else if (not (csDesigning in ComponentState)) and (ActionLink <> nil) then ActionLink.Execute(Self) else if Assigned(FOnClickControl) then FOnClickControl(Self, n, x, y); end; Inc(n); end; end; end; procedure TBCCustomGrid.DrawControl; begin if FBGRA <> nil then FBGRA.Draw(Canvas, 0, 0, False); end; procedure TBCCustomGrid.RenderControl; var n, x, y: integer; r: TRect; begin if (BlockWidth <= 0) or (BlockHeight <= 0) or (GridWidth <= 0) or (GridHeight <= 0) then Exit; if FBGRA <> nil then FreeAndNil(FBGRA); FBGRA := TBGRABitmap.Create(Width, Height); n := 0; for y := 0 to GridHeight - 1 do begin for x := 0 to GridWidth - 1 do begin r.Left := BlockWidth * x; r.Top := BlockHeight * y; r.Right := r.Left + BlockWidth; r.Bottom := r.Top + BlockHeight; FBGRA.Rectangle(r, BGRA(127, 127, 127, 127), BGRA(255, 255, 255, 127), dmDrawWithTransparency); if Assigned(FOnRenderControl) then FOnRenderControl(Self, FBGRA, r, n, x, y); Inc(n); end; end; end; procedure TBCCustomGrid.RenderAndDrawControl; begin RenderControl; Invalidate; end; constructor TBCCustomGrid.Create(AOwner: TComponent); begin inherited Create(AOwner); with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); BlockHeight := 30; BlockWidth := 30; GridHeight := 5; GridWidth := 5; end; destructor TBCCustomGrid.Destroy; begin if FBGRA <> nil then FreeAndNil(FBGRA); inherited Destroy; end; end.
{$include kode.inc} unit fx_jungle; {$define BUFFER_SIZE := (1024*1024)} //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- uses kode_plugin, kode_types; type myPlugin = class(KPlugin) private FBuffer : array[0..BUFFER_SIZE*2] of Single; FRecPos : LongWord; FPlayPos : LongWord; FBeatSize : LongWord; FLoopStart : LongWord; FLoopSize : LongWord; FLooping : Boolean; FButton,FButtonPrev : Boolean; FButton1,FButton2,FButton3,FButton4 : Boolean; FSpeed : Single; public procedure on_create; override; procedure on_parameterChange(AIndex:LongWord; AValue:Single); override; procedure on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord); override; procedure on_processSample(AInputs,AOutputs:PPSingle); override; end; KPluginClass = myPlugin; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses _plugin_id, kode_const, kode_debug, kode_flags, kode_parameter, kode_utils; //---------- procedure myPlugin.on_create; begin FName := 'fx_jungle'; FAuthor := 'skei.audio'; FProduct := FName; FVersion := 0; FUniqueId := KODE_MAGIC + fx_jungle_id; FNumInputs := 2; FNumOutputs := 2; KSetFlag(FFlags, kpf_perSample + kpf_autoUpdateSync ); appendParameter( KParamInt.create( '1/2', 0,0,1) ); appendParameter( KParamInt.create( '1/4', 0,0,1) ); appendParameter( KParamInt.create( '1/8', 0,0,1) ); appendParameter( KParamInt.create( '1/16', 0,0,1) ); FRecPos := 0; FPlayPos := 0; FBeatSize := 0; FLooping := false; FLoopStart := 0; FLoopSize := 0; FButton := false; FButtonPrev := false; FButton1 := false; FButton2 := false; FButton3 := false; FButton4 := false; FSpeed := 1; end; //---------- procedure myPlugin.on_parameterChange(AIndex:LongWord; AValue:Single); //var // v : single; begin case AIndex of 0: FButton1 := (AValue>=0.5); 1: FButton2 := (AValue>=0.5); 2: FButton3 := (AValue>=0.5); 3: FButton4 := (AValue>=0.5); end; FButton := false; if (FButton1 or FButton2 or FButton3 or FButton4) then FButton := true; //KTrace(['FButton: ',FButton,KODE_CR]); end; //---------- procedure myPlugin.on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord); begin FBeatSize := trunc( (FSampleRate * 60) / FTempo ); if FButton then begin if FButton1 then FLoopSize := FBeatSize div 2; if FButton2 then FLoopSize := FBeatSize div 4; if FButton3 then FLoopSize := FBeatSize div 8; if FButton4 then FLoopSize := FBeatSize div 16; if not FButtonPrev then begin FLooping := true; FLoopStart := FRecPos;// - FLoopSize; FPlayPos := 0; FButtonPrev := true; end; end else begin FLooping := false; FButtonPrev := false; end; end; //---------- procedure myPlugin.on_processSample(AInputs,AOutputs:PPSingle); var spl0,spl1 : single; r,p : longword; begin spl0 := AInputs[0]^; spl1 := AInputs[1]^; r := FRecPos * 2; FBuffer[r] := spl0; FBuffer[r+1] := spl1; FRecPos := (FRecPos+1) mod BUFFER_SIZE; if FLooping then begin p := ( FLoopStart + FPlayPos ) mod BUFFER_SIZE; p *= 2; spl0 := FBuffer[p]; spl1 := FBuffer[p+1]; FPlayPos := (FPlayPos+1) mod FLoopSize; end; AOutputs[0]^ := spl0; AOutputs[1]^ := spl1; end; //---------------------------------------------------------------------- end.
unit uLeapTests; interface uses DUnitX.TestFramework; type [TestFixture] YearTest = class(TObject) public [Test] // [Ignore('Comment the "[Ignore]" statement to run the test')] procedure test_leap_year; [Test] [Ignore] procedure test_standard_and_odd_year; [Test] [Ignore] procedure test_standard_even_year; [Test] [Ignore] procedure test_standard_nineteenth_century; [Test] [Ignore] procedure test_standard_eighteenth_century; [Test] [Ignore] procedure test_leap_twenty_fourth_century; [Test] [Ignore] procedure test_leap_y2k; end; implementation uses uLeap; procedure YearTest.test_leap_year; begin assert.IsTrue(TYear.IsLeap(1996), 'Expected ''true'', 1996 is a leap year.'); end; procedure YearTest.test_standard_and_odd_year; begin assert.IsFalse(TYear.IsLeap(1997), 'Expected ''false'', 1997 is not a leap year.'); end; procedure YearTest.test_standard_even_year; begin assert.IsFalse(TYear.IsLeap(1998), 'Expected ''false'', 1998 is not a leap year.'); end; procedure YearTest.test_standard_nineteenth_century; begin assert.IsFalse(TYear.IsLeap(1900), 'Expected ''false'', 1900 is not a leap year.'); end; procedure YearTest.test_standard_eighteenth_century; begin assert.IsFalse(TYear.IsLeap(1800), 'Expected ''false'', 1800 is not a leap year.'); end; procedure YearTest.test_leap_twenty_fourth_century; begin assert.IsTrue(TYear.IsLeap(2400), 'Expected ''true'', 2400 is a leap year.'); end; procedure YearTest.test_leap_y2k; begin assert.IsTrue(TYear.IsLeap(2000), 'Expected ''true'', 2000 is a leap year.'); end; initialization TDUnitX.RegisterTestFixture(YearTest); end.
unit model.person; interface uses Classes, DB, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, dbcbr.mapping.register, ormbr.types.nullable, ormbr.types.blob; type TPersonSub = class private { Private declarations } FId: Integer; FFirstName: string; FLastName: string; FAge: Integer; FSalary: Double; public { Public declarations } property Id: Integer Index 0 read FId write FId; property FirstName: string Index 1 read FFirstName write FFirstName; property LastName: String Index 2 read FLastName write FLastName; property Age: Integer Index 3 read FAge write FAge; property Salary: Double Index 4 read FSalary write FSalary; end; [Entity] [Table('Person','Tabela de pessoas')] [PrimaryKey('Id', NotInc, NoSort, False, 'Chave primária')] [Indexe('IDX_FirstName','FirstName', NoSort, True, 'Indexe por nome')] [Check('CHK_Age', 'Age >= 0')] TPerson = class private { Private declarations } FId: Integer; FFirstName: string; FLastName: string; FAge: Integer; FSalary: Double; FDate: TDateTime; FPessoa: TPersonSub; FPessoas: TObjectList<TPersonSub>; FBlob: String; public { Public declarations } constructor Create; destructor Destroy; override; [Restrictions([NoUpdate, NotNull])] [Column('Id', ftInteger)] [Dictionary('Código ID','Mensagem de validação','0','','',taCenter)] property Id: Integer read FId write FId; [Restrictions([NotNull])] [Column('FirstName', ftString, 40)] [Dictionary('Primeiro nome','Mensagem de validação','','','',taLeftJustify)] property FirstName: string Index 1 read FFirstName write FFirstName; [Column('LastName', ftString, 30)] [Dictionary('Último nome','Mensagem de validação','','','',taLeftJustify)] property LastName: String read FLastName write FLastName; [Restrictions([NotNull])] [Column('Age', ftInteger)] [Dictionary('Idade','Mensagem de validação','0','','',taCenter)] property Age: Integer read FAge write FAge; [Restrictions([NotNull])] [Column('Salary', ftCurrency, 18, 3)] [Dictionary('Preço','Mensagem de validação','0','','',taRightJustify)] property Salary: Double read FSalary write FSalary; [Restrictions([NotNull])] [Column('Date', ftDateTime)] [Dictionary('Nivel','Data de aniversário','Date','','',taRightJustify)] property Date: TDateTime read FDate write FDate; [Column('Imagem', ftBlob)] property Imagem: string read FBlob write FBlob; property Pessoa: TPersonSub read FPessoa write FPessoa; property Pessoas: TObjectList<TPersonSub> read FPessoas write FPessoas; end; implementation { TPerson } constructor TPerson.Create; begin FPessoa := TPersonSub.Create; FPessoas := TObjectList<TPersonSub>.Create(True); end; destructor TPerson.Destroy; begin FPessoa.Free; FPessoas.Free; inherited; end; initialization TRegisterClass.RegisterEntity(TPerson); end.
unit Visao.FormFiltros; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask, Vcl.ExtCtrls, Bd.DmConfig; type TFrmFiltrosRelatorio = class(TForm) rltitulo: TLabel; pfiltros: TPanel; Label1: TLabel; edtDataInicial: TMaskEdit; Label2: TLabel; edtDataFinal: TMaskEdit; btnProcessar: TButton; btnFechar: TButton; procedure btnFecharClick(Sender: TObject); procedure btnProcessarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); function Valida: Boolean; procedure edtDataFinalKeyPress(Sender: TObject; var Key: Char); procedure edtDataInicialKeyPress(Sender: TObject; var Key: Char); private PSQL: String; public { Public declarations } end; var FrmFiltrosRelatorio: TFrmFiltrosRelatorio; implementation uses Visao.RelatorioVendas; {$R *.dfm} procedure TFrmFiltrosRelatorio.btnFecharClick(Sender: TObject); begin Close; end; procedure TFrmFiltrosRelatorio.btnProcessarClick(Sender: TObject); var RelResumoVendas: TRelResumoVendas; vDataInicial, vDataFinal: TDateTime; begin if Valida then begin vDataInicial := StrToDateTimeDef(edtDataInicial.Text, 0); vDataFinal := StrToDateTimeDef(edtDataFinal.Text, 0); if SameText(edtDataInicial.Text, ' / / ') then PSQL := 'Select * From Venda' else begin PSQL := 'Select * From Venda Where Data_Venda between ' + QuotedStr(FormatDateTime('yyyy/mm/dd', vDataInicial)) + ' and ' + QuotedStr(FormatDateTime('yyyy/mm/dd', vDataFinal)); end; RelResumoVendas := TRelResumoVendas.Create(nil); try RelResumoVendas.SQL := PSQL; RelResumoVendas.Visualiza; finally RelResumoVendas.Free; end; end; end; procedure TFrmFiltrosRelatorio.edtDataFinalKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then btnProcessar.SetFocus; end; procedure TFrmFiltrosRelatorio.edtDataInicialKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtDataFinal.SetFocus; end; procedure TFrmFiltrosRelatorio.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; function TFrmFiltrosRelatorio.Valida: Boolean; var vDataInicial, vDataFinal: TDateTime; begin Result := True; vDataInicial := StrToDateTimeDef(edtDataInicial.Text, 0); vDataFinal := StrToDateTimeDef(edtDataFinal.Text, 0); if vDataInicial > vDataFinal then begin MessageBox(Handle, 'Data final maior que a inicial!', 'Erro', MB_OK); Result := False; Exit; end; end; end.
unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, CheckLst, ExtCtrls, StdCtrls, ActnList, Menus; type { TForm2 } TForm2 = class(TForm) Button1: TButton; CheckListBox1: TCheckListBox; Edit1: TEdit; MainMenu1: TMainMenu; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; OpenDialog1: TOpenDialog; Panel1: TPanel; SaveDialog1: TSaveDialog; procedure Button1Click(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: char); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure MenuItem2Click(Sender: TObject); procedure MenuItem3Click(Sender: TObject); procedure MenuItem5Click(Sender: TObject); procedure SaveList(var filename: string); procedure LoadList(var filename: string); private public end; var Form2: TForm2; indexFilename: string; implementation {$R *.lfm} { TForm2 } procedure TForm2.SaveList(var filename: string); var list: TStringList; i: Integer; line: string; begin list := TStringList.Create; for i := 0 to CheckListBox1.Items.Count-1 do begin line := ''; if CheckListBox1.Checked[i] then line += '+' else line += '-'; line += CheckListBox1.Items[i]; list.Add(line); end; list.SaveToFile(filename); list.Free; end; procedure TForm2.LoadList(var filename: string); var list: TStringList; i: Integer; begin list := TStringList.Create; list.LoadFromFile(filename); CheckListBox1.Clear; for i := 0 to list.Count-1 do begin CheckListBox1.Items.Add(RightStr(list[i], Length(list[i])-1)); CheckListBox1.Checked[i] := LeftStr(list[i], 1) = '+'; end; list.Free; end; procedure TForm2.MenuItem2Click(Sender: TObject); var fname: string; begin if SaveDialog1.Execute then begin fname := SaveDialog1.FileName; SaveList(fname); end end; procedure TForm2.Edit1KeyPress(Sender: TObject; var Key: char); var fname: string; begin if key = #13 then begin CheckListBox1.Items.Add(Edit1.Text); Edit1.Text:=''; SaveList(indexFilename); end; end; procedure TForm2.FormClose(Sender: TObject; var CloseAction: TCloseAction); var fname: string; begin SaveList(indexFilename); end; procedure TForm2.FormCreate(Sender: TObject); begin indexFilename := GetUserDir() + '/.coder-toolbox/todo.txt'; end; procedure TForm2.FormShow(Sender: TObject); var fname: string; begin if FileExists(indexFilename) then begin LoadList(indexFilename); end; end; procedure TForm2.Button1Click(Sender: TObject); var fname: string; begin CheckListBox1.Items.Add(Edit1.Text); Edit1.Text:= ''; SaveList(indexFilename); end; procedure TForm2.MenuItem3Click(Sender: TObject); var fname: string; begin if OpenDialog1.Execute then begin fname := OpenDialog1.FileName; LoadList(fname); end; end; procedure TForm2.MenuItem5Click(Sender: TObject); var i: Integer; begin for i:= CheckListBox1.Items.Count-1 downto 0 do begin if CheckListBox1.Checked[i] then CheckListBox1.items.Delete(i); end; end; end.
{ Subroutine STRING_F_INT8H (S, I) * * Convert 8 bit integer I to a 2 character HEX string in S. Only * the low 8 bits of I are used. } module string_f_int8h; define string_f_int8h; %include 'string2.ins.pas'; procedure string_f_int8h ( {make HEX string from 8 bit integer} in out s: univ string_var_arg_t; {output string} in i: sys_int_max_t); {input integer, uses low 8 bits} val_param; var stat: sys_err_t; {error code} begin string_f_int_max_base ( {make string from integer} s, {output string} i & 16#FF, {input integer} 16, {number base} 2, {output field width} [string_fi_leadz_k, {write leading zeros} string_fi_unsig_k], {input number is unsigned} stat); sys_error_abort (stat, 'string', 'internal', nil, 0); end;
unit TextEditor.RightMargin.Colors; interface uses System.Classes, System.UITypes; type TTextEditorRightMarginColors = class(TPersistent) strict private FMargin: TColor; FMovingEdge: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Margin: TColor read FMargin write FMargin default TColors.Silver; property MovingEdge: TColor read FMovingEdge write FMovingEdge default TColors.Silver; end; implementation constructor TTextEditorRightMarginColors.Create; begin inherited; FMargin := TColors.Silver; FMovingEdge := TColors.Silver; end; procedure TTextEditorRightMarginColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorRightMarginColors) then with ASource as TTextEditorRightMarginColors do begin Self.FMargin := FMargin; Self.FMovingEdge := FMovingEdge; end else inherited Assign(ASource); end; end.
unit Employee; interface uses BaseObjects, Registrator, Classes; type // должности TPost = class (TIDObject) protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(ACollection: TIDObjects); override; end; TPosts = class (TIDObjects) private function GetItems(Index: Integer): TPost; public procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override; property Items[Index: Integer]: TPost read GetItems; procedure Reload; override; constructor Create; override; end; // сотрудники TEmployee = class (TRegisteredIDObject) private FPost: TPost; protected procedure AssignTo(Dest: TPersistent); override; public property Post: TPost read FPost write FPost; constructor Create(ACollection: TIDObjects); override; end; TEmployees = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TEmployee; public procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override; property Items[Index: Integer]: TEmployee read GetItems; function ObjectsToStr (AAuthors: string): string; override; constructor Create; override; end; // свои сотрудники TEmployeeOur = class (TEmployee) protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(ACollection: TIDObjects); override; end; TEmployeeOurs= class (TEmployees) public procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override; constructor Create; override; end; // внешние сотрудники TEmployeeOutside = class (TEmployee) protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(ACollection: TIDObjects); override; end; TEmployeeOutsides= class (TEmployees) public procedure Assign (Sourse: TIDObjects; NeedClearing: boolean = true); override; constructor Create; override; end; implementation uses Facade, EmployeePoster; { TEmployee } procedure TEmployee.AssignTo(Dest: TPersistent); begin inherited; end; constructor TEmployee.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Сотрудник ТП НИЦ'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TEmployeeDataPoster]; end; { TEmployees } procedure TEmployees.Assign(Sourse: TIDObjects; NeedClearing: boolean = true); begin inherited; end; constructor TEmployees.Create; begin inherited; FObjectClass := TEmployee; Poster := TMainFacade.GetInstance.DataPosterByClassType[TEmployeeDataPoster]; end; function TEmployees.GetItems(Index: Integer): TEmployee; begin Result := inherited Items[Index] as TEmployee; end; function TEmployees.ObjectsToStr(AAuthors: string): string; begin inherited ObjectsToStr(AAuthors); end; { TEmployeeOur } procedure TEmployeeOur.AssignTo(Dest: TPersistent); begin inherited; end; constructor TEmployeeOur.Create(ACollection: TIDObjects); begin inherited; end; { TEmployeeOurs } procedure TEmployeeOurs.Assign(Sourse: TIDObjects; NeedClearing: boolean = true); begin inherited; end; constructor TEmployeeOurs.Create; begin inherited; end; { TEmployeeOutside } procedure TEmployeeOutside.AssignTo(Dest: TPersistent); begin inherited; end; constructor TEmployeeOutside.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Сторонний сотрудник'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TEmployeeOutsideDataPoster]; end; { TEmployeeOutsides } procedure TEmployeeOutsides.Assign(Sourse: TIDObjects; NeedClearing: boolean = true); begin inherited; end; constructor TEmployeeOutsides.Create; begin inherited; FObjectClass := TEmployeeOutside; Poster := TMainFacade.GetInstance.DataPosterByClassType[TEmployeeOutsideDataPoster]; end; { TPost } procedure TPost.AssignTo(Dest: TPersistent); begin inherited; end; constructor TPost.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Должность'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TPostDataPoster]; end; { TPosts } procedure TPosts.Assign(Sourse: TIDObjects; NeedClearing: boolean = true); begin inherited; end; constructor TPosts.Create; begin inherited; FObjectClass := TPost; Poster := TMainFacade.GetInstance.DataPosterByClassType[TPostDataPoster]; end; function TPosts.GetItems(Index: Integer): TPost; begin Result := inherited Items[Index] as TPost; end; procedure TPosts.Reload; begin if Assigned (FDataPoster) then begin FDataPoster.GetFromDB('', Self); FDataPoster.SaveState(PosterState); end; end; end.
Program PosFIAva; Uses Crt; Const Max=50; Type Elem=Real; Pilha= Record Topo:integer; memo:Array[1..Max] of Elem; End; Valores=array['A'..'Z'] of elem; Var P:Pilha; E:String; V:Valores; Procedure Init; Begin p.Topo:=0; End; Function IsEmpty(Var P:Pilha):Boolean; Begin If p.Topo=0 Then IsEmpty:=True Else IsEmpty:=False; End; Function IsFull(Var P:Pilha):Boolean; Begin If p.topo=Max Then IsFull:=True Else IsFull:=False; End; Procedure Push(Var P:Pilha; x:Elem); Begin If not IsFull(p) Then Begin p.Topo:=p.Topo+1; p.Memo[p.Topo]:=x; End Else Writeln ('Stack Overflow!!'); End; Function Pop(Var P:Pilha): Elem; Begin If not IsEmpty(p) Then Begin Pop:=p.Memo[p.Topo]; p.Topo:= p.Topo-1; End Else Writeln ('Stack Underflow!!'); End; Function Top(Var P:Pilha): Elem; Begin If not IsEmpty(p) Then Top:=p.Memo[p.Topo] Else Writeln ('Stack Underflow!!'); End; Procedure Atribui(Var V:Valores); Var N:Char; Begin Writeln ('Digite . para finalizar...'); Repeat Write ('Nome: '); Readln(n); If N in ['A'..'Z'] Then Begin Write('Valor: '); Readln (V[N]); End; Until (N='.'); End; Function Avalia(E:String;V:Valores):real; Var P:Pilha; x,y:real; i:Integer; Begin Init; For i:=1 to length(E) do If E[i] in ['A'..'Z'] Then Push (P,V[E[i]]) Else If E[i] in ['+','-','*','/'] Then Begin Y:= Pop(p); X:= Pop(p); Case E[i] of '+':Push(P,X+Y); '-':Push(P,X-Y); '*':Push(P,X*Y); '/':Push(P,X/Y); End; End; Avalia:=Pop(p); End; Begin {*Programa Principal*} While True do Begin Clrscr; Writeln ('1. Define expressao'); Writeln ('2. Define Variaveis'); Writeln ('3. Avalia Expressao'); Writeln ('4. Finaliza'); Writeln; Write ('Opcao: '); Case readkey of '1': Begin Writeln; Write('Npr: '); Readln(E); End; '2': Atribui(V); '3': Begin Writeln; Writeln ('Res: ', Avalia(E,V):0:2); Readln; End; '4': Halt; End; End; End.