text stringlengths 14 6.51M |
|---|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clMCUtils;
interface
{$I clVer.inc}
const
cDefaultPop3Port = 110;
cDefaultSmtpPort = 25;
function GenerateMessageID: string;
function GenerateCramMD5Key: string;
implementation
uses
Windows, SysUtils, clSocket;
var
MessageCounter: Integer = 0;
function GenerateMessageID: string;
var
y, mm, d, h, m, s, ms: Word;
begin
DecodeTime(Now(), h, m, s, ms);
DecodeDate(Date(), y, mm, d);
Result := IntToHex(mm, 2) + IntToHex(d, 2) + IntToHex(h, 2)
+ IntToHex(m, 2) + IntToHex(s, 2) + IntToHex(ms, 2);
InterlockedIncrement(MessageCounter);
Result := '<' + IntToHex(GetTickCount(), 8) + '$'
+ system.Copy(Result, 1, 12) + '$'
+ IntToHex(MessageCounter, 3) + IntToHex(MessageCounter * 2, 3) + '@'
+ GetLocalHost() + '>';
end;
function GenerateCramMD5Key: string;
var
y, mm, d, h, m, s, ms: Word;
begin
DecodeTime(Now(), h, m, s, ms);
DecodeDate(Date(), y, mm, d);
Result := Format('<INETSUITE-F%d%d%d%d%d.%s@%s>',
[y, mm, d, h, m, IntToHex(m, 3) + IntToHex(s, 3) + IntToHex(ms, 3) + IntToHex(Random(100), 5),
GetLocalHost()]);
end;
end.
|
unit FDACDataSetProvider;
interface
uses
System.SysUtils, System.Classes
// REST Client Library
, REST.Client
, IPPeerClient
// FireDAC
, FireDAC.Stan.Intf
, FireDAC.Stan.Option
, FireDAC.Stan.Param
, FireDAC.Stan.Error
, FireDAC.DatS
, FireDAC.Phys.Intf
, FireDAC.DApt.Intf
, FireDAC.Stan.Async
, FireDAC.DApt
, FireDAC.Comp.DataSet
, FireDAC.Stan.StorageBin
, FireDAC.UI.Intf
, FireDAC.Comp.UI
, FireDAC.Comp.Client
, Data.FireDACJSONReflect
// , FireDAC.FMXUI.Wait
// , FireDAC.VCLUI.Wait
;
type
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32 or pidiOSSimulator or pidiOSDevice or pidAndroid)]
TFDDataSetProvider = class(TComponent)
private
FClient: TRESTClient;
FRequest: TRESTRequest;
FDataSets: TFDJSONDataSets;
FTargetDataSet: TFDCustomMemTable;
FDataSetsInfo: TStrings;
FDataSetsNames: TStrings;
procedure SetTargetDataSet(const Value: TFDCustomMemTable);
function GetDataSetsCount: Integer;
protected
procedure DoRetrieveData; virtual;
procedure DoUpdateTargetDataSet(const ADataSetNameOrIndex: string); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ClearDataSetsInfo; virtual;
procedure PopulateDataSetsInfo; virtual;
procedure TargetDataSetChanged; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RetrieveData;
procedure UpdateTargetDataSet(const ADataSetName: string); overload;
procedure UpdateTargetDataSet(const ADataSetIndex: Integer); overload;
property DataSets: TFDJSONDataSets read FDataSets;
property DataSetsCount: Integer read GetDataSetsCount;
published
property RESTClient: TRESTClient read FClient write FClient;
property RESTRequest: TRESTRequest read FRequest write FRequest;
property DataSetsInfo: TStrings read FDataSetsInfo;
property DataSetsNames: TStrings read FDataSetsNames;
property TargetDataSet: TFDCustomMemTable read FTargetDataSet write SetTargetDataSet;
end;
procedure Register;
implementation
uses
Data.DBXJSONReflect,
System.JSON;
procedure Register;
begin
RegisterComponents('Andrea Magni', [TFDDataSetProvider]);
end;
{ TFDDataSetProvider }
procedure TFDDataSetProvider.ClearDataSetsInfo;
begin
FDataSetsInfo.Clear;
FDataSetsNames.Clear;
end;
constructor TFDDataSetProvider.Create(AOwner: TComponent);
begin
inherited;
FClient := TRESTClient.Create(Self);
FClient.Name := 'RESTClient';
FClient.SetSubComponent(True);
FRequest := TRESTRequest.Create(Self);
FRequest.Name := 'RESTRequest';
FRequest.SetSubComponent(True);
FRequest.Client := FClient;
FDataSetsInfo := TStringList.Create;
FDataSetsNames := TStringList.Create;
end;
destructor TFDDataSetProvider.Destroy;
begin
FDataSetsNames.Free;
FDataSetsInfo.Free;
FRequest.Free;
FClient.Free;
inherited;
end;
procedure TFDDataSetProvider.DoRetrieveData;
var
LUnmarshaller: TJSONUnMarshal;
LJSONObj: TJSONObject;
begin
FRequest.Execute;
if Assigned(FDataSets) then
FreeAndNil(FDataSets);
ClearDataSetsInfo;
LJSONObj := FRequest.Response.JSONValue.GetValue<TJSONArray>('result').Items[0] as TJSONObject;
LUnmarshaller := TJSONUnMarshal.Create;
try
FDataSets := LUnmarshaller.Unmarshal(LJSONObj) as TFDJSONDataSets;
PopulateDataSetsInfo;
finally
LUnmarshaller.Free;
end;
end;
procedure TFDDataSetProvider.DoUpdateTargetDataSet(const ADataSetNameOrIndex: string);
var
LDataSet: TFDAdaptedDataSet;
LDataSetIndex: Integer;
begin
Assert(Assigned(FTargetDataSet));
Assert(Assigned(FDataSets));
LDataSetIndex := StrToIntDef(ADataSetNameOrIndex, -1);
if LDataSetIndex <> -1 then
LDataSet := TFDJSONDataSetsReader.GetListValue(FDataSets, LDataSetIndex)
else
LDataSet := TFDJSONDataSetsReader.GetListValueByName(FDataSets, ADataSetNameOrIndex);
if not Assigned(LDataSet) then
raise Exception.CreateFmt('Unable to find dataset "%s"', [ADataSetNameOrIndex]);
TargetDataSet.Data := LDataSet;
end;
function TFDDataSetProvider.GetDataSetsCount: Integer;
begin
Result := 0;
if Assigned(FDataSets) then
Result := TFDJSONDataSetsReader.GetListCount(FDataSets);
end;
procedure TFDDataSetProvider.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if (AComponent = FTargetDataSet) then
FTargetDataSet := nil;
end;
end;
procedure TFDDataSetProvider.PopulateDataSetsInfo;
var
LIndex: Integer;
LDataSet: TFDAdaptedDataSet;
LDataSetName: string;
begin
if not Assigned(FDataSets) then
begin
ClearDataSetsInfo;
Exit;
end;
for LIndex := 0 to DataSetsCount-1 do
begin
LDataSet := TFDJSONDataSetsReader.GetListValue(FDataSets, LIndex);
LDataSetName := TFDJSONDataSetsReader.GetListKey(FDataSets, LIndex);
FDataSetsNames.Add(LDataSetName);
FDataSetsInfo.Add(
Format('%d:%s (%d records)', [LIndex, LDataSetName, LDataSet.RecordCount])
);
end;
end;
procedure TFDDataSetProvider.RetrieveData;
begin
DoRetrieveData;
end;
procedure TFDDataSetProvider.SetTargetDataSet(const Value: TFDCustomMemTable);
begin
if FTargetDataSet <> Value then
begin
FTargetDataSet := Value;
TargetDataSetChanged;
end;
end;
procedure TFDDataSetProvider.TargetDataSetChanged;
begin
// if Assigned(FTargetDataSet) and Assigned(FDataSets) then
// UpdateTargetDataSet;
end;
procedure TFDDataSetProvider.UpdateTargetDataSet(const ADataSetName: string);
begin
DoUpdateTargetDataSet(ADataSetName);
end;
procedure TFDDataSetProvider.UpdateTargetDataSet(const ADataSetIndex: Integer);
begin
DoUpdateTargetDataSet(ADataSetIndex.ToString);
end;
end.
|
unit UpdResLegendForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls,
InflatablesList_Manager;
type
TfUpdResLegendForm = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
fILManager: TILManager;
protected
procedure BuildForm;
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowLegend;
end;
var
fUpdResLegendForm: TfUpdResLegendForm;
implementation
{$R *.dfm}
uses
InflatablesList_Types;
procedure TfUpdResLegendForm.BuildForm;
const
BOX_WIDTH = 33;
BOX_HEIGH = 33;
TEXT_VSPACE = 15;
RES_NAMES: array[TILItemShopUpdateResult] of String = (
'Success','Mild success','Data fail','Soft fail','Hard fail',
'Download fail','Parsing fail','Fatal error');
RES_TEXTS: array[TILItemShopUpdateResult] of String = (
'Update was completed succesfully',
'Successful update on untracked link',
'No download link or no parsing data',
'Failed to find or extract available count',
'Failed to find or extract price',
'Download was not successfull',
'Failed parsing of downloaded page',
'Unknown exception or other fatal error occured');
var
CurrentRes: TILItemShopUpdateResult;
VOrigin: Integer;
TempShape: TShape;
TempLabel: TLabel;
MaxWidth: Integer;
begin
VOrigin := 8;
MaxWidth := 0;
For CurrentRes := Low(TILItemShopUpdateResult) to High(TILItemShopUpdateResult) do
begin
// box
TempShape := TShape.Create(Self);
TempShape.Parent := Self;
TempShape.Width := BOX_WIDTH;
TempShape.Height := BOX_HEIGH;
TempShape.Pen.Style := psClear;
TempShape.Brush.Color := IL_ItemShopUpdateResultToColor(CurrentRes);
TempShape.Left := 8;
TempShape.Top := VOrigin;
// name label
TempLabel := TLabel.Create(Self);
TempLabel.Parent := Self;
TempLabel.Left := BOX_WIDTH + 15;
TempLabel.Top := VOrigin + 2;
TempLabel.Font.Style := [fsBold];
TempLabel.Caption := RES_NAMES[CurrentRes];
If TempLabel.Width > MaxWidth then
MaxWidth := TempLabel.Width;
// text label
TempLabel := TLabel.Create(Self);
TempLabel.Parent := Self;
TempLabel.Left := BOX_WIDTH + 16;
TempLabel.Top := VOrigin + TEXT_VSPACE;
TempLabel.Caption := RES_TEXTS[CurrentRes];
If TempLabel.Width > MaxWidth then
MaxWidth := TempLabel.Width;
// move origin
Inc(VOrigin,BOX_HEIGH + 8);
end;
Self.ClientHeight := VOrigin;
Self.ClientWidth := MaxWidth + BOX_WIDTH + 24;
end;
//==============================================================================
procedure TfUpdResLegendForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
end;
//------------------------------------------------------------------------------
procedure TfUpdResLegendForm.Finalize;
begin
// nothing to do here
end;
//------------------------------------------------------------------------------
procedure TfUpdResLegendForm.ShowLegend;
begin
ShowModal;
end;
//==============================================================================
procedure TfUpdResLegendForm.FormCreate(Sender: TObject);
begin
BuildForm;
end;
end.
|
unit AdjustReasonCls;
interface
uses SysUtils;
type
TAdjustReason = class
private
Fid: Integer;
Freason: String;
Fhidden: Integer;
Fsystem: Integer;
Factivated: Integer;
protected
procedure SetReason(argValue: String);
function GetReason(): String;
procedure SetHidden(argValue: Integer);
function GetHidden(): Integer;
procedure SetSystem(argValue: Integer);
function GetSystem(): Integer;
procedure SetActivated(argValue: Integer);
function GetActivated(): Integer;
public
property Id: Integer read Fid write Fid;
property Reason: String read GetReason write SetReason;
property Hidden: Integer read GetHidden write SetHidden;
property System: Integer read GetSystem write SetSystem;
property Activated: Integer read GetActivated write SetActivated;
end;
implementation
{ TAdjustReason }
function TAdjustReason.GetActivated: Integer;
begin
result := self.Factivated;
end;
function TAdjustReason.GetHidden: Integer;
begin
result := self.Fhidden;
end;
function TAdjustReason.GetReason(): String;
begin
result := self.FReason;
end;
function TAdjustReason.GetSystem: Integer;
begin
result := self.Fsystem;
end;
procedure TAdjustReason.SetActivated(argValue: Integer);
begin
self.Factivated := argValue;
if ( argValue = -1 ) then begin
self.Factivated := 1;
end;
end;
procedure TAdjustReason.SetHidden(argValue: Integer);
begin
self.Fhidden := argValue;
if ( argValue = -1 ) then begin
self.Fhidden := 1;
end;
end;
procedure TAdjustReason.SetReason(argValue: String);
begin
if ( length(argValue) = 0 ) then begin
raise Exception.Create('Reason cannot be empty');
end else begin
self.Freason := argValue;
end;
end;
procedure TAdjustReason.SetSystem(argValue: Integer);
begin
self.Fsystem := argValue;
if ( argValue = -1 ) then begin
self.Fsystem := 1;
end;
end;
end.
|
(*
-----------------------------------------------------------------------------------------------------
Version : (292 - 293)
Date : 06.06.2011
Author : Antonio Marcos Fernandes de Souza (amfsouza)
Issue : avoid decrease when parameter ( new parameter ) is set to true.
Solution: set up correct mask to display format properfield object.
Version : (293 - 294)
-----------------------------------------------------------------------------------------------------
Version :
Date : 11.26.2010
Author : Antonio Marcos Fernandes de Souza (amfsouza)
Issue :
Solution: Margin table by level
Version :
-----------------------------------------------------------------------------------------------------
*)
unit uDMCalcPrice;
interface
uses
SysUtils, Classes, ADODB, DBClient, Provider, DB;
type
TModelGroupingType = (mgtNone, mgtCategory, mgtGroup, mgtSubGroup);
TCalcPriceType = (cptSalePrice, cptMSRPPrice, cptBoth);
TDMCalcPrice = class(TDataModule)
quRoundRangeByCategory: TADODataSet;
quRoundRangeByCategoryRoundValues: TStringField;
quRoundRangeByCategoryRoundType: TIntegerField;
quMSRPPriceByCategory: TADODataSet;
quSalePriceByCategory: TADODataSet;
quMSRPPriceByGroup: TADODataSet;
quSalePriceByGroup: TADODataSet;
quMSRPPriceBySubGroup: TADODataSet;
quSalePriceBySubGroup: TADODataSet;
quMSRPPriceByCategoryIDModel: TIntegerField;
quMSRPPriceByCategoryCostPrice: TBCDField;
quMSRPPriceByCategoryMSRPPercent: TFloatField;
quMSRPPriceByGroupIDModel: TIntegerField;
quMSRPPriceByGroupCostPrice: TBCDField;
quMSRPPriceByGroupMSRPPercent: TFloatField;
quMSRPPriceBySubGroupIDModel: TIntegerField;
quMSRPPriceBySubGroupCostPrice: TBCDField;
quMSRPPriceBySubGroupMSRPPercent: TFloatField;
quSalePriceByCategoryIDModel: TIntegerField;
quSalePriceByCategoryCostPrice: TBCDField;
quSalePriceByCategorySPMPercent: TFloatField;
quSalePriceByGroupIDModel: TIntegerField;
quSalePriceByGroupCostPrice: TBCDField;
quSalePriceByGroupSPMPercent: TFloatField;
quSalePriceBySubGroupIDModel: TIntegerField;
quSalePriceBySubGroupCostPrice: TBCDField;
quSalePriceBySubGroupSPMPercent: TFloatField;
quSPMarginByCategory: TADODataSet;
quSPMarginByGroup: TADODataSet;
quSPMarginBySubGroup: TADODataSet;
quMSRPMarginByCategory: TADODataSet;
quMSRPMarginByGroup: TADODataSet;
quMSRPMarginBySubGroup: TADODataSet;
dspModelNewPrices: TDataSetProvider;
quSalePriceByCategoryModel: TStringField;
quSalePriceByCategoryDescription: TStringField;
quSalePriceByGroupModel: TStringField;
quSalePriceByGroupDescription: TStringField;
quSalePriceBySubGroupModel: TStringField;
quSalePriceBySubGroupDescription: TStringField;
quSalePriceByCategoryNewSellingPrice: TBCDField;
quSalePriceByCategoryNewMSRPPrice: TBCDField;
quSalePriceBySubGroupNewSellingPrice: TBCDField;
quSalePriceBySubGroupNewMSRPPrice: TBCDField;
quSalePriceByCategoryIsUpdate: TBooleanField;
quSalePriceByGroupNewSellingPrice: TBCDField;
quSalePriceByGroupNewMSRPPrice: TBCDField;
quSalePriceByGroupIsUpdate: TBooleanField;
quSalePriceBySubGroupIsUpdate: TBooleanField;
quSalePriceByCategorySalePrice: TBCDField;
quSalePriceByCategoryMSRP: TBCDField;
quSalePriceByCategoryRealMarkUpValue: TBCDField;
quSalePriceByCategoryRealMarkUpPercent: TBCDField;
quSalePriceByCategoryMarginPercent: TBCDField;
quSalePriceByCategoryMarginValue: TBCDField;
quSalePriceByCategoryCategory: TStringField;
quSalePriceByCategorySubCategory: TStringField;
quSalePriceByCategoryModelGroup: TStringField;
quSalePriceByGroupSalePrice: TBCDField;
quSalePriceByGroupMSRP: TBCDField;
quSalePriceByGroupRealMarkUpValue: TBCDField;
quSalePriceByGroupRealMarkUpPercent: TBCDField;
quSalePriceByGroupMarginPercent: TBCDField;
quSalePriceByGroupMarginValue: TBCDField;
quSalePriceByGroupCategory: TStringField;
quSalePriceByGroupSubCategory: TStringField;
quSalePriceByGroupModelGroup: TStringField;
quSalePriceBySubGroupSalePrice: TBCDField;
quSalePriceBySubGroupMSRP: TBCDField;
quSalePriceBySubGroupRealMarkUpValue: TBCDField;
quSalePriceBySubGroupRealMarkUpPercent: TBCDField;
quSalePriceBySubGroupMarginPercent: TBCDField;
quSalePriceBySubGroupMarginValue: TBCDField;
quSalePriceBySubGroupCategory: TStringField;
quSalePriceBySubGroupSubCategory: TStringField;
quSalePriceBySubGroupModelGroup: TStringField;
quRoundRangeByGroup: TADODataSet;
StringField1: TStringField;
IntegerField1: TIntegerField;
quRoundRangeBySubGroup: TADODataSet;
StringField2: TStringField;
IntegerField2: TIntegerField;
quModel: TADODataSet;
quSalePriceByCategoryMarkUp: TBCDField;
quSalePriceByGroupMarkUp: TBCDField;
quSalePriceBySubGroupMarkUp: TBCDField;
quModelGroupID: TIntegerField;
quModelIDModelGroup: TIntegerField;
quModelIDModelSubGroup: TIntegerField;
quModelMarkUp: TBCDField;
quModelSellingPrice: TBCDField;
quSalePriceByCategoryIDGroup: TIntegerField;
quSalePriceByCategoryIDModelGroup: TIntegerField;
quSalePriceByCategoryIDModelSubGroup: TIntegerField;
quSalePriceByGroupIDGroup: TIntegerField;
quSalePriceByGroupIDModelGroup: TIntegerField;
quSalePriceByGroupIDModelSubGroup: TIntegerField;
quSalePriceBySubGroupIDGroup: TIntegerField;
quSalePriceBySubGroupIDModelGroup: TIntegerField;
quSalePriceBySubGroupIDModelSubGroup: TIntegerField;
quSalePriceByCategoryCalc: TBooleanField;
quSalePriceBySubGroupCalc: TBooleanField;
quSalePriceByGroupCalc: TBooleanField;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FLogError: TStringList;
FIncreasePriceOnly: boolean;
FUseRound, FUseMargin, FUseMarkupOnCost: Boolean;
FADOCon: TADOConnection;
FMarkupPercent : Double;
FIDGroup : Integer;
FRoundDecimal : Currency;
function GetSalePriceDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
function GetMSRPPriceDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
function GetSPMarginDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
function GetMSRPMarginDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
function GetRoundPrice(Price: Currency; ARoundType: Integer; ARoundValues: String): Currency;
function GetRoundRangeType(AModelGroupingType: TModelGroupingType): TADODataSet;
// function GetModelSalePriceGroupType(AIDModel,AIDCategory, AIDSubCategory, AIDGroup : Integer): TModelGroupingType;
function GetModelMSRPGroupType(AIDCategory, AIDSubCategory, AIDGroup : Integer): TModelGroupingType;
function GetRoundRange(ID: Integer; Price: Currency; AModelGroupingType: TModelGroupingType; var RoundType: Integer; var RoundValues: String): Boolean;
public
//amfsouza 06.06.2011
property IncreasePriceOnly: boolean read FIncreasePriceOnly write FIncreasePriceOnly;
property LogError: TStringList read FLogError write FLogError;
property UseRound: Boolean read FUseRound write FUseRound;
property UseMargin: Boolean read FUseMargin write FUseMargin;
property UseMarkupOnCost : Boolean read FUseMarkupOnCost write FUseMarkupOnCost;
property RoundDecimal : Currency read FRoundDecimal write FRoundDecimal;
procedure SetConnection(ADOCont:TADOConnection);
function GetMarkupPrice(ACostPrice: Currency; ASalePercent: Double): Currency;
function GetMarginPrice(ACostPrice: Currency; ASalePercent: Double): Currency;
function CalcSalePrice(AIDModel,AIDCategory, AIDSubCategory, AIDGroup: Integer; ACostPrice: Currency): Currency;
function CalcMSRPPrice(AIDCategory, AIDSubCategory, AIDGroup: Integer;
ACostPrice: Currency): Currency;
function CalcRounding(AIDCategory: Integer; ASalePrice: Currency): Currency;
function GetNewSaleMSRPPrices(AID: Integer; ACalcPriceType: TCalcPriceType;
AModelGroupingType: TModelGroupingType):OleVariant;
function FormatPrice(Value: Currency): Currency;
// amfsouza 11.26.2010 - get margin considering level ( group, subcategory, category, model ) and cost price
function getValueLevelMarginTable(AConnection: TADOConnection;
AModelGroupingType: TModelGroupingType;
AIdRef: integer; ACost: double): double;
function GetModelSalePriceGroupType(AIDModel,AIDCategory, AIDSubCategory, AIDGroup : Integer): TModelGroupingType;
end;
var
DMCalcPrice: TDMCalcPrice;
implementation
uses uSystemConst, uSqlFunctions, uInventoryCalc, uNumericFunctions, Math;
{$R *.dfm}
{ TDMCalcPrice }
//////////////////
// Código Novo //
//////////////////
procedure TDMCalcPrice.DataModuleCreate(Sender: TObject);
begin
FLogError := TStringList.Create;
FRoundDecimal := 100.0;
end;
procedure TDMCalcPrice.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FLogError);
end;
function TDMCalcPrice.GetSalePriceDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
begin
case AModelGroupingType of
mgtCategory: Result := quSalePriceByCategory;
mgtGroup : Result := quSalePriceByGroup;
mgtSubGroup: Result := quSalePriceBySubGroup;
else
Result := nil;
end;
end;
function TDMCalcPrice.GetMSRPPriceDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
begin
case AModelGroupingType of
mgtCategory: Result := quMSRPPriceByCategory;
mgtGroup : Result := quMSRPPriceByGroup;
mgtSubGroup: Result := quMSRPPriceBySubGroup;
else
Result := nil;
end;
end;
function TDMCalcPrice.GetMarkupPrice(ACostPrice: Currency; ASalePercent: Double): Currency;
begin
Result := ACostPrice;
with TPriceMarkup.Create(ACostPrice, ASalePercent) do
try
Result := CalcMarkup;
finally
Free;
end;
end;
function TDMCalcPrice.GetMarginPrice(ACostPrice: Currency; ASalePercent: Double): Currency;
begin
Result := ACostPrice;
with TPriceMargem.Create(ACostPrice, ASalePercent) do
try
Result := CalcMargem;
finally
Free;
end;
end;
function TDMCalcPrice.CalcMSRPPrice(AIDCategory, AIDSubCategory, AIDGroup: Integer;
ACostPrice: Currency): Currency;
var
MSRPPrice : Currency;
RoundType, iIDCalcMargin: Integer;
RoundValues: String;
AModelGroupingType: TModelGroupingType;
begin
MSRPPrice := ACostPrice;
AModelGroupingType := GetModelMSRPGroupType(AIDCategory, AIDSubCategory, AIDGroup);
case AModelGroupingType of
mgtCategory: iIDCalcMargin := AIDCategory;
mgtGroup : iIDCalcMargin := AIDSubCategory;
mgtSubGroup: iIDCalcMargin := AIDGroup;
end;
try
with GetMSRPMarginDataSet(AModelGroupingType) do
try
Parameters.ParamByName('ID').Value := iIDCalcMargin;
Parameters.ParamByName('Cost1').Value := ACostPrice;
Parameters.ParamByName('Cost2').Value := ACostPrice;
Open;
if UseMargin then
MSRPPrice := GetMarginPrice(ACostPrice, FieldByName('MSRPPercent').AsFloat);
if (MSRPPrice <> ACostPrice) and
GetRoundRange(iIDCalcMargin, MSRPPrice, AModelGroupingType, RoundType, RoundValues) then
MSRPPrice := GetRoundPrice(MSRPPrice,RoundType,RoundValues);
Result := MSRPPrice;
finally
Close;
end;
except
on E: Exception do
FLogError.Add('' + E.Message)
end;
end;
function TDMCalcPrice.CalcSalePrice(AIDModel, AIDCategory, AIDSubCategory, AIDGroup: Integer;
ACostPrice: Currency): Currency;
var
SalePrice : Currency;
RoundType, iIDCalcMargin, MarkupPercent: Integer;
RoundValues: String;
AModelGroupingType: TModelGroupingType;
begin
Result := 0;
iIDCalcMargin := 0;
SalePrice := ACostPrice;
AModelGroupingType := GetModelSalePriceGroupType(AIDModel, AIDCategory, AIDSubCategory, AIDGroup);
case AModelGroupingType of
mgtCategory: iIDCalcMargin := AIDCategory;
mgtGroup : iIDCalcMargin := AIDSubCategory;
mgtSubGroup: iIDCalcMargin := AIDGroup;
end;
try
if iIDCalcMargin <> 0 then
begin
with GetSPMarginDataSet(AModelGroupingType) do
try
Parameters.ParamByName('ID').Value := iIDCalcMargin;
Parameters.ParamByName('Cost1').Value := ACostPrice;
Parameters.ParamByName('Cost2').Value := ACostPrice;
Open;
if UseMargin then
SalePrice := GetMarginPrice(ACostPrice, FieldByName('SPMPercent').AsFloat);
if (SalePrice <> ACostPrice) and
GetRoundRange(iIDCalcMargin, SalePrice, AModelGroupingType, RoundType, RoundValues) then
SalePrice := GetRoundPrice(SalePrice, RoundType, RoundValues);
finally
Close;
end;
end
else
begin
if UseMargin then
SalePrice := GetMarginPrice(ACostPrice, FMarkupPercent)
else
SalePrice := GetMarkupPrice(ACostPrice, FMarkupPercent);
if (SalePrice <> ACostPrice) then
SalePrice := CalcRounding(FIDGroup, SalePrice);
end;
Result := SalePrice;
except
on E: Exception do
FLogError.Add('' + E.Message)
end;
end;
function TDMCalcPrice.GetSPMarginDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
begin
case AModelGroupingType of
mgtCategory: Result := quSPMarginByCategory;
mgtGroup : Result := quSPMarginByGroup;
mgtSubGroup: Result := quSPMarginBySubGroup;
else
Result := nil;
end;
end;
function TDMCalcPrice.GetMSRPMarginDataSet(AModelGroupingType: TModelGroupingType): TADODataSet;
begin
case AModelGroupingType of
mgtCategory: Result := quMSRPMarginByCategory;
mgtGroup : Result := quMSRPMarginByGroup;
mgtSubGroup: Result := quMSRPMarginBySubGroup;
else
Result := nil;
end;
end;
function TDMCalcPrice.GetRoundPrice(Price: Currency;
ARoundType: Integer; ARoundValues: String): Currency;
begin
Result := Price;
if UseRound then
with TPriceRound.Create(Price, ARoundType, ARoundValues) do
try
Result := RoundSalePrice;
finally
Free;
end;
end;
function TDMCalcPrice.GetNewSaleMSRPPrices(AID: Integer;
ACalcPriceType: TCalcPriceType;
AModelGroupingType: TModelGroupingType): OleVariant;
var
NewSalePrice, NewMSRPPrice, cCostPrice: Currency;
RoundType: Integer;
RoundValues: String;
cdsModelNewPrices : TClientDataSet;
fMkpPercent : Double;
SaveSellingPrice: Currency;
begin
try
cdsModelNewPrices := TClientDataSet.Create(self);
dspModelNewPrices.DataSet := GetSalePriceDataSet(AModelGroupingType);
with cdsModelNewPrices do
try
if Active then
Close;
ProviderName := 'dspModelNewPrices';
FetchParams;
Params.ParamByName('ID').Value := AID;
Open;
First;
while not Eof do
begin
if FieldByName('Calc').AsBoolean then
begin
cCostPrice := FormatPrice(FieldByName('CostPrice').AsCurrency);
NewSalePrice := cCostPrice;
//amfsouza 06.06.2011 - newSalePrice = model.sellingprice
SaveSellingPrice := NewSalePrice;
NewMSRPPrice := 0;
if cCostPrice <> 0 then
begin
// Markup
if FUseMarkupOnCost then
NewSalePrice := GetMarkupPrice(cCostPrice, FieldByName('MarkUp').AsFloat)
//Margin
else if UseMargin then
begin
fMkpPercent := FieldByName('MarkUp').AsFloat;
if fMkpPercent = 0 then begin
fMkpPercent := FieldByName('SPMPercent').AsFloat;
newSalePrice := FormatPrice(FieldByName('SalePrice').AsCurrency);
saveSellingPrice := newSalePrice;
end;
if fMkpPercent < 100 then
NewSalePrice := GetMarginPrice(cCostPrice, fMkpPercent);
//amfsouza 06.06.2011 - verify parameter
if ( FIncreasePriceOnly ) then begin
if ( NewSalePrice < SaveSellingPrice ) then
NewSalePrice := SaveSellingPrice;
end;
end;
// Round
if (NewSalePrice <> cCostPrice) then
if GetRoundRange(AID, NewSalePrice, AModelGroupingType, RoundType, RoundValues) then
NewSalePrice := GetRoundPrice(NewSalePrice, RoundType, RoundValues);
// MSRP
NewMSRPPrice := CalcMSRPPrice(FieldByName('IDGroup').AsInteger, FieldByName('IDModelGroup').AsInteger, FieldByName('IDModelSubGroup').AsInteger, cCostPrice);
end;
Edit;
if (cCostPrice <> NewSalePrice) and (NewSalePrice <> 0) then
begin
Fields.FieldByName('NewSellingPrice').AsCurrency := NewSalePrice;
Fields.FieldByName('IsUpdate').AsBoolean := True;
end
else
Fields.FieldByName('NewSellingPrice').AsCurrency := FormatPrice(FieldByName('SalePrice').AsCurrency);
if (cCostPrice <> NewMSRPPrice) and (NewMSRPPrice <> 0) then
begin
Fields.FieldByName('NewMSRPPrice').AsCurrency := NewMSRPPrice;
Fields.FieldByName('IsUpdate').AsBoolean := True;
end
else
Fields.FieldByName('NewMSRPPrice').AsCurrency := FormatPrice(FieldByName('MSRP').AsCurrency);
Post;
end
else
begin
Edit;
Fields.FieldByName('NewSellingPrice').AsCurrency := FormatPrice(FieldByName('SalePrice').AsCurrency);
Fields.FieldByName('NewMSRPPrice').AsCurrency := FormatPrice(FieldByName('MSRP').AsCurrency);
Post;
end;
Next;
end;
Result := cdsModelNewPrices.Data;
finally
Close;
Free;
end;
except
on E: Exception do
FLogError.Add('' + E.Message)
end;
end;
function TDMCalcPrice.GetRoundRangeType(AModelGroupingType: TModelGroupingType): TADODataSet;
begin
case AModelGroupingType of
mgtCategory: Result := quRoundRangeByCategory;
mgtGroup : Result := quRoundRangeByGroup;
mgtSubGroup: Result := quRoundRangeBySubGroup;
else
Result := nil;
end;
end;
function TDMCalcPrice.GetModelSalePriceGroupType(AIDModel,AIDCategory, AIDSubCategory,
AIDGroup: Integer): TModelGroupingType;
begin
Result := mgtCategory;
if (AIDModel <> 0) then
with quModel do
begin
if Active then
Close;
Parameters.ParamByName('IDModel').Value := AIDModel;
try
Open;
FMarkupPercent := FieldByName('MarkUp').AsFloat;
FIDGroup := FieldByName('GroupID').AsInteger;
if FMarkupPercent <> 0 then
begin
Result := mgtNone;
Exit;
end;
finally
Close;
end;
end;
if AIDGroup <> 0 then
with quSalePriceBySubGroup do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := AIDGroup;
try
Open;
if FieldByName('SPMPercent').AsFloat <> 0 then
begin
Result := mgtSubGroup;
Exit;
end;
finally
Close;
end;
end;
if AIDSubCategory <> 0 then
with quSalePriceByGroup do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := AIDSubCategory;
try
Open;
if FieldByName('SPMPercent').AsFloat <> 0 then
begin
Result := mgtGroup;
Exit;
end;
finally
Close;
end;
end;
end;
function TDMCalcPrice.GetModelMSRPGroupType(AIDCategory, AIDSubCategory,
AIDGroup: Integer): TModelGroupingType;
begin
Result := mgtCategory;
if AIDGroup <> 0 then
with quMSRPPriceBySubGroup do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := AIDGroup;
try
Open;
if FieldByName('MSRPPercent').AsFloat <> 0 then
begin
Result := mgtSubGroup;
Exit;
end;
finally
Close;
end;
end;
if AIDSubCategory <> 0 then
with quMSRPPriceByGroup do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := AIDSubCategory;
try
Open;
if FieldByName('MSRPPercent').AsFloat <> 0 then
begin
Result := mgtGroup;
Exit;
end;
finally
Close;
end;
end;
end;
procedure TDMCalcPrice.SetConnection(ADOCont: TADOConnection);
var
i: Integer;
begin
FADOCon := ADOCont;
for i := 0 to Pred(ComponentCount) do
begin
if Components[i] is TADODataSet then
TADODataSet(Components[i]).Connection := FADOCon;
if Components[i] is TADOCommand then
TADOCommand(Components[i]).Connection := FADOCon;
end;
end;
function TDMCalcPrice.GetRoundRange(ID: Integer;
Price: Currency; AModelGroupingType: TModelGroupingType;
var RoundType: Integer; var RoundValues: String): Boolean;
var
Count: Integer;
begin
if not UseRound then
begin
Result := False;
Exit;
end;
with GetRoundRangeType(AModelGroupingType) do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := ID;
Parameters.ParamByName('MinValue').Value := Price;
Parameters.ParamByName('MaxValue').Value := Price;
Open;
if RecordCount > 0 then
begin
RoundType := FieldByName('RoundType').Value;
RoundValues := FieldByName('RoundValues').Value;
end;
Count := RecordCount;
Close;
end;
if Count = 0 then
Result := False
else
Result := True;
end;
function TDMCalcPrice.CalcRounding(AIDCategory: Integer;
ASalePrice: Currency): Currency;
begin
Result := ASalePrice;
if not UseRound then
Exit;
with quRoundRangeByCategory do
begin
if Active then
Close;
Parameters.ParamByName('ID').Value := AIDCategory;
Parameters.ParamByName('MinValue').Value := ASalePrice;
Parameters.ParamByName('MaxValue').Value := ASalePrice;
Open;
if RecordCount > 0 then
Result := GetRoundPrice(ASalePrice,FieldByName('RoundType').Value,FieldByName('RoundValues').Value);
Close;
end;
end;
function TDMCalcPrice.FormatPrice(Value: Currency): Currency;
begin
Result := Round(Value * FRoundDecimal) / FRoundDecimal;
end;
function TDMCalcPrice.getValueLevelMarginTable(AConnection: TADOConnection;
AModelGroupingType: TModelGroupingType; AIdRef: integer;
ACost: double): double;
var
dsMargin: TADOQuery;
sql: String;
IdMarginTable: Integer;
begin
dsMargin := TADOQuery.Create(nil);
dsMargin.Connection := AConnection;
sql := '';
try
//
if ( AModelGroupingType = mgtSubGroup ) then begin
sql :=
'select idsalepricemargemtable from ModelSubGroup ' +
'where idmodelgroup = :idmodelgroup ';
dsMargin.Parameters.ParamByName('idmodelgroup').Value := AIdRef;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idsalepricemargemtable').Value;
if ( not dsMargin.FieldByName('idsalepricemargemtable').IsNull ) then begin
sql := 'select idmargemtable from MargemTable ' +
'where imargemtable = :idmargemtable ';
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idmargemtable').Value;
sql := 'select idmargemtablerange, minvalue, maxvalue, percentage ' +
'where idmargemtable = :idmargemtable '+
' and ( (:unitcostmin >= minvalue) and (:unitcostmax <= maxvalue) )';
dsMargin.SQL.Text := sql;
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Parameters.ParamByName('unitcostmin').Value := Acost;
dsMargin.Parameters.ParamByName('unitcostmax').Value := ACost;
dsMargin.Open;
if ( not dsMargin.Eof ) then begin
result := ( dsMargin.fieldByName('percentage').Value / 100 );
exit;
end;
end;
end
else if ( AModelGroupingType = mgtGroup ) then begin
sql :=
'select idsalepricemargemtable from ModelGroup ' +
'where idmodelgroup = :idmodelgroup ';
dsMargin.SQl.Text := sql;
dsMargin.Parameters.ParamByName('idmodelgroup').Value := AIdRef;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idsalepricemargemtable').Value;
if ( not dsMargin.FieldByName('idsalepricemargemtable').IsNull ) then begin
sql := 'select idmargemtable from MargemTable ' +
'where idmargemtable = :idmargemtable ';
dsMargin.SQl.Text := sql;
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idmargemtable').Value;
sql := 'select idmargemtablerange, minvalue, maxvalue, percentage from MargemTableRange ' +
'where idmargemtable = :idmargemtable '+
' and ( (:unitcostmin >= minvalue) and (:unitcostmax <= maxvalue) )';
dsMargin.SQL.Text := sql;
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Parameters.ParamByName('unitcostmin').Value := Acost;
dsMargin.Parameters.ParamByName('unitcostmax').Value := ACost;
dsMargin.Open;
if ( not dsMargin.Eof ) then begin
result := ( dsMargin.fieldByName('percentage').Value / 100 );
exit;
end;
end;
end
else if ( AModelGroupingType = mgtCategory ) then begin
sql :=
'select idsalepricemargemtable from TabGroup ' +
'where idgroup = :idgroup ';
dsMargin.SQl.Text := sql;
dsMargin.Parameters.ParamByName('idgroup').Value := AIdRef;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idsalepricemargemtable').Value;
if ( not dsMargin.FieldByName('idsalepricemargemtable').IsNull ) then begin
sql := 'select idmargemtable from MargemTable ' +
'where idmargemtable = :idmargemtable ';
dsMargin.SQL.Text := sql;
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Open;
IdMarginTable := dsMargin.fieldByName('idmargemtable').Value;
sql := 'select idmargemtablerange, minvalue, maxvalue, percentage from MargemTableRange ' +
'where idmargemtable = :idmargemtable '+
' and ( (:unitcostmin >= minvalue) and (:unitcostmax <= maxvalue) )';
dsMargin.SQL.Text := sql;
dsMargin.Parameters.ParamByName('idmargemtable').Value := IdMarginTable;
dsMargin.Parameters.ParamByName('unitcostmin').Value := Acost;
dsMargin.Parameters.ParamByName('unitcostmax').Value := ACost;
dsMargin.Open;
if ( not dsMargin.Eof ) then begin
result := ( dsMargin.fieldByName('percentage').Value / 100 );
exit;
end;
end;
end
else if ( AModelGroupingType = mgtNone ) then begin
// under construction
result := 0; //?
end;
finally
freeAndNil(dsMargin);
end;
end;
end.
|
unit nsMediaSettings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls, nsTypes, nsGlobals, ImgList,
System.ImageList;
type
TfrmMediaSettings = class(TForm)
btnOK: TButton;
btnCancel: TButton;
btnHelp: TButton;
PageControl: TPageControl;
Panel1: TPanel;
Label8: TLabel;
btnConnection: TButton;
tsLocal: TTabSheet;
tsFTP: TTabSheet;
Label11: TLabel;
edtHost: TEdit;
Label12: TLabel;
edtPort: TEdit;
chkPassive: TCheckBox;
Label15: TLabel;
edtHostDir: TEdit;
Label13: TLabel;
edtUser: TEdit;
Label14: TLabel;
edtHostPwd: TEdit;
ckbDialup: TCheckBox;
ckbDialupHangup: TCheckBox;
Label10: TLabel;
edtLocalFolder: TEdit;
btnBrowseForLocalFolder: TButton;
tsCD: TTabSheet;
cbDrives: TComboBox;
Label3: TLabel;
ImageList1: TImageList;
cbMediaType: TComboBox;
tsNAS: TTabSheet;
Bevel1: TBevel;
Label1: TLabel;
edtNetPath: TEdit;
Label2: TLabel;
edtNetUser: TEdit;
Label4: TLabel;
edtNetPass: TEdit;
btnBrowseForNetFolder: TButton;
procedure cbMediaTypeChange(Sender: TObject);
procedure btnConnectionClick(Sender: TObject);
procedure btnBrowseForLocalFolderClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnHelpClick(Sender: TObject);
procedure cbDrivesChange(Sender: TObject);
procedure cbMediaTypeDrawItem(Control: TWinControl; Index: integer; Rect: TRect; State: TOwnerDrawState);
procedure btnBrowseForNetFolderClick(Sender: TObject);
protected
procedure UpdateActions; override;
private
{ Private declarations }
FVolume: TNSProject;
FExisting: Boolean;
procedure GetSettings(const AProject: TNSProject);
procedure SetSettings(const AProject: TNSProject);
function CheckSettings: Boolean;
public
{ Public declarations }
end;
function EditMediaSettingsDlg(const AVolume: TNSProject; const AExisting: Boolean = False): Boolean;
implementation
uses
nsOptionsFrm, nsUtils, cdWrapper;
{$R *.dfm}
function EditMediaSettingsDlg(const AVolume: TNSProject; const AExisting: Boolean): Boolean;
begin
with TfrmMediaSettings.Create(Application) do
try
FExisting := AExisting;
GetSettings(AVolume);
Result := ShowModal = mrOk;
if Result then
SetSettings(AVolume);
finally
Free;
end;
end;
procedure TfrmMediaSettings.GetSettings(const AProject: TNSProject);
var
Media: TBackupMedia;
begin
FVolume := AProject;
Caption := Format(sMediaSettings, [AProject.DisplayName]);
for Media := Low(TBackupMedia) to High(TBackupMedia) do
cbMediaType.Items.Add(BackupMediaNames[Media]^);
cbMediaType.ItemIndex := Ord(AProject.BackupMedia);
cbMediaTypeChange(cbMediaType);
UpdateActions;
edtHost.Enabled := not FExisting;
edtHostDir.Enabled := not FExisting;
edtLocalFolder.Enabled := not FExisting;
btnBrowseForLocalFolder.Enabled := edtLocalFolder.Enabled;
cbMediaType.Enabled := not FExisting;
ckbDialupHangup.Checked := AProject.HangUpOnCompleted;
ckbDialup.Checked := AProject.AutoDialUp;
edtHost.Text := AProject.HostName;
edtHostDir.Text := AProject.HostDirName;
edtPort.Text := AProject.Port;
edtUser.Text := AProject.UserName;
edtLocalFolder.Text := AProject.LocalFolder;
edtHostPwd.Text := AProject.Password;
chkPassive.Checked := AProject.Passive;
if (AProject.CDIndex >=0) and (AProject.CDIndex < cbDrives.Items.Count) then
cbDrives.ItemIndex := AProject.CDIndex;
// 3.0.0
edtNetPath.Text := AProject.NetPath;
edtNetUser.Text := AProject.NetUser;
edtNetPass.Text := AProject.NetPass;
end;
procedure TfrmMediaSettings.SetSettings(const AProject: TNSProject);
begin
UpdateActions;
AProject.BackupMedia := TBackupMedia(cbMediaType.ItemIndex);
case AProject.BackupMedia of
bmLocal:
begin
AProject.LocalFolder := edtLocalFolder.Text;
g_LastlocalFolder := AProject.LocalFolder;
end;
bmFTP:
begin
AProject.HostName := edtHost.Text;
g_LastServer := AProject.HostName;
AProject.Port := edtPort.Text;
AProject.HostDirName := edtHostDir.Text;
g_LastHostDir := AProject.HostDirName;
AProject.UserName := edtUser.Text;
g_LastUserName := AProject.UserName;
AProject.Password := edtHostPwd.Text;
AProject.Passive := chkPassive.Checked;
end;
bmCD:
begin
AProject.CDIndex := cbDrives.ItemIndex;
end;
bmNAS:
begin
// 3.0.0
AProject.NetPath := edtNetPath.Text;
AProject.NetUser := edtNetUser.Text;
AProject.NetPass := edtNetPass.Text;
g_LastNetPath := AProject.NetPath;
end;
end;
AProject.AutoDialUp := ckbDialup.Checked;
AProject.HangUpOnCompleted := ckbDialupHangup.Checked;
end;
procedure TfrmMediaSettings.cbMediaTypeChange(Sender: TObject);
begin
PageControl.ActivePageIndex := cbMediaType.ItemIndex;
end;
procedure TfrmMediaSettings.btnConnectionClick(Sender: TObject);
begin
case cbMediaType.ItemIndex of
1: DisplayOptionsDialog(Self, 1);
2: DisplayOptionsDialog(Self, 3);
end;
end;
procedure TfrmMediaSettings.btnBrowseForLocalFolderClick(Sender: TObject);
var
sFolder: String;
begin
sFolder := edtLocalFolder.Text;
if SelectDir(sDestinationSelect, sFolder) then
edtLocalFolder.Text := sFolder;
end;
procedure TfrmMediaSettings.FormCreate(Sender: TObject);
begin
if DiskWriter.GetRecorderList(cbDrives.Items) then
begin
cbDrives.ItemIndex := 0;
cbDrivesChange(Sender);
end;
end;
function TfrmMediaSettings.CheckSettings: Boolean;
var
Index: integer;
Volume: TNSProject;
Root: TNSProject;
S1: string;
S2: string;
begin
if FVolume.Owner is TNSProject then
Root := FVolume.Owner as TNSProject
else
Root := FVolume;
Result := True;
for Index := 0 to Root.VolumeCount - 1 do
begin
Volume := Root.Volumes[Index];
if Volume = FVolume then
Continue;
if cbMediaType.ItemIndex <> Ord(Volume.BackupMedia) then
Continue;
case Volume.BackupMedia of
bmLocal:
begin
S1 := IncludeTrailingPathDelimiter(edtLocalFolder.Text);
S2 := IncludeTrailingPathDelimiter(Volume.LocalFolder);
if AnsiSameText(S1, S2) then
begin
MessageDlg(Format(sDuplicateVolumes, [Volume.GetVolumeString(True)]), mtWarning, [mbOK], 0);
Result := False;
Exit;
end;
end;
bmFtp:
begin
S1 := IncludeTrailingPathDelimiter(edtHost.Text) + IncludeTrailingPathDelimiter(edtHostDir.Text);
S2 := IncludeTrailingPathDelimiter(Volume.HostName) + IncludeTrailingPathDelimiter(Volume.HostDirName);
if AnsiSameText(S1, S2) then
begin
MessageDlg(Format(sDuplicateVolumes, [Volume.GetVolumeString(True)]), mtWarning, [mbOK], 0);
Result := False;
Exit;
end;
end;
bmCD:
begin
if Volume.CDIndex = cbDrives.ItemIndex then
begin
MessageDlg(Format(sDuplicateVolumes, [Volume.GetVolumeString(True)]), mtWarning, [mbOK], 0);
Result := False;
Exit;
end;
end;
bmNAS:
begin
S1 := IncludeTrailingPathDelimiter(edtNetPath.Text);
S2 := IncludeTrailingPathDelimiter(Volume.NetPath);
if AnsiSameText(S1, S2) then
begin
MessageDlg(Format(sDuplicateVolumes, [Volume.GetVolumeString(True)]), mtWarning, [mbOK], 0);
Result := False;
Exit;
end;
end;
end;
end;
end;
procedure TfrmMediaSettings.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if ModalResult <> mrOk then
Exit;
CanClose := CheckSettings;
end;
procedure TfrmMediaSettings.btnHelpClick(Sender: TObject);
begin
Application.HelpSystem.ShowContextHelp(HelpContext, Application.HelpFile);
end;
procedure TfrmMediaSettings.btnBrowseForNetFolderClick(Sender: TObject);
var
sFolder: String;
begin
sFolder := edtNetPath.Text;
if SelectDir(sSelectVolumePath, sFolder) then
edtNetPath.Text := sFolder;
end;
procedure TfrmMediaSettings.UpdateActions;
begin
btnConnection.Enabled := (cbMediaType.ItemIndex in [1, 2]);
case cbMediaType.ItemIndex of
0: btnOk.Enabled := Trim(edtLocalFolder.Text) <> EmptyStr;
1:
begin
btnOk.Enabled := (Trim(edtHost.Text) <> EmptyStr) and (Trim(edtHostDir.Text) <> EmptyStr) and
(Trim(edtUser.Text) <> EmptyStr);
end;
2: btnOK.Enabled := cbDrives.ItemIndex <> -1;
3: btnOK.Enabled := Trim(edtNetPath.Text) <> EmptyStr;
end;
end;
procedure TfrmMediaSettings.cbDrivesChange(Sender: TObject);
begin
if cbDrives.ItemIndex = -1 then
Exit;
DiskWriter.SetActiveRecorder(cbDrives.ItemIndex);
end;
procedure TfrmMediaSettings.cbMediaTypeDrawItem(Control: TWinControl; Index: integer;
Rect: TRect; State: TOwnerDrawState);
begin
with (Control as TComboBox) do
begin
Canvas.FillRect(Rect);
if Index <> -1 then
begin
ImageList1.Draw(Canvas, Rect.Left + 2, Rect.Top + 2, Index, Enabled);
Canvas.TextOut(Rect.Left + 22, Rect.Top + 4, Items[Index]);
end;
end;
end;
end.
|
unit uRepairWoToAPBill;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uTransferBillBaseFrm, DB, DBClient;
type
TRepairWoToApBillFrm = class(TTransferBillBaseFrm)
cdsDestPlan: TClientDataSet;
dsDestPlan: TDataSource;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure ToAPBill(cdsSrcs: array of TClientDataSet);
public
{ Public declarations }
procedure Transfer(cdsSrcs: array of TClientDataSet);override;
procedure OpenDestBillFrm;override;
end;
var
RepairWoToApBillFrm: TRepairWoToApBillFrm;
destBillTypeId:string;
implementation
{$R *.dfm}
uses
FrmCliDM,uUtilsClass,DateUtils,Pub_Fun;
procedure TRepairWoToApBillFrm.Transfer(cdsSrcs: array of TClientDataSet);
var
cdsDests: array[0..2] of TClientDataSet;
destTableNames: array[0..2] of string;
begin
inherited;
destBillTypeId := '510b6503-0105-1000-e000-010fc0a812fd463ED552';
cdsDests[0] := cdsDestMaster;
cdsDests[1] := cdsDestDetail;
cdsDests[2] := cdsDestPlan;
destTableNames[0] := 'T_AP_OtherBill';
destTableNames[1] := 'T_AP_OtherBillentry';
destTableNames[2] := 'T_AP_OtherBillPlan';
//转单代码
ToAPBill(cdsSrcs);
//保存单据
SaveDest(cdsDests,destTableNames);
if IsOpenDestBill then
OpenDestBillFrm
end;
procedure TRepairWoToApBillFrm.OpenDestBillFrm;
begin
inherited;
//打开目标单据代码
end;
procedure TRepairWoToApBillFrm.ToAPBill(cdsSrcs: array of TClientDataSet);
var
sql,errmsg:string;
codeRuleUtils: TCodeRuleUtilsCls;
cdsSrcMaster,cdsSrcDetail,cdsTmp:TClientDataSet;
seq:integer;
qty,price,taxprice,taxrate,tax,amount,taxamount,discountRate:double;
redBill: boolean;
customerID,customerNum,customerName_l1,customerName_l2,customerName_l3: string;
totalAmount,totaltax,totaltaxamount:double;
begin
try
codeRuleUtils := TCodeRuleUtilsCls.Create;
cdsTmp := TClientDataSet.Create(nil);
cdsSrcMaster := cdsSrcs[0];
cdsSrcDetail := cdsSrcs[1];
//转单代码
//表头
cdsDestMaster.Append;
cdsDestMaster.FieldByName('FIsTransBill').AsVariant := '';
cdsDestMaster.FieldByName('FPurOrgID').AsVariant := '';
cdsDestMaster.FieldByName('FBillType').AsVariant := '';
cdsDestMaster.FieldByName('FIsImportBill').AsVariant := '';
cdsDestMaster.FieldByName('FVoucherNumber').AsVariant := '';
cdsDestMaster.FieldByName('FAdminOrgUnitID').AsVariant := '';
cdsDestMaster.FieldByName('FPersonID').AsVariant := '';
cdsDestMaster.FieldByName('FBizTypeID').AsVariant := '';
cdsDestMaster.FieldByName('FPaymentTypeID').AsVariant := '';
cdsDestMaster.FieldByName('FPurchaseGroupID').AsVariant := '';
cdsDestMaster.FieldByName('FLastExhangeRate').AsVariant := '';
cdsDestMaster.FieldByName('FTotalAmount').AsVariant := '';
cdsDestMaster.FieldByName('FTotalTax').AsVariant := '';
cdsDestMaster.FieldByName('FTotalTaxAmount').AsVariant := '';
cdsDestMaster.FieldByName('FIsExchanged').AsVariant := '';
cdsDestMaster.FieldByName('FIsInitializeBill').AsVariant := '';
cdsDestMaster.FieldByName('FVoucherTypeID').AsVariant := '';
cdsDestMaster.FieldByName('FRedBlueType').AsVariant := '';
cdsDestMaster.FieldByName('FYear').AsVariant := '';
cdsDestMaster.FieldByName('FPeriod').AsVariant := '';
cdsDestMaster.FieldByName('FIsSCMBill').AsVariant := '';
cdsDestMaster.FieldByName('FIsPriceWithoutTax').AsVariant := '';
cdsDestMaster.FieldByName('FIsNeedVoucher').AsVariant := '';
cdsDestMaster.FieldByName('FIsAllowanceBill').AsVariant := '';
cdsDestMaster.FieldByName('FIsAppointVoucher').AsVariant := '';
cdsDestMaster.FieldByName('FPriceSource').AsVariant := '';
cdsDestMaster.FieldByName('FPayConditionId').AsVariant := '';
cdsDestMaster.FieldByName('FIsImpFromGL').AsVariant := '';
cdsDestMaster.FieldByName('FAdminOrgUnitId_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FPersonID_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FAsstActID_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FBillDate_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FAsstActTypeID_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FisSplitBill').AsVariant := '';
cdsDestMaster.FieldByName('FIsGenCoopBill').AsVariant := '';
cdsDestMaster.FieldByName('FisCoopBuild').AsVariant := '';
cdsDestMaster.FieldByName('FContractNumber').AsVariant := '';
cdsDestMaster.FieldByName('FBillType_SourceBill').AsVariant := '';
cdsDestMaster.FieldByName('FIsBizBill').AsVariant := '';
cdsDestMaster.FieldByName('FCostCenterID').AsVariant := '';
cdsDestMaster.FieldByName('FBillRelationOption').AsVariant := '';
//表体
cdsSrcDetail.First;
seq := 0;
while not cdsSrcDetail.Eof do
begin
inc(seq);
qty := Pub_Fun.USimpleRoundTo(cdsSrcDetail.FieldByName('CFUnIssueQty').AsFloat);
discountRate := Pub_Fun.USimpleRoundTo(cdsSrcDetail.FieldByName('CFDiscountRate').AsFloat);
price := Pub_Fun.USimpleRoundTo(cdsSrcDetail.FieldByName('CFPrice').AsFloat * (1 - discountRate / 100.0));
taxprice := Pub_Fun.USimpleRoundTo(cdsSrcDetail.FieldByName('CFTaxPrice').AsFloat * (1 - discountRate / 100.0));
taxrate := Pub_Fun.USimpleRoundTo(cdsSrcDetail.FieldByName('CFTaxRate').AsFloat);
tax := Pub_Fun.USimpleRoundTo(qty * price * taxRate / 100);
amount := Pub_Fun.USimpleRoundTo(qty * price);
taxamount := Pub_Fun.USimpleRoundTo(qty * taxPrice);
totaltax := totaltax + tax;
totalAmount := totalamount + amount;
totaltaxamount := totaltaxamount + taxamount;
cdsDestDetail.Append;
cdsSrcDetail.Next;
end;
cdsDestDetail.Post;
cdsDestMaster.FieldByName('FAmount').AsVariant := totaltaxamount;
cdsDestMaster.FieldByName('FAmountLocal').AsVariant := totaltaxamount;
cdsDestMaster.FieldByName('FUnVerifyAmount').AsVariant := totaltaxamount;
cdsDestMaster.FieldByName('FUnVerifyAmountLocal').AsVariant := totaltaxamount;
cdsDestMaster.FieldByName('FTotalAmount').AsVariant := totalAmount;
cdsDestMaster.FieldByName('FTotalTax').AsVariant :=totaltax;
cdsDestMaster.FieldByName('FTotalTaxAmount').AsVariant := totaltaxamount;
cdsDestMaster.Post;
//收款计划
cdsDestPlan.Post;
finally
if cdsTmp <> nil then
cdsTmp.Free;
end;
end;
procedure TRepairWoToApBillFrm.FormCreate(Sender: TObject);
var
OpenTables: array[0..2] of string;
_cds: array[0..2] of TClientDataSet;
ErrMsg : string;
strsql : string;
begin
strsql := 'select * from T_AP_OtherBill where 1 = 2';
OpenTables[0] := strsql;
strsql := 'select * from T_AP_OtherBillentry where 1 = 2';
OpenTables[1] := strsql;
strsql := 'select * from T_AP_OtherBillPlan where 1 = 2';
_cds[0] := cdsDestMaster;
_cds[1] := cdsDestDetail;
_cds[2] := cdsDestPlan;
try
if not CliDM.Get_OpenClients_E('GA003',_cds,OpenTables,ErrMsg) then
begin
ShowError(Handle, ErrMsg,[]);
Abort;
end;
except
on E : Exception do
begin
ShowError(Handle, '打开编辑数据报错:'+E.Message,[]);
Abort;
end;
end;
end;
end.
|
unit StoreDAO;
interface
uses
StoreCls, Classes, DB, ADODb, SysUtils;
type
TStoreDAO = class
private
connection: TADOConnection;
public
constructor create(connection: TADOConnection);
function insert(store: TStoreRegistry): Boolean;
function update(store: TStoreRegistry): Boolean;
function delete(id: Integer): Boolean;
function getStores(): TList;
function getStore(i: Integer): TStoreRegistry;
end;
implementation
{ TStoreDAO }
constructor TStoreDAO.create(connection: TADOConnection);
begin
self.connection := connection;
end;
function TStoreDAO.delete(id: Integer): Boolean;
begin
end;
function TStoreDAO.getStore(i: Integer): TStoreRegistry;
begin
end;
function TStoreDAO.getStores: TList;
var
qry: TADOQuery;
stores: TList;
store: TStoreRegistry;
begin
try
try
stores := TList.Create;
qry := TADOQuery.Create(nil);
qry.Connection := connection;
qry.SQL.Add('select * from Store');
qry.open;
qry.First;
while ( not qry.Eof ) do begin
store := TStoreRegistry.Create;
store.IdStore := (qry.fieldByName('IDStore').Value);
store.Name := (qry.fieldByName('Name').Value);
stores.Add(store);
qry.Next();
end;
result := stores;
except
on e: Exception do begin
raise Exception.create('Failed to read stores: '+e.Message);
end;
end;
finally
freeAndNil(qry);
end;
end;
function TStoreDAO.insert(store: TStoreRegistry): Boolean;
begin
end;
function TStoreDAO.update(store: TStoreRegistry): Boolean;
begin
end;
end.
|
unit UfmAnalyzerSelection;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxStyles, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, cxNavigator, DB, cxDBData, MemDS, DBAccess, Uni,
cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, ExtCtrls, DBClient, Provider,
StdCtrls, Buttons, cxDBLookupComboBox;
type
TfmAnalyzerSelection = class(TForm)
Panel1: TPanel;
gridAnalyzer: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
q_analyzer: TUniQuery;
dp_analyzer: TDataSetProvider;
cds_analyzer: TClientDataSet;
d_analyzer: TDataSource;
btnSelect: TBitBtn;
btnCancel: TBitBtn;
cds_analyzerID: TStringField;
cds_analyzerUSER_NAME: TStringField;
cds_analyzerLOGIN_ID: TStringField;
cds_analyzerLOGIN_PASS: TStringField;
cds_analyzerLOGIN_PASS2: TStringField;
cds_analyzerUSER_KIND: TIntegerField;
cds_analyzerAPPROVED: TIntegerField;
cds_analyzerREG_DATE: TDateField;
cds_analyzerCOMP_ID: TStringField;
cds_analyzerREMARK: TStringField;
cds_analyzerEMAIL: TStringField;
cds_analyzerCONFIRMED: TSmallintField;
cds_analyzerIS_ANALYZER: TSmallintField;
gridAnalyzerID: TcxGridDBColumn;
gridAnalyzerUSER_NAME: TcxGridDBColumn;
gridAnalyzerLOGIN_ID: TcxGridDBColumn;
gridAnalyzerLOGIN_PASS: TcxGridDBColumn;
gridAnalyzerLOGIN_PASS2: TcxGridDBColumn;
gridAnalyzerUSER_KIND: TcxGridDBColumn;
gridAnalyzerAPPROVED: TcxGridDBColumn;
gridAnalyzerREG_DATE: TcxGridDBColumn;
gridAnalyzerCOMP_ID: TcxGridDBColumn;
gridAnalyzerREMARK: TcxGridDBColumn;
gridAnalyzerEMAIL: TcxGridDBColumn;
gridAnalyzerCONFIRMED: TcxGridDBColumn;
gridAnalyzerIS_ANALYZER: TcxGridDBColumn;
q_company_look: TUniQuery;
dp_company_look: TDataSetProvider;
cds_company_look: TClientDataSet;
d_company_look: TDataSource;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmAnalyzerSelection: TfmAnalyzerSelection;
implementation
uses uCapture, UdmDBCommon;
{$R *.dfm}
procedure TfmAnalyzerSelection.FormCreate(Sender: TObject);
begin
cds_company_look.Active := True;
cds_analyzer.Active := True;
end;
end.
|
unit ufrmBeginningBalancePOS;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, Mask,
System.Actions, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer, Vcl.ComCtrls, dxCore,
cxDateUtils, Vcl.Menus, cxCurrencyEdit, ufraFooter4Button, cxButtons,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC, Datasnap.DBClient;
type
TfrmBeginningBalancePOS = class(TfrmMasterBrowse)
pnl3: TPanel;
lbl3: TLabel;
lbl4: TLabel;
lbl5: TLabel;
curredtGrandTot: TcxCurrencyEdit;
edtCashierName: TcxTextEdit;
edtSupervisorID: TcxTextEdit;
edtShift: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtShiftKeyPress(Sender: TObject; var Key: Char);
procedure actPrintExecute(Sender: TObject);
procedure cxGridViewFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure dtAkhirFilterPropertiesEditValueChanged(Sender: TObject);
private
// dataBeginningBlnc: TDataSet;
FCDS: TClientDataSet;
function IsShiftExist: Boolean;
property CDS: TClientDataSet read FCDS write FCDS;
public
FShiftID: string;
function IsBeginningBalanceUsed(aBalance_ID, aUnitID: Integer): Boolean;
procedure ParseDataGrid;
procedure ParseHeaderGrid(jmlData: Integer);
procedure prepareAdd;
procedure prepareEdit;
procedure RefreshData; override;
end;
var
frmBeginningBalancePOS: TfrmBeginningBalancePOS;
implementation
uses
ufrmDialogBeginningBalancePOS, uTSCommonDlg, uConstanta, uRetnoUnit,
uDXUtils, uDBUtils, uDMClient, uModShift, uAppUtils;
const
_Caption : String = 'SETTING POS BEGINNING BALANCE';
// _kolNo : Integer = 0;
// _kolPosCode : Integer = 1;
// _kolCashierName : Integer = 2;
// _kolBegBal : Integer = 3;
// _kolDesc : Integer = 4;
// _kolBegBal_ID : Integer = 5;
// _kolUser_ID : Integer = 6;
{$R *.dfm}
procedure TfrmBeginningBalancePOS.FormCreate(Sender: TObject);
begin
inherited;
lblHeader.Caption := _Caption;
ClearByTag([0]);
AutoRefreshData := true;
// edtSupervisorID.EditValue := FLoginFullname;
end;
procedure TfrmBeginningBalancePOS.FormDestroy(Sender: TObject);
begin
inherited;
frmBeginningBalancePOS := nil;
end;
procedure TfrmBeginningBalancePOS.actAddExecute(Sender: TObject);
begin
inherited;
if VarIsNull(edtShift.EditValue) then
begin
CommonDlg.ShowMessage('Shift harap di isi dulu');
edtShift.SetFocus;
Exit;
end;
ShowDialogForm(TfrmDialogBeginBalancePOS);
end;
procedure TfrmBeginningBalancePOS.actEditExecute(Sender: TObject);
begin
inherited;
{
if IsBeginningBalanceUsed(StrToInt(strgGrid.Cells[_kolBegBal_ID,strgGrid.Row]),masternewunit.id) then
begin
CommonDlg.ShowMessage('Kasir sudah transaksi, tidak bisa diedit.');
Exit;
end;
}
ShowDialogForm(TfrmDialogBeginBalancePOS, CDS.FieldByName('BEGINNING_BALANCE_ID').AsString);
end;
procedure TfrmBeginningBalancePOS.dtAkhirFilterPropertiesEditValueChanged(
Sender: TObject);
begin
inherited;
RefreshData;
end;
procedure TfrmBeginningBalancePOS.ParseHeaderGrid(jmlData: Integer);
begin
{with strgGrid do
begin
Clear;
RowCount := jmlData + 1;
ColCount := 5;
Cells[_kolNo,0] := 'NO.';
Cells[_kolPosCode,0] := 'POS CODE';
Cells[_kolCashierName,0] := 'CASHIER NAME';
Cells[_kolBegBal,0] := 'BEGINNING BALANCE';
Cells[_kolDesc,0] := 'DESCRIPTION';
if jmlData < 1 then
begin
RowCount := 2;
Cells[_kolNo,1] := '';
Cells[_kolPosCode,1] := '';
Cells[_kolCashierName,1] := '';
Cells[_kolBegBal,1] := '';
Cells[_kolDesc,1] := '';
Cells[_kolBegBal_ID,1] := '0';
end;
FixedRows := 1;
AutoSize := true;
end;
}
end;
procedure TfrmBeginningBalancePOS.ParseDataGrid;
//var intI: Integer;
// tempBool: Boolean;
// grandTotal: Currency;
// sTemp : String;
begin
{
if not Assigned(BeginningBalancePOS) then
BeginningBalancePOS := TBeginningBalancePOS.Create;
if not BeginningBalancePOS.CekShift(edtShift.Text, masternewunit.id, sTemp) then
begin
CommonDlg.ShowError(ER_SHIFT_NOT_FOUND);
edtShift.Text:= bufShift;
edtShift.SelectAll;
end;
lblHeader.Caption := _Caption + sTemp;
dataBeginningBlnc := BeginningBalancePOS.GetListDataBeginningBalancePOS(dt1.Date,edtShift.Text,masternewunit.id);
ParseHeaderGrid(dataBeginningBlnc.RecordCount);
if dataBeginningBlnc.RecordCount > 0 then
begin
//initiate
intI := 1;
grandTotal := 0;
dataBeginningBlnc.First;
while not(dataBeginningBlnc.Eof) do
begin
with strgGrid do
begin
Cells[_kolNo,intI] := IntToStr(intI) + '.';
Cells[_kolPosCode,intI] := dataBeginningBlnc.FieldByName('SETUPPOS_TERMINAL_CODE').AsString;
Cells[_kolUser_ID,intI] := dataBeginningBlnc.FieldByName('BALANCE_USR_ID').AsString;
Cells[_kolBegBal,intI] := dataBeginningBlnc.FieldByName('BALANCE_MODAL').AsString;
Alignments[_kolBegBal,intI] := taRightJustify;
if Cells[_kolBegBal,intI] <> '' then
try
grandTotal := grandTotal + StrToCurr(Cells[3,intI]);
except
end;
Cells[_kolDesc,intI] := dataBeginningBlnc.FieldByName('BALANCE_DESCRIPTION').AsString;
Cells[_kolBegBal_ID,intI] := dataBeginningBlnc.FieldByName('BALANCE_ID').AsString;
Cells[_kolCashierName,intI] := dataBeginningBlnc.FieldByName('USR_FULLNAME').AsString;
end; // end with strggrid
Inc(intI);
dataBeginningBlnc.Next;
end; //while not eof
curredtGrandTot.Value := grandTotal;
end;// end if recordcount
strgGrid.FixedRows := 1;
strgGrid.AutoSize := true;
tempBool := True;
strgGridRowChanging(Self,0,1,tempBool);
}
end;
procedure TfrmBeginningBalancePOS.FormShow(Sender: TObject);
begin
inherited;
edtShift.SetFocus;
end;
procedure TfrmBeginningBalancePOS.prepareAdd;
begin
{
if not assigned(frmDialogBeginBalancePOS) then
Application.CreateForm(TfrmDialogBeginBalancePOS, frmDialogBeginBalancePOS);
frmDialogBeginBalancePOS.Caption := 'Add POS Beginning Balance';
// frmDialogBeginBalancePOS.FormMode := fmAdd;
frmDialogBeginBalancePOS.Balance_ID := 0;
frmDialogBeginBalancePOS.Balance_Shift_Date := dtAkhirFilter.Date;
// if not assigned(BeginningBalancePOS) then
// BeginningBalancePOS := TBeginningBalancePOS.Create;
// frmDialogBeginBalancePOS.Balance_Shift_ID := BeginningBalancePOS.GetShiftId(edtShift.Text, masternewunit.id);
SetFormPropertyAndShowDialog(frmDialogBeginBalancePOS);
}
end;
procedure TfrmBeginningBalancePOS.prepareEdit;
begin
{
if not assigned(frmDialogBeginBalancePOS) then
Application.CreateForm(TfrmDialogBeginBalancePOS, frmDialogBeginBalancePOS);
frmDialogBeginBalancePOS.Caption := 'Edit POS Beginning Balance';
frmDialogBeginBalancePOS.FormMode := fmEdit;
//setting var
frmDialogBeginBalancePOS.Balance_ID := StrToInt(strgGrid.Cells[_kolBegBal_ID,strgGrid.Row]);
frmDialogBeginBalancePOS.Balance_Shift_Date := dt1.Date;
if not assigned(BeginningBalancePOS) then
BeginningBalancePOS := TBeginningBalancePOS.Create;
frmDialogBeginBalancePOS.Balance_Shift_ID := BeginningBalancePOS.GetShiftId(edtShift.Text, masternewunit.id);
//write data edit
frmDialogBeginBalancePOS.PosCode := strgGrid.Cells[_kolPosCode,strgGrid.Row];
frmDialogBeginBalancePOS.CashierID := strgGrid.Cells[_kolUser_ID,strgGrid.Row];
frmDialogBeginBalancePOS.CashierName := strgGrid.Cells[_kolCashierName,strgGrid.Row];
frmDialogBeginBalancePOS.Modal := StrToCurr(strgGrid.Cells[_kolBegBal,strgGrid.Row]);
frmDialogBeginBalancePOS.Descrpt := strgGrid.Cells[_kolDesc,strgGrid.Row];
SetFormPropertyAndShowDialog(frmDialogBeginBalancePOS);
}
end;
procedure TfrmBeginningBalancePOS.edtShiftKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_RETURN) then
RefreshData;
end;
procedure TfrmBeginningBalancePOS.actPrintExecute(Sender: TObject);
//var
// sSQL : String;
// SS : TStrings;
// _HeaderFlag : integer;
// sTemp : string;
begin
inherited;
// _HeaderFlag := 4705;
{
sSQL := ' delete from TEMP_LAPORAN '
+ ' WHERE laporan_id = ' + IntToStr(_HeaderFlag)
+ ' AND user_id = ' + IntToStr(FLoginId) ;
cExecSQL(sSQL, True , _HeaderFlag);
SS := TStringList.Create;
Self.Enabled := False;
if not Assigned(BeginningBalancePOS) then
BeginningBalancePOS := TBeginningBalancePOS.Create;
if not BeginningBalancePOS.CekShift(edtShift.Text, masternewunit.id, sTemp) then
begin
CommonDlg.ShowError(ER_SHIFT_NOT_FOUND);
edtShift.Text:= bufShift;
edtShift.SelectAll;
end;
lblHeader.Caption := _Caption + sTemp;
dataBeginningBlnc := BeginningBalancePOS.GetListDataBeginningBalancePOS(dt1.Date,edtShift.Text,masternewunit.id);
dataBeginningBlnc.Last;
if dataBeginningBlnc.RecordCount > 0 then
begin
//initiate
dataBeginningBlnc.First;
end;
try
with dataBeginningBlnc do
while not(Eof) do
begin
sSQL:= 'INSERT INTO TEMP_LAPORAN (LAPORAN_ID, USER_ID, CHAR1, CHAR2, CHAR3,'
+ ' CHAR4, CHAR5, CHAR6,CHAR7, CHAR8, NUM1, NUM2, NUM3, NUM4'
+ ' ) VALUES ('
+ IntToStr(_HeaderFlag) + ', '
+ IntToStr(FLoginId) + ', '
+ Quot(edtShift.Text) + ', '
+ Quot(FieldByName('SETUPPOS_TERMINAL_CODE').AsString) + ', '
+ Quot(FieldByName('USR_FULLNAME').AsString) + ', '
+ Quot(FieldByName('BALANCE_DESCRIPTION').AsString) + ', '
+ Quot(FormatDateTime('dd-MM-yyyy', dt1.Date)) + ', '
+ Quot(FieldByName('SETUPPOS_NO_TRANSAKSI').AsString) + ', '
+ Quot(FieldByName('BALANCE_STATUS').AsString) + ', '
+ Quot(FieldByName('USR_USERNAME').AsString) + ', '
+ FloatToStr(FieldByName('BALANCE_MODAL').AsFloat) + ', '
+ FloatToStr(FieldByName('SHIFT_START_TIME').AsFloat) + ', '
+ FloatToStr(FieldByName('SHIFT_END_TIME').AsFloat) + ', '
+ IntToStr(FieldByName('BALANCE_ID').AsInteger)
+ ')';
SS.Add(sSQL);
dataBeginningBlnc.Next;
end;
if kExecuteSQLs(_HeaderFlag, SS) then
begin
cCommitTrans;
GetExCompanyHeader(dt1.Date, dt1.Date, MasterNewUnit.ID, FLoginUsername, FLoginFullname);
sSQL := 'SELECT '
+ ' laporan_id, user_id, char1 as "SHIFT", char2 as "POS",'
+ ' CHAR3 AS CASHIERNAME, CHAR4 AS Description, CHAR5 AS "tTIme", CHAR6 as "TranscNo",'
+ ' CHAR7 as Status,CHAR8 as CashierCode,'
+ ' num1 as Modal, num2 as SHIFT_START_TIME, num3 as SHIFT_END_TIME, '
+ ' num4 as BALANCE_ID '
+ ' FROM TEMP_LAPORAN'
+ ' WHERE laporan_id = ' + IntToStr(_HeaderFlag)
+ ' AND user_id = ' + IntToStr(FLoginId)
+ ' ORDER BY num1';
dmReportNew.EksekusiReport('CashierBeginningBal', sSQL,'',True);
end;
finally
Self.Enabled := True;
SS.Free;
end;
}
end;
procedure TfrmBeginningBalancePOS.cxGridViewFocusedRecordChanged(Sender:
TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord:
TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean);
begin
inherited;
if Assigned(CDS) then
if CDS.RecordCount > 0 then
edtCashierName.EditValue := CDS.FieldByName('CASHIER_NAME').Value;
end;
function TfrmBeginningBalancePOS.IsBeginningBalanceUsed(aBalance_ID, aUnitID:
Integer): Boolean;
begin
Result := False;
{with TPOSTransaction.Create(Self) do
begin
try
Result := IsBalanceUsed(aBalance_ID,aUnitID);
finally
Free;
end;
end;
}
end;
function TfrmBeginningBalancePOS.IsShiftExist: Boolean;
var
lModShift: TModShift;
begin
Result := False;
lModShift := TModShift.Create;
try
lModShift := DMClient.CrudClient.RetrieveByCode(TModShift.ClassName, edtShift.EditValue) as TModShift;
if lModShift.SHIFT_NAME = '' then
begin
lblHeader.Caption := _Caption;
TAppUtils.Error(ER_SHIFT_NOT_FOUND);
edtShift.SetFocus;
end else
begin
FShiftID := lModShift.ID;
lblHeader.Caption := _Caption + ' ['
+ FormatDateTime('hh:mm:ss', lModShift.SHIFT_START_TIME) + ' - '
+ FormatDateTime('hh:mm:ss', lModShift.SHIFT_END_TIME) + ']';
Result := True;
end;
finally
lModShift.Free;
end;
end;
procedure TfrmBeginningBalancePOS.RefreshData;
begin
inherited;
if edtShift.Text = '' then
Exit
else if not IsShiftExist then
Exit;
edtCashierName.Clear;
edtSupervisorID.Clear;
curredtGrandTot.Value := 0;
if Assigned(FCDS) then FreeAndNil(FCDS);
FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.BeginningBalance_GetDSOverview(dtAkhirFilter.Date, edtShift.EditValue, TRetno.UnitStore.ID) ,Self );
cxGridView.LoadFromCDS(CDS);
cxGridView.SetVisibleColumns(['BEGINNING_BALANCE_ID','AUT$UNIT_ID','BALANCE_SHIFT_DATE','SHIFT_NAME'],False);
cxGridView.SetReadOnlyAllColumns(True);
cxGridView.SetSummaryByColumns(['BEGINNING_BALANCE']);
curredtGrandTot.EditValue := cxGridView.GetFooterSummary('BEGINNING_BALANCE');
// cxGridView.DataController.FocusedRecordIndex := 0;
end;
end.
|
program fossvc;
{$mode objfpc}{$H+}
{$modeswitch nestedprocvars}
{$codepage utf-8}
{$LIBRARYPATH ../../lib}
{$LINKLIB libdladm}
{
fossvc
is a generic smf service method
One svc for all ecf managed services -> create smfs for IP,DHCP,KVM, DNS ...
and acts as starter for IP and ROUTE
1) handle service instance creation and deletion on startup of zone
2) configures ip adresses and routes
}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, CustApp, fosillu_libzonecfg,fre_process,
FRE_SYSTEM,FOS_DEFAULT_IMPLEMENTATION,FOS_TOOL_INTERFACES,FOS_FCOM_TYPES,FRE_APS_INTERFACE,FRE_DB_INTERFACE,
FRE_DB_CORE,fre_dbbase, FRE_CONFIGURATION,fre_hal_schemes, fre_zfs, fosillu_libscf,fos_firmbox_svcctrl,
fosillu_ipadm, fosillu_hal_svcctrl,fosillu_hal_dbo_common,fre_dbbusiness
{ you can add units after this };
type
{ TFRE_fossvc }
TFRE_fossvc = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TFRE_fos_brand }
procedure TFRE_fossvc.DoRun;
var
ErrorMsg : String;
zone_dbo_file : string;
zone_dbo : IFRE_DB_Object;
//zone : TFRE_DB_ZONE;
svclist : IFRE_DB_Object;
foundobj : IFRE_DB_Object;
uid_string : string;
uid : TFRE_DB_GUID;
svc_name : string;
svc : TFRE_DB_SERVICE;
function StartService(const obj: IFRE_DB_Object):boolean;
var ip : TFRE_DB_IP;
r : TFRE_DB_IP_ROUTE;
dl : TFRE_DB_DATALINK;
resdbo : IFRE_DB_Object;
begin
result := false;
if obj.IsA(TFRE_DB_IP,ip) then
begin
writeln('DATALINK PARENT ',ip.Parent.SchemeClass,ip.Parent.DumpToString());
if ip.Parent.IsA(TFRE_DB_DATALINK,dl) then
ip.Field('datalinkname').asstring := dl.ObjectName;
resdbo := ip.StartService;
result := resdbo.Field('started').asboolean;
end;
if obj.IsA(TFRE_DB_IP_ROUTE,r) then
begin
resdbo := r.StartService;
result := resdbo.Field('started').asboolean;
end;
end;
function StopService(const obj: IFRE_DB_Object):boolean;
var ip : TFRE_DB_IP;
r : TFRE_DB_IP_ROUTE;
dl : TFRE_DB_DATALINK;
resdbo : IFRE_DB_Object;
begin
result :=false;
writeln('SWL: STOP');
if obj.IsA(TFRE_DB_IP,ip) then
begin
if ip.Parent.IsA(TFRE_DB_DATALINK,dl) then
ip.Field('datalinkname').asstring := dl.ObjectName;
resdbo := ip.StopService;
result := resdbo.Field('stopped').asboolean;
end;
if obj.IsA(TFRE_DB_IP_ROUTE,r) then
begin
resdbo := r.StopService;
result := resdbo.Field('stopped').asboolean;
end;
end;
function RestartService(const obj: IFRE_DB_Object):boolean;
begin
result :=false;
writeln('SWL: RESTART NOT IMPLEMENTED YET');
end;
function TryToChangeServiceState(const obj: IFRE_DB_Object):boolean;
begin
if HasOption('*','start') then
result := StartService(obj)
else
if HasOption('*','stop') then
result := StopService(obj)
else
if HasOption('*','restart') then
result := RestartService(obj)
else
raise Exception.Create('no enable,disable,restart option choosen!');
end;
procedure CheckServices(const obj: IFRE_DB_Object);
var dl : TFRE_DB_DATALINK;
resdbo : IFRE_DB_Object;
svc : TFRE_DB_SERVICE;
procedure _RemoveIPHostnetService(const fld:IFRE_DB_Field);
var fmri : string;
foundobj : IFRE_DB_Object;
begin
if fld.FieldType=fdbft_String then
begin
fmri := fld.AsString;
if svclist.FetchObjWithStringFieldValue('fmri',fmri,foundobj,'') then
begin
writeln('SWL: IP SERVICE CREATED/EXISTING');
svclist.DeleteField(foundobj.UID.AsHexString);
end;
end;
end;
begin
if obj.IsA(TFRE_DB_DATALINK,dl) then
begin
writeln('SWL: NOW DATALINK ',dl.ObjectName,' ',obj.UID.AsHexString);
resdbo := dl.PHYS_CreateAllServiceSMFs;
resdbo.ForAllFields(@_RemoveIPHostnetService,true);
// writeln(resdbo.DumpToString());
end
else
begin
if obj.IsA(TFRE_DB_SERVICE,svc) then
begin
writeln('SWL: NOW SERVICE ',obj.UID.AsHexString,' ', svc.getFMRI);
if svclist.FetchObjWithStringFieldValue('fmri',svc.getFMRI,foundobj,'') then
begin
writeln('SWL: SERVICE ALREADY CREATED');
svc.PHYS_ConfigureService;
svclist.DeleteField(foundobj.UID.AsHexString);
end
else
begin
writeln('SWL CREATE SERVICE ',svc.getFMRI);
svc.PHYS_CreateServiceSMF;
// writeln(resdbo.DumpToString());
end;
end;
end;
end;
procedure _DeleteService(const obj:IFRE_DB_Object);
var fmri : string;
svc_name : string;
begin
fmri := obj.Field('fmri').asstring;
svc_name := Copy(fmri,6,maxint);
writeln('SWL: REMOVE DEPENDENCY ',fmri);
try
if Pos('fos_ip_',svc_name)>0 then
fre_remove_dependency('fos/fosip',StringReplace(svc_name,'/','',[rfReplaceAll]));
if Pos('fos_routing',svc_name)>0 then
fre_remove_dependency('milestone/network',StringReplace(svc_name,'/','',[rfReplaceAll]));
except on E:Exception do
begin
writeln('SWL: DEPENDENCY FOR '+svc_name+' DOES NOT EXIST');
end;
end;
obj.Field('svc_name').asstring:=svc_name;
writeln('SWL: REMOVE SERVICE ',fmri);
fre_destroy_service(obj);
end;
procedure _LoadZoneDbo;
begin
zone_dbo_file := '/zonedbo/zone.dbo';
zone_dbo := GFRE_DBI.CreateFromFile(zone_dbo_file);
end;
begin
InitMinimal(false);
fre_dbbase.Register_DB_Extensions;
fre_dbbusiness.Register_DB_Extensions;
fre_zfs.Register_DB_Extensions;
fre_hal_schemes.Register_DB_Extensions;
GFRE_DB.Initialize_Extension_ObjectsBuild;
{
uses /zonedbo/zone.dbo for definitions
-s : create all smf instances and deletes smf instances (sync)
-l : list all services (debug)
-t : test function (debug)
-c : creates own service (is normally in template, just for template init)
--ip=uid --start --stop : starts or stops a IP service with uid IP=uid
--routing=uid detto
--enable,disable,refresh : debug function with name same as svcadm en...,dis..
}
writeln('fossvc v0.01');
ErrorMsg:=CheckOptions('cslt',['createsvc','services','list','test','ip:','routing:','start','stop','restart','enable:','disable:','refresh:']);
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
InitIllumosLibraryHandles;
if HasOption('l','list') then
begin
svclist := fre_get_servicelist(GetOptionValue('l','list'));
writeln(svclist.DumpToString);
Terminate;
exit;
end;
if HasOption('c','createsvc') then begin
svc := TFRE_DB_SERVICE.Create;
svc.SetSvcNameandType('fos/foscfg','FirmOS Configuration Service','transient','core,signal');
svc.SetSvcEnvironment('/opt/local/fre','root','root','LANG=C');
svc.SetSvcStart('/opt/local/fre/bin/fossvc --services',60);
svc.SetSvcStop (':kill',60);
svc.AddSvcDependency('datalink-management','svc:/network/datalink-management','require_all','none');
svc.AddSvcDependency('ip-management','svc:/network/ip-interface-management','require_all','none');
svc.AddSvcDependency('loopback','svc:/network/loopback','require_all','none');
fre_create_service(svc);
svc := TFRE_DB_SERVICE.Create;
svc.SetSvcNameandType('fos/fosip','FirmOS IP Setup Ready','transient','core,signal');
svc.SetSvcStart(':true',3); { no start method }
svc.SetSvcStop (':true',3); { no stop method }
svc.AddSvcDependency('foscfg','svc:/fos/foscfg','require_all','none');
svc.AddSvcDependent ('fosip','svc:/milestone/network','require_all','none');
fre_create_service(svc);
Terminate;
Exit;
end;
if HasOption('s','services') then
begin
_LoadZoneDBo;
svclist := fre_get_servicelist('fos_');
try
zone_dbo.ForAllObjects(@CheckServices);
svclist.ForAllObjects(@_DeleteService);
finally
svclist.Finalize;
end;
fre_remove_invalid_dependencies('fos/fosip');
fre_refresh_service('fos/fosip');
fre_refresh_service('milestone/network');
Terminate;
halt(0);
end;
if HasOption('*','ip') or HasOption('*','routing') then
begin
_LoadZoneDBO;
if HasOption('*','ip') then
uid_string := GetOptionValue('*','ip')
else
uid_string := GetOptionValue('*','routing');
if uid_string='' then
raise Exception.Create('No UID for ip option set!');
uid.SetFromHexString(uid_string);
if not zone_dbo.FetchObjByUID(uid,foundobj) then
raise Exception.Create('UID not found for this zone!');
if TryToChangeServiceState(foundobj) then
begin
Terminate;
halt(0);
end
else
begin
Terminate;
halt(1);
end;
end;
if HasOption('t','test') then
begin
fre_remove_dependency('fos/fosip',StringReplace('fos/fosip_cpe0_6761c387e535e2f221106b9776cff2d1','/','',[rfReplaceAll]));
Terminate;
Exit;
svc := TFRE_DB_SERVICE.Create;
svc.SetSvcNameandType('fos/test','Exim Mailservice (MTA)','child','core,signal');
svc.SetSvcEnvironment('/','mail','mail','LANG=C');
svc.SetSvcStart('/opt/local/sbin/exim -C /opt/local/etc/exim/configure -bdf',60);
svc.SetSvcStop (':kill',60);
// svc.AddSvcDependency('network','svc:/milestone/network:default','require_all','error');
// svc.AddSvcDependency('filesystem','svc:/system/filesystem/local','require_all','error');
svc.AddSvcDependent ('fostest','svc:/milestone/network','optional_all','none');
fre_create_service(svc);
Terminate;
Exit;
// readln;
// fre_destroy_service(svc);
end;
if HasOption('*','enable') then
begin
svc_name := GetOptionValue('*','enable');
fre_enable_or_disable_service(svc_name,true);
Terminate;
Exit;
end;
if HasOption('*','disable') then
begin
svc_name := GetOptionValue('*','disable');
fre_enable_or_disable_service(svc_name,false);
Terminate;
Exit;
end;
if HasOption('*','refresh') then
begin
svc_name := GetOptionValue('*','refresh');
fre_refresh_service(svc_name);
Terminate;
Exit;
end;
// stop program loop
Terminate;
end;
constructor TFRE_fossvc.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TFRE_fossvc.Destroy;
begin
inherited Destroy;
end;
procedure TFRE_fossvc.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ',ExeName,' -h');
end;
var
Application: TFRE_fossvc;
begin
Application:=TFRE_fossvc.Create(nil);
Application.Run;
Application.Free;
end.
|
unit SearchExpr;
interface
uses Classes, SysUtils;
const
MaxStack = 100;
MaxExprTokens = 100;
MaxPrecedence = 6;
NoPrecedence = 1;
WildMatchChar = '*';
// search expression token flags
setfNotSearch = $0001; // flag set in token if search should be "negative" search
setfLikeSearch = $0002; // flag set in token if search should be a "likeness" search (soundex)
setfStemSearch = $0004; // flag set in token if search should be a "word stem" search (xyz*)
type
TSchExprPrecedence = 1..MaxPrecedence;
TSchExprTokenKind = (tkWord, tkPhrase, tkFlagOp, tkUnaryOp, tkBinaryOp, tkLeftparen, tkRightparen, tkEndExpression);
TSchExprToken =
record
Text : String;
Kind : TSchExprTokenKind;
Code : Integer;
Priority : TSchExprPrecedence;
Flags : Word;
UserData : Pointer;
end;
TSchExprTokens = array of TSchExprToken;
TSchExprValue = Pointer;
ISchExprValueManager = interface
function CreateValue(var T : TSchExprToken) : TSchExprValue;
function GetSimpleResult(var T : TSchExprToken) : TSchExprValue;
function GetUnaryOpResult(var T : TSchExprToken; const X : TSchExprValue) : TSchExprValue;
function GetBinaryOpResult(var T : TSchExprToken; const X, Y : TSchExprValue) : TSchExprValue;
procedure DisposeValue(const AValue : TSchExprValue);
end;
TSearchExpression = class(TObject)
protected
FValueMgr : ISchExprValueManager;
FImplicitOp : String;
FUnsupportedOps : TStringList;
FInputString : String;
FInfixExpr : TSchExprTokens;
FPostfixExpr : TSchExprTokens;
FExprResult : TSchExprValue;
FOperandsOnly : TStringList;
function IsOperator(const AWord : String; var Token : TSchExprToken) : Boolean; virtual;
procedure ScanInfix; virtual;
procedure CreatePostfix; virtual;
procedure RaiseException(const ACode, APos : Cardinal); virtual;
procedure SetExpression(const AExpr : String); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Execute; virtual;
procedure DisposeResult; virtual;
property Infix : TSchExprTokens read FInfixExpr;
property Postfix : TSchExprTokens read FPostfixExpr;
property Result : TSchExprValue read FExprResult;
property Expression : String read FInputString write SetExpression;
property ValueManager : ISchExprValueManager read FValueMgr write FValueMgr;
property UnsupportedOps : TStringList read FUnsupportedOps;
property ImplicitOp : String read FImplicitOp write FImplicitOp;
property HighlightList : TStringList read FOperandsOnly;
end;
const
tcLeftParen = 2; // should always be equal to 2
tcRightParen = 3; // should always be equal to 3
tcNot = 10;
tcLike = 11;
tcAnd = 12;
tcOr = 13;
tcNear = 14;
implementation
uses IslUtils, StUtils;
const
ecMismatchedParen = 1;
ecIncompleteExpr = 2;
ecBinOpIllegalPos = 3;
ecBinOpExpected = 4;
ecOpFollowsOp = 5;
ecUnrecogSymbol = 6;
ecWrongExpr = 7;
ecBinOpOrParenExp = 8;
ecNoLeftParen = 9;
ecStackOverflow = 10;
ecStackEmpty = 11;
ecCalcError = 12;
ecParmsOverflow = 13;
ecImplicitOpNotFound = 14;
ecFlagOpTokenNotFound = 15;
resourcestring
rsExpressionErrorPrefix = 'Search expression error:';
rsMismatchedParen = 'mismatched parenthesis';
rsIncompleteExpr = 'incomplete expression';
rsBinOpIllegalPos = 'binary operator found in an illegal position';
rsBinOpExpected = 'binary operator expected';
rsOpFollowsOp = 'operator can not follow another operator';
rsUnrecogSymbol = 'unrecognized symbol';
rsWrongExpr = 'invalid expression';
rsBinOpOrParenExp = 'binary operator or parenthesis expected';
rsNoLeftParen = 'no left parenthesis found';
rsStackOverflow = 'stack overflow';
rsStackEmpty = 'stack is empty';
rsCalcError = 'expression calculation error (items still on stack)';
rsParmsOverflow = 'parameters overflow';
rsImplicitOpNotFound = 'implicit operator not found';
rsOperatorNotSupport = '"%s" is not supported at this time';
rsFlagOpTokenNotFound = 'no token found to apply flag to';
constructor TSearchExpression.Create;
begin
inherited Create;
FOperandsOnly := TStringList.Create;
FOperandsOnly.Sorted := True;
FOperandsOnly.Duplicates := dupIgnore;
FUnsupportedOps := TStringList.Create;
FUnsupportedOps.Sorted := True;
FUnsupportedOps.Duplicates := dupIgnore;
FImplicitOp := 'and';
end;
destructor TSearchExpression.Destroy;
begin
DisposeResult;
FUnsupportedOps.Free;
FOperandsOnly.Free;
inherited Destroy;
end;
function TSearchExpression.IsOperator(const AWord : String; var Token : TSchExprToken) : Boolean;
var
TokenId : Integer;
procedure SetTokenValues(const AKind : TSchExprTokenKind; ACode, APriority : Integer);
begin
Token.Kind := AKind; Token.Code := ACode; Token.Priority := APriority;
end;
begin
if FUnsupportedOps.IndexOf(AWord) <> -1 then
raise Exception.CreateFmt(rsOperatorNotSupport, [AWord]);
TokenId := FindString(AWord, ['and', 'or', 'not', 'like', 'near', '(', ')']);
Token.Text := AWord;
if TokenId = -1 then begin
Token.Kind := tkWord;
if AWord[Length(AWord)] = '*' then begin
SetFlag(Token.Flags, setfStemSearch);
Delete(Token.Text, Length(Token.Text), 1);
end;
Result := False;
end else begin
Result := True;
case TokenId of
0 : SetTokenValues(tkBinaryOp, tcAnd, 4);
1 : SetTokenValues(tkBinaryOp, tcOr, 3);
//2 : SetTokenValues(tkUnaryOp, tcNot, 6);
2 : begin SetTokenValues(tkFlagOp, tcNot, 6); Token.Flags := setfNotSearch; end;
3 : begin SetTokenValues(tkFlagOp, tcLike, 6); Token.Flags := setfLikeSearch; end;
4 : SetTokenValues(tkBinaryOp, tcNear, 5);
5 : SetTokenValues(tkLeftParen, tcLeftParen, NoPrecedence);
6 : SetTokenValues(tkRightparen, tcRightParen, NoPrecedence);
end;
end;
end;
procedure TSearchExpression.DisposeResult;
begin
if FValueMgr <> Nil then
FValueMgr.DisposeValue(FExprResult);
FExprResult := Nil;
end;
procedure TSearchExpression.RaiseException(const ACode, APos : Cardinal);
var
Msg : String;
begin
case ACode of
ecMismatchedParen : Msg := rsMismatchedParen;
ecIncompleteExpr : Msg := rsIncompleteExpr;
ecBinOpIllegalPos : Msg := rsBinOpIllegalPos;
ecBinOpExpected : Msg := rsBinOpExpected;
ecOpFollowsOp : Msg := rsOpFollowsOp;
ecUnrecogSymbol : Msg := rsUnrecogSymbol;
ecWrongExpr : Msg := rsWrongExpr;
ecBinOpOrParenExp : Msg := rsBinOpOrParenExp;
ecNoLeftParen : Msg := rsNoLeftParen;
ecStackOverflow : Msg := rsStackOverflow;
ecStackEmpty : Msg := rsStackEmpty;
ecCalcError : Msg := rsCalcError;
ecParmsOverflow : Msg := rsParmsOverflow;
ecImplicitOpNotFound : Msg := rsImplicitOpNotFound;
ecFlagOpTokenNotFound : Msg := rsFlagOpTokenNotFound;
else
Msg := 'Unknown code ' + IntToStr(ACode);
end;
raise Exception.CreateFmt('%s %s (%d)', [rsExpressionErrorPrefix, Msg, APos]);
end;
procedure TSearchExpression.ScanInfix;
const
Whitespace = [' ', #9];
WordChars = ['A'..'Z', 'a'..'z', '0'..'9', '*'];
QuoteChars = ['"'];
var
I, J, ExprLen : Integer; // current size of stack
ParenCount : Integer; // parenthesis level
StringLimit : Integer; // length of string to parse
Position : Integer; // current index into string to parse
ImplicitOperator : TSchExprToken; // when no operator found between words, this is it
TokenToFlagFound : Boolean;
procedure PutInfix(var T : TSchExprToken);
// push a token onto the Infix stack
begin
ExprLen := ExprLen+1;
FInfixExpr[ExprLen] := T;
end;
function Leading : Boolean;
// True if another token is expected after current one is parsed
begin
if ExprLen = 0 then
Result := False
else
Result := FInfixExpr[ExprLen].Kind in [tkFlagOp, tkUnaryOp, tkBinaryOp, tkLeftparen];
end;
procedure ReadToken;
var
ExprWord : String;
Token : TSchExprToken;
begin
ExprWord := ''; // clear the variable name string
while (Position <= StringLimit) and (FInputString[Position] in WordChars) do begin
ExprWord := ExprWord + FInputString[Position];
Position := Position+1;
end;
FillChar(Token, SizeOf(Token), 0);
if IsOperator(ExprWord, Token) then begin
// if the previous token is another word, add an implicit operator
if (ExprLen >= 0) and (Token.Kind in [tkFlagOp, tkUnaryOp]) then begin
if (FInfixExpr[ExprLen].Kind in [tkWord, tkPhrase]) then
PutInfix(ImplicitOperator);
end;
if Leading then begin // are we expecting something?
if Token.Kind = tkBinaryOp then
RaiseException(ecBinOpIllegalPos, Position)
else // got it, stack it
PutInfix(Token);
end else if not (Token.Kind in [tkFlagOp, tkUnaryOp, tkBinaryOp]) then // expecting something, not found
RaiseException(ecBinOpExpected, Position)
else
PutInfix(Token); // got it, stack it
end else begin
// if the previous token is another word, add an implicit operator
if ExprLen >= 0 then begin
if (FInfixExpr[ExprLen].Kind in [tkWord, tkPhrase]) then
PutInfix(ImplicitOperator);
end;
PutInfix(Token); // stack the new word
FOperandsOnly.Add(Token.Text);
end;
end;
procedure ReadSymbol;
// look for a symbol (+, -, /, etc.)
var
Token : TSchExprToken;
begin
FillChar(Token, SizeOf(Token), 0);
if IsOperator(FInputString[Position], Token) then begin
if Leading then begin
if Token.Kind = tkRightParen then // don't want a right parenthesis
RaiseException(ecWrongExpr, Position)
else
PutInfix(Token); // everything ok, stack operator
end else begin
if Token.Kind in [tkRightParen, tkBinaryOp] then
PutInfix(Token)
else
RaiseException(ecBinOpOrParenExp, Position);
end;
end else
RaiseException(ecUnrecogSymbol, Position);
if Token.Kind = tkLeftParen then // check for matching parenthesis
ParenCount := ParenCount + 1
else if Token.Kind = tkRightParen then begin
ParenCount := ParenCount - 1;
if ParenCount < 0 then
RaiseException(ecNoLeftParen, Position);
end;
Position := Position + 1;
end;
begin
FInputString := FInputString + ' ';
StringLimit := Length(FInputString);
SetLength(FInfixExpr, MaxExprTokens);
FOperandsOnly.Clear;
FillChar(ImplicitOperator, SizeOf(ImplicitOperator), 0);
if not IsOperator(FImplicitOp, ImplicitOperator) then
RaiseException(ecImplicitOpNotFound, 0);
ExprLen := -1; // nothing in the stack
ParenCount := 0; // no parenthesis yet
Position := 1; // begin at first character of input string
while Position <= StringLimit do begin
if FInputString[Position] in Whitespace then
Position := Position + 1
else if FInputString[Position] in WordChars then
ReadToken
else
ReadSymbol;
end;
if (ParenCount <> 0) or (Leading) then begin // check parenthesis count
if ParenCount <> 0 then
RaiseException(ecMismatchedParen, Position);
if Leading then
RaiseException(ecIncompleteExpr, Position);
end;
SetLength(FInfixExpr, ExprLen+1);
// flagOps apply flags to the token next to them, so apply the flags now
// -- then, we can just ignore Flag token when it appears the CreatePostfix method
for I := 0 to High(FInfixExpr) do begin
if FInfixExpr[I].Kind = tkFlagOp then begin
TokenToFlagFound := False;
if I < High(FInfixExpr) then begin
for J := Succ(I) to High(FInfixExpr) do begin
if FInfixExpr[J].Kind in [tkWord, tkPhrase] then begin
FInfixExpr[J].Flags := FInfixExpr[J].Flags or FInfixExpr[I].Flags;
TokenToFlagFound := True;
break;
end;
end;
end;
if not TokenToFlagFound then
RaiseException(ecFlagOpTokenNotFound, I);
end;
end;
end;
procedure TSearchExpression.CreatePostfix;
var
InfixIndex, // index to Infix stack
PostIndex : Integer; // index to Postfix stack
InfixLen : Integer; // the length of the infix stack
T, X : TSchExprToken; // temporary token variables
EndRight : Boolean;
TStackIdx : Integer; // token stack index
TokenStack : TSchExprTokens; // actual token stack
procedure GetInfix(var T : TSchExprToken);
// pop infix token from infix stack
begin
if InfixIndex < InfixLen then begin
T := FInfixExpr[InfixIndex];
Inc(InfixIndex);
end else
RaiseException(ecParmsOverflow, 0)
end;
procedure PutToken(T : TSchExprToken);
// push postfix token onto postfix stack
begin
PostIndex := PostIndex+1;
FPostFixExpr[PostIndex] := T;
end;
procedure PushToken(T : TSchExprToken);
// push a token onto the token stack
begin
if TStackIdx < MaxStack then begin
TStackIdx := TStackIdx + 1;
TokenStack[TStackIdx] := T;
end else
RaiseException(ecStackOverflow, 0)
end;
procedure PopToken(var T : TSchExprToken);
// pop a token from the token stack
begin
if TStackIdx < 0 then
RaiseException(ecStackEmpty, 0)
else begin
T := TokenStack[TStackIdx];
TStackIdx := TStackIdx - 1;
end;
end;
begin
SetLength(TokenStack, MaxStack);
SetLength(FPostfixExpr, MaxExprTokens);
InfixIndex := 0; // starting infix index
InfixLen := Length(FInfixExpr); // the length of the infix stack
PostIndex := -1; // no elements in postfix stack
TStackIdx := -1; // no tokens in token stack
while InfixIndex < InfixLen do begin
GetInfix(T); // read a token
case T.Kind of
tkWord, tkPhrase : // operand, just stack it
PutToken(T);
tkLeftparen : // left parenthesis, stack name
PushToken(T);
tkRightparen : // pop till left paren found
begin
PopToken(T); // get a token
while T.Kind <> tkLeftParen do begin
PutToken(T); // put it into the postfix stack
PopToken(T); // get the next token
end;
end;
tkFlagOp : ; // just ignore it, we've taken care of it in ScanInfix
tkUnaryOp, tkBinaryOp :
begin
repeat
if TStackIdx = -1 then // no tokens are available
EndRight := True
else begin
if TokenStack[TStackIdx].Kind = tkLeftParen then
EndRight := True
else begin
if TokenStack[TStackIdx].Priority < T.Priority then
EndRight := True
else if (TokenStack[TStackIdx].Priority = T.Priority) and (T.Priority = MaxPrecedence) then
EndRight := True
else begin
EndRight := False;
PopToken(X); // get token from token stack
PutToken(X); // put it into the postfix stack
end;
end;
end;
until EndRight;
PushToken(T);
end;
end;
end;
while TStackIdx >= 0 do begin
PopToken(X);
PutToken(X);
end;
SetLength(FPostfixExpr, PostIndex+1);
end;
procedure TSearchExpression.Execute;
var
PostIndex : Integer; // index into postfix stack
PostLen : Integer;
X, Y : TSchExprValue; // used for temporary value storage
T : TSchExprToken; // current token
NStackIdx : Integer; // index into stack of values
Stack : array of TSchExprValue; // stack of values
procedure GetToken(var T : TSchExprToken);
// pop token from postfix stack
begin
if PostIndex < PostLen then begin
T := FPostFixExpr[PostIndex];
Inc(PostIndex);;
end else
RaiseException(ecParmsOverflow, 0)
end;
procedure Push(const V : TSchExprValue);
// push value onto value stack
begin
if NStackIdx > MaxStack then
RaiseException(ecStackOverflow, 0)
else begin
NStackIdx := NStackIdx + 1;
Stack[NStackIdx] := V;
end;
end;
procedure Pop(var V : TSchExprValue);
// pop value from value stack
begin
if NStackIdx < 0 then
RaiseException(ecStackEmpty, 0)
else begin
V := Stack[NStackIdx];
NStackIdx := NStackIdx - 1;
end;
end;
begin
Assert(FValueMgr <> Nil, 'ValueManager property not assigned');
SetLength(Stack, MaxStack);
PostIndex := 0; // start at first postfix location
PostLen := Length(FPostfixExpr); // the number of tokens in the postfix
NStackIdx := -1; // no values are stacked yet
if PostLen = 1 then begin
FExprResult := FValueMgr.GetSimpleResult(FPostfixExpr[0]);
Exit;
end;
while PostIndex < PostLen do begin
GetToken(T);
case T.Kind of
tkWord, tkPhrase :
Push(FValueMgr.CreateValue(T));
tkUnaryOp :
begin
Pop(X);
Push(FValueMgr.GetUnaryOpResult(T, X));
FValueMgr.DisposeValue(X);
end;
tkBinaryOp :
begin
Pop(Y);
Pop(X);
Push(FValueMgr.GetBinaryOpResult(T, X, Y));
FValueMgr.DisposeValue(X);
FValueMgr.DisposeValue(Y);
end;
end;
end;
if NStackIdx = 0 then
Pop(FExprResult)
else
RaiseException(ecCalcError, 0);
end;
procedure TSearchExpression.SetExpression(const AExpr : String);
begin
FInputString := AExpr;
ScanInfix;
CreatePostfix;
end;
end.
|
unit Common;
interface
uses
SysUtils, ActiveX, Winsock, Classes;
type
StringArray = array of string;
function Split(const Source: string; ASplit: string): StringArray;
function SplitToStringList(const Source: string; ASplit: string): TStrings; overload;
function SplitToStringList(const Source: string; ASplit: string; Strings: TStrings): TStrings; overload;
function toArr(const Source: string): StringArray; //字符串变为一个数组
function StrToUniCode(text: string): string;
function UnicodeToStr(text: string): string;
procedure CompletStr(var text: string; Lengths: Integer); // 用0填充text为指定长度
function CheckNum(const V: string): Boolean; //验证是否是数子
function CreateOnlyId: string; //产生唯一序列号
function CompletWeight(text: string; LengthInt, LengthFloat: Integer): string; //格式化重量输出
function GetIPAddr: string; //获取ip地址
function FormatDouble(Source: Double; Format: string): Double; //四舍五入数字
function RandomStr(): string; //随机取得4位a到z之间字符串
implementation
function FormatDouble(Source: Double; Format: string): Double;
var
Temp: string;
begin
Temp := FormatFloat(Format, Source);
Result := StrtoFloat(Temp);
end;
function Split(const Source: string; ASplit: string): StringArray;
var
AStr: string;
rArray: StringArray;
I: Integer;
begin
if Source = '' then
Exit;
AStr := Source;
I := pos(ASplit, Source);
Setlength(rArray, 0);
while I <> 0 do
begin
Setlength(rArray, Length(rArray) + 1);
rArray[Length(rArray) - 1] := copy(AStr, 0, I - 1);
Delete(AStr, 1, I + Length(ASplit) - 1);
I := pos(ASplit, AStr);
end;
Setlength(rArray, Length(rArray) + 1);
rArray[Length(rArray) - 1] := AStr;
Result := rArray;
end;
function SplitToStringList(const Source: string; ASplit: string): TStrings;
var
rArray: StringArray;
Roles: TStrings;
I: Integer;
begin
rArray := Split(Source, ASplit);
Roles := TStringList.Create;
for I := 0 to Length(rArray) - 1 do
begin
if rArray[I] = '' then Continue;
if Roles.IndexOf(rArray[I]) = -1 then
Roles.Add(rArray[I]);
end;
Result := Roles;
end;
function SplitToStringList(const Source: string; ASplit: string; Strings: TStrings): TStrings;
var
rArray: StringArray;
I: Integer;
begin
rArray := Split(Source, ASplit);
for I := 0 to Length(rArray) - 1 do
begin
Strings.Add(rArray[I]);
end;
Result := Strings;
end;
function StrToUniCode(text: string): string;
var
I, len: Integer;
cur: Integer;
t: string;
ws: WideString;
begin
Result := '';
ws := text;
len := Length(ws);
I := 1;
Result := 'U';
while I <= len do
begin
cur := Ord(ws[I]);
FmtStr(t, '%4.4X', [cur]);
Result := Result + t;
if I <> len then
Result := Result + ' U';
Inc(I);
end;
end;
// 恢复
function UnicodeToStr(text: string): string;
var
I, len: Integer;
ws: WideString;
begin
ws := '';
I := 1;
len := Length(text);
while I < len do
begin
ws := ws + Widechar(StrToInt('$' + copy(text, I, 4)));
I := I + 4;
end;
Result := ws;
end;
procedure CompletStr(var text: string; Lengths: Integer); // 用0填充text为指定长度
var
L, I: Integer;
begin
L := Lengths - Length(text);
for I := 0 to L - 1 do
begin
text := '0' + text;
end;
end;
function CreateOnlyId: string; //产生唯一序列号
var
AGuid: TGuid;
begin
if CoCreateGuid(AGuid) = s_OK then begin
Result := Split(Split(GUIDToString(AGuid), '{')[1], '}')[0];
end;
end;
function CheckNum(const V: string): Boolean;
var
Temp: Double;
begin
Result := false;
try
Temp := StrtoFloat(V);
Result := true;
except
end;
end;
function CompletWeight(text: string; LengthInt, LengthFloat: Integer): string; //格式化重量输出
var
SA: StringArray;
L, I: Integer;
begin
SA := Split(text, '.');
L := LengthInt - Length(SA[0]);
text := SA[0];
for I := 0 to L - 1 do
begin
text := '0' + text;
end;
text := text + '.';
if Length(SA) = 2 then
begin
L := LengthFloat - Length(SA[1]);
text := text + SA[1];
end
else
begin
L := LengthFloat;
end;
for I := 0 to L - 1 do
begin
text := text + '0';
end;
Result := text;
end;
function toArr(const Source: string): StringArray; //字符串变为一个数组
var
rArray: StringArray;
I: Integer;
begin
for I := 1 to Length(Source) do
begin
SetLength(rArray, Length(rArray) + 1);
rArray[Length(rArray) - 1] := Copy(Source, I, 1);
end;
Result := rArray;
end;
function GetIPAddr: string; //获取ip地址
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: array[0..63] of char;
I: Integer;
GInitData: TWSADATA;
begin
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
I := 0;
while pptr^[I] <> nil do begin
result := StrPas(inet_ntoa(pptr^[I]^));
Inc(I);
end;
WSACleanup;
end;
function RandomStr(): string;
var
PicName: string;
I: Integer;
begin
Randomize;
for I := 1 to 4 do
PicName := PicName + chr(97 + random(26));
RandomStr := PicName;
end;
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 182638
////////////////////////////////////////////////////////////////////////////////
unit android.widget.NumberPicker_OnScrollListener;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.widget.NumberPicker;
type
JNumberPicker_OnScrollListener = interface;
JNumberPicker_OnScrollListenerClass = interface(JObjectClass)
['{0878BE5D-49A1-4DB7-A076-132C9735037E}']
function _GetSCROLL_STATE_FLING : Integer; cdecl; // A: $19
function _GetSCROLL_STATE_IDLE : Integer; cdecl; // A: $19
function _GetSCROLL_STATE_TOUCH_SCROLL : Integer; cdecl; // A: $19
procedure onScrollStateChange(JNumberPickerparam0 : JNumberPicker; Integerparam1 : Integer) ; cdecl;// (Landroid/widget/NumberPicker;I)V A: $401
property SCROLL_STATE_FLING : Integer read _GetSCROLL_STATE_FLING; // I A: $19
property SCROLL_STATE_IDLE : Integer read _GetSCROLL_STATE_IDLE; // I A: $19
property SCROLL_STATE_TOUCH_SCROLL : Integer read _GetSCROLL_STATE_TOUCH_SCROLL;// I A: $19
end;
[JavaSignature('android/widget/NumberPicker_OnScrollListener')]
JNumberPicker_OnScrollListener = interface(JObject)
['{A87A8A34-45A3-4043-BD3B-AA022FB20AD3}']
procedure onScrollStateChange(JNumberPickerparam0 : JNumberPicker; Integerparam1 : Integer) ; cdecl;// (Landroid/widget/NumberPicker;I)V A: $401
end;
TJNumberPicker_OnScrollListener = class(TJavaGenericImport<JNumberPicker_OnScrollListenerClass, JNumberPicker_OnScrollListener>)
end;
const
TJNumberPicker_OnScrollListenerSCROLL_STATE_IDLE = 0;
TJNumberPicker_OnScrollListenerSCROLL_STATE_TOUCH_SCROLL = 1;
TJNumberPicker_OnScrollListenerSCROLL_STATE_FLING = 2;
implementation
end.
|
unit uDigitConverter;
{$I ..\Include\IntXLib.inc}
interface
uses
SysUtils,
uStrings,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Converts <see cref="TIntX"/> digits to/from byte array.
/// </summary>
TDigitConverter = class sealed(TObject)
public
/// <summary>
/// Converts big integer digits to bytes.
/// </summary>
/// <param name="digits"><see cref="TIntX" /> digits.</param>
/// <returns>Resulting bytes.</returns>
/// <remarks>
/// Digits can be obtained using <see cref="TIntX.GetInternalState(TIntXLibUInt32Array,Boolean,Boolean)" /> method.
/// </remarks>
/// <exception cref="EArgumentNilException"><paramref name="digits" /> is a null reference.</exception>
class function ToBytes(digits: TIntXLibUInt32Array): TBytes; static;
/// <summary>
/// Converts bytes to big integer digits.
/// </summary>
/// <param name="bytes">Bytes.</param>
/// <returns>Resulting <see cref="TIntX" /> digits.</returns>
/// <remarks>
/// Big integer can be created from digits using <see cref="TIntX.Create(TIntXLibUInt32Array,Boolean)" /> constructor.
/// </remarks>
/// <exception cref="EArgumentNilException"><paramref name="bytes" /> is a null reference.</exception>
class function FromBytes(bytes: TBytes): TIntXLibUInt32Array; static;
end;
implementation
class function TDigitConverter.ToBytes(digits: TIntXLibUInt32Array): TBytes;
begin
if (digits = Nil) then
begin
raise EArgumentNilException.Create('digits');
end;
SetLength(result, (Length(digits) * 4));
Move(digits[0], result[0], Length(result) * SizeOf(UInt32));
end;
class function TDigitConverter.FromBytes(bytes: TBytes): TIntXLibUInt32Array;
begin
if (bytes = Nil) then
begin
raise EArgumentNilException.Create('bytes');
end;
if (Length(bytes) mod 4 <> 0) then
begin
raise EArgumentException.Create(uStrings.DigitBytesLengthInvalid +
' bytes');
end;
SetLength(result, (Length(bytes) div 4));
Move(bytes[0], result[0], Length(bytes) * SizeOf(Byte));
end;
end.
|
unit DXPSelect;
interface
uses
Classes, Controls, StdCtrls, ExtCtrls, DB, DBClient, SysUtils, DXPSelectBrowser,
Windows, Graphics, Messages, CommCtrl, Forms, DXPEdit, DXPMaskEdit;
type
TDXPSelect = class(TCustomButtonedEdit)
private
FBaseColor: TColor;
FSelectBrowser: TFrmDXPSelectBrowser;
FDataSource: TDataSource;
FEdit: TCustomEdit;
FFieldCaption: string;
FFieldKey: string;
FKey: string;
FKeyValue: string;
FImageList: TImageList;
FOnOpenDataSet: TNotifyEvent;
FOnSelect: TNotifyEvent;
FOnClearEdits: TNotifyEvent;
FReadOnly: boolean;
procedure SetReadOnly(const Value: boolean);
//
property Images;
//
procedure SetDataSource(const Value: TDataSource);
//
procedure OnRightClick(Sender: TObject);
procedure OnSelectExit(Sender: TObject);
procedure OnEditExit(Sender: TObject);
procedure OnSelectKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure OnSelectKeyPress(Sender: TObject; var Key: Char);
//
procedure SearchByCaption;
procedure ShowSelectBrowser;
procedure Select(Sender: TObject);
procedure ClearEdits(Sender: TObject);
{ Private declarations }
protected
procedure DoEnter; override;
procedure DoExit; override;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ExitKey(Sender: TObject);
property KeyValue: string read FKeyValue write FKeyValue;
{ Public declarations }
published
property OnOpenDataSet: TNotifyEvent read FOnOpenDataSet write FOnOpenDataSet;
property OnSelect: TNotifyEvent read FOnSelect write FOnSelect;
property OnClearEdits: TNotifyEvent read FOnClearEdits write FOnClearEdits;
//
property FieldCaption: string read FFieldCaption write FFieldCaption;
property FieldKey: string read FFieldKey write FFieldKey;
property Key: string read FKey write FKey;
property DataSource: TDataSource read FDataSource write SetDataSource;
property Edit: TCustomEdit read FEdit write FEdit;
//
property Align;
property Alignment;
property Anchors;
property AutoSelect;
property AutoSize;
property BevelEdges;
property BevelInner;
property BevelKind default bkNone;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property Ctl3D;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property ImeMode;
property ImeName;
property LeftButton;
property MaxLength;
property OEMConvert;
property NumbersOnly;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly: boolean read FReadOnly write SetReadOnly default false;
property RightButton;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property TextHint;
property Touch;
property Visible;
property OnChange;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnGesture;
property OnLeftButtonClick;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnRightButtonClick;
property OnStartDock;
property OnStartDrag;
{ Published declarations }
end;
implementation
uses udmRepository;
{ TDXPSelect }
procedure TDXPSelect.ClearEdits(Sender: TObject);
begin
FEdit.Clear;
Self.Clear;
if Assigned( FOnClearEdits ) then
FOnClearEdits( Sender );
end;
constructor TDXPSelect.Create(AOwner: TComponent);
var
Repository: TdmRepository;
begin
inherited Create( AOwner );
//
FImageList := TImageList.Create( Self );
//
Repository := TdmRepository.Create( nil );
//
try
FImageList.AddImages(Repository.imgAll);
finally
Repository.Free;
end;
//
Self.Images := FImageList;
Self.LeftButton.Visible := True;
Self.LeftButton.ImageIndex := 1;
Self.RightButton.Visible := True;
Self.RightButton.ImageIndex := 2;
//Self.TextHint := 'Selecione...';
Self.BorderStyle := bsNone;
Self.BevelKind := bkFlat;
//
Self.OnRightButtonClick := OnRightClick;
Self.OnExit := OnSelectExit;
Self.OnKeyDown := OnSelectKeyDown;
Self.OnKeyPress := OnSelectKeyPress;
//
FSelectBrowser := TFrmDXPSelectBrowser.Create( Self );
FSelectBrowser.OnSelect := Select;
end;
destructor TDXPSelect.Destroy;
begin
FSelectBrowser.Free;
FImageList.Free;
inherited;
end;
procedure TDXPSelect.ExitKey(Sender: TObject);
begin
if ( FKeyValue = '' ) then
begin
ClearEdits( Sender );
Exit;
end;
if ( FKey = '' ) then
raise Exception.Create( 'Não foi informado o field para o Id' );
//
FOnOpenDataSet(Self);
//
FDataSource.DataSet.Filtered := False;
FDataSource.DataSet.Filter := 'UPPER(' + FKey + ') = ' + QuotedStr( FKeyValue );
FDataSource.DataSet.Filtered := True;
if FDataSource.DataSet.RecordCount > 0 then
begin
if ( FFieldCaption = '' ) then
raise Exception.Create( 'Não foi informado o Field para o caption.' );
Select( Self );
Self.Text := FDataSource.DataSet.FieldByName( FFieldCaption ).AsString;
end
else
begin
FEdit.Clear;
FEdit.SetFocus;
end;
Self.DataSource.DataSet.Filtered := False;
end;
procedure TDXPSelect.DoEnter;
begin
inherited;
//
FBaseColor := Color;
Color := clInfoBk;
end;
procedure TDXPSelect.DoExit;
begin
Color := FBaseColor;
//
inherited;
end;
procedure TDXPSelect.Loaded;
begin
inherited;
FSelectBrowser.EditKey := FEdit;
FSelectBrowser.Key := FFieldKey;
FSelectBrowser.Caption := FFieldCaption;
//
if Assigned( FEdit ) and not( csDesigning in ComponentState ) then
begin
if ( FEdit is TDXPEdit ) then
( FEdit as TDXPEdit ).OnExit := OnEditExit
else if ( FEdit is TDXPMaskEdit ) then
( FEdit as TDXPMaskEdit ).OnExit := OnEditExit
end;
end;
procedure TDXPSelect.OnEditExit(Sender: TObject);
begin
if ( FEdit is TDXPEdit ) then
begin
if ( Trim( ( FEdit as TDXPEdit ).Text ) = '' ) then
Exit;
end
else if ( FEdit is TDXPMaskEdit ) then
begin
if ( Trim( ( FEdit as TDXPMaskEdit ).Text ) = '' ) then
Exit;
end;
//
if ( FFieldKey = '' ) then
raise Exception.Create( 'Não foi informado o field para o Id' );
//
FOnOpenDataSet(Self);
//
FDataSource.DataSet.Filtered := False;
if ( FEdit is TDXPEdit ) then
FDataSource.DataSet.Filter := 'UPPER(' + FFieldKey + ') = ' + QuotedStr( UpperCase(( FEdit as TDXPEdit ).Text) )
else if ( FEdit is TDXPMaskEdit ) then
FDataSource.DataSet.Filter := 'UPPER(' + FFieldKey + ') = ' + QuotedStr( UpperCase(( FEdit as TDXPMaskEdit ).Text) );
FDataSource.DataSet.Filtered := True;
if FDataSource.DataSet.RecordCount > 0 then
begin
if ( FFieldCaption = '' ) then
raise Exception.Create( 'Não foi informado o Field para o caption.' );
Select( Self );
Self.Text := FDataSource.DataSet.FieldByName( FFieldCaption ).AsString;
end
else
begin
FEdit.Clear;
FEdit.SetFocus;
end;
Self.DataSource.DataSet.Filtered := False;
end;
procedure TDXPSelect.OnSelectExit(Sender: TObject);
begin
if Self.Text <> '' then
SearchByCaption
else if FEdit.Text <> '' then
OnEditExit(Sender);
end;
procedure TDXPSelect.OnSelectKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_NEXT, VK_DOWN: ShowSelectBrowser;
end;
end;
procedure TDXPSelect.OnSelectKeyPress(Sender: TObject; var Key: Char);
begin
if Ord(Key) = 13 then
SearchByCaption;
end;
procedure TDXPSelect.OnRightClick(Sender: TObject);
begin
ShowSelectBrowser;
end;
procedure TDXPSelect.SearchByCaption;
begin
if ( FFieldCaption = '' ) then
raise Exception.Create( 'Não foi informado o Field para o caption.' );
//
FOnOpenDataSet(Self);
//
FDataSource.DataSet.Filtered := False;
FDataSource.DataSet.Filter := 'UPPER(' + FFieldCaption + ') LIKE ' + QuotedStr('%' + UpperCase(Self.Text) + '%');
FDataSource.DataSet.Filtered := True;
if FDataSource.DataSet.RecordCount > 1 then
FSelectBrowser.ShowBrowser
else
begin
if ( FFieldKey = '' ) then
raise Exception.Create( 'Não foi informado o field para o Id' );
Select( Self );
Self.Text := FDataSource.DataSet.FieldByName( FFieldCaption ).AsString;
end;
end;
procedure TDXPSelect.Select(Sender: TObject);
begin
if ( FEdit is TDXPEdit ) then
( FEdit as TDXPEdit ).Text := FDataSource.DataSet.FieldByName( FFieldKey ).AsString
else if ( FEdit is TDXPMaskEdit ) then
( FEdit as TDXPMaskEdit ).Text := FDataSource.DataSet.FieldByName( FFieldKey ).AsString;
FKeyValue := FDataSource.DataSet.FieldByName( FKey ).AsString;
if ( Assigned( FOnSelect ) ) then
FOnSelect( Sender );
end;
procedure TDXPSelect.SetDataSource(const Value: TDataSource);
begin
if not( csDesigning in ComponentState ) and Assigned( Value.DataSet ) and not( Value.DataSet is TClientDataSet ) then
raise Exception.Create( 'Dataset from datasource is not a TClientDataSet' );
//
FDataSource := Value;
//
if not( csDesigning in ComponentState ) and Assigned( FDataSource ) then
FSelectBrowser.grdSelectBrowser.DataSource := FDataSource;
end;
procedure TDXPSelect.SetReadOnly(const Value: boolean);
begin
inherited ReadOnly := Value;
FReadOnly := Value;
//
if FReadOnly then
Color := clBtnFace
else
Color := clWindow;
end;
procedure TDXPSelect.ShowSelectBrowser;
begin
if not( Assigned( FDataSource ) ) then
raise Exception.Create( 'Nenhum DataSource foi ligado ao DXPSelect.' );
//
if FSelectBrowser.Visible then
FSelectBrowser.Close
else
begin
FOnOpenDataSet(Self);
FSelectBrowser.ShowBrowser;
end;
end;
end.
|
program probl_7;
uses crt;
type func=function(x: real):real;
const a=0;
b=6;
var
F: func;
S1, S2, eps: real;
s: string;
err: integer;
{$F+}
function CurrentFunction(x:real):real;
begin
CurrentFunction:=1/sqrt(1+x*x*x*x);
end;
{$F-}
procedure Integral(F: func; var S1, S2: real; a, b, eps: real);
var i, n: integer;
f1, f2: real;
begin
n:=10;
repeat
S1:=0;
S2:=0;
for i:=1 to n do
begin
f1:=F(a+(i-1)*((a+b)/n)) * ((a+b)/n);
f2:=F(a+i*((a+b)/n)) * ((a+b)/n);
S1:=S1+f1;
S2:=S2+f2;
end;
n:=n+10;
until abs(S1-S2)<eps;
end;
BEGIN
clrscr;
repeat
repeat
write('Input eps: eps>0: ');
readln(s);
val(s, eps, err);
until err=0;
until eps>0;
F:=CurrentFunction;
Integral(F, S1, S2, a, b, eps);
write((S2+S1)/2);
readkey;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit CustomizedFeatures;
interface
uses DSServerFeatures, DSServerFeatureManager;
const
// Value used in feature page
cCustomFeatureGroup = TDSServerFeature.dsCustom1;
cCustomFeatureCommentModule = TDSServerFeature.dsCustom2;
cCustomFeatureTimeStampModule = TDSServerFeature.dsCustom3;
cCustomFeatureSampleMethods = TDSServerFeature.dsCustom4;
cCustomFeatureAddFiles = TDSServerFeature.dsCustom5;
// Values used in code templates
// Boolean values
sCustomFeatureCommentModule = 'Customize_CommentModule';
sCustomFeatureTimeStamp = 'Customize_TimeStampModule';
sCustomSampleMethods = 'Customize_IncludeSampleMethods';
// Text values
sCommentModuleText = 'Customize_CommentModuleText';
sTimeStampText = 'Customize_TimeStampText';
function CustomFeatureDescriptions: TArray<TFeatureDescription>;
implementation
uses Generics.Collections;
function CustomFeatureDescriptions: TArray<TFeatureDescription>;
var
LList: TList<TFeatureDescription>;
LDescription: TFeatureDescription;
begin
LList := TList<TFeatureDescription>.Create;
try
// Add some more features
LDescription := TFeatureDescription.Create(
cCustomFeatureGroup, dsNull, 'Comments (new)', 'Add comments to modules',
[wtAll]);
LList.Add(LDescription);
LDescription := TFeatureDescription.Create(
cCustomFeatureGroup, cCustomFeatureCommentModule, 'Comment Server Container (new)', 'Add a comment to the server module',
[wtAll]);
LList.Add(LDescription);
LDescription := TFeatureDescription.Create(
cCustomFeatureGroup, cCustomFeatureTimeStampModule, 'Time Stamps (new)', 'Add a stamp to all modules',
[wtAll]);
LList.Add(LDescription);
// Uncomment to remove TCP protocol
for LDescription in DefaultFeatureDescriptions do
begin
// case LDescription.Group of
// dsProtocols:
// begin
// if LDescription.Feature = dsNull then
// LList.Add(TFeatureDescription.Create(
// LDescription.Group, LDescription.Feature,
// LDescription.Name + ' (TCP Removed)', // Change text of Protocols group
// LDescription.Description,
// LDescription.WizardTypes))
// else if LDescription.Feature <> dsTCPProtocol then // Don't add TCP to
LList.Add(LDescription);
// end;
// else
// LList.Add(LDescription);
// end;
end;
// Add to an existing group
LDescription := TFeatureDescription.Create(
dsServerMethodClass, cCustomFeatureSampleMethods, 'More sample methods (new)', 'Add CustomEchoString, CustomReverseString',
[wtAll]);
LList.Add(LDescription);
// Add new top level check box
LDescription := TFeatureDescription.Create(
dsNull, cCustomFeatureAddFiles, 'Add files to the project (new)', 'Choose some files to add to the project',
[wtWebBrokerRest]); // Note that this option is REST project only
LList.Add(LDescription);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
end.
|
unit UGlobals;
//Variables of user made types e.g. the door which uses the TE type.
//This is hard to reference as units with types in are referenced by this unit.
interface
uses
w3system, UPlat, UGameText, UE, UPlayer, UBullet, UAi, UTurret, ULevelSelector, UOptionsButton, UGlobalsNoUserTypes;
//All arrays here are dynamic, so they can be as big or small as they like
//and can change size at will.
var
Player : TPlayer; //The player
Ai : array of TAi; //the array of Ai Units
EntranceDoor : TE; //The entrance Door
ExitDoor : TE; //The Exit door
FPlats : array of TPlat; //The array of Fixed Plats
Bullets : array of TBullet; //The array of bullets
gameText : array of TText; //The array of Game Text
Options : array of TOptionsButton; //An array of the option buttons
ControlButtons : array of TOptionsButton; //An array of buttons that will move the player
//This is the mobile support as it can be click
Controls : array of TText; //A list of the controls as text elements
Turrets : array of TTurret; //The array of Turrets
Selector : ULevelSelector.TSelect; //The level selector
implementation
end.
|
unit St_sp_Hostel_Form_Add;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, cxTextEdit, cxControls,
cxContainer, cxEdit, cxGroupBox, StdCtrls, cxButtons;
type
TBuildsFormAdd = class(TForm)
OKButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
ShortEdit: TcxTextEdit;
ShortNameLabel: TcxLabel;
NameLabel: TcxLabel;
NameEdit: TcxTextEdit;
NumEdit: TcxTextEdit;
NumLabel: TcxLabel;
cxLabel1: TcxLabel;
ChiefEdit: TcxTextEdit;
SizeLabel: TcxLabel;
SizeEdit: TcxTextEdit;
FloorLabel: TcxLabel;
FloorEdit: TcxTextEdit;
cxGroupBox2: TcxGroupBox;
OblastLabel: TcxLabel;
OblastEdit: TcxTextEdit;
TownLabel: TcxLabel;
TownEdit: TcxTextEdit;
RaionLabel: TcxLabel;
RaionEdit: TcxTextEdit;
StreetLabel: TcxLabel;
StreetEdit: TcxTextEdit;
HouseLabel: TcxLabel;
HouseEdit: TcxTextEdit;
IndexLabel: TcxLabel;
IndexEdit: TcxTextEdit;
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure NumEditKeyPress(Sender: TObject; var Key: Char);
procedure ShortEditKeyPress(Sender: TObject; var Key: Char);
procedure NameEditKeyPress(Sender: TObject; var Key: Char);
procedure SizeEditKeyPress(Sender: TObject; var Key: Char);
procedure ChiefEditKeyPress(Sender: TObject; var Key: Char);
procedure FloorEditKeyPress(Sender: TObject; var Key: Char);
procedure TownEditKeyPress(Sender: TObject; var Key: Char);
procedure OblastEditKeyPress(Sender: TObject; var Key: Char);
procedure RaionEditKeyPress(Sender: TObject; var Key: Char);
procedure StreetEditKeyPress(Sender: TObject; var Key: Char);
procedure HouseEditKeyPress(Sender: TObject; var Key: Char);
procedure IndexEditKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
end;
var
BuildsFormAdd: TBuildsFormAdd;
implementation
uses Unit_of_Utilits;
{$R *.dfm}
procedure TBuildsFormAdd.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TBuildsFormAdd.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TBuildsFormAdd.FormShow(Sender: TObject);
begin
If BuildsFormAdd.cxGroupBox1.Enabled = true then NumEdit.SetFocus
else CancelButton.SetFocus;
end;
procedure TBuildsFormAdd.OKButtonClick(Sender: TObject);
begin
if not IntegerCheck(NumEdit.Text) then begin
ShowMessage('Номер общежития введен неверно.');
NumEdit.SetFocus;
exit;
end;
if ShortEdit.Text = '' then begin
ShowMessage('Необходимо ввести сокращенное название.');
ShortEdit.SetFocus;
exit;
end;
if NameEdit.Text = '' then begin
ShowMessage('Необходимо ввести название.');
NameEdit.SetFocus;
exit;
end;
if ChiefEdit.Text = '' then begin
ShowMessage('Необходимо ввести ФИО коменданта общежития.');
ChiefEdit.SetFocus;
exit;
end;
if not FloatCheck(SizeEdit.Text) then begin
ShowMessage('Площадь введена неверно.');
SizeEdit.SetFocus;
exit;
end;
if not IntegerCheck(FloorEdit.Text) then begin
ShowMessage('Количество этажей введено неверно.');
FloorEdit.SetFocus;
exit;
end;
if not IntegerCheck(IndexEdit.Text) then begin
ShowMessage('Индекс введен неверно.');
IndexEdit.SetFocus;
exit;
end;
ModalResult := mrOK;
end;
procedure TBuildsFormAdd.NumEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then ShortEdit.SetFocus;
end;
procedure TBuildsFormAdd.ShortEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then NameEdit.SetFocus;
end;
procedure TBuildsFormAdd.NameEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then ChiefEdit.SetFocus;
end;
procedure TBuildsFormAdd.SizeEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then FloorEdit.SetFocus;
end;
procedure TBuildsFormAdd.ChiefEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then SizeEdit.SetFocus;
end;
procedure TBuildsFormAdd.FloorEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then OblastEdit.SetFocus;
end;
procedure TBuildsFormAdd.TownEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then RaionEdit.SetFocus;
end;
procedure TBuildsFormAdd.OblastEditKeyPress(Sender: TObject;
var Key: Char);
begin
If Key=#13 then TownEdit.SetFocus;
end;
procedure TBuildsFormAdd.RaionEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then StreetEdit.SetFocus;
end;
procedure TBuildsFormAdd.StreetEditKeyPress(Sender: TObject;
var Key: Char);
begin
If Key=#13 then HouseEdit.SetFocus;
end;
procedure TBuildsFormAdd.HouseEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then IndexEdit.SetFocus;
end;
procedure TBuildsFormAdd.IndexEditKeyPress(Sender: TObject; var Key: Char);
begin
If Key=#13 then OkButton.SetFocus;
end;
end.
|
{---------------------------------------------------------------}
{ RSWAG-98 to RSWAG-99 Update }
{ written 2000 by Valery Votintsev 2:5021/22 }
{---------------------------------------------------------------}
{$M 64565, 0, 655000}
{$I GSF_FLAG.PAS}
PROGRAM rswag99;
uses
CRT,
gsf_shel,
gsf_glbl,
gsf_dos,
vScreen,
vMenu,
vMemo,
vString,
Reader_C,
Reader_U;
Const
UpdateName:string[7] = 'RSWAG99';
{ Include Constant 'UpdateName' with name of new patch}
UpdatePeriod: String[8] = '1999';
Var
TargetArea:byte;
AreaID: String[8];
AreaDescr: string[52];
MsgCounter:Integer;
Procedure EraseFiles(fName:string12);
begin
If GsFileExists(BaseDir+'\'+fname+'.dbf') then begin
GsFileDelete(BaseDir+'\'+fname+'.dbf');
GsFileDelete(BaseDir+'\'+fname+'.cdx');
GsFileDelete(BaseDir+'\'+fname+'.fpt');
end;
end;
Procedure RenameFiles(fName,NewName:string12);
begin
GsFileRename(BaseDir+'\'+fname+'.dbf',BaseDir+'\'+NewName+'.dbf');
GsFileRename(BaseDir+'\'+fname+'.cdx',BaseDir+'\'+NewName+'.cdx');
GsFileRename(BaseDir+'\'+fname+'.fpt',BaseDir+'\'+NewName+'.fpt');
end;
{*────────────────────────────────────────────────────────────────────*}
Procedure WriteCONFIG;
{ Used ConfigFile }
Var
Conf:Text;
ConfigBak: string;
n:byte;
Begin
Writeln('Updating Config file ...');
n:=Pos('.',ConfigFile);
ConFigBak:=Copy(ConfigFile,1,n)+'BAK';
FileCopy(ConfigFile,ConfigBak);
If not FileOpen(Conf,ConfigFile,fmOpenWrite) then begin
writeln('*** Open error of "',ConfigFile,'"');
HALT(1);
end;
Writeln(Conf,';------- RSWAG Reader Configure Parameters --------------------------');
Writeln(Conf);
Writeln(Conf,'[ Work Pathes ]');
Writeln(Conf,'BaseDir = ',BaseDir, ' // Path to DataBases');
Writeln(Conf,'ExtractDir = ',ExtractDir,' // Extract Project Directory');
Writeln(Conf,'ImportDir = ',ImportDir, ' // Import File Directory');
Writeln(Conf,'DocDir = // Document Directory');
Writeln(Conf,'ListDir = ',ListDir, ' // Path to HTML Lists');
Writeln(Conf);
Writeln(Conf,'[ Area & Msg Parameters ]');
Writeln(Conf,';AreaOrder = 0 // Not Ordered Area List (default)');
Writeln(Conf,';AreaOrder = 1 // Order Area List by DESCRIPTION');
Writeln(Conf,';AreaOrder = 2 // Order Area List by AREAID');
Writeln(Conf,'AreaOrder = ',AreaOrder:1,' // Order Area List by');
Writeln(Conf,';MsgOrder = 0 // Not Ordered Msg List (default)');
Writeln(Conf,';MsgOrder = 1 // Order Msg List by FROM');
Writeln(Conf,';MsgOrder = 2 // Order Msg List by SUBJECT');
Writeln(Conf,'MsgOrder = ',MsgOrder:1,' // Order Msg List by');
Writeln(Conf);
Writeln(Conf,';------- RSWAG to HTML Converter Configure Parameters -----------------');
Writeln(Conf,'AreaList = AREAS.LST');
Writeln(Conf,'AreaHeader = AREA.HDR');
Writeln(Conf,'AreaFooter = AREA.FTR');
Writeln(Conf,'AreaRecord = AREA.REC');
Writeln(Conf,'IndexHeader = INDEX.HDR');
Writeln(Conf,'IndexFooter = INDEX.FTR');
Writeln(Conf,'IndexRecord = INDEX.REC');
Writeln(Conf,'MsgHeader = BODY.HDR');
Writeln(Conf,'MsgFooter = BODY.FTR');
Writeln(Conf,'Snipets = 25 // Snipets Per Page');
Writeln(Conf);
Writeln(Conf,'LastUpdate = ',Lastupdate,' // Last updated by putch "PATCHNAME" (w/o .ext)');
FileClose(Conf);
Writeln(' Ok.');
end;
{*────────────────────────────────────────────────────────────────────*}
{var x,y:integer;}
BEGIN
SetPublicVar('READER.INI'); {Initialize Variables}
MsgCounter:=0;
SetColor('W/N');
Writeln('------------',UpdateName,'---------------');
Writeln('Russian SWAG update of ',UpdatePeriod);
Writeln('written 1999-2000 by Valery Votintsev ');
Writeln(' (2:5021/22)');
Writeln;
If CheckWorkPath then begin
Writeln('Updating current RSWAG bases with "'+UpdateName+'"');
If (not GsFileExists(UpdateName+'.dbf')) and
(not GsFileExists(UpdateName+'.fpt')) then begin
SetColor('W+/N');
Write('Error: ');
SetColor('W/N');
Writeln('Update files "'+UpdateName+'.*" not found!');
end else begin
If (Upper(UpdateName)=Upper(LastUpdate)) then begin
SetColor('W+/N');
Write('Error: ');
SetColor('W/N');
Writeln('"',UpdateName,'" update allready used!');
end else begin
FileCopy(UpdateName+'.dbf',BaseDir+'\'+UpdateName+'.dbf');
FileCopy(UpdateName+'.fpt',BaseDir+'\'+UpdateName+'.fpt');
GsFileDelete(UpdateName+'.dbf');
GsFileDelete(UpdateName+'.fpt');
OpenMainBase(AreaBase,'AREAS');
SetTagTo('AreaID');
GoTop;
OpenWorkBase(UpdateName,'NEW',DontAsk);
GoTop;
While not dEOF do begin {Check All Records in 'WORK'}
{Copy the Msg to Another Area}
AreaID:=AllTrim(FieldGet('FILENAME'));
AreaDescr:=FieldGet('AREA');
Write('Adding to "',AreaID,'" ...');
{ x:=WhereX;
y:=WhereY;
}
OpenWorkBase(AreaID,'WORK',DontAsk);
TargetArea:=CurrentArea;
Select ('AREAS');
Find(AreaID);
If dEOF or (not FOUND) then begin
InsertRecord;
FieldPut('FILENAME',AreaID);
FieldPut('AREA',AreaDescr);
Replace;
end;
Select('NEW');
Copy1Record(TargetArea);
Select('WORK');
FieldPut('NEW','T'); {Mark inserted record as NEW}
Replace;
Use('','',False); {Close WORK database}
Select('AREAS');
UpdateMsgCounter(1);
Inc(MsgCounter);
Select('NEW');
Skip(1);
Writeln('ok.');
end;
Select('NEW');
Use('','',False); { Close Update DataBase }
Select('AREAS');
Use('','',False); { Close Main DataBase }
EraseFiles(UpdateName); {Erase Update Databases}
LastUpdate:=UpdateName; {Change LastUpdate}
WriteConfig; {and rewrite config file}
Writeln('Snipets added:',MsgCounter);
Writeln('All done.'); {Repart about the finishing}
end;
end;
end;
END.
|
unit EanRegEditors;
interface
{$I ean.inc}
uses
{$ifdef PSOFT_CLX}
DesignEditors,DesignIntf;
{$else}
Windows, ShellAPI,
{$ifndef PSOFT_D6}DsgnIntf
{$else}
DesignEditors, DesignIntf
{$endif};
{$endif}
type
TEanEditor =class(TDefaultEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{$ifdef PSOFT_PDF417}
TPDF417PropertyEditor=class(TClassProperty)
public
function GetAttributes:TPropertyAttributes; override;
procedure Edit; override;
end;
{$endif}
{$ifdef PSOFT_ACE}
TAceEanEditor =class(TDefaultEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{$endif}
procedure Register;
implementation
uses EanKod,EanDB,
{$ifdef PSOFT_QREPORT} EanQR,EanDBQr, {$endif}
{$ifdef PSOFT_ACE} EanAce, EanAceDB, {$endif}
Classes;
procedure TEanEditor.Edit;
begin
ExecuteVerb(1);
end;
procedure TEanEditor.ExecuteVerb(Index: Integer);
var E:TCustomEan;
begin
E:=nil;
if Component is TCustomEan then E:=TCustomEan(Component);
{$ifdef PSOFT_QREPORT}
if Component is TQrCustomEan then E:=TQrCustomEan(Component).Ean;
{$endif}
if E<>nil then
case Index of
0 : E.Copyright;
1 : E.ActiveSetupWindow('');
2 : E.PrintDialog;
{$ifndef PSOFT_CLX}
3 : ShellExecute(0, 'open', PChar(BarcodeLibraryHomePage), nil, nil, SW_SHOWNORMAL);
4 : ShellExecute(0, 'open', PChar('mailto:'+BarcodeLibraryEmail), nil, nil, SW_SHOWNORMAL);
5 : ShellExecute(0, 'open', PChar(BarcodeLibraryRegisterString), nil, nil, SW_SHOWNORMAL);
{$endif}
end;
end;
function TEanEditor.GetVerb(Index: Integer): String;
begin
case Index of
0 : Result := 'Barcode library - PSOFT company ©1998-2002';
1 : Result := 'Barcode properties editor';
2 : Result := 'Barcode - Print';
{$ifndef PSOFT_CLX}
3 : Result := 'Barcode library homepage';
4 : Result := 'Barcode library - send email to authors';
5 : Result := 'Online registration of Barcode library';
{$endif}
end;
end;
function TEanEditor.GetVerbCount: Integer;
begin
{$ifdef PSOFT_CLX}
Result:= 3;
{$else}
Result:= 6;
{$endif}
end;
{$ifdef PSOFT_PDF417}
function TPDF417PropertyEditor.GetAttributes:TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TPDF417PropertyEditor.Edit;
var E:TCustomEan;
begin
E:=TCustomEan(TpsPDF417(GetOrdValue).Ean);
E.ActiveSetupWindow('SH_PDF417');
end;
{$endif}
{$ifdef PSOFT_ACE}
procedure TAceEanEditor.ExecuteVerb(Index: Integer);
var E:TCustomEan;
begin
if Component is TAceCustomEan then E:=TAceCustomEan(Component).Ean
else E:=nil;
if E<>nil then
case Index of
0 : E.Copyright;
1 : E.ActiveSetupWindow('');
2 : E.PrintDialog;
{$ifndef PSOFT_CLX}
3 : ShellExecute(0, 'open', PChar(BarcodeLibraryHomePage), nil, nil, SW_SHOWNORMAL);
4 : ShellExecute(0, 'open', PChar('mailto:'+BarcodeLibraryEmail), nil, nil, SW_SHOWNORMAL);
5 : ShellExecute(0, 'open', PChar(BarcodeLibraryRegisterString), nil, nil, SW_SHOWNORMAL);
{$endif}
end;
end;
function TAceEanEditor.GetVerb(Index: Integer): String;
begin
case Index of
0 : Result := 'Barcode library - PSOFT company ©1998-2002';
1 : Result := 'Barcode properties editor';
2 : Result := 'Barcode print';
{$ifndef PSOFT_CLX}
3 : Result := 'Barcode library homepage';
4 : Result := 'Barcode library - send email to authors';
5 : Result := 'Online registration of Barcode library';
{$endif}
end;
end;
function TAceEanEditor.GetVerbCount: Integer;
begin
{$ifdef PSOFT_CLX}
Result := 3;
{$else}
Result := 6;
{$endif}
end;
{$endif}
procedure Register;
begin
RegisterComponentEditor(TCustomEAN, TEanEditor);
{$ifdef PSOFT_QREPORT}
RegisterComponentEditor(TQRCustomEAN, TEanEditor);
{$endif}
{$ifdef PSOFT_PDF417}
RegisterPropertyEditor(TypeInfo(TpsPDF417), nil, '',TPDF417PropertyEditor);
{$endif}
{$ifdef PSOFT_ACE}
RegisterComponentEditor(TAceEAN, TAceEanEditor);
RegisterComponentEditor(TAceDBEAN, TAceEanEditor);
{$endif}
end;
end.
|
unit uModDOBonus;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uModApp, uModPO, uModSuplier, uModGudang, System.Generics.Collections,
uModTipeBonus, uModUnit, uModBarang, uModSatuan;
type
TModDOBonusItem = class;
TModDOBonus = class(TModApp)
private
FDOB_COLIE: Double;
FDOB_DATE: TDATEtime;
FDOB_DESCRIPTION: string;
FDOB_DISC: Double;
FDOB_DOBonusItems: TOBjectList<TModDOBonusItem>;
FDOB_GUDANG: TModGudang;
FDOB_NO: string;
FDOB_PO: TModPO;
FDOB_PPN: Double;
FDOB_SUPPLIERMERCHANGRUP: TModSuplierMerchanGroup;
FDOB_TIPEBONUS: TModTipeBonus;
FDOB_TOTAL: Double;
FDOB_UNIT: TModUnit;
function GetDOB_DOBonusItems: TOBjectList<TModDOBonusItem>;
public
property DOB_DOBonusItems: TOBjectList<TModDOBonusItem> read
GetDOB_DOBonusItems write FDOB_DOBonusItems;
published
property DOB_COLIE: Double read FDOB_COLIE write FDOB_COLIE;
property DOB_DATE: TDATEtime read FDOB_DATE write FDOB_DATE;
property DOB_DESCRIPTION: string read FDOB_DESCRIPTION write FDOB_DESCRIPTION;
property DOB_DISC: Double read FDOB_DISC write FDOB_DISC;
property DOB_GUDANG: TModGudang read FDOB_GUDANG write FDOB_GUDANG;
[AttributeOfCode]
property DOB_NO: string read FDOB_NO write FDOB_NO;
property DOB_PO: TModPO read FDOB_PO write FDOB_PO;
property DOB_PPN: Double read FDOB_PPN write FDOB_PPN;
property DOB_SUPPLIERMERCHANGRUP: TModSuplierMerchanGroup read
FDOB_SUPPLIERMERCHANGRUP write FDOB_SUPPLIERMERCHANGRUP;
property DOB_TIPEBONUS: TModTipeBonus read FDOB_TIPEBONUS write
FDOB_TIPEBONUS;
property DOB_TOTAL: Double read FDOB_TOTAL write FDOB_TOTAL;
property DOB_UNIT: TModUnit read FDOB_UNIT write FDOB_UNIT;
end;
TModDOBonusItem = class(TModApp)
private
FDOBI_BARANG: TModBarang;
FDOBI_DISC1: Double;
FDOBI_DISC2: Double;
FDOBI_DISC3: Double;
FDOBI_DOBonus: TModDOBonus;
FDOBI_PPN: Double;
FDOBI_PPNBM: Double;
FDOBI_PPNBM_PERSEN: Double;
FDOBI_PPN_PERSEN: Double;
FDOBI_PRICE: Double;
FDOBI_QTY: Double;
FDOBI_TOTAL: Double;
FDOBI_TOTAL_DISC: Double;
FDOBI_TOTAL_TAX: Double;
FDOBI_TOTAL_TEMP: Double;
FDOBI_UOM: TModSatuan;
published
property DOBI_BARANG: TModBarang read FDOBI_BARANG write FDOBI_BARANG;
property DOBI_DISC1: Double read FDOBI_DISC1 write FDOBI_DISC1;
property DOBI_DISC2: Double read FDOBI_DISC2 write FDOBI_DISC2;
property DOBI_DISC3: Double read FDOBI_DISC3 write FDOBI_DISC3;
[AttributeOfHeader]
property DOBI_DOBonus: TModDOBonus read FDOBI_DOBonus write FDOBI_DOBonus;
property DOBI_PPN: Double read FDOBI_PPN write FDOBI_PPN;
property DOBI_PPNBM: Double read FDOBI_PPNBM write FDOBI_PPNBM;
property DOBI_PPNBM_PERSEN: Double read FDOBI_PPNBM_PERSEN write
FDOBI_PPNBM_PERSEN;
property DOBI_PPN_PERSEN: Double read FDOBI_PPN_PERSEN write
FDOBI_PPN_PERSEN;
property DOBI_PRICE: Double read FDOBI_PRICE write FDOBI_PRICE;
property DOBI_QTY: Double read FDOBI_QTY write FDOBI_QTY;
property DOBI_TOTAL: Double read FDOBI_TOTAL write FDOBI_TOTAL;
property DOBI_TOTAL_DISC: Double read FDOBI_TOTAL_DISC write
FDOBI_TOTAL_DISC;
property DOBI_TOTAL_TAX: Double read FDOBI_TOTAL_TAX write FDOBI_TOTAL_TAX;
property DOBI_TOTAL_TEMP: Double read FDOBI_TOTAL_TEMP write
FDOBI_TOTAL_TEMP;
property DOBI_UOM: TModSatuan read FDOBI_UOM write FDOBI_UOM;
end;
implementation
function TModDOBonus.GetDOB_DOBonusItems: TOBjectList<TModDOBonusItem>;
begin
if FDOB_DOBonusItems = nil then
FDOB_DOBonusItems := TObjectList<TModDOBonusItem>.Create();
Result := FDOB_DOBonusItems;
end;
initialization
TModDOBonus.RegisterRTTI;
end.
|
unit uTypes;
{*******************************************************************************
* *
* Название модуля : *
* *
* uTypes *
* *
* Назначение модуля : *
* *
* Централизованное хранение пользовательских типов, констант и пр. *
* *
* Copyright © Год 2005, Автор: Найдёнов Е.А *
* *
*******************************************************************************}
interface
uses Controls;
const
{*****************************************}
{ *** Константы общего назначения *** }
{*****************************************}
cZERO = 0;
cDIGITS = ['0'..'9']; //Множество натуральных чисел
cLETTERS = ['A'..'Z']; //Множество букв
cDEF_CAN_SORT = True; //Умалчиваемое значение для активации сортировки списка строк
cDEF_IS_ACTIVE = True; //Значение по умолчанию для поля выбора файла скрипта
cDEF_BUTTON_TAG = -1; //Умалчиваемое значение для порядкового номера кнопки панели задач
cDEF_DLG_RESULT = -1; //Значение по умолчанию для результата диалога с пользователем
cDATE_SEPARATOR = '-'; //Символ-разделитель для даты
cMIN_PATH_LENGTH = 3; //Минимальное количество символов, составляющих операционный путь
cDEF_UPDATE_NUMBER = -1; //Умалчиваемый номер обновления, собранного не в ДонНУ
cDATE_DIGITS_COUNT = 10; //Количество цифр, используемых для представления даты
cMIN_SECTIONS_COUNT = 6; //Минимальное количество значащих секций, содержащихся в имени файла скрипта
cDEF_CASE_SENSITIVE = False; //Умалчиваемое значение для регистра символов
cUPDATE_NUMBER_SEPARATOR = '-'; //Символ-разделитель для составного номера обновления
cSECTIONS_SEPARATOR_COUNT = 2; //Количество символов-разделителей, отделяющих друг от друга секции в имени файла скрипта
cUPDATE_MAJ_RESERVED_CHAR_COUNT = 3; //Количество позиций зарезервированных для главной части порядкового номера обновления
cUPDATE_MIN_RESERVED_CHAR_COUNT = 2; //Количество позиций зарезервированных для дополнительной части порядкового номера обновления
cDAYSBETWEEN_RESERVED_CHAR_COUNT = 2; //Количество позиций зарезервированных для разницы в днях между датой создания скрипта и датой его применения
resourcestring
{***************************************}
{ *** Ресурсы общего назначения *** }
{***************************************}
//Сообщения пользовательских исключительных ситуаций
sEFileNotFound = 'Файл не найден';
sEConvertError = 'Некорректное преобразование типов';
//Составляющие сообщения об ошибке
sErrorText = ' Ошибка: ';
sErrorCode = 'Код ошибки: ';
sErrorAddr = 'Адрес ошибки: ';
sContinueQst = ' Продолжить?';
sErrorTextExt = 'Ошибка: ';
sMsgCaptionErr = 'Ошибка';
sMsgCaptionWrn = 'Предупреждение';
sMsgCaptionInf = 'Информация';
sMsgCaptionQst = 'Подтверждение';
sCommentFile = ' Файл: ';
sCommentBevel = ' *************** ';
sCommProjectName = ' Название проекта: ';
sCommScriptsCount = ' Количество скриптов: ';
sCommUpdDateCreate = 'Дата формирования обновления: ';
//Имя файла-отчёта ошибок приложения
sLOG_FILE_NAME = 'AppErrors.log';
//Имя файла-отчёта ошибок тестирования файла обновления
sUPDATE_ERRORS_FILE_NAME = 'Update_Errors.log';
//Имя файла умалчиваемых настроек
sINI_FILE_NAME = 'DefConfig.ini';
//Названия секций для файла умалчиваемых настроек
sSN_DEFAULT_VALUES = 'Default Values';
sSN_PROJECTS = 'Projects';
//Названия ключей для файла умалчиваемых настроек
sKN_DB_PATH = 'DbPath';
sKN_SCR_PATH = 'ScriptPath';
sKN_PASSWORD = 'Password';
sKN_USER_NAME = 'User';
sKN_SERVER_NAME = 'Server';
sKN_IBESCRIPT_PATH = 'IBEscriptPath';
sKN_ACTIVE_PROJECTS= 'ActiveProjects';
sFILE_SIZE_FN = 'FILE_SIZE'; //Название поля для НД, содержащего размер файла скрипта
sIS_ACTIVE_FN = 'IS_ACTIVE'; //Название поля выбора для НД
sDATE_CHANGE_FN = 'DATE_CHANGE'; //Название поля для НД, содержащего дату последнего изменения файла скрипта
sSCRIPT_NAME_FN = 'SCRIPT_NAME'; //Название поля для НД, содержащего имя файла скрипта
//Расширения архивных файлов
sARCH_EXT_GZ = '*.gz';
sARCH_EXT_RAR = '*.rar';
sARCH_EXT_ZIP = '*.zip';
sARCH_EXT_EXE = '*.exe';
sARCH_EXT_TAR = '*.tar';
sARCH_EXT_RPM = '*.rpm';
sARCH_EXT_ARJ = '*.arj';
sCR = #13; //Символ окончания строки
sZERO = '0'; //Символ ноль
sCRLF = #13#10; //Символы окончания строки и перехода на следующую
sSTAR = '*'; //Символ звёздочка
sTICK = ''''; //Символ кавычка
sTICKS = '"'; //Символ кавычка
sSPACE = ' '; //Символ пробел
sMINUS = '-'; //Символ минус
sDEF_DB_EXT = '*.ib'; //Умалчиваемое расширения для файла базы данных
sEMPTY_STR = ''; //Пустая строка
sSEMICOLON = ','; //Символ запятая
sDBL_POINT = ':'; //Символ двоеточие
sBRAKET_OP = '('; //Символ открывающая скобка
sBRAKET_CL = ')'; //Символ закрывающая скобка
sDEF_EXE_EXT = '*.exe'; //Умалчиваемое расширения для исполняемого файла
sUPDATE_EXPR = 'U'; //Ключевое выражение, показывающее вошел ли скрипт в какое-либо обновление или нет
sSCRIPTS_MASK = '*.sql'; //Маска для файлов скриптов
sANY_FILE_MASK = '*.*'; //Маска для любых файлов
sUPDATE_NUMBER = ' Update No '; //Подстрока - составляющая имени файла обновления
sSCRIPT_FILE_EXT = '.sql'; //Расширение файлов скриптов
sBRAKET_COMMENT_OP = '/*'; //Символ, открывающий комментарий
sBRAKET_COMMENT_CL = '*/'; //Символ, закрывающий комментарий
sFMT_ALL_FILES_SIZE = '#0.00'; //Шаблон для форматирования размера всех файлов
sFMT_SEL_FILES_SIZE = '#0.0000'; //Шаблон для форматирования размера выбранных файлов
sFORMAT_DATE_TO_STR = 'yyyy-mm-dd'; //Формат даты для конвертации в строку
sSEPARATOR_FOLDER_WIN = '\'; //Символ-разделитель для Win32-путей
sSEPARATOR_FOLDER_UNX = '/'; //Символ-разделитель для UNIX-путей
sSCRIPT_EXECUTER_NAME = 'ibescript.exe'; //Имя exe-файла для применения скриптов
sCOMMAND_LINE_SCRIPT_EXEC = ' -S -N -V'; //Параметры командной строки для утилиты выполнения скриптов
sSCRIPT_EXECUTER_NAME_NO_EXT = 'ibescript'; //Имя exe-файла без расширения для применения скриптов
sEXECUTE_OPERATION = 'Open'; //Параметр для запуска блокнота для просмотра файла-отчета ошибок применения скрипта
sEXECUTE_SCRIPT_STR = 'Script executed successfully'; //Строка, сигнализирующая о успешном применении скрипта
sDEF_DB_FILTER = 'Data Base Files (*.ib; *.gdb)|*.ib;*.gdb'; //Умалчиваемое значение фильтра для файлов базы данных
sDEF_EXE_FILTER = 'Executable Files (*.exe)|*.exe'; //Умалчиваемое значение фильтра для исполняемых файлов
sDEF_SQL_FILTER = 'Script Files (*.sql)|*.sql'; //Умалчиваемое значение фильтра для файлов скриптов
sTEMP_DIR = 'C:\WINDOWS\TEMP'; //Куда копировать архив
sEMPTY_CHAR = '_'; //Символ, указывающий на пропущенный значащий символ в имени файла скрипта
sDEF_SCR_PATH = '\\It-server\projects\FMAS-WIN\DONNU\TEST\Scripts'; //Путь к хранилищу скриптов
sSCR_SEPARATOR = '='; //Символ-разделитель секций в имени скрипта
sSCR_ERROR_CHAR = '#'; //Символ-маркер для пометки скриптов с ошибками
sDEF_SCR_DATE_BEG = '01.09.2005'; //Нижняя граница даты создания скриптов
sDEF_UPDATE_NUMBER = '-1'; //Умалчиваемый номер обновления, собранного не в ДонНУ
sDEF_ACTIVE_PROJECTS = 'ABGHKMPS'; //Активные проекты по умолчанию
sDEF_DB_PATH = '\\It-server\projects\FMAS-WIN\DNEPR\TEST\FULL_DB.IB'; //Путь к хранилищу скриптов
sDEF_PASSWORD = 'masterkey'; //Умалчиваемый пароль для подключения к БД
sDEF_USER_NAME = 'SYSDBA'; //Умалчиваемое имя пользователя для подключения к БД
sDEF_SERVER_NAME = 'localhost'; //Умалчиваемое имя сервера для подключения к БД
sDEF_IBESCRIPT_PATH = 'C:\Program Files\HK Software\IB Expert 2.0\ibescript.exe'; //Путь к программе применения скриптов
{***********************************************************************}
{ *** Названяи проeктов и соответствующие им ключевые выражения *** }
{***********************************************************************}
//Название проэктов
sMONU_NAME = 'МОНУ';
sKIEV_NAME = 'КИЕВ';
// sLVOV_NAME = 'Львов';
sDNEPR_NAME = 'Днепродзержинск';
sDONUEP_NAME = 'ДонУЭП';
sKHARKOV_NAME = 'Харьков';
sPOLTAVA_NAME = 'Полтава';
sDONGUET_NAME = 'ДонГУЭТ';
sCHERMET_NAME = 'УкрПромВодЧерМет';
sALCHEVSK_NAME = 'Алчевск';
sSTUDCITY_NAME = 'Студгородок';
sGORLOVKA_NAME = 'Горловский Техникум ДонНУ';
sSPORT_UNIVER_NAME = 'Институт Физкультуры';
//Значения ключевых выражений, соответствующие проэктам
sMONU_KEY_EXPR = 'M';
sKIEV_KEY_EXPR = 'K';
// sLVOV_KEY_EXPR = 'L';
sDNEPR_KEY_EXPR = 'D';
sDONUEP_KEY_EXPR = 'E';
sKHARKOV_KEY_EXPR = 'H';
sPOLTAVA_KEY_EXPR = 'P';
sDONGUET_KEY_EXPR = 'G';
sCHERMET_KEY_EXPR = 'C';
sALCHEVSK_KEY_EXPR = 'A';
sSTUDCITY_KEY_EXPR = 'S';
sGORLOVKA_KEY_EXPR = 'O';
sSPORT_UNIVER_KEY_EXPR = 'F';
type
{************************************}
{ *** Типы общего назначения *** }
{************************************}
//Множество чисел
TDigits = Set of '0'..'9';
//Динамический массив для хранения целых чисел
TIntArray = array of Integer;
//Динамический массив для хранения строк
TStrArray = array of String;
//Перечисляемый тип, определяющий режим работы модуля со скриптами
TEnm_AppMode = ( amView, amSearch );
//Перечисляемый тип, определяющий направление поиска
TEnm_Direction = ( dtDown, dtUp );
//Перечисляемый тип, определяющий тип файлов, над которыми будут выполняться действия
TUsrFileType = ( ftScripts, ftModules );
//Перечисляемый тип, определяющий режим заполнения набора данных
TPeriodBound = ( pbNone, pbLeft, pbRight, pbBoth );
//Перечисляемый тип, определяющий режим заполнения набора данных
TFillMode = ( fmInsert, fmAppend );
//Перечисляемый тип, определяющий режим переименования скриптов
TRenameMode = ( rmRename, rmUnRename );
//Перечисляемый тип, определяющий режим сортировки файлов скриптов
TSortMode = ( smAlphabetically, smDate, smOrder );
//Перечисляемый тип, определяющий результат, возвращаемый функцией загрузки скриптов
TLoadScrResult = ( lrNone, lrScrNotFound, lrFilterInvalid, lrLoadSuccess, lrModulesInvalid );
//Перечисляемый тип для организации функции мультивыбора
TSelectionMode = ( smSelectAll, smUnSelectAll, smInvert );
//Перечисляемый тип для определения кол-ва помеченных записей
TCheckedRecCount = ( crcNone, crcSome, crcAll );
//Запись, предназначенная для хранения параметров проэкта
TProjectParams = packed record
Name : String;
KeyExpr : String;
end;
//Запись, предназначенная для хранения параметров переименования
TRenameParams = packed record
KeyExpr : String;
RenameMode : TRenameMode;
DateCreate : TDate;
UpdateNumMajor : Integer;
UpdateNumMinor : Integer;
end;
//Запись, предназначенная для хранения параметров скрипта
TScriptInfo = packed record
CanExecute : Boolean;
Execute : Boolean;
IsInUpdate : Boolean;
DateCreate : TDate;
DateExecute : TDate;
UpdateNumMajor : String;
UpdateNumMinor : String;
end;
//Запись, предназначенная для хранения максимального номера обновления
TUpdateNumInfo = packed record
UpdateNumMajor : Integer;
UpdateNumMinor : Integer;
end;
//Запись, предназначенная для хранения параметров поиска максимального номера обновления
TMaxUpdNumParams = packed record
KeyExpr : String;
FilePath : String;
end;
//Запись, предназначенная для хранения параметров фильтрации
TFilterParams = packed record
KeyExpr : String;
DateBeg : String;
DateEnd : String;
ScriptPath : String;
UpdateNumMajor : Integer;
UpdateNumMinor : Integer;
end;
//Запись, предназначенная для хранения названий параметров конфигурационного файла
TDefIniParams = packed record
Section : String;
Key : String;
DefValue : String;
end;
//Запись, предназначенная для хранения значений параметров конфигурационного файла
TIniParams = packed record
User : String;
Server : String;
DBPath : String;
Password : String;
ScriptPath : String;
end;
TPtr_SearchParams = ^TRec_SearchParams;
//Запись предназначенна для хранения параметров поиска
TRec_SearchParams = packed record
Direction : TEnm_Direction;
TextSearch : String;
FirstFound : String;
CaseSensitive : Boolean;
WholeWordsOnly : Boolean;
end;
//Массив умалчиваемых параметров
TArrDefIniParams = array of TDefIniParams;
const
//Массив расширений файлов скриптов
cScriptExt : array[0..0] of String = (
sSCRIPTS_MASK );
//Массив расширений архивных файлов
cArchiveExt : array[0..6] of String = (
sARCH_EXT_RAR,
sARCH_EXT_ZIP,
sARCH_EXT_EXE,
sARCH_EXT_ARJ,
sARCH_EXT_TAR,
sARCH_EXT_RPM,
sARCH_EXT_GZ);
//Массив умалчиваемых параметров
cDefIniParams : array[0..6] of TDefIniParams = (
( Section: sSN_DEFAULT_VALUES; Key: sKN_SERVER_NAME ; DefValue: sDEF_SERVER_NAME ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_DB_PATH ; DefValue: sDEF_DB_PATH ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_USER_NAME ; DefValue: sDEF_USER_NAME ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_PASSWORD ; DefValue: sDEF_PASSWORD ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_SCR_PATH ; DefValue: sDEF_SCR_PATH ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_IBESCRIPT_PATH; DefValue: sDEF_IBESCRIPT_PATH ),
( Section: sSN_DEFAULT_VALUES; Key: sKN_ACTIVE_PROJECTS; DefValue: sDEF_ACTIVE_PROJECTS));
//Массив параметров проeктов
cProjectParams : array [0..11] of TProjectParams = (
( Name: sMONU_NAME ; KeyExpr: sMONU_KEY_EXPR ),
( Name: sKIEV_NAME ; KeyExpr: sKIEV_KEY_EXPR ),
// ( Name: sLVOV_NAME ; KeyExpr: sLVOV_KEY_EXPR ),
( Name: sDNEPR_NAME ; KeyExpr: sDNEPR_KEY_EXPR ),
( Name: sDONUEP_NAME ; KeyExpr: sDONUEP_KEY_EXPR ),
( Name: sKHARKOV_NAME ; KeyExpr: sKHARKOV_KEY_EXPR ),
( Name: sPOLTAVA_NAME ; KeyExpr: sPOLTAVA_KEY_EXPR ),
( Name: sDONGUET_NAME ; KeyExpr: sDONGUET_KEY_EXPR ),
( Name: sCHERMET_NAME ; KeyExpr: sCHERMET_KEY_EXPR ),
( Name: sALCHEVSK_NAME; KeyExpr: sALCHEVSK_KEY_EXPR ),
( Name: sSTUDCITY_NAME; KeyExpr: sSTUDCITY_KEY_EXPR ),
( Name: sGORLOVKA_NAME; KeyExpr: sGORLOVKA_KEY_EXPR ),
( Name: sSPORT_UNIVER_NAME; KeyExpr: sSPORT_UNIVER_KEY_EXPR ) );
implementation
end.
|
unit FTGifAnimate;
(******************************************************************************
Unit to make an animated GIF.
Author: Finn Tolderlund
Denmark
Date: 14.07.2003
homepage:
http://home20.inet.tele.dk/tolderlund/
http://finn.mobilixnet.dk/
e-mail:
finn@mail.tdcadsl.dk
finn.tolderlund@mobilixnet.dk
This unit requires the GIFImage.pas unit from Anders Melander.
The GIFImage.pas unit can be obtained from my homepage above.
This unit can freely be used and distributed.
Disclaimer:
Use of this unit is on your own responsibility.
I will not under any circumstance be held responsible for anything
which may or may not happen as a result of using this unit.
******************************************************************************
History:
19.07.2003 Added GifAnimateEndGif function.
24.07.2003 Added link to an example Delphi project at Earl F. Glynn's website.
02.09.2003 Renamed function GifAnimateEnd to GifAnimateEndPicture.
Added overloaded function GifAnimateAddImage where you can specify
a specific TransparentColor.
******************************************************************************)
(******************************************************************************
Example of use:
procedure TFormSphereMovie.MakeGifButtonClick(Sender: TObject);
// BitMapArray is an array of TBitmap.
var
FrameIndex: Integer;
Picture: TPicture;
begin
Screen.Cursor := crHourGlass;
try
GifAnimateBegin;
{Step through each frame in in-memory list}
for FrameIndex := Low(BitMapArray) to High(BitMapArray) do
begin
// add frame to animated gif
GifAnimateAddImage(BitMapArray[FrameIndex], False, MillisecondsPerFrame);
end;
// We are using a TPicture but we could have used a TGIFImage instead.
// By not using TGIFImage directly we do not have to add GIFImage to the uses clause.
// By using TPicture we only need to add GifAnimate to the uses clause.
Picture := GifAnimateEndPicture;
Picture.SaveToFile(ExtractFilePath(ParamStr(0)) + 'sphere.gif'); // save gif
ImageMovieFrame.Picture.Assign(Picture); // display gif
Picture.Free;
finally
Screen.Cursor := crDefault;
end;
end;
******************************************************************************)
(******************************************************************************
For a complete Delphi project with source, goto one of these pages:
http://homepages.borland.com/efg2lab/Graphics/SphereInCubeMovie.htm
http://www.efg2.com/Lab/Graphics/SphereInCubeMovie.htm
******************************************************************************)
interface
uses
Windows, Graphics, GIFImage;
procedure GifAnimateBegin;
function GifAnimateEndPicture: TPicture;
function GifAnimateEndGif: TGIFImage;
function GifAnimateAddImage(Source: TGraphic; Transparent: boolean;
DelayMS: word): integer; overload;
// Transparent=True uses lower left pixel as transparent color
function GifAnimateAddImage(Source: TGraphic; TransparentColor: TColor;
DelayMS: word): integer; overload;
// TransparentColor<>-1 uses that color as the transparent.
// Note: There is no guaranteee that the color will actually be in the GIF's color palette.
implementation
var
GIF: TGIFImage;
function TransparentIndex(GIF: TGIFSubImage): byte;
begin
// Use the lower left pixel as the transparent color
Result := GIF.Pixels[0, GIF.Height - 1];
end;
function GifAnimateAddImage(Source: TGraphic; Transparent: boolean;
DelayMS: word): integer;
var
Ext: TGIFGraphicControlExtension;
LoopExt: TGIFAppExtNSLoop;
begin
// Add the source image to the animation
Result := GIF.Add(Source);
// Netscape Loop extension must be the first extension in the first frame!
if (Result = 0) then
begin
LoopExt := TGIFAppExtNSLoop.Create(GIF.Images[Result]);
LoopExt.Loops := 0; // Number of loops (0 = forever)
GIF.Images[Result].Extensions.Add(LoopExt);
end;
// Add Graphic Control Extension
Ext := TGIFGraphicControlExtension.Create(GIF.Images[Result]);
Ext.Delay := DelayMS div 10; // 30; // Animation delay (30 = 300 mS)
// if (Result > 0) then
if (Transparent) then
begin
Ext.Transparent := True;
Ext.TransparentColorIndex := TransparentIndex(GIF.Images[Result]);
end;
GIF.Images[Result].Extensions.Add(Ext);
end;
function GetColorIndex(GIF: TGIFSubImage; Color: TColor): integer;
var
idx, x, y: integer;
begin
// Find index for color in the colormap.
// The same color can be in the colormap more than once.
// Not all color indexes may be in use, so check if this index is being used.
// Return only an index which is actually being used in the image.
// If the index is not being used in the image,
// try to find the next index for the color in the colormap.
for idx := 0 to GIF.ColorMap.Count - 1 do
if GIF.ColorMap.Colors[idx] = Color then
begin
// Found an index, is it being used in the image?
for y := 0 to GIF.Height - 1 do
for x := 0 to GIF.Width - 1 do
if GIF.Pixels[x, y] = idx then
begin
Result := idx; // Index is used in image.
Exit;
end;
// Index not used in the image, try next index.
end;
Result := -1; // didn't find index for the color
end;
function GifAnimateAddImage(Source: TGraphic; TransparentColor: TColor;
DelayMS: word): integer;
var
Ext: TGIFGraphicControlExtension;
LoopExt: TGIFAppExtNSLoop;
idx: integer;
begin
// Add the source image to the animation
Result := GIF.Add(Source);
// Netscape Loop extension must be the first extension in the first frame!
if (Result = 0) then
begin
LoopExt := TGIFAppExtNSLoop.Create(GIF.Images[Result]);
LoopExt.Loops := 0; // Number of loops (0 = forever)
GIF.Images[Result].Extensions.Add(LoopExt);
end;
// Add Graphic Control Extension
Ext := TGIFGraphicControlExtension.Create(GIF.Images[Result]);
Ext.Delay := DelayMS div 10; // 30; // Animation delay (30 = 300 mS)
if TransparentColor <> -1 then
begin
idx := GetColorIndex(GIF.Images[Result], TransparentColor);
if idx in [0..255] then
begin
Ext.Transparent := True;
Ext.TransparentColorIndex := idx;
end;
end;
GIF.Images[Result].Extensions.Add(Ext);
end;
procedure GifAnimateBegin;
begin
GIF.Free;
GIF := TGIFImage.Create;
GIF.ColorReduction := rmQuantizeWindows;
// GIF.DitherMode := dmNearest; // no dither, use nearest color in palette
GIF.DitherMode := dmFloydSteinberg;
GIF.Compression := gcLZW;
end;
function GifAnimateEndPicture: TPicture;
begin
Result := TPicture.Create;
Result.Assign(GIF);
GIF.Free;
GIF := nil;
end;
function GifAnimateEndGif: TGIFImage;
begin
Result := TGIFImage.Create;
Result.Assign(GIF);
GIF.Free;
GIF := nil;
end;
initialization
GIF := nil;
finalization
GIF.Free;
end.
|
unit globals;
{ 1. All global variables.
2. Miscellaneous other procedures required by several Units.
}
{ CMO: addition/change by Christian Mondrup }
interface
const PMXlinelength = 128;
{ !!! One or more of the following constants should be reduced if this
program is to be compiled by a 16-bit compiler (e.g. Turbo Pascal),
otherwise you get a "Data segment too large" error }
lines_in_paragraph = 100;
max_words = 128;
max_notes = 128;
{ Christian Mondrup's suggestion to reduce data segment size:
lines_in_paragraph = 50;
max_words = 64;
max_notes = 64;
}
max_bars = 16;
maxstaves = 15;
maxvoices = 15;
maxgroups = 3;
standardPMXvoices = 12;
max_lyrics_line_length = PMXlinelength-4;
inf = 32000;
unspec = 1000;
default_size = 20;
start_beam = '[';
stop_beam = ']';
rest = 'r';
pause = 'rp';
dotcode = 'd';
grace_group = 'G';
multi_group = 'x';
barsym = '|';
comment = '%';
double_comment: string[2] = '%%';
blank = ' ';
dot = '.';
comma = ',';
colon = ':';
tilde = '~';
dummy = #0;
ndurs = 8;
durations: string[ndurs] = '90248136';
unspecified = '5'; { Not a valid duration }
whole = 2; { position of '0' in durations }
terminators: string = '.x';
digits = '123456789';
digitsdot = '0123456789.';
has_duration: string[8] = 'abcdefgr';
solfa_names: string[7] = 'drmfslt';
choice: char = ' ';
outfile_open: boolean = false;
texdir: string = '';
old_meter_word: string = '';
outlen: integer = 0;
putspace = true;
nospace = false;
ignore_input: boolean = false;
print = true;
type
paragraph_index = 1..lines_in_paragraph;
voice_index = 1..maxvoices;
stave_index = 1..maxstaves;
bar_index0 = 0..max_bars;
word_index0 = 0..max_words;
paragraph_index0 = 0..lines_in_paragraph;
voice_index0 = 0..maxvoices;
stave_index0 = 0..maxstaves;
paragraph = array[paragraph_index] of string;
line_nos = array[paragraph_index] of integer;
var voice_label: array[voice_index] of string;
clef: array[stave_index] of char;
instr, stave, first_on_stave, number_on_stave:
array[stave_index] of voice_index0;
stave_size: array[stave_index] of integer;
nspace: array[stave_index0] of integer;
nvoices, nstaves, ninstr, bottom, top: voice_index0;
one_beat, full_bar, line_no, short_note, musicsize,
meternum, meterdenom, pmnum, pmdenom, paragraph_no,
bar_no, pickup, nbars, nleft: integer;
para_len: paragraph_index0;
xmtrnum0: real;
P, orig_P: paragraph;
orig_line_no: line_nos;
infile, outfile, stylefile: text;
default_duration: char;
fracindent, this_version, this_version_date, multi_bar_rest: string;
pmx_preamble_done, first_paragraph, final_paragraph, must_respace,
must_restyle, some_vocal: boolean;
procedure error(message: string; printLine: boolean);
procedure fatalerror(message: string);
procedure warning(message: string; printLine: boolean);
function PMXinstr (stave: integer): integer;
procedure setDefaultDuration(meterdenom: integer);
procedure getMeter(line: string;
var meternum, meterdenom, pmnum, pmdenom: integer);
procedure setSpace(line: string);
function meterChange(n1, n2: integer; blind: boolean): string;
function meterWord (num, denom, pnum, pdenom: integer): string;
procedure cancel(var num,denom: integer; lowest: integer);
function isNoteOrRest(w: string): boolean;
function isPause(note: string): boolean;
{ CMO: }
function PMXmeterdenom(denom: integer): integer;
implementation uses strings, control, utility;
function isNoteOrRest(w: string): boolean;
begin isNoteOrRest := pos1(w[1],has_duration)>0; end;
function isPause(note: string): boolean;
begin isPause:=startsWith(note,pause); end;
procedure cancel(var num,denom: integer; lowest: integer);
begin while (num mod 2 = 0) and (denom>lowest) do
begin num:=num div 2; denom:=denom div 2; end;
end;
function meterWord (num,denom,pnum,pdenom: integer): string;
begin meterWord := 'm' + toString(num) + '/' + toString(denom) +
'/' + toString(pnum) + '/' + toString(pdenom);
end;
function meterChange(n1, n2: integer; blind: boolean): string;
var f, l: integer;
begin
if blind then
begin f:=64; l:=n1 * (64 div n2);
cancel(l,f,meterdenom);
{ CMO: process denominator value with function PMXmeterdenom }
meterChange := meterWord (l,PMXmeterdenom(f),0,0);
if meternum>0 then
writeln('Blind meter change to ', l, '/', f, ' on line ', line_no);
end
{ CMO: process denominator value with function PMXmeterdenom }
else meterChange := meterWord(n1,PMXmeterdenom(n2),0,0);
end;
procedure setSpace(line: string);
var i: integer;
word: string;
begin
i := pos1(';',line);
if i>0 then
begin
getNum(substr(line,1,i-1),nspace[0]);
predelete (line,i)
end;
i:=0;
while i<ninstr do
begin word:=GetNextWord(line,blank,dummy);
if word='' then exit;
inc(i); getNum(word,nspace[i]);
end;
end;
procedure onumber (s: string; var j, n1: integer);
begin if s[j]='o' then n1:=1 else if s[j]='1' then
begin n1:=10+digit(s[j+1]); inc(j); end
else n1:=digit(s[j]);
inc(j);
end;
procedure extractNumber(var s: string; var k: integer);
var w: string;
begin w:=getNextWord(s,'/',dummy); getNum(w,k);
end;
procedure readMeter (meter: string;
var meternum, meterdenom, pmnum, pmdenom: integer);
var j: integer;
begin if meter[1]='m' then
if pos1('/',meter)=0 then
begin j:=2; onumber(meter,j,meternum); onumber(meter,j,meterdenom);
onumber(meter,j,pmnum); onumber(meter,j,pmdenom);
end
else begin predelete(meter,1);
extractNumber(meter,meternum); extractNumber(meter,meterdenom);
extractNumber(meter,pmnum); extractNumber(meter,pmdenom);
end
else begin getTwoNums(meter, meternum, meterdenom);
pmnum:=meternum; pmdenom:=meterdenom;
end;
end;
procedure getMeter(line: string;
var meternum, meterdenom, pmnum, pmdenom: integer);
var meter: string;
begin meter:=GetNextWord(line,blank,dummy);
if (meter='C/') or (meter='mC/') then
begin meternum:=2; meterdenom:=2; pmdenom:=5; pmnum:=0; end
else if (meter='C') or (meter='mC') then
begin meternum:=4; meterdenom:=4; pmdenom:=6; pmnum:=0; end
else readMeter(meter,meternum,meterdenom,pmnum,pmdenom);
if meterdenom=0 then Error
(meter+': Meter denominator must be nonzero',print);
{ CMO: Convert PMX syntax meter denominator '0' to '1' to be used for
prepmx duration checks }
{ if meterdenom=0 then meterdenom:=1; }
end;
function whereInParagraph(l: integer): integer;
var j: integer;
begin whereInParagraph:=0;
for j:=1 to para_len do if orig_line_no[j]=l then
begin whereInParagraph:=j; exit end;
end;
procedure fatalerror(message: string);
begin setFeature('ignoreErrors',false); error(message,not print) end;
procedure error(message: string; printline: boolean);
var j: integer;
begin
j:=whereInParagraph(line_no); if (j>0) and printline then
writeln(orig_P[j]);
writeln (message, ': ERROR on line ', line_no);
if (j>0) and printline then
begin
writeln ('The line has been modified internally to:');
writeln(P[j]);
end;
if not ignoreErrors then
begin if outfile_open then
begin close(outfile); rewrite(outfile); close(outfile); end;
if line_no=0 then line_no:=10000;
halt(line_no);
end;
end;
procedure warning(message: string; printline: boolean);
var j: integer;
begin
if line_no>0 then
begin writeln (message, ': WARNING on line ', line_no);
if not printline then exit;
j:=whereInParagraph(line_no); if j>0 then writeln(P[j])
end
else writeln (message, ': WARNING in preamble');
end;
function PMXinstr (stave: integer): integer;
begin PMXinstr := ninstr + 1 - instr[stave]; end;
procedure setDefaultDuration(meterdenom: integer);
begin
case meterdenom of
1: default_duration:='0';
2: default_duration:='2';
4: default_duration:='4';
8: default_duration:='8';
16: default_duration:='1';
32: default_duration:='3';
64: default_duration:='6';
end;
end;
function PMXmeterdenom(denom: integer): integer;
begin
{ CMO: Convert M-Tx meter denominators to PMX syntax }
case denom of
1 : PMXmeterdenom:=0;
16 : PMXmeterdenom:=1;
32 : PMXmeterdenom:=3;
64 : PMXmeterdenom:=6;
else
PMXmeterdenom:=denom;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NOTA_FISCAL_CABECALHO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NotaFiscalCabecalhoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL, NotaFiscalDetalheVO;
type
TNotaFiscalCabecalhoVO = class(TVO)
private
FID: Integer;
FID_ECF_FUNCIONARIO: Integer;
FID_CLIENTE: Integer;
FCPF_CNPJ_CLIENTE: String;
FCFOP: Integer;
FNUMERO: String;
FDATA_EMISSAO: TDateTime;
FHORA_EMISSAO: String;
FSERIE: String;
FSUBSERIE: String;
FTOTAL_PRODUTOS: Extended;
FTOTAL_NF: Extended;
FBASE_ICMS: Extended;
FICMS: Extended;
FICMS_OUTRAS: Extended;
FISSQN: Extended;
FPIS: Extended;
FCOFINS: Extended;
FIPI: Extended;
FTAXA_ACRESCIMO: Extended;
FACRESCIMO: Extended;
FACRESCIMO_ITENS: Extended;
FTAXA_DESCONTO: Extended;
FDESCONTO: Extended;
FDESCONTO_ITENS: Extended;
FCANCELADA: String;
FTIPO_NOTA: String;
FNOME_CAIXA: String;
FID_GERADO_CAIXA: Integer;
FDATA_SINCRONIZACAO: TDateTime;
FHORA_SINCRONIZACAO: String;
FListaNotaFiscalDetalheVO: TListaNotaFiscalDetalheVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdEcfFuncionario: Integer read FID_ECF_FUNCIONARIO write FID_ECF_FUNCIONARIO;
property IdCliente: Integer read FID_CLIENTE write FID_CLIENTE;
property CpfCnpjCliente: String read FCPF_CNPJ_CLIENTE write FCPF_CNPJ_CLIENTE;
property Cfop: Integer read FCFOP write FCFOP;
property Numero: String read FNUMERO write FNUMERO;
property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO;
property HoraEmissao: String read FHORA_EMISSAO write FHORA_EMISSAO;
property Serie: String read FSERIE write FSERIE;
property Subserie: String read FSUBSERIE write FSUBSERIE;
property TotalProdutos: Extended read FTOTAL_PRODUTOS write FTOTAL_PRODUTOS;
property TotalNf: Extended read FTOTAL_NF write FTOTAL_NF;
property BaseIcms: Extended read FBASE_ICMS write FBASE_ICMS;
property Icms: Extended read FICMS write FICMS;
property IcmsOutras: Extended read FICMS_OUTRAS write FICMS_OUTRAS;
property Issqn: Extended read FISSQN write FISSQN;
property Pis: Extended read FPIS write FPIS;
property Cofins: Extended read FCOFINS write FCOFINS;
property Ipi: Extended read FIPI write FIPI;
property TaxaAcrescimo: Extended read FTAXA_ACRESCIMO write FTAXA_ACRESCIMO;
property Acrescimo: Extended read FACRESCIMO write FACRESCIMO;
property AcrescimoItens: Extended read FACRESCIMO_ITENS write FACRESCIMO_ITENS;
property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO;
property Desconto: Extended read FDESCONTO write FDESCONTO;
property DescontoItens: Extended read FDESCONTO_ITENS write FDESCONTO_ITENS;
property Cancelada: String read FCANCELADA write FCANCELADA;
property TipoNota: String read FTIPO_NOTA write FTIPO_NOTA;
property NomeCaixa: String read FNOME_CAIXA write FNOME_CAIXA;
property IdGeradoCaixa: Integer read FID_GERADO_CAIXA write FID_GERADO_CAIXA;
property DataSincronizacao: TDateTime read FDATA_SINCRONIZACAO write FDATA_SINCRONIZACAO;
property HoraSincronizacao: String read FHORA_SINCRONIZACAO write FHORA_SINCRONIZACAO;
property ListaNotaFiscalDetalheVO: TListaNotaFiscalDetalheVO read FListaNotaFiscalDetalheVO write FListaNotaFiscalDetalheVO;
end;
TListaNotaFiscalCabecalhoVO = specialize TFPGObjectList<TNotaFiscalCabecalhoVO>;
implementation
constructor TNotaFiscalCabecalhoVO.Create;
begin
inherited;
FListaNotaFiscalDetalheVO := TListaNotaFiscalDetalheVO.Create;
end;
destructor TNotaFiscalCabecalhoVO.Destroy;
begin
FreeAndNil(FListaNotaFiscalDetalheVO);
inherited;
end;
initialization
Classes.RegisterClass(TNotaFiscalCabecalhoVO);
finalization
Classes.UnRegisterClass(TNotaFiscalCabecalhoVO);
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.ListView.Types, System.Rtti, FMX.Controls.Presentation, FMX.Edit,
FMX.Layouts, FMX.Grid, FMX.StdCtrls, FMX.Memo, FMX.ListView,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.Bind.EngExt, Fmx.Bind.DBEngExt,
Fmx.Bind.Grid, System.Bindings.Outputs, Fmx.Bind.Editors,
Data.Bind.Components, Data.Bind.Grid, Data.Bind.DBScope, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, FMX.MultiView, Data.Bind.Controls,
Fmx.Bind.Navigator;
type
TForm1 = class(TForm)
lvTables: TListView;
loTables: TLayout;
loSQL: TLayout;
ToolBar1: TToolBar;
btnRunSQL: TButton;
loData: TLayout;
Grid1: TGrid;
loDB: TLayout;
edtDatabaseName: TEdit;
btConnect: TButton;
FDQuery1: TFDQuery;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
MultiView1: TMultiView;
ToolBar2: TToolBar;
Label1: TLabel;
Memo1: TMemo;
ToolBar3: TToolBar;
Label2: TLabel;
Button1: TButton;
ToolBar4: TToolBar;
Label3: TLabel;
ToolBar5: TToolBar;
NavigatorBindSourceDB1: TBindNavigator;
procedure btConnectClick(Sender: TObject);
procedure btnRunSQLClick(Sender: TObject);
procedure lvTablesItemClick(const Sender: TObject;
const AItem: TListViewItem);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses InterBaseDM, System.IOUtils;
procedure TForm1.btConnectClick(Sender: TObject);
var
DBPath: string;
TableName: string;
I: Integer;
SkipAddTables: Boolean;
begin
if edtDatabaseName.Text.Contains(':') then begin
DBPath := edtDatabaseName.Text;
// For the demo, we only add tables and data to a local database
SkipAddTables := True;
end else begin
SkipAddTables := False;
{$IFNDEF MSWINDOWS}
DBPath := TPath.GetDocumentsPath+PathDelim+'interbase'+PathDelim+edtDatabaseName.Text;
{$ELSE}
DBPath := 'c:\data\'+edtDatabaseName.Text;
if not DirectoryExists('c:\data\') then
ForceDirectories('c:\data\');
{$ENDIF}
end;
dmInterBase.IBLiteDB.Connected := False;
dmInterBase.IBLiteDB.Params.Values['Database'] := DBPath;
dmInterBase.IBLiteDB.Connected := True;
if not SkipAddTables then begin
// Create some local data for demo purposes
if not dmInterBase.TableExists('Foo') then begin
dmInterBase.IBLiteDB.ExecSQL('CREATE TABLE FOO (ID Integer, FOO VarChar(10))');
dmInterBase.Tables.Add('FOO');
FDQuery1.SQL.Text := 'INSERT INTO FOO (ID, FOO) values (:ID, :FOO)';
FDQuery1.Params.ArraySize := 10;
for I := 0 to 9 do begin
FDQuery1.ParamByName('ID').AsIntegers[I] := I;
FDQuery1.ParamByName('FOO').AsStrings[I] := 'Foo '+I.ToString;
end;
FDQuery1.Execute(10);
end;
if not dmInterBase.TableExists('Fee') then begin
dmInterBase.IBLiteDB.ExecSQL('CREATE TABLE FEE (ID Integer, FEE VarChar(10))');
dmInterBase.Tables.Add('FEE');
FDQuery1.SQL.Text := 'INSERT INTO FEE (ID, FEE) values (:ID, :FEE)';
FDQuery1.Params.ArraySize := 10;
for I := 0 to 9 do begin
FDQuery1.ParamByName('ID').AsIntegers[I] := I+100;
FDQuery1.ParamByName('FEE').AsStrings[I] := 'Fee '+(I+100).ToString;
end;
FDQuery1.Execute(10);
end;
end;
lvTables.ClearItems;
for TableName in dmInterBase.Tables do
lvTables.Items.Add.Text := TableName;
end;
procedure TForm1.btnRunSQLClick(Sender: TObject);
begin
if Memo1.Text.Trim.StartsWith('select',True) then
FDQuery1.Open(Memo1.Text)
else begin
FDQuery1.SQL.Text := Memo1.Text;
FDQuery1.ExecSQL;
end;
end;
procedure TForm1.lvTablesItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
Memo1.Text := 'Select * from '+AItem.Text;
btnRunSQLClick(nil);
end;
end.
|
unit fMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts,
System.Actions, FMX.ActnList, FMX.Gestures;
type
TfrmMain = class(TForm)
lytDrawer: TLayout;
lytMain: TLayout;
ToolBar1: TToolBar;
ActionList1: TActionList;
actOpenDrawer: TAction;
btnDrawer: TButton;
GestureManager1: TGestureManager;
procedure FormResize(Sender: TObject);
procedure actOpenDrawerExecute(Sender: TObject);
procedure actOpenDrawerUpdate(Sender: TObject);
private
FDrawerVisible: boolean;
{ Private declarations }
function IsPad : boolean;
function IsLandscape : boolean;
procedure LayoutForm;
procedure SetDrawerVisible(const Value: boolean);
public
{ Public declarations }
property DrawerVisible : boolean read FDrawerVisible write SetDrawerVisible;
end;
var
frmMain: TfrmMain;
implementation
uses
{$IFDEF IOS}
iOSapi.UIKit,
{$ENDIF }
{$IFDEF ANDROID}
FMX.Platform.Android, Androidapi.JNI.GraphicsContentViewText,
{$ENDIF }
FMX.Platform;
{$R *.fmx}
procedure TfrmMain.actOpenDrawerExecute(Sender: TObject);
begin
DrawerVisible := not DrawerVisible;
end;
procedure TfrmMain.actOpenDrawerUpdate(Sender: TObject);
begin
actOpenDrawer.Visible := not (IsPad and IsLandscape);
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
LayoutForm;
end;
function TfrmMain.IsLandscape: boolean;
begin
Result := self.Width > self.Height;
end;
function TfrmMain.IsPad: boolean;
begin
{$IFDEF IOS}
Result := TUIDevice.Wrap(TUIDevice.OCClass.currentDevice).userInterfaceIdiom = UIUserInterfaceIdiomPad;
{$ENDIF}
{$IFDEF ANDROID}
Result := (MainActivity.getResources.getConfiguration.screenLayout and TJConfiguration.JavaClass.SCREENLAYOUT_SIZE_MASK)
>= TJConfiguration.JavaClass.SCREENLAYOUT_SIZE_LARGE;
{$ENDIF}
end;
procedure TfrmMain.LayoutForm;
begin
lytMain.Height := self.Height;
lytDrawer.Height := self.Height;
if IsPad and IsLandscape then
begin
lytDrawer.Align := TAlignLayout.alLeft;
lytMain.Align := TAlignLayout.alClient;
end
else
begin
lytDrawer.Align := TAlignLayout.alNone;
lytMain.Align := TAlignLayout.alNone;
lytMain.Width := self.Width;
if DrawerVisible then
lytMain.Position.X := lytDrawer.Position.X + lytDrawer.Width
else
lytMain.Position.X := 0;
end;
end;
procedure TfrmMain.SetDrawerVisible(const Value: boolean);
begin
if FDrawerVisible <> Value then
begin
FDrawerVisible := Value;
if DrawerVisible then
lytMain.AnimateFloat('Position.X', lytDrawer.Position.X + lytDrawer.Width)
else
lytMain.AnimateFloat('Position.X', 0);
end;
end;
end.
|
{ -$Id: PersonalCommon.pas,v 1.26 2009/03/26 08:50:04 mzagurskaya Exp $}
{******************************************************************************}
{ Автоматизированная система управления персоналом }
{ (c) Донецкий национальный университет, 2002-2004 }
{******************************************************************************}
{ Общий модуль система управления персоналом }
{ Инициализация транзакций, запроса для констант, вспомогательные процедуры }
{ ответственный: Олег Волков }
unit PersonalCommon;
interface
uses
IBDatabase, EditControl, SpComboBox, SpFormUnit, DBGrids, Forms,
IBQuery, SpCommon, Controls, Variants, Buffer, Halcn6db, SysUtils, FR_Class,
FIBDatabase, pFIBDatabase, ComCtrls, uCommonDB,
uIBXCommonDB, uFIBCommonDB, Dialogs, frxClass, ibase, DB, uTableData;
type
TMovingInfo = record
Id_Man_Moving: Integer;
FIO: string;
Department_Full: string;
PostName: string;
Date_Beg: TDate;
Date_End: TDate;
Id_Work_Mode: Integer;
end;
const
UpdateVersion = 13;
var
FIBDatabase: TpFIBDatabase;
FIBWriteTransaction: TpFIBTransaction;
FIBReadTransaction: TpFIBTransaction;
Database: TIBDatabase;
ReadTransaction: TIBTransaction;
WriteTransaction: TIBTransaction;
CurrentLogin: string;
CurrentPassword: string;
CurrentID_PCARD: Integer;
CurrentUserName: string;
DBF_PATH: string;
IMPORT_PATH: string;
Consts_Query: TIBQuery;
DepNameQuery: TIBQuery;
CurrSRQuery: TIBQuery;
FirmQuery: TIBQuery;
AdminMode: Boolean;
NoPassMode: Boolean;
CurrentDepartmentName: string;
ProgramPath: string;
sDesignReport: Boolean;
GPP: Boolean;
Test: Boolean;
NewTable: Boolean;
BufTran: TBufferTransaction; // наша транзакция для записи в dbf
Version: Integer;
ShowEasyPriem: Boolean;
Exit_Time: Variant;
Local_Exit_Time: Variant;
Id_Otdel: Integer; //Внутренний ид для системы разграничения доступа
DontWriteTableToDbf: Boolean;
Curr_SR: Integer; // штатное расписание по умолчанию
Developer: Boolean; // разработчик или нет
Curr_Tar_Plan: Integer;
NewOrders: Boolean;
FirstInstall: Boolean; // первоначальная установка: упрощенный прием и т.д.
ImportType: Integer; // тип первоначального импорта
ImportPeopleDbf: string; // откуда импортировать первоначальные данные
ImportPodrDbf: string;
ImportPostDbf: string;
NewVersion: boolean;
IBX_DB: TDBCenter;
FIB_DB: TDBCenter;
Curr_DB: TDBCenter;
TableData: TTableData;
resourcestring
SignerSQL = 'SELECT * FROM Get_Shtat_Prop_People(:Id_Shtat_Prop, :Cur_Date)';
function Select_Man_Moving(var info: TMovingInfo; Cur_Date: TDate = 0): Boolean;
procedure Init(IBX_Database: TIBDatabase; FIB_Database: TpFIBDatabase);
procedure Done;
procedure ReadCurrSR;
function GPP_Check: Boolean;
procedure ShowError(e: Exception);
function ActionFromEditMode(Mode: TEditMode): Integer;
function CheckAccess(Path: string; Action: string; DisplayMessage: Boolean = False): Integer;
procedure Log_Action(Action: string; Info: string);
function MessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Word; overload;
implementation
uses PCardsViewUnit, FieldControl, uExportReport, StdCtrls,
AccMgmt, GoodFunctionsUnit, WorkModeCentral, TableCentral, Classes,
qFStrings;
function MessageDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Word;
var
form: TForm;
b: TButton;
ModRes: Integer;
i: Integer;
begin
form := CreateMessageDialog(Msg, DlgType, Buttons);
if DlgType = mtConfirmation then
form.Caption := qFConfirmCaption;
if DlgType = mtError then
form.Caption := qFErrorCaption;
for i := 0 to form.ComponentCount - 1 do
if form.Components[i] is TButton then
begin
b := form.Components[i] as TButton;
if b.Name = 'Yes' then b.Caption := qFYesCaption;
if b.Name = 'No' then b.Caption := qFNoCaption;
end;
ModRes := form.ShowModal;
form.Free;
Result := ModRes;
end;
procedure Log_Action(Action: string; Info: string);
var
query: TIBQuery;
begin
query := TIBQuery.Create(nil);
query.Transaction := WriteTransaction;
query.SQL.Text := 'INSERT INTO Act_History(Name_Action, Act_Date, User_Login'
+ ',User_FIO, Info) VALUES(' + QuotedStr(Action) + ',CURRENT_TIMESTAMP,' +
QuotedStr(CurrentLogin) + ',' + QuotedStr(CurrentUserName) + ',' +
QuotedStr(Info) + ')';
ExecQuery(query);
query.Free;
end;
function CheckAccess(Path: string; Action: string;
DisplayMessage: Boolean = False): Integer;
var
i: Integer;
begin
i := 0;
if (not AdminMode) then
begin
// if Version=2 then уже не нужно! qizz
begin
i := fibCheckPermission(Path, Action);
if i <> 0 then
begin
if DisplayMessage then
MessageDlg(AcMgmtErrMsg(i), mtError, [mbOk], 0);
end;
end;
end;
CheckAccess := i;
end;
function GPP_Check: Boolean;
begin
if (not GPP) and (Version = 1) then
begin
MessageDlg('Редагування цього довідника провадиться тільки у ГПП!',
mtError, [mbOk], 0);
Result := False;
end
else
Result := True;
end;
procedure ReadCurrSR;
begin
CurrSRQuery.Close;
CurrSRQuery.Open;
CurrSRQuery.First;
if VarIsNull(CurrSRQuery['Id_SR']) then
Curr_SR := 1
else
Curr_SR := CurrSRQuery['Id_SR'];
if VarIsNull(CurrSRQuery['Id_Tar_Plan']) then
Curr_Tar_Plan := -1
else
Curr_Tar_Plan := CurrSRQuery['Id_Tar_Plan'];
end;
procedure Init(IBX_Database: TIBDatabase; FIB_Database: TpFIBDatabase);
begin
IBX_DATABASE.Open;
FIB_DATABASE.Open;
IBX_DB := IBXCreateDBCenter(IBX_Database.Handle);
FIB_DB := FIBCreateDBCenter(FIB_Database.Handle);
PersonalCommon.Database := IBX_Database;
PersonalCommon.ReadTransaction :=
IBX_DB.ReadTransaction.NativeTransaction as TIBTransaction;
PersonalCommon.WriteTransaction :=
IBX_DB.WriteTransaction.NativeTransaction as TIBTransaction;
PersonalCommon.FIBDatabase := FIB_Database;
PersonalCommon.FIBReadTransaction :=
FIB_DB.ReadTransaction.NativeTransaction as TpFIBTransaction;
PersonalCommon.FIBWriteTransaction :=
FIB_DB.WriteTransaction.NativeTransaction as TpFIBTransaction;
// проинициализировать SpLib
SpInit(IBX_Database.Handle);
EditControl.UpdateQuery.Transaction := WriteTransaction;
// Открыть запрос для констант
Consts_Query.Transaction := ReadTransaction;
Consts_Query.SQL.Text := 'Select * from INI_ASUP_CONSTS';
Consts_Query.Open;
//Открыть запрос для получения названия текущего подр.
DepNameQuery.Transaction := ReadTransaction;
DepNameQuery.SQL.Text := 'Select Name_Short, NAME_FULL FROM SP_DEPARTMENT WHERE ID_DEPARTMENT='
+ IntToStr(Consts_Query['LOCAL_DEPARTMENT']) +
' AND CURRENT_TIMESTAMP BETWEEN Use_Beg AND Use_End';
DepNameQuery.Open;
// получить идентификатор штатного расписания по умолчанию
CurrSRQuery.Transaction := ReadTransaction;
CurrSRQuery.SQL.Text := 'SELECT * FROM Get_Current_SR(CURRENT_DATE)';
ReadCurrSR;
DefaultDateBeg := Date {Consts_Query['Date_Beg']};
DefaultDateEnd := Consts_Query['Date_End'];
// if Consts_Query['Current_Department'] = 2612 then
GPP := True; //
{ else
GPP := False;}
ProgramPath := ExtractFilePath(Application.ExeName);
if ProgramPath = Application.ExeName then ProgramPath := '';
BufferTable := THalcyonDataset.Create(nil);
BufferTable.DatabaseName := Dbf_Path;
BufferTransaction := TIBTransaction.Create(nil);
BufferTransaction.DefaultDatabase := Database;
BufferReadTransaction := WriteTransaction;
// загрузить режимы работы, календарь, типы выходов
WorkModeCenter := TWorkModeCenter.Create(ReadTransaction);
WorkModeCenter.ReLoad;
Calendar := TCalendar.Create(ReadTransaction);
Calendar.ReLoad;
AllVihods := TAllVihods.Create(ReadTransaction);
AllVihods.ReLoad;
Curr_DB := IBX_DB;
// загрузить датамодуль для табеля
TableData := TTableData.Create(nil, FIBDatabase.Handle);
FirmQuery := TIBQuery.Create(nil);
FirmQuery.Transaction := ReadTransaction;
FirmQuery.SQL.Text := 'select cust.SHORT_NAME as NAME from PUB_SYS_DATA s,' +
' PUB_SP_CUSTOMER cust where cust.ID_CUSTOMER = s.ORGANIZATION';
FirmQuery.Open;
InitBuffer(WriteTransaction, ReadTransaction, DontWriteToDbf, Version = 1);
end;
procedure Done;
begin
// ФИБы и не только очень любят глючить...
try
TableData.Free;
SpDone;
IBX_DB.Free;
FIB_DB.Free;
BufferTable.Free;
BufferTransaction.Free;
WorkModeCenter.Free;
Calendar.Free;
AllVihods.Free;
except
end;
end;
procedure ShowError(e: Exception);
begin
if e.Message <> '' then
MessageDlg('При занесенні у базу даних виникла помилка: ' + e.Message,
mtError, [mbOk], 0);
end;
function ActionFromEditMode(Mode: TEditMode): Integer;
begin
if Mode = emNew then
Result := 1
else
Result := 2;
end;
function Select_Man_Moving(var info: TMovingInfo; Cur_Date: TDate = 0): Boolean;
var
//pform: TPCardsViewForm;
new_id_pcard: integer;
mform: TSpForm;
params: TSpParams;
sql: string;
q: TIBQuery;
begin
if Cur_Date = 0 then Cur_Date := Date;
new_id_pcard := getpcard(Cur_date);
//if pform.ShowModal = mrOk then
if new_id_pcard <> -1 then
begin
sql := 'GET_PCARD_MOVINGS(' +
//IntToStr(pform.ResultQuery['Id_PCard']) +
IntToStr(new_id_pcard) + ',''' + DateToStr(Cur_Date) + ''')';
q := TIBQuery.Create(nil);
q.Transaction := ReadTransaction;
q.SQL.Text := 'SELECT * FROM ' + sql;
q.Open;
q.FetchAll;
// если у человека одно место работы, возвратить его
if q.RecordCount = 1 then
begin
with info do
begin
Id_Man_Moving := q['Id_Man_Moving'];
Department_Full := q['Name_Department_Full'];
PostName := q['Post'];
Date_Beg := q['Date_Beg'];
Date_End := q['Date_End'];
//FIO := pform.ResultQuery['FIO'];
FIO := GoodFunctionsUnit.Fam;
Id_Work_Mode := q['Id_Work_Mode'];
end;
Result := True;
//pform.Free;
Exit;
end;
q.Free;
// показать список мест работы если их несколько
mform := TSpForm.Create(nil);
params := TSpParams.Create;
with params do
begin
IdField := 'ID_MAN_MOVING';
SpFields := 'NAME_DEPARTMENT_FULL, POST, DATE_BEG, DATE_END, Id_Work_Mode';
Title := 'Виберіть місце, де працює ' +
//pform.ResultQuery['FIO'];
GoodFunctionsUnit.Fam;
ColumnNames := 'Підрозділ,Посада, Дата початку,Дата кінця,-';
ReadOnly := True;
Table := sql;
SpMode := spmSelect;
end;
mform.Init(params);
mform.Caption := params.Title;
with mform do
if ShowModal = mrOk then
begin
with info do // забрать данные
begin
Id_Man_Moving := ResultQuery['Id_Man_Moving'];
Department_Full := ResultQuery['Name_Department_Full'];
PostName := ResultQuery['Post'];
Date_Beg := ResultQuery['Date_Beg'];
Date_End := ResultQuery['Date_End'];
//FIO := pform.ResultQuery['FIO'];
FIO := GoodFunctionsUnit.Fam;
Id_Work_Mode := ResultQuery['Id_Work_Mode'];
end;
Result := True;
end
else
Result := False; // пользователь отказался от выбора
mform.Free;
params.Free;
end
else
Result := False; // пользователь отказался от выбора
//pform.Free;
end;
initialization
Consts_Query := TIBQuery.Create(nil);
DepNameQuery := TIBQuery.Create(nil);
CurrSRQuery := TIBQuery.Create(nil);
BufTran := TBufferTransaction.Create;
finalization
Consts_Query.Free;
DepNameQuery.Free;
CurrSRQuery.Free;
BufTran.Free;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Controller relacionado aos procedimentos de venda
The MIT License
Copyright: Copyright (C) 2010 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
******************************************************************************* }
unit VendaController;
interface
uses
Classes, SysUtils, NfeCabecalhoVO, NfeDetalheVO, md5, ZDataset,
VO, Controller, Biblioteca, NfeFormaPagamentoVO;
type
TVendaController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaNfeCabecalhoVO;
class function ConsultaObjeto(pFiltro: String): TNfeCabecalhoVO;
class function VendaDetalhe(pFiltro: String): TNfeDetalheVO;
class function Insere(pObjeto: TNfeCabecalhoVO): TNfeCabecalhoVO;
class function InsereItem(pObjeto: TNfeDetalheVO): TNfeDetalheVO;
class function Altera(pObjeto: TNfeCabecalhoVO): Boolean;
class function CancelaVenda(pObjeto: TNfeCabecalhoVO): Boolean;
class function CancelaItemVenda(pItem: Integer): Boolean;
end;
implementation
uses T2TiORM, NfceMovimentoController, ProdutoController, ControleEstoqueController,
NfeDestinatarioVO, NfeDetalheImpostoIcmsVO;
var
ObjetoLocal: TNfeCabecalhoVO;
class function TVendaController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TNfeCabecalhoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TVendaController.ConsultaLista(pFiltro: String): TListaNfeCabecalhoVO;
begin
try
ObjetoLocal := TNfeCabecalhoVO.Create;
Result := TListaNfeCabecalhoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TVendaController.ConsultaObjeto(pFiltro: String): TNfeCabecalhoVO;
var
Filtro: String;
i: Integer;
begin
try
Result := TNfeCabecalhoVO.Create;
Result := TNfeCabecalhoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
if Assigned(Result) then
begin
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Filtro := 'ID_NFE_CABECALHO = ' + IntToStr(Result.Id);
Result.NfeDestinatarioVO := TNfeDestinatarioVO(TT2TiORM.ConsultarUmObjeto(Result.NfeDestinatarioVO, Filtro, True));
if not Assigned(Result.NfeDestinatarioVO) then
Result.NfeDestinatarioVO := TNfeDestinatarioVO.Create;
Result.ListaNfeDetalheVO := TListaNfeDetalheVO(TT2TiORM.Consultar(TNfeDetalheVO.Create, Filtro, True));
for I := 0 to Result.ListaNfeDetalheVO.Count - 1 do
begin
Filtro := 'ID_NFE_DETALHE='+IntToStr(Result.ListaNfeDetalheVO[I].Id);
Result.ListaNfeDetalheVO[I].NfeDetalheImpostoIcmsVO := TNfeDetalheImpostoIcmsVO.Create;
Result.ListaNfeDetalheVO[I].NfeDetalheImpostoIcmsVO := TNfeDetalheImpostoIcmsVO(TT2TiORM.ConsultarUmObjeto(Result.ListaNfeDetalheVO[I].NfeDetalheImpostoIcmsVO, Filtro, True));
end;
end;
finally
end;
end;
class function TVendaController.VendaDetalhe(pFiltro: String): TNfeDetalheVO;
var
Filtro: String;
begin
try
Result := TNfeDetalheVO.Create;
Result := TNfeDetalheVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
//Exercício: crie o método para popular esses objetos automaticamente no T2TiORM
Result.ProdutoVO := TProdutoController.ConsultaObjeto('ID='+IntToStr(Result.IdProduto));
Filtro := 'ID_NFE_DETALHE='+IntToStr(Result.Id);
Result.NfeDetalheImpostoIcmsVO := TNfeDetalheImpostoIcmsVO(TT2TiORM.ConsultarUmObjeto(Result.NfeDetalheImpostoIcmsVO, Filtro, True));
finally
end;
end;
class function TVendaController.Insere(pObjeto: TNfeCabecalhoVO): TNfeCabecalhoVO;
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
{ Destinatario }
if pObjeto.NfeDestinatarioVO.CpfCnpj <> '' then
begin
pObjeto.NfeDestinatarioVO.IdNfeCabecalho := UltimoID;
TT2TiORM.Inserir(pObjeto.NfeDestinatarioVO);
end;
Result := ConsultaObjeto('ID=' + IntToStr(UltimoID));
finally
end;
end;
class function TVendaController.InsereItem(pObjeto: TNfeDetalheVO): TNfeDetalheVO;
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
TControleEstoqueController.AtualizarEstoque(pObjeto.QuantidadeComercial * -1, pObjeto.IdProduto, Sessao.VendaAtual.IdEmpresa, Sessao.Configuracao.EmpresaVO.TipoControleEstoque);
{ Detalhe - Imposto - ICMS }
pObjeto.NfeDetalheImpostoIcmsVO.IdNfeDetalhe := UltimoID;
TT2TiORM.Inserir(pObjeto.NfeDetalheImpostoIcmsVO);
Result := VendaDetalhe('ID = ' + IntToStr(UltimoID));
finally
end;
end;
class function TVendaController.Altera(pObjeto: TNfeCabecalhoVO): Boolean;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
{ Destinatario }
if pObjeto.NfeDestinatarioVO.Id > 0 then
Result := TT2TiORM.Alterar(pObjeto.NfeDestinatarioVO)
else
begin
pObjeto.NfeDestinatarioVO.IdNfeCabecalho := pObjeto.Id;
Result := TT2TiORM.Inserir(pObjeto.NfeDestinatarioVO) > 0;
end;
finally
end;
end;
class function TVendaController.CancelaVenda(pObjeto: TNfeCabecalhoVO): Boolean;
var
I: Integer;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
// Detalhes
for I := 0 to pObjeto.ListaNfeDetalheVO.Count - 1 do
begin
Result := TT2TiORM.Alterar(pObjeto.ListaNfeDetalheVO[I])
end;
// Pagamentos
for I := 0 to pObjeto.ListaNfeFormaPagamentoVO.Count - 1 do
begin
pObjeto.ListaNfeFormaPagamentoVO[I].Estorno := 'S';
Result := TT2TiORM.Alterar(pObjeto.ListaNfeFormaPagamentoVO[I])
end;
finally
end;
end;
class function TVendaController.CancelaItemVenda(pItem: Integer): Boolean;
var
NfeDetalhe: TNfeDetalheVO;
begin
try
NfeDetalhe := TNfeDetalheVO.Create;
NfeDetalhe := TNfeDetalheVO((TT2TiORM.ConsultarUmObjeto(NfeDetalhe, 'NUMERO_ITEM=' + IntToStr(pitem) + ' AND ID_NFE_CABECALHO=' + IntToStr(Sessao.VendaAtual.Id), True)));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_COFINS where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_PIS where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_ICMS where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_II where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_IPI where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE_IMPOSTO_ISSQN where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DET_ESPECIFICO_COMBUSTIVEL where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DET_ESPECIFICO_VEICULO where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DET_ESPECIFICO_ARMAMENTO where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DET_ESPECIFICO_MEDICAMENTO where ID_NFE_DETALHE = ' + IntToStr(NfeDetalhe.Id));
// Exercício - atualize o estoque
Result := TT2TiORM.ComandoSQL('DELETE FROM NFE_DETALHE where ID = ' + IntToStr(NfeDetalhe.Id));
finally
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082358
////////////////////////////////////////////////////////////////////////////////
unit java.nio.file.attribute.FileTime;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.concurrent.TimeUnit,
java.time.chrono.ChronoLocalDate;
type
JFileTime = interface;
JFileTimeClass = interface(JObjectClass)
['{214C131B-9077-4BF3-8FEF-E692F13AAC87}']
function &to(&unit : JTimeUnit) : Int64; cdecl; // (Ljava/util/concurrent/TimeUnit;)J A: $1
function compareTo(other : JFileTime) : Integer; cdecl; // (Ljava/nio/file/attribute/FileTime;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function from(instant : JInstant) : JFileTime; cdecl; overload; // (Ljava/time/Instant;)Ljava/nio/file/attribute/FileTime; A: $9
function from(value : Int64; &unit : JTimeUnit) : JFileTime; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/nio/file/attribute/FileTime; A: $9
function fromMillis(value : Int64) : JFileTime; cdecl; // (J)Ljava/nio/file/attribute/FileTime; A: $9
function hashCode : Integer; cdecl; // ()I A: $1
function toInstant : JInstant; cdecl; // ()Ljava/time/Instant; A: $1
function toMillis : Int64; cdecl; // ()J A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
[JavaSignature('java/nio/file/attribute/FileTime')]
JFileTime = interface(JObject)
['{94462DB0-2F58-43BB-AC89-DCE428D35C26}']
function &to(&unit : JTimeUnit) : Int64; cdecl; // (Ljava/util/concurrent/TimeUnit;)J A: $1
function compareTo(other : JFileTime) : Integer; cdecl; // (Ljava/nio/file/attribute/FileTime;)I A: $1
function equals(obj : JObject) : boolean; cdecl; // (Ljava/lang/Object;)Z A: $1
function hashCode : Integer; cdecl; // ()I A: $1
function toInstant : JInstant; cdecl; // ()Ljava/time/Instant; A: $1
function toMillis : Int64; cdecl; // ()J A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJFileTime = class(TJavaGenericImport<JFileTimeClass, JFileTime>)
end;
implementation
end.
|
unit FileOperations;
{This unit contains the service functions and
procedures for file and directory operations.}
interface
uses files, Classes, ComCTRLS, StdCtrls, SysUtils, GOBLFD, WAD, LAB;
Const
{OpenFileWrite flags}
fm_Create=1; {Create new file}
fm_LetReWrite=2;{Let rewrite file
if exists - OpenFileWrite}
fm_AskUser=4; {Ask user if something}
fm_CreateAskRewrite=fm_Create+fm_LetRewrite+fm_AskUser;
{OpenFileRead&Write flags}
fm_Share=8; {Let share file}
fm_Buffered=16;
Type
TWildCardMask=class
private
masks:TStringList;
Procedure SetMask(s:string);
Function GetMask:String;
Public
Constructor Create;
Property mask:String read GetMask Write SetMask;
Procedure AddTrailingAsterisks;
Function Match(s:String):boolean;
end;
TMaskedDirectoryControl=class
Dir:TContainerFile;
LBDir:TListBox;
LVDir:TListView;
Mask:String;
control_type:(LBox,LView);
LastViewStyle:TViewStyle;
Constructor CreateFromLB(L:TlistBox); {ListBox}
Constructor CreateFromLV(L:TlistView); {ListView}
Procedure SetDir(D:TContainerFile);
Procedure SetMask(mask:string);
Private
Procedure AddFile(s:string);
Procedure ClearControl;
Procedure BeginUpdate;
Procedure EndUpdate;
end;
Function OpenFileRead(path:TFileName;mode:word):TFile;
Function OpenFileWrite(path:TFileName;mode:word):TFile;
Function IsContainer(path:TFileName):boolean;
Function OpenContainer(path:TFileName):TContainerFile;
Function ExtractExt(path:String):String;
Function ExtractPath(path:String):String;
Function ExtractName(path:String):String;
implementation
Function GetQuote(ps,quote:pchar):pchar;
var p,p1:pchar;
begin
if ps^ in ['?','*'] then
begin
GetQuote:=ps+1;
quote^:=ps^;
(quote+1)^:=#0;
exit;
end;
p:=StrScan(ps,'?'); if p=nil then p:=StrEnd(ps);
p1:=StrScan(ps,'*'); if p1=nil then p1:=StrEnd(ps);
if p>p1 then p:=p1;
StrLCopy(quote,ps,p-ps);
GetQuote:=p;
end;
Function WildCardMatch(mask,s:string):boolean;
var pmask,ps,p:pchar;
quote:array[0..100] of char;
begin
{ mask[length(mask)+1]:=#0;
s[length(s)+1]:=#0;}
result:=false;
pmask:=@mask[1];
ps:=@s[1];
While Pmask^<>#0 do
begin
pmask:=GetQuote(pmask,quote);
case Quote[0] of
'?': if ps^<>#0 then inc(ps);
'*': begin
p:=GetQuote(pmask,quote);
if quote[0] in ['*','?'] then continue;
if Quote[0]=#0 then begin ps:=StrEnd(ps); continue; end;
pmask:=p;
p:=StrPos(ps,quote);
if p=nil then exit;
ps:=p+StrLen(quote);
end;
else if StrLComp(ps,quote,StrLen(quote))=0 then inc(ps,StrLen(quote)) else exit;
end;
end;
if ps^=#0 then result:=true;
end;
Function ParseMasks(m:string):TStringList;{ mask -> masks string list. ie to handle "*.txt;*.asc" type masks}
var p,ps:Pchar;
s:array[0..255] of char;
Msk:TStringList;
begin
msk:=TStringList.Create;
if m='' then
begin
Msk.Add('');
Result:=msk;
exit;
end;
ps:=@m[1];
Repeat
p:=StrScan(ps,';');
if p=nil then p:=StrEnd(ps);
StrLCopy(s,Ps,p-ps);
Msk.Add(UpperCase(s));
ps:=p; if ps^=';' then inc(ps);
Until PS^=#0;
Result:=msk;
end;
Procedure TWildCardMask.SetMask(s:string);
begin
if masks<>nil then masks.free;
masks:=ParseMasks(s);
end;
Function TWildCardMask.GetMask:String;
var i:Integer;
begin
Result:='';
for i:=0 to masks.count-1 do Result:=Concat(Result,masks[i]);
end;
Procedure TWildCardMask.AddTrailingAsterisks;
var i:integer;s:string;
begin
for i:=0 to masks.count-1 do
begin
s:=masks[i];
if s='' then s:='*'
else if s[length(s)]<>'*' then s:=s+'*';
masks[i]:=s;
end;
end;
Function TWildCardMask.Match(s:String):boolean;
var i:integer;
begin
s:=UpperCase(s);
Result:=false;
for i:=0 to masks.count-1 do
begin
Result:=Result or WildCardMatch(masks.Strings[j],s);
if Result then break;
end;
end;
Type
ct_type=(ct_unknown,ct_gob,ct_wad,ct_lab);
Function WhatContainer(Path:String):ct_type;
var ext:String;
begin
Result:=ct_unknown;
if not FileExists(path) then exit;
Ext:=UpperCase(ExtractFileExt(path));
if ext='.WAD' then result:=ct_wad
else if ext='.GOB' then result:=ct_gob
else if ext='.LAB' then result:=ct_lab;
end;
Function IsContainer(path:TFileName):boolean;
begin
Result:=WhatContainer(path)<>ct_unknown;
end;
Function OpenContainer(path:TFileName):TContainerFile;
begin
Case WhatContainer(Path) of
ct_gob: Result:=TGOBDirectory.CreateOpen(path);
ct_wad: Result:=TWADDirectory.CreateOpen(path);
ct_lab: Result:=TLABDirectory.CreateOpen(path);
else Raise Exception.Create(Path+' is not a container');
end;
end;
Function OpenFileRead(path:TFileName;mode:word):TFile;
begin
Result:=TDiskFile.CreateRead(path);
end;
Function OpenFileWrite(path:TFileName;mode:word):TFile;
begin
Result:=TDiskFile.CreateWrite(path);
end;
Procedure TMaskedDirectoryControl.ClearControl;
begin
Case Control_type of
LBox: LbDir.Items.Clear;
LView: LVdir.Items.Clear;
end;
end;
Procedure TMaskedDirectoryControl.SetDir(D:TContainerFile);
var s:String;i:integer;
begin
Dir:=d;
if control_type=LBox then
begin
s:=''; for i:=0 to d.AvgFileNameLength-1 do s:=s+Chr(Ord('A')+i);
LBDir.Columns:=lBDir.Width div lBDir.canvas.TextWidth(s);
end;
end;
Constructor TMaskedDirectoryControl.CreateFromLB(L:TlistBox);
begin
LBDir:=l;
control_type:=LBox;
Mask:='*.*';
end;
Constructor TMaskedDirectoryControl.CreateFromLV(L:TlistView);
begin
LVDir:=l;
control_type:=LView;
Mask:='*.*'
end;
Function AddAsteriscs(mask:String):String;
var p,ps:pchar;
begin
if mask='' then begin result:='*'; exit; end;
Result:=mask;
ps:=@result[1];
Repeat
p:=StrScan(ps,';'); if p=nil then break;
if (p-1)^<>'*' then Insert('*',Result,p-@Result[1]+1);
ps:=p+2;
Until false;
if Result[length(Result)] in ['*',';'] then
else Result:=Concat(Result,'*');
end;
Procedure TMaskedDirectoryControl.BeginUpdate;
begin
Case Control_type of
LBox: begin
LBDir.Sorted:=false;
LBDir.Items.BeginUpdate;
end;
LView: begin
LastViewStyle:=LVDir.ViewStyle;
LVDir.ViewStyle:=vsReport;
LVDir.Items.BeginUpdate;
end;
end;
end;
Procedure TMaskedDirectoryControl.EndUpdate;
begin
Case Control_type of
LBox: begin
LBDir.Items.EndUpdate;
end;
LView: begin
LVDir.ViewStyle:=LastViewStyle;
LVDir.Items.EndUpdate;
end;
end;
end;
procedure TMaskedDirectoryControl.AddFile;
var LI:TListItem;
begin
Case Control_type of
LBox: LBDir.Items.Add(s);
LView: With LVDir.Items do
begin
Li:=Add;
Li.Caption:=s;
end;
end;
end;
Procedure TMaskedDirectoryControl.SetMask(mask:string);
var Masks,Ts:TStringList;
i,j:integer;s:string;
match:boolean;
begin
ClearControl;
Mask:=AddAsteriscs(mask);
Masks:=ParseMasks(mask);
ts:=Dir.ListFiles;
BeginUpdate;
for i:=0 to ts.count-1 do
begin
s:=UpperCase(ts.Strings[i]);
match:=false;
for j:=0 to masks.count-1 do
begin
match:=match or WildCardMatch(masks.Strings[j],s);
if match then begin AddFile(ts.Strings[i]); break; end;
end;
end;
EndUpdate;
masks.free;
end;
Function ExtractExt(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFileExt(path);
end;
Function ExtractPath(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFilePath(Path);
if p<>0 then Result[p]:='>';
end;
Function ExtractName(path:String):String;
var p:integer;
begin
p:=Pos('>',path);
if p<>0 then path[p]:='\';
Result:=ExtractFileName(Path);
end;
end.
|
unit Invoice.Model.OrderPayment;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
Invoice.Model.Order,
Invoice.Model.TypePayment,
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('Invoice.dbo.OrderPayment', '')]
[PrimaryKey('idOrder', NotInc, NoSort, False, 'Chave primária')]
[PrimaryKey('amountOrder', NotInc, NoSort, False, 'Chave primária')]
TOrderPayment = class
private
{ Private declarations }
FidOrder: Integer;
FamountOrder: Integer;
FidTypePayment: Integer;
FdataPayment: TDateTime;
FvaluePayment: Currency;
FOrder_0: TOrder;
FTypePayment_1: TTypePayment;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
[Restrictions([NotNull])]
[Column('idOrder', ftInteger)]
[ForeignKey('Order', 'idOrder', SetNull, SetNull)]
[Dictionary('idOrder', 'Mensagem de validação', '', '', '', taCenter)]
property idOrder: Integer Index 0 read FidOrder write FidOrder;
[Restrictions([NotNull])]
[Column('amountOrder', ftInteger)]
[Dictionary('amountOrder', 'Mensagem de validação', '', '', '', taCenter)]
property amountOrder: Integer Index 1 read FamountOrder write FamountOrder;
[Restrictions([NotNull])]
[Column('idTypePayment', ftInteger)]
[ForeignKey('TypePayment', 'idTypePayment', SetNull, SetNull)]
[Dictionary('idTypePayment', 'Mensagem de validação', '', '', '', taCenter)]
property idTypePayment: Integer Index 2 read FidTypePayment write FidTypePayment;
[Restrictions([NotNull])]
[Column('dataPayment', ftDateTime)]
[Dictionary('dataPayment', 'Mensagem de validação', 'Now', '', '!##/##/####;1;_', taCenter)]
property dataPayment: TDateTime Index 3 read FdataPayment write FdataPayment;
[Restrictions([NotNull])]
[Column('valuePayment', ftCurrency)]
[Dictionary('valuePayment', 'Mensagem de validação', '0', '', '', taRightJustify)]
property valuePayment: Currency Index 4 read FvaluePayment write FvaluePayment;
[Association(OneToOne,'idOrder','idOrder')]
property Order: TOrder read FOrder_0 write FOrder_0;
[Association(OneToOne,'idTypePayment','idTypePayment')]
property TypePayment: TTypePayment read FTypePayment_1 write FTypePayment_1;
end;
implementation
constructor TOrderPayment.Create;
begin
FOrder_0 := TOrder.Create;
FTypePayment_1 := TTypePayment.Create;
end;
destructor TOrderPayment.Destroy;
begin
FOrder_0.Free;
FTypePayment_1.Free;
inherited;
end;
initialization
TRegisterClass.RegisterEntity(TOrderPayment)
end.
|
unit ufrmDialogTipePengirimanPO;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, StdCtrls,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button, uInterface,
uModTipeKirimPO;
type
TfrmDialogTipePengirimanPO = class(TfrmMasterDialog, ICrudAble)
lbl1: TLabel;
lbl2: TLabel;
edtKodeTipePengirimanPO: TEdit;
edtTipePengirimanPO: TEdit;
procedure actDeleteExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
private
FModTipeKirimPO: TModTipeKirimPO;
function GetModTipeKirimPO: TModTipeKirimPO;
procedure LoadData(aID: string = '');
procedure SaveData;
property ModTipeKirimPO: TModTipeKirimPO read GetModTipeKirimPO write
FModTipeKirimPO;
public
end;
var
frmDialogTipePengirimanPO: TfrmDialogTipePengirimanPO;
implementation
uses uTSCommonDlg,uRetnoUnit, ufrmTipePengirimanPO, uDMClient, uAppUtils,
uConstanta, uDXUtils;
{$R *.dfm}
procedure TfrmDialogTipePengirimanPO.actDeleteExecute(Sender: TObject);
begin
inherited;
if TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE)<>True then exit;
Try
DMClient.CrudClient.DeleteFromDB(ModTipeKirimPO);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult:=mrOk;
Except
TAppUtils.Error(ER_DELETE_FAILED);
Raise;
end;
end;
procedure TfrmDialogTipePengirimanPO.FormCreate(Sender: TObject);
begin
inherited;
Self.AssignKeyDownEvent;
end;
procedure TfrmDialogTipePengirimanPO.actSaveExecute(Sender: TObject);
begin
inherited;
SaveData;
end;
function TfrmDialogTipePengirimanPO.GetModTipeKirimPO: TModTipeKirimPO;
begin
if not assigned(FModTipeKirimPO) then
FModTipeKirimPO:=TModTipeKirimPO.Create;
Result := FModTipeKirimPO;
end;
procedure TfrmDialogTipePengirimanPO.LoadData(aID: string = '');
begin
FreeAndNil(FModTipeKirimPO);
FModTipeKirimPO:= Dmclient.CrudClient.Retrieve(TModTipeKirimPO.ClassName,aID) as TModTipeKirimPO;
edtKodeTipePengirimanPO.Text:=ModTipeKirimPO.TPKRMPO_CODE;
edtTipePengirimanPO.Text:=ModTipeKirimPO.TPKRMPO_NAME;
end;
procedure TfrmDialogTipePengirimanPO.SaveData;
begin
if not ValidateEmptyCtrl then exit;
ModTipeKirimPO.TPKRMPO_CODE:=edtKodeTipePengirimanPO.Text;
ModTipeKirimPO.TPKRMPO_NAME:=edtTipePengirimanPO.Text;
Try
DMClient.CrudClient.SaveToDB(ModTipeKirimPO);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
Self.ModalResult:=mrOk;
Except
TAppUtils.Error(ER_INSERT_FAILED);
Raise;
End;
end;
end.
|
unit uDBContext;
interface
uses
Generics.Collections,
Winapi.Windows,
System.SysUtils,
System.Classes,
Data.DB,
Dmitry.CRC32,
Dmitry.Utils.System,
UnitINI,
uConstants,
uDBForm,
uSettings,
uDBConnection,
uDBClasses,
uDBScheme,
uDBEntities;
type
IMediaRepository = interface
function GetIdByFileName(FileName: string): Integer;
function GetFileNameById(ID: Integer): string;
procedure SetFileNameById(ID: Integer; FileName: string);
procedure SetAccess(ID, Access: Integer);
procedure SetRotate(ID, Rotate: Integer);
procedure SetRating(ID, Rating: Integer);
procedure SetAttribute(ID, Attribute: Integer);
procedure DeleteFromCollection(FileName: string; ID: Integer);
procedure DeleteFromCollectionEx(IDs: TList<Integer>);
procedure PermanentlyDeleteFromCollectionEx(IDs: TList<Integer>);
procedure DeleteDirectoryFromCollection(FirectoryName: string);
function GetCount: Integer;
function GetMenuItemByID(ID: Integer): TMediaItem;
function GetMenuItemsByID(ID: Integer): TMediaItemCollection;
function GetMenuInfosByUniqId(UniqId: string): TMediaItemCollection;
procedure UpdateMediaInfosFromDB(Info: TMediaItemCollection);
function UpdateMediaFromDB(Media: TMediaItem; LoadThumbnail: Boolean): Boolean;
procedure IncMediaCounter(ID: Integer);
procedure UpdateLinks(ID: Integer; NewLinks: string);
function GetTopImagesWithPersons(MinDate: TDateTime; MaxItems: Integer): TMediaItemCollection;
procedure RefreshImagesCache;
end;
IGroupsRepository = interface
function GetAll(LoadImages: Boolean; SortByName: Boolean; UseInclude: Boolean = False): TGroups;
function Add(Group: TGroup): Boolean;
function Update(Group: TGroup): Boolean;
function Delete(Group: TGroup): Boolean;
function GetByCode(GroupCode: string; LoadImage: Boolean): TGroup;
function GetByName(GroupName: string; LoadImage: Boolean): TGroup;
function FindCodeByName(GroupName: string): string;
function FindNameByCode(GroupCode: string): string;
function HasGroupWithCode(GroupCode: string): Boolean;
function HasGroupWithName(GroupName: string): Boolean;
end;
const
PERSON_TYPE = 1;
type
TPersonFoundCallBack = reference to procedure(P: TPerson; var StopOperation: Boolean);
IPeopleRepository = interface
procedure LoadPersonList(Persons: TPersonCollection);
procedure LoadTopPersons(CallBack: TPersonFoundCallBack);
function FindPerson(PersonID: Integer; Person: TPerson): Boolean; overload;
function FindPerson(PersonName: string; Person: TPerson): Boolean; overload;
function GetPerson(PersonID: Integer; LoadImage: Boolean): TPerson;
function GetPersonByName(PersonName: string): TPerson;
function RenamePerson(PersonName, NewName: string): Boolean;
function CreateNewPerson(Person: TPerson): Integer;
function DeletePerson(PersonID: Integer): Boolean; overload;
function DeletePerson(PersonName: string): Boolean; overload;
function UpdatePerson(Person: TPerson; UpdateImage: Boolean): Boolean;
function GetPersonsOnImage(ImageID: Integer): TPersonCollection;
function GetPersonsByNames(Persons: TStringList): TPersonCollection;
function GetAreasOnImage(ImageID: Integer): TPersonAreaCollection;
function AddPersonForPhoto(Sender: TDBForm; PersonArea: TPersonArea): Boolean;
function RemovePersonFromPhoto(ImageID: Integer; PersonArea: TPersonArea): Boolean;
function ChangePerson(PersonArea: TPersonArea; ToPersonID: Integer): Boolean;
procedure FillLatestSelections(Persons: TPersonCollection);
procedure MarkLatestPerson(PersonID: Integer);
function UpdatePersonArea(PersonArea: TPersonArea): Boolean;
function UpdatePersonAreaCollection(PersonAreas: TPersonAreaCollection): Boolean;
end;
ISettingsRepository = interface
function Get: TSettings;
function Update(Options: TSettings): Boolean;
end;
IDBContext = interface
function IsValid: Boolean;
function GetCollectionFileName: string;
property CollectionFileName: string read GetCollectionFileName;
//low-level
function CreateQuery(IsolationLevel: TDBIsolationLevel = dbilReadWrite): TDataSet;
//middle-level
function CreateSelect(TableName: string): TSelectCommand;
function CreateUpdate(TableName: string; Background: Boolean = False): TUpdateCommand;
function CreateInsert(TableName: string): TInsertCommand;
function CreateDelete(TableName: string): TDeleteCommand;
//repositories
function Settings: ISettingsRepository;
function Groups: IGroupsRepository;
function People: IPeopleRepository;
function Media: IMediaRepository;
end;
TBaseRepository<T: TBaseEntity> = class(TInterfacedObject)
private
FContext: IDBContext;
public
constructor Create(Context: IDBContext); virtual;
property Context: IDBContext read FContext;
end;
TDBContext = class(TInterfacedObject, IDBContext)
private
FCollectionFile: string;
FIsValid: Boolean;
function InitCollection: Boolean;
public
//function CreateSelect: TSelectCommand;
constructor Create(CollectionFile: string);
function IsValid: Boolean;
function GetCollectionFileName: string;
//low-level
function CreateQuery(IsolationLevel: TDBIsolationLevel = dbilReadWrite): TDataSet;
//middle-level
function CreateSelect(TableName: string): TSelectCommand;
function CreateUpdate(TableName: string; Background: Boolean = False): TUpdateCommand;
function CreateInsert(TableName: string): TInsertCommand;
function CreateDelete(TableName: string): TDeleteCommand;
//todo: high-level
//repositories
function Settings: ISettingsRepository;
function Groups: IGroupsRepository;
function People: IPeopleRepository;
function Media: IMediaRepository;
end;
implementation
uses
uMediaRepository,
uGroupsRepository,
uPeopleRepository,
uSettingsRepository;
{ TDBContext }
constructor TDBContext.Create(CollectionFile: string);
begin
FCollectionFile := CollectionFile;
FIsValid := InitCollection;
end;
function TDBContext.InitCollection: Boolean;
var
Section: TBDRegistry;
Version: Integer;
begin
Result := False;
Section := uSettings.AppSettings.GetSection(RegRoot + 'CollectionSettings\' + IntToHex(Integer(StringCRC(FCollectionFile)), 8) + '_' + ProductVersion, False);
Version := Section.ReadInteger('Version');
if Version < CURRENT_DB_SCHEME_VERSION then
begin
if TDBScheme.IsOldColectionFile(FCollectionFile) then
TDBScheme.UpdateCollection(FCollectionFile, Version, True);
if TDBScheme.IsValidCollectionFile(FCollectionFile) then
Result := True;
if Result then
Section.WriteInteger('Version', CURRENT_DB_SCHEME_VERSION);
end else
Result := True;
end;
function TDBContext.IsValid: Boolean;
begin
Result := FIsValid;
end;
function TDBContext.Media: IMediaRepository;
begin
Result := TMediaRepository.Create(Self);
end;
function TDBContext.People: IPeopleRepository;
begin
Result := TPeopleRepository.Create(Self);
end;
function TDBContext.GetCollectionFileName: string;
begin
Result := FCollectionFile;
end;
function TDBContext.Settings: ISettingsRepository;
begin
Result := TSettingsRepository.Create(Self);
end;
function TDBContext.Groups: IGroupsRepository;
begin
Result := TGroupsRepository.Create(Self);
end;
function TDBContext.CreateQuery(IsolationLevel: TDBIsolationLevel): TDataSet;
begin
Result := GetQuery(FCollectionFile, False, IsolationLevel);
end;
function TDBContext.CreateInsert(TableName: string): TInsertCommand;
begin
Result := TInsertCommand.Create(TableName, FCollectionFile);
end;
function TDBContext.CreateSelect(TableName: string): TSelectCommand;
begin
Result := TSelectCommand.Create(TableName, FCollectionFile, False, dbilRead);
end;
function TDBContext.CreateUpdate(TableName: string; Background: Boolean = False): TUpdateCommand;
const
Isolations: array[Boolean] of TDBIsolationLevel = (dbilReadWrite, dbilBackgroundWrite);
begin
Result := TUpdateCommand.Create(TableName, FCollectionFile, Isolations[Background]);
end;
function TDBContext.CreateDelete(TableName: string): TDeleteCommand;
begin
Result := TDeleteCommand.Create(TableName, FCollectionFile);
end;
{ TBaseRepository<T> }
constructor TBaseRepository<T>.Create(Context: IDBContext);
begin
FContext := Context;
end;
end.
|
unit VolumeGreyData;
interface
uses Windows, Graphics, Abstract3DVolumeData, AbstractDataSet, SingleDataSet,
dglOpenGL, Math;
type
T3DVolumeGreyData = class (TAbstract3DVolumeData)
private
// Gets
function GetData(_x, _y, _z: integer):single;
function GetDataUnsafe(_x, _y, _z: integer):single;
// Sets
procedure SetData(_x, _y, _z: integer; _value: single);
procedure SetDataUnsafe(_x, _y, _z: integer; _value: single);
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
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_value: single);
// properties
property Data[_x,_y,_z:integer]:single read GetData write SetData; default;
property DataUnsafe[_x,_y,_z:integer]:single read GetDataUnsafe write SetDataUnsafe;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeGreyData.Initialize;
begin
FData := TSingleDataSet.Create;
end;
// Gets
function T3DVolumeGreyData.GetData(_x, _y, _z: integer):single;
begin
if IsPixelValid(_x,_y,_z) then
begin
Result := (FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end
else
begin
Result := -99999;
end;
end;
function T3DVolumeGreyData.GetDataUnsafe(_x, _y, _z: integer):single;
begin
Result := (FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeGreyData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB(Round((FData as TSingleDataSet).Data[_Position]) and $FF,Round((FData as TSingleDataSet).Data[_Position]) and $FF,Round((FData as TSingleDataSet).Data[_Position]) and $FF);
end;
function T3DVolumeGreyData.GetRPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF;
end;
function T3DVolumeGreyData.GetGPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF;
end;
function T3DVolumeGreyData.GetBPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TSingleDataSet).Data[_Position]) and $FF;
end;
function T3DVolumeGreyData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T3DVolumeGreyData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeGreyData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeGreyData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T3DVolumeGreyData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TSingleDataSet).Data[_Position] := (0.299 * GetRValue(_Color)) + (0.587 * GetGValue(_Color)) + (0.114 * GetBValue(_Color));
end;
procedure T3DVolumeGreyData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TSingleDataSet).Data[_Position] := (0.299 * _r) + (0.587 * _g) + (0.114 * _b);
end;
procedure T3DVolumeGreyData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
procedure T3DVolumeGreyData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
// Do nothing
end;
procedure T3DVolumeGreyData.SetData(_x, _y, _z: integer; _value: single);
begin
if IsPixelValid(_x,_y,_z) then
begin
(FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
procedure T3DVolumeGreyData.SetDataUnsafe(_x, _y, _z: integer; _value: single);
begin
(FData as TSingleDataSet).Data[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
// Copies
procedure T3DVolumeGreyData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
if (_DataXSize = 0) or (_DataYSize = 0) or (_DataZSize = 0) then
exit;
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYSize * FXSize;
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 TSingleDataSet).Data[x] := (_Data as TSingleDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeGreyData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TSingleDataSet).Data[x] := (FData as TSingleDataSet).Data[x] * _Value;
end;
end;
procedure T3DVolumeGreyData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TSingleDataSet).Data[x] := 1 - (FData as TSingleDataSet).Data[x];
end;
end;
procedure T3DVolumeGreyData.Fill(_value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TSingleDataSet).Data[x] := _value;
end;
end;
end.
|
unit ThCellSorter;
interface
uses
Types, Classes, Controls, Contnrs, Graphics;
type
TCellData = Record
W, H: Integer;
ColSpan, RowSpan: Integer;
Control: TControl;
Index: Integer;
end;
//
TCellControl = class
public
Control: TControl;
CellRect: TRect;
Index: Integer;
constructor Create(inControl: TControl; const inRect: TRect;
inIndex: Integer);
end;
//
TEdgeAxis = ( eaX, eaY );
TEdgeSide = ( esStart, esEnd );
//
TCellTable = class
protected
Grid: array of array of Integer;
ControlList: TList;
protected
procedure ClearGrid;
function BuildSortedEdgeList(inAxis: TEdgeAxis;
inSize: Integer = 0): TObjectList;
procedure BuildGrid(inXL, inYL: TList);
procedure BuildRow0(inXlist: TList);
function CollapseCols(inI, inJ: Integer; inList: TList;
var ioW: Integer): Integer;
function CollapseRows(inI, inJ, inColSpan: Integer; inList: TList;
var ioH: Integer): Integer;
procedure BuildRows(inXlist, inYlist: TList);
public
Rows: array of array of TCellData;
constructor Create;
destructor Destroy; override;
procedure AddControl(inControl: TControl; const inRect: TRect;
inIndex: Integer);
procedure Generate(inW, inH: Integer);
function RowCount: Integer;
function ColCount: Integer;
end;
//
TCellEdge = class
Pos: Integer;
Span: Integer;
constructor Create(inPos: Integer);
end;
implementation
{ TCellControl }
constructor TCellControl.Create(inControl: TControl; const inRect: TRect;
inIndex: Integer);
begin
Control := inControl;
CellRect := inRect;
Index := inIndex;
end;
{ TCellData }
function CellData(inW, inH, inCols, inRows: Integer;
inIndex: Integer {inControl: TControl}): TCellData;
begin
with Result do
begin
W := inW;
H := inH;
ColSpan := inCols;
RowSpan := inRows;
Index := inIndex;
//Control := inControl;
end;
end;
{ TCellEdge }
constructor TCellEdge.Create(inPos: Integer);
begin
Pos := inPos;
end;
{ TCellTable }
constructor TCellTable.Create;
begin
ControlList := TObjectList.Create(true);
end;
destructor TCellTable.Destroy;
begin
ControlList.Free;
inherited;
end;
procedure TCellTable.AddControl(inControl: TControl; const inRect: TRect;
inIndex: Integer);
begin
ControlList.Add(TCellControl.Create(inControl, inRect, inIndex));
end;
function CompareCellEdges(Item1, Item2: Pointer): Integer;
begin
Result := TCellEdge(Item1).Pos - TCellEdge(Item2).Pos;
end;
function TCellTable.BuildSortedEdgeList(inAxis: TEdgeAxis;
inSize: Integer = 0): TObjectList;
function EdgeOf(inControl: TCellControl; inAxis: TEdgeAxis;
inEdgeSide: TEdgeSide): Integer;
var
r: TRect;
begin
r := inControl.CellRect;
case inAxis of
eaX:
case inEdgeSide of
esStart: Result := r.Left;
else Result := r.Right;
end;
else
case inEdgeSide of
esStart: Result := r.Top;
else Result := r.Bottom;
end;
end;
end;
procedure CalcEdgeSpans(inList: TList);
var
i, p: Integer;
begin
p := 0;
for i := 0 to inList.Count - 1 do
with TCellEdge(inList[i]) do
begin
Span := Pos - p;
p := Pos;
end;
end;
procedure RemoveCoincidentEdges(inList: TList);
var
i: Integer;
begin
i := 1;
while (i < inList.Count) do
begin
if TCellEdge(inList[i-1]).Pos = TCellEdge(inList[i]).Pos then
begin
//TCellEdge(inList[i]).Free;
inList.Delete(i)
end else
Inc(i);
end;
end;
var
i: Integer;
begin
Result := TObjectList.Create;
with Result do
begin
Add(TCellEdge.Create(0));
Add(TCellEdge.Create(inSize));
for i := 0 to ControlList.Count - 1 do
begin
Add(TCellEdge.Create(EdgeOf(ControlList[i], inAxis, esStart)));
Add(TCellEdge.Create(EdgeOf(ControlList[i], inAxis, esEnd)));
end;
Sort(CompareCellEdges);
end;
RemoveCoincidentEdges(Result);
CalcEdgeSpans(Result);
end;
procedure TCellTable.BuildGrid(inXL, inYL: TList);
function FindCellEdge(inList: TList; inPos: Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to inList.Count - 1 do
with TCellEdge(inList[i]) do
if Pos = inPos then
begin
Result := i + 1;
exit;
end;
end;
var
n, i, j: Integer;
c: TCellControl;
x0, y0, x1, y1: Integer;
r: TRect;
begin
SetLength(Grid, inYL.Count + 1);
for j := 0 to inYL.Count do SetLength(Grid[j], inXL.Count + 1);
//
for n := 0 to ControlList.Count - 1 do
begin
c := TCellControl(ControlList[n]);
r := c.CellRect;
//
x0 := FindCellEdge(inXL, r.Left);
y0 := FindCellEdge(inYL, r.Top);
x1 := FindCellEdge(inXL, r.Right);
y1 := FindCellEdge(inYL, r.Bottom);
//
for j := y0 to y1 - 1 do
for i := x0 to x1 - 1 do
Grid[j][i] := n + 1;
end;
end;
procedure TCellTable.BuildRow0(inXlist: TList);
var
i, col, w: Integer;
begin
col := 0;
SetLength(Rows[0], inXlist.Count);
for i := 0 to inXlist.Count - 1 do
begin
w := TCellEdge(inXlist[i]).Span;
if w = 0 then
continue;
Rows[0][col] := CellData(w, 0, 1, 1, -1);
Inc(col);
end;
SetLength(Rows[0], col);
end;
function TCellTable.CollapseCols(inI, inJ: Integer; inList: TList;
var ioW: Integer): Integer;
var
gc, si: Integer;
begin
Result := 1;
gc := Grid[inJ][inI];
//
if (gc <= 0) then
exit;
//
si := inI + 1;
while (si < inList.Count) and (Grid[inJ][si] = gc) do
begin
Grid[inJ][si] := -1;
ioW := ioW + TCellEdge(inList[si]).Span;
Inc(Result);
Inc(si);
end;
end;
function TCellTable.CollapseRows(inI, inJ, inColSpan: Integer; inList: TList;
var ioH: Integer): Integer;
var
gc, sj, k: Integer;
begin
Result := 1;
gc := Grid[inJ][inI];
//
if (gc <= 0) then
exit;
//
sj := inJ + 1;
while (sj < inList.Count) and (Grid[sj][inI] = gc) do
begin
Grid[sj][inI] := -1;
for k := 1 to inColSpan - 1 do
Grid[sj][inI+k] := -1;
ioH := ioH + TCellEdge(inList[sj]).Span;
Inc(Result);
Inc(sj);
end;
end;
procedure TCellTable.BuildRows(inXlist, inYlist: TList);
var
i, j, col, row, h, w: Integer;
gc, col_span, row_span, span_w, span_h: Integer;
//c: TControl;
c: Integer;
begin
SetLength(Rows, inYlist.Count + 1);
//
row := 0;
//
//BuildRow0(inXlist);
//row := 1;
//
for j := 0 to inYlist.Count - 1 do
begin
h := TCellEdge(inYlist[j]).Span;
if (h = 0) then
continue;
//
col := 0;
SetLength(Rows[row], inXlist.Count);
//
for i := 0 to inXlist.Count - 1 do
begin
w := TCellEdge(inXlist[i]).Span;
if w = 0 then
continue;
//
gc := Grid[j][i];
if (gc >= 0) then
begin
span_w := w;
span_h := h;
//
col_span := CollapseCols(i, j, inXlist, span_w);
row_span := CollapseRows(i, j, col_span, inYlist, span_h);
//
if (gc > 0) then
c := TCellControl(ControlList[gc - 1]).Index
else
c := -1;
//
Rows[row][col] := CellData(span_w, span_h, col_span, row_span, c);
//
Inc(col);
end;
end;
//
SetLength(Rows[row], col);
Inc(row);
end;
//
SetLength(Rows, row);
end;
procedure TCellTable.ClearGrid;
var
cj, j: Integer;
begin
cj := Length(Grid);
for j := 0 to cj - 1 do
Grid[j] := nil;
Grid := nil;
end;
procedure TCellTable.Generate(inW, inH: Integer);
var
xlist, ylist: TList;
begin
try
xlist := BuildSortedEdgeList(eaX, inW);
try
ylist := BuildSortedEdgeList(eaY, inH);
try
BuildGrid(xlist, ylist);
BuildRows(xlist, ylist);
finally
ylist.Free;
end;
finally
xlist.Free;
end;
finally
ClearGrid;
end;
end;
function TCellTable.ColCount: Integer;
begin
if RowCount > 0 then
Result := Length(Rows[0])
else
Result := 0;
end;
function TCellTable.RowCount: Integer;
begin
Result := Length(Rows);
end;
end.
|
unit PosFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, GameLogic, ImgList;
const
ANSWERS_SIZE = 128;
ANSWERS_LIMIT = ANSWERS_SIZE - 1;
ANIMATE_SUBSTEP_COUNT = 4;
type
TAcceptMoveEvent = procedure (Sender: TObject; const NewPosition: TPosition) of object;
TPositionFrame = class(TFrame)
ImageList: TImageList;
Image: TImage;
Timer: TTimer;
TransparentImages: TImageList;
procedure ImageMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure TimerTimer(Sender: TObject);
private
FPosition: TPosition;
FSelectedCells: array[0..31] of Boolean;
FAnswers: array[0..ANSWERS_LIMIT] of TPosition;
FAnswersCount: Integer;
FEnabledAnswer: array[0..ANSWERS_LIMIT] of Integer;
FUserSelect: array[0..12] of Integer;
FAnimatePosition: TPosition;
FAnimateWay: array[0..63] of Integer;
FAnimateStep: Integer;
FAnimateSubStep: Integer;
FAnimateObject: Integer;
FUserSelectCount: Integer;
FFlipBoard: Boolean;
FSelected: Integer;
FOnAcceptMove: TAcceptMoveEvent;
FAcceptMove: Boolean;
FDebug: TStrings;
procedure SetFlipBoard(const Value: Boolean);
procedure SetAcceptMove(const Value: Boolean);
procedure OutputDebugSelectMove;
function GetAnimate: Boolean;
public
procedure Loaded; override;
procedure SetPosition(const Position: TPosition; NeedAnimate: Boolean = True);
procedure RefreshView;
procedure DrawField(X, Y, Index: Integer);
function IsWhite(X, Y: Integer): Boolean;
function CellToField(X, Y: Integer): Integer;
procedure SelectCell(X, Y: Integer);
procedure BeginMove(Field: Integer);
procedure ClearSelect;
procedure BeginDebug;
procedure EndDebug;
procedure OutputDebug(const St: string); overload;
procedure OutputDebug(const St: string; const Args: array of const); overload;
function PrepareAccept: Boolean;
procedure InitSelectMoveVars;
procedure AddCellToMove(X, Y: Integer);
function Unselect(Field: Integer): Boolean;
function ThinkBetter(Field: Integer): Boolean;
function MoveComplete(Field: Integer): Boolean;
procedure ContinueMove(Field: Integer);
procedure BeginAnimate(const Position: TPosition);
function CellRect(X, Y: Integer; Grow: Integer = 0): TRect;
property Debug: TStrings read FDebug write FDebug;
property FlipBoard: Boolean read FFlipBoard write SetFlipBoard;
property AcceptMove: Boolean read FAcceptMove write SetAcceptMove;
property OnAcceptMove: TAcceptMoveEvent read FOnAcceptMove write FOnAcceptMove;
property Position: TPosition read FPosition;
property Animate: Boolean read GetAnimate;
end;
implementation
{$R *.DFM}
{ TPositionFrame }
procedure TPositionFrame.BeginDebug;
begin
{$IFDEF SELECT_DEBUG}
if Assigned(Debug) then
begin
Debug.BeginUpdate;
Debug.Clear;
end;
{$ENDIF}
end;
procedure TPositionFrame.EndDebug;
begin
{$IFDEF SELECT_DEBUG}
if Assigned(Debug) then Debug.EndUpdate;
{$ENDIF}
end;
procedure TPositionFrame.OutputDebug(const St: string);
begin
{$IFDEF SELECT_DEBUG}
Debug.Add(St);
{$ENDIF}
end;
procedure TPositionFrame.OutputDebug(const St: string; const Args: array of const);
begin
{$IFDEF SELECT_DEBUG}
OutputDebug(Format(St, Args));
{$ENDIF}
end;
procedure TPositionFrame.OutputDebugSelectMove;
{$IFDEF SELECT_DEBUG}
var
I, J: Integer;
St: string;
{$ENDIF}
begin
{$IFDEF SELECT_DEBUG}
OutputDebug('Возможные хода:');
for I := 0 to FAnswersCount - 1 do
begin
St := PointsDef[FAnswers[I].MoveStr[0]];
J := 1;
repeat
if FAnswers[I].MoveStr[J] = -1 then Break;
St := St + FAnswers[I].TakeChar + PointsDef[FAnswers[I].MoveStr[J]];
J := J + 1;
until False;
OutputDebug('(%d) %s', [I, St]);
end;
OutputDebug('');
St := '';
for I := 0 to 31 do
if FSelectedCells[I] then St := ' ' + PointsDef[I];
OutputDebug('Selected =' + St);
St := '';
for I := 0 to FAnswersCount-1 do
St := St + Format(' %d(%d)', [FEnabledAnswer[I], I]);
OutputDebug('EnabledAnswer =' + St);
St := '';
for I := 0 to FUserSelectCount-1 do
St := St + ' ' + PointsDef[FUserSelect[I]];
OutputDebug('UserSelect =' + St);
{$ENDIF}
end;
function TPositionFrame.CellToField(X, Y: Integer): Integer;
begin
if FlipBoard
then Result := 4*Y + (7-X) div 2
else Result := 28 - 4*Y + (X div 2);
end;
procedure TPositionFrame.ClearSelect;
begin
FSelected := -1;
RefreshView;
end;
procedure TPositionFrame.DrawField(X, Y, Index: Integer);
begin
ImageList.Draw(Image.Canvas, X*ImageList.Width, Y*ImageList.Height, Index);
end;
function TPositionFrame.IsWhite(X, Y: Integer): Boolean;
begin
Result := ((X xor Y) and 1) = 0;
end;
procedure TPositionFrame.Loaded;
begin
inherited;
FSelected := -1;
end;
procedure TPositionFrame.RefreshView;
var
X, Y: Integer;
X1, X2, Y1, Y2: Integer;
P, Q: Single;
FieldIndex: Integer;
OutPosition: PPosition;
begin
if Animate
then OutPosition := @FAnimatePosition
else OutPosition := @FPosition;
ClientWidth := 8 * ImageList.Width;
ClientWidth := 8 * ImageList.Height;
for Y := 0 to 7 do
for X := 0 to 7 do
if IsWhite(X, Y) then
DrawField(X, Y, 0)
else begin
FieldIndex := CellToField(X, Y);
if Animate and (Position.MoveStr[0] = FieldIndex) then
DrawField(X, Y, 1)
else
case OutPosition.Field[FieldIndex] of
brWhiteSingle: DrawField(X, Y, 2);
brBlackSingle: DrawField(X, Y, 3);
brWhiteMam: DrawField(X, Y, 4);
brBlackMam: DrawField(X, Y, 5);
brEmpty: DrawField(X, Y, 1)
else DrawField(X, Y, 6)
end;
if FSelectedCells[FieldIndex] then
begin
Image.Canvas.Brush.Style := bsClear;
Image.Canvas.Pen.Width := 1;
Image.Canvas.Pen.Color := clGreen;
Image.Canvas.Rectangle(CellRect(X, Y));
Image.Canvas.Rectangle(CellRect(X, Y, -1));
end;
end;
if Animate then
begin
if FlipBoard then
begin
X1 := ImageList.Width * (7 - FAnimateWay[FAnimateStep-1] mod 8);
Y1 := ImageList.Height * (FAnimateWay[FAnimateStep-1] div 8);
X2 := ImageList.Width * (7 - FAnimateWay[FAnimateStep] mod 8);
Y2 := ImageList.Height * (FAnimateWay[FAnimateStep] div 8);
end
else begin
X1 := ImageList.Width * (FAnimateWay[FAnimateStep-1] mod 8);
Y1 := ImageList.Height * (7 - FAnimateWay[FAnimateStep-1] div 8);
X2 := ImageList.Width * (FAnimateWay[FAnimateStep] mod 8);
Y2 := ImageList.Height * (7 - FAnimateWay[FAnimateStep] div 8);
end;
P := FAnimateSubStep /ANIMATE_SUBSTEP_COUNT;
Q := 1 - P;
X := Round(Q*X1+P*X2);
Y := Round(Q*Y1+P*Y2);
TransparentImages.Draw(Image.Canvas, X, Y, FAnimateObject);
end;
Image.Refresh;
end;
procedure TPositionFrame.SelectCell(X, Y: Integer);
begin
if IsWhite(X, Y) then Exit;
FSelected := CellToField(X, Y);
RefreshView;
end;
procedure TPositionFrame.SetFlipBoard(const Value: Boolean);
begin
if FFlipBoard = Value then Exit;
FFlipBoard := Value;
RefreshView;
end;
procedure TPositionFrame.SetPosition(const Position: TPosition; NeedAnimate: Boolean);
begin
FAnimatePosition := FPosition;
FPosition := Position;
if AcceptMove then PrepareAccept;
if NeedAnimate and (Position.MoveStr[0] <> -1)
then BeginAnimate(Position)
else RefreshView
end;
procedure TPositionFrame.ImageMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if not AcceptMove then Exit;
BeginDebug;
try
OutputDebug('Перед ходом:');
OutputDebug('=========================================');
OutputDebugSelectMove;
AddCellToMove(X div ImageList.Width, Y div ImageList.Height);
OutputDebug('');
OutputDebug('Ппосле хода:');
OutputDebug('=========================================');
OutputDebugSelectMove;
finally
EndDebug;
end;
end;
function TPositionFrame.CellRect(X, Y: Integer; Grow: Integer = 0): TRect;
begin
Result.Left := X * ImageList.Width - Grow;
Result.Top := Y * ImageList.Height - Grow;
Result.Right := Result.Left + ImageList.Width + 2*Grow;
Result.Bottom := Result.Top + ImageList.Height + 2*Grow;
end;
procedure TPositionFrame.SetAcceptMove(const Value: Boolean);
begin
if FAcceptMove = Value then Exit;
if Value and not PrepareAccept then Exit;
FAcceptMove := Value;
end;
procedure TPositionFrame.InitSelectMoveVars;
begin
FillChar(FSelectedCells, SizeOf(FSelectedCells), $00);
FillChar(FEnabledAnswer, SizeOf(FEnabledAnswer), $00);
FUserSelectCount := 0;
end;
function TPositionFrame.PrepareAccept: Boolean;
begin
FAnswersCount := GetMoves(FPosition, @FAnswers, ANSWERS_SIZE);
Result := (FAnswersCount <> 0) and (FAnswersCount <= ANSWERS_SIZE);
InitSelectMoveVars;
end;
procedure TPositionFrame.AddCellToMove(X, Y: Integer);
begin
if IsWhite(X, Y) then Exit;
if FUserSelectCount = 0 then
begin
BeginMove(CellToField(X, Y));
Exit;
end;
if Unselect(CellToField(X, Y)) then Exit;
if ThinkBetter(CellToField(X, Y)) then Exit;
if MoveComplete(CellToField(X, Y)) then Exit;
ContinueMove(CellToField(X, Y));
end;
procedure TPositionFrame.BeginMove(Field: Integer);
var
I: Integer;
FindMove: Boolean;
begin
FindMove := False;
for I := 0 to FAnswersCount-1 do
if FAnswers[I].MoveStr[0] = Field then
begin
FindMove := True;
FEnabledAnswer[I] := 1;
end;
if not FindMove then Exit;
FUserSelect[0] := Field;
FUserSelectCount := 1;
FSelectedCells[Field] := True;
RefreshView;
end;
function TPositionFrame.Unselect(Field: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if FUserSelectCount = 0 then Exit;
if FUserSelect[FUserSelectCount-1] <> Field then Exit;
FSelectedCells[Field] := False;
for I := 0 to FAnswersCount-1 do
if FEnabledAnswer[I] = FUserSelectCount then
FEnabledAnswer[I] := FEnabledAnswer[I] - 1;
FUserSelectCount := FUserSelectCount - 1;
RefreshView;
Result := True;
end;
function TPositionFrame.ThinkBetter(Field: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if FUserSelectCount <> 1 then Exit;
for I := 0 to FAnswersCount-1 do
begin
if FAnswers[I].MoveStr[0] = Field then
begin
InitSelectMoveVars;
BeginMove(Field);
Result := True;
Exit;
end;
end;
end;
function TPositionFrame.MoveComplete(Field: Integer): Boolean;
var
I, J: Integer;
UserMove: Integer;
begin
Result := False;
UserMove := -1;
for I := 0 to FAnswersCount-1 do
begin
if FEnabledAnswer[I] <> FUserSelectCount then Continue;
J := 2;
while FAnswers[I].MoveStr[J] <> -1 do J := J + 1;
if FAnswers[I].MoveStr[J-1] = Field then
if UserMove <> -1 then Exit
else UserMove := I;
end;
if UserMove = -1 then Exit;
AcceptMove := False;
FillChar(FSelectedCells, SizeOf(FSelectedCells), $00);
if Assigned(FOnAcceptMove) then FOnAcceptMove(Self, FAnswers[UserMove]);
Result := True;
end;
procedure TPositionFrame.ContinueMove(Field: Integer);
var
I: Integer;
FindMove: Boolean;
function FreeWay(Field1, Field2: Integer): Boolean;
var
NextI: Integer;
Direction: TDirection;
begin
Result := False;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := Field1;
repeat
NextI := DirectionTable[Direction, NextI];
if NextI = -1 then Break;
if FPosition.Field[NextI] <> 0 then Break;
if NextI = Field2 then
begin
Result := True;
Exit;
end;
until False;
end;
end;
function SameDiagonal(StartField, Field1, Field2, Field3: Integer): Boolean;
var
FindCount: Integer;
NextI: Integer;
Direction: TDirection;
begin
Result := False;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := StartField;
FindCount := 0;
repeat
NextI := DirectionTable[Direction, NextI];
if NextI = -1 then Break;
if NextI = Field1 then FindCount := FindCount + 1;
if NextI = Field2 then FindCount := FindCount + 1;
if NextI = Field3 then FindCount := FindCount + 1;
if FindCount = 3 then
begin
Result := True;
Exit;
end;
until False;
end;
end;
function AcceptMarginaly: Boolean;
begin
Assert(FUserSelectCount > 0);
Result :=
(FAnswers[I].MoveStr[FUserSelectCount+1] <> -1) and // это не последнее поле
FreeWay(FAnswers[I].MoveStr[FUserSelectCount], Field) and // можно пройти
SameDiagonal( // Одна диагональ
FAnswers[I].MoveStr[FUserSelectCount-1],
FAnswers[I].MoveStr[FUserSelectCount],
Field,
FAnswers[I].MoveStr[FUserSelectCount+1])
end;
function AcceptDirectly: Boolean;
begin
Result := Field = FAnswers[I].MoveStr[FUserSelectCount];
end;
function AcceptVariant: Boolean;
begin
Result := AcceptDirectly or AcceptMarginaly;
end;
begin
FindMove := False;
for I := 0 to FAnswersCount-1 do
begin
if FEnabledAnswer[I] <> FUserSelectCount then Continue;
if AcceptVariant then
begin
FindMove := True;
FEnabledAnswer[I] := FEnabledAnswer[I] + 1;
end;
end;
if FindMove then
begin
FUserSelect[FUserSelectCount] := Field;
FUserSelectCount := FUserSelectCount + 1;
FSelectedCells[Field] := True;
RefreshView;
end;
end;
function TPositionFrame.GetAnimate: Boolean;
begin
Result := Timer.Enabled;
end;
procedure TPositionFrame.BeginAnimate(const Position: TPosition);
var
AnimateWayPos: Integer;
I: Integer;
procedure ProcessPair(Field1, Field2: Integer);
var
Delta: Integer;
Step: Integer;
NextI: Integer;
begin
Delta := Abs(Field1 - Field2);
if Field1 > Field2 then
begin
if Delta mod 9 = 0
then Step := -9
else Step := -7
end
else begin
if Delta mod 9 = 0
then Step := 9
else Step := 7
end;
NextI := Field1;
repeat
NextI := NextI + Step;
FAnimateWay[AnimateWayPos] := NextI;
AnimateWayPos := AnimateWayPos + 1;
until NextI = Field2;
end;
begin
// Вычисляем путь
with Position do
begin
if MoveStr[0] = -1 then Exit;
FAnimateWay[0] := DecodeField[MoveStr[0]];
AnimateWayPos := 1;
I := 1;
while MoveStr[I] <> -1 do
begin
ProcessPair(DecodeField[MoveStr[I-1]], DecodeField[MoveStr[I]]);
I := I + 1;
end;
case FAnimatePosition.Field[MoveStr[0]] of
brWhiteSingle: FAnimateObject := 0;
brBlackSingle: FAnimateObject := 1;
brWhiteMam: FAnimateObject := 2;
brBlackMam: FAnimateObject := 3;
end;
end;
FAnimateWay[AnimateWayPos] := -1;
FAnimateStep := 1;
FAnimateSubStep := 0;
Timer.Enabled := True;
end;
procedure TPositionFrame.TimerTimer(Sender: TObject);
begin
FAnimateSubStep := FAnimateSubStep + 1;
if FAnimateSubStep = ANIMATE_SUBSTEP_COUNT then
begin
FAnimateStep := FAnimateStep + 1;
if FAnimateWay[FAnimateStep] = -1 then Timer.Enabled := False;
if (FAnimateObject = 0) and (FAnimateWay[FAnimateStep] >= 56) then FAnimateObject := 2;
if (FAnimateObject = 1) and (FAnimateWay[FAnimateStep] <= 7) then FAnimateObject := 3;
FAnimateSubStep := 0;
end;
RefreshView;
end;
end.
|
unit Helper.Variant;
interface
uses
System.Variants;
type
TVariantHelper = record helper for Variant
function IsNull: Boolean;
end;
implementation
{ TVariantHelper }
function TVariantHelper.IsNull: Boolean;
begin
Result := VarIsNull(Self);
end;
end.
|
{*********** File handling utilities **********}
unit fileops;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes,
logger, regexpr,
{$ifdef unix}
unixlib
{$endif}
{$ifdef windows}
windowslib
{$endif}
;
type
TFileFuncName = function(const FileName: string;
Params: TFPList): boolean;
//Return the name of the file without extension or directory path
function FileNameNoExt(Name:String):String;
function FileNameNoEXEExt(Name:String):String;
function MakeDirs(Dirs: string): boolean;
function CopyFile(FromName: string; ToName: string; DeleteOriginal: boolean = False;
const Count: longint = -1): boolean;
function MoveFile(FromName: string; ToName: string;
const DeleteFirst: boolean = False): boolean;
function MakeBackup(const FromName: string; const ToName: string;
const NoToKeep: integer = 3): boolean;
function FindZipHdr(const FileName: string; const StartAt: int64 = 0): int64;
function FindZipHdr(Stream: TStream; const StartAt: int64 = 0): int64;
procedure ForEachFile(const WildPath: string; Func: TFileFuncName;
Params: TFPList; const Flags: longint = faAnyFile and faDirectory);
procedure DeleteDirectory(const Dir: string);
implementation
//
// Delete directories recursively
//
procedure DeleteDirectory(const Dir: string);
var
F: TSearchRec;
begin
if FindFirst(Dir + DirectorySeparator +'*', faAnyFile, F) = 0 then begin
try
repeat
if (F.Attr and faDirectory <> 0) then begin
if (F.Name <> '.') and (F.Name <> '..') then begin
DeleteDirectory(ConcatPaths([Dir,F.Name]));
end;
end else begin
//LogFmt('Deleting %s', [ConcatPaths([Dir,F.Name])]);
DeleteFile(ConcatPaths([Dir,F.Name]));
end;
until FindNext(F) <> 0;
finally
FindClose(F);
end;
//LogFmt('Deleting %s/', [Dir]);
RemoveDir(Dir);
end;
end;
//
// Get File name without extension
//
function FileNameNoExt(Name:String):String;
begin
Result:=ChangeFileExt(ExtractFileName(Name),'');
end;
function FileNameNoEXEExt(Name:String):String;
Var
OSExt:string='';
begin
Result := ExtractFileName(Name);
OSExt := GetOSEXEExt();
If (OSExt <> '') and (ExtractFileExt(Name) = OSExt) then
Result:=ChangeFileExt(Result,'');
end;
procedure ForEachFile(const WildPath: string; Func: TFileFuncName;
Params: TFPList; const Flags: longint = faAnyFile and faDirectory);
var
Info: TSearchRec;
Stop: boolean;
begin
//Result:=False;
Stop := False;
if FindFirst(WildPath, Flags, Info) = 0 then
begin
repeat
Stop := Func(Info.Name, Params);
until (FindNext(info) <> 0) or Stop;
end;
FindClose(Info);
end;
function CompareBakEntries(BakList: TStringList; i, j: integer): integer;
begin
Result := StrToInt64Def(BakList.Names[j], 0) - StrToInt64Def(BakList.Names[i], 0);
end;
function MakeList(const Name: string; Params: TFPList): boolean;
const
DateRegex = '_(\d{4})_(\d{2})_(\d{2})__(\d{2})_(\d{2})_(\d{2})';
var
DT,Basename,S,Regex: string;
List: TStrings;
begin
Result := False;
Basename := string(Params[0]);
List := TStringList(Params[1]);
Regex := QuoteRegExprMetaChars(FileNameNoExt(Basename)) + DateRegex
+ QuoteRegExprMetaChars(ExtractFileExt(Basename));
S := Name;
if ExecRegExpr(Regex, S) then
begin
DT := ReplaceRegExpr(Regex, S, '$1$2$3$4$5$6', True);
List.Add(DT + '=' + Name);
end;
end;
procedure DeleteOld(const BaseName: string; const NoToKeep: integer);
var
List: TStringList;
Params: TFPList;
i, DCount: integer;
Dir, FN: string;
begin
List := TStringList.Create;
Params := TFPList.Create;
try
try
//Build list of files
Dir := ConcatPaths([ExtractFilePath(BaseName), '*']);
Params.Add(Pointer(BaseName));
Params.Add(Pointer(List));
ForEachFile(Dir, @MakeList, Params);
//Exit if we are asked to keep more than what already exists
if NoToKeep >= List.Count then
Exit;
//Sort the list
List.CustomSort(@CompareBakEntries);
DCount := 0;
//Now delete the last files in the list
for i := NoToKeep to List.Count - 1 do
begin
FN := ConcatPaths([ExtractFilePath(BaseName), List.ValueFromIndex[i]]);
FN := ExpandFileName(FN);
DeleteFile(FN);
Inc(DCount);
end;
Log('Deleted (' + IntToStr(DCount) + ') backups.');
finally
if Assigned(List) then
FreeAndNil(List);
if Assigned(Params) then
FreeAndNil(Params);
end;
except
on E: Exception do
Error('Unable to delete old backups: ' + E.toString + ' - ' + E.Message);
end;
end;
//Make the directories needed for file in Dirs
function MakeDirs(Dirs: string): boolean;
var
i: integer;
D: string;
L: TStringList;
OK: boolean;
begin
Result := False;
Dirs := ExtractFilePath(Dirs);
//Exit if directory is already there
if DirectoryExists(Dirs) then
begin
Result := True;
Exit;
end;
//Exit if Dirs is not ended with the directory separator
if (Length(Dirs) = 0) or (Dirs[Length(Dirs)] <> DirectorySeparator) then
Exit;
try
//Get each one of the Paths recursively: e.g. for 'ok/ok1/ok2/'
//make a list: [ 'ok/ok1/ok2', 'ok/ok1', 'ok', '']
try
D := Dirs;
L := TStringList.Create;
repeat
D := ExtractFileDir(D);
L.Add(D);
until (D = '') or (AnsiLastChar(D) = DirectorySeparator);
//Create each of the needed directories
OK := True;
for i := L.Count - 2 downto 0 do
begin
if not DirectoryExists(L[i]) then
OK := OK and CreateDir(L[i]);
end;
Result := OK;
finally
If Assigned(L) then
FreeAndNil(L);
end;
except on E:Exception do
Raise Exception.CreateFmt('Unable to create directory ''%s'': %s',[Dirs,E.toString]);
end;
end;
function CopyFile(FromName: string; ToName: string; DeleteOriginal: boolean = False;
const Count: longint = -1): boolean;
var
SourceF, DestF: TFileStream;
_Count: longint;
begin
//Return failed copy by default
Result := False;
_Count := Count;
if FromName = ToName then
Exit;
try
try
MakeDirs(ToName);
Log('Copying ''' + FromName + ''' to ''' + ToName + '''');
SourceF := TFileStream.Create(FromName, fmOpenRead);
DestF := TFileStream.Create(ToName, fmCreate);
if _Count = -1 then
_Count := SourceF.Size;
DestF.CopyFrom(SourceF, _Count);
//Now the copy succeded
Result := True;
finally
if Assigned(SourceF) then
FreeAndNil(SourceF);
if Assigned(DestF) then
FreeAndNil(DestF);
end;
except on E:Exception do
raise Exception.CreateFmt('Unable to copy ''%s'' to ''%s'' : %s',[FromName,ToName,E.toString]);
end;
//Delete original file if asked
if Result and DeleteOriginal then
DeleteFile(FromName);
end;
function MoveFile(FromName: string; ToName: string;
const DeleteFirst: boolean = False): boolean;
var
Dir: string;
OK: boolean;
begin
Dir := ExtractFilePath(ToName);
OK := MakeDirs(Dir);
if OK then
begin
if DeleteFirst and FileExists(ToName) then
DeleteFile(ExpandFileName(ToName));
OK := RenameFile(FromName, ToName);
end;
if not OK then
logger.Error('Unable to move ''' + FromName + ''' to ''' + ToName + '''');
Result := OK;
end;
function MakeBackup(const FromName: string; const ToName: string;
const NoToKeep: integer = 3): boolean;
var
OK: boolean;
Suffix: string;
Ext: string;
Dir: string;
FName: string;
BakName: string;
begin
Ext := ExtractFileExt(ToName);
Dir := ExtractFilePath(ToName);
FName := ExtractFileName(ToName);
FName := ChangeFileExt(FName, '');
Suffix := FormatDateTime('_YYYY_MM_DD__hh_nn_ss', Now);
BakName := Dir + FName + Suffix + Ext;
OK := fileops.CopyFile(FromName, BakName);
DeleteOld(ToName, NoToKeep); //Now delete old files
Result := OK;
end;
function FindZipHdr(const FileName: string; const StartAt: int64 = 0): int64;
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
Result := FindZipHdr(Stream, StartAt);
FreeAndNil(Stream);
end;
function FindZipHdr(Stream: TStream; const StartAt: int64 = 0): int64;
var
Buf: string;
ZipPos, ReadCount: int64;
i: integer;
//Shift the header signature one bit right because otherwise it
//can be found in the executable also
//Header is 50 4b 03 04 14 00 00 00 for our unzip utility
ZipHdr: array[0..7] of byte = ($50 shl 1, $4b shl 1, $03 shl 1,
$04 shl 1, $14 shl 1, $00 shl 1,
$00 shl 1, $00 shl 1);
ZipHdrC: array[0..7] of AnsiChar; //To use Pos()
const
BUFSIZE = 33 * 1024; //To honor Our Lord On the Vigil of Dec 8,2015
begin
ZipPos := -1;
Result := -1;
//Unshift the Zip header
for i := 0 to 7 do
ZipHdrC[i] := char(ZipHdr[i] shr 1);
//Position stream at specified offset ( to prevent going through parts
// of the file which we know don't have the ziphdr)
if StartAt > Stream.Size then
raise Exception.Create('Find Zip Header - offset ''' + IntToStr(StartAt) +
'''is greater than file size!');
Stream.Seek(StartAt, soBeginning);
SetLength(Buf, BUFSIZE);
repeat
ReadCount := Stream.Read(Buf[1], BUFSIZE);
SetLength(Buf, ReadCount);
ZipPos := Pos(ZipHdrC, Buf);
until (ZipPos > 0) or (Stream.Size = Stream.Position);
if (ZipPos > 0) then //Zip Header found
begin
Stream.Seek(-ReadCount + (ZipPos - 1), soCurrent);
ZipPos := Stream.Position;
end
else
ZipPos := -1;
Log('Zip header found at: ' + IntToStr(ZipPos));
Result := ZipPos;
end;
end.
|
unit PromoItemClass;
interface
uses PromoItemInterface, PromoConfigClass, uSaleItem, contnrs, dbClient, SysUtils;
type
TPromoItem = class(TInterfacedObject, IPromoItem)
private
fIdPresale: Integer;
fIdMov: Integer;
fIdPromo: Integer;
fPromoType: Integer;
fFlatPromo: Boolean;
fIdPromoItem: Integer;
fIdModel: Integer;
fIdModelParent: Integer;
fQuantity: Double;
fQuantityXPromo: Double;
fQuantityYPromo: Double;
fDiscount: Double;
fDiscountType: Integer;
fSellingPrice: Double;
fTotalQty: Double;
fTotalDiscount: Double;
fHighestDiscount: Double; // highest discount found to item.
fCustomerDiscount: Double;
function getSellingPrice(arg_IdModel: Integer; arg_sellingPrice: Double): Double; overload;
function isPriceBreak(): Boolean;
procedure createSubListOfItemsY(arg_promoConfigLines: TClientDataset);
public
fListModelY: TObjectList;
constructor create(); overload;
constructor create(arg_promoConfigLines: TClientDataset; arg_saleItem:TSaleItem; arg_customerDiscount: Double); overload;
function getIdPresale(): Integer;
function getDiscountType(): Integer;
function getPromoType(): Integer;
function getIdMov(): Integer;
function getQuantity(): Double;
function getIdPromo(): Integer;
function getIdPromoItem(): Integer;
function getIdModel(): Integer;
function getIdModelParent(): Integer;
function getQtyX(): Double;
function getDiscount(): Double;
function getSellingPrice(): Double; overload;
function getFlatPromo(): Boolean;
function getHighestDiscount(arg_discount: Double): Double; overload;
function getHighestDiscount(): Double; overload;
procedure addQuantityToToTal(arg_qty: Double);
procedure addDiscount(arg_discount: Double);
procedure setCustomerDiscount(arg_discount: Double);
function getCustomerDiscount(): Double;
end;
implementation
{ TPromoItem }
procedure TPromoItem.addDiscount(arg_discount: Double);
begin
fTotalDiscount := fTotalDiscount + arg_discount;
end;
procedure TPromoItem.addQuantityToToTal(arg_qty: Double);
begin
fTotalQty := fTotalQty + arg_qty;
end;
constructor TPromoItem.create(arg_promoConfigLines:TClientDataset; arg_saleItem:TSaleItem; arg_customerDiscount: Double);
begin
fIdPresale := arg_saleItem.IDPreSale;
fIdModel := arg_saleItem.IDModel;
fQuantity := arg_saleItem.Qty;
fIdPromo := arg_promoConfigLines.fieldByName('idPromo').value;
fIdPromoItem := arg_promoConfigLines.fieldByName('idPromoItem').value;
fQuantityXPromo := arg_promoConfigLines.fieldByName('qtyPromoItem').value;
fDiscount := arg_promoConfigLines.fieldByName('discountValue').Value;
fDiscountType := arg_promoConfigLines.fieldByName('discountType').value;
fPromoType := arg_promoConfigLines.fieldByName('promoType').Value;
fFlatPromo := arg_promoConfigLines.FieldByName('flatPromo').value;
// todo -cPromoItemSubList -oAntonio: Creating createSubList
if ( not fFlatPromo ) then begin
createSubListOfItemsY(arg_promoConfigLines);
end;
fCustomerDiscount := arg_customerDiscount;
end;
function TPromoItem.getCustomerDiscount: Double;
begin
result := fCustomerDiscount;
end;
function TPromoItem.getDiscount: Double;
begin
result := fDiscount;
end;
function TPromoItem.getDiscountType: Integer;
begin
result := fDiscountType;
end;
function TPromoItem.getFlatPromo: Boolean;
begin
result := fFlatPromo;
end;
function TPromoItem.getHighestDiscount(arg_discount: Double): Double;
begin
if ( arg_discount > fHighestDiscount ) then
fHighestDiscount := arg_discount;
addDiscount(fHighestDiscount);
result := fHighestDiscount;
end;
function TPromoItem.getHighestDiscount: Double;
begin
result := fHighestDiscount;
end;
function TPromoItem.getIdModel: Integer;
begin
result := fIdModel;
end;
function TPromoItem.getIdModelParent: Integer;
begin
Result := fIdModelParent;
end;
function TPromoItem.getIdMov: Integer;
begin
result := fIdMov;
end;
function TPromoItem.getIdPresale: Integer;
begin
result := fIdPresale;
end;
function TPromoItem.getIdPromo: Integer;
begin
result := fIdPromo;
end;
function TPromoItem.getIdPromoItem: Integer;
begin
result := fIdPromoItem
end;
function TPromoItem.getPromoType: Integer;
begin
result := fPromoType;
end;
function TPromoItem.getQuantity: Double;
begin
result := fQuantity;
end;
function TPromoItem.getQtyX: Double;
begin
result := fQuantityXPromo;
end;
function TPromoItem.getSellingPrice(arg_IdModel: Integer; arg_sellingPrice: Double): Double;
begin
if isPriceBreak() then begin
result := 0
end
else
result := arg_sellingPrice;
fSellingPrice := result;
end;
function TPromoItem.getSellingPrice: Double;
begin
result := fSellingPrice;
end;
function TPromoItem.isPriceBreak(): Boolean;
begin
result := false // to be implemented.
end;
procedure TPromoItem.setCustomerDiscount(arg_discount: Double);
begin
fCustomerDiscount := fSellingPrice * ( arg_discount / 100);
end;
constructor TPromoItem.create;
begin
//
end;
procedure TPromoItem.createSubListOfItemsY(arg_promoConfigLines: TClientDataset);
var
subList: TClientDataset;
begin
try
subList := TClientDataset.create(nil);
sublist := arg_promoConfigLines;
sublist.First;
sublist.Filter := format('idPromo = %d and idModel = %d', [fIdPromo, fIdModel]);
sublist.Filtered := true;
while ( not subList.Eof ) do begin
self.create();
self.fIdPromo := subList.fieldByName('idPromo').Value;
self.fPromoType := subList.fieldByName('promoType').Value;
self.fIdPromoItem := subList.fieldByName('idPromoItem').Value;
self.fIdModelParent := subList.fieldByName('idModel').Value;
self.fIdModel := sublist.fieldByName('prizeIdModel').Value;
fListModelY.Add(self);
sublist.Next;
end;
finally
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: O3TCImage<p>
Good for preview picture in OpenDialog,
so you may include both O3TCImage (preview) and GLFileO3TC (loading)
<li>24/01/10 - Yar - Improved FPC compatibility
<li>21/01/10 - Yar - Creation
</ul></font>
}
unit O3TCImage;
interface
{$i GLScene.inc}
uses
{$IFDEF LCL}LCLProc,LCLIntf,{$ELSE}Windows,{$ENDIF} Classes, SysUtils, GLCrossPlatform, GLVectorGeometry, GLGraphics,
OpenGL1x, GLPBuffer;
type
TO3TCImage = class (TGLBitmap)
public
{ Public Declarations }
procedure LoadFromStream(stream : TStream); override;
procedure SaveToStream(stream : TStream); override;
end;
implementation
uses
{$IFDEF FPC} graphtype, {$ENDIF}
GLFileO3TC, GLTextureFormat;
// ------------------
// ------------------ TO3TCImage ------------------
// ------------------
// LoadFromStream
//
procedure TO3TCImage.LoadFromStream(stream : TStream);
var
FullO3TC : TGLO3TCImage;
PBuf : TGLPixelBuffer;
size: integer;
tempBuff: PGLubyte;
tempTex : GLuint;
DC : HDC;
RC : HGLRC;
{$IFNDEF FPC}
src, dst: PGLubyte;
y: Integer;
{$ELSE}
RIMG: TRawImage;
{$ENDIF}
begin
FullO3TC := TGLO3TCImage.Create;
try
FullO3TC.LoadFromStream( stream );
except
FullO3TC.Free;
raise;
end;
// Copy surface as posible to TBitmap
DC := wglGetCurrentDC;
RC := wglGetCurrentContext;
// Create minimal pixel buffer
if (DC=0) or (RC=0) then
begin
PBuf := TGLPixelBuffer.Create;
try
PBuf.Initialize(1, 1);
except
FullO3TC.Free;
raise;
end;
tempTex := PBuf.TextureID;
end
else begin
Pbuf := nil;
glPushAttrib(GL_TEXTURE_BIT);
glGenTextures(1, @tempTex);
end;
// Setup texture
glEnable ( GL_TEXTURE_2D );
glBindTexture ( GL_TEXTURE_2D, tempTex);
// copy texture to video memory
size := ((FullO3TC.Width + 3) div 4)
* ((FullO3TC.Height + 3) div 4)
* FullO3TC.ElementSize;
glCompressedTexImage2DARB( GL_TEXTURE_2D, 0,
InternalFormatToOpenGLFormat(FullO3TC.InternalFormat),
FullO3TC.Width, FullO3TC.Height, 0, size,
FullO3TC.GetLevelData(0));
CheckOpenGLError;
GetMem( tempBuff, FullO3TC.Width*FullO3TC.Height*4 );
// get texture from video memory in simple format
glGetTexImage( GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_BYTE, tempBuff);
Width := FullO3TC.Width;
Height := FullO3TC.Height;
Transparent := true;
PixelFormat := glpf32bit;
{$IFNDEF FPC}
src := tempBuff;
for y := 0 to Height - 1 do begin
dst := ScanLine[Height - 1 - y];
Move(src^, dst^, Width*4);
Inc(src, Width*4);
end;
{$ELSE}
RIMG.Init;
rimg.Description.Init_BPP32_B8G8R8A8_BIO_TTB(Width, Height);
rimg.Description.RedShift := 16;
rimg.Description.BlueShift := 0;
rimg.Description.LineOrder := riloBottomToTop;
RIMG.DataSize := Width*Height*4;
rimg.Data := PByte(tempBuff);
LoadFromRawImage(rimg, false);
{$ENDIF}
FullO3TC.Free;
FreeMem( tempBuff );
CheckOpenGLError;
if Assigned( pBuf ) then
pBuf.Destroy
else begin
glDeleteTextures(1, @tempTex);
glPopAttrib;
end;
end;
// SaveToStream
//
procedure TO3TCImage.SaveToStream(stream : TStream);
begin
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
TGLPicture.RegisterFileFormat(
'o3tc', 'oZone3D Texture Compression', TO3TCImage);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
TGLPicture.UnregisterGraphicClass(TO3TCImage);
end.
|
unit uClassSinaisSintomas;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TSinaisSintomas }
TSinaisSintomas = class
private
FAlteracaoApetite: string;
FcalorExagerado: string;
FcansaFacil: string;
FcoceiraAnormal: string;
FdificuldadeEngolir: string;
FdificuldadeMastigar: string;
FdorFacial: string;
FdorFrequenteCabeca: string;
FdorOuvidoFrequente: string;
FemagrecimentoAcentuado: string;
FfebreFrequente: string;
FidSinaisSintomas: integer;
FidTblPaciente: integer;
FindigestaoFrequente: string;
FmaCicatrizacao: string;
FmiccaoFrequente: string;
FpoucaSaliva: string;
FrangeDentes: string;
FrespiraPelaBoca: string;
FsangramentoAnormal: string;
FestaloMandibula: string;
FtonturaDesmaio: string;
public
property idSinaisSintomas: integer read FidSinaisSintomas write FidSinaisSintomas;
property alteracaoApetite: string read FAlteracaoApetite write FAlteracaoApetite;
property calorExagerado: string read FcalorExagerado write FcalorExagerado;
property cansaFacil: string read FcansaFacil write FcansaFacil;
property coceiraAnormal: string read FcoceiraAnormal write FcoceiraAnormal;
property dificuldadeEngolir: string read FdificuldadeEngolir write FdificuldadeEngolir;
property dificuldadeMastigar: string read FdificuldadeMastigar write FdificuldadeMastigar;
property dorFacial: string read FdorFacial write FdorFacial;
property dorFrequenteCabeca: string read FdorFrequenteCabeca write FdorFrequenteCabeca;
property dorOuvidoFrequente: string read FdorOuvidoFrequente write FdorOuvidoFrequente;
property emagrecimentoAcentuado: string read FemagrecimentoAcentuado write FemagrecimentoAcentuado;
property estaloMandibula: string read FestaloMandibula write FestaloMandibula;
property febreFrequente: string read FfebreFrequente write FfebreFrequente;
property indigestaoFrequente: string read FindigestaoFrequente write FindigestaoFrequente;
property maCicatrizacao: string read FmaCicatrizacao write FmaCicatrizacao;
property miccaoFrequente: string read FmiccaoFrequente write FmiccaoFrequente;
property rangeDentes: string read FrangeDentes write FrangeDentes;
property respiraPelaBoca: string read FrespiraPelaBoca write FrespiraPelaBoca;
property sangramentoAnormal: string read FsangramentoAnormal write FsangramentoAnormal;
property tonturaDesmaio: string read FtonturaDesmaio write FtonturaDesmaio;
property poucaSaliva: string read FpoucaSaliva write FpoucaSaliva;
property idTblPaciente: integer read FidTblPaciente write FidTblPaciente;
//constructor Create;
//destructor Destroy; override;
end;
implementation
{ TSinaisSintomas }
end.
|
unit UVolumeControl;
interface
uses Classes, Windows, SysUtils, MMSystem;
type
TVolumeRec = record
case Integer of
0: (LongVolume: Longint);
1: (LeftVolume, RightVolume : Word);
end;
procedure SetVolume(DeviceIndex: Cardinal; aVolume:Byte);
function GetVolume(DeviceIndex: Cardinal): Cardinal;
const
DEVICE_WAVE = 0;
DEVICE_MIDI = 1;
DEVICE_CD = 2;
DEVICE_LINEIN = 3;
DEVICE_MICROPHONE = 4;
DEVICE_MASTER = 5;
DEVICE_PCSPEAKER = 6;
implementation
procedure SetVolume(DeviceIndex: Cardinal; aVolume:Byte);
var
Vol: TVolumeRec;
begin
Vol.LeftVolume := aVolume shl 8;
Vol.RightVolume:= Vol.LeftVolume;
auxSetVolume(UINT(DeviceIndex), Vol.LongVolume);
end;
function GetVolume(DeviceIndex: Cardinal): Cardinal;
var
Vol: TVolumeRec;
begin
AuxGetVolume(UINT(DeviceIndex), @Vol.LongVolume);
Result := (Vol.LeftVolume + Vol.RightVolume) shr 9;
end;
end.
|
// Cette unité sert à tester la classe Requete. Cette classe comprend des tests
// pour vérifier le bon fonctionnement du constructeur ainsi que les accesseurs
// pour l'adresse demandeur, la date de réception d'une requête, la version du
// protocole, la méthode utilisée pour le transfert de l'adresse et l'url.
unit uniteTestRequete;
interface
uses SysUtils, TestFrameWork, uniteRequete, DateUtils;
type
// Nom de la classe pour faire les tests.
TestRequete = class(TTestCase)
published
// Test sur l'accesseur de l'adresse demandeur de la classe Requete.
procedure testGetAdresseDemandeur;
// Test sur l'accesseur de la version du protocole de la classe Requete.
procedure testGetVersionProtocole;
// Test sur l'accesseur de l'url de la classe Requete.
procedure testGetURL;
// Test sur l'accesseur de ls méthode utilisée pour le transfert d'une adresse
// de la classe Requete.
procedure testGetMethode;
// Test sur la date de réception concernant la requête en cours.
procedure testGetDateReception;
end;
implementation
// Test sur l'accesseur de l'adresse demandeur de la classe Requete.
procedure testRequete.testGetAdresseDemandeur;
var
// Sert pour la création d'une requête afin de vérifier le bon fonctionnement
// de l'accesseur de getAdresseDemandeur de la classe Requete.
uneRequete : Requete;
begin
// Création d'un objet de type Requete.
uneRequete := Requete.create('100.0.0.1',now,'HTTP/1.1','GET','index.html');
// Vérifie si la valeur retournée par l'accesseur getAdresseDemandeur
// correspond à la valeur passée au constructeur.
check( uneRequete.getAdresseDemandeur = '100.0.0.1' );
// Destruction de l'objet après la création.
uneRequete.destroy;
end;
// Test sur le constructeur de la classe Requete avec une version protocole incorrecte.
procedure testRequete.testGetVersionProtocole;
var
// Sert pour la création d'une requête afin de vérifier le bon fonctionnement
// de l'accesseur de getVersionProtocole de la classe Requete.
uneRequete : Requete;
begin
// Création d'un objet de type Requete.
uneRequete := Requete.create('100.0.0.1',now,'HTTP/1.1','GET','index.html');
// Vérifie si la valeur retournée par l'accesseur getVersionProtocole
// correspond à la valeur passée au constructeur.
check( uneRequete.getVersionProtocole = 'HTTP/1.1' );
// Destruction de l'objet après la création.
uneRequete.destroy;
end;
// Test sur l'accesseur de l'url de la classe Requete.
procedure testRequete.testGetURL;
var
// Sert pour la création d'une requête afin de vérifier le bon fonctionnement
// de l'accesseur de getURL de la classe Requete.
uneRequete : Requete;
begin
// Création d'un objet de type Requete.
uneRequete := Requete.create('100.0.0.1',now,'HTTP/1.1','GET','index.html');
// Vérifie si la valeur retournée par l'accesseur getURL
// correspond à la valeur passée au constructeur.
check( uneRequete.getURL = 'index.html' );
// Destruction de l'objet après la création.
uneRequete.destroy;
end;
// Test sur l'accesseur de ls méthode utilisée pour le transfert d'une adresse
// de la classe Requete.
procedure testRequete.testGetMethode;
var
// Sert pour la création d'une requête afin de vérifier le bon fonctionnement
// de l'accesseur de getMethode de la classe Requete.
uneRequete : Requete;
begin
// Création d'un objet de type Requete.
uneRequete := Requete.create('100.0.0.1',now,'HTTP/1.1','GET','index.html');
// Vérifie si la valeur retournée par l'accesseur getMethode
// correspond à la valeur passée au constructeur.
check( uneRequete.getMethode = 'GET' );
// Destruction de l'objet après la création.
uneRequete.destroy;
end;
// Test sur la date de réception concernant la requête en cours.
procedure testRequete.testGetDateReception;
var
// Sert pour la création d'une requête afin de vérifier le bon fonctionnement
// de l'accesseur de getDateReception de la classe Requete.
uneRequete : Requete;
// Sert pour la comparaison de la date et heure courante du système avec
// la valeur retournée par l'accesseur getDateReception;
uneDate : TDateTime;
begin
// Date courante du système.
uneDate := now;
// Création d'un objet de type Requete.
uneRequete := Requete.create('100.0.0.1',now,'HTTP/1.1','GET','index.html');
// Vérifie si la valeur retournée par l'accesseur getDateReception
// correspond à la valeur passée au constructeur.
check(( compareDate( uneRequete.getDateReception, uneDate ) = 0 ) and
( hoursBetween ( uneRequete.getDateReception, uneDate ) = 0 ) and
( minutesBetween ( uneRequete.getDateReception, uneDate ) = 0 ));
// Destruction de l'objet après la création.
uneRequete.destroy;
end;
initialization
TestFrameWork.RegisterTest(TestRequete.Suite);
end.
|
unit ZStageUnit;
// ========================================================================
// MesoScan: Z Stage control module
// (c) J.Dempster, Strathclyde Institute for Pharmacy & Biomedical Sciences
// ========================================================================
// 7/6/12 Supports Prior OptiScan II controller
// 14.5.14 Supports voltage-controlled lens positioner
// 27.0.16 Z stage pressure switch protection implemented
// 11.02.17 .Enabled removed, XPosition, YPosition added
// 16.01.17 ZStage.XScaleFactor and ZStage.YScaleFactor added
// 10.05.17 ZPositionMax,ZPositionMin limits added
// 24.05.17 ProScanEnableZStageTTLAction now executed before first Z stage position
// check because commands fail to work immediatelt after opening of com link to
// ProSCan III stage
// 08.08.17 Prior stage: ProScanEnableZStageTTLAction - stop all movement command added
// to TTL triggered list to abort any move commands in progress.
// Now operates in standard mode to allow 'R' command responses to be returned immediately after command
// Moves can now be changed while in progress.
// 18.10.17 Now reports if COM port cannot be opened and disables send/recieves to controller
// 14.11.18 Conversion to Threaded COM I/O in progress
// 03.12.18 Now tested and working with threaded COM I/O
// 15.01.19 Adding support for Thorlabs TDC001
// 20.02.19 COM port thread now terminated before freeing.
interface
uses
System.SysUtils, System.Classes, Windows, FMX.Dialogs, math, strutils, ZStageComThreadUnit,
Vcl.ExtCtrls ;
type
TTLI_DeviceInfo = packed record
typeID : DWord ;
description : Array[0..64] of ANSIChar ;
serialNo : Array[0..8] of ANSIChar ;
PID :DWORD ;
isKnownType : Boolean ;
motorType : DWord ;
isPiezoDevice : Boolean ;
isLaser : Boolean ;
isCustomType : Boolean ;
isRack : Boolean ;
maxChannels : SmallInt
end ;
TTLI_BuildDeviceList = function : SmallInt ; cdecl ;
TTLI_GetDeviceListSize = function : SmallInt ; cdecl ;
TLI_GetDeviceListByTypeExt = function(
receiveBuffer : PANSIChar ;
sizeOfBuffer : DWORD ;
typeID : Integer ) : SmallInt ; cdecl ;
TTLI_GetDeviceInfo = function(
serialNo :PANSIChar ;
info : TTLI_DeviceInfo ) : SmallInt ; cdecl ;
TCC_Open = function( serialNo :PANSIChar ) : SmallInt ; cdecl ;
TCC_Close = procedure( serialNo :PANSIChar ) ; cdecl ;
TCC_StartPolling = function( serialNo :PANSIChar ;
Milliseconds : Integer ) : WordBool ; cdecl ;
TCC_StopPolling = function( serialNo :PANSIChar ) : WordBool ; cdecl ;
TCC_ClearMessageQueue = procedure( serialNo :PANSIChar ) ; cdecl ;
TCC_Home = function( serialNo :PANSIChar ) : SmallInt ; cdecl ;
TCC_WaitForMessage = function(
serialNo :PANSIChar ;
var messageType : DWORD ;
var messageID : DWORD ;
var messageData : DWORD ) : Boolean ; cdecl ;
TCC_GetVelParams = function(
serialNo :PANSIChar ;
var acceleration : Integer ;
var maxVelocity : Integer ) : SmallInt ; cdecl ;
TCC_SetVelParams = function(
serialNo :PANSIChar ;
acceleration : Integer ;
maxVelocity : Integer ) : SmallInt ; cdecl ;
TCC_MoveToPosition = function(
serialNo :PANSIChar ;
Index : Integer ) : SmallInt ; cdecl ;
TCC_GetPosition = function(
serialNo :PANSIChar ) : Integer ; cdecl ;
TCC_GetMotorParamsExt = function(
serialNo : PANSIChar ;
var stepsPerRev : double ;
var gearBoxRatio : double ;
var pitch : double ) : SMallInt ; cdecl ;
TCC_GetRealValueFromDeviceUnit = function(
serialNo : PANSIChar ;
device_unit : Integer ;
//var real_unit : Double ;
p : Pointer ;
unitType : Integer ) : SMallInt ; cdecl ;
TCC_GetDeviceUnitFromRealValue = function(
serialNo : PANSIChar ;
real_unit : Double ;
var device_unit : Integer ;
unitType : Integer ) : SMallInt ; cdecl ;
TCC_SetMotorTravelLimits = function(
serialNo : PANSIChar ;
minPosition : Double ;
maxPosition : Double ) : SMallInt ; cdecl ;
TCC_GetMotorTravelLimits = function(
serialNo : PANSIChar ;
var minPosition : Double ;
var maxPosition : Double ) : SMallInt ; cdecl ;
TZStage = class(TDataModule)
Timer1: TTimer;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FStageType : Integer ; // Type of stage
FStageIsOpen : Boolean ; // TRUE = stage is open for use
FSerialNumber : ANSIString ; // Device serial number
// FControlPort : DWord ; // Control port number
FBaudRate : DWord ; // Com port baud rate
ControlState : Integer ; // Z stage control state
Status : String ; // Z stage status report
MoveToRequest : Boolean ; // Go to Final flag
RequestedXPos : Double ; // Intermediate X position
RequestedYPos : Double ; // Intermediate Y position
RequestedZPos : Double ; // Intermediate Z position
StageInitRequired : Boolean ; // Stage needs to be initialised
WaitingForPositionUpdate : Boolean ;
ComThread : TZStageComThread ;
// Thorlabs TDC001 procedures and variables
LibraryHnd : THandle ;
CommonLibraryHnd : THandle ;
mmToDeviceUnits : Double ;
DeviceUnitsTomm : Double ;
TLI_BuildDeviceList : TTLI_BuildDeviceList ;
TLI_GetDeviceListSize : TTLI_GetDeviceListSize ;
TLI_GetDeviceListByTypeExt : TLI_GetDeviceListByTypeExt ;
TLI_GetDeviceInfo : TTLI_GetDeviceInfo ;
CC_Open : TCC_Open ;
CC_Close : TCC_Close ;
CC_StartPolling : TCC_StartPolling ;
CC_StopPolling : TCC_StopPolling ;
CC_ClearMessageQueue : TCC_ClearMessageQueue ;
CC_Home : TCC_Home ;
CC_WaitForMessage : TCC_WaitForMessage ;
CC_GetVelParams : TCC_GetVelParams ;
CC_SetVelParams : TCC_SetVelParams ;
CC_MoveToPosition : TCC_MoveToPosition ;
CC_GetPosition : TCC_GetPosition ;
CC_GetMotorParamsExt : TCC_GetMotorParamsExt ;
CC_GetRealValueFromDeviceUnit : TCC_GetRealValueFromDeviceUnit ;
CC_GetDeviceUnitFromRealValue : TCC_GetDeviceUnitFromRealValue ;
CC_SetMotorTravelLimits : TCC_SetMotorTravelLimits ;
CC_GetMotorTravelLimits : TCC_GetMotorTravelLimits ;
procedure SetControlPort( Value : DWord ) ;
procedure SetStageType( Value : Integer ) ;
procedure MoveToPrior( X : Double ; // New X pos.
Y : Double ; // NEw Y pos.
Z : Double // New Z pos.
) ;
procedure MoveToPZ( Position : Double ) ;
function GetScaleFactorUnits : string ;
procedure StopComThread ;
public
{ Public declarations }
XPosition : Double ; // X position (um)
XScaleFactor : Double ; // X step scaling factor
YPosition : Double ; // Y position (um)
YScaleFactor : Double ; // Y step scaling factor
ZPosition : Double ; // Z position (um)
ZPositionMax : Double ; // Z position upper limit (um)
ZPositionMin : Double ; // Z position lower limit (um)
ZScaleFactor : Double ; // Z step scaling factor
ZStepTime : Double ; // Time to perform Z step (s)
FControlPort : DWord ; // Control port number
CommandList : TstringList ; // Light Source command list
ReplyList : TstringList ; // Light source replies
TickCounter : Integer ; // Timer tick counter
ReplyZeroCount : Integer ; // No. of '0' replies to wait for before init complete
Initialised : Boolean ; // TRUE = stage initialised
procedure Open ;
procedure Close ;
procedure MoveTo( X : Double ; // New X pos.
Y : Double ; // NEw Y pos.
Z : Double // New Z pos.
) ;
procedure GetZStageTypes( List : TStrings ) ;
procedure GetControlPorts( List : TStrings ) ;
function IsControlPortRequired : Boolean ;
function IsSerialNumberRequired : Boolean ;
procedure SetSerialNumber( Value : String ) ;
function GetSerialNumber : string ;
procedure PriorHandleMessages ;
procedure TDC001_Open ;
procedure TDC001_GetPosition ;
procedure TDC001_MoveTo( Z : Double ) ;
procedure TDC001_Close ;
procedure TDC001_LoadLibrary ;
function GetDLLAddress(
Handle : THandle ;
const ProcName : string ) : Pointer ;
published
Property ControlPort : DWORD read FControlPort write SetControlPort ;
Property StageType : Integer read FStageType write SetStageType ;
Property ScaleFactorUnits : string read GetScaleFactorUnits ;
Property ControlPortRequired : Boolean read IsControlPortRequired ;
Property SerialNumberRequired : Boolean read IsSerialNumberRequired ;
Property SerialNumber : String read GetSerialNumber write SetSerialNumber ;
Property IsOpen : Boolean read FStageIsOpen ;
end;
var
ZStage: TZStage;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses LabIOUnit, mmsystem;
{$R *.dfm}
const
csIdle = 0 ;
csWaitingForPosition = 1 ;
csWaitingForCompletion = 2 ;
stNone = 0 ;
stOptiscanII = 1 ;
stProscanIII = 2 ;
stPiezo = 3 ;
stTDC001 = 4 ;
XMaxStep = 10000.0 ;
YMaxStep = 10000.0 ;
ZMaxStep = 10000.0 ;
procedure TZStage.DataModuleCreate(Sender: TObject);
// ---------------------------------------
// Initialisations when module is created
// ---------------------------------------
begin
FStageType := stNone ;
FControlPort := 0 ;
FBaudRate := 9600 ;
Status := '' ;
ControlState := csIdle ;
XPosition := 0.0 ;
XscaleFactor := 1.0 ;
YPosition := 0.0 ;
YScaleFactor := 1.0 ;
ZPosition := 0.0 ;
ZPositionMax := 10000.0 ;
ZPositionMin := -10000.0 ;
ZScaleFactor := 10.0 ;
RequestedXPos := 0.0 ;
RequestedYPos := 0.0 ;
RequestedZPos := 0.0 ;
CommandList := TStringList.Create ;
ReplyList := TStringList.Create ;
ComThread := Nil ;
TickCounter := 0 ;
Initialised := False ;
WaitingForPositionUpdate := False ;
MoveToRequest := False ;
StageInitRequired := False ;
// Thorlab device variable inits.
FSerialNumber := '0' ;
LibraryHnd := 0 ;
CommonLibraryHnd := 0 ;
FStageIsOpen := False ;
end;
procedure TZStage.DataModuleDestroy(Sender: TObject);
// --------------------------------
// Tidy up when module is destroyed
// --------------------------------
begin
StopComThread ;
CommandList.Free ;
ReplyList.Free ;
// Free DLLs
//if LibraryHnd <> 0 then FreeLibrary(LibraryHnd) ;
LibraryHnd := 0 ;
if CommonLibraryHnd <> 0 then FreeLibrary(CommonLibraryHnd) ;
CommonLibraryHnd := 0 ;
end;
procedure TZStage.StopComThread ;
// ------------------------
// Stop and free COM thread
// ------------------------
begin
if ComThread = Nil Then Exit ;
ComThread.Terminate ;
ComThread.WaitFor ;
FreeAndNil(ComThread);
end;
procedure TZStage.GetZStageTypes( List : TStrings ) ;
// -----------------------------------
// Get list of supported Z stage types
// -----------------------------------
begin
List.Clear ;
List.Add('None') ;
List.Add('Prior Optiscan II') ;
List.Add('Prior Proscan III') ;
List.Add('Piezo (Voltage Controlled)');
List.Add('Thorlabs TDC001');
end;
procedure TZStage.GetControlPorts( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
begin
List.Clear ;
case FStageType of
stOptiscanII,stProScanIII : begin
// COM ports
List.Add(format('None',[0]));
for i := 1 to 16 do List.Add(format('COM%d',[i]));
end ;
stPiezo : begin
// Analog outputs
for iDev := 1 to LabIO.NumDevices do
for i := 0 to LabIO.NumDACs[iDev]-1 do begin
List.Add(Format('Dev%d:AO%d',[iDev,i])) ;
end;
end;
else begin
List.Add('None');
end ;
end;
end;
procedure TZStage.Open ;
// ---------------------------
// Open Z stage for operation
// ---------------------------
begin
// Close COM thread (if open)
StopComThread ;
case FStageType of
stOptiscanII :
begin
ComThread := TZStageComThread.Create ;
CommandList.Add('COMP 0') ;
FStageIsOpen := True ;
end;
stProScanIII :
begin
ComThread := TZStageComThread.Create ;
// Download stage protection handler
// (Returns stage to Z=0 when stage microswitch triggered
CommandList.Add('COMP 0') ;
CommandList.Add('SMZ 20') ; // Set Z stage speed to 20% of maximum
CommandList.Add( 'TTLDEL,1') ;
CommandList.Add( 'TTLTP,1,1') ; // Enable trigger on input #1 going high
CommandList.Add( 'TTLACT,1,70,0,0,0') ; // Stop all movement
CommandList.Add( 'TTLACT,1,31,0,0,0') ; // Move Z axis to zero position
CommandList.Add( 'TTLTRG,1') ; // Enable triggers
ReplyZeroCount := 6 ;
StageInitRequired := True ;
WaitingForPositionUpdate := False ;
FStageIsOpen := True ;
end ;
stPiezo :
begin
FStageIsOpen := True ;
end;
stTDC001 :
begin
TDC001_Open ;
end;
else
begin
FStageIsOpen := True ;
end;
end;
end;
function TZStage.GetScaleFactorUnits : string ;
// -------------------------------
// Return units for Z scale factor
// -------------------------------
begin
case FStageType of
stOptiscanII,stProScanIII,stTDC001 : Result := 'steps/um' ;
stPiezo : Result := 'V/um' ;
else Result := '' ;
end;
end;
procedure TZStage.Close ;
// ---------------------------
// Close down Z stage operation
// ---------------------------
begin
if not FStageIsOpen then Exit ;
// Stop COM port thread if it is running
StopComThread ;
case FStageType of
stTDC001 :
begin
TDC001_Close ;
end;
end;
FStageIsOpen := False ;
end;
procedure TZStage.MoveTo( X : Double ; // New X pos.
Y : Double ; // New Y pos.
Z : Double // New Z pos.
) ;
// ----------------
// Go to Z position
// ----------------
begin
if not FStageIsOpen then Exit ;
// Keep within limits
Z := Min(Max(Z,ZPositionMin),ZPositionMax);
case FStageType of
stOptiscanII,stProScanIII : MoveToPrior( X,Y,Z ) ;
stTDC001 : TDC001_MoveTo(Z) ;
stPiezo : MoveToPZ( Z ) ;
end;
end;
function TZStage.IsControlPortRequired : Boolean ;
// --------------------------------------------------------------------
// Returns TRUE if a control port is required to communicate with stage
// --------------------------------------------------------------------
begin
case FStageType of
stOptiscanII,stProScanIII,stPiezo : Result := True ;
else Result := False ;
end;
end ;
function TZStage.IsSerialNumberRequired : Boolean ;
// --------------------------------------------------------------------
// Returns TRUE if a serial number is required to identify the stage
// --------------------------------------------------------------------
begin
case FStageType of
stTDC001 : Result := True
else Result := False ;
end;
end ;
procedure TZStage.SetSerialNumber( Value : string ) ;
// ------------------------
// Set device serial number
// ------------------------
begin
if FSerialNumber <> Value then
begin
FSerialNumber := ansisTRING(Value) ;
if IsSerialNumberRequired and FStageIsOpen then
begin
// Close and re-open stage
Close ;
Open ;
end;
end;
end;
function TZStage.GetSerialNumber : string ;
// ------------------------
// Get device serial number
// ------------------------
begin
Result := FSerialNumber ;
end;
procedure TZStage.MoveToPrior( X : Double ; // New X pos.
Y : Double ; // New Y pos.
Z : Double // New Z pos.
) ;
// ------------------------------
// Go to Z position (Optoscan II)
// ------------------------------
begin
// Stop any stage moves in progress
CommandList.Add('I') ;
RequestedXPos := X ;
RequestedYPos := Y ;
RequestedZPos := Z ;
// Move to new position
CommandList.Add( format('G %d,%d,%d',
[Round(RequestedXPos*XScaleFactor),
Round(RequestedYPos*YScaleFactor),
Round(RequestedZPos*ZScaleFactor)]));
end;
procedure TZStage.SetControlPort( Value : DWord ) ;
// ----------------
// Set Control Port
//-----------------
begin
FControlPort := Max(Value,0) ;
// If stage is open for use, close and re-open
if FStageIsOpen then
begin
Close ;
Open ;
end;
end;
procedure TZStage.SetStageType( Value : Integer ) ;
// ------------------------------
// Set type of Z stage controller
// ------------------------------
begin
if not FStageIsOpen then FStageType := Value
else
begin
// If stage is open, close, set type and re-open
Close ;
FStageType := Value ;
Open ;
end;
end;
procedure TZStage.Timer1Timer(Sender: TObject);
// --------------------------------------------
// Timed interval Z stage monitoring tasks
// --------------------------------------------
begin
if not FStageIsOpen then Exit ;
case FStageType of
stOptiscanII,stProScanIII : PriorHandleMessages ;
stTDC001 : TDC001_GetPosition ;
end;
end;
procedure TZStage.PriorHandleMessages ;
// -----------------------------------
// Handle Prior Z stage reply messages
// -----------------------------------
var
OldInitialised : Boolean ;
Reply,s,c : string ;
i,iNum : Integer ;
begin
OldInitialised := Initialised ;
if Initialised and (not WaitingForPositionUpdate) then
begin
CommandList.Add('P') ;
WaitingForPositionUpdate := True ;
end;
if ReplyList.Count > 0 then
begin
if (ReplyList[0] = 'R') {or (ReplyList[0] = 'O')} then
begin
end
else if ReplyList[0] = '0' then
begin
Dec(ReplyZeroCount) ;
if ReplyZeroCount = 0 then Initialised := True ;
end
else
begin
Reply := ReplyList[0] ;
i := 1 ;
s := '' ;
iNum := 0 ;
XScaleFactor := Max(XScaleFactor,1E-4) ;
YScaleFactor := Max(YScaleFactor,1E-4) ;
ZScaleFactor := Max(ZScaleFactor,1E-4) ;
while i <= Length(Reply) do
begin
c := Reply[i] ;
if (c = ',') or (i = Length(Reply)) then
begin
if c <> ',' then s := s + Reply[i] ;
// Remove error flag (if represent)
s := ReplaceText(s,'R','');
if (not ContainsText(s,'R')) and (s<>'') then
begin
case iNum of
0 : XPosition := StrToInt64(s)/XScaleFactor ;
1 : YPosition := StrToInt64(s)/YScaleFactor ;
2 : begin
ZPosition := StrToInt64(s)/ZScaleFactor ;
end;
end ;
end;
Inc(INum) ;
s := '' ;
end
else s := s + Reply[i] ;
Inc(i) ;
end;
WaitingForPositionUpdate := False ;
end;
ReplyList.Delete(0);
end;
// Increment init counter
Inc(TickCounter) ;
// Initialise light source after 20 ticks (2 seconds) if not already init'd
if TickCounter > 40 then Initialised := True ;
end;
procedure TZStage.MoveToPZ( Position : Double ) ;
// -------------------------
// Go to Z position (Piezo)
// -------------------------
var
iPort,iChan,iDev : Integer ;
begin
ZPosition := Position ;
iPort := 0 ;
for iDev := 1 to LabIO.NumDevices do
for iChan := 0 to LabIO.NumDACs[iDev]-1 do
begin
if iPort = FControlPort then
begin
LabIO.WriteDAC(iDev,Position*ZScaleFactor,iChan);
end;
inc(iPort) ;
end;
end ;
procedure TZStage.TDC001_Open ;
// --------------------
// Open Thorlabs device
// --------------------
begin
FStageIsOpen := False ;
// Load DLL library
TDC001_LoadLibrary ;
// Open selected device
if CC_Open(PANSIChar(FSerialNumber)) <> 0 then Exit ;
CC_StartPolling(PANSIChar(FSerialNumber), 200);
CC_ClearMessageQueue(PANSIChar(FSerialNumber));
// Move to home position
CC_Home(PANSIChar(FSerialNumber)) ;
FStageIsOpen := True ;
end;
procedure TZStage.TDC001_LoadLibrary ;
// -----------------------------
// Load Thorlabs DLL libraries
// -----------------------------
var
Path : Array[0..255] of Char ;
LibFileName,SYSDrive : String ;
begin
// Exit if library already loaded
if LibraryHnd <> 0 then Exit ;
// Get system drive
GetSystemDirectory( Path, High(Path) ) ;
SYSDrive := ExtractFileDrive(String(Path)) ;
LibFileName := SYSDrive + '\Program Files\Thorlabs\Kinesis\Thorlabs.MotionControl.DeviceManager.DLL' ;
CommonLibraryHnd := LoadLibrary( PChar(LibFileName ) );
if CommonLibraryHnd = 0 then begin
ShowMessage( 'Unable to open' + LibFileName ) ;
Exit ;
end ;
LibFileName := SYSDrive + '\Program Files\Thorlabs\Kinesis\Thorlabs.MotionControl.TCube.DCServo.DLL' ;
LibraryHnd := LoadLibrary( PChar(LibFileName));
if LibraryHnd = 0 then begin
ShowMessage( 'Unable to open' + LibFileName ) ;
Exit ;
end ;
@TLI_BuildDeviceList := GetDLLAddress( LibraryHnd, 'TLI_BuildDeviceList' ) ;
@TLI_GetDeviceListSize := GetDLLAddress( LibraryHnd, 'TLI_GetDeviceListSize' ) ;
@TLI_GetDeviceListByTypeExt := GetDLLAddress( LibraryHnd, 'TLI_GetDeviceListByTypeExt' ) ;
@TLI_GetDeviceInfo := GetDLLAddress( LibraryHnd, 'TLI_GetDeviceInfo' ) ;
@CC_Open := GetDLLAddress( LibraryHnd, 'CC_Open' ) ;
@CC_Close := GetDLLAddress( LibraryHnd, 'CC_Close' ) ;
@CC_StartPolling := GetDLLAddress( LibraryHnd, 'CC_StartPolling' ) ;
@CC_StopPolling := GetDLLAddress( LibraryHnd, 'CC_StopPolling' ) ;
@CC_ClearMessageQueue := GetDLLAddress( LibraryHnd, 'CC_ClearMessageQueue' ) ;
@CC_Home := GetDLLAddress( LibraryHnd, 'CC_Home' ) ;
@CC_WaitForMessage := GetDLLAddress( LibraryHnd, 'CC_WaitForMessage' ) ;
@CC_GetVelParams := GetDLLAddress( LibraryHnd, 'CC_GetVelParams' ) ;
@CC_SetVelParams := GetDLLAddress( LibraryHnd, 'CC_SetVelParams' ) ;
@CC_MoveToPosition := GetDLLAddress( LibraryHnd, 'CC_MoveToPosition' ) ;
@CC_GetPosition := GetDLLAddress( LibraryHnd, 'CC_GetPosition' ) ;
@CC_GetMotorParamsExt := GetDLLAddress( LibraryHnd, 'CC_GetMotorParamsExt' ) ;
@CC_GetRealValueFromDeviceUnit := GetDLLAddress( LibraryHnd, 'CC_GetRealValueFromDeviceUnit' ) ;
@CC_GetDeviceUnitFromRealValue := GetDLLAddress( LibraryHnd, 'CC_GetDeviceUnitFromRealValue' ) ;
@CC_SetMotorTravelLimits := GetDLLAddress( LibraryHnd, 'CC_SetMotorTravelLimits' ) ;
@CC_GetMotorTravelLimits := GetDLLAddress( LibraryHnd, 'CC_GetMotorTravelLimits' ) ;
end;
procedure TZStage.TDC001_GetPosition ;
// --------------------------------
// Handle data returned from TDC001
// --------------------------------
var
DeviceUnits : Integer ;
ii : Int64 ;
begin
if not FStageIsOpen then Exit ;
DeviceUnits := CC_GetPosition( PANSIChar(FSerialNumber) ) ;
if ZScaleFactor <> 0.0 then ZPosition := DeviceUnits / ZScaleFactor ;
end;
procedure TZStage.TDC001_MoveTo( Z : Double ) ;
// -------------------------------------
// Move to selected Z position (microns)
// -------------------------------------
var
Steps : Integer ;
begin
// Keep within limits
z := Max(Min(Z,ZPositionMax),ZPositionMin);
Steps := Round(Z*ZScaleFactor) ;
CC_MoveToPosition( PANSIChar(FSerialNumber), Steps ) ;
end;
procedure TZStage.TDC001_Close ;
// ----------------------------------------
// Close Thorlabs TDC001 DC servo controller
// ----------------------------------------
begin
if not FStageIsOpen then Exit ;
// Stop polling device
CC_StopPolling(PANSIChar(FSerialNumber)) ;
CC_ClearMessageQueue(PANSIChar(FSerialNumber)) ;
// Close device
CC_Close(PANSIChar(FSerialNumber)) ;
FStageIsOpen := False ;
end;
function TZStage.GetDLLAddress(
Handle : THandle ;
const ProcName : string ) : Pointer ;
// -----------------------------------------
// Get address of procedure within DLL
// -----------------------------------------
begin
Result := GetProcAddress(Handle,PChar(ProcName)) ;
if Result = Nil then ShowMessage('DLL: ' + ProcName + ' not found') ;
end ;
end.
|
unit uLog;
interface
uses
Winapi.Windows,
Classes,
Variants,
SysUtils;
// fix current time
procedure log_tick;
// get deltatime (ms)
function log_delta: single;
// tick count
function log_tcount: integer;
// log
procedure log(a_Msg:string; color:integer = 7);
// log if exp
function logExp(a_Exp:boolean; a_Msg:string): boolean;
implementation
var
_cc: cardinal;
_tc: integer = -1;
procedure log_tick;
begin
_cc := GetTickCount();
inc( _tc );
end;
function log_tcount: integer;
begin
result := _tc;
end;
function log_delta: single;
begin
result := (GetTickCount() - _cc) * 0.001;
end;
procedure log;
var
sTime: TSystemTime;
begin
if not isConsole then exit;
GetLocalTime(sTime);
with sTime do begin
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
/// writeln(Format('[%.2d:%.2d:%.2d.%.3d] ' + a_Msg,[wHour,wMinute,wSecond,wMilliseconds]));
end;
end;
function logExp(a_Exp:boolean; a_Msg:string): boolean;
begin
result := a_Exp;
if a_Exp then
log(a_Msg, 14);
end;
end.
|
program poj1046;
var n,m,a,b,l,i,j,k:int64;
gg:int64;
x,y:int64;
aa,bb:int64;
d,t:int64;
function gcd(a,b:int64):int64;
begin
if b=0 then exit(a);
gcd:=gcd(b,a mod b);
end;
function exgcd(a,b:int64; var x,y:int64):longint;
var t:int64;
begin
if b=0 then
begin
exgcd:=a;
x:=1;
y:=0;
end
else
begin
exgcd:=exgcd(b,a mod b,x,y);
t:=x;
x:=y;
y:=x-(a div b)*y;
end;
end;
begin
read(a,b,m,n,l);
gg:=gcd(l,n-m);
if gg mod (a-b)<>0 then
writeln('Impossible');
a:=l div gg;
b:=(n-m) div gg;
d:=(a-b) div gg;
exgcd(a,b,x,y);
t:=d*x div b;
x:=d*x-t*b;
if x<0 then
x:=x+b;
writeln(x);
end.
|
unit XED.NonterminalEnum;
{$Z4}
interface
type
TXED_Nonterminal_Enum = (
XED_NONTERMINAL_INVALID,
XED_NONTERMINAL_AR10,
XED_NONTERMINAL_AR11,
XED_NONTERMINAL_AR12,
XED_NONTERMINAL_AR13,
XED_NONTERMINAL_AR14,
XED_NONTERMINAL_AR15,
XED_NONTERMINAL_AR8,
XED_NONTERMINAL_AR9,
XED_NONTERMINAL_ARAX,
XED_NONTERMINAL_ARBP,
XED_NONTERMINAL_ARBX,
XED_NONTERMINAL_ARCX,
XED_NONTERMINAL_ARDI,
XED_NONTERMINAL_ARDX,
XED_NONTERMINAL_ARSI,
XED_NONTERMINAL_ARSP,
XED_NONTERMINAL_ASZ_NONTERM,
XED_NONTERMINAL_AVX512_ROUND,
XED_NONTERMINAL_AVX_INSTRUCTIONS,
XED_NONTERMINAL_AVX_SPLITTER,
XED_NONTERMINAL_A_GPR_B,
XED_NONTERMINAL_A_GPR_R,
XED_NONTERMINAL_BND_B,
XED_NONTERMINAL_BND_B_CHECK,
XED_NONTERMINAL_BND_R,
XED_NONTERMINAL_BND_R_CHECK,
XED_NONTERMINAL_BRANCH_HINT,
XED_NONTERMINAL_BRDISP32,
XED_NONTERMINAL_BRDISP8,
XED_NONTERMINAL_BRDISPZ,
XED_NONTERMINAL_CET_NO_TRACK,
XED_NONTERMINAL_CR_B,
XED_NONTERMINAL_CR_R,
XED_NONTERMINAL_CR_WIDTH,
XED_NONTERMINAL_DF64,
XED_NONTERMINAL_DR_R,
XED_NONTERMINAL_ESIZE_128_BITS,
XED_NONTERMINAL_ESIZE_16_BITS,
XED_NONTERMINAL_ESIZE_1_BITS,
XED_NONTERMINAL_ESIZE_2_BITS,
XED_NONTERMINAL_ESIZE_32_BITS,
XED_NONTERMINAL_ESIZE_4_BITS,
XED_NONTERMINAL_ESIZE_64_BITS,
XED_NONTERMINAL_ESIZE_8_BITS,
XED_NONTERMINAL_EVEX_INSTRUCTIONS,
XED_NONTERMINAL_EVEX_SPLITTER,
XED_NONTERMINAL_FINAL_DSEG,
XED_NONTERMINAL_FINAL_DSEG1,
XED_NONTERMINAL_FINAL_DSEG1_MODE64,
XED_NONTERMINAL_FINAL_DSEG1_NOT64,
XED_NONTERMINAL_FINAL_DSEG_MODE64,
XED_NONTERMINAL_FINAL_DSEG_NOT64,
XED_NONTERMINAL_FINAL_ESEG,
XED_NONTERMINAL_FINAL_ESEG1,
XED_NONTERMINAL_FINAL_SSEG,
XED_NONTERMINAL_FINAL_SSEG0,
XED_NONTERMINAL_FINAL_SSEG1,
XED_NONTERMINAL_FINAL_SSEG_MODE64,
XED_NONTERMINAL_FINAL_SSEG_NOT64,
XED_NONTERMINAL_FIX_ROUND_LEN128,
XED_NONTERMINAL_FIX_ROUND_LEN512,
XED_NONTERMINAL_FORCE64,
XED_NONTERMINAL_GPR16_B,
XED_NONTERMINAL_GPR16_R,
XED_NONTERMINAL_GPR16_SB,
XED_NONTERMINAL_GPR32_B,
XED_NONTERMINAL_GPR32_R,
XED_NONTERMINAL_GPR32_SB,
XED_NONTERMINAL_GPR32_X,
XED_NONTERMINAL_GPR64_B,
XED_NONTERMINAL_GPR64_R,
XED_NONTERMINAL_GPR64_SB,
XED_NONTERMINAL_GPR64_X,
XED_NONTERMINAL_GPR8_B,
XED_NONTERMINAL_GPR8_R,
XED_NONTERMINAL_GPR8_SB,
XED_NONTERMINAL_GPRV_B,
XED_NONTERMINAL_GPRV_R,
XED_NONTERMINAL_GPRV_SB,
XED_NONTERMINAL_GPRY_B,
XED_NONTERMINAL_GPRY_R,
XED_NONTERMINAL_GPRZ_B,
XED_NONTERMINAL_GPRZ_R,
XED_NONTERMINAL_IGNORE66,
XED_NONTERMINAL_IMMUNE66,
XED_NONTERMINAL_IMMUNE66_LOOP64,
XED_NONTERMINAL_IMMUNE_REXW,
XED_NONTERMINAL_INSTRUCTIONS,
XED_NONTERMINAL_ISA,
XED_NONTERMINAL_MASK1,
XED_NONTERMINAL_MASKNOT0,
XED_NONTERMINAL_MASK_B,
XED_NONTERMINAL_MASK_N,
XED_NONTERMINAL_MASK_N32,
XED_NONTERMINAL_MASK_N64,
XED_NONTERMINAL_MASK_R,
XED_NONTERMINAL_MEMDISP,
XED_NONTERMINAL_MEMDISP16,
XED_NONTERMINAL_MEMDISP32,
XED_NONTERMINAL_MEMDISP8,
XED_NONTERMINAL_MEMDISPV,
XED_NONTERMINAL_MMX_B,
XED_NONTERMINAL_MMX_R,
XED_NONTERMINAL_MODRM,
XED_NONTERMINAL_MODRM16,
XED_NONTERMINAL_MODRM32,
XED_NONTERMINAL_MODRM64ALT32,
XED_NONTERMINAL_NELEM_EIGHTHMEM,
XED_NONTERMINAL_NELEM_FULL,
XED_NONTERMINAL_NELEM_FULLMEM,
XED_NONTERMINAL_NELEM_GPR_READER,
XED_NONTERMINAL_NELEM_GPR_READER_BYTE,
XED_NONTERMINAL_NELEM_GPR_READER_SUBDWORD,
XED_NONTERMINAL_NELEM_GPR_READER_WORD,
XED_NONTERMINAL_NELEM_GPR_WRITER_LDOP,
XED_NONTERMINAL_NELEM_GPR_WRITER_LDOP_D,
XED_NONTERMINAL_NELEM_GPR_WRITER_LDOP_Q,
XED_NONTERMINAL_NELEM_GPR_WRITER_STORE,
XED_NONTERMINAL_NELEM_GPR_WRITER_STORE_BYTE,
XED_NONTERMINAL_NELEM_GPR_WRITER_STORE_SUBDWORD,
XED_NONTERMINAL_NELEM_GPR_WRITER_STORE_WORD,
XED_NONTERMINAL_NELEM_GSCAT,
XED_NONTERMINAL_NELEM_HALF,
XED_NONTERMINAL_NELEM_HALFMEM,
XED_NONTERMINAL_NELEM_MEM128,
XED_NONTERMINAL_NELEM_MOVDDUP,
XED_NONTERMINAL_NELEM_QUARTER,
XED_NONTERMINAL_NELEM_QUARTERMEM,
XED_NONTERMINAL_NELEM_SCALAR,
XED_NONTERMINAL_NELEM_TUPLE1,
XED_NONTERMINAL_NELEM_TUPLE1_4X,
XED_NONTERMINAL_NELEM_TUPLE1_BYTE,
XED_NONTERMINAL_NELEM_TUPLE1_SUBDWORD,
XED_NONTERMINAL_NELEM_TUPLE1_WORD,
XED_NONTERMINAL_NELEM_TUPLE2,
XED_NONTERMINAL_NELEM_TUPLE4,
XED_NONTERMINAL_NELEM_TUPLE8,
XED_NONTERMINAL_OEAX,
XED_NONTERMINAL_ONE,
XED_NONTERMINAL_ORAX,
XED_NONTERMINAL_ORBP,
XED_NONTERMINAL_ORBX,
XED_NONTERMINAL_ORCX,
XED_NONTERMINAL_ORDX,
XED_NONTERMINAL_ORSP,
XED_NONTERMINAL_OSZ_NONTERM,
XED_NONTERMINAL_OVERRIDE_SEG0,
XED_NONTERMINAL_OVERRIDE_SEG1,
XED_NONTERMINAL_PREFIXES,
XED_NONTERMINAL_REFINING66,
XED_NONTERMINAL_REMOVE_SEGMENT,
XED_NONTERMINAL_RFLAGS,
XED_NONTERMINAL_RIP,
XED_NONTERMINAL_RIPA,
XED_NONTERMINAL_SAE,
XED_NONTERMINAL_SEG,
XED_NONTERMINAL_SEG_MOV,
XED_NONTERMINAL_SE_IMM8,
XED_NONTERMINAL_SIB,
XED_NONTERMINAL_SIB_BASE0,
XED_NONTERMINAL_SIMM8,
XED_NONTERMINAL_SIMMZ,
XED_NONTERMINAL_SRBP,
XED_NONTERMINAL_SRSP,
XED_NONTERMINAL_TMM_B,
XED_NONTERMINAL_TMM_N,
XED_NONTERMINAL_TMM_R,
XED_NONTERMINAL_UIMM16,
XED_NONTERMINAL_UIMM32,
XED_NONTERMINAL_UIMM8,
XED_NONTERMINAL_UIMM8_1,
XED_NONTERMINAL_UIMMV,
XED_NONTERMINAL_UISA_VMODRM_XMM,
XED_NONTERMINAL_UISA_VMODRM_YMM,
XED_NONTERMINAL_UISA_VMODRM_ZMM,
XED_NONTERMINAL_UISA_VSIB_BASE,
XED_NONTERMINAL_UISA_VSIB_INDEX_XMM,
XED_NONTERMINAL_UISA_VSIB_INDEX_YMM,
XED_NONTERMINAL_UISA_VSIB_INDEX_ZMM,
XED_NONTERMINAL_UISA_VSIB_XMM,
XED_NONTERMINAL_UISA_VSIB_YMM,
XED_NONTERMINAL_UISA_VSIB_ZMM,
XED_NONTERMINAL_VGPR32_B,
XED_NONTERMINAL_VGPR32_B_32,
XED_NONTERMINAL_VGPR32_B_64,
XED_NONTERMINAL_VGPR32_N,
XED_NONTERMINAL_VGPR32_N_32,
XED_NONTERMINAL_VGPR32_N_64,
XED_NONTERMINAL_VGPR32_R,
XED_NONTERMINAL_VGPR32_R_32,
XED_NONTERMINAL_VGPR32_R_64,
XED_NONTERMINAL_VGPR64_B,
XED_NONTERMINAL_VGPR64_N,
XED_NONTERMINAL_VGPR64_R,
XED_NONTERMINAL_VGPRY_B,
XED_NONTERMINAL_VGPRY_N,
XED_NONTERMINAL_VGPRY_R,
XED_NONTERMINAL_VMODRM_XMM,
XED_NONTERMINAL_VMODRM_YMM,
XED_NONTERMINAL_VSIB_BASE,
XED_NONTERMINAL_VSIB_INDEX_XMM,
XED_NONTERMINAL_VSIB_INDEX_YMM,
XED_NONTERMINAL_VSIB_XMM,
XED_NONTERMINAL_VSIB_YMM,
XED_NONTERMINAL_X87,
XED_NONTERMINAL_XMM_B,
XED_NONTERMINAL_XMM_B3,
XED_NONTERMINAL_XMM_B3_32,
XED_NONTERMINAL_XMM_B3_64,
XED_NONTERMINAL_XMM_B_32,
XED_NONTERMINAL_XMM_B_64,
XED_NONTERMINAL_XMM_N,
XED_NONTERMINAL_XMM_N3,
XED_NONTERMINAL_XMM_N3_32,
XED_NONTERMINAL_XMM_N3_64,
XED_NONTERMINAL_XMM_N_32,
XED_NONTERMINAL_XMM_N_64,
XED_NONTERMINAL_XMM_R,
XED_NONTERMINAL_XMM_R3,
XED_NONTERMINAL_XMM_R3_32,
XED_NONTERMINAL_XMM_R3_64,
XED_NONTERMINAL_XMM_R_32,
XED_NONTERMINAL_XMM_R_64,
XED_NONTERMINAL_XMM_SE,
XED_NONTERMINAL_XMM_SE32,
XED_NONTERMINAL_XMM_SE64,
XED_NONTERMINAL_XOP_INSTRUCTIONS,
XED_NONTERMINAL_YMM_B,
XED_NONTERMINAL_YMM_B3,
XED_NONTERMINAL_YMM_B3_32,
XED_NONTERMINAL_YMM_B3_64,
XED_NONTERMINAL_YMM_B_32,
XED_NONTERMINAL_YMM_B_64,
XED_NONTERMINAL_YMM_N,
XED_NONTERMINAL_YMM_N3,
XED_NONTERMINAL_YMM_N3_32,
XED_NONTERMINAL_YMM_N3_64,
XED_NONTERMINAL_YMM_N_32,
XED_NONTERMINAL_YMM_N_64,
XED_NONTERMINAL_YMM_R,
XED_NONTERMINAL_YMM_R3,
XED_NONTERMINAL_YMM_R3_32,
XED_NONTERMINAL_YMM_R3_64,
XED_NONTERMINAL_YMM_R_32,
XED_NONTERMINAL_YMM_R_64,
XED_NONTERMINAL_YMM_SE,
XED_NONTERMINAL_YMM_SE32,
XED_NONTERMINAL_YMM_SE64,
XED_NONTERMINAL_ZMM_B3,
XED_NONTERMINAL_ZMM_B3_32,
XED_NONTERMINAL_ZMM_B3_64,
XED_NONTERMINAL_ZMM_N3,
XED_NONTERMINAL_ZMM_N3_32,
XED_NONTERMINAL_ZMM_N3_64,
XED_NONTERMINAL_ZMM_R3,
XED_NONTERMINAL_ZMM_R3_32,
XED_NONTERMINAL_ZMM_R3_64,
XED_NONTERMINAL_LAST);
/// This converts strings to #xed_reg_enum_t types.
/// @param s A C-string.
/// @return #xed_reg_enum_t
/// @ingroup ENUM
function str2xed_nonterminal_enum_t(s: PAnsiChar): TXED_Nonterminal_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_reg_enum_t types.
/// @param p An enumeration element of type xed_reg_enum_t.
/// @return string
/// @ingroup ENUM
function xed_nonterminal_enum_t2str(const p: TXED_Nonterminal_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_reg_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_nonterminal_enum_t_last:TXED_Nonterminal_Enum;cdecl; external 'xed.dll';
implementation
end.
|
unit FormDataSet6;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, DBClient, DSConnect, ExtCtrls, DBCtrls, StdCtrls,
Mask, MasterForm, DBXCommon, DSClientProxy, DBXDBReaders;
type
TFormDM6 = class(TFormMaster)
DBGrid1: TDBGrid;
CDSCopy: TClientDataSet;
DSCopy: TDataSource;
DBNavigator1: TDBNavigator;
Button1: TButton;
procedure CDSCopyReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure DoInit; override;
procedure DoClose; override;
end;
var
FormDM6: TFormDM6;
implementation
uses DMClient, RecError;
{$R *.dfm}
procedure TFormDM6.Button1Click(Sender: TObject);
var
Reader: TDBXReader;
DepClient: TDMDataSet6Client;
begin
inherited;
DepClient := TDMDataSet6Client.Create
(DMClientContainer.MyDSServer.DBXConnection, False);
try
Reader := DepClient.GetDepartments;
try
if Assigned(Reader) then
TDBXDataSetReader.CopyReaderToClientDataSet(Reader, CDSCopy);
finally
FreeAndNil(Reader);
end;
finally
DepClient.Free;
end;
end;
procedure TFormDM6.CDSCopyReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind; var Action: TReconcileAction);
begin
HandleReconcileError(DataSet, UpdateKind, E);
end;
procedure TFormDM6.DoClose;
begin
end;
procedure TFormDM6.doInit;
begin
end;
end.
|
unit MeshSmoothFaceNormals;
interface
uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector, LOD;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSmoothFaceNormals = class (TMeshProcessingBase)
protected
procedure MeshSmoothFaceNormalsOperation(var _FaceNormals: TAVector3f; const _Vertices: TAVector3f; const _Neighbors : TNeighborDetector);
procedure DoMeshProcessing(var _Mesh: TMesh); override;
public
DistanceFunction: TDistanceFunc;
constructor Create(var _LOD: TLOD); override;
end;
implementation
uses MeshPluginBase, GLConstants, NeighborhoodDataPlugin, MeshBRepGeometry,
Math3d, Math, DistanceFormulas;
constructor TMeshSmoothFaceNormals.Create(var _LOD:TLOD);
begin
inherited Create(_LOD);
DistanceFunction := GetLinearDistance;
end;
procedure TMeshSmoothFaceNormals.DoMeshProcessing(var _Mesh: TMesh);
var
Neighbors : TNeighborDetector;
NeighborhoodPlugin : PMeshPluginBase;
begin
// Setup Neighbors.
NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR);
_Mesh.Geometry.GoToFirstElement;
if (High((_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals) > 0) then
begin
if NeighborhoodPlugin <> nil then
begin
Neighbors := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceNeighbors;
end
else
begin
Neighbors := TNeighborDetector.Create;
Neighbors.NeighborType := C_NEIGHBTYPE_FACE_FACE_FROM_EDGE;
Neighbors.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1);
end;
MeshSmoothFaceNormalsOperation((_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals,_Mesh.Vertices,Neighbors);
// Free memory
if NeighborhoodPlugin = nil then
begin
Neighbors.Free;
end;
_Mesh.ForceRefresh;
end;
end;
procedure TMeshSmoothFaceNormals.MeshSmoothFaceNormalsOperation(var _FaceNormals: TAVector3f; const _Vertices: TAVector3f; const _Neighbors : TNeighborDetector);
var
i,Value : integer;
NormalsHandicap : TAVector3f;
Counter : single;
Distance: single;
begin
// Setup Normals Handicap.
SetLength(NormalsHandicap,High(_FaceNormals)+1);
for i := Low(NormalsHandicap) to High(NormalsHandicap) do
begin
NormalsHandicap[i].X := 0;
NormalsHandicap[i].Y := 0;
NormalsHandicap[i].Z := 0;
end;
// Main loop goes here.
for i := Low(NormalsHandicap) to High(NormalsHandicap) do
begin
Counter := 0;
Value := _Neighbors.GetNeighborFromID(i); // Get face neighbor from face (common edge)
while Value <> -1 do
begin
Distance := _Vertices[Value].X - _Vertices[i].X;
if Distance <> 0 then
NormalsHandicap[i].X := NormalsHandicap[i].X + (_FaceNormals[Value].X * DistanceFunction(Distance));
Distance := _Vertices[Value].Y - _Vertices[i].Y;
if Distance <> 0 then
NormalsHandicap[i].Y := NormalsHandicap[i].Y + (_FaceNormals[Value].Y * DistanceFunction(Distance));
Distance := _Vertices[Value].Z - _Vertices[i].Z;
if Distance <> 0 then
NormalsHandicap[i].Z := NormalsHandicap[i].Z + (_FaceNormals[Value].Z * DistanceFunction(Distance));
Distance := sqrt(Power(_Vertices[Value].X - _Vertices[i].X,2) + Power(_Vertices[Value].Y - _Vertices[i].Y,2) + Power(_Vertices[Value].Z - _Vertices[i].Z,2));
Counter := Counter + Distance;
Value := _Neighbors.GetNextNeighbor;
end;
if Counter > 0 then
begin
_FaceNormals[i].X := _FaceNormals[i].X + (NormalsHandicap[i].X / Counter);
_FaceNormals[i].Y := _FaceNormals[i].Y + (NormalsHandicap[i].Y / Counter);
_FaceNormals[i].Z := _FaceNormals[i].Z + (NormalsHandicap[i].Z / Counter);
Normalize(_FaceNormals[i]);
end;
end;
// Free memory
SetLength(NormalsHandicap,0);
end;
end.
|
unit uRepositorySystemSQLServer;
interface
uses
Dialogs, uDM_RepositorySQLServer, uiRepoSystem, uCustomers, uUsers, uProducts,
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TDM_RepositorySystemSQLServer = class(TDataModule, IRepoSystem)
QryCustomerSQLServer: TFDQuery;
QryUserSQLServer: TFDQuery;
QryProductSQLServer: TFDQuery;
private
{ Private declarations }
public
{ Public declarations }
function ReturnCustomer(id: Integer): TCustomer;
function ReturnProduct(id: Integer): TProducts;
function ReturnUser(id: Integer): TUser;
end;
var
DM_RepositorySystemSQLServer: TDM_RepositorySystemSQLServer;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TDM_RepositorySystemSQLServer }
function TDM_RepositorySystemSQLServer.ReturnCustomer(id: Integer): TCustomer;
begin
Try
QryCustomerSQLServer.Close;
QryCustomerSQLServer.ParamByName('id').Value := id;
QryCustomerSQLServer.Open;
if not QryCustomerSQLServer.IsEmpty then
begin
Result := TCustomer.Create;
Result.id := QryCustomerSQLServer.FieldByName('id_customer').AsInteger;
Result.name := QryCustomerSQLServer.FieldByName('customer_name').AsString;
Result.status := QryCustomerSQLServer.FieldByName('customer_status').AsInteger;
end
else
Result := nil;
Except
On E : Exception do
ShowMessage(E.Message);
End;
end;
function TDM_RepositorySystemSQLServer.ReturnProduct(id: Integer): TProducts;
begin
Try
QryProductSQLServer.Close;
QryProductSQLServer.ParamByName('id').Value := id;
QryProductSQLServer.Open;
if not QryProductSQLServer.IsEmpty then
begin
Result := TProducts.Create;
Result.id := QryProductSQLServer.FieldByName('id_product').AsInteger;
Result.code := QryProductSQLServer.FieldByName('code').AsString;
Result.descr := QryProductSQLServer.FieldByName('descr').AsString;
Result.list_price := QryProductSQLServer.FieldByName('list_price').AsFloat;
Result.tax := QryProductSQLServer.FieldByName('tax').AsFloat;
Result.quantity := QryProductSQLServer.FieldByName('quantity').AsFloat;
end
else
Result := nil;
Except
On E : Exception do
ShowMessage(E.Message);
End;
end;
function TDM_RepositorySystemSQLServer.ReturnUser(id: Integer): TUser;
begin
Try
QryUserSQLServer.Close;
QryUserSQLServer.ParamByName('id').Value := id;
QryUserSQLServer.Open;
if not QryUserSQLServer.IsEmpty then
begin
Result := TUser.Create;
Result.id := QryUserSQLServer.FieldByName('id_user').AsInteger;
Result.login := QryUserSQLServer.FieldByName('login').AsString;
Result.password := QryUserSQLServer.FieldByName('password').AsString;
end
else
Result := nil;
Except
On E : Exception do
ShowMessage(E.Message);
End;
end;
end.
|
unit CatResMin;
{
Minimal version of CatRes.pas with most used functions only
Copyright (c) 2003-2019 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
GetResourceAsPointer is based on an example from the Pascal Newsletter #25
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, System.SysUtils;
{$ELSE}
Windows, SysUtils;
{$ENDIF}
function GetResourceAsPointer(const ResName: string;
out Size: longword): pointer;
function GetResourceAsString(const ResName: string): string;
implementation
{$IFDEF UNICODE}
function StrToResType(const s: string): PWideChar;
begin
result := PWideChar(s);
end;
{$ELSE}
function StrToResType(const s: string): PAnsiChar;
begin
result := PAnsiChar(AnsiString(s));
end;
{$ENDIF}
function GetResourceAsPointer(const ResName: string;
out Size: longword): pointer;
var
ib: HRSRC; // InfoBlock
gmb: HGLOBAL; // GlobalMemoryBlock
begin
ib := FindResource(hInstance, StrToResType(ResName), RT_RCDATA);
if ib = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
Size := SizeofResource(hInstance, ib);
if Size = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
gmb := LoadResource(hInstance, ib);
if gmb = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
result := LockResource(gmb);
if result = nil then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
// Example: Memo1.Lines.Text := GetResourceAsString('sample_txt');
function GetResourceAsString(const ResName: string): string;
var
rd: PAnsiChar;
sz: longword;
begin
rd := GetResourceAsPointer(ResName, sz);
SetString(result, rd, sz);
end;
//------------------------------------------------------------------------//
end. |
unit nfsButtonPosBerechnung;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Winapi.CommCtrl, Vcl.ImgList, vcl.Graphics,
Vcl.StdCtrls, System.Types, Winapi.Messages, nfsPropPos, System.UITypes, Vcl.comStrs,
Vcl.Consts, Vcl.ToolWin, Vcl.ListActns, Vcl.StdActns, Vcl.Forms, Contnrs;
type
TFlaeche = class
private
fHoehe: Integer;
fBreite: Integer;
public
property Hoehe: Integer read fHoehe write fHoehe;
property Breite: Integer read fBreite write fBreite;
constructor Create;
destructor Destroy; Override;
procedure Init;
end;
type
TnfsButtonPosBerechnung = class
private
fBMP: TFlaeche;
fCaption: string;
fGlyphIsDrawing: Boolean;
fZeichenFlaeche: TFlaeche;
fShowCaption: Boolean;
fCanvas: TCanvas;
fShowAccelChar: Boolean;
fImageMargin: TMargins;
fImageLeft: Boolean;
fImageRight: Boolean;
public
BMPPos: TPoint;
CaptionPos: TPoint;
property ZeichenFlaeche: TFlaeche read fZeichenFlaeche write fZeichenFlaeche;
property BMP: TFlaeche read fBMP write fBMP;
property Caption: string read fCaption write fCaption;
property GlyphIsDrawing: Boolean read fGlyphIsDrawing write fGlyphIsDrawing;
property ShowCaption: Boolean read fShowCaption write fShowCaption;
property Canvas: TCanvas read fCanvas write fCanvas;
property ShowAccelChar: Boolean read fShowAccelChar write fShowAccelChar;
property ImageMargin: TMargins read fImageMargin write fImageMargin;
property ImageLeft: Boolean read fImageLeft write fImageLeft;
property ImageRight: Boolean read fImageRight write fImageRight;
procedure Berechne;
constructor Create;
destructor Destroy; Override;
end;
implementation
{ TFlaeche }
constructor TFlaeche.Create;
begin
Init;
end;
destructor TFlaeche.Destroy;
begin
inherited;
end;
procedure TFlaeche.Init;
begin
fHoehe := 0;
fBreite := 0;
end;
{ TnfsButtonPosBerechnung }
constructor TnfsButtonPosBerechnung.Create;
begin
fCanvas := nil;
fImageMargin := TMargins.Create(nil);
fZeichenFlaeche := TFlaeche.Create;
fBMP := TFlaeche.Create;
fImageLeft := true;
fImageRight := false;
end;
destructor TnfsButtonPosBerechnung.Destroy;
begin
inherited;
FreeAndNil(fImageMargin);
FreeAndNil(fZeichenFlaeche);
FreeAndNil(fBMP);
end;
procedure TnfsButtonPosBerechnung.Berechne;
var
TextMass: TFlaeche;
ZeichenflaecheMitte: TFlaeche;
Ausgabe: TFlaeche;
CaptionText: string;
BmpMass: TFlaeche;
begin
BMPPos.X := 0;
BMPPos.Y := 0;
CaptionPos.X := 0;
CaptionPos.Y := 0;
if fCanvas = nil then
exit;
TextMass := TFlaeche.Create;
ZeichenflaecheMitte := TFlaeche.Create;
Ausgabe := TFlaeche.Create;
BmpMass := TFlaeche.Create;
try
CaptionText := '';
if (fShowCaption) and (Trim(fCaption) > '') then
begin
CaptionText := Trim(fCaption);
if (fShowAccelChar) and (Length(CaptionText) > 1) and (CaptionText[1]='&') then
CaptionText := Trim(copy(CaptionText, 2, Length(CaptionText)));
end;
if CaptionText > '' then
begin
TextMass.Hoehe := canvas.TextHeight(CaptionText);
TextMass.Breite := canvas.TextWidth(CaptionText);
end;
if (fGlyphIsDrawing) then
begin
BmpMass.Hoehe := fbmp.Hoehe;
BmpMass.Breite := fBmp.Breite;
end;
Ausgabe.Breite := BmpMass.Breite + fImageMargin.Right + TextMass.Breite;
ZeichenflaecheMitte.Hoehe := trunc(ZeichenFlaeche.Hoehe / 2);
ZeichenflaecheMitte.Breite := trunc(ZeichenFlaeche.Breite / 2);
BMPPos.X := ZeichenflaecheMitte.Breite - trunc(Ausgabe.Breite / 2);
BMPPos.Y := ZeichenflaecheMitte.Hoehe - trunc(BMPMass.Hoehe / 2);
CaptionPos.X := BMPPos.X + BmpMass.Breite + fImageMargin.Right;
CaptionPos.Y := ZeichenflaecheMitte.Hoehe - trunc((TextMass.Hoehe / 2)+0.5);
if fImageRight then
begin
CaptionPos.X := ZeichenflaecheMitte.Breite - trunc(Ausgabe.Breite / 2);
BMPPos.X := CaptionPos.X + TextMass.Breite + fImageMargin.Left;
end;
finally
FreeAndNil(TextMass);
FreeAndNil(ZeichenflaecheMitte);
FreeAndNil(BmpMass);
FreeAndNil(Ausgabe);
end;
end;
end.
|
unit ThdTimer;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses
Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs;
type
TThreadedTimer = class;
TTimerThread = class(TThread)
OwnerTimer: TThreadedTimer;
Interval: DWord;
FirstInterval:Dword;
first:boolean;
procedure Execute; override;
procedure DoTimer;
end;
TThreadedTimer = class(TComponent)
private
FEnabled: Boolean;
FInterval,FFirstInterval: DWord;
FOnTimer: TNotifyEvent;
FTimerThread: TTimerThread;
FThreadPriority: TThreadPriority;
protected
procedure UpdateTimer;
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: DWord);
procedure SetFirstInterval(Value: DWord);
procedure SetOnTimer(Value: TNotifyEvent);
procedure SetThreadPriority(Value: TThreadPriority);
procedure Timer; dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Reset;
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Interval: DWord read FInterval write SetInterval default 1000;
property FirstInterval: DWord read FFirstInterval write SetFirstInterval default 1000;
property OnTimer: TNotifyEvent read FOnTimer write SetOnTimer;
property ThreadPriority: TThreadPriority read FThreadPriority
write SetThreadPriority;
end;
procedure Register;
implementation
procedure TTimerThread.Execute;
begin
repeat
if first then
begin
SleepEx(FirstInterval, False);
first:=false;
end
else SleepEx(Interval, False);
DoTimer;
until Terminated;
end;
procedure TTimerThread.DoTimer;
begin
OwnerTimer.Timer;
end;
constructor TThreadedTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := True;
FInterval := 1000;
FfirstInterval := 1000;
FThreadPriority := tpNormal;
FTimerThread := TTimerThread.Create(False);
FTimerThread.OwnerTimer := Self;
FTimerThread.Interval := FInterval;
FTimerThread.FirstInterval := FfirstInterval;
FTimerThread.first:=true;
FTimerThread.Priority := FThreadPriority;
end;
destructor TThreadedTimer.Destroy;
begin
FEnabled := False;
UpdateTimer;
FTimerThread.Free;
inherited Destroy;
end;
procedure TThreadedTimer.UpdateTimer;
begin
if FTimerThread.Suspended = False then
FTimerThread.Suspend;
if (FInterval <> 0) and FEnabled and Assigned(FOnTimer) then
FTimerThread.Resume;
end;
procedure TThreadedTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
UpdateTimer;
end;
end;
procedure TThreadedTimer.SetInterval(Value: DWord);
begin
if Value <> FInterval then
begin
FInterval := Value;
FTimerThread.Interval := FInterval;
UpdateTimer;
end;
end;
procedure TThreadedTimer.SetFirstInterval(Value: DWord);
begin
if Value <> FirstInterval then
begin
FFirstInterval := Value;
FTimerThread.FirstInterval := FFirstInterval;
UpdateTimer;
end;
end;
procedure TThreadedTimer.SetOnTimer(Value: TNotifyEvent);
begin
FOnTimer := Value;
UpdateTimer;
end;
procedure TThreadedTimer.SetThreadPriority(Value: TThreadPriority);
begin
if Value <> FThreadPriority then
begin
FThreadPriority := Value;
FTimerThread.Priority := Value;
UpdateTimer;
end;
end;
procedure TThreadedTimer.Timer;
begin
if Assigned(FOnTimer) then
FOnTimer(Self);
end;
procedure TThreadedTimer.Reset;
begin
FTimerThread.Free;
FTimerThread := TTimerThread.Create(False);
FTimerThread.OwnerTimer := Self;
FTimerThread.Priority := FThreadPriority;
UpdateTimer;
end;
procedure Register;
begin
RegisterComponents('System', [TThreadedTimer]);
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit MV.TgaBitmap;
{$POINTERMATH ON}
interface
uses
System.SysUtils, System.Classes, FMX.Types;
type
TTgaBitmap = class(TBitmap)
private
procedure LoadTargaFile(const AFileName: String);
public
constructor CreateFromFile(const AFileName: String); override;
end;
implementation
type
TTargaHeader = packed record
IDLength : UInt8;
ColorMapType : UInt8;
ImageType : UInt8;
ColorMapOff : UInt16;
ColorMapLength: UInt16;
ColorEntrySize: UInt8;
XOrg : Int16;
YOrg : Int16;
Width : Int16;
Height : Int16;
PixelSize : UInt8;
Desc : UInt8;
end;
{ TTgaBitmap }
constructor TTgaBitmap.CreateFromFile(const AFileName: String);
begin
if SameText(ExtractFileExt(AFileName), '.TGA') then
begin
Create(0, 0);
LoadTargaFile(AFileName);
end
else
raise EFilerError.Create('Unsupported targa file format.');
end;
procedure TTgaBitmap.LoadTargaFile(const AFileName: String);
var
f: TFileStream;
LHeader: TTargaHeader;
LBuffer, LSource, LDest: ^Int32;
LSize, i, j: Integer;
begin
try
f := TFileStream.Create(AFileName, fmOpenRead);
f.ReadBuffer(LHeader, SizeOf(LHeader));
f.Seek(LHeader.IDLength, soFromCurrent);
// only supported uncompressed ARGB
if (LHeader.ImageType <> 2) or (LHeader.PixelSize <> 32) then
raise EFilerError.Create('Unsupported targa file format.');
LSize := LHeader.Width * LHeader.Height * 4;
SetSize(LHeader.Width, LHeader.Height);
GetMem(LBuffer, LSize);
f.ReadBuffer(LBuffer^, LSize);
LDest := Pointer(StartLine);
for i := LHeader.Height - 1 downto 0 do
begin
LSource := @LBuffer[(i * (LHeader.Width))];
Move(LSource^, LDest^, LHeader.Width * 4);
Inc(LDest, LHeader.Width);
end;
FreeMem(LBuffer);
finally
f.Free;
end;
end;
end.
|
unit PaiDeFichas;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, DB, DBTables, DbCtrls, DateBox, FormConfig, Mask, Buttons,
dbGrids, uSystemTypes, ADODB, RCADOQuery, PowerADOQuery, Variants, siComp,
siLangRT;
type
TOnValidadeFieldEvent = function(Sender: TObject): boolean of object;
type
TFrmPaiDeFch = class(TForm)
dsForm: TDataSource;
quForm: TPowerADOQuery;
FormConfig: TFormConfig;
Panel5: TPanel;
lblUserName: TLabel;
Panel6: TPanel;
Panel7: TPanel;
Panel8: TPanel;
sbHelp: TSpeedButton;
btCancel: TButton;
btClose: TButton;
siLang: TsiLangRT;
procedure dsFormStateChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure quFormPostError(DataSet: TDataSet; E: EDatabaseError;
var Action: TDataAction);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure quFormAfterOpen(DataSet: TDataSet);
private
{ Private declarations }
//Translation
IsPost: Boolean;
bAnyPost: Boolean;
sCloseButton,
sCancelButton,
sSaveButton,
sFields,
sCannot : String;
fldSystem : TBooleanField;
MaxLastKey : integer;
NotNullFields : TStringList;
function SaveHighChange : Boolean;
procedure ClearParam;
procedure SyncFichaToBrowse;
protected
{ protected }
FieldKey1, FieldKey2 : String;
frmCommand : TBtnCommandType;
MybrwQuery : TPowerADOQuery;
FOnValidadeFieldEvent: TOnValidadeFieldEvent;
fLangLoaded : Boolean;
procedure PushError(ErrorType: Integer; sError: String);
function TestFieldFill: boolean;
function OnValidadeField: boolean; virtual;
function SaveChange: boolean; virtual;
function DoPost: boolean; virtual;
function BeforeChange: boolean; virtual;
function TestOnEditModes: boolean; virtual;
procedure NextAppend; virtual;
procedure CancelUpdates; virtual;
function OnAfterSaveChange(var iError:Integer):Boolean; virtual;
procedure DoCancel(DeleteOnInc : Boolean);
procedure OnAfterDoCancel; virtual;
procedure OnBeforePrepare;
procedure OnAfterCommit; virtual;
procedure OnAfterRollBack; virtual;
procedure OnBeforeStart; virtual;
procedure OnBeforeShow; virtual;
procedure OnAfterStart; virtual;
public
{ Public declarations }
FchBrowse : TObject; // Aponta para o browse da ficha
sParam : string;
function Start(pCommand : TBtnCommandType;
brwQuery : TPowerADOQuery;
IsLoopInc : Boolean;
var PosID1, PosID2 : String) : Boolean;
published
property OnValidateFields: TOnValidadeFieldEvent read FOnValidadeFieldEvent write FOnValidadeFieldEvent;
end;
implementation
{$R *.DFM}
uses xBase, uDM, uMsgBox, SuperComboADO, uParamFunctions,
uSqlFunctions, uMsgConstant, uVarianteFunctions, uDataBaseFunctions,
uHandleError, uDMGlobal;
procedure TFrmPaiDeFch.SyncFichaToBrowse;
var
i : Integer;
begin
quForm.Close;
if not MybrwQuery.IsEmpty then
with quForm do
if not (MybrwQuery.Eof and MybrwQuery.Bof) then
for i := 0 to Parameters.Count-1 do
Parameters[i].Value := MybrwQuery.FieldByName(Parameters[i].Name).Value;
quForm.Open;
end;
procedure TFrmPaiDeFch.PushError(ErrorType: Integer; sError: String);
begin
DM.SetError(ErrorType, Self.Name, sError);
end;
function TFrmPaiDeFch.Start(pCommand : TBtnCommandType;
brwQuery : TPowerADOQuery;
IsLoopInc : Boolean;
var PosID1, PosID2 : String) : Boolean;
begin
inherited;
Screen.Cursor := crHourGlass;
// Seta variáveis globais
frmCommand := pCommand;
IsPost := False;
bAnyPost := False;
MybrwQuery := brwQuery;
OnBeforeStart;
// Seta os FilterFields
if brwQuery <> nil then
if (frmCommand = btInc) and (brwQuery is TPowerADOQuery) then
with quForm do
begin
FilterFields.Assign(TPowerADOQuery(brwQuery).FilterFields);
FilterValues.Assign(TPowerADOQuery(brwQuery).FilterValues);
end;
// Seta o filtro do registro a ser mostrado
if frmCommand = btAlt then
with quForm do
begin
Close;
if (brwQuery <> nil) then
begin
SyncFichaToBrowse;
end
else
if PosID1 <> '' then
begin
Parameters.Items[0].Value := ConvVariant(Parameters.Items[0].DataType, PosID1);
if PosID2 <> '' then
Parameters.Items[1].Value := ConvVariant(Parameters.Items[1].DataType, PosID2);
Open;
end;
end
else
begin
ClearParam;
end;
Screen.Cursor := crDefault;
OnBeforeShow;
ShowModal;
with quForm do
if Active then Close;
if IsPost then
begin
PosID1 := FieldKey1;
PosID2 := FieldKey2;
end;
OnAfterStart;
Result := bAnyPost;
end;
procedure TFrmPaiDeFch.OnBeforeStart;
begin
// Para se herdado
end;
procedure TFrmPaiDeFch.OnAfterStart;
begin
// Para se herdado
end;
procedure TFrmPaiDeFch.OnBeforeShow;
begin
// Para se herdado
end;
procedure TFrmPaiDeFch.dsFormStateChange(Sender: TObject);
begin
inherited;
if TestOnEditModes then
begin
btCancel.Font.Style := [fsBold];
btCancel.Caption := sCancelButton;
end;
end;
procedure TFrmPaiDeFch.FormShow(Sender: TObject);
begin
inherited;
case frmCommand of
btInc : begin
NextAppend;
end;
btAlt : begin
end;
end;
btClose.Caption := sSaveButton;
Screen.Cursor := crDefault;
end;
procedure TFrmPaiDeFch.NextAppend;
var
i : integer;
slRequired: TStringList;
procedure UnMarkRequiredFields;
var
i: integer;
begin
// Desmarco todos os fields que estao required, para marcar de novo,
// depois do post
slRequired := TStringList.Create;
with quForm do
for i := 0 to FieldCount-1 do
begin
if Fields[i].Required then
begin
slRequired.Add(Fields[i].FieldName);
Fields[i].Required := False;
end;
end;
end;
procedure MarkRequiredFields;
var
i: integer;
begin
// Volto a marcar os campos como required
with slRequired do
for i := 0 to Count-1 do
quForm.FieldByName(slRequired[i]).Required := True;
slRequired.Free;
end;
begin
// Faz o post automatico
if not quForm.Active then
quForm.Open; // ** Ivanil
try
quForm.Append;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.NextAppend.quForm.Append.Exception' + #13#10 + E.Message);
Exit;
end;
end;
if FormConfig.IsAutoIncKey and FormConfig.PostOnInsert then
begin
NotNullFields.Clear;
UnMarkRequiredFields;
with quForm do
begin
MaxLastKey := DM.GetNextID(GetSQLFirstTableName(quForm.CommandText)+'.'+Parameters.Items[0].Name);
quForm.FieldbyName(quForm.Parameters.Items[0].Name).AsInteger := MaxLastKey;
for i := 0 to FormConfig.RequiredFields.Count - 1 do
begin
if FieldByName(FormConfig.RequiredFields.Strings[i]).IsNull then
case FieldByName(FormConfig.RequiredFields.Strings[i]).DataType of
ftString,
ftMemo : FieldByName(FormConfig.RequiredFields.Strings[i]).AsString := IntToStr(MaxLastKey);
ftDateTime,
ftDate : FieldByName(FormConfig.RequiredFields.Strings[i]).AsDateTime := Now;
ftInteger : FieldByName(FormConfig.RequiredFields.Strings[i]).AsInteger := 0;
ftFloat : FieldByName(FormConfig.RequiredFields.Strings[i]).AsFloat := 0;
ftBoolean : FieldByName(FormConfig.RequiredFields.Strings[i]).AsBoolean := False;
end
else
begin
NotNullFields.Add(FormConfig.RequiredFields.Strings[i]);
end;
end;
try
// Inicia uma transação no Servidor
DM.ADODBConnect.BeginTrans;
//quForm.UpdateBatch;
quForm.Post;
// Marca a gravacao
FieldKey1 := IntToStr(MaxLastKey);
IsPost := True;
// Confirma as alterações para o servidor
DM.ADODBConnect.CommitTrans;
except
on E: Exception do
begin
// Cancela as alterações feitas
DM.ADODBConnect.RollbackTrans;
PushError(CRITICAL_ERROR, 'ParentFch.NextAppend.GetLastKey.Exception' + #13#10 + E.Message);
Exit;
end;
end;
Close;
Parameters.Items[0].Value := MaxLastKey;
Try
Open;
Edit;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.NextAppend.quForm.Open.Exception' + #13#10 + E.Message);
Exit;
end;
end;
MarkRequiredFields;
// Reseta os campos que sao required
if FormConfig.RequiredFields.Count > 0 then
begin
for i := 0 to FormConfig.RequiredFields.Count - 1 do
if NotNullFields.IndexOf(FormConfig.RequiredFields.Strings[i]) = -1 then
FieldByName(FormConfig.RequiredFields.Strings[i]).Clear;
end;
end;
end;
end;
procedure TFrmPaiDeFch.btCloseClick(Sender: TObject);
begin
inherited;
ModalResult := mrNone;
with quForm do
if TestOnEditModes then
begin
if quForm.State in dsEditModes then
quForm.UpdateRecord; // Force pending updates
if not (OnValidadeField and TestFieldFill) then
Exit;
if not BeforeChange then
Exit;
// Testa se deve confirmar a alteracao
if (not FormConfig.ConfirmPost) or
(MsgBox(MSG_QST_CONFIRM, vbYesNo + vbQuestion) = vbYes) then
begin
if not SaveHighChange then
Exit;
// Deixa a inclusão dar o refresh
IsPost := True;
bAnyPost := True;
end
else
begin
Screen.Cursor := crdefault;
Exit; // Caso cancele a operação
end;
end;
if (frmCommand <> btInc) then
ModalResult := mrOK
else
//if btLoopInc.Down then
// NextAppend
//else
ModalResult := mrOK;
end;
function TFrmPaiDeFch.SaveHighChange: Boolean;
var
iSPError : integer;
begin
with DM.ADODBConnect do
begin
try
// Abre uma transction no serve
BeginTrans;
Result := SaveChange;
if Result = True then
Result := OnAfterSaveChange(iSPError);
Finally
if Result then
begin
CommitTrans;
Try
OnAfterCommit;
Except
on E : Exception do
PushError(CRITICAL_ERROR, 'ParentFch.OnAfterCommit.Exception' + #13#10 + E.Message);
end;
end
else
begin
RollbackTrans;
OnAfterRollBack;
PushError(CRITICAL_ERROR, 'ParentFch.SaveChange.Exception' + #13#10 + 'Result False');
ShowMessage('Stored Proc error:'+ IntToStr(iSPError));
end;
end;
end;
end;
function TFrmPaiDeFch.BeforeChange : boolean;
begin
// funcao para ser herdada
Result := True;
end;
function TFrmPaiDeFch.TestOnEditModes : boolean;
begin
Result := quForm.State in dsEditModes;
end;
function TFrmPaiDeFch.DoPost: boolean;
begin
try
if quForm.State in dsEditModes then
quForm.Post;
Result := True;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.FormPost.quFormPost.Exception' + #13#10 + E.Message);
Result := False;
end;
end;
end;
function TFrmPaiDeFch.SaveChange : boolean;
begin
// Se necessário pego o próximo ID
if (frmCommand = btInc) and (FormConfig.AutoIncField <> '') then
begin
try
if quForm.FieldByName(FormConfig.AutoIncField).AsString = '' then
quForm.FieldByName(FormConfig.AutoIncField).Value :=
DM.GetNextID(UpperCase(GetSQLFirstTableName(quForm.CommandText) + '.' + FormConfig.AutoIncField));
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.SaveChange.AutoGenCode.Exception' + #13#10 + E.Message);
Exit;
end;
end;
end;
//Da o Post
if not DoPost then
Exit;
Try
// Salva os valores da chave para identity
if (frmCommand = btInc) then
begin
// Inclusao
if FormConfig.IsAutoIncKey then
begin
if FormConfig.PostOnInsert then
FieldKey1 := quForm.Parameters.Items[0].Value
else
//FieldKey1 := IntToStr(DM.GetlastKey);
FieldKey1 := quForm.FieldByName(FormConfig.AutoIncField).Value;
end
else
begin
// Salva os valores da chave para nao identity
FieldKey1 := quForm.FieldByName(quForm.Parameters.Items[0].Name).AsString;
if quForm.Parameters.Count > 1 then
FieldKey2 := quForm.FieldByName(quForm.Parameters.Items[1].Name).AsString;
end;
end
else
begin
// Alteracao
FieldKey1 := quForm.Parameters.Items[0].Value;
if quForm.Parameters.Count > 1 then
FieldKey2 := quForm.Parameters.Items[1].Value;
end;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.FormPost.GetChave.Exception' + #13#10 + E.Message);
Exit;
end;
end;
Result := True;
end;
procedure TFrmPaiDeFch.btCancelClick(Sender: TObject);
begin
inherited;
ModalResult := mrCancel;
end;
procedure TFrmPaiDeFch.FormCreate(Sender: TObject);
var
MySqlStatement : TSQlStatement;
//MyDateType : Array [1..5] of TDataType;
i : integer;
IsSystem : Boolean;
begin
fLangLoaded := (DMGlobal.IDLanguage = LANG_ENGLISH);
//Load Translation
if (not fLangLoaded) and (siLang.StorageFile <> '') then
begin
if FileExists(DMGlobal.LangFilesPath + siLang.StorageFile) then
siLang.LoadAllFromFile(DMGlobal.LangFilesPath + siLang.StorageFile, True)
else
MsgBox(MSG_INF_DICTIONARI_NOT_FOUND ,vbOKOnly + vbInformation);
fLangLoaded := True;
end;
bAnyPost := False;
OnBeforePrepare;
// ** herda a procedure FormCreate do Pai (frmParent)
inherited;
// ** instancia estes objetos
NotNullFields := TStringList.Create;
//MyquFormParams := TParameters.Create(nil, nil);
if FormConfig.SystemReadOnly then
begin
with quForm do
begin
// testa se ja exite campo system
IsSystem := False;
i := 0;
while (i < FieldCount) and (not IsSystem) do
begin
IsSystem := ('SYSTEM' = Trim(UpperCase(Fields[i].FieldName)));
Inc(i);
end;
if not IsSystem then
begin
// Salva os parametros do quForm
//MyquFormParams.Assign(Parameters);
//for i := 0 to Parameters.Count - 1 do
//MyDateType[i] := Parameters.Items[i].DataType;
// Muda a string SQL para incluir o campo desativado
MySqlStatement := UnMountSQL(CommandText);
MySqlStatement[ST_SELECT] := MySqlStatement[ST_SELECT] + ' , ' +
GetSQLFirstTableAlias(CommandText) + '.' +
'SYSTEM';
CommandText := MountSQL(MySqlStatement);
// crio o novo field
fldSystem := TBooleanField.Create(Self);
fldSystem.FieldName := 'SYSTEM';
fldSystem.Name := 'PaideFichasrt' + fldSystem.FieldName;
fldSystem.Index := FieldCount;
fldSystem.DataSet := quForm;
FieldDefs.UpDate;
// Restaura os tipos dos paramteros do browse
//for i := 0 to Parameters.Count - 1 do
//Parameters.Items[i].DataType := MyquFormParams.Items[i].DataType;
//for i := 0 to Parameters.Count - 1 do
//Parameters.Items[i].DataType := MyDateType[i];
end;
end;
end;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sCloseButton := 'Close';
sCancelButton := 'Cancel';
sSaveButton := 'Save';
sFields := 'Field [';
sCannot := '] can not be empty !';
end;
LANG_PORTUGUESE :
begin
sCloseButton := 'Fechar';
sCancelButton := 'Cancelar';
sSaveButton := 'Salvar';
sFields := 'Campos [';
sCannot := '] não podem ser nulos !';
end;
LANG_SPANISH :
begin
sCloseButton := 'Cerrar';
sCancelButton := 'Cancelar';
sSaveButton := 'Guardar';
sFields := 'Campos [';
sCannot := '] no pueden estar vacios !';
end;
end;
end;
procedure TFrmPaiDeFch.FormDestroy(Sender: TObject);
begin
inherited;
// ** Destrói estes componentes
//MyquFormParams.Free;
NotNullFields.Free;
with quForm do
begin
if Active then
Close;
//UnPrepare;
end;
end;
procedure TFrmPaiDeFch.quFormPostError(DataSet: TDataSet;
E: EDatabaseError; var Action: TDataAction);
function SetFieldFocus(strField : String) : String;
begin
{ Seta o foco para o campo com erro }
try
DataSet.FieldByName(strField).FocusControl;
Result := DataSet.FieldByName(strField).DisplayName;
except
on exception do
raise exception.create('The index ' + strField + ' is not compatibel with the field.');
end;
end;
{ Funcao principal }
var
strField, RetMessage : String;
begin
inherited;
strField := HandleDataBaseError(E.Message, RetMessage);
if strField <> '' then
begin
Action := daAbort; { erros conhecidos }
MsgBox(SetFieldFocus(strField) + ' ' + RetMessage,
vbOKOnly + vbInformation);
end
else
{ erro desconhecido }
Action := daFail;
end;
procedure TFrmPaiDeFch.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
DoCancel((ModalResult = mrCancel));
end;
procedure TFrmPaiDeFch.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
CanClose := True;
if (frmCommand <> btInc) and TestOnEditModes then
begin
if (not FormConfig.ConfirmCancel) or
(MsgBox(MSG_QST_UNSAVE_CHANGES, vbYesNo + vbQuestion) = vbYes) then
begin
CanClose := True;
CancelUpdates;
end
else
CanClose := False;
end;
end;
procedure TFrmPaiDeFch.DoCancel(DeleteOnInc : Boolean);
var
i : integer;
sValue : String;
begin
Try
if quForm.State in dsEditModes then
quForm.Cancel;
except
on E: Exception do
begin
PushError(CRITICAL_ERROR, 'ParentFch.DoCancel.CancelUpdates.Exception' + #13#10 + E.Message);
end;
end;
// Deleta o incluido e que nao foi aceito
if (frmCommand = btInc) and DeleteOnInc and
(FormConfig.IsAutoIncKey) and (FormConfig.PostOnInsert) then
begin
try
DM.ADODBConnect.BeginTrans;
for i := 0 to FormConfig.DependentTables.Count -1 do
with DM.quFreeSQL do
begin
if Active then
Close;
sValue := quForm.Parameters.Items[0].Value;
SQl.Text := 'DELETE FROM ' + FormConfig.DependentTables.Strings[i] +
' WHERE ' + FormConfig.DependentTableKeys.Strings[i] + ' = ' + sValue;
ExecSQL;
end;
quForm.Delete;
DM.ADODBConnect.CommitTrans;
except
on E: Exception do
begin
DM.ADODBConnect.RollbackTrans;
PushError(CRITICAL_ERROR, 'ParentFch.DoCancel.DependentTables.Exception' + #13#10 + E.Message);
end;
end;
end;
OnAfterDoCancel;
end;
procedure TFrmPaiDeFch.CancelUpdates;
begin
quForm.Cancel;
end;
function TFrmPaiDeFch.OnAfterSaveChange(var iError:Integer):Boolean;
begin
// Somente para ser herdado
Result := True;
end;
procedure TFrmPaiDeFch.OnBeforePrepare;
begin
// Somente para ser herdado
end;
function TFrmPaiDeFch.OnValidadeField: boolean;
begin
// Somente para ser herdado
Result := True;
end;
procedure TFrmPaiDeFch.OnAfterCommit;
begin
// Somente para ser herdado
end;
procedure TFrmPaiDeFch.OnAfterRollBack;
begin
// Somente para ser herdado
end;
procedure TFrmPaiDeFch.OnAfterDoCancel;
begin
// Somente para ser herdado
end;
function TFrmPaiDeFch.TestFieldFill: boolean;
var
i: integer;
Msg1, Msg2: String;
begin
Result := True;
Msg2 := '';
with quForm do
if State in dsEditModes then
UpdateRecord;
with quForm do
for i := 0 to FieldCount-1 do
begin
if Fields[i].Required and (Fields[i].AsString = '') and Result then
begin
Result := False;
Msg1 := sFields + Fields[i].DisplayLabel + sCannot;
Fields[i].FocusControl;
end;
if Fields[i].Required and (Fields[i].AsString = '') then
begin
if Msg2 <> '' then
Msg2 := Msg2 + ', ';
Msg2 := Msg2 + Fields[i].DisplayLabel;
end;
end;
if not Result then
begin
MsgBox( Msg1 + MSG_CRT_PART_FIELDS_NO_EMPTY + Msg2,
vbCritical + vbOkOnly);
end;
end;
procedure TFrmPaiDeFch.ClearParam;
var
i: integer;
begin
with quForm do
begin
for i := 0 to ParamCount-1 do
Parameters.Items[i].Value := Null;
end;
end;
procedure TFrmPaiDeFch.quFormAfterOpen(DataSet: TDataSet);
begin
inherited;
btCancel.Caption := sCloseButton;
btCancel.Font.Style := [];
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.Compiler.Factory;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Compiler.Interfaces;
type
TCompilerFactory = class(TInterfacedObject, ICompilerFactory)
private
FLogger : ILogger;
FEnv : ICompilerEnvironmentProvider;
protected
function CreateCompiler(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : ICompiler;
public
constructor Create(const logger : ILogger; const env : ICompilerEnvironmentProvider);
end;
implementation
uses
DPM.Core.Compiler.MSBuild;
{ TCompilerFactory }
constructor TCompilerFactory.Create(const logger : ILogger; const env : ICompilerEnvironmentProvider);
begin
FLogger := logger;
FEnv := env;
end;
function TCompilerFactory.CreateCompiler(const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : ICompiler;
begin
//if we have different compiler implementations then work that out here.
result := TMSBuildCompiler.Create(FLogger, compilerVersion, platform, FEnv);
end;
end.
|
unit ExtSlider;
// Generated by ExtToPascal v.0.9.8, at 3/5/2010 11:59:34
// from "C:\Trabalho\ext\docs\output" detected as ExtJS v.3
interface
uses
StrUtils, ExtPascal, ExtPascalUtils, Ext;
type
TExtSliderThumb = class;
TExtSliderMultiSlider = class;
TExtSliderSingleSlider = class;
TExtSliderTip = class;
TExtSliderThumb = class(TExtFunction)
private
FConstrain : Boolean;
FSlider : TExtSliderMultiSlider;
FSlider_ : TExtSliderMultiSlider;
procedure SetFConstrain(Value : Boolean);
procedure SetFSlider(Value : TExtSliderMultiSlider);
procedure SetFSlider_(Value : TExtSliderMultiSlider);
protected
procedure InitDefaults; override;
public
function JSClassName : string; override;
function Disable : TExtFunction;
function Enable : TExtFunction;
function InitEvents : TExtFunction;
function Render : TExtFunction;
property Constrain : Boolean read FConstrain write SetFConstrain;
property Slider : TExtSliderMultiSlider read FSlider write SetFSlider;
property Slider_ : TExtSliderMultiSlider read FSlider_ write SetFSlider_;
end;
// Procedural types for events TExtSliderMultiSlider
TExtSliderMultiSliderOnBeforechange = procedure(Slider : TExtSlider; NewValue : Integer; OldValue : Integer) of object;
TExtSliderMultiSliderOnChange = procedure(Slider : TExtSlider; NewValue : Integer; Thumb : TExtSliderThumb) of object;
TExtSliderMultiSliderOnChangecomplete = procedure(Slider : TExtSlider; NewValue : Integer; Thumb : TExtSliderThumb) of object;
TExtSliderMultiSliderOnDrag = procedure(Slider : TExtSlider; E : TExtEventObjectSingleton) of object;
TExtSliderMultiSliderOnDragend = procedure(Slider : TExtSlider; E : TExtEventObjectSingleton) of object;
TExtSliderMultiSliderOnDragstart = procedure(Slider : TExtSlider; E : TExtEventObjectSingleton) of object;
TExtSliderMultiSlider = class(TExtBoxComponent)
private
FAnimate : Boolean;
FClickToChange : Boolean;
FConstrainThumbs : Boolean;
FDecimalPrecision : Integer;
FDecimalPrecisionBoolean : Boolean;
FIncrement : Integer;
FKeyIncrement : Integer;
FMaxValue : Integer;
FMinValue : Integer;
FValue : Integer;
FVertical : Boolean;
FDragging : Boolean;
FThumbs : TExtObjectList;
FValues : TExtObjectList;
FOnBeforechange : TExtSliderMultiSliderOnBeforechange;
FOnChange : TExtSliderMultiSliderOnChange;
FOnChangecomplete : TExtSliderMultiSliderOnChangecomplete;
FOnDrag : TExtSliderMultiSliderOnDrag;
FOnDragend : TExtSliderMultiSliderOnDragend;
FOnDragstart : TExtSliderMultiSliderOnDragstart;
procedure SetFAnimate(Value : Boolean);
procedure SetFClickToChange(Value : Boolean);
procedure SetFConstrainThumbs(Value : Boolean);
procedure SetFDecimalPrecision(Value : Integer);
procedure SetFDecimalPrecisionBoolean(Value : Boolean);
procedure SetFIncrement(Value : Integer);
procedure SetFKeyIncrement(Value : Integer);
procedure SetFMaxValue(Value : Integer);
procedure SetFMinValue(Value : Integer);
procedure SetFValue(Value : Integer);
procedure SetFVertical(Value : Boolean);
procedure SetFDragging(Value : Boolean);
procedure SetFThumbs(Value : TExtObjectList);
procedure SetFValues(Value : TExtObjectList);
procedure SetFOnBeforechange(Value : TExtSliderMultiSliderOnBeforechange);
procedure SetFOnChange(Value : TExtSliderMultiSliderOnChange);
procedure SetFOnChangecomplete(Value : TExtSliderMultiSliderOnChangecomplete);
procedure SetFOnDrag(Value : TExtSliderMultiSliderOnDrag);
procedure SetFOnDragend(Value : TExtSliderMultiSliderOnDragend);
procedure SetFOnDragstart(Value : TExtSliderMultiSliderOnDragstart);
protected
procedure InitDefaults; override;
procedure HandleEvent(const AEvtName: string); override;
public
function JSClassName : string; override;
function AddThumb(Value : Integer) : TExtFunction;
function GetValue(Index : Integer) : TExtFunction;
function GetValues : TExtFunction;
function SetMaxValue(Val : Integer) : TExtFunction;
function SetMinValue(Val : Integer) : TExtFunction;
function SetValue(Index : Integer; Value : Integer; Animate : Boolean) : TExtFunction;
function SyncThumb : TExtFunction;
property Animate : Boolean read FAnimate write SetFAnimate;
property ClickToChange : Boolean read FClickToChange write SetFClickToChange;
property ConstrainThumbs : Boolean read FConstrainThumbs write SetFConstrainThumbs;
property DecimalPrecision : Integer read FDecimalPrecision write SetFDecimalPrecision;
property DecimalPrecisionBoolean : Boolean read FDecimalPrecisionBoolean write SetFDecimalPrecisionBoolean;
property Increment : Integer read FIncrement write SetFIncrement;
property KeyIncrement : Integer read FKeyIncrement write SetFKeyIncrement;
property MaxValue : Integer read FMaxValue write SetFMaxValue;
property MinValue : Integer read FMinValue write SetFMinValue;
property Value : Integer read FValue write SetFValue;
property Vertical : Boolean read FVertical write SetFVertical;
property Dragging : Boolean read FDragging write SetFDragging;
property Thumbs : TExtObjectList read FThumbs write SetFThumbs;
property Values : TExtObjectList read FValues write SetFValues;
property OnBeforechange : TExtSliderMultiSliderOnBeforechange read FOnBeforechange write SetFOnBeforechange;
property OnChange : TExtSliderMultiSliderOnChange read FOnChange write SetFOnChange;
property OnChangecomplete : TExtSliderMultiSliderOnChangecomplete read FOnChangecomplete write SetFOnChangecomplete;
property OnDrag : TExtSliderMultiSliderOnDrag read FOnDrag write SetFOnDrag;
property OnDragend : TExtSliderMultiSliderOnDragend read FOnDragend write SetFOnDragend;
property OnDragstart : TExtSliderMultiSliderOnDragstart read FOnDragstart write SetFOnDragstart;
end;
TExtSliderSingleSlider = class(TExtSliderMultiSlider)
protected
procedure InitDefaults; override;
public
function JSClassName : string; override;
function GetValue : TExtFunction;
function SetValue(Value : Integer; Animate : Boolean) : TExtFunction;
function SyncThumb : TExtFunction;
end;
TExtSliderTip = class(TExtTip)
protected
procedure InitDefaults; override;
public
function JSClassName : string; override;
function GetText(Thumb : TExtSliderThumb) : TExtFunction;
end;
implementation
procedure TExtSliderThumb.SetFConstrain(Value : Boolean);
begin
FConstrain := Value;
JSCode('constrain:' + VarToJSON([Value]));
end;
procedure TExtSliderThumb.SetFSlider(Value : TExtSliderMultiSlider);
begin
FSlider := Value;
JSCode('slider:' + VarToJSON([Value, false]));
end;
procedure TExtSliderThumb.SetFSlider_(Value : TExtSliderMultiSlider);
begin
FSlider_ := Value;
JSCode(JSName + '.slider=' + VarToJSON([Value, false]) + ';');
end;
function TExtSliderThumb.JSClassName : string;
begin
Result := 'Ext.slider.Thumb';
end;
procedure TExtSliderThumb.InitDefaults;
begin
inherited;
FSlider := TExtSliderMultiSlider.CreateInternal(Self, 'slider');
FSlider_ := TExtSliderMultiSlider.CreateInternal(Self, 'slider');
end;
function TExtSliderThumb.Disable : TExtFunction;
begin
JSCode(JSName + '.disable();', 'TExtSliderThumb');
Result := Self;
end;
function TExtSliderThumb.Enable : TExtFunction;
begin
JSCode(JSName + '.enable();', 'TExtSliderThumb');
Result := Self;
end;
function TExtSliderThumb.InitEvents : TExtFunction;
begin
JSCode(JSName + '.initEvents();', 'TExtSliderThumb');
Result := Self;
end;
function TExtSliderThumb.Render : TExtFunction;
begin
JSCode(JSName + '.render();', 'TExtSliderThumb');
Result := Self;
end;
procedure TExtSliderMultiSlider.SetFAnimate(Value : Boolean);
begin
FAnimate := Value;
JSCode('animate:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFClickToChange(Value : Boolean);
begin
FClickToChange := Value;
JSCode('clickToChange:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFConstrainThumbs(Value : Boolean);
begin
FConstrainThumbs := Value;
JSCode('constrainThumbs:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFDecimalPrecision(Value : Integer);
begin
FDecimalPrecision := Value;
JSCode('decimalPrecision:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFDecimalPrecisionBoolean(Value : Boolean);
begin
FDecimalPrecisionBoolean := Value;
JSCode('decimalPrecision:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFIncrement(Value : Integer);
begin
FIncrement := Value;
JSCode('increment:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFKeyIncrement(Value : Integer);
begin
FKeyIncrement := Value;
JSCode('keyIncrement:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFMaxValue(Value : Integer);
begin
FMaxValue := Value;
if not ConfigAvailable(JSName) then
SetMaxValue(Value)
else
JSCode('maxValue:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFMinValue(Value : Integer);
begin
FMinValue := Value;
if not ConfigAvailable(JSName) then
SetMinValue(Value)
else
JSCode('minValue:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFValue(Value : Integer);
begin
FValue := Value;
if not ConfigAvailable(JSName) then
SetValue(Value, 0, false)
else
JSCode('value:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFVertical(Value : Boolean);
begin
FVertical := Value;
JSCode('vertical:' + VarToJSON([Value]));
end;
procedure TExtSliderMultiSlider.SetFDragging(Value : Boolean);
begin
FDragging := Value;
JSCode(JSName + '.dragging=' + VarToJSON([Value]) + ';');
end;
procedure TExtSliderMultiSlider.SetFThumbs(Value : TExtObjectList);
begin
FThumbs := Value;
JSCode(JSName + '.thumbs=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtSliderMultiSlider.SetFValues(Value : TExtObjectList);
begin
FValues := Value;
JSCode(JSName + '.values=' + VarToJSON([Value, false]) + ';');
end;
procedure TExtSliderMultiSlider.SetFOnBeforechange(Value : TExtSliderMultiSliderOnBeforechange);
begin
if Assigned(FOnBeforechange) then
JSCode(JSName+'.events ["beforechange"].listeners=[];');
if Assigned(Value) then
On('beforechange', Ajax('beforechange', ['Slider', '%0.nm','NewValue', '%1','OldValue', '%2'], true));
FOnBeforechange := Value;
end;
procedure TExtSliderMultiSlider.SetFOnChange(Value : TExtSliderMultiSliderOnChange);
begin
if Assigned(FOnChange) then
JSCode(JSName+'.events ["change"].listeners=[];');
if Assigned(Value) then
On('change', Ajax('change', ['Slider', '%0.nm','NewValue', '%1','Thumb', '%2.nm'], true));
FOnChange := Value;
end;
procedure TExtSliderMultiSlider.SetFOnChangecomplete(Value : TExtSliderMultiSliderOnChangecomplete);
begin
if Assigned(FOnChangecomplete) then
JSCode(JSName+'.events ["changecomplete"].listeners=[];');
if Assigned(Value) then
On('changecomplete', Ajax('changecomplete', ['Slider', '%0.nm','NewValue', '%1','Thumb', '%2.nm'], true));
FOnChangecomplete := Value;
end;
procedure TExtSliderMultiSlider.SetFOnDrag(Value : TExtSliderMultiSliderOnDrag);
begin
if Assigned(FOnDrag) then
JSCode(JSName+'.events ["drag"].listeners=[];');
if Assigned(Value) then
On('drag', Ajax('drag', ['Slider', '%0.nm','E', '%1.nm'], true));
FOnDrag := Value;
end;
procedure TExtSliderMultiSlider.SetFOnDragend(Value : TExtSliderMultiSliderOnDragend);
begin
if Assigned(FOnDragend) then
JSCode(JSName+'.events ["dragend"].listeners=[];');
if Assigned(Value) then
On('dragend', Ajax('dragend', ['Slider', '%0.nm','E', '%1.nm'], true));
FOnDragend := Value;
end;
procedure TExtSliderMultiSlider.SetFOnDragstart(Value : TExtSliderMultiSliderOnDragstart);
begin
if Assigned(FOnDragstart) then
JSCode(JSName+'.events ["dragstart"].listeners=[];');
if Assigned(Value) then
On('dragstart', Ajax('dragstart', ['Slider', '%0.nm','E', '%1.nm'], true));
FOnDragstart := Value;
end;
function TExtSliderMultiSlider.JSClassName : string;
begin
Result := 'Ext.slider.MultiSlider';
end;
procedure TExtSliderMultiSlider.InitDefaults;
begin
inherited;
FThumbs := TExtObjectList.CreateAsAttribute(Self, 'thumbs');
FValues := TExtObjectList.CreateAsAttribute(Self, 'values');
end;
function TExtSliderMultiSlider.AddThumb(Value : Integer) : TExtFunction;
begin
JSCode(JSName + '.addThumb(' + VarToJSON([Value]) + ');', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.GetValue(Index : Integer) : TExtFunction;
begin
JSCode(JSName + '.getValue(' + VarToJSON([Index]) + ');', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.GetValues : TExtFunction;
begin
JSCode(JSName + '.getValues();', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.SetMaxValue(Val : Integer) : TExtFunction;
begin
JSCode(JSName + '.setMaxValue(' + VarToJSON([Val]) + ');', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.SetMinValue(Val : Integer) : TExtFunction;
begin
JSCode(JSName + '.setMinValue(' + VarToJSON([Val]) + ');', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.SetValue(Index : Integer; Value : Integer; Animate : Boolean) : TExtFunction;
begin
JSCode(JSName + '.setValue(' + VarToJSON([Index, Value, Animate]) + ');', 'TExtSliderMultiSlider');
Result := Self;
end;
function TExtSliderMultiSlider.SyncThumb : TExtFunction;
begin
JSCode(JSName + '.syncThumb();', 'TExtSliderMultiSlider');
Result := Self;
end;
procedure TExtSliderMultiSlider.HandleEvent(const AEvtName : string);
begin
inherited;
if (AEvtName = 'beforechange') and Assigned(FOnBeforechange) then
FOnBeforechange(TExtSlider(ParamAsObject('Slider')), ParamAsInteger('NewValue'), ParamAsInteger('OldValue'))
else if (AEvtName = 'change') and Assigned(FOnChange) then
FOnChange(TExtSlider(ParamAsObject('Slider')), ParamAsInteger('NewValue'), TExtSliderThumb(ParamAsObject('Thumb')))
else if (AEvtName = 'changecomplete') and Assigned(FOnChangecomplete) then
FOnChangecomplete(TExtSlider(ParamAsObject('Slider')), ParamAsInteger('NewValue'), TExtSliderThumb(ParamAsObject('Thumb')))
else if (AEvtName = 'drag') and Assigned(FOnDrag) then
FOnDrag(TExtSlider(ParamAsObject('Slider')), ExtEventObject)
else if (AEvtName = 'dragend') and Assigned(FOnDragend) then
FOnDragend(TExtSlider(ParamAsObject('Slider')), ExtEventObject)
else if (AEvtName = 'dragstart') and Assigned(FOnDragstart) then
FOnDragstart(TExtSlider(ParamAsObject('Slider')), ExtEventObject);
end;
function TExtSliderSingleSlider.JSClassName : string;
begin
Result := 'Ext.slider.SingleSlider';
end;
procedure TExtSliderSingleSlider.InitDefaults;
begin
inherited;
end;
function TExtSliderSingleSlider.GetValue : TExtFunction;
begin
JSCode(JSName + '.getValue();', 'TExtSliderSingleSlider');
Result := Self;
end;
function TExtSliderSingleSlider.SetValue(Value : Integer; Animate : Boolean) : TExtFunction;
begin
JSCode(JSName + '.setValue(' + VarToJSON([Value, Animate]) + ');', 'TExtSliderSingleSlider');
Result := Self;
end;
function TExtSliderSingleSlider.SyncThumb : TExtFunction;
begin
JSCode(JSName + '.syncThumb();', 'TExtSliderSingleSlider');
Result := Self;
end;
function TExtSliderTip.JSClassName : string;
begin
Result := 'Ext.slider.Tip';
end;
procedure TExtSliderTip.InitDefaults;
begin
inherited;
end;
function TExtSliderTip.GetText(Thumb : TExtSliderThumb) : TExtFunction;
begin
JSCode(JSName + '.getText(' + VarToJSON([Thumb, false]) + ');', 'TExtSliderTip');
Result := Self;
end;
end. |
procedure TurnOffKey(Key: integer);
//
// Desliga uma Tecla
//
Var
KeyState : TKeyboardState;
begin
GetKeyboardState(KeyState);
if (KeyState[Key] = 1) then
begin
KeyState[Key] := 0;
end;
SetKeyboardState(KeyState);
end;
|
unit ThStyledCtrl;
interface
uses
Classes, Controls, Graphics, Messages, Types, ExtCtrls,
ThMessages, ThCustomCtrl, ThGraphicCtrl, ThCssStyle,
ThStylePainter;
type
IThStyled = interface
['{308F2155-A4B8-4347-B00C-100BF6624BBF}']
function GetStyle: TThCssStyle;
function GetStyleClass: string;
procedure SetStyleClass(const inStyleClass: string);
end;
//
//:$ Ancestor class for all TurboHtml Windowed controls, base class for
//:$ TThHtmlCustomControl.
//:: TThStyledCustomControl adds style machinery to TThCustomControl.
TThStyledCustomControl = class(TThCustomControl, IThStyled)
private
FCtrlStyle: TThCssStyle;
FStyle: TThCssStyle;
FStyleClass: string;
FStylePainter: TThStylePainter;
FDesignOpaque: Boolean;
protected
function GetClientRect: TRect; override;
function GetPageStyle: TThCssStyle; virtual;
function GetSheetStyle: TThCssStyle; virtual;
function GetStyle: TThCssStyle;
function GetStyleClass: string;
procedure SetDesignOpaque(const Value: Boolean);
procedure SetStyle(const Value: TThCssStyle);
procedure SetStyleClass(const Value: string);
protected
//:$ <br>Return the rect with margins adjusted by the CtrlStyle.
procedure AdjustClientRect(var inRect: TRect); override;
//:$ <br>Build the Style property.
//:: Builds the read-only Style property by combining the SheetStyle,
//:: the Style, and the page default styles.
procedure BuildStyle; virtual;
procedure CssStyleChanged; virtual;
procedure Loaded; override;
//:$ <br>Default painting operations.
//:: Invokes the Painter object and sets the Canvas' brush color.
procedure Paint; override;
procedure StyleChanged(inSender: TObject);
procedure ThmStyleChange(var inMessage); message THM_STYLECHANGE;
procedure ThmUpdatePicture(var inMessage); message THM_UPDATEPICTURE;
protected
//:$ <br>The default style for the page containing this control.
property PageStyle: TThCssStyle read GetPageStyle;
//:$ <br>Style painter object used for common style painting tasks.
property Painter: TThStylePainter read FStylePainter;
//:$ <br>Local CSS style properties for the control.
//:: The CtrlStyle for the control is a combination of the SheetStyle
//:: and the Style. Style properties take precedence over
//:: SheetStyle style properties.
property Style: TThCssStyle read GetStyle write SetStyle;
//:$ <br>The CSS class to assign to this control.
//:: If the specified class belongs to a StyleSheet on the same page,
//:: the control is painted using the specified style.
//:: The final control for the style (the CtrlStyle) is a combination of
//:: the SheetStyle and the Style. Style property takes precendence.
property StyleClass: string read GetStyleClass write SetStyleClass;
//:$ <br>The StyleSheet style (or nil) identified by StyleClass.
property SheetStyle: TThCssStyle read GetSheetStyle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//:$ <br>Return the client rect with margins adjusted by the CtrlStyle.
function AdjustedClientRect: TRect;
//:$ <br>Return the client height as adjusted by the CtrlStyle.
function AdjustedClientHeight: Integer;
//:$ <br>Return the client width as adjusted by the CtrlStyle.
function AdjustedClientWidth: Integer;
public
//:$ <br>CSS style properties for the control.
//:: This is the style resulting from a blend of the default styles,
//:: the SheetStyle, and the Style.
property CtrlStyle: TThCssStyle read FCtrlStyle;
//:$ <br>Set true for opaque painting at design time.
property DesignOpaque: Boolean read FDesignOpaque write SetDesignOpaque;
end;
//
//:$ Ancestor class for all TurboHtml graphic controls, base class for
//:$ TThHtmlGraphicControl.
//:: TThStyledGraphicControl adds style machinery to TThGraphicControl.
TThStyledGraphicControl = class(TThGraphicControl, IThStyled)
private
FCtrlStyle: TThCssStyle;
FStyle: TThCssStyle;
FStyleClass: string;
FStylePainter: TThStylePainter;
FDesignOpaque: Boolean;
function GetStyle: TThCssStyle;
function GetStyleClass: string;
protected
function GetPageStyle: TThCssStyle; virtual;
function GetSheetStyle: TThCssStyle; virtual;
procedure SetDesignOpaque(const Value: Boolean); virtual;
procedure SetStyle(const Value: TThCssStyle); virtual;
procedure SetStyleClass(const Value: string); virtual;
protected
//:$ <br>Return the rect with margins adjusted by the CtrlStyle.
procedure AdjustClientRect(var inRect: TRect);
//:$ <br>Build the Style property.
//:: Builds the read-only Style property by combining the SheetStyle,
//:: the Style, and the page default styles.
procedure BuildStyle; virtual;
procedure CssStyleChanged; virtual;
procedure Loaded; override;
//:$ <br>Default painting operations.
//:: Invokes the Painter object and sets the Canvas' brush color.
procedure Paint; override;
procedure SetParent({$ifdef __ThClx__}const{$endif}
inParent: TWinControl); override;
procedure StyleChanged(inSender: TObject);
procedure ThmStyleChange(var inMessage); message ThM_STYLECHANGE;
procedure ThmUpdatePicture(var inMessage); message THM_UPDATEPICTURE;
protected
//:$ <br>The default style for the page containing this control.
property PageStyle: TThCssStyle read GetPageStyle;
//:$ <br>Style painter object used for common style painting tasks.
property Painter: TThStylePainter read FStylePainter;
//:$ <br>Local CSS style properties for the control.
//:: The CtrlStyle for the control is a combination of the SheetStyle
//:: and the Style. Style properties take precedence over
//:: SheetStyle style properties.
property Style: TThCssStyle read GetStyle write SetStyle;
//:$ <br>The CSS class to assign to this control.
//:: If the specified class belongs to a StyleSheet on the same page,
//:: the control is painted using the specified style.
//:: The final control for the style (the CtrlStyle) is a combination of
//:: the SheetStyle and the Style. Style property takes precendence.
property StyleClass: string read GetStyleClass write SetStyleClass;
//:$ <br>The StyleSheet style (or nil) identified by StyleClass.
property SheetStyle: TThCssStyle read GetSheetStyle;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//:$ <br>Return the client rect with margins adjusted by the CtrlStyle.
function AdjustedClientRect: TRect;
//:$ <br>Return the client height as adjusted by the CtrlStyle.
function AdjustedClientHeight: Integer;
//:$ <br>Return the client width as adjusted by the CtrlStyle.
function AdjustedClientWidth: Integer;
public
//:$ <br>CSS style properties for the control.
//:: This is the style resulting from a blend of the default styles,
//:: the SheetStyle, and the Style.
property CtrlStyle: TThCssStyle read FCtrlStyle;
//:$ <br>Set true for opaque painting at design time.
property DesignOpaque: Boolean read FDesignOpaque write SetDesignOpaque;
end;
implementation
uses
ThHtmlPage, ThStyleSheet, ThVclUtils;
{ TThStyledCustomControl }
constructor TThStyledCustomControl.Create(AOwner: TComponent);
begin
inherited;
Transparent := true;
FStyle := TThCssStyle.Create(Self);
FStyle.OnChanged := StyleChanged;
FCtrlStyle := TThCssStyle.Create(Self);
FStylePainter := TThStylePainter.Create;
BuildStyle;
SetBounds(0, 0, 86, 64);
end;
destructor TThStyledCustomControl.Destroy;
begin
FStylePainter.Free;
FCtrlStyle.Free;
FStyle.Free;
inherited;
end;
procedure TThStyledCustomControl.Loaded;
begin
inherited;
CssStyleChanged;
end;
function TThStyledCustomControl.GetStyle: TThCssStyle;
begin
Result := FStyle;
end;
function TThStyledCustomControl.GetStyleClass: string;
begin
Result := FStyleClass;
end;
function TThStyledCustomControl.GetSheetStyle: TThCssStyle;
begin
Result := ThFindStyleSheetStyle(Self, StyleClass);
end;
function TThStyledCustomControl.GetPageStyle: TThCssStyle;
var
p: TThHtmlPage;
begin
p := TThHtmlPage(ThFindElderComponent(Self, TThHtmlPage));
if (p <> nil) then
Result := p.Style
else
Result := NilStyle;
end;
procedure TThStyledCustomControl.BuildStyle;
begin
CtrlStyle.Assign(Style);
CtrlStyle.Inherit(SheetStyle);
CtrlStyle.Font.Inherit(PageStyle.Font);
CtrlStyle.Font.ToFont(Font);
Canvas.Font := Font;
Color := CtrlStyle.Color;
if not ThVisibleColor(Color) and DesignOpaque then
if (Parent <> nil) then
Color := TPanel(Parent).Color;
end;
procedure TThStyledCustomControl.CssStyleChanged;
begin
BuildStyle;
Invalidate;
AdjustSize;
Realign;
end;
procedure TThStyledCustomControl.StyleChanged(inSender: TObject);
begin
CssStyleChanged;
end;
procedure TThStyledCustomControl.ThmStyleChange(var inMessage);
begin
CssStyleChanged;
end;
procedure TThStyledCustomControl.ThmUpdatePicture(var inMessage);
begin
Style.Background.Picture.ResolvePicturePath;
CssStyleChanged;
end;
procedure TThStyledCustomControl.SetStyle(const Value: TThCssStyle);
begin
FStyle.Assign(Value);
CssStyleChanged;
end;
procedure TThStyledCustomControl.SetStyleClass(const Value: string);
begin
FStyleClass := Value;
CssStyleChanged;
end;
function TThStyledCustomControl.GetClientRect: TRect;
begin
Result := inherited GetClientRect;
//AdjustClientRect(Result);
end;
procedure TThStyledCustomControl.AdjustClientRect(var inRect: TRect);
begin
CtrlStyle.AdjustClientRect(inRect);
end;
function TThStyledCustomControl.AdjustedClientWidth: Integer;
begin
Result := CtrlStyle.AdjustWidth(ClientWidth);
end;
function TThStyledCustomControl.AdjustedClientHeight: Integer;
begin
Result := CtrlStyle.AdjustHeight(ClientHeight);
end;
function TThStyledCustomControl.AdjustedClientRect: TRect;
begin
Result := ClientRect;
AdjustClientRect(Result);
end;
procedure TThStyledCustomControl.Paint;
begin
inherited;
Painter.Prepare(Color, CtrlStyle, Canvas, Rect(0, 0, Width, Height));
Painter.PaintBackground;
Painter.PaintBorders;
Canvas.Font := Font;
Canvas.Brush.Color := Color;
end;
procedure TThStyledCustomControl.SetDesignOpaque(const Value: Boolean);
begin
FDesignOpaque := Value;
BuildStyle;
Invalidate;
end;
{ TThStyledGraphicControl }
constructor TThStyledGraphicControl.Create(AOwner: TComponent);
begin
inherited;
FStyle := TThCssStyle.Create(Self);
FStyle.OnChanged := StyleChanged;
FCtrlStyle := TThCssStyle.Create(Self);
FStylePainter := TThStylePainter.Create; //(Self);
//BuildStyle;
//Width := 86;
//Height := 64;
SetBounds(0, 0, 86, 64);
end;
destructor TThStyledGraphicControl.Destroy;
begin
FStylePainter.Free;
FStyle.Free;
FCtrlStyle.Free;
inherited;
end;
procedure TThStyledGraphicControl.Loaded;
begin
inherited;
CssStyleChanged;
end;
procedure TThStyledGraphicControl.SetParent({$ifdef __ThClx__}const{$endif}
inParent: TWinControl);
begin
inherited;
if (inParent <> nil) and not (csDestroying in ComponentState)
and not (csLoading in ComponentState) then
CssStyleChanged;
end;
function TThStyledGraphicControl.GetStyle: TThCssStyle;
begin
Result := FStyle;
end;
function TThStyledGraphicControl.GetStyleClass: string;
begin
Result := FStyleClass;
end;
function TThStyledGraphicControl.GetSheetStyle: TThCssStyle;
begin
Result := ThFindStyleSheetStyle(Self, StyleClass);
end;
function TThStyledGraphicControl.GetPageStyle: TThCssStyle;
var
p: TThHtmlPage;
begin
p := TThHtmlPage(ThFindElderComponent(Self, TThHtmlPage));
if (p <> nil) then
Result := p.Style
else
Result := NilStyle;
end;
procedure TThStyledGraphicControl.BuildStyle;
//var
// p: TWinControl;
begin
CtrlStyle.Assign(Style);
CtrlStyle.Inherit(SheetStyle);
CtrlStyle.Font.Inherit(PageStyle.Font);
CtrlStyle.Font.ToFont(Font);
Canvas.Font := Font;
Color := CtrlStyle.Color;
//
{
p := Parent;
while (p <> nil) and not ThVisibleColor(Color) and DesignOpaque do
begin
Color := TPanel(p).Color;
p := p.Parent;
end;
}
if not ThVisibleColor(Color) and DesignOpaque then
if (Parent <> nil) then
Color := TPanel(Parent).Color;
end;
procedure TThStyledGraphicControl.CssStyleChanged;
begin
Invalidate;
BuildStyle;
AdjustSize;
end;
procedure TThStyledGraphicControl.StyleChanged(inSender: TObject);
begin
CssStyleChanged;
end;
procedure TThStyledGraphicControl.ThmStyleChange(var inMessage);
begin
CssStyleChanged;
end;
procedure TThStyledGraphicControl.ThmUpdatePicture(var inMessage);
begin
Style.Background.Picture.ResolvePicturePath;
CssStyleChanged;
end;
procedure TThStyledGraphicControl.SetStyle(const Value: TThCssStyle);
begin
FStyle.Assign(Value);
CssStyleChanged;
end;
procedure TThStyledGraphicControl.SetStyleClass(const Value: string);
begin
FStyleClass := Value;
CssStyleChanged;
end;
procedure TThStyledGraphicControl.Paint;
begin
Painter.Prepare(Color, CtrlStyle, Canvas, Rect(0, 0, Width, Height));
Painter.PaintBackground;
Painter.PaintBorders;
Canvas.Brush.Color := Color;
end;
procedure TThStyledGraphicControl.AdjustClientRect(var inRect: TRect);
begin
CtrlStyle.AdjustClientRect(inRect);
end;
function TThStyledGraphicControl.AdjustedClientWidth: Integer;
begin
Result := CtrlStyle.AdjustWidth(ClientWidth);
end;
function TThStyledGraphicControl.AdjustedClientHeight: Integer;
begin
Result := CtrlStyle.AdjustHeight(ClientHeight);
end;
function TThStyledGraphicControl.AdjustedClientRect: TRect;
begin
Result := ClientRect;
AdjustClientRect(Result);
end;
procedure TThStyledGraphicControl.SetDesignOpaque(const Value: Boolean);
begin
FDesignOpaque := Value;
BuildStyle;
Invalidate;
end;
end.
|
unit MessageWin;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RXCtrls, ExtCtrls, StdCtrls;
type
TMessageWindow = class(TForm)
Messages: TMemo;
ToolPanel: TPanel;
ClearBtn: TRxSpeedButton;
SaveBtn: TRxSpeedButton;
SaveDialog: TSaveDialog;
procedure ClearBtnClick(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
private
{ Private declarations }
public
procedure Add(const AType, AMessage: String); overload;
procedure Add(const AType : String; AMessages: TStrings); overload;
procedure Add(const AType, AFormat : String; AParams : array of const); overload;
end;
var
MessageWindow: TMessageWindow;
implementation
uses Main;
{$R *.DFM}
procedure TMessageWindow.ClearBtnClick(Sender: TObject);
begin
Messages.Lines.Clear;
end;
procedure TMessageWindow.SaveBtnClick(Sender: TObject);
begin
if SaveDialog.Execute then begin
Messages.Lines.SaveToFile(SaveDialog.FileName);
ShowMessage('Messages saved to ' + SaveDialog.FileName + '.');
end;
end;
procedure TMessageWindow.Add(const AType, AMessage: String);
begin
Messages.Lines.Insert(0, Format('[%s] %s', [AType, AMessage]));
end;
procedure TMessageWindow.Add(const AType : String; AMessages: TStrings);
var
I : Integer;
begin
if AMessages.Count > 0 then
for I := 0 to AMessages.Count-1 do
Add(AType, AMessages[I]);
end;
procedure TMessageWindow.Add(const AType, AFormat : String; AParams : array of const);
begin
Messages.Lines.Insert(0, '[' + AType + '] ' + Format(AFormat, AParams));
end;
end.
|
unit uPochasPrint;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, FIBDataSet, pFIBDataSet, frxExportRTF, frxExportXML,
frxClass, frxExportPDF, frxDBSet, cxLookAndFeelPainters, cxLabel,
cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, StdCtrls, cxButtons;
type
TfrmPochasTarifPrint = class(TForm)
PochasPrintDSet: TpFIBDataSet;
PochasDBDSet: TfrxDBDataset;
frxPDFExport1: TfrxPDFExport;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
btnPrint: TcxButton;
btnCancel: TcxButton;
PeriodBeg: TcxDateEdit;
PeriodEnd: TcxDateEdit;
isCheckPeriod: TcxCheckBox;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
PochasReport: TfrxReport;
procedure btnPrintClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure isCheckPeriodPropertiesChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPochasTarifPrint: TfrmPochasTarifPrint;
implementation
{$R *.dfm}
uses uPochasTarif, BaseTypes;
procedure TfrmPochasTarifPrint.btnPrintClick(Sender: TObject);
begin
try
if PeriodBeg.Date>PeriodEnd.Date then
begin
agMessageDlg('Увага!', 'Дата початку не може бути більше дати кінця!', mtInformation, [mbOK]);
Exit;
end;
if PochasPrintDSet.Active then PochasPrintDSet.Close;
PochasPrintDSet.SQLs.SelectSQL.Text:='Select * From Up_Sp_Pochas_Tarif_Print(:Period_Beg, :Period_End)';
if isCheckPeriod.Checked then
begin
PochasPrintDSet.ParamByName('Period_Beg').AsDate:=PeriodBeg.Date;
PochasPrintDSet.ParamByName('Period_End').AsDate:=PeriodEnd.Date;
end
else
begin
PochasPrintDSet.ParamByName('Period_Beg').Value:=null;
PochasPrintDSet.ParamByName('Period_End').Value:=null;
end;
PochasPrintDSet.Open;
PochasReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\UP\UpPochasTarif.fr3', True);
if isCheckPeriod.Checked then PochasReport.Variables['isCheckPeriod']:=QuotedStr('T')
else PochasReport.Variables['isCheckPeriod']:=QuotedStr('F');
PochasReport.Variables['Period_Beg']:=QuotedStr(PeriodBeg.Text);
PochasReport.Variables['Period_End']:=QuotedStr(PeriodEnd.Text);
PochasReport.ShowReport;
except on E:Exception do
begin
agMessageDlg(Application.Title, E.Message, mtInformation, [mbOK]);
PochasPrintDSet.Close;
end;
end;
end;
procedure TfrmPochasTarifPrint.btnCancelClick(Sender: TObject);
begin
close;
end;
procedure TfrmPochasTarifPrint.isCheckPeriodPropertiesChange(
Sender: TObject);
begin
PeriodBeg.Enabled:=isCheckPeriod.Checked;
PeriodEnd.Enabled:=isCheckPeriod.Checked;
end;
procedure TfrmPochasTarifPrint.FormCreate(Sender: TObject);
begin
PeriodBeg.Date:=Date;
PeriodEnd.Date:=Date;
end;
end.
|
unit iOS.Services;
interface
uses
Xplat.Services,
iOSApi.UiKit,
FMX.Platform.iOS,
System.Generics.Collections;
type
TioSPleaseWait = class(TInterfacedObject, IPleaseWaitService)
private
FView: UIActivityIndicatorView;
FCount: Integer;
public
procedure StartWait;
procedure StopWait;
end;
implementation
uses
FMX.Forms, FMX.Platform, Apple.Utils;
{ TiOSPleaseWait }
procedure TioSPleaseWait.StartWait;
var
lView: UIView;
begin
AtomicIncrement(FCount);
if FCount = 1 then
begin
lView := ActiveView;
FView := TUIActivityIndicatorView.Create;
FView.setCenter(lView.center);
FView.setActivityIndicatorViewStyle(UIActivityIndicatorViewStyleGray);
lView.addSubview(FView);
SharedApplication.setNetworkActivityIndicatorVisible(True);
FView.startAnimating;
end;
end;
procedure TioSPleaseWait.StopWait;
begin
AtomicDecrement(FCount);
if (FCount = 0) and Assigned(FView) then
begin
FView.stopAnimating;
FView.removeFromSuperview;
SharedApplication.setNetworkActivityIndicatorVisible(False);
FView := nil;
end;
end;
initialization
TPlatformServices.Current.AddPlatformService(IPleaseWaitService, TioSPleaseWait.Create);
finalization
TPlatformServices.Current.RemovePlatformService(IPleaseWaitService);
end.
|
namespace GlHelper;
interface
{$GLOBALS ON}
uses
rtl;
type
{ A 2-dimensional vector. Can be used to represent points or vectors in
2D space, using the X and Y fields. You can also use it to represent
texture coordinates, by using S and T (these are just aliases for X and Y).
It can also be used to group 2 arbitrary values together in an array (using
C[0] and C[1], which are also just aliases for X and Y).
}
TVector2 = public record
{$REGION 'Internal Declarations'}
private
method GetComponent(const AIndex: Integer): Single;
method SetComponent(const AIndex: Integer; const Value: Single);
method GetLength: Single;
method SetLength(const AValue: Single);
method GetLengthSquared: Single;
method SetLengthSquared(const AValue: Single);
method GetAngle: Single;
method SetAngle(const AValue: Single);
{$ENDREGION 'Internal Declarations'}
public
{ Sets the two elements (X and Y) to 0. }
method Init;
{ Sets the two elements (X and Y) to A.
Parameters:
A: the value to set the two elements to. }
method Init(const A: Single);
{ Sets the two elements (X and Y) to A1 and A2 respectively.
Parameters:
A1: the value to set the first element to.
A2: the value to set the second element to. }
method Init(const A1, A2: Single);
{ Checks two vectors for equality.
Returns:
True if the two vectors match each other exactly. }
class operator &Equal(const A, B: TVector2): Boolean; //inline;
{ Checks two vectors for inequality.
Returns:
True if the two vectors are not equal. }
class operator NotEqual(const A, B: TVector2): Boolean; inline;
{ Negates a vector.
Returns:
The negative value of a vector (eg. (-A.X, -A.Y)) }
class operator Minus(const A: TVector2): TVector2; {$IF FM_INLINE }inline;{$ENDIF}
{ Adds a scalar value to a vector.
Returns:
(A.X + B, A.Y + B) }
class operator Add(const A: TVector2; const B: Single): TVector2; inline;
{ Adds a vector to a scalar value.
Returns:
(A + B.X, A + B.Y) }
class operator Add(const A: Single; const B: TVector2): TVector2; inline;
{ Adds two vectors.
Returns:
(A.X + B.X, A.Y + B.Y) }
class operator Add(const A, B: TVector2): TVector2; {$IF FM_INLINE }inline;{$ENDIF}
{ Subtracts a scalar value from a vector.
Returns:
(A.X - B, A.Y - B) }
class operator Subtract(const A: TVector2; const B: Single): TVector2; inline;
{ Subtracts a vector from a scalar value.
Returns:
(A - B.X, A - B.Y) }
class operator Subtract(const A: Single; const B: TVector2): TVector2; inline;
{ Subtracts two vectors.
Returns:
(A.X - B.X, A.Y - B.Y) }
class operator Subtract(const A, B: TVector2): TVector2; inline;
{ Multiplies a vector with a scalar value.
Returns:
(A.X * B, A.Y * B) }
class operator Multiply(const A: TVector2; const B: Single): TVector2; inline;
{ Multiplies a scalar value with a vector.
Returns:
(A * B.X, A * B.Y) }
class operator Multiply(const A: Single; const B: TVector2): TVector2; inline;
{ Multiplies two vectors component-wise.
To calculate a dot or cross product instead, use the Dot or Cross function.
Returns:
(A.X * B.X, A.Y * B.Y) }
class operator Multiply(const A, B: TVector2): TVector2; inline;
{ Divides a vector by a scalar value.
Returns:
(A.X / B, A.Y / B) }
class operator Divide(const A: TVector2; const B: Single): TVector2; inline;
{ Divides a scalar value by a vector.
Returns:
(A / B.X, A / B.Y) }
class operator Divide(const A: Single; const B: TVector2): TVector2;inline;
{ Divides two vectors component-wise.
Returns:
(A.X / B.X, A.Y / B.Y) }
class operator Divide(const A, B: TVector2): TVector2; inline;
{ Whether this vector equals another vector, within a certain tolerance.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if both vectors are equal (within the given tolerance). }
method Equals(const AOther: TVector2; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Calculates the distance between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The distance between this vector and AOther.
@bold(Note): If you only want to compare distances, you should use
DistanceSquared instead, which is faster. }
method Distance(const AOther: TVector2): Single;
{ Calculates the squared distance between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The squared distance between this vector and AOther. }
method DistanceSquared(const AOther: TVector2): Single;
{ Calculates the dot product between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The dot product between this vector and AOther. }
method Dot(const AOther: TVector2): Single; inline;
{ Calculates the cross product between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The cross product between this vector and AOther. }
method Cross(const AOther: TVector2): Single; inline;
{ Offsets this vector in a certain direction.
Parameters:
ADeltaX: the delta X direction.
ADeltaY: the delta Y direction. }
method Offset(const ADeltaX, ADeltaY: Single);
{ Offsets this vector in a certain direction.
Parameters:
ADelta: the delta.
@bold(Note): this is equivalent to adding two vectors together. }
method Offset(const ADelta: TVector2);
{ Calculates a normalized version of this vector.
Returns:
The normalized version of of this vector. That is, a vector in the same
direction as A, but with a length of 1.
@bold(Note): for a faster, less accurate version, use NormalizeFast.
@bold(Note): Does not change this vector. To update this vector itself,
use SetNormalized. }
method Normalize: TVector2;
{ Normalizes this vector. This is, keep the current direction, but set the
length to 1.
@bold(Note): The SIMD optimized versions of this method use an
approximation, resulting in a very small error.
@bold(Note): If you do not want to change this vector, but get a
normalized version instead, then use Normalize. }
method SetNormalized;
{ Calculates a normalized version of this vector.
Returns:
The normalized version of of this vector. That is, a vector in the same
direction as A, but with a length of 1.
@bold(Note): this is an SIMD optimized version that uses an approximation,
resulting in a small error. For an accurate version, use Normalize.
@bold(Note): Does not change this vector. To update this vector itself,
use SetNormalizedFast. }
method NormalizeFast: TVector2; inline;
{ Normalizes this vector. This is, keep the current direction, but set the
length to 1.
@bold(Note): this is an SIMD optimized version that uses an approximation,
resulting in a small error. For an accurate version, use SetNormalized.
@bold(Note): If you do not want to change this vector, but get a
normalized version instead, then use NormalizeFast. }
method SetNormalizedFast; inline;
{ Calculates a vector pointing in the same direction as this vector.
Parameters:
I: the incident vector.
NRef: the reference vector.
Returns:
A vector that points away from the surface as defined by its normal. If
NRef.Dot(I) < 0 then it returns this vector, otherwise it returns the
negative of this vector. }
method FaceForward(const I, NRef: TVector2): TVector2;
{ Calculates the reflection direction for this (incident) vector.
Parameters:
N: the normal vector. Should be normalized in order to achieve the desired
result.
Returns:
The reflection direction calculated as Self - 2 * N.Dot(Self) * N. }
method Reflect(const N: TVector2): TVector2;
{ Calculates the refraction direction for this (incident) vector.
Parameters:
N: the normal vector. Should be normalized in order to achieve the
desired result.
Eta: the ratio of indices of refraction.
Returns:
The refraction vector.
@bold(Note): This vector should be normalized in order to achieve the
desired result.}
method Refract(const N: TVector2; const Eta: Single): TVector2;
{ Creates a vector with the same direction as this vector, but with the
length limited, based on the desired maximum length.
Parameters:
AMaxLength: The desired maximum length of the vector.
Returns:
A length-limited version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLimit. }
method Limit(const AMaxLength: Single): TVector2;
{ Limits the length of this vector, based on the desired maximum length.
Parameters:
AMaxLength: The desired maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-limited version instead, then use Limit. }
method SetLimit(const AMaxLength: Single);
{ Creates a vector with the same direction as this vector, but with the
length limited, based on the desired squared maximum length.
Parameters:
AMaxLengthSquared: The desired squared maximum length of the vector.
Returns:
A length-limited version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLimitSquared. }
method LimitSquared(const AMaxLengthSquared: Single): TVector2;
{ Limits the length of this vector, based on the desired squared maximum
length.
Parameters:
AMaxLengthSquared: The desired squared maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-limited version instead, then use LimitSquared. }
method SetLimitSquared(const AMaxLengthSquared: Single);
{ Creates a vector with the same direction as this vector, but with the
length clamped between a minimim and maximum length.
Parameters:
AMinLength: The minimum length of the vector.
AMaxLength: The maximum length of the vector.
Returns:
A length-clamped version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetClamped. }
method Clamp(const AMinLength, AMaxLength: Single): TVector2;
{ Clamps the length of this vector between a minimim and maximum length.
Parameters:
AMinLength: The minimum length of this vector.
AMaxLength: The maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-clamped version instead, then use Clamp. }
method SetClamped(const AMinLength, AMaxLength: Single);
{ Creates a vector by rotating this vector counter-clockwise.
AParameters:
ARadians: the rotation angle in radians, counter-clockwise assuming the
Y-axis points up.
Returns:
A rotated version version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetRotated. }
method Rotate(const ARadians: Single): TVector2;
{ Rotates this vector counter-clockwise.
AParameters:
ARadians: the rotation angle in radians, counter-clockwise assuming the
Y-axis points up.
@bold(Note): If you do not want to change this vector, but get a
rotated version instead, then use Rotate. }
method SetRotated(const ARadians: Single);
{ Creates a vector by rotating this vector 90 degrees counter-clockwise.
Returns:
A rotated version version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetRotated90CCW. }
method Rotate90CCW: TVector2;
{ Rotates this vector 90 degrees counter-clockwise.
@bold(Note): If you do not want to change this vector, but get a
rotated version instead, then use Rotate90CCW. }
method SetRotated90CCW;
{ Creates a vector by rotating this vector 90 degrees clockwise.
Returns:
A rotated version version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetRotated90CW. }
method Rotate90CW: TVector2;
{ Rotates this vector 90 degrees clockwise.
@bold(Note): If you do not want to change this vector, but get a
rotated version instead, then use Rotate90CW. }
method SetRotated90CW;
{ Calculates the angle in radians to rotate this vector/point to a target
vector. Angles are towards the positive Y-axis (counter-clockwise).
Parameters:
ATarget: the target vector.
Returns:
The angle in radians to the target vector, in the range -Pi to Pi. }
method AngleTo(const ATarget: TVector2): Single;
{ Linearly interpolates between this vector and a target vector.
Parameters:
ATarget: the target vector.
AAlpha: the interpolation coefficient (between 0.0 and 1.0).
Returns:
The interpolation result vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLerp. }
method Lerp(const ATarget: TVector2; const AAlpha: Single): TVector2;
{ Linearly interpolates between this vector and a target vector and stores
the result in this vector.
Parameters:
ATarget: the target vector.
AAlpha: the interpolation coefficient (between 0.0 and 1.0).
@bold(Note): If you do not want to change this vector, but get an
interpolated version instead, then use Lerp. }
method SetLerp(const ATarget: TVector2; const AAlpha: Single);
{ Whether the vector is normalized (within a small margin of error).
Returns:
True if the length of the vector is (very close to) 1.0 }
method IsNormalized: Boolean;
{ Whether the vector is normalized within a given margin of error.
Parameters:
AErrorMargin: the allowed margin of error.
Returns:
True if the squared length of the vector is 1.0 within the margin of
error. }
method IsNormalized(const AErrorMargin: Single): Boolean;
{ Whether this is a zero vector.
Returns:
True if X and Y are exactly 0.0 }
method IsZero: Boolean;
{ Whether this is a zero vector within a given margin of error.
Parameters:
AErrorMargin: the allowed margin of error.
Returns:
True if the squared length is smaller then the margin of error. }
method IsZero(const AErrorMargin: Single): Boolean;
{ Whether this vector has a similar direction compared to another vector.
Parameters:
AOther: the other vector.
Returns:
True if the normalized dot product is greater than 0. }
method HasSameDirection(const AOther: TVector2): Boolean;
{ Whether this vector has an opposite direction compared to another vector.
Parameters:
AOther: the other vector.
Returns:
True if the normalized dot product is less than 0. }
method HasOppositeDirection(const AOther: TVector2): Boolean;
{ Whether this vector runs parallel to another vector (either in the same
or the opposite direction).
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector runs parallel to AOther (within the given tolerance)
@bold(Note): every vector is considered to run parallel to a zero vector. }
method IsParallel(const AOther: TVector2; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is collinear with another vector. Two vectors are
collinear if they run parallel to each other and point in the same
direction.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is collinear to AOther (within the given tolerance) }
method IsCollinear(const AOther: TVector2; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is opposite collinear with another vector. Two vectors
are opposite collinear if they run parallel to each other and point in
opposite directions.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is opposite collinear to AOther (within the given
tolerance) }
method IsCollinearOpposite(const AOther: TVector2; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is perpendicular to another vector.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is perpendicular to AOther. That is, if the dot
product is 0 (within the given tolerance) }
method IsPerpendicular(const AOther: TVector2; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Returns the components of the vector.
This is identical to accessing the C-field, but this property can be used
as a default array property.
{ The euclidean length of this vector.
@bold(Note): If you only want to compare lengths of vectors, you should
use LengthSquared instead, which is faster.
@bold(Note): You can also set the length of the vector. In that case, it
will keep the current direction. }
property Length: Single read GetLength write SetLength;
{ The squared length of the vector.
@bold(Note): This property is faster than Length because it avoids
calculating a square root. It is useful for comparing lengths instead of
calculating actual lengths.
@bold(Note): You can also set the squared length of the vector. In that
case, it will keep the current direction. }
property LengthSquared: Single read GetLengthSquared write SetLengthSquared;
{ The angle in radians of this vector/point relative to the X-axis. Angles
are towards the positive Y-axis (counter-clockwise).
When getting the angle, the result will be between -Pi and Pi. }
property Angle: Single read GetAngle write SetAngle;
public
X,Y : Single;
property R : Single read X write X;
property G : Single read X write X;
property S : Single read X write X;
property T : Single read X write X;
{ Parameters:
AIndex: index of the component to return (0 or 1). Range is checked
with an assertion. }
property C[const AIndex: Integer]: Single read GetComponent write SetComponent; default;
// Union :
// { X and Y components of the vector. Aliases for C[0] and C[1]. }
// 0: (X, Y: Single);
//
// { Red and Green components of the vector. Aliases for C[0] and C[1]. }
// 1: (R, G: Single);
//
// { S and T components of the vector. Aliases for C[0] and C[1]. }
// 2: (S, T: Single);
//
// { The two components of the vector. }
// 3: (C: array [0..1] of Single);
end;
implementation
{ TVector2 }
class operator TVector2.Add(const A: TVector2; const B: Single): TVector2;
begin
Result.X := A.X + B;
Result.Y := A.Y + B;
end;
class operator TVector2.Add(const A: Single; const B: TVector2): TVector2;
begin
Result.X := A + B.X;
Result.Y := A + B.Y;
end;
class operator TVector2.Add(const A, B: TVector2): TVector2;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
method TVector2.Distance(const AOther: TVector2): Single;
begin
Result := (Self - AOther).Length;
end;
method TVector2.DistanceSquared(const AOther: TVector2): Single;
begin
Result := (Self - AOther).LengthSquared;
end;
class operator TVector2.Divide(const A: TVector2; const B: Single): TVector2;
var
InvB: Single;
begin
InvB := 1 / B;
Result.X := A.X * InvB;
Result.Y := A.Y * InvB;
end;
class operator TVector2.Divide(const A: Single; const B: TVector2): TVector2;
begin
Result.X := A / B.X;
Result.Y := A / B.Y;
end;
class operator TVector2.Divide(const A, B: TVector2): TVector2;
begin
Result.X := A.X / B.X;
Result.Y := A.Y / B.Y;
end;
method TVector2.Dot(const AOther: TVector2): Single;
begin
Result := (X * AOther.X) + (Y * AOther.Y);
end;
method TVector2.FaceForward(const I, NRef: TVector2): TVector2;
begin
if (NRef.Dot(I) < 0) then
Result := Self
else
Result := -Self;
end;
method TVector2.GetLength: Single;
begin
Result := Sqrt((X * X) + (Y * Y));
end;
method TVector2.GetLengthSquared: Single;
begin
Result := (X * X) + (Y * Y);
end;
class operator TVector2.Multiply(const A: TVector2; const B: Single): TVector2;
begin
Result.X := A.X * B;
Result.Y := A.Y * B;
end;
class operator TVector2.Multiply(const A: Single; const B: TVector2): TVector2;
begin
Result.X := A * B.X;
Result.Y := A * B.Y;
end;
class operator TVector2.Multiply(const A, B: TVector2): TVector2;
begin
Result.X := A.X * B.X;
Result.Y := A.Y * B.Y;
end;
method TVector2.NormalizeFast: TVector2;
begin
Result := Self * InverseSqrt(Self.LengthSquared);
end;
method TVector2.Reflect(const N: TVector2): TVector2;
begin
Result := Self - ((2 * N.Dot(Self)) * N);
end;
method TVector2.Refract(const N: TVector2; const Eta: Single): TVector2;
var
D, K: Single;
begin
D := N.Dot(Self);
K := 1 - Eta * Eta * (1 - D * D);
if (K < 0) then
Result.Init
else
Result := (Eta * Self) - ((Eta * D + Sqrt(K)) * N);
end;
method TVector2.SetNormalizedFast;
begin
Self := Self * InverseSqrt(Self.LengthSquared);
end;
class operator TVector2.Subtract(const A: TVector2; const B: Single): TVector2;
begin
Result.X := A.X - B;
Result.Y := A.Y - B;
end;
class operator TVector2.Subtract(const A: Single; const B: TVector2): TVector2;
begin
Result.X := A - B.X;
Result.Y := A - B.Y;
end;
class operator TVector2.Subtract(const A, B: TVector2): TVector2;
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
{ TVector2 }
method TVector2.AngleTo(const ATarget: TVector2): Single;
begin
Result := ArcTan2(Cross(ATarget), Dot(ATarget));
end;
method TVector2.Clamp(const AMinLength, AMaxLength: Single): TVector2;
var
LenSq, EdgeSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq = 0) then
Exit(Self);
EdgeSq := AMaxLength * AMaxLength;
if (LenSq > EdgeSq) then
Exit(Self * Sqrt(EdgeSq / LenSq));
EdgeSq := AMinLength * AMinLength;
if (LenSq < EdgeSq) then
Exit(Self * Sqrt(EdgeSq / LenSq));
Result := Self;
end;
method TVector2.Cross(const AOther: TVector2): Single;
begin
Result := (X * AOther.Y) - (Y * AOther.X);
end;
class operator TVector2.Equal(const A, B: TVector2): Boolean;
begin
Result := (A.X = B.X) and (A.Y = B.Y);
end;
method TVector2.Equals(const AOther: TVector2; const ATolerance: Single): Boolean;
begin
Result := (Abs(X - AOther.X) <= ATolerance)
and (Abs(Y - AOther.Y) <= ATolerance);
end;
method TVector2.GetAngle: Single;
begin
Result := ArcTan2(Y, X)
end;
method TVector2.GetComponent(const AIndex: Integer): Single;
begin
if AIndex = 0 then exit X else exit Y;
end;
method TVector2.HasSameDirection(const AOther: TVector2): Boolean;
begin
Result := (Dot(AOther) > 0);
end;
method TVector2.HasOppositeDirection(const AOther: TVector2): Boolean;
begin
Result := (Dot(AOther) < 0);
end;
method TVector2.Init;
begin
X := 0;
Y := 0;
end;
method TVector2.Init(const A: Single);
begin
X := A;
Y := A;
end;
method TVector2.Init(const A1, A2: Single);
begin
X := A1;
Y := A2;
end;
method TVector2.IsCollinear(const AOther: TVector2; const ATolerance: Single): Boolean;
begin
Result := IsParallel(AOther, ATolerance) and (Dot(AOther) > 0);
end;
method TVector2.IsCollinearOpposite(const AOther: TVector2; const ATolerance: Single): Boolean;
begin
Result := IsParallel(AOther, ATolerance) and (Dot(AOther) < 0);
end;
method TVector2.IsNormalized: Boolean;
begin
Result := IsNormalized(0.000000001);
end;
method TVector2.IsNormalized(const AErrorMargin: Single): Boolean;
begin
Result := (Abs(LengthSquared - 1.0) < AErrorMargin);
end;
method TVector2.IsParallel(const AOther: TVector2; const ATolerance: Single): Boolean;
begin
Result := (Abs(X * AOther.Y - Y * AOther.X) <= ATolerance);
end;
method TVector2.IsPerpendicular(const AOther: TVector2; const ATolerance: Single): Boolean;
begin
Result := (Abs(Dot(AOther)) <= ATolerance);
end;
method TVector2.IsZero: Boolean;
begin
Result := (X = 0) and (Y = 0);
end;
method TVector2.IsZero(const AErrorMargin: Single): Boolean;
begin
Result := (LengthSquared < AErrorMargin);
end;
method TVector2.Lerp(const ATarget: TVector2; const AAlpha: Single): TVector2;
begin
Result := Mix(Self, ATarget, AAlpha);
end;
method TVector2.Limit(const AMaxLength: Single): TVector2;
begin
Result := LimitSquared(AMaxLength * AMaxLength);
end;
method TVector2.LimitSquared(const AMaxLengthSquared: Single): TVector2;
var
LenSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq > AMaxLengthSquared) then
Result := Self * Sqrt(AMaxLengthSquared / LenSq)
else
Result := Self;
end;
class operator TVector2.Minus(const A: TVector2): TVector2;
begin
Result.X := -A.X;
Result.Y := -A.Y;
end;
method TVector2.Normalize: TVector2;
begin
Result := Self / Length;
end;
class operator TVector2.NotEqual(const A, B: TVector2): Boolean;
begin
Result := (A.X <> B.X) or (A.Y <> B.Y);
end;
method TVector2.Offset(const ADeltaX, ADeltaY: Single);
begin
X := X + ADeltaX;
Y := Y + ADeltaY;
end;
method TVector2.Offset(const ADelta: TVector2);
begin
Self := Self + ADelta;
end;
method TVector2.Rotate(const ARadians: Single): TVector2;
var
lS, lC: Single;
begin
SinCos(ARadians, out lS, out lC);
Result.X := (X * lC) - (Y * lS);
Result.Y := (X * lS) + (Y * lC);
end;
method TVector2.Rotate90CCW: TVector2;
begin
Result.X := -Y;
Result.Y := X;
end;
method TVector2.Rotate90CW: TVector2;
begin
Result.X := Y;
Result.Y := -X;
end;
method TVector2.SetLerp(const ATarget: TVector2; const AAlpha: Single);
begin
Self := Mix(Self, ATarget, AAlpha);
end;
method TVector2.SetNormalized;
begin
Self := Self / Length;
end;
method TVector2.SetRotated90CCW;
begin
Self := Rotate90CCW;
end;
method TVector2.SetRotated90CW;
begin
Self := Rotate90CW;
end;
method TVector2.SetAngle(const AValue: Single);
begin
X := Length;
Y := 0;
SetRotated(AValue);
end;
method TVector2.SetClamped(const AMinLength, AMaxLength: Single);
begin
Self := Clamp(AMinLength, AMaxLength);
end;
method TVector2.SetComponent(const AIndex: Integer; const Value: Single);
begin
if AIndex = 0 then X := Value else Y := Value;
end;
method TVector2.SetLength(const AValue: Single);
begin
setLengthSquared(AValue * AValue);
end;
method TVector2.SetLengthSquared(const AValue: Single);
var
LenSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq <> 0) and (LenSq <> AValue) then
Self := Self * Sqrt(AValue / LenSq);
end;
method TVector2.SetLimit(const AMaxLength: Single);
begin
Self := LimitSquared(AMaxLength * AMaxLength);
end;
method TVector2.SetLimitSquared(const AMaxLengthSquared: Single);
begin
Self := LimitSquared(AMaxLengthSquared);
end;
method TVector2.SetRotated(const ARadians: Single);
begin
Self := Rotate(ARadians);
end;
end. |
unit LoginBusiness;
interface
function LoginUser(username, password : String) : Boolean;
implementation
uses
SimpleDS, Hash, DatabaseConnection, GlobalObjects, UserBusiness, TypInfo,
SysUtils;
function QueryUser(username, password : string) : TSimpleDataset;
const
FindUserQuery = 'SELECT id ' +
'FROM users '+
'WHERE username = :username AND '+
'password = :password';
var
queryParams : TSqlParams;
begin
queryParams := TSqlParams.Create;
queryParams.AddString('username', username);
queryParams.AddString('password', getsha256(password));
Result := DbConnection.ExecuteSelect(FindUserQuery, queryParams);
FreeAndNil(queryParams);
end;
function LoginUser(username, password : String) : Boolean;
var
userQueryResult : TSimpleDataSet;
userId : String;
begin
userQueryResult := QueryUser(username, password);
if not Assigned(userQueryResult) then
begin
WriteLog('System has failed to get user information during login');
Result := False;
Exit;
end;
Result := True;
if userQueryResult.RecordCount = 0 then
begin
Result := False;
end;
userId := userQueryResult.FieldByName('id').AsString;
LoggedUser := GetUser(userId);
if not Assigned(LoggedUser) then
begin
WriteLog('The system has failed to load the logged user with id "%s"', [userId]);
Result := False;
end;
FreeAndNil(userQueryResult);
end;
end.
|
PROGRAM SortAlg;
// === STATS ===
VAR
assCount, compCount: LONGINT;
PROCEDURE ResetStats;
BEGIN
assCount := 0;
compCount := 0;
END;
PROCEDURE PrintStats;
BEGIN
WriteLn('A = ', assCount, ' / C = ', compCount, ' / T = ', assCount + compCount);
END;
FUNCTION LT(a, b: LONGINT): BOOLEAN;
BEGIN
compCount := compCount + 1;
LT := a < b;
END;
PROCEDURE Assign(VAR dest: LONGINT; src: LONGINT);
BEGIN
assCount := assCount + 1;
dest := src;
END;
PROCEDURE Swap(VAR a, b: LONGINT);
VAR
h: LONGINT;
BEGIN
assCount := assCount + 3;
h := a;
a := b;
b := h;
END;
PROCEDURE DisplayArray(arr: Array of Longint);
VAR
i: Longint;
BEGIN
FOR i := Low(arr) TO High(arr) DO
Write(arr[i], ' ');
WriteLn();
END;
// === ALGORITHMS ===
// F(n) = n - 1 * (n+n+1) -> n^2 € O(n^2)
PROCEDURE InsertionSort(VAR arr: Array of LONGINT);
VAR
i, j: LONGINT; // Laufvariablen
h: LONGINT; // Inhalt
BEGIN
FOR i := Low(arr) TO High(arr) - 1 DO BEGIN
Assign(h, arr[i + 1]);
j := i;
WriteLn('1. i: ', i, ' j: ', j, ' h: ', h);
ReadLn();
WHILE (j >= Low(arr)) AND LT(h, arr[j]) DO
BEGIN
WriteLn('2. i: ', i, ' j: ', j, ' h: ', h);
DisplayArray(arr);
Assign(arr[j + 1], arr[j]);
ReadLn();
DisplayArray(arr);
Dec(j);
END;
WriteLn(j);
Assign(arr[j + 1], h);
END;
END;
// F(n) = n - 1 * (n/2 + 3) = n^2 € O(n^2)
PROCEDURE SelectionSort(VAR arr: Array of LONGINT);
VAR
i, j, minPos: LONGINT;
BEGIN
FOR i := Low(arr) TO High(arr) - 1 DO
BEGIN
minPos := i;
FOR j := i + 1 TO High(arr) DO
IF LT(arr[j], arr[minPos]) THEN
minPos := j;
Swap(arr[i], arr[minPos]);
END;
END;
// F(n) = n*(n+1) = n^2 + 1 € O(n^2)
PROCEDURE BubbleSort(VAR arr: Array of LONGINT);
VAR
i: LONGINT;
noSwaps: BOOLEAN;
BEGIN
repeat
noSwaps := true;
FOR i := Low(arr) TO High(arr) - 1 DO
BEGIN
IF LT(arr[i + 1], arr[i]) THEN BEGIN
Swap(arr[i + 1], arr[i]);
noSwaps := false;
END;
END;
until noSwaps;
END;
PROCEDURE CombSort(VAR arr: Array of LONGINT);
VAR
i: LONGINT;
noSwaps: BOOLEAN;
gap: LONGINT;
BEGIN
gap := High(arr) - Low(arr) + 1;
repeat
gap := ( gap * 10 ) DIV 13;
IF gap = 0 then
gap := 1;
noSwaps := true;
FOR i := Low(arr) TO High(arr) - gap DO
BEGIN
IF LT(arr[i + gap], arr[i]) THEN BEGIN
Swap(arr[i + gap], arr[i]);
noSwaps := false;
END;
END;
until noSwaps AND (gap = 1);
END;
PROCEDURE ShellSort(VAR arr: Array of LONGINT);
VAR
i, j, m: LONGINT; // Laufvariablen
h: LONGINT; // Inhalt
BEGIN
m := (High(arr) - Low(arr) + 1) DIV 2;
WHILE m > 0 DO BEGIN
FOR i := Low(arr) TO High(arr) - m DO BEGIN
Assign(h, arr[i + m]);
j := i;
WHILE (j >= Low(arr)) AND LT(h, arr[j]) DO
BEGIN
Assign(arr[j + m], arr[j]);
j := j - m;
END;
Assign(arr[j + m], h);
END;
m := m DIV 2;
END;
END;
// O(n * ld(n))
PROCEDURE QuickSort(VAR arr: Array of LONGINT);
PROCEDURE Sort(left, right: LONGINT);
VAR
i, j: LONGINT;
m: LONGINT;
BEGIN
i := left;
j := right;
m := arr[(right + left) DIV 2];
repeat
WHILE LT (arr[i], m) DO Inc(i);
WHILE LT (m, arr[j]) DO Dec(j);
IF (i <= j) THEN begin
Swap(arr[i], arr[j]);
Inc(i);
Dec(j);
end;
until i > j;
IF j > left then
Sort(left, j);
IF i < right then
Sort(i, right);
END;
BEGIN
Sort(Low(arr), High(arr));
END;
// Kleine Anzahl an Einträgen werden von anderen Sorts schneller sortiert
PROCEDURE BetterQuickSort(VAR arr: Array of LONGINT);
PROCEDURE Sort(left, right: LONGINT);
VAR
i, j: LONGINT;
m: LONGINT;
BEGIN
IF (j - i) > 40 THEN BEGIN
// do quicksort
END else BEGIN
// short part left --> sort with a classic algorithm here
END;
i := left;
j := right;
m := arr[(right + left) DIV 2];
repeat
WHILE LT (arr[i], m) DO Inc(i);
WHILE LT (m, arr[j]) DO Dec(j);
IF (i <= j) THEN begin
Swap(arr[i], arr[j]);
Inc(i);
Dec(j);
end;
until i > j;
IF j > left then
Sort(left, j);
IF i < right then
Sort(i, right);
END;
BEGIN
Sort(Low(arr), High(arr));
END;
// === TEST ===
PROCEDURE FillArray(VAR arr: ARRAY OF LONGINT);
VAR
i: LONGINT;
BEGIN
RandSeed := 12345;
FOR i := Low(arr) TO High(arr) DO
arr[i] := Random(10) + 1;
END;
VAR
a: ARRAY[1..10] OF LONGINT;
BEGIN
WriteLn('------ SelectionSort ------ ');
ResetStats; FillArray(a);
// DisplayArray(a);
SelectionSort(a);
// DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
WriteLn('------ InsertionSort ------');
ResetStats; FillArray(a);
// DisplayArray(a);
InsertionSort(a);
// DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
WriteLn('------ BubbleSort ------');
ResetStats; FillArray(a);
// DisplayArray(a);
BubbleSort(a);
DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
WriteLn('------ ShellSort ------');
ResetStats; FillArray(a);
// DisplayArray(a);
ShellSort(a);
// DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
WriteLn('------ CombSort ------');
ResetStats; FillArray(a);
// DisplayArray(a);
CombSort(a);
// DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
WriteLn('------ QuickSort ------');
ResetStats; FillArray(a);
// DisplayArray(a);
QuickSort(a);
// DisplayArray(a);
PrintStats;
WriteLn();
WriteLn();
END. |
{
Conversion of /usr/include/asm-generic/ioctl.h
1.0 - 2019.04.24 - Nicola Perotto <nicola@nicolaperotto.it>
}
{$I+,R+,Q+,H+}
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
Unit IOCtl;
Interface
Const
_IOC_NRBITS = 8;
_IOC_TYPEBITS = 8;
_IOC_SIZEBITS = 14;
_IOC_DIRBITS = 2;
_IOC_NRMASK = (1 shl _IOC_NRBITS) -1;
_IOC_TYPEMASK = (1 shl _IOC_TYPEBITS) -1;
_IOC_SIZEMASK = (1 shl _IOC_SIZEBITS) -1;
_IOC_DIRMASK = (1 shl _IOC_DIRBITS) -1;
_IOC_NRSHIFT = 0;
_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS;
_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS;
_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS;
_IOC_NONE = 0; //U
_IOC_WRITE = 1; //U
_IOC_READ = 2; //U
//You have to do it manually because Pascal lacks the C Pre-Processor!
//the constant generated is 32 bits
{
_IOC(dir, type, nr, size) := (dir shl _IOC_DIRSHIFT) or (type shl _IOC_TYPESHIFT) or (nr shl _IOC_NRSHIFT) or (size shl _IOC_SIZESHIFT);
_IO(type, nr) := _IOC(_IOC_NONE, type, nr, 0);
_IOR(type, nr, size) := _IOC(_IOC_READ, type, nr, size);
_IOW(type, nr, size) := _IOC(_IOC_WRITE, type, nr, size);
_IOWR(type, nr, size) := _IOC(_IOC_READ or _IOC_WRITE, type, nr, size);
_IOR_BAD(type, nr, size) := _IOC(_IOC_READ, type, nr, sizeof(size));
_IOW_BAD(type, nr, size) := _IOC(_IOC_WRITE, type, nr, sizeof(size));
_IOWR_BAD(type, nr, size) := _IOC(_IOC_READ or _IOC_WRITE, type, nr, sizeof(size));
}
//* used to decode ioctl numbers.. */
//_IOC_DIR(nr) := (((nr) shr _IOC_DIRSHIFT) and _IOC_DIRMASK);
//_IOC_TYPE(nr) := (((nr) shr _IOC_TYPESHIFT) and _IOC_TYPEMASK);
//_IOC_NR(nr) := (((nr) shr _IOC_NRSHIFT) and _IOC_NRMASK);
//_IOC_SIZE(nr) := (((nr) shr _IOC_SIZESHIFT) and _IOC_SIZEMASK);
//* ...and for the drivers/sound files... */
Const
IOC_IN = _IOC_WRITE shl _IOC_DIRSHIFT;
IOC_OUT = _IOC_READ shl _IOC_DIRSHIFT;
IOC_INOUT = (_IOC_WRITE or _IOC_READ) shl _IOC_DIRSHIFT;
IOCSIZE_MASK = _IOC_SIZEMASK or _IOC_SIZESHIFT;
IOCSIZE_SHIFT = _IOC_SIZESHIFT;
//example:
//#define EVIOCGVERSION _IOR('E', 0x01, int) /* get driver version */
// EVIOCGVERSION = (_IOC_READ shl _IOC_DIRSHIFT) or (Ord('E') shl _IOC_TYPESHIFT) or (1 shl _IOC_NRSHIFT) or (SizeOf(Integer) shl _IOC_SIZESHIFT);
Type //this is to check the parameters at compile time and skip at runtime!
EIOCTLDir = 0..(1 shl _IOC_DIRBITS) -1;
EIOCTLType = 0..(1 shl _IOC_TYPEBITS) -1;
EIOCTLNumber = 0..(1 shl _IOC_NRBITS) -1;
EIOCTLSize = 0..(1 shl _IOC_SIZEBITS) -1;
//TIOCtlRequest = cInt;
Function Compose_IOC(Const aDir:EIOCTLDir; Const aType:EIOCTLType; Const aNumber:EIOCTLNumber; Const aSize:EIOCTLSize):Integer;
Implementation
Function Compose_IOC(Const aDir:EIOCTLDir; Const aType:EIOCTLType; Const aNumber:EIOCTLNumber; Const aSize:EIOCTLSize):Integer;
begin //uses typecast because of range
Result := Integer((aDir shl _IOC_DIRSHIFT) or (aType shl _IOC_TYPESHIFT) or (aNumber shl _IOC_NRSHIFT) or (aSize shl _IOC_SIZESHIFT));
end; //Compose_IOC
end.
|
unit Render2;
interface
uses
SysUtils, Types, Graphics,
Style, Render;
type
TCustomRenderer = class
private
Blocks: TBoxList;
Canvas: TCanvas;
Pen: TPoint;
Width: Integer;
protected
function GetContextRect(inBlock: TBox): TRect;
procedure RenderBlock(inBlock: TBox); virtual;
procedure RenderBlocks;
public
constructor Create;
destructor Destroy; override;
procedure Render(inBlocks: TBoxList; inCanvas: TCanvas; inRect: TRect);
end;
//
TBlockRenderer = class(TCustomRenderer)
protected
procedure RenderBlock(inBlock: TBox); override;
end;
//
TInlineRenderer = class(TCustomRenderer)
protected
procedure RenderBlock(inBlock: TBox); override;
end;
//
TCustomNode = class(TNode)
protected
function CreateRenderer: TCustomRenderer; virtual; abstract;
procedure Paint(inCanvas: TCanvas; inRect: TRect); virtual;
public
procedure Render(inBox: TBox; inCanvas: TCanvas;
inRect: TRect);
end;
//
TNodeClass = class of TCustomNode;
//
TBlockContextNode = class(TCustomNode)
protected
function CreateRenderer: TCustomRenderer; override;
end;
//
TInlineContextNode = class(TCustomNode)
protected
function CreateRenderer: TCustomRenderer; override;
end;
procedure TestBlockRenderer(inCanvas: TCanvas; inRect: TRect);
implementation
function BuildBlock(inClass: TNodeClass; inW, inH: Integer): TBox;
function rc: Integer;
begin
Result := Random(192) + 64;
end;
begin
Result := TBox.Create;
Result.Width := inW;
Result.Height := inH;
Result.Node := inClass.Create;
Result.Node.Style.BackgroundColor := (rc shl 16) + (rc shl 8) + rc;
Result.Node.Text := 'Box ' + IntToStr(Random(255));
end;
function BuildBlocks(inClass: TNodeClass; inCount, inW, inH: Integer): TBoxList;
var
i: Integer;
begin
Result := TBoxList.Create;
for i := 1 to inCount do
Result.Add(BuildBlock(inClass, inW, inH));
end;
function BuildTestBlocks: TBoxList;
begin
RandSeed := 234535;
Result := TBoxList.Create;
Result.Add(BuildBlock(TBlockContextNode, 500, 100));
Result.Add(BuildBlock(TBlockContextNode, 500, 100));
Result.Add(BuildBlock(TBlockContextNode, 500, 100));
// Result[2].Boxes := BuildBlocks(TBlockContextNode, 3, 500, 20);
Result.Add(BuildBlock(TInlineContextNode, 500, 100));
Result[3].Boxes := BuildBlocks(TBlockContextNode, 3, 50, 20);
Result.Add(BuildBlock(TBlockContextNode, 500, 100));
// Result[4].Boxes := BuildBlocks(TBlockContextNode, 5, 500, 20);
Result.Add(BuildBlock(TBlockContextNode, 500, 100));
end;
procedure TestBlockRenderer(inCanvas: TCanvas; inRect: TRect);
var
r: TBlockRenderer;
b: TBoxList;
begin
r := TBlockRenderer.Create;
try
b := BuildTestBlocks;
try
r.Render(b, inCanvas, inRect);
finally
b.Free;
end;
finally
r.Free;
end;
end;
{ TCustomRenderer }
constructor TCustomRenderer.Create;
begin
end;
destructor TCustomRenderer.Destroy;
begin
inherited;
end;
procedure TCustomRenderer.RenderBlocks;
var
i: Integer;
begin
for i := 0 to Blocks.Max do
RenderBlock(Blocks[i]);
end;
function TCustomRenderer.GetContextRect(inBlock: TBox): TRect;
begin
with inBlock do
Result := Rect(Left, Top, Left + Width, Top + Height);
OffsetRect(Result, Pen.X, Pen.Y);
end;
procedure TCustomRenderer.RenderBlock(inBlock: TBox);
begin
TCustomNode(inBlock.Node).Render(inBlock, Canvas, GetContextRect(inBlock));
end;
procedure TCustomRenderer.Render(inBlocks: TBoxList; inCanvas: TCanvas; inRect: TRect);
begin
Blocks := inBlocks;
Canvas := inCanvas;
Width := inRect.Right - inRect.Left;
Pen := Point(inRect.Left, inRect.Top);
RenderBlocks;
end;
{ TBlockRenderer }
procedure TBlockRenderer.RenderBlock(inBlock: TBox);
begin
inherited;
Inc(Pen.Y, inBlock.Height);
end;
{ TInlineRenderer }
procedure TInlineRenderer.RenderBlock(inBlock: TBox);
begin
inherited;
Inc(Pen.X, inBlock.Width);
end;
{ TCustomNode }
procedure TCustomNode.Paint(inCanvas: TCanvas; inRect: TRect);
begin
if (Style.BackgroundColor <> clDefault) then
begin
inCanvas.Brush.Style := bsSolid;
inCanvas.Brush.Color := Style.BackgroundColor;
inCanvas.FillRect(inRect);
end;
if (Style.Color <> clDefault) then
inCanvas.Font.Color := Style.Color;
inCanvas.TextOut(inRect.Left, inRect.Top, Text);
inCanvas.Brush.Style := bsClear;
inCanvas.Rectangle(inRect);
end;
procedure TCustomNode.Render(inBox: TBox; inCanvas: TCanvas; inRect: TRect);
procedure RenderBoxes;
begin
if (inBox.Boxes.Count > 0) then
with CreateRenderer do
try
Render(inBox.Boxes, inCanvas, inRect);
finally
Free;
end;
end;
begin
Paint(inCanvas, inRect);
RenderBoxes;
end;
{ TBlockContextNode }
function TBlockContextNode.CreateRenderer: TCustomRenderer;
begin
Result := TBlockRenderer.Create;
end;
{ TInlineContextNode }
function TInlineContextNode.CreateRenderer: TCustomRenderer;
begin
Result := TInlineRenderer.Create;
end;
end.
|
unit o_SendMail;
interface
uses
SysUtils, Classes,
IdMessage, IdPOP3, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, Vcl.StdCtrls, IdIOHandler,
IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdGlobal;
type
TSendMail = class(TObject)
private
FSmtp: TIdSMTP;
FMsg: TIdMessage;
FIOHandler: TIdSSLIOHandlerSocketOpenSSL;
FMeineEmail: string;
FMeinPasswort: string;
FBetreff: string;
FNachricht: string;
FEMailAdresse: string;
procedure VersendeEMail;
public
constructor Create;
destructor Destroy; override;
property MeineEMail: string read FMeineEmail write FMeineEMail;
property MeinPasswort: string read FMeinPasswort write FMeinPasswort;
property Betreff: string read FBetreff write FBetreff;
property Nachricht: string read FNachricht write FNachricht;
property EMailAdresse: string read FEMailAdresse write FEMailAdresse;
procedure SendenUeberWebDe;
procedure SendenUeberGMail;
end;
implementation
{ TSendMail }
constructor TSendMail.Create;
begin
inherited;
FSmtp := TIdSMTP.Create(nil);
FMsg := TIdMessage.Create(nil);
FIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
FSmtp.IOHandler := FIOHandler;
FMeineEmail := '';
FMeinPasswort := '';
FBetreff := '';
FNachricht := '';
FEMailAdresse := '';
end;
destructor TSendMail.Destroy;
begin
FreeAndNil(FSmtp);
FreeAndNil(FMsg);
FreeAndNil(FIOHandler);
inherited;
end;
procedure TSendMail.SendenUeberGMail;
begin
Fsmtp.Host := 'smtp.gmail.com';
Fsmtp.Password := FMeinPasswort;
Fsmtp.Port := 587;
Fsmtp.UseTLS := utUseExplicitTLS;
Fsmtp.Username := FMeineEmail;
FIOHandler.Destination := 'smtp.gmail.com:587';
FIOHandler.Host := 'smtp.gmail.com';
FIOHandler.MaxLineAction := maException;
FIOHandler.Port := 587;
FIOHandler.SSLOptions.Method := ssLvTlSv1;
FIOHandler.SSLOptions.Mode := sslmUnassigned;
FIOHandler.SSLOptions.VerifyMode := [];
FIOHandler.SSLOptions.VerifyDepth := 0;
VersendeEMail;
end;
procedure TSendMail.SendenUeberWebDe;
begin
Fsmtp.Host := 'smtp.web.de';
Fsmtp.Password := FMeinPasswort;
Fsmtp.Port := 587;
Fsmtp.UseTLS := utUseExplicitTLS;
Fsmtp.Username := FMeineEmail;
FIOHandler.Destination := 'smtp.web.de:587';
FIOHandler.Host := 'smtp.web.de';
FIOHandler.MaxLineAction := maException;
FIOHandler.Port := 587;
FIOHandler.SSLOptions.Method := ssLvTlSv1;
FIOHandler.SSLOptions.Mode := sslmUnassigned;
FIOHandler.SSLOptions.VerifyMode := [];
FIOHandler.SSLOptions.VerifyDepth := 0;
VersendeEMail;
end;
procedure TSendMail.VersendeEMail;
begin
FMsg.From.Address := FMeineEmail;
FMsg.Recipients.EMailAddresses := FEMailAdresse;
FMsg.Body.Add(FNachricht);
FMsg.Subject := FBetreff;
Fsmtp.Connect;
Fsmtp.Send(FMsg);
Fsmtp.Disconnect;
end;
end.
|
namespace GlHelper;
interface
uses
rtl;
type
{ A 3-dimensional vector. Can be used for a variety of purposes:
* To represent points or vectors in 3D space, using the X, Y and Z fields.
* To represent colors (using the R, G and B fields, which are just aliases
for X, Y and Z)
* To represent texture coordinates (S, T and P, again just aliases for X, Y
and Z).
* To group 3 arbitrary values together in an array (C[0]..C[2], also just
aliases for X, Y and Z)
@bold(Note): when possible, use TVector4 instead of TVector3, since TVector4
has better hardware support. Operations on TVector4 types are usually faster
than operations on TVector3 types.
}
TVector3 = public record
{$REGION 'Internal Declarations'}
private
method GetComponent(const AIndex: Integer): Single;
method SetComponent(const AIndex: Integer; const Value: Single);
method GetLength: Single;
method SetLength(const AValue: Single);
method GetLengthSquared: Single;
method SetLengthSquared(const AValue: Single);
{$ENDREGION 'Internal Declarations'}
public
constructor (const A1, A2, A3: Single);
class method Vector3(const A1, A2, A3: Single): TVector3;
{ Sets the three elements (X, Y and Z) to 0. }
method Init;
{ Sets the three elements (X, Y and Z) to A.
Parameters:
A: the value to set the three elements to. }
method Init(const A: Single);
{ Sets the three elements (X, Y and Z) to A1, A2 and A3 respectively.
Parameters:
A1: the value to set the first element to.
A2: the value to set the second element to.
A3: the value to set the third element to. }
method Init(const A1, A2, A3: Single);
{ Sets the first two elements from a 2D vector, and the third element from
a scalar.
Parameters:
A1: the vector to use for the first two elements.
A2: the value to set the third element to. }
method Init(const A1: TVector2; const A2: Single);
{ Sets the first element from a scaler, and the last two elements from a
2D vector.
Parameters:
A1: the value to set the first element to.
A2: the vector to use for the last two elements. }
method Init(const A1: Single; const A2: TVector2);
{ Checks two vectors for equality.
Returns:
True if the two vectors match each other exactly. }
class operator Equal(const A, B: TVector3): Boolean; inline;
{ Checks two vectors for inequality.
Returns:
True if the two vectors are not equal. }
class operator NotEqual(const A, B: TVector3): Boolean; inline;
{ Negates a vector.
Returns:
The negative value of a vector (eg. (-A.X, -A.Y, -A.Z)) }
class operator Minus(const A: TVector3): TVector3; inline;
{ Adds a scalar value to a vector.
Returns:
(A.X + B, A.Y + B, A.Z + B) }
class operator Add(const A: TVector3; const B: Single): TVector3; inline;
{ Adds a vector to a scalar value.
Returns:
(A + B.X, A + B.Y, A + B.Z) }
class operator Add(const A: Single; const B: TVector3): TVector3; inline;
{ Adds two vectors.
Returns:
(A.X + B.X, A.Y + B.Y, A.Z + B.Z) }
class operator Add(const A, B: TVector3): TVector3; inline;
{ Subtracts a scalar value from a vector.
Returns:
(A.X - B, A.Y - B, A.Z - B) }
class operator Subtract(const A: TVector3; const B: Single): TVector3;inline;
{ Subtracts a vector from a scalar value.
Returns:
(A - B.X, A - B.Y, A - B.Z) }
class operator Subtract(const A: Single; const B: TVector3): TVector3; inline;
{ Subtracts two vectors.
Returns:
(A.X - B.X, A.Y - B.Y, A.Z - B.Z) }
class operator Subtract(const A, B: TVector3): TVector3; inline;
{ Multiplies a vector with a scalar value.
Returns:
(A.X * B, A.Y * B, A.Z * B) }
class operator Multiply(const A: TVector3; const B: Single): TVector3; inline;
{ Multiplies a scalar value with a vector.
Returns:
(A * B.X, A * B.Y, A * B.Z) }
class operator Multiply(const A: Single; const B: TVector3): TVector3; inline;
{ Multiplies two vectors component-wise.
To calculate a dot or cross product instead, use the Dot or Cross function.
Returns:
(A.X * B.X, A.Y * B.Y, A.Z * B.Z) }
class operator Multiply(const A, B: TVector3): TVector3; inline;
{ Divides a vector by a scalar value.
Returns:
(A.X / B, A.Y / B, A.Z / B) }
class operator Divide(const A: TVector3; const B: Single): TVector3; inline;
{ Divides a scalar value by a vector.
Returns:
(A / B.X, A / B.Y, A / B.Z) }
class operator Divide(const A: Single; const B: TVector3): TVector3; inline;
{ Divides two vectors component-wise.
Returns:
(A.X / B.X, A.Y / B.Y, A.Z / B.Z) }
class operator Divide(const A, B: TVector3): TVector3; inline;
{ Whether this vector equals another vector, within a certain tolerance.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if both vectors are equal (within the given tolerance). }
method Equals(const AOther: TVector3; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Calculates the distance between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The distance between this vector and AOther.
@bold(Note): If you only want to compare distances, you should use
DistanceSquared instead, which is faster. }
method Distance(const AOther: TVector3): Single;
{ Calculates the squared distance between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The squared distance between this vector and AOther. }
method DistanceSquared(const AOther: TVector3): Single;
{ Calculates the dot product between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The dot product between this vector and AOther. }
method Dot(const AOther: TVector3): Single;
{ Calculates the cross product between this vector and another vector.
Parameters:
AOther: the other vector.
Returns:
The cross product between this vector and AOther. }
method Cross(const AOther: TVector3): TVector3;
{ Offsets this vector in a certain direction.
Parameters:
ADeltaX: the delta X direction.
ADeltaY: the delta Y direction.
ADeltaZ: the delta Z direction. }
method Offset(const ADeltaX, ADeltaY, ADeltaZ: Single);
{ Offsets this vector in a certain direction.
Parameters:
ADelta: the delta.
@bold(Note): this is equivalent to adding two vectors together. }
method Offset(const ADelta: TVector3);
{ Calculates a normalized version of this vector.
Returns:
The normalized version of of this vector. That is, a vector in the same
direction as A, but with a length of 1.
@bold(Note): for a faster, less accurate version, use NormalizeFast.
@bold(Note): Does not change this vector. To update this vector itself,
use SetNormalized. }
method Normalize: TVector3;
{ Normalizes this vector. This is, keep the current direction, but set the
length to 1.
@bold(Note): The SIMD optimized versions of this method use an
approximation, resulting in a very small error.
@bold(Note): If you do not want to change this vector, but get a
normalized version instead, then use Normalize. }
method SetNormalized;
{ Calculates a normalized version of this vector.
Returns:
The normalized version of of this vector. That is, a vector in the same
direction as A, but with a length of 1.
@bold(Note): this is an SIMD optimized version that uses an approximation,
resulting in a small error. For an accurate version, use Normalize.
@bold(Note): Does not change this vector. To update this vector itself,
use SetNormalizedFast. }
method NormalizeFast: TVector3;
{ Normalizes this vector. This is, keep the current direction, but set the
length to 1.
@bold(Note): this is an SIMD optimized version that uses an approximation,
resulting in a small error. For an accurate version, use SetNormalized.
@bold(Note): If you do not want to change this vector, but get a
normalized version instead, then use NormalizeFast. }
method SetNormalizedFast;
{ Calculates a vector pointing in the same direction as this vector.
Parameters:
I: the incident vector.
NRef: the reference vector.
Returns:
A vector that points away from the surface as defined by its normal. If
NRef.Dot(I) < 0 then it returns this vector, otherwise it returns the
negative of this vector. }
method FaceForward(const I, NRef: TVector3): TVector3;
{ Calculates the reflection direction for this (incident) vector.
Parameters:
N: the normal vector. Should be normalized in order to achieve the desired
result.
Returns:
The reflection direction calculated as Self - 2 * N.Dot(Self) * N. }
method Reflect(const N: TVector3): TVector3;
{ Calculates the refraction direction for this (incident) vector.
Parameters:
N: the normal vector. Should be normalized in order to achieve the
desired result.
Eta: the ratio of indices of refraction.
Returns:
The refraction vector.
@bold(Note): This vector should be normalized in order to achieve the
desired result.}
method Refract(const N: TVector3; const Eta: Single): TVector3;
{ Creates a vector with the same direction as this vector, but with the
length limited, based on the desired maximum length.
Parameters:
AMaxLength: The desired maximum length of the vector.
Returns:
A length-limited version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLimit. }
method Limit(const AMaxLength: Single): TVector3;
{ Limits the length of this vector, based on the desired maximum length.
Parameters:
AMaxLength: The desired maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-limited version instead, then use Limit. }
method SetLimit(const AMaxLength: Single);
{ Creates a vector with the same direction as this vector, but with the
length limited, based on the desired squared maximum length.
Parameters:
AMaxLengthSquared: The desired squared maximum length of the vector.
Returns:
A length-limited version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLimitSquared. }
method LimitSquared(const AMaxLengthSquared: Single): TVector3;
{ Limits the length of this vector, based on the desired squared maximum
length.
Parameters:
AMaxLengthSquared: The desired squared maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-limited version instead, then use LimitSquared. }
method SetLimitSquared(const AMaxLengthSquared: Single);
{ Creates a vector with the same direction as this vector, but with the
length clamped between a minimim and maximum length.
Parameters:
AMinLength: The minimum length of the vector.
AMaxLength: The maximum length of the vector.
Returns:
A length-clamped version of this vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetClamped. }
method Clamp(const AMinLength, AMaxLength: Single): TVector3;
{ Clamps the length of this vector between a minimim and maximum length.
Parameters:
AMinLength: The minimum length of this vector.
AMaxLength: The maximum length of this vector.
@bold(Note): If you do not want to change this vector, but get a
length-clamped version instead, then use Clamp. }
method SetClamped(const AMinLength, AMaxLength: Single);
{ Linearly interpolates between this vector and a target vector.
Parameters:
ATarget: the target vector.
AAlpha: the interpolation coefficient (between 0.0 and 1.0).
Returns:
The interpolation result vector.
@bold(Note): Does not change this vector. To update this vector itself,
use SetLerp. }
method Lerp(const ATarget: TVector3; const AAlpha: Single): TVector3;
{ Linearly interpolates between this vector and a target vector and stores
the result in this vector.
Parameters:
ATarget: the target vector.
AAlpha: the interpolation coefficient (between 0.0 and 1.0).
@bold(Note): If you do not want to change this vector, but get an
interpolated version instead, then use Lerp. }
method SetLerp(const ATarget: TVector3; const AAlpha: Single);
{ Whether the vector is normalized (within a small margin of error).
Returns:
True if the length of the vector is (very close to) 1.0 }
method IsNormalized: Boolean;
{ Whether the vector is normalized within a given margin of error.
Parameters:
AErrorMargin: the allowed margin of error.
Returns:
True if the squared length of the vector is 1.0 within the margin of
error. }
method IsNormalized(const AErrorMargin: Single): Boolean;
{ Whether this is a zero vector.
Returns:
True if X, Y and Z are exactly 0.0 }
method IsZero: Boolean;
{ Whether this is a zero vector within a given margin of error.
Parameters:
AErrorMargin: the allowed margin of error.
Returns:
True if the squared length is smaller then the margin of error. }
method IsZero(const AErrorMargin: Single): Boolean;
{ Whether this vector has a similar direction compared to another vector.
Parameters:
AOther: the other vector.
Returns:
True if the normalized dot product is greater than 0. }
method HasSameDirection(const AOther: TVector3): Boolean;
{ Whether this vector has an opposite direction compared to another vector.
Parameters:
AOther: the other vector.
Returns:
True if the normalized dot product is less than 0. }
method HasOppositeDirection(const AOther: TVector3): Boolean;
{ Whether this vector runs parallel to another vector (either in the same
or the opposite direction).
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector runs parallel to AOther (within the given tolerance) }
method IsParallel(const AOther: TVector3; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is collinear with another vector. Two vectors are
collinear if they run parallel to each other and point in the same
direction.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is collinear to AOther (within the given tolerance) }
method IsCollinear(const AOther: TVector3; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is opposite collinear with another vector. Two vectors
are opposite collinear if they run parallel to each other and point in
opposite directions.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is opposite collinear to AOther (within the given
tolerance) }
method IsCollinearOpposite(const AOther: TVector3; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Whether this vector is perpendicular to another vector.
Parameters:
AOther: the other vector.
ATolerance: (optional) tolerance. If not specified, a small tolerance
is used.
Returns:
True if this vector is perpendicular to AOther. That is, if the dot
product is 0 (within the given tolerance) }
method IsPerpendicular(const AOther: TVector3; const ATolerance: Single := SINGLE_TOLERANCE): Boolean;
{ Returns the components of the vector.
This is identical to accessing the C-field, but this property can be used
as a default array property.
Parameters:
AIndex: index of the component to return (0-2). Range is checked
with an assertion. }
property Components[const AIndex: Integer]: Single read GetComponent write SetComponent; default;
{ The euclidean length of this vector.
@bold(Note): If you only want to compare lengths of vectors, you should
use LengthSquared instead, which is faster.
@bold(Note): You can also set the length of the vector. In that case, it
will keep the current direction. }
property Length: Single read GetLength write SetLength;
{ The squared length of the vector.
@bold(Note): This property is faster than Length because it avoids
calculating a square root. It is useful for comparing lengths instead of
calculating actual lengths.
@bold(Note): You can also set the squared length of the vector. In that
case, it will keep the current direction. }
property LengthSquared: Single read GetLengthSquared write SetLengthSquared;
public
X, Y, Z: Single;
property R : Single read X write X;
property G : Single read Y write Y;
property B : Single read Z write Z;
property S : Single read X write X;
property T : Single read Y write Y;
property P : Single read Z write Z;
// case Byte of
// { X, Y and Z components of the vector. Aliases for C[0], C[1] and C[2]. }
// 0: (X, Y, Z: Single);
//
// { Red, Green and Blue components of the vector. Aliases for C[0], C[1]
// and C[2]. }
// 1: (R, G, B: Single);
//
// { S, T and P components of the vector. Aliases for C[0], C[1] and C[2]. }
// 2: (S, T, P: Single);
//
// { The three components of the vector. }
// 3: (C: array [0..2] of Single);
end;
implementation
{ TVector3 }
class operator TVector3.Add(const A: TVector3; const B: Single): TVector3;
begin
Result.X := A.X + B;
Result.Y := A.Y + B;
Result.Z := A.Z + B;
end;
class operator TVector3.Add(const A: Single; const B: TVector3): TVector3;
begin
Result.X := A + B.X;
Result.Y := A + B.Y;
Result.Z := A + B.Z;
end;
class operator TVector3.Add(const A, B: TVector3): TVector3;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
Result.Z := A.Z + B.Z;
end;
method TVector3.Distance(const AOther: TVector3): Single;
begin
Result := (Self - AOther).Length;
end;
method TVector3.DistanceSquared(const AOther: TVector3): Single;
begin
Result := (Self - AOther).LengthSquared;
end;
class operator TVector3.Divide(const A: TVector3; const B: Single): TVector3;
var
InvB: Single;
begin
InvB := 1 / B;
Result.X := A.X * InvB;
Result.Y := A.Y * InvB;
Result.Z := A.Z * InvB;
end;
class operator TVector3.Divide(const A: Single; const B: TVector3): TVector3;
begin
Result.X := A / B.X;
Result.Y := A / B.Y;
Result.Z := A / B.Z;
end;
class operator TVector3.Divide(const A, B: TVector3): TVector3;
begin
Result.X := A.X / B.X;
Result.Y := A.Y / B.Y;
Result.Z := A.Z / B.Z;
end;
method TVector3.Cross(const AOther: TVector3): TVector3;
begin
Result.X := (Y * AOther.Z) - (AOther.Y * Z);
Result.Y := (Z * AOther.X) - (AOther.Z * X);
Result.Z := (X * AOther.Y) - (AOther.X * Y);
end;
method TVector3.Dot(const AOther: TVector3): Single;
begin
Result := (X * AOther.X) + (Y * AOther.Y) + (Z * AOther.Z);
end;
method TVector3.FaceForward(const I, NRef: TVector3): TVector3;
begin
if (NRef.Dot(I) < 0) then
Result := Self
else
Result := -Self;
end;
method TVector3.GetLength: Single;
begin
Result := Sqrt((X * X) + (Y * Y) + (Z * Z));
end;
method TVector3.GetLengthSquared: Single;
begin
Result := (X * X) + (Y * Y) + (Z * Z);
end;
class operator TVector3.Multiply(const A: TVector3; const B: Single): TVector3;
begin
Result.X := A.X * B;
Result.Y := A.Y * B;
Result.Z := A.Z * B;
end;
class operator TVector3.Multiply(const A: Single; const B: TVector3): TVector3;
begin
Result.X := A * B.X;
Result.Y := A * B.Y;
Result.Z := A * B.Z;
end;
class operator TVector3.Multiply(const A, B: TVector3): TVector3;
begin
Result.X := A.X * B.X;
Result.Y := A.Y * B.Y;
Result.Z := A.Z * B.Z;
end;
class operator TVector3.Minus(const A: TVector3): TVector3;
begin
Result.X := -A.X;
Result.Y := -A.Y;
Result.Z := -A.Z;
end;
method TVector3.NormalizeFast: TVector3;
begin
Result := Self * InverseSqrt(Self.LengthSquared);
end;
method TVector3.Reflect(const N: TVector3): TVector3;
begin
Result := Self - ((2 * N.Dot(Self)) * N);
end;
method TVector3.Refract(const N: TVector3; const Eta: Single): TVector3;
var
D, K: Single;
begin
D := N.Dot(Self);
K := 1 - Eta * Eta * (1 - D * D);
if (K < 0) then
Result.Init
else
Result := (Eta * Self) - ((Eta * D + Sqrt(K)) * N);
end;
method TVector3.SetNormalizedFast;
begin
Self := Self * InverseSqrt(Self.LengthSquared);
end;
class operator TVector3.Subtract(const A: TVector3; const B: Single): TVector3;
begin
Result.X := A.X - B;
Result.Y := A.Y - B;
Result.Z := A.Z - B;
end;
class operator TVector3.Subtract(const A: Single; const B: TVector3): TVector3;
begin
Result.X := A - B.X;
Result.Y := A - B.Y;
Result.Z := A - B.Z;
end;
class operator TVector3.Subtract(const A, B: TVector3): TVector3;
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
Result.Z := A.Z - B.Z;
end;
{ TVector3 }
method TVector3.Clamp(const AMinLength, AMaxLength: Single): TVector3;
var
LenSq, EdgeSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq = 0) then
Exit(Self);
EdgeSq := AMaxLength * AMaxLength;
if (LenSq > EdgeSq) then
Exit(Self * Sqrt(EdgeSq / LenSq));
EdgeSq := AMinLength * AMinLength;
if (LenSq < EdgeSq) then
Exit(Self * Sqrt(EdgeSq / LenSq));
Result := Self;
end;
class operator TVector3.Equal(const A, B: TVector3): Boolean;
begin
Result := (A.X = B.X) and (A.Y = B.Y) and (A.Z = B.Z);
end;
method TVector3.Equals(const AOther: TVector3; const ATolerance: Single): Boolean;
begin
Result := (Abs(X - AOther.X) <= ATolerance)
and (Abs(Y - AOther.Y) <= ATolerance)
and (Abs(Z - AOther.Z) <= ATolerance);
end;
method TVector3.GetComponent(const AIndex: Integer): Single;
begin
case AIndex of
0 : result := X;
1 : result := Y;
2 : result := Z;
end;
//Result := C[AIndex];
end;
method TVector3.HasSameDirection(const AOther: TVector3): Boolean;
begin
Result := (Dot(AOther) > 0);
end;
method TVector3.HasOppositeDirection(const AOther: TVector3): Boolean;
begin
Result := (Dot(AOther) < 0);
end;
method TVector3.Init(const A: Single);
begin
X := A;
Y := A;
Z := A;
end;
method TVector3.Init;
begin
X := 0;
Y := 0;
Z := 0;
end;
method TVector3.Init(const A1, A2, A3: Single);
begin
X := A1;
Y := A2;
Z := A3;
end;
method TVector3.Init(const A1: Single; const A2: TVector2);
begin
X := A1;
Y := A2.X;
Z := A2.Y;
end;
method TVector3.Init(const A1: TVector2; const A2: Single);
begin
X := A1.X;
Y := A1.Y;
Z := A2;
end;
method TVector3.IsCollinear(const AOther: TVector3; const ATolerance: Single): Boolean;
begin
Result := IsParallel(AOther, ATolerance) and (Dot(AOther) > 0);
end;
method TVector3.IsCollinearOpposite(const AOther: TVector3; const ATolerance: Single): Boolean;
begin
Result := IsParallel(AOther, ATolerance) and (Dot(AOther) < 0);
end;
method TVector3.IsNormalized: Boolean;
begin
Result := IsNormalized(0.000000001);
end;
method TVector3.IsNormalized(const AErrorMargin: Single): Boolean;
begin
Result := (Abs(LengthSquared - 1.0) < AErrorMargin);
end;
method TVector3.IsParallel(const AOther: TVector3; const ATolerance: Single): Boolean;
begin
Result := ((Vector3(Y * AOther.Z - Z * AOther.Y,
Z * AOther.X - X * AOther.Z,
X * AOther.Y - Y * AOther.X).LengthSquared) <= ATolerance);
end;
method TVector3.IsPerpendicular(const AOther: TVector3; const ATolerance: Single): Boolean;
begin
Result := (Abs(Dot(AOther)) <= ATolerance);
end;
method TVector3.IsZero: Boolean;
begin
Result := (X = 0) and (Y = 0) and (Z = 0);
end;
method TVector3.IsZero(const AErrorMargin: Single): Boolean;
begin
Result := (LengthSquared < AErrorMargin);
end;
method TVector3.Lerp(const ATarget: TVector3; const AAlpha: Single): TVector3;
begin
Result := Mix(Self, ATarget, AAlpha);
end;
method TVector3.Limit(const AMaxLength: Single): TVector3;
begin
Result := LimitSquared(AMaxLength * AMaxLength);
end;
method TVector3.LimitSquared(const AMaxLengthSquared: Single): TVector3;
var
LenSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq > AMaxLengthSquared) then
Result := Self * Sqrt(AMaxLengthSquared / LenSq)
else
Result := Self;
end;
method TVector3.Normalize: TVector3;
begin
Result := Self / Length;
end;
class operator TVector3.NotEqual(const A, B: TVector3): Boolean;
begin
Result := (A.X <> B.X) or (A.Y <> B.Y) or (A.Z <> B.Z);
end;
method TVector3.Offset(const ADeltaX, ADeltaY, ADeltaZ: Single);
begin
X := X + ADeltaX;
Y := Y + ADeltaY;
Z := Z + ADeltaZ;
end;
method TVector3.Offset(const ADelta: TVector3);
begin
Self := Self + ADelta;
end;
method TVector3.SetClamped(const AMinLength, AMaxLength: Single);
begin
Self := Clamp(AMinLength, AMaxLength);
end;
method TVector3.SetComponent(const AIndex: Integer; const Value: Single);
begin
case AIndex of
0 : X := Value;
1 : Y := Value;
2 : Z := Value;
end;
//C[AIndex] := Value;
end;
method TVector3.SetLength(const AValue: Single);
begin
setLengthSquared(AValue * AValue);
end;
method TVector3.SetLengthSquared(const AValue: Single);
var
LenSq: Single;
begin
LenSq := GetLengthSquared;
if (LenSq <> 0) and (LenSq <> AValue) then
Self := Self * Sqrt(AValue / LenSq);
end;
method TVector3.SetLerp(const ATarget: TVector3; const AAlpha: Single);
begin
Self := Mix(Self, ATarget, AAlpha);
end;
method TVector3.SetLimit(const AMaxLength: Single);
begin
Self := LimitSquared(AMaxLength * AMaxLength);
end;
method TVector3.SetLimitSquared(const AMaxLengthSquared: Single);
begin
Self := LimitSquared(AMaxLengthSquared);
end;
method TVector3.SetNormalized;
begin
Self := Self / Length;
end;
class method TVector3.Vector3(const A1: Single; const A2: Single; const A3: Single): TVector3;
begin
result.Init(A1, A2, A3);
end;
constructor TVector3(const A1: Single; const A2: Single; const A3: Single);
begin
X := A1;
Y := A2;
Z := A3;
end;
end. |
program dynamicArrFill1;
type
twoDimIntArr = array of array of integer;
var
arr1:twoDimIntArr;
arr2:array[1..20, 2..10] of integer;
arr3:array[1..20] of array[2..10] of integer;
{----------------------------------------}
procedure fillTwoDimArr(var arr:twoDimIntArr);
var
i, j:integer;
begin
for i:=low(arr) to high(arr) do
begin
for j:=low(arr[i]) to high(arr[i]) do
begin
arr[i][j] := i * length(arr[i]) + j;
end;
end;
end;
{----------------------------------------}
procedure showTwoDimArr(var arr:twoDimIntArr);
var
i, j:integer;
begin
writeln('length(arr):', length(arr), '; low(arr):', low(arr), '; high(arr):', high(arr));
for i:=low(arr) to high(arr) do
begin
for j:=low(arr[i]) to high(arr[i]) do
begin
write(arr[i,j], ' ');
end;
writeln;
end;
writeln;
end;
{----------------------------------------}
procedure fillArr(var arr:array of integer);
var
i:integer;
begin
for i:=low(arr) to high(arr) do
begin
arr[i] := i;
end;
end;
{----------------------------------------}
procedure showArr(var arr:array of integer);
var
i:integer;
begin
writeln('length(arr):', length(arr), '; low(arr):', low(arr), '; high(arr):', high(arr));
for i:=low(arr) to high(arr) do
begin
write(arr[i], ' ');
end;
writeln;
end;
{----------------------------------------}
begin
writeln('length(arr2):', length(arr2), '; low(arr2):', low(arr2), '; high(arr2):', high(arr2));
writeln('length(arr3):', length(arr3), '; low(arr3):', low(arr3), '; high(arr3):', high(arr3));
writeln('length(arr2):', length(arr2[1]), '; low(arr2):', low(arr2[1]), '; high(arr2):', high(arr2[1]));
setLength(arr1, 10, 5);
fillTwoDimArr(arr1);
showTwoDimArr(arr1);
fillArr(arr2[low(arr3)]);
showArr(arr2[low(arr3)]);
setLength(arr1, 9);
setLength(arr1[high(arr1)], 2);
showTwoDimArr(arr1);
writeln(arr1[high(arr1)][high(arr1[high(arr1)]) + 1]);
{
setLength(arr1, 17);
showArr(arr1);
writeln('-------------------');
writeln('fillArrValue:');
fillArrValue(arr1);
showArr(arr1);
writeln('-------------------');
fillArr(arr1);
showArr(arr1);
writeln('-------------------');
setLength(arr1, 20);
showArr(arr1);
writeln('-------------------');
setLength(arr1, 10);
showArr(arr1);
writeln('-------------------');
writeln('length(arr2):', length(arr2), '; low(arr2):', low(arr2), '; high(arr2):', high(arr2));
showArr(arr2);
writeln('-------------------');
}
end.
|
unit MainUnit;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{$IFDEF FPC}
LCLIntf, LCLType,
{$ENDIF}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Buttons, StdCtrls, Math, Types,
OSM.SlippyMapUtils, OSM.MapControl, OSM.TileStorage,
OSM.NetworkRequest, {SynapseRequest,} WinInetRequest;
const
MSG_GOTTILE = WM_APP + 200;
type
// Nice trick to avoid registering TMapControl as design-time component
TScrollBox = class(TMapControl)
end;
TGotTileData = record
Tile: TTile;
Ms: TMemoryStream;
Error: string;
end;
PGotTileData = ^TGotTileData;
TMainForm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Splitter1: TSplitter;
btnZoomIn: TSpeedButton;
btnZoomOut: TSpeedButton;
Button1: TButton;
mMap: TScrollBox;
mLog: TMemo;
Label1: TLabel;
Label2: TLabel;
lblZoom: TLabel;
Button2: TButton;
Button3: TButton;
btnMouseModePan: TSpeedButton;
btnMouseModeSel: TSpeedButton;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure btnZoomInClick(Sender: TObject);
procedure btnZoomOutClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure MsgGotTile(var Message: TMessage); message MSG_GOTTILE;
procedure NetReqGotTileBgThr(const Tile: TTile; Ms: TMemoryStream; const Error: string);
procedure mMapMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure mMapGetTile(Sender: TMapControl; TileHorzNum, TileVertNum: Cardinal; out TileBmp: TBitmap);
procedure mMapZoomChanged(Sender: TObject);
procedure mMapSelectionBox(Sender: TMapControl; const GeoRect: TGeoRect);
procedure Button2Click(Sender: TObject);
procedure btnMouseModePanClick(Sender: TObject);
procedure btnMouseModeSelClick(Sender: TObject);
private
NetRequest: TNetworkRequestQueue;
TileStorage: TTileStorage;
procedure Log(const s: string);
end;
var
MainForm: TMainForm;
implementation
{$IFDEF FPC}
{$R *.lfm}
{$ENDIF}
{$IFDEF DCC}
{$R *.dfm}
{$ENDIF}
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Memory/disc cache of tile images
// You probably won't need it if you have another fast storage (f.e. database)
TileStorage := TTileStorage.Create(30);
TileStorage.FileCacheBaseDir := ExpandFileName('..\Map\');
// Queuer of tile image network requests
// You won't need it if you have another source (f.e. database)
NetRequest := TNetworkRequestQueue.Create(4, 3, {}{SynapseRequest.}WinInetRequest.NetworkRequest, NetReqGotTileBgThr);
mMap.OnGetTile := mMapGetTile;
mMap.OnZoomChanged := mMapZoomChanged;
mMap.OnSelectionBox := mMapSelectionBox;
mMap.SetZoom(1);
mMap.MaxZoom := 10;
mMap.MapMarkCaptionFont.Style := [fsItalic, fsBold];
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
//...
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(NetRequest);
FreeAndNil(TileStorage);
end;
procedure TMainForm.Log(const s: string);
begin
mLog.Lines.Add(DateTimeToStr(Now)+' '+s);
{$IF DECLARED(OutputDebugString)}
OutputDebugString(PChar(DateTimeToStr(Now)+' '+s));
{$IFEND}
end;
// Callback from map control to receive a tile image
procedure TMainForm.mMapGetTile(Sender: TMapControl; TileHorzNum, TileVertNum: Cardinal; out TileBmp: TBitmap);
var
Tile: TTile;
begin
Tile.Zoom := Sender.Zoom;
Tile.ParameterX := TileHorzNum;
Tile.ParameterY := TileVertNum;
// Query tile from storage
TileBmp := TileStorage.GetTile(Tile);
// Tile image unavailable - queue network request
if TileBmp = nil then
begin
NetRequest.RequestTile(Tile);
Log(Format('Queued request from inet %s', [TileToStr(Tile)]));
end;
end;
procedure TMainForm.mMapMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
MapPt: TPoint;
GeoPt: TGeoPoint;
begin
MapPt := mMap.ViewToMap(Point(X, Y));
MapPt.X := EnsureRange(MapPt.X, 0, MapWidth(mMap.Zoom));
MapPt.Y := EnsureRange(MapPt.Y, 0, MapHeight(mMap.Zoom));
GeoPt := mMap.MapToGeoCoords(MapPt);
Label1.Caption := Format('Pixels: %d : %d', [MapPt.X, MapPt.Y]);
Label2.Caption := Format('Geo coords: %.3f : %.3f', [GeoPt.Long, GeoPt.Lat]);
end;
procedure TMainForm.mMapZoomChanged(Sender: TObject);
begin
lblZoom.Caption := Format('%d / %d', [TMapControl(Sender).Zoom, High(TMapZoomLevel)]);
end;
// Zoom to show selected region
procedure TMainForm.mMapSelectionBox(Sender: TMapControl; const GeoRect: TGeoRect);
begin
Log(Format('Selected region: (%.3f : %.3f; %.3f : %.3f)',
[GeoRect.TopLeft.Long, GeoRect.TopLeft.Lat, GeoRect.BottomRight.Long, GeoRect.BottomRight.Lat]));
Sender.ZoomToArea(GeoRect);
end;
// Callback from a thread of network requester that request has been done
// To avoid thread access troubles, re-post all the data to form
procedure TMainForm.NetReqGotTileBgThr(const Tile: TTile; Ms: TMemoryStream; const Error: string);
var
pData: PGotTileData;
begin
New(pData);
pData.Tile := Tile;
pData.Ms := Ms;
pData.Error := Error;
if not PostMessage(Handle, MSG_GOTTILE, 0, LPARAM(pData)) then
begin
Dispose(pData);
FreeAndNil(Ms);
end;
end;
procedure TMainForm.MsgGotTile(var Message: TMessage);
var
pData: PGotTileData;
begin
pData := PGotTileData(Message.LParam);
if pData.Error <> '' then
begin
Log(Format('Error getting tile %s: %s', [TileToStr(pData.Tile), pData.Error]));
end
else
begin
Log(Format('Got from inet %s', [TileToStr(pData.Tile)]));
TileStorage.StoreTile(pData.Tile, pData.Ms);
mMap.RefreshTile(pData.Tile.ParameterX, pData.Tile.ParameterY);
end;
FreeAndNil(pData.Ms);
Dispose(pData);
end;
procedure TMainForm.btnZoomInClick(Sender: TObject);
begin
mMap.SetZoom(mMap.Zoom + 1);
end;
procedure TMainForm.btnZoomOutClick(Sender: TObject);
begin
mMap.SetZoom(mMap.Zoom - 1);
end;
procedure TMainForm.Button1Click(Sender: TObject);
var
bmp, bmTile: TBitmap;
col, row: Integer;
tile: TTile;
imgAbsent: Boolean;
begin
bmp := TBitmap.Create;
bmp.Height := TileCount(mMap.Zoom)*TILE_IMAGE_HEIGHT;
bmp.Width := TileCount(mMap.Zoom)*TILE_IMAGE_WIDTH;
try
imgAbsent := False;
for col := 0 to TileCount(mMap.Zoom) - 1 do
for row := 0 to TileCount(mMap.Zoom) - 1 do
begin
tile.Zoom := mMap.Zoom;
tile.ParameterX := col;
tile.ParameterY := row;
bmTile := TileStorage.GetTile(tile);
if bmTile = nil then
begin
NetRequest.RequestTile(tile);
imgAbsent := True;
Continue;
end;
bmp.Canvas.Draw(col*TILE_IMAGE_WIDTH, row*TILE_IMAGE_HEIGHT, bmTile);
end;
if imgAbsent then
begin
ShowMessage('Some images were absent');
Exit;
end;
bmp.SaveToFile('Map'+IntToStr(mMap.Zoom)+'.bmp');
ShowMessage('Saved to Map'+IntToStr(mMap.Zoom)+'.bmp');
finally
FreeAndNil(bmp);
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
const
Colors: array[0..6] of TColor = (clRed, clYellow, clGreen, clBlue, clBlack, clLime, clPurple);
var
i: Integer;
begin
Randomize;
for i := 1 to 100 do
begin
with mMap.MapMarks.Add(TGeoPoint.Create(RandomRange(-180, 180), RandomRange(-85, 85)), 'Mapmark #' + IntToStr(i)) do
begin
CustomProps := [propGlyphStyle, propCaptionStyle];
GlyphStyle.Shape := TMapMarkGlyphShape(Random(Ord(High(TMapMarkGlyphShape)) + 1));
CaptionStyle.Color := Colors[Random(High(Colors) + 1)];
end;
end;
mMap.Invalidate;
end;
procedure TMainForm.btnMouseModePanClick(Sender: TObject);
begin
mMap.MouseMode := mmDrag;
end;
procedure TMainForm.btnMouseModeSelClick(Sender: TObject);
begin
mMap.MouseMode := mmSelect;
end;
end.
|
{$A+,B-,D+,E+,F-,G-,I-,L+,N-,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65384,0,655360}
{ 48þ EL camino de Eric China 2000
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
Hab¡a una vez, en una escuela donde el que tuviera el pelo largo era
un proscrito y era perseguido. El que estuviera huyendo sab¡a que si
era agarrado por el director tendr¡a luego que lucir un bello pelado a
rape.
Pero yo tengo un amigo que estimaba mucho su cabello y se dispuso a
mantenerse en pleno escape. ¨ C¢mo lo conseguir¡a ? Tratar¡a siempre
de no hacer coincidir su camino con el del director; pero el vivir en
una gran escuela da muchos posibles caminos ¢ptimos y es dif¡cil
calcular. El conoc¡a a unos programadores y les puso la tarea de
ayudarlo.
Para mejor ubicaci¢n la escuela fue resumida a un simple esquema donde
aparecer¡an las escaleras, aulas, pasillos, etc. como simples nodos
(numerados de 1..N) y nuestro amigo se tendr¡a que pelar si coincid¡a
con el director en un mismo nodo (si llegaba a un nodo al mismo tiempo
que el director) y para eso el dirigente usaba un m‚todo secreto casi
infalible y era capaz de calcular siempre el mejor camino para ‚l.
Tanto el Director como Eric se van a estar moviendo siempre lo que
implica que nunca van a permanecer en un nodo sin realizar alg£n
movimiento.
Entrada
Sabiendo que Eric y el director viajan a la misma velocidad; se tiene
un fichero de entrada con el siguiente formato:
N : n£mero de nodos. (1 <= N <= 300)
E F : nodo donde se encuentra Eric [espacio] nodo a donde desea
llegar.
D : nodo donde se encuentra el director.
y luego N l¡neas donde:
en la l¡nea K est n ubicados los nodos a los que se puede
llegar desde K. El fin de l¡nea ser indicado por un n£mero 0.
Salida
Ud. debe calcular el o los caminos "salvadores" m s cortos.
L : Menor longitud de los caminos salvadores.
C : Cantidad de caminos "salvadores" de longitud L. y mostrar un
camino de longitud L. Imprimiendo los nodos en el orden del
recorrido. En caso de no existir soluci¢n se imprimir el cartel
"No Soluci¢n".
ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ Entrada ³ Explicaci¢n ³
ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÅÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´
³ 7 ³ Cantidad de nodos. ³
³ 1 4 ³ Posici¢n de Eric <espacio> nodo al que desea llegar. ³
³ 6 ³ Posici¢n inicial del director. ³
³ 2 0 ³ Nodos a los que se puede llegar desde 1 ³
³ 5 3 0 ³ Nodos a los que se puede llegar desde 2 ³
³ 4 0 ³ ³
³ 0 ³ ³
³ 3 4 0 ³ . . . ³
³ 1 7 0 ³ ³
³ 2 0 ³ Nodos a los que se puede llegar desde 7 ³
ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÂÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿
³ Salida ³ Explicaci¢n ³
ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÅÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´
³ 3 ³ Los caminos "salvadores" m s cortos tienen long. 3 ³
³ 2 ³ Hay 2 caminos "salvadores". ³
³ 1 2 3 4 ³ Posible caminos salvador ³
ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÁÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
}
const
max = 321;
type
range = 0..max;
mx = array[1..max] of range;
var
fe,fs : text;
n,mov,best,long : range;
posi : array[1..3] of range;
cant : array[boolean,1..max] of range;
tab : array[1..max] of ^mx;
cam : array[1..max*2] of ^mx;
cont : array[1..max] of range;
sav : array[boolean,1..2,1..max] of range;
procedure open;
var
i,aux : range;
buff : array[1..64000] of byte;
begin
assign(fe,'chi048.in'); reset(fe);
assign(fs,'chi048.out'); rewrite(fs);
settextbuf(fe,buff);
readln(fe,n);
readln(fe,posi[1],posi[2]);
readln(fe,posi[3]);
for i:=1 to n do
begin
new(tab[i]); fillchar(tab[i]^,sizeof(tab[i]^),0);
read(fe,aux);
while aux <> 0 do
begin
inc(cont[i]);
tab[i]^[cont[i]]:=aux;
read(fe,aux);
end;
readln(fe);
end;
close(fe);
end;
procedure bfs;
var
cp1,cp2,ch1,ch2,i,j,c,d : range;
mk : array[1..max] of boolean;
s : boolean;
begin
s:=true; cp1:=1; cp2:=1; mov:=0; best:=0;
sav[s,1,1]:=posi[1]; sav[s,2,1]:=posi[3];
cant[s,posi[1]]:=1;
while (cp1 > 0) and (cp2 > 0) do
begin
inc(mov);
new(cam[mov]);
fillchar(cam[mov]^,sizeof(cam[mov]^),0);
ch1:=0; ch2:=0;
fillchar(mk,sizeof(mk),false);
for i:=1 to cp2 do {Director Move}
begin
d:=sav[s,2,i];
for j:=1 to cont[d] do
begin
c:=tab[d]^[j];
if not mk[c] then
begin
inc(ch2);
sav[not s,2,ch2]:=c;
mk[c]:=true;
cant[not s,c]:=0;
end;
end;
end; {End Director Move}
for i:=1 to cp1 do {Erick Move}
begin
d:=sav[s,1,i];
for j:=1 to cont[d] do
begin
c:=tab[d]^[j];
if not mk[c] then
begin
inc(ch1);
sav[not s,1,ch1]:=c;
mk[c]:=true;
cam[mov]^[c]:=sav[s,1,i];
cant[not s,c]:=cant[s,d];
end
else
cant[not s,c]:=cant[not s,c] + cant[s,d];
end; {End Erick Move}
end;
cp1:=ch1;
cp2:=ch2;
s:=not s;
for i:=1 to cp1 do {Verif. Si Llego}
begin
if sav[s,1,i] = posi[2] then
begin
best:=mov;
long:=cant[s,posi[2]];
exit;
end;
end; {End Verif.}
end;
end;
procedure camino(x,y : range);
begin
if (x > 0) and (y > 0) then
begin
camino(cam[y]^[x],y-1);
write(fs,cam[y]^[x],' ');
end;
end;
procedure closer;
begin
if best = 0 then
writeln(fs,'No Soluci¢n')
else
begin
writeln(fs,best);
writeln(fs,long);
n:=0;
camino(posi[2],best);
write(fs,posi[2]);
end;
close(fs);
end;
begin
open;
bfs;
closer;
end. |
unit database;
interface
uses MyServis;
var
// Credentials and options
DB_HOST:string='127.0.0.1';
DB_DATABASE:string='';
DB_LOGIN:string='';
DB_PASSWORD:string='';
DB_CHARSET:string='utf8';
const
// Error codes
dbeNoError = 0;
dbeNotConnected = 1;
dbePingFailed = 2;
dbeServerError = 3;
dbeQueryFailed = 4;
type
// Basic abstract class
TDatabase=class
connected:boolean;
rowCount,colCount:integer;
lastError:string;
lastErrorCode:integer;
constructor Create;
procedure Connect; virtual; abstract;
// Выполняет запрос, возвращает массив строк размером (число строк)*(число столбцов)
// В случае ошибки возвращает массив из одной строки: ERROR: <текст ошибки>
// Если запрос не подразумевает возврат данных и выполняется успешно - возвращает
// пустой массив (0 строк)
function Query(DBquery:string):StringArr; virtual; abstract;
destructor Destroy; virtual;
private
crSect:TMyCriticalSection;
name:string;
end;
// MySQL interface
TMySQLDatabase=class(TDatabase)
constructor Create;
procedure Connect; override;
function Query(DBquery:string):StringArr; override;
destructor Destroy; override;
private
ms:pointer;
reserve:array[0..255] of integer; // резерв для структуры ms
end;
// Escape special characters (so string can be used in query)
procedure SQLString(var st:string);
function SQLSafe(st:string):string;
implementation
uses SysUtils,mysql;
var
counter:integer=0; // MySQL library usage counter
procedure SQLString(var st:string);
var
i:integer;
begin
st:=StringReplace(st,'\','\\',[rfReplaceAll]);
st:=StringReplace(st,'"','\"',[rfReplaceAll]);
st:=StringReplace(st,'@','\@',[rfReplaceAll]);
st:=StringReplace(st,#13,'\r',[rfReplaceAll]);
st:=StringReplace(st,#10,'\n',[rfReplaceAll]);
st:=StringReplace(st,#9,'\t',[rfReplaceAll]);
st:=StringReplace(st,#0,'\0',[rfReplaceAll]);
i:=1;
while i<length(st) do
if st[i]<' ' then delete(st,i,1) else inc(i);
end;
function SQLSafe(st:string):string;
begin
SQLString(st);
result:=st;
end;
{ TDatabase }
constructor TDatabase.Create;
begin
InitCritSect(crSect,name,100);
rowCount:=0; colCount:=0;
end;
destructor TDatabase.Destroy;
begin
DeleteCritSect(crSect);
end;
{ TMySQLDatabase }
procedure TMySQLDatabase.Connect;
var
bool:longbool;
i:integer;
begin
try
sleep(100);
ms:=mysql_init(nil);
bool:=true;
mysql_options(ms,MYSQL_OPT_RECONNECT,@bool);
mysql_options(ms,MYSQL_SET_CHARSET_NAME,PChar(DB_CHARSET));
i:=1;
while (mysql_real_connect(ms,PChar(DB_HOST),PChar(DB_LOGIN),PChar(DB_PASSWORD),
PChar(DB_DATABASE),0,'',0{CLIENT_COMPRESS})<>ms) and
(i<4) do begin
ForceLogMessage(name+': Error connecting to MySQL server ('+mysql_error(ms)+'), retry in 3 sec');
sleep(3000); inc(i);
end;
if i=4 then raise EError.Create(name+': Failed to connect to MySQL server');
bool:=true;
mysql_options(ms,MYSQL_OPT_RECONNECT,@bool);
connected:=true;
ForceLogMessage(name+': MySQL connection established');
except
on e:exception do ForceLogMessage(name+': error during MySQL Connect: '+e.message);
end;
end;
constructor TMySQLDatabase.Create;
begin
inherited;
if counter=0 then begin
libmysql_load(nil);
end;
inc(counter);
name:='DB-'+inttostr(counter);
end;
destructor TMySQLDatabase.Destroy;
begin
inherited;
dec(counter);
if counter>0 then exit;
libmysql_free;
end;
function TMySQLDatabase.Query(DBquery: string): StringArr;
var
r,flds,rows,i,j:integer;
st:string;
res:PMYSQL_RES;
myrow:PMYSQL_ROW;
begin
if not connected then begin
SetLength(result,1);
lastError:='ERROR: Not connected';
lastErrorCode:=dbeNotConnected;
result[0]:=lastError;
exit;
end;
EnterCriticalSection(crSect);
try
if DBquery='' then begin
// Пустой запрос для поддержания связи с БД
SetLength(result,0);
r:=mysql_ping(ms);
if r<>0 then begin
st:=mysql_error(ms);
lastError:=st;
lastErrorCode:=dbePingFailed;
LogMessage('ERROR! Failed to ping MySQL: '+st);
end;
exit;
end;
// непустой запрос
r:=mysql_real_query(ms,@DBquery[1],length(DBquery));
if r<>0 then begin
st:=mysql_error(ms);
lastError:=st;
lastErrorCode:=dbeServerError;
LogMessage('SQL_ERROR: '+st);
setLength(result,1);
result[0]:='ERROR: '+st;
exit;
end;
res:=mysql_use_result(ms);
if res=nil then begin
st:=mysql_error(ms);
if st<>'' then begin
lastError:=st;
lastErrorCode:=dbeQueryFailed;
LogMessage('SQL_ERROR: '+st);
setLength(result,1);
result[0]:='ERROR: '+st;
end else
setLength(result,0);
exit;
end;
flds:=mysql_num_fields(res); // кол-во полей в результате
colCount:=flds;
rowCount:=0;
try
j:=0;
setLength(result,flds); // allocate for 1 row
while true do begin
// выборка строки и извлечение данных в массив row
myrow:=mysql_fetch_row(res);
if myrow<>nil then begin
inc(rowCount);
for i:=0 to flds-1 do begin
if j>=length(result) then
setLength(result,j*2+flds*16); // re-allocate
result[j]:=myrow[i];
inc(j);
end;
end else break;
end;
if j<>length(result) then setLength(result,j);
finally
mysql_free_result(res);
end;
finally
LeaveCriticalSection(crSect);
end;
end;
end.
|
unit UInquilinoUnidade;
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, UGenericVO, Generics.Collections,
UInquilinoUnidadeController, UPessoa, UPessoasVO, UUnidadeVO, UPessoasController, Biblioteca,
UInquilinoUnidadeVO;
type
TFTelaCadastroInquilino = class(TFTelaCadastro)
LabelEditCodigo: TLabeledEdit;
btnConsultaPessoa: TBitBtn;
MaskEditDtInicio: TMaskEdit;
Label1: TLabel;
LabelNome: TLabel;
procedure btnConsultaPessoaClick(Sender: TObject);
function MontaFiltro: string;
procedure FormCreate(Sender: TObject);
function DoSalvar: boolean; override;
function DoExcluir: boolean; override;
procedure DoConsultar; override;
procedure BitBtnNovoClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MaskEditDtInicioExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Idunidade : integer;
procedure GridParaEdits; override;
function EditsToObject(InquilinoUnidade: TInquilinoUnidadeVO): TInquilinoUnidadeVO;
end;
var
FTelaCadastroInquilino: TFTelaCadastroInquilino;
ControllerInquilinoUnidade :TInquilinoUnidadeController;
implementation
{$R *.dfm}
uses UUnidade;
{ TFTelaCadastroInquilino }
procedure TFTelaCadastroInquilino.BitBtnNovoClick(Sender: TObject);
begin
inherited;
LabelEditCodigo.SetFocus;
end;
procedure TFTelaCadastroInquilino.btnConsultaPessoaClick(Sender: TObject);
var
FormPessoaConsulta: TFTelaCadastroPessoa;
begin
FormPessoaConsulta := TFTelaCadastroPessoa.Create(nil);
FormPessoaConsulta.FechaForm := true;
FormPessoaConsulta.ShowModal;
if (FormPessoaConsulta.ObjetoRetornoVO <> nil) then
begin
LabelEditCodigo.Text := IntToStr(TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).idpessoa);
LabelNome.Caption := TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).nome;
end;
FormPessoaConsulta.Release;
end;
procedure TFTelaCadastroInquilino.DoConsultar;
var
listaInquilinoUnidade: TObjectList<TInquilinoUnidadeVO>;
filtro: string;
begin
filtro := MontaFiltro;
listaInquilinoUnidade := ControllerInquilinoUnidade.Consultar(filtro, 'ORDER BY DTINICIO DESC');
PopulaGrid<TInquilinoUnidadeVO>(listaInquilinoUnidade);
end;
function TFTelaCadastroInquilino.DoExcluir: boolean;
var
InquilinoUnidade: TInquilinoUnidadeVO;
begin
try
try
InquilinoUnidade := TInquilinoUnidadeVO.Create;
InquilinoUnidade.idinquilinounidade := CDSGrid.FieldByName('IDINQUILINOUNIDADE')
.AsInteger;
ControllerInquilinoUnidade.Excluir(InquilinoUnidade);
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 TFTelaCadastroInquilino.DoSalvar: boolean;
var
InquilinoUnidade: TInquilinoUnidadeVo;
begin
InquilinoUnidade:=EditsToObject(TInquilinoUnidadeVo.Create);
try
try
InquilinoUnidade.ValidarCampos();
if (StatusTela = stInserindo) then
begin
InquilinoUnidade.idUnidade := idunidade;
ControllerInquilinoUnidade.Inserir(InquilinoUnidade);
Result := true;
end
else if (StatusTela = stEditando) then
begin
InquilinoUnidade := ControllerInquilinoUnidade.ConsultarPorId(CDSGrid.FieldByName('IDINQUILINOUNIDADE')
.AsInteger);
InquilinoUnidade := EditsToObject(InquilinoUnidade);
ControllerInquilinoUnidade.Alterar(InquilinoUnidade);
Result := true;
end;
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroInquilino.EditsToObject(InquilinoUnidade: TInquilinoUnidadeVO): TInquilinoUnidadeVO;
var
FormConsultaUnidade : TFTelaCadastroUnidade;
begin
if(LabelEditCodigo.Text<>'')then
InquilinoUnidade.idPessoa := StrToInt(LabelEditCodigo.text);
// InquilinoUnidade.IdUnidade := idunidade;
if(MaskEditDtInicio.Text<> ' / / ' )then
InquilinoUnidade.DtInicio := StrToDateTime(MaskEditDtInicio.Text);
result := InquilinoUnidade;
end;
procedure TFTelaCadastroInquilino.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerInquilinoUnidade);
end;
procedure TFTelaCadastroInquilino.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TInquilinoUnidadeVo;
ControllerInquilinoUnidade := TInquilinoUnidadeController.Create;
inherited;
end;
procedure TFTelaCadastroInquilino.GridParaEdits;
var
InquilinoUnidade: TInquilinoUnidadeVo;
FormPessoaConsulta : TFTelaCadastroPessoa;
pessoaController : TPessoasController;
begin
inherited;
if not CDSGrid.IsEmpty then
InquilinoUnidade := ControllerInquilinoUnidade.ConsultarPorId
(CDSGrid.FieldByName('IDINQUILINOUNIDADE').AsInteger);
if Assigned(InquilinoUnidade) then
begin
LabelEditCodigo.Text := IntToStr(InquilinoUnidade.idPessoa);
LabelNome.Caption := InquilinoUnidade.PessoaVo.nome;
MaskEditDtInicio.Text := DateTimeToStr(InquilinoUnidade.DtInicio);
end;
end;
procedure TFTelaCadastroInquilino.MaskEditDtInicioExit(Sender: TObject);
begin
EventoValidaData(sender);
end;
function TFTelaCadastroInquilino.MontaFiltro: string;
begin
Result := ' (IDUNIDADE = '+inttostr(Idunidade)+')';
if(editbusca.Text<>'')then
Result:= result+ ' AND Upper(Nome) like '+QuotedStr('%'+Uppercase(EditBusca.Text)+'%')
end;
end.
|
unit DSA.Search.BinarySearch;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils;
type
generic TBinarySearch<T> = class
private
type
TArr_T = specialize TArray<T>;
ICmp_T = specialize IDSA_Comparer<T>;
var
class function __search2(const arr: TArr_T; target: T;
l, r: integer; const cmp: ICmp_T): integer;
public
/// <summary>
/// 二分查找法,在有序数组arr中,查找target
/// 如果找到target,返回相应的索引index
/// 如果没有找到target,返回-1
/// </summary>
class function Search(const arr: TArr_T; target: T; const cmp: ICmp_T): integer;
/// <summary> 用递归的方式写二分查找法 </summary>
class function Search2(const arr: TArr_T; target: T;
const cmp: ICmp_T): integer;
end;
procedure Main;
implementation
type
TBinarySearch_int = specialize TBinarySearch<integer>;
procedure Main;
var
n, i, v: integer;
arr: TArray_int;
startTime, endTime: double;
begin
n := 1000000;
SetLength(arr, n);
for i := 0 to n - 1 do
arr[i] := i;
// 测试非递归二分查找法
startTime := TThread.GetTickCount64;
for i := 0 to 2 * n - 1 do
begin
v := TBinarySearch_int.Search(arr, i, TComparer_int.Default);
if (i < n) then
Assert(v = i)
else
Assert(v = -1);
end;
endTime := TThread.GetTickCount64;
Writeln('Binary Search (Without Recursion): ',
((endTime - startTime) / 1000).ToString, ' s');
// 测试非递归二分查找法
startTime := TThread.GetTickCount64;
for i := 0 to 2 * n - 1 do
begin
v := TBinarySearch_int.Search2(arr, i, TComparer_int.Default);
if (i < n) then
Assert(v = i)
else
Assert(v = -1);
end;
endTime := TThread.GetTickCount64;
Writeln('Binary Search (Recursion): ',
((endTime - startTime) / 1000).ToString, ' s');
end;
{ TBinarySearch }
class function TBinarySearch.Search(const arr: TArr_T; target: T;
const cmp: ICmp_T): integer;
var
l, r, mid: integer;
begin
// 在arr[l...r]之中查找target
l := 0;
r := Length(arr) - 1;
while l <= r do
begin
mid := l + (r - l) div 2;
if cmp.Compare(arr[mid], target) = 0 then
begin
Result := mid;
Exit;
end;
if cmp.Compare(arr[mid], target) > 0 then
r := mid - 1
else
l := mid + 1;
end;
Result := -1;
end;
class function TBinarySearch.Search2(const arr: TArr_T; target: T;
const cmp: ICmp_T): integer;
begin
Result := __search2(arr, target, 0, Length(arr) - 1, cmp);
end;
class function TBinarySearch.__search2(const arr: TArr_T; target: T;
l, r: integer; const cmp: ICmp_T): integer;
var
mid: integer;
begin
if l > r then
begin
Result := -1;
Exit;
end;
mid := l + (r - l) div 2;
if cmp.Compare(arr[mid], target) = 0 then
begin
Result := mid;
Exit;
end
else if cmp.Compare(arr[mid], target) > 0 then
Result := __Search2(arr, target, l, mid - 1, cmp)
else
Result := __Search2(arr, target, mid + 1, r, cmp);
end;
end.
|
unit SDL2_SimpleGUI_Master;
{:< The Master Class Unit}
{ Simple GUI is a generic SDL2/Pascal GUI library by Matthias J. Molski,
get more infos here:
https://github.com/Free-Pascal-meets-SDL-Website/SimpleGUI.
It is based upon LK GUI by Lachlan Kingsford for SDL 1.2/Free Pascal,
get it here: https://sourceforge.net/projects/lkgui.
Written permission to re-license the library has been granted to me by the
original author.
Copyright (c) 2016-2020 Matthias J. Molski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. }
interface
uses
SysUtils, SDL2, SDL2_SimpleGUI_Element;
type
{ TGUI_Master }
{: TGUI_Master is a special GUI_Element which is designed to be a parent
and draw nothing but itself. Its a special case because it can be given
a surface to draw upon }
TGUI_Master = class(TGUI_Element)
public
constructor Create;
destructor Destroy; override;
{: Set the window for master and all children }
procedure SetWindow(NewWindow: PSDL_Window);
{: Set the renderer for master and all children }
procedure SetRenderer(NewRenderer: PSDL_Renderer);
{: Set the renderer for master and all children }
procedure SetParent(NewParent: TGUI_Element); override;
procedure SetWidth(NewWidth: Word); override;
procedure SetHeight(NewHeight: Word); override;
procedure SetLeft(NewLeft: Word); override;
procedure SetTop(NewTop: Word); override;
{: The master is represented by a background color (black) only. Except
for this, it is kind of invisible (and should be). }
procedure Render; override;
{: Inject/promote an SDL event to the master and its children. }
procedure InjectSDLEvent(event: PSDL_Event);
protected
private
end;
implementation
var
Exceptn: Exception;
constructor TGUI_Master.Create;
begin
inherited Create;
SetVisible(True);
{ turn TextInput off initially: don't catch SDL events of type SDL_TextInput }
SDL_StopTextInput;
end;
destructor TGUI_Master.Destroy;
begin
inherited Destroy;
end;
procedure TGUI_Master.Render;
begin
SDL_SetRenderDrawColor(Renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(Renderer);
end;
procedure TGUI_Master.SetWindow(NewWindow: PSDL_Window);
begin
Window := NewWindow;
Width := Window^.w;
Height := Window^.h;
Left := 0;
Top := 0;
end;
procedure TGUI_Master.SetRenderer(NewRenderer: PSDL_Renderer);
begin
Renderer := NewRenderer;
end;
procedure TGUI_Master.SetParent(NewParent: TGUI_Element);
begin
Exceptn.Create('SetParent called in TGUI_Element');
end;
procedure TGUI_Master.SetWidth(NewWidth: Word);
begin
Exceptn.Create('SetWidth called in TGUI_Master');
end;
procedure TGUI_Master.SetHeight(NewHeight: Word);
begin
Exceptn.Create('SetHeight called in TGUI_Master');
end;
procedure TGUI_Master.SetLeft(NewLeft: Word);
begin
Exceptn.Create('SetLeft called in TGUI_Master');
end;
procedure TGUI_Master.SetTop(NewTop: Word);
begin
Exceptn.Create('SetTop called in TGUI_Master');
end;
procedure TGUI_Master.InjectSDLEvent(event: PSDL_Event);
begin
case event^.type_ of
SDL_KEYDOWN:
begin
ctrl_KeyDown(Event^.Key.KeySym);
end;
SDL_KEYUP:
begin
ctrl_KeyUp(Event^.Key.KeySym);
end;
SDL_MOUSEMOTION:
begin
ctrl_MouseMotion(event^.motion.X, event^.motion.Y, event^.motion.state);
end;
SDL_MOUSEBUTTONDOWN:
begin
ctrl_MouseDown(event^.button.X, event^.button.Y, event^.button.button);
end;
SDL_MOUSEBUTTONUP:
begin
ctrl_MouseUp(event^.button.X, event^.button.Y, event^.button.button);
end;
SDL_TEXTINPUT:
begin
ctrl_TextInput(event^.Text.Text);
end;
end;
ctrl_SDLPassthrough(event);
end;
begin
end.
|
unit uCheckUpdate;
interface
uses
Analyse,System.Classes, AppInfo, System.IniFiles, Transfer,
System.SysUtils,Vcl.Forms;
type
TCheckUpdateThread = class(TThread)
procedure CheckUpdates;
private
FOnExecuteResult: TOnResult;
public
protected
procedure Execute; override;
procedure ExecuteResult(str: TStrings);
published
property OnExecuteResult: TOnResult read FOnExecuteResult write
FOnExecuteResult;
end;
procedure CheckUpdate(OnExecuteResult: TOnResult);
const
UpdateAppIniFileName = 'UpdateApps.ini';
implementation
procedure CheckUpdate(OnExecuteResult: TOnResult);
var
t: TCheckUpdateThread;
begin
t := TCheckUpdateThread.Create;
t.OnExecuteResult := OnExecuteResult;
t.FreeOnTerminate := True;
t.Resume;
end;
procedure TCheckUpdateThread.CheckUpdates;
var
IniFile: TInifile;
Section: String;
FAnalyse: TAnalyse;
FAppInfo: TAppinfo;
FUpdateList: TStrings;
FTransferFactory: TTransferFactory;
function CreateTransfer(URL: String): TTransfer;
var
ProxySeting: TProxySeting;
begin
Result := FTransferFactory.CreateTransfer(URL);
if FAppInfo.ProxyServer <> '' then
begin
ProxySeting.ProxyServer := FAppInfo.ProxyServer;
ProxySeting.ProxyPort := StrToInt(FAppInfo.ProxyPort);
ProxySeting.ProxyUser := FAppInfo.LoginUser;
ProxySeting.ProxyPass := FAppInfo.LoginPass;
Result.SetProxy(ProxySeting);
end
else
Result.ClearProxySeting;
end;
begin
FTransferFactory := TTransferFactory.Create;
IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
try
Section := IniFile.ReadString('Application', 'ApplicationName', '');
if Section <> '' then
begin
FAppInfo := TIniAppInfo.Create(ExtractFilePath(Application.ExeName) + UpdateAppIniFileName, Section);
FAnalyse := TXMLAnalyse.Create;
FAppInfo.AppName := Section;
FAnalyse.UpdateList := FAppInfo.UpdateServer + FAppInfo.ListDefFile;
FAnalyse.Transfer := CreateTransfer(FAnalyse.UpdateList);
FUpdateList := FAnalyse.GetUpdateList;
ExecuteResult(FUpdateList);
end;
finally
FreeAndNil(IniFile);
if Assigned(FAppInfo) then
FreeAndNil(FAppinfo);
if Assigned(FAnalyse) then
FreeAndNil(FAnalyse);
FreeAndNil(FTransferFactory);
end;
end;
procedure TCheckUpdateThread.Execute;
begin
inherited;
CheckUpdates;
end;
procedure TCheckUpdateThread.ExecuteResult(str: TStrings);
begin
if Assigned(FOnExecuteResult) then FOnExecuteResult(str);
end;
end.
|
unit FD.Compiler.Lexer.Tokens;
interface
uses
System.RTTI, RRPG.Unicode, FD.Compiler.Exceptions;
type
TTokenType = (ttUnknown, // Token with unidentified type
ttKeyword, // Reserved word, like "unit", "begin", "if" on Pascal
ttIdentifier, // Something that is not a Literal value, like a variable name
ttOperator, // A separator or operator char/string, like "(", ";", ",", "->", "+", "-"
ttLiteralInteger, // A integer value, like "25", "$256", "0x656"
ttLiteralString, // A string value, like "Test"
ttLiteralFloat, // A float point value, like "25.56" or "10e-5";
ttLiteralBoolean, // A literal boolean value. "True" or "False"
ttLiteralChar, // A literal char value
ttCommentary, // A commentary block
ttPreprocessorDirective, // Something like {$I ....} or {$R ...} {$M+}, etc..
ttWhiteSpace,
ttMalformedToken,
ttEOF // End of Content
);
TFileRange = record
FileName: String;
LineIndex: NativeInt;
ColumnIndex: NativeInt; // In Glyph Index
UTF16CharStartIndex: NativeInt;
UTF16CharCount: Integer;
procedure Initialize;
end;
TCodeLocation = record
RealLocation: TFileRange;
StackLocation: TArray<TFileRange>; // Used mostly when the code use a #include like operation and the token is located within that included file.
procedure Initialize;
end;
TTokenFlag = (tfCaseSensitive);
TTokenFlags = set of TTokenFlag;
TToken = record
private
function GetParsedValueAsInt64: Int64;
procedure SetParsedValueAsInt64(const V: Int64);
function GetParsedValueAsFloat: Double;
procedure SetParsedValueAsFloat(const Value: Double);
function GetParsedValueAsString: String;
procedure SetParsedValueAsString(const Value: String);
public
TokenType: TTokenType;
Location: TCodeLocation;
InputString: String; // String containing complete token. Eg: In a commentary, Value will contain the text and Complete Token will contain the opening/closing characters of the commentary
MalformedDescription: String;
ParsedValue: TValue;
Flags: TTokenFlags;
procedure Initialize;
function IsKeyword(const Keyword: String): Boolean;
function IsIdentifier: Boolean; overload; inline;
function IsIdentifier(const IdentifierName: String): Boolean; overload;
function IsOperator: Boolean; overload; inline;
function IsOperator(const OperatorSymbol: String): Boolean; overload;
function IsLiteralInteger: Boolean; overload; inline;
function IsLiteralInteger(const Value: Int64): Boolean; overload;
function IsLiteralFloat: Boolean; overload; inline;
function IsLiteralFloat(const Value: Double): Boolean; overload;
function IsLiteralString: Boolean; overload; inline;
function IsLiteralString(const StringContent: String): Boolean; overload;
function IsMalformedToken: Boolean; overload; inline;
function IsMalformedToken(const InputString: String): Boolean; overload;
function IsMalformedToken(const InputString: String; const MalformedDescription: String): Boolean; overload;
function IsWhiteSpace: Boolean; inline;
function IsEOF: Boolean; inline;
class function CreateEOF(const CodeLocation: TCodeLocation): TToken; static;
property ParsedValueAsInt64: Int64 read GetParsedValueAsInt64 write SetParsedValueAsInt64;
property ParsedValueAsFloat: Double read GetParsedValueAsFloat write SetParsedValueAsFloat;
property ParsedValueAsString: String read GetParsedValueAsString write SetParsedValueAsString;
end;
ECodeLocationException = class(EFDException)
protected
FCodeLocation: TCodeLocation;
public
constructor Create(CodeLocation: TCodeLocation; const Msg: String); reintroduce;
property CodeLocation: TCodeLocation read FCodeLocation;
end;
ETokenException = class(ECodeLocationException)
protected
FToken: TToken;
public
constructor Create(Token: TToken; const Msg: String); reintroduce;
property Token: TToken read FToken;
end;
implementation
uses
System.Math;
{ TToken }
class function TToken.CreateEOF(const CodeLocation: TCodeLocation): TToken;
begin
Result.Initialize;
Result.TokenType := ttEOF;
Result.Location := CodeLocation;
end;
function TToken.GetParsedValueAsFloat: Double;
begin
Assert(not Self.ParsedValue.IsEmpty);
Assert(Self.ParsedValue.IsType<Double>);
Result := Self.ParsedValue.AsType<Double>;
end;
function TToken.GetParsedValueAsInt64: Int64;
begin
Assert(not Self.ParsedValue.IsEmpty);
Assert(Self.ParsedValue.IsType<Int64>);
Result := Self.ParsedValue.AsType<Int64>;
end;
function TToken.GetParsedValueAsString: String;
begin
Assert(not Self.ParsedValue.IsEmpty);
Assert(Self.ParsedValue.IsType<String>);
Result := Self.ParsedValue.AsType<String>;
end;
procedure TToken.Initialize;
begin
Self.TokenType := TTokenType.ttUnknown;
Self.InputString := '';
Self.MalformedDescription := '';
Self.Location.Initialize;
Self.ParsedValue := TValue.Empty;
Self.Flags := [];
end;
function TToken.IsIdentifier: Boolean;
begin
Result := Self.TokenType = ttIdentifier;
end;
function TToken.IsEOF: Boolean;
begin
Result := Self.TokenType = ttEOF;
end;
function TToken.IsIdentifier(const IdentifierName: String): Boolean;
begin
if Self.TokenType = ttIdentifier then
begin
if TTokenFlag.tfCaseSensitive in Self.Flags then
Result := Self.InputString = IdentifierName
else
Result := TUnicode.Compare(Self.InputString, IdentifierName, [TUnicodeCollateOption.ucoIgnoreCase]) = 0;
end else
Result := False;
end;
function TToken.IsKeyword(const Keyword: String): Boolean;
begin
if Self.TokenType = ttKeyword then
begin
if TTokenFlag.tfCaseSensitive in Self.Flags then
Result := Self.InputString = Keyword
else
Result := TUnicode.Compare(Self.InputString, Keyword, [TUnicodeCollateOption.ucoIgnoreCase]) = 0;
end else
Result := False;
end;
function TToken.IsLiteralInteger: Boolean;
begin
Result := Self.TokenType = ttLiteralInteger;
end;
function TToken.IsLiteralFloat: Boolean;
begin
Result := Self.TokenType = ttLiteralFloat;
end;
function TToken.IsLiteralFloat(const Value: Double): Boolean;
begin
if Self.TokenType = ttLiteralFloat then
Result := SameValue(Self.ParsedValueAsFloat, Value)
else
Result := False;
end;
function TToken.IsLiteralInteger(const Value: Int64): Boolean;
begin
if Self.TokenType = ttLiteralInteger then
Result := Self.GetParsedValueAsInt64() = Value
else
Result := False;
end;
function TToken.IsMalformedToken: Boolean;
begin
Result := Self.TokenType = ttMalformedToken;
end;
function TToken.IsMalformedToken(const InputString: String): Boolean;
begin
if Self.TokenType = ttMalformedToken then
begin
if TTokenFlag.tfCaseSensitive in Self.Flags then
Result := Self.InputString = InputString
else
Result := TUnicode.Compare(Self.InputString, InputString, [TUnicodeCollateOption.ucoIgnoreCase]) = 0;
end else
Result := False;
end;
function TToken.IsOperator: Boolean;
begin
Result := Self.TokenType = ttOperator;
end;
function TToken.IsOperator(const OperatorSymbol: String): Boolean;
begin
if Self.TokenType = ttOperator then
begin
if TTokenFlag.tfCaseSensitive in Self.Flags then
Result := Self.InputString = OperatorSymbol
else
Result := TUnicode.Compare(Self.InputString, OperatorSymbol, [TUnicodeCollateOption.ucoIgnoreCase]) = 0;
end else
Result := False;
end;
function TToken.IsLiteralString: Boolean;
begin
Result := Self.TokenType = ttLiteralString;
end;
function TToken.IsLiteralString(const StringContent: String): Boolean;
begin
if Self.TokenType = ttLiteralString then
Result := Self.ParsedValueAsString = StringContent
else
Result := False;
end;
function TToken.IsMalformedToken(const InputString,
MalformedDescription: String): Boolean;
begin
if Self.TokenType = ttMalformedToken then
begin
if TTokenFlag.tfCaseSensitive in Self.Flags then
Result := Self.InputString = InputString
else
Result := TUnicode.Compare(Self.InputString, InputString, [TUnicodeCollateOption.ucoIgnoreCase]) = 0;
if Result then
Result := TUnicode.Compare(Self.MalformedDescription, MalformedDescription) = 0;
end else
Result := False;
end;
function TToken.IsWhiteSpace: Boolean;
begin
Result := Self.TokenType = ttWhiteSpace;
end;
procedure TToken.SetParsedValueAsFloat(const Value: Double);
begin
Self.ParsedValue := TValue.From<Double>(Value);
end;
procedure TToken.SetParsedValueAsInt64(const V: Int64);
begin
Self.ParsedValue := TValue.From<Int64>(V);
end;
procedure TToken.SetParsedValueAsString(const Value: String);
begin
Self.ParsedValue := TValue.From<String>(Value);
end;
{ TCodeLocation }
procedure TCodeLocation.Initialize;
begin
Self.RealLocation.Initialize;
SetLength(Self.StackLocation, 0);
end;
{ TFileRange }
procedure TFileRange.Initialize;
begin
Self.FileName := '';
Self.UTF16CharStartIndex := -1;
Self.UTF16CharCount := 0;
Self.LineIndex := -1;
Self.ColumnIndex := -1;
end;
{ ECodeLocationException }
constructor ECodeLocationException.Create(CodeLocation: TCodeLocation;
const Msg: String);
begin
inherited Create(Msg);
FCodeLocation := CodeLocation;
end;
{ ETokenException }
constructor ETokenException.Create(Token: TToken; const Msg: String);
begin
inherited Create(Token.Location, Msg);
FToken := Token;
end;
end.
|
unit CatCSCommand;
{
Console Output Capturer
Copyright (c) 2020 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Original code of callback function by David Heffernan (@davidheff)
Changes:
* 28.09.2020, FD - Rewrite based on example by DH.
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, Vcl.Forms, System.Classes, System.SysUtils;
{$ELSE}
Windows, Forms, Classes, SysUtils;
{$ENDIF}
type
TCatCSCommandOutput = procedure(const s: String) of object;
{$IFDEF DXE2_OR_UP}
type
TCmdOutputArg<T> = reference to procedure(const Arg: T);
{$ENDIF}
type
TCatCSCommand = class
private
fOnOutput: TCatCSCommandOutput;
fPID: Cardinal;
fTimeout: Cardinal;
procedure SetTimeout(const ms:Cardinal);
public
procedure Run(const Command, Parameters: String);
constructor Create;
destructor Destroy; override;
property OnOutput:TCatCSCommandOutput read fOnOutput write fOnOutput;
property PID: Cardinal read fPID;
property Timeout: Cardinal read fTimeout write SetTimeout;
end;
{$IFDEF DXE2_OR_UP}
procedure RunCmdWithCallBack(const Command: string; const Parameters: string;
CallBack: TCmdOutputArg<string>;const Timeout:dword=100);
{$ENDIF}
implementation
const
InheritHandleSecurityAttributes: TSecurityAttributes =
(nLength: SizeOf(TSecurityAttributes); bInheritHandle: True);
procedure TCatCSCommand.Run(const Command, Parameters: String);
var
hReadStdout, hWriteStdout: THandle;
si: TStartupInfo;
pi: TProcessInformation;
WaitRes, BytesRead: DWORD;
FileSize: Int64;
AnsiBuffer: array [0 .. 819200 - 1] of AnsiChar;
begin
Win32Check(CreatePipe(hReadStdout, hWriteStdout,
@InheritHandleSecurityAttributes, 0));
try
si := Default (TStartupInfo);
si.cb := SizeOf(TStartupInfo);
si.dwFlags := STARTF_USESTDHANDLES;
si.hStdOutput := hWriteStdout;
si.hStdError := hWriteStdout;
Win32Check(CreateProcess(nil, PChar(Command + ' ' + Parameters), nil, nil,
True, CREATE_NO_WINDOW, nil, nil, si, pi));
fPID := pi.dwProcessId;
try
while True do
begin
WaitRes := WaitForSingleObject(pi.hProcess, fTimeout);
Win32Check(WaitRes <> WAIT_FAILED);
while True do
begin
Win32Check(GetFileSizeEx(hReadStdout, FileSize));
if FileSize = 0 then
begin
break;
end;
Win32Check(ReadFile(hReadStdout, AnsiBuffer, SizeOf(AnsiBuffer) - 1,
BytesRead, nil));
if BytesRead = 0 then
begin
break;
end;
AnsiBuffer[BytesRead] := #0;
OemToAnsi(AnsiBuffer, AnsiBuffer);
if Assigned(fOnOutput) then
fOnOutput(string(AnsiBuffer));
end;
if WaitRes = WAIT_OBJECT_0 then
begin
break;
end;
end;
finally
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
end;
finally
CloseHandle(hReadStdout);
CloseHandle(hWriteStdout);
end;
end;
{$IFDEF DXE2_OR_UP}
procedure RunCmdWithCallBack(const Command: string; const Parameters: string;
CallBack: TCmdOutputArg<string>;const Timeout:dword=100);
var
hReadStdout, hWriteStdout: THandle;
si: TStartupInfo;
pi: TProcessInformation;
WaitRes, BytesRead: DWORD;
FileSize: Int64;
AnsiBuffer: array [0 .. 819200 -1] of AnsiChar; // original was 1024 -1
PID: Cardinal;
begin
Win32Check(CreatePipe(hReadStdout, hWriteStdout,
@InheritHandleSecurityAttributes, 0));
try
si := Default (TStartupInfo);
si.cb := SizeOf(TStartupInfo);
si.dwFlags := STARTF_USESTDHANDLES;
si.hStdOutput := hWriteStdout;
si.hStdError := hWriteStdout;
Win32Check(CreateProcess(nil, PChar(Command + ' ' + Parameters), nil, nil,
True, CREATE_NO_WINDOW, nil, nil, si, pi));
PID := pi.dwProcessId;
try
while True do
begin
WaitRes := WaitForSingleObject(pi.hProcess, Timeout);
Win32Check(WaitRes <> WAIT_FAILED);
while True do
begin
Win32Check(GetFileSizeEx(hReadStdout, FileSize));
if FileSize = 0 then
begin
break;
end;
Win32Check(ReadFile(hReadStdout, AnsiBuffer, SizeOf(AnsiBuffer) - 1,
BytesRead, nil));
if BytesRead = 0 then
begin
break;
end;
AnsiBuffer[BytesRead] := #0;
OemToAnsi(AnsiBuffer, AnsiBuffer);
if Assigned(CallBack) then
begin
CallBack(string(AnsiBuffer));
end;
end;
if WaitRes = WAIT_OBJECT_0 then
begin
break;
end;
end;
finally
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
end;
finally
CloseHandle(hReadStdout);
CloseHandle(hWriteStdout);
end;
end;
{$ENDIF}
procedure TCatCSCommand.SetTimeout(const ms:Cardinal);
begin
fTimeout := ms;
end;
constructor TCatCSCommand.Create;
begin
inherited Create;
SetTimeout(100);
end;
destructor TCatCSCommand.Destroy;
begin
inherited;
end;
end.
|
unit u_gen_svm;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
u_sem,
u_tokens,
u_ast_blocks,
u_ast_constructions_blocks,
u_ast_expression_blocks,
u_ast_expression;
type
TMashGeneratorSVM = class
public
constructor Create;
destructor Destroy; override;
procedure Generate(Sem: TMashSem; Outp: TStringList);
private
gcn: cardinal;
break_points, continue_points: TStringList;
procedure GenImports(Sem: TMashSem; Outp: TStringList);
procedure GenHeader(Sem: TMashSem; Outp: TStringList);
procedure GenEnums(Sem: TMashSem; Outp: TStringList);
procedure GenFinallyCode(Sem: TMashSem; Outp: TStringList);
function GenMethodHeader(Outp: TStringList; m: TMashASTB_Method): string;
procedure GenMethodEnd(Outp: TStringList; m: TMashASTB_Method; mname: string);
procedure NextNode(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
node: TMashASTBlock);
procedure GenOperation(Outp: TStringList; op: TMashTokenID);
procedure GenOperationLR(Outp: TStringList; op: TMashTokenID);
procedure GenArrayAlloc(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
IndexedObj: TMashASTP_IndexedObject);
procedure GenArrayOp(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
IndexedObj: TMashASTP_IndexedObject; targetOp: string);
procedure GenRefOp(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
RefObj: TMashASTP_Reference; targetOp: string);
procedure GenCall(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
Call: TMashASTP_Call);
end;
implementation
constructor TMashGeneratorSVM.Create;
begin
inherited Create;
self.gcn := 0;
self.break_points := TStringList.Create;
self.continue_points := TStringList.Create;
end;
destructor TMashGeneratorSVM.Destroy;
begin
FreeAndNil(self.break_points);
FreeAndNil(self.continue_points);
inherited;
end;
procedure TMashGeneratorSVM.Generate(Sem: TMashSem; Outp: TStringList);
var
c, j: cardinal;
mname: string;
m: TMashASTB_Method;
begin
GenImports(Sem, Outp);
GenHeader(Sem, Outp);
c := 0;
while c < sem.global_nodes.count do
begin
self.NextNode(Sem, Outp, false, '', nil, TMashASTBlock(Sem.global_nodes[c]));
Inc(c);
end;
c := 0;
while c < sem.methods.count do
begin
m := TMashASTB_Method(sem.methods[c]);
mname := self.GenMethodHeader(Outp, m);
j := 0;
while j < m.Nodes.count do
begin
self.NextNode(Sem, Outp, true, mname, m, TMashASTBlock(m.Nodes[j]));
Inc(j);
end;
self.GenMethodEnd(Outp, m, mname);
Inc(c);
end;
c := 0;
while c < sem.class_methods.count do
begin
m := TMashASTB_Method(sem.class_methods[c]);
mname := self.GenMethodHeader(Outp, m);
j := 0;
while j < m.Nodes.count do
begin
self.NextNode(Sem, Outp, true, mname, m, TMashASTBlock(m.Nodes[j]));
Inc(j);
end;
self.GenMethodEnd(Outp, m, mname);
Inc(c);
end;
GenFinallyCode(Sem, Outp);
end;
procedure TMashGeneratorSVM.GenImports(Sem: TMashSem; Outp: TStringList);
var
c: cardinal;
begin
c := 0;
while c < Sem.imp_lst.count do
begin
Outp.Add(
'import ' + TMashASTB_Import(Sem.imp_lst[c]).method_name +
' "' + TMashASTB_Import(Sem.imp_lst[c]).lib_name + '" "' +
TMashASTB_Import(Sem.imp_lst[c]).native_name + '"'
);
Inc(c);
end;
c := 0;
while c < Sem.regapi_lst.count do
begin
Outp.Add(
'import ' + TMashASTB_RegAPI(Sem.regapi_lst[c]).method_name +
' ' + TMashASTB_RegAPI(Sem.regapi_lst[c]).number
);
Inc(c);
end;
end;
procedure TMashGeneratorSVM.GenHeader(Sem: TMashSem; Outp: TStringList);
var
c: cardinal;
cnst: TMashASTB_Const;
begin
c := 0;
while c < Sem.const_lst.count do
begin
cnst := TMashASTB_Const(Sem.const_lst[c]);
if cnst.isStream then
Outp.Add('stream ' + cnst.const_name + ' "' + cnst.const_value.value + '"')
else
if cnst.const_value.info = ttString then
Outp.Add('str ' + cnst.const_name + ' "' + cnst.const_value.value + '"')
else
if pos('.', cnst.const_value.value) > 0 then
Outp.Add('real ' + cnst.const_name + ' ' + cnst.const_value.value)
else
if pos('-', cnst.const_value.value) > 0 then
Outp.Add('int ' + cnst.const_name + ' ' + cnst.const_value.value)
else
Outp.Add('word ' + cnst.const_name + ' ' + cnst.const_value.value);
Inc(c);
end;
c := 0;
while c < Sem.virtual_table.count do
begin
Outp.Add('word vtable__' + Sem.virtual_table[c] + ' ' + IntToStr(c));
Inc(c);
end;
Outp.Add('@global.arg_counter');
Outp.Add('@global.this');
Outp.Add('@global.temp');
Outp.Add('word global.zero 0');
Outp.Add('word global.one 1');
Outp.Add('str global.raised "ERaisedException"');
Outp.Add('pushc global.zero');
Outp.Add('peek global.arg_counter');
Outp.Add('pop');
c := 0;
while c < Sem.global_vars.count do
begin
Outp.Add('@' + Sem.global_vars[c]);
Inc(c);
end;
c := 0;
while c < Sem.classes_names.count do
begin
Outp.Add('word ' + Sem.classes_names[c] + ' ' + IntToStr(c + 8)); // 8 - offset for introspection
Outp.Add('@structure_instance_' + Sem.classes_names[c]);
Outp.Add('pushcp __allocator__' + Sem.classes_names[c]);
Outp.Add('jc');
Outp.Add('peek structure_instance_' + Sem.classes_names[c]);
Outp.Add('pop');
Inc(c);
end;
self.GenEnums(Sem, Outp);
Outp.Add('pushcp __init__');
Outp.Add('jc');
end;
procedure TMashGeneratorSVM.GenEnums(Sem: TMashSem; Outp: TStringList);
var
c, j: cardinal;
e: TMashASTB_Enum;
ei: TMashASTB_EnumItem;
begin
c := 0;
while c < Sem.enums.count do
begin
e := TMashASTB_Enum(Sem.enums[c]);
Outp.Add('@' + e.Name);
Outp.Add('word const.gcn.' + IntToStr(self.gcn) + ' ' + IntToStr(e.Nodes.count));
Outp.Add('pushcp const.gcn.' + IntToStr(self.gcn));
Outp.Add('pushcp global.one');
Outp.Add('newa');
Outp.Add('peek ' + e.Name);
Outp.Add('pushc global.zero');
Outp.Add('peek global.temp');
Outp.Add('pop');
j := 0;
while j < e.Nodes.count do
begin
ei := TMashASTB_EnumItem(e.Nodes[j]);
if ei.hasDefValue then
begin
if ei.DefValue.info = ttString then
Outp.Add('str ' + ei.Name + ' "' + ei.DefValue.value + '"')
else
if Pos('.', ei.DefValue.value) > 0 then
Outp.Add('real ' + ei.Name + ' ' + ei.DefValue.value)
else
if Pos('-', ei.DefValue.value) > 0 then
Outp.Add('int ' + ei.Name + ' ' + ei.DefValue.value)
else
Outp.Add('word ' + ei.Name + ' ' + ei.DefValue.value);
end
else
Outp.Add('word ' + ei.Name + ' ' + IntToStr(j));
Outp.Add('pcopy');
Outp.Add('pushc ' + ei.Name);
Outp.Add('swp');
Outp.Add('push global.temp');
Outp.Add('swp');
Outp.Add('peekai');
Outp.Add('push global.temp');
Outp.Add('inc');
Outp.Add('pop');
Inc(j);
end;
Outp.Add('pop');
Inc(Self.gcn);
Inc(c);
end;
end;
procedure TMashGeneratorSVM.GenFinallyCode(Sem: TMashSem; Outp: TStringList);
var
c, j: cardinal;
cl: TMashASTB_Class;
begin
if Sem.methods_names.IndexOf('main') <> -1 then
begin
Outp.Add('pushcp main');
Outp.Add('jc');
end;
Outp.Add('word __vtable__size__ ' + IntToStr(Sem.virtual_table.count));
c := 0;
while c < Sem.classes_lst.count do
begin
cl := TMashASTB_Class(Sem.classes_lst[c]);
Outp.Add('pushcp __allocator__' + cl.class_name + '__end');
Outp.Add('jp');
Outp.Add('__allocator__' + cl.class_name + ':');
Outp.Add('pushcp __vtable__size__');
Outp.Add('pushcp global.one');
Outp.Add('newa');
Outp.Add('typemarkclass');
Outp.Add('pcopy');
Outp.Add('pushc ' + cl.class_name);
Outp.Add('swp');
Outp.Add('pushcp vtable__type');
Outp.Add('swp');
Outp.Add('peekai');
j := 0;
while j < cl.class_methods.count do
begin
Outp.Add('pcopy');
Outp.Add('pushc ' + TMashClassMethodReference(cl.class_methods[j]).reference.class_name + '__' + TMashClassMethodReference(cl.class_methods[j]).reference.method_name);
Outp.Add('swp');
Outp.Add('pushcp vtable__' + TMashClassMethodReference(cl.class_methods[j]).method_name);
Outp.Add('swp');
Outp.Add('peekai');
Inc(j);
end;
Outp.Add('jr');
Outp.Add('__allocator__' + cl.class_name + '__end:');
Inc(c);
end;
end;
function TMashGeneratorSVM.GenMethodHeader(Outp: TStringList; m: TMashASTB_Method): string;
var
c: cardinal;
mname: string;
p: TMashASTB_Param;
begin
mname := '';
if m.is_class_method then
mname := m.class_name + '__';
mname := mname + m.method_name;
Result := mname;
Outp.Add('pushcp ' + mname + '__end');
Outp.Add('jp');
Outp.Add(mname + ':');
c := 0;
while c < m.local_vars.count do
begin
Outp.Add('@' + mname + '.' + m.local_vars[c]);
Inc(c);
end;
Outp.Add('pushcp safecall_' + mname + '.finally');
Outp.Add('pushcp safecall_' + mname + '.catch');
Outp.Add('tr');
c := 0;
while c < m.params.count do
begin
p := TMashASTB_Param(m.params[c]);
if p.is_enumerable then
begin
Outp.Add('word const.gcn.' + IntToStr(self.gcn) + ' ' + IntToStr(m.params.count - 1));
Outp.Add('pushcp const.gcn.' + IntToStr(self.gcn));
Outp.Add('push global.arg_counter');
Outp.Add('sub');
Outp.Add('pushcp system_op_argsarr');
Outp.Add('jc');
Outp.Add('peek ' + mname + '.' + p.param.value);
Outp.Add('pop');
Inc(self.gcn);
end
else
begin
Outp.Add('peek ' + mname + '.' + p.param.value);
Outp.Add('pop');
end;
Inc(c);
end;
if m.is_class_method then
begin
Outp.Add('push global.this');
Outp.Add('peek ' + mname + '.this');
Outp.Add('pop');
end;
end;
procedure TMashGeneratorSVM.GenMethodEnd(Outp: TStringList; m: TMashASTB_Method; mname: string);
var
w: word;
begin
w := 0;
Outp.Add('pushn');
while w < m.local_vars.count do
begin
Outp.Add('peek ' + mname + '.' + m.local_vars[w]);
inc(w);
end;
Outp.Add('pop');
Outp.Add('trs');
Outp.Add('safecall_' + mname + '.catch:');
Outp.Add('peek global.temp');
Outp.Add('pushcp ' + mname);
Outp.Add('push global.temp');
Outp.Add('bg');
Outp.Add('push global.temp');
Outp.Add('pushcp ' + mname + '__end');
Outp.Add('bg');
Outp.Add('and');
Outp.Add('pushcp safecall_' + mname + '.catch_stkctrl_noneed');
Outp.Add('swp');
Outp.Add('jn');
Outp.Add('pop');
// clean
w := 0;
while w < m.local_vars.Count do
begin
Outp.Add('rld');
Outp.Add('pop');
Inc(w);
end;
Outp.Add('jrp');
Outp.Add('safecall_' + mname + '.catch_stkctrl_noneed:');
Outp.Add('rst');
Outp.Add('rst');
Outp.Add('rst');
Outp.Add('pushc ' + mname);
Outp.Add('str safecall_' + mname + '.m_info "' + mname + '"');
Outp.Add('pushc safecall_' + mname + '.m_info');
Outp.Add('push global.temp');
Outp.Add('pushcp system_traceback');
Outp.Add('jc');
Outp.Add('rld');
Outp.Add('rld');
Outp.Add('rld');
Outp.Add('trr');
Outp.Add('safecall_' + mname + '.finally:');
Outp.Add('jr');
Outp.Add(mname + '__end:');
end;
procedure TMashGeneratorSVM.NextNode(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
node: TMashASTBlock);
var
p: pointer;
i: integer;
s: string;
b: boolean;
begin
case node.GetType of
// Expressions
btEOperation:
begin
if TMashASTE_Operation(node).Op.Op.short = tkNew then
begin
if (TMashASTE_Operation(node).A.GetType = btPCall) and
(TMashASTP_Call(TMashASTE_Operation(node).A).Obj.GetType = btPSimpleObject) then
begin
if TMashASTP_SimpleObject(TMashASTP_Call(TMashASTE_Operation(node).A).Obj).Obj.info = ttWord then
begin // Correct constructor call
if isMethodNode then
begin
i := 0;
while i < method.local_vars.count do
begin
Outp.Add('push ' + mname + '.' + method.local_vars[i]);
Outp.Add('rst');
Inc(i);
end;
end;
Outp.Add('pushcp __allocator__' + TMashASTP_SimpleObject(TMashASTP_Call(TMashASTE_Operation(node).A).Obj).Obj.value);
Outp.Add('jc');
s := 'constructor_call.temp.gcn.' + IntToStr(self.gcn);
Inc(self.gcn);
Outp.Add('@' + s);
Outp.Add('peek ' + s);
Outp.Add('pop');
i := TMashASTP_Call(TMashASTE_Operation(node).A).Args.Objects.count - 1;
while i >= 0 do
begin
self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTP_Call(TMashASTE_Operation(node).A).Args.Objects[i]));
Dec(i);
end;
Outp.Add('push ' + s);
Outp.Add('peek global.this');
Outp.Add('pushcp vtable__create');
Outp.Add('swp');
Outp.Add('pushai');
Outp.Add('word const.gcn.' + IntToStr(self.gcn) + ' ' + IntToStr(TMashASTP_Call(TMashASTE_Operation(node).A).Args.Objects.count));
Outp.Add('pushcp const.gcn.' + IntToStr(self.gcn));
Outp.Add('push global.arg_counter');
Outp.Add('mov');
Inc(self.gcn);
Outp.Add('jc');
Outp.Add('push ' + s);
if isMethodNode then
begin
i := method.local_vars.count - 1;
while i >= 0 do
begin
Outp.Add('rld');
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
Dec(i);
end;
end;
end
else
raise Exception.Create(
'Uncorrect using of ''new'' operator.'
);
end
else
if (TMashASTE_Operation(node).A.GetType = btPSimpleObject) and
(TMashASTP_SimpleObject(TMashASTE_Operation(node).A).Obj.info = ttWord) then
begin // Correct allocation
Outp.Add('pushcp __allocator__' + TMashASTP_SimpleObject(TMashASTE_Operation(node).A).Obj.value);
Outp.Add('jc');
end
else
raise Exception.Create(
'Uncorrect using of ''new'' operator.'
);
end
else // Simple operations
begin
self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_Operation(node).A);
self.GenOperation(Outp, TMashASTE_Operation(node).Op.Op.short);
end;
end;
btEOperationLR:
begin
if TMashASTE_OperationLR(Node).Op.Op.short = tkAssign then
begin
case TMashASTE_OperationLR(Node).L.GetType of
btPSimpleObject:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).R);
s := TMashASTP_SimpleObject(TMashASTE_OperationLR(Node).L).Obj.value;
b := Sem.global_vars.IndexOf(s) <> -1;
if (not b) and isMethodNode then
b := method.local_vars.IndexOf(s) <> -1;
if not b then
raise Exception.Create('Invalid assigment for ''' + s + '''.');
if isMethodNode and (method.local_vars.IndexOf(s) <> -1) then
Outp.Add('peek ' + mname + '.' + s)
else
Outp.Add('peek ' + s);
Outp.Add('pop');
end;
btPIndexedObject:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).R);
Self.GenArrayOp(Sem, Outp, isMethodNode, mname, method,
TMashASTP_IndexedObject(TMashASTE_OperationLR(Node).L),
'peekai');
end;
btPReference:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).R);
Self.GenRefOp(Sem, Outp, isMethodNode, mname, method,
TMashASTP_Reference(TMashASTE_OperationLR(Node).L),
'peekai');
end;
end;
end
else
begin
if TMashASTE_OperationLR(Node).Op.Op.short = tkDot then
begin
if TMashASTE_OperationLR(Node).R.GetType = btPCall then
begin
TMashASTP_Call(TMashASTE_OperationLR(Node).R).Args.Objects.Insert(
0, TMashASTE_OperationLR(Node).L
);
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).R);
end
else
raise Exception.Create('Invalid operations with ''.''!');
end
else
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).R);
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTE_OperationLR(Node).L);
Self.GenOperationLR(Outp, TMashASTE_OperationLR(Node).Op.Op.short);
end;
end;
end;
btPSimpleObject:
begin
case TMashASTP_SimpleObject(Node).Obj.info of
ttDigit:
begin
if Pos('.', TMashASTP_SimpleObject(Node).Obj.value) > 0 then
Outp.Add('real generator.const.gcn.' + IntToStr(self.gcn) + ' ' + TMashASTP_SimpleObject(Node).Obj.value)
else
Outp.Add('word generator.const.gcn.' + IntToStr(self.gcn) + ' ' + TMashASTP_SimpleObject(Node).Obj.value);
Outp.Add('pushc generator.const.gcn.' + IntToStr(self.gcn));
Inc(self.gcn);
end;
ttString:
begin
Outp.Add('str generator.const.gcn.' + IntToStr(self.gcn) + ' "' + TMashASTP_SimpleObject(Node).Obj.value + '"');
Outp.Add('pushc generator.const.gcn.' + IntToStr(self.gcn));
Inc(self.gcn);
end;
ttWord:
begin
s := TMashASTP_SimpleObject(Node).Obj.value;
if (Sem.methods_names.IndexOf(s) <> -1) or
(Sem.imports.IndexOf(s) <> -1) or
(Sem.consts.IndexOf(s) <> -1) then
Outp.Add('pushc ' + s)
else
begin
if isMethodNode then
if (method.local_vars.IndexOf(s) <> -1) and (Sem.global_vars.IndexOf(s) = -1) then
s := mname + '.' + s;
Outp.Add('push ' + s);
end;
end;
end;
end;
btPReference:
Self.GenRefOp(Sem, Outp, isMethodNode, mname, method,
TMashASTP_Reference(Node), 'pushai');
btPIndexedObject:
begin
b := false;
if TMashASTP_IndexedObject(Node).Obj.GetType = btPSimpleObject then
if TMashASTP_SimpleObject(TMashASTP_IndexedObject(Node).Obj).Obj.value = 'new' then
begin
b := true;
Self.GenArrayAlloc(Sem, Outp, isMethodNode, mname, method, TMashASTP_IndexedObject(Node));
end;
if not b then
Self.GenArrayOp(Sem, Outp, isMethodNode, mname, method,
TMashASTP_IndexedObject(Node), 'pushai');
end;
btPCall:
Self.GenCall(Sem, Outp, isMethodNode, mname, method, TMashASTP_Call(Node));
btPEnum:
begin
i := TMashASTP_Enum(Node).Objects.Count;
Outp.Add('word generator.const.gcn.' + IntToStr(Self.gcn) + ' ' + IntToStr(i));
Outp.Add('pushcp generator.const.gcn.' + IntToStr(Self.gcn));
Inc(Self.gcn);
Outp.Add('pushcp global.one');
Outp.Add('newa');
Outp.Add('rst');
i := 0;
while i < TMashASTP_Enum(Node).Objects.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTP_Enum(Node).Objects[i]));
Outp.Add('rld');
Outp.Add('pcopy');
Outp.Add('rst');
Outp.Add('word generator.const.gcn.' + IntToStr(Self.gcn) + ' ' + IntToStr(i));
Outp.Add('pushcp generator.const.gcn.' + IntToStr(Self.gcn));
Inc(Self.gcn);
Outp.Add('swp');
Outp.Add('peekai');
Inc(i);
end;
Outp.Add('rld');
end;
btExpression:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTExpression(TMashASTB_Expression(Node).ast).TreeNode);
end;
// Constructions
btInline:
begin
s := TMashASTB_Inline(Node).asm_string;
if (pos('$', s) > 0) and isMethodNode then
s := StringReplace(s, '$', mname + '.', [rfReplaceAll]);
Outp.Add(s);
end;
btIf:
begin
s := 'generator.if.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Outp.Add('pushcp ' + s + '.else');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_If(Node).Expr);
Outp.Add('jz');
Outp.Add('pop');
i := 0;
while i < TMashASTB_If(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_If(Node).Nodes[i]));
Inc(i);
end;
if TMashASTB_If(Node).hasElse then
begin
Outp.Add('pushcp ' + s + '.end');
Outp.Add('jp');
Outp.Add(s + '.else:');
i := 0;
while i < TMashASTB_If(Node).ElseNodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_If(Node).ElseNodes[i]));
Inc(i);
end;
Outp.Add(s + '.end:');
end
else
Outp.Add(s + '.else:');
end;
btWhile:
begin
s := 'generator.while.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.break_points.Add(s + '.end');
Self.continue_points.Add(s + '.start');
Outp.Add(s + '.start:');
Outp.Add('pushcp ' + s + '.end');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_While(Node).Expr);
Outp.Add('jz');
Outp.Add('pop');
i := 0;
while i < TMashASTB_While(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_While(Node).Nodes[i]));
Inc(i);
end;
Outp.Add('pushcp ' + s + '.start');
Outp.Add('jp');
Outp.Add(s + '.end:');
Self.break_points.Delete(Self.break_points.Count - 1);
Self.continue_points.Delete(Self.continue_points.Count - 1);
end;
btWhilst:
begin
s := 'generator.whilst.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.break_points.Add(s + '.end');
Self.continue_points.Add(s + '.start');
Outp.Add(s + '.start:');
i := 0;
while i < TMashASTB_Whilst(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Whilst(Node).Nodes[i]));
Inc(i);
end;
Outp.Add('pushcp ' + s + '.start');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Whilst(Node).Expr);
Outp.Add('jn');
Outp.Add('pop');
Outp.Add(s + '.end:');
Self.break_points.Delete(Self.break_points.Count - 1);
Self.continue_points.Delete(Self.continue_points.Count - 1);
end;
btForEach:
begin
s := 'generator.foreach.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.break_points.Add(s + '.end');
Self.continue_points.Add(s + '.continue');
Outp.Add('@' + s + '.array');
Outp.Add('@' + s + '.i');
Outp.Add('@' + s + '.to');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_ForEach(Node).Expr);
Outp.Add('peek ' + s + '.array');
Outp.Add('alen');
if TMashASTB_ForEach(Node).isBack then
begin
Outp.Add('peek ' + s + '.i');
Outp.Add('dec');
Outp.Add('pop');
Outp.Add('pushc global.zero');
Outp.Add('peek ' + s + '.to');
Outp.Add('dec');
Outp.Add('pop');
end
else
begin
Outp.Add('peek ' + s + '.to');
Outp.Add('pop');
Outp.Add('pushc global.zero');
Outp.Add('peek ' + s + '.i');
Outp.Add('pop');
end;
Outp.Add(s + '.start:');
Outp.Add('pushcp ' + s + '.end');
Outp.Add('push ' + s + '.i');
Outp.Add('push ' + s + '.to');
Outp.Add('eq');
Outp.Add('not');
Outp.Add('jz');
Outp.Add('pop');
Outp.Add('push ' + s + '.i');
Outp.Add('push ' + s + '.array');
Outp.Add('pushai');
if isMethodNode then
Outp.Add('peek ' + mname + '.' + TMashASTB_ForEach(Node).forVar)
else
Outp.Add('peek ' + TMashASTB_ForEach(Node).forVar);
Outp.Add('pop');
i := 0;
while i < TMashASTB_ForEach(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_While(Node).Nodes[i]));
Inc(i);
end;
Outp.Add(s + '.continue:');
Outp.Add('push ' + s + '.i');
if TMashASTB_ForEach(Node).isBack then
Outp.Add('dec')
else
Outp.Add('inc');
Outp.Add('pop');
Outp.Add('pushcp ' + s + '.start');
Outp.Add('jp');
Outp.Add(s + '.end:');
Self.break_points.Delete(Self.break_points.Count - 1);
Self.continue_points.Delete(Self.continue_points.Count - 1);
end;
btReturn:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Return(Node).Expr);
Outp.Add('trs');
end;
btBreak:
begin
if Self.break_points.Count > 0 then
begin
Outp.Add('pushcp ' + Self.break_points[Self.break_points.Count - 1]);
Outp.Add('jp');
end
else
raise Exception.Create('Bad ''break'' position. Can''t jump out of code here.');
end;
btContinue:
begin
if Self.continue_points.Count > 0 then
begin
Outp.Add('pushcp ' + Self.continue_points[Self.continue_points.Count - 1]);
Outp.Add('jp');
end
else
raise Exception.Create('Bad ''continue'' position. Can''t jump from here.');
end;
btSwitch:
begin
s := 'generator.switch.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.break_points.Add(s + '.end');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Switch(Node).Expr);
i := 0;
while i < TMashASTB_Switch(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Switch(Node).Nodes[i]));
Inc(i);
end;
if TMashASTB_Switch(Node).hasElse then
begin
i := 0;
while i < TMashASTB_Case(TMashASTB_Switch(Node).ElseCase).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Case(TMashASTB_Switch(Node).ElseCase).Nodes[i]));
Inc(i);
end;
end;
Outp.Add(s + '.end:');
Self.break_points.Delete(Self.break_points.Count - 1);
end;
btCase:
begin
s := 'generator.case.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Outp.Add('pcopy');
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Case(Node).Expr);
Outp.Add('eq');
Outp.Add('pushcp ' + s + '.end');
Outp.Add('swp');
Outp.Add('jz');
i := 0;
while i < TMashASTB_Case(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Case(Node).Nodes[i]));
Inc(i);
end;
Outp.Add('pushcp ' + Self.break_points[Self.break_points.Count - 1]);
Outp.Add('jp');
Outp.Add(s + '.end:');
end;
btLaunch:
begin
s := 'generator.launch.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
if isMethodNode then
begin
i := 0;
while i < method.local_vars.count do
begin
Outp.Add('push ' + mname + '.' + method.local_vars[i]);
Outp.Add('copy');
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
Inc(i);
end;
end;
Outp.Add('pushn');
Outp.Add('pushcp ' + s + '.start');
Outp.Add('cthr');
Outp.Add('rthr');
Outp.Add('pushcp ' + s + '.end');
Outp.Add('jp');
Outp.Add(s + '.start:');
Outp.Add('pop');
Outp.Add('pushcp system_reset_traceback');
Outp.Add('jc');
i := 0;
while i < TMashASTB_Launch(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Launch(Node).Nodes[i]));
Inc(i);
end;
Outp.Add('jr');
Outp.Add(s + '.end:');
if isMethodNode then
begin
i := method.local_vars.count - 1;
while i >= 0 do
begin
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
Dec(i);
end;
end;
end;
btAsync:
begin
s := 'generator.async.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
if isMethodNode then
begin
i := 0;
while i < method.local_vars.count do
begin
if method.local_vars[i] <> TMashASTB_Async(Node).forVar then
begin
Outp.Add('push ' + mname + '.' + method.local_vars[i]);
Outp.Add('copy');
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
end;
Inc(i);
end;
end;
Outp.Add('pushc global.zero');
if isMethodNode then
Outp.Add('peek ' + mname + '.' + TMashASTB_Async(Node).forVar)
else
Outp.Add('peek ' + TMashASTB_Async(Node).forVar);
Outp.Add('pop');
Outp.Add('pushn');
Outp.Add('pushcp ' + s + '.start');
Outp.Add('cthr');
Outp.Add('rthr');
Outp.Add('pushcp ' + s + '.end');
Outp.Add('jp');
Outp.Add(s + '.start:');
Outp.Add('pop');
Outp.Add('pushcp system_reset_traceback');
Outp.Add('jc');
i := 0;
while i < TMashASTB_Async(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Async(Node).Nodes[i]));
Inc(i);
end;
if isMethodNode then
Outp.Add('push ' + mname + '.' + TMashASTB_Async(Node).forVar)
else
Outp.Add('push ' + TMashASTB_Async(Node).forVar);
Outp.Add('inc');
Outp.Add('pop');
Outp.Add('jr');
Outp.Add(s + '.end:');
if isMethodNode then
begin
i := method.local_vars.count - 1;
while i >= 0 do
begin
if method.local_vars[i] <> TMashASTB_Async(Node).forVar then
begin
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
end;
Dec(i);
end;
end;
end;
btWait:
begin
s := 'generator.wait.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Wait(Node).Expr);
Outp.Add('pushcp ' + s + '.check');
Outp.Add('jp');
Outp.Add(s + '.start:');
Outp.Add('pushcp global.one');
Outp.Add('pushcp sleep');
Outp.Add('invoke');
Outp.Add(s + '.check:');
Outp.Add('pcopy');
Outp.Add('pushcp ' + s + '.start');
Outp.Add('swp');
Outp.Add('jz');
Outp.Add('pop');
Outp.Add('pop');
end;
btTry:
begin
s := 'generator.try.gcn.' + IntToStr(Self.gcn);
Inc(Self.gcn);
Self.break_points.Add(s + '.break');
Outp.Add('pushcp ' + s + '.finally');
Outp.Add('pushcp ' + s + '.catch');
Outp.Add('tr');
i := 0;
while i < TMashASTB_Try(Node).Nodes.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Try(Node).Nodes[i]));
Inc(i);
end;
Outp.Add(s + '.break:');
Outp.Add('trs');
Self.break_points.Delete(Self.break_points.Count - 1);
Self.break_points.Add(s + '.finally');
Outp.Add(s + '.catch:');
if isMethodNode then
begin
Outp.Add('peek global.temp');
Outp.Add('pushcp ' + mname);
Outp.Add('push global.temp');
Outp.Add('bg');
Outp.Add('push global.temp');
Outp.Add('pushcp ' + mname + '__end');
Outp.Add('bg');
Outp.Add('and');
Outp.Add('pushcp ' + s + '.catch_stkctrl_noneed');
Outp.Add('swp');
Outp.Add('jn');
Outp.Add('pop');
// clean
i := 0;
while i < method.local_vars.Count do
begin
Outp.Add('rld');
Outp.Add('pop');
Inc(i);
end;
Outp.Add('jrp');
Outp.Add(s + '.catch_stkctrl_noneed:');
end;
if TMashASTB_Try(Node).hasCatch then
begin
if isMethodNode then
begin
Outp.Add('pcopy');
Outp.Add('rst');
Outp.Add('swp');
Outp.Add('rst');
Outp.Add('swp');
Outp.Add('rst');
Outp.Add('pushc ' + mname);
Outp.Add('swp');
Outp.Add('str ' + s + '.m_info "' + mname + '"');
Outp.Add('pushc ' + s + '.m_info');
Outp.Add('swp');
Outp.Add('pushcp system_traceback');
Outp.Add('jc');
Outp.Add('rld');
Outp.Add('rld');
Outp.Add('rld');
end;
Outp.Add('pushcp system_makeexception');
Outp.Add('jc');
if isMethodNode then
Outp.Add('peek ' + mname + '.' + TMashASTB_Try(Node).forVar)
else
Outp.Add('peek ' + TMashASTB_Try(Node).forVar);
Outp.Add('pop');
Outp.Add('pushcp system_reset_traceback');
Outp.Add('jc');
i := 0;
while i < TMashASTB_Try(Node).NodesCatch.Count do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(TMashASTB_Try(Node).NodesCatch[i]));
Inc(i);
end;
end
else
begin
Outp.Add('pop');
Outp.Add('pop');
Outp.Add('pop');
Outp.Add('pushcp system_reset_traceback');
Outp.Add('jc');
end;
Outp.Add(s + '.finally:');
Self.break_points.Delete(Self.break_points.Count - 1);
end;
btRaise:
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Raise(Node).Expr);
Outp.Add('pushc global.raised');
Outp.Add('pushc ' + mname);
Outp.Add('inc');
Outp.Add('trr');
end;
{ btSafe:
begin
if isMethodNode then
begin
i := 0;
while i < method.local_vars.count do
begin
Outp.Add('push ' + mname + '.' + method.local_vars[i]);
Outp.Add('rst');
Inc(i);
end;
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Safe(Node).Expr);
i := method.local_vars.count - 1;
while i >= 0 do
begin
Outp.Add('rld');
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
Dec(i);
end;
end
else
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTB_Safe(Node).Expr);
end;}
end;
end;
procedure TMashGeneratorSVM.GenCall(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
Call: TMashASTP_Call);
function FindReference(Cls: TMashASTB_Class; mn: string): TMashClassMethodReference;
var
k, d, p: word;
pCls: TMashASTB_Class;
mr: TMashClassMethodReference;
begin
Result := nil;
k := 0;
while k < Cls.class_parents.Count do
begin
d := 0;
while d < Sem.classes_lst.count do
begin
pCls := TMashASTB_Class(Sem.classes_lst[d]);
if pCls.class_name = Cls.class_parents[k] then
begin
p := 0;
while p < pCls.class_methods.count do
begin
mr := TMashClassMethodReference(pCls.class_methods[p]);
if mr.method_name = mn then
begin
Result := mr;
break;
end;
Inc(p);
end;
if (pCls.class_parents.count > 0) and (Result = nil) then
Result := FindReference(pCls, mn);
end;
if Result <> nil then
break;
Inc(d);
end;
if Result <> nil then
break;
Inc(k);
end;
end;
var
isSuper, isInvoke, founded: boolean;
i, j: integer;
SuperRef: TMashClassMethodReference;
begin
isSuper := false;
isInvoke := false;
if Call.Obj.GetType = btPSimpleObject then
if TMashASTP_SimpleObject(Call.Obj).Obj.value = 'super' then
isSuper := true
else
if Sem.imports.IndexOf(TMashASTP_SimpleObject(Call.Obj).Obj.value) <> -1 then
isInvoke := true;
if isMethodNode and (not isInvoke) then
begin
i := 0;
while i < method.local_vars.count do
begin
Outp.Add('push ' + mname + '.' + method.local_vars[i]);
Outp.Add('rst');
Inc(i);
end;
end;
i := Call.Args.Objects.count - 1;
while i >= 0 do
begin
Self.NextNode(Sem, Outp, isMethodNode, mname, method,
TMashASTBlock(Call.Args.Objects[i]));
Dec(i);
end;
if isSuper then
begin
if isMethodNode then
begin
if method.is_class_method then
begin
founded := false;
i := 0;
while i < Sem.classes_lst.Count do
begin
if TMashASTB_Class(Sem.classes_lst[i]).class_name = method.class_name then
begin
SuperRef := FindReference(TMashASTB_Class(Sem.classes_lst[i]), method.method_name);
founded := true;
break;
end;
Inc(i);
end;
if founded then
begin
Outp.Add('push ' + mname + '.this');
Outp.Add('peek global.this');
Outp.Add('pop');
Outp.Add('pushcp ' + SuperRef.reference.class_name + '__' + SuperRef.reference.method_name);
end
else
raise Exception.Create('super() - reference not resolved.');
end
else
raise Exception.Create('Using super() over class method.');
end
else
raise Exception.Create('Using super() over class method.');
end
else
Self.NextNode(Sem, Outp, isMethodNode, mname, method, Call.Obj);
if isInvoke then
Outp.Add('invoke')
else
begin
Outp.Add('word generator.const.gcn.' + IntToStr(Self.gcn) + ' ' +
IntToStr(Call.Args.Objects.Count));
Outp.Add('pushcp generator.const.gcn.' + IntToStr(Self.gcn));
Outp.Add('push global.arg_counter');
Outp.Add('mov');
Inc(Self.gcn);
Outp.Add('jc');
if isMethodNode then
begin
i := method.local_vars.count - 1;
while i >= 0 do
begin
Outp.Add('rld');
Outp.Add('peek ' + mname + '.' + method.local_vars[i]);
Outp.Add('pop');
Dec(i);
end;
end;
end;
end;
procedure TMashGeneratorSVM.GenArrayAlloc(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
IndexedObj: TMashASTP_IndexedObject);
var
i: integer;
begin
i := IndexedObj.Indexes.count - 1;
while i >= 0 do
begin
self.NextNode(Sem, Outp, isMethodNode, mname, method, TMashASTBlock(IndexedObj.Indexes[i]));
Dec(i);
end;
Outp.Add('word const.gcn.' + IntToStr(self.gcn) + ' ' + IntToStr(IndexedObj.Indexes.count));
Outp.Add('pushcp const.gcn.' + IntToStr(self.gcn));
Outp.Add('newa');
Inc(self.gcn);
end;
procedure TMashGeneratorSVM.GenArrayOp(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
IndexedObj: TMashASTP_IndexedObject;
targetOp: string);
var
i: integer;
begin
self.NextNode(Sem, Outp, isMethodNode, mname, method, IndexedObj.Obj);
i := 0;
while i < IndexedObj.Indexes.count do
begin
self.NextNode(Sem, Outp, isMethodNode, mname, method, TMashASTBlock(IndexedObj.Indexes[i]));
Outp.Add('swp');
Inc(i);
if i < IndexedObj.Indexes.count then
Outp.Add('pushai')
else
Outp.Add(targetOp);
end;
end;
procedure TMashGeneratorSVM.GenRefOp(Sem: TMashSem; Outp: TStringList;
isMethodNode: boolean; mname: string; method: TMashASTB_Method;
RefObj: TMashASTP_Reference;
targetOp: string);
var
i: integer;
first: TMashASTBlock;
isPkg: boolean;
cnt: word;
begin
first := TMashASTBlock(RefObj.ObjPath[0]);
isPkg := false;
if first.GetType = btPSimpleObject then
if TMashASTP_SimpleObject(first).Obj.info = ttWord then
if Sem.classes_names.IndexOf(TMashASTP_SimpleObject(first).Obj.value) <> -1 then
begin
isPkg := true;
Outp.Add('push structure_instance_' + TMashASTP_SimpleObject(first).Obj.value);
end;
if not isPkg then
self.NextNode(Sem, Outp, isMethodNode, mname, method, first);
i := 1;
cnt := RefObj.ObjPath.Count;
while i < cnt do
begin
if i + 1 >= cnt then
Outp.Add('peek global.this');
if TMashASTBlock(RefObj.ObjPath[i]).GetType = btPSimpleObject then
Outp.Add('pushcp ' + TMashASTP_SimpleObject(RefObj.ObjPath[i]).Obj.value)
else
self.NextNode(Sem, Outp, isMethodNode, mname, method, TMashASTBlock(RefObj.ObjPath[i]));
Outp.Add('swp');
Inc(i);
if i < cnt then
Outp.Add('pushai')
else
Outp.Add(targetOp);
end;
end;
procedure TMashGeneratorSVM.GenOperation(Outp: TStringList; op: TMashTokenID);
begin
case op of
tkGVBP:
Outp.Add('gvbp');
tkGP:
begin
Outp.Add('new');
Outp.Add('peek global.temp');
Outp.Add('movp');
Outp.Add('push global.temp');
end;
tkNotSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('not');
end;
tkSubSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('neg');
end;
tkInc:
begin
Outp.Add('inc');
Outp.Add('pop');
end;
tkDec:
begin
Outp.Add('dec');
Outp.Add('pop');
end;
end;
end;
procedure TMashGeneratorSVM.GenOperationLR(Outp: TStringList; op: TMashTokenID);
begin
case op of
tkAddSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('add');
end;
tkSubSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('sub');
end;
tkMulSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('mul');
end;
tkDivSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('div');
end;
tkIDivSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('idiv');
end;
tkModSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('mod');
end;
tkAndSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('and');
end;
tkOrSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('or');
end;
tkXorSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('xor');
end;
tkShlSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('shl');
end;
tkShrSym:
begin
Outp.Add('copy');
Outp.Add('swp');
Outp.Add('pop');
Outp.Add('shr');
end;
tkBg:
Outp.Add('bg');
tkBEq:
Outp.Add('be');
tkEq:
Outp.Add('eq');
tkNEq:
begin
Outp.Add('eq');
Outp.Add('not');
end;
tkSm:
begin
Outp.Add('swp');
Outp.Add('bg');
end;
tkSEq:
begin
Outp.Add('swp');
Outp.Add('be');
end;
tkIn:
begin
Outp.Add('pushcp system_op_in');
Outp.Add('jc');
end;
tkIs:
begin
Outp.Add('pushcp system_op_is');
Outp.Add('jc');
end;
tkRange:
begin
Outp.Add('pushcp system_op_range');
Outp.Add('jc');
end;
tkAdd:
begin
Outp.Add('add');
Outp.Add('pop');
end;
tkSub:
begin
Outp.Add('sub');
Outp.Add('pop');
end;
tkMul:
begin
Outp.Add('mul');
Outp.Add('pop');
end;
tkDiv:
begin
Outp.Add('div');
Outp.Add('pop');
end;
tkIDiv:
begin
Outp.Add('idiv');
Outp.Add('pop');
end;
tkMod:
begin
Outp.Add('mod');
Outp.Add('pop');
end;
tkAnd:
begin
Outp.Add('and');
Outp.Add('pop');
end;
tkOr:
begin
Outp.Add('or');
Outp.Add('pop');
end;
tkXor:
begin
Outp.Add('xor');
Outp.Add('pop');
end;
tkShl:
begin
Outp.Add('shl');
Outp.Add('pop');
end;
tkShr:
begin
Outp.Add('shr');
Outp.Add('pop');
end;
tkMov:
Outp.Add('mov');
tkMovBP:
Outp.Add('mvbp');
end;
end;
end.
|
unit DSA.Sorts.HeapSort;
interface
uses
System.SysUtils,
System.Math,
DSA.Interfaces.Comparer,
DSA.Utils,
DSA.Tree.Heap;
type
THeapSort<T> = class
private type
TArr_T = TArray<T>;
ICmp_T = IComparer<T>;
TCmp_T = TComparer<T>;
THeap_T = THeap<T>;
var
class var __cmp: ICmp_T;
class procedure __shiftDwon(var arr: TArr_T; k: integer; Count: integer);
public
/// <summary> 使用THeap类 </summary>
class procedure Sort(var arr: TArr_T; cmp: ICmp_T);
/// <summary> 原地排序 </summary>
class procedure Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
uses
DSA.Sorts.QuickSort,
DSA.Sorts.MergeSort;
type
THeapSort_int = THeapSort<integer>;
TMergeSort_int = TMergeSort<integer>;
TQuickSort_int = TQuickSort<integer>;
procedure Main;
var
sourceArr, targetArr: TArray_int;
n, swapTimes: integer;
begin
n := 1000000;
WriteLn('Test for random array, size = ', n, ', random range [0, ', n, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, n);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
Free;
end;
swapTimes := 100;
WriteLn('Test for nearly ordered array, size = ', n, ', swap time = ',
swapTimes);
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateNearlyOrderedArray(n, swapTimes);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
Free;
end;
WriteLn('Test for random array, size = ', n, ', random range [0, ', 10, ']');
with TSortTestHelper_int.Create do
begin
sourceArr := GenerateRandomArray(n, 10);
targetArr := CopyArray(sourceArr);
TestSort('MergeSort'#9#9, targetArr, TMergeSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('QuickSort3Ways'#9#9, targetArr, TQuickSort_int.Sort3Ways);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort'#9#9, targetArr, THeapSort_int.Sort);
targetArr := CopyArray(sourceArr);
TestSort('HeapSort_Adv'#9#9, targetArr, THeapSort_int.Sort_Adv);
Free;
end;
end;
{ THeapSort<T> }
class procedure THeapSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T);
var
heapMin: THeap_T;
i: integer;
begin
heapMin := THeap_T.Create(arr);
for i := 0 to Length(arr) - 1 do
arr[i] := heapMin.ExtractFirst;
end;
class procedure THeapSort<T>.Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
var
i: integer;
tmp: T;
begin
__cmp := cmp;
for i := (Length(arr) - 1 - 1) div 2 downto 0 do
__shiftDwon(arr, i, Length(arr));
for i := Length(arr) - 1 downto 1 do
begin
tmp := arr[0];
arr[0] := arr[i];
arr[i] := tmp;
__shiftDwon(arr, 0, i);
end;
end;
class procedure THeapSort<T>.__shiftDwon(var arr: TArr_T; k: integer;
Count: integer);
var
j: integer;
e: T;
begin
e := arr[k];
while 2 * k + 1 < Count do
begin
j := 2 * k + 1;
if (j + 1 < Count) and (__cmp.Compare(arr[j + 1], arr[j]) > 0) then
inc(j);
if __cmp.Compare(e, arr[j]) >= 0 then
Break;
arr[k] := arr[j];
k := j;
end;
arr[k] := e;
end;
end.
|
unit AI.TreeNode;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DeepStar.Utils;
type
TTreeNode = class(TObject)
private
procedure __clear;
public
Val: integer;
Left: TTreeNode;
Right: TTreeNode;
constructor Create(newVal: integer = 0; newLeft: TTreeNode = nil; newRight: TTreeNode = nil);
constructor Create(arr: TArr_int);
destructor Destroy; override;
procedure Add(n: integer);
procedure ClearAndFree;
end;
implementation
{ TTreeNode }
constructor TTreeNode.Create(newVal: integer; newLeft: TTreeNode; newRight: TTreeNode);
begin
Val := newVal;
Left := newLeft;
Right := newRight;
end;
constructor TTreeNode.Create(arr: TArr_int);
var
i: integer;
begin
Create(arr[0]);
for i := 1 to High(arr) do
begin
Add(arr[i]);
end;
end;
procedure TTreeNode.Add(n: integer);
function __add__(node: TTreeNode): TTreeNode;
begin
if node = nil then
begin
Result := TTreeNode.Create(n);
Exit;
end;
if n < node.Val then
node.Left := __add__(node.Left)
else if n > node.Val then
node.Right := __add__(node.Right)
else
node := node;
Result := node;
end;
begin
Self := __add__(self);
end;
procedure TTreeNode.ClearAndFree;
begin
__clear;
self.Free;
end;
destructor TTreeNode.Destroy;
begin
inherited Destroy;
end;
procedure TTreeNode.__clear;
procedure __clear__(node: TTreeNode);
begin
if node = nil then Exit;
__clear__(node.Left);
__clear__(node.Right);
FreeAndNil(node);
end;
begin
__clear__(Self.Left);
__clear__(Self.Right);
end;
end.
|
unit mrConfigLookupCli;
interface
uses
SysUtils, Classes, DB, Contnrs, Provider, ADODB, Variants, DBClient;
type
TRecordType = (rtEnabled, rtDisabled, rtBoth);
TmrCommandButton = (cbNew, cbOpen, cbDelete, cbClear);
TmrCommandButtons = set of TmrCommandButton;
TmrConfigLookupCli = class(TComponent)
private
FLookupComboList: TObjectList;
FFchClassName: String;
FRecordType: TRecordType;
FListFieldName: String;
FKeyFieldName: String;
FSQLWhereClause: String;
FSQLOrderClause: String;
FSQLGroupClause: String;
FCommanButtons: TmrCommandButtons;
FOnGetDataSetProperties: TGetDSProps;
FDataSetProvider: TDataSetProvider;
FConnectionSourceName: String;
FProviderSourceName: String;
FOnBeforeGetRecords: TRemoteEvent;
FOnAfterGetRecords: TRemoteEvent;
FTableNamePrefix: String;
procedure SetLookupCombos;
procedure SetCommanButtons(const Value: TmrCommandButtons);
procedure SetKeyFieldName(const Value: String);
procedure SetListFieldName(const Value: String);
procedure SetSQLWhereClause(const Value: String);
procedure SetSQLOrderClause(const Value: String);
procedure SetSQLGroupClause(const Value: String);
function GetCommandButtons(ACommandButtons: TmrCommandButtons): String;
procedure SetDataSetProvider(const Value: TDataSetProvider);
procedure DoGetDataSetProperties(Sender: TObject; DataSet: TDataSet; out Properties: OleVariant);
procedure DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant);
procedure DoAfterGetRecords(Sender: TObject; var OwnerData: OleVariant);
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
published
property DataSetProvider: TDataSetProvider read FDataSetProvider write SetDataSetProvider;
property ConnectionSourceName: String read FConnectionSourceName write FConnectionSourceName;
property ProviderSourceName: String read FProviderSourceName write FProviderSourceName;
property FchClassName: String read FFchClassName write FFchClassName;
property RecordType: TRecordType read FRecordType write FRecordType;
property ListFieldName: String read FListFieldName write SetListFieldName;
property TableNamePrefix: String read FTableNamePrefix write FTableNamePrefix;
property KeyFieldName: String read FKeyFieldName write SetKeyFieldName;
property SQLWhereClause: String read FSQLWhereClause write SetSQLWhereClause;
property SQLOrderClause: String read FSQLOrderClause write SetSQLOrderClause;
property SQLGroupClause: String read FSQLGroupClause write SetSQLGroupClause;
property CommandButtons: TmrCommandButtons read FCommanButtons write SetCommanButtons default [cbNew, cbOpen, cbDelete, cbClear];
property OnAfterGetRecords: TRemoteEvent read FOnAfterGetRecords write FOnAfterGetRecords;
property OnBeforeGetRecords: TRemoteEvent read FOnBeforeGetRecords write FOnBeforeGetRecords;
property OnGetDataSetProperties: TGetDSProps read FOnGetDataSetProperties write FOnGetDataSetProperties;
end;
procedure Register;
implementation
uses mrLookupCombo;
procedure Register;
begin
RegisterComponents('MultiTierLib', [TmrConfigLookupCli]);
end;
{ TmrConfigLookupCli }
procedure TmrConfigLookupCli.DoGetDataSetProperties(Sender: TObject;
DataSet: TDataSet; out Properties: OleVariant);
var
CommandButtonsList: OleVariant;
begin
Properties := VarArrayCreate([0, 8], varVariant);
CommandButtonsList := GetCommandButtons(CommandButtons);
Properties[0] := VarArrayOf(['CommandButtons', CommandButtonsList, True]);
Properties[1] := VarArrayOf(['FchClassName', FFchClassName, True]);
Properties[2] := VarArrayOf(['KeyFieldName', FKeyFieldName, True]);
Properties[3] := VarArrayOf(['ListFieldName', FListFieldName, True]);
Properties[4] := VarArrayOf(['ConnectionSourceName', FConnectionSourceName, True]);
Properties[5] := VarArrayOf(['ProviderSourceName', FProviderSourceName, True]);
Properties[6] := VarArrayOf(['SQLWhereClause', FSQLWhereClause, True]);
Properties[7] := VarArrayOf(['SQLOrderClause', FSQLOrderClause, True]);
Properties[8] := VarArrayOf(['SQLGroupClause', FSQLGroupClause, True]);
if Assigned(FOnGetDataSetProperties) then
OnGetDataSetProperties(Sender, DataSet, Properties);
end;
constructor TmrConfigLookupCli.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
FCommanButtons := [cbNew, cbOpen, cbDelete, cbClear];
FLookupComboList := TObjectList.Create;
FLookupComboList.OwnsObjects := False;
end;
destructor TmrConfigLookupCli.Destroy;
begin
FLookupComboList.Free;
inherited;
end;
function TmrConfigLookupCli.GetCommandButtons(ACommandButtons: TmrCommandButtons): String;
begin
Result := '';
if cbNew in ACommandButtons then
Result := Result + 'cbNew;';
if cbOpen in ACommandButtons then
Result := Result + 'cbOpen;';
if cbDelete in ACommandButtons then
Result := Result + 'cbDelete;';
if cbClear in ACommandButtons then
Result := Result + 'cbClear;';
end;
procedure TmrConfigLookupCli.SetCommanButtons(const Value: TmrCommandButtons);
begin
FCommanButtons := Value;
SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetDataSetProvider(
const Value: TDataSetProvider);
begin
FDataSetProvider := Value;
with FDataSetProvider do
if Value <> nil then
begin
OnGetDataSetProperties := DoGetDataSetProperties;
BeforeGetRecords := DoBeforeGetRecords;
AfterGetRecords := DoAfterGetRecords;
end;
end;
procedure TmrConfigLookupCli.SetKeyFieldName(const Value: String);
begin
FKeyFieldName := Value;
SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetListFieldName(const Value: String);
begin
FListFieldName := Value;
SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetSQLWhereClause(const Value: String);
begin
FSQLWhereClause := Value;
// SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetSQLOrderClause(const Value: String);
begin
FSQLOrderClause := Value;
// SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetSQLGroupClause(const Value: String);
begin
FSQLGroupClause := Value;
// SetLookupCombos;
end;
procedure TmrConfigLookupCli.SetLookupCombos;
var
I: Integer;
begin
for I := 0 to FLookupComboList.Count - 1 do
TmrLookupCombo(FLookupComboList[I]).SetInternalList;
end;
procedure TmrConfigLookupCli.DoBeforeGetRecords(Sender: TObject; var OwnerData: OleVariant);
var
OldSql : String;
sWhere : String;
begin
if Assigned(FOnBeforeGetRecords) then
OnBeforeGetRecords(Sender, OwnerData);
with TADOQuery(FDataSetProvider.DataSet) do
if (OwnerData <> '')
or (FSQLWhereClause <> '')
or (FSQLGroupClause <> '')
or (FSQLOrderClause <> '') then
begin
OldSql := SQL.Text;
sWhere := '';
if FSQLWhereClause <> '' then
if Pos(SQL.Text,'Where') = 0 then
sWhere := sWhere + 'WHERE ' + FSQLWhereClause
else
sWhere := sWhere + 'AND ' + FSQLWhereClause;
if OwnerData <> '' then
if sWhere = '' then
sWhere := sWhere + 'WHERE ' + OwnerData
else
sWhere := sWhere + #13 + #10 + 'AND ' + OwnerData;
if sWhere <> '' then
SQL.Add(sWhere);
if FSQLGroupClause <> '' then
SQL.Add('GROUP BY ' + FSQLGroupClause);
if FSQLOrderClause <> '' then
SQL.Add('ORDER BY ' + FSQLOrderClause)
else if FListFieldName <> '' then
if FTableNamePrefix <> '' then
SQL.Add('ORDER BY ' + FTableNamePrefix + '.' + FListFieldName)
else
SQL.Add('ORDER BY ' + FListFieldName);
OwnerData := OldSql;
end
else
OwnerData := '';
end;
procedure TmrConfigLookupCli.DoAfterGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
with TADOQuery(FDataSetProvider.DataSet) do
if OwnerData <> '' then
SQL.Text := OwnerData;
if Assigned(FOnAfterGetRecords) then
OnAfterGetRecords(Sender, OwnerData);
end;
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Globalization;
using System.Windows.Data;
namespace NotLimited.Framework.Wpf.Converters
{
[ValueConversion(typeof(string), typeof(string))]
public class AppendTextConverter : IValueConverter
{
public object Convert(object obj, Type targetType, object parameter, CultureInfo culture)
{
var value = obj as string;
if (value == null)
return null;
if (parameter == null)
return value;
return value + parameter.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
} |
unit UMainTextOrder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ibase, FIBDatabase, pFIBDatabase, StdCtrls, Buttons, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, DB, FIBDataSet,
pFIBDataSet, AppStruClasses, pFibStoredProc, uFControl, uLabeledFControl,
uSpravControl, uCommonSp, cxLookAndFeelPainters, cxButtons;
type
TfrmMainTextOrder = class(TForm)
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
BottomPanel: TPanel;
OkButton: TBitBtn;
CancelButton: TBitBtn;
cxMemo1: TcxMemo;
MainOrderDataSet: TpFIBDataSet;
Panel1: TPanel;
PCardValue: TqFSpravControl;
Label1: TLabel;
cxButton1: TcxButton;
Label2: TLabel;
cxButton2: TcxButton;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure PCardValueOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure cxButton1Click(Sender: TObject);
procedure cxMemo1PropertiesChange(Sender: TObject);
procedure cxMemo1PropertiesEditValueChanged(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LocalasFrame:Boolean;
outer_hwnd:HWND;
id_order_type:Integer;
base_num_item:Integer;
base_num_sub_item:Integer;
idorder:Int64;
EditMode:Integer;
Key_session:Int64;
EditIdOrderItem:Int64;
procedure CreateBuffInfoByIdItem;
procedure GetData;
procedure CreateEmptyTemplate;
function SaveData:Boolean;
procedure ShowErrors;
constructor Create(AOwner:TComponent;
Db_Handle:TISC_DB_HANDLE;
id_order:int64;
id_order_type:Integer;
num_item:Integer;
num_sub_item:Integer;
id_order_item:Variant;
mode:integer;
asFrame:Boolean;
outer_hwnd:Variant); reintroduce;
end;
implementation
{$R *.dfm}
uses UpKernelUnit, BaseTypes, RxMemDS, uUnivSprav, uSP_Text_Order;
{ TfrmMainTextOrder }
constructor TfrmMainTextOrder.Create(AOwner: TComponent;
Db_Handle: TISC_DB_HANDLE; id_order: int64; id_order_type, num_item,
num_sub_item: Integer; id_order_item: Variant; mode: integer;
asFrame: Boolean; outer_hwnd: Variant);
begin
if asFrame
then inherited Create(AOwner)
else inherited Create(AOwner);
self.LocalasFrame:=asFrame;
self.outer_hwnd:=outer_hwnd;
//Если показываем форму как фрейм
if self.LocalasFrame
then begin
self.BorderStyle:=bsNone;
///self.Align :=alClient;
self.BorderIcons:=[];
self.Visible :=true;
end;
WorkDatabase.Handle :=Db_Handle;
ReadTransaction.StartTransaction;
StartHistory(ReadTransaction);
self.id_order_type :=id_order_type;
self.base_num_item :=num_item;
self.base_num_sub_item:=num_sub_item;
self.idorder :=id_order;
self.EditMode :=Mode;
Key_session :=WorkDatabase.Gen_Id('GEN_UP_ID_SESSION',1);
if (self.EditMode=0) then CreateEmptyTemplate;
if (self.EditMode in [1,2]) //Необходимо сгенерить информацию в буффера
then begin
self.EditIdOrderItem :=VarAsType(id_order_item,varInt64);
CreateBuffInfoByIdItem;
end;
if self.EditMode=2
then begin
BottomPanel.Visible:=false;
cxMemo1.Properties.ReadOnly:=true;
PCardValue.Blocked:=true;
end;
//Отображение информации о надбавках в приказе
GetData;
if (MainOrderDataSet.RecordCount>0)
then begin
end;
if OkButton.HandleAllocated
then SendMessage(self.outer_hwnd, FMAS_MESS_GET_BUTTON_OK,OkButton.Handle,OkButton.Handle);
if CancelButton.HandleAllocated
then SendMessage(self.outer_hwnd, FMAS_MESS_GET_BUTTON_OK,CancelButton.Handle,CancelButton.Handle);
end;
procedure TfrmMainTextOrder.CreateBuffInfoByIdItem;
var StoredProc:TpFibStoredProc;
begin
StoredProc :=TpFibStoredProc.Create(nil);
StoredProc.Database :=WorkDatabase;
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
StoredProc.StoredProcName:='UP_DT_TEXT_ORDER_BUFF_INS_EX';
StoredProc.Prepare;
StoredProc.ParamByName('KEY_SESSION').AsInt64 :=self.Key_session;
StoredProc.ParamByName('ID_ORDER_ITEM').asInt64 :=self.EditIdOrderItem;
StoredProc.ExecProc;
StoredProc.Close;
WriteTransaction.Commit;
StoredProc.Free;
end;
procedure TfrmMainTextOrder.GetData;
begin
MainOrderDataSet.Close;
if (self.EditMode=0) //Добавление
then begin
MainOrderDataSet.SelectSQL.Text:='SELECT * FROM UP_DT_TEXT_BUFF_SEL('+IntToStr(self.Key_session)+')';
end;
if (self.EditMode=1) //Редактирование
then begin
MainOrderDataSet.SelectSQL.Text:='SELECT * FROM UP_DT_TEXT_BUFF_SEL('+IntToStr(self.Key_session)+')';
end;
if (self.EditMode=2) //Только просмотр
then begin
MainOrderDataSet.SelectSQL.Text:='SELECT * FROM UP_DT_TEXT_BUFF_SEL('+IntToStr(self.Key_session)+')';
end;
MainOrderDataSet.Open;
MainOrderDataSet.FetchAll;
if (MainOrderDataSet.RecordCount>0)
then begin
cxMemo1.Lines.Add(MainOrderDataSet.FieldByName('BODY').AsString);
if (MainOrderDataSet.FieldByName('ID_PCARD').Value<>null)
then begin
PCardValue.Value:=MainOrderDataSet.FieldByName('ID_PCARD').Value;
PCardValue.DisplayText:=MainOrderDataSet.FieldByName('FIO').ASstring;
if (self.EditMode in [0,1])
then begin
Label2.Enabled:=true;
cxButton1.Enabled:=true;
cxButton2.Enabled:=true;
end;
end;
end;
end;
procedure TfrmMainTextOrder.CancelButtonClick(Sender: TObject);
begin
if LocalasFrame
then SendMessage(outer_hwnd,FMAS_MESS_CLOSE_FRAME,0,0)
else Close;
end;
procedure TfrmMainTextOrder.CreateEmptyTemplate;
var StoredProc:TpFibStoredProc;
begin
StoredProc :=TpFibStoredProc.Create(nil);
StoredProc.Database :=WorkDatabase;
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
StoredProc.StoredProcName:='UP_DT_TEXT_ORDER_BUFF_INS';
StoredProc.Prepare;
StoredProc.ParamByName('KEY_SESSION').AsInt64 :=self.Key_session;
StoredProc.ParamByName('NUM_ITEM').Value :=self.base_num_item;
StoredProc.ParamByName('NUM_SUB_ITEM').Value :=self.base_num_sub_item;
StoredProc.ParamByName('ID_ORDER').AsInt64 :=self.idorder;
StoredProc.ParamByName('ID_ORDER_TYPE').Value :=self.id_order_type;
StoredProc.ExecProc;
StoredProc.Close;
WriteTransaction.Commit;
StoredProc.Free;
end;
procedure TfrmMainTextOrder.OkButtonClick(Sender: TObject);
begin
if SaveData
then begin
agShowMessage('Інформація по наказу успішно збережена!');
if not LocalasFrame
then ModalResult:=mrOk
else SendMessage(outer_hwnd,FMAS_MESS_SAVE_ITEM_OK,0,0);
end
else begin
agShowMessage('Знайдені помилки під час проведення наказу через ядро системи!');
ShowErrors;
GetData;
end;
end;
function TfrmMainTextOrder.SaveData: Boolean;
var AddStru:UP_KERNEL_MODE_STRUCTURE;
StoredProc:TpFibStoredProc;
begin
StoredProc :=TpFibStoredProc.Create(nil);
StoredProc.Database :=WorkDatabase;
StoredProc.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
StoredProc.StoredProcName:='UP_DT_TEXT_ORDER_BUFF_UPD';
StoredProc.Prepare;
StoredProc.ParamByName('ID_ORDER_ITEM').AsInt64 :=StrToInt64(MainOrderDataSet.FieldByName('ID_ORDER_ITEM').AsString);
StoredProc.ParamByName('BODY').Value :=self.cxMemo1.Lines.Text;
StoredProc.ExecProc;
StoredProc.Close;
WriteTransaction.Commit;
StoredProc.Free;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
AddStru.AOWNER :=self;
AddStru.ID_ORDER :=self.IdOrder;
AddStru.ID_ORDER_ITEM_IN :=StrToInt64(MainOrderDataSet.FieldByName('ID_ORDER_ITEM').AsString);
AddStru.KEY_SESSION :=self.Key_session;
AddStru.DBHANDLE :=WorkDatabase.Handle;
AddStru.TRHANDLE :=WriteTransaction.Handle;
Result:=UpKernelDo(@AddStru);
if Result
then WriteTransaction.Commit;
end;
procedure TfrmMainTextOrder.ShowErrors;
begin
UpKernelUnit.GetUpSessionErrors(self,WorkDatabase.Handle,Key_session,StrToInt64(MainOrderDataSet.FieldByName('ID_ORDER_ITEM').AsString));
end;
procedure TfrmMainTextOrder.FormClose(Sender: TObject;
var Action: TCloseAction);
var ClearSP:TpFibStoredProc;
begin
ClearSP:=TpFibStoredProc.Create(nil);
ClearSP.Database :=WorkDatabase;
ClearSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
ClearSP.StoredProcName:='UP_KER_CLEAR_TMP_EX';
ClearSP.Prepare;
ClearSP.ParamByName('KEY_SESSION').AsInt64:=self.Key_session;
ClearSP.ExecProc;
WriteTransaction.Commit;
ClearSP.Close;
ClearSP.Free;
Action:=caFree;
end;
procedure TfrmMainTextOrder.PCardValueOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
UpdateSP:TpFibStoredProc;
begin
if MainOrderDataSet.RecordCount>0
then begin
sp := GetSprav('asup\PCardsList');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(workDatabase.Handle);
FieldValues['ActualDate'] := Date;
FieldValues['AdminMode'] := 0;
FieldValues['Select'] := 1;
FieldValues['ShowStyle'] := 0;
if FindField('NewVersion')<>nil
then begin
FieldValues['NewVersion'] := 1;
end;
Post;
end;
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty
then begin
Value := sp.Output['ID_PCARD'];
DisplayText := sp.Output['FIO'];
UpdateSP:=TpFibStoredProc.Create(self);
UpdateSP.Database:=WorkDatabase;
UpdateSP.Transaction:=WriteTransaction;
WriteTransaction.StartTransaction;
StartHistory(WriteTransaction);
UpdateSP.StoredProcName:='UP_DT_ORDER_ITEMS_UPD_PCARD';
UpdateSP.Prepare;
UpdateSP.ParamByName('KEY_SESSION').AsInt64 :=self.Key_session;
UpdateSP.ParamByName('ID_ITEM').AsInt64 :=StrToInt64(MainOrderDataSet.FieldByName('ID_ORDER_ITEM').AsString);
UpdateSP.ParamByName('ID_PCARD').Value :=Value;
UpdateSP.ExecProc;
WriteTransaction.Commit;
UpdateSP.Close;
UpdateSP.Free;
Label2.Enabled:=true;
cxButton1.Enabled:=true;
cxButton2.Enabled:=true;
end;
end;
end;
end;
procedure TfrmMainTextOrder.cxButton1Click(Sender: TObject);
var GetSP:TpFibDataSet;
Str:String;
begin
Str:='';
GetSP:=TpFibDataSet.Create(self);
GetSP.Database:=WorkDatabase;
GetSP.Transaction:=ReadTransaction;
GetSP.SelectSQL.Text:=' SELECT * FROM UP_KER_MAN_ACTUAL_REGARD_SELECT('+varToStr(PCardValue.Value)+') ';
GetSP.Open;
if (GetSP.RecordCount>0)
then begin
while not GetSP.eof do
begin
Str:=GetSp.FieldByName('FULL_NAME').AsString+' '+GetSp.FieldByName('NUM_DOC_REGARD').AsString;
cxMemo1.Lines.Add(Str);
GetSP.Next;
end;
end;
GetSP.Close;
GetSP.Free;
SendMessage(outer_hwnd,FMAS_MESS_ITEM_INFO_CHANGED,0,0);
end;
procedure TfrmMainTextOrder.cxMemo1PropertiesChange(Sender: TObject);
begin
SendMessage(outer_hwnd,FMAS_MESS_ITEM_INFO_CHANGED,0,0);
end;
procedure TfrmMainTextOrder.cxMemo1PropertiesEditValueChanged(
Sender: TObject);
begin
SendMessage(outer_hwnd,FMAS_MESS_ITEM_INFO_CHANGED,0,0);
end;
procedure TfrmMainTextOrder.cxButton2Click(Sender: TObject);
var
sp: TSprav;
begin
sp := GetSprav('UP\SPTextOrder');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(workDatabase.Handle);
//FieldValues['ActualDate'] := Date;
//FieldValues['AdminMode'] := 0;
FieldValues['Select'] := 1;
FieldValues['ShowStyle'] := 0;
// if FindField('NewVersion')<>nil
//then begin
// FieldValues['NewVersion'] := 1;
// end;
Post;
end;
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty
then begin
cxMemo1.Text:=(sp.output['Text1']);
end;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: frmIDEDockWin
Author: Kiriakos Vlahos
Date: 18-Mar-2005
Purpose: Base form for docked windows
History:
-----------------------------------------------------------------------------}
unit frmIDEDockWin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvComponent, JvDockControlForm, ExtCtrls, TBX, TBXThemes,
JvComponentBase;
type
TIDEDockWindow = class(TForm)
DockClient: TJvDockClient;
FGPanel: TPanel;
procedure FGPanelEnter(Sender: TObject);
procedure FGPanelExit(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure DockClientTabHostFormCreated(DockClient: TJvDockClient;
TabHost: TJvDockTabHostForm);
private
{ Private declarations }
protected
procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE;
public
{ Public declarations }
HasFocus : Boolean;
end;
var
IDEDockWindow: TIDEDockWindow;
implementation
uses frmPyIDEMain, uCommonFunctions, JvDockGlobals;
{$R *.dfm}
procedure TIDEDockWindow.FGPanelEnter(Sender: TObject);
begin
HasFocus := True;
Color := CurrentTheme.GetItemColor(GetItemInfo('hot'));
end;
procedure TIDEDockWindow.FGPanelExit(Sender: TObject);
begin
HasFocus := False;
//Color := CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Color := GetBorderColor('inactive');
end;
procedure TIDEDockWindow.FormResize(Sender: TObject);
begin
with FGPanel do begin
if (Top <> 3) or (Left <> 3) or (Width <> Self.ClientWidth - 6)
or (Height <> Self.ClientHeight - 6)
then begin
Anchors :=[];
Top := 3;
Left := 3;
Width := Self.ClientWidth - 6;
Height := Self.ClientHeight - 6;
Anchors :=[akLeft, akRight, akTop, akBottom];
end;
end;
end;
procedure TIDEDockWindow.TBMThemeChange(var Message: TMessage);
begin
if Message.WParam = TSC_VIEWCHANGE then begin
if HasFocus then
Color := CurrentTheme.GetItemColor(GetItemInfo('hot'))
//Color := GetBorderColor('active')
else
Color := GetBorderColor('inactive');
//Color := CurrentTheme.GetItemColor(GetItemInfo('inactive'));
Invalidate;
end;
end;
procedure TIDEDockWindow.FormCreate(Sender: TObject);
begin
FGPanel.ControlStyle := FGPanel.ControlStyle + [csOpaque];
FormResize(Self);
FGPanelExit(Self);
AddThemeNotification(Self);
end;
procedure TIDEDockWindow.FormDestroy(Sender: TObject);
begin
RemoveThemeNotification(Self);
end;
procedure TIDEDockWindow.DockClientTabHostFormCreated(
DockClient: TJvDockClient; TabHost: TJvDockTabHostForm);
begin
TabHost.TBDockHeight := DockClient.TBDockHeight;
TabHost.LRDockWidth := DockClient.LRDockWidth;
end;
end.
|
unit SprPensionDataModule;
interface
uses
SysUtils, Classes, FIBDatabase, pFIBDatabase, DB, FIBDataSet, pFIBDataSet,
frxDesgn, frxClass, frxDBSet, ibase, Forms, FIBQuery, pFIBQuery,
pFIBStoredProc, ZWait, ZMessages, Unit_SprSubs_Consts, Dialogs,
RxMemDS, IniFiles, ZProc, Dates,
Variants, Math, frxExportXLS;
Type TFilterData = record
ID_man : integer;
TN:integer;
TIN: variant;
FIO: string;
Kod_setup1:integer;
Kod_setup2:integer;
AOwner:TComponent;
end;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
ReportDBDSet: TfrxDBDataset;
Designer: TfrxDesigner;
ReportDBDSetFoundationData: TfrxDBDataset;
DSetFoundationData: TpFIBDataSet;
StProc: TpFIBStoredProc;
UpdateTransaction: TpFIBTransaction;
Report: TfrxReport;
frxXLSExport1: TfrxXLSExport;
procedure DataModuleDestroy(Sender: TObject);
private
PID_Report:integer;
MemoryData: TRxMemoryData;
public
function PrintSpr(ADb_Handle: TISC_DB_HANDLE; AParameter:TFilterData):variant;
end;
implementation
{$R *.dfm}
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'Pension';
const NameReport = 'Reports\Zarplata\Pension.fr3';
function TDM.PrintSpr(ADb_Handle: TISC_DB_HANDLE; AParameter:TFilterData):variant;
var IniFile:TIniFile;
ViewMode:integer;
PathReport:string;
wf:TForm;
i: integer;
k: integer;
HeaderBand: TfrxHeader;
FooterBand: TfrxFooter;
Memo: TfrxMemoView;
SummaAll:Extended;
begin
DB.Handle:=ADb_Handle;
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='Z_PERSONIFICATION_REPORT_I';
StProc.Prepare;
StProc.ExecProc;
PID_Report:=StProc.ParamByName('ID').AsInteger;
StProc.Transaction.Commit;
except
on E:Exception do
begin
ZShowMessage(TFSprSubs_InputError_Caption,e.Message,mtWarning,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='GR_MAN_BY_ID';
StProc.ParamByName('IN_ID_MAN').AsInteger:=AParameter.ID_man;
StProc.Prepare;
StProc.ExecProc;
AParameter.TIN:=StProc.ParamByName('TIN').AsVariant;
StProc.Transaction.Commit;
except
on E:Exception do
begin
ZShowMessage(TFSprSubs_InputError_Caption,e.Message,mtWarning,[mbOK]);
StProc.Transaction.Rollback;
end
end;
try
wf:=ShowWaitForm(TForm(AParameter.AOwner));
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='Z_PERSONIFACATION';
StProc.ParamByName('TIN').AsString:=AParameter.TIN;
StProc.ParamByName('KOD_SETUP_B').AsInteger:=AParameter.Kod_setup1;
StProc.ParamByName('KOD_SETUP_E').AsInteger:=AParameter.Kod_setup2;
StProc.ParamByName('ID_REPORT').AsInteger:=PID_Report;
StProc.Prepare;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
CloseWaitForm(wf);
ZShowMessage(TFSprSubs_InputError_Caption,e.Message,mtWarning,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SPR_PENSION('+IntToStr(PID_Report)+')';
DSetFoundationData.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SPR_SUBS_FOUNDATION_DATA('+IntToStr(AParameter.ID_man)+','+IntToStr(AParameter.Kod_setup2)+')';
DSet.Open;
DSetFoundationData.Open;
MemoryData:=TRxMemoryData.Create(self);
MemoryData.FieldDefs.Add('MONTH',ftVariant);
MemoryData.FieldDefs.Add('SUMMA1',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA2',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA3',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA4',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA5',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA6',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA7',ftCurrency);
MemoryData.FieldDefs.Add('SUMMA8',ftCurrency);
MemoryData.Open;
i:=12;
while(i>=1)do
begin
MemoryData.Insert;
MemoryData['MONTH']:=MonthNumToName(i);
MemoryData.Post;
Dec(i);
end;
DSet.Last;
AParameter.Kod_setup2:=DSet['KOD_SETUP'];
DSet.First;
AParameter.Kod_setup1:=DSet['KOD_SETUP'];
MemoryData.First;
k:=AParameter.Kod_setup1 mod 12;
if(k=0)then k:=12;
for i:=1 to k-1 do
MemoryData.Next;
i:=1;
SummaAll:=0;
k:=AParameter.Kod_setup1;
while not(DSet.Eof)do
begin
if(DSet['KOD_SETUP']=k)then
begin
SummaAll:=SummaAll+DSet['SUM_DOX_PENS'];
MemoryData.Edit;
MemoryData['SUMMA'+IntToStr(i)]:=DSet['SUM_DOX_PENS'];
MemoryData.Post;
DSet.Next;
end;
Inc(k);
MemoryData.Next;
if(k=12)then k:=0;
if(MemoryData.Eof)then
begin
MemoryData.First;
Inc(i);
end;
end;
ReportDBDSet.DataSet:=MemoryData;
ReportDBDSet.Open;
CloseWaitForm(wf);
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,'ReeDepVo',NameReport);
IniFile.Free;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True);
Report.Variables.Clear;
Report.Variables[' '+'User Category']:=NULL;
Report.Variables.AddVariable('User Category',
'PSumAll',
''''+StringPrepareToQueryText(SumToString(RoundTo(SummaAll,-2)))+'''');
Report.Variables.AddVariable('User Category',
'KodSetup1',
YearMonthFromKodSetup(AParameter.Kod_setup1));
Report.Variables.AddVariable('User Category',
'KodSetup2',
YearMonthFromKodSetup(AParameter.Kod_setup2));
k:=YearMonthFromKodSetup(AParameter.Kod_setup2)-YearMonthFromKodSetup(AParameter.Kod_setup1);
HeaderBand:=Report.FindObject('Header1') as TfrxHeader;
for i:=0 to k do
begin
Memo:=HeaderBand.FindObject('Memo'+IntToStr(i+12)) as TfrxMemoView;
Memo.Text:=IntToStr(YearMonthFromKodSetup(AParameter.Kod_setup1)+i);
end;
FooterBand:=Report.FindObject('Footer1') as TfrxFooter;
for i:=0 to k do
begin
Memo:=FooterBand.FindObject('Memo'+IntToStr(i+20)) as TfrxMemoView;
Memo.Text:='[SUM(<ReportDBDSet."SUMMA'+IntToStr(i+1)+'">,MasterData1)]';
end;
if zDesignReport then Report.DesignReport
else Report.ShowReport;
Report.Free;
try
StProc.Transaction.StartTransaction;
StProc.StoredProcName:='Z_PERSONIFICATION_REPORT_D';
StProc.Prepare;
StProc.ParamByName('ID').AsInteger:=PID_Report;
StProc.ExecProc;
StProc.Transaction.Commit;
except
on E:Exception do
begin
ZShowMessage(TFSprSubs_InputError_Caption,e.Message,mtWarning,[mbOK]);
StProc.Transaction.Rollback;
end;
end;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
end.
|
unit EffectsToolThreadUnit;
interface
uses
Windows,
Classes,
EffectsToolUnit,
Graphics,
Forms,
uConstants,
uLogger,
uEditorTypes,
uShellIntegration,
uMemory,
uDBThread;
type
TBaseEffectThread = class(TDBThread)
private
{ Private declarations }
FSID: string;
FProc: TBaseEffectProc;
BaseImage: TBitmap;
IntParam: Integer;
FOnExit: TBaseEffectProcThreadExit;
D: TBitmap;
FOwner: TObject;
FEditor: TImageEditorForm;
FProgress: Integer;
FBreak: Boolean;
protected
procedure Execute; override;
public
constructor Create(AOwner: TObject; Proc: TBaseEffectProc; S: TBitmap; SID: string;
OnExit: TBaseEffectProcThreadExit; Editor: TImageEditorForm);
procedure CallBack(Progress: Integer; var Break: Boolean);
procedure CallBackSync;
procedure SetProgress;
procedure DoExit;
procedure ClearText;
end;
implementation
uses
ImEditor;
procedure TBaseEffectThread.CallBack(Progress: Integer; var Break: Boolean);
begin
FProgress := Progress;
FBreak := Break;
SynchronizeEx(CallBackSync);
Break := FBreak;
end;
procedure TBaseEffectThread.CallBackSync;
begin
IntParam := FProgress;
SetProgress;
if not EditorsManager.IsEditor(FEditor) then
Exit;
if (FEditor as TImageEditor).ToolClass = FOwner then
if FOwner is TEffectsToolPanelClass then
FBreak := (FOwner as TEffectsToolPanelClass).FSID <> FSID;
end;
procedure TBaseEffectThread.ClearText;
begin
if not EditorsManager.IsEditor(FEditor) then
Exit;
if (FEditor as TImageEditor).ToolClass = FOwner then
(FEditor as TImageEditor).StatusBar1.Panels[1].Text := '';
end;
constructor TBaseEffectThread.Create(AOwner: TObject; Proc: TBaseEffectProc; S: TBitmap; SID: string;
OnExit: TBaseEffectProcThreadExit; Editor: TImageEditorForm);
begin
inherited Create(Editor, False);
FOwner := AOwner;
FSID := SID;
FOnExit := OnExit;
FProc := Proc;
BaseImage := S;
FEditor := Editor;
end;
procedure TBaseEffectThread.DoExit;
begin
if EditorsManager.IsEditor(FEditor) and ((FEditor as TImageEditor).ToolClass = FOwner) then
begin
Synchronize(ClearText);
FOnExit(D, FSID);
Exit;
end;
F(D);
end;
procedure TBaseEffectThread.Execute;
begin
inherited;
FreeOnTerminate := True;
D := TBitmap.Create;
FProc(BaseImage, D, CallBack);
if not SynchronizeEx(DoExit) then
F(D);
F(BaseImage);
IntParam := 0;
SynchronizeEx(SetProgress);
end;
procedure TBaseEffectThread.SetProgress;
begin
try
if not EditorsManager.IsEditor(FEditor) then
Exit;
if (FEditor as TImageEditor).ToolClass = FOwner then
begin
if FOwner is TEffectsToolPanelClass then
(FOwner as TEffectsToolPanelClass).SetProgress(IntParam, FSID);
end;
except
if (FEditor as TImageEditor).ToolClass = FOwner then
if FOwner is TEffectsToolPanelClass then
begin
EventLog('TBaseEffectThread.SetProgress() exception!');
MessageBoxDB(Handle, 'TBaseEffectThread.SetProgress() exception!',
'TBaseEffectThread.SetProgress() exception!', TD_BUTTON_OK, TD_ICON_ERROR);
end;
end;
end;
end.
|
unit Class_CACH_DATA_IN_GKZF;
interface
uses
Classes,SysUtils,Uni,UniEngine;
type
TCachData=class(TUniEngine)
private
FCachIdentity: string;
FCachIdex: Integer;
FCachName: string;
FMastCode: string;
FMasterData: string;
FDetailData: string;
protected
procedure SetParameters;override;
function GetStrInsert:string;override;
function GetStrUpdate:string;override;
function GetStrDelete:string;override;
public
function GetStrsIndex:string;override;
public
function GetNextIdex:Integer;overload;
function GetNextIdex(AUniConnection:TUniConnection):Integer;overload;
public
function CheckExist(AUniConnection:TUniConnection):Boolean;override;
public
destructor Destroy; override;
constructor Create;
published
property CachIdentity: string read FCachIdentity write FCachIdentity;
property CachIdex: Integer read FCachIdex write FCachIdex;
property CachName: string read FCachName write FCachName;
property MastCode: string read FMastCode write FMastCode;
property MasterData: string read FMasterData write FMasterData;
property DetailData: string read FDetailData write FDetailData;
public
class function ReadDS(AUniQuery:TUniQuery):TUniEngine;override;
class procedure ReadDS(AUniQuery:TUniQuery;var Result:TUniEngine);override;
class function CopyIt(ACachData:TCachData):TCachData;overload;
class procedure CopyIt(ACachData:TCachData;var Result:TCachData);overload;
end;
implementation
{ TCachData }
procedure TCachData.SetParameters;
begin
inherited;
with FUniSQL.Params do
begin
case FOptTyp of
otAddx:
begin
ParamByName('CACH_IDENTITY').Value := CACHIDENTITY;
ParamByName('CACH_IDEX').Value := CACHIDEX;
ParamByName('CACH_NAME').Value := CACHNAME;
ParamByName('MAST_CODE').Value := MASTCODE;
ParamByName('MASTER_DATA').Value := MASTERDATA;
ParamByName('DETAIL_DATA').Value := DETAILDATA;
end;
otEdit:
begin
ParamByName('CACH_IDENTITY').Value := CACHIDENTITY;
ParamByName('CACH_IDEX').Value := CACHIDEX;
ParamByName('CACH_NAME').Value := CACHNAME;
ParamByName('MAST_CODE').Value := MASTCODE;
ParamByName('MASTER_DATA').Value := MASTERDATA;
ParamByName('DETAIL_DATA').Value := DETAILDATA;
end;
otDelt:
begin
ParamByName('CACH_IDENTITY').Value := CACHIDENTITY;
ParamByName('CACH_IDEX').Value := CACHIDEX;
end;
end;
end;
end;
function TCachData.CheckExist(AUniConnection: TUniConnection): Boolean;
begin
Result:=CheckExist('GKX_CACH_DATA',['CACH_IDENTITY',CACHIDENTITY,'CACH_IDEX',CACHIDEX],AUniConnection);
end;
function TCachData.GetNextIdex: Integer;
begin
end;
function TCachData.GetNextIdex(AUniConnection: TUniConnection): Integer;
begin
end;
function TCachData.GetStrDelete: string;
begin
Result:='DELETE FROM GKX_CACH_DATA WHERE CACH_IDENTITY=:CACH_IDENTITY AND CACH_IDEX=:CACH_IDEX';
end;
function TCachData.GetStrInsert: string;
begin
Result:='INSERT INTO GKX_CACH_DATA'
+' ( CACH_IDENTITY, CACH_IDEX, CACH_NAME, MAST_CODE, MASTER_DATA'
+' , DETAIL_DATA)'
+' VALUES'
+' (:CACH_IDENTITY,:CACH_IDEX,:CACH_NAME,:MAST_CODE,:MASTER_DATA'
+' ,:DETAIL_DATA)';
end;
function TCachData.GetStrsIndex: string;
begin
Result:=Format('%S-%D',[CACHIDENTITY,CACHIDEX]);
end;
function TCachData.GetStrUpdate: string;
begin
Result:='UPDATE GKX_CACH_DATA SET'
+' CACH_NAME=:CACH_NAME,'
+' MAST_CODE=:MAST_CODE,'
+' MASTER_DATA=:MASTER_DATA,'
+' DETAIL_DATA=:DETAIL_DATA'
+' WHERE CACH_IDENTITY=:CACH_IDENTITY'
+' AND CACH_IDEX=:CACH_IDEX';
end;
constructor TCachData.Create;
begin
CachIdex:=1;
CachName:='Δ¬ΘΟΓόΓϋ';
end;
destructor TCachData.Destroy;
begin
inherited;
end;
class function TCachData.ReadDS(AUniQuery: TUniQuery): TUniEngine;
begin
Result:=TCachData.Create;
with TCachData(Result) do
begin
CACHIDENTITY:=AUniQuery.FieldByName('CACH_IDENTITY').AsString;
CACHIDEX:=AUniQuery.FieldByName('CACH_IDEX').AsInteger;
CACHNAME:=AUniQuery.FieldByName('CACH_NAME').AsString;
MASTCODE:=AUniQuery.FieldByName('MAST_CODE').AsString;
MASTERDATA:=AUniQuery.FieldByName('MASTER_DATA').AsString;
DETAILDATA:=AUniQuery.FieldByName('DETAIL_DATA').AsString;
end;
end;
class procedure TCachData.ReadDS(AUniQuery: TUniQuery; var Result: TUniEngine);
begin
if Result=nil then Exit;
with TCachData(Result) do
begin
CACHIDENTITY:=AUniQuery.FieldByName('CACH_IDENTITY').AsString;
CACHIDEX:=AUniQuery.FieldByName('CACH_IDEX').AsInteger;
CACHNAME:=AUniQuery.FieldByName('CACH_NAME').AsString;
MASTCODE:=AUniQuery.FieldByName('MAST_CODE').AsString;
MASTERDATA:=AUniQuery.FieldByName('MASTER_DATA').AsString;
DETAILDATA:=AUniQuery.FieldByName('DETAIL_DATA').AsString;
end;
end;
class function TCachData.CopyIt(ACachData: TCachData): TCachData;
begin
Result:=TCachData.Create;
TCachData.CopyIt(ACachData,Result)
end;
class procedure TCachData.CopyIt(ACachData:TCachData;var Result:TCachData);
begin
if Result=nil then Exit;
Result.CACHIDENTITY:=ACachData.CACHIDENTITY;
Result.CACHIDEX:=ACachData.CACHIDEX;
Result.CACHNAME:=ACachData.CACHNAME;
Result.MASTCODE:=ACachData.MASTCODE;
Result.MASTERDATA:=ACachData.MASTERDATA;
Result.DETAILDATA:=ACachData.DETAILDATA;
end;
end.
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: BasicHLSLunit.pas,v 1.23 2007/02/05 22:21:01 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: BasicHLSL.cpp
//
// This sample shows a simple example of the Microsoft Direct3D's High-Level
// Shader Language (HLSL) using the Effect interface.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit BasicHLSLunit;
interface
uses
Windows, SysUtils, StrSafe,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pSprite: ID3DXSprite; // Sprite for batching draw text calls
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_Camera: CModelViewerCamera; // A model viewing camera
g_pEffect: ID3DXEffect; // D3DX effect interface
g_pMesh: ID3DXMesh; // Mesh object
g_pMeshTexture: IDirect3DTexture9; // Mesh texture
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // manages the 3D UI
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_bEnablePreshader: Boolean; // if TRUE, then D3DXSHADER_NO_PRESHADER is used when compiling the shader
g_mCenterWorld: TD3DXMatrixA16;
const
MAX_LIGHTS = 3;
var
g_LightControl: array[0..MAX_LIGHTS-1] of CDXUTDirectionWidget;
g_fLightScale: Single;
g_nNumActiveLights: Integer;
g_nActiveLight: Integer;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_ENABLE_PRESHADER = 5;
IDC_NUM_LIGHTS = 6;
IDC_NUM_LIGHTS_STATIC = 7;
IDC_ACTIVE_LIGHT = 8;
IDC_LIGHT_SCALE = 9;
IDC_LIGHT_SCALE_STATIC = 10;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
procedure RenderText(fTime: Double);
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
i: Integer;
iY: Integer;
sz: array[0..99] of WideChar;
begin
g_bEnablePreshader := True;
for i := 0 to MAX_LIGHTS - 1 do
g_LightControl[i].SetLightDirection(D3DXVector3(sin(D3DX_PI*2*i/MAX_LIGHTS-D3DX_PI/6), 0, -cos(D3DX_PI*2*i/MAX_LIGHTS-D3DX_PI/6)));
g_nActiveLight := 0;
g_nNumActiveLights := 1;
g_fLightScale := 1.0;
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2); // Inc(iY, 24);
g_SampleUI.SetCallback(OnGUIEvent); iY := 10;
Inc(iY, 24);
StringCchFormat(sz, 100, '# Lights: %d'#0, [g_nNumActiveLights]);
g_SampleUI.AddStatic(IDC_NUM_LIGHTS_STATIC, sz, 35, iY, 125, 22); Inc(iY, 24);
g_SampleUI.AddSlider(IDC_NUM_LIGHTS, 50, iY, 100, 22, 1, MAX_LIGHTS, g_nNumActiveLights); Inc(iY, 24);
Inc(iY, 24);
// StringCchFormat(sz, 100, 'Light scale: %0.2f', [g_fLightScale]); // Delphi WideFormat() bug
StringCchFormat(sz, 100, 'Light scale: %0f', [g_fLightScale]);
g_SampleUI.AddStatic(IDC_LIGHT_SCALE_STATIC, sz, 35, iY, 125, 22); Inc(iY, 24);
g_SampleUI.AddSlider(IDC_LIGHT_SCALE, 50, iY, 100, 22, 0, 20, Trunc(g_fLightScale * 10.0)); Inc(iY, 24);
Inc(iY, 24);
g_SampleUI.AddButton(IDC_ACTIVE_LIGHT, 'Change active light (K)', 35, iY, 125, 22, Ord('K')); Inc(iY, 24);
g_SampleUI.AddCheckBox(IDC_ENABLE_PRESHADER, 'Enable preshaders', 35, iY, 125, 22, g_bEnablePreshader); // Inc(iY, 24);
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning E_FAIL.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result := False;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result := True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
pData: PD3DXVector3;
vCenter: TD3DXVector3;
fObjectRadius: Single;
m: TD3DXMatrixA16;
i: Integer;
dwShaderFlags: DWORD;
str: array [0..MAX_PATH-1] of WideChar;
colorMtrlDiffuse, colorMtrlAmbient: TD3DXColor;
vecEye, vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Load the mesh
Result := LoadMesh(pd3dDevice, 'tiny\tiny.x', g_pMesh);
if V_Failed(Result) then Exit;
V(g_pMesh.LockVertexBuffer(0, Pointer(pData)));
V(D3DXComputeBoundingSphere(pData, g_pMesh.GetNumVertices, D3DXGetFVFVertexSize(g_pMesh.GetFVF), vCenter, fObjectRadius));
V(g_pMesh.UnlockVertexBuffer);
D3DXMatrixTranslation(g_mCenterWorld, -vCenter.x, -vCenter.y, -vCenter.z);
D3DXMatrixRotationY(m, D3DX_PI);
D3DXMatrixMultiply(g_mCenterWorld, g_mCenterWorld, m);
D3DXMatrixRotationX(m, D3DX_PI / 2.0);
D3DXMatrixMultiply(g_mCenterWorld, g_mCenterWorld, m); // g_mCenterWorld *= m;
Result := CDXUTDirectionWidget.StaticOnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
for i := 0 to MAX_LIGHTS - 1 do
g_LightControl[i].Radius := fObjectRadius;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Preshaders are parts of the shader that the effect system pulls out of the
// shader and runs on the host CPU. They should be used if you are GPU limited.
// The D3DXSHADER_NO_PRESHADER flag disables preshaders.
if not g_bEnablePreshader then dwShaderFlags := dwShaderFlags or D3DXSHADER_NO_PRESHADER;
// Read the D3DX effect file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('BasicHLSL.fx'));
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// why the .fx file failed to compile
Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags, nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Create the mesh texture from a file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('tiny\tiny_skin.dds'));
if V_Failed(Result) then Exit;
Result := D3DXCreateTextureFromFileExW(pd3dDevice, str, D3DX_DEFAULT, D3DX_DEFAULT,
D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED,
D3DX_DEFAULT, D3DX_DEFAULT, 0,
nil, nil, g_pMeshTexture);
if V_Failed(Result) then Exit;
// Set effect variables as needed
colorMtrlDiffuse := D3DXColor(1.0, 1.0, 1.0, 1.0);
colorMtrlAmbient := D3DXColor(0.35, 0.35, 0.35, 0);
Result:= g_pEffect.SetValue('g_MaterialAmbientColor', @colorMtrlAmbient, SizeOf(TD3DXColor));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetValue('g_MaterialDiffuseColor', @colorMtrlDiffuse, SizeOf(TD3DXColor));
if V_Failed(Result) then Exit;
Result:= g_pEffect.SetTexture('g_MeshTexture', g_pMeshTexture);
if V_Failed(Result) then Exit;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -15.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
g_Camera.SetRadius(fObjectRadius*3.0, fObjectRadius*0.5, fObjectRadius*10.0);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This function loads the mesh and ensures the mesh has normals; it also optimizes the
// mesh for the graphics card's vertex cache, which improves performance by organizing
// the internal triangle list for less cache misses.
//--------------------------------------------------------------------------------------
function LoadMesh(const pd3dDevice: IDirect3DDevice9; strFileName: PWideChar; out ppMesh: ID3DXMesh): HRESULT;
var
pMesh: ID3DXMesh;
str: array[0..MAX_PATH-1] of WideChar;
rgdwAdjacency: PDWORD;
pTempMesh: ID3DXMesh;
begin
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, strFileName);
if V_Failed(Result) then Exit;
Result := D3DXLoadMeshFromXW(str, D3DXMESH_MANAGED, pd3dDevice, nil, nil, nil, nil, pMesh);
if V_Failed(Result) then Exit;
// rgdwAdjacency := nil;
// Make sure there are normals which are required for lighting
if (pMesh.GetFVF and D3DFVF_NORMAL = 0) then
begin
V(pMesh.CloneMeshFVF(pMesh.GetOptions,
pMesh.GetFVF or D3DFVF_NORMAL,
pd3dDevice, pTempMesh));
V(D3DXComputeNormals(pTempMesh, nil));
SAFE_RELEASE(pMesh);
pMesh := pTempMesh;
end;
// Optimize the mesh for this graphics card's vertex cache
// so when rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader
// on those vertices so it will improve perf.
GetMem(rgdwAdjacency, SizeOf(DWORD)*pMesh.GetNumFaces*3);
try
// if (rgdwAdjacency = nil) then Result:= E_OUTOFMEMORY;
V(pMesh.GenerateAdjacency(1e-6, rgdwAdjacency));
V(pMesh.OptimizeInplace(D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, nil, nil, nil));
finally
FreeMem(rgdwAdjacency);
end;
ppMesh := pMesh;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
i: Integer;
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pSprite);
if V_Failed(Result) then Exit;
for i := 0 to MAX_LIGHTS - 1 do
g_LightControl[i].OnResetDevice(pBackBufferSurfaceDesc);
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 2.0, 4000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_Camera.SetButtonMasks(MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-300);
g_SampleUI.SetSize(170, 300);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorldViewProjection: TD3DXMatrixA16;
vLightDir: array[0..MAX_LIGHTS-1] of TD3DXVector3;
vLightDiffuse: array[0..MAX_LIGHTS-1] of TD3DXColor;
iPass, cPasses: LongWord;
m, mWorld, mView, mProj: TD3DXMatrixA16;
i: Integer;
arrowColor: TD3DXColor;
vWhite: TD3DXColor;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DXColorToDWord(D3DXColor(0.0,0.25,0.25,0.55)), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
D3DXMatrixMultiply(mWorld, g_mCenterWorld, g_Camera.GetWorldMatrix^);
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
// Render the light arrow so the user can visually see the light dir
for i := 0 to g_nNumActiveLights - 1 do
begin
if (i = g_nActiveLight) then arrowColor := D3DXColor(1,1,0,1) else arrowColor := D3DXColor(1,1,1,1);
V(g_LightControl[i].OnRender(arrowColor, mView, mProj, g_Camera.GetEyePt^));
vLightDir[i] := g_LightControl[i].LightDirection;
D3DXColorScale(vLightDiffuse[i], D3DXColor(1,1,1,1), g_fLightScale); // vLightDiffuse[i] := g_fLightScale * D3DXColor(1,1,1,1);
end;
V(g_pEffect.SetValue('g_LightDir', @vLightDir, SizeOf(TD3DXVector3)*MAX_LIGHTS));
V(g_pEffect.SetValue('g_LightDiffuse', @vLightDiffuse, SizeOf(TD3DXVector4)*MAX_LIGHTS));
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
V(g_pEffect.SetFloat('g_fTime', fTime));
vWhite := D3DXColor(1,1,1,1);
V(g_pEffect.SetValue('g_MaterialDiffuseColor', @vWhite, SizeOf(TD3DXColor)));
V(g_pEffect.SetFloat('g_fTime', fTime));
V(g_pEffect.SetInt('g_nNumLights', g_nNumActiveLights));
// Render the scene with this technique
// as defined in the .fx file
if (GetDXUTState.Caps.PixelShaderVersion < D3DPS_VERSION(1, 1)) then
case g_nNumActiveLights of
1: V(g_pEffect.SetTechnique('RenderSceneWithTexture1LightNOPS'));
2: V(g_pEffect.SetTechnique('RenderSceneWithTexture2LightNOPS'));
3: V(g_pEffect.SetTechnique('RenderSceneWithTexture3LightNOPS'));
end else
case g_nNumActiveLights of
1: V(g_pEffect.SetTechnique('RenderSceneWithTexture1Light'));
2: V(g_pEffect.SetTechnique('RenderSceneWithTexture2Light'));
3: V(g_pEffect.SetTechnique('RenderSceneWithTexture3Light'));
end;
// Apply the technique contained in the effect
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
// The effect interface queues up the changes and performs them
// with the CommitChanges call. You do not need to call CommitChanges if
// you are not setting any parameters between the BeginPass and EndPass.
// V( g_pEffect->CommitChanges() );
// Render the mesh with the applied technique
V(g_pMesh.DrawSubset(0));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
g_HUD.OnRender(fElapsedTime);
g_SampleUI.OnRender(fElapsedTime);
RenderText(fTime);
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText(fTime: Double);
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work fine however the
// pFont->DrawText() will not be batched together. Batching calls will improves perf.
txtHelper:= CDXUTTextHelper.Create(g_pFont, g_pSprite, 15);
try
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(2, 0);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
// txtHelper.DrawFormattedTextLine('fTime: %0.1f sin(fTime): %0.4f', [fTime, sin(fTime)]);
{$IFDEF FPC}
txtHelper.DrawTextLine(PWideChar(WideFormat('fTime: %0.1f sin(fTime): %0.4f', [fTime, sin(fTime)])));
{$ELSE}
txtHelper.DrawTextLine(PAnsiChar(Format('fTime: %0.1f sin(fTime): %0.4f', [fTime, sin(fTime)]))); // Delphi WideFormat bug
{$ENDIF}
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(2, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls:');
txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Rotate model: Left mouse button'#10+
'Rotate light: Right mouse button'#10+
'Rotate camera: Middle mouse button'#10+
'Zoom camera: Mouse wheel scroll'#10);
txtHelper.SetInsertionPos(250, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Hide help: F1'#10+
'Quit: ESC'#10);
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
finally
txtHelper.Free;
end;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
g_LightControl[g_nActiveLight].HandleMessages(hWnd, uMsg, wParam, lParam);
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
var
sz: array[0..99] of WideChar;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_ENABLE_PRESHADER:
begin
g_bEnablePreshader := g_SampleUI.GetCheckBox(IDC_ENABLE_PRESHADER).Checked;
if (DXUTGetD3DDevice <> nil) then
begin
OnLostDevice(nil);
OnDestroyDevice(nil);
OnCreateDevice(DXUTGetD3DDevice, DXUTGetBackBufferSurfaceDesc^, nil);
OnResetDevice(DXUTGetD3DDevice, DXUTGetBackBufferSurfaceDesc^, nil);
end;
end;
IDC_ACTIVE_LIGHT:
if not g_LightControl[g_nActiveLight].IsBeingDragged then
begin
Inc(g_nActiveLight);
g_nActiveLight := g_nActiveLight mod g_nNumActiveLights;
end;
IDC_NUM_LIGHTS:
if not g_LightControl[g_nActiveLight].IsBeingDragged then
begin
StringCchFormat(sz, 100, '# Lights: %d', [g_SampleUI.GetSlider(IDC_NUM_LIGHTS).Value]);
g_SampleUI.GetStatic(IDC_NUM_LIGHTS_STATIC).Text := sz;
g_nNumActiveLights := g_SampleUI.GetSlider(IDC_NUM_LIGHTS).Value;
g_nActiveLight := g_nActiveLight mod g_nNumActiveLights;
end;
IDC_LIGHT_SCALE:
begin
g_fLightScale := g_SampleUI.GetSlider(IDC_LIGHT_SCALE).Value * 0.10;
// WideFormatBuf(sz, 100, 'Light scale: %0.2f', [g_fLightScale]);
StringCchFormat(sz, 100, 'Light scale: %f', [g_fLightScale]); // Delphi WideFormat() bug
g_SampleUI.GetStatic(IDC_LIGHT_SCALE_STATIC).Text := sz;
end;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
CDXUTDirectionWidget.StaticOnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
CDXUTDirectionWidget.StaticOnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
SAFE_RELEASE(g_pMesh);
SAFE_RELEASE(g_pMeshTexture);
end;
procedure CreateCustomDXUTobjects;
var
i: Integer;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
for i:= 0 to MAX_LIGHTS-1 do g_LightControl[i]:= CDXUTDirectionWidget.Create;
g_Camera:= CModelViewerCamera.Create; // A model viewing camera
g_HUD:= CDXUTDialog.Create; // manages the 3D UI
g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls
end;
procedure DestroyCustomDXUTobjects;
var
i: Integer;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
for i:= 0 to MAX_LIGHTS-1 do
FreeAndNil(g_LightControl[i]);
end;
end.
|
unit Voxel_Engine;
interface
uses Windows,Voxel,Palette,StdCtrls,ExtCtrls,Graphics,Math,SysUtils,Types,cls_config,Constants,
Menus,Clipbrd,mouse, forms, Dialogs;
{$INCLUDE Global_Conditionals.inc}
type
PPaintBox = ^TPaintBox;
PLabel = ^TLabel;
PMenuItem = ^TMenuItem;
TVector3f = record
X, Y, Z : single;
end;
TVector3i = record
X, Y, Z : integer;
end;
TTempViewData = record
V : TVoxelUnpacked;
VC : TVector3i; // Cordinates of V
VU : Boolean; // Is V Used, if so we can do this to the VXL file when needed
X,Y : Integer;
end;
TTempView = record
Data : Array of TTempViewData;
Data_no : integer;
end;
TPaletteList = record
Data : array of String;
Data_no : integer;
end;
TColourSchemes = array of packed record
Name,Filename,By,Website : string;
Data : array [0..255] of byte;
end;
Var
VoxelFile : TVoxel;
ActiveSection : TVoxelSection;
CurrentSection : cardinal;
SpectrumMode : ESpectrumMode;
ViewMode: EViewMode;
VXLFilename : String;
VoxelOpen : Boolean = false;
isEditable : Boolean = false;
isLeftMouseDown : Boolean = false;
isLeftMB : Boolean = false;
isCursorReset : Boolean = false;
scrollbar_editable : Boolean = false;
UsedColoursOption : Boolean = false;
BGViewColor : TColor;
CnvView : array [0..2] of PPaintBox;
lblView : array [0..2] of PLabel;
ActiveNormalsCount,ActiveColour,ActiveNormal : integer;
VXLBrush : integer = 0;
VXLTool : integer = 0;
DarkenLighten : integer = 1;
LastClick : array [0..2] of TVector3i;
TempView : TTempView;
mnuReopen : PMenuItem;
PaletteList : TPaletteList;
VXLChanged : Boolean = false;
ColourSchemes : TColourSchemes;
// 1.2b adition:
UsedColours : array [0..255] of boolean;
UsedNormals : array [0..244] of boolean;
Config: TConfiguration; // For File History
mnuHistory: Array[0..HistoryDepth-1] of TMenuItem;
Const
TestBuild = false;
TestBuildVersion = '5';
DefultZoom = 7;
VIEWBGCOLOR = -1;
VXLTool_Brush = 0;
VXLTool_Line = 1;
VXLTool_Erase = 2;
VXLTool_FloodFill = 3;
VXLTool_Dropper = 4;
VXLTool_Rectangle = 5;
VXLTool_FilledRectangle = 6;
VXLTool_Darken = 7;
VXLTool_Lighten = 8;
VXLTool_SmoothNormal = 9;
VXLTool_FloodFillErase = 10;
ViewName: array[0..5] of string = (
' Back',
' Front',
' Right',
' Left',
' Top',
' Bottom');
Function LoadVoxel(Filename : String) : boolean;
Function NewVoxel(Game,x,y,z : integer) : boolean;
Procedure ChangeSection;
Procedure SetupViews;
Procedure SetSpectrumMode;
Procedure SetNormalsCount;
Function CleanVCol(Color : TVector3f) : TColor;
Function GetVXLPaletteColor(Color : integer) : TColor;
Procedure PaintView(WndIndex: Integer; isMouseLeftDown : boolean; var Cnv: PPaintBox; var View: TVoxelView);
function colourtogray(colour : cardinal): cardinal;
procedure SplitColour(raw: TColor; var red, green, blue: Byte);
Procedure PaintPalette(var cnvPalette : TPaintBox; Mark : boolean);
Procedure CentreView(WndIndex: Integer);
Procedure CentreViews;
procedure ZoomToFit(WndIndex: Integer);
Procedure RepaintViews;
procedure TranslateClick(WndIndex, sx, sy: Integer; var lx, ly, lz: Integer);
procedure TranslateClick2(WndIndex, sx, sy: Integer; var lx, ly, lz: Integer);
procedure MoveCursor(lx, ly, lz: Integer; Repaint : boolean);
Function GetPaletteColourFromVoxel(x,y, WndIndex : integer) : integer;
procedure ActivateView(Idx: Integer);
procedure SyncViews;
procedure RefreshViews;
procedure drawstraightline(const a : TVoxelSection; var tempview : Ttempview; var last,first : TVector3i; v: TVoxelUnpacked);
procedure VXLRectangle(Xpos,Ypos,Zpos,Xpos2,Ypos2,Zpos2:Integer; Fill: Boolean; v : TVoxelUnpacked);
Function ApplyNormalsToVXL(var VXL : TVoxelSection) : integer;
Function ApplyCubedNormalsToVXL(var VXL : TVoxelSection) : integer;
Function ApplyInfluenceNormalsToVXL(var VXL : TVoxelSection) : integer;
Function RemoveRedundantVoxelsFromVXL(var VXL : TVoxelSection) : integer;
procedure UpdateHistoryMenu;
procedure VXLBrushTool(VXL : TVoxelSection; Xc,Yc,Zc: Integer; V: TVoxelUnpacked; BrushMode: Integer; BrushView: EVoxelViewOrient);
procedure VXLBrushToolDarkenLighten(VXL : TVoxelSection; Xc,Yc,Zc: Integer; BrushMode: Integer; BrushView: EVoxelViewOrient; Darken : Boolean);
procedure ClearVXLLayer(var Vxl : TVoxelSection);
Function ApplyTempView(var vxl :TVoxelSection): Boolean;
Procedure VXLCopyToClipboard(Vxl : TVoxelSection);
Procedure VXLCutToClipboard(Vxl : TVoxelSection);
procedure VXLFloodFillTool(Vxl : TVoxelSection; Xpos,Ypos,Zpos: Integer; v: TVoxelUnpacked; EditView: EVoxelViewOrient);
Procedure RemoveDoublesFromTempView;
Procedure PasteFullVXL(var Vxl : TVoxelsection);
Procedure PasteVXL(var Vxl : TVoxelsection);
procedure PaintView2(WndIndex: Integer; isMouseLeftDown : boolean; var Cnv: PPaintBox; var View: TVoxelView);
Procedure SmoothVXLNormals(var Vxl : TVoxelSection);
procedure VXLSmoothBrushTool(VXL : TVoxelSection; Xc,Yc,Zc: Integer; V: TVoxelUnpacked; BrushMode: Integer; BrushView: EVoxelViewOrient);
function SetVector(x, y, z : single) : TVector3f;
function SetVectorI(x, y, z : integer) : TVector3i;
Procedure SetVoxelFileDefults;
Function IsVoxelValid : Boolean;
Function HasNormalsBug : Boolean;
Procedure SetNormals(Normal : Integer);
implementation
uses Voxel_Tools,undo_engine, Controls, FormMain;
function SetVector(x, y, z : single) : TVector3f;
begin
result.x := x;
result.y := y;
result.z := z;
end;
function SetVectorI(x, y, z : integer) : TVector3i;
begin
result.x := x;
result.y := y;
result.z := z;
end;
Function HasNormalsBug : Boolean;
var
x,N : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: HasNormalsBug');
{$endif}
Result := False;
N := VoxelFile.Section[0].Tailer.Unknown;
for x := 0 to VoxelFile.Header.NumSections -1 do
if VoxelFile.Section[x].Tailer.Unknown <> N then
Result := True;
end;
Function IsVoxelValid : Boolean;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: IsVoxelValid');
{$endif}
if AsciizToStr(VoxelFile.Header.FileType,16) <> 'Voxel Animation' then
Result := False
else if VoxelFile.Header.Unknown <> 1 then
Result := False
else
Result := True;
end;
Function LoadVoxel(Filename : String) : boolean;
begin
Result := false;
try
VoxelFile.Free;
VoxelFile := TVoxel.Create;
VoxelFile.LoadFromFile(Filename);
CurrentSection := 0;
ActiveSection := VoxelFile.Section[CurrentSection];
except
VoxelOpen := false;
exit;
end;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: LoadVoxel');
{$endif}
VXLFilename := Filename;
Config.AddFileToHistory(VXLFilename);
UpdateHistoryMenu;
VoxelOpen := true;
Result := true;
SetupViews;
SetNormalsCount;
SetSpectrumMode;
VXLChanged := false;
end;
procedure SetHeaderFileType(Name: String);
const
MAX_LEN = 16;
var
i: integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetHeaderFileType');
{$endif}
for i:=1 to 16 do
VoxelFile.Header.FileType[i]:=#0;
for i := 1 to Length(Name) do
begin
if i > MAX_LEN then break;
VoxelFile.Header.FileType[i] := Name[i];
end;
end;
Procedure SetVoxelFileDefults;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetVoxelFileDefaults');
{$endif}
SetHeaderFileType('Voxel Animation');
VoxelFile.Header.Unknown := 1;
VoxelFile.Header.StartPaletteRemap := 16;
VoxelFile.Header.EndPaletteRemap := 31;
VoxelFile.Header.BodySize := 0;
end;
Function NewVoxel(Game,x,y,z : integer) : boolean;
begin
Result := false;
try
VoxelFile.Free;
VoxelFile := TVoxel.Create;
SetVoxelFileDefults;
VoxelFile.Header.NumSections := 0;
VoxelFile.Header.NumSections2 := 0;
CurrentSection := 0;
VoxelFile.InsertSection(0,'Body',x,y,z);
ActiveSection := VoxelFile.Section[CurrentSection];
ActiveSection.Tailer.Unknown := Game;
except
VoxelOpen := false;
exit;
end;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: NewVoxel');
{$endif}
VXLFilename := '';
VoxelOpen := true;
VoxelFile.Loaded := true;
Result := true;
if FrmMain.p_Frm3DPreview <> nil then
begin
FrmMain.p_Frm3DPreview^.SpStopClick(nil);
FrmMain.p_Frm3DPreview^.SpFrame.MaxValue := 1;
end;
SetupViews;
SetNormalsCount;
SetSpectrumMode;
VXLChanged := true;
end;
Procedure ChangeSection;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: ChangeSection');
{$endif}
ActiveSection := VoxelFile.Section[CurrentSection];
SetupViews;
end;
Procedure SetupViews;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetupViews');
{$endif}
ActiveSection.View[0].Refresh;
ActiveSection.View[1].Refresh;
ActiveSection.View[2].Refresh;
ActiveSection.Viewport[0].Zoom := DefultZoom;
ActiveSection.Viewport[1].Zoom := DefultZoom;
ActiveSection.Viewport[2].Zoom := DefultZoom;
ZoomToFit(1);
ZoomToFit(2);
// CentreView(0);
CentreViews;
end;
Procedure SetSpectrumMode;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetSpectrumMode');
{$endif}
VoxelFile.setSpectrum(SpectrumMode);
end;
Procedure SetNormalsCount;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetNormalsCount');
{$endif}
ActiveNormalsCount := MAXNORM_TIBERIAN_SUN;
if ActiveSection.Tailer.Unknown = 4 then
ActiveNormalsCount := MAXNORM_RED_ALERT2;
end;
Function CleanVCol(Color : TVector3f) : TColor;
Var
T : TVector3f;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: CleanVCol');
{$endif}
T.X := Color.X;
T.Y := Color.Y;
T.Z := Color.Z;
If T.X > 255 then
T.X := 255
else If T.X < 0 then
T.X := 0;
If T.Y > 255 then
T.Y := 255
else If T.Y < 0 then
T.Y := 0;
If T.Z > 255 then
T.Z := 255
else if T.Z < 0 then
T.Z := 0;
Result := RGB(trunc(T.X),trunc(T.Y),trunc(T.Z));
end;
Function GetVXLPaletteColor(Color : integer) : TColor;
Var
T : TVector3f;
NormalNum : Integer;
NormalDiv : single;
N : integer;
begin
if Color < 0 then
begin
Result := BGViewColor;
exit;
end;
if SpectrumMode = ModeColours then
Result := VXLPalette[color]
else
begin
if ActiveSection.Tailer.Unknown = 4 then
begin
NormalNum := 244;
NormalDiv := 3;
end
else
begin
NormalNum := 35;
NormalDiv := 0.5;
end;
N := Color;
If N > NormalNum Then
N := NormalNum;
T.X := 127 + (N - (NormalNum/2))/NormalDiv;
T.Y := 127 + (N - (NormalNum/2))/NormalDiv;
T.Z := 127 + (N - (NormalNum/2))/NormalDiv;
// T.X := N;
// T.Y := N;
// T.Z := N;
Result := CleanVCol(T);
end;
end;
procedure PaintView(WndIndex: Integer; isMouseLeftDown : boolean; var Cnv: PPaintBox; var View: TVoxelView);
var
x,xx, y, txx,tyy: Integer;
r: TRect;
PalIdx : integer;
Viewport: TViewport;
f : boolean;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: PaintView');
{$endif}
if (not Cnv.Enabled) or (not IsEditable) then
begin // draw it empty then
with Cnv.Canvas do
begin
r.Left := 0;
r.Top := 0;
r.Right := Cnv.Width;
r.Bottom := Cnv.Height;
Brush.Color := clBtnFace;
FillRect(r);
end;
Exit; // don't do anything else then
end;
if View = nil then Exit;
Viewport := ActiveSection.Viewport[WndIndex];
// fill margins around shape
Cnv.Canvas.Brush.Style := bsSolid;
Cnv.Canvas.Brush.Color := BGViewColor;
// left side?
if (Viewport.Left > 0) then
begin
with r do
begin // left size
Left := 0;
Right := Viewport.Left;
Top := 0;
Bottom := Cnv.Height;
end;
with Cnv.Canvas do
FillRect(r);
end;
// right side?
if (Viewport.Left + (Viewport.Zoom * View.Width)) < Cnv.Width then
begin
with r do
begin // right side
Left := Viewport.Left + (Viewport.Zoom * View.Width);
Right := Cnv.Width;
Top := 0;
Bottom := Cnv.Height;
end;
with Cnv.Canvas do
FillRect(r);
end;
// top
if (Viewport.Top > 0) then
begin
with r do
begin // top
Left := 0;
Right := Cnv.Width;
Top := 0;
Bottom := Viewport.Top;
end;
with Cnv.Canvas do
FillRect(r);
end;
// bottom
if (Viewport.Top + (Viewport.Zoom * View.Height)) < Cnv.Height then
begin
with r do
begin // bottom
Top := Viewport.Top + (Viewport.Zoom * View.Height);
Bottom := Cnv.Height;
Left := 0;
Right := Cnv.Width;
end;
with Cnv.Canvas do
FillRect(r);
end;
Cnv.Canvas.Brush.Style := bsSolid;
// paint view
Cnv.Canvas.Pen.Color := clRed; //VXLPalette[Transparent];
for x := 0 to (View.Width - 1) do
begin
r.Left := (x * Viewport.Zoom) + Viewport.Left;
r.Right := r.Left + Viewport.Zoom;
if r.Right < 0 then Continue; // not visible checks
if r.Left > Cnv.Width then Continue; // not visible checks
r.Top := Viewport.Top;
r.Bottom := r.Top + Viewport.Zoom;
for y := 0 to (View.Height - 1) do
begin
if (r.Bottom >= 0) and (r.Top <= Cnv.Height) then
begin // not visible checks
if (ViewMode = ModeCrossSection) and (wndindex=0) then
begin
if View.Canvas[x,y].Depth = View.Foreground then
PalIdx := View.Canvas[x,y].Colour
else
PalIdx := VIEWBGCOLOR;
end
else if View.Canvas[x,y].Colour = VTRANSPARENT then // ModeFull or ModeEmpDepth
PalIdx := VIEWBGCOLOR
else
PalIdx := View.Canvas[x,y].Colour;
f := false;
if WndIndex = 0 then
if tempview.Data_no > 0 then
begin
for xx := 1 to tempview.Data_no do
begin
if (View.getViewNameIdx = 1) or (View.getViewNameIdx = 3) or (View.getViewNameIdx = 5) then
txx := View.Width - 1-tempview.data[xx].X
else
txx := tempview.data[xx].X;
if (txx = x) and (View.Height - 1-tempview.data[xx].Y = y) then
begin
if tempview.data[xx].VU then
begin
if tempview.data[xx].V.Used then
PalIdx := tempview.data[xx].V.Normal;
end
else
begin
if SpectrumMode = ModeColours then
PalIdx := ActiveColour
else
PalIdx := ActiveNormal;
end;
f := true;
end;
end;
end;
with Cnv.Canvas do
begin
Brush.Color := GetVXLPaletteColor(PalIdx);
if ((ViewMode = ModeEmphasiseDepth) and (wndindex=0) and (View.Canvas[x,y].Depth = View.Foreground)) or (f = true) then
begin
if Viewport.Zoom = 1 then
Pixels[r.Left,r.Top] := Pen.Color
else
Rectangle(r.Left,r.Top,r.Right,r.Bottom)
end
else
FillRect(r);
{$IFDEF DEBUG_NORMALS}
if (SpectrumMode = ModeNormals) then
if (PalIdx > -1) then
if Viewport.Zoom > 10 then
begin
Font.Color := VXLPalette[PalIdx] shr 2;
TextOut(r.Left,r.Top,IntToStr(View.Canvas[x,y].Colour));
end;
{$ENDIF}
end;
end;
Inc(r.Top,Viewport.Zoom);
Inc(r.Bottom,Viewport.Zoom);
end;
end;
// draw cursor, but not if drawing!
if not isMouseLeftDown then
begin
View.getPhysicalCursorCoords(x,y);
//set brush color, or else it will get the color of the bottom-right voxel
Cnv.Canvas.Brush.Color:= BGViewColor;
// vert
r.Top := Max(Viewport.Top,0);
r.Bottom := Min(Viewport.Top + (View.Height * Viewport.Zoom), Cnv.Height);
r.Left := (x * Viewport.Zoom) + Viewport.Left + (Viewport.Zoom div 2) - 1;
r.Right := r.Left + 2;
Cnv.Canvas.DrawFocusRect(r);
// horiz
r.Left := Max(Viewport.Left,0);
r.Right := Min(Viewport.Left + (View.Width * Viewport.Zoom), Cnv.Width);
r.Top := (y * Viewport.Zoom) + Viewport.Top + (Viewport.Zoom div 2) - 1;
r.Bottom := r.Top + 2;
Cnv.Canvas.DrawFocusRect(r);
end
else
begin
View.getPhysicalCursorCoords(x,y);
//set brush color, or else it will get the color of the bottom-right voxel
Cnv.Canvas.Brush.Color:= clbtnface;
// vert
r.Top := Max(Viewport.Top,0)-1;
r.Bottom := Min(Viewport.Top + (View.Height * Viewport.Zoom), Cnv.Height)+1;
r.Left := Max(Viewport.Left,0)-1;
r.Right := Min(Viewport.Left + (View.Width * Viewport.Zoom), Cnv.Width)+1;
Cnv.Canvas.FrameRect(r);
end;
end;
procedure PaintView2(WndIndex: Integer; isMouseLeftDown : boolean; var Cnv: PPaintBox; var View: TVoxelView);
var
x,xx, y, txx,tyy: Integer;
r: TRect;
PalIdx : integer;
Viewport: TViewport;
f : boolean;
Bitmap : TBitmap;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: PaintView2');
{$endif}
Bitmap := nil;
if (not Cnv.Enabled) or (not IsEditable) then
begin // draw it empty then
with Cnv.Canvas do
begin
r.Left := 0;
r.Top := 0;
r.Right := Cnv.Width;
r.Bottom := Cnv.Height;
Brush.Color := clBtnFace;
FillRect(r);
end;
Exit; // don't do anything else then
end;
if View = nil then Exit;
Viewport := ActiveSection.Viewport[WndIndex];
// fill margins around shape
Bitmap := TBitmap.Create;
Bitmap.Canvas.Brush.Style := bsSolid;
Bitmap.Canvas.Brush.Color := BGViewColor;
Bitmap.Width := Cnv.Width;
Bitmap.Height := Cnv.Height;
// left side?
if (Viewport.Left > 0) then
begin
with r do
begin // left size
Left := 0;
Right := Viewport.Left;
Top := 0;
Bottom := Cnv.Height;
end;
with Bitmap.Canvas do
FillRect(r);
end;
// right side?
if (Viewport.Left + (Viewport.Zoom * View.Width)) < Cnv.Width then
begin
with r do
begin // right side
Left := Viewport.Left + (Viewport.Zoom * View.Width);
Right := Cnv.Width;
Top := 0;
Bottom := Cnv.Height;
end;
with Bitmap.Canvas do
FillRect(r);
end;
// top
if (Viewport.Top > 0) then
begin
with r do
begin // top
Left := 0;
Right := Cnv.Width;
Top := 0;
Bottom := Viewport.Top;
end;
with Bitmap.Canvas do
FillRect(r);
end;
// bottom
if (Viewport.Top + (Viewport.Zoom * View.Height)) < Cnv.Height then
begin
with r do
begin // bottom
Top := Viewport.Top + (Viewport.Zoom * View.Height);
Bottom := Cnv.Height;
Left := 0;
Right := Cnv.Width;
end;
with Bitmap.Canvas do
FillRect(r);
end;
Bitmap.Canvas.Brush.Style := bsSolid;
// paint view
Bitmap.Canvas.Pen.Color := clRed; //VXLPalette[Transparent];
for x := 0 to (View.Width - 1) do
begin
r.Left := (x * Viewport.Zoom) + Viewport.Left;
r.Right := r.Left + Viewport.Zoom;
if r.Right < 0 then Continue; // not visible checks
if r.Left > Cnv.Width then Continue; // not visible checks
r.Top := Viewport.Top;
r.Bottom := r.Top + Viewport.Zoom;
for y := 0 to (View.Height - 1) do begin
if (r.Bottom >= 0) and (r.Top <= Cnv.Height) then begin // not visible checks
if (ViewMode = ModeCrossSection) and (wndindex=0) then begin
if View.Canvas[x,y].Depth = View.Foreground then
PalIdx := View.Canvas[x,y].Colour
else
PalIdx := VIEWBGCOLOR;
end else if View.Canvas[x,y].Colour = VTRANSPARENT then // ModeFull or ModeEmpDepth
PalIdx := VIEWBGCOLOR
else
PalIdx := View.Canvas[x,y].Colour;
f := false;
{if WndIndex = 0 then
if tempview.Data_no > 0 then
begin
if View.getViewNameIdx = 3 then
txx := tempview.Data[xx].X
else
txx := tempview.Data[xx].X;
end;}
if WndIndex = 0 then
if tempview.Data_no > 0 then
begin
for xx := 1 to tempview.Data_no do
begin
if (View.getViewNameIdx = 1) or(View.getViewNameIdx = 3) or (View.getViewNameIdx = 5) then
txx := View.Width - 1-tempview.data[xx].X
else
txx := tempview.data[xx].X;
if (txx = x) and (View.Height - 1-tempview.data[xx].Y = y) then
if tempview.data[xx].VU then
begin
if SpectrumMode = ModeColours then
PalIdx := tempview.data[xx].V.Colour
else
PalIdx := tempview.data[xx].V.Normal;
f := true;
end;
end;
end;
with Bitmap.Canvas do begin
Brush.Color := GetVXLPaletteColor(PalIdx);
if ((ViewMode = ModeEmphasiseDepth) and (wndindex=0) and
(View.Canvas[x,y].Depth = View.Foreground)) or (f = true) then begin
if Viewport.Zoom = 1 then
Pixels[r.Left,r.Top] := Pen.Color
else
Rectangle(r.Left,r.Top,r.Right,r.Bottom)
end else
FillRect(r);
{$IFDEF DEBUG_NORMALS}
if (SpectrumMode = ModeNormals) then
if (PalIdx > -1) then
if Viewport.Zoom > 10 then begin
Font.Color := VXLPalette[PalIdx] shr 2;
TextOut(r.Left,r.Top,IntToStr(View.Canvas[x,y].Colour));
end;
{$ENDIF}
end;
end;
Inc(r.Top,Viewport.Zoom);
Inc(r.Bottom,Viewport.Zoom);
end;
end;
// draw cursor, but not if drawing!
if not isMouseLeftDown then begin
View.getPhysicalCursorCoords(x,y);
//set brush color, or else it will get the color of the bottom-right voxel
Bitmap.Canvas.Brush.Color:= BGViewColor;
// vert
r.Top := Max(Viewport.Top,0);
r.Bottom := Min(Viewport.Top + (View.Height * Viewport.Zoom), Cnv.Height);
r.Left := (x * Viewport.Zoom) + Viewport.Left + (Viewport.Zoom div 2) - 1;
r.Right := r.Left + 2;
Bitmap.Canvas.DrawFocusRect(r);
// horiz
r.Left := Max(Viewport.Left,0);
r.Right := Min(Viewport.Left + (View.Width * Viewport.Zoom), Cnv.Width);
r.Top := (y * Viewport.Zoom) + Viewport.Top + (Viewport.Zoom div 2) - 1;
r.Bottom := r.Top + 2;
Bitmap.Canvas.DrawFocusRect(r);
end
else
begin
View.getPhysicalCursorCoords(x,y);
//set brush color, or else it will get the color of the bottom-right voxel
Bitmap.Canvas.Brush.Color:= clbtnface;
// vert
r.Top := Max(Viewport.Top,0)-1;
r.Bottom := Min(Viewport.Top + (View.Height * Viewport.Zoom), Cnv.Height)+1;
r.Left := Max(Viewport.Left,0)-1;
r.Right := Min(Viewport.Left + (View.Width * Viewport.Zoom), Cnv.Width)+1;
Bitmap.Canvas.DrawFocusRect(r);
{ // horiz
r.Left := Max(Viewport.Left,0);
r.Right := Min(Viewport.Left + (View.Width * Viewport.Zoom), Cnv.Width);
r.Top := Viewport.Top;
r.Bottom := r.Top + 2;
Cnv.Canvas.DrawFocusRect(r); }
end;
Cnv.Canvas.Draw(0,0,Bitmap); // Draw to Canvas, should stop flickerings
//Cnv.Canvas.TextOut(0,0,'hmm');
Bitmap.Free;
end;
function colourtogray(colour : cardinal): cardinal;
var
temp : char;
begin
temp := char((GetBValue(colour)*29 + GetGValue(colour)*150 + GetRValue(colour)*77) DIV 256);
Result := RGB(ord(temp),ord(temp),ord(temp));
end;
procedure SplitColour(raw: TColor; var red, green, blue: Byte);
begin
red := (raw and $00FF0000) shr 16;
green := (raw and $0000FF00) shr 8;
blue := raw and $000000FF;
end;
Procedure PaintPalette(var cnvPalette : TPaintBox; Mark : boolean);
var
colwidth, rowheight: Real;
i, j, idx: Integer;
r: TRect;
red, green, blue, mixcol: Byte;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: PaintPalette');
{$endif}
// Start colour mode.
if SpectrumMode = ModeColours then
begin
// Get basic measures.
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
// starts palette painting procedures...
idx := 0;
for i := 0 to 8 do
begin
r.Left := Trunc(i * colwidth);
r.Right := Ceil(r.Left + colwidth);
for j := 0 to 31 do
begin
r.Top := Trunc(j * rowheight);
r.Bottom := Ceil(r.Top + rowheight);
// dimensions are set. Now the colour.
with cnvPalette.Canvas do
begin
// This set if it's the original palette or...
// Greyscale (when no file is opened)
if isEditable then
Brush.Color := GetVXLPaletteColor(idx)
else
Brush.Color := colourtogray(GetVXLPaletteColor(idx));
// Check if it's suposed to be marked, it's active colour
// and... it's not used. Why? -- Banshee
if Mark and (((not UsedColoursOption) and (Idx = ActiveColour))) or ((UsedColoursOption) and (UsedColours[idx])) then
begin // the current pen
// This part makes a square and a 'X' through the colour box.
SplitColour(GetVXLPaletteColor(idx),red,green,blue);
mixcol := (red + green + blue);
Pen.Color := RGB(128 + mixcol,255 - mixcol, mixcol);
//Pen.Mode := pmNotXOR;
Rectangle(r.Left,r.Top,r.Right,r.Bottom);
MoveTo(r.Left,r.Top);
LineTo(r.Right,r.Bottom);
MoveTo(r.Right,r.Top);
LineTo(r.Left,r.Bottom);
end
else // Otherwise it just square it with the selected colour
FillRect(r);
end; // Next index...
Inc(Idx);
end;
end;
end
else
begin // SpectrumMode = ModeNormals
colwidth := cnvPalette.Width / 8;
rowheight := cnvPalette.Height / 32;
// clear background
r.Left := 0;
r.Right :=cnvPalette.Width;
r.Top := 0;
r.Bottom := cnvPalette.Height;
with cnvPalette.Canvas do
begin
Brush.Color := clBtnFace;
FillRect(r);
end;
// and draw Normals palette
idx := 0;
for i := 0 to 8 do begin
r.Left := Trunc(i * colwidth);
r.Right := Ceil(r.Left + colwidth);
for j := 0 to 31 do begin
r.Top := Trunc(j * rowheight);
r.Bottom := Ceil(r.Top + rowheight);
with cnvPalette.Canvas do begin
if isEditable then
Brush.Color := GetVXLPaletteColor(idx)
else
Brush.Color := colourtogray(GetVXLPaletteColor(idx));
FillRect(r);
if Mark and (((not UsedColoursOption) and (Idx = ActiveNormal))) or ((UsedColoursOption) and (UsedNormals[idx])) then
begin // the current pen
SplitColour(GetVXLPaletteColor(idx),red,green,blue);
mixcol := (red + green + blue);
Pen.Color := RGB(128 + mixcol,255 - mixcol, mixcol);
//Pen.Mode := pmNotXOR;
Rectangle(r.Left,r.Top,r.Right,r.Bottom);
MoveTo(r.Left,r.Top);
LineTo(r.Right,r.Bottom);
MoveTo(r.Right,r.Top);
LineTo(r.Left,r.Bottom);
end;
end;
Inc(idx);
if idx > ActiveNormalsCount-1 then Break;
end;
if idx > ActiveNormalsCount-1 then Break;
end;
end;
end;
procedure CentreView(WndIndex: Integer);
var Width, Height, x, y: Integer;
begin
if not VoxelOpen then Exit;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: CentreView');
{$endif}
Width := CnvView[WndIndex].Width;
Height := CnvView[WndIndex].Height;
with ActiveSection.Viewport[WndIndex] do
begin
x := ActiveSection.View[WndIndex].Width * Zoom;
if x > Width then
Left := 0 - ((x - Width) div 2)
else
Left := (Width - x) div 2;
y := ActiveSection.View[WndIndex].Height * Zoom;
if y > Height then
Top := 0 - ((y - Height) div 2)
else
Top := (Height - y) div 2;
end;
end;
procedure CentreViews;
var
WndIndex: Integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: CentreViews');
{$endif}
for WndIndex := 0 to 2 do
CentreView(WndIndex);
end;
procedure ZoomToFit(WndIndex: Integer);
var Width, Height: Integer;
begin
if not VoxelOpen then Exit;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: ZoomToFit');
{$endif}
Width := CnvView[WndIndex].Width;
Height := CnvView[WndIndex].Height;
with ActiveSection.Viewport[WndIndex] do
begin
Left := 0;
Top := 0;
Zoom := Trunc(Min(Width / ActiveSection.View[WndIndex].Width,Height / ActiveSection.View[WndIndex].Height));
if Zoom <= 0 then
Zoom := 1;
end;
end;
Procedure RepaintViews;
var
I : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: RepaintViews');
{$endif}
for i := 0 to 2 do
begin
CnvView[i].Refresh;
end;
end;
procedure TranslateClick(WndIndex, sx, sy: Integer; var lx, ly, lz: Integer);
var
p, q: Integer; // physical coords
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: TranslateClick');
{$endif}
//following code needs to be fixed/replaced
with ActiveSection do
begin
//new conversion routines?
p:=(sx - Viewport[WndIndex].Left) div Viewport[WndIndex].Zoom;
q:=(sy - Viewport[WndIndex].Top) div Viewport[WndIndex].Zoom;
p:=Max(p,0); //make sure p is >=0
q:=Max(q,0); //same for q
//also make sure they're in range of 0..(Width/Height/Depth)-1
p:=Min(p,View[WndIndex].Width - 1);
q:=Min(q,View[WndIndex].Height - 1);
//px/py were from original version, but they give wrong values sometimes (because they use / and trunc instead of div)!
//px := Min(Max(Trunc((sx - Viewport[WndIndex].Left) / Viewport[WndIndex].Zoom),0),View[WndIndex].Width - 1);
//py := Min(Max(Ceil((sy - Viewport[WndIndex].Top) / Viewport[WndIndex].Zoom),0),View[WndIndex].Height - 1);
View[WndIndex].TranslateClick(p,q,lx,ly,lz);
end;
//I want range checks - on lx,ly and lz
//Range checks are already performed somewhere else, but where?!
//They are flawed!
//the only reason the program doesn't crash with X is because it can write in
//other parts of the file!!!
{ if not (lx in [0..ActiveSection.Tailer.XSize-1]) then ShowMessage('X range error');
if not (ly in [0..ActiveSection.Tailer.YSize-1]) then ShowMessage('Y range error');
if not (lz in [0..ActiveSection.Tailer.ZSize-1]) then ShowMessage('Z range error');}
end;
procedure TranslateClick2(WndIndex, sx, sy: Integer; var lx, ly, lz: Integer);
var
p, q: Integer; // physical coords
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: TranslateClick2');
{$endif}
//following code needs to be fixed/replaced
with ActiveSection do
begin
//new conversion routines?
p:=(sx - Viewport[WndIndex].Left) div Viewport[WndIndex].Zoom;
q:=(sy - Viewport[WndIndex].Top) div Viewport[WndIndex].Zoom;
//p:=Max(p,0); //make sure p is >=0
//q:=Max(q,0); //same for q
//also make sure they're in range of 0..(Width/Height/Depth)-1
// p:=Min(p,View[WndIndex].Width - 1);
// q:=Min(q,View[WndIndex].Height - 1);
//px/py were from original version, but they give wrong values sometimes (because they use / and trunc instead of div)!
//px := Min(Max(Trunc((sx - Viewport[WndIndex].Left) / Viewport[WndIndex].Zoom),0),View[WndIndex].Width - 1);
//py := Min(Max(Ceil((sy - Viewport[WndIndex].Top) / Viewport[WndIndex].Zoom),0),View[WndIndex].Height - 1);
View[WndIndex].TranslateClick(p,q,lx,ly,lz);
end;
//I want range checks - on lx,ly and lz
//Range checks are already performed somewhere else, but where?!
//They are flawed!
//the only reason the program doesn't crash with X is because it can write in
//other parts of the file!!!
{ if not (lx in [0..ActiveSection.Tailer.XSize-1]) then ShowMessage('X range error');
if not (ly in [0..ActiveSection.Tailer.YSize-1]) then ShowMessage('Y range error');
if not (lz in [0..ActiveSection.Tailer.ZSize-1]) then ShowMessage('Z range error');}
end;
procedure MoveCursor(lx, ly, lz: Integer; Repaint : boolean);
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: Move Cursor');
{$endif}
with ActiveSection do
begin
SetX(lx);
SetY(ly);
SetZ(lz);
View[0].Refresh;
View[1].Refresh;
View[2].Refresh;
end;
if Repaint then
RepaintViews;
end;
Function GetPaletteColourFromVoxel(x,y, WndIndex : integer) : integer;
var
Pos : TVector3i;
v : TVoxelUnpacked;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: GetPaletteColourFromVoxel');
{$endif}
Result := -1;
TranslateClick(WndIndex,x,y,Pos.x,Pos.y,Pos.z);
ActiveSection.GetVoxel(Pos.x,Pos.y,Pos.z,v);
if v.Used then
if SpectrumMode = ModeColours then
Result := v.Colour
else
Result := v.Normal;
end;
procedure ActivateView(Idx: Integer);
var
swapView: TVoxelView;
swapThumb: TThumbNail;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: ActivateView');
{$endif}
with ActiveSection do
begin
swapView := View[0];
View[0] := View[Idx];
View[Idx] := swapView;
swapThumb := Thumb[0];
Thumb[0] := Thumb[Idx];
Thumb[Idx] := swapThumb;
Viewport[0].Zoom := DefultZoom;
end;
SyncViews;
CentreView(0);
ZoomToFit(Idx);
CentreView(Idx);
RepaintViews;
end;
procedure SyncViews;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SyncViews');
{$endif}
lblView[0].Caption := ' Editing View: ' + ViewName[ActiveSection.View[0].GetViewNameIdx];
lblView[1].Caption := ' View: ' + ViewName[ActiveSection.View[1].GetViewNameIdx];
lblView[2].Caption := ' View: ' + ViewName[ActiveSection.View[2].GetViewNameIdx];
end;
procedure RefreshViews;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: RefreshViews');
{$endif}
with ActiveSection do
begin
View[0].Refresh;
View[1].Refresh;
View[2].Refresh;
end;
end;
function getgradient(last,first : TVector3i) : single;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: GetGradient');
{$endif}
if (first.X-last.X = 0) or (first.Y-last.Y = 0) then
result := 0
else
result := (first.Y-last.Y) / (first.X-last.X);
end;
procedure drawstraightline(const a : TVoxelSection; var tempview : Ttempview; var last,first : TVector3i; v: TVoxelUnpacked);
var
x,y,ss : integer;
gradient,c : single;
o : byte;
begin
// Straight Line Equation : Y=MX+C
o := 0;
if (a.View[0].getOrient = oriX) then
begin
ss := last.x;
last.X := last.Z;
first.X := first.Z;
o := 1;
end
else
if (a.View[0].getOrient = oriY) then
begin
ss := last.y;
last.Y := last.Z;
first.Y := first.Z;
o := 2;
end
else
if (a.View[0].getOrient = oriZ) then
ss := last.z
else
begin
messagebox(0,'Error: Can`t Draw 3D Line','Math Error',0);
exit;
end;
gradient := getgradient(last,first);
c := last.Y-(last.X * gradient);
tempview.Data_no := 0;
setlength(tempview.Data,0);
if (first.X = last.X) then
for y := min(first.Y,last.y) to max(first.Y,last.y) do
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no+1);
if o = 1 then
begin
tempview.Data[tempview.Data_no].X := y;
tempview.Data[tempview.Data_no].Y := first.X;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=ss;
tempview.Data[tempview.Data_no].VC.Y :=y;
tempview.Data[tempview.Data_no].VC.Z :=first.X;
tempview.Data[tempview.Data_no].V := V;
end
else
if o = 2 then
begin
tempview.Data[tempview.Data_no].X := first.X;
tempview.Data[tempview.Data_no].Y := y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=first.X;
tempview.Data[tempview.Data_no].VC.Y :=ss;
tempview.Data[tempview.Data_no].VC.Z :=y;
tempview.Data[tempview.Data_no].V := V;
end
else
begin
tempview.Data[tempview.Data_no].X := first.X;
tempview.Data[tempview.Data_no].Y := y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=first.X;
tempview.Data[tempview.Data_no].VC.Y :=y;
tempview.Data[tempview.Data_no].VC.Z :=ss;
tempview.Data[tempview.Data_no].V := V;
end;
end
else
if (first.Y = last.Y) then
for x := min(first.x,last.x) to max(first.x,last.x) do
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no+1);
if o = 1 then
begin
tempview.Data[tempview.Data_no].X := first.Y;
tempview.Data[tempview.Data_no].Y := x;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=ss;
tempview.Data[tempview.Data_no].VC.Y :=first.y;
tempview.Data[tempview.Data_no].VC.Z :=x;
tempview.Data[tempview.Data_no].V := V;
end
else
if o = 2 then
begin
tempview.Data[tempview.Data_no].X := x;
tempview.Data[tempview.Data_no].Y := first.Y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=x;
tempview.Data[tempview.Data_no].VC.Y :=ss;
tempview.Data[tempview.Data_no].VC.Z :=first.y;
tempview.Data[tempview.Data_no].V := V;
end
else
begin
tempview.Data[tempview.Data_no].X := x;
tempview.Data[tempview.Data_no].Y := first.Y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=x;
tempview.Data[tempview.Data_no].VC.Y :=first.y;
tempview.Data[tempview.Data_no].VC.Z :=ss;
tempview.Data[tempview.Data_no].V := V;
end;
end
else
begin
for x := min(first.X,last.X) to max(first.X,last.X) do
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no+1);
if o = 1 then
begin
tempview.Data[tempview.Data_no].X := round((gradient*x)+c);
tempview.Data[tempview.Data_no].Y := x;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=ss;
tempview.Data[tempview.Data_no].VC.Y :=round((gradient*x)+c);
tempview.Data[tempview.Data_no].VC.Z :=x;
tempview.Data[tempview.Data_no].V := V;
end
else
if o = 2 then
begin
tempview.Data[tempview.Data_no].X := x;
tempview.Data[tempview.Data_no].Y := round((gradient*x)+c);
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=x;
tempview.Data[tempview.Data_no].VC.Y :=ss;
tempview.Data[tempview.Data_no].VC.Z :=round((gradient*x)+c);
tempview.Data[tempview.Data_no].V := V;
end
else
begin
tempview.Data[tempview.Data_no].X := x;
tempview.Data[tempview.Data_no].Y := round((gradient*x)+c);
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=x;
tempview.Data[tempview.Data_no].VC.Y :=round((gradient*x)+c);
tempview.Data[tempview.Data_no].VC.Z :=ss;
tempview.Data[tempview.Data_no].V := V;
end;
end;
for y := min(first.Y,last.Y) to max(first.Y,last.Y) do
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no+1);
if o = 1 then
begin
tempview.Data[tempview.Data_no].X := y;
tempview.Data[tempview.Data_no].Y := round((y-c)/ gradient);
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=ss;
tempview.Data[tempview.Data_no].VC.Y :=y;
tempview.Data[tempview.Data_no].VC.Z :=round((y-c)/ gradient);
tempview.Data[tempview.Data_no].V := V;
end
else
if o = 2 then
begin
tempview.Data[tempview.Data_no].X := round((y-c)/ gradient);
tempview.Data[tempview.Data_no].Y := y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=round((y-c)/ gradient);
tempview.Data[tempview.Data_no].VC.Y :=ss;
tempview.Data[tempview.Data_no].VC.Z :=y;
tempview.Data[tempview.Data_no].V := V;
end
else
begin
tempview.Data[tempview.Data_no].X := round((y-c)/ gradient);
tempview.Data[tempview.Data_no].Y := y;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X :=round((y-c)/ gradient);
tempview.Data[tempview.Data_no].VC.Y :=y;
tempview.Data[tempview.Data_no].VC.Z :=ss;
tempview.Data[tempview.Data_no].V := V;
end;
end;
end;
RemoveDoublesFromTempView;
end;
procedure VXLRectangle(Xpos,Ypos,Zpos,Xpos2,Ypos2,Zpos2:Integer; Fill: Boolean; v : TVoxelUnpacked);
{type
EOrientRect = (oriUnDef, oriX, oriY, oriZ); }
var
i,j,k: Integer;
O: EVoxelViewOrient;
Inside,Exact: Integer;
begin
O:=ActiveSection.View[0].getOrient;
tempview.Data_no := 0;
setlength(tempview.Data,0);
{ //this isn't efficient...
for i:=0 to Tailer.XSize do begin
for j:=0 to Tailer.YSize do begin
for k:=0 to Tailer.ZSize do begin}
//this is better
for i:=Min(Xpos,Xpos2) to Max(Xpos,Xpos2) do begin
for j:=Min(Ypos,Ypos2) to Max(Ypos,Ypos2) do begin
for k:=Min(Zpos,Zpos2) to Max(Zpos,Zpos2) do begin
Inside:=0; Exact:=0;
case O of
oriX: begin
if (i=Xpos) then begin //we're in the right slice
if (j>Min(Ypos,Ypos2)) and (j<Max(Ypos,Ypos2)) then Inc(Inside);
if (k>Min(Zpos,Zpos2)) and (k<Max(Zpos,Zpos2)) then Inc(Inside);
if (j=Min(Ypos,Ypos2)) or (j=Max(Ypos,Ypos2)) then Inc(Exact);
if (k=Min(Zpos,Zpos2)) or (k=Max(Zpos,Zpos2)) then Inc(Exact);
end;
end;
oriY: begin
if (j=Ypos) then begin //we're in the right slice
if (i>Min(Xpos,Xpos2)) and (i<Max(Xpos,Xpos2)) then Inc(Inside);
if (k>Min(Zpos,Zpos2)) and (k<Max(Zpos,Zpos2)) then Inc(Inside);
if (i=Min(Xpos,Xpos2)) or (i=Max(Xpos,Xpos2)) then Inc(Exact);
if (k=Min(Zpos,Zpos2)) or (k=Max(Zpos,Zpos2)) then Inc(Exact);
end;
end;
oriZ: begin
if (k=Zpos) then begin //we're in the right slice
if (i>Min(Xpos,Xpos2)) and (i<Max(Xpos,Xpos2)) then Inc(Inside);
if (j>Min(Ypos,Ypos2)) and (j<Max(Ypos,Ypos2)) then Inc(Inside);
if (i=Min(Xpos,Xpos2)) or (i=Max(Xpos,Xpos2)) then Inc(Exact);
if (j=Min(Ypos,Ypos2)) or (j=Max(Ypos,Ypos2)) then Inc(Exact);
end;
end;
end;
if Fill then begin
if Inside+Exact=2 then begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
if O = oriX then
begin
tempview.Data[tempview.Data_no].X := j;
tempview.Data[tempview.Data_no].Y := k;
end
else
if O = oriY then
begin
tempview.Data[tempview.Data_no].X := i;
tempview.Data[tempview.Data_no].Y := k;
end
else
if O = oriZ then
begin
tempview.Data[tempview.Data_no].X := i;
tempview.Data[tempview.Data_no].Y := j;
end;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X := i;
tempview.Data[tempview.Data_no].VC.Y := j;
tempview.Data[tempview.Data_no].VC.Z := k;
tempview.Data[tempview.Data_no].V := v;
// SetVoxel(i,j,k,v);
end;
end else begin
if (Exact>=1) and (Inside+Exact=2) then begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
if O = oriX then
begin
tempview.Data[tempview.Data_no].X := j;
tempview.Data[tempview.Data_no].Y := k;
end
else
if O = oriY then
begin
tempview.Data[tempview.Data_no].X := i;
tempview.Data[tempview.Data_no].Y := k;
end
else
if O = oriZ then
begin
tempview.Data[tempview.Data_no].X := i;
tempview.Data[tempview.Data_no].Y := j;
end;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].VC.X := i;
tempview.Data[tempview.Data_no].VC.Y := j;
tempview.Data[tempview.Data_no].VC.Z := k;
tempview.Data[tempview.Data_no].V := v;
//SetVoxel(i,j,k,v);
end;
end;
end;
end;
end;
end;
Function ApplyNormalsToVXL(var VXL : TVoxelSection) : integer;
var
Res : TApplyNormalsResult;
begin
Res := ApplyNormals(VXL);
VXLChanged := true;
Result := Res.confused;
MessageBox(0,pchar('AutoNormals v1.1' + #13#13 + 'Total: ' + inttostr(Res.applied + Res.confused) + #13 +'Applied: ' + inttostr(Res.applied) + #13 + 'Confused: ' +inttostr(Res.confused) {+ #13+ 'Redundent: ' +inttostr(Res.redundant)}),'6-Faced Auto Normal Results',0);
end;
Function ApplyCubedNormalsToVXL(var VXL : TVoxelSection) : integer;
var
Res : TApplyNormalsResult;
begin
Res := ApplyCubedNormals(VXL,1.74,1,1,true,true,false);
VXLChanged := true;
Result := Res.applied;
MessageBox(0,pchar('AutoNormals v5.2' + #13#13 + 'Total: ' + inttostr(Res.applied) + ' voxels modified.'),'Cubed Auto Normal Results',0);
end;
Function ApplyInfluenceNormalsToVXL(var VXL : TVoxelSection) : integer;
var
Res : TApplyNormalsResult;
begin
Res := ApplyInfluenceNormals(VXL,3.55,1,1,true,false,false);
VXLChanged := true;
Result := Res.applied;
MessageBox(0,pchar('AutoNormals v6.1' + #13#13 + 'Total: ' + inttostr(Res.applied) + ' voxels modified.'),'Cubed Auto Normal Results',0);
end;
Function RemoveRedundantVoxelsFromVXL(var VXL : TVoxelSection) : integer;
begin
result := RemoveRedundantVoxels(VXL);
result := result + RemoveRedundantVoxelsOld(VXL);
VXLChanged := true;
end;
procedure UpdateHistoryMenu;
var
i: Integer;
S: String;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: UpdateHistoryMenu');
{$endif}
//update the history menu (recently used file menu, whatever it's called)
for i:=0 to HistoryDepth - 1 do
begin
S := Config.GetHistory(i);
mnuHistory[i].Tag:=i;
if S='' then
mnuHistory[i].Visible:=False
else
mnuHistory[i].Visible:=True;
mnuHistory[i].Caption:='&'+IntToStr(i+1)+' '+S;
end;
end;
procedure VXLBrushTool(VXL : TVoxelSection; Xc,Yc,Zc: Integer; V: TVoxelUnpacked; BrushMode: Integer; BrushView: EVoxelViewOrient);
var
Shape: Array[-5..5,-5..5] of 0..1;
i,j,r1,r2,x,y: Integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLBrushTool');
{$endif}
randomize;
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
Shape[0,0]:=1;
if BrushMode>=1 then
begin
Shape[0,1]:=1; Shape[0,-1]:=1; Shape[1,0]:=1; Shape[-1,0]:=1;
end;
if BrushMode>=2 then
begin
Shape[1,1]:=1; Shape[1,-1]:=1; Shape[-1,-1]:=1; Shape[-1,1]:=1;
end;
if BrushMode>=3 then
begin
Shape[0,2]:=1; Shape[0,-2]:=1; Shape[2,0]:=1; Shape[-2,0]:=1;
end;
if BrushMode =4 then
begin
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
for i:=1 to 3 do
begin
r1 := random(7)-3; r2 := random(7)-3;
Shape[r1,r2]:=1;
end;
end;
//Brush completed, now actually use it!
//for every pixel of the brush, check if we need to draw it (Shape),
//if so, use the correct view to set the voxel (with range checking!)
for i:=-5 to 5 do
begin
for j:=-5 to 5 do
begin
if Shape[i,j]=1 then
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
case BrushView of
oriX:
Begin
tempview.Data[tempview.Data_no].VC.X := Xc;
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+i,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := tempview.Data[tempview.Data_no].VC.Y;
tempview.Data[tempview.Data_no].Y := tempview.Data[tempview.Data_no].VC.Z;
//VXL.SetVoxel(Xc,Max(Min(Yc+i,VXL.Tailer.YSize-1),0),Max(Min(Zc+j,VXL.Tailer.ZSize-1),0),v);
end;
oriY:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Yc;
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
//VXL.SetVoxel(Max(Min(Xc+i,VXL.Tailer.XSize-1),0),Yc,Max(Min(Zc+j,VXL.Tailer.ZSize-1),0),v);
end;
oriZ:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Zc;
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
//VXL.SetVoxel(Max(Min(Xc+i,VXL.Tailer.XSize-1),0),Max(Min(Yc+j,VXL.Tailer.YSize-1),0),Zc,v);
end;
end;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
end;
end;
end;
if tempview.Data_no > 0 then
for x := 1 to tempview.Data_no do
for y := x to tempview.Data_no do
if y <> x then
if tempview.Data[x].VU then
if (tempview.Data[x].X = tempview.Data[y].X) and (tempview.Data[x].Y = tempview.Data[y].Y) then
tempview.Data[x].VU := false;
end;
function DarkenLightenEnv(V: TVoxelUnpacked; Darken : Boolean) : TVoxelUnpacked;
var
VUP : TVoxelUnpacked;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: DarkenLightenEnv');
{$endif}
VUP := V;
if Darken then
if VUP.Used then
begin
if (SpectrumMode = ModeColours) then
VUP.Colour := VUP.Colour + DarkenLighten;
if (SpectrumMode = ModeNormals) then
VUP.Normal := VUP.Normal + DarkenLighten;
end;
if not Darken then
if VUP.Used then
begin
if (SpectrumMode = ModeColours) then
VUP.Colour := VUP.Colour - DarkenLighten;
if (SpectrumMode = ModeNormals) then
VUP.Normal := VUP.Normal - DarkenLighten;
end;
if VUP.Normal > ActiveNormalsCount then
VUP.Normal := ActiveNormalsCount;
result := VUP;
end;
procedure VXLBrushToolDarkenLighten(VXL : TVoxelSection; Xc,Yc,Zc: Integer; BrushMode: Integer; BrushView: EVoxelViewOrient; Darken : Boolean);
var
Shape: Array[-5..5,-5..5] of 0..1;
i,j,r1,r2: Integer;
v : TVoxelUnpacked;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLBrushToolDarkenLighten');
{$endif}
randomize;
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
Shape[0,0]:=1;
if BrushMode>=1 then
begin
Shape[0,1]:=1; Shape[0,-1]:=1; Shape[1,0]:=1; Shape[-1,0]:=1;
end;
if BrushMode>=2 then
begin
Shape[1,1]:=1; Shape[1,-1]:=1; Shape[-1,-1]:=1; Shape[-1,1]:=1;
end;
if BrushMode>=3 then
begin
Shape[0,2]:=1; Shape[0,-2]:=1; Shape[2,0]:=1; Shape[-2,0]:=1;
end;
if BrushMode =4 then
begin
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
for i:=1 to 3 do
begin
r1 := random(7)-3; r2 := random(7)-3;
Shape[r1,r2]:=1;
end;
end;
//Brush completed, now actually use it!
//for every pixel of the brush, check if we need to draw it (Shape),
//if so, use the correct view to set the voxel (with range checking!)
for i:=-5 to 5 do
begin
for j:=-5 to 5 do
begin
if Shape[i,j]=1 then
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
case BrushView of
oriX:
Begin
tempview.Data[tempview.Data_no].VC.X := Xc;
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+i,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := tempview.Data[tempview.Data_no].VC.Y;
tempview.Data[tempview.Data_no].Y := tempview.Data[tempview.Data_no].VC.Z;
//VXL.SetVoxel(Xc,Max(Min(Yc+i,VXL.Tailer.YSize-1),0),Max(Min(Zc+j,VXL.Tailer.ZSize-1),0),v);
end;
oriY:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Yc;
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
//VXL.SetVoxel(Max(Min(Xc+i,VXL.Tailer.XSize-1),0),Yc,Max(Min(Zc+j,VXL.Tailer.ZSize-1),0),v);
end;
oriZ:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Zc;
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
//VXL.SetVoxel(Max(Min(Xc+i,VXL.Tailer.XSize-1),0),Max(Min(Yc+j,VXL.Tailer.YSize-1),0),Zc,v);
end;
end;
tempview.Data[tempview.Data_no].VU := true;
VXL.GetVoxel(tempview.Data[tempview.Data_no].VC.X,tempview.Data[tempview.Data_no].VC.Y,tempview.Data[tempview.Data_no].VC.Z,v);
tempview.Data[tempview.Data_no].V := DarkenLightenEnv(v,Darken);
end;
end;
end;
RemoveDoublesFromTempView;
end;
Procedure RemoveDoublesFromTempView;
var
x,y : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: RemoveDoublesFromTempView');
{$endif}
if tempview.Data_no > 0 then
for x := 1 to tempview.Data_no do
for y := x to tempview.Data_no do
if y <> x then
if tempview.Data[x].VU then
if (tempview.Data[x].X = tempview.Data[y].X) and (tempview.Data[x].Y = tempview.Data[y].Y) then
tempview.Data[x].VU := false;
end;
Function ApplyTempView(var vxl :TVoxelSection): Boolean;
var
v : TVoxelUnpacked;
i : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: ApplyTempView');
{$endif}
// 1.2: Fix Flood Fill Outside Voxel Undo Bug
Result := false;
if TempView.Data_no > 0 then
begin
// 1.2: Fix Flood Fill Outside Voxel Undo Bug
Result := CreateRestorePoint(TempView,Undo);
for i := 1 to TempView.Data_no do
if TempView.Data[i].VU then // If VU = true apply to VXL
begin
vxl.GetVoxel(TempView.Data[i].VC.X,TempView.Data[i].VC.Y,TempView.Data[i].VC.Z,v);
if (SpectrumMode = ModeColours) or (v.Used=False) then
v.Colour := TempView.Data[i].V.Colour;
if (SpectrumMode = ModeNormals) or (v.Used=False) then
v.Normal := TempView.Data[i].V.Normal;
v.Used := TempView.Data[i].V.Used;
vxl.SetVoxel(TempView.Data[i].VC.X,TempView.Data[i].VC.Y,TempView.Data[i].VC.Z,v);
end;
TempView.Data_no := 0;
SetLength(TempView.Data,0);
// 1.2 Fix: CreateRestorePoint will confirm VXLChanged.
// VXLChanged := true;
end;
end;
procedure ClearVXLLayer(var Vxl : TVoxelSection);
var
v : TVoxelUnpacked;
x,y,z : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: ClearVXLLayer');
{$endif}
tempview.Data_no := 0;
setlength(tempview.Data,0);
if vxl.View[0].GetOrient = oriX then
begin
for z := 0 to vxl.Tailer.ZSize-1 do
for y := 0 to vxl.Tailer.YSize-1 do
begin
vxl.GetVoxel(vxl.X,y,z,v);
v.Used := false;
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := vxl.X;
tempview.Data[tempview.Data_no].VC.Y := y;
tempview.Data[tempview.Data_no].VC.Z := z;
tempview.Data[tempview.Data_no].X := 0;
tempview.Data[tempview.Data_no].Y := 0;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
//vxl.SetVoxel(vxl.X,y,z,v);
end;
end;
if vxl.View[0].GetOrient = oriY then
begin
for x := 0 to vxl.Tailer.XSize-1 do
for z := 0 to vxl.Tailer.ZSize-1 do
begin
vxl.GetVoxel(x,vxl.Y,z,v);
v.Used := false;
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := x;
tempview.Data[tempview.Data_no].VC.Y := vxl.Y;
tempview.Data[tempview.Data_no].VC.Z := z;
tempview.Data[tempview.Data_no].X := 0;
tempview.Data[tempview.Data_no].Y := 0;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
//vxl.SetVoxel(x,vxl.Y,z,v);
end;
end;
if vxl.View[0].GetOrient = oriZ then
begin
for x := 0 to vxl.Tailer.XSize-1 do
for y := 0 to vxl.Tailer.YSize-1 do
begin
vxl.GetVoxel(x,y,vxl.z,v);
v.Used := false;
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := x;
tempview.Data[tempview.Data_no].VC.Y := y;
tempview.Data[tempview.Data_no].VC.Z := vxl.z;
tempview.Data[tempview.Data_no].X := 0;
tempview.Data[tempview.Data_no].Y := 0;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
//vxl.SetVoxel(x,y,vxl.z,v);
end;
end;
ApplyTempView(Vxl);
end;
Procedure VXLCopyToClipboard(Vxl : TVoxelSection);
var
x,y,z : integer;
v : tvoxelunpacked;
image : TBitmap;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLCopyToClipboard');
{$endif}
image := TBitmap.Create;
image.Canvas.Brush.Color := GetVXLPaletteColor(-1);
image.Canvas.Brush.Style := bsSolid;
if ActiveSection.View[0].GetOrient = oriX then
begin
image.Width := ActiveSection.Tailer.ZSize;
image.Height := ActiveSection.Tailer.YSize;
for z := 0 to ActiveSection.Tailer.ZSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
ActiveSection.GetVoxel(ActiveSection.X,y,z,v);
if v.Used then
If SpectrumMode = ModeColours then
image.Canvas.Pixels[z,y] := GetVXLPaletteColor(v.Colour)
else
image.Canvas.Pixels[z,y] := GetVXLPaletteColor(v.Normal);
end;
end;
if ActiveSection.View[0].GetOrient = oriY then
begin
image.Width := ActiveSection.Tailer.XSize;
image.Height := ActiveSection.Tailer.ZSize;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for z := 0 to ActiveSection.Tailer.ZSize-1 do
begin
ActiveSection.GetVoxel(x,ActiveSection.Y,z,v);
if v.Used then
If SpectrumMode = ModeColours then
image.Canvas.Pixels[x,z] := GetVXLPaletteColor(v.Colour)
else
image.Canvas.Pixels[x,z] := GetVXLPaletteColor(v.Normal);
end;
end;
if ActiveSection.View[0].GetOrient = oriZ then
begin
image.Width := ActiveSection.Tailer.XSize;
image.Height := ActiveSection.Tailer.YSize;
for x := 0 to ActiveSection.Tailer.XSize-1 do
for y := 0 to ActiveSection.Tailer.YSize-1 do
begin
ActiveSection.GetVoxel(x,y,ActiveSection.z,v);
if v.Used then
If SpectrumMode = ModeColours then
image.Canvas.Pixels[x,y] := GetVXLPaletteColor(v.Colour)
else
image.Canvas.Pixels[x,y] := GetVXLPaletteColor(v.Normal);
end;
end;
Clipboard.Clear;
Clipboard.Assign(image);
end;
Procedure VXLCutToClipboard(Vxl : TVoxelSection);
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLCutToClipboard');
{$endif}
VXLCopyToClipboard(VXL);
ClearVXLLayer(VXL);
end;
Procedure AddtoTempView(X,Y,Z : integer; V : TVoxelUnpacked; O : EVoxelViewOrient);
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: AddToTempView');
{$endif}
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
tempview.Data[tempview.Data_no].VC.X := x;
tempview.Data[tempview.Data_no].VC.Y := y;
tempview.Data[tempview.Data_no].VC.Z := z;
case O of
oriX:
begin
tempview.Data[tempview.Data_no].X := Y;
tempview.Data[tempview.Data_no].Y := Z;
end;
oriY:
begin
tempview.Data[tempview.Data_no].X := X;
tempview.Data[tempview.Data_no].Y := Z;
end;
oriZ:
begin
tempview.Data[tempview.Data_no].X := X;
tempview.Data[tempview.Data_no].Y := Y;
end;
end;
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := v;
end;
// Paste the full voxel into another O.o
Procedure PasteFullVXL(var Vxl : TVoxelsection);
var
x,y,z : integer;
image : TBitmap;
v : tvoxelunpacked;
begin
Image := nil;
// Security Check
if not isEditable then exit;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: PasteFullVXL');
{$endif}
// Prepare the voxel mapping image.
image := TBitmap.Create;
image.Canvas.Brush.Color := GetVXLPaletteColor(-1);
image.Canvas.Brush.Style := bsSolid;
image.Assign(Clipboard);
// Check if it's oriented to axis x
if Vxl.View[0].GetOrient = oriX then
begin
for z := 0 to Vxl.Tailer.ZSize-1 do
for y := 0 to Vxl.Tailer.YSize-1 do
begin
// Get current voxel block data
Vxl.GetVoxel(Vxl.X,y,z,v);
// Check if voxel is used
if image.Canvas.Pixels[z,y] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
// Verify the colour/normal
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(z,y,image)
else
v.Normal := getnormalcolour(z,y,image);
// Update voxel
Vxl.SetVoxel(Vxl.X,y,z,v);
end;
end;
// Check if it's oriented to axis y
if Vxl.View[0].GetOrient = oriY then
begin
for x := 0 to Vxl.Tailer.XSize-1 do
for z := 0 to Vxl.Tailer.ZSize-1 do
begin
// Get current voxel block data
Vxl.GetVoxel(x,Vxl.y,z,v);
// Check if voxel is used
if image.Canvas.Pixels[x,z] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
// Verify the colour/normal
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(x,z,image)
else
v.Normal := getnormalcolour(x,z,image);
// Update voxel
Vxl.SetVoxel(x,Vxl.y,z,v);
end;
end;
// Check if it's oriented to axis z
if Vxl.View[0].GetOrient = oriZ then
begin
for x := 0 to Vxl.Tailer.XSize-1 do
for y := 0 to Vxl.Tailer.YSize-1 do
begin
// Get current voxel block data
Vxl.GetVoxel(x,y,Vxl.z,v);
// Check if voxel is used
if image.Canvas.Pixels[x,y] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
// Verify the colour/normal
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(x,y,image)
else
v.Normal := getnormalcolour(x,y,image);
// Update voxel
Vxl.SetVoxel(x,y,Vxl.z,v);
end;
end;
end;
Procedure PasteVXL(var Vxl : TVoxelsection);
var
x,y,z : integer;
image : TBitmap;
v : tvoxelunpacked;
begin
// Security Check
if not isEditable then exit;
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: PasteVXL');
{$endif}
image := TBitmap.Create;
image.Canvas.Brush.Color := GetVXLPaletteColor(-1);
image.Canvas.Brush.Style := bsSolid;
image.Assign(Clipboard);
if Vxl.View[0].GetOrient = oriX then
begin
for z := 0 to Vxl.Tailer.ZSize-1 do
for y := 0 to Vxl.Tailer.YSize-1 do
begin
Vxl.GetVoxel(Vxl.X,y,z,v);
if image.Canvas.Pixels[z,y] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(z,y,image)
else
v.Normal := getnormalcolour(z,y,image);
if v.Used = true then
Vxl.SetVoxel(Vxl.X,y,z,v);
end;
end;
if Vxl.View[0].GetOrient = oriY then
begin
for x := 0 to Vxl.Tailer.XSize-1 do
for z := 0 to Vxl.Tailer.ZSize-1 do
begin
Vxl.GetVoxel(x,Vxl.y,z,v);
if image.Canvas.Pixels[x,z] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(x,z,image)
else
v.Normal := getnormalcolour(x,z,image);
if v.Used = true then
Vxl.SetVoxel(x,Vxl.y,z,v);
end;
end;
if Vxl.View[0].GetOrient = oriZ then
begin
for x := 0 to Vxl.Tailer.XSize-1 do
for y := 0 to Vxl.Tailer.YSize-1 do
begin
Vxl.GetVoxel(x,y,Vxl.z,v);
if image.Canvas.Pixels[x,y] <> GetVXLPaletteColor(-1) then
v.Used := true
else
v.Used := false;
If SpectrumMode = ModeColours then
v.Colour := getsquarecolour(x,y,image)
else
v.Normal := getnormalcolour(x,y,image);
if v.Used = true then
Vxl.SetVoxel(x,y,Vxl.z,v);
end;
end;
end;
procedure VXLFloodFillTool(Vxl : TVoxelSection; Xpos,Ypos,Zpos: Integer; v: TVoxelUnpacked; EditView: EVoxelViewOrient);
type
FloodSet = (Left,Right,Up,Down);
Flood3DPoint = record
X,Y,Z: Integer;
end;
StackType = record
Dir: set of FloodSet;
p: Flood3DPoint;
end;
function PointOK(l: Flood3DPoint): Boolean;
begin
PointOK:=False;
if (l.X<0) or (l.Y<0) or (l.Z<0) then Exit;
if (l.X>=vxl.Tailer.XSize) or (l.Y>=vxl.Tailer.YSize) or (l.Z>=vxl.Tailer.ZSize) then Exit;
PointOK:=True;
end;
var
z1,z2: TVoxelUnpacked;
i,j,k: Integer; //this isn't 100% FloodFill, but function is very handy for user;
Stack: Array of StackType; //this is the floodfill stack for my code
SC,Sp: Integer; //stack counter and stack pointer
po: Flood3DPoint;
Full: set of FloodSet;
Done: Array of Array of Array of Boolean;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLFloodFillTool');
{$endif}
tempview.Data_no := 0;
setlength(tempview.Data,0);
SetLength(Done,vxl.Tailer.XSize,vxl.Tailer.YSize,vxl.Tailer.ZSize);
SetLength(Stack,vxl.Tailer.XSize*vxl.Tailer.YSize*vxl.Tailer.ZSize);
//this array avoids creation of extra stack objects when it isn't needed.
for i:=0 to vxl.Tailer.XSize - 1 do
for j:=0 to vxl.Tailer.YSize - 1 do
for k:=0 to vxl.Tailer.ZSize - 1 do
Done[i,j,k]:=False;
vxl.GetVoxel(Xpos,Ypos,Zpos,z1);
AddtoTempView(Xpos,Ypos,Zpos,v,EditView);
Full:=[Left,Right,Up,Down];
Sp:=0;
Stack[Sp].Dir:=Full;
Stack[Sp].p.X:=Xpos; Stack[Sp].p.Y:=Ypos; Stack[Sp].p.Z:=Zpos;
SC:=1;
while (SC>0) do
begin
if Left in Stack[Sp].Dir then
begin //it's in there - check left
//not in there anymore! we're going to do that one now.
Stack[Sp].Dir:=Stack[Sp].Dir - [Left];
po:=Stack[Sp].p;
case EditView of
oriX: Dec(po.Y);
oriY: Dec(po.X);
oriZ: Dec(po.X);
end;
//now check this point - only if it's within range, check it.
if PointOK(po) then
begin
vxl.GetVoxel(po.X,po.Y,po.Z,z2);
if z2.Colour=z1.Colour then
begin
AddtoTempView(po.X,po.Y,po.Z,v,EditView);
if not Done[po.X,po.Y,po.Z] then
begin
Stack[SC].Dir:=Full-[Right]; //Don't go back
Stack[SC].p:=po;
Inc(SC);
Inc(Sp); //increase stack pointer
end;
Done[po.X,po.Y,po.Z]:=True;
end;
end;
end;
if Right in Stack[Sp].Dir then
begin //it's in there - check left
//not in there anymore! we're going to do that one now.
Stack[Sp].Dir:=Stack[Sp].Dir - [Right];
po:=Stack[Sp].p;
case EditView of
oriX: Inc(po.Y);
oriY: Inc(po.X);
oriZ: Inc(po.X);
end;
//now check this point - only if it's within range, check it.
if PointOK(po) then
begin
vxl.GetVoxel(po.X,po.Y,po.Z,z2);
if z2.Colour=z1.Colour then
begin
AddtoTempView(po.X,po.Y,po.Z,v,EditView);
if not Done[po.X,po.Y,po.Z] then
begin
Stack[SC].Dir:=Full-[Left]; //Don't go back
Stack[SC].p:=po;
Inc(SC);
Inc(Sp); //increase stack pointer
end;
Done[po.X,po.Y,po.Z]:=True;
end;
end;
end;
if Up in Stack[Sp].Dir then
begin //it's in there - check left
//not in there anymore! we're going to do that one now.
Stack[Sp].Dir:=Stack[Sp].Dir - [Up];
po:=Stack[Sp].p;
case EditView of
oriX: Dec(po.Z);
oriY: Dec(po.Z);
oriZ: Dec(po.Y);
end;
//now check this point - only if it's within range, check it.
if PointOK(po) then
begin
vxl.GetVoxel(po.X,po.Y,po.Z,z2);
if z2.Colour=z1.Colour then
begin
AddtoTempView(po.X,po.Y,po.Z,v,EditView);
if not Done[po.X,po.Y,po.Z] then
begin
Stack[SC].Dir:=Full-[Down]; //Don't go back
Stack[SC].p:=po;
Inc(SC);
Inc(Sp); //increase stack pointer
end;
Done[po.X,po.Y,po.Z]:=True;
end;
end;
end;
if Down in Stack[Sp].Dir then
begin //it's in there - check left
//not in there anymore! we're going to do that one now.
Stack[Sp].Dir:=Stack[Sp].Dir - [Down];
po:=Stack[Sp].p;
case EditView of
oriX: Inc(po.Z);
oriY: Inc(po.Z);
oriZ: Inc(po.Y);
end;
//now check this point - only if it's within range, check it.
if PointOK(po) then
begin
vxl.GetVoxel(po.X,po.Y,po.Z,z2);
if z2.Colour=z1.Colour then
begin
AddtoTempView(po.X,po.Y,po.Z,v,EditView);
if not Done[po.X,po.Y,po.Z] then
begin
Stack[SC].Dir:=Full-[Up]; //Don't go back
Stack[SC].p:=po;
Inc(SC);
Inc(Sp); //increase stack pointer
end;
Done[po.X,po.Y,po.Z]:=True;
end;
end;
end;
if (Stack[Sp].Dir = []) then
begin
Dec(Sp);
Dec(SC);
//decrease stack pointer and stack count
end;
end;
SetLength(Stack,0); // Free Up Memory
RemoveDoublesFromTempView;
for i := Low(Done) to High(Done) do
begin
for j := Low(Done[i]) to High(Done[i]) do
SetLength(Done[i,j],0);
SetLength(Done[i],0);
end;
SetLength(Done,0);
end;
Procedure SmoothVXLNormals(var Vxl : TVoxelSection);
var
Res : TApplyNormalsResult;
begin
Res := SmoothNormals(Vxl);
MessageBox(0,pchar('Smooth Normals v1.0' + #13#13 + 'Total: ' + inttostr(Res.applied + Res.confused) + #13 +'Applyed: ' + inttostr(Res.applied) + #13 + 'Confused: ' +inttostr(Res.confused) {+ #13+ 'Redundent: ' +inttostr(Res.redundant)}),'Smooth Normals Result',0);
end;
procedure VXLSmoothBrushTool(VXL : TVoxelSection; Xc,Yc,Zc: Integer; V: TVoxelUnpacked; BrushMode: Integer; BrushView: EVoxelViewOrient);
var
Shape: Array[-5..5,-5..5] of 0..1;
i,j,r1,r2,x,y: Integer;
VV : TVoxelUnpacked;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: VXLSmoothBrushTool');
{$endif}
randomize;
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
Shape[0,0]:=1;
if BrushMode>=1 then
begin
Shape[0,1]:=1; Shape[0,-1]:=1; Shape[1,0]:=1; Shape[-1,0]:=1;
end;
if BrushMode>=2 then
begin
Shape[1,1]:=1; Shape[1,-1]:=1; Shape[-1,-1]:=1; Shape[-1,1]:=1;
end;
if BrushMode>=3 then
begin
Shape[0,2]:=1; Shape[0,-2]:=1; Shape[2,0]:=1; Shape[-2,0]:=1;
end;
if BrushMode =4 then
begin
for i:=-5 to 5 do
for j:=-5 to 5 do
Shape[i,j]:=0;
for i:=1 to 3 do
begin
r1 := random(7)-3; r2 := random(7)-3;
Shape[r1,r2]:=1;
end;
end;
//Brush completed, now actually use it!
//for every pixel of the brush, check if we need to draw it (Shape),
//if so, use the correct view to set the voxel (with range checking!)
for i:=-5 to 5 do
begin
for j:=-5 to 5 do
begin
if Shape[i,j]=1 then
begin
tempview.Data_no := tempview.Data_no +1;
setlength(tempview.Data,tempview.Data_no +1);
case BrushView of
oriX:
Begin
tempview.Data[tempview.Data_no].VC.X := Xc;
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+i,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := tempview.Data[tempview.Data_no].VC.Y;
tempview.Data[tempview.Data_no].Y := tempview.Data[tempview.Data_no].VC.Z;
end;
oriY:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Yc;
tempview.Data[tempview.Data_no].VC.Z := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Zc+j,VXL.Tailer.ZSize-1),0);
end;
oriZ:
Begin
tempview.Data[tempview.Data_no].VC.X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].VC.Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
tempview.Data[tempview.Data_no].VC.Z := Zc;
tempview.Data[tempview.Data_no].X := Max(Min(Xc+i,VXL.Tailer.XSize-1),0);
tempview.Data[tempview.Data_no].Y := Max(Min(Yc+j,VXL.Tailer.YSize-1),0);
end;
end;
with tempview.Data[tempview.Data_no].VC do
ActiveSection.GetVoxel(X,Y,Z,VV);
if VV.Used then
tempview.Data[tempview.Data_no].VU := true;
tempview.Data[tempview.Data_no].V := V;
with tempview.Data[tempview.Data_no].VC do
tempview.Data[tempview.Data_no].V.Normal := GetSmoothNormal(Vxl,X,Y,Z,V.Normal);
end;
end;
end;
if tempview.Data_no > 0 then
for x := 1 to tempview.Data_no do
for y := x to tempview.Data_no do
if y <> x then
if tempview.Data[x].VU then
if (tempview.Data[x].X = tempview.Data[y].X) and (tempview.Data[x].Y = tempview.Data[y].Y) then
tempview.Data[x].VU := false;
end;
Procedure SetNormals(Normal : Integer);
var
x : integer;
begin
{$ifdef DEBUG_FILE}
FrmMain.DebugFile.Add('VoxelEngine: SetNormals');
{$endif}
for x := 0 to VoxelFile.Header.NumSections -1 do
VoxelFile.Section[x].Tailer.Unknown := Normal;
end;
begin
// Load default palette
LoadPaletteFromFile(ExtractFileDir(ParamStr(0)) + '\palettes\TS\unittem.pal');
BGViewColor := RGB(140,170,235);
VoxelFile := TVoxel.Create;
VoxelFile.InsertSection(0,'Dummy',1,1,1);
ActiveSection := VoxelFile.Section[0];
SpectrumMode := ModeColours;
ViewMode := ModeEmphasiseDepth;
if not LoadMouseCursors then
begin
messagebox(0,'Files Missing Load Aborted','Files Missing',0);
Application.Terminate;
exit;
end;
if TestBuild then
messagebox(0,'Voxel Section Editor III' + #13#13 + 'Version: TB '+testbuildversion+ #13#13#13 + 'THIS IS NOT TO BE DISTRIBUTED','Test Build Message',0);
end.
|
unit LrProject;
interface
uses
SysUtils, Classes, Contnrs,
LrDocument;
type
TLrProjectItem = class(TComponent)
private
FSource: string;
FDestination: string;
FDisplayName: string;
protected
function GetDestination: string; virtual;
function GetDisplayName: string; virtual;
function GetSource: string; virtual;
procedure SetDestination(const Value: string); virtual;
procedure SetDisplayName(const Value: string);
procedure SetSource(const Value: string); virtual;
public
constructor Create; reintroduce; virtual;
published
property Destination: string read GetDestination write SetDestination;
property DisplayName: string read GetDisplayName write SetDisplayName;
property Source: string read GetSource write SetSource;
end;
//
TLrProjectItems = class(TComponent)
protected
function GetCount: Integer;
function GetItems(inIndex: Integer): TLrProjectItem;
procedure Clear;
procedure DefineProperties(Filer: TFiler); override;
procedure LoadFromStream(inStream: TStream);
procedure ReadItems(Stream: TStream);
procedure SaveToStream(inStream: TStream);
procedure WriteItems(Stream: TStream);
public
constructor Create(inOwner: TComponent); reintroduce;
destructor Destroy; override;
function Find(const inSource: string): TLrProjectItem;
procedure Add(inItem: TLrProjectItem);
property Count: Integer read GetCount;
property Items[inIndex: Integer]: TLrProjectItem read GetItems; default;
end;
//
TLrProjectDocument = class(TLrDocument)
private
FItems: TLrProjectItems;
protected
function GetUntitledName: string; override;
public
constructor Create; override;
destructor Destroy; override;
function Find(const inSource: string): TLrProjectItem;
function GetUniqueName(const inName: string): string;
procedure AddItem(inItem: TLrProjectItem);
//procedure DocumentOpened(inDocument: TLrDocument);
//procedure DocumentClosed(inDocument: TLrDocument);
//procedure DocumentChange(Sender: TObject);
procedure Open(const inFilename: string); override;
procedure Save; override;
property Items: TLrProjectItems read FItems;
end;
implementation
uses
LrVclUtils;
{ TLrProjectItem }
constructor TLrProjectItem.Create;
begin
inherited Create(nil);
end;
function TLrProjectItem.GetDestination: string;
begin
Result := FDestination;
end;
function TLrProjectItem.GetDisplayName: string;
begin
if FDisplayName <> '' then
Result := FDisplayName
else begin
Result := ExtractFileName(Source);
if Result = '' then
Result := '(untitled)';
end;
end;
function TLrProjectItem.GetSource: string;
begin
Result := FSource;
end;
procedure TLrProjectItem.SetDestination(const Value: string);
begin
FDestination := Value;
end;
procedure TLrProjectItem.SetDisplayName(const Value: string);
begin
FDisplayName := Value;
end;
procedure TLrProjectItem.SetSource(const Value: string);
begin
FSource := Value;
end;
{ TLrProjectItems }
constructor TLrProjectItems.Create(inOwner: TComponent);
begin
inherited Create(inOwner);
end;
destructor TLrProjectItems.Destroy;
begin
inherited;
end;
procedure TLrProjectItems.Clear;
begin
DestroyComponents;
end;
procedure TLrProjectItems.ReadItems(Stream: TStream);
var
c, i: Integer;
begin
Stream.Read(c, 4);
for i := 0 to Pred(c) do
Add(TLrProjectItem(Stream.ReadComponent(nil)));
end;
procedure TLrProjectItems.WriteItems(Stream: TStream);
var
c, i: Integer;
begin
c := Count;
Stream.Write(c, 4);
for i := 0 to Pred(Count) do
Stream.WriteComponent(Items[i]);
end;
procedure TLrProjectItems.DefineProperties(Filer: TFiler);
begin
Filer.DefineBinaryProperty('Items', ReadItems, WriteItems, true);
end;
procedure TLrProjectItems.SaveToStream(inStream: TStream);
begin
LrSaveComponentToStream(Self, inStream);
end;
procedure TLrProjectItems.LoadFromStream(inStream: TStream);
begin
Clear;
LrLoadComponentFromStream(Self, inStream);
end;
function TLrProjectItems.GetCount: Integer;
begin
Result := ComponentCount;
end;
function TLrProjectItems.GetItems(inIndex: Integer): TLrProjectItem;
begin
Result := TLrProjectItem(Components[inIndex]);
end;
procedure TLrProjectItems.Add(inItem: TLrProjectItem);
begin
InsertComponent(inItem);
end;
function TLrProjectItems.Find(const inSource: string): TLrProjectItem;
var
i: Integer;
begin
Result := nil;
for i := 0 to Pred(Count) do
if (Items[i].Source = inSource) then
begin
Result := Items[i];
break;
end;
end;
{ TLrProjectDocument }
constructor TLrProjectDocument.Create;
begin
inherited;
//EnableSaveAs('TurboPhp Projects', '.trboprj');
FItems := TLrProjectItems.Create(nil);
end;
destructor TLrProjectDocument.Destroy;
begin
Items.Free;
inherited;
end;
function TLrProjectDocument.GetUntitledName: string;
begin
Result := 'Untitled Project';
end;
procedure TLrProjectDocument.Open(const inFilename: string);
var
s: TStream;
begin
Filename := inFilename;
s := TFileStream.Create(Filename, fmOpenRead);
try
Items.LoadFromStream(s);
finally
s.Free;
end;
inherited;
end;
procedure TLrProjectDocument.Save;
var
s: TStream;
begin
s := TFileStream.Create(Filename, fmCreate);
try
Items.SaveToStream(s);
finally
s.Free;
end;
inherited;
end;
function TLrProjectDocument.Find(const inSource: string): TLrProjectItem;
begin
Result := Items.Find(inSource);
end;
function TLrProjectDocument.GetUniqueName(const inName: string): string;
var
i: Integer;
begin
if Find(inName) = nil then
Result := inName
else begin
i := 0;
repeat
Inc(i);
Result := inName + IntToStr(i);
until Find(Result) = nil;
end;
end;
procedure TLrProjectDocument.AddItem(inItem: TLrProjectItem);
begin
Items.Add(inItem);
Change;
end;
{
procedure TLrProjectDocument.AddFile(const inFilename: string);
var
e: string;
begin
e := LowerCase(ExtractFileExt(inFilename));
if (e = cPageExt) then
AddTurboPhpDocumentItem(inFilename);
end;
procedure TLrProjectDocument.DocumentOpened(inDocument: TLrDocument);
var
item: TLrProjectItem;
begin
item := Find(inDocument.Filename);
if item is TDocumentItem then
TDocumentItem(item).Document := inDocument;
end;
procedure TLrProjectDocument.DocumentClosed(inDocument: TLrDocument);
var
item: TLrProjectItem;
begin
item := Find(inDocument.Filename);
if item is TDocumentItem then
TDocumentItem(item).Document := nil;
end;
procedure TLrProjectDocument.DocumentChange(Sender: TObject);
begin
Change;
end;
}
end.
|
unit fmAddPochasUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, uFormControl, StdCtrls, Buttons, uFControl,
uLabeledFControl, uSpravControl, uCharControl, uFloatControl,
uDateControl, uCommonSP, GlobalSPR, ExtCtrls, ibase, qfTools, AllPeopleUnit,
DB, FIBDataSet, pFIBDataSet, uSelectForm;
type
TfmAddPochas = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
KeyList: TActionList;
OkAction: TAction;
CancelAction: TAction;
Panel1: TPanel;
Man: TqFSpravControl;
Smeta: TqFSpravControl;
KolHours: TqFFloatControl;
Department: TqFSpravControl;
PeriodBeg: TqFDateControl;
PeriodEnd: TqFDateControl;
Tarif: TqFSpravControl;
PochasType: TqFSpravControl;
PochasTypeSelect: TpFIBDataSet;
PochasTypeSelectID_POCHAS_TYPE: TFIBIntegerField;
PochasTypeSelectPOCHAS_TYPE_NAME: TFIBStringField;
Reason: TqFCharControl;
SmNumberEdit: TEdit;
PubSprSmet: TpFIBDataSet;
PubSprSmetID_SMETA: TFIBBCDField;
PubSprSmetSMETA_TITLE: TFIBStringField;
PubSprSmetSMETA_KOD: TFIBIntegerField;
procedure OkActionExecute(Sender: TObject);
procedure DepartmentOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure SmetaOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure Prepare;
procedure TarifOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure CancelActionExecute(Sender: TObject);
procedure ManOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure PochasTypeOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure SmNumberEditChange(Sender: TObject);
private
{ Private declarations }
public
FMode : TFormMode;
end;
type
TView_FZ_PeopleModal_Sp = function(AOwner : TComponent;DB:TISC_DB_HANDLE):Variant; stdcall;
var
fmAddPochas: TfmAddPochas;
View_FZ_PeopleModal_Sp : TView_FZ_PeopleModal_Sp;
PeopleModule : Cardinal;
implementation
uses fmPochasOrderUnit;
{$R *.dfm}
procedure TfmAddPochas.Prepare;
//var
// y, m, d : Word;
begin
case FMode of
fmAdd : begin
qFAutoLoadFromRegistry(Self, nil);
Caption := 'Додавання джерела фінансування';
//DecodeDate(Date, y, m, d);
//PeriodBeg.Value := EncodeDate(y, 9, 1);
//PeriodEnd.Value := EncodeDate(y + 1, 5, 31);
end;
fmModify : begin
Caption := 'Редагування джерела фінансування';
end;
fmInfo : begin
Caption := 'Перегляд джерела фінансування';
Panel1.Enabled := False;
end;
end;
end;
procedure TfmAddPochas.OkActionExecute(Sender: TObject);
begin
if qFCheckAll(Self) then begin
ModalResult := mrOk;
qFAutoSaveIntoRegistry(Self, nil);
end;
end;
procedure TfmAddPochas.DepartmentOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(fmPochasOrder.LocalDatabase.Handle);
FieldValues['Actual_Date'] := fmPochasOrder.Date_Order;
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_Department'];
DisplayText := sp.Output['Name_Full'];
end;
sp.Free;
end;
end;
procedure TfmAddPochas.SmetaOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
var
id : Variant;
begin
id := GlobalSPR.GetSmets(Owner, fmPochasOrder.LocalDatabase.Handle, fmPochasOrder.Date_Order, psmSmet);
if ( VarArrayDimCount(id)>0 ) and ( id[0] <> Null ) then
begin
Value := id[0];
DisplayText := IntToStr(id[3]) + '. ' + id[2];
end;
end;
procedure TfmAddPochas.TarifOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('Asup\SpPochasTarif');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(fmPochasOrder.LocalDatabase.Handle);
FieldValues['SpDate'] := fmPochasOrder.Date_Order;
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if ( sp.Output <> nil ) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Id_Tarif'];
DisplayText := sp.Output['Tarif'];
Smeta.Value := sp.Output['KOD_SM'];
Smeta.DisplayText := sp.Output['SM_TITLE'];
end;
sp.Free;
end;
end;
procedure TfmAddPochas.CancelActionExecute(Sender: TObject);
begin
Close;
end;
procedure TfmAddPochas.ManOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
var
result : Variant;
begin
try
result := AllPeopleUnit.GetMan(Self, fmPochasOrder.LocalDatabase.Handle, False, True);
if (not VarIsNull(result)) and not (VarType(result) = varNull) and
not (VarArrayDimCount(result) = 0) then begin
Value := result[0];
DisplayText := result[1];
Reason.Value := 'Заява ' + result[2] + ' ' + Copy(result[3],1,1) +
'.' + Copy(result[4],1,1) + '.';
end;
except on e:Exception do begin
qFErrorDialog('Неможливо завантажити довідник фізичних осіб! Виникла помилка: "' +
e.Message + '"');
exit;
end;
end;
end;
procedure TfmAddPochas.PochasTypeOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
begin
if qSelect(PochasTypeSelect, 'Виберіть тип погодинной праці!') then begin
Value := PochasTypeSelectID_POCHAS_TYPE.Value;
DisplayText := PochasTypeSelectPOCHAS_TYPE_NAME.Value;
end;
end;
procedure TfmAddPochas.SmNumberEditChange(Sender: TObject);
begin
if SmNumberEdit.Text = '' then
exit;
try
PubSprSmet.Close;
PubSprSmet.ParamByName('smeta_kod').AsInteger := StrToInt(SmNumberEdit.Text);
PubSprSmet.Open;
PubSprSmet.FetchAll;
if PubSprSmet.RecordCount = 1 then begin
Smeta.Value := PubSprSmetID_SMETA.Value;
Smeta.DisplayText := PubSprSmetSMETA_KOD.AsString +
'. ' + PubSprSmetSMETA_TITLE.Value;
end;
except
end;
end;
end.
|
unit uCrudArticulos;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons,
uEstructura, uDAOArticulos;
type
{ TfrmCrudArticulos }
TfrmCrudArticulos = class(TForm)
edtId: TEdit;
edtCodigo: TEdit;
edtDescripcion: TEdit;
edtPrecioUnitario: TEdit;
edtStock: TEdit;
lblTitulo: TLabel;
lblId: TLabel;
lblCodigo: TLabel;
lblDescripcion: TLabel;
lblStock: TLabel;
lblPrecioUnitario: TLabel;
SpeedButtonAlta: TSpeedButton;
SpeedButtonVolver: TSpeedButton;
procedure FormActivate(Sender: TObject);
procedure SpeedButtonAltaClick(Sender: TObject);
procedure SpeedButtonVolverClick(Sender: TObject);
private
public
procedure Control;
Function ValidarCodigo():boolean;
Function ValidarDescripcion():boolean;
Function ValidarCampos():boolean;
Function ValidarPrecio():boolean;
Procedure LeerDatos(var rArticulo:TArticulo);
Procedure LimpiarCampos();
function LongitudCodigo(): boolean;
end;
var
frmCrudArticulos: TfrmCrudArticulos;
control0,control1:cadena50;
descripcion,codigo:boolean;
implementation
{$R *.lfm}
{ TfrmCrudArticulos }
function TfrmCrudArticulos.LongitudCodigo(): boolean;
begin
if(Length(edtCodigo.Text)>6)and(11>Length(edtCodigo.Text)) then
LongitudCodigo:=true
else
begin
LongitudCodigo:=false;
ShowMessage('ERROR: El código debe estar entre 7 y 10 caracteres');
edtCodigo.Text:='';
edtCodigo.SetFocus;
end;
end;
Function TfrmCrudArticulos.ValidarCodigo():boolean;
var
pos: integer;
codigo: cadena50;
begin
ValidarCodigo:=true;
codigo:=edtCodigo.text;
pos:=buscarCod(fi, edtCodigo.text);
if pos<> NO_ENCONTRADO then
begin
ShowMessage('ERROR: El código '+codigo+' ya existe' );
edtCodigo.Text:='';
edtCodigo.setfocus;
ValidarCodigo:=false;
end;
end;
Function TfrmCrudArticulos.ValidarDescripcion():boolean;
var
pos: integer;
descripcion: cadena50;
begin
ValidarDescripcion:=true;
descripcion:=edtDescripcion.text;
pos:=buscarDescripcion(fi,edtDescripcion.text);
if pos<> NO_ENCONTRADO then
begin
ShowMessage('ERROR: La descripción '+descripcion+' ya existe' );
edtDescripcion.text:='';
edtDescripcion.setfocus;
ValidarDescripcion:=false;
end;
end;
Function TfrmCrudArticulos.ValidarCampos():boolean;
var
codigo, descripcion, precio, stock: string;
begin
codigo:=edtCodigo.text;
descripcion:=edtDescripcion.text;
precio:=edtPrecioUnitario.text;
stock:=edtStock.text;
ValidarCampos:=true;
if (codigo='')or(descripcion='')or(precio='')or(stock='') then
begin
ShowMessage('ERROR: Debe completar todos los campos!');
ValidarCampos:=false;
end
end;
Function TfrmCrudArticulos.ValidarPrecio():boolean;
var
codigo:integer;
auxprecio: real;
begin
val(edtPrecioUnitario.text,auxprecio, codigo);
if auxprecio>0 then
ValidarPrecio:=true
else
begin
ShowMessage('ERROR: Ingrese un precio válido!');
edtPrecioUnitario.Text:='';
edtPrecioUnitario.setfocus;
ValidarPrecio:=false;
end;
end;
Procedure TfrmCrudArticulos.LeerDatos(var rArticulo:TArticulo);
var
code,idInt: integer;
precioUnitario: real;
begin
val(edtPrecioUnitario.text, precioUnitario, code);
val(edtId.text,idInt);
rArticulo.id:=idInt;
rArticulo.codigo:=edtCodigo.text;
rArticulo.descripcion:=edtDescripcion.text;
rArticulo.precioUnitario:=precioUnitario;
rArticulo.stock:=StrToInt(edtStock.text);
rArticulo.estado:=Estado_Activo;
end;
Procedure TfrmCrudArticulos.LimpiarCampos();
begin
edtCodigo.text:='';
edtDescripcion.text:='';
edtPrecioUnitario.text:='';
edtStock.text:='';
end;
procedure TfrmCrudArticulos.Control;
begin
descripcion:=False;
codigo:=False;
if uppercase(control0)=uppercase(edtDescripcion.Text) then
descripcion:=True
else
if ValidarDescripcion() then
descripcion:=True;
if (control1=edtCodigo.Text) then
codigo:=True
else
if ValidarCodigo() then
codigo:=true;
end;
procedure TfrmCrudArticulos.FormActivate(Sender: TObject);
begin
control0:=edtDescripcion.Text;
control1:=edtCodigo.Text;
end;
procedure TfrmCrudArticulos.SpeedButtonAltaClick(Sender: TObject);
var
articulo:TArticulo;
posicion:integer;
id:integer;
begin
if ValidarCampos()and ValidarPrecio()and LongitudCodigo() then
begin
leerDatos(articulo);
id:=strtoint(edtId.Text);
posicion:=buscarID(fi,id);
if (SpeedButtonAlta.Caption='ALTA') then
begin
if ValidarDescripcion() and ValidarCodigo()then
begin
Nuevo(articulo);
ShowMessage('Datos cargados correctamente');
edtId.caption:=IntToStr(getSiguienteId());
LimpiarCampos();
end;
end;
if (SpeedButtonAlta.Caption='MODIFICAR')then
begin
control;
if (descripcion=True) and (codigo=True) then
begin
Modificar(articulo,posicion);
showMessage('Datos modificados correctamente.');
LimpiarCampos();
close;
end;
end;
end;
end;
procedure TfrmCrudArticulos.SpeedButtonVolverClick(Sender: TObject);
begin
LimpiarCampos();
close;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
This shader allows to apply multiple textures, gathering them from existing materials.
This allows saving resources, since you can reference the textures of any material in
any materialLibrary.
Note that actually the component references a Material (not a texture) but
it uses that material's texture. The referenced material settings will be ignored,
but the texture's settings (like TextureMode, ImageGamma, ImageBrightness) will be used.
Instead the local material settings (listed in the collection) will be used.
}
unit VXS.TextureSharingShader;
interface
uses
System.Classes,
System.SysUtils,
VXS.XOpenGL,
VXS.Scene,
VXS.VectorGeometry,
VXS.Color,
VXS.Material,
VXS.Strings,
VXS.VectorFileObjects,
VXS.State,
VXS.PersistentClasses,
VXS.Coordinates,
VXS.RenderContextInfo;
type
TVXTextureSharingShader = class;
TVXTextureSharingShaderMaterial = class(TVXInterfacedCollectionItem, IVXMaterialLibrarySupported)
private
FTextureMatrix: TMatrix;
FNeedToUpdateTextureMatrix: Boolean;
FTextureMatrixIsUnitary: Boolean;
FLibMaterial: TVXLibMaterial;
FTexOffset: TVXCoordinates2;
FTexScale: TVXCoordinates2;
FBlendingMode: TBlendingMode;
FSpecular: TVXColor;
FAmbient: TVXColor;
FDiffuse: TVXColor;
FEmission: TVXColor;
FShininess: TShininess;
FMaterialLibrary: TVXMaterialLibrary;
FLibMaterialName: TVXLibMaterialName;
procedure SetAmbient(const Value: TVXColor);
procedure SetDiffuse(const Value: TVXColor);
procedure SetEmission(const Value: TVXColor);
procedure SetShininess(const Value: TShininess);
procedure SetSpecular(const Value: TVXColor);
procedure SetMaterialLibrary(const Value: TVXMaterialLibrary);
procedure SetLibMaterialName(const Value: TVXLibMaterialName);
procedure SetBlendingMode(const Value: TBlendingMode);
procedure SetLibMaterial(const Value: TVXLibMaterial);
procedure SetTexOffset(const Value: TVXCoordinates2);
procedure SetTexScale(const Value: TVXCoordinates2);
function GetTextureMatrix: TMatrix;
function GetTextureMatrixIsUnitary: Boolean;
protected
procedure coordNotifychange(Sender: TObject);
procedure OtherNotifychange(Sender: TObject);
function GetDisplayName: string; override;
function GetTextureSharingShader: TVXTextureSharingShader;
// Implementing IVKMaterialLibrarySupported.
function GetMaterialLibrary: TVXAbstractMaterialLibrary; virtual;
public
procedure Apply(var rci: TVXRenderContextInfo);
procedure UnApply(var rci: TVXRenderContextInfo);
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
property LibMaterial: TVXLibMaterial read FLibMaterial write SetLibMaterial;
property TextureMatrix: TMatrix read GetTextureMatrix;
property TextureMatrixIsUnitary: Boolean read GetTextureMatrixIsUnitary;
published
property TexOffset: TVXCoordinates2 read FTexOffset write SetTexOffset;
property TexScale: TVXCoordinates2 read FTexScale write SetTexScale;
property BlendingMode: TBlendingMode read FBlendingMode write SetBlendingMode;
property Emission: TVXColor read FEmission write SetEmission;
property Ambient: TVXColor read FAmbient write SetAmbient;
property Diffuse: TVXColor read FDiffuse write SetDiffuse;
property Specular: TVXColor read FSpecular write SetSpecular;
property Shininess: TShininess read FShininess write SetShininess;
property MaterialLibrary: TVXMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
property LibMaterialName: TVXLibMaterialName read FLibMaterialName write SetLibMaterialName;
end;
TVXTextureSharingShaderMaterials = class(TOwnedCollection)
protected
function GetItems(const AIndex: Integer): TVXTextureSharingShaderMaterial;
procedure SetItems(const AIndex: Integer; const Value: TVXTextureSharingShaderMaterial);
function GetParent: TVXTextureSharingShader;
public
function Add: TVXTextureSharingShaderMaterial;
constructor Create(AOwner: TVXTextureSharingShader);
property Items[const AIndex: Integer]: TVXTextureSharingShaderMaterial read GetItems write SetItems; default;
end;
TVXTextureSharingShader = class(TVXShader)
private
FMaterials: TVXTextureSharingShaderMaterials;
FCurrentPass: Integer;
procedure SetMaterials(const Value: TVXTextureSharingShaderMaterials);
protected
procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddLibMaterial(const ALibMaterial: TVXLibMaterial): TVXTextureSharingShaderMaterial;
function FindLibMaterial(const ALibMaterial: TVXLibMaterial): TVXTextureSharingShaderMaterial;
published
property Materials: TVXTextureSharingShaderMaterials read FMaterials write SetMaterials;
end;
//=======================================================================
implementation
//=======================================================================
//----------------------------------------------------------------------------
{ TVXTextureSharingShaderMaterial }
//----------------------------------------------------------------------------
procedure TVXTextureSharingShaderMaterial.Apply(var rci: TVXRenderContextInfo);
begin
if not Assigned(FLibMaterial) then
Exit;
xglBeginUpdate;
if Assigned(FLibMaterial.Shader) then
begin
case FLibMaterial.Shader.ShaderStyle of
ssHighLevel: FLibMaterial.Shader.Apply(rci, FLibMaterial);
ssReplace:
begin
FLibMaterial.Shader.Apply(rci, FLibMaterial);
Exit;
end;
end;
end;
if not FLibMaterial.Material.Texture.Disabled then
begin
if not (GetTextureMatrixIsUnitary) then
begin
rci.VXStates.SetTextureMatrix(TextureMatrix);
end;
end;
if moNoLighting in FLibMaterial.Material.MaterialOptions then
rci.VXStates.Disable(stLighting);
if stLighting in rci.VXStates.States then
begin
rci.VXStates.SetMaterialColors(cmFront,
Emission.Color, Ambient.Color, Diffuse.Color, Specular.Color, Shininess);
rci.VXStates.PolygonMode :=FLibMaterial.Material.PolygonMode;
end
else
FLibMaterial.Material.FrontProperties.ApplyNoLighting(rci, cmFront);
if (stCullFace in rci.VXStates.States) then
begin
case FLibMaterial.Material.FaceCulling of
fcBufferDefault: if not rci.bufferFaceCull then
begin
rci.VXStates.Disable(stCullFace);
FLibMaterial.Material.BackProperties.Apply(rci, cmBack);
end;
fcCull: ; // nothing to do
fcNoCull:
begin
rci.VXStates.Disable(stCullFace);
FLibMaterial.Material.BackProperties.Apply(rci, cmBack);
end;
else
Assert(False);
end;
end
else
begin
// currently NOT culling
case FLibMaterial.Material.FaceCulling of
fcBufferDefault:
begin
if rci.bufferFaceCull then
rci.VXStates.Enable(stCullFace)
else
FLibMaterial.Material.BackProperties.Apply(rci, cmBack);
end;
fcCull: rci.VXStates.Enable(stCullFace);
fcNoCull: FLibMaterial.Material.BackProperties.Apply(rci, cmBack);
else
Assert(False);
end;
end;
// Apply Blending mode
if not rci.ignoreBlendingRequests then
case BlendingMode of
bmOpaque:
begin
rci.VXStates.Disable(stBlend);
rci.VXStates.Disable(stAlphaTest);
end;
bmTransparency:
begin
rci.VXStates.Enable(stBlend);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
end;
bmAdditive:
begin
rci.VXStates.Enable(stBlend);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetBlendFunc(bfSrcAlpha, bfOne);
end;
bmAlphaTest50:
begin
rci.VXStates.Disable(stBlend);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetAlphaFunction(cfGEqual, 0.5);
end;
bmAlphaTest100:
begin
rci.VXStates.Disable(stBlend);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetAlphaFunction(cfGEqual, 1.0);
end;
bmModulate:
begin
rci.VXStates.Enable(stBlend);
rci.VXStates.Enable(stAlphaTest);
rci.VXStates.SetBlendFunc(bfDstColor, bfZero);
end;
else
Assert(False);
end;
// Fog switch
if moIgnoreFog in FLibMaterial.Material.MaterialOptions then
begin
if stFog in rci.VXStates.States then
begin
rci.VXStates.Disable(stFog);
Inc(rci.fogDisabledCounter);
end;
end;
if not Assigned(FLibMaterial.Material.TextureEx) then
begin
if Assigned(FLibMaterial.Material.Texture) then
FLibMaterial.Material.Texture.Apply(rci);
end
else
begin
if Assigned(FLibMaterial.Material.Texture) and not FLibMaterial.Material.TextureEx.IsTextureEnabled(0) then
FLibMaterial.Material.Texture.Apply(rci)
else
if FLibMaterial.Material.TextureEx.Count > 0 then
FLibMaterial.Material.TextureEx.Apply(rci);
end;
if Assigned(FLibMaterial.Shader) then
begin
case FLibMaterial.Shader.ShaderStyle of
ssLowLevel: FLibMaterial.Shader.Apply(rci, FLibMaterial);
end;
end;
xglEndUpdate;
end;
procedure TVXTextureSharingShaderMaterial.coordNotifychange(Sender: TObject);
begin
FNeedToUpdateTextureMatrix := True;
GetTextureSharingShader.NotifyChange(Self);
end;
constructor TVXTextureSharingShaderMaterial.Create(Collection: TCollection);
begin
inherited;
FSpecular := TVXColor.Create(Self);
FSpecular.OnNotifyChange := OtherNotifychange;
FAmbient := TVXColor.Create(Self);
FAmbient.OnNotifyChange := OtherNotifychange;
FDiffuse := TVXColor.Create(Self);
FDiffuse.OnNotifyChange := OtherNotifychange;
FEmission := TVXColor.Create(Self);
FEmission.OnNotifyChange := OtherNotifychange;
FTexOffset := TVXCoordinates2.CreateInitialized(Self, NullHmgVector, csPoint2d);
FTexOffset.OnNotifyChange := coordNotifychange;
FTexScale := TVXCoordinates2.CreateInitialized(Self, XYZHmgVector, csPoint2d);
FTexScale.OnNotifyChange := coordNotifychange;
FNeedToUpdateTextureMatrix := True;
end;
destructor TVXTextureSharingShaderMaterial.Destroy;
begin
FSpecular.Free;
FAmbient.Free;
FDiffuse.Free;
FEmission.Free;
FTexOffset.Free;
FTexScale.Free;
inherited;
end;
function TVXTextureSharingShaderMaterial.GetDisplayName: string;
var
st: string;
begin
if Assigned(MaterialLibrary) then
st := MaterialLibrary.Name
else
st := '';
Result := '[' + st + '.' + Self.LibMaterialName + ']';
end;
function TVXTextureSharingShaderMaterial.GetMaterialLibrary: TVXAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
function TVXTextureSharingShaderMaterial.GetTextureMatrix: TMatrix;
begin
if FNeedToUpdateTextureMatrix then
begin
if not (TexOffset.Equals(NullHmgVector) and TexScale.Equals(XYZHmgVector)) then
begin
FTextureMatrixIsUnitary := False;
FTextureMatrix := CreateScaleAndTranslationMatrix(TexScale.AsVector, TexOffset.AsVector)
end
else
FTextureMatrixIsUnitary := True;
FNeedToUpdateTextureMatrix := False;
end;
Result := FTextureMatrix;
end;
function TVXTextureSharingShaderMaterial.GetTextureMatrixIsUnitary: Boolean;
begin
if FNeedToUpdateTextureMatrix then
GetTextureMatrix;
Result := FTextureMatrixIsUnitary;
end;
function TVXTextureSharingShaderMaterial.GetTextureSharingShader: TVXTextureSharingShader;
begin
if Collection is TVXTextureSharingShaderMaterials then
Result := TVXTextureSharingShaderMaterials(Collection).GetParent
else
Result := nil;
end;
procedure TVXTextureSharingShaderMaterial.OtherNotifychange(Sender: TObject);
begin
GetTextureSharingShader.NotifyChange(Self);
end;
procedure TVXTextureSharingShaderMaterial.SetAmbient(const Value: TVXColor);
begin
FAmbient.Assign(Value);
end;
procedure TVXTextureSharingShaderMaterial.SetBlendingMode(const Value: TBlendingMode);
begin
FBlendingMode := Value;
end;
procedure TVXTextureSharingShaderMaterial.SetDiffuse(const Value: TVXColor);
begin
FDiffuse.Assign(Value);
end;
procedure TVXTextureSharingShaderMaterial.SetEmission(const Value: TVXColor);
begin
FEmission.Assign(Value);
end;
procedure TVXTextureSharingShaderMaterial.SetLibMaterialName(const Value: TVXLibMaterialName);
begin
FLibMaterialName := Value;
if (FLibMaterialName = '') or (FMaterialLibrary = nil) then
FLibMaterial := nil
else
SetLibMaterial(FMaterialLibrary.LibMaterialByName(FLibMaterialName));
end;
procedure TVXTextureSharingShaderMaterial.SetLibMaterial(const Value: TVXLibMaterial);
begin
FLibMaterial := Value;
if FLibMaterial <> nil then
begin
FLibMaterialName := FLibMaterial.DisplayName;
FMaterialLibrary := TVXMaterialLibrary(TVXLibMaterials(Value.Collection).Owner);
if not (csloading in GetTextureSharingShader.ComponentState) then
begin
FTexOffset.Assign(FLibMaterial.TextureOffset);
FTexScale.Assign(FLibMaterial.TextureScale);
FBlendingMode := FLibMaterial.Material.BlendingMode;
fEmission.Assign(FLibMaterial.Material.FrontProperties.Emission);
fAmbient.Assign(FLibMaterial.Material.FrontProperties.Ambient);
fDiffuse.Assign(FLibMaterial.Material.FrontProperties.Diffuse);
fSpecular.Assign(FLibMaterial.Material.FrontProperties.Specular);
fShininess := FLibMaterial.Material.FrontProperties.Shininess;
end;
end;
end;
procedure TVXTextureSharingShaderMaterial.SetMaterialLibrary(const Value: TVXMaterialLibrary);
begin
FMaterialLibrary := Value;
if (FLibMaterialName = '') or (FMaterialLibrary = nil) then
FLibMaterial := nil
else
SetLibMaterial(FMaterialLibrary.LibMaterialByName(FLibMaterialName));
end;
procedure TVXTextureSharingShaderMaterial.SetShininess(const Value: TShininess);
begin
FShininess := Value;
end;
procedure TVXTextureSharingShaderMaterial.SetSpecular(const Value: TVXColor);
begin
FSpecular.Assign(Value);
end;
procedure TVXTextureSharingShaderMaterial.SetTexOffset(const Value: TVXCoordinates2);
begin
FTexOffset.Assign(Value);
FNeedToUpdateTextureMatrix := True;
end;
procedure TVXTextureSharingShaderMaterial.SetTexScale(const Value: TVXCoordinates2);
begin
FTexScale.Assign(Value);
FNeedToUpdateTextureMatrix := True;
end;
procedure TVXTextureSharingShaderMaterial.UnApply(var rci: TVXRenderContextInfo);
begin
if not Assigned(FLibMaterial) then
Exit;
if Assigned(FLibMaterial.Shader) then
begin
case FLibMaterial.Shader.ShaderStyle of
ssLowLevel: FLibMaterial.Shader.UnApply(rci);
ssReplace:
begin
FLibMaterial.Shader.UnApply(rci);
Exit;
end;
end;
end;
FLibMaterial.Material.UnApply(rci);
if not FLibMaterial.Material.Texture.Disabled then
if not (GetTextureMatrixIsUnitary) then
begin
rci.VXStates.ResetTextureMatrix;
end;
if Assigned(FLibMaterial.Shader) then
begin
case FLibMaterial.Shader.ShaderStyle of
ssHighLevel: FLibMaterial.Shader.UnApply(rci);
end;
end;
end;
{ TVXTextureSharingShader }
function TVXTextureSharingShader.AddLibMaterial(const ALibMaterial: TVXLibMaterial): TVXTextureSharingShaderMaterial;
begin
Result := FMaterials.Add;
Result.SetLibMaterial(ALibMaterial);
end;
constructor TVXTextureSharingShader.Create(AOwner: TComponent);
begin
inherited;
FMaterials := TVXTextureSharingShaderMaterials.Create(Self);
ShaderStyle := ssReplace;
end;
destructor TVXTextureSharingShader.Destroy;
begin
FMaterials.Free;
inherited;
end;
procedure TVXTextureSharingShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject);
begin
if Materials.Count > 0 then
begin
rci.VXStates.Enable(stDepthTest);
rci.VXStates.DepthFunc := cfLEqual;
Materials[0].Apply(rci);
FCurrentPass := 1;
end;
end;
function TVXTextureSharingShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean;
begin
Result := False;
if Materials.Count > 0 then
begin
Materials[FCurrentPass - 1].UnApply(rci);
if FCurrentPass < Materials.Count then
begin
Materials[FCurrentPass].Apply(rci);
Inc(FCurrentPass);
Result := True;
end
else
begin
rci.VXStates.DepthFunc := cfLess;
rci.VXStates.Disable(stBlend);
rci.VXStates.Disable(stAlphaTest);
FCurrentPass := 0;
end;
end;
end;
function TVXTextureSharingShader.FindLibMaterial(const ALibMaterial: TVXLibMaterial): TVXTextureSharingShaderMaterial;
var
I: Integer;
begin
Result := nil;
for I := 0 to FMaterials.Count - 1 do
if FMaterials[I].FLibMaterial = ALibMaterial then
begin
Result := FMaterials[I];
Break;
end;
end;
procedure TVXTextureSharingShader.Notification(AComponent: TComponent; Operation: TOperation);
var
I: Integer;
begin
inherited;
if Operation = opRemove then
begin
if AComponent is TVXMaterialLibrary then
begin
for I := 0 to Materials.Count - 1 do
begin
if Materials.Items[I].MaterialLibrary = AComponent then
Materials.Items[I].MaterialLibrary := nil;
end;
end;
end;
end;
procedure TVXTextureSharingShader.SetMaterials(const Value: TVXTextureSharingShaderMaterials);
begin
FMaterials.Assign(Value);
end;
{ TVXTextureSharingShaderMaterials }
function TVXTextureSharingShaderMaterials.Add: TVXTextureSharingShaderMaterial;
begin
Result := (inherited Add) as TVXTextureSharingShaderMaterial;
end;
constructor TVXTextureSharingShaderMaterials.Create(AOwner: TVXTextureSharingShader);
begin
inherited Create(AOwner, TVXTextureSharingShaderMaterial);
end;
function TVXTextureSharingShaderMaterials.GetItems(const AIndex: Integer): TVXTextureSharingShaderMaterial;
begin
Result := (inherited Items[AIndex]) as TVXTextureSharingShaderMaterial;
end;
function TVXTextureSharingShaderMaterials.GetParent: TVXTextureSharingShader;
begin
Result := TVXTextureSharingShader(GetOwner);
end;
procedure TVXTextureSharingShaderMaterials.SetItems(const AIndex: Integer; const Value: TVXTextureSharingShaderMaterial);
begin
inherited Items[AIndex] := Value;
end;
//----------------------------------------------------------------------------
initialization
//----------------------------------------------------------------------------
RegisterClasses([TVXTextureSharingShader, TVXTextureSharingShaderMaterials,
TVXTextureSharingShaderMaterial]);
end.
|
unit fGridOptions;
interface
uses
Windows, Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.Math,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Buttons,
OpenGLTokens,
GLVectorTypes,
GLCoordinates,
GLVectorGeometry,
uGlobal,
uParser,
fGridColors;
type
TGridOptionsForm = class(TForm)
GroupBoxXY: TGroupBox;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label11: TLabel;
Label12: TLabel;
Label10: TLabel;
EditxyGridMinx: TEdit;
EditxyGridMaxx: TEdit;
EditxyGridStpx: TEdit;
EditxyGridMiny: TEdit;
EditxyGridMaxy: TEdit;
EditxyGridStpy: TEdit;
EditxyGridPosz: TEdit;
xyLock: TCheckBox;
GroupBoxXZ: TGroupBox;
Label13: TLabel;
Label18: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
EditxzGridMinx: TEdit;
EditxzGridMaxx: TEdit;
EditxzGridStpx: TEdit;
EditxzGridMinz: TEdit;
EditxzGridMaxz: TEdit;
EditxzGridStpz: TEdit;
EditxzGridPosy: TEdit;
zLock: TCheckBox;
GroupBoxYZ: TGroupBox;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
Label29: TLabel;
EdityzGridMiny: TEdit;
EdityzGridMaxy: TEdit;
EdityzGridStpy: TEdit;
EdityzGridMinz: TEdit;
EdityzGridMaxz: TEdit;
EdityzGridStpz: TEdit;
EdityzGridPosx: TEdit;
GroupBoxOp: TGroupBox;
Label14: TLabel;
Label19: TLabel;
Colors: TSpeedButton;
xyGridCB: TCheckBox;
xzGridCB: TCheckBox;
yzGridCB: TCheckBox;
EditViewDepth: TEdit;
MinLock: TCheckBox;
Label1: TLabel;
EditzScale: TEdit;
Centre: TSpeedButton;
BoxOutlineCB: TCheckBox;
Label4: TLabel;
EditBoxLnWidth: TEdit;
BitBtn1: TBitBtn;
PlotValues: TSpeedButton;
procedure ColorsClick(Sender: TObject);
procedure FloatKeyPress(Sender: TObject; var Key: Char);
procedure PositiveKeyPress(Sender: TObject; var Key: Char);
procedure EditxyGridMinxChange(Sender: TObject);
procedure EditxyGridMaxxChange(Sender: TObject);
procedure EditxyGridStpxChange(Sender: TObject);
procedure EditxyGridPoszChange(Sender: TObject);
procedure EditxyGridMinyChange(Sender: TObject);
procedure EditxyGridMaxyChange(Sender: TObject);
procedure EditxyGridStpyChange(Sender: TObject);
procedure EditxzGridMinxChange(Sender: TObject);
procedure EditxzGridMaxxChange(Sender: TObject);
procedure EditxzGridStpxChange(Sender: TObject);
procedure EditxzGridPosyChange(Sender: TObject);
procedure EditxzGridMinzChange(Sender: TObject);
procedure EditxzGridMaxzChange(Sender: TObject);
procedure EditxzGridStpzChange(Sender: TObject);
procedure EdityzGridMinyChange(Sender: TObject);
procedure EdityzGridMaxyChange(Sender: TObject);
procedure EdityzGridStpyChange(Sender: TObject);
procedure EdityzGridPosxChange(Sender: TObject);
procedure EdityzGridMinzChange(Sender: TObject);
procedure EdityzGridMaxzChange(Sender: TObject);
procedure EdityzGridStpzChange(Sender: TObject);
procedure xyGridCBClick(Sender: TObject);
procedure xzGridCBClick(Sender: TObject);
procedure yzGridCBClick(Sender: TObject);
procedure xyLockClick(Sender: TObject);
procedure zLockClick(Sender: TObject);
procedure MinLockClick(Sender: TObject);
procedure ComboBoxMouseEnter(Sender: TObject);
procedure EditViewDepthChange(Sender: TObject);
procedure CentreClick(Sender: TObject);
procedure EditzScaleKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BoxOutlineCBClick(Sender: TObject);
procedure IntKeyPress(Sender: TObject; var Key: Char);
procedure EditBoxLnWidthKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BitBtn1Click(Sender: TObject);
procedure EditxzGridStpxExit(Sender: TObject);
procedure EdityzGridStpyExit(Sender: TObject);
procedure EdityzGridStpzExit(Sender: TObject);
procedure PlotValuesClick(Sender: TObject);
private
{ Private declarations }
public
procedure DrawOutline(const Show: Boolean);
end;
var
GridOptionsForm: TGridOptionsForm;
//=====================================================================
implementation
//=====================================================================
uses
fMain,
fEvaluate,
fCoordOptions,
fFunctions;
{$R *.dfm}
procedure TGridOptionsForm.CentreClick(Sender: TObject);
var
x, y, z: TGLFloat;
begin
with ViewForm do
begin
MousePoint.X := Maxint;
if GLxyGrid.XSamplingScale.Max - GLxyGrid.XSamplingScale.Min >
GLxzGrid.XSamplingScale.Max - GLxzGrid.XSamplingScale.Min
then x := GLxyGrid.XSamplingScale.Max + GLxyGrid.XSamplingScale.Min
else x := GLxzGrid.XSamplingScale.Max + GLxzGrid.XSamplingScale.Min;
if GLxyGrid.YSamplingScale.Max - GLxyGrid.YSamplingScale.Min >
GLyzGrid.YSamplingScale.Max - GLxzGrid.YSamplingScale.Min
then y := GLxyGrid.YSamplingScale.Max + GLxyGrid.YSamplingScale.Min
else y := GLyzGrid.YSamplingScale.Max + GLyzGrid.YSamplingScale.Min;
if GLxzGrid.ZSamplingScale.Max - GLxzGrid.ZSamplingScale.Min >
GLyzGrid.ZSamplingScale.Max - GLyzGrid.ZSamplingScale.Min
then z := GLxzGrid.ZSamplingScale.Max + GLxzGrid.ZSamplingScale.Min
else z := GLyzGrid.ZSamplingScale.Max + GLyzGrid.ZSamplingScale.Min;
TargetCube.Position.SetPoint(x/2, y/2, (ViewData.xyGrid.zScale*z)/2);
end;
Altered := True;
ViewForm.ShowDisplacement;
end;
procedure TGridOptionsForm.BitBtn1Click(Sender: TObject);
begin
Close;
end;
procedure TGridOptionsForm.BoxOutlineCBClick(Sender: TObject);
begin
ViewData.BoxChecked := BoxOutlineCB.Checked;
DrawOutline(ViewData.BoxChecked);
Altered := True;
end;
procedure TGridOptionsForm.ColorsClick(Sender: TObject);
begin
GridColorsForm.Show;
end;
procedure TGridOptionsForm.IntKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['0'..'9', #8]) then Key := #0
end;
procedure TGridOptionsForm.EditBoxLnWidthKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
w: integer;
begin
try
w := StrToInt(EditBoxLnWidth.Text);
except
w := 3;
end;
ViewData.BoxLnWidth := w;
ViewForm.BoxLine1.LineWidth := w;
ViewForm.BoxLine2.LineWidth := w;
ViewForm.BoxLine3.LineWidth := w;
ViewForm.BoxLine4.LineWidth := w;
Altered := True;
end;
procedure TGridOptionsForm.EditViewDepthChange(Sender: TObject);
var
v: TGLFloat;
begin
if Active then
begin
try
v := StrToFloat(EditViewDepth.Text);
except
v := 1000;
end;
if v = 0 then Exit;
ViewData.ViewDepth := v;
ViewForm.GLSViewer.Camera.DepthOfView := v;
end;
end;
procedure TGridOptionsForm.PlotValuesClick(Sender: TObject);
begin
if xyLock.Checked and zLock.Checked and MinLock.Checked then
begin
EditxyGridMinx.Text := FloatToStrF(PlotData.xMin, ffGeneral, 7, 4);
EditxyGridMaxx.Text := FloatToStrF(PlotData.xMax, ffGeneral, 7, 4);
EditxyGridMiny.Text := FloatToStrF(PlotData.yMin, ffGeneral, 7, 4);
EditxyGridMaxy.Text := FloatToStrF(PlotData.yMax, ffGeneral, 7, 4);
EditxzGridMinz.Text := FloatToStrF(PlotData.zMin, ffGeneral, 7, 4);
EditxzGridMaxz.Text := FloatToStrF(PlotData.zMax, ffGeneral, 7, 4);
end;
end;
procedure TGridOptionsForm.PositiveKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, ['+', '0'..'9', '.', #8]) then Key := #0;
end;
procedure TGridOptionsForm.EditxyGridMaxxChange(Sender: TObject);
var
x: TGLFloat;
begin {2}
if Active then
begin
try
x := StrToFloat(EditxyGridMaxx.Text);
except
x := 1.0;
end;
ViewData.xyGrid.xRange.Maximum := x;
ViewForm.GLxyGrid.XSamplingScale.Max := x;
if xyLock.Checked then
begin
ViewData.xzGrid.xRange.Maximum := x;
ViewForm.GLxzGrid.XSamplingScale.Max := x;
EditxzGridMaxx.Text := EditxyGridMaxx.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxyGridMaxyChange(Sender: TObject);
var
y: TGLFloat;
begin {5}
if Active then
begin
try
y := StrToFloat(EditxyGridMaxy.Text);
except
y := 1.0;
end;
ViewData.xyGrid.yRange.Maximum := y;
ViewForm.GLxyGrid.YSamplingScale.Max := y;
if xyLock.Checked then
begin
ViewData.yzGrid.yRange.Maximum := y;
ViewForm.GLyzGrid.YSamplingScale.Max := y;
EdityzGridMaxy.Text := EditxyGridMaxy.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxyGridMinxChange(Sender: TObject);
var
x: TGLFloat;
begin {1}
if Active then
begin
try
x := StrToFloat(EditxyGridMinx.Text);
except
x := -1.0;
end;
ViewData.xyGrid.xRange.Minimum := x;
ViewForm.GLxyGrid.XSamplingScale.Min := x;
if xyLock.Checked then
begin
ViewData.xzGrid.xRange.Minimum := x;
ViewForm.GLxzGrid.XSamplingScale.Min := x;
EditxzGridMinx.Text := EditxyGridMinx.Text;
end;
if MinLock.Checked then
begin
ViewData.yzGrid.xPosition := x;
ViewForm.GLyzGrid.Position.X := x;
EdityzGridPosx.Text := EditxyGridMinx.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxyGridMinyChange(Sender: TObject);
var
y: TGLFloat;
begin {4}
if Active then
begin {1}
try
y := StrToFloat(EditxyGridMiny.Text);
except
y := -1.0;
end;
if xyLock.Checked then
ViewData.xyGrid.yRange.Minimum := y;
ViewForm.GLxyGrid.YSamplingScale.Min := y;
if xyLock.Checked then
begin
ViewData.yzGrid.yRange.Minimum := y;
ViewForm.GLyzGrid.YSamplingScale.Min := y;
EdityzGridMiny.Text := EditxyGridMiny.Text;
end;
if MinLock.Checked then
begin
ViewData.xzGrid.yPosition := y;
ViewForm.GLxzGrid.Position.Y := y;
EditxzGridPosy.Text := EditxyGridMiny.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxyGridPoszChange(Sender: TObject);
var
z: TGLFloat;
begin {-}
if Active then
begin
try
z := StrToFloat(EditxyGridPosz.Text);
except
z := 0.0;
end;
ViewData.xyGrid.zPosition := z;
ViewForm.GLxyGrid.Position.Z := z*ViewData.xyGrid.zScale;
EvaluateForm.UpdateEvaluate;
DrawOutline(ViewData.BoxChecked);
end;
end;
procedure TGridOptionsForm.EditxyGridStpxChange(Sender: TObject);
var
x: TGLFloat;
begin {3}
if Active then
begin
try
x := StrToFloat(EditxyGridStpx.Text);
except
x := 1.0;
end;
if x = 0 then x := 1;
ViewData.xyGrid.xRange.Step := x;
ViewForm.GLxyGrid.XSamplingScale.Step := x;
if xyLock.Checked then
begin
ViewData.xzGrid.xRange.Step := x;
ViewForm.GLxzGrid.XSamplingScale.Step := x;
EditxzGridStpx.Text := EditxyGridStpx.Text;
end;
CoordsForm.UpdateCoordText;
EvaluateForm.DoEvaluate;
end;
end;
procedure TGridOptionsForm.EditxyGridStpyChange(Sender: TObject);
var
y: TGLFloat;
begin {6}
if Active then
begin
try
y := StrToFloat(EditxyGridStpy.Text);
except
y := 1.0;
end;
if y = 0 then y := 1;
ViewData.xyGrid.yRange.Step := y;
ViewForm.GLxyGrid.YSamplingScale.Step := y;
if xyLock.Checked then
begin
ViewData.yzGrid.yRange.Step := y;
ViewForm.GLyzGrid.YSamplingScale.Step := y;
EdityzGridStpy.Text := EditxyGridStpy.Text;
end;
CoordsForm.UpdateCoordText;
EvaluateForm.DoEvaluate;
end;
end;
procedure TGridOptionsForm.EditxzGridMaxxChange(Sender: TObject);
var
x: TGLFloat;
begin {2}
if Active then
begin
try
x := StrToFloat(EditxzGridMaxx.Text);
except
x := 1.0;
end;
ViewData.xzGrid.xRange.Maximum := x;
ViewForm.GLxzGrid.XSamplingScale.Max := x;
if xyLock.Checked then
begin
ViewData.xyGrid.xRange.Maximum := x;
ViewForm.GLxyGrid.XSamplingScale.Max := x;
EditxyGridMaxx.Text := EditxzGridMaxx.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxzGridMaxzChange(Sender: TObject);
var
z: TGLFloat;
begin {8}
if Active then
begin
try
z := StrToFloat(EditxzGridMaxz.Text);
except
z:= 1.0;
end;
ViewData.xzGrid.zRange.Maximum := z;
ViewForm.GLxzGrid.ZSamplingScale.Max := z;
if zLock.Checked then
begin
ViewData.yzGrid.zRange.Maximum := z;
ViewForm.GLyzGrid.ZSamplingScale.Max := z;
EdityzGridMaxz.Text := EditxzGridMaxz.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxzGridMinxChange(Sender: TObject);
var
x: TGLFloat;
begin {1}
if Active then
begin
try
x := StrToFloat(EditxzGridMinx.Text);
except
x := -1.0;
end;
ViewData.xzGrid.xRange.Minimum := x;
ViewForm.GLxzGrid.XSamplingScale.Min := x;
if xyLock.Checked then
begin
ViewData.xyGrid.xRange.Minimum := x;
ViewForm.GLxyGrid.XSamplingScale.Min := x;
EditxyGridMinx.Text := EditxzGridMinx.Text;
end;
if MinLock.Checked then
begin
ViewData.yzGrid.xPosition := x;
ViewForm.GLyzGrid.Position.X := x;
EdityzGridPosx.Text := EditxzGridMinx.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxzGridMinzChange(Sender: TObject);
var
z: TGLFloat;
begin {7}
if Active then
begin
try
z := StrToFloat(EditxzGridMinz.Text);
except
z := -1.0;
end;
ViewData.xzGrid.zRange.Minimum := z;
ViewForm.GLxzGrid.ZSamplingScale.Min := z;
if zLock.Checked then
begin
ViewData.yzGrid.zRange.Minimum := z;
ViewForm.GLyzGrid.ZSamplingScale.Min := z;
EdityzGridMinz.Text := EditxzGridMinz.Text;
end;
if MinLock.Checked then
begin
ViewData.xyGrid.zPosition := z;
ViewForm.GLxyGrid.Position.Z := z*ViewData.xyGrid.zScale;
EditxyGridPosz.Text := EditxzGridMinz.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxzGridPosyChange(Sender: TObject);
var
y: TGLFloat;
begin {-}
if Active then
begin
try
y := StrToFloat(EditxzGridPosy.Text);
except
y := 1.0;
end;
ViewData.xzGrid.yPosition := y;
ViewForm.GLxzGrid.Position.Y := y;
EvaluateForm.UpdateEvaluate;
DrawOutline(ViewData.BoxChecked);
end;
end;
procedure TGridOptionsForm.EditxzGridStpxChange(Sender: TObject);
var
x: TGLFloat;
begin {3}
if Active then
begin
try
x := StrToFloat(EditxzGridStpx.Text);
except
x := 1.0;
end;
if x = 0 then x := 1;
ViewData.xzGrid.xRange.Step := x;
ViewForm.GLxzGrid.XSamplingScale.Step := x;
if xyLock.Checked then
begin
ViewData.xyGrid.xRange.Step := x;
ViewForm.GLxyGrid.XSamplingScale.Step := x;
end;
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EditxzGridStpxExit(Sender: TObject);
begin
if xyLock.Checked then EditxyGridStpx.Text := EditxzGridStpx.Text;
end;
procedure TGridOptionsForm.EditxzGridStpzChange(Sender: TObject);
var
z: TGLFloat;
begin {9}
if Active then
begin
try
z := StrToFloat(EditxzGridStpz.Text);
except
z := 1.0;
end;
if z = 0 then z := 1;
ViewData.xzGrid.zRange.Step := z;
ViewForm.GLxzGrid.ZSamplingScale.Step := z;
if zLock.Checked then
begin
ViewData.yzGrid.zRange.Step := z;
ViewForm.GLyzGrid.ZSamplingScale.Step := z;
EdityzGridStpz.Text := EditxzGridStpz.Text;
end;
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridMaxyChange(Sender: TObject);
var
y: TGLFloat;
begin {5}
if Active then
begin
try
y := StrToFloat(EdityzGridMaxy.Text);
except
y:= 1.0;
end;
ViewData.yzGrid.yRange.Maximum := y;
ViewForm.GLyzGrid.YSamplingScale.Max := y;
if xyLock.Checked then
begin
ViewData.xyGrid.yRange.Maximum := y;
ViewForm.GLxyGrid.YSamplingScale.Max := y;
EditxyGridMaxy.Text := EdityzGridMaxy.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridMaxzChange(Sender: TObject);
var
z: TGLFloat;
begin {8}
if Active then
begin
try
z := StrToFloat(EdityzGridMaxz.Text);
except
z := 1.0;
end;
ViewData.yzGrid.zRange.Maximum := z;
ViewForm.GLyzGrid.ZSamplingScale.Max := z;
if zLock.Checked then
begin
ViewData.xzGrid.zRange.Maximum := z;
ViewForm.GLxzGrid.ZSamplingScale.Max := z;
EditxzGridMaxz.Text := EdityzGridMaxz.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridMinyChange(Sender: TObject);
var
y: TGLFloat;
begin {4}
if Active then
begin
try
y := StrToFloat(EdityzGridMiny.Text);
except
y := -1.0;
end;
ViewData.yzGrid.yRange.Minimum := y;
ViewForm.GLyzGrid.YSamplingScale.Min := y;
if xyLock.Checked then
begin
ViewData.xyGrid.yRange.Minimum := y;
ViewForm.GLxyGrid.YSamplingScale.Min := y;
EditxyGridMiny.Text := EdityzGridMiny.Text;
end;
if MinLock.Checked then
begin
ViewData.xzGrid.yPosition := y;
ViewForm.GLxzGrid.Position.Y := y;
EditxzGridPosy.Text := EdityzGridMiny.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridMinzChange(Sender: TObject);
var
z: TGLFloat;
begin {7}
if Active then
begin
try
z := StrToFloat(EdityzGridMinz.Text);
except
z := -1.0;
end;
ViewData.yzGrid.zRange.Minimum := z;
ViewForm.GLyzGrid.ZSamplingScale.Min := z;
if zLock.Checked then
begin
ViewData.xyGrid.zPosition := z;
ViewForm.GLxzGrid.ZSamplingScale.Min := z;
EditxzGridMinz.Text := EdityzGridMinz.Text;
end;
if MinLock.Checked then
begin
ViewData.xyGrid.zPosition := z;
ViewForm.GLxyGrid.Position.Z := z*ViewData.xyGrid.zScale;
EditxyGridPosz.Text := EdityzGridMinz.Text;
end;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridPosxChange(Sender: TObject);
var
x: TGLFloat;
begin {-}
if Active then
begin
try
x := StrToFloat(EdityzGridPosx.Text);
except
x := 1.0;
end;
ViewData.yzGrid.xPosition := x;
ViewForm.GLyzGrid.Position.X := x;
EvaluateForm.UpdateEvaluate;
DrawOutline(ViewData.BoxChecked);
end;
end;
procedure TGridOptionsForm.EdityzGridStpyChange(Sender: TObject);
var
y: TGLFloat;
begin {6}
if Active then
begin
try
y := StrToFloat(EdityzGridStpy.Text);
except
y := 1.0;
end;
if y = 0 then y := 1;
ViewData.yzGrid.yRange.Step := y;
ViewForm.GLyzGrid.YSamplingScale.Step := y;
if xyLock.Checked then
begin
ViewData.xyGrid.yRange.Step := y;
ViewForm.GLxyGrid.YSamplingScale.Step := y;
end;
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridStpyExit(Sender: TObject);
begin
if xyLock.Checked then EditxyGridStpy.Text := EdityzGridStpy.Text;
end;
procedure TGridOptionsForm.EdityzGridStpzChange(Sender: TObject);
var
z: TGLFloat;
begin {9}
if Active then
begin
try
z := StrToFloat(EdityzGridStpz.Text);
except
z := 1.0;
end;
if z = 0 then z := 1;
ViewData.yzGrid.zRange.Step := z;
ViewForm.GLyzGrid.ZSamplingScale.Step := z;
if zLock.Checked then
begin
ViewData.xzGrid.zRange.Step := z;
ViewForm.GLxzGrid.ZSamplingScale.Step := z;
end;
CoordsForm.UpdateCoordText;
end;
end;
procedure TGridOptionsForm.EdityzGridStpzExit(Sender: TObject);
begin
if zLock.Checked then EditxzGridStpz.Text := EdityzGridStpz.Text;
end;
procedure TGridOptionsForm.EditzScaleKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
z: TGLFloat;
begin
if Key <> 9 then
begin
try
z := StrToFloat(EditzScale.Text);
except
z := 1.0;
end;
if z = 0 then Exit;
ViewData.xyGrid.zScale := z;
ViewForm.GLxzGrid.Scale.Z := z;
ViewForm.GLyzGrid.Scale.Z := z;
ViewForm.GLxyGrid.Position.Z := ViewData.xyGrid.zPosition*ViewData.xyGrid.zScale;
DrawOutline(ViewData.BoxChecked);
CoordsForm.UpdateCoordText;
EvaluateForm.UpdateEvaluate;
FunctionsForm.ApplyBtnClick(Sender);
end;
end;
procedure TGridOptionsForm.FloatKeyPress(Sender: TObject; var Key: Char);
begin
with Sender as TEdit do
if not CharInSet(Key, AnyFloat) then Key := #0;
end;
procedure TGridOptionsForm.MinLockClick(Sender: TObject);
var
x, y, z: TGLFloat;
begin
if MinLock.Checked then
begin
if ViewData.xyGrid.xRange.Minimum < ViewData.xzGrid.xRange.Minimum
then x := ViewData.xyGrid.xRange.Minimum
else x := ViewData.xzGrid.xRange.Minimum;
ViewForm.GLyzGrid.Position.X := x;
EdityzGridPosx.Text := FloatToStrF(x, ffGeneral, 7, 4);
if ViewData.xyGrid.yRange.Minimum < ViewData.yzGrid.yRange.Minimum
then y := ViewData.xyGrid.yRange.Minimum
else y := ViewData.yzGrid.yRange.Minimum;
ViewForm.GLxzGrid.Position.Y := y;
EditxzGridPosy.Text := FloatToStrF(y, ffGeneral, 7, 4);
if ViewData.xzGrid.zRange.Minimum < ViewData.yzGrid.zRange.Minimum
then z := ViewData.xzGrid.zRange.Minimum
else z := ViewData.yzGrid.zRange.Minimum;
ViewForm.GLxyGrid.Position.Z := z*ViewData.xyGrid.zScale;
EditxyGridPosz.Text := FloatToStrF(z, ffGeneral, 7, 4);
end;
ViewData.yzGrid.IsChecked := MinLock.Checked;
Altered := True;
end;
procedure TGridOptionsForm.ComboBoxMouseEnter(Sender: TObject);
begin
ViewForm.MousePoint.X := Maxint;
end;
procedure TGridOptionsForm.xyGridCBClick(Sender: TObject);
begin
ViewForm.GLxyGrid.Visible := xyGridCB.Checked;
ViewData.xyGrid.IsVisible := xyGridCB.Checked;
Altered := True;
end;
procedure TGridOptionsForm.xyLockClick(Sender: TObject);
begin
if xyLock.Checked then
begin
if ViewData.xyGrid.xRange.Minimum < ViewData.xzGrid.xRange.Minimum
then EditxzGridMinx.Text := FloatToStrF(ViewData.xyGrid.xRange.Minimum, ffGeneral, 7, 4)
else EditxyGridMinx.Text := FloatToStrF(ViewData.xzGrid.xRange.Minimum, ffGeneral, 7, 4);
if ViewData.xyGrid.yRange.Minimum < ViewData.yzGrid.yRange.Minimum
then EdityzGridMiny.Text := FloatToStrF(ViewData.xyGrid.yRange.Minimum, ffGeneral, 7, 4)
else EditxyGridMiny.Text := FloatToStrF(ViewData.yzGrid.yRange.Minimum, ffGeneral, 7, 4);
end;
ViewData.xyGrid.IsChecked := xyLock.Checked;
Altered := True;
end;
procedure TGridOptionsForm.xzGridCBClick(Sender: TObject);
begin
ViewForm.GLxzGrid.Visible := xzGridCB.Checked;
ViewData.xzGrid.IsVisible := xzGridCB.Checked;
Altered := True;
end;
procedure TGridOptionsForm.yzGridCBClick(Sender: TObject);
begin
ViewForm.GLyzGrid.Visible := yzGridCB.Checked;
ViewData.yzGrid.IsVisible := yzGridCB.Checked;
Altered := True;
end;
procedure TGridOptionsForm.zLockClick(Sender: TObject);
begin
if zLock.Checked then
begin
if ViewData.xzGrid.zRange.Minimum < ViewData.yzGrid.zRange.Minimum
then EdityzGridMinz.Text := FloatToStrF(ViewData.xzGrid.zRange.Minimum, ffGeneral, 7, 4)
else EditxzGridMinz.Text := FloatToStrF(ViewData.yzGrid.zRange.Minimum, ffGeneral, 7, 4);
end;
ViewData.xzGrid.IsChecked := zLock.Checked;
Altered := True;
end;
procedure TGridOptionsForm.DrawOutline(const Show: Boolean);
var
Vectors: array[0..7] of TVector;
begin
ViewForm.BoxLine1.Visible := Show;
ViewForm.BoxLine1.LineWidth := ViewData.BoxLnWidth;
ViewForm.BoxLine2.Visible := Show;
ViewForm.BoxLine2.LineWidth := ViewData.BoxLnWidth;
ViewForm.BoxLine3.Visible := Show;
ViewForm.BoxLine3.LineWidth := ViewData.BoxLnWidth;
ViewForm.BoxLine4.Visible := Show;
ViewForm.BoxLine4.LineWidth := ViewData.BoxLnWidth;
if Show then
begin
if ViewData.xyGrid.xRange.Minimum < ViewData.xzGrid.xRange.Minimum
then Vectors[0].X := ViewData.xyGrid.xRange.Minimum
else Vectors[0].X := ViewData.xzGrid.xRange.Minimum;
if ViewData.xyGrid.xRange.Maximum > ViewData.xzGrid.xRange.Maximum
then Vectors[1].X := ViewData.xyGrid.xRange.Maximum
else Vectors[1].X := ViewData.xzGrid.xRange.Maximum;
if ViewData.xyGrid.yRange.Minimum < ViewData.yzGrid.yRange.Minimum
then Vectors[0].Y := ViewData.xyGrid.yRange.Minimum
else Vectors[0].Y := ViewData.yzGrid.yRange.Minimum;
if ViewData.xyGrid.yRange.Maximum > ViewData.yzGrid.yRange.Maximum
then Vectors[2].Y := ViewData.xyGrid.yRange.Maximum
else Vectors[2].Y := ViewData.yzGrid.yRange.Maximum;
if ViewData.xzGrid.zRange.Minimum < ViewData.yzGrid.zRange.Minimum
then Vectors[0].Z := ViewData.xzGrid.zRange.Minimum*ViewData.xyGrid.zScale
else Vectors[0].Z := ViewData.yzGrid.zRange.Minimum*ViewData.xyGrid.zScale;
if ViewData.xzGrid.zRange.Maximum > ViewData.yzGrid.zRange.Maximum
then Vectors[4].Z := ViewData.xzGrid.zRange.Maximum*ViewData.xyGrid.zScale
else Vectors[4].Z := ViewData.yzGrid.zRange.Maximum*ViewData.xyGrid.zScale;
Vectors[1].Y := Vectors[0].Y;
Vectors[1].Z := Vectors[0].Z;
Vectors[2].X := Vectors[1].X;
Vectors[2].Z := Vectors[0].Z;
Vectors[3].X := Vectors[0].X;
Vectors[3].Y := Vectors[2].Y;
Vectors[3].Z := Vectors[0].Z;
Vectors[4].X := Vectors[0].X;
Vectors[4].Y := Vectors[0].Y;
Vectors[5].X := Vectors[1].X;
Vectors[5].Y := Vectors[1].Y;
Vectors[5].Z := Vectors[4].Z;
Vectors[6].X := Vectors[2].X;
Vectors[6].Y := Vectors[2].Y;
Vectors[6].Z := Vectors[4].Z;
Vectors[7].X := Vectors[3].X;
Vectors[7].Y := Vectors[3].Y;
Vectors[7].Z := Vectors[4].Z;
with ViewForm.BoxLine1 do
begin
Nodes[0].AsVector := Vectors[0];
Nodes[1].AsVector := Vectors[1];
Nodes[2].AsVector := Vectors[2];
Nodes[3].AsVector := Vectors[3];
Nodes[4].AsVector := Vectors[0];
Nodes[5].AsVector := Vectors[4];
Nodes[6].AsVector := Vectors[5];
Nodes[7].AsVector := Vectors[6];
Nodes[8].AsVector := Vectors[7];
Nodes[9].AsVector := Vectors[4];
end;
with ViewForm.BoxLine2 do
begin
Nodes[0].AsVector := Vectors[1];
Nodes[1].AsVector := Vectors[5];
end;
with ViewForm.BoxLine3 do
begin
Nodes[0].AsVector := Vectors[2];
Nodes[1].AsVector := Vectors[6];
end;
with ViewForm.BoxLine4 do
begin
Nodes[0].AsVector := Vectors[3];
Nodes[1].AsVector := Vectors[7];
end;
end;
end;
end.
|
unit uEducationFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridDBTableView, cxGrid, uEducationDataModule, Buttons, ExtCtrls,
ActnList, DBCtrls, EducationUnit, SpCommon, cxContainer, cxTextEdit,
cxMemo, uFormControl, FIBQuery, pFIBQuery, pFIBStoredProc,pFIBDataSet,
FIBDataSet, UpKernelUnit, iBase;
type
TfmPCardEducationPage = class(TFrame)
EducationGrid: TcxGrid;
EducationView: TcxGridDBTableView;
EducationGridLevel1: TcxGridLevel;
StyleRepository: TcxStyleRepository;
EducationViewNAME_Education: TcxGridDBColumn;
EducationViewDATE_BEG: TcxGridDBColumn;
EducationViewDATE_END: TcxGridDBColumn;
EducationViewID_Education: TcxGridDBColumn;
Panel11: TPanel;
SB_AddEduc: TSpeedButton;
SB_DelEduc: TSpeedButton;
SB_ModifEduc: TSpeedButton;
ALEducation: TActionList;
AddEducA: TAction;
ModifEducA: TAction;
DelEducA: TAction;
ShowInformation: TAction;
Panel1: TPanel;
Label24: TLabel;
Label25: TLabel;
Label26: TLabel;
Label27: TLabel;
Label28: TLabel;
AkredText: TDBText;
SpecName: TDBText;
KvalText: TDBText;
DiplomText: TDBText;
DateText: TDBText;
Panel2: TPanel;
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;
cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet;
cxMemo1: TcxMemo;
pFIBStoredProc1: TpFIBStoredProc;
ManEducSet: TpFIBDataSet;
EducationViewDBColumn1: TcxGridDBColumn;
procedure AddEducAExecute(Sender: TObject);
procedure ModifEducAExecute(Sender: TObject);
procedure DelEducAExecute(Sender: TObject);
procedure EducationViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FrameEnter(Sender: TObject);
procedure FrameExit(Sender: TObject);
procedure EducationGridFocusedViewChanged(Sender: TcxCustomGrid;
APrevFocusedView, AFocusedView: TcxCustomGridView);
procedure EducationSelectAfterOpen(DataSet: TDataSet);
private
DbHandle:TISC_DB_HANDLE;
{ Private declarations }
public
DM:TdmEducation;
id_pcard:integer;
constructor Create(AOwner: TComponent; DMod: TdmEducation; Id_PC: Integer; modify :integer); reintroduce;
end;
implementation
{$R *.dfm}
constructor TfmPCardEducationPage.Create(AOwner: TComponent; DMod: TdmEducation; Id_PC: Integer; modify :integer);
begin
inherited Create(AOwner);
DM:=Dmod; id_pcard:=Id_PC;
DM.EducationSelect.ParamByName('Id_PCard').AsInteger := Id_PCard;
DM.EducationSelect.AfterOpen:=EducationSelectAfterOpen;
DM.EducationSelect.Open;
EducationView.DataController.DataSource := DM.EducationSource;
AkredText.DataSource:=DM.EducationSource;
DateText.DataSource:=DM.EducationSource;
DiplomText.DataSource:=DM.EducationSource;
KvalText.DataSource:=DM.EducationSource;
SpecName.DataSource:=DM.EducationSource;
DM.pFIBDS_IsShow.Open;
DbHandle:=DM.DB.Handle;
if (DM.pFIBDS_IsShow['show_old_educ']='T') then
begin
DM.pFIBDS_OldEduc.ParamByName('Id_PCard').AsInteger := Id_PCard;
DM.pFIBDS_OldEduc.Open;
if (VarIsNull(DM.pFIBDS_OldEduc['EDUCATION'])) then
cxMemo1.Visible:=False
else
cxMemo1.Text:=DM.pFIBDS_OldEduc['EDUCATION'];
end
else
cxMemo1.Visible:=False;
if (modify=0) then
begin
AddEducA.Enabled:=False;
DelEducA.Enabled:=False;
ModifEducA.Enabled:=False;
end;
end;
procedure TfmPCardEducationPage.EducationSelectAfterOpen(DataSet: TDataSet);
begin
EducationView.ViewData.Expand(True);
end;
procedure TfmPCardEducationPage.AddEducAExecute(Sender: TObject);
var
form: TEducationForm;
ManeducAdd:TpFIBStoredProc;
// ManEducRet:TpFIBDataSet;
ret_param:Integer;
begin
//ManEducRet:=TpFIBDataSet.Create(Self);
//ManEducRet.Database:=DM.DB;
//ManEducRet.Transaction:=DM.ReadTransaction;
//ManEducRet.Close;
form := TEducationForm.Create(Self, DbHandle);
form.HDLE:=Integer(DM.DB.Handle);
form.qFIC_Akr.Visible:=false;
ManeducAdd:=TpFIBStoredProc.Create(Self);
ManeducAdd.Database:=DM.DB;
form.Caption:='Додати';
ManeducAdd.Transaction:=DM.DefaultTransaction;
ManeducAdd.StoredProcName:='ASUP_DT_MAN_EDUCATION_IU';
ManeducAdd.Transaction.StartTransaction;
//StartHistory(DM.DefaultTransaction);
if Form.ShowModal=mrOk then
begin
try
ManeducAdd.Prepare;
ManeducAdd.ParamByName('ID_PCARD').AsInteger:=id_pcard;
ManeducAdd.ParamByName('ID_ORG').AsInteger:=form.qFSC_Org.Value;
ManeducAdd.ParamByName('DATE_BEG').AsDate:=form.qFDC_Beg.Value;
ManeducAdd.ParamByName('DATE_END').AsDate:=form.qFDC_End.Value;
ManeducAdd.ParamByName('ID_SPEC').Value:=form.qFSC_Spec.Value;
ManeducAdd.ParamByName('ID_KVAL').Value:=form.qFSC_Kval.Value;
ManeducAdd.ParamByName('ID_EDUC').AsInteger:=form.qFSC_Educ.Value;
ManeducAdd.ParamByName('DIPLOM_NUMBER').AsString:=form.DiplomNumberEdit.Text;
ManeducAdd.ParamByName('DIPLOM_DATE').AsDate:=form.qFDC_Diplom.Value;
//ManeducAdd.ParamByName('AKREDITATION').AsInteger:=id_pcard;
ManeducAdd.ParamByName('IS_FSHR').Value:=form.qFBoolControl1.Value;
ManeducAdd.ExecProc;
//ret_param:=ManeducAdd.FldByName['ID'].AsInteger;
ManeducAdd.Transaction.Commit;
ManeducAdd.Close;
ManeducAdd.Free;
DM.EducationSelect.Close;
DM.EducationSelect.Open;
except on E: Exception do
ShowMessage(E.Message);
end;
end;
form.Free;
//DM.EducationSelect.Locate('ID_EDUC_KEY',ret_param,[]);
end;
procedure TfmPCardEducationPage.ModifEducAExecute(Sender: TObject);
var Form: TEducationForm;
ManeducUpd:TpFIBStoredProc;
EducSet, SpecSet, KvalSet, OrgSet:TpFIBDataSet;
Educ_Key:Integer;
begin
form := TEducationForm.Create(Self, DbHandle);
Form.qFIC_Akr.Visible:=false;
form.Caption:='Змінити';
ManEducSet.Close;
ManEducSet.SQLs.SelectSQL.Text:='select id_org, id_spec, id_kval, id_educ from man_educ where id_educ_key=:educ_key';
ManEducSet.ParamByName('EDUC_KEY').AsInteger:=DM.EducationSelect['ID_EDUC_KEY'];
ManEducSet.Open;
//отбор по типу образования
EducSet:=TpFIBDataSet.Create(Self);
EducSet.Database:=DM.DB;
EducSet.Transaction:=DM.ReadTransaction;
EducSet.Close;
EducSet.SQLs.SelectSQL.Text:='select id_educ, name_educ from SP_EDUCATION where id_educ=:educ';
EducSet.ParamByName('EDUC').AsInteger:=ManEducSet['ID_EDUC'];
EducSet.Open;
Form.qFSC_Educ.DisplayText:=EducSet['name_educ'];
//отбор специальности
SpecSet:=TpFIBDataSet.Create(Self);
SpecSet.Database:=DM.DB;
SpecSet.Transaction:=DM.ReadTransaction;
SpecSet.Close;
SpecSet.SQLs.SelectSQL.Text:='select id_spec, name_spec from SP_SPEC where id_spec=:spec';
SpecSet.ParamByName('spec').Value:=ManEducSet['ID_SPEC'];
SpecSet.Open;
Form.qFSC_Spec.DisplayText:=SpecSet['name_spec'];
//отбор по уровню квалификации
KvalSet:=TpFIBDataSet.Create(Self);
KvalSet.Database:=DM.DB;
KvalSet.Transaction:=DM.ReadTransaction;
KvalSet.Close;
KvalSet.SQLs.SelectSQL.Text:='select id_kval, name_kval from SP_KVALIFICATION where id_kval=:kval';
KvalSet.ParamByName('kval').Value:=ManEducSet['ID_KVAL'];
KvalSet.Open;
Form.qFSC_Kval.DisplayText:=KvalSet['name_kval'];
//отбор ВУЗов
OrgSet:=TpFIBDataSet.Create(Self);
OrgSet.Database:=DM.DB;
OrgSet.Transaction:=DM.ReadTransaction;
OrgSet.Close;
OrgSet.SQLs.SelectSQL.Text:='select id_org, name_full from SP_EDUCORG where id_org=:org';
OrgSet.ParamByName('org').AsInteger:=ManEducSet['ID_ORG'];
OrgSet.Open;
Form.qFSC_Org.DisplayText:=OrgSet['name_full'];
Educ_Key:=DM.EducationSelect['ID_EDUC_KEY'];
form.qFSC_Org.Value:=ManEducSet['ID_ORG'];
form.qFDC_Beg.Value:=DM.EducationSelect['DATE_BEG'];
form.qFDC_End.Value:=DM.EducationSelect['DATE_END'];
form.qFSC_Spec.Value:=ManEducSet['ID_SPEC'];
form.qFSC_Kval.Value:=ManEducSet['ID_KVAL'];
form.qFSC_Educ.Value:=ManEducSet['ID_EDUC'];
form.DiplomNumberEdit.Text:=DM.EducationSelect['DIPLOM_NUMBER'];
form.qFDC_Diplom.Value:=DM.EducationSelect['DIPLOM_DATE'];
//form.qFBoolControl1.Value:=ManEducSet['IS_FSHR'];
form.HDLE:=Integer(DM.DB.Handle);
ManeducUpd:=TpFIBStoredProc.Create(Self);
ManeducUpd.Database:=DM.DB;
ManeducUpd.Transaction:=DM.DefaultTransaction;
ManeducUpd.StoredProcName:='ASUP_DT_MAN_EDUCATION_IU';
ManeducUpd.Transaction.StartTransaction;
StartHistory(DM.DefaultTransaction);
if Form.ShowModal=mrOk then
begin
ManeducUpd.Prepare;
ManeducUpd.ParamByName('ID_PCARD').AsInteger:=id_pcard;
ManeducUpd.ParamByName('ID_ORG').AsInteger:=form.qFSC_Org.Value;
ManeducUpd.ParamByName('DATE_BEG').AsDate:=form.qFDC_Beg.Value;
ManeducUpd.ParamByName('DATE_END').AsDate:=form.qFDC_End.Value;
ManeducUpd.ParamByName('ID_SPEC').Value:=form.qFSC_Spec.Value;
ManeducUpd.ParamByName('ID_KVAL').Value:=form.qFSC_Kval.Value;
ManeducUpd.ParamByName('ID_EDUC').AsInteger:=form.qFSC_Educ.Value;
ManeducUpd.ParamByName('DIPLOM_NUMBER').AsString:=form.DiplomNumberEdit.Text;
ManeducUpd.ParamByName('DIPLOM_DATE').AsDate:=form.qFDC_Diplom.Value;
//ManeducUpd.ParamByName('AKREDITATION').AsInteger:=id_pcard;
ManeducUpd.ParamByName('IS_FSHR').Value:=form.qFBoolControl1.Value;
ManeducUpd.ParamByName('ID_EDUC_KEY').AsInt64:=Educ_Key;
ManeducUpd.ExecProc;
ManeducUpd.Transaction.Commit;
ManeducUpd.Close;
ManeducUpd.Free;
DM.EducationSelect.Close;
DM.EducationSelect.Open;
end;
form.Free;
DM.EducationSelect.Locate('ID_EDUC_KEY',Educ_Key,[])
end;
procedure TfmPCardEducationPage.DelEducAExecute(Sender: TObject);
begin
if DM.EducationSelect.IsEmpty then
begin
MessageDlg('Не можливо видалити запис бо довідник пустий',mtError,[mbYes],0);
Exit;
end;
if (MessageDlg('Чи ви справді бажаєте вилучити цей запис?',mtConfirmation,[mbYes,mbNo],0) = mrNo) then Exit;
with DM do
try
DeleteQuery.Transaction.StartTransaction;
StartHistory(DM.DefaultTransaction);
DeleteQuery.ParamByName('id_Educ').AsInteger:=EducationSelect['id_Educ_key'];
DeleteQuery.ExecProc;
DefaultTransaction.Commit;
except on e: Exception do
begin
MessageDlg('Не вдалося видалити запис: '+#13+e.Message,mtError,[mbYes],0);
DefaultTransaction.RollBack;
end;
end;
DM.EducationSelect.Close;
DM.EducationSelect.Open;
end;
procedure TfmPCardEducationPage.EducationViewKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (( Key = VK_F12) and (ssShift in Shift)) then
ShowInfo(EducationView.DataController.DataSource.DataSet);
end;
procedure TfmPCardEducationPage.FrameEnter(Sender: TObject);
begin
if not DM.ReadTransaction.InTransaction
then DM.ReadTransaction.StartTransaction;
if DM.EducationSelect.Active
then DM.EducationSelect.Close;
DM.EducationSelect.Open;
EducationView.ViewData.Expand(True);
EducationGrid.SetFocus;
end;
procedure TfmPCardEducationPage.FrameExit(Sender: TObject);
begin
DM.ReadTransaction.CommitRetaining;
end;
procedure TfmPCardEducationPage.EducationGridFocusedViewChanged(
Sender: TcxCustomGrid; APrevFocusedView,
AFocusedView: TcxCustomGridView);
begin
EducationView.ViewData.Expand(True);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.