text stringlengths 14 6.51M |
|---|
Program media_aluno_rep_ap;
{Faça um programa que receba duas notas, calcule e mostre a média aritmética e a mensagem que se encontra na tabela a seguir:
0,0 - 3,0 - Reprovado
3,0 - 7,0 - Exame
7,0 - 10,0 - Aprovado
}
var n1, n2, media : real;
Begin
write('Nota 1: ');
readln(n1);
write('Nota 2: ');
readln(n2);
media := (n1 + n2) / 2;
writeln('Media = ',media:0:2);
if media <= 3 then
writeln('Reprovado.')
else if (media > 3) and (media <= 7) then
writeln('Exame.')
else
writeln('Aprovado.');
readln;
End. |
unit PublicFacility;
interface
uses
Protocol, Kernel, Population, Classes, Collection, BackupInterfaces, Accounts,
WorkCenterBlock;
type
TPFInfoDef =
record
Kind : string;
Strength : integer;
end;
function PFInfoDef( Kind : string; Strength : integer ) : TPFInfoDef;
type
TPFInfo =
class
private
constructor Create( aPFInfoDef : TPFInfoDef );
private
fKind : TMetaPublicFacilityInfo;
fStrength : integer;
public
property Kind : TMetaPublicFacilityInfo read fKind;
property Strength : integer read fStrength;
end;
type
TMetaPublicFacility =
class( TMetaWorkCenter )
public
constructor Create( anId : string;
aCapacities : array of TFluidValue;
PFInfo : array of TPFInfoDef;
aBlockClass : CBlock );
destructor Destroy; override;
private
fKinds : TCollection;
fUpEffectOnMod : single;
fDissabledStop : boolean;
fMinPubSalary : TPercent;
fMaintCost : TMoney;
fMaintBoost : single;
published
property Kinds : TCollection read fKinds;
property UpEffectOnMod : single read fUpEffectOnMod write fUpEffectOnMod;
property DissabledStop : boolean read fDissabledStop write fDissabledStop;
property MinPubSalary : TPercent read fMinPubSalary write fMinPubSalary;
property MaintCost : TMoney read fMaintCost write fMaintCost;
end;
TPublicFacility =
class( TFinanciatedWorkCenter )
protected
constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override;
public
destructor Destroy; override;
private
fModifiers : TCollection;
fEfficiency : single;
public
function Evaluate : TEvaluationResult; override;
procedure AutoConnect( loaded : boolean ); override;
protected
function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override;
public
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
protected
procedure Deleted; override;
end;
procedure RegisterBackup;
implementation
uses
ClassStorage, Surfaces, PyramidalModifier, BasicAccounts, SimHints, SysUtils,
MathUtils, Languages;
function PFInfoDef( Kind : string; Strength : integer ) : TPFInfoDef;
begin
result.Kind := Kind;
result.Strength := Strength;
end;
// TPFInfo
constructor TPFInfo.Create( aPFInfoDef : TPFInfoDef );
begin
inherited Create;
fKind := TMetaPublicFacilityInfo(TheClassStorage.ClassById[tidClassFamily_PublicFacilities, aPFInfoDef.Kind]);
fStrength := aPFInfoDef.Strength;
end;
// TMetaPublicFacility
constructor TMetaPublicFacility.Create( anId : string; aCapacities : array of TFluidValue; PFInfo : array of TPFInfoDef; aBlockClass : CBlock );
var
i : integer;
Info : TPFInfo;
begin
inherited Create( anId, aCapacities, accIdx_None, accIdx_None, accIdx_PF_Salaries, aBlockClass );
fKinds := TCollection.Create( 0, rkBelonguer );
for i := low(PFInfo) to high(PFInfo) do
begin
Info := TPFInfo.Create( PFInfo[i] );
fKinds.Insert( Info );
end;
Prestige := Prestige + 5;
MaxUpgrade := StrToInt(TheGlobalConfigHandler.GetConfigParm('MaxCivicsUpgrade', '20'));
fUpEffectOnMod := 1;
fDissabledStop := TheGlobalConfigHandler.GetConfigParm('StopCivics', 'yes') = 'no';
fMinPubSalary := StrToInt(TheGlobalConfigHandler.GetConfigParm('MinCivicsWage', '250'));
MinColDist := StrToInt(TheGlobalConfigHandler.GetConfigParm('MinPubFacSep', '4'));
fMaintBoost := StrToFloat(TheGlobalConfigHandler.GetConfigParm('PubMaintBoost', '1.7'));
end;
destructor TMetaPublicFacility.Destroy;
begin
fKinds.Free;
inherited;
end;
// TPublicFacility
constructor TPublicFacility.Create( aMetaBlock : TMetaBlock; aFacility : TFacility );
var
kind : TPeopleKind;
begin
inherited;
for kind := low(kind) to high(kind) do
ExtraAdmitance[kind] := 100;
end;
destructor TPublicFacility.Destroy;
begin
fModifiers.ExtractAll;
fModifiers.Free;
inherited;
end;
function TPublicFacility.Evaluate : TEvaluationResult;
var
idx : integer;
i : integer;
uprlv : single;
begin
// Cannot Stop Civics.
if TMetaPublicFacility(MetaBlock).DissabledStop and not Facility.Deleted and (Facility.Company <> nil) and (Facility.Company.Owner <> nil) and not Facility.Company.Owner.IsRole
then Facility.ClearTrouble(facStoppedByTycoon);
// Cannot pay less than req%
AdjustMinimunWages(TMetaPublicFacility(MetaBlock).MinPubSalary);
result := inherited Evaluate;
uprlv := realmax(1, UpgradeLevel);
with TMetaPublicFacility(MetaBlock), TTownHall((TInhabitedTown(Facility.Town).TownHall.CurrBlock)) do
begin
// Compute actual efficiency
if not self.Facility.CriticalTrouble // >> ÑOHHHH!!!!!!!
then
begin
fEfficiency := WorkForceEfficiency;
if self.Facility.CompanyDir <> nil
then fEfficiency := realmin( 1, self.Facility.CompanyDir.Support )*fEfficiency;
self.BlockGenMoney(-self.dt*realmax(1, uprlv/3)*TMetaPublicFacility(self.MetaBlock).MaintCost*TMetaPublicFacility(self.MetaBlock).fMaintBoost, accIdx_PF_PublicOperation);
end
else fEfficiency := 0;
// Report coverage, update modifiers
idx := 0;
for i := 0 to pred(Kinds.Count) do
with TPFInfo(Kinds[i]) do
begin
ReportPublicFacility( Kind, round(uprlv*fEfficiency*Strength) );
if Kind.SurfaceId <> ''
then
begin
TSurfaceModifier(fModifiers[idx]).Value := (1 + UpEffectOnMod*(uprlv - 1))*fEfficiency*Kind.ModFact*Strength;
inc( idx );
end;
end;
// Ask workforce
if not self.Facility.CriticalTrouble
then HireWorkForce( 1 );
end;
end;
procedure TPublicFacility.AutoConnect( loaded : boolean );
var
i : integer;
Modifier : TSurfaceModifier;
begin
inherited;
fModifiers := TCollection.Create( 0, rkBelonguer );
with TMetaPublicFacility(MetaBlock), TTownHall((TInhabitedTown(Facility.Town).TownHall.CurrBlock)) do
for i := 0 to pred(Kinds.Count) do
with TPFInfo(Kinds[i]) do
if Kind.SurfaceId <> ''
then
begin
Modifier :=
TPyramidalModifier.Create(
Kind.SurfaceId,
Point(self.xOrigin, self.yOrigin),
Kind.ModFact*Strength,
Kind.ModStrength );
fModifiers.Insert( Modifier );
end;
end;
function TPublicFacility.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string;
var
TownHall : TTownHall;
info : TPublicFacilityInfo;
i : integer;
CoveredPeople : single;
begin
result := inherited GetStatusText( kind, ToTycoon );
case kind of
sttMain :
result := result +
//IntToStr(round(100*fEfficiency)) + '% operational.';
SimHints.GetHintText( mtidPubFacMain.Values[ToTycoon.Language], [round(100*fEfficiency)] );
sttSecondary :
begin
TownHall := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock);
result := Format(mtidUpgradeLevel.Values[ToTycoon.Language], [UpgradeLevel]) + ' ';
if TownHall.TotalPopulation > 0
then
with TMetaPublicFacility(MetaBlock) do
for i := 0 to pred(Kinds.Count) do
with TPFInfo(Kinds[i]) do
begin
info := TownHall.PublicFacilities[Kind];
if info <> nil
then CoveredPeople := realmin(info.Strength, TownHall.TotalPopulation)
else CoveredPeople := 0;
result := result + SimHints.GetHintText( mtidPubFacCov.Values[ToTycoon.Language], [Kind.Name_MLS.Values[ToTycoon.Language], round(100*CoveredPeople/TownHall.TotalPopulation)] ) + ' ';
end
else result := SimHints.GetHintText( mtidEmptyCity.Values[ToTycoon.Language], [0] )
end;
sttHint :
if fEfficiency < 0.8
then
if (Facility.CompanyDir = nil) or (Facility.CompanyDir.Support > 0.9)
then result := SimHints.GetHintText( mtidPublicFacNeedsWorkers.Values[ToTycoon.Language], [0] )
else result := SimHints.GetHintText( mtidPublicFacNeedsSupport.Values[ToTycoon.Language], [0] )
end;
end;
procedure TPublicFacility.LoadFromBackup( Reader : IBackupReader );
begin
inherited;
// Reader.ReadObject( 'Modifiers', fModifiers, nil );
end;
procedure TPublicFacility.StoreToBackup( Writer : IBackupWriter );
begin
inherited;
// Writer.WriteLooseObject( 'Modifiers', fModifiers );
end;
procedure TPublicFacility.Deleted;
var
i : integer;
begin
for i := 0 to pred(fModifiers.Count) do
TSurfaceModifier(fModifiers[i]).Delete;
inherited;
end;
// RegisterBackup;
procedure RegisterBackup;
begin
BackupInterfaces.RegisterClass( TPublicFacility );
end;
end.
|
unit MoveFav;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ImgList, StdCtrls, ComCtrls, FramedButton, ExtCtrls, FavView, VoyagerServerInterfaces,
InternationalizerComponent;
type
TMoveFavDlg = class(TForm)
BorderPanel: TPanel;
Panel2: TPanel;
BtnsPanel: TPanel;
bOK: TFramedButton;
bCancel: TFramedButton;
CaptionPanel: TPanel;
TreeView: TTreeView;
Label8: TLabel;
ImageList2: TImageList;
InternationalizerComponent1: TInternationalizerComponent;
procedure bOKClick(Sender: TObject);
procedure bCancelClick(Sender: TObject);
procedure TreeViewChange(Sender: TObject; Node: TTreeNode);
procedure TreeViewExpanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
procedure FormShow(Sender: TObject);
private
fClientView : IClientView;
public
property ClientView : IClientView write fClientView;
private
procedure RenderFolder( Location : string );
function LocateTreeNode( Location : string; StartNode : TTreeNode ) : TTreeNode;
private
procedure threadedGetFolderInfo( const parms : array of const );
procedure syncGetFolderInfo( const parms : array of const );
end;
var
MoveFavDlg: TMoveFavDlg;
implementation
uses
Threads, CompStringsParser, FavProtocol;
{$R *.DFM}
procedure TMoveFavDlg.bOKClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TMoveFavDlg.bCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TMoveFavDlg.RenderFolder( Location : string );
var
ParentContent : string;
p : integer;
ItemStr : string;
Id, Kind, Cnt : integer;
Name, Info : string;
Node, NewNode : TTreeNode;
wasdefined : boolean;
hadchildren : boolean;
empty : boolean;
locations : TStringList;
begin
Node := LocateTreeNode( Location, TreeView.Items.GetFirstNode );
if (Node.Data = nil) or not TNodeExtraInfo(Node.Data).defined
then
begin
if Node.Data = nil
then
begin
Node.Data := TNodeExtraInfo.Create;
TNodeExtraInfo(Node.Data).location := Location;
end;
Node.ImageIndex := 2;
Node.SelectedIndex := 2;
hadchildren := Node.HasChildren;
Node.DeleteChildren;
Node.HasChildren := hadchildren;
TNodeExtraInfo(Node.Data).rendered := false;
locations := TStringList.Create;
locations.Add( Location );
Fork( threadedGetFolderInfo, priNormal, [locations, false, false] );
wasdefined := false
end
else
begin
ParentContent := TNodeExtraInfo(Node.Data).content;
wasdefined := true;
end;
if wasdefined
then
begin
empty := true;
p := 1;
repeat
ItemStr := GetNextStringUpTo( ParentContent, p, chrItemSeparator );
if ItemStr <> ''
then
begin
UnSerializeItemProps( ItemStr, Id, Kind, Name, Info, Cnt );
empty := false;
if (Kind = fvkFolder) and not TNodeExtraInfo(Node.Data).rendered
then
begin
NewNode := TreeView.Items.AddChild( Node, Name );
NewNode.HasChildren := Cnt > 0;
NewNode.Data := TNodeExtraInfo.Create;
TNodeExtraInfo(NewNode.Data).location := Location + chrPathSeparator + IntToStr(Id);
end;
end;
until ItemStr = '';
TNodeExtraInfo(Node.Data).rendered := true;
TNodeExtraInfo(Node.Data).empty := empty;
Node.ImageIndex := 0;
end;
end;
function TMoveFavDlg.LocateTreeNode( Location : string; StartNode : TTreeNode ) : TTreeNode;
var
i : integer;
begin
if (StartNode.Data <> nil) and (TNodeExtraInfo(StartNode.Data).location <> Location)
then
begin
result := nil;
i := 0;
while (i < StartNode.Count) and (result = nil) do
begin
result := LocateTreeNode( Location, StartNode.Item[i] );
inc( i );
end;
end
else result := StartNode;
end;
procedure TMoveFavDlg.threadedGetFolderInfo( const parms : array of const );
var
locations : TStringList absolute parms[0].vObject;
updateList : boolean;
hadchildren : boolean;
content : string;
i : integer;
begin
sleep( 100 + random(300) );
updateList := parms[1].vBoolean;
hadchildren := parms[2].vBoolean;
for i := 0 to pred(locations.Count) do
begin
content := fClientView.FavGetSubItems( locations[i] );
Join( syncGetFolderInfo, [locations[i], content, updateList, hadchildren] );
end;
locations.Free;
end;
procedure TMoveFavDlg.syncGetFolderInfo( const parms : array of const );
var
location : string;
content : string;
Node : TTreeNode;
begin
location := parms[0].vPchar;
content := parms[1].vPchar;
Node := LocateTreeNode( Location, TreeView.Items.GetFirstNode );
if (Node <> nil) and (Node.Data <> nil)
then
begin
TNodeExtraInfo(Node.Data).content := content;
TNodeExtraInfo(Node.Data).defined := true;
RenderFolder( location );
Node.Expand( false );
end;
Node.ImageIndex := 0;
Node.SelectedIndex := 1;
end;
procedure TMoveFavDlg.TreeViewChange(Sender: TObject; Node: TTreeNode);
begin
if Node.Data <> nil
then RenderFolder( TNodeExtraInfo(Node.Data).location );
end;
procedure TMoveFavDlg.TreeViewExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean);
begin
if Node.Data <> nil
then RenderFolder( TNodeExtraInfo(Node.Data).location );
end;
procedure TMoveFavDlg.FormShow(Sender: TObject);
begin
TreeView.Items.Clear;
with TreeView.Items.Add( nil, 'Favorites' ) do
begin
HasChildren := true;
Data := nil;
end;
RenderFolder( '' );
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Content plugin search control
Copyright (C) 2014-2018 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit uSearchContent;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, StdCtrls, ExtCtrls, uFindFiles;
type
{ TPluginPanel }
TPluginPanel = class(TPanel)
private
FPlugin,
FField,
FOperator,
FValue,
FUnit: TComboBox;
private
function GetCompare: TPluginOperator;
function GetField: String;
function GetFieldType: Integer;
function GetPlugin: String;
function GetUnitName: String;
function GetValue: Variant;
procedure PluginChange(Sender: TObject);
procedure FieldChange(Sender: TObject);
procedure SetCompare(AValue: TPluginOperator);
procedure SetField(AValue: String);
procedure SetPlugin(AValue: String);
procedure SetUnitName(AValue: String);
procedure SetValue(AValue: Variant);
procedure SetComboBox(ComboBox: TComboBox; const Value, Error: String);
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
public
property Plugin: String read GetPlugin write SetPlugin;
property Field: String read GetField write SetField;
property UnitName: String read GetUnitName write SetUnitName;
property FieldType: Integer read GetFieldType;
property Compare: TPluginOperator read GetCompare write SetCompare;
property Value: Variant read GetValue write SetValue;
end;
implementation
uses
uLng, Variants, StrUtils, WdxPlugin, uGlobs, uWDXModule, Graphics, uShowMsg;
{ TPluginPanel }
function TPluginPanel.GetCompare: TPluginOperator;
begin
Result:= TPluginOperator(PtrInt(FOperator.Items.Objects[FOperator.ItemIndex]));
end;
function TPluginPanel.GetField: String;
begin
Result:= FField.Text;
end;
function TPluginPanel.GetFieldType: Integer;
begin
Result:= PtrInt(FField.Items.Objects[FField.ItemIndex]);
end;
function TPluginPanel.GetPlugin: String;
begin
Result:= FPlugin.Text;
end;
function TPluginPanel.GetUnitName: String;
begin
Result:= FUnit.Text;
end;
function TPluginPanel.GetValue: Variant;
begin
Result:= StrToVar(FValue.Text, PtrInt(FField.Items.Objects[FField.ItemIndex]));
end;
procedure TPluginPanel.PluginChange(Sender: TObject);
var
I: Integer;
Module: TWDXModule;
begin
if FPlugin.ItemIndex < 0 then Exit;
FField.Clear;
Module:= gWdxPlugins.GetWdxModule(FPlugin.Text);
if Assigned(Module) then
for I:= 0 to Module.FieldList.Count - 1 do
begin
FField.Items.AddObject(Module.FieldList[I], TObject(PtrInt(TWdxField(Module.FieldList.Objects[I]).FType)));
end;
if FField.Items.Count > 0 then
begin
FField.ItemIndex:= 0;
FieldChange(FField);
end;
end;
procedure TPluginPanel.FieldChange(Sender: TObject);
var
I, J: Integer;
sUnits: String;
Module: TWDXModule;
begin
FUnit.Items.Clear;
FValue.Items.Clear;
FOperator.Items.Clear;
Module:= gWdxPlugins.GetWdxModule(FPlugin.Text);
J:= Module.GetFieldIndex(FField.Text);
if J < 0 then Exit;
I:= TWdxField(Module.FieldList.Objects[J]).FType;
if (I <> FT_MULTIPLECHOICE) then
begin
sUnits:= TWdxField(Module.FieldList.Objects[J]).FUnits;
while sUnits <> EmptyStr do FUnit.Items.Add(Copy2SymbDel(sUnits, '|'));
end;
FUnit.Enabled := (I <> FT_MULTIPLECHOICE) AND (FUnit.Items.Count > 0);
if FUnit.Enabled then FUnit.ItemIndex:= 0;
case I of
FT_NUMERIC_32,
FT_NUMERIC_64,
FT_NUMERIC_FLOATING,
FT_DATE,
FT_TIME,
FT_DATETIME:
begin
FValue.Style:= csDropDown;
FOperator.Items.AddObject('=', TObject(PtrInt(poEqualCaseSensitive)));
FOperator.Items.AddObject('!=', TObject(PtrInt(poNotEqualCaseSensitive)));
FOperator.Items.AddObject('>', TObject(PtrInt(poMore)));
FOperator.Items.AddObject('<', TObject(PtrInt(poLess)));
FOperator.Items.AddObject('>=', TObject(PtrInt(poMoreEqual)));
FOperator.Items.AddObject('<=', TObject(PtrInt(poLessEqual)));
end;
FT_BOOLEAN:
begin
FValue.Items.Add(rsSimpleWordTrue);
FValue.Items.Add(rsSimpleWordFalse);
FValue.ItemIndex:= 0;
FValue.Style:= csDropDownList;
FOperator.Items.AddObject('=', TObject(PtrInt(poEqualCaseSensitive)));
end;
FT_MULTIPLECHOICE:
begin
begin
FValue.Style:= csDropDownList;
FOperator.Items.AddObject('=', TObject(PtrInt(poEqualCaseSensitive)));
FOperator.Items.AddObject('!=', TObject(PtrInt(poNotEqualCaseSensitive)));
sUnits:= TWdxField(Module.FieldList.Objects[J]).FUnits;
while sUnits <> EmptyStr do
begin
FValue.Items.Add(Copy2SymbDel(sUnits, '|'));
end;
if FValue.Items.Count > 0 then FValue.ItemIndex:= 0;
end;
end;
FT_STRING,
FT_STRINGW:
begin
FValue.Style:= csDropDown;
FOperator.Items.AddObject(rsPluginSearchEqualNotCase, TObject(PtrInt(poEqualCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchNotEqualNotCase, TObject(PtrInt(poNotEqualCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchEqualCaseSensitive, TObject(PtrInt(poEqualCaseSensitive)));
FOperator.Items.AddObject(rsPluginSearchNotEquaCaseSensitive, TObject(PtrInt(poNotEqualCaseSensitive)));
FOperator.Items.AddObject(rsPluginSearchContainsNotCase, TObject(PtrInt(poContainsCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchNotContainsNotCase, TObject(PtrInt(poNotContainsCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchContainsCaseSenstive, TObject(PtrInt(poContainsCaseSensitive)));
FOperator.Items.AddObject(rsPluginSearchNotContainsCaseSenstive, TObject(PtrInt(poNotContainsCaseSensitive)));
FOperator.Items.AddObject(rsPluginSearchRegExpr, TObject(PtrInt(poRegExpr)));
FOperator.Items.AddObject(rsPluginSearchNotRegExpr, TObject(PtrInt(poNotRegExpr)));
end;
FT_FULLTEXT,
FT_FULLTEXTW:
begin
FValue.Style:= csDropDown;
FOperator.Items.AddObject(rsPluginSearchContainsNotCase, TObject(PtrInt(poContainsCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchNotContainsNotCase, TObject(PtrInt(poNotContainsCaseInsensitive)));
FOperator.Items.AddObject(rsPluginSearchContainsCaseSenstive, TObject(PtrInt(poContainsCaseSensitive)));
FOperator.Items.AddObject(rsPluginSearchNotContainsCaseSenstive, TObject(PtrInt(poNotContainsCaseSensitive)));
end;
end;
if FOperator.Items.Count > 0 then FOperator.ItemIndex:= 0;
end;
procedure TPluginPanel.SetCompare(AValue: TPluginOperator);
var
Index: Integer;
begin
Index:= FOperator.Items.IndexOfObject(TObject(PtrInt(AValue)));
if Index >= 0 then FOperator.ItemIndex:= Index;
end;
procedure TPluginPanel.SetField(AValue: String);
begin
SetComboBox(FField, AValue, Format(rsPluginSearchFieldNotFound, [AValue]));
end;
procedure TPluginPanel.SetPlugin(AValue: String);
begin
SetComboBox(FPlugin, AValue, Format(rsPluginSearchPluginNotFound, [AValue]));
end;
procedure TPluginPanel.SetUnitName(AValue: String);
begin
if FUnit.Enabled then
SetComboBox(FUnit, AValue, Format(rsPluginSearchUnitNotFoundForField, [AValue, Self.Field]));
end;
procedure TPluginPanel.SetValue(AValue: Variant);
begin
FValue.Text:= VarToStr(AValue)
end;
procedure TPluginPanel.SetComboBox(ComboBox: TComboBox; const Value,
Error: String);
var
Index: Integer;
begin
Index:= ComboBox.Items.IndexOf(Value);
if Index < 0 then
msgError(Error)
else begin
ComboBox.ItemIndex:= Index;
if Assigned(ComboBox.OnChange) then ComboBox.OnChange(ComboBox);
end;
end;
constructor TPluginPanel.Create(TheOwner: TComponent);
var
I: Integer;
begin
inherited Create(TheOwner);
AutoSize:= True;
BevelOuter:= bvNone;
ChildSizing.ControlsPerLine:= 5;
ChildSizing.Layout:= cclLeftToRightThenTopToBottom;
ChildSizing.EnlargeHorizontal:= crsScaleChilds;
FPlugin:= TComboBox.Create(Self);
FPlugin.Parent:= Self;
FPlugin.Style:= csDropDownList;
FPlugin.OnChange:= @PluginChange;
FField:= TComboBox.Create(Self);
FField.Parent:= Self;
FField.Style:= csDropDownList;
FField.OnChange:= @FieldChange;
FOperator:= TComboBox.Create(Self);
FOperator.Parent:= Self;
FOperator.Style:= csDropDownList;
FValue:= TComboBox.Create(Self);
FValue.Parent:= Self;
FUnit:= TComboBox.Create(Self);
FUnit.Style:= csDropDownList;
FUnit.Parent:= Self;
for I:= 0 to gWDXPlugins.Count - 1do
begin
if gWdxPlugins.GetWdxModule(I).IsLoaded or gWdxPlugins.GetWdxModule(I).LoadModule then
begin
FPlugin.Items.Add(gWdxPlugins.GetWdxModule(I).Name);
end;
end;
if FPlugin.Items.Count > 0 then
begin
FPlugin.ItemIndex:= 0;
PluginChange(FPlugin);
end;
end;
destructor TPluginPanel.Destroy;
begin
FPlugin.Free;
FField.Free;
FOperator.Free;
FValue.Free;
FUnit.Free;
inherited Destroy;
end;
end.
|
unit SpeedButtons;
interface
uses WinTypes, WinProcs, OWindows, WIN31, Strings, Generics, Aligner;
const STATESCONT = 3;
WM_SPEEDBUTTON = wm_User + $0001;
type
PSpeedButton = ^TSpeedButton;
TSpeedButton = object(TGeneric)
private
Bitmap: HBitmap;
Origin: TPoint;
Size: TPoint;
Command: Word;
Switch: Boolean;
StatusText: PChar;
Enabled: Boolean;
Group: Integer;
public
constructor Create(AX, AY: Integer; ACommand: Word; AGroup: Integer; BitmapRes: PChar; AStatusText: PChar);
destructor Destroy; virtual;
procedure Draw(DC: HDC; State: Integer); virtual;
function ContainsPoint(APoint: TPoint): Boolean;
function GetStatusText: PChar; virtual;
function GetCommand: Word; virtual;
procedure GetSize(var ASize: TPoint); virtual;
procedure GetPos(var APos: Tpoint); virtual;
procedure Enable(AEnable: Boolean); virtual;
procedure EnableGroup(AGroup: Integer; AEnable: Boolean); virtual;
procedure EnableCommand(ACommand: Word; AEnable: Boolean); virtual;
end;
PSpeedBottonAligner = ^TSpeedBottonAligner;
TSpeedBottonAligner = object(TAligner)
Button: PSpeedButton;
constructor Create(AAlign: TAlign; AButton: PSpeedButton);
function GetDim: Integer; virtual;
procedure AlignItem(ARect: TRect); virtual;
end;
PSpeedButtonsHandler = ^TSpeedButtonsHandler;
TSpeedButtonsHandler = object(TGeneric)
Buttons: TContainerCollection{PSpeedButton};
ActiveButton: PSpeedButton;
Window: HWND;
TempDC: HDC;
ActiveButtonState: Integer;
constructor Create(AWindow: HWND);
destructor Destroy; virtual;
procedure Draw(DC: HDC); virtual;
procedure Invalidate; virtual;
procedure InsertButton(AButton: PSpeedButton); virtual;
procedure EnableGroup(AGroup: Integer; AEnable: Boolean); virtual;
procedure EnableCommand(ACommand: Word; AEnable: Boolean); virtual;
procedure WMLButtonDown(var Msg:TMessage); virtual;
procedure WMLButtonUp(var Msg:TMessage); virtual;
procedure WMMouseMove(var Msg:TMessage); virtual;
end;
procedure DrawBitmap(ADC: HDC; AX, AY, AWidth, AHeight: Integer; ABitmap: HBitmap);
implementation
procedure DrawBitmap(ADC: HDC; AX, AY, AWidth, AHeight: Integer; ABitmap: HBitmap);
var OldBitmap: HBitmap;
MemDC: HDC;
begin
if (ABitmap <> 0)
then begin
MemDC := CreateCompatibleDC(ADC);
OldBitmap := SelectObject(MemDC, ABitmap);
BitBlt(ADC ,AX, AY, AWidth, AHeight, MemDC, 0,0,SRCCOPY);
SelectObject(MemDC, OldBitmap);
DeleteDC(MemDC);
end;
end;
constructor TSpeedButton.Create(AX, AY: Integer; ACommand: Word; AGroup: Integer; BitmapRes: PChar; AStatusText: PChar);
var BM: TBITMAP;
begin
inherited Create;
if (BitmapRes <> nil)
then Bitmap := LoadBitmap(HInstance, BitmapRes)
else Bitmap := 0;
if (Bitmap <> 0)
then begin
GetObject(Bitmap, SizeOf(BM), @BM);
Size.X := BM.bmWidth div STATESCONT;
Size.Y := BM.bmHeight;
end
else begin
Size.X := 0;
Size.Y := 0;
end;
{Size.X := LOWORD(L) div STATESCONT;
Size.Y := HIWORD(L);}
Origin.X := AX;
Origin.Y := AY;
Command := ACommand;
Group := AGroup;
Enabled := True;
Switch := False;
if (AStatusText <> nil)
then StatusText := StrNew(AStatusText)
else StatusText := nil;
end;
destructor TSpeedButton.Destroy;
begin
DeleteObject(Bitmap);
if (StatusText <> nil)
then StrDispose(StatusText);
inherited Destroy;
end;
procedure TSpeedButton.Draw(DC: HDC; State: Integer);
var OldBitmap: HBitmap;
MemDC: HDC;
begin
if (Bitmap <> 0)
then begin
MemDC := CreateCompatibleDC(DC);
OldBitmap := SelectObject(MemDC, Bitmap);
if Enabled
then BitBlt(DC ,Origin.X,Origin.Y,Size.X,Size.Y,MemDC,Size.X * State,0,SRCCOPY)
else BitBlt(DC ,Origin.X,Origin.Y,Size.X,Size.Y,MemDC,Size.X * 2,0,SRCCOPY);
SelectObject(MemDC, OldBitmap);
DeleteDC(MemDC);
end;
end;
function TSpeedButton.ContainsPoint(APoint: TPoint): Boolean;
begin
ContainsPoint := Enabled and ((APoint.X >= Origin.X)
and (APoint.Y >= Origin.Y)
and (APoint.X < (Origin.X + Size.X))
and (APoint.Y < (Origin.Y + Size.Y)));
end;
function TSpeedButton.GetCommand: Word;
begin
GetCommand := Command;
end;
function TSpeedButton.GetStatusText: PChar;
begin
GetStatusText := StatusText;
end;
procedure TSpeedButton.GetSize(var ASize: TPoint);
begin
ASize := Size;
end;
procedure TSpeedButton.GetPos(var APos: Tpoint);
begin
APos := Origin;
end;
procedure TSpeedButton.Enable(AEnable: Boolean);
begin
Enabled := AEnable;
end;
procedure TSpeedButton.EnableGroup(AGroup: Integer; AEnable: Boolean);
begin
if (Group = AGroup)
then Enabled := AEnable;
end;
procedure TSpeedButton.EnableCommand(ACommand: Word; AEnable: Boolean);
begin
if (Command = ACommand)
then Enabled := AEnable;
end;
constructor TSpeedBottonAligner.Create(AAlign: TAlign; AButton: PSpeedButton);
begin
inherited Create(AAlign);
Button := AButton;
end;
function TSpeedBottonAligner.GetDim: Integer;
begin
if (Button <> nil)
then begin
case Align
of alTop,
alBottom: GetDim := Button^.Size.Y;
alLeft,
alRight: GetDim := Button^.Size.X;
else
GetDim := 0;
end;
end
else GetDim := -1;
end;
procedure TSpeedBottonAligner.AlignItem(ARect: TRect);
begin
if (Button <> nil)
then begin
Button^.Origin.X := ARect.Left;
Button^.Origin.Y := ARect.Top;
end;
end;
constructor TSpeedButtonsHandler.Create(AWindow: HWND);
begin
inherited Create;
Buttons.Create;
ActiveButton := nil;
Window := AWindow;
TempDC := 0;
end;
destructor TSpeedButtonsHandler.Destroy;
begin
Buttons.Destroy;
inherited Destroy;
end;
procedure TSpeedButtonsHandler.Draw(DC: HDC);
var TempButton: PSpeedButton;
begin
TempButton := PSpeedButton(Buttons.GetFirst);
while (TempButton <> nil)
do begin
TempButton^.Draw(DC,0);
TempButton := PSpeedButton(Buttons.GetNext);
end;
end;
procedure TSpeedButtonsHandler.Invalidate;
begin
if (Window <> 0)
then InvalidateRect(Window, nil, False);
end;
procedure TSpeedButtonsHandler.InsertButton(AButton: PSpeedButton);
begin
if (AButton <> nil)
then begin
Buttons.PushLast(AButton);
Invalidate;
end;
end;
procedure TSpeedButtonsHandler.EnableGroup(AGroup: Integer; AEnable: Boolean);
var TempButton: PSpeedButton;
begin
TempButton := PSpeedButton(Buttons.GetFirst);
while (TempButton <> nil)
do begin
TempButton^.EnableGroup(AGroup, AEnable);
TempButton := PSpeedButton(Buttons.GetNext);
end;
Invalidate;
end;
procedure TSpeedButtonsHandler.EnableCommand(ACommand: Word; AEnable: Boolean);
var TempButton: PSpeedButton;
begin
TempButton := PSpeedButton(Buttons.GetFirst);
while (TempButton <> nil)
do begin
TempButton^.EnableCommand(ACommand, AEnable);
TempButton := PSpeedButton(Buttons.GetNext);
end;
Invalidate;
end;
procedure TSpeedButtonsHandler.WMLButtonDown(var Msg:TMessage);
var Pos: TPoint;
TempButton: PSpeedButton;
Found: Boolean;
begin
TempButton := PSpeedButton(Buttons.GetLast);
if (TempButton <> nil)
then begin
Pos.X := LOWORD(Msg.LParam);
Pos.Y := HIWORD(Msg.LParam);
Found := False;
repeat
if TempButton^.ContainsPoint(Pos)
then begin
Found := True;
Break;
end
else TempButton := PSpeedButton(Buttons.GetPrev);
until (TempButton = nil);
if Found
then begin
ActiveButton := TempButton;
TempDC := GetDC(Window);
ActiveButton^.Draw(TempDC, 1);
ActiveButtonState := 1;
SetCapture(Window);
end;
end;
end;
procedure TSpeedButtonsHandler.WMLButtonUp(var Msg:TMessage);
var Pos: TPoint;
Command: Word;
begin
if (ActiveButton <> nil)
then begin
Pos.X := LOWORD(Msg.LParam);
Pos.Y := HIWORD(Msg.LParam);
ReleaseCapture;
ActiveButton^.Draw(TempDC, 0);
ActiveButtonState := 0;
ReleaseDC(Window, TempDC);
if ActiveButton^.ContainsPoint(Pos)
then begin
Command := ActiveButton^.GetCommand;
SendMessage(Window, WM_SPEEDBUTTON, Command, 0);
end;
ActiveButton := nil;
end;
end;
procedure TSpeedButtonsHandler.WMMouseMove(var Msg:TMessage);
var Pos: TPoint;
begin
if (ActiveButton <> nil)
then begin
Pos.X := LOWORD(Msg.LParam);
Pos.Y := HIWORD(Msg.LParam);
if ActiveButton^.ContainsPoint(Pos)
then begin
if (ActiveButtonState <> 1)
then begin
ActiveButton^.Draw(TempDC, 1);
ActiveButtonState := 1;
end;
end
else begin
if (ActiveButtonState <> 0)
then begin
ActiveButton^.Draw(TempDC, 0);
ActiveButtonState := 0;
end;
end;
end;
end;
end. |
unit WorkflowView;
interface
uses
Xmldoc, XmlIntf, Generics.Collections, SysUtils, ActionHandler, Classes;
const
XML_ROOT = 'View';
XML_FOLDER = 'Folder';
XML_ITEM = 'Item';
XML_ATTR_NAME = 'name';
XML_ATTR_VISIBLE = 'true';
type
TViewWorkSpace = class;
TViewFolder = class;
TViewItem = class;
TStringArray = array of string;
TAbstractViewNode = class
private
FNodes: TObjectList<TAbstractViewNode>;
FXMLNodeName: string;
FView: TViewWorkSpace;
FCaption: string;
FTag: Integer;
FVisible: Boolean;
FImageIndex: Integer;
FParent: TAbstractViewNode;
function GetNode(Index: Integer): TAbstractViewNode;
function GetCount: Integer;
function GetAttribValue(Node: IXMLNode; AttribName: string; Default: Variant): Variant;
protected
procedure LoadAttribs(Node: IXMLNode); virtual;
procedure SaveAttribs(Node: IXMLNode); virtual;
procedure LoadFromNode(Node: IXMLNode); virtual;
procedure SaveToNode(Node: IXMLNode); virtual;
public
constructor Create(View: TViewWorkSpace); virtual;
procedure Add(Node: TAbstractViewNode);
procedure Delete(Index: Integer);
procedure Clear;
procedure EnumNodes(L: TList);
function Extract(Item: TAbstractViewNode): TAbstractViewNode;
destructor Destroy; override;
property Nodes[Index: Integer]: TAbstractViewNode read GetNode;
property NodesCount: Integer read GetCount;
property Caption: string read FCaption write FCaption;
property Visible: Boolean read FVisible write FVisible;
property ImageIndex: Integer read FImageIndex write FImageIndex;
property Tag: Integer read FTag write FTag;
property Parent: TAbstractViewNode read FParent;
end;
TViewFolder = class(TAbstractViewNode)
public
constructor Create(View: TViewWorkSpace); override;
end;
TViewItem = class(TAbstractViewNode)
private
FTargetActionName: String;
FActionKind: TActionHandlerKind;
protected
procedure LoadAttribs(Node: IXMLNode); override;
procedure SaveAttribs(Node: IXMLNode); override;
public
constructor Create(View: TViewWorkSpace); override;
property TargetActionName: string read FTargetActionName write FTargetActionName;
property ActionKind: TActionHandlerKind read FActionKind write FActionKind;
end;
TViewWorkSpace = class
private
FRoot: TAbstractViewNode;
function GetNode(Index: Integer): TAbstractViewNode;
function GetCount: Integer;
function GetVisible: Boolean;
public
constructor Create;
procedure LoadFromFile(FileName: string);
function AddFolder(Parent: TAbstractViewNode): TAbstractViewNode;
function AddItem(Parent: TAbstractViewNode): TAbstractViewNode;
procedure EnumNodes(L: TList);
procedure SaveToFile(FileName: string);
destructor Destroy; override;
property Nodes[Index: Integer]: TAbstractViewNode read GetNode;
property NodesCount: Integer read GetCount;
property Visible: Boolean read GetVisible;
end;
implementation
{ TViewWorkSpace }
function TViewWorkSpace.AddFolder(Parent: TAbstractViewNode): TAbstractViewNode;
begin
Result := TViewFolder.Create(Self);
if Parent = nil then
FRoot.Add(Result)
else
Parent.Add(Result);
end;
function TViewWorkSpace.AddItem(Parent: TAbstractViewNode): TAbstractViewNode;
begin
Result := TViewItem.Create(Self);
if Parent = nil then
FRoot.Add(Result)
else
Parent.Add(Result);
end;
constructor TViewWorkSpace.Create;
begin
inherited Create;
FRoot := TAbstractViewNode.Create(Self);
end;
destructor TViewWorkSpace.Destroy;
begin
FRoot.Free;
inherited Destroy;
end;
procedure TViewWorkSpace.EnumNodes(L: TList);
begin
FRoot.EnumNodes(L);
end;
function TViewWorkSpace.GetCount: Integer;
begin
Result := FRoot.GetCount;
end;
function TViewWorkSpace.GetNode(Index: Integer): TAbstractViewNode;
begin
Result := FRoot.GetNode(Index);
end;
function TViewWorkSpace.GetVisible: Boolean;
begin
Result := FRoot.Visible;
end;
procedure TViewWorkSpace.LoadFromFile(FileName: string);
var
Document: IXMLDocument;
begin
Document := TXMLDocument.Create(nil);
try
Document.LoadFromFile(FileName);
if Document.DocumentElement.NodeName <> XML_ROOT then
raise Exception.Create('Неверный формат файла настроек.');
FRoot.LoadFromNode(Document.DocumentElement);
finally
Document := nil;
end;
end;
procedure TViewWorkSpace.SaveToFile(FileName: string);
var
Document: IXMLDocument;
begin
Document := TXMLDocument.Create(nil);
try
Document.Active := True;
Document.Version := '1.0';
Document.Encoding := 'windows-1251';
Document.DocumentElement := Document.AddChild(XML_ROOT);
FRoot.SaveToNode(Document.DocumentElement);
Document.SaveToFile(FileName);
finally
Document := nil;
end;
end;
{ TViewNode }
procedure TAbstractViewNode.Add(Node: TAbstractViewNode);
begin
FNodes.Add(Node);
Node.FParent := Self;
end;
procedure TAbstractViewNode.Clear;
begin
FNodes.Clear;
end;
constructor TAbstractViewNode.Create(View: TViewWorkSpace);
begin
inherited Create;
FView := View;
FNodes := TObjectList<TAbstractViewNode>.Create;
end;
procedure TAbstractViewNode.Delete(Index: Integer);
begin
FNodes.Delete(Index);
end;
destructor TAbstractViewNode.Destroy;
begin
FNodes.Free;
inherited Destroy;
end;
procedure TAbstractViewNode.EnumNodes(L: TList);
var
I: Integer;
begin
for I := 0 to NodesCount - 1 do
begin
L.Add(Nodes[I]);
Nodes[I].EnumNodes(L);
end;
end;
function TAbstractViewNode.Extract(Item: TAbstractViewNode): TAbstractViewNode;
begin
Result := FNodes.Extract(Item);
end;
function TAbstractViewNode.GetAttribValue(Node: IXMLNode; AttribName: string; Default: Variant): Variant;
begin
if Node.HasAttribute(AttribName) then
Result := Node.Attributes[AttribName]
else
Result := Default;
end;
function TAbstractViewNode.GetCount: Integer;
begin
Result := FNodes.Count;
end;
function TAbstractViewNode.GetNode(Index: Integer): TAbstractViewNode;
begin
Result := TAbstractViewNode(FNodes[Index]);
end;
procedure TAbstractViewNode.LoadAttribs(Node: IXMLNode);
begin
FCaption := GetAttribValue(Node, 'caption', EmptyStr);
FVisible := GetAttribValue(Node, 'visible', True);
FImageIndex := GetAttribValue(Node, 'image', -1);
end;
procedure TAbstractViewNode.LoadFromNode(Node: IXMLNode);
var
I: Integer;
Child: TAbstractViewNode;
begin
FXMLNodeName := Node.NodeName;
LoadAttribs(Node);
for I := 0 to Node.ChildNodes.Count - 1 do
begin
if Node.ChildNodes[I].NodeName = XML_FOLDER then
Child := TViewFolder.Create(FView)
else
if Node.ChildNodes[I].NodeName = XML_ITEM then
Child := TViewItem.Create(FView)
else
raise Exception.Create('Неопознанный узел');
Child.LoadFromNode(Node.ChildNodes[I]);
Add(Child);
end;
end;
procedure TAbstractViewNode.SaveAttribs(Node: IXMLNode);
begin
Node.Attributes['caption'] := FCaption;
if FImageIndex >= 0 then
Node.Attributes['image'] := FImageIndex;
Node.Attributes['visible'] := FVisible;
end;
procedure TAbstractViewNode.SaveToNode(Node: IXMLNode);
var
I: Integer;
Child: IXMLNode;
begin
SaveAttribs(Node);
for I := 0 to FNodes.Count - 1 do
begin
Child := Node.AddChild(FNodes[I].FXMLNodeName);
FNodes[I].SaveToNode(Child);
end;
end;
{ TViewItem }
constructor TViewItem.Create(View: TViewWorkSpace);
begin
inherited Create(View);
FXMLNodeName := 'Item';
FVisible := True;
FImageIndex := -1;
end;
procedure TViewItem.LoadAttribs(Node: IXMLNode);
begin
inherited LoadAttribs(Node);
FTargetActionName := GetAttribValue(Node, 'target', EmptyStr);
FActionKind := GetAttribValue(Node, 'action', 0);
end;
procedure TViewItem.SaveAttribs(Node: IXMLNode);
begin
inherited;
Node.Attributes['visible'] := FVisible;
Node.Attributes['action'] := FActionKind;
Node.Attributes['target'] := FTargetActionName;
end;
{ TViewFolder }
constructor TViewFolder.Create(View: TViewWorkSpace);
begin
inherited Create(View);
FXMLNodeName := XML_FOLDER;
end;
end.
|
unit uSubGrupo;
interface
uses System.Classes,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Dialogs,
ZAbstractConnection,
ZConnection,
ZAbstractRODataset,
ZAbstractDataset,
ZDataset,
System.SysUtils;
type
TSubGrupo = class
private
ConexaoDB:TZConnection;
F_SubGrupo_cod: Integer;
F_SubGrupo_Nome: string;
F_SubGrupo_Descricao: string;
F_Grupo_cod :Integer;
public
constructor Create(aConexao: TZConnection);
destructor Destroy; override;
function Inserir: Boolean;
function Atualizar: Boolean;
function Apagar: Boolean;
function Selecionar(id: Integer): Boolean;
published
property SubGrupo_cod: Integer read F_SubGrupo_cod write F_SubGrupo_cod;
property SubGrupo_Nome: string read F_SubGrupo_Nome write F_SubGrupo_Nome;
property SubGrupo_Descricao: string read F_SubGrupo_Descricao write F_SubGrupo_Descricao;
property Grupo_Cod :Integer read F_Grupo_cod write F_Grupo_cod;
end;
implementation
{ TCategoria }
{$region 'Constructor and Destructor'}
constructor TSubGrupo.Create(aConexao:TZConnection);
begin
ConexaoDB:=aConexao;
end;
destructor TSubGrupo.Destroy;
begin
inherited;
end;
{$endRegion}
{$region 'CRUD'}
function TSubGrupo.Apagar: Boolean;
var Qry:TZQuery;
begin
if MessageDlg('Apagar o Registro: '+#13+#13+
'Código: '+IntToStr(F_SubGrupo_cod)+#13+
'Descrição: '+F_SubGrupo_Nome,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin
Result:=false;
abort;
end;
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM SubGRUPO '+
' WHERE SubGRUPO_COD=:SubGRUPO_COD ');
Qry.ParamByName('SubGRUPO_COD').AsInteger :=F_SubGrupo_cod;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TSubGrupo.Atualizar: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE SUBGRUPO '+
' SET SubGrupo_nome =:nome '+
' ,SubGrupo_descriccao =:descricao, '+
' ,SubGrupo_Grupo_Cod =:Grupo_Cod '+
' WHERE SubGrupo_Cod =:SubGrupo_Cod ');
Qry.ParamByName('Grupo_Cod').AsInteger :=Self.F_SubGrupo_cod;
Qry.ParamByName('nome').AsString :=Self.SubGrupo_Nome;
Qry.ParamByName('descricao').AsString :=Self.SubGrupo_Descricao;
Qry.ParamByName('Grupo_Cod').AsInteger :=Self.F_Grupo_cod;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TSubGrupo.Inserir: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO SubGrupo (SubGrupo_Nome, '+
' SubGrupo_Descricao,'+
' SubGrupo_GrupoId )' +
' VALUES (:nome, '+
' :descricao, '+
' :Grupo_Cod )') ;
Qry.ParamByName('nome' ).AsString :=Self.F_SubGrupo_Nome;
Qry.ParamByName('descricao').AsString :=Self.F_SubGrupo_Descricao;
Qry.ParamByName('Grupo_cod').AsInteger :=Self.F_Grupo_cod;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TSubGrupo.Selecionar(id: Integer): Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT SubGrupo_Cod,'+
' subGrupo_nome, '+
' SubGrupo_descricao, '+
' SubGrupo_Grupo_cod'+
' FROM produtos '+
' WHERE SubGrupo_Cod=:SubGrupo_Cod');
Qry.ParamByName('SubGrupo_Cod').AsInteger:=id;
Try
Qry.Open;
Self.F_SubGrupo_cod := Qry.FieldByName('SubGrupo_Cod').AsInteger;
Self.F_SubGrupo_Nome := Qry.FieldByName('SubGrupo_nome').AsString;
Self.F_SubGrupo_Descricao := Qry.FieldByName('SubGrupo_descricao').AsString;
Self.F_SubGrupo_cod := Qry.FieldByName('SubGrupo_Grupo_Cod').AsInteger;
Except
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
end.
|
unit dcDispLabel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, DataController, dbctrls, db;
type
TdcDispLabel = class(TLabel)
private
{ Private declarations }
fdcLink : TdcLink;
fTranData : String;
protected
{ Protected declarations }
// std data awareness
function GetDataSource:TDataSource;
procedure SetDataSource(value:Tdatasource);
function GetDataField:string;
procedure SetDataField(value:string);
// data controller
function GetDataController:TDataController;
procedure SetDataController(value:TDataController);
procedure ReadData(sender:TObject);
public
{ Public declarations }
constructor Create(AOwner:Tcomponent);override;
destructor Destroy;override;
property TranData : String read fTranData;
published
{ Published declarations }
property DataController : TDataController read GetDataController write setDataController;
property DataField : String read GetDataField write SetDataField;
property DataSource : TDataSource read getDataSource write SetDatasource;
end;
procedure Register;
implementation
constructor TdcDispLabel.Create(AOwner:Tcomponent);
begin
inherited;
fdclink := tdclink.create(self);
fdclink.OnReadData := ReadData;
fdclink.OnWriteData := nil;
AutoSize := false;
end;
destructor TdcDispLabel.Destroy;
begin
fdclink.Free;
inherited;
end;
procedure TdcDispLabel.SetDataController(value:TDataController);
begin
fdcLink.datacontroller := value;
end;
function TdcDispLabel.GetDataController:TDataController;
begin
result := fdcLink.DataController;
end;
procedure TdcDispLabel.SetDataSource(value:TDataSource);
begin
end;
function TdcDispLabel.GetDataField:string;
begin
result := fdclink.FieldName;
end;
function TdcDispLabel.GetDataSource:TDataSource;
begin
result := fdclink.DataSource;
end;
procedure TdcDispLabel.SetDataField(value:string);
begin
fdclink.FieldName := value;
end;
procedure TdcDispLabel.ReadData;
begin
if fdclink.Field <> nil then begin
caption := trim(fdclink.Field.DisplayName);
end;
end;
procedure Register;
begin
RegisterComponents('FFS Data Entry', [TdcDispLabel]);
end;
end.
|
unit frmALTRun;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
AppEvnts,
CoolTrayIcon,
ActnList,
Menus,
HotKeyManager,
ExtCtrls,
Buttons,
ImgList,
ShellAPI,
MMSystem,
frmParam,
frmAutoHide,
untShortCutMan,
untClipboard,
untALTRunOption,
untUtilities, jpeg;
type
TALTRunForm = class(TForm)
lblShortCut: TLabel;
edtShortCut: TEdit;
lstShortCut: TListBox;
evtMain: TApplicationEvents;
ntfMain: TCoolTrayIcon;
pmMain: TPopupMenu;
actlstMain: TActionList;
actShow: TAction;
actShortCut: TAction;
actConfig: TAction;
actClose: TAction;
hkmHotkey1: THotKeyManager;
actAbout: TAction;
Show1: TMenuItem;
ShortCut1: TMenuItem;
Config1: TMenuItem;
About1: TMenuItem;
Close1: TMenuItem;
actExecute: TAction;
actSelectChange: TAction;
imgBackground: TImage;
actHide: TAction;
pmList: TPopupMenu;
actAddItem: TAction;
actEditItem: TAction;
actDeleteItem: TAction;
mniAddItem: TMenuItem;
mniEditItem: TMenuItem;
mniDeleteItem: TMenuItem;
tmrHide: TTimer;
ilHotRun: TImageList;
btnShortCut: TSpeedButton;
btnClose: TSpeedButton;
edtHint: TEdit;
edtCommandLine: TEdit;
mniN1: TMenuItem;
actOpenDir: TAction;
mniOpenDir: TMenuItem;
tmrExit: TTimer;
edtCopy: TEdit;
tmrCopy: TTimer;
btnConfig: TSpeedButton;
tmrFocus: TTimer;
actUp: TAction;
actDown: TAction;
hkmHotkey2: THotKeyManager;
pmCommandLine: TPopupMenu;
actCopyCommandLine: TAction;
hkmHotkey3: THotKeyManager;
procedure WndProc(var Msg: TMessage); override;
procedure edtShortCutChange(Sender: TObject);
procedure edtShortCutKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure evtMainIdle(Sender: TObject; var Done: Boolean);
procedure evtMainMinimize(Sender: TObject);
procedure actShowExecute(Sender: TObject);
procedure actConfigExecute(Sender: TObject);
procedure actCloseExecute(Sender: TObject);
procedure actAboutExecute(Sender: TObject);
procedure hkmHotkeyHotKeyPressed(HotKey: Cardinal; Index: Word);
procedure FormDestroy(Sender: TObject);
procedure actExecuteExecute(Sender: TObject);
procedure edtShortCutKeyPress(Sender: TObject; var Key: Char);
procedure actSelectChangeExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure lstShortCutKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure actHideExecute(Sender: TObject);
procedure actShortCutExecute(Sender: TObject);
procedure btnShortCutClick(Sender: TObject);
procedure actAddItemExecute(Sender: TObject);
procedure actEditItemExecute(Sender: TObject);
procedure actDeleteItemExecute(Sender: TObject);
procedure lblShortCutMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgBackgroundMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure tmrHideTimer(Sender: TObject);
procedure evtMainDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ntfMainDblClick(Sender: TObject);
procedure lstShortCutMouseActivate(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
procedure edtShortCutMouseActivate(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
procedure lblShortCutMouseActivate(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
procedure edtCommandLineKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure actOpenDirExecute(Sender: TObject);
procedure lstShortCutMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pmListPopup(Sender: TObject);
procedure tmrExitTimer(Sender: TObject);
procedure tmrCopyTimer(Sender: TObject);
procedure tmrFocusTimer(Sender: TObject);
procedure evtMainActivate(Sender: TObject);
procedure evtMainMessage(var Msg: tagMSG; var Handled: Boolean);
procedure evtMainShortCut(var Msg: TWMKey; var Handled: Boolean);
procedure actUpExecute(Sender: TObject);
procedure actDownExecute(Sender: TObject);
procedure MiddleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure actCopyCommandLineExecute(Sender: TObject);
procedure hkmHotkey3HotKeyPressed(HotKey: Cardinal; Index: Word);
private
m_IsShow: Boolean;
m_IsFirstShow: Boolean;
m_IsFirstDblClickIcon: Boolean;
m_LastShortCutPointerList: array[0..9] of Pointer;
m_LastShortCutCmdIndex: Integer;
m_LastShortCutListCount: Integer;
m_LastKeyIsNumKey: Boolean;
m_LastActiveTime: Cardinal;
m_IsExited: Boolean;
m_AgeOfFile: Integer;
m_NeedRefresh: Boolean;
m_IsTop: Boolean;
m_LastShortCutText: string;
function ApplyHotKey1: Boolean;
function ApplyHotKey2: Boolean;
function GetHotKeyString: string;
procedure GetLastCmdList;
procedure RestartHideTimer(Delay: Integer);
procedure StopTimer;
function DirAvailable: Boolean;
procedure RefreshOperationHint;
function GetLangList(List: TStringList): Boolean;
procedure RestartMe;
procedure DisplayShortCutItem(Item: TShortCutItem);
procedure ShowLatestShortCutList;
public
property IsExited: Boolean read m_IsExited;
end;
var
ALTRunForm: TALTRunForm;
const
WM_ALTRUN_ADD_SHORTCUT = WM_USER + 2000;
WM_ALTRUN_SHOW_WINDOW = WM_USER + 2001;
implementation
{$R *.dfm}
uses
untLogger,
frmConfig,
frmAbout,
frmShortCut,
frmShortCutMan,
frmLang;
procedure TALTRunForm.actAboutExecute(Sender: TObject);
var
AboutForm: TAboutForm;
hALTRun:HWND;
begin
TraceMsg('actAboutExecute()');
if DEBUG_MODE then
begin
hALTRun := Self.Handle;
hALTRun := FindWindow(nil, TITLE);
hALTRun := FindWindow('TALTRunForm', nil);
// hALTRun := FindWindowByCaption(TITLE);
SendMessage(hALTRun, WM_ALTRUN_ADD_SHORTCUT, 0, 0);
//SendMessage(Self.Handle, WM_ALTRUN_ADD_SHORTCUT, 0, 0);
Exit;
end;
try
AboutForm := TAboutForm.Create(Self);
AboutForm.Caption := Format('%s %s %s', [resAbout, TITLE, ALTRUN_VERSION]);
AboutForm.ShowModal;
finally
AboutForm.Free;
end;
end;
procedure TALTRunForm.actAddItemExecute(Sender: TObject);
begin
TraceMsg('actAddItemExecute()');
m_IsTop := False;
ShortCutMan.AddFileShortCut(edtShortCut.Text);
m_IsTop := True;
if m_IsShow then edtShortCutChange(Self);
end;
procedure TALTRunForm.actCloseExecute(Sender: TObject);
begin
TraceMsg('actCloseExecute()');
//保存窗体位置
if m_IsShow then
begin
WinTop := Self.Top;
WinLeft := Self.Left;
end;
//保存最近使用快捷方式的列表
LatestList := ShortCutMan.GetLatestShortCutIndexList;
HandleID := 0;
SaveSettings;
//若保留此行,在右键添加后,直接退出本程序,此新添快捷项将丢失
ShortCutMan.SaveShortCutList;
Application.Terminate;
end;
procedure TALTRunForm.actConfigExecute(Sender: TObject);
var
ConfigForm: TConfigForm;
lg: longint;
i: Cardinal;
LangList: TStringList;
IsNeedRestart: Boolean;
begin
TraceMsg('actConfigExecute()');
try
//取消HotKey以免冲突
hkmHotkey1.ClearHotKeys;
hkmHotkey2.ClearHotKeys;
ConfigForm := TConfigForm.Create(Self);
IsNeedRestart := False;
//调用当前配置
with ConfigForm do
begin
DisplayHotKey1(HotKeyStr1);
DisplayHotKey2(HotKeyStr2);
//AutoRun
chklstConfig.Checked[0] := AutoRun;
//AddToSendTo
chklstConfig.Checked[1] := AddToSendTo;
//EnableRegex
chklstConfig.Checked[2] := EnableRegex;
//MatchAnywhere
chklstConfig.Checked[3] := MatchAnywhere;
//EnableNumberKey
chklstConfig.Checked[4] := EnableNumberKey;
//IndexFrom0to9
chklstConfig.Checked[5] := IndexFrom0to9;
//RememberFavouratMatch
chklstConfig.Checked[6] := RememberFavouratMatch;
//ShowOperationHint
chklstConfig.Checked[7] := ShowOperationHint;
//ShowCommandLine
chklstConfig.Checked[8] := ShowCommandLine;
//ShowStartNotification
chklstConfig.Checked[9] := ShowStartNotification;
//ShowTopTen
chklstConfig.Checked[10] := ShowTopTen;
//PlayPopupNotify
chklstConfig.Checked[11] := PlayPopupNotify;
//ExitWhenExecute
chklstConfig.Checked[12] := ExitWhenExecute;
//ShowSkin
chklstConfig.Checked[13] := ShowSkin;
//ShowMeWhenStart
chklstConfig.Checked[14] := ShowMeWhenStart;
//ShowTrayIcon
chklstConfig.Checked[15] := ShowTrayIcon;
//ShowShortCutButton
chklstConfig.Checked[16] := ShowShortCutButton;
//ShowConfigButton
chklstConfig.Checked[17] := ShowConfigButton;
//ShowCloseButton
chklstConfig.Checked[18] := ShowCloseButton;
//ExecuteIfOnlyOne
chklstConfig.Checked[19] := ExecuteIfOnlyOne;
//edtBGFileName.Text := BGFileName;
StrToFont(TitleFontStr, lblTitleSample.Font);
StrToFont(KeywordFontStr, lblKeywordSample.Font);
StrToFont(ListFontStr, lblListSample.Font);
for i := Low(ListFormatList) to High(ListFormatList) do
cbbListFormat.Items.Add(ListFormatList[i]);
if cbbListFormat.Items.IndexOf(ListFormat) < 0 then
cbbListFormat.Items.Add(ListFormat);
cbbListFormat.ItemIndex := cbbListFormat.Items.IndexOf(ListFormat);
cbbListFormatChange(Sender);
lstAlphaColor.Selected := AlphaColor;
seAlpha.Value := Alpha;
seRoundBorderRadius.Value := RoundBorderRadius;
seFormWidth.Value := FormWidth;
//语言
try
cbbLang.Items.Add(DEFAULT_LANG);
cbbLang.ItemIndex := 0;
LangList := TStringList.Create;
if not GetLangList(LangList) then Exit;
if LangList.Count > 0 then
begin
for i := 0 to LangList.Count - 1 do
if cbbLang.Items.IndexOf(LangList.Strings[i]) < 0 then
cbbLang.Items.Add(LangList.Strings[i]);
for i := 0 to cbbLang.Items.Count - 1 do
if cbbLang.Items[i] = Lang then
begin
cbbLang.ItemIndex := i;
Break;
end;
end;
finally
LangList.Free;
end;
m_IsTop := False;
ShowModal;
m_IsTop := True;
//如果确认
case ModalResult of
mrOk:
begin
HotKeyStr1 := GetHotKey1;
HotKeyStr2 := GetHotKey2;
AutoRun := chklstConfig.Checked[0];
AddToSendTo := chklstConfig.Checked[1];
EnableRegex := chklstConfig.Checked[2];
MatchAnywhere := chklstConfig.Checked[3];
EnableNumberKey := chklstConfig.Checked[4];
IndexFrom0to9 := chklstConfig.Checked[5];
RememberFavouratMatch := chklstConfig.Checked[6];
ShowOperationHint := chklstConfig.Checked[7];
ShowCommandLine := chklstConfig.Checked[8];
ShowStartNotification := chklstConfig.Checked[9];
ShowTopTen := chklstConfig.Checked[10];
PlayPopupNotify := chklstConfig.Checked[11];
ExitWhenExecute := chklstConfig.Checked[12];
ShowSkin := chklstConfig.Checked[13];
ShowMeWhenStart := chklstConfig.Checked[14];
ShowTrayIcon := chklstConfig.Checked[15];
ShowShortCutButton := chklstConfig.Checked[16];
ShowConfigButton := chklstConfig.Checked[17];
ShowCloseButton := chklstConfig.Checked[18];
ExecuteIfOnlyOne := chklstConfig.Checked[19];
TitleFontStr := FontToStr(lblTitleSample.Font);
KeywordFontStr := FontToStr(lblKeywordSample.Font);
ListFontStr := FontToStr(lblListSample.Font);
ListFormat := cbbListFormat.Text;
if not IsNeedRestart then IsNeedRestart := (AlphaColor <> lstAlphaColor.Selected);
AlphaColor := lstAlphaColor.Selected;
if not IsNeedRestart then IsNeedRestart := (Alpha <> seAlpha.Value);
Alpha := Round(seAlpha.Value);
if not IsNeedRestart then IsNeedRestart := (RoundBorderRadius <> seRoundBorderRadius.Value);
RoundBorderRadius := Round(seRoundBorderRadius.Value);
if not IsNeedRestart then IsNeedRestart := (FormWidth <> seFormWidth.Value);
FormWidth := Round(seFormWidth.Value);
if not IsNeedRestart then IsNeedRestart := (Lang <> cbbLang.Text);
Lang := cbbLang.Text;
//不让修改背景图片的文件名
//BGFileName := edtBGFileName.Text;
//if BGFileName <> '' then
//begin
// if FileExists(BGFileName) then
// Self.imgBackground.Picture.LoadFromFile(BGFileName)
// else if FileExists(ExtractFilePath(Application.ExeName) + BGFileName) then
// Self.imgBackground.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + BGFileName)
// else
// Application.MessageBox(PChar(Format('File %s does not exist!',
// [BGFileName])), resInfo, MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
//end;
//保存新的项目
ShortCutMan.SaveShortCutList;
ShortCutMan.LoadShortCutList;
ShortCutMan.NeedRefresh := True;
end;
mrRetry:
begin
DeleteFile(ExtractFilePath(Application.ExeName) + TITLE + '.ini');
LoadSettings;
IsNeedRestart := True;
end;
else
ApplyHotKey1;
ApplyHotKey2;
Exit;
end;
//应用修改的配置
if (ModalResult = mrOk) or (ModalResult = mrRetry) then
begin
//SetAutoRun(TITLE, Application.ExeName, AutoRun);
SetAutoRunInStartUp(TITLE, Application.ExeName, AutoRun);
AddMeToSendTo(TITLE, AddToSendTo);
StrToFont(TitleFontStr, Self.lblShortCut.Font);
StrToFont(KeywordFontStr, Self.edtShortCut.Font);
StrToFont(ListFontStr, Self.lstShortCut.Font);
//应用快捷键
ApplyHotKey1;
ApplyHotKey2;
ntfMain.Hint := Format(resMainHint, [TITLE, ALTRUN_VERSION, #13#10, GetHotKeyString]);
if ShowSkin then
imgBackground.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + BGFileName)
else
imgBackground.Picture := nil;
//显示图标
ntfMain.IconVisible := ShowTrayIcon;
//按钮是否显示
btnShortCut.Visible := ShowShortCutButton;
btnConfig.Visible := ShowConfigButton;
btnClose.Visible := ShowCloseButton;
//根据按钮显示决定标题栏显示长度
//快捷项管理按钮
if ShowShortCutButton then
lblShortCut.Left := btnShortCut.Left + btnShortCut.Width
else
lblShortCut.Left := 0;
//配置按钮和关闭按钮
if ShowCloseButton then
begin
if ShowConfigButton then
begin
btnConfig.Left := btnClose.Left - btnConfig.Width - 10;
lblShortCut.Width := btnConfig.Left - lblShortCut.Left;
end
else
begin
lblShortCut.Width := btnClose.Left - lblShortCut.Left;
end;
end
else
begin
if ShowConfigButton then
begin
btnConfig.Left := Self.Width - btnConfig.Width - 10;
lblShortCut.Width := btnConfig.Left - lblShortCut.Left;
end
else
begin
lblShortCut.Width := Self.Width - lblShortCut.Left;
end
end;
//半透明效果
lg := getWindowLong(Handle, GWL_EXSTYLE);
lg := lg or WS_EX_LAYERED;
SetWindowLong(handle, GWL_EXSTYLE, lg);
SetLayeredWindowAttributes(handle, AlphaColor, Alpha, LWA_ALPHA or LWA_COLORKEY);
//圆角矩形窗体
SetWindowRgn(Handle, CreateRoundRectRgn(0, 0, Width, Height, RoundBorderRadius, RoundBorderRadius), True);
//应用语言修改
SetActiveLanguage;
//数字编号顺序
edtShortCutChange(Sender);
//显示命令行
if ShowCommandLine then
Self.Height := 250
else
Self.Height := 230;
SaveSettings;
if IsNeedRestart then
begin
Application.MessageBox(PChar(resRestartMeInfo),
PChar(resInfo), MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
RestartMe;
end;
end;
end;
finally
ConfigForm.Free;
end;
end;
procedure TALTRunForm.actCopyCommandLineExecute(Sender: TObject);
begin
if lstShortCut.ItemIndex>=0 then
begin
//SetClipboardText(TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]).CommandLine);
Clipboard.AsUnicodeText := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]).CommandLine;
edtCopy.Show;
tmrCopy.Enabled := True;
end;
end;
procedure TALTRunForm.actDeleteItemExecute(Sender: TObject);
var
itm: TShortCutItem;
Index: Integer;
begin
TraceMsg('actDeleteItemExecute(%d)', [lstShortCut.ItemIndex]);
if lstShortCut.ItemIndex < 0 then Exit;
itm := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]);
if Application.MessageBox(PChar(Format('%s %s(%s)?', [resDelete, itm.ShortCut, itm.Name])),
PChar(resInfo), MB_OKCANCEL + MB_ICONQUESTION + MB_TOPMOST) = IDOK then
begin
Index := ShortCutMan.GetShortCutItemIndex(itm);
ShortCutMan.DeleteShortCutItem(Index);
//不加这一句,一旦添加“1111”,再删除“1111”,会报错
m_LastShortCutListCount := 0;
//刷新
edtShortCutChange(Sender);
end;
end;
procedure TALTRunForm.actDownExecute(Sender: TObject);
begin
TraceMsg('actDownExecute');
with lstShortCut do
if Visible then
begin
if Count = 0 then Exit;
//列表上下走
if ItemIndex = -1 then
ItemIndex := 0
else
if ItemIndex = Count - 1 then
ItemIndex := 0
else
ItemIndex := ItemIndex + 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
m_LastShortCutCmdIndex := ItemIndex;
if ShowOperationHint
and (lstShortCut.ItemIndex >= 0)
and (Length(edtShortCut.Text) < 10)
and (lstShortCut.Items[lstShortCut.ItemIndex][2] in ['0'..'9']) then
edtHint.Text := Format(resRunNum,
[lstShortCut.Items[lstShortCut.ItemIndex][2],
lstShortCut.Items[lstShortCut.ItemIndex][2]]);
end;
end;
procedure TALTRunForm.actEditItemExecute(Sender: TObject);
var
ShortCutForm: TShortCutForm;
itm: TShortCutItem;
Index: Integer;
begin
TraceMsg('actEditItemExecute(%d)', [lstShortCut.ItemIndex]);
if lstShortCut.ItemIndex < 0 then Exit;
itm := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]);
Index := ShortCutMan.GetShortCutItemIndex(itm);
try
ShortCutForm := TShortCutForm.Create(Self);
with ShortCutForm do
begin
lbledtShortCut.Text := itm.ShortCut;
lbledtName.Text := itm.Name;
lbledtCommandLine.Text := itm.CommandLine;
rgParam.ItemIndex := Ord(itm.ParamType);
m_IsTop := False;
ShowModal;
m_IsTop := True;
if ModalResult = mrCancel then Exit;
//取得新的项目
itm.ShortCutType := scItem;
itm.ShortCut := lbledtShortCut.Text;
itm.Name := lbledtName.Text;
itm.CommandLine := lbledtCommandLine.Text;
itm.ParamType := TParamType(rgParam.ItemIndex);
//保存新的项目
ShortCutMan.SaveShortCutList;
ShortCutMan.LoadShortCutList;
//刷新
edtShortCutChange(Sender);
end;
finally
ShortCutForm.Free;
end;
end;
procedure TALTRunForm.actExecuteExecute(Sender: TObject);
var
cmd: string;
ret: Integer;
ShortCutForm: TShortCutForm;
Item: TShortCutItem;
ShellApplication: Variant;
i: Cardinal;
ch: Char;
begin
TraceMsg('actExecuteExecute(%d)', [lstShortCut.ItemIndex]);
//若下面有选中某项
if lstShortCut.Count > 0 then
begin
evtMainMinimize(Self);
//Self.Hide;
//WINEXEC//调用可执行文件
//winexec('command.com /c copy *.* c:\',SW_Normal);
//winexec('start abc.txt');
//ShellExecute或ShellExecuteEx//启动文件关联程序
//function executefile(const filename,params,defaultDir:string;showCmd:integer):THandle;
//ExecuteFile('C:\abc\a.txt','x.abc','c:\abc\',0);
//ExecuteFile('http://tingweb.yeah.net','','',0);
//ExecuteFile('mailto:tingweb@wx88.net','','',0);
//如果WinExec返回值小于32,就是失败,那就使用ShellExecute来搞
//这种发送键盘的方法并不太好,所以屏蔽掉
// for i := 1 to Length(cmd) do
// begin
// ch := UpCase(cmd[i]);
// case ch of
// 'A'..'Z': PostKeyEx32(ORD(ch), [], FALSE);
// '0'..'9': PostKeyEx32(ORD(ch), [], FALSE); R
// '.': PostKeyEx32(VK_DECIMAL, [], FALSE);
// '+': PostKeyEx32(VK_ADD, [], FALSE);
// '-': PostKeyEx32(VK_SUBTRACT, [], FALSE);
// '*': PostKeyEx32(VK_MULTIPLY, [], FALSE);
// '/': PostKeyEx32(VK_DIVIDE, [], FALSE);
// ' ': PostKeyEx32(VK_SPACE, [], FALSE);
// ';': PostKeyEx32(186, [], FALSE);
// '=': PostKeyEx32(187, [], FALSE);
// ',': PostKeyEx32(188, [], FALSE);
// '[': PostKeyEx32(219, [], FALSE);
// '\': PostKeyEx32(220, [], FALSE);
// ']': PostKeyEx32(221, [], FALSE);
// else
// ShowMessage(ch);
// end;
// //sleep(50);
// end;
//
// PostKeyEx32(VK_RETURN, [], FALSE);
//下面这种方法也不好
//如果一种方式无法运行,就换一种
//if WinExec(PChar(cmd), SW_SHOWNORMAL) < 33 then
//begin
// if ShellExecute(0, 'open', PChar(cmd), nil, nil, SW_SHOWNORMAL) < 33 then
// begin
// //写批处理的这招,先不用
// //WriteLineToFile('D:\My\Code\Delphi\HotRun\Bin\shit.bat', cmd);
// //if ShellExecute(0, 'open', 'D:\My\Code\Delphi\HotRun\Bin\shit.bat', nil, nil, SW_HIDE) < 33 then
// Application.MessageBox(PChar(Format('Can not execute "%s"', [cmd])), 'Warning', MB_OK + MB_ICONWARNING);
// end;
//end;
//执行快捷项
ShortCutMan.Execute(TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]), edtShortCut.Text);
//清空输入框
edtShortCut.Text := '';
//下面的方法,有时候键盘序列会发到其他窗口
//打开“开始/运行”对话框,发送键盘序列
//ShellApplication := CreateOleObject('Shell.Application');
//ShellApplication.FileRun;
//sleep(500);
//SendKeys(PChar(cmd), False, True);
//SendKeys('~', True, True); //回车
//如果需要执行完就退出
if ExitWhenExecute then tmrExit.Enabled := True;
end
else
//如果没有合适项目,则提示是否添加之
if Application.MessageBox(
PChar(Format(resNoItemAndAdd, [edtShortCut.Text])),
PChar(resInfo), MB_OKCANCEL + MB_ICONQUESTION) = IDOK then
actAddItemExecute(Sender);
end;
procedure TALTRunForm.actHideExecute(Sender: TObject);
begin
TraceMsg('actHideExecute()');
evtMainMinimize(Sender);
edtShortCut.Text := '';
end;
procedure TALTRunForm.actOpenDirExecute(Sender: TObject);
var
itm: TShortCutItem;
Index: Integer;
cmdobj: TCmdObject;
CommandLine: string;
SlashPos: Integer;
i: Cardinal;
begin
TraceMsg('actOpenDirExecute(%d)', [lstShortCut.ItemIndex]);
if lstShortCut.ItemIndex < 0 then Exit;
itm := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]);
Index := ShortCutMan.GetShortCutItemIndex(itm);
//if not (FileExists(itm.CommandLine) or DirectoryExists(itm.CommandLine)) then Exit;
cmdobj := TCmdObject.Create;
cmdobj.Param := '';
//cmdobj.Command := ExtractFileDir(RemoveQuotationMark(itm.CommandLine, '"'));
//去除前导的@/@+/@-
CommandLine := itm.CommandLine;
if Pos(SHOW_MAX_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_MAX_FLAG))
else if Pos(SHOW_MIN_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_MIN_FLAG))
else if Pos(SHOW_HIDE_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_HIDE_FLAG));
cmdobj.Command := RemoveQuotationMark(CommandLine, '"');
if (Pos('.\', itm.CommandLine) > 0) or (Pos('..\', itm.CommandLine) > 0) then
begin
TraceMsg('CommandLine = %s', [itm.CommandLine]);
TraceMsg('Application.ExeName = %s', [Application.ExeName]);
TraceMsg('WorkingDir = %s', [ExtractFilePath(Application.ExeName)]);
cmdobj.Command := ExtractFileDir(CommandLine);
cmdobj.WorkingDir := ExtractFilePath(Application.ExeName);
end
else if FileExists(ExtractFileDir(itm.CommandLine)) then
begin
cmdobj.Command := ExtractFileDir(CommandLine);
cmdobj.WorkingDir := ExtractFileDir(itm.CommandLine);
end
else
begin
SlashPos := 0;
if Length(cmdobj.Command) > 1 then
for i := Length(cmdobj.Command) - 1 downto 1 do
if cmdobj.Command[i] = '\' then
begin
SlashPos := i;
Break;
end;
if SlashPos > 0 then
begin
// 如果第一个字符是"
if cmdobj.Command[1] = '"' then
cmdobj.Command := (Copy(cmdobj.Command, 2, SlashPos - 1))
else
cmdobj.Command := (Copy(cmdobj.Command, 1, SlashPos));
cmdobj.WorkingDir := cmdobj.Command;
end
else
begin
cmdobj.Command := ExtractFileDir(cmdobj.Command);
cmdobj.WorkingDir := '';
end;
end;
ShortCutMan.Execute(cmdobj);
end;
procedure TALTRunForm.actSelectChangeExecute(Sender: TObject);
begin
TraceMsg('actSelectChangeExecute(%d)', [lstShortCut.ItemIndex]);
if lstShortCut.ItemIndex = -1 then Exit;
lblShortCut.Caption := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]).Name;
lblShortCut.Hint := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]).CommandLine;
//edtCommandLine.Hint := lblShortCut.Hint;
edtCommandLine.Text := resCMDLine + lblShortCut.Hint;
if DirAvailable then lblShortCut.Caption := '[' + lblShortCut.Caption + ']';
end;
procedure TALTRunForm.actShortCutExecute(Sender: TObject);
const
TEST_ITEM_COUNT = 10;
Test_Array: array[0..TEST_ITEM_COUNT - 1] of Integer = (3, 0, 8, 2, 8, 6, 1, 3, 0, 8);
var
ShortCutManForm: TShortCutManForm;
StringList: TStringList;
i: Cardinal;
str: string;
Item: TShortCutItem;
ret:Integer;
FileDate: Integer;
hALTRun:HWND;
begin
TraceMsg('actShortCutExecute()');
if DEBUG_MODE then
begin
//Randomize;
//StringList := TStringList.Create;
//try
// TraceMsg('- Before QuickSort');
//
// for i := 0 to TEST_ITEM_COUNT - 1 do
// begin
// Item := TShortCutItem.Create;
// with Item do
// begin
// ShortCutType := scItem;
// Freq := Test_Array[i]; //Random(TEST_ITEM_COUNT);
// Rank := Freq;
// Name := IntToStr(Rank);
// ParamType := ptNone;
//
// TraceMsg(' - [%d] = %d', [i, Freq]);
// end;
//
// StringList.AddObject(Item.Name, Item);
// end;
//
// ShortCutMan.QuickSort(StringList, 0, TEST_ITEM_COUNT - 1);
//
// TraceMsg('- After QuickSort');
//
// for i := 0 to TEST_ITEM_COUNT - 1 do
// begin
// Item := TShortCutItem(StringList.Objects[i]);
// with Item do
// begin
// TraceMsg(' - [%d] = %d', [i, Freq]);
// end;
//
// Item.Free;
// end;
//
// TraceMsg('- End QuickSort');
//finally
// StringList.Free;
//end;
//ret := ShellExecute(0, nil, PChar(GetEnvironmentVariable('windir')), nil, nil, SW_SHOWNORMAL);
//ret := WinExec('%windir%', 1);
//FileDate := FileAge('123.txt');
//FileDate := 975878736;
//SetFileModifyTime('123.txt', FileDateToDateTime(FileDate));
//hALTRun := FindWindowByCaption('ALTRun');
//ShowMessage(IntToStr(hALTRun));
//PostMessage(FindWindowByCaption('ALTRun'), WM_ALTRUN_ADD_SHORTCUT, 0, 0);
//m_IsFirstDblClickIcon := True;
//ntfMainDblClick(nil);
//edtShortCut.ImeMode := imOpen;
//TraceMsg('ImeMode = %d, ImeName = %s', [Ord(edtShortCut.ImeMode), edtShortCut.ImeName]);
SetEnvironmentVariable(PChar('MyTool'), PChar('C:\'));
Exit;
end;
try
ShortCutManForm := TShortCutManForm.Create(Self);
with ShortCutManForm do
begin
m_IsTop := False;
StopTimer;
ShowModal;
m_IsTop := True;
if ModalResult = mrOk then
begin
//刷新快捷项列表
ShortCutMan.LoadFromListView(lvShortCut);
ShortCutMan.SaveShortCutList;
ShortCutMan.LoadShortCutList;
if m_IsShow then
begin
edtShortCutChange(Sender);
try
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
end;
end;
end;
RestartHideTimer(HideDelay);
end;
finally
ShortCutManForm.Free;
end;
end;
procedure TALTRunForm.actShowExecute(Sender: TObject);
var
lg: longint;
WinMediaFileName, PopupFileName: string;
IsForeWindow: Boolean;
TryTimes: Integer;
OldTickCount: Cardinal;
begin
TraceMsg('actShowExecute()');
Self.Caption := TITLE;
if ParamForm <> nil then ParamForm.ModalResult := mrCancel;
ShortCutMan.LoadShortCutList;
//如果输入框有字,则清空再刷新
if (edtShortCut.Text <> '') then
begin
edtShortCut.Text := '';
end
else
begin
if m_IsFirstShow or m_NeedRefresh or ShortCutMan.NeedRefresh then
begin
m_NeedRefresh := False;
edtShortCutChange(Sender);
ShortCutMan.NeedRefresh := False;
end
else
begin
RefreshOperationHint;
if lstShortCut.Items.Count > 0 then
begin
lstShortCut.ItemIndex := 0;
lblShortCut.Caption := TShortCutItem(lstShortCut.Items.Objects[0]).Name;
if DirAvailable then lblShortCut.Caption := '[' + lblShortCut.Caption + ']';
end;
end;
end;
Self.Show;
if m_IsFirstShow then
begin
m_IsFirstShow := False;
//设置窗体位置
if (WinTop <= 0) or (WinLeft <= 0) then
begin
Self.Position := poScreenCenter;
end
else
begin
Self.Top := WinTop;
Self.Left := WinLeft;
Self.Width := FormWidth;
end;
//字体
StrToFont(TitleFontStr, lblShortCut.Font);
StrToFont(KeywordFontStr, edtShortCut.Font);
StrToFont(ListFontStr, lstShortCut.Font);
//修改背景图
if not FileExists(ExtractFilePath(Application.ExeName) + BGFileName) then
imgBackground.Picture.SaveToFile(ExtractFilePath(Application.ExeName) + BGFileName);
if ShowSkin then
imgBackground.Picture.LoadFromFile(ExtractFilePath(Application.ExeName) + BGFileName)
else
imgBackground.Picture := nil;
//按钮是否显示
btnShortCut.Visible := ShowShortCutButton;
btnConfig.Visible := ShowConfigButton;
btnClose.Visible := ShowCloseButton;
//根据按钮显示决定标题栏显示长度
//快捷项管理按钮
if ShowShortCutButton then
lblShortCut.Left := btnShortCut.Left + btnShortCut.Width
else
lblShortCut.Left := 0;
//配置按钮和关闭按钮
if ShowCloseButton then
begin
if ShowConfigButton then
begin
btnConfig.Left := btnClose.Left - btnConfig.Width - 10;
lblShortCut.Width := btnConfig.Left - lblShortCut.Left;
end
else
begin
lblShortCut.Width := btnClose.Left - lblShortCut.Left;
end;
end
else
begin
if ShowConfigButton then
begin
btnConfig.Left := Self.Width - btnConfig.Width - 10;
lblShortCut.Width := btnConfig.Left - lblShortCut.Left;
end
else
begin
lblShortCut.Width := Self.Width - lblShortCut.Left;
end
end;
//半透明效果
lg := getWindowLong(Handle, GWL_EXSTYLE);
lg := lg or WS_EX_LAYERED;
SetWindowLong(handle, GWL_EXSTYLE, lg);
//第二个参数是指定透明颜色
//第二个参数若为0则使用第四个参数设置alpha值,从0到255
SetLayeredWindowAttributes(handle, AlphaColor, Alpha, LWA_ALPHA or LWA_COLORKEY);
//圆角矩形窗体
SetWindowRgn(Handle, CreateRoundRectRgn(0, 0, Width, Height, RoundBorderRadius, RoundBorderRadius), True);
//获得最近使用快捷方式的列表
ShortCutMan.SetLatestShortCutIndexList(LatestList);
lstShortCut.Height := 10 * lstShortCut.ItemHeight;
//显示命令行
if ShowCommandLine then
Self.Height := 250 {Self.Height + 20}
else
Self.Height := 230 {Self.Height - 20};
{
edtCommandLine.Top := lstShortCut.Top + lstShortCut.Height + 6;
if ShowCommandLine then
begin
Self.Height := edtCommandLine.Top + edtCommandLine.Height + 6;
end
else
Self.Height := edtCommandLine.Top;
}
end;
//把窗体放到顶端
Application.Restore;
SetForegroundWindow(Application.Handle);
m_IsShow := True;
edtShortCut.SetFocus;
GetLastCmdList;
RestartHideTimer(HideDelay);
tmrFocus.Enabled := True;
//保存窗体位置
WinTop := Self.Top;
WinLeft := Self.Left;
//取得最近一次击键时间
m_LastActiveTime := GetTickCount;
m_IsTop := True;
//播放声音
if PlayPopupNotify then
begin
PopupFileName := ExtractFilePath(Application.ExeName) + 'Popup.wav';
//WinMediaFileName := GetEnvironmentVariable('windir') + '\Media\ding.wav';
if not FileExists(PopupFileName) then
//CopyFile(PChar(WinMediaFileName), PChar(PopupFileName), True);
ExtractRes('WAVE', 'PopupWav', 'Popup.wav');
if FileExists(PopupFileName) then
PlaySound(PChar(PopupFileName), 0, snd_ASYNC)
else
PlaySound(PChar('PopupWav'), HInstance, snd_ASYNC or SND_RESOURCE);
end;
end;
procedure TALTRunForm.actUpExecute(Sender: TObject);
begin
TraceMsg('actUpExecute');
with lstShortCut do
if Visible then
begin
if Count = 0 then Exit;
//列表上下走
if ItemIndex = -1 then
ItemIndex := Count - 1
else
if ItemIndex = 0 then
ItemIndex := Count - 1
else
ItemIndex := ItemIndex - 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
m_LastShortCutCmdIndex := ItemIndex;
if ShowOperationHint
and (lstShortCut.ItemIndex >= 0)
and (Length(edtShortCut.Text) < 10)
and (lstShortCut.Items[lstShortCut.ItemIndex][2] in ['0'..'9']) then
edtHint.Text := Format(resRunNum,
[lstShortCut.Items[lstShortCut.ItemIndex][2],
lstShortCut.Items[lstShortCut.ItemIndex][2]]);
end;
end;
function TALTRunForm.ApplyHotKey1: Boolean;
var
HotKeyVar: Cardinal;
begin
Result := False;
TraceMsg('ApplyHotKey1(%s)', [HotKeyStr1]);
HotKeyVar := TextToHotKey(HotKeyStr1, LOCALIZED_KEYNAMES);
if (HotKeyVar = 0) or (hkmHotkey1.AddHotKey(HotKeyVar) = 0) then
begin
Application.MessageBox(PChar(Format(resHotKeyError, [HotKeyStr1])),
PChar(resWarning), MB_OK + MB_ICONWARNING);
Exit;
end;
Result := True;
end;
function TALTRunForm.ApplyHotKey2: Boolean;
var
HotKeyVar: Cardinal;
begin
Result := False;
TraceMsg('ApplyHotKey2(%s)', [HotKeyStr2]);
HotKeyVar := TextToHotKey(HotKeyStr2, LOCALIZED_KEYNAMES);
if (HotKeyVar = 0) or (hkmHotkey2.AddHotKey(HotKeyVar) = 0) then
begin
if (HotKeyStr2 <> '') and (HotKeyStr2 <> resVoidHotKey) then
begin
Application.MessageBox(PChar(Format(resHotKeyError, [HotKeyStr2])),
PChar(resWarning), MB_OK + MB_ICONWARNING);
HotKeyStr2 := '';
end;
Exit;
end;
Result := True;
end;
procedure TALTRunForm.btnShortCutClick(Sender: TObject);
begin
TraceMsg('btnShortCutClick()');
if DEBUG_MODE then
begin
if ShortCutMan.Test then
ShowMessage('True')
else
ShowMessage('False');
end
else
begin
actShortCutExecute(Sender);
if m_IsShow then
try
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
end;
end;
end;
function TALTRunForm.DirAvailable: Boolean;
var
itm: TShortCutItem;
Index: Integer;
CommandLine: string;
SlashPos: Integer;
i: Cardinal;
begin
Result := False;
if lstShortCut.ItemIndex < 0 then Exit;
itm := TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]);
Index := ShortCutMan.GetShortCutItemIndex(itm);
//去除前导的@/@+/@-
CommandLine := itm.CommandLine;
if Pos(SHOW_MAX_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_MAX_FLAG))
else if Pos(SHOW_MIN_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_MIN_FLAG))
else if Pos(SHOW_HIDE_FLAG, CommandLine) = 1 then
CommandLine := CutLeftString(CommandLine, Length(SHOW_HIDE_FLAG));
CommandLine := RemoveQuotationMark(CommandLine, '"');
if Pos('\\', CommandLine) > 0 then Exit;
if (FileExists(CommandLine) {or DirectoryExists(CommandLine)}) then
Result := True
else
begin
if Pos('.\', CommandLine) = 1 then
Result := True
else
begin
// 查找最后一个"\",以此来定路径
SlashPos := 0;
if Length(CommandLine) > 1 then
for i := Length(CommandLine) - 1 downto 1 do
if CommandLine[i] = '\' then
begin
SlashPos := i;
Break;
end;
if SlashPos > 0 then
begin
// 如果第一个字符是"
if CommandLine[1] = '"' then
Result := DirectoryExists(Copy(CommandLine, 2, SlashPos - 1))
else
Result := DirectoryExists(Copy(CommandLine, 1, SlashPos));
end
else
Result := False;
end;
end;
if Result then
TraceMsg('DirAvailable(%s) = True', [itm.CommandLine])
else
TraceMsg('DirAvailable(%s) = False', [itm.CommandLine]);
end;
procedure TALTRunForm.DisplayShortCutItem(Item: TShortCutItem);
begin
TraceMsg('DisplayShortCutItem()');
lblShortCut.Caption := Item.Name;
lblShortCut.Hint := Item.CommandLine;
edtCommandLine.Text := resCMDLine + Item.CommandLine;
if DirAvailable then lblShortCut.Caption := '[' + Item.Name + ']';
end;
procedure TALTRunForm.edtCommandLineKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
TraceMsg('edtCommandLineKeyDown( #%d = %s )', [Key, Chr(Key)]);
if not ((ssShift in Shift) or (ssAlt in Shift) or (ssCtrl in Shift)) then
case Key of
//回车
13: ;
VK_PRIOR, VK_NEXT: ;
else
if m_IsShow then
begin
//传到这里的键,都转发给edtShortCut
PostMessage(edtShortCut.Handle, WM_KEYDOWN, Key, 0);
try
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
end;
end;
end;
end;
procedure TALTRunForm.MiddleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbMiddle then
begin
actExecuteExecute(Sender);
end;
end;
procedure TALTRunForm.edtShortCutChange(Sender: TObject);
var
i, j, k: Cardinal;
Rank, ExistRank: Integer;
IsInserted: Boolean;
StringList: TStringList;
HintIndex: Integer;
begin
// 有时候内容没有变化,却触发这个消息,那是因为有人主动调用它了
//if edtShortCut.Text = m_LastShortCutText then Exit;
//m_LastShortCutText := edtShortCut.Text;
TraceMsg('edtShortCutChange(%s)', [edtShortCut.Text]);
lblShortCut.Caption := '';
lblShortCut.Hint := '';
lstShortCut.Hint := '';
edtCommandLine.Text := '';
lstShortCut.Clear;
//更新列表
try
StringList := TStringList.Create;
//lstShortCut.Hide;
if ShortCutMan.FilterKeyWord(edtShortCut.Text, StringList) then
begin
if ShowTopTen then
begin
for i := 0 to 9 do
if i >= StringList.Count then
Break
else
lstShortCut.Items.AddObject(StringList[i], StringList.Objects[i])
end
else
lstShortCut.Items.Assign(StringList);
end;
finally
StringList.Free;
end;
//显示第一项
if lstShortCut.Count = 0 then
begin
lblShortCut.Caption := '';
lblShortCut.Hint := '';
lstShortCut.Hint := '';
edtCommandLine.Text := '';
//看最后一个字符是否是数字0-9
if EnableNumberKey and m_LastKeyIsNumKey then
if (edtShortCut.Text[Length(edtShortCut.Text)] in ['0'..'9']) then
begin
k := StrToInt(edtShortCut.Text[Length(edtShortCut.Text)]);
if IndexFrom0to9 then
begin
if k <= m_LastShortCutListCount - 1 then
begin
evtMainMinimize(Self);
ShortCutMan.Execute(TShortCutItem(m_LastShortCutPointerList[k]),
Copy(edtShortCut.Text, 1, Length(edtShortCut.Text) - 1));
edtShortCut.Text := '';
end;
end
else
begin
if k = 0 then k := 10;
if k <= m_LastShortCutListCount then
begin
evtMainMinimize(Self);
ShortCutMan.Execute(TShortCutItem(m_LastShortCutPointerList[k - 1]),
Copy(edtShortCut.Text, 1, Length(edtShortCut.Text) - 1));
edtShortCut.Text := '';
end;
end;
end;
//最后一个如果是空格
if (edtShortCut.Text <> '') and (edtShortCut.Text[Length(edtShortCut.Text)] in [' ']) then
begin
if (m_LastShortCutListCount > 0)
and (m_LastShortCutCmdIndex >= 0)
and (m_LastShortCutCmdIndex < m_LastShortCutListCount) then
begin
evtMainMinimize(Self);
ShortCutMan.Execute(TShortCutItem(m_LastShortCutPointerList[m_LastShortCutCmdIndex]),
Copy(edtShortCut.Text, 1, Length(edtShortCut.Text) - 1));
edtShortCut.Text := '';
//如果需要执行完就退出
if ExitWhenExecute then tmrExit.Enabled := True;
end;
end;
end
else
begin
lstShortCut.ItemIndex := 0;
lblShortCut.Caption := TShortCutItem(lstShortCut.Items.Objects[0]).Name;
lblShortCut.Hint := TShortCutItem(lstShortCut.Items.Objects[0]).CommandLine;
edtCommandLine.Text := resCMDLine + lblShortCut.Hint;
//如果只有一项就立即执行
if ExecuteIfOnlyOne and (lstShortCut.Count = 1) then
begin
actExecuteExecute(Sender);
end;
end;
//如果可以打开文件夹,标记下
if DirAvailable then lblShortCut.Caption := '[' + lblShortCut.Caption + ']';
//刷新上一次的列表
GetLastCmdList;
//刷新提示
RefreshOperationHint;
end;
procedure TALTRunForm.edtShortCutKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Index: Integer;
begin
TraceMsg('edtShortCutKeyDown( #%d = %s )', [Key, Chr(Key)]);
m_LastKeyIsNumKey := False;
//关闭tmrFocus
tmrFocus.Enabled := False;
case Key of
{ VK_UP:
with lstShortCut do
if Visible then
begin
//为了防止向上键导致光标位置移动,故吞掉之
Key := VK_NONAME;
//列表上下走
if ItemIndex = -1 then
ItemIndex := Count - 1
else
if ItemIndex = 0 then
ItemIndex := Count - 1
else
ItemIndex := ItemIndex - 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
end;
VK_DOWN:
with lstShortCut do
if Visible then
begin
//为了防止向下键导致光标位置移动,故吞掉之
Key := VK_NONAME;
//列表上下走
if ItemIndex = -1 then
ItemIndex := 0
else
if ItemIndex = Count - 1 then
ItemIndex := 0
else
ItemIndex := ItemIndex + 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
end;
}
VK_PRIOR:
with lstShortCut do
begin
Key := VK_NONAME;
PostMessage(lstShortCut.Handle, WM_KEYDOWN, VK_PRIOR, 0);
end;
VK_NEXT:
with lstShortCut do
begin
Key := VK_NONAME;
PostMessage(lstShortCut.Handle, WM_KEYDOWN, VK_NEXT, 0);
end;
//数字键0-9,和小键盘数字键. ALT+Num 或 CTRL+Num 都可以执行
48..57, 96..105:
begin
m_LastKeyIsNumKey := True;
if (ssCtrl in Shift) or (ssAlt in Shift) then
begin
if Key >= 96 then
Index := Key - 96
else
Index := Key - 48;
//看看数字是否超出已有总数
if IndexFrom0to9 and (Index > lstShortCut.Count - 1) then Exit;
if (not IndexFrom0to9) and (Index > lstShortCut.Count) then Exit;
evtMainMinimize(Self);
if IndexFrom0to9 then
ShortCutMan.Execute(TShortCutItem(lstShortCut.Items.Objects[Index]), edtShortCut.Text)
else
ShortCutMan.Execute(TShortCutItem(lstShortCut.Items.Objects[(Index + 9) mod 10]), edtShortCut.Text);
edtShortCut.Text := '';
end;
end;
//分号键 = No.2 , '号键 = No.3
186, 222:
begin
if Key = 186 then
Index := 2
else
Index := 3;
//看看数字是否超出已有总数
if IndexFrom0to9 and (Index > lstShortCut.Count - 1) then Exit;
if (not IndexFrom0to9) and (Index > lstShortCut.Count) then Exit;
evtMainMinimize(Self);
if IndexFrom0to9 then
ShortCutMan.Execute(TShortCutItem(lstShortCut.Items.Objects[Index]), edtShortCut.Text)
else
ShortCutMan.Execute(TShortCutItem(lstShortCut.Items.Objects[(Index + 9) mod 10]), edtShortCut.Text);
edtShortCut.Text := '';
end;
//CTRL+D,打开文件夹
68:
begin
if (ssCtrl in Shift) then
begin
KillMessage(Self.Handle, WM_CHAR);
if not DirAvailable then Exit;
evtMainMinimize(Self);
actOpenDirExecute(Sender);
edtShortCut.Text := '';
end;
end;
//CTRL+C,复制CommandLine
67:
begin
if (ssCtrl in Shift) then
begin
//这个方法对于中文是乱码,必须用Unicode来搞
//Clipboard.SetTextBuf(PChar(TShortCutItem(lstShortCut.Items.Objects[lstShortCut.ItemIndex]).CommandLine));
actCopyCommandLineExecute(Sender);
end;
end;
//CTRL+L,列出最近使用的列表(最多只取10个)
76:
begin
if (ssCtrl in Shift) then
begin
ShowLatestShortCutList;
KillMessage(Self.Handle, WM_CHAR);
end;
end;
VK_ESCAPE:
begin
//如果不为空,就清空,否则隐藏
if edtShortCut.Text = '' then
evtMainMinimize(Self)
else
edtShortCut.Text := '';
end;
end;
if ShowOperationHint
and (lstShortCut.ItemIndex >= 0)
and (Length(edtShortCut.Text) < 10)
and (lstShortCut.Items[lstShortCut.ItemIndex][2] in ['0'..'9']) then
edtHint.Text := Format(resRunNum,
[lstShortCut.Items[lstShortCut.ItemIndex][2],
lstShortCut.Items[lstShortCut.ItemIndex][2]]);
end;
procedure TALTRunForm.edtShortCutKeyPress(Sender: TObject; var Key: Char);
begin
TraceMsg('edtShortCutKeyPress(%d)', [Key]);
// 看起来这块儿根本执行不到
Exit;
//如果回车,就执行程序
if Key = #13 then
begin
Key := #0;
actExecuteExecute(Sender);
end;
end;
procedure TALTRunForm.edtShortCutMouseActivate(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
begin
TraceMsg('edtShortCutMouseActivate()');
RestartHideTimer(HideDelay);
end;
procedure TALTRunForm.evtMainActivate(Sender: TObject);
begin
TraceMsg('evtMainActivate()');
RestartHideTimer(HideDelay);
end;
procedure TALTRunForm.evtMainDeactivate(Sender: TObject);
var
IsActivated: Boolean;
begin
TraceMsg('evtMainDeactivate(%d)', [GetTickCount - m_LastActiveTime]);
// 失去焦点就一律隐藏
evtMainMinimize(Sender);
edtShortCut.Text := '';
//如果失去焦点,且离上一次击键超过一定时间,就隐藏
// if (GetTickCount - m_LastActiveTime) > 500 then
// begin
// TraceMsg('Lost focus for a long time, so hide me');
//
// evtMainMinimize(Sender);
// edtShortCut.Text := '';
// end
// else
// begin
// if m_IsShow then
// begin
// //TraceMsg('Lost focus, try to activate me');
//
// //tmrFocus.Enabled := True;
// Exit;
// {
// IsActivated := False;
// while not IsActivated do
// begin
// TraceMsg('SetForegroundWindow failed, try again');
// IsActivated := SetForegroundWindow(Application.Handle);
// Sleep(100);
// Application.HandleMessage;
// end;
//
// TraceMsg('Application.Active = %s', [BoolToStr(Application.Active)]);
//
// edtShortCut.SetFocus;
// RestartHideTimer(HideDelay);
// }
// end;
//
// //SetActiveWindow(Application.Handle);
// //SetForegroundWindow(Application.Handle);
// //Self.Show;
// //Self.SetFocus;
//// try
//// edtShortCut.SetFocus;
//// except
//// TraceErr('edtShortCut.SetFocus = Fail');
//// end;
////
//// RestartHideTimer(1);
// end;
end;
procedure TALTRunForm.evtMainIdle(Sender: TObject; var Done: Boolean);
begin
ReduceWorkingSize;
end;
procedure TALTRunForm.evtMainMessage(var Msg: tagMSG; var Handled: Boolean);
var
FileName: string;
begin
{
// 本来想防止用户乱用输入法的,现在看来没必要
case Msg.message of
WM_INPUTLANGCHANGEREQUEST:
begin
TraceMsg('WM_INPUTLANGCHANGEREQUEST(%d, %d)',[Msg.wParam, Msg.lParam]);
if AllowIMEinEditShortCut then
Handled := False
else
begin
if edtShortCut.Focused then
begin
TraceMsg('edtShortCut.Focused = True');
Handled := True;
end
else
begin
TraceMsg('edtShortCut.Focused = False');
Handled := False;
end;
end;
end;
end;
}
case Msg.message of
WM_SYSCOMMAND: //点击关闭按钮
if Msg.WParam = SC_CLOSE then
begin
if DEBUG_MODE then
actCloseExecute(Self) //如果Debug模式,可以Alt-F4关闭
else
begin
evtMainMinimize(Self); //正常模式,仅仅隐藏
edtShortCut.Text := '';
end
end
else
inherited;
WM_QUERYENDSESSION, WM_ENDSESSION: //系统关机
begin
TraceMsg('System shutdown');
actCloseExecute(Self);
inherited;
end;
WM_MOUSEWHEEL:
begin
if m_IsTop then
begin
if Msg.wParam > 0 then
PostMessage(lstShortCut.Handle, WM_KEYDOWN, VK_UP, 0)
else
PostMessage(lstShortCut.Handle, WM_KEYDOWN, VK_DOWN, 0);
end;
Handled := False;
end;
end;
end;
procedure TALTRunForm.evtMainMinimize(Sender: TObject);
begin
inherited;
TraceMsg('evtMainMinimize()');
edtCopy.Visible := False;
m_IsShow := False;
self.Hide;
StopTimer;
end;
procedure TALTRunForm.evtMainShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
// 在ActionList中创建actUp和actDown,分别对应SecondaryShortCuts为Shift+Tab和Tab
end;
procedure TALTRunForm.FormActivate(Sender: TObject);
begin
TraceMsg('FormActivate()');
RestartHideTimer(HideDelay);
end;
procedure TALTRunForm.FormCreate(Sender: TObject);
var
lg: longint;
LangForm: TLangForm;
LangList: TStringList;
i: Cardinal;
hALTRun: HWND;
FileName: string;
begin
Self.Caption := TITLE;
//初始化不显示图标
ntfMain.IconVisible := False;
//窗体防闪
Self.DoubleBuffered := True;
lstShortCut.DoubleBuffered := True;
edtShortCut.DoubleBuffered := True;
edtHint.DoubleBuffered := True;
edtCommandLine.DoubleBuffered := True;
edtCopy.DoubleBuffered := True;
//Load 配置
//LoadSettings;
m_IsExited := False;
//如果是第一次使用,提示选择语言
if IsRunFirstTime then
begin
try
LangForm := TLangForm.Create(Self);
LangForm.cbbLang.Items.Add(DEFAULT_LANG);
LangForm.cbbLang.ItemIndex := 0;
LangList := TStringList.Create;
if GetLangList(LangList) then
begin
if LangList.Count > 0 then
begin
for i := 0 to LangList.Count - 1 do
if LangForm.cbbLang.Items.IndexOf(LangList.Strings[i]) < 0 then
LangForm.cbbLang.Items.Add(LangList.Strings[i]);
for i := 0 to LangForm.cbbLang.Items.Count - 1 do
if LangForm.cbbLang.Items[i] = Lang then
begin
LangForm.cbbLang.ItemIndex := i;
Break;
end;
end;
end;
if LangList.Count > 0 then
begin
// 专门为了简体中文
if Lang = '简体中文' then
LangForm.Caption := '请选择界面语言';
LangForm.ShowModal;
if LangForm.ModalResult = mrOk then
begin
Lang := LangForm.cbbLang.Text;
SetActiveLanguage;
end
else
begin
DeleteFile(ExtractFilePath(Application.ExeName) + TITLE + '.ini');
Halt(1);
end;
end;
finally
LangList.Free;
LangForm.Free;
end;
end
else
begin
SetActiveLanguage;
end;
//Load 快捷方式
ShortCutMan := TShortCutMan.Create;
ShortCutMan.LoadShortCutList;
m_AgeOfFile := FileAge(ShortCutMan.ShortCutFileName);
//初始化上次列表
m_LastShortCutCmdIndex := -1;
m_LastKeyIsNumKey := False;
//若有参数,则判断之
if ParamStr(1) <> '' then
begin
//自动重启软件
if ParamStr(1) = RESTART_FLAG then
begin
Sleep(2000);
end
//删除软件时清理环境
else if ParamStr(1) = CLEAN_FLAG then
begin
if Application.MessageBox(PChar(resCleanConfirm), PChar(resInfo),
MB_YESNO + MB_ICONQUESTION + MB_TOPMOST) = IDYES then
begin
SetAutoRun(TITLE, '', False);
SetAutoRunInStartUp(TITLE, '', False);
AddMeToSendTo(TITLE, False);
end;
Application.Terminate;
Exit;
end
else
//添加快捷方式
begin
Self.Caption := TITLE + ' - Add ShortCut';
{
hALTRun := FindWindow('TALTRunForm', TITLE);
if hALTRun <> 0 then
begin
SendMessage(hALTRun, WM_ALTRUN_ADD_SHORTCUT, 0, 0);
//等待文件被写入,从而时间更改,以此为判断依据
while FileAge(ShortCutMan.ShortCutFileName) = m_AgeOfFile do
begin
Application.HandleMessage;
end;
//此时可以重载文件
ShortCutMan.LoadShortCutList;
end;
}
//读取当前的快捷项列表文件,如果ALTRun已经运行,
//则通过 WM_ALTRUN_ADD_SHORTCUT 将快捷项字符串发送过去
//如果ALTRun并未启动,则直接保存到快捷项列表文件中
//处理长文件名, 对于路径中有空格的,前后带上""
FileName := ParamStr(1);
if Pos(' ', FileName) > 0 then FileName := '"' + FileName + '"';
if DEBUG_MODE then
ShowMessageFmt('Add %s', [FileName]);
//查找ALTRun, 窗口不好查找,直接读取INI文件
//hend;ALTRun := FindWindow('TALTRunForm', TITLE);
hALTRun := HandleID;
if (hALTRun <> 0) and IsWindow(hALTRun) then
begin
//Application.MessageBox(PChar(Format('ALTRun is running = %d', [hALTRun])),
// 'Debug', MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
SendMessage(hALTRun, WM_SETTEXT, 1, Integer(PChar(FileName)));
end
else
begin
//Application.MessageBox(PChar('ALTRun is NOT running'),
// 'Debug', MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
ShortCutMan.LoadShortCutList;
ShortCutMan.AddFileShortCut(FileName);
end;
m_IsExited := True;
Application.Terminate;
Exit;
end;
end;
if IsRunningInstance('ALTRUN_MUTEX') then
begin
// 发送消息,让ALTRun显示出来
SendMessage(HandleID, WM_ALTRUN_SHOW_WINDOW, 0, 0);
Halt(1);
//Application.Terminate;
//Exit;
end;
//LOG
//InitLogger(DEBUG_MODE,DEBUG_MODE, False);
InitLogger(DEBUG_MODE,False, False);
//Trace
TraceMsg('FormCreate()');
//判断是否是Vista
TraceMsg('OS is Vista = %s', [BoolToStr(IsVista)]);
//干掉老的HotRun的启动项和SendTo
if LowerCase(ExtractFilePath(GetAutoRunItemPath('HotRun')))
= LowerCase(ExtractFilePath(Application.ExeName)) then
SetAutoRun('HotRun', '', False);
if LowerCase(ExtractFilePath(GetAutoRunItemPath('HotRun.exe')))
= LowerCase(ExtractFilePath(Application.ExeName)) then
begin
SetAutoRun('HotRun.exe', '', False);
SetAutoRunInStartUp('HotRun.exe', '', False);
end;
if LowerCase(ExtractFilePath(ResolveLink(GetSendToDir + '\HotRun.lnk')))
= LowerCase(ExtractFilePath(Application.ExeName)) then
AddMeToSendTo('HotRun', False);
if FileExists(ExtractFilePath(Application.ExeName) + 'HotRun.ini') then
RenameFile(ExtractFilePath(Application.ExeName) + 'HotRun.ini',
ExtractFilePath(Application.ExeName) + TITLE + '.ini');
if LowerCase(ExtractFilePath(GetAutoRunItemPath('ALTRun.exe')))
= LowerCase(ExtractFilePath(Application.ExeName)) then
begin
SetAutoRun('ALTRun.exe', '', False);
SetAutoRunInStartUp('ALTRun.exe', '', False);
end;
//配置设置
ApplyHotKey1;
ApplyHotKey2;
//TODO: 暂时以ALT+L作为调用最近一次快捷项的热键
hkmHotkey3.AddHotKey(TextToHotKey(LastItemHotKeyStr, LOCALIZED_KEYNAMES));
//配置菜单语言
actShow.Caption := resMenuShow;
actShortCut.Caption := resMenuShortCut;
actConfig.Caption := resMenuConfig;
actAbout.Caption := resMenuAbout;
actClose.Caption := resMenuClose;
//配置Hint
btnShortCut.Hint := resBtnShortCutHint;
btnConfig.Hint := resBtnConfigHint;
btnClose.Hint := resBtnFakeCloseHint;
edtShortCut.Hint := resEdtShortCutHint;
//先删除后增加,目的是防止有人放到别的目录运行,导致出现多个启动项
SetAutoRun(TITLE, Application.ExeName, False);
SetAutoRunInStartUp(TITLE, Application.ExeName, False);
//如果是第一次使用,提示是否添加到自动启动
if IsRunFirstTime then
AutoRun := (Application.MessageBox(PChar(resAutoRunWhenStart),
PChar(resInfo), MB_YESNO + MB_ICONQUESTION + MB_TOPMOST) = IDYES);
//SetAutoRun(TITLE, Application.ExeName, AutoRun);
SetAutoRunInStartUp(TITLE, Application.ExeName, AutoRun);
AddMeToSendTo(TITLE, False);
//如果是第一次使用,提示是否添加到发送到
if IsRunFirstTime then
AddToSendTo := (Application.MessageBox(PChar(resAddToSendToMenu),
PChar(resInfo), MB_YESNO + MB_ICONQUESTION + MB_TOPMOST) = IDYES);
//添加到发送到
AddMeToSendTo(TITLE, AddToSendTo);
//保存设置
HandleID := Self.Handle;
SaveSettings;
//如果是第一次使用,重启一次以保证右键发送到不受影响
if IsRunFirstTime then
begin
RestartMe;
Exit;
end;
//第一次显示
m_IsFirstShow := True;
//第一次双击图标
m_IsFirstDblClickIcon := True;
//显示图标
ntfMain.IconVisible := ShowTrayIcon;
//显示按钮
btnShortCut.Visible := ShowShortCutButton;
btnConfig.Visible := ShowConfigButton;
btnClose.Visible := ShowCloseButton;
//提示
if ShowStartNotification then
ntfMain.ShowBalloonHint(resInfo,
Format(resStarted + #13#10 + resPressKeyToShowMe,
[TITLE, ALTRUN_VERSION, GetHotKeyString]), bitInfo, 5);
//浮动提示
ntfMain.Hint := Format(resMainHint, [TITLE, ALTRUN_VERSION, #13#10, GetHotKeyString]);
//需要刷新
m_NeedRefresh := True;
if ShowMeWhenStart then actShowExecute(Sender);
end;
procedure TALTRunForm.FormDestroy(Sender: TObject);
begin
//ShortCutMan.SaveShortCutList;
//如果是右键添加启动的程序,保存文件时,不改变修改时间
//这样正常运行的主程序不需要
//if m_IsExited then FileSetDate(ShortCutMan.ShortCutFileName, m_AgeOfFile);
ShortCutMan.Free;
end;
procedure TALTRunForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
TraceMsg('FormKeyDown( #%d = %s )', [Key, Chr(Key)]);
//取得最近一次击键时间
m_LastActiveTime := GetTickCount;
//关闭tmrFocus
tmrFocus.Enabled := False;
//重起Timer
RestartHideTimer(HideDelay);
//如果命令行获得焦点,就什么也不管
if edtCommandLine.Focused then Exit;
case Key of
VK_UP:
with lstShortCut do
begin
//为了防止向上键导致光标位置移动,故吞掉之
Key := VK_NONAME;
if Count = 0 then Exit;
//列表上下走
if ItemIndex = -1 then
ItemIndex := Count - 1
else
if ItemIndex = 0 then
ItemIndex := Count - 1
else
ItemIndex := ItemIndex - 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
m_LastShortCutCmdIndex := ItemIndex;
end;
VK_DOWN:
with lstShortCut do
begin
//为了防止向下键导致光标位置移动,故吞掉之
Key := VK_NONAME;
if Count = 0 then Exit;
//列表上下走
if ItemIndex = -1 then
ItemIndex := 0
else
if ItemIndex = Count - 1 then
ItemIndex := 0
else
ItemIndex := ItemIndex + 1;
DisplayShortCutItem(TShortCutItem(Items.Objects[ItemIndex]));
m_LastShortCutCmdIndex := ItemIndex;
end;
VK_F1:
begin
Key := VK_NONAME;
actAboutExecute(Sender);
end;
VK_F2:
begin
Key := VK_NONAME;
actEditItemExecute(Sender);
end;
VK_INSERT:
begin
Key := VK_NONAME;
actAddItemExecute(Sender);
end;
VK_DELETE:
begin
if lstShortCut.ItemIndex >= 0 then
begin
Key := VK_NONAME;
actDeleteItemExecute(Sender);
end;
end;
VK_ESCAPE:
begin
Key := VK_NONAME;
//如果不为空,就清空,否则隐藏
if edtShortCut.Text = '' then
evtMainMinimize(Self)
else
edtShortCut.Text := '';
end;
{分别对actConfig和actShortCut分配了快捷键
//ALT+C,显示配置窗口
$43:
begin
if (ssAlt in Shift) then actConfigExecute(Sender);
end;
//ALT+S,显示快捷键列表
$53:
begin
if (ssAlt in Shift) then actShortCutExecute(Sender);
end;
}
else
begin
if m_IsShow then
try
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
end;
end;
end;
end;
procedure TALTRunForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
TraceMsg('FormKeyPress(%s)', [Key]);
//关闭tmrFocus
tmrFocus.Enabled := False;
case Key of
//如果回车,就执行程序
#13:
begin
Key := #0;
if Self.Visible then actExecuteExecute(Sender);
end;
//如果ESC,就吞掉
#27:
begin
Key := #0;
end;
end;
end;
function TALTRunForm.GetHotKeyString: string;
begin
if (HotKeyStr2 = '') or (HotKeyStr2 = resVoidHotKey) then
Result := HotKeyStr1
else
Result := Format('%s %s %s', [HotKeyStr1, resWordOr, HotKeyStr2]);
end;
function TALTRunForm.GetLangList(List: TStringList): Boolean;
var
i: Cardinal;
FileList: TStringList;
begin
TraceMsg('GetLangList()');
Result := False;
try
FileList := TStringList.Create;
List.Clear;
if GetFileListInDir(FileList, ExtractFileDir(Application.ExeName), 'lang', False) then
begin
if FileList.Count > 0 then
for i := 0 to FileList.Count - 1 do
List.Add(Copy(FileList.Strings[i], 1, Length(FileList.Strings[i]) - 5));
Result := True;
end
else
Result := False;
finally
FileList.Free;
end;
end;
procedure TALTRunForm.GetLastCmdList;
var
i, n: Cardinal;
ShortCutItem: TShortCutItem;
begin
TraceMsg('GetLastCmdList()');
m_LastShortCutListCount := 0;
m_LastShortCutCmdIndex := -1;
if lstShortCut.Count > 0 then
begin
m_LastShortCutCmdIndex := lstShortCut.ItemIndex;
if lstShortCut.Count > 10 then
n := 10
else
n := lstShortCut.Count;
for i := 0 to n - 1 do
begin
if lstShortCut.Items.Objects[i] <> nil then
begin
m_LastShortCutPointerList[m_LastShortCutListCount] := Pointer(lstShortCut.Items.Objects[i]);
Inc(m_LastShortCutListCount);
end;
end;
end;
end;
procedure TALTRunForm.hkmHotkey3HotKeyPressed(HotKey: Cardinal; Index: Word);
var
Buf: array[0..254] of Char;
StringList: TStringList;
begin
TraceMsg('hkmHotkey3HotKeyPressed(%d)', [HotKey]);
// 取得当前剪贴板中的文字
ShortCutMan.Param[0] := Clipboard.AsUnicodeText;
// 取得当前前台窗体ID及标题
ShortCutMan.Param[1] := IntToStr(GetForegroundWindow);
GetWindowText(GetForegroundWindow, Buf, 255);
if Buf <> '' then ShortCutMan.Param[2] := Buf;
GetClassName(GetForegroundWindow, Buf, 255);
if Buf <> '' then ShortCutMan.Param[3] := Buf;
TraceMsg('WinID = %s, WinCaption = %s, Class = %s',
[ShortCutMan.Param[1], ShortCutMan.Param[2], ShortCutMan.Param[3]]);
// 取得最近一次的项目
try
StringList := TStringList.Create;
ShortCutMan.GetLatestShortCutItemList(StringList);
if StringList.Count > 0 then
ShortCutMan.Execute(TShortCutItem(StringList.Objects[0]));
finally
StringList.Free;
end;
end;
procedure TALTRunForm.hkmHotkeyHotKeyPressed(HotKey: Cardinal; Index: Word);
var
Buf: array[0..254] of Char;
begin
TraceMsg('hkmMainHotKeyPressed(%d)', [HotKey]);
if DEBUG_SORT then
begin
actShortCutExecute(Self);
Exit;
end;
// 取得当前剪贴板中的文字
ShortCutMan.Param[0] := Clipboard.AsUnicodeText;
// 取得当前前台窗体ID, 标题, Class
ShortCutMan.Param[1] := IntToStr(GetForegroundWindow);
GetWindowText(GetForegroundWindow, Buf, 255);
if Buf <> '' then ShortCutMan.Param[2] := Buf;
GetClassName(GetForegroundWindow, Buf, 255);
if Buf <> '' then ShortCutMan.Param[3] := Buf;
TraceMsg('WinID = %s, WinCaption = %s, Class = %s',
[ShortCutMan.Param[1], ShortCutMan.Param[2], ShortCutMan.Param[3]]);
if m_IsShow then
actHideExecute(Self)
else
actShowExecute(Self);
end;
procedure TALTRunForm.imgBackgroundMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
ReleaseCapture;
SendMessage(Handle, WM_SYSCOMMAND, SC_DRAGMOVE, 0);
end
else if Button = mbMiddle then
begin
actExecuteExecute(Sender);
end;
end;
procedure TALTRunForm.lblShortCutMouseActivate(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
begin
TraceMsg('lblShortCutMouseActivate()');
RestartHideTimer(HideDelay);
end;
procedure TALTRunForm.lblShortCutMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
ReleaseCapture;
SendMessage(Handle, WM_SYSCOMMAND, SC_DRAGMOVE, 0);
end
else if Button = mbMiddle then
begin
actExecuteExecute(Sender);
end;
end;
procedure TALTRunForm.lstShortCutKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
TraceMsg('lstShortCutKeyDown( #%d = %s )', [Key, Chr(Key)]);
//关闭tmrFocus
tmrFocus.Enabled := False;
case Key of
// VK_F2:
// actEditItemExecute(Sender);
//
// VK_INSERT:
// actAddItemExecute(Sender);
//
// VK_DELETE:
// actDeleteItemExecute(Sender);
//回车
13: ;
VK_PRIOR, VK_NEXT: ;
else
if m_IsShow then
begin
//传到这里的键,都转发给edtShortCut
PostMessage(edtShortCut.Handle, WM_KEYDOWN, Key, 0);
try
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
end;
end;
end;
end;
procedure TALTRunForm.lstShortCutMouseActivate(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y, HitTest: Integer;
var MouseActivate: TMouseActivate);
begin
TraceMsg('lstShortCutMouseActivate()');
RestartHideTimer(HideDelay);
end;
procedure TALTRunForm.lstShortCutMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
TraceMsg('lstShortCutMouseDown()');
//右键点击,就选中该项
if Button = mbRight then
begin
lstShortCut.Perform(WM_LBUTTONDOWN, MK_LBUTTON, (y shl 16) + x);
actSelectChangeExecute(Sender);
end
else if Button = mbMiddle then
begin
//lstShortCut.Perform(WM_LBUTTONDOWN, 0, (y shl 16) + x);
actExecuteExecute(Sender);
end;
end;
procedure TALTRunForm.ntfMainDblClick(Sender: TObject);
var
AutoHideForm: TAutoHideForm;
begin
TraceMsg('ntfMainDblClick()');
if m_IsFirstDblClickIcon then
begin
m_IsFirstDblClickIcon := False;
//对话框没法消失,不优秀,换成自动消失的
//Application.MessageBox(
// PChar(Format(resShowMeByHotKey, [HotKeyStr])),
// PChar(resInfo), MB_OK + MB_ICONINFORMATION + MB_TOPMOST);
try
AutoHideForm := TAutoHideForm.Create(Self);
AutoHideForm.Caption := resInfo;
AutoHideForm.Info := Format(resShowMeByHotKey, [HotKeyStr1]);
AutoHideForm.Info := Format(resShowMeByHotKey, [GetHotKeyString]);
AutoHideForm.ShowModal;
finally
AutoHideForm.Free;
end;
end;
if m_IsShow then
actHideExecute(Self)
else
actShowExecute(Self);
end;
procedure TALTRunForm.pmListPopup(Sender: TObject);
begin
mniOpenDir.Visible := DirAvailable;
mniN1.Visible := mniOpenDir.Visible
end;
procedure TALTRunForm.RefreshOperationHint;
var
HintIndex: Integer;
begin
TraceMsg('RefreshOperationHint()');
//刷新提示
if not ShowOperationHint then
edtHint.Hide
else
begin
edtHint.Show;
if Length(edtShortCut.Text) = 0 then
begin
//随机挑选一个提示显示出来
Randomize;
repeat
HintIndex := Random(Length(HintList));
until Trim(HintList[HintIndex]) <> '';
edtHint.Text := HintList[HintIndex];
end
else if Length(edtShortCut.Text) < 6 then
begin
if lstShortCut.Count = 0 then
begin
edtHint.Text := resKeyToAdd;
end
else if DirAvailable then
edtHint.Text := resKeyToOpenFolder
else
edtHint.Text := resKeyToRun;
end
else
edtHint.Hide;
end;
end;
procedure TALTRunForm.RestartMe;
begin
TraceMsg('RestartMe()');
ShellExecute(0, nil, PChar(Application.ExeName), RESTART_FLAG, nil, SW_SHOWNORMAL);
actCloseExecute(Self);
end;
procedure TALTRunForm.RestartHideTimer(Delay: Integer);
begin
TraceMsg('RestartHideTimer()');
if m_IsShow then
begin
tmrHide.Enabled := False;
tmrHide.Interval := Delay * 1000;
tmrHide.Enabled := True;
end;
end;
procedure TALTRunForm.ShowLatestShortCutList;
var
StringList: TStringList;
begin
TraceMsg('ShowLatestShortCutList');
lblShortCut.Caption := '';
lblShortCut.Hint := '';
lstShortCut.Hint := '';
edtCommandLine.Text := '';
lstShortCut.Clear;
try
StringList := TStringList.Create;
ShortCutMan.GetLatestShortCutItemList(StringList);
lstShortCut.Items.Assign(StringList);
m_NeedRefresh := True;
finally
StringList.Free;
end;
if lstShortCut.Count = 0 then
begin
lblShortCut.Caption := '';
lblShortCut.Hint := '';
lstShortCut.Hint := '';
edtCommandLine.Text := '';
end
else
begin
lstShortCut.ItemIndex := 0;
lblShortCut.Caption := TShortCutItem(lstShortCut.Items.Objects[0]).Name;
lblShortCut.Hint := TShortCutItem(lstShortCut.Items.Objects[0]).CommandLine;
edtCommandLine.Text := resCMDLine + lblShortCut.Hint;
end;
//如果可以打开文件夹,标记下
if DirAvailable then lblShortCut.Caption := '[' + lblShortCut.Caption + ']';
//更新最近的命令列表
GetLastCmdList;
//刷新提示
RefreshOperationHint;
end;
procedure TALTRunForm.StopTimer;
begin
TraceMsg('StopTimer()');
tmrHide.Enabled := False;
tmrFocus.Enabled := False;
end;
procedure TALTRunForm.tmrCopyTimer(Sender: TObject);
begin
tmrCopy.Enabled := False;
edtCopy.Hide;
end;
procedure TALTRunForm.tmrExitTimer(Sender: TObject);
begin
TraceMsg('tmrExitTimer()');
tmrExit.Enabled := False;
actCloseExecute(Sender);
end;
procedure TALTRunForm.tmrFocusTimer(Sender: TObject);
var
IsActivated: Boolean;
begin
TraceMsg('tmrFocusTimer()');
tmrFocus.Enabled := False;
// 因为将窗体重新置于前台经常失败,故放弃这个Timer
Exit;
{
// 如果窗体显示却没有获得焦点,则获得焦点
if m_IsShow then
begin
try
TraceMsg('Lost Focus, try again');
SetForegroundWindow(Application.Handle);
edtShortCut.SetFocus;
except
TraceMsg('edtShortCut.SetFocus failed');
tmrFocus.Enabled := True;
end;
end;
}
end;
procedure TALTRunForm.tmrHideTimer(Sender: TObject);
begin
TraceMsg('tmrHideTimer()');
evtMainMinimize(Sender);
edtShortCut.Text := '';
end;
procedure TALTRunForm.WndProc(var Msg: TMessage);
var
FileName: string;
begin
case msg.Msg of
WM_ALTRUN_ADD_SHORTCUT:
begin
TraceMsg('WM_ALTRUN_ADD_SHORTCUT');
//ShortCutMan.AddFileShortCut(PChar(msg.WParam)));
//ShortCutMan.SaveShortCutList;
//ShowMessage('WM_ALTRUN_ADD_SHORTCUT');
end;
WM_ALTRUN_SHOW_WINDOW:
begin
TraceMsg('WM_ALTRUN_SHOW_WINDOW');
actShowExecute(Self);
SetForegroundWindow(Application.Handle);
end;
WM_SETTEXT:
begin
//Msg.WParam = 1 表示是自己程序发过来的
if Msg.WParam = 1 then
begin
FileName := StrPas(PChar(msg.LParam));
TraceMsg('Received FileName = %s', [FileName]);
ShortCutMan.AddFileShortCut(FileName);
end;
end;
WM_SETTINGCHANGE:
begin
// 用户环境变量发生变化,故强行再次读取,然后设置以生效
// When the system sends this message as a result of a change in locale settings, this parameter is zero.
// To effect a change in the environment variables for the system or the user,
// broadcast this message with lParam set to the string "Environment".
if (Msg.WParam = 0) and ((PChar(Msg.LParam)) = 'Environment') then
begin
// 根据注册表内容,强行刷新自身的环境变量
RefreshEnvironmentVars;
end;
inherited;
end;
else
//TraceMsg('msg.Msg = %d, msg.LParam = %d, ms.WParam = %d', [msg.Msg, msg.LParam, msg.WParam]);
inherited;
end;
end;
end.
|
const max = 20;
type vector = array [1..max] of word;
function BiSearch (const a: vector; const n: byte; const key: word):integer;
var left, right, i, find:byte;
flag:boolean;
begin
flag:=true;
find:=0;
left:=1;
right:=n;
for var j:=2 to n do
if (a[j] < a[j-1])
then flag:=false;
if (flag = true)
then while (left <= right) do begin
i:=(left + right) div 2;
if (key < a[i])
then right:= i-1
else if (key > a[i])
then left:=left+1
else begin
find:=i;
left:=right + 1;
end;
end;
if (flag = false)
then result := -1
else result:=find;
end;
function UniformBiSearch (const a: vector; const n: byte; const key: word):integer;
var d: vector;
max, i, j, find: byte;
flag, search: boolean;
begin
search:=true;
flag:= true;
for i:=2 to n do
if (a[i] < a[i-1])
then flag:=false;
if (flag = true) then begin
max:= trunc(ln(n)/ln(2)) + 2;
for j:= 1 to max do
d[j]:= trunc((n + exp((j - 1) * ln(2))) / (exp(j * ln(2))));
i:=d[1];
j:=2;
while (search = true) and (find = 0) and ((i>0) and (i<=n)) do begin
if (key < a[i])
then begin
if (d[j] = 0)
then search:=false
else begin
i:=i-d[j];
j:=j+1;
end;
end
else if (key > a[i])
then begin
if (d[j] = 0)
then search:=false
else begin
i:=i+d[j];
j:=j+1;
end;
end
else if (key = a[i])
then find:=i;
end;
end;
if (flag = false)
then result:=-1
else result:=find;
end;
var matrix: array [1..max] of vector;
a: vector;
size, k, l, i, j: byte;
key:word;
find: integer;
begin
k:=0;
i:=0;
j:=0;
writeln ('Enter size of matrix:');
readln(size);
for i:= 1 to size do begin
writeln ('Enter ', i,' line:');
for j:= 1 to size do
read (matrix[i,j]);
end;
writeln('Enter key:');
readln(key);
l:=1;
write ('Vector: ');
for i:= 1 to size do begin//diagonal
inc(k);
a[k]:=matrix[i,i];
if (k < size)
then write(a[k],' ')
else write(a[k],'. ');
end;
writeln;
find:= BiSearch(a, size, key);
if (find = -1)
then writeln ('(Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Binary) Key is not found.')
else writeln ('(Binary): [', find,',',find,']');
find:= UniformBiSearch(a, size, key);
if (find = -1)
then writeln ('(Uniform Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Uniform Binary) Key is not found.')
else writeln ('(Uniform Binary): [', find,',',find,']');
while (l <= size - 1) do begin
k:=0;
write ('Vector: ');
for i:= 1 to size-l do begin //above the main diagonal
inc(k);
a[k]:= matrix[i, i + l];
if (k < size - l)
then write(a[k],' ')
else write(a[k],'. ');
end;
writeln;
find:= BiSearch(a, size-l, key);
if (find = -1)
then writeln ('(Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Binary) Key is not found.')
else writeln ('(Binary): [', find,',',find+l,']');
find:= UniformBiSearch(a, size-l, key);
if (find = -1)
then writeln ('(Uniform Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Uniform Binary) Key is not found.')
else writeln ('(Uniform Binary): [', find,',',find+l,']');
k:=0;
writeln;
write ('Vector: ');
for i:= l + 1 to size do begin //under the main diagonal
inc(k);
a[k]:= matrix[i, i - l];
if (k < size - l)
then write(a[k],' ')
else write(a[k],'. ');
end;
writeln;
find:= BiSearch(a, size-l, key);
if (find = -1)
then writeln ('(Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Binary) Key is not found.')
else writeln ('(Binary): [', find+l,',',find,']');
find:= UniformBiSearch(a, size-l, key);
if (find = -1)
then writeln ('(Uniform Binary) Error: Sequence is not sorted.')
else if (find = 0)
then writeln ('(Uniform Binary) Key is not found.')
else writeln ('(Uniform Binary): [', find+l,',',find,']');
inc(l);
for i:=1 to k do
a[i]:=0;
writeln;
end;
end. |
unit Parser;
interface
uses
Classes;
type
TUCICommand =
(
cmdUCI,
cmdQuit,
cmdNewGame,
cmdPositionFen,
cmdPositionStartPos,
cmdGo,
cmdIsReady,
cmdStop,
cmdUnknown
);
TUCICommandParser = class
//private
moves: TStringList;
position: string;
//protected
constructor Create;
destructor Destroy; override;
//public
function ParseCommand(const aCommand: string): TUCICommand;
end;
implementation
uses
Expressions;
constructor TUCICommandParser.Create;
begin
moves := Expressions.list;
end;
destructor TUCICommandParser.Destroy;
begin
inherited Destroy;
end;
function TUCICommandParser.ParseCommand(const aCommand: string): TUCICommand;
begin
if aCommand = 'uci' then
result := cmdUCI
else
if aCommand = 'quit' then
result := cmdQuit
else
if aCommand = 'ucinewgame' then
result := cmdNewGame
else
if (Pos('position fen', aCommand) = 1)
and ExtractFEN(aCommand, position) then
result := cmdPositionFen
else
if (Pos('position startpos', aCommand) = 1) then
begin
result := cmdPositionStartPos;
ExtractMoves(aCommand);
end else
if Pos('go', aCommand) = 1 then
result := cmdGo
else
if aCommand = 'isready' then
result := cmdIsReady
else
if aCommand = 'stop' then
result := cmdStop
else
result := cmdUnknown;
end;
end.
|
unit PluginManager;
interface
uses
Windows,
SysUtils,
Classes;
type
EPluginManagerError = class(Exception);
EPluginLoadError = class(EPluginManagerError);
EPluginsLoadError = class(EPluginLoadError)
private
FItems: TStrings;
public
constructor Create(const AText: String; const AFailedPlugins: TStrings);
destructor Destroy; override;
property FailedPluginFileNames: TStrings read FItems;
end;
IPlugin = interface
// protected
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetFileName: String;
// function GetMask: String;
function GetActionID: Integer;
function GetExtension: String;
function GetDescription: String;
function GetFileType:Char;
// function GetFilterIndex: Integer;
// procedure SetFilterIndex(const AValue: Integer);
// public
property Index: Integer read GetIndex;
property Handle: HMODULE read GetHandle;
property FileName: String read GetFileName;
property ActionID: Integer read GetActionID;
property Extension: String read GetExtension;
property FileType: Char read GetFileType;
// property Mask: String read GetMask;
property Description: String read GetDescription;
// property FilterIndex: Integer read GetFilterIndex write SetFilterIndex;
end;
IPluginManager = interface
// protected
function GetItem(const AIndex: Integer): IPlugin;
function GetCount: Integer;
// public
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder: String; const AFileExt: String = '');
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
property Items[const AIndex: Integer]: IPlugin read GetItem; default;
property Count: Integer read GetCount;
procedure UnloadAll;
procedure SetVersion(const AVersion: Integer);
end;
function Plugins: IPluginManager;
implementation
uses
Registry,
PluginAPI;
resourcestring
rsPluginsLoadError = 'One or more plugins has failed to load:' + sLineBreak + '%s';
type
TPluginManager = class(TInterfacedObject, IUnknown, IPluginManager, ICore)
private
FItems: array of IPlugin;
FCount: Integer;
FBanned: TStringList;
FVersion: Integer;
protected
function GetItem(const AIndex: Integer): IPlugin;
function GetCount: Integer;
function CanLoad(const AFileName: String): Boolean;
procedure SetVersion(const AVersion: Integer);
function GetVersion: Integer; safecall;
public
constructor Create;
destructor Destroy; override;
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder, AFileExt: String);
function IndexOf(const APlugin: IPlugin): Integer;
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
procedure UnloadAll;
end;
TPlugin = class(TInterfacedObject, IUnknown, IPlugin)
private
FManager: TPluginManager;
FFileName: String;
FHandle: HMODULE;
FInit: TInitPluginFunc;
FDone: TDonePluginFunc;
// FFilterIndex: Integer;
FPlugin: PluginAPI.IPlugin;
FInfoRetrieved: Boolean;
// FMask: String;
FActionID: Integer;
FExtension:string;
FFileType:Char;
FDescription: String;
procedure GetInfo;
protected
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetFileName: String;
// function GetMask: String;
function GetDescription: String;
function GetActionID:integer;
function GetExtension:string;
function GetFileType:Char;
// function GetFilterIndex: Integer;
// procedure SetFilterIndex(const AValue: Integer);
public
constructor Create(const APluginManger: TPluginManager; const AFileName: String); virtual;
destructor Destroy; override;
end;
{ TPluginManager }
constructor TPluginManager.Create;
begin
inherited Create;
FBanned := TStringList.Create;
SetVersion(1);
end;
destructor TPluginManager.Destroy;
begin
FreeAndNil(FBanned);
inherited;
end;
function TPluginManager.LoadPlugin(const AFileName: String): IPlugin;
begin
if CanLoad(AFileName) then
begin
Result := nil;
Exit;
end;
// Загружаем плагин
try
Result := TPlugin.Create(Self, AFileName);
except
on E: Exception do
raise EPluginLoadError.Create(Format('[%s] %s', [E.ClassName, E.Message]));
end;
// Заносим в список
if Length(FItems) >= FCount then // "Capacity"
SetLength(FItems, Length(FItems) + 64);
FItems[FCount] := Result;
Inc(FCount);
end;
procedure TPluginManager.LoadPlugins(const AFolder, AFileExt: String);
function PluginOK(const APluginName, AFileExt: String): Boolean;
begin
Result := (AFileExt = '');
if Result then
Exit;
Result := SameFileName(ExtractFileExt(APluginName), AFileExt);
end;
var
Path: String;
SR: TSearchRec;
Failures: TStringList;
FailedPlugins: TStringList;
begin
Path := IncludeTrailingPathDelimiter(AFolder);
Failures := TStringList.Create;
FailedPlugins := TStringList.Create;
try
if FindFirst(Path + '*.*', 0, SR) = 0 then
try
repeat
if ((SR.Attr and faDirectory) = 0) and
PluginOK(SR.Name, AFileExt) then
try
LoadPlugin(Path + SR.Name);
except
on E: Exception do
begin
FailedPlugins.Add(SR.Name);
Failures.Add(Format('%s: %s', [SR.Name, E.Message]));
end;
end;
until FindNext(SR) <> 0;
finally
FindClose(SR);
end;
if Failures.Count > 0 then
raise EPluginsLoadError.Create(Format(rsPluginsLoadError, [Failures.Text]), FailedPlugins);
finally
FreeAndNil(FailedPlugins);
FreeAndNil(Failures);
end;
end;
procedure TPluginManager.UnloadAll;
begin
Finalize(FItems);
end;
procedure TPluginManager.UnloadPlugin(const AIndex: Integer);
var
X: Integer;
begin
// Выгрузить плагин
FItems[AIndex] := nil;
// Сдвинуть плагины в списке, чтобы закрыть "дырку"
for X := AIndex to FCount - 1 do
FItems[X] := FItems[X + 1];
// Не забыть учесть последний
FItems[FCount - 1] := nil;
Dec(FCount);
end;
function TPluginManager.IndexOf(const APlugin: IPlugin): Integer;
var
X: Integer;
begin
Result := -1;
for X := 0 to FCount - 1 do
if FItems[X] = APlugin then
begin
Result := X;
Break;
end;
end;
procedure TPluginManager.Ban(const AFileName: String);
begin
Unban(AFileName);
FBanned.Add(AFileName);
end;
procedure TPluginManager.Unban(const AFileName: String);
var
X: Integer;
begin
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
FBanned.Delete(X);
Break;
end;
end;
function TPluginManager.CanLoad(const AFileName: String): Boolean;
var
X: Integer;
begin
// Не грузить отключенные
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
Result := True;
Exit;
end;
// Не грузить уже загруженные
for X := 0 to FCount - 1 do
if SameFileName(FItems[X].FileName, AFileName) then
begin
Result := True;
Exit;
end;
Result := False;
end;
const
SRegDisabledPlugins = 'Disabled plugins';
SRegPluginX = 'Plugin%d';
procedure TPluginManager.SaveSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_ALL_ACCESS);
try
// Удаляем старые
Reg.EraseSection(SRegDisabledPlugins);
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, True) then
Exit;
// Сохраняем новые
for X := 0 to FBanned.Count - 1 do
Reg.WriteString(Path, Format(SRegPluginX, [X]), FBanned[X]);
finally
FreeAndNil(Reg);
end;
end;
procedure TPluginManager.SetVersion(const AVersion: Integer);
begin
FVersion := AVersion;
end;
procedure TPluginManager.LoadSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_READ);
try
FBanned.BeginUpdate;
try
FBanned.Clear;
// Читаем
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, True) then
Exit;
Reg.ReadSectionValues(Path, FBanned);
// Убираем "Plugin5=" из строк
for X := 0 to FBanned.Count - 1 do
FBanned[X] := FBanned.ValueFromIndex[X];
finally
FBanned.EndUpdate;
end;
finally
FreeAndNil(Reg);
end;
end;
function TPluginManager.GetCount: Integer;
begin
Result := FCount;
end;
function TPluginManager.GetItem(const AIndex: Integer): IPlugin;
begin
Result := FItems[AIndex];
end;
function TPluginManager.GetVersion: Integer;
begin
Result := FVersion;
end;
{ TPlugin }
constructor TPlugin.Create(const APluginManger: TPluginManager;
const AFileName: String);
begin
inherited Create;
FManager := APluginManger;
FFileName := AFileName;
// FFilterIndex := -1;
FHandle := SafeLoadLibrary(AFileName, SEM_NOOPENFILEERRORBOX or SEM_FAILCRITICALERRORS);
Win32Check(FHandle <> 0);
FDone := GetProcAddress(FHandle, SPluginDoneFuncName);
FInit := GetProcAddress(FHandle, SPluginInitFuncName);
Win32Check(Assigned(FInit));
FPlugin := FInit(FManager);
end;
destructor TPlugin.Destroy;
begin
FPlugin := nil;
if Assigned(FDone) then
FDone;
if FHandle <> 0 then
begin
FreeLibrary(FHandle);
FHandle := 0;
end;
inherited;
end;
function TPlugin.GetFileName: String;
begin
Result := FFileName;
end;
function TPlugin.GetHandle: HMODULE;
begin
Result := FHandle;
end;
function TPlugin.GetIndex: Integer;
begin
Result := FManager.IndexOf(Self);
end;
procedure TPlugin.GetInfo;
begin
if FInfoRetrieved then
Exit;
// FMask := FPlugin.Mask;
FDescription := FPlugin.Description;
FActionID:=FPlugin.ActionID;
FExtension:=FPlugin.Extension;
FFileType:=Char(FPlugin.FileType);
FInfoRetrieved := True;
end;
{function TPlugin.GetMask: String;
begin
GetInfo;
Result := FMask;
end;}
function TPlugin.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if Failed(Result) then
Result := FPlugin.QueryInterface(IID, Obj);
end;
{procedure TPlugin.SetFilterIndex(const AValue: Integer);
begin
FFilterIndex := AValue;
end;}
function TPlugin.GetDescription: String;
begin
GetInfo;
Result := FDescription;
end;
function TPlugin.GetActionID: integer;
begin
GetInfo;
Result:=FActionID;
end;
function TPlugin.GetExtension: string;
begin
GetInfo;
Result:=FExtension;
end;
function TPlugin.GetFileType: Char;
begin
GetInfo;
Result:=FFileType;
end;
{ EPluginsLoadError }
constructor EPluginsLoadError.Create(const AText: String;
const AFailedPlugins: TStrings);
begin
inherited Create(AText);
FItems := TStringList.Create;
FItems.Assign(AFailedPlugins);
end;
destructor EPluginsLoadError.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
//________________________________________________________________
var
FPluginManager: IPluginManager;
function Plugins: IPluginManager;
begin
Result := FPluginManager;
end;
initialization
FPluginManager := TPluginManager.Create;
finalization
if Assigned(FPluginManager) then
FPluginManager.UnloadAll;
FPluginManager := nil;
end.
|
unit ExportBySizeAndMain;
{* Экспорт, разделённый по размеру и мейну (мейн - в шаблонах имён файлов) }
// Модуль: "w:\archi\source\projects\ImportExportTest\ExportBySizeAndMain.pas"
// Стереотип: "TestCase"
// Элемент модели: "ExportBySizeAndMain" MUID: (55FFF13302B8)
// Имя типа: "TExportBySizeAndMain"
{$Include w:\archi\source\projects\ImportExportTest.inc}
interface
{$If Defined(nsTest)}
uses
l3IntfUses
, ExportPipeTestPrim
;
type
TExportBySizeAndMain = class(TExportPipeTestPrim)
{* Экспорт, разделённый по размеру и мейну (мейн - в шаблонах имён файлов) }
protected
procedure TuneExportPipe; override;
{* Процедура настройки трубы. Метод для перекрытия в потомках. }
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TExportBySizeAndMain
{$IfEnd} // Defined(nsTest)
implementation
{$If Defined(nsTest)}
uses
l3ImplUses
, TestFrameWork
, ddPipeOutInterfaces
, l3Base
//#UC START# *55FFF13302B8impl_uses*
//#UC END# *55FFF13302B8impl_uses*
;
procedure TExportBySizeAndMain.TuneExportPipe;
{* Процедура настройки трубы. Метод для перекрытия в потомках. }
//#UC START# *55EEA16603AE_55FFF13302B8_var*
//#UC END# *55EEA16603AE_55FFF13302B8_var*
begin
//#UC START# *55EEA16603AE_55FFF13302B8_impl*
Pipe.AllPartsDivideBy([edbSize]);
Pipe.OutputFileSize := 4096;
Pipe.FileMask[edpReference] := l3CStr('rel_%main%');
Pipe.FileMask[edpDocument] := l3CStr('doc_%main%');
//#UC END# *55EEA16603AE_55FFF13302B8_impl*
end;//TExportBySizeAndMain.TuneExportPipe
function TExportBySizeAndMain.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'ExportPipeTests';
end;//TExportBySizeAndMain.GetFolder
function TExportBySizeAndMain.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55FFF13302B8';
end;//TExportBySizeAndMain.GetModelElementGUID
initialization
TestFramework.RegisterTest(TExportBySizeAndMain.Suite);
{$IfEnd} // Defined(nsTest)
end.
|
unit xn.grid.link;
interface
uses xn.grid.common, xn.grid.data;
type
TxnGridLink = class(TInterfacedObject, IxnGridData)
private
fDataSort: TxnGridDataSort;
fDataFilter: TxnGridDataFilter;
public
constructor Create(aGridData: IxnGridData; aFilterItems: IxnGridFilterItems; aSortItems: IxnGridSortItems);
destructor Destroy; override;
procedure Fill; virtual;
procedure Sort; overload;
function Seek1(aKeys: TArray<variant>): integer;
function Seek2(aKeys: TArray<variant>): integer;
function RowCountGet: integer; virtual;
function AsDebug: String; virtual;
function ValueString(aCol, aRow: integer): String; virtual;
function ValueFloat(aCol, aRow: integer): Double; virtual;
end;
implementation
function TxnGridLink.AsDebug: String;
begin
Result := fDataSort.AsDebug;
end;
constructor TxnGridLink.Create(aGridData: IxnGridData; aFilterItems: IxnGridFilterItems; aSortItems: IxnGridSortItems);
begin
fDataFilter := TxnGridDataFilter.Create(aGridData, aFilterItems);
fDataSort := TxnGridDataSort.Create(fDataFilter, aSortItems);
end;
destructor TxnGridLink.Destroy;
begin
fDataSort.Free;
inherited;
end;
procedure TxnGridLink.Fill;
begin
fDataFilter.Fill;
fDataSort.Fill;
end;
function TxnGridLink.RowCountGet: integer;
begin
Result := fDataSort.RowCountGet;
end;
function TxnGridLink.Seek1(aKeys: TArray<variant>): integer;
begin
Result := fDataSort.Seek1(aKeys);
end;
function TxnGridLink.Seek2(aKeys: TArray<variant>): integer;
begin
Result := fDataSort.Seek2(aKeys);
end;
procedure TxnGridLink.Sort;
begin
fDataSort.Sort;
end;
function TxnGridLink.ValueFloat(aCol, aRow: integer): Double;
begin
Result := fDataSort.ValueFloat(aCol, aRow)
end;
function TxnGridLink.ValueString(aCol, aRow: integer): String;
begin
Result := fDataSort.ValueString(aCol, aRow)
end;
end.
|
unit uQueueThread;
interface
uses
SysUtils, Classes, uInterfaceListExt, SyncObjs;
type
TQueueThread = class;
TQueueItemProcessEvent = procedure (AQueueThread: TQueueThread; AItem: IInterface) of object;
TQueueThread = class(TThread)
private
FCurrentItem: IInterface;
FItemDelay: Integer;
FOnProcess: TQueueItemProcessEvent;
FQueue: IInterfaceListExt;
FScanDelay: Integer;
FSynchronousProcessing: Boolean;
procedure SetItemDelay(const Value: Integer);
procedure SetScanDelay(const Value: Integer);
procedure SetSynchronousProcessing(const Value: Boolean);
protected
procedure SyncProcess;
procedure Process(AItem: IInterface); virtual;
public
constructor Create;
procedure Enqueue(AItem: IInterface);
procedure Execute; override;
procedure SyncronizeCall(Proc: TThreadMethod);
property ItemDelay: Integer read FItemDelay write SetItemDelay;
property ScanDelay: Integer read FScanDelay write SetScanDelay;
property SynchronousProcessing: Boolean read FSynchronousProcessing write
SetSynchronousProcessing;
property OnProcess: TQueueItemProcessEvent read FOnProcess write FOnProcess;
end;
implementation
constructor TQueueThread.Create;
begin
inherited Create(True);
FQueue := CreateInterfaceListExt();
FreeOnTerminate := False;
FItemDelay := 10;
FScanDelay := 10;
FSynchronousProcessing := True;
Resume;
end;
{
********************************* TQueueThread *********************************
}
procedure TQueueThread.Enqueue(AItem: IInterface);
begin
FQueue.Add(AItem);
end;
procedure TQueueThread.Execute;
begin
while not Terminated do
begin
while not Terminated and (FQueue.Count > 0) do
begin
FQueue.Lock;
try
FCurrentItem := FQueue[0];
FQueue.Delete(0);
finally
FQueue.Unlock;
end;
if not Terminated then
begin
if SynchronousProcessing then
Synchronize(SyncProcess)
else
Process(FCurrentItem);
if not Terminated then
Sleep(FItemDelay);
end;
end;
if not Terminated then
Sleep(FScanDelay);
end;
end;
procedure TQueueThread.Process(AItem: IInterface);
begin
if Assigned(FOnProcess) then FOnProcess(Self, AItem);
end;
procedure TQueueThread.SetItemDelay(const Value: Integer);
begin
if FItemDelay <> Value then
begin
FItemDelay := Value;
end;
end;
procedure TQueueThread.SetScanDelay(const Value: Integer);
begin
if FScanDelay <> Value then
begin
FScanDelay := Value;
end;
end;
procedure TQueueThread.SetSynchronousProcessing(const Value: Boolean);
begin
if FSynchronousProcessing <> Value then
begin
FSynchronousProcessing := Value;
end;
end;
procedure TQueueThread.SyncProcess;
begin
Process(FCurrentItem);
end;
procedure TQueueThread.SyncronizeCall(Proc: TThreadMethod);
begin
Synchronize(Proc);
end;
end.
|
unit uTags;
{
Copyright 2020 Dmitriy Sosnovich, dmitriy@sosnovich.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.}
interface
const
cEmptyTag = 'Empty_Tag' ;
cEmptyAttr = 'Empty_Attr' ;
cInventoryTag = 'INVENTORY';
cDonorTag = 'DONOR';
cCBUTag = 'CBU';
cTagsXPathList: array of string = ['GRID',
'ATTR',
'BIRTH_DATE',
'SEX',
'ABO',
'RHESUS',
'ETHN',
'CCR5',
'HLA',
'KIR',
'IDM',
'RSV_PAT',
'STATUS',
'STAT_END_DATE',
'STAT_REASON',
'CONTACT_DATE',
'CHECKUP_DATE',
'WEIGHT',
'HEIGHT',
'NMBR_TRANS',
'NMBR_PREG',
'NMBR_MARR',
'NMBR_PBSC',
'COLL_TYPE',
'LOCAL_ID',
'BAG_ID',
'COLL_DATE',
'PROC_DATE',
'PROC_METH',
'PROC_METH_TYPE',
'FREEZE_DATE',
'FREEZE_METH',
'PROD_MOD',
'BAG_TYPE',
'BAGS',
'BACT_CULT',
'FUNG_CULT',
'HEMO_STATUS',
'VOL',
'VOL_FRZN',
'TNC',
'TNC_FRZN',
'RED_BC_FRZN',
'MNC_FRZN',
'CD34PC',
'CD34PC_FRZN',
'CFU_FRZN',
'VIABILITY',
'VIABILITY_DATE',
'VIABILITY_CELLS',
'VIABILITY_METHOD',
'ATT_SEG',
'DNA_SMPL',
'OTH_SMPL',
'CT_COMPLETE_DATE',
'CT_SMPL_TYPE',
'AL_RED_BC',
'AL_SER',
'SER_QUANT',
'AL_PLA',
'PLA_QUANT',
'ID',
'MAT_ID',
'MAT_ID_BANK',
'AL_SER',
'SER_QUANT',
'AL_PLA',
'PLA_QUANT',
'IDM/CMV',
'IDM/CMV_NAT',
'IDM/CMV_DATE',
'IDM/HBS_AG',
'IDM/ANTI_HBC',
'IDM/ANTI_HBS',
'IDM/ANTI_HCV',
'IDM/ANTI_HIV_12',
'IDM/HIV_1_NAT',
'IDM/HIV_P24',
'IDM/HCV_NAT',
'IDM/ANTI_HTLV',
'IDM/SYPHILIS',
'IDM/WNV',
'IDM/CHAGAS',
'IDM/EBV',
'IDM/TOXO',
'IDM/HBV_NAT',
'IDM/PB19_NAT',
'IDM/ALT',
'MAT/IDM/CMV',
'MAT/IDM/CMV_NAT',
'MAT/IDM/CMV_DATE',
'MAT/IDM/HBS_AG',
'MAT/IDM/ANTI_HBC',
'MAT/IDM/ANTI_HBS',
'MAT/IDM/ANTI_HCV',
'MAT/IDM/ANTI_HIV_12',
'MAT/IDM/HIV_1_NAT',
'MAT/IDM/HIV_P24',
'MAT/IDM/HCV_NAT',
'MAT/IDM/ANTI_HTLV',
'MAT/IDM/SYPHILIS',
'MAT/IDM/WNV',
'MAT/IDM/CHAGAS',
'MAT/IDM/EBV',
'MAT/IDM/TOXO',
'MAT/IDM/HBV_NAT',
'MAT/IDM/PB19_NAT',
'MAT/IDM/ALT',
'KIR/KIR2DL1',
'KIR/KIR2DL2',
'KIR/KIR2DL3',
'KIR/KIR2DL4',
'KIR/KIR2DL5A',
'KIR/KIR2DL5B',
'KIR/KIR2DS1',
'KIR/KIR2DS2',
'KIR/KIR2DS3',
'KIR/KIR2DS4',
'KIR/KIR2DS5',
'KIR/KIR2DP1',
'KIR/KIR3DL1',
'KIR/KIR3DL2',
'KIR/KIR3DL3',
'KIR/KIR3DS1',
'KIR/KIR3DP1',
'KIR/KIR_GL',
'HLA/A/SER/FIELD1',
'HLA/A/SER/FIELD2',
'HLA/A/DNA/FIELD1',
'HLA/A/DNA/FIELD2',
'HLA/B/SER/FIELD1',
'HLA/B/SER/FIELD2',
'HLA/B/DNA/FIELD1',
'HLA/B/DNA/FIELD2',
'HLA/C/SER/FIELD1',
'HLA/C/SER/FIELD2',
'HLA/C/DNA/FIELD1',
'HLA/C/DNA/FIELD2',
'HLA/DRB1/SER/FIELD1',
'HLA/DRB1/SER/FIELD2',
'HLA/DRB1/DNA/FIELD1',
'HLA/DRB1/DNA/FIELD2',
'HLA/DRB3/DNA/FIELD1',
'HLA/DRB3/DNA/FIELD2',
'HLA/DRB4/DNA/FIELD1',
'HLA/DRB4/DNA/FIELD2',
'HLA/DRB5/DNA/FIELD1',
'HLA/DRB5/DNA/FIELD2',
'HLA/DQA1/DNA/FIELD1',
'HLA/DQA1/DNA/FIELD2',
'HLA/DQB1/SER/FIELD1',
'HLA/DQB1/SER/FIELD2',
'HLA/DQB1/DNA/FIELD1',
'HLA/DQB1/DNA/FIELD2',
'HLA/DQB1/DNA/FIELD1',
'HLA/DPA1/DNA/FIELD1',
'HLA/DPA1/DNA/FIELD2',
'HLA/DPB1/DNA/FIELD1',
'HLA/DPB1/DNA/FIELD2',
'MAT/HLA/A/SER/FIELD1',
'MAT/HLA/A/SER_FIELD2',
'MAT/HLA/A/DNA/FIELD1',
'MAT/HLA/A/DNA/FIELD2',
'MAT/HLA/B/SER/FIELD1',
'MAT/HLA/B/SER/FIELD2',
'MAT/HLA/B/DNA/FIELD1',
'MAT/HLA/B/DNA/FIELD2',
'MAT/HLA/C/SER/FIELD1',
'MAT/HLA/C/SER/FIELD2',
'MAT/HLA/C/DNA/FIELD1',
'MAT/HLA/C/DNA/FIELD2',
'MAT/HLA/DRB1/SER/FIELD1',
'MAT/HLA/DRB1/SER/FIELD2',
'MAT/HLA/DRB1/DNA/FIELD1',
'MAT/HLA/DRB1/DNA/FIELD2',
'MAT/HLA/DRB3/DNA/FIELD1',
'MAT/HLA/DRB3/DNA/FIELD2',
'MAT/HLA/DRB4/DNA/FIELD1',
'MAT/HLA/DRB4/DNA/FIELD2',
'MAT/HLA/DRB5/DNA/FIELD1',
'MAT/HLA/DRB5/DNA/FIELD2',
'MAT/HLA/DQA1/DNA/FIELD1',
'MAT/HLA/DQA1/DNA/FIELD2',
'MAT/HLA/DQB1/SER/FIELD1',
'MAT/HLA/DQB1/SER/FIELD2',
'MAT/HLA/DQB1/DNA/FIELD1',
'MAT/HLA/DQB1/DNA/FIELD2',
'MAT/HLA/DPA1/DNA/FIELD1',
'MAT/HLA/DPA1/DNA/FIELD2',
'MAT/HLA/DPB1/DNA/FIELD1',
'MAT/HLA/DPB1/DNA/FIELD2',
'IDM/ANTI_CMV',
'IDM/ANTI_CMV_DATE',
'IDM/CMV_NAT_DATE',
'MAT/IDM/ANTI_CMV',
'MAT/IDM/ANTI_CMV_DATE',
'MAT/IDM/CMV_NAT_DATE',
'BANK_MANUF_ID',
'BANK_DISTRIB_ID'];
cHeadersList: array of string = ['GRID',
'ATTR',
'BIRTH_DATE',
'SEX',
'ABO',
'RHESUS',
'ETHN',
'CCR5',
'HLA',
'KIR',
'IDM',
'RSV_PAT',
'STATUS',
'STAT_END_DATE',
'STAT_REASON',
'CONTACT_DATE',
'CHECKUP_DATE',
'WEIGHT',
'HEIGHT',
'NMBR_TRANS',
'NMBR_PREG',
'NMBR_MARR',
'NMBR_PBSC',
'COLL_TYPE',
'LOCAL_ID',
'BAG_ID',
'COLL_DATE',
'PROC_DATE',
'PROC_METH',
'PROC_METH_TYPE',
'FREEZE_DATE',
'FREEZE_METH',
'PROD_MOD',
'BAG_TYPE',
'BAGS',
'BACT_CULT',
'FUNG_CULT',
'HEMO_STATUS',
'VOL',
'VOL_FRZN',
'TNC',
'TNC_FRZN',
'RED_BC_FRZN',
'MNC_FRZN',
'CD34PC',
'CD34PC_FRZN',
'CFU_FRZN',
'VIABILITY',
'VIABILITY_DATE',
'VIABILITY_CELLS',
'VIABILITY_METHOD',
'ATT_SEG',
'DNA_SMPL',
'OTH_SMPL',
'CT_COMPLETE_DATE',
'CT_SMPL_TYPE',
'AL_RED_BC',
'AL_SER',
'SER_QUANT',
'AL_PLA',
'PLA_QUANT',
'ID',
'MAT_ID',
'MAT_ID_BANK',
'AL_SER',
'SER_QUANT',
'AL_PLA',
'PLA_QUANT',
'IDM_CMV',
'IDM_CMV_NAT',
'IDM_CMV_DATE',
'IDM_HBS_AG',
'IDM_ANTI_HBC',
'IDM_ANTI_HBS',
'IDM_ANTI_HCV',
'IDM_ANTI_HIV_12',
'IDM_HIV_1_NAT',
'IDM_HIV_P24',
'IDM_HCV_NAT',
'IDM_ANTI_HTLV',
'IDM_SYPHILIS',
'IDM_WNV',
'IDM_CHAGAS',
'IDM_EBV',
'IDM_TOXO',
'IDM_HBV_NAT',
'IDM_PB19_NAT',
'IDM_ALT',
'MAT_IDM_CMV',
'MAT_IDM_CMV_NAT',
'MAT_IDM_CMV_DATE',
'MAT_IDM_HBS_AG',
'MAT_IDM_ANTI_HBC',
'MAT_IDM_ANTI_HBS',
'MAT_IDM_ANTI_HCV',
'MAT_IDM_ANTI_HIV_12',
'MAT_IDM_HIV_1_NAT',
'MAT_IDM_HIV_P24',
'MAT_IDM_HCV_NAT',
'MAT_IDM_ANTI_HTLV',
'MAT_IDM_SYPHILIS',
'MAT_IDM_WNV',
'MAT_IDM_CHAGAS',
'MAT_IDM_EBV',
'MAT_IDM_TOXO',
'MAT_IDM_HBV_NAT',
'MAT_IDM_PB19_NAT',
'MAT_IDM_ALT',
'KIR_KIR2DL1',
'KIR_KIR2DL2',
'KIR_KIR2DL3',
'KIR_KIR2DL4',
'KIR_KIR2DL5A',
'KIR_KIR2DL5B',
'KIR_KIR2DS1',
'KIR_KIR2DS2',
'KIR_KIR2DS3',
'KIR_KIR2DS4',
'KIR_KIR2DS5',
'KIR_KIR2DP1',
'KIR_KIR3DL1',
'KIR_KIR3DL2',
'KIR_KIR3DL3',
'KIR_KIR3DS1',
'KIR_KIR3DP1',
'KIR_KIR_GL',
'HLA_A_SER_FIELD1',
'HLA_A_SER_FIELD2',
'HLA_A_DNA_FIELD1',
'HLA_A_DNA_FIELD2',
'HLA_B_SER_FIELD1',
'HLA_B_SER_FIELD2',
'HLA_B_DNA_FIELD1',
'HLA_B_DNA_FIELD2',
'HLA_C_SER_FIELD1',
'HLA_C_SER_FIELD2',
'HLA_C_DNA_FIELD1',
'HLA_C_DNA_FIELD2',
'HLA_DRB1_SER_FIELD1',
'HLA_DRB1_SER_FIELD2',
'HLA_DRB1_DNA_FIELD1',
'HLA_DRB1_DNA_FIELD2',
'HLA_DRB3_DNA_FIELD1',
'HLA_DRB3_DNA_FIELD2',
'HLA_DRB4_DNA_FIELD1',
'HLA_DRB4_DNA_FIELD2',
'HLA_DRB5_DNA_FIELD1',
'HLA_DRB5_DNA_FIELD2',
'HLA_DQA1_DNA_FIELD1',
'HLA_DQA1_DNA_FIELD2',
'HLA_DQB1_SER_FIELD1',
'HLA_DQB1_SER_FIELD2',
'HLA_DQB1_DNA_FIELD1',
'HLA_DQB1_DNA_FIELD2',
'HLA_DQB1_DNA_FIELD1',
'HLA_DPA1_DNA_FIELD1',
'HLA_DPA1_DNA_FIELD2',
'HLA_DPB1_DNA_FIELD1',
'HLA_DPB1_DNA_FIELD2',
'MAT_HLA_A_SER_FIELD1',
'MAT_HLA_A_SER_FIELD2',
'MAT_HLA_A_DNA_FIELD1',
'MAT_HLA_A_DNA_FIELD2',
'MAT_HLA_B_SER_FIELD1',
'MAT_HLA_B_SER_FIELD2',
'MAT_HLA_B_DNA_FIELD1',
'MAT_HLA_B_DNA_FIELD2',
'MAT_HLA_C_SER_FIELD1',
'MAT_HLA_C_SER_FIELD2',
'MAT_HLA_C_DNA_FIELD1',
'MAT_HLA_C_DNA_FIELD2',
'MAT_HLA_DRB1_SER_FIELD1',
'MAT_HLA_DRB1_SER_FIELD2',
'MAT_HLA_DRB1_DNA_FIELD1',
'MAT_HLA_DRB1_DNA_FIELD2',
'MAT_HLA_DRB3_DNA_FIELD1',
'MAT_HLA_DRB3_DNA_FIELD2',
'MAT_HLA_DRB4_DNA_FIELD1',
'MAT_HLA_DRB4_DNA_FIELD2',
'MAT_HLA_DRB5_DNA_FIELD1',
'MAT_HLA_DRB5_DNA_FIELD2',
'MAT_HLA_DQA1_DNA_FIELD1',
'MAT_HLA_DQA1_DNA_FIELD2',
'MAT_HLA_DQB1_SER_FIELD1',
'MAT_HLA_DQB1_SER_FIELD2',
'MAT_HLA_DQB1_DNA_FIELD1',
'MAT_HLA_DQB1_DNA_FIELD2',
'MAT_HLA_DPA1_DNA_FIELD1',
'MAT_HLA_DPA1_DNA_FIELD2',
'MAT_HLA_DPB1_DNA_FIELD1',
'MAT_HLA_DPB1_DNA_FIELD2',
'IDM_ANTI_CMV',
'IDM_ANTI_CMV_DATE',
'IDM_CMV_NAT_DATE',
'MAT_IDM_ANTI_CMV',
'MAT_IDM_ANTI_CMV_DATE',
'MAT_IDM_CMV_NAT_DATE'
];
cBanksManDistr21: array of string = ['BANK_MANUF_ID', 'BANK_DISTRIB'];
cBanksManDistr22: array of string = ['BANK_MANUF_ID_WMDAID', 'BANK_MANUF_ID_EMDISID', 'BANK_DISTRIB_ID_WMDAID', 'BANK_DISTRIB_EMDISID'];
cINVENTORY = 'INVENTORY';
cVersionAttrib = 'SCHEMA_VERSION';
cv2_1 = '2.1';
cv2_2 = '2.2';
implementation
end.
|
{
*****************************************************************************
* *
* This file is part of the iPhone Laz Extension *
* *
* See the file COPYING.modifiedLGPL.txt, included in this distribution, *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
*****************************************************************************
}
unit XCodeProject;
{$mode objfpc}{$H+}
// todo: re-write, using RTTI
{$TYPEINFO ON}
interface
uses
contnrs, Classes, SysUtils, TypInfo;
const
UTF8Mark = '// !$*UTF8*$!';
FileType_AppWrapper = 'wrapper.application';
FileType_Bundle = FileType_AppWrapper;
FileType_PList = 'text.plist.xml';
// sourceTree = BUILT_PRODUCTS_DIR
type
TXCodeObjectID = string[24];
TStringValues = class(TStringList);
{ TXCodeObject }
TXCodeObject = class(TObject)
private
fOwner : TXCodeObject;
fChild : TFPList;
fValues : TStringList;
fID : TXCodeObjectID;
protected
procedure AddObject(const AName: String; AObject: TXCodeObject);
function GetChild(i: Integer): TXCodeObject;
function GetCount: Integer;
procedure Clear;
function GetValue(const AName: String): String;
procedure SetValue(const AName: String; const AValue: String);
public
class function isa: ShortString; virtual; abstract;
constructor Create;
destructor Destroy; override;
property Child[i: integer]: TXCodeObject read GetChild;
property ChildCount: Integer read GetCount;
property Owner: TXCodeObject read fOwner;
property ID: TXCodeObjectID read fID;
property StrValue[const AName: String]: String read GetValue write SetValue;
function GetChildObject(const AName: String): TXCodeObject;
function GetObjectArray(const AName: String): TFPObjectList;
function GetStringArray(const AName: String): TStringList;
function GetStringValues(const AName: String): TStringValues;
end;
TXCodeObjectClass = class of TXCodeObject;
{ TPBXFileReference }
TPBXFileReference = class(TXCodeObject)
private
function GetExplicitFileType: string;
function GetPath: String;
function GetSourceTree: String;
procedure SetExplicitFileType(const AValue: string);
procedure SetPath(const AValue: String);
procedure SetSourceTree(const AValue: String);
public
class function isa: ShortString; override;
property explicitFileType: string read GetExplicitFileType write SetExplicitFileType;
property path : String read GetPath write SetPath;
property sourceTree: String read GetSourceTree write SetSourceTree;
end;
// 0A7E1DA610EAD478000D7855 /* iPhoneApp.app */ =
{isa = PBXFileReference;
explicitFileType = wrapper.application;
includeInIndex = 0;
path = iPhoneApp.app;
sourceTree = BUILT_PRODUCTS_DIR; }
{isa = PBXFileReference;
lastKnownFileType = text.plist.xml;
path = "iPhoneApp-Info.plist"; sourceTree = "<group>"; }
TXCodeBuildPhase = class(TXCodeObject);
{ TPBXShellScriptBuildPhase }
TPBXShellScriptBuildPhase = class(TXCodeBuildPhase)
private
function GetBuildMask: Integer;
function GetShellPath: string;
function GetShellScript: String;
procedure SetBuildMask(const AValue: Integer);
procedure SetShellPath(const AValue: string);
procedure SetShellScript(const AValue: String);
public
constructor Create;
class function isa: ShortString; override;
property BuildActionMask : Integer read GetBuildMask write SetBuildMask;
property ShellPath : string read GetShellPath write SetShellPath;
property ShellScript : String read GetShellScript write SetShellScript;
end;
{ TPBXBuildFile }
TPBXBuildFile = class(TXCodeObject)
public
fileRef : TPBXFileReference;
constructor Create;
destructor Destroy; override;
class function isa: ShortString; override;
end;
{ TXCBuildConfiguration }
TXCBuildConfiguration = class(TXCodeObject)
private
function GetName: String;
procedure SetName(const AValue: String);
function GetBuildSettings: TStringValues;
public
class function isa: ShortString; override;
constructor Create;
destructor Destroy; override;
property name: String read GetName write SetName;
property Settings: TStringValues read GetBuildSettings;
end;
{ TXCConfigurationList }
TXCConfigurationList = class(TXCodeObject)
private
fConfigs : TFPObjectList;
protected
function GetConfig(i: integer): TXCBuildConfiguration;
function GetCount: Integer;
function GetName: string;
procedure SetName(const AValue: string);
function GetVisible: Boolean;
procedure SetVisible(AVisible: Boolean);
public
class function isa: ShortString; override;
constructor Create;
destructor Destroy; override;
function AddList: TXCBuildConfiguration;
property Config[i: Integer] : TXCBuildConfiguration read GetConfig;
property ConfigCount: Integer read GetCount;
property defaultVisible: Boolean read GetVisible write SetVisible;
property defaulConfigName: string read GetName write SetName;
end;
{ TPBXNativeTarget }
TPBXNativeTarget = class(TXCodeObject)
private
fConfigList : TXCConfigurationList;
fRef : TPBXFileReference;
function GetName: String;
function GetProductFile: TPBXFileReference;
function GetProductName: String;
function GetProductType: String;
procedure SetName(const AValue: String);
procedure SetProductName(const AValue: String);
procedure SetProductType(const AValue: String);
function GetConfigList: TXCConfigurationList;
public
constructor Create;
class function isa: ShortString; override;
function AddBuildConfig: TXCBuildConfiguration;
function AddScriptPhase: TPBXShellScriptBuildPhase;
property name: String read GetName write SetName;
property productName: String read GetProductName write SetProductName;
property productType: String read GetProductType write SetProductType;
property productFile: TPBXFileReference read GetProductFile;
end;
{ TPBXProject }
TPBXProject = class(TXCodeObject)
private
fConfigList : TXCConfigurationList;
function GetDirPath: string;
function GetRoot: String;
procedure SetDirPath(const AValue: string);
procedure SetRoot(const AValue: String);
protected
function GetConfigList: TXCConfigurationList;
function GetTargets: TFPObjectList;
function GetVersion: String;
procedure SetVersion(const AVersion: string);
public
constructor Create;
class function isa: ShortString; override;
function AddTarget: TPBXNativeTarget;
function AddBuildConfig: TXCBuildConfiguration;
property DirPath: string read GetDirPath write SetDirPath;
property Root: String read GetRoot write SetRoot;
property compatibilityVersion: String read GetVersion write SetVersion;
end;
{ TPBXGroup }
TPBXGroup = class(TXCodeObject)
protected
function GetPath: String;
procedure SetPath(const APath: String);
function GetSourceTree: String;
procedure SetSourceTree(const ATree: String);
public
class function isa: ShortString; override;
property Path: String read GetPath write SetPath;
property sourceTree: String read GetSourceTree write SetSourceTree;
end;
procedure WritePBXProjFile(RootObject: TXCodeObject; Dst: TStream);
procedure WritePBXProjFile(RootObject: TXCodeObject; const FileName: String);
implementation
const
BoolVal : array[Boolean] of String = ('false', 'true');
function isQuotedStr(const s: string): Boolean;
begin
Result:=(length(s)>=2) and (s[1] = '"') and (s[length(s)]='"');
end;
function QuotedStr(const s: string): String;
begin
if isQuotedStr(s) then Result:=s
else Result:='"'+s+'"';
end;
function UnquoteStr(const s: string): String;
begin
if not isQuotedStr(s) then Result:=s
else Result:=Copy(s, 2, length(s)-2);
end;
function GetBoolValue(xobj: TXCodeObject; const AName: String): boolean;
begin
Result:=xobj.StrValue[AName]=BoolVal[True];
end;
procedure SetBoolValue(xobj: TXCodeObject; const AName: String; AValue: Boolean);
begin
xobj.StrValue[AName]:=BoolVal[AValue];
end;
{ TXCConfigurationList }
function TXCConfigurationList.GetName: string;
begin
Result:=StrValue['defaultConfigurationName'];
end;
procedure TXCConfigurationList.SetName(const AValue: string);
begin
StrValue['defaultConfigurationName']:=AValue;
end;
function TXCConfigurationList.GetVisible: Boolean;
begin
Result:=GetBoolValue(Self, 'defaultConfigurationIsVisible');
end;
procedure TXCConfigurationList.SetVisible(AVisible: Boolean);
begin
SetBoolValue(Self, 'defaultConfigurationIsVisible', AVisible);
end;
function TXCConfigurationList.GetConfig(i: integer): TXCBuildConfiguration;
begin
Result:=TXCBuildConfiguration(fConfigs[i]);
end;
function TXCConfigurationList.GetCount: Integer;
begin
Result:=fConfigs.Count;
end;
class function TXCConfigurationList.isa: ShortString;
begin
Result:='XCConfigurationList';
end;
constructor TXCConfigurationList.Create;
begin
inherited Create;
fConfigs:=GetObjectArray('buildConfigurations');
end;
destructor TXCConfigurationList.Destroy;
begin
inherited Destroy;
end;
function TXCConfigurationList.AddList: TXCBuildConfiguration;
begin
Result:=TXCBuildConfiguration.Create;
AddObject('', Result);
fConfigs.Add(Result);
end;
{ TXCBuildConfiguration }
constructor TXCBuildConfiguration.Create;
begin
inherited Create;
GetStringValues('buildSettings');
end;
destructor TXCBuildConfiguration.Destroy;
begin
inherited Destroy;
end;
function TXCBuildConfiguration.GetName: String;
begin
Result:=GetValue('name');
end;
procedure TXCBuildConfiguration.SetName(const AValue: String);
begin
SetValue('name', AValue);
end;
function TXCBuildConfiguration.getBuildSettings: TStringValues;
begin
Result:=GetStringValues('buildSettings');
end;
class function TXCBuildConfiguration.isa: ShortString;
begin
Result:='XCBuildConfiguration';
end;
{ TPBXGroup }
function TPBXGroup.GetPath: String;
begin
Result:=StrValue['Path'];
end;
procedure TPBXGroup.SetPath(const APath: String);
begin
StrValue['Path']:=APath;
end;
function TPBXGroup.GetSourceTree: String;
begin
Result:=StrValue['sourceTree'];
end;
procedure TPBXGroup.SetSourceTree(const ATree: String);
begin
StrValue['sourceTree']:=ATree;
end;
class function TPBXGroup.isa: ShortString;
begin
Result:='PBXGroup';
end;
{ TPBXFileReference }
class function TPBXFileReference.isa: ShortString;
begin
Result:='PBXFileReference';
end;
function TPBXFileReference.GetExplicitFileType: string;
begin
Result:=GetValue('explicitFileType');
end;
function TPBXFileReference.GetPath: String;
begin
Result:=GetValue('path');
end;
function TPBXFileReference.GetSourceTree: String;
begin
Result:=GetValue('sourceTree');
end;
procedure TPBXFileReference.SetExplicitFileType(const AValue: string);
begin
SetValue('explicitFileType', AValue);
end;
procedure TPBXFileReference.SetPath(const AValue: String);
begin
SetValue('path', AValue);
end;
procedure TPBXFileReference.SetSourceTree(const AValue: String);
begin
SetValue('sourceTree', AValue);
end;
{ TPBXBuildFile }
constructor TPBXBuildFile.Create;
begin
fileRef:=TPBXFileReference.Create;
end;
destructor TPBXBuildFile.Destroy;
begin
inherited Destroy;
end;
class function TPBXBuildFile.isa: ShortString;
begin
Result:='PBXBuildFile';
end;
{ TXCodeObject }
procedure TXCodeObject.AddObject(const AName: String; AObject: TXCodeObject);
begin
AObject.fOwner:=Self;
fChild.Add(AObject);
if AName<>'' then
fValues.AddObject(AName, AObject);
end;
function TXCodeObject.GetChild(i: Integer): TXCodeObject;
begin
Result:=TXCodeObject(fChild[i]);
end;
function TXCodeObject.GetCount: Integer;
begin
Result:=fChild.Count;
end;
procedure TXCodeObject.Clear;
var
i : integer;
begin
for i:=0 to fValues.Count-1 do begin
if Assigned(fValues.Objects[i]) and not (fValues.Objects[i] is TXCodeObject) then
fValues.Objects[i].Free;
end;
fValues.Clear;
for i:=0 to fChild.Count-1 do
TObject(fChild[i]).Free;
fChild.Clear;
end;
function TXCodeObject.GetValue(const AName: String): String;
begin
Result:=fValues.Values[AName];
end;
procedure TXCodeObject.SetValue(const AName, AValue: String);
begin
fValues.Values[AName]:=Avalue;
end;
constructor TXCodeObject.Create;
var
q : Qword;
begin
inherited;
fChild:=TFPList.Create;
fValues:=TStringList.Create;
Q:=PtrUInt(Self);
fID:=hexStr(q, 24);
end;
destructor TXCodeObject.Destroy;
begin
Clear;
fChild.Free;
fValues.Free;
inherited Destroy;
end;
function TXCodeObject.GetChildObject(const AName: String): TXCodeObject;
var
i : integer;
begin
Result:=nil;
i:=fValues.IndexOfName(AName);
if i>=0 then
if fValues.Objects[i] is TXCodeObject then
Result:=TXCodeObject(fValues.Objects[i]);
end;
function TXCodeObject.GetObjectArray(const AName: String): TFPObjectList;
var
i : integer;
begin
i:=fValues.IndexOfName(AName);
if i<0 then begin
Result:=TFPObjectList.Create(false);
fValues.AddObject(AName, Result);
end else begin
if not (fValues.Objects[i] is TFPObjectList) then
Result:=nil
else
Result:= TFPObjectList(fValues.Objects[i]);
end;
end;
function TXCodeObject.GetStringArray(const AName: String): TStringList;
var
i : integer;
begin
i:=fValues.IndexOfName(AName);
if i<0 then begin
Result:=TStringList.Create;
fValues.AddObject(AName, Result);
end else begin
if not (fValues.Objects[i] is TStringList) then
Result:=nil
else
Result:= TStringList(fValues.Objects[i]);
end;
end;
function TXCodeObject.GetStringValues(const AName: String): TStringValues;
var
i : integer;
begin
i:=fValues.IndexOfName(AName);
if i<0 then begin
Result:=TStringValues.Create;
fValues.Values[AName]:='?';
i:=fValues.IndexOfName(AName);
fValues.Objects[i]:=Result;
//i:=fValues.AddObject(AName + ' = ', Result);
end else begin
if not (fValues.Objects[i] is TStringValues) then
Result:=nil
else
Result:= TStringValues(fValues.Objects[i]);
end;
end;
type
{ TPBXWriter }
TPBXWriter = class(TObject)
private
fDst : TStream;
fPrefix : String;
fIndent : String;
protected
procedure WriteItems(data:TObject;arg:pointer);
public
constructor Create(Dst: TStream);
destructor Destroy; override;
procedure Indent;
procedure Unindent;
procedure WriteLn(const utf8: AnsiString);
end;
{ TPBXWriter }
procedure TPBXWriter.WriteItems(data: TObject; arg: pointer);
var
list : TFPList;
i : Integer;
j : Integer;
k : Integer;
xobj : TXCodeObject;
vobj : TObject;
sublist : TFPObjectList;
st : TStringList;
prefix : String;
begin
list:=TFPList(data);
if not Assigned(list) or (list.Count=0) then Exit;
for i:=0 to list.Count-1 do begin
xobj:=TXCodeObject(list[i]);
Self.WriteLn( xobj.ID + ' = {');
Self.Indent;
Self.Writeln('isa = ' + xobj.isa+';');
for j:=0 to xobj.fValues.Count - 1 do begin
vobj:=xobj.fValues.Objects[j];
if not Assigned(vobj) then begin
prefix:=xobj.fValues.Names[j] + ' = ';
Writeln(prefix + xobj.fValues.ValueFromIndex[j]+';')
end else begin
if vobj is TXCodeObject then begin
prefix:=xobj.fValues[j] + ' = ';
Writeln(prefix + TXCodeObject(vobj).ID+';')
end else if vobj is TStringValues then begin
st:=TStringValues(vobj);
prefix:=xobj.fValues.Names[j]+' = ';
Self.Writeln(prefix + ' {');
Self.Indent;
for k:=0 to st.Count-1 do
Self.WritelN(st.Names[k] + ' = ' + st.ValueFromIndex[k] + ';' );
Self.Unindent;
Self.Writeln('};')
end else if vobj is TStringList then begin
prefix:=xobj.fValues[j] + ' = ';
st:=TStringValues(vobj);
Self.Writeln(prefix + ' (');
Self.Indent;
for k:=0 to st.Count-1 do
Self.WritelN(' ' + st[k] + ',' );
Self.Unindent;
Self.Writeln(');')
end else if vobj is TFPObjectList then begin
prefix:=xobj.fValues[j] + ' = ';
sublist:=TFPObjectList(vobj);
Self.Writeln(prefix + '(');
Self.Indent;
for k:=0 to sublist.Count-1 do
Self.WritelN(TXCodeObject(sublist[k]).ID+',');
Self.Unindent;
Self.Writeln(');')
end;
end;
end;
Self.Unindent;
Self.WritelN('};');
end;
end;
constructor TPBXWriter.Create(Dst: TStream);
begin
inherited Create;
fDst:=Dst;
fIndent:=#9;
end;
destructor TPBXWriter.Destroy;
begin
inherited Destroy;
end;
procedure TPBXWriter.Indent;
begin
fPrefix:=fPrefix+fIndent;
end;
procedure TPBXWriter.Unindent;
begin
fPrefix:=Copy(fPrefix,1, length(fPrefix)-length(fIndent));
end;
procedure TPBXWriter.WriteLn(const utf8: AnsiString);
const
LF : string = #10;
begin
if utf8='' then Exit;
if fPrefix<>'' then fDst.Write(fPrefix[1], length(fPrefix));
fDst.Write(utf8[1], length(utf8));
fDst.Write(LF[1], length(LF));
end;
procedure WritePBXProjFile(RootObject: TXCodeObject; Dst: TStream);
var
lists : TFPHashObjectList; // list of TFPList
items : TFPList;
p : TXCodeObject;
stack : TFPList;
i : Integer;
xobjcount : Integer;
wr : TPBXWriter;
begin
if RootObject=nil then Exit;
lists:=TFPHashObjectList.Create(True);
stack:=TFPList.Create;
xobjcount:=1;
stack.Add(RootObject);
while stack.Count > 0 do begin
p:= TXCodeObject(stack[0]);
items:=TFPList(lists.Find(p.isa));
if not Assigned(items) then begin
items:=TFPList.Create;
lists.Add(p.isa, items);
end;
items.Add(p);
inc(xobjcount, p.ChildCount);
for i:=0 to p.ChildCount-1 do stack.Add(p.Child[i]);
stack.Delete(0);
end;
stack.Free;
wr:=TPBXWriter.Create(Dst);
wr.WriteLn(UTF8Mark);
wr.WriteLn('{');
wr.Indent;
wr.WriteLn('archiveVersion = 1;');
wr.WriteLn('classes = {};');
wr.WriteLn('objectVersion = 45;');
wr.WriteLn('objects = { ');
wr.Indent;
lists.ForEachCall(@wr.WriteItems, nil);
wr.Unindent;
wr.WriteLn('};');
wr.WriteLn('rootObject = '+RootObject.ID+';');
wr.Unindent;
wr.WriteLn('}');
wr.Free;
lists.Free;
end;
procedure WritePBXProjFile(RootObject: TXCodeObject; const FileName: String);
var
fs : TFileStream;
begin
fs:=TFileStream.Create(FileName, fmCreate);
WritePBXProjFile(RootOBject, fs);
fs.Free;
end;
{ TXCProject }
function TPBXProject.GetDirPath: string;
begin
Result:=UnquoteStr(StrValue['projectDirPath']);
end;
function TPBXProject.GetRoot: String;
begin
Result:=UnquoteStr(StrValue['projectRoot']);
end;
procedure TPBXProject.SetDirPath(const AValue: string);
begin
StrValue['projectDirPath']:=QuotedStr(AValue);
end;
procedure TPBXProject.SetRoot(const AValue: String);
begin
StrValue['projectRoot']:=QuotedStr(AValue);
end;
function TPBXProject.GetConfigList: TXCConfigurationList;
begin
if not Assigned(fConfigList) then begin
fConfigList:=TXCConfigurationList.Create;
AddObject('buildConfigurationList', fConfigList);
end;
Result:=fConfigList;
end;
function TPBXProject.GetTargets: TFPObjectList;
begin
Result:=GetObjectArray('targets');
end;
function TPBXProject.GetVersion: String;
begin
Result:=GetValue('compatibilityVersion');
end;
procedure TPBXProject.SetVersion(const AVersion: string);
begin
SetValue('compatibilityVersion', AVersion);
end;
constructor TPBXProject.Create;
begin
inherited Create;
Root:='';
DirPath:='';
end;
class function TPBXProject.isa: ShortString;
begin
Result:='PBXProject';
end;
function TPBXProject.AddTarget: TPBXNativeTarget;
var
list : TFPObjectList;
begin
// adding a target forces configuration list
//if fConfigList=nil then GetConfigList;
list:=GetObjectArray('targets');
Result:=TPBXNativeTarget.Create;
AddObject('', Result);
list.Add(Result);
end;
function TPBXProject.AddBuildConfig: TXCBuildConfiguration;
begin
Result:=GetConfigList.AddList;
end;
{ TPBXNativeTarget }
function TPBXNativeTarget.GetName: String;
begin
Result:=GetValue('name');
end;
function TPBXNativeTarget.GetProductFile: TPBXFileReference;
begin
if not Assigned(fRef) then begin
fRef:=TPBXFileReference.Create;
AddObject('productReference', fRef);
end;
Result:=fRef;
end;
procedure TPBXNativeTarget.SetName(const AValue: String);
begin
SetValue('name', AValue);
end;
function TPBXNativeTarget.GetProductName: String;
begin
Result:=GetValue('productName');
end;
procedure TPBXNativeTarget.SetProductName(const AValue: String);
begin
SetValue('productName', AValue);
end;
function TPBXNativeTarget.GetProductType: String;
begin
Result:=GetValue('productType');
end;
procedure TPBXNativeTarget.SetProductType(const AValue: String);
begin
SetValue('productType', AValue)
end;
function TPBXNativeTarget.GetConfigList: TXCConfigurationList;
begin
if not Assigned(fConfigList) then begin
fConfigList:=TXCConfigurationList.Create;
AddObject('buildConfigurationList', fConfigList);
end;
Result:=fConfigList;
end;
constructor TPBXNativeTarget.Create;
begin
inherited Create;
productType := '"com.apple.product-type.application"';
GetObjectArray('buildPhases');
GetObjectArray('buildRules');
GetObjectArray('dependencies');
end;
class function TPBXNativeTarget.isa: ShortString;
begin
Result:='PBXNativeTarget';
end;
function TPBXNativeTarget.AddBuildConfig: TXCBuildConfiguration;
begin
Result:=GetConfigList.AddList;
end;
function TPBXNativeTarget.AddScriptPhase: TPBXShellScriptBuildPhase;
begin
Result:=TPBXShellScriptBuildPhase.Create;
AddObject('', Result);
GetObjectArray('buildPhases').Add(Result);
end;
{ TPBXShellScriptBuildPhase }
function TPBXShellScriptBuildPhase.GetBuildMask: Integer;
begin
Result:=StrToIntDef( GetValue('buildActionMask'), 0);
end;
procedure TPBXShellScriptBuildPhase.SetBuildMask(const AValue: Integer);
begin
SetValue('buildActionMask', IntToStr(AValue));
end;
function TPBXShellScriptBuildPhase.GetShellPath: string;
begin
Result:=GetValue('shellPath');
end;
procedure TPBXShellScriptBuildPhase.SetShellPath(const AValue: string);
begin
SetValue('shellPath', AValue);
end;
function TPBXShellScriptBuildPhase.GetShellScript: String;
begin
Result:=UnquoteStr(GetValue('shellScript'));
end;
procedure TPBXShellScriptBuildPhase.SetShellScript(const AValue: String);
begin
SetValue('shellScript', QuotedStr(AValue));
end;
constructor TPBXShellScriptBuildPhase.Create;
begin
inherited Create;
ShellPath:='/bin/sh';
GetObjectArray('files');
GetObjectArray('inputPaths');
GetObjectArray('outputPaths');
end;
class function TPBXShellScriptBuildPhase.isa: ShortString;
begin
Result:='PBXShellScriptBuildPhase';
end;
end.
|
unit cVisit;
interface
uses cpac, cDoctor, cDiagnoses, fDM;
type
TVisit =Class
public
id:integer;
dateVisit:Tdate;
Pac:TPacient;
Doc:TDoctor;
Diag:TDiagnoses;
procedure Get(Find_id: integer);
procedure New;
procedure Change;
procedure Del(Find_id: integer);
constructor Create;
destructor Destroy;
End;
implementation
{ TVisit }
procedure TVisit.Change;
begin
with dm.QVisit do
begin
close;
sql.clear;
sql.Add('update Visit ');
sql.Add('set date_visit=:date_visit, pac=:pac, doctor=:doctor, ');
sql.Add('diagnos=:diagnos where id=:id');
parameters.ParamValues['id']:=id;
parameters.ParamValues['date_visit']:=dateVisit;
parameters.ParamValues['pac']:=pac.id;
parameters.ParamValues['doctor']:=doc.id;
parameters.ParamValues['diagnos']:=diag.id;
ExecSQl;
end;
end;
constructor TVisit.Create;
begin
doc:=TDoctor.Create;
pac:=TPacient.Create;
Diag:=TDiagnoses.Create;
end;
procedure TVisit.Del(Find_id: integer);
begin
with dm.QVisit do
begin
close;
sql.clear;
sql.Add('delete Visit where id=:id');
parameters.ParamValues['id']:=Find_id;
ExecSQL;
end;
end;
destructor TVisit.Destroy;
begin
pac.Destroy;
doc.Destroy;
diag.Destroy;
end;
procedure TVisit.Get(Find_id: integer);
begin
with dm.QVisit do
begin
close;
sql.clear;
sql.Add('select date_visit, pac, doctor, diagnos from Visit where id=:id');
parameters.ParamValues['id']:=Find_id;
open;
end;
id:=find_id;
dateVisit:=dm.QVisit.FieldByName('date_visit').AsDateTime;
pac.GetAtr(dm.QVisit.FieldByName('pac').AsInteger);
doc.GetAtr(dm.QVisit.FieldByName('doctor').AsInteger);
diag.GetAtr(dm.QVisit.FieldByName('diagnos').AsInteger);
end;
procedure TVisit.New;
begin
with dm.QVisit do
begin
close;
sql.clear;
sql.Add('insert Visit (date_visit, pac, doctor, diagnos)');
sql.Add('values (:date_visit, :pac, :doctor, :diagnos)');
parameters.ParamValues['date_visit']:=dateVisit;
parameters.ParamValues['pac']:=pac.id;
parameters.ParamValues['doctor']:=doc.id;
parameters.ParamValues['diagnos']:=diag.id;
ExecSQl;
end;
end;
end.
|
unit ctFakeBoxStrings;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VT"
// Автор: Люлин А.В.
// Модуль: "w:/common/components/gui/Garant/VT/ComboTree/ctFakeBoxStrings.pas"
// Начат: 07.07.2008 23:02
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VT::ComboTree::TctFakeBoxStrings
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\common\components\gui\Garant\VT\vtDefine.inc}
interface
uses
FakeBox,
ComboBoxStrings,
Classes
;
type
TctFakeBoxStrings = class(TComboBoxStrings)
private
// private fields
f_SubOwner : TFakeBox;
{* Поле для свойства SubOwner}
public
// overridden public methods
procedure Assign(Source: TPersistent); override;
procedure Clear; override;
public
// public methods
constructor Create(anOwner: TFakeBox); reintroduce;
protected
// protected properties
property SubOwner: TFakeBox
read f_SubOwner;
end;//TctFakeBoxStrings
implementation
uses
l3String
;
// start class TctFakeBoxStrings
constructor TctFakeBoxStrings.Create(anOwner: TFakeBox);
//#UC START# *487268F8027E_487268A90374_var*
//#UC END# *487268F8027E_487268A90374_var*
begin
//#UC START# *487268F8027E_487268A90374_impl*
inherited Create;
f_SubOwner := anOwner;
//#UC END# *487268F8027E_487268A90374_impl*
end;//TctFakeBoxStrings.Create
procedure TctFakeBoxStrings.Assign(Source: TPersistent);
//#UC START# *478CF34E02CE_487268A90374_var*
var
l_Index : Integer;
l_Same : Boolean;
//#UC END# *478CF34E02CE_487268A90374_var*
begin
//#UC START# *478CF34E02CE_487268A90374_impl*
if (Source is TStrings) then
begin
if (Count = TStrings(Source).Count) then
begin
l_Same := true;
for l_Index := 0 to Pred(Count) do
if not l3Same(ItemW[l_Index], TStrings(Source)[l_Index]) then
begin
l_Same := false;
break;
end;//not l3Same(ItemW[l_Index], TStrings(Source)[l_Index])
if l_Same then
Exit;
end;//Count = TStrings(Source).Count
end;//Source is TStrings
inherited;
//#UC END# *478CF34E02CE_487268A90374_impl*
end;//TctFakeBoxStrings.Assign
procedure TctFakeBoxStrings.Clear;
//#UC START# *47B1C16D0188_487268A90374_var*
//#UC END# *47B1C16D0188_487268A90374_var*
begin
//#UC START# *47B1C16D0188_487268A90374_impl*
if (Count > 0) then
f_SubOwner.ItemIndex := -1;
inherited;
//#UC END# *47B1C16D0188_487268A90374_impl*
end;//TctFakeBoxStrings.Clear
end. |
unit Model.ExtratosExpressas;
interface
uses Common.ENum, FireDAC.Comp.Client, System.Classes;
type
TExtratosExpressas = class
private
var
FId: Integer;
FAgente: Integer;
FEntregador: Integer;
FDataInicio: TDate;
FDataFinal: TDate;
FDataPagamento: TDate;
FVolumes: Integer;
FEntregas: Integer;
FAtrasos: Integer;
FVolumesExtra: Double;
FSLA: Double;
FVerba: Double;
FValorEntregas: Double;
FValorVolumesExtra: Double;
FValorProducao: Double;
FValorCreditos: Double;
FValorRestricao: Double;
FValorExtravio: Double;
FValorDebitos: Double;
FValorTotalCreditos: Double;
FValorTotalDebitos: Double;
FValorTotalGeral: Double;
FFechado: Integer;
FTotalVerbaFranquia: Double;
FLog: String;
FPFP: Integer;
FAcao: TAcao;
FExtrato: String;
FNomeEntregador: String;
FNomeAgente: String;
public
property Id: Integer read FId write FId;
property Agente: Integer read FAgente write FAgente;
property Entregador: Integer read FEntregador write FEntregador;
property DataInicio: TDate read FDataInicio write FDataInicio;
property DataFinal: TDate read FDataFinal write FDataFinal;
property DataPagamento: TDate read FDataPagamento write FDataPagamento;
property Volumes: Integer read FVolumes write FVolumes;
property Entregas: Integer read FEntregas write FEntregas;
property Atrasos: Integer read FAtrasos write FAtrasos;
property VolumesExtra: Double read FVolumesExtra write FVolumesExtra;
property SLA: Double read FSLA write FSLA;
property Verba: Double read FVerba write FVerba;
property ValorEntregas: Double read FValorEntregas write FValorEntregas;
property ValorVolumesExtra: Double read FValorVolumesExtra write FValorVolumesExtra;
property ValorProducao: Double read FValorProducao write FValorProducao;
property ValorCreditos: Double read FValorCreditos write FValorCreditos;
property ValorRestricao: Double read FValorRestricao write FValorRestricao;
property ValorExtravio: Double read FValorExtravio write FValorExtravio;
property ValorDebitos: Double read FValorDebitos write FValorDebitos;
property ValorTotalCreditos: Double read FValorTotalCreditos write FValorTotalCreditos;
property ValorTotalDebitos: Double read FValorTotalDebitos write FValorTotalDebitos;
property ValorTotalGeral: Double read FValorTotalGeral write FValorTotalGeral;
property Fechado: Integer read FFechado write FFechado;
property TotalVerbaFranquia: Double read FTotalVerbaFranquia write FTotalVerbaFranquia;
property PFP: Integer read FPFP write FPFP;
property Log: String read FLog write FLog;
property Extrato: String read FExtrato write FExtrato;
property NomeAgente: String read FNomeAgente write FNomeAgente;
property NomeEntregador: String read FNomeEntregador write FNomeEntregador;
property Acao: TAcao read FAcao write FAcao;
function GetID(): Integer;
function Gravar(): Boolean;
function CancelaExtrato(aParam: array of Variant): Boolean;
function Localizar(aParam: array of Variant): TFDQuery;
function DatasPagamentos(iBase: Integer): TStringList;
end;
implementation
{ TExtratosExpressas }
uses DAO.ExtratosExpressas;
function TExtratosExpressas.CancelaExtrato(aParam: array of Variant): Boolean;
var
extratosDAO : TExtratosExpressasDAO;
begin
try
extratosDAO := TExtratosExpressasDAO.Create;
Result := extratosDAO.CancelaExtrato(aParam);
finally
extratosDAO.Free;
end;
end;
function TExtratosExpressas.DatasPagamentos(iBase: Integer): TStringList;
var
extratosDAO : TExtratosExpressasDAO;
begin
try
extratosDAO := TExtratosExpressasDAO.Create;
Result := extratosDAO.DatasPagamentos(iBase);
finally
extratosDAO.Free;
end;
end;
function TExtratosExpressas.GetID: Integer;
var
extratosDAO : TExtratosExpressasDAO;
begin
try
extratosDAO := TExtratosExpressasDAO.Create;
Result := extratosDAO.GetID;
finally
extratosDAO.Free;
end;
end;
function TExtratosExpressas.Gravar: Boolean;
var
extratosDAO : TExtratosExpressasDAO;
begin
try
Result := False;
extratosDAO := TExtratosExpressasDAO.Create;
case FAcao of
Common.ENum.tacIncluir: Result := extratosDAO.Insert(Self);
Common.ENum.tacAlterar: Result := extratosDAO.Update(Self);
Common.ENum.tacExcluir: Result := extratosDAO.Delete(Self);
end;
finally
extratosDAO.Free;
end;
end;
function TExtratosExpressas.Localizar(aParam: array of Variant): TFDQuery;
var
extratosDAO : TExtratosExpressasDAO;
begin
try
extratosDAO := TExtratosExpressasDAO.Create;
Result := extratosDAO.FindExtrato(aParam);
finally
extratosDAO.Free;
end;
end;
end.
|
unit Literals;
interface
procedure SetBasePath(const transfilespath : string);
procedure SetLanguage(languageid : integer);
function GetLiteral(const id : string) : string;
function GetFormattedLiteral(const id : string; const Args : array of const) : string;
implementation
uses
Classes, Windows, SysUtils;
const
cLiteralsTableName = 'Literals';
var
vLiterals : TStringList;
vTransFilesPath : string;
procedure SetBasePath(const transfilespath : string);
begin
vTransFilesPath := transfilespath;
if (vTransFilesPath <> '') and (vTransFilesPath[length(vTransFilesPath)] <> '\')
then vTransFilesPath := vTransFilesPath + '\';
end;
procedure SetLanguage(languageid : integer);
begin
if FileExists(vTransFilesPath + IntToStr(languageid) + '\' + cLiteralsTableName + '.tln')
then
begin
vLiterals.Clear;
vLiterals.LoadFromFile(vTransFilesPath + IntToStr(languageid) + '\' + cLiteralsTableName + '.tln');
end;
end;
function GetLiteral(const id : string) : string;
begin
Result := vLiterals.Values[id];
end;
function GetFormattedLiteral(const id : string; const Args : array of const) : string;
begin
try
Result := Format(GetLiteral(id), Args);
except
Result := GetLiteral(id);
end;
end;
initialization
vLiterals := TStringList.Create;
finalization
vLiterals.Free;
end.
|
unit DVBNetworkForma;
{$I defines.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, FIBDataSet, pFIBDataSet, OkCancel_frame, FIBDatabase,
pFIBDatabase, StdCtrls, DBCtrls, Mask, DBCtrlsEh, ExtDlgs, uDBImages;
type
TDVBNetworkForm = class(TForm)
OkCancelFrame1: TOkCancelFrame;
dsNetwork: TpFIBDataSet;
srcNetwork: TDataSource;
trWrite: TpFIBTransaction;
edtNAME: TDBEditEh;
edtTIMEOFFSET: TDBNumberEditEh;
edtNID: TDBNumberEditEh;
GroupBoxPID: TGroupBox;
chkNIT: TDBCheckBoxEh;
chkSDT: TDBCheckBoxEh;
chkTDT: TDBCheckBoxEh;
GroupBoxEIT: TGroupBox;
chkDescParental: TDBCheckBoxEh;
chkDescContent: TDBCheckBoxEh;
chkDescExtended: TDBCheckBoxEh;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
DBMemo1: TDBMemoEh;
Label5: TLabel;
lbl1: TLabel;
cbLang: TDBComboBoxEh;
lbl2: TLabel;
cbCOUNTRY: TDBComboBoxEh;
edtONID: TDBNumberEditEh;
lbl3: TLabel;
procedure OkCancelFrame1bbOkClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DBEditEh2KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
function DescriptorsToStr: String;
function PIDsToStr: String;
procedure SetPID(const pid: string);
procedure StrToDescriptors;
procedure StrToPIDs;
public
{ Public declarations }
end;
function EditDVBNetwork(const aDVBN_ID: Int64; const Mode: integer = 1): Int64;
implementation
uses
DM;
{$R *.dfm}
function EditDVBNetwork(const aDVBN_ID: Int64; const Mode: integer = 1): Int64;
var
DVBNetworkForm: TDVBNetworkForm;
begin
result := -1;
DVBNetworkForm := TDVBNetworkForm.Create(Application);
with DVBNetworkForm do
try
dsNetwork.ParamByName('DVBN_ID').AsInt64 := aDVBN_ID;
dsNetwork.Open;
StrToDescriptors;
StrToPIDs;
if Mode <> 0
then begin
if aDVBN_ID > 0
then dsNetwork.Edit
else begin
dsNetwork.Insert;
end;
end;
if ShowModal = mrOk
then begin
if aDVBN_ID = -1
then dsNetwork['DVBN_ID'] := dmMain.dbTV.Gen_Id('GEN_OPERATIONS_UID', 1);
dsNetwork['DESCRIPTORS'] := DescriptorsToStr;
dsNetwork['PIDS'] := PIDsToStr;
dsNetwork.Post;
result := dsNetwork['DVBN_ID'];
end
else begin
if dsNetwork.State in [dsEdit, dsInsert]
then dsNetwork.Cancel;
end;
finally free
end;
end;
procedure TDVBNetworkForm.DBEditEh2KeyPress(Sender: TObject; var Key: Char);
begin
if ((UpCase(Key) < 'A') or (UpCase(Key) > 'Z'))
then Key := #0;
end;
procedure TDVBNetworkForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN)
then OkCancelFrame1bbOkClick(Sender);
end;
procedure TDVBNetworkForm.OkCancelFrame1bbOkClick(Sender: TObject);
begin
OkCancelFrame1.actExitExecute(Sender);
end;
function TDVBNetworkForm.DescriptorsToStr: String;
begin
//
// ExtendedEventDescriptor - расширеное описание
// ParentalRatingDescriptor - возрастной контроль
// ContentDescriptor - жанр
result := '';
if chkDescExtended.Checked
then result := result + 'ExtendedEventDescriptor, ';
if chkDescParental.Checked
then result := result + 'ParentalRatingDescriptor, ';
if chkDescContent.Checked
then result := result + 'ContentDescriptor, ';
if result <> ''
then result := Copy(result, 1, Length(result) - 2);
end;
function TDVBNetworkForm.PIDsToStr: String;
var
PIDs: TStringList;
begin
{
BAT - Bouquet Association Table
CAT - Conditional Access Table
CIT - Content Identifier Table
DIT - Discontinuity Information Table
EIT - Event Information Table
NIT - Network Information Table
PAT - Program Association Table
RNT - RAR Notification Table
RST - Running Status Table
SDT - Service Description Table
SIT - Selection Information Table
ST - Stuffing Table
TDT - Time and Date Table
TOT - Time Offset Table
TSDT- Transport Stream Description Table
}
result := '';
PIDs := TStringList.Create;
try
PIDs.Delimiter := ',';
if chkNIT.Checked
then PIDs.Add('NIT');
if chkTDT.Checked
then begin
PIDs.Add('TDT');
PIDs.Add('TOT');
end;
if chkSDT.Checked
then PIDs.Add('SDT');
result := PIDs.DelimitedText;
finally PIDs.free
end;
end;
procedure TDVBNetworkForm.StrToDescriptors;
var
s: string;
begin
if dsNetwork.FieldByName('DESCRIPTORS').IsNull
then Exit;
s := AnsiUpperCase(dsNetwork['DESCRIPTORS']);
chkDescExtended.Checked := (Pos('EXTENDEDEVENTDESCRIPTOR', s) > 0);
chkDescParental.Checked := (Pos('PARENTALRATINGDESCRIPTOR', s) > 0);
chkDescContent.Checked := (Pos('CONTENTDESCRIPTOR', s) > 0);
end;
procedure TDVBNetworkForm.SetPID(const pid: string);
begin
if pid = 'SDT'
then chkSDT.Checked := True
else if pid = 'NIT'
then chkNIT.Checked := True
else if pid = 'TDT'
then chkTDT.Checked := True
else if pid = 'TOT'
then chkTDT.Checked := True;
end;
procedure TDVBNetworkForm.StrToPIDs;
var
s: string;
i: integer;
PIDs: TStringList;
begin
if dsNetwork.FieldByName('PIDS').IsNull
then Exit;
s := AnsiUpperCase(dsNetwork['PIDS']);
{
BAT - Bouquet Association Table
CAT - Conditional Access Table
CIT - Content Identifier Table
DIT - Discontinuity Information Table
EIT - Event Information Table
NIT - Network Information Table
PAT - Program Association Table
RNT - RAR Notification Table
RST - Running Status Table
SDT - Service Description Table
SIT - Selection Information Table
ST - Stuffing Table
TDT - Time and Date Table
TOT - Time Offset Table
TSDT- Transport Stream Description Table
}
PIDs := TStringList.Create;
try
PIDs.Delimiter := ',';
PIDs.DelimitedText := s;
for i := 0 to PIDs.Count - 1 do begin
s := Trim(PIDs[i]);
SetPID(s);
end;
finally PIDs.free
end;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.RTTI.fpc.Compatibility (only freepascal)
Description : Delphi compatibility RTTI functions
Author : Kike Pérez
Version : 1.0
Created : 20/08/2018
Modified : 25/08/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
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 Quick.Rtti.fpc.Compatibility;
{$i QuickLib.inc}
interface
uses
SysUtils,
Rtti;
type
TValueHelper = record helper for TValue
function AsVariant : Variant;
end;
implementation
{ TValueHelper }
function TValueHelper.AsVariant: Variant;
begin
case Kind of
tkShortString, tkWideString, tkAnsiString, tkUString : Result := AsString;
tkInteger : result := IntToStr(AsInteger);
tkInt64 : Result := IntToStr(AsInt64);
tkBool : Result := BoolToStr(AsBoolean, True);
tkFloat : Result := FloatToStr(AsExtended);
else
Result := '';
end;
end;
end.
|
unit Model.PlanilhaEntradaTFO;
interface
uses Generics.Collections, System.Classes, System.SysUtils;
type
TPlanilhaEntradaTFO = class
private
FContainer: String;
FLogradouro: String;
FPrevisao: String;
FPeso: String;
FCodigoDestino: String;
FBairro: String;
FAltura: String;
FExpedicao: String;
FNossoNumero: String;
FNomeEntregador: String;
FAosCuidados: String;
FCEP: STring;
FNomeConsumidor: String;
FLargura: String;
FStatus: String;
FNomeDestiono: String;
FVolume: String;
FValorVerba: String;
FComplemento: String;
FCodigoCliente: String;
FValorProuto: String;
FComprimento: String;
FDescricaoStatus: String;
FCidade: String;
FTelefone: String;
FNumeroNF: String;
FMensagem: String;
FPlanilha: TObjectList<TPlanilhaEntradaTFO>;
public
property CodigoDestino : String read FCodigoDestino write FCodigoDestino;
property NomeDestino : String read FNomeDestiono write FNomeDestiono;
property NossoNumero: String read FNossoNumero write FNossoNumero;
property CodigoCliente: String read FCodigoCliente write FCodigoCliente;
property NumeroNF: String read FNumeroNF write FNumeroNF;
property NomeConsumidor: String read FNomeConsumidor write FNomeConsumidor;
property AosCuidados: String read FAosCuidados write FAosCuidados;
property Logradouro: String read FLogradouro write FLogradouro;
property Complemento: String read FComplemento write FComplemento;
property Bairro: String read FBairro write FBairro;
property Cidade: String read FCidade write FCidade;
property CEP: STring read FCEP write FCEP;
property Telefone: String read FTelefone write FTelefone;
property Expedicao: String read FExpedicao write FExpedicao;
property Previsao: String read FPrevisao write FPrevisao;
property Status: String read FStatus write FStatus;
property DescricaoStatus: String read FDescricaoStatus write FDescricaoStatus;
property NomeEntregador: String read FNomeEntregador write FNomeEntregador;
property Container: String read FContainer write FContainer;
property ValorProuto: String read FValorProuto write FValorProuto;
property ValorVerba: String read FValorVerba write FValorVerba;
property Altura: String read FAltura write FAltura;
property Largura: String read FLargura write FLargura;
property Comprimento: String read FComprimento write FComprimento;
property Peso: String read FPeso write FPeso;
property Volume: String read FVolume write FVolume;
property MensagemProcesso: String read FMensagem write FMensagem;
property Planilha: TObjectList<TPlanilhaEntradaTFO> read FPlanilha write FPlanilha;
function GetPlanilha(sFile: String): Boolean;
end;
implementation
{ TPlanilhaEntradaTFO }
uses Common.Utils;
function TPlanilhaEntradaTFO.GetPlanilha(sFile: String): boolean;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
i : Integer;
lstRemessa: TStringList;
iIndex: Integer;
bFlag: Boolean;
begin
try
REsult := False;
FPlanilha := TObjectList<TPlanilhaEntradaTFO>.Create;
if not FileExists(sFile) then
begin
FMensagem := 'Arquivo ' + sFile + ' não foi encontrado!';
Exit;
end;
AssignFile(ArquivoCSV, sFile);
if sFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
lstRemessa := TStringList.Create;
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
if Copy(sLinha, 0, 38) <> 'CONSULTA DE ENTREGAS NA WEB POR STATUS' then
begin
FMensagem := 'Arquivo informado não foi identificado como a Planilha de Entrada de Entregas!';
Exit;
end;
sDetalhe.DelimitedText := sLinha;
if sDetalhe.Count <> 26 then
begin
FMensagem := 'Quantidade de Colunas não indica ser da Planilha de Entrada de Entregas!';
Exit;
end;
i := 0;
iIndex := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
bFlag := False;
if TUtils.ENumero(sDetalhe[0]) then
begin
if StrToIntDef(sDetalhe[25], 1) > 1 then
begin
if not lstRemessa.Find(sDetalhe[2], iIndex) then
begin
lstRemessa.Add(sDetalhe[2]);
lstRemessa.Sort;
bFlag := True;
end
else
begin
bFlag := False;
end;
end
else
begin
bFlag := True;
end;
if bFlag then
begin
FPlanilha.Add(TPlanilhaEntradaTFO.Create);
i := FPlanilha.Count - 1;
FPlanilha[i].CodigoDestino := sDetalhe[0];
FPlanilha[i].NomeDestino := sDetalhe[1];
FPlanilha[i].NossoNumero := sDetalhe[2];
FPlanilha[i].CodigoCliente := sDetalhe[3];
FPlanilha[i].NumeroNF := sDetalhe[4];
FPlanilha[i].NomeConsumidor := sDetalhe[5];
FPlanilha[i].AosCuidados := sDetalhe[6];
FPlanilha[i].Logradouro := sDetalhe[7];
FPlanilha[i].Complemento := sDetalhe[8];
FPlanilha[i].Bairro := sDetalhe[9];
FPlanilha[i].Cidade := sDetalhe[10];
FPlanilha[i].CEP := sDetalhe[11];
FPlanilha[i].Telefone := sDetalhe[12];
FPlanilha[i].Expedicao := sDetalhe[13];
FPlanilha[i].Previsao := sDetalhe[14];
FPlanilha[i].Status := sDetalhe[15];
FPlanilha[i].DescricaoStatus := sDetalhe[16];
FPlanilha[i].NomeEntregador := sDetalhe[17];
FPlanilha[i].Container := sDetalhe[18];
FPlanilha[i].ValorProuto := sDetalhe[19];
FPlanilha[i].ValorVerba := sDetalhe[20];
FPlanilha[i].Altura := sDetalhe[21];
FPlanilha[i].Largura := sDetalhe[22];
FPlanilha[i].Comprimento := sDetalhe[23];
FPlanilha[i].Peso := sDetalhe[24];
FPlanilha[i].Volume := sDetalhe[25];
end;
end;
end;
if FPlanilha.Count = 0 then
begin
FMensagem := 'Nenhuma informação foi importada da planilha!';
Exit;
end;
Result := True;
finally
CloseFile(ArquivoCSV);
end;
end;
end.
|
unit CoreTypes;
interface
uses
Classes;
type
IEnumStrings =
interface
function Next(out which : array of string) : integer;
function Skip(count : integer) : integer;
procedure Reset;
end;
type
IEnumClasses =
interface
function Next(out which : array of TClass) : integer;
function Skip(count : integer) : integer;
procedure Reset;
end;
type
IEnumObjects =
interface
function Next(out which : array of TObject) : integer;
function Skip(count : integer) : integer;
procedure Reset;
end;
type
ICollection =
interface
function GetCount : integer;
procedure SetCount(NewCount : integer);
function Get(Index : integer) : pointer;
procedure Put(Index : integer; Item : pointer);
function Add(Item : pointer) : integer;
procedure Clear;
procedure Delete(Index : integer);
function IndexOf(Item : pointer) : integer;
procedure Insert(Index : integer; Item : pointer);
function Remove(Item : pointer) : integer;
procedure Pack;
function List : PPointerList;
property Count : integer read GetCount write SetCount;
property Items[idx : integer] : pointer read Get write Put; default;
end;
type
TRelationshipKind = (rkUse, rkContaining);
const
rkBelonguer = rkContaining;
type
TSyncronizedList =
class
public
constructor Create(aRelKind : TRelationshipKind);
public
function Lock : ICollection;
private
fItems : ICollection;
end;
implementation
uses
Windows;
type
TLockableList =
class(Tlist, ICollection)
public
constructor Create(aRelKind : TRelationshipKind);
destructor Destroy; override;
private // IUnknown
fRelKind : TRelationshipKind;
fRefCount : integer;
fLock : TRTLCriticalSection;
function QueryInterface(const iid : TGUID; out obj) : hresult; stdcall;
function _AddRef : integer; stdcall;
function _Release : integer; stdcall;
private // ICollection
function ICollection.List = GetList;
function GetCount : integer;
function GetList : PPointerList;
private
procedure Lock;
procedure Unlock;
end;
// TSyncronizedList
constructor TSyncronizedList.Create(aRelKind : TRelationshipKind);
begin
inherited Create;
fItems := TLockableList.Create(aRelKind);
end;
function TSyncronizedList.Lock : ICollection;
begin
Result := fItems;
end;
// TLockableList
constructor TLockableList.Create(aRelKind : TRelationshipKind);
begin
inherited Create;
fRelKind := aRelKind;
InitializeCriticalSection(fLock);
end;
destructor TLockableList.Destroy;
var
i : integer;
pp : PPointerList;
begin
if fRelKind = rkContaining
then
begin
pp := List;
for i := pred(Count) downto 0 do
TObject(pp[i]).Free;
end;
DeleteCriticalSection(fLock);
inherited;
end;
function TLockableList.QueryInterface(const iid : TGUID; out obj) : hresult;
const
E_NOINTERFACE = $80004002;
begin
if GetInterface(iid, obj)
then Result := 0
else Result := E_NOINTERFACE;
end;
function TLockableList._AddRef : integer;
begin
if fRefCount = 1
then Lock;
inc(fRefCount);
Result := fRefCount;
end;
function TLockableList._Release : integer;
begin
dec(fRefCount);
Result := fRefCount;
if fRefCount = 1
then Unlock
else
if fRefCount = 0
then Destroy;
end;
function TLockableList.GetCount : integer;
begin
Result := Count;
end;
function TLockableList.GetList : PPointerList;
begin
Result := List;
end;
procedure TLockableList.Lock;
begin
EnterCriticalSection(fLock);
end;
procedure TLockableList.Unlock;
begin
LeaveCriticalSection(fLock);
end;
end.
|
(* Gomoku-Computerspieler von Sabine Wolf, q5999219@bonsai.fernuni-hagen.de, Version vom 7.9.02 *)
unit q5999219;
interface
type
tStatus = ( EINS_AM_ZUG, ZWEI_AM_ZUG,
EINS_GEWINNT, ZWEI_GEWINNT, UNENTSCHIEDEN,
UNDEFINIERT );
procedure gibStatus ( var Status: tStatus );
(* Der Status des aktuellen Spiels kann abgefragt werden. *)
(* Am Anfang (ohne neuesSpiel) UNDEFINIERT. *)
(* Nach neuesSpiel EINS_AM_ZUG, spaeter nach setzeStein *)
(* oder ComputerZug entsprechend EINS_AM_ZUG bzw. ZWEI_AM_ZUG. *)
(* Wenn die Partie durch den letzten Zug beendet wurde, dann *)
(* EINS_GEWINNT, ZWEI_GEWINNT oder UNENTSCHIEDEN. *)
procedure neuesSpiel ( var ok: boolean );
(* Ein neues Spiel wird mit den aktuellen Einstellungen begonnen. *)
(* ok = false, falls das aus irgendeinem Grund unmoeglich sein sollte.*)
procedure setzeStein ( x: integer; y: integer; var ok: boolean );
(* Es wird ein Stein auf das Brett gesetzt ( Koordinaten x,y ) *)
(* setzeStein kann beliebig oft HINTEREINANDER aufgerufen werden, *)
(* z. B. um eine Stellung auf dem Brett darzustellen. *)
(* Sollte dieser Zug nicht m=F6glich sein, ist ok = false. *)
procedure computerZug ( var px: integer; var py: integer; var ok: boolean );
(* Der Computer macht einen Zug fr EINS oder ZWEI, wer grad am Zug ist.*)
(* computerZug kann beliebig oft HINTEREINANDER aufgerufen werden, der *)
(* Computer kann also JEDERZEIT einen Zug fr die entsprechende Seite *)
(* machen. Sollte kein Zug mglich sein, ist ok = false. *)
procedure zugZurueck ( var x: integer; var y: integer; var ok: boolean );
(* Die Rcknahme eines Zuges. ok = false wenn nicht mglich. *)
(* zugZurueck kann beliebig oft hintereinander aufgerufen werden. *)
(* zugZurueck nimmt NUR EINEN Zug zurck. *)
procedure zugVor ( var x: integer; var y: integer; var ok: boolean );
(* Ein Zug, der mit zugZurueck zur=FCckgenommen wurde, wird wieder=
gesetzt.*)
(* zugVor macht KEINE NEUEN Z=DCGE. ok = false, falls kein Zug mehr =
*)
(* vorhanden ist. zugVor kann beliebig oft aufgerufen werden. *)
(* zugVor setzt NUR EINEN Zug. *)
procedure setzeSpielstufe ( Stufe: integer; var ok: boolean );
(* Die aktuelle Spielstufe des Computers wird gesetzt, *)
(* ok = false bei illegaler Spielstufe. *)
(* Bei Eingabe einer illegalen Spielstufe wird *)
(* die aktuelle Spielstufe beibehalten. *)
procedure gibSpielstufe ( var Stufe: integer );
(* Die aktuelle Spielstufe wird abgefragt. *)
(* Vor dem ersten Aufruf von setzeSpielstufe ist Stufe=2. *)
procedure setzeFeldgroesse ( x: integer; y: integer; var ok: boolean );
(* Die Groesse des Spielfeldes wird gesetzt. Das Spielfeld ist rechteckig *)
(* und besteht aus x mal y Kaestchen, beide zwischen 5 und 30. *)
(* Bei Erfolg ist der Status = UNDEFINIERT, danach ist neuesSpiel *)
(* notwendig, ok = false bei illegaler Feldgroesse. *)
(* Die aktuelle Feldgroesse wird bei einer *)
(* illegalen Eingabe beibehalten, ebenso der Status. *)
procedure gibFeldgroesse ( var x: integer; var y: integer );
(* Die Gr=F6=DFe des Spielfeldes wird abgefragt. *)
(* Vor dem ersten Aufruf von setzeFeldgroesse gilt x=y=18. *)
procedure gibGewinnreihe ( var x1: integer; var y1: integer;
var x2: integer; var y2: integer; var ok:boolean);
(* Der Anfangsstein x1,y1 und der Endstein x2,y2 einer Gewinnreihe wird *)
(* Uebergeben. ok = false falls noch kein Gewinner existiert. *)
procedure gibNamen ( var name: string );
(* Vor- und Nachname der Programmiererin / des Programmierers wird *)
(* uebergeben. Die Stringlaenge ist <= 30. *)
procedure gibSpitzNamen ( var name: string );
(* Der Spitzname des Programms, unter dem das Turnier gespielt wird. *)
(* Denken Sie sich etwas originelles/witziges aus. *)
(* Die Stringlaenge ist <= 30. *)
implementation
const
MINFELDSIZE = 5;
MAXFELDSIZE = 30;
DEFFELDSIZE = 13;
{Die maximale Anzahl potentieller Zge, unter denen ausgewhlt wird.}
MAXAUSWAHL =100;
type
{Die Zustnde die ein Feld haben kann.}
tStein = (Leer,Weiss,Schwarz,Rand);
{Die Groesse, die das Feld haben kann.}
tFeldSize = MINFELDSIZE..MAXFELDSIZE;
{Eine Koordinate des Feldes}
tFeldKoord = 0..MAXFELDSIZE+1;
{Das Feldarray, das die Belegung des Spielfeldes mit Steinen speichert.}
tFeld = array[tFeldKoord,tFeldKoord] of tStein;
{Ein Zug mit seiner Position und seinem Status.}
tZug = record
x : tFeldKoord;
y : tFeldKoord;
State : tStatus
end;
{Array zur Speicherung der Zge}
tAZug = array [0..MAXFELDSIZE*MAXFELDSIZE] of tZug;
tzAZug = ^tAZug;
Offset = -1..1;
tRichtung = record
x : Offset;
y : Offset;
end;
tFeldPos = record
x : tFeldKoord;
y : tFeldKoord;
end;
tBewertung = record
x : tFeldKoord;
y : tFeldKoord;
bewe : longint;
end;
{In solchen Arrays werden mgliche Zugkandidaten gespeichert.}
tsBewertungA = array[0..MAXAUSWAHL] of tBewertung;
tBewertungA = array[0..MAXFELDSIZE*MAXFELDSIZE] of tBewertung;
{Die 4 mglichen Grundrichtungen}
tAusrichtung = (waagerecht,senkrecht,vorschraeg,rueckschraeg);
var
{In diesem Array tragen sich Steine in ihre Umgebung ein, damit jedes Feld ber seine
Umgebung Bescheid weiá.}
Umgebung : array[tFeldKoord,tFeldKoord,tAusrichtung,0..1] of integer;
{Zweierpotenzen fr die 4 Richtungen.}
pfak : array[tAusrichtung] of word;
{In dieses Array tragen sich Steine in ihre nhere Nachbarschaft ein, damit ein Feld schnell
weiá, ob es in der Nachbarschaft eines Steines liegt.}
Nachbarn : array[tFeldKoord,tFeldKoord] of word;
{Die Nummer des aktuellen Zuges und die Anzahl des gespeicherten Zge.
Im normalen Spiel sind beide Werte gleich, nur nach Zugrcknahme ist aktZug<endZug.}
aktZug,endZug : integer;
{Das Array, das die Zge speichert.}
Zug : tzAZug;
FeldSizeX,FeldSizeY : tFeldSize;
{Das Spielfeldarray, in dem die Steine eingetragen werden.}
Feld : tFeld;
{EINS_AM_ZUG->Weiss,ZWEI_AM_ZUG->Schwarz}
Steinzuordnung : array[tStatus] of tStein;
{EINS_AM_ZUG->ZWEI_AM_ZUG,ZWEI_AM_ZUG->EINS_AM_ZUG}
Flip : array [tStatus] of tStatus;
Spielstufe : 0..2;
rv :array[tAusrichtung] of tRichtung;
AnfangsPos,EndPos : tFeldPos;
{Setzt einen Stein in das Feldarray und addiert den um die Entfernung mal 2
nach links geshifteten Steinwert(1 fr Weiá,2 fr Schwarz) auf die entsprechenden
Umgebungswerte der in alle 8 Richtungen liegenden Nachbarn bis zu einer Entfernung
von 5 Feldern. Zur schnellen berprfung, ob ein Stein in der nheren Nachbarschaft
eines anderen liegt, wird der Stein noch ohne Unterscheidung der Steinfarbe
auf den Nachbarschaftswert der nheren Nachbarn addiert, jede der 8 Richtungen hat
eine entsprechende Bitposition dafr, fr die unmittelbaren Nachbarn wird das ganze nochmal um 8 Bits nach links geschoben,
so daá 16 Bits fr 16 Nachbarn verwendet werden.
}
procedure eintragen(x,y:tFeldKoord;stein:tStein);
var
xx,yy,t,val : integer;
ausr: tAusrichtung;
begin
val:=ord(stein);
Feld[x,y]:=stein;
if stein<Rand then
for ausr:=waagerecht to rueckschraeg do
begin
inc(nachbarn[x-rv[ausr].x,y-rv[ausr].y],pfak[ausr]*256);
if (x-rv[ausr].x*2>0) and (y-rv[ausr].y*2>0) and
(x-rv[ausr].x*2<=FeldSizeX) then
inc(nachbarn[x-rv[ausr].x*2,y-rv[ausr].y*2],pfak[ausr]);
inc(nachbarn[x+rv[ausr].x,y+rv[ausr].y],pfak[ausr]*512);
if (x+rv[ausr].x*2>0) and
(x+rv[ausr].x*2<=FeldSizeX) and (y+rv[ausr].y*2<=FELDSIZEY) then
inc(nachbarn[x+rv[ausr].x*2,y+rv[ausr].y*2],pfak[ausr]*2);
end;
for t:=1 to 5 do
begin
for ausr:=waagerecht to rueckschraeg do
begin
xx:=x+rv[ausr].x*t;
yy:=y+rv[ausr].y*t;
if (xx>0) and (yy>0) and (xx<=FeldSizeX) and (yy<=FeldSizeY) then
inc(umgebung[xx,yy,ausr,0],val);
xx:=x-rv[ausr].x*t;
yy:=y-rv[ausr].y*t;
if (xx>0) and (yy>0) and (xx<=FeldSizeX) and (yy<=FeldSizeY)then
inc(umgebung[xx,yy,ausr,1],val);
end;
{Der Steinwert wird um 2 Bits nach links geschoben.}
val:=val*4;
end;
end;
{Diese Prozedur trgt einen Stein wieder aus und macht alle von eintragen
vorgenommenen nderungen wieder rckgngig.}
procedure austragen(x,y:tFeldKoord;stein:tStein);
var
xx,yy,t,val : integer;
ausr: tAusrichtung;
begin
val:=ord(stein);
Feld[x,y]:=Leer;
if stein<Rand then
for ausr:=waagerecht to rueckschraeg do
begin
dec(nachbarn[x-rv[ausr].x,y-rv[ausr].y],pfak[ausr]*256);
if (x-rv[ausr].x*2>0) and (y-rv[ausr].y*2>0) and
(x-rv[ausr].x*2<=FeldSizeX) then
dec(nachbarn[x-rv[ausr].x*2,y-rv[ausr].y*2],pfak[ausr]);
dec(nachbarn[x+rv[ausr].x,y+rv[ausr].y],pfak[ausr]*512);
if (x+rv[ausr].x*2>0) and
(x+rv[ausr].x*2<=FeldSizeX) and (y+rv[ausr].y*2<=FELDSIZEY) then
dec(nachbarn[x+rv[ausr].x*2,y+rv[ausr].y*2],pfak[ausr]*2);
end;
for t:=1 to 5 do
begin
for ausr:=waagerecht to rueckschraeg do
begin
xx:=x+rv[ausr].x*t;
yy:=y+rv[ausr].y*t;
if (xx>0) and (yy>0)and (xx<=FeldSizeX) and (yy<=FeldSizeY) then
dec(umgebung[xx,yy,ausr,0],val);
xx:=x-rv[ausr].x*t;
yy:=y-rv[ausr].y*t;
if (xx>0) and (yy>0) and (xx<=FeldSizeX) and (yy<=FeldSizeY)then
dec(umgebung[xx,yy,ausr,1],val);
end;
val:=val*4;
end;
end;
procedure gibStatus ( var Status: tStatus );
begin;
Status := Zug^[aktZug].State;
end;
{Initialisiert fr ein neues Spiel das Feld-, das Nachbarschaft- und
das Umgebungsarray, trgt den Rand in das Umgebungsarray ein,
setzt das Zugarray zurck und den Spielstatus auf EINS_AM_ZUG.}
procedure neuesSpiel(var ok:boolean);
var
x,y : tFeldKoord;
ausr: tAusrichtung;
begin;
for x:= 0 to FeldSizeX+1 do
for y := 0 to FeldSizeY+1 do
begin
Feld[x,y]:=Leer;
nachbarn[x,y]:=0;
for ausr:=waagerecht to rueckschraeg do
begin
umgebung[x,y,ausr,0]:=0;
umgebung[x,y,ausr,1]:=0;
end;
end;
for x:= 0 to FeldSizeX+1 do
for y := 0 to FeldSizeY+1 do
begin
if (x=0) or (x=FeldSizeX+1) or (y=0) or (y=FeldSizeY+1) then
eintragen(x,y,Rand);
end;
aktzug:=0;
endzug:=0;
Zug^[aktZug].State := EINS_AM_ZUG;
ok:=true;
end;
{Setzt einen Stein und schaut, ob sich durch das Setzen ein Sieg oder ein
Unentschieden ergeben hat.}
procedure setzeStein ( x: integer; y: integer; var ok: boolean );
var
ausr : tAusrichtung;
shift : integer;
begin;
if ((Zug^[aktZug].State=EINS_AM_ZUG) or (Zug^[aktZug].State=ZWEI_AM_ZUG)) AND
(x>0) and (x<=FeldSizeX) and
(y>0) and (y<=FeldSizeY) then
begin
if Feld[x,y]=Leer then
begin
Zug^[aktzug].x := x;
Zug^[aktZug].y := y;
eintragen(x,y,Steinzuordnung[Zug^[aktzug].State]);
Zug^[aktZug+1].State := Flip[Zug^[aktZug].State];
inc(aktzug);
endzug := aktzug;
{Wenn das Spielfeld voll ist, gibt es ein Unentschieden, es sei denn, es wird
noch ein Sieg festgestellt.}
if aktzug=FeldSizeX*FeldSizeY then
Zug^[aktZug].State:=UNENTSCHIEDEN;
{Es wird geschaut, ob sich durch das Setzen des Steins eine Fnfer-Reihe ergeben hat.
Die der gesetzte Stein am Anfang, dazwischen oder am Ende einer solchen Reihe stehen kann,
werden alle 5 Positionen abgefragt.}
for ausr := waagerecht to rueckschraeg do
begin
shift:=0;
if ((umgebung[x,y,ausr,1] and 255)=85*ord(Feld[x,y])) then
shift:=1;
if (((umgebung[x,y,ausr,1] and 63)=21*ord(Feld[x,y])) and
((umgebung[x,y,ausr,0] and 3)=ord(Feld[x,y]))) then
shift:=2;
if (((umgebung[x,y,ausr,1] and 15)=5*ord(Feld[x,y])) and
((umgebung[x,y,ausr,0] and 15)=5*ord(Feld[x,y]))) then
shift:=3 ;
if (((umgebung[x,y,ausr,1] and 3)=ord(Feld[x,y])) and
((umgebung[x,y,ausr,0] and 63)=21*ord(Feld[x,y]))) then
shift:=4 ;
if ((umgebung[x,y,ausr,0] and 255)=85*ord(Feld[x,y])) then
shift:=5;
if shift>0 then
begin
if Feld[x,y]=Weiss then
Zug^[aktZug].State:= EINS_GEWINNT
else
Zug^[aktZug].State:= ZWEI_GEWINNT;
{Je nach Positon des aktuellen Steines in der Siegreihe wird der Anfangs- und
der Endstein gesetzt.}
AnfangsPos.x:=x-rv[ausr].x*(shift-1);
AnfangsPos.y:=y-rv[ausr].y*(shift-1);
Endpos.x:=x+rv[ausr].x*(5-shift);
EndPos.y:=y+rv[ausr].y*(5-shift);
end ;
end;
ok:=true;
end
else
ok:=false
end
else
ok:=false;
end;
{Der Computer ermittelt den fr in gnstigsten Stein und setzt diesen. Dabei geht er
je nach Spielstufe mehr oder weniger intelligent vor.}
procedure computerZug ( var px: integer; var py: integer; var ok: boolean);
var
Computerstein,Spielerstein : tStein;
auswahl,ost : integer;
State : tStatus;
qual : longint;
nzuege : tBewertungA;
{BesterZug ermittelt den besten Zug, bekommt dafr mitgeteilt,
bis zu welcher Tiefe Zge kalkuliert werden drfen,,welche Farbe
der Computer und welche der Gegner hat,wie hoch die
Bewertungsschwelle ist, ab der gute Felder als solche erkannt und
wie stark zu verlngernde gegenber zu blockierenden Ketten gewichtet
werden sollen.}
function besterZug (var px,py : integer;
Zugtiefe : integer;
cpst,spst : tStein;
schwelle : integer;
gewicht : integer ) : longint;
var sumbewe,bewe,faktor,ri : integer;
st : tStein;
ausr : tAusrichtung;
x,y,siegx,siegy : tFeldKoord;
xx,yy,xxx,yyy,t,
nAusw,nNach,sieg,ssieg : integer;
zuege : tsBewertungA;
kett3,block3,block4 : boolean;
skett1,sblock1,
skett2,sblock2,
skett3,skett3b,
sblock3,sblock3b,
sblock4: integer;
maxqual : longint;
begin
nNach:=0;
sieg:=0;
siegx:=1;
siegy:=1;
sblock3:=0;
skett3:=0;
sblock4:=0;
for y:=1 to FeldSizeY do
for x:=1 to FeldSizeX do
if (Feld[x,y]=Leer) and (nachbarn[x,y]>0) and (sieg<4000) then
{Wenn ein Feld leer ist und in der Umgebung eines anderen Steines liegt
(direkt drann oder mit einem Feld Abstand), wird es nher untersucht, ob
sich eigene Ketten bilden oder gegnerische Ketten abblocken lassen. Eine
gegebene Kette zu verlngern zhlt das dreifache wie das Abblocken einer
solchen Kette. Lngere Ketten geben mehr Punkte, vllig freie Ketten mehr
als die, die mit einem Stein schon geblockt werden knnen.}
begin
sumbewe:=0;
block3:=false;
kett3:=false;
block4:=false;
skett3b:=0;
sblock3b:=0;
skett1:=0;
sblock1:=0;
skett2:=0;
sblock2:=0;
for st:=Weiss to Schwarz do
begin
ost:=ord(st);
if st=cpst then
faktor:=gewicht
else
faktor:=1;
for ausr := waagerecht to rueckschraeg do
for ri:=0 to 1 do
begin
bewe:=0;
{oo?..} if ((umgebung[x,y,ausr,ri] and 15) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 0) then
bewe:=1;
{oo.?.} if ((umgebung[x,y,ausr,ri] and 63) = 20*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=1;
{oo..?} if ((umgebung[x,y,ausr,ri] and 255) = 80*ost) then
bewe:=1;
{...o?.} if ((umgebung[x,y,ausr,ri] and 255) = ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=1;
{..o?..} if ((umgebung[x,y,ausr,ri] and 63) = ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 0) then
bewe:=1;
{.o?...} if ((umgebung[x,y,ausr,ri] and 15) = ost) and
((umgebung[x,y,ausr,1-ri] and 63) = 0) then
bewe:=1;
{.o.?..} if ((umgebung[x,y,ausr,ri] and 63) = 4*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 0) then
bewe:=1;
{.o..?.} if ((umgebung[x,y,ausr,ri] and 255) = 16*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=1;
{.oo?..} if ((umgebung[x,y,ausr,ri] and 63) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 0) then
bewe:=9;
{..oo?.} if ((umgebung[x,y,ausr,ri] and 255) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=9;
{.oo.?.} if ((umgebung[x,y,ausr,ri] and 255) = 20*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=9;
{.o.o?.} if ((umgebung[x,y,ausr,ri] and 255) = 17*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0)then
bewe:=9;
{..o?o.} if ((umgebung[x,y,ausr,ri] and 63) = ost) and
((umgebung[x,y,ausr,1-ri] and 15) = ost)then
bewe:=9;
{..o?o..} if ((umgebung[x,y,ausr,ri] and 63) = ost) and
((umgebung[x,y,ausr,1-ri] and 63) = ost)then
begin {wegen Symmetrie nur in einer Richtung werten.}
if ri=0 then bewe:=9 else bewe:=0;
end;
{.o.?o.} if ((umgebung[x,y,ausr,ri] and 63) = 4*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = ost)then
bewe:=9;
{o.o?o} if ((umgebung[x,y,ausr,ri] and 63) = 17*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = ost) then
bewe:=9*5;
{.o.o?o} if ((umgebung[x,y,ausr,ri] and 255) = 17*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = ost) then
bewe:=0;
{.o?o.o} if ((umgebung[x,y,ausr,ri] and 15) = ost) and
((umgebung[x,y,ausr,1-ri] and 63) = 17*ost) then
bewe:=9*5;
{.ooo?} if ((umgebung[x,y,ausr,ri] and 255) = 21*ost) then
bewe:=9*5;
{ooo?.} if ((umgebung[x,y,ausr,ri] and 63) = 21*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=9*5;
{ooo.?} if ((umgebung[x,y,ausr,ri] and 255) = 84*ost) then
bewe:=9*5;
{oo?o.} if ((umgebung[x,y,ausr,ri] and 15) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = ost) then
bewe:=9*5;
{oo?.o} if ((umgebung[x,y,ausr,ri] and 15) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 4*ost)then
bewe:=9*5;
{oo.?o} if ((umgebung[x,y,ausr,ri] and 63) = 20*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = ost)then
bewe:=9*5;
{.ooo.?} if ((umgebung[x,y,ausr,ri] and 1023) = 84*ost) then
bewe:=0;
{o.o?o.o} if ((umgebung[x,y,ausr,ri] and 63) = 17*ost) and
((umgebung[x,y,ausr,1-ri] and 63) = 17*ost) then
bewe:=81;
{o.oo?.o} if ((umgebung[x,y,ausr,ri] and 255) = 69*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 4*ost) then
bewe:=81;
{.ooo?.} if ((umgebung[x,y,ausr,ri] and 255) = 21*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = 0) then
bewe:=81;
{.oo?o.} if ((umgebung[x,y,ausr,ri] and 63) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = ost) then
bewe:=82;
{folgende 2 Positionen sind nur zum Blocken.}
{.oo.o?} if ((umgebung[x,y,ausr,ri] and 1023) = 81*ost) and
(st<>cpst) then
bewe:=81;
{.o.oo?} if ((umgebung[x,y,ausr,ri] and 1023) = 69*ost) and
(st<>cpst) then
bewe:=81;
{oooo?} if (umgebung[x,y,ausr,ri] and 255) = 85*ost then
bewe:=1000;
{ooo?o} if ((umgebung[x,y,ausr,ri] and 15) = 5*ost) and
((umgebung[x,y,ausr,1-ri] and 15) = 5*ost) then
bewe:=1000;
{oo?oo} if ((umgebung[x,y,ausr,ri] and 63) = 21*ost) and
((umgebung[x,y,ausr,1-ri] and 3) = ost) then
bewe:=1000;
{.oooo?} if ((umgebung[x,y,ausr,ri] and 1023) = 85*ost) and (st<>cpst) and (sieg<>3000) then
begin
sieg:=-4000;
siegx:=x;
siegy:=y;
end;
{Wenn eine 4er-Kette verlngert werden kann,
bedeutet das den sofortigen Sieg, Blocken ist zwingend.}
if (bewe=1000) then
begin
nNach:=0;
if (st=cpst) then
begin
sieg:=4000;
siegx:=x;
siegy:=y;
end
else
block4:=true;
end;
{Eine freie Dreierreihe muá geblockt oder verlngert werden.}
if bewe>=81 then
begin
if st=cpst then
kett3:=true
else
block3:=true
end;
{Halboffene 3er-Ketten werden gezhlt.}
if (bewe=9*5) then
begin
if st=cpst then
inc(skett3b)
else
inc(sblock3b);
end;
{Offene 2er-Ketten werden gezhlt.}
if (bewe=9) then
begin
if st=cpst then
inc(skett2)
else
inc(sblock2);
end;
{Offene einzelne Steine werden gezhlt.}
if (bewe=1) then
begin
if st=cpst then
inc(skett1)
else
inc(sblock1);
end;
inc(sumbewe,bewe*faktor);
end;
end;
if sieg<4000 then
begin
ssieg:=0;
if (sblock3b>1) or ((sblock3b>0) and (sblock2>0)) then
begin
block3:=true;
inc(sblock3);
end;
{Zhle zu verlngernde 3er-Kettenenden.}
if kett3 then
begin
inc(skett3);
{Wenn die besten Zge eine freie 3er-Kette verlngern, bedeutet das auch den Sieg.}
if (sieg>=-3000) and (skett3>0) then
ssieg:=3000;
end;
if (skett1>1) and (sumbewe<9*faktor)then
inc(sumbewe,8*faktor);
if (sblock1>1) and (sumbewe<9) then
inc(sumbewe,8);
{Zhle zu blockierende 3er-Kettenenden.}
if block3 then
begin
inc(sblock3);
{Wenn es zwei zu blockende 3er-Ketten gibt, es also mehr als 3 Enden gibt,
die zu blockieren sind, bedeutet das die Niederlage.}
if (sieg=0) and (sblock3>3) then
ssieg:=-3000;
end;
{Zhle zu blockierende 4er-Kettenenden.}
if block4 then
begin
inc(sblock4);
{Wenn es mehr als ein zu blockierendes 4er-Ketten-Ende gibt,
so bedeutet daá eine Niederlage.}
if (sblock4>1) then
ssieg:=-4000;
end;
{Wenn ein Stein 2 offene Zweierketten oder halboffene 3er-Ketten verlngert, so
bedeutet das den Sieg, wenn es nichts mit hherer Prioritt gibt.}
if (sieg=0) and (skett2+skett3b>1) and ((Spielstufe=2) or (skett3b>0)) then
ssieg:=2000;
{Wenn ein Stein 2 halboffene 3er-Ketten verlngert, bedeutet auch das den Sieg.}
if (sieg>=-3000) and (skett3b>1) then
ssieg:=3000;
if (ssieg<>0) and (sblock4=0) then
begin
sieg:=ssieg;
siegx:=x;
siegy:=y;
end;
end;
if (sblock2>1) and (sumbewe<81) and (Spielstufe=2) then
inc(sumbewe,9*4);
if (block3) and (sumbewe<81) and (Spielstufe=1) then
inc(sumbewe,9*4);
if ((sblock3>0) and (sieg=2000)) or ((sblock4>0) and (sieg=3000)) then
sieg:=0;
{Wenn die Bewertung eines Feldes >= der momentanen Schwelle ist, wird des Feld in
die Liste der mglichen Zge eingetragen.}
if sumbewe>=schwelle then
begin
{Wenn die Rekursionstiefe erreicht ist, werden nur die besten Zge eingetragen.}
if (Zugtiefe=0) then
begin
if (sumbewe>schwelle) then
begin
nNach:=0;
schwelle:=sumbewe;
end
end
{Ansonsten werden Zge einer bestimmten Gruppe eingetragen. Wenn es z.B. einen
Feld mit einer Bewertung von mind. 81 gibt, heiát das, das dieses Feld unbedingt
geblockt werden muá, Felder mit einer niedrigeren Bewertung sind damit irrelevant.}
else
begin
while (sumbewe>=schwelle*9) do
begin
nNach:=0;
schwelle:=schwelle*9;
end
end;
if nNach<MAXAUSWAHL then
begin
zuege[nNach].x:=x;
zuege[nNach].y:=y;
zuege[nNach].bewe:=sumbewe;
end
else
begin
{Reicht der Platz im Array nicht aus, wird ein Feld berschrieben mit
einer gewissen Wahrscheinlichkeit.}
auswahl:=random(nNach);
if auswahl<MAXAUSWAHL then
begin
zuege[auswahl].x:=x;
zuege[auswahl].y:=y;
zuege[auswahl].bewe:=sumbewe;
end;
end;
inc(nNach);
end;
end;
{Wurden keine guten Felder gefunden, so wird zufllig ein Feld ausgewhlt,
das in der Nachbarschaft eines Steines liegt.}
if nNach=0 then
begin
for y:=1 to FeldSizeY do
for x:=1 to FeldSizeX do
if (Feld[x,y]=Leer) and (nachbarn[x,y]>255) then
begin
nzuege[nNach].x:=x;
nzuege[nNach].y:=y;
inc(nNach);
end;
auswahl:=random(nNach);
px:=nzuege[auswahl].x;
py:=nzuege[auswahl].y;
besterZug:=0;
end
else
begin
{Wenn die Stellung Sieg oder Niederlage bedeutet, wird ein sehr hoher Wert
fr Sieg und ein sehr niedriger Wert fr Niederlage zurckgegeben.}
if sieg<>0 then
begin
px:=siegx;
py:=siegy;
besterZug:=sieg;
end
else
{Wenn die Zugtiefe erreicht ist, wird zufllig ein Feld aus der Liste
ausgewhlt, da alle diese Felder gleich gut bewertet wurden.}
if Zugtiefe=0 then
begin
auswahl:=random(nNach);
px:=zuege[auswahl].x;
py:=zuege[auswahl].y;
besterZug:=zuege[auswahl].bewe;
end
else
{Ansonsten wird jedes Feld aus der Liste erstmal gesetzt und nach dem besten Zug
gesucht, mit dem die andere Steinfarbe auf diesen Zug reagieren knnte.
Die Felder, die in der Summe aus der zweifachen eigenen Bewertung minus der Bewertung
aus der besten mglichen gegnerischen Reaktion darauf, am besten abschneiden werden genommen.
Der Faktor zwei ergab sich empirisch beim Spielen der Stufe 2 gegen Stufe 0.
}
begin
maxqual:=-5000;
nAusw:=0;
for t:=0 to nNach-1 do
begin
xx:=zuege[t].x;
yy:=zuege[t].y;
eintragen(xx,yy,cpst);
qual:=zuege[t].bewe*2*Zugtiefe-besterZug(xxx,yyy,Zugtiefe-1,spst,cpst,1,3);
if qual>=maxqual then
begin
if qual>maxqual then
begin
maxqual:=qual;
nAusw:=0;
end;
zuege[nAusw].x:=xx;
zuege[nAusw].y:=yy;
inc(nAusw);
end;
{ Der spekulativ gesetze Stein wird wieder zurckgenommen.}
austragen(xx,yy,cpst);
end;
{Aus den besten Feldern wird einer ausgewhlt.}
auswahl:=random(nAusw);
px:=zuege[auswahl].x;
py:=zuege[auswahl].y;
besterZug:=maxqual;
end;
end;
end;
begin;
State := Zug^[aktZug].State;
{Nur wenn das Spiel luft, kann der Computer einen Zug machen.}
if (State<>EINS_AM_ZUG) and (State<>ZWEI_AM_ZUG) then
ok := false
else
begin
ok:=true;
Computerstein := Steinzuordnung[State];
Spielerstein := Steinzuordnung[Flip[State]];
{Beim ersten Zug wird fr die Spielstufen 0 und 1 ein zuflliges Feld
ausgewhlt, fr die Stufe zwei eines in der Mitte.}
if aktZug=0 then
begin
if Spielstufe<2 then
begin
px := random(FeldSizeX)+1;
py := random(FeldSizeY)+1;
end
else
begin
px := (FeldSizeX - random(2)) div 2 + 1;
py := (FeldSizeY - random(2)) div 2 + 1;
end
end
else
begin
case Spielstufe of
{Nur Viererketten werden erkannt.}
0 : qual:=besterZug(px,py,0,Computerstein,Spielerstein,1000,2);
{Dreier und Viererketten werden erkannt.}
1 : qual:=besterZug(px,py,2,Computerstein,Spielerstein,81,2);
{auch kuerzere Ketten werden bewertet.}
2 : qual:=besterZug(px,py,2,Computerstein,Spielerstein,1,3);
end;
end;
{Der ausgewhlte Stein wird gesetzt.}
setzeStein(px,py,ok);
end;
end;
{zieht einen Zug zurck, indem der vorherige Zug zum aktuellen gemacht wird
und dessen Stein zurckgenommen wird. Ist der aktuelle Zug allerdings der erste,
wird ok wird ok auf false gesetzt.x und y wird auf die Position des zurckgenommenen
Steines gesetzt.}
procedure zugZurueck ( var x: integer; var y: integer; var ok: boolean );
begin;
if aktZug = 0 then
ok := false
else
begin
ok := true;
dec(aktZug);
x := Zug^[aktZug].x;
y := Zug^[aktZug].y;
austragen(x,y,Feld[x,y]);
end;
end;
{zieht einen Zug vor, indem der aktuelle Stein wieder auf das Feld gesetzt
wird und der nchste Zug zum aktuellen gemacht wird. Ist der aktuelle Zug
allerdings schon der letzte, wird ok auf false gesetzt. x und y werden auf
die Position des gesetzten Steines gesetzt.}
procedure zugVor ( var x: integer; var y: integer; var ok: boolean );
begin;
if aktZug = endZug then
ok := false
else
begin
ok := true;
x := Zug^[aktZug].x;
y := Zug^[aktZug].y;
eintragen(x,y,Steinzuordnung[Zug^[aktZug].State]);
inc(aktZug);
end;
end;
{Setzt die Spielstufe.}
procedure setzeSpielstufe ( Stufe: integer; var ok: boolean );
begin;
if (Stufe<0) or (Stufe>2) then
ok := false
else
begin
ok := true;
Spielstufe:=Stufe;
end;
end;
{Gibt die Spielstufe zurck.}
procedure gibSpielstufe ( var Stufe: integer );
begin;
Stufe:=Spielstufe;
end;
{Setzt die Feldgráe.}
procedure setzeFeldgroesse ( x: integer; y: integer; var ok: boolean );
begin;
if (x<MINFELDSIZE) or (x>MAXFELDSIZE) or (y<MINFELDSIZE) or (y>MAXFELDSIZE) then
ok := false
else
begin
ok := true;
FeldSizeX:=x;
FeldSizeY:=y;
aktzug:=0;
endzug:=0;
Zug^[aktZug].State := UNDEFINIERT;
end;
end;
{Gibt die Feldgráe zurck.}
procedure gibFeldgroesse ( var x: integer; var y: integer );
begin;
x:=FeldSizeX;
y:=FeldSizeY;
end;
{Gibt die Gewinnreihe zurck.}
procedure gibGewinnreihe (var x1 : integer; var y1: integer;
var x2 : integer; var y2: integer; var ok: boolean);
begin;
if (Zug^[aktZug].State=EINS_GEWINNT) or (Zug^[aktZug].State=ZWEI_GEWINNT) then
begin
x1:=AnfangsPos.x;
y1:=AnfangsPos.y;
x2:=EndPos.x;
y2:=EndPos.y;
ok := true;
end
else
ok := false;
end;
{Gibt meinen Namen zurck.}
procedure gibNamen ( var name: string );
begin;
name := 'Sabine Wolf';
end;
{Gibt den Spitznamen des Computerspielers zurck.}
procedure gibSpitzNamen ( var name: string );
begin;
name:='Neck-Breaker';
end;
{Variablen werden initialisiert und auf Defaultwerte gesetzt.}
begin
FeldSizeX := DEFFELDSIZE;
FeldSizeY := DEFFELDSIZE;
Spielstufe := 2;
aktZug := 0;
endzug := 0;
new(Zug);
Zug^[aktZug].State := UNDEFINIERT;
Steinzuordnung[EINS_AM_ZUG] := Weiss;
Steinzuordnung[ZWEI_AM_ZUG] := Schwarz;
Flip[EINS_AM_ZUG] := ZWEI_AM_ZUG;
Flip[ZWEI_AM_ZUG] := EINS_AM_ZUG;
{Zufall wird initialisiert}
randomize;
{die Vektoren der vier Richtungen}
rv[waagerecht].x := 1;
rv[waagerecht].y := 0;
rv[senkrecht].x := 0;
rv[senkrecht].y := 1;
rv[vorschraeg].x := 1;
rv[vorschraeg].y := 1;
rv[rueckschraeg].x := -1;
rv[rueckschraeg].y := 1;
{die den Richtungen zugeordneten Zweierpotenzen}
pfak[waagerecht]:=1;
pfak[senkrecht]:=4;
pfak[vorschraeg]:=16;
pfak[rueckschraeg]:=64;
end.
|
unit eAtasOrais.view.principal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Objects, FMX.ListBox,
FMX.Edit, FMX.SearchBox, FMX.Effects, FMX.MultiView, FMX.DateTimeCtrls,
FMX.ComboEdit, FMX.Filter.Effects, FMX.TabControl, FMX.Ani, FMX.ScrollBox,
FMX.Memo;
type
TFormPrincipal = class(TForm)
Estilos: TStyleBook;
LayPrincipal: TLayout;
Barra: TToolBar;
BtMenu: TButton;
ImgMenu: TPath;
ImgPrincipal: TImage;
LayTitulo: TLayout;
TituloMain: TLabel;
VersaoTitulo: TLabel;
BtGerarAtas: TButton;
ImgGerarRams: TPath;
ComboPeriodo: TComboBox;
ListaTurmasLayout: TRectangle;
SombraTurmas: TShadowEffect;
LayListaTurmas: TLayout;
BarraTurmas: TLayout;
ListaTurmas: TListBox;
BuscaTurmas: TSearchBox;
BtRefreshTurmas: TButton;
ImgRefresh: TPath;
LabelListaTurmas: TLabel;
SombraBarra: TShadowEffect;
LayAlunosInfo: TLayout;
LayAlunos1: TLayout;
LayAlunos2: TLayout;
LayAlunos3: TLayout;
LayAlunos4: TLayout;
ListaAlunos: TListBox;
SombraListaAlunos: TShadowEffect;
CabecalhoAlunos: TListBoxHeader;
LabelListaAlunos: TLabel;
BtRefreshAlunos: TButton;
img_refreshAlunos: TPath;
LabelTurma: TLabel;
Turma: TLabel;
LabelHorario: TLabel;
Horario: TLabel;
LabelDias: TLabel;
Dias: TLabel;
Labelexaminador: TLabel;
BtRefreshPeriodos: TButton;
Img_refresfperiodos: TPath;
LabelProf: TLabel;
Professor: TLabel;
MenuPrincipal: TMultiView;
Config_title: TLayout;
Img_setup: TPath;
LabelConfigTitle: TLabel;
LinhaDiv: TLine;
LayoutConfig1: TLayout;
LabelCFG1: TLabel;
EdCFGServidor: TEdit;
LayoutConfig2: TLayout;
LabelCFG2: TLabel;
EdCFGUID: TEdit;
LayoutConfig3: TLayout;
LabelCFG3: TLabel;
EdCFGPWD: TEdit;
LayoutConfig4: TLayout;
LabelCFG4: TLabel;
EdCFGPasta: TEdit;
LayoutConfig5: TLayout;
LabelCFG5: TLabel;
EdCFGUnidade: TEdit;
LayoutConfig10: TLayout;
LabelCFG10: TLabel;
EdCFGBanco: TEdit;
BtSalvaConfig: TButton;
PasswordEditButton1: TPasswordEditButton;
ClearEditButton1: TClearEditButton;
LayoutHorario: TLayout;
BtFechar: TButton;
imgFechar: TPath;
Line2: TLine;
FillRGBEffect1: TFillRGBEffect;
CaixaSobre: TMultiView;
LaySobre1: TLayout;
LaySobre2: TLayout;
ImgSobre: TImage;
LaySobre3: TLayout;
LabelSobre1: TLabel;
LabelSobre2: TLabel;
LabelSobre3: TLabel;
LaySobre4: TLayout;
LabelSobre4: TLabel;
LineSobre: TLine;
LabelSobre5: TLabel;
LayMsg: TLayout;
Sombra: TRectangle;
TabMensagem: TTabControl;
TabProcessando: TTabItem;
TabGerado: TTabItem;
LayMsg2: TLayout;
LabelMsg2: TLabel;
LayMsg1: TLayout;
LabelMsg1: TLabel;
ImgSucessoMsg: TRectangle;
LayoutConfig11: TLayout;
LabelCFG11: TLabel;
EdCFGTestes: TSwitch;
TabErro: TTabItem;
LayoutMsg3: TLayout;
LabelMsgErro: TLabel;
imgMsgErro: TRectangle;
MsgAnimation: TAniIndicator;
AnimaMsgAbre: TFloatAnimation;
AnimaMsgFecha: TFloatAnimation;
RecCombo3: TRectangle;
ListBoxItem1: TListBoxItem;
Examinador: TComboEdit;
procedure MenuPrincipalStartShowing(Sender: TObject);
procedure BtSalvaConfigClick(Sender: TObject);
procedure BtRefreshPeriodosClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtRefreshTurmasClick(Sender: TObject);
procedure ListaTurmasItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
procedure ComboPeriodoChange(Sender: TObject);
procedure BtRefreshAlunosClick(Sender: TObject);
procedure BtFecharClick(Sender: TObject);
procedure ImgPrincipalClick(Sender: TObject);
procedure BtGerarAtasClick(Sender: TObject);
procedure AnimaMsgFechaFinish(Sender: TObject);
procedure ExaminadorTyping(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FPeriodo : string;
FTurma : string;
FCod_cur : string;
FNum_niv : string;
FNum_tur : string;
FDias : string;
FHorario : string;
FProfessor : string;
FAlunos : TStrings;
FConceitos : TStrings;
Procedure ExibeSobre;
public
{ Public declarations }
end;
var
FormPrincipal: TFormPrincipal;
implementation
uses
eAtasOrais.Controller.Factory, eAtasOrais.Controller.interfaces;
{$R *.fmx}
procedure TFormPrincipal.AnimaMsgFechaFinish(Sender: TObject);
begin
LayMsg.Visible := False;
end;
procedure TFormPrincipal.BtFecharClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFormPrincipal.BtGerarAtasClick(Sender: TObject);
var i : integer;
begin
FAlunos.Clear;
FConceitos.Clear;
for I := 0 to ListaAlunos.Items.Count-1 do
begin
Falunos.Add(ListaAlunos.ListItems[i].ItemData.Text);
FConceitos.Add(listaalunos.ListItems[i].ItemData.Detail);
end;
TControllerFactory.New.Atas
.Periodo(FPeriodo)
.Alunos(Falunos)
.Conceitos(FConceitos)
.Examinador(FProfessor)
.Dias(Dias.Text)
.horario(Horario.Text)
.Turma(FTurma)
.Gerar;
end;
procedure TFormPrincipal.BtRefreshAlunosClick(Sender: TObject);
begin
TControllerFactory.New.alunos.Listar(Fperiodo, FCod_cur, fNum_Niv, FNum_Tur, ListaAlunos);
end;
procedure TFormPrincipal.BtRefreshPeriodosClick(Sender: TObject);
begin
TControllerFactory.New.Periodos.Listar(ComboPeriodo);
end;
procedure TFormPrincipal.BtRefreshTurmasClick(Sender: TObject);
begin
TControllerFactory.New.turmas.Listar(ComboPeriodo.Selected.Text, listaturmas);
TControllerFactory.New.Funcoes.LimpaTela;
BtRefreshTurmas.Enabled := True;
end;
procedure TFormPrincipal.BtSalvaConfigClick(Sender: TObject);
begin
TControllerFactory.New.Configuracao
.Servidor(EdCFGServidor.Text)
.UID(EdCFGUID.Text)
.PWD(EdCFGPWD.Text)
.Pasta(EdCFGPasta.Text)
.Unidade(EdCFGUnidade.Text)
.Banco(EdCFGBanco.Text)
.Testes(EdCFGTestes.IsChecked)
.Gravar;
MenuPrincipal.HideMaster;
ShowMessage('Configurações salvas com sucesso!');
end;
procedure TFormPrincipal.ComboPeriodoChange(Sender: TObject);
begin
if ComboPeriodo.ItemIndex <> -1 then
begin
TControllerFactory.New.turmas.Listar(ComboPeriodo.Selected.Text, listaturmas);
FPeriodo := ComboPeriodo.Selected.Text;
TControllerFactory.New.Professores.Listar(FPeriodo, Examinador);
BtRefreshTurmas.Enabled := True;
TControllerFactory.New.Funcoes.LimpaTela;
BtGerarAtas.Enabled := (ListaAlunos.Items.Count > 0);
end;
end;
procedure TFormPrincipal.ExaminadorTyping(Sender: TObject);
begin
Examinador.Text := UpperCase(Examinador.Text);
end;
procedure TFormPrincipal.ExibeSobre;
begin
CaixaSobre.ShowMaster;
end;
procedure TFormPrincipal.FormCreate(Sender: TObject);
begin
FAlunos := TStringList.Create;
FConceitos := TStringList.Create;
formprincipal.BtRefreshAlunos.Enabled := false;
formprincipal.BtRefreshTurmas.Enabled := False;
TControllerFactory.New.Funcoes.LimpaTela;
ReportMemoryLeaksOnShutdown := true;
TControllerFactory.New.Periodos.Listar(ComboPeriodo);
end;
procedure TFormPrincipal.FormDestroy(Sender: TObject);
begin
FAlunos.DisposeOf;
FConceitos.DisposeOf;
end;
procedure TFormPrincipal.ImgPrincipalClick(Sender: TObject);
begin
ExibeSobre;
end;
procedure TFormPrincipal.ListaTurmasItemClick(const Sender: TCustomListBox;
const Item: TListBoxItem);
var Fturmas : icontrollerturmas;
begin
Fturmas := TControllerFactory.New.turmas.Buscar(FPeriodo, item.Text);
FTurma := FTurmas.Turma;
FCod_cur := Fturmas.Cod_cur;
FNum_niv := Fturmas.Num_Niv;
FNum_tur := Fturmas.Num_Tur;
FDias := Fturmas.Dias;
FHorario := Fturmas.Horario;
FProfessor := Fturmas.Professor;
Turma.Text := FTurmas.Turma;
Horario.Text := FTurmas.Horario;
Professor.Text := FTurmas.Professor;
Examinador.Text := FTurmas.Professor;
Dias.Text := FTurmas.DiasApresentar;
BtRefreshAlunos.Enabled := true;
Examinador.Enabled := True;
TControllerFactory.New.alunos.Listar(fperiodo, fcod_cur, fnum_niv, fnum_tur, ListaAlunos);
BtGerarAtas.Enabled := (ListaAlunos.Items.Count > 0);
end;
procedure TFormPrincipal.MenuPrincipalStartShowing(Sender: TObject);
begin
TControllerFactory.New.Configuracao
.Servidor(EdCFGServidor)
.UID(EdCFGUID)
.PWD(EdCFGPWD)
.Pasta(EdCFGPasta)
.Unidade(EdCFGUnidade)
.Banco(EdCFGBanco)
.Testes(EdCFGTestes);
end;
end.
|
unit udmDadosAverbaCli;
interface
uses
System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS;
type
TdmDadosAverbaCli = class(TdmPadrao)
qryLocalizacaoCNPJAVERBA: TStringField;
qryLocalizacaoCODIGOAVERBA: TStringField;
qryLocalizacaoUSUARIOAVERBA: TStringField;
qryLocalizacaoSENHAAVERBA: TStringField;
qryLocalizacaoCAMINHOPASTAAVERBA: TStringField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryManutencaoCNPJAVERBA: TStringField;
qryManutencaoCODIGOAVERBA: TStringField;
qryManutencaoUSUARIOAVERBA: TStringField;
qryManutencaoSENHAAVERBA: TStringField;
qryManutencaoCAMINHOPASTAAVERBA: TStringField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
private
FCNPJcliAverba : String;
public
property CNPJcliAverba: String read FCNPJcliAverba write FCNPJcliAverba;
end;
const
SQL_DEFAULT = 'SELECT * FROM STWAVERBACLI AVB';
var
dmDadosAverbaCli: TdmDadosAverbaCli;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TdmDadosAverbaCli }
procedure TdmDadosAverbaCli.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add(' WHERE AVB.CNPJAVERBA = :CNPJAVERBA');
Params[0].AsString := FCNPJcliAverba ;
Open;
end;
end;
end.
|
//Exercicio 100: Faça uma função que tenha como parâmetro uma temperatura em Celsius e retorne a temperatura em Kelvin.
//( K = 273 + C ).
{ Solução em Portugol
Algoritmo Exercicio 100;
Var
K: real;
Procedimento ConversorKelvin(Var k: real);
Inicio
exiba("Digite uma temperatura em Celsius:");
leia(c);
enquanto(c < -273)faça
exiba("Digite uma temperatura válida:");
leia(c);
fimenquanto;
k <- 273 + c;
exiba(c," Celsius equivalem a ");
Fim;
Inicio
exiba("Programa que converte de Celsius para Kelvin.");
ConversorKelvin(K);
exiba(K," Kelvin.");
Fim.
}
// Solução em Pascal
Program Exercicio100;
uses crt;
Var
K: real;
Procedure ConversorKelvin(Var k: real);
Var
c: real;
Begin
writeln('Digite uma temperatura em Celsius:');
readln(c);
while(c < -273)do
Begin
writeln('Digite uma temperatura válida:');
readln(c);
end;
k := 273 + c;
write(c:0:2,' Celsius equivalem a ');
End;
Begin
writeln('Programa que converte de Celsius para Kelvin.');
ConversorKelvin(K);
writeln(K:0:2,' Kelvin.');
repeat until keypressed;
end. |
unit ssPopupTreeEdit;
interface
uses
SysUtils, Classes, Controls, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxTL, cxDBTL, DB, ImgList, dialogs, cxLookAndFeels,
Messages;
type
TssLocateOptions = set of (loPartialKey, loCaseInsensitive);
TssPopupTreeEdit = class(TcxPopupEdit)
private
FTree: TcxDBTreeList;
FParentField: string;
FKeyField: string;
FDisplayField: string;
FValue: integer;
FShowExpandedTree: boolean;
FOnGetNodeImageIndex: TcxTreeListGetNodeImageIndexEvent;
FAllowEmpty: Boolean;
function GetListSource: TDataSource;
procedure SetListSource(const Value: TDataSource);
procedure SetKeyField(const Value: string);
procedure SetParentField(const Value: string);
procedure SetDisplayField(const Value: string);
procedure SetValue(const Value: integer);
procedure TreeDblClick(Sender: TObject);
procedure TreeKeyPress(Sender: TObject; var Key: Char);
procedure TreeGetNodeImageIndex(Sender: TObject; ANode: TcxTreeListNode; AIndexType: TcxTreeListImageIndexType;var AIndex: TImageIndex);
function GetImages: TCustomImageList;
procedure SetImages(const Value: TCustomImageList);
procedure RefreshLookupItems;
procedure SetAllowEmpty(const Value: Boolean);
protected
procedure DoInitPopup; override;
procedure DoEditKeyPress(var Key: Char); override;
procedure DoEditKeyUp(var Key: Word; Shift: TShiftState); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure CloseUp(AAccept: Boolean); override;
property Value: integer read FValue write SetValue;
property InnerTree: TcxDBTreeList read FTree;
function Locate(AValue: Variant; ACol: integer; ALocateOptions: TssLocateOptions = []): boolean;
published
property OnGetNodeImageIndex: TcxTreeListGetNodeImageIndexEvent read FOnGetNodeImageIndex write FOnGetNodeImageIndex;
property AllowEmpty: Boolean read FAllowEmpty write SetAllowEmpty default True;
property ListSource: TDataSource read GetListSource write SetListSource;
property KeyField: string read FKeyField write SetKeyField;
property ParentField: string read FParentField write SetParentField;
property DisplayField: string read FDisplayField write SetDisplayField;
property ShowExpandedTree: boolean read FShowExpandedTree write FShowExpandedTree;
property Images: TCustomImageList read GetImages write SetImages;
end;
implementation
uses Windows;
{ TssPopupTreeEdit }
procedure TssPopupTreeEdit.CloseUp(AAccept: Boolean);
begin
inherited;
end;
constructor TssPopupTreeEdit.Create(AOwner: TComponent);
var
FCol: TcxTreeListColumn;
begin
inherited;
Properties.PopupSizeable := False;
Properties.PopupAutoSize := False;
FAllowEmpty := True;
Text := '';
FTree := TcxDBTreeList.Create(nil);
with FTree do begin
Font.Assign(Self.Font);
LookAndFeel.Kind := lfFlat;
CreateColumn;
FCol := CreateColumn;
FCol.Visible := False;
BorderStyle := cxcbsNone;
OptionsView.Headers := False;
OptionsView.ColumnAutoWidth := True;
OptionsSelection.CellSelect := False;
Self.Properties.PopupControl := FTree;
OnDblClick := TreeDblClick;
OnKeyPress := TreeKeyPress;
OnGetNodeImageIndex := TreeGetNodeImageIndex;
end;
end;
destructor TssPopupTreeEdit.Destroy;
begin
FTree.Free;
inherited;
end;
procedure TssPopupTreeEdit.DoEditKeyPress(var Key: Char);
var
FText: string;
begin
if (Key=#8) and ((Length(EditingText)<>SelLength) or not FAllowEmpty)
then Key:=#0
else if Key=' ' then begin
DropDown;
Key:=#0;
end
else if (Key>#29) then begin
FText:=Copy(EditingText, 1, SelStart)+Key;
Key:=#0;
if Locate(FText, 0, [loPartialKey]) then begin
EditingText:=FTree.FocusedNode.Values[0];
FValue:=FTree.FocusedNode.Values[1];
SelStart:=Length(FText);
SelLength:=Length(EditingText) - SelStart;
end;
end
else inherited;
end;
procedure TssPopupTreeEdit.DoEditKeyUp(var Key: Word; Shift: TShiftState);
begin
if (Key in [VK_DOWN, VK_UP]) and (Shift = []) and (FTree.Count > 0) then begin
if EditingText = '' then begin
EditingText := FTree.FocusedNode.Values[0];
FValue:=FTree.FocusedNode.Values[1];
SelectAll;
end
else
case Key of
VK_DOWN:
if FTree.FocusedNode<>FTree.LastNode then begin
if not FTree.FocusedNode.Expanded then FTree.FocusedNode.Expand(False);
FTree.FocusedNode:=FTree.FocusedNode.GetNext;
EditingText:=FTree.FocusedNode.Values[0];
SelectAll;
FValue:=FTree.FocusedNode.Values[1];
end;
VK_UP:
if FTree.FocusedNode.AbsoluteIndex<>0 then begin
FTree.FocusedNode:=FTree.FocusedNode.GetPrev;
EditingText:=FTree.FocusedNode.Values[0];
SelectAll;
FValue:=FTree.FocusedNode.Values[1];
end;
end;
end
else inherited;
end;
procedure TssPopupTreeEdit.DoInitPopup;
begin
if FShowExpandedTree then FTree.FullExpand;
inherited;
end;
function TssPopupTreeEdit.GetImages: TCustomImageList;
begin
Result:=FTree.Images;
end;
function TssPopupTreeEdit.GetListSource: TDataSource;
begin
Result:=FTree.DataController.DataSource;
end;
procedure TssPopupTreeEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if (Key in [VK_BACK, VK_DELETE]) and ((Length(EditingText)<>SelLength) or not FAllowEmpty)
then Key:=0;
end;
procedure TssPopupTreeEdit.Loaded;
begin
inherited;
FTree.Width := Self.Width - 2;
Properties.PopupWidth := Self.Width - 2;
end;
function TssPopupTreeEdit.Locate(AValue: Variant; ACol: integer; ALocateOptions: TssLocateOptions = []): boolean;
var
i: integer;
function LocateNode(AValue: Variant; ACol: integer; ANode: TcxTreeListNode): boolean;
var
i: integer;
res: boolean;
begin
Result:=False;
if loPartialKey in ALocateOptions
then res:=Pos(AnsiLowerCase(AValue), AnsiLowerCase(ANode.Values[ACol]))=1
else res:=ANode.Values[ACol]=AValue;
if res then begin
FTree.FocusedNode:=ANode;
Result:=True;
Exit;
end;
if not ANode.Expanded then ANode.Expand(False);
for i:=0 to ANode.Count-1 do begin
if LocateNode(AValue, ACol, ANode.Items[i]) then begin
Result:=True;
Exit;
end;
end;
if not FShowExpandedTree then ANode.Collapse(False);
end;
begin
Result:=False;
for i:=0 to FTree.Count-1 do begin
if LocateNode(AValue, ACol, FTree.Items[i]) then begin
Result:=True;
Exit;
end;
end;
end;
procedure TssPopupTreeEdit.RefreshLookupItems;
var
BM: TBookmark;
begin
with Properties.LookupItems do begin
Clear;
if (ListSource<>nil) and (ListSource.DataSet<>nil) and not ListSource.DataSet.IsEmpty
then begin
BM:=ListSource.DataSet.GetBookmark;
try
ListSource.DataSet.First;
while not ListSource.DataSet.Eof do begin
Add(ListSource.DataSet.fieldbyname(FDisplayField).AsString);
ListSource.DataSet.Next;
end;
finally
ListSource.DataSet.GotoBookmark(BM);
ListSource.DataSet.FreeBookmark(BM);
end;
end;
end;
end;
procedure TssPopupTreeEdit.SetAllowEmpty(const Value: Boolean);
begin
FAllowEmpty := Value;
end;
procedure TssPopupTreeEdit.SetDisplayField(const Value: string);
begin
FDisplayField := Value;
FTree.Columns[0].DataBinding.FieldName:=Value;
end;
procedure TssPopupTreeEdit.SetImages(const Value: TCustomImageList);
begin
FTree.Images:=Value;
end;
procedure TssPopupTreeEdit.SetKeyField(const Value: string);
begin
FKeyField := Value;
FTree.DataController.KeyField:=Value;
FTree.Columns[1].DataBinding.FieldName:=Value;
end;
procedure TssPopupTreeEdit.SetListSource(const Value: TDataSource);
begin
FTree.DataController.DataSource:=Value;
RefreshLookupItems;
end;
procedure TssPopupTreeEdit.SetParentField(const Value: string);
begin
FParentField := Value;
FTree.DataController.ParentField:=Value;
end;
procedure TssPopupTreeEdit.SetValue(const Value: integer);
begin
if Locate(Value, 1) or (Value = 0) then begin
FValue := Value;
if Value <> 0 then Self.Text:=FTree.FocusedNode.Values[0];
end;
end;
procedure TssPopupTreeEdit.TreeDblClick(Sender: TObject);
begin
if FTree.FocusedNode <> nil then begin
FValue := FTree.FocusedNode.Values[1];
Self.Text := FTree.FocusedNode.Values[0];
Self.CloseUp(False);
end;
end;
procedure TssPopupTreeEdit.TreeGetNodeImageIndex(Sender: TObject; ANode: TcxTreeListNode; AIndexType: TcxTreeListImageIndexType; var AIndex: TImageIndex);
begin
if Assigned(OnGetNodeImageIndex) then
OnGetNodeImageIndex(Sender, ANode, AIndexType, AIndex);
end;
procedure TssPopupTreeEdit.TreeKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
#13: TreeDblClick(Sender);
#27: CloseUp(True);
end;
end;
end.
|
unit UPlatform;
interface
uses
UTickCount;
type
TPlatform = Class
public
class function GetTickCount : TTickCount;
class function GetElapsedMilliseconds(Const previousTickCount : TTickCount) : Int64;
End;
implementation
{$IFNDEF FPC}
Uses windows;
{$ENDIF}
{ TPlatform }
class function TPlatform.GetElapsedMilliseconds(const previousTickCount: TTickCount): Int64;
begin
Result := (Self.GetTickCount - previousTickCount);
end;
class function TPlatform.GetTickCount: TTickCount;
begin
Result := {$IFDEF CPU64}GetTickCount64{$ELSE}{$IFNDEF FPC}Windows.{$ELSE}SysUtils.{$ENDIF}GetTickCount{$ENDIF};
end;
end.
|
unit tc6PublicInfo;
{$Include l3XE.inc}
{$I tc6_ver.inc}
interface
{$IfNDef XE}
uses
Classes, ActiveX, tc6OpenAppClasses;
function VarToObject(const V: OleVariant): TObject;
function VarFromObject(Obj: TObject): IDispatch;
{$IFNDEF DELPHI3}
function VarFromInt64(const Int64Val: Int64): OleVariant;
{$ENDIF DELPHI3}
procedure VarToSet(TypeInfo: Pointer; const V: OleVariant; var S; Size: Integer);
function VarFromSet(TypeInfo: Pointer; const S; Size: Integer): OleVariant;
function __coerce_Boolean(const Arg: TVariantArg): Boolean;
function __coerce_Byte(const Arg: TVariantArg): Byte;
function __coerce_Word(const Arg: TVariantArg): Word;
function __coerce_Integer(const Arg: TVariantArg): Integer;
function __coerce_Cardinal(const Arg: TVariantArg): Cardinal;
function __coerce_Shortint(const Arg: TVariantArg): Shortint;
function __coerce_Smallint(const Arg: TVariantArg): Smallint;
function __coerce_Longint(const Arg: TVariantArg): Longint;
function __coerce_Variant(const Arg: TVariantArg): Variant;
function __coerce_OleVariant(const Arg: TVariantArg): OleVariant;
{$IFNDEF DELPHI3}
function __coerce_Longword(const Arg: TVariantArg): Longword;
function __coerce_Int64(const Arg: TVariantArg): Int64;
{$ENDIF DELPHI3}
function __coerce_Largeint(const Arg: TVariantArg): Largeint;
function __coerce_WordBool(const Arg: TVariantArg): WordBool;
function __coerce_Char(const Arg: TVariantArg): Char;
function __coerce_WideChar(const Arg: TVariantArg): WideChar;
function __coerce_String(const Arg: TVariantArg): WideString;
function __coerce_WideString(const Arg: TVariantArg): WideString;
function __coerce_Real(const Arg: TVariantArg): Real;
function __coerce_Single(const Arg: TVariantArg): Single;
{$IFDEF DELPHI4}
function __coerce_Comp(const Arg: TVariantArg): Comp;
{$ENDIF DELPHI4}
function __coerce_Currency(const Arg: TVariantArg): Currency;
function __coerce_Extended(const Arg: TVariantArg): Extended;
function __coerce_Double(const Arg: TVariantArg): Double;
function __coerce_PChar(const Arg: TVariantArg): PChar;
function __coerce_PWideChar(const Arg: TVariantArg): PWideChar;
function __coerce_TObject(const Arg: TVariantArg): TObject;
function __coerce_IUnknown(const Arg: TVariantArg): IUnknown;
function __coerce_IDispatch(const Arg: TVariantArg): IDispatch;
function _RegisterMethod(ClassInfo: Pointer; MethodType: TtcMethodType;
const MethodName: WideString; RetVal: Pointer; const Params: array of Pointer;
const Names: array of WideString; MethodProc: TtcMethodProc): Boolean;
{$EndIf XE}
implementation
{$IfNDef XE}
uses
{$IFDEF DELPHI6}
Variants,
{$ELSE}
Forms,
{$ENDIF}
SysUtils,
TypInfo,
Messages,
Windows
{$IFDEF DELPHI7}
{$IFNDEF BCB}
, ObjAuto
{$ENDIF}
{$ENDIF}
;
type
TtcMethodList = class(TList)
protected
{$IFDEF DELPHI5}
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
{$ENDIF DELPHI5}
end;
PtcCallData = ^TtcCallData;
TtcCallData = packed record
MethodProc: TtcMethodProc;
Instance: TObject;
Args: PVariantArgList;
Value: OleVariant;
Cookie: Cardinal;
end;
PtcFrameData = ^TtcFrameData;
TtcFrameData = packed record
CallData: PtcCallData;
FrameException: WideString;
Signal: THandle;
end;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
PtcClassMethodCookieData = ^TtcClassMethodCookieData;
TtcClassMethodCookieData = packed record
MethodInfo: PMethodInfoHeader;
ParamCount: Integer;
Params: array of PParamInfo;
end;
{$ENDIF}
{$ENDIF}
TtcPublicInfoLibrary = class
private
FTable: TtcTable;
FCompiledTable: TtcTable;
FFrame: THandle;
FMainThread: Cardinal;
FBufferList: TList;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
FMethodCookieList: TList;
{$ENDIF}
{$ENDIF}
protected
procedure FrameProcedure(var Message: TMessage);
procedure DispatchData(Data: PtcCallData);
procedure Clear;
public
constructor Create;
destructor Destroy; override;
function RegisterMethod(ClassInfo: Pointer; MethodType: TtcMethodType;
const MethodName: WideString; RetVal: Pointer; const Params: array of Pointer;
const Names: array of WideString; MethodProc: TtcMethodProc): Boolean;
function GetMethodList(ClassInfo: Pointer; out MethodInfoList: PtcMethodInfoList;
out Size: Integer): Boolean;
procedure ReleaseMethodList(MethodList: PtcMethodInfoList);
end;
{$IFNDEF DELPHI5}
TIntegerSet = set of 0..SizeOf(Integer) * 8 - 1;
{$ENDIF}
var
PublicInfoLibrary: TtcPublicInfoLibrary;
const
TypType2Type: array[TTypeKind] of TtcTypeKind = (
tckUnknown, tckInteger, tckChar, tckEnumeration, tckFloat,
tckString, tckSet, tckClass, tckMethod, tckWChar, tckLString, tckWString,
tckVariant, tckArray, tckRecord, tckInterface {$IFNDEF DELPHI3}, tckInt64, tckDynArray{$ENDIF DELPHI3}
);
TypeToVT: array[TtcTypeKind] of Integer = (
VT_EMPTY, VT_I4, VT_I1, VT_I4, VT_R8,
VT_BSTR, VT_BSTR, VT_DISPATCH, VT_EMPTY, VT_BSTR, VT_BSTR, VT_BSTR,
VT_VARIANT, VT_EMPTY, VT_EMPTY, VT_UNKNOWN, VT_DECIMAL, VT_EMPTY
);
VisibleTypeKinds: TTypeKinds = [tkInteger, tkChar, tkEnumeration, tkFloat,
tkString, tkSet, tkClass, tkWChar, tkLString, tkWString,
tkVariant, tkInterface];
var
CMD_DISPATCH: UINT;
{$IFNDEF DELPHI6}
function VarToWideStr(const V: Variant): WideString;
begin
if not VarIsNull(V) then
Result := V
else
Result := '';
end;
{$ENDIF}
function _RegisterMethod(ClassInfo: Pointer; MethodType: TtcMethodType;
const MethodName: WideString; RetVal: Pointer; const Params: array of Pointer;
const Names: array of WideString; MethodProc: TtcMethodProc): Boolean;
begin
Result := PublicInfoLibrary.RegisterMethod(ClassInfo, MethodType,
MethodName, RetVal, Params, Names, MethodProc);
end;
function GetMethodList(ClassInfo: Pointer;
out MethodInfoList: PtcMethodInfoList; out Size: Integer): Boolean;
begin
Result := PublicInfoLibrary.GetMethodList(ClassInfo, MethodInfoList, Size);
end;
procedure ReleaseMethodList(MethodList: PtcMethodInfoList);
begin
if PublicInfoLibrary <> nil then
PublicInfoLibrary.ReleaseMethodList(MethodList);
end;
function CreateParameter(ParamType: Pointer; const Name: WideString): PtcParameter;
var
Info: PTypeInfo;
begin
New(Result);
Result.Name := Name;
Info := PTypeInfo(ParamType);
if Info <> nil then
begin
Result.TypeKind := TypType2Type[Info.Kind];
Result.TypeName := Info.Name;
Result.VT := TypeToVT[Result.TypeKind];
case Result.TypeKind of
tckEnumeration:
if SameText(Result.TypeName, 'Boolean') then
Result.VT := VT_BOOL;
tckInterface:
if SameText(Result.TypeName, 'IDispatch') then
Result.VT := VT_DISPATCH;
end;
end;
Result.Data := Info;
end;
procedure _PropSetMethodSync(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
PropInfo: PPropInfo;
V: OleVariant;
S: WideString;
begin
PropInfo := PPropInfo(Cookie);
Assert(PropInfo <> nil);
V := OleVariant(Args^[0]);
case PropInfo.PropType^.Kind of
tkInteger:
SetOrdProp(Instance, PropInfo, V);
tkWChar, tkChar:
begin
S := VarToWideStr(V);
if S = '' then
SetOrdProp(Instance, PropInfo, 0)
else
SetOrdProp(Instance, PropInfo, Ord(S[1]));
end;
tkString, tkLString, tkWString:
SetStrProp(Instance, PropInfo, VarToWideStr(V));
tkEnumeration:
if SameText(PropInfo.PropType^.Name, 'Boolean') then
SetOrdProp(Instance, PropInfo, Integer(Boolean(V)))
else
SetOrdProp(Instance, PropInfo, V);
tkFloat:
SetFloatProp(Instance, PropInfo, V);
{$IFDEF DELPHI5}
tkSet:
SetSetProp(Instance, PropInfo, VarToWideStr(V));
{$ENDIF DELPHI5}
tkClass:
SetOrdProp(Instance, PropInfo, Integer(VarToObject(V)));
tkVariant:
SetVariantProp(Instance, PropInfo, V);
{$IFDEF DELPHI6}
tkInt64:
SetInt64Prop(Instance, PropInfo, Trunc(V));
tkInterface:
SetInterfaceProp(Instance, PropInfo, IUnknown(V));
{$ENDIF DELPHI6}
else
// Unsupported types:
// tkUnknown, tkMethod, tkRecord, tkArray, tkDynArray
end;
end;
procedure _PropSetMethod(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
CallData: TtcCallData;
begin
CallData.MethodProc := _PropSetMethodSync;
CallData.Instance := Instance;
CallData.Args := Args;
CallData.Cookie := Cookie;
PublicInfoLibrary.DispatchData(@CallData);
Value := CallData.Value;
end;
procedure _PropGetMethodSync(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
PropInfo: PPropInfo;
begin
PropInfo := PPropInfo(Cookie);
Assert(PropInfo <> nil);
case PropInfo.PropType^.Kind of
tkInteger:
Value := GetOrdProp(Instance, PropInfo);
tkWChar, tkChar:
Value := WideString(WideChar(GetOrdProp(Instance, PropInfo)));
tkString, tkLString, tkWString:
Value := GetStrProp(Instance, PropInfo);
tkEnumeration:
begin
Value := GetOrdProp(Instance, PropInfo);
if SameText(PropInfo.PropType^.Name, 'Boolean') then
Value := Boolean(Value);
end;
tkFloat:
Value := GetFloatProp(Instance, PropInfo);
{$IFDEF DELPHI5}
tkSet:
Value := GetSetProp(Instance, PropInfo);
{$ENDIF DELPHI5}
tkClass:
Value := VarFromObject(TObject(GetOrdProp(Instance, PropInfo)));
tkVariant:
Value := GetVariantProp(Instance, PropInfo);
{$IFDEF DELPHI6}
tkInt64:
Value := GetInt64Prop(Instance, PropInfo);
tkInterface:
Value := GetInterfaceProp(Instance, PropInfo);
{$ENDIF DELPHI6}
else
// Unsupported types:
// tkUnknown, tkMethod, tkRecord, tkArray, tkDynArray
Value := Null;
end;
end;
procedure _PropGetMethod(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
CallData: TtcCallData;
begin
CallData.MethodProc := _PropGetMethodSync;
CallData.Instance := Instance;
CallData.Args := Args;
CallData.Cookie := Cookie;
PublicInfoLibrary.DispatchData(@CallData);
Value := CallData.Value;
end;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
function GetVarDataInd(AVarData: PVarData): PVarData;
begin
if AVarData^.VType and varByRef <> 0 then
Result := GetVarDataInd(AVarData.VPointer)
else
Result := AVarData;
end;
// GetVariantType and InterfaceDerivesFrom: see ObjAuto.pas
function GetVariantType(TypeInfo: PTypeInfo): TVarType;
function InterfaceDerivesFrom(TypeData: PTypeData; const GUID: TGUID): Boolean;
begin
Result := True;
while TypeData <> nil do
begin
if IsEqualGUID(TypeData^.Guid, GUID) then
Exit;
if (TypeData^.IntfParent <> nil) and (TypeData^.IntfParent^ <> nil) then
TypeData := GetTypeData(TypeData^.IntfParent^)
else
Break;
end;
Result := False;
end;
var
TypeData: PTypeData;
begin
case TypeInfo^.Kind of
tkUnknown: Result := varError;
tkInteger, tkChar, tkEnumeration, tkWChar:
if (TypeInfo = System.TypeInfo(Boolean)) or
(TypeInfo = System.TypeInfo(WordBool)) or
(TypeInfo = System.TypeInfo(LongBool)) then
Result := varBoolean
else
begin
TypeData := GetTypeData(TypeInfo);
if TypeData^.MinValue >= 0 then
if Cardinal(TypeData^.MaxValue) > $FFFF then
Result := varLongWord
else if TypeData^.MaxValue > $FF then
Result := varWord
else
Result := varByte
else
if (TypeData^.MaxValue > $7FFF) or (TypeData^.MinValue < -$7FFF - 1) then
Result := varInteger
else if (TypeData^.MaxValue > $7F) or (TypeData^.MinValue < -$7F - 1) then
Result := varSmallint
else
Result := varShortint;
end;
tkFloat:
begin
TypeData := GetTypeData(TypeInfo);
case TypeData^.FloatType of
ftSingle: Result := varSingle;
ftDouble:
if TypeInfo = System.TypeInfo(TDateTime) then
Result := varDate
else
Result := varDouble;
ftComp, ftCurr: Result := varCurrency;
else
Result := varError;
end;
end;
tkString: Result := varString;
tkLString: Result := varString;
tkWString: Result := varOleStr;
tkInterface:
begin
TypeData := GetTypeData(TypeInfo);
if InterfaceDerivesFrom(TypeData, IDispatch) then
Result := varDispatch
else
Result := varUnknown;
end;
tkVariant: Result := varVariant;
tkInt64: Result := varInt64;
else
Result := varError;
end;
end;
procedure _ExecuteClassMethod(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
ParamIndexes: array of Integer;
Params: array of Variant;
ParamInfo: PParamInfo;
l, i, j: Integer;
MethodCookie: PtcClassMethodCookieData;
CurrentParam: OleVariant;
VarType: TVarType;
VarData: PVarData;
begin
MethodCookie := PtcClassMethodCookieData(Cookie);
Assert(MethodCookie <> nil);
l := MethodCookie.ParamCount;
SetLength(ParamIndexes, l);
SetLength(Params, l);
j := 0;
for i := l - 1 downto 0 do
begin
ParamInfo := MethodCookie.Params[j];
if ParamInfo.Flags * [pfOut, pfVar] <> [] then
begin
VariantInit(CurrentParam);
VarType := GetVariantType(ParamInfo.ParamType^) or varByRef;
if ParamInfo.ParamType^.Kind <> tkVariant then
begin
TVarData(CurrentParam).VType := VarType;
VarData := GetVarDataInd(PVarData(@Args^[i]));
TVarData(CurrentParam).VPointer := @VarData.VPointer;
end
else
CurrentParam := OleVariant(Args^[i]);
end
else
CurrentParam := OleVariant(Args^[i]);
Params[j] := CurrentParam;
ParamIndexes[j] := j + 1;
Inc(j);
end;
Value := ObjAuto.ObjectInvoke(Instance, MethodCookie.MethodInfo, ParamIndexes, Params);
//
j := 0;
for i := l - 1 downto 0 do
begin
ParamInfo := MethodCookie.Params[j];
if ParamInfo.Flags * [pfOut, pfVar] <> [] then
begin
if ParamInfo.ParamType^.Kind <> tkVariant then
Continue
else
VarCopy(Args^[i].pvarVal^, Params[j]);
end;
Inc(j);
end;
end;
{$ENDIF}
{$ENDIF}
procedure _StdMethod(Instance: TObject; Args: PVariantArgList; out Value: OleVariant; Cookie: Cardinal); stdcall;
var
CallData: TtcCallData;
begin
CallData.MethodProc := TtcMethodProc(Cookie);
CallData.Instance := Instance;
CallData.Args := Args;
CallData.Cookie := 0;
PublicInfoLibrary.DispatchData(@CallData);
Value := CallData.Value;
end;
function GetClassTypeInfo(ClassInstance: Pointer): Pointer;
asm
MOV EAX, [EAX + vmtTypeInfo]
end;
function VarToObject(const V: OleVariant): TObject;
begin
Assert(Assigned(VarToObjectProc));
if Assigned(VarToObjectProc) then
Result := VarToObjectProc(V)
else
Result := nil;
end;
function VarFromObject(Obj: TObject): IDispatch;
begin
Assert(Assigned(VarFromObjectProc));
if Assigned(VarFromObjectProc) then
Result := VarFromObjectProc(Obj)
else
Result := nil;
end;
{$IFNDEF DELPHI3}
function VarFromInt64(const Int64Val: Int64): OleVariant;
const
VT_I8 = $0014;
begin
Result := Null;
tagVariant(Result).vt := VT_I8;
PInt64(@tagVariant(Result).lVal)^ := Int64Val;
end;
{$ENDIF DELPHI3}
function SetToInt(const S; Size: Integer): Integer;
begin
case Size of
1:
Result := Byte(S);
2:
Result := Word(S);
else
Result := Integer(S);
end;
end;
procedure SetFromInt(I: Integer; var S; Size: Integer);
begin
case Size of
1:
Byte(S) := I;
2:
Word(S) := I;
else
Integer(S) := I;
end;
end;
procedure VarToSet(TypeInfo: Pointer; const V: OleVariant; var S; Size: Integer);
var
P: PChar;
EnumName: string;
EnumValue: Longint;
EnumInfo: PTypeInfo;
// grab the next enum name
function NextWord(var P: PChar): string;
var
i: Integer;
begin
i := 0;
// scan til whitespace
while not (P[i] in [',', ' ', #0,']']) do
Inc(i);
SetString(Result, P, i);
// skip whitespace
while P[i] in [',', ' ',']'] do
Inc(i);
Inc(P, i);
end;
var
i4: Integer;
Value: String;
begin
i4 := 0;
SetFromInt(i4, S, Size);
Value := VarToWideStr(V);
if Value = '' then Exit;
P := PChar(Value);
// skip leading bracket and whitespace
while P^ in ['[',' '] do
Inc(P);
EnumInfo := GetTypeData(TypeInfo)^.CompType^;
EnumName := NextWord(P);
while EnumName <> '' do
begin
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
break;
Include(TIntegerSet(i4), EnumValue);
EnumName := NextWord(P);
end;
SetFromInt(i4, S, Size);
end;
function VarFromSet(TypeInfo: Pointer; const S; Size: Integer): OleVariant;
var
IntSet: TIntegerSet;
CompType: PTypeInfo;
I: Integer;
Str: WideString;
begin
Integer(IntSet) := SetToInt(S, Size);
CompType := GetTypeData(TypeInfo)^.CompType^;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in IntSet then
begin
if Str <> '' then
Str := Str + ',';
Str := Str + GetEnumName(CompType, I);
end;
Result := Str;
end;
// Standard coerce procedures
function __coerce_Boolean(const Arg: TVariantArg): Boolean;
begin
Result := OleVariant(Arg);
end;
function __coerce_Integer(const Arg: TVariantArg): Integer;
begin
Result := OleVariant(Arg);
end;
function __coerce_TObject(const Arg: TVariantArg): TObject;
begin
Result := VarToObject(OleVariant(Arg));
end;
function __coerce_WideString(const Arg: TVariantArg): WideString;
begin
Result := VarToWideStr(OleVariant(Arg));
end;
function __coerce_Byte(const Arg: TVariantArg): Byte;
begin
Result := OleVariant(Arg);
end;
function __coerce_IUnknown(const Arg: TVariantArg): IUnknown;
begin
Result := IUnknown(OleVariant(Arg));
end;
function __coerce_IDispatch(const Arg: TVariantArg): IDispatch;
begin
Result := IUnknown(OleVariant(Arg)) as IDispatch;
end;
function __coerce_Word(const Arg: TVariantArg): Word;
begin
Result := OleVariant(Arg);
end;
function __coerce_Cardinal(const Arg: TVariantArg): Cardinal;
begin
Result := OleVariant(Arg);
end;
function __coerce_Shortint(const Arg: TVariantArg): Shortint;
begin
Result := OleVariant(Arg);
end;
function __coerce_Smallint(const Arg: TVariantArg): Smallint;
begin
Result := OleVariant(Arg);
end;
function __coerce_Longint(const Arg: TVariantArg): Longint;
begin
Result := OleVariant(Arg);
end;
function __coerce_Variant(const Arg: TVariantArg): Variant;
begin
Result := OleVariant(Arg);
end;
function __coerce_OleVariant(const Arg: TVariantArg): OleVariant;
begin
Result := OleVariant(Arg);
end;
{$IFNDEF DELPHI6}
function _VarToInt64(const V: OleVariant): Largeint;
const
VAR_LOCALE_USER_DEFAULT = $400; // = Windows.LOCALE_USER_DEFAULT
var
LTemp: OleVariant;
LResult: HResult;
begin
LResult := VariantChangeTypeEx(LTemp, V, VAR_LOCALE_USER_DEFAULT, 0, varInteger);
if LResult = S_OK then
Result := TVarData(LTemp).VInteger
else
begin
LResult := VariantChangeTypeEx(LTemp, V, VAR_LOCALE_USER_DEFAULT, 0, varDouble);
if LResult = S_OK then
Result := Round(TVarData(LTemp).VDouble)
else if LResult = DISP_E_TYPEMISMATCH then
begin
{$IFNDEF DELPHI3}
LResult := VariantChangeTypeEx(LTemp, V, VAR_LOCALE_USER_DEFAULT, 0, varBoolean);
if LResult = S_OK then
Result := Largeint(TVarData(LTemp).VBoolean)
else
{$ENDIF DELPHI3}
Result := 0;
end
else
Result := 0;
end;
end;
{$ENDIF DELPHI6}
{$IFNDEF DELPHI3}
function __coerce_Longword(const Arg: TVariantArg): Longword;
begin
Result := OleVariant(Arg);
end;
function __coerce_Int64(const Arg: TVariantArg): Int64;
begin
{$IFDEF DELPHI6}
Result := OleVariant(Arg);
{$ELSE}
Result := _VarToInt64(OleVariant(Arg));
{$ENDIF DELPHI6}
end;
{$ENDIF DELPHI3}
function __coerce_Largeint(const Arg: TVariantArg): Largeint;
begin
{$IFDEF DELPHI6}
Result := OleVariant(Arg);
{$ELSE}
Result := _VarToInt64(OleVariant(Arg));
{$ENDIF DELPHI6}
end;
function __coerce_WordBool(const Arg: TVariantArg): WordBool;
begin
Result := OleVariant(Arg);
end;
function __coerce_Char(const Arg: TVariantArg): Char;
begin
Result := String(VarToWideStr(OleVariant(Arg)))[1];
end;
function __coerce_WideChar(const Arg: TVariantArg): WideChar;
begin
Result := VarToWideStr(OleVariant(Arg))[1];
end;
function __coerce_String(const Arg: TVariantArg): WideString;
begin
Result := VarToWideStr(OleVariant(Arg));
end;
function __coerce_Real(const Arg: TVariantArg): Real;
begin
Result := OleVariant(Arg);
end;
function __coerce_Single(const Arg: TVariantArg): Single;
begin
Result := OleVariant(Arg);
end;
{$IFDEF DELPHI4}
function __coerce_Comp(const Arg: TVariantArg): Comp;
begin
Result := OleVariant(Arg);
end;
{$ENDIF DELPHI4}
function __coerce_Currency(const Arg: TVariantArg): Currency;
begin
Result := OleVariant(Arg);
end;
function __coerce_Extended(const Arg: TVariantArg): Extended;
begin
Result := OleVariant(Arg);
end;
function __coerce_Double(const Arg: TVariantArg): Double;
begin
Result := OleVariant(Arg);
end;
function __coerce_PChar(const Arg: TVariantArg): PChar;
begin
Result := PChar(String(VarToWideStr(OleVariant(Arg))));
end;
function __coerce_PWideChar(const Arg: TVariantArg): PWideChar;
begin
Result := PWideChar(VarToWideStr(OleVariant(Arg)));
end;
{ TtcPublicInfoLibrary }
procedure TtcPublicInfoLibrary.Clear;
var
I: Integer;
begin
for I := 0 to FBufferList.Count - 1 do
FreeMem(FBufferList[I]);
{$IFDEF DELPHI7}
{$IFNDEF BCB}
for I := 0 to FMethodCookieList.Count - 1 do
begin
SetLength(PtcClassMethodCookieData(FMethodCookieList[I]).Params, 0);
FreeMem(FMethodCookieList[I]);
end;
{$ENDIF}
{$ENDIF}
FTable.Clear;
FCompiledTable.Clear;
end;
constructor TtcPublicInfoLibrary.Create;
begin
FMainThread := GetCurrentThreadId;
FTable := TtcObjectTable.Create;
FCompiledTable := TtcObjectTable.Create;
FFrame := AllocateHWnd(FrameProcedure);
FBufferList := TList.Create;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
FMethodCookieList := TList.Create;
{$ENDIF}
{$ENDIF}
end;
destructor TtcPublicInfoLibrary.Destroy;
begin
Clear;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
FreeAndNil(FMethodCookieList);
{$ENDIF}
{$ENDIF}
FreeAndNil(FBufferList);
FreeAndNil(FTable);
FreeAndNil(FCompiledTable);
DeallocateHWnd(FFrame);
inherited;
end;
procedure TtcPublicInfoLibrary.DispatchData(Data: PtcCallData);
var
FrameData: TtcFrameData;
begin
FrameData.CallData := Data;
try
if FMainThread <> GetCurrentThreadId then
begin
// Avoid COM ISC
FrameData.Signal := CreateEvent(nil, True, False, nil);
try
PostMessage(FFrame, CMD_DISPATCH, Integer(@FrameData), 0);
WaitForSingleObject(FrameData.Signal, INFINITE);
finally
CloseHandle(FrameData.Signal);
end;
end
else
SendMessage(FFrame, CMD_DISPATCH, Integer(@FrameData), 0);
finally
if FrameData.FrameException <> '' then
raise Exception.Create(FrameData.FrameException);
end;
end;
procedure TtcPublicInfoLibrary.FrameProcedure(var Message: TMessage);
begin
if Message.Msg = CMD_DISPATCH then
begin
try
with PtcFrameData(Message.WParam).CallData^ do
MethodProc(Instance, Args, Value, Cookie);
except
on E: Exception do
PtcFrameData(Message.WParam)^.FrameException := E.Message;
end;
SetEvent(PtcFrameData(Message.WParam).Signal);
Message.Result := 0;
end
else
Message.Result := DefWindowProc(FFrame, Message.Msg, Message.WParam, Message.LParam);
end;
function TtcPublicInfoLibrary.GetMethodList(ClassInfo: Pointer;
out MethodInfoList: PtcMethodInfoList; out Size: Integer): Boolean;
var
List: TList;
procedure RetrieveTypeInfoMethods(ClassInfo: Pointer);
function Clone(MethodInfo: PtcMethodInfo): PtcMethodInfo;
var
I: Integer;
Parameter: PtcParameter;
begin
New(Result);
Result.ParamCount := 0;
Result.Params := nil;
Result.MethodType := MethodInfo.MethodType;
Result.MethodName := MethodInfo.MethodName;
Result.MethodProc := MethodInfo.MethodProc;
Result.Cookie := MethodInfo.Cookie;
if MethodInfo.RetVal <> nil then
begin
New(Result.RetVal);
Result.RetVal^ := MethodInfo.RetVal^;
end
else
Result.RetVal := nil;
if MethodInfo.ParamCount > 0 then
begin
Result.ParamCount := MethodInfo.ParamCount;
GetMem(Result.Params, Result.ParamCount * SizeOf(Pointer));
for I := 0 to MethodInfo.ParamCount - 1 do
begin
New(Parameter);
Parameter^ := PtcParameter(MethodInfo.Params^[I])^;
Result.Params^[I] := Parameter;
end;
end;
end;
var
I: Integer;
MethodList: TtcMethodList;
begin
if ClassInfo <> nil then
begin
MethodList := TtcMethodList(FTable.Get(ClassInfo));
if MethodList <> nil then
begin
for I := 0 to MethodList.Count - 1 do
List.Add(Clone(PtcMethodInfo(MethodList[I])));
end;
end;
end;
procedure IterateOverAncestors(ClassInfo: Pointer);
var
Ancestor: TClass;
begin
if ClassInfo <> nil then
begin
Ancestor := TClass(ClassInfo).ClassParent;
if Ancestor <> nil then
begin
RetrieveTypeInfoMethods(Ancestor);
IterateOverAncestors(Ancestor);
end;
end;
end;
procedure FillTypInfo;
var
I, Count: Integer;
TypeData: PTypeData;
PropList: PPropList;
PropInfo: PPropInfo;
MethodInfo: PtcMethodInfo;
TypeInfo: PTypeInfo;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
J: Integer;
MethodInfoProvider: ItcMethodInfoProvider;
ParamInfo: PParamInfo;
ReturnInfo: PReturnInfo;
CookieData: PtcClassMethodCookieData;
{$ENDIF}
{$ENDIF}
begin
TypeInfo := PTypeInfo(TClass(ClassInfo).ClassInfo);
if TypeInfo = nil then
exit;
TypeData := GetTypeData(TypeInfo);
if TypeData = nil then
exit;
Count := TypeData.PropCount;
if Count = 0 then
exit;
GetMem(PropList, SizeOf(Pointer) * Count);
Assert(PropList <> nil);
if PropList = nil then
exit;
FBufferList.Add(PropList);
Count := GetPropList(TypeInfo, VisibleTypeKinds, PropList);
for I := 0 to Count - 1 do
begin
PropInfo := PPropInfo(PropList^[I]);
if PropInfo.SetProc <> nil then
begin
New(MethodInfo);
MethodInfo.MethodType := mtPut;
MethodInfo.MethodName := PropInfo.Name;
MethodInfo.RetVal := nil;
MethodInfo.ParamCount := 1;
GetMem(MethodInfo.Params, SizeOf(Pointer));
MethodInfo.Params^[0] := CreateParameter(PropInfo.PropType^, 'Value');
MethodInfo.MethodProc := _PropSetMethod;
MethodInfo.Cookie := Cardinal(PropInfo);
List.Add(MethodInfo);
end;
if PropInfo.GetProc <> nil then
begin
New(MethodInfo);
MethodInfo.ParamCount := 0;
MethodInfo.Params := nil;
MethodInfo.MethodType := mtGet;
MethodInfo.MethodName := PropInfo.Name;
MethodInfo.RetVal := CreateParameter(PropInfo.PropType^, '');
MethodInfo.MethodProc := _PropGetMethod;
MethodInfo.Cookie := Cardinal(PropInfo);
List.Add(MethodInfo);
end;
end;
{$IFDEF DELPHI7}
{$IFNDEF BCB}
MethodInfoProvider := CreateMethodInfoProvider(TClass(ClassInfo));
Count := MethodInfoProvider.GetCount;
for I := 0 to Count - 1 do
begin
New(MethodInfo);
MethodInfo.MethodType := mtInvoke;
MethodInfo.MethodName := MethodInfoProvider.GetName(I);
MethodInfo.ParamCount := MethodInfoProvider.GetParamCount(I);
MethodInfo.MethodProc := _ExecuteClassMethod;
//
GetMem(CookieData, SizeOf(CookieData^));
FillChar(CookieData^, SizeOf(CookieData^), #0);
SetLength(CookieData.Params, MethodInfo.ParamCount);
CookieData.MethodInfo := MethodInfoProvider.GetCookie(I);
CookieData.ParamCount := MethodInfo.ParamCount;
MethodInfo.Cookie := Cardinal(CookieData);
//
if MethodInfo.ParamCount > 0 then
begin
GetMem(MethodInfo.Params, SizeOf(Pointer) * MethodInfo.ParamCount);
for J := 0 to MethodInfo.ParamCount - 1 do
begin
ParamInfo := MethodInfoProvider.GetParamInfo(I, J);
Assert(ParamInfo <> nil);
CookieData.Params[J] := ParamInfo;
MethodInfo.Params^[J] := CreateParameter(ParamInfo.ParamType^, ParamInfo.Name);
end;
end;
ReturnInfo := MethodInfoProvider.GetReturnInfo(I);
if (ReturnInfo <> nil) and (ReturnInfo.ReturnType <> nil) then
MethodInfo.RetVal := CreateParameter(ReturnInfo.ReturnType^, '')
else
MethodInfo.RetVal := nil;
//
List.Add(MethodInfo);
FMethodCookieList.Add(CookieData);
end;
{$ENDIF}
{$ENDIF}
end;
begin
Assert(ClassInfo <> nil);
if not FCompiledTable.ContainsKey(ClassInfo) then
begin
List := TtcMethodList.Create;
RetrieveTypeInfoMethods(ClassInfo);
IterateOverAncestors(ClassInfo);
//QC if List.Count = 0 then
FillTypInfo;
FCompiledTable.Put(ClassInfo, List);
end
else
List := TList(FCompiledTable.Get(ClassInfo));
Size := List.Count;
GetMem(MethodInfoList, Size * SizeOf(Pointer));
Move(List.List^, MethodInfoList^, Size * SizeOf(Pointer));
Result := Size > 0;
end;
function TtcPublicInfoLibrary.RegisterMethod(ClassInfo: Pointer;
MethodType: TtcMethodType; const MethodName: WideString; RetVal: Pointer;
const Params: array of Pointer; const Names: array of WideString; MethodProc: TtcMethodProc): Boolean;
var
List: TtcMethodList;
MethodInfo: PtcMethodInfo;
I: Integer;
begin
Result := False;
Assert(ClassInfo <> nil);
if ClassInfo = nil then
exit;
if not FTable.ContainsKey(ClassInfo) then
begin
List := TtcMethodList.Create;
FTable.Put(ClassInfo, List);
end
else
List := TtcMethodList(FTable.Get(ClassInfo));
Assert(List <> nil);
New(MethodInfo);
MethodInfo.MethodType := MethodType;
MethodInfo.MethodName := MethodName;
MethodInfo.MethodProc := _StdMethod;
if RetVal <> nil then
MethodInfo.RetVal := CreateParameter(RetVal, '')
else
MethodInfo.RetVal := nil;
TtcMethodProc(MethodInfo.Cookie) := MethodProc;
Assert((High(Params) - Low(Params)) = (High(Names) - Low(Names)));
if (High(Params) = Low(Params)) and (Params[Low(Params)] = nil) then
begin
MethodInfo.ParamCount := 0;
MethodInfo.Params := nil;
end
else
begin
MethodInfo.ParamCount := High(Params) - Low(Params) + 1;
GetMem(MethodInfo.Params, MethodInfo.ParamCount * SizeOf(Pointer));
for I := Low(Params) to High(Params) do
MethodInfo.Params^[I - Low(Params)] := CreateParameter(Params[I], Names[I]);
end;
List.Add(MethodInfo);
Result := True;
end;
procedure TtcPublicInfoLibrary.ReleaseMethodList(
MethodList: PtcMethodInfoList);
begin
FreeMem(MethodList);
end;
{ TtcMethodList }
{$IFDEF DELPHI5}
procedure TtcMethodList.Notify(Ptr: Pointer; Action: TListNotification);
var
I: Integer;
begin
inherited;
if Action = lnDeleted then
begin
for I := 0 to PtcMethodInfo(Ptr).ParamCount - 1 do
Dispose(PtcMethodInfo(Ptr).Params[I]);
if PtcMethodInfo(Ptr).ParamCount > 0 then
FreeMem(PtcMethodInfo(Ptr).Params);
if PtcMethodInfo(Ptr).RetVal <> nil then
Dispose(PtcMethodInfo(Ptr).RetVal);
Dispose(PtcMethodInfo(Ptr));
end;
end;
{$ENDIF DELPHI5}
initialization
CMD_DISPATCH := RegisterWindowMessage('97A7D25DF77E429F8004E2EA817885F4');
PublicInfoLibrary := TtcPublicInfoLibrary.Create;
tc6OpenAppClasses.GetMethodListProc := GetMethodList;
tc6OpenAppClasses.ReleaseMethodListProc := ReleaseMethodList;
finalization
FreeAndNil(PublicInfoLibrary);
{$EndIf XE}
end.
|
unit IdSASLDigest;
interface
{$i IdCompilerDefines.inc}
uses
Classes,
SysUtils, //here to facilitate inline expansion
IdSASL, IdSASLUserPass, IdUserPassProvider, IdException;
type
TIdSASLDigest = class(TIdSASLUserPass)
protected
Fauthzid : String;
public
function StartAuthenticate(const AChallenge, AHost, AProtocolName:string) : String; override;
function ContinueAuthenticate(const ALastResponse, AHost, AProtocolName : string): string; override;
class function ServiceName: TIdSASLServiceName; override;
function IsReadyToStart: Boolean; override;
published
property authzid : String read Fauthzid write Fauthzid;
end;
EIdSASLDigestException = class(EIdException);
EIdSASLDigestChallException = class(EIdSASLDigestException);
EIdSASLDigestChallNoAlgorithm = class(EIdSASLDigestChallException);
EIdSASLDigestChallInvalidAlg = class(EIdSASLDigestChallException);
EIdSASLDigestAuthConfNotSupported = class(EIdSASLDigestException);
//done this way so we can use testboxes
function CalcDigestResponse(const AUserName, APassword, ARealm, ANonce, ACNonce : String;
const ANC : Integer;
const AQop, ADigestURI : String; const AAuthzid : String = '') : String;
implementation
uses
IdFIPS, IdGlobal, IdGlobalProtocols, IdHash, IdHashMessageDigest, IdResourceStringsProtocols;
const
SASL_DIGEST_METHOD = 'AUTHENTICATE:'; {do not localize}
function NCToStr(const AValue : Integer):String;
{$IFDEF USE_INLINE} inline; {$ENDIF}
begin
Result := IntToHex(AValue,8);
end;
function Unquote(var S: String): String;
{$IFDEF USE_INLINE} inline; {$ENDIF}
var
I, Len: Integer;
begin
Len := Length(S);
I := 2; // skip first quote
while I <= Len do
begin
if S[I] = '"' then begin
Break;
end;
if S[I] = '\' then begin
Inc(I);
end;
Inc(I);
end;
Result := Copy(S, 2, I-2);
S := Copy(S, I+1, MaxInt);
end;
//
function HashResult(const AStr : String): TIdBytes;
{$IFDEF USE_INLINE} inline; {$ENDIF}
begin
with TIdHashMessageDigest5.Create do
try
Result := HashString(AStr);
finally
Free;
end;
end;
function HashResultAsHex(const ABytes : TIdBytes) : String; overload;
{$IFDEF USE_INLINE} inline; {$ENDIF}
begin
with TIdHashMessageDigest5.Create do
try
Result := LowerCase(HashBytesAsHex(ABytes));
finally
Free;
end;
end;
function HashResultAsHex(const AStr : String) : String; overload;
{$IFDEF USE_INLINE} inline; {$ENDIF}
begin
with TIdHashMessageDigest5.Create do
try
Result := LowerCase(HashStringAsHex(AStr));
finally
Free;
end;
end;
function CalcDigestResponse(const AUserName, APassword, ARealm, ANonce, ACNonce : String;
const ANC : Integer; const AQop, ADigestURI : String; const AAuthzid : String = '') : String;
var
LA1 : TIdBytes;
LA2: TIdBytes;
LA1_P : TIdBytes;
begin
LA1_P := IdGlobal.ToBytes(':' + ANonce + ':' + ACNonce);
LA1 := HashResult(AUserName + ':' + ARealm + ':' +
APassword);
IdGlobal.AppendBytes(LA1,LA1_P);
If AAuthzid <> '' then begin
IdGlobal.AppendBytes(LA1,IdGlobal.ToBytes(AAuthzid));
end;
if AQop = 'auth' then begin
LA2 := ToBytes('AUTHENTICATE:' + ADigestURI);
end
else if (AQop = 'auth-int') or (AQop = 'auth-conf') then begin
LA2 := ToBytes('AUTHENTICATE:' + ADigestURI + ':00000000000000000000000000000000');
end else begin
SetLength(LA2,0);
end;
Result := HashResultAsHex(HashResultAsHex(LA1) + ':' + ANonce + ':' +
NCToStr(ANC) + ':' + ACNonce + ':' + AQop +':' + HashResultAsHex(LA2));
end;
//
{ TIdSASLDigest }
function TIdSASLDigest.ContinueAuthenticate(const ALastResponse, AHost,
AProtocolName: string): string;
begin
Result := '';
end;
function TIdSASLDigest.IsReadyToStart: Boolean;
begin
Result := not GetFIPSMode;
end;
class function TIdSASLDigest.ServiceName: TIdSASLServiceName;
begin
Result := 'DIGEST-MD5';
end;
function TIdSASLDigest.StartAuthenticate(const AChallenge, AHost, AProtocolName: string): String;
var
LBuf : String;
LChallange: TStringList;
LReply : TStringList;
Lqop : String;
LstrCNonce : String;
LstrResponse : String;
LURL : String;
LCharset : String;
LQopOptions: TStrings;
LAlgorithm : String;
LNonce : String;
LRealm: String;
LName, LValue: String;
begin
LURL := AProtocolName+'/'+AHost;
LReply := TStringList.Create;
LChallange := TStringList.Create;
LQopOptions:= TStringList.Create;
try
LBuf := AChallenge;
while Length(LBuf) > 0 do begin
LName := Trim(Fetch(LBuf, '=')); {do not localize}
LBuf := TrimLeft(LBuf);
if TextStartsWith(LBuf, '"') then begin {do not localize}
LValue := Unquote(LBuf); {do not localize}
Fetch(LBuf, ','); {do not localize}
end else begin
LValue := Trim(Fetch(LBuf, ','));
end;
LChallange.Add(LName + '=' + LValue);
LBuf := TrimLeft(LBuf);
end;
LQopOptions.CommaText := LChallange.Values['qop'];
if LQopOptions.IndexOf('auth-int') > -1 then begin
Lqop := 'auth-int';
end else begin
Lqop := 'auth';
end;
if LQopOptions.IndexOf('auth-conf') > -1 then begin
if LQopOptions.IndexOf('auth') = -1 then begin
EIdSASLDigestAuthConfNotSupported.Toss(RSSASLDigestAuthConfNotSupported);
end;
end;
LNonce := LChallange.Values['nonce'];
LRealm := LChallange.Values['realm'];
LAlgorithm := LChallange.Values['algorithm'];
if LAlgorithm = '' then begin
EIdSASLDigestChallNoAlgorithm.Toss(RSSASLDigestMissingAlgorithm);
end;
{
if LAlgorithm <> 'md5-sess' then begin
EIdSASLDigestChallInvalidAlg.Toss(RSSASLDigestInvalidAlgorithm);
end;
}
//Commented out for case test mentioned in RFC 2831
LstrCNonce := HashResultAsHex(DateTimeToStr(Now));
LCharset := LChallange.Values['charset'];
LstrResponse := CalcDigestResponse(GetUserName,Self.GetPassword,LRealm,LNonce,LstrCNonce,
1, Lqop, LURL,Fauthzid);
// if LQopOptions.IndexOf('auth-conf') > -1 then begin
// if LQopOptions.IndexOf('auth') = -1 then begin
// EIdSASLDigestAuthConfNotSupported.Toss(RSSASLDigestAuthConfNotSupported);
// end;
// end;
if LCharset = '' then begin
Result := '';
end else begin
Result := 'charset='+LCharset+',';
end;
{
#( username | realm | nonce | cnonce |
nonce-count | qop | digest-uri | response |
maxbuf | charset | cipher | authzid |
auth-param )
}
Result := Result + 'username="'+GetUsername+'"'+
',realm="'+LRealm+'"'+ {Do not localize}
',nonce="'+ LNonce+'"'+
',nc='+NCToStr(1)+
',cnonce="'+LstrCNonce+'"'+
',digest-uri="'+LURL+'"'+
',response='+LstrResponse+
',qop='+Lqop;
finally
FreeAndNil(LQopOptions);
FreeAndNil(LChallange);
FreeAndNil(LReply);
end;
end;
end.
|
{$MODE OBJFPC}
program MaximumBipartiteMatching;
const
InputFile = 'ASSIGN.INP';
OutputFile = 'ASSIGN.OUT';
maxN = 100000;
maxM = 100000;
var
p, q: Integer;
adj: array[1..maxM] of Integer;
link: array[1..maxM] of Integer;
head: array[1..maxN] of Integer;
match: array[1..maxN] of Integer;
lab: array[1..maxN] of Integer;
avail: array[1..maxN] of Boolean;
List: array[1..maxN] of Integer;
nList: Integer;
res: Integer;
procedure Enter;
var
i: Integer;
x, y: Integer;
f: TextFile;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, p, q);
FillChar(head[1], p * SizeOf(head[1]), 0);
FillDWord(match[1], q, 0);
FillDWord(lab[1], p, 0);
i := 0;
while not SeekEof(f) do
begin
Inc(i);
ReadLn(f, x, y);
adj[i] := y;
link[i] := head[x]; head[x] := i;
if (lab[x] = 0) and (match[y] = 0) then
begin
match[y] := x;
lab[x] := y;
end;
end;
finally
CloseFile(f);
end;
end;
procedure Init;
var
i: Integer;
begin
nList := 0;
for i := 1 to p do
if lab[i] = 0 then
begin
Inc(nList); List[nList] := i;
end;
end;
procedure SuccessiveAugmentingPaths;
var
Found: Boolean;
Old, i: Integer;
procedure Visit(x: Integer);
var
i: Integer;
y: Integer;
begin
i := head[x];
while i <> 0 do
begin
y := adj[i];
if avail[y] then
begin
avail[y] := False;
if match[y] = 0 then Found := True
else Visit(match[y]);
if Found then
begin
match[y] := x;
Exit;
end;
end;
i := link[i];
end;
end;
begin
repeat
Old := nList;
FillChar(avail[1], q * SizeOf(avail[1]), True);
for i := nList downto 1 do
begin
Found := False;
Visit(List[i]);
if Found then
begin
List[i] := List[nList];
Dec(nList);
end;
end;
until Old = nList;
res := p - nList;
end;
procedure PrintResult;
var
f: TextFile;
i: Integer;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
WriteLn(f, res);
for i := 1 to q do
Write(f, match[i], ' ');
finally
CloseFile(f);
end;
end;
begin
Enter;
Init;
SuccessiveAugmentingPaths;
PrintResult;
end.
4 3
1 1
1 3
2 1
2 2
3 2
4 1
|
{
\file DGLE.pas
\author Korotkov Andrey aka DRON
\version 2:0.3.1
\date 17.11.2014 (c)Korotkov Andrey
\brief Main DGLE engine header.
To use engine you should just include this header to your project.
This header is a part of DGLE_SDK.
}
unit DGLE;
interface
{$I include.inc}
{$IFNDEF DGLE_HEADER}
{$DEFINE DGLE_HEADER}
{$ENDIF}
uses
DGLE_Types, DGLE_Base, DGLE_CoreRenderer;
const
_DGLE_VER_ = '2:0.3.0';
_DGLE_SDK_VER_ = 1;
_DGLE_PLUGIN_SDK_VER_ = _DGLE_SDK_VER_;
type
{Engine Base Object interface flags}
{Events Interfaces flags}
E_EVENT_TYPE =
(
ET_UNKNOWN = 0,
ET_BEFORE_INITIALIZATION = 1,
ET_BEFORE_RENDER = 2,
ET_AFTER_RENDER = 3,
ET_ON_PROFILER_DRAW = 4,
ET_ON_WINDOW_MESSAGE = 5,
ET_ON_GET_SUBSYSTEM = 6,
ET_ON_ENGINE_FATAL_MESSAGE = 7,
ET_ON_CONSOLE_WRITE = 8,
ET_ON_FULLSCREEN = 9,
ET_ON_PER_SECOND_TIMER = 10
);
{Main Engine System flags}
E_ENGINE_PROCEDURE_TYPE =
(
EPT_UPDATE = 0,
EPT_RENDER = 1,
EPT_INIT = 2,
EPT_FREE = 3
);
E_LOG_TYPE =
(
LT_INFO = 0,
LT_WARNING = 1,
LT_ERROR = 2,
LT_FATAL = 3
);
{Render SubSystem flags}
E_GET_POINT3_MODE =
(
GP3M_FROM_DEPTH_BUFFER = 0,
GP3M_FROM_FAR_PLANE = 1,
GP3M_FROM_NEAR_PLANE = 2
);
E_BLENDING_EFFECT =
(
BE_NORMAL = 0,
BE_ADD = 1,
BE_MULT = 2,
BE_BLACK = 3,
BE_WHITE = 4,
BE_MASK = 5
);
E_BATCH_MODE2D =
(
BM_AUTO = 0,
BM_DISABLED = 1,
BM_ENABLED_UPDATE_EVERY_TICK = 2,
BM_ENABLED_UPDATE_EVERY_FRAME = 3
);
E_FIND_FLAGS =
(
FF_RECURSIVE = 1
);
E_FILE_SYSTEM_SEEK_FLAG =
(
FSSF_BEGIN = 0,
FSSF_CURRENT = 1,
FSSF_END = 2
);
const
//E_ENGINE_INIT_FLAGS
EIF_DEFAULT = $00000000;
EIF_CATCH_UNHANDLED = $00000001;
EIF_FORCE_NO_SOUND = $00000002;
EIF_LOAD_ALL_PLUGINS = $00000004;
EIF_FORCE_LIMIT_FPS = $00000010;
EIF_FORCE_16_BIT_COLOR = $00000020;
EIF_ENABLE_FLOATING_UPDATE = $00000040;
EIF_ENABLE_PER_FRAME_UPDATE = $00000100;
EIF_FORCE_NO_WINDOW = $00000200;
EIF_NO_SPLASH = $10000000;
{Resource Manager SubSystem flags}
//E_TEXTURE_CREATE_FLAGS
TCF_DEFAULT = $00000000;
TCF_PIXEL_ALIGNMENT_1 = $00000001; //use only if your texture input data is not 4 byte aligned
TCF_MIPMAPS_PRESENTED = $00000002; //all mip levels must be presented
//E_TEXTURE_LOAD_FLAGS
TLF_FILTERING_NONE = $00000001;
TLF_FILTERING_BILINEAR = $00000002;
TLF_FILTERING_TRILINEAR = $00000004;
TLF_FILTERING_ANISOTROPIC = $00000008;
TLF_DECREASE_QUALITY_MEDIUM = $00000020;
TLF_DECREASE_QUALITY_HIGH = $00000040;
TLF_COMPRESS = $00000100;
TLF_COORDS_REPEAT = $00001000;
TLF_COORDS_CLAMP = $00002000;
TLF_COORDS_MIRROR_REPEAT = $00004000;
TLF_COORDS_MIRROR_CLAMP = $00008000;
TLF_GENERATE_MIPMAPS = $00040000;
TLF_ANISOTROPY_2X = $00100000;
TLF_ANISOTROPY_4X = $00200000;
TLF_ANISOTROPY_8X = $00400000;
TLF_ANISOTROPY_16X = $00800000;
// E_BITMAP_FONT_LOAD_FLAGS
BFLF_FILTERING_NONE = $00000001;
BFLF_GENERATE_MIPMAPS = $00000002;
BFLF_FORCE_ALPHA_TEST_2D = $00000004;
//E_MESH_CREATE_FLAGS
MCF_ONLY_DEFAULT_DATA = $00000000;//vertex and index arrays must be presented
MCF_NORMALS_PRESENTED = $00000001;
MCF_TEXTURE_COORDS_PRESENTED = $00000002;
MCF_TANGENT_SPACE_PRESENTED = $00000004;
MCF_VERTEX_DATA_INTERLEAVED = $00000008;
//E_MESH_MODEL_LOAD_FLAGS
MMLF_FORCE_SOFTWARE_BUFFER = $00000001;
MMLF_DYNAMIC_BUFFER = $00000002;
MMLF_FORCE_MODEL_TO_MESH = $00000004;
//E_SOUND_SAMPLE_LOAD_FLAGS
SSLF_LOAD_AS_MUSIC = $00000001;
TEXTURE_LOAD_DEFAULT_2D = TLF_FILTERING_BILINEAR or TLF_COORDS_CLAMP;
TEXTURE_LOAD_DEFAULT_3D = TLF_FILTERING_TRILINEAR or TLF_GENERATE_MIPMAPS or TLF_COORDS_REPEAT;
RES_LOAD_DEFAULT = $00000000;
{Render2D interface FLAGS}
//E_PRIMITIVE2D_FLAGS
PF_DEFAULT = $00000000;
PF_LINE = $00000000;
PF_FILL = $00000001;
PF_VERTICES_COLORS = $00000002;
//E_EFFECT2D_FLAGS
EF_DEFAULT = $00000000;
EF_NONE = $00000001;
EF_ALPHA_TEST = $00000002;
EF_BLEND = $00000004;
EF_FLIP_HORIZONTALLY = $00000008;
EF_FLIP_VERTICALLY = $00000010;
EF_COLOR_MIX = $00000020;
EF_SCALE = $00000040;
EF_VERTICES_OFFSETS = $00000080;
EF_VERTICES_COLORS = $00000100;
EF_ROTATION_POINT = $00000200;
EF_TILE_TEXTURE = $00000400;
{Render3D interface FLAGS}
//E_PUSH_STATES_FLAGS
PSF_ALL = $00000000;
PSF_MATRIX = $00000001;
PSF_STATES = $00000002;
{Input Subsystem flags}
//E_INPUT_CONFIGURATION_FLAGS
ICF_DEFAULT = $00000000;
ICF_EXCLUSIVE = $00000001;
ICF_HIDE_CURSOR = $00000002;
ICF_CURSOR_BEYOND_SCREEN = $00000004;
{SoundSample interface}
//E_SOUND_SAMPLE_PARAMS
SSP_NONE = $00000000;
SSP_LOOPED = $00000001;
{FileSystem interfaces flags}
//E_FILE_SYSTEM_OPEN_FLAGS
FSOF_READ = $00000001;
FSOF_WRITE = $00000002;
FSOF_TRUNC = $00000004;
FSOF_BINARY = $00000008;
type
//Engine Plugin interface//
IPlugin = interface(IDGLE_Base)
['{B94E0E40-8885-41dd-8BC5-4CD663AE5709}']
function GetPluginInfo(out stInfo: TPluginInfo): DGLE_RESULT; stdcall;
function GetPluginInterfaceName(pcName: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
end;
//Engine Subsystem Plugin interface//
// Base interface of any engine core subsystem plugin.
ISubSystemPlugin = interface(IPlugin)
['{27908E31-8D8E-4076-AE33-087A1BE5DCB3}']
function GetSubSystemInterface(out prSubSystem: IEngineSubSystem): DGLE_RESULT; stdcall;
end;
//Engine Base Object interface//
IEngineBaseObject = interface(IDGLE_Base)
['{C010239A-6457-40f5-87EF-FAA3156CE6E2}']
function Free(): DGLE_RESULT; stdcall; // Never use this use IResourceManager.FreeResource instead!
function GetType(out eObjType: E_ENGINE_OBJECT_TYPE): DGLE_RESULT; stdcall;
function GetUnknownType(out uiObjUnknownType: Cardinal): DGLE_RESULT; stdcall;
end;
//Events Interfaces//
IBaseEvent = interface(IDGLE_Base)
['{6DFEF982-AADF-42e9-A369-378BDB31404A}']
function GetEventType(out eEvType: E_EVENT_TYPE): DGLE_RESULT; stdcall;
function GetUnknownEventType(out uiUnknEvType: Cardinal): DGLE_RESULT; stdcall;
end;
IEvBeforeInitialization = interface(IBaseEvent)
['{EB735739-3D12-4522-B6D7-EEE3225DF934}']
function SetParameters(const stWindowParam: TEngineWindow; eInitFlags:{E_ENGINE_INIT_FLAGS}Integer): DGLE_RESULT; stdcall;
function GetParameters(out stWindowParam: TEngineWindow; eInitFlags:{E_ENGINE_INIT_FLAGS}Integer): DGLE_RESULT; stdcall;
end;
IEvConsoleWrite = interface(IBaseEvent)
['{9E35969A-B0D4-4E5A-A89B-1A5AAD057028}']
function GetText(pcTxt: PAnsiChar; out uiCharsCount: Cardinal; out bToPrevLine: Boolean): DGLE_RESULT; stdcall;
end;
IEvFatalMessage = interface(IBaseEvent)
['{DAA4E3BC-C958-4def-B603-F63EEC908226}']
function GetMessageText(pcTxt: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function FreezeEngine(bFreeze: Boolean): DGLE_RESULT; stdcall;
function ForceNoMessage(): DGLE_RESULT; stdcall;
function ForceIgnoreError(): DGLE_RESULT; stdcall;
end;
IEvWindowMessage = interface(IBaseEvent)
['{8D718E48-581D-4cbb-9C40-C04998106F8D}']
function GetMessage(out stWinMsg: TWindowMessage): DGLE_RESULT; stdcall;
end;
IEvGetSubSystem = interface(IBaseEvent)
['{2B6D2547-716E-490c-B1F1-422CB428738F}']
function GetSubSystemType(out eSubSystem: E_ENGINE_SUB_SYSTEM): DGLE_RESULT; stdcall;
function OverrideSubSystem(prSubSystem: IEngineSubSystem): DGLE_RESULT; stdcall;
end;
IEvGoFullScreen = interface(IBaseEvent)
['{CEC9184C-74D9-4739-BF48-BB800467665B}']
function GetResolution(out uiScreenWidth, uiScreenHeight: Cardinal; out bGoFullScreen: Boolean): DGLE_RESULT; stdcall;
function SetResolution(uiScreenWidth, uiScreenHeight: Cardinal): DGLE_RESULT; stdcall;
end;
//Main Engine System//
IEngineCallback = interface(IDGLE_Base)
['{371B1338-BB25-4B8C-BD6A-BCDF241CC52C}']
function Initialize(): DGLE_RESULT; stdcall;
function Free(): DGLE_RESULT; stdcall;
function Update(uiDeltaTime: Cardinal): DGLE_RESULT; stdcall;
function Render(): DGLE_RESULT; stdcall;
function OnEvent(eEventType: E_EVENT_TYPE; pEvent: IBaseEvent): DGLE_RESULT; stdcall;
end;
TProcedure = Procedure(pParameter: Pointer); stdcall;
TEventProcedure = Procedure(pParameter: Pointer; const prBaseEvent: IBaseEvent); stdcall;
TStringProcedure = Procedure(pParameter: Pointer; const pcParam: PAnsiChar); stdcall;
TStringFunction = Function(pParameter: Pointer; const pcParam: PAnsiChar): DGLE_RESULT; stdcall;
IFileSystem = interface;
TFSDelProcedure = Procedure(pParameter: Pointer; const prVFS: IFileSystem); stdcall;
IEngineCore = interface(IDGLE_Base)
['{111BB884-2BA6-4e84-95A5-5E4700309CBA}']
function LoadSplashPicture(const pcBmpFileName: PAnsiChar): DGLE_RESULT; stdcall;
function AddPluginToInitializationList(const pcFileName: PAnsiChar): DGLE_RESULT; stdcall;
function InitializeEngine(tHandle: TWindowHandle; const pcApplicationName: PAnsiChar; const stWindowParam: TEngineWindow; uiUpdateInterval: Cardinal = 33; eInitFlags: {E_ENGINE_INIT_FLAGS}Integer = EIF_DEFAULT): DGLE_RESULT; stdcall;
function SetUpdateInterval(uiUpdateInterval: Cardinal): DGLE_RESULT; stdcall;
function StartEngine(): DGLE_RESULT; stdcall;
function QuitEngine(): DGLE_RESULT; stdcall;
function ConnectPlugin(const pcFileName: PAnsiChar; out prPlugin: IPlugin): DGLE_RESULT; stdcall;
function DisconnectPlugin(pPlugin: IPlugin): DGLE_RESULT; stdcall;
function GetPlugin(const pcPluginName: PAnsiChar; out prPlugin: IPlugin): DGLE_RESULT; stdcall;
function AddEngineCallback(pEngineCallback: IEngineCallback): DGLE_RESULT; stdcall;
function RemoveEngineCallback(pEngineCallback: IEngineCallback): DGLE_RESULT; stdcall;
function AddProcedure(eProcType: E_ENGINE_PROCEDURE_TYPE; pProc: TProcedure; pParameter: Pointer = nil): DGLE_RESULT; stdcall;
function RemoveProcedure(eProcType: E_ENGINE_PROCEDURE_TYPE; pProc: TProcedure; pParameter: Pointer = nil): DGLE_RESULT; stdcall;
function CastEvent(eEventType: E_EVENT_TYPE; pEvent: IBaseEvent): DGLE_RESULT; stdcall;
function AddEventListener(eEventType: E_EVENT_TYPE; pListenerProc: TEventProcedure; pParameter: Pointer): DGLE_RESULT; stdcall;
function RemoveEventListener(eEventType: E_EVENT_TYPE; pListenerProc: TEventProcedure; pParameter: Pointer): DGLE_RESULT; stdcall;
function GetSubSystem(eSubSystem: E_ENGINE_SUB_SYSTEM; out prSubSystem: IEngineSubSystem): DGLE_RESULT; stdcall;
function RenderFrame(): DGLE_RESULT; stdcall;
function RenderProfilerText(const pcTxt: PAnsiChar; const stColor: TColor4): DGLE_RESULT; stdcall;
function GetInstanceIndex(out uiIdx: Cardinal): DGLE_RESULT; stdcall;
function GetTimer(out uiTick: {$IFDEF UInt64_Support} UInt64 {$ELSE} Int64 {$ENDIF}): DGLE_RESULT; stdcall;
function GetSystemInfo(out stSysInfo: TSystemInfo): DGLE_RESULT; stdcall;
function GetCurrentWindow(out stWin: TEngineWindow): DGLE_RESULT; stdcall;
function GetFPS(out uiFPS: Cardinal): DGLE_RESULT; stdcall;
function GetLastUpdateDeltaTime(out uiDeltaTime: Cardinal): DGLE_RESULT; stdcall;
function GetElapsedTime(out ui64ElapsedTime: {$IFDEF UInt64_Support} UInt64 {$ELSE} Int64 {$ENDIF}): DGLE_RESULT; stdcall;
function GetWindowHandle(out tHandle: TWindowHandle): DGLE_RESULT; stdcall;
function ChangeWindowMode(const stNewWin: TEngineWindow): DGLE_RESULT; stdcall;
function GetDesktopResolution(out uiWidth, uiHeight: Cardinal): DGLE_RESULT; stdcall;
function AllowPause(bAllow: Boolean): DGLE_RESULT; stdcall;
function WriteToLog(const pcTxt: PAnsiChar): DGLE_RESULT; stdcall;
function WriteToLogEx(const pcTxt: PAnsiChar; eType: E_LOG_TYPE; const pcSrcFileName: PAnsiChar; iSrcLineNumber: Integer): DGLE_RESULT; stdcall;
function ConsoleVisible(bIsVisible: Boolean): DGLE_RESULT; stdcall;
function ConsoleWrite(const pcTxt: PAnsiChar; bWriteToPreviousLine: Boolean = false): DGLE_RESULT; stdcall;
function ConsoleExecute(const pcCommandTxt: PAnsiChar): DGLE_RESULT; stdcall;
function ConsoleRegisterCommand(const pcCommandName: PAnsiChar; const pcCommandHelp: PAnsiChar; pProc: TStringFunction; pParameter: Pointer = nil): DGLE_RESULT; stdcall;
function ConsoleRegisterVariable(const pcCommandName: PAnsiChar; const pcCommandHelp: PAnsiChar; var piVar :Integer; iMinValue: Integer; iMaxValue: Integer; pProc: TStringFunction; pParameter: Pointer = nil): DGLE_RESULT; stdcall;
function ConsoleUnregister(const pcCommandName: PAnsiChar): DGLE_RESULT; stdcall;
function GetVersion(pcBuffer: PAnsiChar; out uiBufferSize: Cardinal): DGLE_RESULT; stdcall;
end;
//Resource Manager SubSystem//
IFile = interface;
ITexture = interface;
IMesh = interface;
ILight = interface;
IModel = interface;
IMaterial = interface;
ISoundSample = interface;
ISoundChannel = interface;
TFileLoadProcedure = Procedure(out rpFile: IFile; out prObj: IEngineBaseObject; uiLoadFlags: Cardinal; pParameter: Pointer); stdcall;
IResourceManager = interface(IEngineSubSystem)
['{139505B6-5EFC-4f02-A5E8-18CD1FBD69E3}']
function CreateTexture(out prTex: ITexture; const pData: Pointer; uiWidth, uiHeight :Cardinal; eDataFormat: E_TEXTURE_DATA_FORMAT; eCreateFlags: {E_TEXTURE_CREATE_FLAGS} Integer;
eLoadFlags: {E_TEXTURE_LOAD_FLAGS} Integer; const pcName: PAnsiChar = nil; bAddResource: Boolean = True): DGLE_RESULT; stdcall;
function CreateMaterial(out prMaterial: IMaterial; const pcName: PAnsiChar = nil; bAddResource: Boolean = True): DGLE_RESULT; stdcall;
function CreateLight(out prLight: ILight; const pcName: PAnsiChar = nil; bAddResource: Boolean = True): DGLE_RESULT; stdcall;
function CreateMesh(out prMesh: IMesh; const pubtData: Pointer; uiDataSize, uiNumVerts, uiNumFaces: Cardinal; eCreateFlags: {E_MESH_CREATE_FLAGS} Integer;
eLoadFlags: {E_MESH_MODEL_LOAD_FLAGS} Integer; const pcName: PAnsiChar = nil; bAddResource: Boolean = True): DGLE_RESULT; stdcall;
function CreateModel(out prModel: IModel; const pcName: PAnsiChar = nil; bAddResource: Boolean = True): DGLE_RESULT; stdcall;
function CreateSound(out prSndSample: ISoundSample; uiSamplesPerSec, uiBitsPerSample: Cardinal; bStereo: Boolean; const pData: Pointer; ui32DataSize: Cardinal; const pcName: PAnsiChar; bAddResource: Boolean = False): DGLE_RESULT; stdcall;
function RegisterFileFormat(const pcExtension: PAnsiChar; eObjType: E_ENGINE_OBJECT_TYPE; const pcDescription: PAnsiChar; pLoadProc: TFileLoadProcedure; pParameter: Pointer): DGLE_RESULT; stdcall;
function UnregisterFileFormat(const pcExtension: PAnsiChar): DGLE_RESULT; stdcall;
function RegisterDefaultResource(eObjType: E_ENGINE_OBJECT_TYPE; pObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function UnregisterDefaultResource(eObjType: E_ENGINE_OBJECT_TYPE; pObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function GetRegisteredExtensions(pcTxt: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetExtensionDescription(const pcExtension: PAnsiChar; pcTxt: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetExtensionType(const pcExtension: PAnsiChar; out eType: E_ENGINE_OBJECT_TYPE): DGLE_RESULT; stdcall;
function GetResourceByName(const pcName: PAnsiChar; out prObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function GetResourceByIndex(uiIdx: Cardinal; out prObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function GetResourceName(pObj: IEngineBaseObject; pcName: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetDefaultResource(eObjType: E_ENGINE_OBJECT_TYPE; out prObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function GetResourcesCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function Load(const pcFileName: PAnsiChar; out prObj: IEngineBaseObject; uiLoadFlags: Cardinal = RES_LOAD_DEFAULT; const pcName: PAnsiChar = nil): DGLE_RESULT; stdcall;
function LoadEx(pFile: IFile; out prObj: IEngineBaseObject; uiLoadFlags: Cardinal = RES_LOAD_DEFAULT; const pcName: PAnsiChar = nil): DGLE_RESULT; stdcall;
function FreeResource(var prObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function AddResource(const pcName: PAnsiChar; pObj: IEngineBaseObject): DGLE_RESULT; stdcall;
function RemoveResource(pObj: IEngineBaseObject; out bCanDelete: Boolean): DGLE_RESULT; stdcall;
end;
//Render SubSystem//
IRender2D = interface;
IRender3D = interface;
IRender = interface(IEngineSubSystem)
['{EA03C661-A334-4225-B5DB-4C45452CCC41}']
function SetClearColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function GetClearColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function ClearColorBuffer(): DGLE_RESULT; stdcall;
function Unbind(eType: E_ENGINE_OBJECT_TYPE): DGLE_RESULT; stdcall; // use EOT_UNKNOWN to unbind all
function EnableScissor(const stArea: TRectf): DGLE_RESULT; stdcall;
function DisableScissor(): DGLE_RESULT; stdcall;
function GetScissor(out bEnabled: Boolean; out stArea: TRectF): DGLE_RESULT; stdcall;
function SetRenderTarget(pTargetTex: ITexture): DGLE_RESULT; stdcall;
function GetRenderTarget(out prTargetTex: ITexture): DGLE_RESULT; stdcall;
function GetRender2D(out prRender2D: IRender2D): DGLE_RESULT; stdcall;
function GetRender3D(out prRender3D: IRender3D): DGLE_RESULT; stdcall;
end;
//Render2D interface//
IRender2D = interface(IDGLE_Base)
['{F5F3257A-F8B8-4d91-BA67-451167A8D63F}']
function Begin2D(): DGLE_RESULT; stdcall;
function End2D(): DGLE_RESULT; stdcall;
function BatchRender(eMode: E_BATCH_MODE2D): DGLE_RESULT; stdcall;
function InvalidateBatchData(): DGLE_RESULT; stdcall;
function BeginBatch(bUpdateEveryFrame: Boolean = false): DGLE_RESULT; stdcall;
function EndBatch(): DGLE_RESULT; stdcall;
function NeedToUpdateBatchData(out bNeedUpdate: Boolean): DGLE_RESULT; stdcall;
function SetResolutionCorrection(uiResX, uiResY: Cardinal; bConstantProportions: Boolean = True): DGLE_RESULT; stdcall; //Set resx and resy to current screen size to turn off correction
function ResolutionCorrectToAbsolute(const stLogicCoord: TPoint2; out stAbsoluteCoord: TPoint2): DGLE_RESULT; stdcall;
function AbsoluteToResolutionCorrect(const stAbsoluteCoord: TPoint2; out stLogicCoord: TPoint2): DGLE_RESULT; stdcall;
function SetCamera(const stCenter: TPoint2; fAngle: Single; const stScale: TVector2): DGLE_RESULT; stdcall;
function ResetCamera(): DGLE_RESULT; stdcall;
function UnprojectCameraToScreen(const stCameraCoord: TPoint2; out stScreenCoord: TPoint2): DGLE_RESULT; stdcall;
function ProjectScreenToCamera(const stScreenCoord: TPoint2; out stCameraCoord: TPoint2): DGLE_RESULT; stdcall;
function CullBoundingBox(const stBBox: TRectF; fAngle: Single; out bCull: Boolean): DGLE_RESULT; stdcall;
// 2D Primitives
function SetLineWidth(uiWidth: Cardinal): DGLE_RESULT; stdcall;
function DrawPoint(const stCoords: TPoint2; const stColor: TColor4; uiSize: Cardinal = 1): DGLE_RESULT; stdcall;
function DrawLine(const stCoords1, stCoords2: TPoint2; const stColor: TColor4; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
function DrawRectangle(const stRect: TRectf; const stColor: TColor4; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
function DrawCircle(const stCoords: TPoint2; uiRadius, uiQuality: Cardinal; const stColor: TColor4; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
function DrawEllipse(const stCoords: TPoint2; stRadius: TVector2; uiQuality: Cardinal; const stColor: TColor4; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
function DrawPolygon(pTexture: ITexture; const pstVertices: PVertex2; uiVerticesCount: Cardinal; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
// 2D Sprites
function DrawTexture(pTexture: ITexture; const stCoords: TPoint2; const stDimensions: TVector2; fAngle: Single = 0.; eFlags: {E_EFFECT2D_FLAGS}Integer = EF_DEFAULT): DGLE_RESULT; stdcall;
function DrawTextureCropped(pTexture: ITexture; const stCoords: TPoint2; const stDimensions: TVector2; const stTexCropRect: TRectf; fAngle: Single = 0.; eFlags: {E_EFFECT2D_FLAGS}Integer = EF_DEFAULT): DGLE_RESULT; stdcall;
function DrawTextureSprite(pTexture: ITexture; const stCoords: TPoint2; const stDimensions: TVector2; uiFrameIndex: Cardinal; fAngle: Single = 0.; eFlags: {E_EFFECT2D_FLAGS}Integer = EF_DEFAULT): DGLE_RESULT; stdcall;
// Extra
function DrawTriangles(pTexture: ITexture; const pstVertices: PVertex2; uiVerticesCount: Cardinal; eFlags: {E_PRIMITIVE2D_FLAGS}Integer = PF_DEFAULT): DGLE_RESULT; stdcall;
function DrawMesh(pMesh: IMesh; pTexture: ITexture; const stCoords: TPoint2; const stDimensions: TVector3; const stAxis: TVector3; fAngle: Single = 0; eFlags: {E_EFFECT2D_FLAGS}Integer = EF_DEFAULT;
bClip: Boolean = True; fFovY: Single = 90.0; bClearDepthBuffer: Boolean = False): DGLE_RESULT; stdcall;
//Advanced
function Draw(pTexture: ITexture; const stDrawDesc: TDrawDataDesc; eMode: E_CORE_RENDERER_DRAW_MODE; uiCount: Cardinal; const stAABB: TRectF; eFlags: {E_EFFECT2D_FLAGS}Integer): DGLE_RESULT; stdcall;
function DrawBuffer(pTexture: ITexture; pBuffer: ICoreGeometryBuffer; const stAABB: TRectF; eFlags: {E_EFFECT2D_FLAGS}Integer): DGLE_RESULT; stdcall;
function DrawBuffer3D(pTexture: ITexture; pBuffer: ICoreGeometryBuffer; eFlags: {E_EFFECT2D_FLAGS} Integer; const stTransform: TMatrix4x4;
const stCenter: TPoint3; const stExtents: TVector3; bClip: Boolean; fFovY: Single; bClearDepthBuffer: Boolean): DGLE_RESULT; stdcall;
// Effects
function SetRotationPoint(const stCoords: TPoint2): DGLE_RESULT; stdcall; //In texture stCoords system
function SetScale(const stScale: TPoint2): DGLE_RESULT; stdcall;
function SetColorMix(const stColor: TColor4): DGLE_RESULT; stdcall;
function SetBlendMode(eMode: E_BLENDING_EFFECT = BE_NORMAL): DGLE_RESULT; stdcall;
function SetVerticesOffsets(const stCoords1, stCoords2, stCoords3, stCoords4: TPoint2): DGLE_RESULT; stdcall;
function SetVerticesColors(const stColor1, stColor2, stColor3, stColor4 : TColor4): DGLE_RESULT; stdcall;
function GetRotationPoint(out stCoords: TPoint2): DGLE_RESULT; stdcall;
function GetScale(out stScale: TPoint2): DGLE_RESULT; stdcall;
function GetColorMix(out stColor: TColor4): DGLE_RESULT; stdcall;
function GetBlendMode(out eMode: E_BLENDING_EFFECT): DGLE_RESULT; stdcall;
function GetVerticesOffsets(out stCoords1, stCoords2, stCoords3, stCoords4: TPoint2): DGLE_RESULT; stdcall;
function GetVerticesColors(out stColor1, stColor2, stColor3, stColor4: TColor4): DGLE_RESULT; stdcall;
end;
//Render3D interface//
IRender3D = interface(IDGLE_Base)
['{5275F43A-4FF9-48b2-B88E-B2F842461AB3}']
function SetPerspective(fFovAngle, fZNear, fZFar: Single): DGLE_RESULT; stdcall;
function GetPerspective(out fFovAngle, fZNear, fZFar: Single): DGLE_RESULT; stdcall;
function SetColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function GetColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function BindTexture(pTex: ITexture; uiTextureLayer: Cardinal): DGLE_RESULT; stdcall;
function GetTexture(out prTex: ITexture; uiTextureLayer: Cardinal): DGLE_RESULT; stdcall;
function GetMaxLightsPerPassCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function UpdateLight(pLight: ILight): DGLE_RESULT; stdcall;
function BindMaterial(pMat: IMaterial): DGLE_RESULT; stdcall;
function GetMaterial(out prMat: IMaterial): DGLE_RESULT; stdcall;
function ToggleBlending(bEnabled: Boolean): DGLE_RESULT; stdcall;
function IsBlendingEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function SetBlendMode(eMode: E_BLENDING_EFFECT = BE_NORMAL): DGLE_RESULT; stdcall;
function GetBlendMode(out eMode: E_BLENDING_EFFECT): DGLE_RESULT; stdcall;
function ToggleAlphaTest(bEnabled: Boolean): DGLE_RESULT; stdcall;
function SetAlphaTreshold(fTreshold: Single): DGLE_RESULT; stdcall;
function IsAlphaTestEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function GetAlphaTreshold(out fTreshold: Single): DGLE_RESULT; stdcall;
function ClearDepthBuffer(): DGLE_RESULT; stdcall;
function ToggleDepthTest(bEnabled: Boolean): DGLE_RESULT; stdcall;
function IsDepthTestEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function ToggleBackfaceCulling(bEnabled: Boolean): DGLE_RESULT; stdcall;
function IsBackfaceCullingEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function Draw(const stDrawDesc: TDrawDataDesc; eMode: E_CORE_RENDERER_DRAW_MODE; uiCount: Cardinal): DGLE_RESULT; stdcall;
function DrawBuffer(pBuffer: ICoreGeometryBuffer): DGLE_RESULT; stdcall;
function ToggleFog(bEnabled: Boolean): DGLE_RESULT; stdcall;
function SetLinearFogBounds(fStart, fEnd: Single): DGLE_RESULT; stdcall;
function SetFogColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function SetFogDensity(fDensity: Single): DGLE_RESULT; stdcall;
function IsFogEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function GetLinearFogBounds(out fStart, fEnd: Single): DGLE_RESULT; stdcall;
function GetFogColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function GetFogDensity(out fDensity: Single): DGLE_RESULT; stdcall;
function SetMatrix(const stMatrix: TMatrix4x4): DGLE_RESULT; stdcall;
function MultMatrix(const stMatrix: TMatrix4x4): DGLE_RESULT; stdcall;
function PushMatrix(): DGLE_RESULT; stdcall;
function PopMatrix(): DGLE_RESULT; stdcall;
function GetMatrix(out stMatrix: TMatrix4x4): DGLE_RESULT; stdcall;
function DrawAxes(fSize: Single = 1.0; bNoDepthTest: Boolean = False): DGLE_RESULT; stdcall;
function ResetStates(): DGLE_RESULT; stdcall;
function PushStates(): DGLE_RESULT; stdcall;
function PopStates(): DGLE_RESULT; stdcall;
function GetPoint3(const stPointOnScreen: TPoint2; out stResultPoint: TPoint3; eFlag: E_GET_POINT3_MODE = GP3M_FROM_DEPTH_BUFFER): DGLE_RESULT; stdcall;
function GetPoint2(const stPoint: TPoint3; out stResultPointOnScreen: TPoint2): DGLE_RESULT; stdcall;
function SetupFrustum(): DGLE_RESULT; stdcall;
function CullPoint(const stCoords: TPoint3; out bCull: Boolean): DGLE_RESULT; stdcall;
function CullSphere(const stCenter: TPoint3; fRadius: Single; out bCull: Boolean): DGLE_RESULT; stdcall;
function CullBox(const stCenterCoords, stExtents: TVector3; out bCull: Boolean): DGLE_RESULT; stdcall;
function ToggleLighting(bEnabled: Boolean): DGLE_RESULT; stdcall;
function SetGlobalAmbientLighting(const stColor: TColor4): DGLE_RESULT; stdcall;
function IsLightingEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function GetGlobalAmbientLighting(out stColor: TColor4): DGLE_RESULT; stdcall;
end;
//Light interface//
ILight = interface(IEngineBaseObject)
['{EB73AC84-A465-4554-994D-8BED29744C9D}']
function SetEnabled(bEnabled: Boolean): DGLE_RESULT; stdcall;
function SetColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function SetPosition(const stPos: TPoint3): DGLE_RESULT; stdcall;
function SetDirection(const stDir: TVector3): DGLE_RESULT; stdcall;
function SetRange(fRange: Single): DGLE_RESULT; stdcall;
function SetIntensity(fIntensity: Single): DGLE_RESULT; stdcall;
function SetSpotAngle(fAngle: Single): DGLE_RESULT; stdcall;
function SetType(eType: E_LIGHT_TYPE): DGLE_RESULT; stdcall;
function GetEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall;
function GetColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function GetPosition(out stPos: TPoint3): DGLE_RESULT; stdcall;
function GetDirection(out stDir: TVector3): DGLE_RESULT; stdcall;
function GetRange(out fRange: Single): DGLE_RESULT; stdcall;
function GetIntensity(out fIntensity: Single): DGLE_RESULT; stdcall;
function GetSpotAngle(out fAngle: Single): DGLE_RESULT; stdcall;
function GetType(out eType: E_LIGHT_TYPE): DGLE_RESULT; stdcall;
function Update(): DGLE_RESULT; stdcall;
end;
//Texture interface//
ITexture = interface(IEngineBaseObject)
['{85BDDBC2-F126-4cae-946D-7D6B079E5CCE}']
function GetDimensions(out uiWidth, uiHeight: Cardinal): DGLE_RESULT; stdcall;
function SetFrameSize(uiFrameWidth, uiFrameHeight: Cardinal): DGLE_RESULT; stdcall;
function GetFrameSize(out uiFrameWidth, uiFrameHeight: Cardinal): DGLE_RESULT; stdcall;
function FramesCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function GetCoreTexture(out prCoreTex: ICoreTexture): DGLE_RESULT; stdcall;
function Draw2DSimple(iX, iY: Integer; uiFrameIndex: Cardinal = 0): DGLE_RESULT; stdcall;
function Draw2D(iX, iY: Integer; uiWidth, uiHeight: Cardinal; fAngle: Single = 0.0; uiFrameIndex: Cardinal = 0): DGLE_RESULT; stdcall;
function Draw3D(uiFrameIndex: Cardinal = 0): DGLE_RESULT; stdcall;
function Bind(uiTextureLayer: Cardinal = 0): DGLE_RESULT; stdcall;
end;
//Material interface//
IMaterial = interface(IEngineBaseObject)
['{B6506749-BB41-423d-B6C0-982081EF63F9}']
function SetDiffuseColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function SetSpecularColor(const stColor: TColor4): DGLE_RESULT; stdcall;
function SetShininess(fShininess: Single): DGLE_RESULT; stdcall;
function SetDiffuseTexture(pTexture: ITexture): DGLE_RESULT; stdcall;
function SetBlending(bEnabled: Boolean; eMode: E_BLENDING_EFFECT): DGLE_RESULT; stdcall;
function SetAlphaTest(bEnabled: Boolean; fTreshold: Single): DGLE_RESULT; stdcall;
function GetDiffuseColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function GetSpecularColor(out stColor: TColor4): DGLE_RESULT; stdcall;
function GetShininess(out fShininess: Single): DGLE_RESULT; stdcall;
function GetDiffuseTexture(out prTexture: ITexture): DGLE_RESULT; stdcall;
function GetBlending(out bEnabled: Boolean; out eMode: E_BLENDING_EFFECT): DGLE_RESULT; stdcall;
function GetAlphaTest(out bEnabled: Boolean; out fTreshold: Single): DGLE_RESULT; stdcall;
function Bind(): DGLE_RESULT; stdcall;
end;
//BitmapFont interface//
IBitmapFont = interface(IEngineBaseObject)
['{0B03E8D7-23A3-4c79-9E82-5BC6E50E1EBA}']
function GetTexture(out prTexture: ITexture): DGLE_RESULT; stdcall;
function SetScale(fScale: Single): DGLE_RESULT; stdcall;
function GetScale(out fScale: Single): DGLE_RESULT; stdcall;
function GetTextDimensions(const pcTxt: PAnsiChar; out uiWidth, uiHeight: Cardinal): DGLE_RESULT; stdcall;
function Draw2DSimple(iX, iY: Integer; const pcTxt: PAnsiChar; const stColor: TColor4): DGLE_RESULT; stdcall;
function Draw2D(fX, fY: Single; const pcTxt: PAnsiChar; const stColor: TColor4; fAngle: Single = 0; bVerticesColors: Boolean = False): DGLE_RESULT; stdcall;
function Draw3D(const pcTxt: PAnsiChar): DGLE_RESULT; stdcall;
end;
//3D Objects interfaces//
//Mesh interface//
IMesh = interface(IEngineBaseObject)
['{85E360A8-07B3-4f22-AA29-07C7FC7C6893}']
function Draw(): DGLE_RESULT; stdcall;
function GetCenter(out stCenter: TPoint3): DGLE_RESULT; stdcall;
function GetExtents(out stExtents: TVector3): DGLE_RESULT; stdcall;
function GetTrianglesCount(out uiCnt: Cardinal): DGLE_RESULT; stdcall;
function GetGeometryBuffer(out prBuffer:ICoreGeometryBuffer): DGLE_RESULT; stdcall;
function SetGeometryBuffer(pBuffer: ICoreGeometryBuffer; bFreeCurrentBuffer: Boolean): DGLE_RESULT; stdcall;
function RecalculateNormals(bInvert: Boolean = False): DGLE_RESULT; stdcall;
function RecalculateTangentSpace(): DGLE_RESULT; stdcall;
function RecalculateBounds(): DGLE_RESULT; stdcall;
function TransformVertices(const stTransMatrix: TMatrix4x4): DGLE_RESULT; stdcall;
function Optimize(): DGLE_RESULT; stdcall;
function GetOwner(out prModel: IModel): DGLE_RESULT; stdcall;
function SetOwner(pModel: IModel): DGLE_RESULT; stdcall;
end;
//Multi mesh interface//
IModel = interface(IEngineBaseObject)
['{6107C296-FC07-48d1-B6A7-F88CC2DAE897}']
function Draw(): DGLE_RESULT; stdcall;
function DrawMesh(uiMeshIdx: Cardinal): DGLE_RESULT; stdcall;
function GetCenter(out stCenter: TPoint3): DGLE_RESULT; stdcall;
function GetExtents(out stExtents: TVector3): DGLE_RESULT; stdcall;
function MeshesCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function GetMesh(uiMeshIdx: Cardinal; out prMesh: IMesh): DGLE_RESULT; stdcall;
function SetModelMaterial(pMaterial: IMaterial): DGLE_RESULT; stdcall;
function GetModelMaterial(out prMaterial: IMaterial): DGLE_RESULT; stdcall;
function SetMeshMaterial(uiMeshIdx: Cardinal; pMaterial: IMaterial): DGLE_RESULT; stdcall;
function GetMeshMaterial(uiMeshIdx: Cardinal; out prMaterial: IMaterial): DGLE_RESULT; stdcall;
function AddMesh(pMesh: IMesh): DGLE_RESULT; stdcall;
function RemoveMesh(pMesh: IMesh): DGLE_RESULT; stdcall;
function ReplaceMesh(uiMeshIdx: Cardinal; pMesh: IMesh): DGLE_RESULT; stdcall;
end;
//Input Subsystem//
IInput = interface(IEngineSubSystem)
['{64DAAF7F-F92C-425f-8B92-3BE40D8C6666}']
function Configure(eFlags: {E_INPUT_CONFIGURATION_FLAGS}Integer = ICF_DEFAULT): DGLE_RESULT; stdcall;
function GetMouseStates(out stMStates: TMouseStates): DGLE_RESULT; stdcall;
function GetKey(eKeyCode: E_KEYBOARD_KEY_CODES; out bPressed: Boolean): DGLE_RESULT; stdcall;
function GetKeyName(eKeyCode: E_KEYBOARD_KEY_CODES; out cASCIICode: Char): DGLE_RESULT; stdcall;
function BeginTextInput(pcBuffer: PAnsiChar; uiBufferSize: Cardinal): DGLE_RESULT; stdcall;
function EndTextInput(): DGLE_RESULT; stdcall;
function GetJoysticksCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function GetJoystickName(uiJoyId: Cardinal; pcName: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetJoystickStates(uiJoyId: Cardinal; out stJoyStates: TJoystickStates): DGLE_RESULT; stdcall;
end;
StreamCallbackFunc = function(pParameter: Pointer; ui32DataPos: Cardinal; pBufferData: Pointer; uiBufferSize: Cardinal): DGLE_RESULT; stdcall;
//Sound SubSystem interfaces//
ISound = interface(IEngineSubSystem)
['{054C07EE-2724-42f2-AC2B-E81FCF5B4ADA}']
function SetMasterVolume(uiVolume: Cardinal): DGLE_RESULT; stdcall;
function MasterPause(bPaused: Boolean): DGLE_RESULT; stdcall;
function StopAllChannels(): DGLE_RESULT; stdcall;
function GetMaxChannelsCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function GetFreeChannelsCount(out uiCount: Cardinal): DGLE_RESULT; stdcall;
function ReleaseChannelsByData(const pData: Pointer): DGLE_RESULT; stdcall;
function ReleaseChannelsByCallback(pStreamCallback: StreamCallbackFunc): DGLE_RESULT; stdcall;
function CreateChannel(out prSndChnl: ISoundChannel; uiSamplesPerSec, uiBitsPerSample: Cardinal;
bStereo: Boolean; const pData: Pointer; ui32DataSize: Cardinal): DGLE_RESULT; stdcall; //Data not copied!
function CreateStreamableChannel(out prSndChnl: ISoundChannel; uiSamplesPerSec, uiBitsPerSample: Cardinal; bStereo: Boolean;
ui32DataSize: Cardinal; pStreamCallback: StreamCallbackFunc; pParameter: Pointer): DGLE_RESULT; stdcall;
end;
// Sound Sample Interface
ISoundChannel = interface(IDGLE_Base)
['{DE6F7CDD-8262-445c-8D20-68E3324D99A6}']
function Play(bLooped: Boolean): DGLE_RESULT; stdcall;
function Pause(): DGLE_RESULT; stdcall;
function Stop(): DGLE_RESULT; stdcall;
function IsPlaying(out bIsPlaying: Boolean): DGLE_RESULT; stdcall;
function SetVolume(uiVolume: Cardinal): DGLE_RESULT; stdcall; //from 0 to 100
function GetVolume(out uiVolume: Cardinal): DGLE_RESULT; stdcall;
function SetPan(iPan: Integer): DGLE_RESULT; stdcall; //from -100 to 100
function GetPan(out iPan: Integer): DGLE_RESULT; stdcall;
function SetSpeed(uiSpeed: Cardinal): DGLE_RESULT; stdcall;//in percents
function GetSpeed(out uiSpeed: Cardinal): DGLE_RESULT; stdcall;
function SetCurrentPosition(uiPos: Cardinal): DGLE_RESULT; stdcall;
function GetCurrentPosition(out uiPos: Cardinal): DGLE_RESULT; stdcall;
function GetLength(out uiLength: Cardinal): DGLE_RESULT; stdcall;
function IsStreamable(out bStreamable: Boolean): DGLE_RESULT; stdcall;
function Unaquire(): DGLE_RESULT; stdcall;
end;
//SoundSample interface//
ISoundSample = interface(IEngineBaseObject)
['{30DD8C94-D3FA-40cf-9C49-649211424919}']
function Play(): DGLE_RESULT; stdcall;
function PlayEx(out pSndChnl: ISoundChannel; eFlags: {E_SOUND_SAMPLE_PARAMS}Integer = SSP_NONE): DGLE_RESULT; stdcall; //pSndChnl must be checked on nul
end;
//Music interface//
IMusic = interface(IEngineBaseObject)
['{81F1E67B-3FEB-4ab1-9AD2-D27C4E662164}']
function Play(bLooped : Boolean = True): DGLE_RESULT; stdcall;
function Pause(bPaused : Boolean): DGLE_RESULT; stdcall;
function Stop(): DGLE_RESULT; stdcall;
function IsPlaying(out bIsPlaying : Boolean): DGLE_RESULT; stdcall;
function SetVolume(uiVolume : Cardinal): DGLE_RESULT; stdcall;
function GetVolume(out uiVolume : Cardinal): DGLE_RESULT; stdcall;
function SetCurrentPosition(uiPos : Cardinal): DGLE_RESULT; stdcall;
function GetCurrentPosition(out uiPos : Cardinal): DGLE_RESULT; stdcall;
function GetLength(out uiLength : Cardinal): DGLE_RESULT; stdcall;
end;
//FileSystem Subsystem//
IMainFileSystem = interface(IEngineSubSystem)
['{4850286F-4770-4bcf-A90A-33D7BE41E686}']
function LoadFile(const pcFileName: PAnsiChar; out prFile: IFile): DGLE_RESULT; stdcall;// c:\data.zip|img.jpg
function FreeFile(var prFile: IFile): DGLE_RESULT; stdcall;
function GetVirtualFileSystem(const pcVFSExtension: PAnsiChar{NULL to get HDD file system}; out prVFS: IFileSystem): DGLE_RESULT; stdcall;
function RegisterVirtualFileSystem(const pcVFSExtension: PAnsiChar; const pcDescription: PAnsiChar; pVFS: IFileSystem; pDeleteCallback: TFSDelProcedure; pParameter: Pointer = nil): DGLE_RESULT; stdcall;
function UnregisterVirtualFileSystem(const pcVFSExtension: PAnsiChar): DGLE_RESULT; stdcall;
function GetRegisteredVirtualFileSystems(pcTxt: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetVirtualFileSystemDescription(const pcVFSExtension: PAnsiChar; pcTxt: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
end;
//File interface//
IFile = interface(IDGLE_Base)
['{AE6E8AE7-3E5B-4bc4-A512-42E1CF1DF005}']
function Read(pBuffer: Pointer; uiCount: Cardinal; out uiRead: Cardinal): DGLE_RESULT; stdcall;
function Write(const pBuffer: Pointer; uiCount: Cardinal; out uiWritten: Cardinal): DGLE_RESULT; stdcall;
function Seek(ui32Offset: Cardinal; eWay: E_FILE_SYSTEM_SEEK_FLAG; out ui32Position: Cardinal): DGLE_RESULT; stdcall;
function GetSize(out ui32Size: Cardinal): DGLE_RESULT; stdcall;
function IsOpen(out bOpened: Boolean): DGLE_RESULT; stdcall;
function GetName(pcName: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function GetPath(pcPath: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function Free(): DGLE_RESULT; stdcall; // Never use this use IMainFileSystem.FreeFile instead!
end;
//FileIterator interface//
IFileIterator = interface(IDGLE_Base)
['{5D73F249-0E74-4cc5-9646-270CB1E22750}']
function FileName(pcName: PAnsiChar; out uiCharsCount: Cardinal): DGLE_RESULT; stdcall;
function Next(): DGLE_RESULT; stdcall;
function Free(): DGLE_RESULT; stdcall;
end;
//FileSystem interface//
IFileSystem = interface(IDGLE_Base)
['{2DAE578E-9636-4fae-BABB-7D835EEA7518}']
function OpenFile(const pcName: PAnsiChar; eFlags: {E_FILE_SYSTEM_OPEN_FLAGS}Integer; out prFile: IFile): DGLE_RESULT; stdcall;
function DeleteFile(const pcName: PAnsiChar): DGLE_RESULT; stdcall;
function FileExists(const pcName: PAnsiChar; out bExists: Boolean): DGLE_RESULT; stdcall;
function Find(const pcMask: PAnsiChar; eFlags: E_FIND_FLAGS; out prIterator: IFileIterator): DGLE_RESULT; stdcall;
end;
const
//E_GET_ENGINE_FLAGS
GEF_DEFAULT = $00000000;
GEF_FORCE_SINGLE_THREAD = $00000001;
GEF_FORCE_NO_LOG_FILE = $00000002;
GEF_FORCE_QUIT = $00000004;
function CreateEngine(out pEngineCore: IEngineCore; eFlags: {E_GET_ENGINE_FLAGS}Integer = GEF_DEFAULT): Boolean;
function GetEngine(pcDllFileName: AnsiString; out pEngineCore :IEngineCore; eFlags: {E_GET_ENGINE_FLAGS}Integer = GEF_DEFAULT): Boolean;
function FreeEngine(pEngineCore: IEngineCore = nil; bFreeDLL: Boolean = true): Boolean;
implementation
uses
Windows;
type
TCreateEngineFunc = Function(out pEngineCore: IEngineCore; eFlags: {E_GET_ENGINE_FLAGS}Integer; ubtSDKVer: byte): Boolean; stdcall;
TFreeEngineFunc = Function(pEngineCore: IEngineCore): Boolean; stdcall;
var
hServer : THandle = 0;
pCreateEngine : TCreateEngineFunc;
pFreeEngine : TFreeEngineFunc;
function CreateEngine(out pEngineCore: IEngineCore; eFlags: {E_GET_ENGINE_FLAGS}Integer = GEF_DEFAULT): Boolean;
begin
Result := false;
if @pCreateEngine = nil then
Exit;
Result := pCreateEngine(pEngineCore, eFlags, _DGLE_SDK_VER_);
end;
function FreeEngine(pEngineCore: IEngineCore = nil; bFreeDLL: Boolean = true): Boolean;
begin
if pEngineCore <> nil then
pFreeEngine(pEngineCore);
if bFreeDLL and(hServer <> 0) then
begin
FreeLibrary(hServer);
hServer := 0;
pCreateEngine := nil;
pFreeEngine := nil;
end;
Result := true;
end;
function GetEngine(pcDllFileName: AnsiString; out pEngineCore: IEngineCore; eFlags: {E_GET_ENGINE_FLAGS}Integer = GEF_DEFAULT): Boolean;
function FunctionUnassigned(pf: PPointer): Boolean;
begin
Result := pf{$IFDEF FPC_OBJFPC}^{$ENDIF} = nil;
end;
begin
Result := false;
if hServer = 0 then
begin
pEngineCore := nil;
if hServer = 0 then
begin
hServer := LoadLibraryA(PAnsiChar(pcDllFileName));
if hServer = 0 then
Exit;
end;
if FunctionUnassigned(@pCreateEngine) and FunctionUnassigned(@pFreeEngine) then
begin
pCreateEngine := TCreateEngineFunc(GetProcAddress(hServer,'CreateEngine'));
pFreeEngine := TFreeEngineFunc(GetProcAddress(hServer,'FreeEngine'));
if FunctionUnassigned(@pCreateEngine) or FunctionUnassigned(@pFreeEngine) then
begin
FreeLibrary(hServer);
hServer := 0;
end;
end;
end;
if hServer <> 0 then
Result := CreateEngine(pEngineCore, eFlags);
end;
begin
Set8087CW($133F);
IsMultiThread := True;
end.
|
{ ***************************************************************************
Copyright (c) 2015-2018 Kike Pérez
Unit : Quick.JSONRecord
Description : Serializable class
Author : Kike Pérez
Version : 1.2
Created : 05/05/2018
Modified : 06/11/2018
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
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 Quick.JSONRecord;
{$i QuickLib.inc}
interface
uses
Classes,
Quick.Json.Serializer,
Quick.AutoMapper;
type
IJsonable = interface
['{AF71F59C-89A5-4BFB-8227-0CC3068B7671}']
procedure FromJson(const aJson : string);
procedure LoadFromFile(const aJsonFilename : string);
function ToJson(aIdent : Boolean = False) : string;
procedure SaveToFile(const aJsonFilename : string; aIndent : Boolean = True);
procedure MapTo(aTgtObj : TObject);
procedure MapFrom(aSrcObj : TObject);
end;
TJsonRecord = class(TInterfacedObject,IJsonable)
public
constructor CreateFromJson(const aJson : string);
constructor CreateFromFile(const aJsonFilename : string);
procedure LoadFromFile(const aJsonFilename : string);
procedure FromJson(const aJson : string);
function ToJson(aIndent : Boolean = False) : string;
procedure SaveToFile(const aJsonFilename : string; aIndent : Boolean = True);
function Map<T : class, constructor> : T;
procedure MapTo(aTgtObj : TObject);
procedure MapFrom(aSrcObj : TObject);
function Clone : TObject; virtual;
end;
implementation
{ TJsonRecord }
constructor TJsonRecord.CreateFromJson(const aJson: string);
var
serializer : TJsonSerializer;
begin
//inherited Create;
serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty);
try
serializer.JsonToObject(Self,aJson);
finally
serializer.Free;
end;
end;
procedure TJsonRecord.FromJson(const aJson: string);
var
serializer : TJsonSerializer;
begin
serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty);
try
serializer.JsonToObject(Self,aJson);
finally
serializer.Free;
end;
end;
procedure TJsonRecord.LoadFromFile(const aJsonFilename: string);
var
json : TStringList;
begin
json := TStringList.Create;
try
json.LoadFromFile(aJsonFilename);
Self.FromJson(json.Text);
finally
json.Free;
end;
end;
constructor TJsonRecord.CreateFromFile(const aJsonFilename : string);
var
json : TStringList;
begin
json := TStringList.Create;
try
json.LoadFromFile(aJsonFilename);
CreateFromJson(json.Text);
finally
json.Free;
end;
end;
procedure TJsonRecord.SaveToFile(const aJsonFilename : string; aIndent : Boolean = True);
var
json : TStringList;
begin
json := TStringList.Create;
try
json.Text := Self.ToJson(aIndent);
json.SaveToFile(aJsonFilename);
finally
json.Free;
end;
end;
function TJsonRecord.Map<T> : T;
begin
Result := TMapper<T>.Map(Self);
end;
procedure TJsonRecord.MapFrom(aSrcObj: TObject);
begin
TObjMapper.Map(aSrcObj,Self);
end;
procedure TJsonRecord.MapTo(aTgtObj: TObject);
begin
TObjMapper.Map(Self,aTgtObj);
end;
function TJsonRecord.ToJson(aIndent : Boolean = False) : string;
var
serializer : TJsonSerializer;
begin
serializer := TJsonSerializer.Create(TSerializeLevel.slPublishedProperty);
try
Result := serializer.ObjectToJson(Self,aIndent);
finally
serializer.Free;
end;
end;
function TJsonRecord.Clone : TObject;
begin
Result := Self.ClassType.Create;
TObjMapper.Map(Self,Result);
end;
end.
|
unit Accounts;
interface
uses
MetaInstances, Classes, Collection, Persistent, BackupInterfaces, CacheAgent, Plotter, Languages;
const
tidClassFamily_Accounts = 'Accounts';
type
TMoney = currency;
TAccountId = integer;
const
MaxAccounts = 1000;
type
CAccount = class of TAccount;
TMetaAccount =
class( TMetaInstance )
public
constructor Create( anAccId, aMasterAccId : TAccountId; aName, aDesc : string; anAccountClass : CAccount );
destructor Destroy; override;
private
fAccId : TAccountId;
fAccountClass : CAccount;
fMasterAccount : TMetaAccount;
fSubAccounts : TStringList;
fName : string;
fDesc : string;
fName_MLS : TMultiString;
fDesc_MLS : TMultiString;
fTaxable : boolean;
fTaxAccount : boolean;
fRankeable : boolean;
public
property AccId : TAccountId read fAccId;
property MasterAccount : TMetaAccount read fMasterAccount;
property SubAccounts : TStringList read fSubAccounts;
//property Name : string read fName;
//property Desc : string read fDesc;
property Name_MLS : TMultiString read fName_MLS;
property Desc_MLS : TMultiString read fDesc_MLS;
property Taxable : boolean read fTaxable write fTaxable;
property TaxAccount : boolean read fTaxAccount write fTaxAccount;
property Rankeable : boolean read fRankeable write fRankeable;
public
procedure RetrieveTexts( Container : TDictionary ); override;
procedure StoreTexts ( Container : TDictionary ); override;
end;
TAccount =
class( TPersistent )
protected
constructor Create( aMetaAccount : TMetaAccount; aSuperAccount : TAccount ); virtual;
public
destructor Destroy; override;
private
fMetaAccount : TMetaAccount;
fValue : TMoney;
fSecValue : TMoney;
fSuperAccount : TAccount;
fSubAccounts : TCollection;
fHistory : TPlotter;
fModified : boolean;
private
procedure SetValue( aValue : TMoney );
public
property MetaAccount : TMetaAccount read fMetaAccount;
property Value : TMoney read fValue write SetValue;
property SecValue : TMoney read fSecValue write fSecValue;
property SuperAccount : TAccount read fSuperAccount;
property SubAccounts : TCollection read fSubAccounts;
property Modified : boolean read fModified;
property History : TPlotter read fHistory;
protected
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
protected
procedure EndOfPeriod; virtual;
procedure Assign( Account : TAccount ); virtual;
end;
TAccountArray = array[0..MaxAccounts] of TAccount;
TAccountingSystem =
class( TPersistent )
public
constructor Create;
destructor Destroy; override;
private
fMasterAccount : TAccount;
fAccountArray : TAccountArray;
public
property MasterAccount : TAccount read fMasterAccount;
property AccountArray : TAccountArray read fAccountArray;
public
procedure StoreToCache( Cache : TObjectCache );
protected
procedure LoadFromBackup( Reader : IBackupReader ); override;
procedure StoreToBackup ( Writer : IBackupWriter ); override;
private
procedure InitAccountArray( Account : TAccount );
function InstantiateAccount( MetaAccountId : string; SuperAccount : TAccount ) : TAccount;
function GetAccount( Id : TAccountId; Accounts : TCollection ) : TAccount;
procedure CopyAccounts( Account : TAccount; Accounts : TCollection );
procedure CollectAccounts( Account : TAccount; Collection : TCollection );
public
procedure EndOfPeriod( ResetTaxes : boolean ); virtual;
procedure Reset;
procedure Check;
end;
procedure RegisterBackup;
implementation
uses
SysUtils, ClassStorage, BasicAccounts, Logs, Kernel;
// TMetaAccount
constructor TMetaAccount.Create( anAccId, aMasterAccId : TAccountId; aName, aDesc : string; anAccountClass : CAccount );
begin
inherited Create( IntToStr(anAccId) );
fAccId := anAccId;
fAccountClass := anAccountClass;
fName := aName;
fDesc := aDesc;
fSubAccounts := TStringList.Create;
if aMasterAccId <> accIdx_None
then
begin
fMasterAccount := TMetaAccount(TheClassStorage.ClassById[tidClassFamily_Accounts, IntToStr(aMasterAccId)]);
fMasterAccount.fSubAccounts.Add( Id );
end;
fName_MLS := TMultiString.Create;
fDesc_MLS := TMultiString.Create;
end;
destructor TMetaAccount.Destroy;
begin
fSubAccounts.Free;
inherited;
end;
procedure TMetaAccount.RetrieveTexts( Container : TDictionary );
begin
inherited;
if fName_MLS = nil
then fName_MLS := TMultiString.Create;
if fDesc_MLS = nil
then fDesc_MLS := TMultiString.Create;
fName_MLS.Values[Container.LangId] := Container.Values[Family + '.' + Id + '.' + 'Name'];
fDesc_MLS.Values[Container.LangId] := Container.Values[Family + '.' + Id + '.' + 'Desc'];
end;
procedure TMetaAccount.StoreTexts( Container : TDictionary );
begin
inherited;
if (fName_MLS = nil) or (fName_MLS.Values[Container.LangId] = '')
then Container.Values[Family + '.' + Id + '.' + 'Name'] := fName;
if (fDesc_MLS = nil) or (fDesc_MLS.Values[Container.LangId] = '')
then Container.Values[Family + '.' + Id + '.' + 'Desc'] := fDesc;
end;
// TAccount
constructor TAccount.Create( aMetaAccount : TMetaAccount; aSuperAccount : TAccount );
begin
inherited Create;
if SuperAccount <> self
then
begin
fMetaAccount := aMetaAccount;
fSuperAccount := aSuperAccount;
fSubAccounts := TCollection.Create( 0, rkBelonguer );
fHistory := TPlotter.Create;
if fSuperAccount <> nil
then fSuperAccount.SubAccounts.Insert( self );
end
//else raise Exception.Create( 'Invalid SuperAccount for ' + MetaAccount.Name );
end;
destructor TAccount.Destroy;
begin
try
Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName );
except
end;
fSubAccounts.Free;
inherited;
end;
procedure TAccount.SetValue( aValue : TMoney );
begin
if SuperAccount <> nil
then SuperAccount.Value := SuperAccount.Value - fValue + aValue;
fValue := aValue;
fModified := true;
end;
procedure TAccount.LoadFromBackup( Reader : IBackupReader );
var
MetaAccountId : string;
begin
inherited;
MetaAccountId := Reader.ReadString( 'MetaAccountId', '' );
try
fMetaAccount := TMetaAccount(TheClassStorage.ClassById[tidClassFamily_Accounts, MetaAccountId]);
except
fMetaAccount := nil;
end;
Reader.ReadObject( 'History', fHistory, nil );
if fHistory = nil
then fHistory := TPlotter.Create;
fModified := Reader.ReadBoolean( 'Modified', false );
fValue := Reader.ReadCurrency( 'Value', 0 );
end;
procedure TAccount.StoreToBackup( Writer : IBackupWriter );
begin
inherited;
Writer.WriteString( 'MetaAccountId', fMetaAccount.Id );
Writer.WriteObject( 'History', fHistory );
Writer.WriteBoolean( 'Modified', fModified );
Writer.WriteCurrency( 'Value', fValue );
end;
procedure TAccount.EndOfPeriod;
var
OldValue : TMoney;
begin
OldValue := fValue;
fValue := 0;
fModified := false;
fSecValue := 0;
try
if fHistory <> nil
then fHistory.Plot( 0, round(OldValue/1000), round(OldValue/1000) );
except
end;
end;
procedure TAccount.Assign( Account : TAccount );
begin
fValue := Account.Value;
fSecValue := Account.SecValue;
if fHistory <> nil
then fHistory.Assign( Account.fHistory );
fModified := Account.Modified;
end;
// TAccountingSystem
constructor TAccountingSystem.Create;
begin
inherited Create;
fillchar( fAccountArray, sizeof(fAccountArray), 0 );
fMasterAccount := InstantiateAccount( IntToStr(accIdx_Master), nil );
InitAccountArray( fMasterAccount );
end;
destructor TAccountingSystem.Destroy;
begin
fMasterAccount.Free;
inherited;
end;
procedure TAccountingSystem.StoreToCache( Cache : TObjectCache );
var
count : integer;
procedure StoreAccount( Account : TAccount; level : integer );
var
i : integer;
begin
Cache.WriteString( 'AccountId' + IntToStr(count), Account.MetaAccount.Id );
//Cache.WriteString( 'AccountName' + IntToStr(count), Account.MetaAccount.Name );
StoreMultiStringToCache( 'AccountName' + IntToStr(count) + '.', Account.MetaAccount.Name_MLS, Cache );
Cache.WriteCurrency( 'AccountValue' + IntToStr(count), Account.Value );
Cache.WriteCurrency( 'AccountSecValue' + IntToStr(count), Account.SecValue );
Cache.WriteInteger( 'AccountLevel' + IntToStr(count), level );
Cache.WriteBoolean( 'AccountIsTax' + IntToStr(count), Account.MetaAccount.TaxAccount );
Cache.WriteString( 'AccountHistory' + IntToStr(count), Account.History.Serialize );
inc( count );
for i := 0 to pred(Account.SubAccounts.Count) do
if TAccount(Account.SubAccounts[i]).Modified
then StoreAccount( TAccount(Account.SubAccounts[i]), succ(level) );
end;
begin
count := 0;
StoreAccount( fMasterAccount, 0 );
Cache.WriteInteger( 'AccountCount', count );
end;
procedure TAccountingSystem.LoadFromBackup( Reader : IBackupReader );
var
Accounts : TCollection;
begin
inherited;
fillchar( fAccountArray, sizeof(fAccountArray), 0 );
fMasterAccount := InstantiateAccount( IntToStr(accIdx_Master), nil );
InitAccountArray( fMasterAccount );
Reader.ReadLooseObject( 'Accounts', Accounts, nil );
CopyAccounts( fMasterAccount, Accounts );
Accounts.ExtractAll;
Accounts.Free;
end;
procedure TAccountingSystem.StoreToBackup( Writer : IBackupWriter );
var
Accounts : TCollection;
begin
inherited;
//Check; >> ??
Accounts := TCollection.Create( 0, rkBelonguer );
try
CollectAccounts( fMasterAccount, Accounts );
Writer.WriteLooseObject( 'Accounts', Accounts );
finally
Accounts.ExtractAll;
Accounts.Free;
end;
end;
procedure TAccountingSystem.InitAccountArray( Account : TAccount );
var
i : integer;
begin
if Account.MetaAccount.AccId < MaxAccounts
then fAccountArray[Account.MetaAccount.AccId] := Account;
for i := 0 to pred(Account.SubAccounts.Count) do
InitAccountArray( TAccount(Account.SubAccounts[i]) );
end;
function TAccountingSystem.InstantiateAccount( MetaAccountId : string; SuperAccount : TAccount ) : TAccount;
var
MetaAccount : TMetaAccount;
i : integer;
begin
MetaAccount := TMetaAccount(TheClassStorage.ClassById[tidClassFamily_Accounts, MetaAccountId]);
result := MetaAccount.fAccountClass.Create( MetaAccount, SuperAccount );
for i := 0 to pred(MetaAccount.SubAccounts.Count) do
InstantiateAccount( MetaAccount.SubAccounts[i], result );
end;
function TAccountingSystem.GetAccount( Id : TAccountId; Accounts : TCollection ) : TAccount;
var
i : integer;
begin
if Accounts <> nil
then
begin
i := 0;
while (i < Accounts.Count) and (TAccount(Accounts[i]).MetaAccount.AccId <> Id) do
inc( i );
if i < Accounts.Count
then result := TAccount(Accounts[i])
else result := nil;
end
else result := nil;
end;
procedure TAccountingSystem.CopyAccounts( Account : TAccount; Accounts : TCollection );
var
OldClone : TAccount;
i : integer;
begin
OldClone := GetAccount( Account.MetaAccount.AccId, Accounts );
if OldClone <> nil
then Account.Assign( OldClone );
for i := 0 to pred(Account.SubAccounts.Count) do
CopyAccounts( TAccount(Account.SubAccounts[i]), Accounts );
end;
procedure TAccountingSystem.CollectAccounts( Account : TAccount; Collection : TCollection );
var
i : integer;
begin
try
if MetaInstances.ObjectIs( TAccount.ClassName, Account )
then
begin
if Account.Value <> 0
then Collection.Insert( Account );
for i := 0 to pred(Account.SubAccounts.Count) do
CollectAccounts( TAccount(Account.SubAccounts[i]), Collection );
end
else Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Corrupted account skipped!' );
except
on E : Exception do
begin
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' Error collecting account: ' + E.Message );
Logs.Log( tidLog_Survival, TimeToStr(Now) + ' (more) Error collecting account: ' + IntToStr(Account.MetaAccount.AccId) );
raise;
end;
end;
end;
procedure TAccountingSystem.EndOfPeriod( ResetTaxes : boolean );
procedure NotifyEndOfPeriod( Account : TAccount );
var
i : integer;
begin
if not (Account.MetaAccount.TaxAccount xor ResetTaxes)
then Account.EndOfPeriod;
for i := 0 to pred(Account.SubAccounts.Count) do
NotifyEndOfPeriod( TAccount(Account.SubAccounts[i]) );
end;
begin
NotifyEndOfPeriod( fMasterAccount );
end;
procedure TAccountingSystem.Reset;
procedure ResetAccount( Account : TAccount );
var
i : integer;
begin
Account.Value := 0;
for i := 0 to pred(Account.SubAccounts.Count) do
ResetAccount( TAccount(Account.SubAccounts[i]) );
end;
procedure ResetAccountArray;
var
i : integer;
Acc : TAccount;
begin
for i := low(fAccountArray) to high(fAccountArray) do
begin
Acc := TAccount(fAccountArray[i]);
if Acc <> nil
then Acc.EndOfPeriod;
end;
end;
begin
ResetAccount( MasterAccount );
ResetAccountArray;
end;
procedure TAccountingSystem.Check;
var
Accounts : TCollection;
begin
Accounts := TCollection.Create( 0, rkUse );
try
CollectAccounts( fMasterAccount, Accounts );
fillchar( fAccountArray, sizeof(fAccountArray), 0 );
fMasterAccount := InstantiateAccount( IntToStr(accIdx_Master), nil );
InitAccountArray( fMasterAccount );
CopyAccounts( fMasterAccount, Accounts );
finally
Accounts.Free;
end;
end;
// RegisterBackup
procedure RegisterBackup;
begin
RegisterClass( TAccount );
RegisterClass( TAccountingSystem );
end;
end.
|
unit xBackupObjects;
interface
uses
SysUtils, Classes, ObjectIndex;
const
LineBreak = #13#10;
IndentInc = ' ';
EqualSign = ' = ';
BeginMark = '{';
EndMark = '}';
NilValue = 'nil';
const
chkMatch = 0;
chkNoMatch = 2;
chkFail = 3;
type
TBackupObject = class;
TBackupWriter = class;
TBackupReader = class;
TBackupObject =
class
public
constructor Create(aStream : TStream);
destructor Destroy; override;
protected
fStream : TStream;
fIndent : string;
public
procedure AddIndentation; virtual;
procedure DecIndentation; virtual;
end;
TBackupWriter =
class(TBackupObject)
private
fCurLine : string;
public
procedure WriteString(Name : string; Value : string);
procedure WriteChar(Name : string; Value : char);
procedure WriteBoolean(Name : string; Value : boolean);
procedure WriteByte(Name : string; Value : byte);
procedure WriteWord(Name : string; Value : word);
procedure WriteInteger(Name : string; Value : integer);
procedure WriteSingle(Name : string; Value : single);
procedure WriteDouble(Name : string; Value : double);
procedure WriteCurrency(Name : string; Value : double);
private
procedure _WriteObject(Name : string; Value : TObject; Loose : boolean);
public
procedure WriteObject(Name : string; Value : TObject);
procedure WriteObjectRef(Name : string; Value : TObject);
procedure WriteLooseObject(Name : string; Value : TObject);
procedure WriteMethod(Name : string; Method : TMethod);
public
procedure AddIndentation; override;
procedure DecIndentation; override;
private
procedure WriteLine(line : string);
end;
TBackupReader =
class(TBackupObject)
public
constructor Create(aStream : TStream);
destructor Destroy; override;
private
fFixups : TObjectIndex;
public
function ReadString(Name : string) : string;
function ReadChar(Name : string) : char;
function ReadBoolean(Name : string) : boolean;
function ReadByte(Name : string) : byte;
function ReadWord(Name : string) : word;
function ReadInteger(Name : string) : integer;
function ReadSingle(Name : string) : single;
function ReadDouble(Name : string) : double;
function ReadCurrency(Name : string) : double;
function ReadObject(Name : string; var O) : string; // Returns the class name
procedure ReadMethod(Name : string; var Method : TMethod);
public
procedure AddIndentation; override;
procedure DecIndentation; override;
private
function ReadProp(Name : string) : string;
end;
EInternalBackupError = class(Exception);
CBackupAgent = class of TBackupAgent;
TBackupAgent =
class
public
class procedure Register(const Classes : array of TClass);
protected
class function CreateObject(aClass : TClass) : TObject; virtual;
class procedure Write(Stream : TBackupWriter; Obj : TObject); virtual; abstract;
class procedure Read (Stream : TBackupReader; Obj : TObject); virtual; abstract;
end;
procedure RegisterClass(aClass : TClass);
function CreateBackup(Path : string) : TBackupWriter;
function OpenBackup(Path : string) : TBackupReader;
function GetBackupAgent(ClassName : string; var Agent : CBackupAgent; var ClassType : TClass) : boolean;
implementation
uses
DelphiStreamUtils, CompStringsParser; //, BackupAgentRegistry;
type
PObject = ^TObject;
const
NoIndex = -1;
const
TypeMissmathCode = 'Type missmatch error';
// External routines
procedure RegisterBackupAgent(aClass, anAgent : TClass); external 'BackupRegistry.dll';
procedure GetClassAgent(const ClassName : string; var TheAgent, TheClass : TClass); external 'BackupRegistry.dll';
// TBackupObject
constructor TBackupObject.Create(aStream : TStream);
begin
inherited Create;
fStream := aStream;
end;
destructor TBackupObject.Destroy;
begin
fStream.Free;
inherited;
end;
procedure TBackupObject.AddIndentation;
begin
fIndent := fIndent + IndentInc;
end;
procedure TBackupObject.DecIndentation;
begin
if fIndent <> ''
then SetLength(fIndent, Length(fIndent) - 2);
end;
// TBackupWriter
procedure TBackupWriter.WriteString(Name : string; Value : string);
begin
// WriteLine(Name + EqualSign + IntToStr(length(Value)) + ' ' + Value);
WriteLine(Name + EqualSign + Value);
end;
procedure TBackupWriter.WriteChar(Name : string; Value : char);
begin
WriteLine(Name + EqualSign + IntToStr(length(Value)) + ' ' + Value);
end;
procedure TBackupWriter.WriteBoolean(Name : string; Value : boolean);
begin
if Value
then WriteLine(Name + EqualSign + 'T')
else WriteLine(Name + EqualSign + 'F');
end;
procedure TBackupWriter.WriteByte(Name : string; Value : byte);
begin
WriteLine(Name + EqualSign + IntToStr(Value));
end;
procedure TBackupWriter.WriteWord(Name : string; Value : word);
begin
WriteLine(Name + EqualSign + IntToStr(Value));
end;
procedure TBackupWriter.WriteInteger(Name : string; Value : integer);
begin
WriteLine(Name + EqualSign + IntToStr(Value));
end;
procedure TBackupWriter.WriteSingle(Name : string; Value : single);
begin
WriteLine(Name + EqualSign + FloatToStr(Value));
end;
procedure TBackupWriter.WriteDouble(Name : string; Value : double);
begin
WriteLine(Name + EqualSign + FloatToStr(Value));
end;
procedure TBackupWriter.WriteCurrency(Name : string; Value : double);
begin
WriteLine(Name + EqualSign + FloatToStr(Value));
end;
procedure TBackupWriter._WriteObject(Name : string; Value : TObject; Loose : boolean);
var
BackupAgent : CBackupAgent;
TheClass : TClass;
begin
if Value = nil
then
WriteLine(Name + EqualSign + NilValue)
else
begin
if Loose
then WriteLine(Name + EqualSign + Value.ClassName)
else WriteLine(Name + EqualSign + Value.ClassName + '(' + IntToStr(integer(Value)) + ')');
AddIndentation;
try
if GetBackupAgent(Value.ClassName, BackupAgent, TheClass)
then BackupAgent.Write(Self, Value)
else raise EInternalBackupError.Create('Error class ' + Value.ClassName + ' not registered');
finally
DecIndentation;
end;
end;
end;
procedure TBackupWriter.WriteObject(Name : string; Value : TObject);
begin
_WriteObject(Name, Value, false);
end;
procedure TBackupWriter.WriteObjectRef(Name : string; Value : TObject);
begin
if Value <> nil
then WriteLine(Name + EqualSign + Value.ClassName + '(' + IntToStr(integer(Value)) + ')!')
else WriteLine(Name + EqualSign + NilValue);
end;
procedure TBackupWriter.WriteLooseObject(Name : string; Value : TObject);
begin
_WriteObject(Name, Value, true);
end;
procedure TBackupWriter.WriteMethod(Name : string; Method : TMethod);
begin
if (Method.Code <> nil) and (Method.Data <> nil)
then
with Method do
begin
WriteLine(Name + EqualSign + 'Method');
AddIndentation;
WriteObjectRef('Object', Data);
WriteLine('Code' + EqualSign + TObject(Data).MethodName(Code));
DecIndentation;
end
else WriteLine(Name + EqualSign + NilValue);
end;
procedure TBackupWriter.AddIndentation;
begin
WriteLine(BeginMark);
inherited AddIndentation;
end;
procedure TBackupWriter.DecIndentation;
begin
inherited DecIndentation;
WriteLine(EndMark);
end;
procedure TBackupWriter.WriteLine(line : string);
begin
if fIndent <> ''
then fStream.Write(fIndent[1], Length(fIndent));
if line <> ''
then fStream.Write(line[1], Length(line));
fStream.Write(LineBreak, 2);
fCurLine := '';
end;
// TBackupReader
constructor TBackupReader.Create(aStream : TStream);
begin
inherited;
fFixups := TObjectIndex.Create(1024); // >>
end;
destructor TBackupReader.Destroy;
begin
fFixups.Free;
inherited;
end;
function TBackupReader.ReadString(Name : string) : string;
begin
result := ReadProp(Name);
end;
function TBackupReader.ReadChar(Name : string) : char;
var
aux : string;
begin
aux := ReadProp(Name);
if length(aux) <> 1
then result := aux[1]
else raise EInternalBackupError.Create(TypeMissmathCode);
end;
function TBackupReader.ReadBoolean(Name : string) : boolean;
var
aux : string;
begin
aux := ReadProp(Name);
if length(aux) = 1
then result := aux[1] = 'T'
else raise EInternalBackupError.Create(TypeMissmathCode);
end;
function TBackupReader.ReadByte(Name : string) : byte;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToInt(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
function TBackupReader.ReadWord(Name : string) : word;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToInt(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
function TBackupReader.ReadInteger(Name : string) : integer;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToInt(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
function TBackupReader.ReadSingle(Name : string) : single;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToFloat(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
function TBackupReader.ReadDouble(Name : string) : double;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToFloat(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
function TBackupReader.ReadCurrency(Name : string) : double;
var
aux : string;
begin
aux := ReadProp(Name);
try
result := StrToCurr(aux);
except
raise EInternalBackupError.Create(TypeMissmathCode);
end;
end;
procedure TBackupReader.ReadMethod(Name : string; var Method : TMethod);
var
aux : string;
BackupAgent : CBackupAgent;
ClassType : TClass;
ClsName : string;
begin
aux := ReadProp(Name);
if aux <> NilValue
then
begin
AddIndentation;
ClsName := ReadObject('Object', TObject(Method.Data));
if GetBackupAgent(ClsName, BackupAgent, ClassType)
then Method.Code := ClassType.MethodAddress(ReadString('Code'))
else raise EInternalBackupError.Create('Error class "' + ClsName + '" not registered');
DecIndentation;
end
else
begin
Method.Data := nil;
Method.Code := nil;
end;
end;
function TBackupReader.ReadObject(Name : string; var O) : string;
var
Obj : TObject absolute O;
aux : string;
cls : string;
ref : integer;
p : integer;
IdxEntry : TIndexEntry;
Index : integer;
procedure UpdateFixups;
var
AuxPtr : PObject;
Index : integer;
begin
Index := fFixups.IdIndex[ref];
if Index = NoIndex
then
fFixups.AddEntry(IndexEntry(ref, Obj, true))
else
begin
// Fix anything in the fixup
IdxEntry := fFixups.Entries[Index];
AuxPtr := PObject(IdxEntry.Obj);
while AuxPtr <> nil do
begin
IdxEntry.Obj := TObject(PObject(IdxEntry.Obj)^);
AuxPtr^ := Obj;
AuxPtr := PObject(IdxEntry.Obj);
end;
IdxEntry.Obj := Obj;
IdxEntry.Flg := true;
fFixups.Entries[Index] := IdxEntry;
end;
end;
procedure DoReadObject(ClassName : string; UpdateFixup : boolean);
var
BackupAgent : CBackupAgent;
TheClass : TClass;
begin
AddIndentation;
if GetBackupAgent(ClassName, BackupAgent, TheClass)
then
begin
Obj := BackupAgent.CreateObject(TheClass);
if Obj <> nil
then
try
if UpdateFixup
then UpdateFixups;
BackupAgent.Read(Self, Obj)
except
Obj.Free;
raise;
end
else raise EInternalBackupError.Create('Error unspected incongruity')
end
else raise EInternalBackupError.Create('Error class not registered: ' + ClassName);
DecIndentation;
end;
begin
aux := ReadProp(Name);
if aux = NilValue
then
begin
Obj := nil;
result := '';
end
else
begin
p := 1;
// Read the class
cls := GetNextStringUpTo(aux, p, '(');
if cls <> ''
then
if p > length(aux)
then // No fixup is needed
DoReadObject(cls, false)
else // This object must update the fixups
begin
inc(p);
try
ref := StrToInt(GetNextStringUpTo(aux, p, ')'));
inc(p);
if p = length(aux)
then // This an object reference X=TX(121212)!
begin
Index := fFixups.IdIndex[ref];
if Index <> NoIndex
then
begin
IdxEntry := fFixups.Entries[Index];
if IdxEntry.Flg
then
Obj := IdxEntry.Obj
else
begin
// Insert the reference in the fixups
IdxEntry.Obj := TObject(@Obj);
IdxEntry.Flg := false;
Obj := IdxEntry.Obj;
fFixups.Entries[Index] := IdxEntry;
end;
end
else
begin
// Create the fixup for this object
Obj := nil;
fFixups.AddObject(ref, TObject(@Obj));
end
end
else DoReadObject(cls, true); // >> This an object, lets read it
except
raise;
end;
end
else raise EInternalBackupError.Create('No class found');
result := cls;
end;
end;
procedure TBackupReader.AddIndentation;
var
bm : string;
begin
fStream.Seek(length(fIndent), soFromCurrent);
if DelphiStreamUtils.ReadLine(fStream, bm) and (bm = BeginMark)
then inherited AddIndentation
else raise EInternalBackupError.Create('');
end;
procedure TBackupReader.DecIndentation;
var
em : string;
begin
inherited DecIndentation;
fStream.Seek(length(fIndent), soFromCurrent);
if DelphiStreamUtils.ReadLine(fStream, em) and (em = EndMark)
then else raise EInternalBackupError.Create('Remaining data to read');
end;
function TBackupReader.ReadProp(Name : string) : string;
var
aux : string;
AuxName : string;
p : integer;
begin
result := '';
fStream.Seek(length(fIndent), soFromCurrent);
if DelphiStreamUtils.ReadLine(fStream, aux)
then
begin
p := pos(EqualSign, aux);
if p <> 0
then
begin
AuxName := copy(aux, 1, p - 1);
if (Name = '') or (AuxName = Name)
then result := copy(aux, p + length(EqualSign), length(aux))
else raise EInternalBackupError.Create('');
end
else raise EInternalBackupError.Create('');
end
else raise EInternalBackupError.Create('');
end;
// TBackupAgent
class procedure TBackupAgent.Register;
var
i : integer;
begin
try
for i := low(Classes) to high(Classes) do
RegisterBackupAgent(Classes[i], Self);
except
raise EInternalBackupError.Create('Class already registered');
end;
end;
class function TBackupAgent.CreateObject(aClass : TClass) : TObject;
begin
result := aClass.Create;
end;
// Utility functions
procedure RegisterClass(aClass : TClass);
var
Agent : CBackupAgent;
aux : TClass;
Cls : TClass;
begin
Agent := nil;
aux := aClass;
while (aux <> nil) and (Agent = nil) do
begin
GetBackupAgent(aux.ClassName, Agent, Cls);
aux := aux.ClassParent;
end;
if Agent <> nil
then RegisterBackupAgent(aClass, Agent)
else raise EInternalBackupError.Create('No class for "' + aClass.ClassName + '" parent has been registered yet');
end;
function CreateBackup(Path : string) : TBackupWriter;
begin
result := TBackupWriter.Create(TFileStream.Create(Path, fmCreate));
end;
function OpenBackup(Path : string) : TBackupReader;
begin
result := TBackupReader.Create(TFileStream.Create(Path, fmOpenRead));
end;
function GetBackupAgent(ClassName : string; var Agent : CBackupAgent; var ClassType : TClass) : boolean;
begin
GetClassAgent(ClassName, TClass(Agent), ClassType);
result := (Agent <> nil) and (ClassType <> nil);
end;
end.
|
unit cmdlinecfguijson;
interface
{$mode delphi}
uses
Classes, SysUtils, cmdlinecfgui, fpjson, jsonparser;
function CmdLineUIJSONReadFile(stream: TStream; lt: TCmdLineLayoutInfo): Boolean; overload;
function CmdLineUIJSONReadFile(const FileName: String; lt: TCmdLineLayoutInfo): Boolean; overload;
procedure CmdLineCfgUIJSONLoadFilesFromDir(const Dir: String; list: TList; const Mask : string = '*.coptui');
implementation
type
{ TSectionIterator }
TSectionIterator = class(TObject)
public
lt : TCmdLineLayoutInfo;
sc : TLayoutSection;
constructor Create;
destructor Destroy; override;
procedure Iterate(Const AName : TJSONStringType; Item: TJSONData; Data: TObject; var DoContinue: Boolean);
end;
function CmdLineUIJSONReadFile(stream: TStream; lt: TCmdLineLayoutInfo): Boolean;
var
p : TJSONParser;
d : TJSONData;
core : TJSONObject;
st : TSectionIterator;
begin
Result:=False;
d:=nil;
p:=TJSONParser.Create(stream);
try
d:=p.Parse;
if d.JSONType<>jtObject then Exit;
core:=TJSONObject(d);
st:=TSectionIterator.Create;
try
st.lt:=lt;
st.sc:=lt.RootElement;
core.Iterate( st.Iterate, st)
finally
st.Free;
end;
Result:=true;
finally
d.Free;
p.Free;
end;
end;
function CmdLineUIJSONReadFile(const FileName: String; lt: TCmdLineLayoutInfo): Boolean;
var
fs : TFileStream;
begin
fs := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
Result:=CmdLineUIJSONReadFile(fs, lt);
finally
fs.Free;
end;
end;
procedure CmdLineCfgUIJSONLoadFilesFromDir(const Dir: String; list: TList; const Mask : string = '*.coptui');
var
rslt : TSearchRec;
res : Integer;
pth : string;
cfg : TCmdLineLayoutInfo;
begin
pth:=IncludeTrailingPathDelimiter(Dir);
res:=FindFirst( pth+Mask, faAnyFile, rslt);
try
while res = 0 do begin
if (rslt.Attr and faDirectory=0) and (rslt.Size>0) then begin
cfg := TCmdLineLayoutInfo.Create;
if not CmdLineUIJSONReadFile(pth+rslt.Name, cfg) then cfg.Free
else list.Add(cfg);
end;
res:=FindNext(rslt);
end;
finally
FindClose(rslt);
end;
end;
{ TSectionIterator }
constructor TSectionIterator.Create;
begin
inherited Create;
end;
destructor TSectionIterator.Destroy;
begin
inherited Destroy;
end;
procedure TSectionIterator.Iterate(const AName: TJSONStringType;
Item: TJSONData; Data: TObject; var DoContinue: Boolean);
var
l : string;
a : TJSONArray;
i : Integer;
st : TSectionIterator;
subnm : string;
begin
l:=AnsiLowerCase(AName);
if (l='switches') and (Item.JSONType=jtArray) then begin
a:=TJSONArray(Item);
for i:=0 to a.Count-1 do begin
if (a.Items[i].JSONType=jtString) then
sc.AddElement( TJSONString(a.Items[i]).AsString, letSwitch );
end;
end else if (l='display') and (Item.JSONType=jtString) then begin
sc.Display:=Item.AsString;
end else if (l='hint') and (Item.JSONType=jtString) then begin
sc.GUIHint:=Item.AsString;
end else if (item.JSONType=jtObject) then begin
// sub section
st:=TSectionIterator.Create;
try
st.sc:=Self.sc.AddElement(AName, letSection);
st.lt:=Self.lt;
TJSONObject(Item).Iterate(st.Iterate, st);
finally
st.Free;
end;
end;
end;
end.
|
unit uCadProdutos;
interface
uses System.Classes,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Dialogs,
ZAbstractConnection,
ZConnection,
ZAbstractRODataset,
ZAbstractDataset,
ZDataset,
System.SysUtils;
type
TProduto = class
private
ConexaoDB:TZConnection;
F_produtoId:Integer; //Int
F_nome:String; //VarChar
F_descricao: string;
F_Desc_Redu : string;
F_valor:Double;
F_quantidade: Double;
F_GrupoId: Integer;
F_SubGrupoId :Integer;
F_UnMedida :string;
F_Obs :string;
F_CodEan :string;
F_Marca :string;
public
constructor Create(aConexao:TZConnection);
destructor Destroy; override;
function Inserir:Boolean;
function Atualizar:Boolean;
function Apagar:Boolean;
function Selecionar(id:Integer):Boolean;
published
property codigo :Integer read F_produtoId write F_produtoId;
property nome :string read F_nome write F_nome;
property descricao :string read F_descricao write F_descricao;
property desc_Redu :string read F_desc_Redu write F_desc_Redu;
property valor :Double read F_valor write F_valor;
property quantidade :Double read F_quantidade write F_quantidade;
property GrupoId :Integer read F_GrupoId write F_GrupoId;
property SubGrupoId :Integer read F_SubGrupoId write F_SubGrupoId;
property UnMedida :string read F_UnMedida write F_UnMedida;
property Obs :String read F_Obs write F_Obs;
property CodEan :string read F_CodEan write F_CodEan;
property Marca :string read F_Marca write F_Marca;
end;
implementation
{ TCategoria }
{$region 'Constructor and Destructor'}
constructor TProduto.Create(aConexao:TZConnection);
begin
ConexaoDB:=aConexao;
end;
destructor TProduto.Destroy;
begin
inherited;
end;
{$endRegion}
{$region 'CRUD'}
function TProduto.Apagar: Boolean;
var Qry:TZQuery;
begin
if MessageDlg('Apagar o Registro: '+#13+#13+
'Código: '+IntToStr(F_produtoId)+#13+
'Descrição: '+F_nome,mtConfirmation,[mbYes, mbNo],0)=mrNo then begin
Result:=false;
abort;
end;
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('DELETE FROM produtos '+
' WHERE prod_cod=:prod_cod ');
Qry.ParamByName('prod_cod').AsInteger :=F_produtoId;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TProduto.Atualizar: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('UPDATE produtos '+
' SET prod_nome =:nome '+
' ,Prod_Descricao =:descricao '+
' ,Prod_Desc_redu =:des_Redu '+
' ,Prod_valorUnit =:ValorUnit '+
' ,Prod_qtde =:Qtde '+
' ,Prod_Grupo =:Grupo '+
' ,Prod_SubGrupo =:SubGrupo '+
' ,Prod_UnMedida =:UnMedida '+
' ,Prod_Obs =:Obs '+
' ,prod_CodEan =:CODEAN'+
' ,prod_Marca =:Marca'+
' WHERE Prod_Cod =:Prod_Cod ');
Qry.ParamByName('Prod_Cod').AsInteger :=Self.F_produtoId;
Qry.ParamByName('nome').AsString :=Self.nome;
Qry.ParamByName('descricao').AsString :=Self.F_descricao;
Qry.ParamByName('des_Redu').AsString :=Self.F_Desc_Redu;
Qry.ParamByName('ValorUnit').AsFloat :=Self.F_valor;
Qry.ParamByName('Qtde').AsFloat :=Self.F_quantidade;
Qry.ParamByName('Grupo').AsFloat :=Self.F_GrupoId;
Qry.ParamByName('SubGrupo').AsFloat :=Self.F_SubGrupoId;
Qry.ParamByName('UnMedida').AsString :=Self.F_UnMedida;
Qry.ParamByName('Obs').AsString :=Self.F_Obs;
Qry.ParamByName('CODEAN').AsString :=Self.CodEan;
Qry.ParamByName('Marca').AsString :=Self.F_Marca;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TProduto.Inserir: Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('INSERT INTO produtos (prod_nome, '+
' Prod_Descricao, '+
' Prod_Desc_Redu, '+
' Prod_valorUnit, '+
' Prod_qtde, '+
' Prod_Grupo, '+
' Prod_SubGrupo,'+
' Prod_UnMedida,'+
' Prod_Obs,'+
' Prod_CodEan,'+
' Prod_Marca) '+
' VALUES (:nome, '+
' :descricao, '+
' :des_Redu, '+
' :valor, '+
' :quantidade, '+
' :Grupo, '+
' :SubGrupo,'+
' :UnMedida,'+
' :Obs,'+
' :CODEAN,'+
' :MARCA)' );
Qry.ParamByName('nome').AsString :=Self.F_nome;
Qry.ParamByName('descricao').AsString :=Self.F_descricao;
Qry.ParamByName('des_Redu').AsString :=Self.F_Desc_Redu;
Qry.ParamByName('valor').AsFloat :=Self.F_valor;
Qry.ParamByName('quantidade').AsFloat :=Self.F_quantidade;
Qry.ParamByName('Grupo').AsInteger :=Self.F_GrupoId;
Qry.ParamByName('SubGrupo').AsInteger :=Self.F_SubGrupoId;
Qry.ParamByName('UnMedida').AsString :=Self.F_UnMedida;
Qry.ParamByName('Obs').AsString :=Self.F_Obs;
Qry.ParamByName('CODEAN').AsString :=Self.F_CODEAN;
Qry.ParamByName('Marca').AsString :=Self.F_Marca;
Try
ConexaoDB.StartTransaction;
Qry.ExecSQL;
ConexaoDB.Commit;
Except
ConexaoDB.Rollback;
Result:=false;
End;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
function TProduto.Selecionar(id: Integer): Boolean;
var Qry:TZQuery;
begin
try
Result:=true;
Qry:=TZQuery.Create(nil);
Qry.Connection:=ConexaoDB;
Qry.SQL.Clear;
Qry.SQL.Add('SELECT prod_cod,'+
' prod_CodEAN,'+
' prod_nome, '+
' prod_descricao, '+
' prod_Desc_Redu,'+
' prod_qtde, '+
' prod_Grupo, '+
' prod_SubGrupo, '+
' prod_valorUnit,'+
' prod_Marca,'+
' prod_Obs,'+
' prod_FornecedorId,'+
' prod_UnMedida'+
' FROM produtos '+
' WHERE Prod_Cod=:Prod_cod');
Qry.ParamByName('Prod_cod').AsInteger:=id;
try
Qry.Open;
self.F_CodEan := Qry.FieldByName('prod_CodEAN').AsString;
self.F_descricao := Qry.FieldByName('Prod_descricao').AsString;
Self.F_produtoId := Qry.FieldByName('Prod_Cod').AsInteger;
Self.nome := Qry.FieldByName('Prod_nome').AsString;
Self.F_descricao := Qry.FieldByName('Prod_descricao').AsString;
Self.F_Desc_Redu := Qry.FieldByName('Prod_desc_Redu').AsString;
Self.F_valor := Qry.FieldByName('Prod_ValorUnit').AsFloat;
Self.F_quantidade := Qry.FieldByName('Prod_Qtde').AsFloat;
Self.F_GrupoId := Qry.FieldByName('Prod_Grupo').AsInteger;
Self.F_SubGrupoId := Qry.FieldByName('Prod_SubGrupo').AsInteger;
Self.F_UnMedida := Qry.FieldByName('Prod_UnMedida').AsString;
Self.F_Obs := Qry.FieldByName('Prod_Obs').AsString;
Self.F_Marca := Qry.FieldByName('prod_Marca').AsString;
except
Result := false;
end;
finally
if Assigned(Qry) then
FreeAndNil(Qry);
end;
end;
{$endregion}
end.
|
// makes globally registered Midas.dll unnecessary.
// this global HKLM-registration requires UAC-elevation, prone to DLL-Hell, might prevent
// copying of app folder from backup or retiring computer, etc
// this unit searches for XE2-or-later midas.dll as registered in HKLM-registry, in
// the app's exe folder and one folder above, in current working folder and above.
//
// registering custom MIDAS is based on stock MidasLib unit
// DLL-based Midas is reportedly workig faster than Pascal implementaion which can be linked
// into monolythic EXE (MidasLib unit)
unit MidasDLL;
interface
implementation
uses Winapi.Windows, Winapi.ActiveX, Datasnap.DSIntf, SysUtils, Registry;
// function DllGetDataSnapClassObject(const CLSID, IID: TGUID; var Obj): HResult; stdcall; external 'Midas.DLL';
//var DllGetDataSnapClassObject: function(const CLSID, IID: TGUID; var Obj): HResult; stdcall; //external 'Midas.DLL';
var DllGetDataSnapClassObject: pointer; //external 'Midas.DLL';
const dllFN = 'Midas.DLL'; dllSubN = 'DllGetDataSnapClassObject';
var DllHandle: HMODULE = 0;
function RegisteredMidasPath: TFileName;
const rpath = '\SOFTWARE\Classes\CLSID\{9E8D2FA1-591C-11D0-BF52-0020AF32BD64}\InProcServer32';
var rry: TRegistry;
begin
rry := TRegistry.Create( KEY_READ );
try
rry.RootKey := HKEY_LOCAL_MACHINE;
if rry.OpenKeyReadOnly( rpath ) then begin
Result := rry.ReadString('');
if not FileExists( Result ) then
Result := '';
end;
finally
rry.Destroy;
end;
end;
procedure TryFindMidas;
var fPath, msg: string;
function TryOne(const fName: TFileName): boolean;
const ver_16_0 = 1048576; // $00060001 - XE2-shipped version. Would accept later ones, not older ones.
var ver: Cardinal; ver2w: LongRec absolute ver;
begin
Result := false;
ver := GetFileVersion( fName );
if LongInt(ver)+1 = 0 then exit; // -1 --> not found
if ver < ver_16_0 then begin
msg := msg + #13#10 +
// 'Найдена версия '+IntToStr(ver2w.Hi) + '.' + IntToStr(ver2w.Lo) + ' в библиотеке ' + fName;
'Version found: '+IntToStr(ver2w.Hi) + '.' + IntToStr(ver2w.Lo) + ' of the library: ' + fName;
exit;
end;
DllHandle := SafeLoadLibrary(fName);
if DllHandle = 0 then begin
msg := msg + #13#10 +
// 'Невозможно загрузить ' + fName + '. Возможно 64-битная версия библиотеки, или другая проблема.';
'Cannot load ' + fName + '. It could have been a 64-bits build DLL or some other loading problem.';
exit;
end;
DllGetDataSnapClassObject := GetProcAddress( DllHandle, dllSubN);
if nil = DllGetDataSnapClassObject then begin
msg := msg + #13#10 +
// 'Невозможно загрузить ' + fName + '. Не найден ' + dllSubN;
'Cannot load ' + fName + '. Cannot find ' + dllSubN;
FreeLibrary( DllHandle );
DllHandle := 0;
end;
Result := true;
end;
function TryTwo(const fName: TFileName): boolean; // Searching for DLL file in the given folder and its ..
begin
Result := TryOne(fName + dllFN);
if not Result then
Result := TryOne(fName + '..\' + dllFN); // for sub-project EXEs in directly nested subfolders
end;
begin
fPath := ExtractFilePath( ParamStr(0) );
if TryTwo( fPath ) then exit;
fPath := IncludeTrailingBackslash( GetCurrentDir() );
if TryTwo( fPath ) then exit;
fPath := RegisteredMidasPath;
if fPath > '' then
if TryOne( fPath ) then exit;
// msg := 'Программе необходима библиотека ' + dllFN + ' версии 16.0 и выше.'#13#10 +
// 'Такой библиотеки не найдено, работа программы невозможна.'#13#10 + #13#10 + msg;
msg := 'This application need ' + dllFN + ' library of version 16.0 or newer.'#13#10 +
'Because of a failure to locate this library the application can not work.'#13#10 + #13#10 + msg;
Winapi.Windows.MessageBox(0, PChar(msg),
'Application start failed!',
// 'Ошибка запуска!',
MB_ICONSTOP or MB_TASKMODAL or MB_DEFAULT_DESKTOP_ONLY or MB_TOPMOST );
Halt(1);
end;
initialization
// RegisterMidasLib(@DllGetDataSnapClassObject); -- static linking does not work for (InstallDir)\(SubProjectDir)\SubProject.exe
TryFindMidas; // Halts the program if MIDAS was not found. Останавливает программу, если не найдено
RegisterMidasLib(DllGetDataSnapClassObject);
finalization
if DllHandle <> 0 then
if FreeLibrary( DllHandle ) then
DllHandle := 0;
end.
|
unit Ragna.State;
{$IF DEFINED(FPC)}
{$MODE DELPHI}{$H+}
{$ENDIF}
interface
uses System.Generics.Collections, {$IFDEF UNIDAC}Uni{$ELSE}FireDac.Comp.Client{$ENDIF}, System.Rtti;
type
TListQueryAndSql = TDictionary<{$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}, string>;
TRagnaState = class
private
FStates: TListQueryAndSql;
FVmi: TVirtualMethodInterceptor;
class var FInstance: TRagnaState;
procedure OnBeforVMI(Instance: TObject; Method: TRttiMethod; const Args: TArray<TValue>; out DoInvoke: Boolean; out Result: TValue);
public
destructor Destroy; override;
property States: TListQueryAndSql read FStates write FStates;
procedure SetState(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}; const ASQL: string);
function GetState(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}; out ASQL: string): Boolean;
class function GetInstance: TRagnaState;
class procedure Release;
constructor Create;
end;
implementation
constructor TRagnaState.Create;
begin
FVmi := TVirtualMethodInterceptor.Create({$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF});
FVmi.OnBefore := OnBeforVMI;
FStates := TListQueryAndSql.Create;
end;
destructor TRagnaState.Destroy;
begin
FStates.Free;
FVmi.Free;
end;
class function TRagnaState.GetInstance: TRagnaState;
begin
if not assigned(FInstance) then
FInstance := TRagnaState.Create;
Result := FInstance;
end;
function TRagnaState.GetState(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}; out ASQL: string): Boolean;
begin
TMonitor.Enter(FStates);
try
Result := FStates.TryGetValue(AQuery, ASQL);
finally
TMonitor.Exit(FStates);
end;
end;
procedure TRagnaState.OnBeforVMI(Instance: TObject; Method: TRttiMethod; const Args: TArray<TValue>; out DoInvoke: Boolean;
out Result: TValue);
begin
if Method.Name <> 'BeforeDestruction' then
Exit;
TMonitor.Enter(FStates);
try
FStates.Remove(Instance as {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF});
finally
TMonitor.Exit(FStates);
end;
end;
class procedure TRagnaState.Release;
begin
FInstance.Free;
end;
procedure TRagnaState.SetState(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}; const ASQL: string);
begin
TMonitor.Enter(FStates);
try
if FVmi.ProxyClass <> AQuery.ClassType then
FVmi.Proxify(AQuery);
FStates.AddOrSetValue(AQuery, ASQL);
finally
TMonitor.Exit(FStates);
end;
end;
initialization
TRagnaState.GetInstance;
finalization
TRagnaState.Release;
end.
|
unit FMX.Dialogs.Wait;
{
The MIT License (MIT)
Copyright (c) 2014, Takehiko Iwanaga.
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
System.Classes, System.SysUtils, System.UITypes, FMX.Dialogs, FMX.Forms;
function MessageDlgWait(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons; const AHelpContext: LongInt): Integer;
implementation
type
TDialogThread = class(TThread)
private
F_Message: String;
F_DialogType: TMsgDlgType;
F_Buttons: TMsgDlgButtons;
F_HelpContext: LongInt;
F_Result: Integer;
F_IsFinished: Boolean;
protected
procedure Execute; override;
public
constructor Create;
procedure Start(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons; const AHelpContext: LongInt);
property Result:Integer read F_Result write F_Result;
end;
constructor TDialogThread.Create;
begin
inherited Create(True);
FreeOnTerminate := False;
end;
procedure TDialogThread.Start(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons; const AHelpContext: LongInt);
begin
F_Message := AMessage;
F_DialogType := ADialogType;
F_Buttons := AButtons;
F_HelpContext := AHelpContext;
inherited Start();
end;
procedure TDialogThread.Execute;
var
IsFinished: Boolean;
begin
IsFinished := False;
Synchronize(procedure begin
MessageDlg(F_Message, F_DialogType, F_Buttons, F_HelpContext,
procedure(const AResult: TModalResult) begin
F_Result := AResult;
IsFinished := True;
end
)
end);
repeat
Sleep(100);
Application.ProcessMessages;
until (IsFinished);
end;
function MessageDlgWait(const AMessage: string; const ADialogType: TMsgDlgType; const AButtons: TMsgDlgButtons; const AHelpContext: LongInt): Integer;
{$IFDEF ANDROID}
var
DialogThread: TDialogThread;
begin
DialogThread := TDialogThread.Create();
DialogThread.Start(AMessage, ADialogType, AButtons, AHelpContext);
DialogThread.WaitFor();
Result := DialogThread.Result;
FreeAndNil(DialogThread);
end;
{$ELSE}
begin
Result := MessageDlg(AMessage, ADialogType, AButtons, AHelpContext);
end;
{$ENDIF}
end.
|
unit mnFonts;
{$mode objfpc}
{$H+}
{**
* Raster/Bitmap Fonts
*
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
{$ifdef wince}
Windows,
{$endif}
SysUtils, Classes, Graphics, FPCanvas, FPimage, IniFiles, zstream;
type
TCallbackDrawChar = function(const Target; x, y:Integer; c: char): Boolean of Object;
{ TmnfRasterFont }
TmnfRasterFont = class(TFPCustomDrawFont)
protected
procedure DoDrawText(x, y: Integer; Text: String); override;
procedure DoGetTextSize(Text: String; var w, h: Integer); override;
function DoGetTextHeight(Text: String): Integer; override;
function DoGetTextWidth(Text: String): Integer; override;
function DrawCharCanvas(const Target; x, y:Integer; c: char): Boolean;
{$ifdef wince}
function DrawCharDC(const Target; x, y:Integer; c: char): Boolean;
{$endif}
procedure PrintString(CallbackDrawChar: TCallbackDrawChar; const Target; x, y: Integer; Text: String);
function CreateImage: TPortableNetworkGraphic;
public
Image: TPortableNetworkGraphic;
Rows, Columns: Integer;
Chars: widestring;
CharCount: Integer;
CharWidth: Integer;
CharHeight: Integer;
CharStart: Integer;
constructor Create; override;
procedure Generate(FontName: String = 'Courier'; FontSize: integer = 10; Antialiasing: Boolean = False);
procedure PrintText(ACanvas: TFPCustomCanvas; x, y: Integer; Text: String);
{$ifdef wince}
procedure PrintText(DC: HDC; x, y: Integer; Text: String);
{$endif}
procedure LoadFromFile(FileName: String);
procedure SaveToFile(FileName: String);
procedure LoadInfoFromFile(FileName: String);
procedure SaveInfoToFile(FileName: String);
end;
implementation
uses
IntfGraphics, GraphType;
{ TmnfRasterFont }
procedure TmnfRasterFont.DoDrawText(x, y: Integer; Text: String);
begin
PrintText(Canvas, x, y, Text);
end;
procedure TmnfRasterFont.DoGetTextSize(Text: String; var w, h: Integer);
begin
w := Length(Text) * CharWidth;
h := CharHeight;
end;
function TmnfRasterFont.DoGetTextHeight(Text: String): Integer;
begin
Result := CharHeight;
end;
function TmnfRasterFont.DoGetTextWidth(Text: String): Integer;
begin
Result := Length(Text) * CharWidth;
end;
{$ifdef wince}
function TmnfRasterFont.DrawCharDC(const Target; x, y: Integer; c: char): Boolean;
var
index: Integer;
cx, cy: Integer;
begin
index := Ord(c) - CharStart;
cy := (index div Columns) * CharHeight;
cx := (index mod Columns) * CharWidth;
BitBlt(HDC(Target), x, y, CharWidth, CharHeight, Image.Canvas.Handle, cx, cy, MERGECOPY);
Result := true;
end;
{$endif}
function TmnfRasterFont.DrawCharCanvas(const Target; x, y: Integer; c: char): Boolean;
var
cRect: TRect;
index: Integer;
cx, cy: Integer;
ACanvas: TFPCustomCanvas;
begin
ACanvas:=TFPCustomCanvas(Target);
index := Ord(c) - CharStart;
cy := (index div Columns) * CharHeight;
cx := (index mod Columns) * CharWidth;
cRect := rect(cx, cy, cx + CharWidth - 1, cy + CharHeight - 1);
if ACanvas is TCanvas then
(ACanvas as TCanvas).CopyMode := cmMergeCopy;
ACanvas.CopyRect(x, y, Image.Canvas, cRect);
Result := true;
end;
constructor TmnfRasterFont.Create;
begin
inherited Create;
CharStart := 32;
CharCount := 256 - CharStart;
Columns := 32;
Rows := 8;
Image := CreateImage;
end;
procedure TmnfRasterFont.PrintText(ACanvas: TFPCustomCanvas; x, y: Integer; Text: String);
begin
PrintString(@DrawCharCanvas, ACanvas, x, y, Text);
end;
{$ifdef wince}
procedure TmnfRasterFont.PrintText(DC: HDC; x, y: Integer; Text: String);
begin
PrintString(@DrawCharDC, Dc, x, y, Text);
end;
{$endif}
procedure TmnfRasterFont.PrintString(CallbackDrawChar: TCallbackDrawChar; const Target; x, y: Integer; Text: String);
var
i: Integer;
begin
for i := 1 to Length(Text) do
begin
if not CallbackDrawChar(Target, x, y, text[i]) then
break;
x := x + CharWidth;
end;
end;
procedure TmnfRasterFont.LoadFromFile(FileName: String);
begin
FreeAndNil(Image);
Image := CreateImage;
with Image do
LoadFromFile(FileName);
end;
procedure TmnfRasterFont.LoadInfoFromFile(FileName: String);
var
ini: TIniFile;
begin
ini := TIniFile.Create(FileName);
try
CharStart := ini.ReadInteger('Font', 'CharStart', 0);
Rows := ini.ReadInteger('Font', 'Rows', 0);
Columns := ini.ReadInteger('Font', 'Columns', 0);
CharCount := ini.ReadInteger('Font', 'CharCount', 256);
CharWidth := ini.ReadInteger('Font', 'CharWidth', 0);
CharHeight := ini.ReadInteger('Font', 'CharHeight', 0);
finally
ini.Free;
end;
end;
procedure TmnfRasterFont.SaveToFile(FileName: String);
begin
Image.SaveToFile(fileName);
end;
procedure TmnfRasterFont.SaveInfoToFile(FileName: String);
var
ini: TIniFile;
begin
ini:=TIniFile.Create(FileName);
try
ini.WriteInteger('Font', 'CharStart', CharStart);
ini.WriteInteger('Font', 'Rows', Rows);
ini.WriteInteger('Font', 'Columns', Columns);
ini.WriteInteger('Font', 'CharCount', CharCount);
ini.WriteInteger('Font', 'CharWidth', CharWidth);
ini.WriteInteger('Font', 'CharHeight', CharHeight);
finally
ini.Free;
end;
end;
function TmnfRasterFont.CreateImage: TPortableNetworkGraphic;
begin
Result := TPortableNetworkGraphic.Create;
with Result do
begin
Width := 0;
Height := 0;
Transparent := True;
TransparentMode := tmFixed;
PixelFormat := pf16bit;
end;
end;
procedure TmnfRasterFont.Generate(FontName: String; FontSize: integer; Antialiasing: Boolean);
var
dx, dy: Integer;
i, c, r: Integer;
count: integer;
char: widechar;
aTextStyle: TTextStyle;
IntfImg: TLazIntfImage;
pngWriter : TLazWriterPNG;
begin
with Image do
begin
Masked := True;
Transparent := True;
TransparentColor := clYellow;
Canvas.Brush.Color := clFuchsia;
Canvas.Pen.Color := clWhite;
Canvas.Font.Color := clWhite;
//PixelFormat := pf32bit;
Canvas.Font.Size := FontSize;
Canvas.Font.Name := FontName;
Canvas.Font.Style := [];
if Antialiasing then
Canvas.Font.Quality := fqDefault
else
Canvas.Font.Quality := fqNonAntialiased;
CharWidth := Canvas.TextWidth('W');
CharHeight := Canvas.TextHeight('W');
if Chars <> '' then
count := Length(Chars)
else
count := CharCount;
Rows := round(count / Columns);
Height := CharHeight * Rows;
Width := CharWidth * Columns;
Canvas.FillRect(0, 0, Width, Height);
if Chars <> '' then
i := 1
else
i := CharStart;
for r := 0 to Rows -1 do
for c := 0 to Columns -1 do
begin
if Chars <> '' then
char := Chars[i]
else
char := WideChar(i);
aTextStyle.Opaque := False;
aTextStyle.Alignment := taLeftJustify;
aTextStyle.Clipping := False;
aTextStyle.Layout := tlCenter;
Canvas.TextStyle := aTextStyle;
Canvas.TextOut(c * CharWidth, r * CharHeight, char);
//Canvas.Frame(c * CharWidth, r * CharHeight, c * CharWidth + CharWidth, r * CharHeight + CharHeight );
inc(i);
end;
end;
IntfImg := TLazIntfImage.Create(0, 0, [riqfRGB, riqfAlpha]);
IntfImg.SetSize(Image.Width, Image.Height);
IntfImg.LoadFromBitmap(Image.BitmapHandle, Image.MaskHandle);
//IntfImg.UsePalette := True;
//IntfImg := Image.CreateIntfImage;
//trans := colWhite;
//trans.alpha := 0;
for dy := 0 to Image.Height - 1 do
begin
for dx:=0 to Image.Width - 1 do
begin
if IntfImg.Colors[dx,dy] = colFuchsia then
IntfImg.Colors[dx, dy] := colTransparent;
end;
end;
pngWriter := TLazWriterPNG.create;
pngWriter.UseAlpha := true;
pngWriter.CompressionLevel := TCompressionLevel.clnone;
IntfImg.SaveToFile('d:\temp\my_font2.png', pngWriter);
Image.LoadFromIntfImage(IntfImg);
pngWriter.Free;
IntfImg.Free;
Image.SaveToFile('d:\temp\my_font.png');
end;
end.
|
(******************************************************************)
(* SFX for DelZip v1.8 *)
(* Copyright 2002-2004, 2008 *)
(* *)
(* written by Markus Stephany *)
(* modified by Russell Peters, Roger Aelbrecht
Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht,
Eric W. Engler and Chris Vleghert.
This file is part of TZipMaster Version 1.9.
TZipMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TZipMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TZipMaster. If not, see <http://www.gnu.org/licenses/>.
contact: problems@delphizip.org (include ZipMaster in the subject).
updates: http://www.delphizip.org
DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip
modified 30-Jan-2008
---------------------------------------------------------------------------*)
unit ZMSFXStrings19;
{
this unit contains localized strings
}
interface
uses Windows;
const
SFX_LVC_Filename = 1;//1024; // 'Filename';
SFX_LVC_Filesize = 2;//1025; // 'Size';
// error messages
SFX_Err_CannotCloseFile = 3;//1040; // 'Cannot close ><';
SFX_Err_Archive = 5;//1041; // 'Error reading archive ><';
SFX_Err_InvalidFileName = 6;//1042; // 'Invalid filename.';
SFX_Err_Directory = 7;//1043; // 'Error in directory ><';
SFX_Err_ZipUnknownComp = 8;//1044; // 'Unknown compression type';
SFX_Err_ArchiveCorrupted = 9;//1045; // 'Archive corrupted, please try to download this file again.';
SFX_Err_CannotOpenFile = 10;//1046; // 'Cannot open ><';
SFX_Err_CannotWriteFile = 11;//1047; // 'Cannot write to ><';
SFX_Err_Run_Run = 12;//1048; // 'Couldn''t run >< ><';
SFX_Err_Run_Inst = 13;//1049; // 'Couldn''t install >< ><';
SFX_Err_CRC32 = 14;//1050; // 'CRC32 Error in ><';
// SFX_Err_BadFilename = 15;
// messages
SFX_Msg_RunCheckBox_Run = 16;//1072; // 'After extraction, run: >< ><';
SFX_Msg_RunCheckBox_Inst = 17;//1073; // 'After extraction, install: >< ><';
SFX_Msg_FileExists = 18;//1074; // '>< already exists, overwrite ?';
SFX_Msg_AllExtracted = 19;//1075; // 'All files have been extracted.';
SFX_Msg_SelNotExtracted = 20;//1076; // 'The selected file(s) couldn''t get extracted.';
SFX_Msg_SomeNotExtracted = 21;//1077; // 'Some file(s) couldn''t get extracted.';
SFX_Msg_QueryCancel = 22;//1078; // 'Do you want to cancel extraction?';
SFX_Msg_InsertDiskVolume = 23;//1079; // 'Please insert disk volume >< in drive ><';
// about text
// SFX_Msg_About = 1088;
SFX_MSG_ABOUT0 = 60;
SFX_MSG_ABOUT1 = 61;
SFX_MSG_AUTHORS = 62;//1089;//'The authors';
SFX_MSG_ABOUT2 = 63;
SFX_MSG_CREDITS = 64;//1090;//'Credits to';
SFX_MSG_ABOUT3 = 65;
SFX_MSG_TRANSLATION = 66;//1091;//' ';
// message / dialog box titles
SFX_Cap_Err = 28;//1104; // 'Error...';
SFX_Cap_App = 29;//1105; // 'DelZip Self-Extractor';
SFX_Cap_Browse = 30;//1106; // 'Please choose the destination directory';
SFX_Cap_About = 31;//1107; // 'About DelZip Self-Extractor...';
SFX_Cap_Finished = 32;//1108; // 'Finished.';
SFX_Cap_Password = 33;//1109; // 'Enter password for ><:';
// Main Dialog buttons
SFX_Btn_Start = 34;//1120; // 1
SFX_Btn_Close = 35;//1121; // 2
SFX_Btn_About = 36;//1122; // 103
SFX_Btn_Files = 37;//1123; // 501
SFX_Btn_Existing = 38;//1124; // 602
SFX_Btn_ShowFiles = 39;//1125; // 105
SFX_Btn_ExtractTo = 40;//1126; // 601
SFX_Btn_OvrAsk = 41;//1127; // 703
SFX_Btn_OvrSkip = 42;//1128; // 702
SFX_Btn_OvrAll = 43;//1129; // 701
// FileExists Dialog
SFX_Btn_Yes = 44;//1136; // 1
SFX_Btn_No = 46;//1137; // 2
SFX_Btn_DontAsk = 47;//1138; // 301
// Password Dialog
SFX_Btn_Ok = 48;//1152; // 1
SFX_Btn_Cancel = 49;//1153; // 2
// Dialog titles
SFX_Ttl_Main = 50;//1068;
SFX_Ttl_File = 51;//1069;
SFX_Ttl_PWrd = 52;//1070;
// Language Dialog
SFX_Btn_Select = 53;//1085;
Var
VRec_DefStrings: PByte = nil; // pointer to table of strings
VRec_Strings: PByte = nil; // pointer to table of strings
const
MaxStringLen = MAX_PATH * 2;
procedure SetDlgStrings(Dlg: hWnd; val: cardinal);
function SFXString(id: integer): string;
function To_Str(CP: Integer; Source: pAnsiChar; len: integer; IsName: Boolean;
var Bad: boolean): string;
// table format - ident: byte, strng[]: byte, 0: byte; ...;0
function LoadSFXStr(ptbl: pByte; ident: Byte): String;
implementation
uses
ZMSFXDefs19;
type
IdTbleRec2 = packed record
DlgId: byte;
Ctrl: word;
StrId: byte;
end;
const
SOFF = 0;//1024;
IdTbl1: array [0..22] of IdTbleRec2 = (
(DlgID: SFX_DLG_MAIN; Ctrl: 0; StrId: SFX_Ttl_Main - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 1; StrId: SFX_Btn_Start - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 2; StrId: SFX_Btn_Close - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 103; StrId: SFX_Btn_About - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 501; StrId: SFX_Btn_Files - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 602; StrId: SFX_Btn_Existing - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 601; StrId: SFX_Btn_ExtractTo - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 105; StrId: SFX_Btn_ShowFiles - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 703; StrId: SFX_Btn_OVRAsk - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 702; StrId: SFX_Btn_OVRSkip - SOFF),
(DlgID: SFX_DLG_MAIN; Ctrl: 701; StrId: SFX_Btn_OVRAll - SOFF),
(DlgID: SFX_DLG_FILE; Ctrl: 0; StrId: SFX_Ttl_File - SOFF),
(DlgID: SFX_DLG_FILE; Ctrl: 1; StrId: SFX_Btn_Yes - SOFF),
(DlgID: SFX_DLG_FILE; Ctrl: 2; StrId: SFX_Btn_No - SOFF),
(DlgID: SFX_DLG_FILE; Ctrl: 301; StrId: SFX_Btn_DontAsk - SOFF),
(DlgID: SFX_DLG_PWRD; Ctrl: 0; StrId: SFX_Ttl_PWrd - SOFF),
(DlgID: SFX_DLG_PWRD; Ctrl: 1; StrId: SFX_Btn_Ok - SOFF),
(DlgID: SFX_DLG_PWRD; Ctrl: 2; StrId: SFX_Btn_Cancel - SOFF),
(DlgID: SFX_DLG_LANG; Ctrl: 0; StrId: SFX_Ttl_Main - SOFF),
(DlgID: SFX_DLG_LANG; Ctrl: 1; StrId: SFX_Btn_Ok - SOFF),
(DlgID: SFX_DLG_LANG; Ctrl: 2; StrId: SFX_Btn_Close - SOFF),
(DlgID: SFX_DLG_LANG; Ctrl: ID_LANG_SELECT; StrId: SFX_Btn_Select - SOFF),
(DlgID: 0; Ctrl: 0; StrId: 0)
);
procedure SetDlgStrings(Dlg: hWnd; val: cardinal);
var
d: cardinal;
i: cardinal;
s: string;
x: cardinal;
begin
i := 0;
repeat
d := IdTbl1[i].DlgId;
if d = val then
begin
s := SFXString(IdTbl1[i].StrId + SOFF);
if s <> '' then
begin
x := IdTbl1[i].Ctrl;
if x = 0 then
SetWindowText(Dlg, pChar(s))
else
SetDlgItemText(Dlg, x, PChar(s));
end;
end;
Inc(i);
until (d = 0) or (d > val);
end;
function StrHasExt(Source: pAnsiChar; len: integer): Boolean;
var
c: AnsiChar;
i: integer;
begin
Result := false;
if len < 0 then
len := 4096;
for i := 1 to Len do
begin
c := Source^;
if c = #0 then
break;
if (c > #126) {or (c < #31)} then
begin
Result := True;
break;
end;
inc(Source);
end;
end;
function To_Str(CP: Integer; Source: pAnsiChar; len: integer; IsName: Boolean;
var Bad: boolean): string;
const
WC_NO_BEST_FIT_CHARS = $00000400; // do not use best fit chars
var
{$IFNDEF UNICODE}
buffer: array [0..(MaxStringLen + 3)] of widechar;
cnt: integer;
flg: cardinal;
notsup: longBool;
{$ENDIF}
wcnt: integer;
begin
Result := '';
Bad := false; // hopefully
if Source^ = #0 then
exit;
{$IFNDEF UNICODE}
if (CP = 0) and (len > 0) then
begin
SetLength(Result, len);
Move(Source^, PChar(Result)^, len);
exit;
end;
wcnt := MultiByteToWideChar(CP, 0, Source, len, nil, 0);
if (wcnt > 0) and (wcnt < MaxStringLen) then
begin
wcnt := MultiByteToWideChar(CP, 0, Source, len,
pWideChar(@buffer[0]), MaxStringLen);
if wcnt > 0 then
begin
buffer[wcnt] := #0;
if IsName then
flg := WC_NO_BEST_FIT_CHARS
else
flg := 0;
cnt := WideCharToMultiByte(0, flg, pWideChar(@buffer[0]),
wcnt + 1, nil, 0, nil, @notsup);
Bad := IsName and notsup;
if (cnt > 0) then
begin
SetLength(Result, cnt);
cnt := WideCharToMultiByte(0, flg, pWideChar(@buffer[0]),
wcnt + 1, PAnsiChar(Result), cnt, nil, nil);
if cnt = 0 then
Bad := True
else
Result := PAnsiChar(Result);
end;
end;
end;
{$ELSE}
wcnt := MultiByteToWideChar(CP, 0, Source, len, nil, 0);
if (wcnt > 0) then
begin
SetLength(Result, wcnt);
wcnt := MultiByteToWideChar(CP, 0, Source, len, PChar(Result), wcnt);
if (wcnt > 0) then
Result := PWideChar(Result); // don't want end 0
end
else
Bad := True;
{$ENDIF}
end;
// table format - ident: byte, strng[]: byte, 0: byte; ...;0
function LoadSFXStr(ptbl: pByte; ident: Byte): String;
var
bad: Boolean;
id: Byte;
begin
Result := '';
if (ptbl = nil) or (ident = 0) then
exit;
id := ptbl^;
while (id <> 0) and (id <> ident) do
begin
while ptbl^ <> 0 do
inc(ptbl);
inc(ptbl);
id := ptbl^;
end;
if id = ident then
begin
inc(ptbl);
Result := To_Str(CP_UTF8, pAnsiChar(ptbl), -1, false, bad);
end;
end;
function SFXString(id: integer): string;
begin
Result := '';
if VRec_Strings <> nil then
Result := LoadSFXStr(VRec_Strings, id);
if Result = '' then
// Result := LoadSFXStr(@StrBlok, {true,} id);
begin
if VRec_DefStrings <> nil then
Result := LoadSFXStr(VRec_DefStrings, id)
else
begin
MessageBox(0, 'Missing resource!', 'DelphiZip SFX', MB_ICONSTOP or MB_TASKMODAL);
Halt(2);
end;
end;
end;
end.
|
unit DAO.StatusCadastro;
interface
uses DAO.Base, Model.StatusCadastro, Generics.Collections, System.Classes;
type
TStatusCadastroDAO = class(TDAO)
public
function Insert(aStatus: Model.StatusCadastro.TStatusCadastro): Boolean;
function Update(aStatus: Model.StatusCadastro.TStatusCadastro): Boolean;
function Delete(sFiltro: String): Boolean;
function FindStatus(sFiltro: String): TObjectList<Model.StatusCadastro.TStatusCadastro>;
end;
const
TABLENAME = 'CAD_STATUS';
implementation
uses System.SysUtils, FireDAC.Comp.Client, Data.DB;
function TStatusCadastroDAO.Insert(aStatus: TStatusCadastro): Boolean;
var
sSQL : System.string;
begin
Result := False;
aStatus.ID := GetKeyValue(TABLENAME, 'ID_STATUS');
sSQL := 'INSERT INTO ' + TABLENAME + ' '+
'(ID_STATUS, DES_STATUS, DOM_ATIVO, DES_LOG) ' +
'VALUES ' +
'(:ID, :DESCRICAO, :ATIVO, :LOG);';
Connection.ExecSQL(sSQL,[aStatus.ID, aStatus.Descricao, aStatus.Ativo, aStatus.Log],
[ftInteger, ftString, ftBoolean, ftString]);
Result := True;
end;
function TStatusCadastroDAO.Update(aStatus: TStatusCadastro): Boolean;
var
sSQL: System.string;
begin
Result := False;
sSQL := 'UPDATE ' + TABLENAME + ' ' +
'SET ' +
'DES_STATUS = :DESCRICAO, DOM_ATIVO = :ATIVO, DES_LOG = :LOG ' +
'WHERE ID_STATUS = :ID;';
Connection.ExecSQL(sSQL,[aStatus.Descricao, aStatus.Ativo, aStatus.Log, aStatus.ID],
[ftString, ftBoolean, ftString, ftInteger]);
Result := True;
end;
function TStatusCadastroDAO.Delete(sFiltro: string): Boolean;
var
sSQL : String;
begin
Result := False;
sSQL := 'DELETE FROM ' + TABLENAME + ' ';
if not sFiltro.IsEmpty then
begin
sSQl := sSQL + sFiltro;
end
else
begin
Exit;
end;
Connection.ExecSQL(sSQL);
Result := True;
end;
function TStatusCadastroDAO.FindStatus(sFiltro: string): TObjectList<Model.StatusCadastro.TStatusCadastro>;
var
FDQuery: TFDQuery;
status: TObjectList<TStatusCadastro>;
begin
FDQuery := TFDQuery.Create(nil);
try
FDQuery.Connection := Connection;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
if not sFiltro.IsEmpty then
begin
FDQuery.SQL.Add(sFiltro);
end;
FDQuery.Open();
status := TObjectList<TStatusCadastro>.Create();
while not FDQuery.Eof do
begin
status.Add(TStatusCadastro.Create(FDQuery.FieldByName('ID_STATUS').AsInteger, FDQuery.FieldByName('DES_STATUS').AsString,
FDQuery.FieldByName('DOM_ATIVO').AsBoolean, FDQuery.FieldByName('DES_LOG').AsString));
FDQuery.Next;
end;
finally
FDQuery.Free;
end;
Result := status;
end;
end.
|
//Exercicio 41: Escreva um algoritmo que calcule o valor de X, sendo este determinado pela série:
// X = 1/1 + 3/2 + 5/3 + 7/4 + ... + 99/50.
{ Solução em Portugol
Algoritmo Exercicio 41;
Var
X: real;
contador: inteiro;
Inicio
exiba("Programa que calcula uma soma maluca.");
X <- 0;
contador <- 1;
enquanto(contador <= 50)faca
X <- X + (2* contador - 1)/contador;
contador <- contador + 1;
fimenquanto;
exiba("O valor da soma é: ", X:0:2);
Fim.
}
// Solução em Pascal
Program Exercicio41;
uses crt;
var
X: real;
contador: integer;
begin
clrscr;
writeln('Programa que calcula uma soma maluca.');
X := 0;
contador := 1;
while(contador <= 50)do
Begin
X := X + (2 * contador - 1)/contador;
contador := contador + 1;
End;
writeln('O valor da soma é: ', X:0:2);
repeat until keypressed;
end. |
unit nsIntegrationSupport;
interface
type
TIntergationDataKind = (idkCommand, idkLink, idkCheckIntegrationKey);
TnsLinkDataArray = array [0..0] of byte;
PnsLinkDataArray = ^TnsLinkDataArray;
PIntegrationData = ^TIntegrationData;
TIntegrationData = packed record
OpenInNewWindow: Boolean;
case Kind: TIntergationDataKind of
idkCommand: (Command: Integer);
idkLink: (LinkLength: Integer; Link: TnsLinkDataArray);
idkCheckIntegrationKey: (KeyLength: Integer; Key: TnsLinkDataArray);
end;
const
c_IntegrationMessageName = '{394AC4BC-9BC4-4A75-BE21-40CC58511CD6}';
c_IntergationMutexName = '{BC46C623-DBC9-473E-B8CC-9E7CBD8ACBC3}';
c_LastMainWindowMessageName = '{1CDEED58-DDBF-4AC9-B86F-8D957B46E59C}';
// коды ошибок
GI_OK = 0; // Нет ошибок
GI_NOTFOUND = 1; // Система Гарант не найдена
GI_INVALIDLINKFORMAT = 2; // Неверный формат ссылки
GI_BUSY = 3; // Система Гарант занята (отображает модальный диалог, печатает и т.д.)
// и не может обработать запрос
GI_TIMEOUT = 4; // Тайм-аут при получении ссылки на главное окно Гаранта
GI_ALREADYRUNNING = 5; // Система Гарант уже запущена
GI_SYSTEMERROR = 6; // Общесистемная ошибка (нет xml-парсера, битая база и пр.)
GI_QUERYPARAMSHASABSENTVALUES = 7; // Ссылка-запрос содержит условия, которые при
// попытке выполнить запрос на текущей
// базе будут игнорированы
GI_USERDENYLOGIN = 8; // При запуске системы пользователь отказался от авторизации
GI_TRYTOFINDEMPTYCONTEXT = 9; // Попытка поиска пустого контекста
GI_TOOMANYOPENWINDOWS = 10; // Слишком много открытых окон
// Команды
GC_ACTIVATE = 0; // Просто запустить/активировать текущее окно
GC_MAIN_MENU = 1; // Основное меню
GC_NAVIGATOR = 2; // Правовой навигатор
GC_SITUATION_SEARCH = 3; // Поиски по ситуации,
GC_ATTRIBUTES_SEARCH = 4; // Поиски по реквизитам,
GC_PUBLISH_SOURCE_SEARCH = 5; // Поиски по источнику опубликования,
GC_REVIEW = 7; // Обзор изменений в законодательстве
GC_DICTION = 8; // Толковый словарь
GC_NEW_DOCS = 9; // Новые документы из Справочной информации
GC_INPHARM_SEARCH = 10; // Поиск лекарственного препарата
GC_DRUG_LIST = 11; // Список лекарственных препаратов
GC_INPHARM_MAIN_MENU = 12; // Основное меню Инфарм
GC_IMPHARM_DICTION = 13; // Словарь мед. терминов
GC_INTERNET_AGENT = 14; // Новости онлайн
GC_OPEN_CONSULT = 15; // Задать вопрос эксперту
GC_PRIME = 16; // Моя новостная лента
GC_FIRST = GC_ACTIVATE;
GC_LAST = GC_PRIME;
implementation
end. |
unit MyUtils;
(* Nektere pomocne obsluzne utility *)
interface
uses
Graphics, SysUtils;
function ZpracujNaCislo(Text:String):String;
procedure VypisTextDoObrazku(Cvs:TCanvas;StartX,EndX:Integer;var now_y:integer;Text:String);
implementation
(* function ZpracujNaCislo
FUNKCE:
Ze zadaneho textoveho retezce (Text:String) odstrani
vsechny nenumericke znaky. Je-li pak retezec prazdny,
vrati '0'
*)
function ZpracujNaCislo(Text:String):String;
var OutText:String;
IntSet:set of '0'..'9'; //mnozina pripustnych hodnot
NulaNaZacatku:boolean;
i:integer;
begin
IntSet:=['0','1','2','3','4','5','6','7','8','9'];
NulaNaZacatku:=true;
for i:=1 to Length(Text) do
if Text[i] in IntSet
then begin
if Text[i]='0'
then begin
if NulaNaZacatku=false
then OutText:=OutText+Text[i];
end
else begin
NulaNaZacatku:=false;
OutText:=OutText+Text[i];
end;
end;
if OutText='' then OutText:='0';
Result:=OutText;
end;
(* VypisTextDoObrazku
FUNKCE:
Do zadaneho Canvasu vypise zadany text...
ARGUMENTY:
Cvs - Canvas do ktereho se ma kreslit
StartX - LEVY kraj oblasti plochy kam se ma vypisovat
EndX - PRAVY kraj oblasti plochy kam se ma vypisovat
now_y - souradnice 'y' v plose kam se kresli (na jaky radek)
Text - text k vypsani
*)
procedure VypisTextDoObrazku(Cvs:TCanvas;StartX,EndX:Integer;var now_y:integer;Text:String);
var char_y,sirkaplochy,i,space:integer;
showtext,slovo:string;
begin
char_y:=Cvs.TextHeight('M');
sirkaplochy:=EndX-StartX;
i:=1; //aktualni pozice ve vstupnim textovem retezci
space:=0; //pozice posledni mezery
showtext:=''; //obsahuje jeden "graficky radek" k vypsani
while i<=Length(Text) do begin
//zkopiruje z textu jedno slovo
while ((i<=Length(Text)) and (Text[i]<>' '))
do begin
slovo:=slovo+Text[i];
i:=i+1;
end;
//zjisti jestli se nactene slovo jeste vleze na dany
//radek, pokud ano pripoji ho k radku, pokud ne
//vypise radek a skoci na novy
if Cvs.TextWidth(showtext+slovo)<sirkaplochy
then begin
showtext:=showtext+slovo;
slovo:=' ';
i:=i+1;
space:=i;
end
else begin
Cvs.TextOut(StartX,now_y,showtext);
now_y:=now_y+char_y;
showtext:='';
slovo:='';
i:=space;
end;
end;
Cvs.TextOut(StartX,now_y,showtext);
now_y:=now_y+char_y;
end;
end.
|
// ***************************************************************************
//
// A Simple Firemonkey Rating Bar Component
//
// Copyright 2017 谢顿 (zhaoyipeng@hotmail.com)
//
// https://github.com/zhaoyipeng/FMXComponents
//
// ***************************************************************************
// version history
// 2017-01-20, v0.1.0.0 :
// first release
// 2017-09-22, v0.2.0.0 :
// merge Aone's version
// add Data(TPathData) property, support user define rating shape
// thanks Aone, QQ: 1467948783
// http://www.cnblogs.com/onechen
unit FMX.RatingBar;
interface
uses
System.Classes,
System.SysUtils,
System.Math,
System.Math.Vectors,
System.Types,
System.UITypes,
System.UIConsts,
FMX.Types,
FMX.Layouts,
FMX.Graphics,
FMX.Controls,
FMX.Objects,
FMX.ComponentsCommon;
type
[ComponentPlatformsAttribute(TFMXPlatforms)]
TFMXRatingBar = class(TShape, IPathObject)
private
FData: TPathData;
FCount: Integer;
FMaximum: Single;
FValue: Single;
FSpace: Single;
FActiveColor: TAlphaColor;
FInActiveColor: TAlphaColor;
FActiveBrush: TBrush;
FInActiveBrush: TBrush;
FMouseDown: Boolean;
FOnChanged: TNotifyEvent;
procedure SetPathData(const Value: TPathData);
procedure SetCount(const Value: Integer);
procedure SetMaximum(const Value: Single);
procedure SetValue(const Value: Single);
procedure SetSpace(const Value: Single);
procedure SetActiveColor(const Value: TAlphaColor);
procedure SetInActiveColor(const Value: TAlphaColor);
{ IPathObject }
function GetPath: TPathData;
procedure CreateBrush;
procedure FreeBrush;
procedure CalcValue(X: Single);
procedure SetOnChanged(const Value: TNotifyEvent);
procedure DoChanged;
protected
procedure Resize; override;
procedure Paint; override;
procedure DrawRating(ARect: TRectF; AValue: Single);
procedure FillChanged(Sender: TObject);
procedure StrokeChanged(Sender: TObject);
procedure PathDataChanged(Sender: TObject);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Align;
property Anchors;
property ClipChildren default False;
property ClipParent default False;
property Cursor default crDefault;
property DragMode default TDragMode.dmManual;
property EnableDragHighlight default True;
property Enabled default True;
property Locked default False;
property Height;
property HitTest default True;
property Padding;
property Opacity;
property Margins;
property PopupMenu;
property Position;
property RotationAngle;
property RotationCenter;
property Scale;
property Size;
property Visible default True;
property Width;
{ Drag and Drop events }
property OnDragEnter;
property OnDragLeave;
property OnDragOver;
property OnDragDrop;
property OnDragEnd;
{ Mouse events }
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseEnter;
property OnMouseLeave;
property OnPainting;
property OnPaint;
property OnResize;
{$IF (RTLVersion >= 32)} // Tokyo
property OnResized;
{$ENDIF}
property Data: TPathData read FData write SetPathData;
property ActiveColor: TAlphaColor read FActiveColor write SetActiveColor;
property InActiveColor: TAlphaColor read FInActiveColor write SetInActiveColor;
property Stroke;
property Space: Single read FSpace write SetSpace;
property Count: Integer read FCount write SetCount default 5;
property Value: Single read FValue write SetValue;
property Maximum: Single read FMaximum write SetMaximum;
property OnChanged: TNotifyEvent read FOnChanged write SetOnChanged;
end;
implementation
{ THHRating }
constructor TFMXRatingBar.Create(AOwner: TComponent);
begin
inherited;
FMouseDown := False;
HitTest := True;
Width := 180;
Height := 30;
FData := TPathData.Create;
FData.Data := 'm 4677,2657 -1004,727 385,1179 -1002,-731 -1002,731 386,-1179 -1005,-727 1240,3 381,-1181 381,1181 z';
FData.OnChanged := PathDataChanged;
// 星 (瘦)
FCount := 5;
FMaximum := 5;
FValue := 0;
FSpace := 6;
FActiveColor := claRoyalblue;
FInActiveColor := $30000000;
Stroke.Color := claNull;
end;
destructor TFMXRatingBar.Destroy;
begin
FData.Free;
FreeBrush;
inherited;
end;
procedure TFMXRatingBar.DoChanged;
begin
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
procedure TFMXRatingBar.CreateBrush;
begin
if not Assigned(FActiveBrush) then
FActiveBrush := TBrush.Create(TBrushKind.Solid, FActiveColor);
if not Assigned(FInActiveBrush) then
FInActiveBrush := TBrush.Create(TBrushKind.Solid, FInActiveColor);
end;
procedure TFMXRatingBar.FillChanged(Sender: TObject);
begin
if FUpdating = 0 then
Repaint;
end;
procedure TFMXRatingBar.FreeBrush;
begin
FreeAndNil(FActiveBrush);
FreeAndNil(FInActiveBrush);
end;
procedure TFMXRatingBar.Assign(Source: TPersistent);
var
src: TFMXRatingBar;
begin
if Source is TFMXRatingBar then
begin
src := TFMXRatingBar(Source);
Stroke := src.Stroke;
FData.Assign(src.FData);
FCount := src.FCount;
FMaximum := src.FMaximum;
FValue := src.FValue;
FSpace := src.FSpace;
FActiveColor := src.FActiveColor;
FInActiveColor := src.FInActiveColor;
FreeBrush;
Repaint;
end
else
inherited;
end;
procedure TFMXRatingBar.CalcValue(X: Single);
var
w: Single;
Idx: Integer;
Sum: Single;
NewValue: Single;
begin
w := (Width - FSpace * 4) / Count;
if X <= 0 then
Value := 0
else if X >= Width then
Value := Maximum
else
begin
Idx := 1;
Sum := w;
while (X > Sum) and (Idx < Count) do
begin
Inc(Idx);
Sum := Sum + w + FSpace;
end;
NewValue := Idx * Maximum / Count;
if NewValue <> Value then
begin
Value := NewValue;
DoChanged;
end;
end;
end;
procedure TFMXRatingBar.DrawRating(ARect: TRectF; AValue: Single);
var
State: TCanvasSaveState;
l: Single;
R: TRectF;
begin
FData.FitToRect(ARect);
Canvas.BeginScene;
if AValue = 0 then
begin
Canvas.FillPath(FData, Opacity, FInActiveBrush);
end
else if AValue = 1 then
begin
Canvas.FillPath(FData, Opacity, FActiveBrush);
end
else
begin
Canvas.FillPath(FData, Opacity, FInActiveBrush);
l := Min(ARect.Height, ARect.Width);
R := RectF(ARect.CenterPoint.X - l, ARect.Top, ARect.CenterPoint.X + l * (AValue - 0.5), ARect.Bottom);
State := Canvas.SaveState;
Canvas.IntersectClipRect(R);
Canvas.FillPath(FData, Opacity, FActiveBrush);
Canvas.RestoreState(State);
end;
// 顯示外框
Canvas.DrawPath(FData, Opacity);
Canvas.EndScene;
end;
procedure TFMXRatingBar.Paint;
var
l, w: Single;
I: Integer;
R: TRectF;
DV, V: Single;
begin
inherited;
CreateBrush;
w := (Width - FSpace * 4) / Count;
DV := (FValue / FMaximum) * Count;
for I := 0 to Count - 1 do
begin
l := (w + FSpace) * I;
R := RectF(l, 0, l + w, Height);
if DV - I >= 1 then
V := 1
else if DV <= I then
V := 0
else
V := DV - I;
DrawRating(R, V);
end;
end;
procedure TFMXRatingBar.PathDataChanged(Sender: TObject);
begin
if FUpdating = 0 then
Repaint;
end;
procedure TFMXRatingBar.Resize;
begin
inherited;
Repaint;
end;
function TFMXRatingBar.GetPath: TPathData;
begin
Result := FData;
end;
procedure TFMXRatingBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if Button = TMouseButton.mbLeft then
begin
FMouseDown := True;
CalcValue(X);
end;
end;
procedure TFMXRatingBar.MouseMove(Shift: TShiftState; X, Y: Single);
begin
inherited;
if FMouseDown then
begin
CalcValue(X);
end;
end;
procedure TFMXRatingBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
FMouseDown := False;
end;
procedure TFMXRatingBar.SetPathData(const Value: TPathData);
begin
FData.Assign(Value);
Repaint;
end;
procedure TFMXRatingBar.SetActiveColor(const Value: TAlphaColor);
begin
if FActiveColor <> Value then
begin
FActiveColor := Value;
FreeAndNil(FActiveBrush);
Repaint;
end;
end;
procedure TFMXRatingBar.SetCount(const Value: Integer);
begin
if FCount <> Value then
begin
FCount := Value;
Repaint;
end;
end;
procedure TFMXRatingBar.SetInActiveColor(const Value: TAlphaColor);
begin
if FInActiveColor <> Value then
begin
FInActiveColor := Value;
FreeAndNil(FInActiveBrush);
Repaint;
end;
end;
procedure TFMXRatingBar.SetMaximum(const Value: Single);
begin
if FMaximum <> Value then
begin
FMaximum := Value;
Repaint;
end;
end;
procedure TFMXRatingBar.SetOnChanged(const Value: TNotifyEvent);
begin
FOnChanged := Value;
end;
procedure TFMXRatingBar.SetSpace(const Value: Single);
begin
if FSpace <> Value then
begin
FSpace := Value;
Repaint;
end;
end;
procedure TFMXRatingBar.SetValue(const Value: Single);
begin
if FValue <> Value then
begin
FValue := Value;
Repaint;
end;
end;
procedure TFMXRatingBar.StrokeChanged(Sender: TObject);
begin
if FUpdating = 0 then
Repaint;
end;
end.
|
unit TimeUtils;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
{$macro on}
{$inline on}
interface
uses SysUtils;
function EpochToTime(UnixTime: Double): TDateTime; cdecl;
function TimeSinceEpoch(OffsetSec:UInt32=0): Double; cdecl;
function FormatEpochTime(FormatString:String; UnixTime: Double): String; cdecl;
function EpochTimeToSysTime(UnixTime: Double): TSystemTime; cdecl;
function MarkTime(): double; cdecl;
//------------------------------------------------------------------------------
implementation
uses
DateUtils, Math,{$IFDEF WINDOWS}Windows{$ELSE}BaseUnix,Unix{$ENDIF};
(* "Date math" and whatnots ***************************************************)
function Modulo(X,Y:Double): Double; Inline;
begin
Result := X - Floor(X / Y) * Y;
end;
function DaysInMonth(Month, Year: UInt32): UInt32; Inline;
var
IsLeap: Boolean;
begin
IsLeap := (year mod 4=0) and ((year mod 100 <> 0) or (year mod 400 = 0));
if (month = 2) then
if IsLeap then Exit(29)
else Exit(28);
if Month in [4,6,9,11] then
Exit(30);
Exit(31);
end;
function DaysInYear(Year: UInt32): UInt32; Inline;
var
IsLeap: Boolean;
begin
Result := 365;
IsLeap := (year mod 4=0) and ((year mod 100 <> 0) or (year mod 400 = 0));
if IsLeap then
Result := 366;
end;
function ReduceDaysToYear(var D: Double): Int32; Inline;
begin
Result := 1970;
while D > DaysInYear(Result) do
begin
D := D - DaysInYear(Result);
Inc(Result);
end;
end;
function ReduceDaysToMonths(var D: Double; Year: UInt32): UInt32; Inline;
begin
Result := 1;
while D > DaysInMonth(Result,Year) do
begin
D := D - DaysInMonth(Result,Year);
Inc(Result);
end;
end;
(* Functions exported *********************************************************)
// Converts epoch time to TDateTime
// A "bit" overvomplicated, but I don't see how it matters.
function EpochToTime(UnixTime: Double): TDateTime; cdecl;
var
Ms, Sec, Min, Hour, Year, Month, Day: UInt32;
begin
Ms := Trunc(Frac(UnixTime)*1000);
Sec := Trunc(Modulo(UnixTime, 60));
UnixTime := UnixTime / 60;
Min := Trunc(Modulo(UnixTime, 60));
UnixTime := UnixTime / 60;
Hour := Trunc(Modulo(UnixTime, 24));
UnixTime := UnixTime / 24;
Year := ReduceDaysToYear(UnixTime);
Month := ReduceDaysToMonths(UnixTime, Year);
Day := Trunc(UnixTime) + 1;
Result := EncodeDateTime(Year, Month, Day, Hour, Min, Sec, Ms);
end;
// Computes the time since the unix epoch (01/01/1970)
function TimeSinceEpoch(OffsetSec:UInt32=0): Double; cdecl;
const
Epoch: TDateTime = 25569.0;
begin
Result := (Now() - Epoch) * (60*60*24) - OffsetSec;
end;
// Cool and simple string formating of the give unix-UnixTime
function FormatEpochTime(FormatString:String; UnixTime: Double): String; cdecl;
begin
Result := FormatDateTime(FormatString, EpochToTime(UnixTime));
end;
// UnitTime -> TSystemTime format
function EpochTimeToSysTime(UnixTime: Double): TSystemTime; cdecl;
var t:TDateTime;
begin
t := EpochToTime(UnixTime);
DateTimeToSystemTime(t, Result);
end;
function MarkTime(): Double; cdecl;
var
frequency,count:Int64;
{$IFDEF UNIX}
TV:TTimeVal; TZ:PTimeZone;
{$ENDIF}
begin
{$IFDEF WINDOWS}
QueryPerformanceFrequency(frequency);
QueryPerformanceCounter(count);
Result := count / frequency * 1000;
{$ELSE}
TZ := nil;
fpGetTimeOfDay(@TV, TZ);
count := Int64(TV.tv_sec) * 1000000 + Int64(TV.tv_usec);
Result := count / 1000;
{$ENDIF}
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2019 Kike Pérez
Unit : Quick.MemoryCache.Serializer.Json
Description : Cache Json serializer
Author : Kike Pérez
Version : 1.0
Created : 14/07/2019
Modified : 02/11/2019
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
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 Quick.MemoryCache.Serializer.Json;
{$i QuickLib.inc}
interface
uses
RTTI,
//System.JSON.Serializers,
Quick.Json.Serializer,
Quick.MemoryCache.Types;
type
TCacheJsonSerializer = class(TInterfacedObject,ICacheSerializer)
private
fJsonSerializer : TJsonSerializer;
public
constructor Create;
destructor Destroy; override;
function Serialize(aObject : TObject) : string; overload;
function Serialize(aArray : TArray<string>) : string; overload;
function Serialize(aArray: TArray<TObject>): string; overload;
procedure Deserialize(const aValue : string; aObject : TObject); overload;
procedure Deserialize(const aValue : string; var aArray : TArray<string>); overload;
procedure Deserialize(const aValue : string; var aArray: TArray<TObject>); overload;
end;
implementation
{ TCacheJsonSerializer }
constructor TCacheJsonSerializer.Create;
begin
fJsonSerializer := TJsonSerializer.Create(TSerializeLevel.slPublicProperty,False);
//fJsonSerializer := TJsonSerializer.Create;
end;
destructor TCacheJsonSerializer.Destroy;
begin
fJsonSerializer.Free;
inherited;
end;
function TCacheJsonSerializer.Serialize(aObject: TObject): string;
begin
Result := fJsonSerializer.ObjectToJson(aObject,False);
//Result := fJsonSerializer.Serialize<TObject>(aObject);
end;
function TCacheJsonSerializer.Serialize(aArray: TArray<string>): string;
begin
Result := fJsonSerializer.ArrayToJson<string>(aArray);
end;
function TCacheJsonSerializer.Serialize(aArray: TArray<TObject>): string;
begin
Result := fJsonSerializer.ArrayToJson<TObject>(aArray);
end;
procedure TCacheJsonSerializer.Deserialize(const aValue: string; aObject: TObject);
begin
fJsonSerializer.JsonToObject(aObject,aValue);
//aObject := fJsonSerializer.Deserialize<TObject>(aValue);
end;
procedure TCacheJsonSerializer.Deserialize(const aValue: string; var aArray: TArray<string>);
begin
aArray := fJsonSerializer.JsonToArray<string>(aValue);
end;
procedure TCacheJsonSerializer.Deserialize(const aValue: string; var aArray: TArray<TObject>);
begin
aArray := fJsonSerializer.JsonToArray<TObject>(aValue);
end;
end.
|
unit Principal;
interface
uses System.Classes;
//-------------COMPONENTE--------------
procedure register;
type
TNotifyEvent = procedure (Sender : TObject) of Object;
TEventos = class(TComponent)
private
FNome: String;
FStatus: TNotifyEvent;
procedure SetNome(const Value: String);
procedure SetStatus(const Value: TNotifyEvent);
public
function TamanhoString(Value : String) : Integer;
procedure OnStatus;
{ PUBLISHED -> Se colocar nessa seção. ao compilar já ira aparecer nas Units }
published
property Nome : String read FNome write SetNome;
property Status : TNotifyEvent read FStatus write SetStatus;
end;
implementation
{ TEventos }
procedure register;
begin
RegisterComponents('DelphiUpdates',[TEventos])
{
Onde DelphiUpdates seria a sessão e TEventos as classes liberadas
Após registrar, botão direito no componente em ProjectManager, Compile e depois Install.. Criar um
novo projeto ou formulário e utilizar o evento de Tool Palette
}
end;
procedure TEventos.OnStatus;
begin
if Assigned(Status) then
Status(Self);
end;
procedure TEventos.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TEventos.SetStatus(const Value: TNotifyEvent);
begin
FStatus := Value;
end;
function TEventos.TamanhoString(Value: String): Integer;
begin
Nome := Value;
Result := Length(Value);
OnStatus;
end;
end.
|
UNIT GraphsUnit ;
INTERFACE
{************* CONSTANTS ******************}
Const
INFINITY = MAXINT; { Use this anywhere you need "infinity" }
MAX = 33;
{ This is the maximum size of graph. You can make this bigger if you want. }
{************* TYPE DEFINITIONS *********************}
Type
{ These type definitions define an adjacency matrix graph representation that stores edge weights. }
GraphSize = 0..MAX;
VertexNumber = 1..MAX;
AdjacencyRow = Array [VertexNumber] of integer;
GraphRep = Array [VertexNumber] of AdjacencyRow;
{ forward declarations }
procedure NewGraph( var G:GraphRep; S:GraphSize);
procedure AddEdge( var G:GraphRep; S:GraphSize; Origin, Terminus: VertexNumber;
Weight: integer );
procedure ShortestPath( var G: GraphRep; S: GraphSize; Origin: VertexNumber;
var ShortestDistance: AdjacencyRow ) ;
procedure DisplayMST(G: GraphRep; S: GraphSize) ;
procedure Show_adj_matrix ( G: graphrep; S: graphsize ) ;
procedure IdentifyMyself;
IMPLEMENTATION
{procedure NewGraph(G,S)
pre: S is the size of graph to create.
post: G should be an adjacency matrix or adjacency list that corresponds to a graph with
S vertices and no edges. If using an adjacency matrix, you must initialize the entire matrix.
HINT: Remember that the distance from a vertex to itself is always 0.}
procedure NewGraph ;
var
i, j: integer ;
begin
for i := 1 to S do
for j := 1 to S do
if i = j then
G[i, j] := 0
else
G[i, j] := INFINITY
end; { proc NewGraph }
{procedure AddEdge(G,S,Origin,Terminus,Weight)
pre: G is a graph representation with S vertices. Origin, Terminus, and Weight
define an edge to be added to G.
post: G has the specified edge added. HINT - you might want to print an error message
if Origin or Terminus are bigger than S.}
procedure AddEdge ;
begin
if ( not ( Origin in [1.. S] ) ) or ( not ( Terminus in [1..S] ) ) then
writeln( 'Error: Origin and Terminus must be in the range 1 to ', S )
else if ( Origin = Terminus ) and ( Weight <> 0 ) then
writeln( 'Error: the distance from a vertex to itself is always 0. ' )
else
G[Origin][Terminus] := Weight
end; { proc AddEdge }
{procedure ShortestPath(G,S,Origin,ShortestDistance)
pre: G is a graph representation with S vertices. Origin is the start vertex.
post: ShortestDistance is an array containing the shortest distances from Origin to each vertex.
HINT - program strategy 10.16 uses set variables. This is possible in Pascal, but you can't really
use them the way you need to here. I suggest implementing the set W as an array
of booleans. Initialize them all to FALSE and then each time you want to put a new
vertex in the set, change the corresponding value to TRUE. You also might want to
keep a count of the number of vertices in W.
HINT - Watch out for the two "W" variables in 10.16. They use a big W and a small w.
You can't do that in Pascal. I suggest using "w" for the small one and "BigW" for
the big one. Of course you are free to use whatever variable names you want, but
the closer you stick to the book, the easier it will be to mark.
HINT - Comment this well! }
procedure ShortestPath ;
var
Edges: GraphRep ;
ans: string[13] ;
V, BigW : set of GraphSize ;
MinDistance : integer ;
w, i, j, k, l : VertexNumber ;
begin
NewGraph(Edges, S) ;
V := [1..S] ;
BigW := [Origin] ;
for i := 1 to S do
BEGIN
ShortestDistance[i] := G[Origin, i] ;
if ( G[Origin, i] <> 0 ) and ( G[Origin, i] <> INFINITY ) then AddEdge(Edges, S, Origin, i, 1)
END ; { for }
while BigW <> V do
BEGIN
MinDistance := INFINITY ;
for j := 1 to S do
if ( j in ( V - BigW ) ) and ( ShortestDistance[j] <= MinDistance ) then
BEGIN
MinDistance := ShortestDistance[j] ;
w := j
END ;
BigW := BigW + [w] ;
for k := 1 to S do
if ( k in ( V - BigW ) ) and ( G[w, k] <> INFINITY ) then
if ( ShortestDistance[w] + G[w, k] ) < ( ShortestDistance[k] ) then
BEGIN
ShortestDistance[k] := ( ShortestDistance[w] + G[w, k] ) ;
for l := 1 to S do
if ( l <> k ) then AddEdge(Edges, S, l, k, INFINITY) ;
AddEdge(Edges, S, w, k, 1)
END { if }
END; { while }
writeln ;
write('Would you like to see the adjacency matrix for the shortest paths (y/n)? ' );
readln(ans); writeln;
if (ans[1] in ['y', 'Y'] ) then
Show_adj_matrix ( Edges, S ) ;
end; { proc ShortestPath }
procedure Calc_min_span(G: GraphRep; S: GraphSize; var SpanTree: GraphRep; Start: VertexNumber) ;
var
V, W: set of GraphSize ;
Min, i, j, i2, j2 : integer ;
begin
V := [1..S] ;
W := [Start] ;
while (W <> V) do
BEGIN
Min := INFINITY ;
for i := 1 to S do if (i in W) then
for j := 1 to S do if (j in (V - W)) and (G[i, j] <= Min) then
BEGIN
Min := G[i, j] ;
i2 := i ;
j2 := j ;
END; { for }
AddEdge(SpanTree, S, i2, j2, Min) ;
W := W + [j2]
END; { while }
end; { proc Calc_min_span }
procedure Convert_undirected( var U: graphrep; S: graphsize ) ;
var
i, j : integer ;
begin
for i := 1 to S do
for j := i to S do if i <> j then
BEGIN
if U[j, i] = INFINITY then
U[j, i] := U[i, j]
else if U[i, j] = INFINITY then
U[i, j] := U[j, i]
else
BEGIN
U[j, i] := ( U[i, j] + U[j, i] ) div 2 ;
U[i, j] := U[j, i]
END { else }
END { for }
end; { proc convert_undirected }
procedure Show_adj_matrix ( G: graphrep; S: graphsize ) ;
var
row, col : integer ;
begin
writeln ;
for row := 1 to S do
BEGIN
for col := 1 to S do
if G[row,col] = INFINITY then
write (' INF')
else
write (G[row,col]:5) ;
writeln
END; { for }
writeln;
end; { proc show_adj_matrix }
procedure DisplayMST ( G: GraphRep; S: GraphSize ) ;
var
SpanTree, U, Umin: GraphRep ;
Start, Ustart: VertexNumber ;
ans : string[13] ;
begin
NewGraph(SpanTree, S) ;
repeat
write('Choose a starting vertex (1 to ', S, '): ') ;
readln(Start) ;
until Start in [1..S] ;
Calc_min_span(G, S, SpanTree, Start) ;
writeln ('Here is Prim''s algorithm run against the directed graph: ' ) ;
Show_adj_matrix ( SpanTree, S ) ;
writeln ;
write('Would you like to see the MST for the undirected version of this graph (y/n) ? ' ) ;
readln(ans) ;
if (ans[1] in ['y', 'Y'] ) then
BEGIN
U := G ;
Convert_undirected ( U, S ) ;
writeln ( 'Here is the adjacency matrix for the undirected graph: ' ) ;
Show_adj_matrix ( U, S ) ;
repeat
write('Choose a starting vertex (1 to ', S, ') for the MST of the undirected graph: ') ;
readln(Ustart) ;
until Ustart in [1..S] ;
NewGraph(Umin, S) ;
Calc_min_span(U, S, Umin, Ustart) ;
writeln ( 'Here is the adjacency matrix for the MST of the undirected graph: ' ) ;
Show_adj_matrix ( Umin, S ) ;
END { if }
end; { proc DisplayMST }
(**************************** IDENTIFICATION **************************)
(* Change this procedure to identify yourself *)
procedure IdentifyMyself;
begin
writeln;
writeln('***** Student Name: Mark Sattolo');
writeln('***** Student Number: 428500');
writeln('***** Professor Name: Sam Scott');
writeln('***** Course Number: CSI-2114D');
writeln('***** T.A. Name: Adam Murray');
writeln('***** Tutorial Number: D-1');
writeln;
end;
end. |
unit __form__;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.CustomizeDlg, Vcl.ExtCtrls, task_1,
WebAdapt, WebComp, Data.DB, Bde.DBTables, Vcl.StdCtrls, Vcl.Grids, Wizard1, System.Generics.Collections;
type
SomeArr<T> = array of T;
type
TMainView = class(TForm)
PushOnGrid: TButton;
Goods: TStringGrid;
LinkLabel1: TLinkLabel;
LinkLabel2: TLinkLabel;
LinkLabel3: TLinkLabel;
export_to_json: TButton;
SaveDialog1: TSaveDialog;
procedure _save_diolog_logic;
procedure PushOnGridClick(Sender: TObject);
procedure PushNewItemInGoods(item: TGoods);
procedure export_to_jsonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure export_goods_to_json(fPath: String);
procedure GoodsClick(Sender: TObject);
private
goods_items: TArray<TGoods>;
public
end;
procedure grid_remove_row(grid: TStringGrid; RowIndex: Integer);
procedure array_remove_by_index(var arr: TArray<TGoods>; index: Integer);
var
MainView: TMainView;
implementation
{$R *.dfm}
uses System.RegularExpressions;
procedure array_remove_by_index(var arr: TArray<TGoods>; index: Integer);
var i: Integer;
begin
for i := index+1 to Length(arr) - 1 do
arr[i-1] := arr[i];
SetLength(arr, Length(arr)-1);
end;
procedure TMainView.export_goods_to_json(fPath: String);
var _file: TextFile;
content: String;
i: Integer;
re: TRegEx;
begin
content := '[';
re := TRegEx.Create(',$');
AssignFile(_file, fPath);
Rewrite(_file);
for I := 0 to Length(self.goods_items)-1 do
begin
if self.goods_items[i] is TBook then
content := content + '{' + (self.goods_items[i] as TBook).stringfy + '},';
if self.goods_items[i] is TMagazine then
content := content + '{' + (self.goods_items[i] as TMagazine).stringfy + '},';
end;
write(_file, re.Replace(content, '')+ ']');
CloseFile(_file);
end;
procedure TMainView.export_to_jsonClick(Sender: TObject);
begin
if Length(self.goods_items) = 0 then
begin MessageBox(handle, PChar('Table is empty...'), PChar('Info'), MB_OK); end
else
begin
self._save_diolog_logic;
end;
end;
procedure TMainView._save_diolog_logic;
var
fPath: String;
re: TRegEx;
begin
re := TRegEx.Create('\.json$');
if self.SaveDialog1.Execute(handle) then
begin fPath := self.SaveDialog1.FileName;
if re.Match(fPath).Length = 0 then fPath := fPath + '.json';
if FileExists(fPath) then
begin if MessageDlg('File exists, reWrite?', mtConfirmation, [mbYes, mbNo], 0) = mrNo
then self._save_diolog_logic;
end;
self.export_goods_to_json(fPath);
end;
end;
procedure TMainView.FormCreate(Sender: TObject);
begin
self.SaveDialog1.Filter := 'JSON files (*.json)|*.JSON';
end;
procedure TMainView.GoodsClick(Sender: TObject);
var RowIndex: Integer;
grid: TStringGrid;
i: Integer;
begin
grid := Sender As TStringGrid;
RowIndex := grid.Row;
if (Length(self.goods_items) > 0) and
(MessageDlg('Remove Item?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
begin
grid_remove_row(grid, RowIndex);
array_remove_by_index(self.goods_items, RowIndex);
end;
end;
procedure TMainView.PushNewItemInGoods(item: TGoods);
var row: Integer;
begin
row := Length(self.goods_items);
self.Goods.RowCount := row + 1;
SetLength(self.goods_items, Length(self.goods_items)+1);
self.goods_items[High(self.goods_items)] := item;
self.Goods.Cells[0, row] := item.Name;
self.Goods.Cells[1, row] := IntTostr(item.Price);
self.Goods.Cells[2, row] := item.Description;
end;
procedure TMainView.PushOnGridClick(Sender: TObject);
var row: Integer;
begin
Push_Item_Wizard.Show(self, self.PushNewItemInGoods);
end;
procedure grid_remove_row(grid: TStringGrid; RowIndex: Integer);
var i: Integer;
begin
for i := RowIndex to grid.RowCount-2 do
grid.Rows[i].Assign(grid.Rows[i+1]);
grid.Rows[grid.RowCount-1].Clear;
grid.RowCount := grid.RowCount -1;
end;
end.
|
unit ufmMain;
interface
uses
{ EnterCriticalSection }
Winapi.Windows,
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls,
System.Generics.Collections,
{ IViewControl }
uIViews;
type
TfmMain = class(TForm, IViewControl)
scrollBoxImages: TScrollBox;
btnLoadImagesFromFolder: TButton;
btnFreeImages: TButton;
lblLoadingImagesProgress: TLabel;
lblThreadsCompleted: TLabel;
btnStopLoading: TButton;
memHelp: TMemo;
procedure btnLoadImagesFromFolderClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnFreeImagesClick(Sender: TObject);
procedure btnStopLoadingClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
{$REGION 'Implements interface "IViewControl" '}
procedure CreateControls;
procedure UpdateImage(ABitmap: TBitmap);
procedure ImageThreadComleted(const AThread: TThread);
procedure UpdateLoadProgress(AValue: Integer);
function GetImageViewsControl: TWinControl;
{$ENDREGION}
procedure EnDsControls(AStatus: Boolean);
public
end;
var
fmMain: TfmMain;
implementation
uses
{ CriticalSection }
uCore.CriticalSection,
uConsts,
{ TaskImages }
uTask.Images,
{ WM_VSCROLL }
Winapi.Messages;
{$R *.dfm}
procedure TfmMain.btnLoadImagesFromFolderClick(Sender: TObject);
begin
EnDsControls(False);
TaskImages.LoadAndDisplayImages('F:\Pictures\My Photos\Y2016', CONST_FILE_TYPES);
end;
procedure TfmMain.btnStopLoadingClick(Sender: TObject);
begin
TaskImages.StopTasks;
end;
procedure TfmMain.btnFreeImagesClick(Sender: TObject);
begin
TaskImages.FreeImages;
end;
procedure TfmMain.EnDsControls(AStatus: Boolean);
begin
btnLoadImagesFromFolder.Enabled := AStatus;
btnFreeImages.Enabled := AStatus;
end;
procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TaskImages.StopTasks;
with CriticalSection do
if FImagesThreadPool.LockList.Count > 0 then
begin
Action := caNone;
EnterCriticalSection(Section);
try
FPostponedCloseOnceAllTaskCompleted := True;
finally
LeaveCriticalSection(Section);
end;
end;
end;
procedure TfmMain.FormDestroy(Sender: TObject);
begin
TaskImages.FreeImages;
end;
procedure TfmMain.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
const
CONST_SCROLL_LINES = 2;
var
I, J: Integer;
LScrollBox: TScrollBox;
LControl: TWinControl;
begin
LControl := FindVCLWindow(Mouse.CursorPos);
Handled := LControl is TScrollBox;
if not Handled then
Exit;
LScrollBox := LControl as TScrollBox;
for I := 1 to Mouse.WheelScrollLines do
try
for J := 1 to CONST_SCROLL_LINES do
if WheelDelta > 0 then
LScrollBox.Perform(WM_VSCROLL, SB_LINEUP, 0)
else
LScrollBox.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
finally
LScrollBox.Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
end;
end;
{$REGION 'Implements interface "IViewControl" '}
procedure TfmMain.CreateControls;
begin
end;
procedure TfmMain.UpdateImage(ABitmap: TBitmap);
begin
with CriticalSection do
begin
EnterCriticalSection(Section);
try
if FImages.Count > 0 then
begin
FImages[FDisplayIndex].Picture.Assign(ABitmap);
Inc(FDisplayIndex);
end;
finally
LeaveCriticalSection(Section);
end;
end;
end;
procedure TfmMain.ImageThreadComleted(const AThread: TThread);
function FormatProgressLabel(AValue: Integer): String;
begin
Result := Format('There are %d images loaded', [AValue]);
end;
var
LFileName: String;
LIndex: Integer;
LActionRequired: Boolean;
LPostponedCloseOnceAllTaskCompleted: Boolean;
LThreadsCompleted: Integer;
begin
{ Remove thread from pool list }
LIndex := CriticalSection.FImagesThreadPool.LockList.IndexOf(AThread);
if LIndex = -1 then
Exit;
CriticalSection.FImagesThreadPool.LockList.Remove(
CriticalSection.FImagesThreadPool.LockList.Items[LIndex]);
if CriticalSection.FImagesThreadPool.LockList.Count = 0 then
EnDsControls(True);
EnterCriticalSection(CriticalSection.Section);
try
LPostponedCloseOnceAllTaskCompleted :=
CriticalSection.FPostponedCloseOnceAllTaskCompleted;
finally
LeaveCriticalSection(CriticalSection.Section);
end;
if LPostponedCloseOnceAllTaskCompleted then
Close;
{ Should we run next thread? }
EnterCriticalSection(CriticalSection.Section);
try
LActionRequired :=
(CriticalSection.FImagesThreadPool.LockList.Count < CONST_MAX_THREADS)
and (CriticalSection.FPendingFiles.Count > 0);
Inc(CriticalSection.FThreadsCompleted);
LThreadsCompleted := CriticalSection.FThreadsCompleted;
finally
LeaveCriticalSection(CriticalSection.Section);
end;
{ GUI }
lblThreadsCompleted.Caption := FormatProgressLabel(LThreadsCompleted);
if not LActionRequired then
Exit;
with CriticalSection do
begin
EnterCriticalSection(CriticalSection.Section);
try
LFileName := FPendingFiles[FPendingFiles.Count - 1];
FPendingFiles.Delete(FPendingFiles.Count - 1);
finally
LeaveCriticalSection(Section);
end;
end;
{ Run next thread }
TaskImages.RunImageViewThread(LFileName, tpLowest);
end;
procedure TfmMain.UpdateLoadProgress(AValue: Integer);
begin
lblLoadingImagesProgress.Caption := Format('There are %d images in folder',
[AValue])
end;
function TfmMain.GetImageViewsControl: TWinControl;
begin
Result := scrollBoxImages;
end;
{$ENDREGION}
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 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 ADLoginResourceU;
// EMS Resource Unit
interface
uses
System.SysUtils, System.Classes, System.JSON, EMS.Services, EMS.ResourceAPI,
EMS.ResourceTypes;
type
{$METHODINFO ON}
/// <summary>
/// This class is a custom resource for the EMS server. It provides the
/// connectivity to the active directory (AD).
/// </summary>
[ResourceName('ADLogin')]
TCustomLogonResource = class(TObject)
strict private const
cCommentField = 'comment';
cLocalServer = 'localhost';
cMasterPassword = 'AdEmsPwd#01';
strict private
/// <summary>
/// This method validates the username and the password. It checks if it
/// is possible to connect to the AD with this credentials. If there is
/// no username or password, or if it is not possible to connect to the AD
/// it raises an Unauthorized (401) error.
/// </summary>
procedure ValidateCredentials(const ARequest: TEndpointRequest; const AResponse: TEndpointResponse); overload;
/// <summary>
/// This method validates the username and the password. It checks if it
/// is possible to connect to the AD with this credentials. If there is
/// no username or password, or if it is not possible to connect to the AD
/// it raises an Unauthorized (401) error.
/// The username and password are returned.
/// </summary>
procedure ValidateCredentials(const ARequest: TEndpointRequest; const AResponse: TEndpointResponse; out AUserName, APassword: string); overload;
/// <summary>
/// This method returns internal password, which will be provided
/// to EMS instead of real AD end user password. This is required for
/// importing AD users when an AD user password is unknown, to avoid
/// need to sync AD and EMS password, and to avoid EMS users login
/// without AD autorization.
/// The internal password is returned.
/// </summary>
function GetIntPassword(const AUserName: string): string;
public
/// <summary>
/// This method deletes all EMS users that are not AD users. It is also
/// possible to add an optional group. This means that all EMS users are
/// deleted that are not member of the group. Be careful to call this.
/// Before the deletion happens the credential are checked with
/// ValidateCredentials. This means that the user and password are tested
/// towards the AD.
/// </summary>
[EndpointName('CustomDeleteUsers')]
[ResourceSuffix('deleteusers')]
procedure PostDeleteUsers(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
/// <summary>
/// This method enumerates all AD groups. Before the enumeration happens
/// the credential are checked with ValidateCredentials. This means that
/// the user and password are tested towards the AD.
/// </summary>
[EndpointName('CustomEnumGroups')]
[ResourceSuffix('enumgroups')]
procedure PostEnumGroups(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
/// <summary>
/// This method enumerates all AD users. Optionally you can add a group
/// so that you will get all AD users of the AD group. Before the
/// enumeration happens the credential are checked with ValidateCredentials.
/// This means that the user and password are tested towards the AD.
/// </summary>
[EndpointName('CustomEnumUsers')]
[ResourceSuffix('enumusers')]
procedure PostEnumUsers(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
/// <summary>
/// This method imports all AD users into the EMS. If an EMS user already
/// exists nothing happens. That's why you can call this method several
/// times. It is also possible to add an optional group. Then only the AD
/// users of the AD group are imported. Before the deletion happens the
/// credential are checked with ValidateCredentials. This means that the
/// user and password are tested towards the AD.
/// </summary>
[EndpointName('CustomImport')]
[ResourceSuffix('import')]
procedure PostImport(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
/// <summary>
/// This method replaces the normal login towards the EMS systems with an
/// login towards the AD.
/// </summary>
[EndpointName('CustomLoginUser')]
// Declare endpoint that matches signature of Users.LoginUser
[ResourceSuffix('login')]
procedure PostLogin(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
/// <summary>
/// This method checks the credentials versus the AD and then signs the
/// user into the EMS system. It replaces the normal signup towards the
/// EMS system.
/// </summary>
[EndpointName('CustomSignupUser')]
// Declare endpoint that matches signature of Users.SignupUser
[ResourceSuffix('signup')]
procedure PostSignup(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
end;
{$METHODINFO OFF}
procedure Register;
implementation
uses
System.Generics.Collections, System.Hash, EMS.AD.Classes;
resourcestring
SMissingCredentials = 'Missing credentials';
SCustomAdded = 'This user added by CustomResource.CustomSignupUser';
procedure Register;
begin
RegisterResource(TypeInfo(TCustomLogonResource));
end;
{ TCustomLogonResource }
procedure TCustomLogonResource.ValidateCredentials(const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lUserName: string;
lPassword: string;
begin
ValidateCredentials(ARequest, AResponse, lUserName, lPassword);
end;
procedure TCustomLogonResource.ValidateCredentials(const ARequest: TEndpointRequest; const AResponse: TEndpointResponse; out AUserName, APassword: string);
var
bCredentials: Boolean;
lValue: TJSONValue;
lError: string;
begin
AUserName := '';
APassword := '';
bCredentials := ARequest.Body.TryGetValue(lValue) and
lValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.UserName, AUserName) and
lValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.Password, APassword);
if not bCredentials then
AResponse.RaiseUnauthorized('', SMissingCredentials)
else if not TEnumAD.CredentialsValid('', AUserName, APassword, lError) then
AResponse.RaiseUnauthorized('', lError);
APassword := GetIntPassword(AUserName);
end;
function TCustomLogonResource.GetIntPassword(const AUserName: string): string;
begin
Result := THashMD5.GetHashString(cMasterPassword + AUserName);
end;
procedure TCustomLogonResource.PostDeleteUsers(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lEMSAPI: TEMSInternalAPI;
lValue: TJSONValue;
lResponse: TJSONObject;
lGroup: string;
lContent: IEMSResourceResponseContent;
lParams: TEMSResourceRequestQueryParams;
lADUsers: TDictionary<string, string>;
lUserId: string;
lUser: string;
lBuffer: string;
lArray: TJSONArray;
begin
ValidateCredentials(ARequest, AResponse);
lResponse := nil;
lADUsers := nil;
lEMSAPI := TEMSInternalAPI.Create(AContext);
try
lValue := ARequest.Body.GetValue;
lADUsers := TDictionary<string, string>.Create;
if not lValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.GroupName, lGroup) then
TEnumAD.EnumUsers(cLocalServer,
procedure(AUserName: string)
begin
lADUsers.Add(AUserName, AUserName);
end)
else
TEnumAD.EnumUsersOfAGroup(cLocalServer, lGroup,
procedure(AUserName: string)
begin
lADUsers.Add(AUserName, AUserName);
end);
lResponse := TJSONObject.Create;
lContent := lEMSAPI.QueryUsers(lParams);
if lContent.TryGetValue(lValue) then
begin
lArray := lValue as TJSONArray;
for lValue in lArray do
begin
lUserId := lValue.GetValue<string>(TEMSInternalAPI.TJSONNames.UserID);
lUser := lValue.GetValue<string>(TEMSInternalAPI.TJSONNames.UserName);
if not lADUsers.TryGetValue(lUser, lBuffer) then
begin
lEMSAPI.DeleteUser(lUserId);
lResponse.AddPair(lUser, lUser);
end;
end;
end;
AResponse.Body.SetValue(lResponse, False);
finally
lResponse.Free;
lADUsers.Free;
lEMSAPI.Free;
end;
end;
procedure TCustomLogonResource.PostEnumGroups(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lGroupName: string;
lGroups: TStrings;
lResponse: TJSONObject;
begin
ValidateCredentials(ARequest, AResponse);
lResponse := nil;
lGroups := TStringList.Create;
try
TEnumAD.EnumGroups(cLocalServer, lGroups);
lResponse := TJSONObject.Create;
for lGroupName in lGroups do
lResponse.AddPair(lGroupName, lGroupName);
AResponse.Body.SetValue(lResponse, False);
finally
lGroups.Free;
lResponse.Free;
end;
end;
procedure TCustomLogonResource.PostEnumUsers(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lUserName: string;
lUsers: TStrings;
lResponse: TJSONObject;
lValue: TJSONValue;
lGroup: string;
begin
ValidateCredentials(ARequest, AResponse);
lResponse := nil;
lUsers := TStringList.Create;
try
lValue := ARequest.Body.GetValue;
if not lValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.GroupName, lGroup) then
TEnumAD.EnumUsers(cLocalServer, lUsers)
else
TEnumAD.EnumUsersOfAGroup(cLocalServer, lGroup, lUsers);
lResponse := TJSONObject.Create;
for lUserName in lUsers do
lResponse.AddPair(lUserName, lUserName);
AResponse.Body.SetValue(lResponse, False);
finally
lUsers.Free;
lResponse.Free;
end;
end;
procedure TCustomLogonResource.PostImport(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lEMSAPI: TEMSInternalAPI;
lUserName: string;
lUserFields: TJSONObject;
lUsers: TStrings;
lValue: TJSONValue;
lResponse: TJSONObject;
lGroup: string;
begin
ValidateCredentials(ARequest, AResponse);
lResponse := nil;
lUserFields := nil;
lUsers := nil;
lEMSAPI := TEMSInternalAPI.Create(AContext);
try
lValue := ARequest.Body.GetValue;
lUsers := TStringList.Create;
if not lValue.TryGetValue<string>(TEMSInternalAPI.TJSONNames.GroupName, lGroup) then
TEnumAD.EnumUsers(cLocalServer, lUsers)
else
TEnumAD.EnumUsersOfAGroup(cLocalServer, lGroup, lUsers);
lUserFields := TJSONObject.Create;
lUserFields.AddPair(cCommentField, SCustomAdded);
lResponse := TJSONObject.Create;
for lUserName in lUsers do
begin
if not lEMSAPI.QueryUserName(lUserName) then
begin
lEMSAPI.SignupUser(lUserName, GetIntPassword(lUserName), lUserFields);
lResponse.AddPair(lUserName, lUserName);
end;
end;
AResponse.Body.SetValue(lResponse, False);
finally
lResponse.Free;
lUsers.Free;
lUserFields.Free;
lEMSAPI.Free;
end;
end;
procedure TCustomLogonResource.PostLogin(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lEMSAPI: TEMSInternalAPI;
lResponse: IEMSResourceResponseContent;
lValue: TJSONValue;
lUserName: string;
lPassword: string;
begin
ValidateCredentials(ARequest, AResponse, lUserName, lPassword);
lEMSAPI := TEMSInternalAPI.Create(AContext);
try
// Uncomment to automatically create an EMS user if the AD credentials are valid,
// but EMS user does not exist. Otherwise, EMS will raise a not-found exception
// if an EMS user has not already been signed up.
{
if not lEMSAPI.QueryUserName(lUserName) then
PostSignup(AContext, ARequest, AResponse);
}
lResponse := lEMSAPI.LoginUser(lUserName, lPassword);
if lResponse.TryGetValue(lValue) then
AResponse.Body.SetValue(lValue, False);
finally
lEMSAPI.Free;
end;
end;
procedure TCustomLogonResource.PostSignup(const AContext: TEndpointContext; const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
var
lEMSAPI: TEMSInternalAPI;
lResponse: IEMSResourceResponseContent;
lValue: TJSONObject;
lUserName: string;
lPassword: string;
lUserFields: TJSONObject;
begin
ValidateCredentials(ARequest, AResponse, lUserName, lPassword);
lEMSAPI := TEMSInternalAPI.Create(AContext);
try
lValue := ARequest.Body.GetObject;
lUserFields := lValue.Clone as TJSONObject;
try
// Remove meta data
lUserFields.RemovePair(TEMSInternalAPI.TJSONNames.UserName).Free;
lUserFields.RemovePair(TEMSInternalAPI.TJSONNames.Password).Free;
// Add another field, for example
lUserFields.AddPair(cCommentField, SCustomAdded);
// in-process call to actual Users/Signup endpoint
lResponse := lEMSAPI.SignupUser(lUserName, lPassword, lUserFields)
finally
lUserFields.Free;
end;
if lResponse.TryGetObject(lValue) then
AResponse.Body.SetValue(lValue, False);
finally
lEMSAPI.Free;
end;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StAstro.pas 4.04 *}
{*********************************************************}
{* SysTools: Astronomical Routines *}
{*********************************************************}
{$I StDefine.inc}
{ ************************************************************** }
{ Sources: }
{ 1. Astronomical Algorithms, Jean Meeus, Willmann-Bell, 1991. }
{ }
{ 2. Planetary and Lunar Coordinates (1984-2000), U.S. Govt, }
{ 1983. }
{ }
{ 3. Supplement to the American Ephemeris and Nautical Almanac,}
{ U.S. Govt, 1964. }
{ }
{ 4. MPO96 source files, Brian D. Warner, 1995. }
{ }
{ ************************************************************** }
unit StAstro;
interface
uses
Windows, SysUtils,
StConst, StBase, StDate, StStrL, StDateSt, StMath;
type
TStTwilight = (ttCivil, ttNautical, ttAstronomical);
TStRiseSetRec = record
ORise : TStTime;
OSet : TStTime;
end;
TStPosRec = record
RA,
DC : Double;
end;
TStPosRecArray = array[1..3] of TStPosRec;
TStSunXYZRec = record
SunX,
SunY,
SunZ,
RV,
SLong,
SLat : Double;
end;
TStLunarRecord = record
T : array[0..1] of TStDateTimeRec;
end;
TStPhaseRecord = packed record
NMDate,
FQDate,
FMDate,
LQDate : Double;
end;
TStPhaseArray = array[0..13] of TStPhaseRecord;
TStDLSDateRec = record
Starts : TStDate;
Ends : TStDate;
end;
TStMoonPosRec = record
RA,
DC,
Phase,
Dia,
Plx,
Elong : Double;
end;
const
radcor = 57.29577951308232; {number of degrees in a radian}
StdDate = 2451545.0; {Ast. Julian Date for J2000 Epoch}
OB2000 = 0.409092804; {J2000 obliquity of the ecliptic (radians)}
{Sun procedures/functions}
function AmountOfSunlight(LD : TStDate; Longitude, Latitude : Double) : TStTime;
{-compute the hours, min, sec of sunlight on a given date}
function FixedRiseSet(LD : TStDate; RA, DC, Longitude, Latitude : Double) : TStRiseSetRec;
{-compute the rise and set time for a fixed object, e.g., a star}
function SunPos(UT : TStDateTimeRec) : TStPosRec;
{-compute the J2000 RA/Declination of the Sun}
function SunPosPrim(UT : TStDateTimeRec) : TStSunXYZRec;
{-compute the J2000 geocentric rectangular & ecliptic coordinates of the sun}
function SunRiseSet(LD : TStDate; Longitude, Latitude : Double) : TStRiseSetRec;
{-compute the Sun rise or set time}
function Twilight(LD : TStDate; Longitude, Latitude : Double; TwiType : TStTwilight) : TStRiseSetRec;
{-compute the beginning and end of twilight (civil, nautical, or astron.)}
{Lunar procedures/functions}
function LunarPhase(UT : TStDateTimeRec) : Double;
{-compute the phase of the moon}
function MoonPos(UT : TStDateTimeRec) : TStMoonPosRec;
{-compute the J2000 RA/Declination of the moon}
function MoonRiseSet(LD : TStDate; Longitude, Latitude : Double) : TStRiseSetRec;
{-compute the Moon rise and set time}
function FirstQuarter(D : TStDate) : TStLunarRecord;
{-compute date/time of FirstQuarter(s)}
function FullMoon(D : TStDate) : TStLunarRecord;
{-compute the date/time of FullMoon(s)}
function LastQuarter(D : TStDate) : TStLunarRecord;
{-compute the date/time of LastQuarter(s)}
function NewMoon(D : TStDate) : TStLunarRecord;
{-compute the date/time of NewMoon(s)}
function NextFirstQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest FirstQuarter}
function NextFullMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest FullMoon}
function NextLastQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest LastQuarter}
function NextNewMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest NewMoon}
function PrevFirstQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest FirstQuarter}
function PrevFullMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest FullMoon}
function PrevLastQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest LastQuarter}
function PrevNewMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest NewMoon}
{Calendar procedures/functions}
function SiderealTime(UT : TStDateTimeRec) : Double;
{-compute Sidereal Time at Greenwich}
function Solstice(Y, Epoch : Integer; Summer : Boolean) : TStDateTimeRec;
{-compute the date/time of the summer or winter solstice}
function Equinox(Y, Epoch : Integer; Vernal : Boolean) : TStDateTimeRec;
{-compute the date/time of the vernal/autumnal equinox}
function Easter(Y, Epoch : Integer) : TStDate;
{-compute the date of Easter (astronmical calendar)}
{Astronomical Julian Date Conversions}
function DateTimeToAJD(D : TDateTime) : Double;
{Conversion routines}
function HoursMin(RA : Double) : String;
{-convert RA to hh:mm:ss string}
function DegsMin(DC : Double) : String;
{-convert Declination to +/-dd:mm:ss string}
function AJDToDateTime(D : Double) : TDateTime;
implementation
var
AJDOffset : Double;
function CheckDate(UT : TStDateTimeRec) : Boolean;
begin
with UT do begin
if (D < MinDate) or (D > MaxDate) or
(T < 0) or (T > MaxTime) then
Result := False
else
Result := True;
end;
end;
function CheckYear(Y, Epoch : Integer) : Integer;
begin
if Y < 100 then begin
if Y >= (Epoch mod 100) then
Result := ((Epoch div 100) * 100) + Y
else
Result := ((Epoch div 100) * 100) + 100 + Y;
end else
Result := Y;
end;
function SiderealTime(UT : TStDateTimeRec) : Double;
{-compute Sidereal Time at Greenwich in degrees}
var
T,
JD : Double;
begin
if not CheckDate(UT) then begin
Result := -1;
Exit;
end;
JD := AstJulianDate(UT.D) + UT.T/86400;
T := (JD - 2451545.0) / 36525.0;
Result := 280.46061837
+ 360.98564736629 * (JD - 2451545.0)
+ 0.000387933 * sqr(T)
- (sqr(T) * T / 38710000);
Result := Frac(Result/360.0) * 360.0;
if Result < 0 then
Result := 360 + Result;
end;
function SunPosPrim(UT : TStDateTimeRec) : TStSunXYZRec;
{-compute J2000 XYZ coordinates of the Sun}
var
JD,
T0,
A,
L,
B,
X,Y,Z : Double;
begin
if not CheckDate(UT) then begin
with Result do begin
SunX := -99;
SunY := -99;
SunZ := -99;
RV := -99;
SLong := -99;
SLat := -99;
end;
Exit;
end;
JD := AstJulianDate(UT.D) + UT.T/86400;
T0 := (JD - StdDate) / 365250;
{solar longitude}
L := 175347046
+ 3341656 * cos(4.6692568 + 6283.07585*T0)
+ 34894 * cos(4.6261000 + 12566.1517*T0)
+ 3497 * cos(2.7441000 + 5753.3849*T0)
+ 3418 * cos(2.8289000 + 3.5231*T0)
+ 3136 * cos(3.6277000 + 77713.7715*T0)
+ 2676 * cos(4.4181000 + 7860.4194*T0)
+ 2343 * cos(6.1352000 + 3930.2097*T0)
+ 1324 * cos(0.7425000 + 11506.7698*T0)
+ 1273 * cos(2.0371000 + 529.6910*T0)
+ 1199 * cos(1.1096000 + 1577.3435*T0)
+ 990 * cos(5.2330000 + 5884.9270*T0)
+ 902 * cos(2.0450000 + 26.1490*T0)
+ 857 * cos(3.5080000 + 398.149*T0)
+ 780 * cos(1.1790000 + 5223.694*T0)
+ 753 * cos(2.5330000 + 5507.553*T0)
+ 505 * cos(4.5830000 + 18849.228*T0)
+ 492 * cos(4.2050000 + 775.523*T0)
+ 357 * cos(2.9200000 + 0.067*T0)
+ 317 * cos(5.8490000 + 11790.626*T0)
+ 284 * cos(1.8990000 + 796.298*T0)
+ 271 * cos(0.3150000 + 10977.079*T0)
+ 243 * cos(0.3450000 + 5486.778*T0)
+ 206 * cos(4.8060000 + 2544.314*T0)
+ 205 * cos(1.8690000 + 5573.143*T0)
+ 202 * cos(2.4580000 + 6069.777*T0)
+ 156 * cos(0.8330000 + 213.299*T0)
+ 132 * cos(3.4110000 + 2942.463*T0)
+ 126 * cos(1.0830000 + 20.775*T0)
+ 115 * cos(0.6450000 + 0.980*T0)
+ 103 * cos(0.6360000 + 4694.003*T0)
+ 102 * cos(0.9760000 + 15720.839*T0)
+ 102 * cos(4.2670000 + 7.114*T0)
+ 99 * cos(6.2100000 + 2146.170*T0)
+ 98 * cos(0.6800000 + 155.420*T0)
+ 86 * cos(5.9800000 +161000.690*T0)
+ 85 * cos(1.3000000 + 6275.960*T0)
+ 85 * cos(3.6700000 + 71430.700*T0)
+ 80 * cos(1.8100000 + 17260.150*T0);
A := 628307584999.0
+ 206059 * cos(2.678235 + 6283.07585*T0)
+ 4303 * cos(2.635100 + 12566.1517*T0)
+ 425 * cos(1.590000 + 3.523*T0)
+ 119 * cos(5.796000 + 26.298*T0)
+ 109 * cos(2.966000 + 1577.344*T0)
+ 93 * cos(2.590000 + 18849.23*T0)
+ 72 * cos(1.140000 + 529.69*T0)
+ 68 * cos(1.870000 + 398.15*T0)
+ 67 * cos(4.410000 + 5507.55*T0)
+ 59 * cos(2.890000 + 5223.69*T0)
+ 56 * cos(2.170000 + 155.42*T0)
+ 45 * cos(0.400000 + 796.30*T0)
+ 36 * cos(0.470000 + 775.52*T0)
+ 29 * cos(2.650000 + 7.11*T0)
+ 21 * cos(5.340000 + 0.98*T0)
+ 19 * cos(1.850000 + 5486.78*T0)
+ 19 * cos(4.970000 + 213.30*T0)
+ 17 * cos(2.990000 + 6275.96*T0)
+ 16 * cos(0.030000 + 2544.31*T0);
L := L + (A * T0);
A := 8722 * cos(1.0725 + 6283.0758*T0)
+ 991 * cos(3.1416)
+ 295 * cos(0.437 + 12566.1520*T0)
+ 27 * cos(0.050 + 3.52*T0)
+ 16 * cos(5.190 + 26.30*T0)
+ 16 * cos(3.69 + 155.42*T0)
+ 9 * cos(0.30 + 18849.23*T0)
+ 9 * cos(2.06 + 77713.77*T0);
L := L + (A * sqr(T0));
A := 289 * cos(5.842 + 6283.076*T0)
+ 21 * cos(6.05 + 12566.15*T0)
+ 3 * cos(5.20 + 155.42*T0)
+ 3 * cos(3.14);
L := L + (A * sqr(T0) * T0);
L := L / 1.0E+8;
{solar latitude}
B := 280 * cos(3.199 + 84334.662*T0)
+ 102 * cos(5.422 + 5507.553*T0)
+ 80 * cos(3.88 + 5223.69*T0)
+ 44 * cos(3.70 + 2352.87*T0)
+ 32 * cos(4.00 + 1577.34*T0);
B := B / 1.0E+8;
A := 227778 * cos(3.413766 + 6283.07585*T0)
+ 3806 * cos(3.3706 + 12566.1517*T0)
+ 3620
+ 72 * cos(3.33 + 18849.23*T0)
+ 8 * cos(3.89 + 5507.55*T0)
+ 8 * cos(1.79 + 5223.69*T0)
+ 6 * cos(5.20 + 2352.87*T0);
B := B + (A * T0 / 1.0E+8);
A := 9721 * cos(5.1519 + 6283.07585*T0)
+ 233 * cos(3.1416)
+ 134 * cos(0.644 + 12566.152*T0)
+ 7 * cos(1.07 + 18849.23*T0);
B := B + (A * sqr(T0) / 1.0E+8);
A := 276 * cos(0.595 + 6283.076*T0)
+ 17 * cos(3.14)
+ 4 * cos(0.12 + 12566.15*T0);
B := B + (A * sqr(T0) * T0 / 1.0E+8);
{solar radius vector (astronomical units)}
Result.RV := 100013989
+ 1670700 * cos(3.0984635 + 6283.07585*T0)
+ 13956 * cos(3.05525 + 12566.15170*T0)
+ 3084 * cos(5.1985 + 77713.7715*T0)
+ 1628 * cos(1.1739 + 5753.3849*T0)
+ 1576 * cos(2.8649 + 7860.4194*T0)
+ 925 * cos(5.453 + 11506.770*T0)
+ 542 * cos(4.564 + 3930.210*T0)
+ 472 * cos(3.661 + 5884.927*T0)
+ 346 * cos(0.964 + 5507.553*T0)
+ 329 * cos(5.900 + 5223.694*T0)
+ 307 * cos(0.299 + 5573.143*T0)
+ 243 * cos(4.273 + 11790.629*T0)
+ 212 * cos(5.847 + 1577.344*T0)
+ 186 * cos(5.022 + 10977.079*T0)
+ 175 * cos(3.012 + 18849.228*T0)
+ 110 * cos(5.055 + 5486.778*T0)
+ 98 * cos(0.89 + 6069.78*T0)
+ 86 * cos(5.69 + 15720.84*T0)
+ 86 * cos(1.27 +161000.69*T0)
+ 65 * cos(0.27 + 17260.15*T0)
+ 63 * cos(0.92 + 529.69*T0)
+ 57 * cos(2.01 + 83996.85*T0)
+ 56 * cos(5.24 + 71430.70*T0)
+ 49 * cos(3.25 + 2544.31*T0)
+ 47 * cos(2.58 + 775.52*T0)
+ 45 * cos(5.54 + 9437.76*T0)
+ 43 * cos(6.01 + 6275.96*T0)
+ 39 * cos(5.36 + 4694.00*T0)
+ 38 * cos(2.39 + 8827.39*T0)
+ 37 * cos(0.83 + 19651.05*T0)
+ 37 * cos(4.90 + 12139.55*T0)
+ 36 * cos(1.67 + 12036.46*T0)
+ 35 * cos(1.84 + 2942.46*T0)
+ 33 * cos(0.24 + 7084.90*T0)
+ 32 * cos(0.18 + 5088.63*T0)
+ 32 * cos(1.78 + 398.15*T0)
+ 28 * cos(1.21 + 6286.60*T0)
+ 28 * cos(1.90 + 6279.55*T0)
+ 26 * cos(4.59 + 10447.39*T0);
Result.RV := Result.RV / 1.0E+8;
A := 103019 * cos(1.107490 + 6283.075850*T0)
+ 1721 * cos(1.0644 + 12566.1517*T0)
+ 702 * cos(3.142)
+ 32 * cos(1.02 + 18849.23*T0)
+ 31 * cos(2.84 + 5507.55*T0)
+ 25 * cos(1.32 + 5223.69*T0)
+ 18 * cos(1.42 + 1577.34*T0)
+ 10 * cos(5.91 + 10977.08*T0)
+ 9 * cos(1.42 + 6275.96*T0)
+ 9 * cos(0.27 + 5486.78*T0);
Result.RV := Result.RV + (A * T0 / 1.0E+8);
A := 4359 * cos(5.7846 + 6283.0758*T0)
+ 124 * cos(5.579 + 12566.152*T0)
+ 12 * cos(3.14)
+ 9 * cos(3.63 + 77713.77*T0)
+ 6 * cos(1.87 + 5573.14*T0)
+ 3 * cos(5.47 + 18849.23*T0);
Result.RV := Result.RV + (A * sqr(T0) / 1.0E+8);
L := (L + PI);
L := Frac(L / 2.0 / PI) * 2.0 * Pi;
if L < 0 then
L := L + (2.0*PI);
B := -B;
Result.SLong := L * radcor;
Result.SLat := B * radcor;
X := Result.RV * cos(B) * cos(L);
Y := Result.RV * cos(B) * sin(L);
Z := Result.RV * sin(B);
Result.SunX := X + 4.40360E-7 * Y - 1.90919E-7 * Z;
Result.SunY := -4.79966E-7 * X + 0.917482137087 * Y - 0.397776982902 * Z;
Result.SunZ := 0.397776982902 * Y + 0.917482137087 * Z;
end;
function MoonPosPrim(UT : TStDateTimeRec) : TStMoonPosRec;
{-computes J2000 coordinates of the moon}
var
JD,
TD,
JCent,
JC2, JC3, JC4,
LP, D,
M, MP,
F, I,
A1,A2,A3,
MoonLong,
MoonLat,
MoonDst,
S1,C1,
SunRA,
SunDC,
EE,EES : Double;
SP : TStSunXYZRec;
begin
JD := AstJulianDate(UT.D) + UT.T/86400;
JCent := (JD - 2451545) / 36525;
JC2 := sqr(JCent);
JC3 := JC2 * JCent;
JC4 := sqr(JC2);
SP := SunPosPrim(UT);
SunRA := StInvTan2(SP.SunX, SP.SunY) * radcor;
SunDC := StInvSin(SP.SunZ / SP.RV) * radcor;
{Lunar mean longitude}
LP := 218.3164591 + (481267.88134236 * JCent)
- (1.3268E-3 * JC2) + (JC3 / 538841) - (JC4 / 65194000);
LP := Frac(LP/360) * 360;
if LP < 0 then
LP := LP + 360;
LP := LP/radcor;
{Lunar mean elongation}
D := 297.8502042 + (445267.1115168 * JCent)
- (1.63E-3 * JC2) + (JC3 / 545868) - (JC4 / 113065000);
D := Frac(D/360) * 360;
if D < 0 then
D := D + 360;
D := D/radcor;
{Solar mean anomaly}
M := 357.5291092 + (35999.0502909 * JCent)
- (1.536E-4 * JC2) + (JC3 / 24490000);
M := Frac(M/360) * 360;
if M < 0 then
M := M + 360;
M := M/radcor;
{Lunar mean anomaly}
MP := 134.9634114 + (477198.8676313 * JCent)
+ (8.997E-3 * JC2) + (JC3 / 69699) - (JC4 / 14712000);
MP := Frac(MP/360) * 360;
if MP < 0 then
MP := MP + 360;
MP := MP/radcor;
{Lunar argument of latitude}
F := 93.2720993 + (483202.0175273 * JCent)
- (3.4029E-3 * JC2) - (JC3 / 3526000) + (JC4 / 863310000);
F := Frac(F/360) * 360;
if F < 0 then
F := F + 360;
F := F/radcor;
{Other required arguments}
A1 := 119.75 + (131.849 * JCent);
A1 := Frac(A1/360) * 360;
if A1 < 0 then
A1 := A1 + 360;
A1 := A1/radcor;
A2 := 53.09 + (479264.290 * JCent);
A2 := Frac(A2/360) * 360;
if A2 < 0 then
A2 := A2 + 360;
A2 := A2/radcor;
A3 := 313.45 + (481266.484 * JCent);
A3 := Frac(A3/360) * 360;
if A3 < 0 then
A3 := A3 + 360;
A3 := A3/radcor;
{Earth's orbital eccentricity}
EE := 1.0 - (2.516E-3 * JCent) - (7.4E-6 * JC2);
EES := sqr(EE);
MoonLong := 6288774 * sin(MP)
+ 1274027 * sin(2*D - MP)
+ 658314 * sin(2*D)
+ 213618 * sin(2*MP)
- 185116 * sin(M) * EE
- 114332 * sin(2*F)
+ 58793 * sin(2*(D-MP))
+ 57066 * sin(2*D-M-MP) * EE
+ 53322 * sin(2*D-MP)
+ 45758 * sin(2*D-M) * EE
- 40923 * sin(M-MP) * EE
- 34720 * sin(D)
- 30383 * sin(M+MP) * EE
+ 15327 * sin(2*(D-F))
- 12528 * sin(MP+2*F)
+ 10980 * sin(MP-2*F)
+ 10675 * sin(4*D-MP)
+ 10034 * sin(3*MP)
+ 8548 * sin(4*D-2*MP)
- 7888 * sin(2*D+M-MP) * EE
- 6766 * sin(2*D+M) * EE
- 5163 * sin(D-MP)
+ 4987 * sin(D+M) * EE
+ 4036 * sin(2*D-M+MP) * EE
+ 3994 * sin(2*(D+MP))
+ 3861 * sin(4*D)
+ 3665 * sin(2*D-3*MP)
- 2689 * sin(M-2*MP) * EE
- 2602 * sin(2*D-MP+2*F)
+ 2390 * sin(2*D-M-2*MP) * EE
- 2348 * sin(D-MP)
+ 2236 * sin(2*(D-M)) * EES
- 2120 * sin(M-2*MP) * EE
- 2069 * sin(2*M) * EE
+ 2048 * sin(2*D-2*M-MP) * EES
- 1773 * sin(2*D+MP-2*F)
- 1595 * sin(2*(D+F))
+ 1215 * sin(4*D-M-MP) * EE
- 1110 * sin(2*(MP+F))
- 892 * sin(3*D-MP)
- 810 * sin(2*D-M-MP) * EE
+ 759 * sin(4*D-M-2*MP) * EE
- 713 * sin(2*M-MP) * EE
- 700 * sin(2*D+2*M-MP) * EES
+ 691 * sin(2*D+M-2*MP) * EE
+ 596 * sin(2*D-M-2*F) * EE
+ 549 * sin(4*D+MP)
+ 537 * sin(4*MP)
+ 520 * sin(4*D-M) * EE;
MoonDst := - 20905355 * cos(MP)
- 3699111 * cos(2*D - MP)
- 2955968 * cos(2*D)
- 569925 * cos(2*MP)
+ 48888 * cos(M) * EE
- 3149 * cos(2*F)
+ 246158 * cos(2*(D-MP))
- 152138 * cos(2*D-M-MP) * EE
- 170733 * cos(2*D-MP)
- 204586 * cos(2*D-M) * EE
- 129620 * cos(M-MP) * EE
+ 108743 * cos(D)
+ 104755 * cos(M-MP) * EE
+ 10321 * cos(2*D-2*F)
+ 79661 * cos(MP-2*F)
- 34782 * cos(4*D-MP)
- 23210 * cos(3*MP)
- 21636 * cos(4*D-2*MP)
+ 24208 * cos(2*D+M-MP) * EE
+ 30824 * cos(2*D-M) * EE
- 8379 * cos(D-MP)
- 16675 * cos(D+M) * EE
- 12831 * cos(2*D-M+MP) * EE
- 10445 * cos(2*D+2*MP)
- 11650 * cos(4*D) * EE
+ 14403 * cos(2*D+3*MP)
- 7003 * cos(M-2*MP) * EE
+ 10056 * cos(2*D-M-2*MP) * EE
+ 6322 * cos(D+MP)
- 9884 * cos(2*D-2*M) * EES
+ 5751 * cos(M+2*MP) * EE
- 4950 * cos(2*D-2*M-MP) * EES
+ 4130 * cos(2*D+MP+2*F)
- 3958 * cos(4*D-M-MP) * EE
+ 3258 * cos(3*D-MP)
+ 2616 * cos(2*D+M+MP) * EE
- 1897 * cos(4*D-M-2*MP) * EE
- 2117 * cos(2*M-MP) * EES
+ 2354 * cos(2*D+2*M-MP) * EES
- 1423 * cos(4*D+MP)
- 1117 * cos(4*MP)
- 1571 * cos(4*D-M) * EE
- 1739 * cos(D-2*MP)
- 4421 * cos(2*MP-2*F)
+ 1165 * cos(2*M+MP)
+ 8752 * cos(2*D-MP-2*F);
MoonLat := 5128122 * sin(F)
+ 280602 * sin(MP+F)
+ 277693 * sin(MP-F)
+ 173237 * sin(2*D-F)
+ 55413 * sin(2*D-MP+F)
+ 46271 * sin(2*D-MP-F)
+ 32573 * sin(2*D+F)
+ 17198 * sin(2*MP+F)
+ 9266 * sin(2*D+MP-F)
+ 8822 * sin(2*MP-F)
+ 8216 * sin(2*D-M-F) * EE
+ 4324 * sin(2*D-2*MP-F)
+ 4200 * sin(2*D+MP+F)
- 3359 * sin(2*D+M-F) * EE
+ 2463 * sin(2*D-M-MP+F) * EE
+ 2211 * sin(2*D-M+F) * EE
+ 2065 * sin(2*D-M-MP-F) * EE
- 1870 * sin(M-MP-F) * EE
+ 1828 * sin(4*D-MP-F)
- 1794 * sin(M+F) * EE
- 1749 * sin(3*F)
- 1565 * sin(M-MP+F) * EE
- 1491 * sin(D+F)
- 1475 * sin(M+MP+F) * EE
- 1410 * sin(M+MP-F) * EE
- 1344 * sin(M-F) * EE
- 1335 * sin(D-F)
+ 1107 * sin(3*MP+F)
+ 1021 * sin(4*D-F)
+ 833 * sin(4*D-MP+F)
+ 777 * sin(MP-3*F)
+ 671 * sin(4*D-2*MP+F)
+ 607 * sin(2*D-3*F)
+ 596 * sin(2*D+2*MP-F)
+ 491 * sin(2*D-M+MP-F) * EE
- 451 * sin(2*D-2*MP+F)
+ 439 * sin(3*MP-F)
+ 422 * sin(2*D+2*MP+F)
+ 421 * sin(2*D-3*MP-F)
- 366 * sin(2*D+M-MP+F) * EE
- 351 * sin(2*D+M+F) * EE
+ 331 * sin(4*D+F)
+ 315 * sin(2*D-M+MP+F) * EE
+ 302 * sin(2*D-2*M-F) * EES
- 283 * sin(MP + 3*F)
- 229 * sin(2*D+M+MP-F) * EE
+ 223 * sin(D+M-F) * EE
+ 223 * sin(D+M+F) * EE;
MoonLong := MoonLong
+ 3958 * sin(A1)
+ 1962 * sin(LP-F)
+ 318 * sin(A2);
MoonLat := MoonLat
- 2235 * sin(LP)
+ 382 * sin(A3)
+ 175 * sin(A1-F)
+ 175 * sin(A1+F)
+ 127 * sin(LP-MP)
- 115 * sin(LP+MP);
MoonLong := LP + MoonLong/1000000/radcor;
MoonLat := MoonLat/1000000/radcor;
MoonDst := 385000.56 + MoonDst/1000;
Result.Plx := StInvSin(6378.14/MoonDst) * radcor;
Result.Dia := 358473400 / MoonDst * 2 / 3600;
S1 := sin(MoonLong) * cos(OB2000) - StTan(MoonLat) * sin(OB2000);
C1 := cos(MoonLong);
Result.RA := StInvTan2(C1, S1) * radcor;
TD := sin(MoonLat) * cos(OB2000)
+ cos(MoonLat) * sin(OB2000) * sin(MoonLong);
TD := StInvSin(TD);
Result.DC := TD * radcor;
I := sin(SunDC/radcor) * sin(TD)
+ cos(SunDC/radcor) * cos(TD) * cos((SunRA-Result.RA)/radcor);
Result.Phase := (1 - I) / 2;
I := StInvCos(I) * radcor;
Result.Elong := (Result.RA - SunRA);
if Result.Elong < 0 then
Result.Elong := 360 + Result.Elong;
if Result.Elong >= 180 then begin
Result.Phase := -Result.Phase; {waning moon}
Result.Elong := -I
end else
Result.Elong := I;
end;
function AmountOfSunlight(LD : TStDate; Longitude, Latitude : Double): TStTime;
{-compute the hours, min, sec of sunlight on a given date}
var
RS : TStRiseSetRec;
begin
RS := SunRiseSet(LD, Longitude, Latitude);
with RS do begin
if ORise = -3 then begin
{sun is always above the horizon}
Result := SecondsInDay;
Exit;
end;
if ORise = -2 then begin
{sun is always below horizon}
Result := 0;
Exit;
end;
if (ORise > -1) then begin
if (OSet > -1) then
Result := OSet - ORise
else
Result := SecondsInDay - ORise;
end else begin
if (OSet > -1) then
Result := OSet
else
Result := 0;
end;
end;
if (Result < 0) then
Result := Result + SecondsInDay
else if (Result >= SecondsInDay) then
Result := Result - SecondsInDay;
end;
function SunPos(UT : TStDateTimeRec) : TStPosRec;
{-compute the RA/Declination of the Sun}
var
SP : TStSunXYZRec;
begin
if not CheckDate(UT) then begin
Result.RA := -1;
Result.DC := -99;
Exit;
end;
SP := SunPosPrim(UT);
Result.RA := StInvTan2(SP.SunX, SP.SunY) * radcor;
Result.DC := StInvSin(SP.SunZ / SP.RV) * radcor;
end;
function RiseSetPrim(LD : TStDate;
Longitude, Latitude, H0 : Double;
PR : TStPosRecArray;
ApproxOnly : Boolean) : TStRiseSetRec;
{-primitive routine for finding rise/set times}
var
ST,
NST,
HA,
LatR,
N1,
N2,
N3,
TTran,
TRise,
TSet,
TV1,
TV2,
A1,
A2,
DeltaR,
DeltaS,
RA,
DC,
Alt : Double;
ICount : SmallInt;
UT : TStDateTimeRec;
begin
H0 := H0/radcor;
UT.D := LD;
UT.T := 0;
ST := SiderealTime(UT);
LatR := Latitude/radcor;
{check if object never rises/sets}
N1 := sin(H0) - sin(LatR) * sin(PR[2].DC/radcor);
N2 := cos(LatR) * cos(PR[2].DC/radcor);
HA := N1 / N2;
if (abs(HA) >= 1) then begin
{ if ((Latitude - 90) >= 90) then begin}
if (HA > 0) then begin
{object never rises}
Result.ORise := -2;
Result.OSet := -2;
end else begin
{object never sets, i.e., it is circumpolar}
Result.ORise := -3;
Result.OSet := -3;
end;
Exit;
end;
HA := StInvCos(HA) * radcor;
if HA > 180 then
HA := HA - 180;
if HA < 0 then
HA := HA + 180;
{compute approximate hour angle at transit}
TTran := (PR[2].RA - Longitude - ST) / 360;
if abs(TTran) >= 1 then
TTran:= Frac(TTran);
if TTran < 0 then
TTran := TTran + 1;
TRise := TTran - HA/360;
TSet := TTran + HA/360;
if abs(TRise) >= 1 then
TRise:= Frac(TRise);
if TRise < 0 then
TRise := TRise + 1;
if abs(TSet) >= 1 then
TSet := Frac(TSet);
if TSet < 0 then
TSet := TSet + 1;
if not ApproxOnly then begin
{refine rise time by interpolation/iteration}
ICount := 0;
TV1 := 0;
A1 := 0;
repeat
NST := ST + 360.985647 * TRise;
NST := Frac(NST / 360.0) * 360;
N1 := PR[2].RA - PR[1].RA;
N2 := PR[3].RA - PR[2].RA;
N3 := N2 - N1;
RA := PR[2].RA + TRise/2 * (N1 + N2 + TRise*N3);
N1 := PR[2].DC - PR[1].DC;
N2 := PR[3].DC - PR[2].DC;
N3 := N2 - N1;
DC := PR[2].DC + TRise/2 * (N1 + N2 + TRise*N3);
DC := DC/radcor;
HA := (NST + Longitude - RA) / radcor;
Alt := StInvSin(sin(LatR) * sin(DC) + cos(LatR) * cos(DC) * cos(HA));
DeltaR := ((Alt - H0) * radcor) / (360 * cos(DC) * cos(LatR) * sin(HA));
TRise := TRise + DeltaR;
Inc(ICount);
if (ICount > 3) and (abs(DeltaR) >= 0.0005) then begin
if (ICount = 4) then begin
TV1 := TRise;
A1 := (Alt-H0) * radcor;
end else if (ICount = 5) then begin
TV2 := TRise;
A2 := (Alt-H0) * radcor;
TRise := TV1 + (A1 / A2) * (TV1 - TV2);
break;
end;
end;
until (abs(DeltaR) < 0.0005); {0.0005d = 0.72 min}
{refine set time by interpolation/iteration}
ICount := 0;
TV1 := 0;
A1 := 0;
repeat
NST := ST + 360.985647 * TSet;
NST := Frac(NST / 360.0) * 360;
N1 := PR[2].RA - PR[1].RA;
N2 := PR[3].RA - PR[2].RA;
N3 := N2 - N1;
RA := PR[2].RA + TSet/2 * (N1 + N2 + TSet*N3);
N1 := PR[2].DC - PR[1].DC;
N2 := PR[3].DC - PR[2].DC;
N3 := N2 - N1;
DC := PR[2].DC + TSet/2 * (N1 + N2 + TSet*N3);
DC := DC/radcor;
HA := (NST + Longitude - RA) / radcor;
Alt := StInvSin(sin(LatR) * sin(DC) + cos(LatR) * cos(DC) * cos(HA));
DeltaS := ((Alt - H0) * radcor) / (360 * cos(DC) * cos(LatR) * sin(HA));
TSet := TSet + DeltaS;
Inc(ICount);
if (ICount > 3) and (abs(DeltaS) >= 0.0005) then begin
if (ICount = 4) then begin
TV1 := TSet;
A1 := (Alt-H0) * radcor;
end else if (ICount = 5) then begin
TV2 := TSet;
A2 := (Alt-H0) * radcor;
TSet := TV1 + (A1 / A2) * (TV1 - TV2);
break;
end;
end;
until (abs(DeltaS) < 0.0005); {0.0005d = 0.72 min}
end;
if (TRise >= 0) and (TRise < 1) then
Result.ORise := Trunc(TRise * SecondsInDay)
else begin
if TRise < 0 then
Result.ORise := Trunc((TRise + 1) * SecondsInDay)
else
Result.ORise := Trunc(Frac(TRise) * SecondsInDay);
end;
if Result.ORise < 0 then
Inc(Result.ORise, SecondsInDay);
if Result.ORise >= SecondsInDay then
Dec(Result.ORise, SecondsInDay);
if (TSet >= 0) and (TSet < 1) then
Result.OSet := Trunc(TSet * SecondsInDay)
else begin
if TSet < 0 then
Result.OSet := Trunc((TSet + 1) * SecondsInDay)
else
Result.OSet := Trunc(Frac(TSet) * SecondsInDay);
end;
if Result.OSet < 0 then
Inc(Result.OSet, SecondsInDay);
if Result.OSet >= SecondsInDay then
Dec(Result.OSet, SecondsInDay);
end;
function SunRiseSet(LD : TStDate; Longitude, Latitude : Double) : TStRiseSetRec;
{-compute the Sun rise or set time}
{the value for H0 accounts for approximate refraction of 0.5667 deg. and}
{that rise or set is based on the upper limb instead of the center of the solar disc}
var
I : Integer;
H0 : Double;
UT : TStDateTimeRec;
RP : TStPosRecArray;
begin
Dec(LD);
H0 := -0.8333;
UT.T := 0;
UT.D := LD-1;
if CheckDate(UT) then begin
UT.D := UT.D + 2;
if (not CheckDate(UT)) then begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end else
UT.D := UT.D-2;
end else begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end;
for I := 1 to 3 do begin
RP[I] := SunPos(UT);
if I >= 2 then begin
if RP[I].RA < RP[I-1].RA then
RP[I].RA := RP[I].RA + 360;
end;
Inc(UT.D);
end;
Result := RiseSetPrim(LD, Longitude, Latitude, H0, RP, False);
end;
function Twilight(LD : TStDate; Longitude, Latitude : Double;
TwiType : TStTwilight) : TStRiseSetRec;
{-compute the beginning or end of twilight}
{twilight computations are based on the zenith distance of the center }
{of the solar disc.}
{Civil = 6 deg. below the horizon}
{Nautical = 12 deg. below the horizon}
{Astronomical = 18 deg. below the horizon}
var
I : Integer;
H0 : Double;
UT : TStDateTimeRec;
RP : TStPosRecArray;
begin
UT.D := LD-1;
UT.T := 0;
if CheckDate(UT) then begin
UT.D := UT.D + 2;
if (not CheckDate(UT)) then begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end else
UT.D := UT.D-2;
end else begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end;
case TwiType of
ttCivil : H0 := -6.0;
ttNautical : H0 := -12.0;
ttAstronomical : H0 := -18.0;
else
H0 := -18.0;
end;
for I := 1 to 3 do begin
UT.D := LD + I-1;
RP[I] := SunPos(UT);
if (I > 1) then begin
if RP[I].RA < RP[I-1].RA then
RP[I].RA := RP[I].RA + 360.0;
end;
end;
Result := RiseSetPrim(LD, Longitude, Latitude, H0, RP, False);
end;
function FixedRiseSet(LD : TStDate;
RA, DC, Longitude, Latitude : Double) : TStRiseSetRec;
{-compute the rise/set time for a fixed object, e.g., star}
{the value for H0 accounts for approximate refraction of 0.5667 deg.}
{this routine does not refine the intial estimate and so may be off by five}
{minutes or so}
var
H0 : Double;
UT : TStDateTimeRec;
RP : TStPosRecArray;
begin
H0 := -0.5667;
UT.T := 0;
UT.D := LD;
if not CheckDate(UT) then begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end;
RP[2].RA := RA;
RP[2].DC := DC;
Result := RiseSetPrim(LD, Longitude, Latitude, H0, RP, True);
end;
function MoonPos(UT : TStDateTimeRec) : TStMoonPosRec;
{-compute the J2000 RA/Declination of the moon}
begin
if not CheckDate(UT) then begin
Result.RA := -1;
Result.DC := -1;
Exit;
end;
Result := MoonPosPrim(UT);
end;
function MoonRiseSet(LD : TStDate; Longitude, Latitude : Double) : TStRiseSetRec;
{compute the Moon rise and set time}
{the value for H0 accounts for approximate refraction of 0.5667 deg., }
{that rise or set is based on the upper limb instead of the center of the}
{lunar disc, and the lunar parallax. In accordance with American Ephemeris }
{practice, the phase of the moon is not taken into account, i.e., the time}
{is based on the upper limb whether it is lit or not}
var
I : Integer;
H0 : Double;
UT : TStDateTimeRec;
RP : TStPosRecArray;
MPR : TStMoonPosRec;
begin
H0 := 0.125; { default value }
Dec(LD);
UT.T := 0;
UT.D := LD;
if CheckDate(UT) then begin
UT.D := UT.D + 2;
if (not CheckDate(UT)) then begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end else
UT.D := UT.D-2;
end else begin
Result.ORise := -4;
Result.OSet := -4;
Exit;
end;
for I := 1 to 3 do begin
MPR := MoonPos(UT);
RP[I].RA := MPR.RA;
RP[I].DC := MPR.DC;
if I >= 2 then begin
if I = 2 then
H0 := 0.7275*MPR.Plx - 0.5667;
if RP[I].RA < RP[I-1].RA then
RP[I].RA := RP[I].RA + 360;
end;
Inc(UT.D);
end;
Result := RiseSetPrim(LD, Longitude, Latitude, H0, RP, False);
end;
function LunarPhase(UT : TStDateTimeRec) : Double;
{-compute the phase of the moon}
{The value is positive if between New and Full Moon}
{ negative if between Full and New Moon}
var
MPR : TStMoonPosRec;
begin
MPR := MoonPosPrim(UT);
Result := MPR.Phase;
end;
procedure GetPhases(K : Double; var PR : TStPhaseRecord);
{primitive routine to find the date/time of phases in a lunar cycle}
var
JD,
NK,
TD,
J1,
J2,
J3 : Double;
step : Integer;
E,
FP,
S1,
M1,
M2,
M3 : Double;
function AddCor : Double;
begin
AddCor := 0.000325 * sin((299.77 + 0.107408*K - 0.009173*J2)/radcor)
+ 0.000165 * sin((251.88 + 0.016321*K)/radcor)
+ 0.000164 * sin((251.83 + 26.651886*K)/radcor)
+ 0.000126 * sin((349.42 + 36.412478*K)/radcor)
+ 0.000110 * sin((84.660 + 18.206239*K)/radcor)
+ 0.000062 * sin((141.74 + 53.303771*K)/radcor)
+ 0.000060 * sin((207.14 + 2.453732*K)/radcor)
+ 0.000056 * sin((154.84 + 7.306860*K)/radcor)
+ 0.000047 * sin((34.520 + 27.261239*K)/radcor)
+ 0.000042 * sin((207.19 + 0.121824*K)/radcor)
+ 0.000040 * sin((291.34 + 1.844379*K)/radcor)
+ 0.000037 * sin((161.72 + 24.198154*K)/radcor)
+ 0.000035 * sin((239.56 + 25.513099*K)/radcor)
+ 0.000023 * sin((331.55 + 3.592518*K)/radcor);
end;
begin
NK := K;
FillChar(PR, SizeOf(TStPhaseRecord), #0);
for step := 0 to 3 do begin
K := NK + (step*0.25);
FP := Frac(K);
if FP < 0 then
FP := FP + 1;
{compute Julian Centuries}
J1 := K / 1236.85;
J2 := Sqr(J1);
J3 := J2 * J1;
{solar mean anomaly}
S1 := 2.5534
+ 29.1053569 * K
- 0.0000218 * J2
- 0.00000011 * J3;
S1 := Frac(S1 / 360.0) * 360;
if S1 < 0 then
S1 := S1 + 360.0;
{lunar mean anomaly}
M1 := 201.5643
+ 385.81693528 * K
+ 0.0107438 * J2
+ 0.00001239 * J3
- 0.000000058 * J2 * J2;
M1 := Frac(M1 / 360.0) * 360;
if M1 < 0 then
M1 := M1 + 360.0;
{lunar argument of latitude}
M2 := 160.7108
+ 390.67050274 * K
- 0.0016341 * J2
- 0.00000227 * J3
+ 0.000000011 * J2 * J2;
M2 := Frac(M2 / 360.0) * 360;
if M2 < 0 then
M2 := M2 + 360.0;
{lunar ascending node}
M3 := 124.7746
- 1.56375580 * K
+ 0.0020691 * J2
+ 0.00000215 * J3;
M3 := Frac(M3 / 360.0) * 360;
if M3 < 0 then
M3 := M3 + 360.0;
{convert to radians}
S1 := S1/radcor;
M1 := M1/radcor;
M2 := M2/radcor;
M3 := M3/radcor;
{mean Julian Date for phase}
JD := 2451550.09765
+ 29.530588853 * K
+ 0.0001337 * J2
- 0.000000150 * J3
+ 0.00000000073 * J2 * J2;
{earth's orbital eccentricity}
E := 1.0 - 0.002516 * J1 - 0.0000074 * J2;
{New Moon date time}
if FP < 0.01 then begin
TD := - 0.40720 * sin(M1)
+ 0.17241 * E * sin(S1)
+ 0.01608 * sin(2*M1)
+ 0.01039 * sin(2*M2)
+ 0.00739 * E * sin(M1-S1)
- 0.00514 * E * sin(M1 + S1)
+ 0.00208 * E * E * sin(2 * S1)
- 0.00111 * sin(M1 - 2*M2)
- 0.00057 * sin(M1 + 2*M2)
+ 0.00056 * E * sin(2*M1 + S1)
- 0.00042 * sin(3 * M1)
+ 0.00042 * E * sin(S1 + 2*M2)
+ 0.00038 * E * sin(S1 - 2*M2)
- 0.00024 * E * sin(2*(M1-S1))
- 0.00017 * sin(M3)
- 0.00007 * sin(M1 + 2*S1);
JD := JD + TD + AddCor;
PR.NMDate := JD;
end;
{Full Moon date/time}
if Abs(FP - 0.5) < 0.01 then begin
TD := - 0.40614 * sin(M1)
+ 0.17302 * E * sin(S1)
+ 0.01614 * sin(2*M1)
+ 0.01043 * sin(2*M2)
+ 0.00734 * E * sin(M1-S1)
- 0.00515 * E * sin(M1 + S1)
+ 0.00209 * E * E * sin(2 * S1)
- 0.00111 * sin(M1 - 2*M2)
- 0.00057 * sin(M1 + 2*M2)
+ 0.00056 * E * sin(2*M1 + S1)
- 0.00042 * sin(3 * M1)
+ 0.00042 * E * sin(S1 + 2*M2)
+ 0.00038 * E * sin(S1 - 2*M2)
- 0.00024 * E * sin(2*(M1-S1))
- 0.00017 * sin(M3)
- 0.00007 * sin(M1 + 2*S1);
JD := JD + TD + AddCor;
PR.FMDate := JD;
end;
{Quarters date/time}
if (abs(FP - 0.25) < 0.01) or (abs(FP - 0.75) < 0.01) then begin
TD := - 0.62801 * sin(M1)
+ 0.17172 * sin(S1) * E
- 0.01183 * sin(M1+S1) * E
+ 0.00862 * sin(2*M1)
+ 0.00804 * sin(2*M2)
+ 0.00454 * sin(M1-S1) * E
+ 0.00204 * sin(2*S1) * E * E
- 0.00180 * sin(M1 - 2*M2)
- 0.00070 * sin(M1 + 2*M2)
- 0.00040 * sin(3*M1)
- 0.00034 * sin(2*M1-S1) * E
+ 0.00032 * sin(S1 + 2*M2) * E
+ 0.00032 * sin(S1 - 2*M2) * E
- 0.00028 * sin(M1 + 2*S1) * E * E
+ 0.00027 * sin(2*M1 + S1) * E
- 0.00017 * sin(M3)
- 0.00005 * sin(M1 - S1 - 2*M2);
JD := JD + TD + AddCor;
{adjustment to computed Julian Date}
TD := 0.00306
- 0.00038 * E * cos(S1)
+ 0.00026 * cos(M1)
- 0.00002 * cos(M1-S1)
+ 0.00002 * cos(M1+S1)
+ 0.00002 * cos(2*M2);
if Abs(FP - 0.25) < 0.01 then
PR.FQDate := JD + TD
else
PR.LQDate := JD - TD;
end;
end;
end;
procedure PhasePrim(LD : TStDate; var PhaseArray : TStPhaseArray);
{-primitive phase calculation}
var
I,
D,
M,
Y : Integer;
K, TD,
LYear : Double;
begin
StDateToDMY(LD, D, M, Y);
LYear := Y - 0.05;
K := (LYear - 2000) * 12.3685;
K := Int(K);
TD := K / 12.3685 + 2000;
if TD > Y then
K := K-1;
{compute phases for each lunar cycle throughout the year}
for I := 0 to 13 do begin
GetPhases(K, PhaseArray[I]);
K := K + 1;
end;
end;
function GenSearchPhase(SD : TStDate; PV : Byte) : TStLunarRecord;
{searches for the specified phase in the given month/year expressed by SD}
var
I,
C,
LD,
LM,
LY,
TD,
TM,
TY : Integer;
ADate : TStDate;
JD : Double;
PhaseArray : TStPhaseArray;
begin
C := 0;
FillChar(Result, SizeOf(Result), $FF);
StDateToDMY(SD, LD, LM, LY);
PhasePrim(SD, PhaseArray);
for I := LM-1 to LM+1 do begin
if (PV = 0) then
JD := PhaseArray[I].NMDate
else if (PV = 1) then
JD := PhaseArray[I].FQDate
else if (PV = 2) then
JD := PhaseArray[I].FMDate
else
JD := PhaseArray[I].LQDate;
ADate := AstJulianDateToStDate(JD, True);
StDateToDMY(ADate, TD, TM, TY);
if TM < LM then
continue
else if TM = LM then begin
Result.T[C].D := ADate;
Result.T[C].T := Trunc((Frac(JD) + 0.5) * 86400);
if Result.T[C].T >= SecondsInDay then
Dec(Result.T[C].T, SecondsInDay);
Inc(C);
end;
end;
end;
function FirstQuarter(D : TStDate) : TStLunarRecord;
{-compute date/time of FirstQuarter(s)}
begin
Result := GenSearchPhase(D, 1);
end;
function FullMoon(D : TStDate) : TStLunarRecord;
{-compute the date/time of FullMoon(s)}
begin
Result := GenSearchPhase(D, 2);
end;
function LastQuarter(D: TStDate) : TStLunarRecord;
{-compute the date/time of LastQuarter(s)}
begin
Result := GenSearchPhase(D, 3);
end;
function NewMoon(D : TStDate) : TStLunarRecord;
{-compute the date/time of NewMoon(s)}
begin
Result := GenSearchPhase(D, 0);
end;
function NextPrevPhase(D : TStDate; Ph : Byte;
FindNext : Boolean) : TStDateTimeRec;
var
LD,
LM,
LY : Integer;
K,
JD,
TJD : Double;
PR : TStPhaseRecord;
OK : Boolean;
begin
if (D < MinDate) or (D > MaxDate) then begin
Result.D := BadDate;
Result.T := BadTime;
Exit;
end;
StDateToDMY(D, LD, LM, LY);
K := ((LY + LM/12 + LD/365.25) - 2000) * 12.3685 - 0.5;
if FindNext then
K := Round(K)-1
else
K := Round(K)-2;
OK := False;
TJD := AstJulianDate(D);
repeat
GetPhases(K, PR);
if (Ph = 0) then
JD := PR.NMDate
else if (Ph = 1) then
JD := PR.FQDate
else if (Ph = 2) then
JD := PR.FMDate
else
JD := PR.LQDate;
if (FindNext) then begin
if (JD > TJD) then
OK := True
else
K := K + 1;
end else begin
if (JD < TJD) then
OK := True
else
K := K - 1;
end;
until OK;
Result.D := AstJulianDateToStDate(JD, True);
if (Result.D <> BadDate) then begin
Result.T := Trunc((Frac(JD) + 0.5) * 86400);
if Result.T >= SecondsInDay then
Dec(Result.T, SecondsInDay);
end else
Result.T := BadTime;
end;
function NextFirstQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest FirstQuarter}
begin
Result := NextPrevPhase(D, 1, True);
end;
function NextFullMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest FullMoon}
begin
Result := NextPrevPhase(D, 2, True);
end;
function NextLastQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest LastQuarter}
begin
Result := NextPrevPhase(D, 3, True);
end;
function NextNewMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the next closest NewMoon}
begin
Result := NextPrevPhase(D, 0, True);
end;
function PrevFirstQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest FirstQuarter}
begin
Result := NextPrevPhase(D, 1, False);
end;
function PrevFullMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest FullMoon}
begin
Result := NextPrevPhase(D, 2, False);
end;
function PrevLastQuarter(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest LastQuarter}
begin
Result := NextPrevPhase(D, 3, False);
end;
function PrevNewMoon(D : TStDate) : TStDateTimeRec;
{-compute the date/time of the prev closest NewMoon}
begin
Result := NextPrevPhase(D, 0, False);
end;
{Calendar procedures/functions}
function SolEqPrim(Y : Integer; K : Byte) : TStDateTimeRec;
{primitive routine for finding equinoxes and solstices}
var
JD, TD, LY,
JCent, MA,
SLong : Double;
begin
JD := 0;
Result.D := BadDate;
Result.T := BadTime;
{the following algorithm is valid only in the range of [1000..3000 AD]}
{but is limited to returning dates in [MinYear..MaxYear]}
if (Y < MinYear) or (Y > MaxYear) then
Exit;
{compute approximate date/time for specified event}
LY := (Y - 2000) / 1000;
case K of
0 : JD := 2451623.80984
+ 365242.37404 * LY
+ 0.05169 * sqr(LY)
- 0.00411 * LY * sqr(LY)
- 0.00057 * sqr(sqr(LY));
1 : JD := 2451716.56767
+ 365241.62603 * LY
+ 0.00325 * sqr(LY)
+ 0.00888 * LY * sqr(LY)
- 0.00030 * sqr(sqr(LY));
2 : JD := 2451810.21715
+ 365242.01767 * LY
- 0.11575 * sqr(LY)
+ 0.00337 * sqr(LY) * LY
+ 0.00078 * sqr(sqr(LY));
3 : JD := 2451900.05952
+ 365242.74049 * LY
- 0.06223 * sqr(LY)
- 0.00823 * LY * sqr(LY)
+ 0.00032 * sqr(sqr(LY));
end;
{refine date/time by computing corrections due to solar longitude,}
{nutation and abberation. Iterate using the corrected time until}
{correction is less than one minute}
repeat
Result.D := AstJulianDateToStDate(JD, True);
Result.T := Trunc((Frac(JD) + 0.5) * 86400);
if Result.T >= SecondsInDay then
Dec(Result.T, SecondsInDay);
JCent := (JD - 2451545.0)/36525.0;
{approximate solar longitude - no FK5 correction}
SLong := 280.46645
+ 36000.76983 * JCent
+ 0.0003032 * sqr(JCent);
SLong := Frac((SLong)/360.0) * 360.0;
if SLong < 0 then
SLong := SLong + 360;
{Equation of the center correction}
MA := 357.52910
+ 35999.05030 * JCent;
MA := MA/radcor;
SLong := SLong
+ (1.914600 - 0.004817 * JCent - 0.000014 * sqr(JCent)) * sin(MA)
+ (0.019993 - 0.000101 * JCent) * sin(2*MA);
{approximate nutation}
TD := 125.04452
- 1934.136261 * JCent
+ 0.0020708 * sqr(JCent);
TD := TD/radcor;
TD := (-17.20 * sin(TD) - 1.32 * sin(2*SLong/radcor))/3600;
{approximate abberation - solar distance is assumed to be 1 A.U.}
SLong := SLong - (20.4989/3600) + TD;
{correction to compute Julian Date for event}
TD := 58 * sin((K*90 - SLong)/radcor);
if abs(TD) >= 0.0005 then
JD := JD + TD;
until abs(TD) < 0.0005;
end;
function Solstice(Y, Epoch : Integer; Summer : Boolean) : TStDateTimeRec;
{-compute the date/time of the summer or winter solstice}
{if Summer = True, compute astronomical summer solstice (summer in N. Hem.)}
{ = False, compute astronomical winter solstice (winter in N. Hem.)}
begin
Y := CheckYear(Y, Epoch);
if Summer then
Result := SolEqPrim(Y, 1)
else
Result := SolEqPrim(Y, 3);
end;
function Equinox(Y, Epoch : Integer; Vernal : Boolean) : TStDateTimeRec;
{-compute the date/time of the vernal/autumnal equinox}
{if Vernal = True, compute astronomical vernal equinox (spring in N. Hem.)}
{ = False, compute astronomical autumnal equinox (fall in N. Hem.)}
begin
Y := CheckYear(Y, Epoch);
if Vernal then
Result := SolEqPrim(Y, 0)
else
Result := SolEqPrim(Y, 2);
end;
function Easter(Y : Integer; Epoch : Integer) : TStDate;
{-compute the date of Easter}
var
A, B,
C, D,
E, F,
G, H,
I, K,
L, M,
N, P : Integer;
begin
Y := CheckYear(Y, Epoch);
if (Y < MinYear) or (Y > MaxYear) then begin
Result := BadDate;
Exit;
end;
A := Y mod 19;
B := Y div 100;
C := Y mod 100;
D := B div 4;
E := B mod 4;
F := (B+8) div 25;
G := (B-F+1) div 3;
H := (19*A + B - D - G + 15) mod 30;
I := C div 4;
K := C mod 4;
L := (32 + 2*E + 2*I - H - K) mod 7;
M := (A + 11*H + 22*L) div 451;
N := (H + L - 7*M + 114) div 31;
P := (H + L - 7*M + 114) mod 31 + 1;
Result := DMYToStDate(P, N, Y, Epoch);
end;
{Conversion routines}
function HoursMin(RA : Double) : String;
{-convert RA to formatted hh:mm:ss string}
var
HR, MR : Double;
HS, MS : string;
sBuffer: ShortString;
begin
if abs(RA) >= 360.0 then
RA := Frac(RA / 360.0) * 360;
if RA < 0 then
RA := RA + 360.0;
HR := Int(RA / 15.0);
MR := Frac(RA / 15.0) * 60;
Str(MR:5:2, sBuffer);
MS := string(sBuffer);
if MS = '60.00' then begin
MS := '00.00';
HR := HR + 1;
if HR = 24 then
HS := '0'
else
begin
Str(HR:2:0, sBuffer);
HS := string(sBuffer);
end;
end else begin
if MS[1] = ' ' then
MS[1] := '0';
Str(Hr:2:0, sBuffer);
HS := string(sBuffer)
end;
Result := HS + ' ' + MS;
end;
function DegsMin(DC : Double) : String;
{-convert Declination to formatted +/-dd:mm:ss string}
var
DR, MR : Double;
DS, MS : string;
sBuffer: ShortString;
begin
if abs(DC) > 90 then
DC := Frac(DC / 90.0) * 90.0;
DR := Int(DC);
MR := Frac(abs(DC)) * 60;
Str(MR:4:1, sBuffer);
MS := string(sBuffer);
if MS = '60.0' then begin
MS := '00.0';
if DC >= 0 then
DR := DR + 1
else
DR := DR - 1;
end;
if abs(DC) < 10 then begin
Str(DR:2:0, sBuffer);
DS := string(sBuffer);
DS := TrimLeadL(DS);
if DC < 0 then begin
if DC > -1 then
DS := '- 0'
else
DS := '- ' + DS[2];
end else
DS := '+ ' + DS;
end else begin
Str(DR:3:0, sBuffer);
DS := string(sBuffer);
DS := TrimLeadL(DS);
if DC < 0 then begin
Delete(DS,1,1);
DS := '-' + DS;
end else
DS := '+' + DS;
end;
if MS[1] = ' ' then
MS[1] := '0';
Result := DS + ' ' + MS;
end;
function DateTimeToAJD(D : TDateTime) : Double;
begin
Result := D + AJDOffset;
end;
function AJDToDateTime(D : Double) : TDateTime;
begin
Result := D - AJDOffset;
end;
initialization
AJDOffSet := AstJulianDatePrim(1600, 1, 1, 0) - EncodeDate(1600, 1, 1);
end.
|
unit uLembrete;
interface
uses System.SysUtils;
type
TLembrete = class
private
FIDPessoa: integer;
FTitulo: string;
FDescricao: string;
FData: TDate;
FHora: TTime;
constructor Create;
procedure setTitulo(Value: String);
procedure setDescricao(Value: String);
procedure setData(Value: TDate);
procedure setHora(Value: TTime);
procedure setIDLembrete(Value: integer);
function getTitulo: string;
function getDescricao: string;
function getData: TDate;
function getHora: TTime;
function getIDLembrete: integer;
public
property IDLembrete: integer read getIDLembrete write setIDLembrete;
property titulo: string read getTitulo write setTitulo;
property descricao: string read getDescricao write setDescricao;
property data: TDate read getData write setData;
property hora: TTime read getHora write setHora;
end;
implementation
{ TLembrete }
constructor TLembrete.Create;
begin
FIDPessoa := 0;
FTitulo := '';
FDescricao := '';
FData := EncodeDate(1900, 1, 1);
FHora := EncodeTime(00, 00, 00, 00);
end;
function TLembrete.getData: TDate;
begin
Result := FData;
end;
function TLembrete.getHora: TTime;
begin
Result := FHora;
end;
function TLembrete.getDescricao: string;
begin
Result := FDescricao;
end;
function TLembrete.getIDLembrete: integer;
begin
Result := FIDPessoa;
end;
function TLembrete.getTitulo: string;
begin
Result := FTitulo;
end;
procedure TLembrete.setData(Value: TDate);
begin
FData := Value;
end;
procedure TLembrete.setHora(Value: TTime);
begin
FHora := Value;
end;
procedure TLembrete.setDescricao(Value: String);
begin
FDescricao := Value;
end;
procedure TLembrete.setIDLembrete(Value: integer);
begin
FIDPessoa := Value;
end;
procedure TLembrete.setTitulo(Value: String);
begin
FTitulo := Value;
end;
end.
|
unit VoyagerUIEvents;
interface
uses
Windows;
const
evnBase_UIEvents = 100;
const
evnScrollStart = evnBase_UIEvents + 0;
evnScroll = evnBase_UIEvents + 1;
evnScrollEnd = evnBase_UIEvents + 2;
type
TScrollDirection = (scrHorizontal, scrVertical);
TScrollBias = (sbsNone, sbsNegative, sbsPositive);
TScrollDirInfo = array[TScrollDirection] of TScrollBias;
type
TEvnScrollStartInfo =
record
MousePos : TPoint;
end;
TEvnScrollInfo =
record
DirInfo : TScrollDirInfo;
MousePos : TPoint;
end;
TEvnScrollEndInfo =
record
MousePos : TPoint;
end;
implementation
end.
|
program RijndaelTool;
{ Copyright (c) 2001, Tom Verhoeff (TUE) }
{ Version 1.0 (July 2001) }
{ Interactive example program using FreePascal library RijndaelECB }
uses RijndaelECB;
procedure Pad0 ( var s: String );
begin
s := UpCase ( s )
; while Length ( s ) < HexStrLen do begin
s := s + '0'
end { while }
end; { Pad0 }
procedure Interact;
{ interactively encrypt/decrypt messages }
const
Unmodified = ''; { to mark unmodified block }
Modified = ' <-- updated'; { to mark modified block }
var
command: Char; { input command }
p, k, c, tmp: HexStr;
pt, ck, ct: Block;
pStatus, kStatus, cStatus: String;
begin
p := ''
; k := ''
; c := ''
; pStatus := Unmodified
; kStatus := Unmodified
; cStatus := Unmodified
; repeat
writeln
; Pad0 ( p )
; Pad0 ( k )
; Pad0 ( c )
; writeln ( 'Plaintext = ', p, pStatus )
; writeln ( 'Key = ', k, kStatus )
; writeln ( 'Ciphertext = ', c, cStatus )
; writeln ( 'HexStr index 12345678901234567890123456789012 (mod 10)' )
; writeln ( 'Block index 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 (mod 10)' )
; pStatus := Unmodified
; kStatus := Unmodified
; cStatus := Unmodified
; write ( 'P(laintext, K(ey, C(iphertext, E(ncrypt, D(ecrypt, S(wap, Q(uit? ' )
; readln ( command )
; command := UpCase ( command )
; case command of
'P': begin
write ( 'Plaintext? ' )
; readln ( p )
; pStatus := Modified
end;
'K': begin
write ( 'Key? ' )
; readln ( k )
; kStatus := Modified
end;
'C': begin
write ( 'Ciphertext? ' )
; readln ( c )
; cStatus := Modified
end;
'E': begin
HexStrToBlock ( p, pt )
; HexStrToBlock ( k, ck )
; Encrypt ( pt, ck, ct )
; BlockToHexStr ( ct, c )
; writeln ( 'Encrypted plaintext with key to ciphertext' )
; cStatus := Modified
end;
'D': begin
HexStrToBlock ( c, ct )
; HexStrToBlock ( k, ck )
; Decrypt ( ct, ck, pt )
; BlockToHexStr ( pt, p )
; writeln ( 'Decrypted ciphertext with key to plaintext' )
; pStatus := Modified
end;
'S': begin
tmp := p
; p := c
; c := tmp
; writeln ( 'Swapped plaintext and ciphertext' )
; pStatus := Modified
; cStatus := Modified
end;
'Q': writeln ( 'End of Interaction with RijndaelECB' );
else writeln ( 'Unknown command ''', command, '''' )
end { case }
until command = 'Q'
end; { Interact }
begin
writeln ( 'Interactive Tool for Using FreePascal Library RijndaelECB' )
; Interact
end.
|
unit Circuits;
interface
uses
Windows, VoyagerServerInterfaces;
type
ICircuitsRendering =
interface
end;
type
IPointsArray =
interface
function GetPointCount : integer;
function GetPointAt(idx : integer) : TPoint;
procedure AddPoint(const Point : TPoint);
procedure RemovePoint( idx : integer);
function HasPoint(x, y : integer) : boolean;
procedure RemoveAll;
function Clone : IPointsArray;
property PointCount : integer read GetPointCount;
property Points[idx : integer] : TPoint read GetPointAt; default;
end;
type
TPointsBuffer = array [1..1] of TPoint;
PPointsBuffer = ^TPointsBuffer;
type
TPointsArray =
class(TInterfacedObject, IPointsArray)
private
fPoints : PPointsBuffer;
fAllocated : integer;
fCount : integer;
private // IPointsArray
function GetPointCount : integer;
function GetPointAt(idx : integer) : TPoint;
procedure AddPoint(const Point : TPoint);
procedure RemovePoint(idx : integer);
function HasPoint(x, y : integer) : boolean;
procedure RemoveAll;
function Clone : IPointsArray;
public
constructor Create;
constructor CreateEmpty;
destructor Destroy; override;
end;
function FindCircuitSegments(x1, y1, x2, y2 : integer) : TSegmentReport;
function FindCircuitPoints(x1, y1, x2, y2 : integer) : IPointsArray;
procedure ClipSegments(var SegmentReport : TSegmentReport; xmin, ymin, xmax, ymax : integer);
implementation
uses
SysUtils;
// TPointsArray
const
idxNone = 0;
const
AllocChunk = 10;
constructor TPointsArray.Create;
begin
inherited;
fAllocated := AllocChunk;
getmem(fPoints, AllocChunk*sizeof(TPoint));
end;
constructor TPointsArray.CreateEmpty;
begin
inherited;
end;
destructor TPointsArray.Destroy;
begin
freemem(fPoints);
end;
function TPointsArray.GetPointCount : integer;
begin
Result := fCount;
end;
function TPointsArray.GetPointAt( idx : integer ) : TPoint;
begin
if (idx >= 1 ) and (idx <= fCount)
then Result := fPoints[idx]
else raise Exception.Create( 'Illegal point index' );
end;
procedure TPointsArray.AddPoint(const Point : TPoint);
begin
if fCount = fAllocated
then
begin
inc(fAllocated, AllocChunk);
reallocmem(fPoints, fAllocated*sizeof(Point));
end;
inc(fCount);
fPoints[fCount] := Point;
end;
procedure TPointsArray.RemovePoint(idx : integer);
begin
move(fPoints^[idx + 1], fPoints^[idx], (fCount - idx)*sizeof(fPoints[1]));
dec(fCount);
end;
function TPointsArray.HasPoint(x, y : integer) : boolean;
var
PtIdx : integer;
begin
PtIdx := 1;
while (PtIdx <= fCount) and ((fPoints[PtIdx].x <> x) or (fPoints[PtIdx].y <> y)) do
inc(PtIdx);
if PtIdx <= fCount
then Result := true
else Result := false;
end;
procedure TPointsArray.RemoveAll;
begin
fCount := 0;
if fAllocated <> AllocChunk
then
begin
fAllocated := AllocChunk;
freemem(fPoints);
getmem(fPoints, AllocChunk*sizeof(fPoints[1]));
end;
end;
function TPointsArray.Clone : IPointsArray;
var
Tmp : TPointsArray;
begin
Tmp := TPointsArray.CreateEmpty;
Tmp.fAllocated := fAllocated;
Tmp.fCount := fCount;
getMem(Tmp.fPoints, Tmp.fAllocated*sizeof(fPoints[1]));
move(fPoints^, Tmp.fPoints^, fCount*sizeof(fPoints[1]));
Result := Tmp;
end;
function FindCircuitSegments(x1, y1, x2, y2 : integer) : TSegmentReport;
var
x : integer;
y : integer;
deltax : integer;
deltay : integer;
SegReport : TSegmentReport;
aSegment : TSegmentInfo;
procedure AddSegment(SegInfo : TSegmentInfo);
begin
with SegReport do
begin
inc( SegmentCount );
reallocmem(Segments, SegmentCount*SizeOf(TSegmentInfo));
Segments[SegmentCount - 1] := SegInfo;
end
end;
begin
with SegReport do
begin
SegmentCount := 0;
Segments := nil
end;
x := x1;
y := y1;
if x2 > x1
then deltax := 1
else deltax := -1;
if y2 > y1
then deltay := 1
else deltay := -1;
if abs(x2 - x1) <= abs(y2 - y1)
then // try to approach a vertical line
begin
while (x <> x2) and (y <> y2) do
begin
aSegment.x1 := x;
aSegment.y1 := y;
aSegment.x2 := x + deltax;
aSegment.y2 := y;
AddSegment(aSegment);
aSegment.x1 := x + deltax;
aSegment.y1 := y;
aSegment.x2 := x + deltax;
aSegment.y2 := y + deltay;
AddSegment(aSegment);
inc(y, deltay);
inc(x, deltax);
end;
if y <> y2
then
begin
aSegment.x1 := x;
aSegment.y1 := y;
aSegment.x2 := x2;
aSegment.y2 := y2;
AddSegment(aSegment);
end
end
else // try to approach a horizontal line
begin
while (x <> x2) and (y <> y2) do
begin
aSegment.x1 := x;
aSegment.y1 := y;
aSegment.x2 := x;
aSegment.y2 := y + deltay;
AddSegment(aSegment);
aSegment.x1 := x;
aSegment.y1 := y + deltay;
aSegment.x2 := x + deltax;
aSegment.y2 := y + deltay;
AddSegment(aSegment);
inc(y, deltay);
inc(x, deltax);
end;
if x <> x2
then
begin
aSegment.x1 := x;
aSegment.y1 := y;
aSegment.x2 := x2;
aSegment.y2 := y2;
AddSegment(aSegment);
end
end;
Result := SegReport;
end;
function FindCircuitPoints(x1, y1, x2, y2 : integer) : IPointsArray;
var
x : integer;
y : integer;
deltax : integer;
deltay : integer;
CircPoints : IPointsArray;
aPoint : TPoint;
begin
CircPoints := TPointsArray.Create;
x := x1;
y := y1;
aPoint.x := x;
aPoint.y := y;
CircPoints.AddPoint(aPoint);
if x2 > x1
then deltax := 1
else deltax := -1;
if y2 > y1
then deltay := 1
else deltay := -1;
if abs(x2 - x1) <= abs(y2 - y1)
then // try to approach a vertical line
begin
while (x <> x2) and (y <> y2) do
begin
aPoint.x := x + deltax;
aPoint.y := y;
CircPoints.AddPoint(aPoint);
aPoint.x := x + deltax;
aPoint.y := y + deltay;
CircPoints.AddPoint(aPoint);
inc(y, deltay);
inc(x, deltax);
end;
if y <> y2
then
repeat
inc(y, deltay);
aPoint.x := x;
aPoint.y := y;
CircPoints.AddPoint(aPoint);
until y = y2;
end
else // try to approach a horizontal line
begin
while (x <> x2) and (y <> y2) do
begin
aPoint.x := x;
aPoint.y := y + deltay;
CircPoints.AddPoint(aPoint);
aPoint.x := x + deltax;
aPoint.y := y + deltay;
CircPoints.AddPoint(aPoint);
inc(y, deltay);
inc(x, deltax);
end;
if x <> x2
then
repeat
inc(x, deltax);
aPoint.x := x;
aPoint.y := y;
CircPoints.AddPoint(aPoint);
until x = x2;
end;
Result := CircPoints;
end;
procedure ClipSegments(var SegmentReport : TSegmentReport; xmin, ymin, xmax, ymax : integer);
function ClipInteger(Val, Min, Max : integer) : integer;
begin
if Val < Min
then Result := Min
else
if Val > Max
then Result := Max
else Result := Val;
end;
var
SegIdx : integer;
SegCnt : integer;
begin
SegCnt := 0;
with SegmentReport do
begin
for SegIdx := 0 to pred(SegmentCount) do
begin
if (((Segments[SegIdx].x1 >= xmin) or (Segments[SegIdx].x2 >= xmin)) and
((Segments[SegIdx].x1 <= xmax) or (Segments[SegIdx].x2 <= xmax))) and
(((Segments[SegIdx].y1 >= ymin) or (Segments[SegIdx].y2 >= ymin)) and
((Segments[SegIdx].y1 <= ymax) or (Segments[SegIdx].y2 <= ymax)))
then
begin
Segments[SegCnt].x1 := ClipInteger(Segments[SegIdx].x1, xmin, xmax);
Segments[SegCnt].x2 := ClipInteger(Segments[SegIdx].x2, xmin, xmax);
Segments[SegCnt].y1 := ClipInteger(Segments[SegIdx].y1, ymin, ymax);
Segments[SegCnt].y2 := ClipInteger(Segments[SegIdx].y2, ymin, ymax);
inc(SegCnt);
end;
end;
reallocmem(Segments, SegCnt*sizeof(Segments[0]));
SegmentCount := SegCnt;
end;
end;
end.
|
unit NativeClassStorage;
interface
uses
ClassStorageInt, Classes, Windows, SysUtils;
type
TNativeClassStorage =
class( TClassStorage )
public
constructor Create;
destructor Destroy; override;
protected
function GetClassByIdx( ClassFamilyId : TClassFamilyId; Idx : integer ) : TObject; override;
function GetClassById ( ClassFamilyId : TClassFamilyId; Id : TClassId ) : TObject; override;
function GetClassCount( ClassFamilyId : TClassFamilyId ) : integer; override;
published
procedure RegisterClass( ClassFamilyId : TClassFamilyId; TheClassId : TClassId; TheClass : TObject ); override;
procedure RegisterEqv( ClassFamilyId : TClassFamilyId; OldId, NewId : TClassId ); override;
private
fFamilies : TStringList;
fEqvList : TStringList;
fLock : TRTLCriticalSection;
end;
implementation
// TNativeClassStorage
constructor TNativeClassStorage.Create;
begin
inherited;
InitializeCriticalSection( fLock );
EnterCriticalSection( fLock );
fFamilies := TStringList.Create;
fFamilies.Sorted := true;
fFamilies.Duplicates := dupError;
fEqvList := TStringList.Create;
LeaveCriticalSection( fLock );
end;
destructor TNativeClassStorage.Destroy;
var
i : integer;
Family : TStringList;
begin
EnterCriticalSection( fLock );
for i := 0 to pred(fFamilies.Count) do
begin
Family := TStringList(fFamilies.Objects[i]);
{ >> Pending for solution
for j := 0 to pred(Family.Count) do
Family.Objects[j].Free;
}
Family.Clear;
Family.Free;
end;
fFamilies.Clear;
fFamilies.Free;
fEqvList.Free;
LeaveCriticalSection( fLock );
DeleteCriticalSection( fLock );
inherited;
end;
function TNativeClassStorage.GetClassByIdx( ClassFamilyId : TClassFamilyId; Idx : integer ) : TObject;
var
Family : TStringList;
FamIdx : integer;
begin
result := nil;
EnterCriticalSection( fLock );
try
if fFamilies.Find( ClassFamilyId, FamIdx )
then
begin
Family := fFamilies.Objects[FamIdx] as TStringList;
if Idx < Family.Count
then result := Family.Objects[Idx]
else raise EClassStorageException.Create( 'Index out of range in family "' + ClassFamilyId + '".' );
end
else raise EClassStorageException.Create( 'Unknown class family "' + ClassFamilyId + '".');
finally
LeaveCriticalSection( fLock );
end;
end;
function TNativeClassStorage.GetClassById( ClassFamilyId : TClassFamilyId; Id : TClassId ) : TObject;
var
Family : TStringList;
Idx : integer;
NewId : string;
begin
result := nil;
EnterCriticalSection( fLock );
try
if fFamilies.Find( ClassFamilyId, Idx )
then
begin
Family := fFamilies.Objects[Idx] as TStringList;
if Family.Find( Id, Idx )
then result := Family.Objects[Idx]
else
begin
NewId := fEqvList.Values[ClassFamilyId + '.' + Id];
if NewId <> ''
then result := GetClassById( ClassFamilyId, NewId )
else result := nil //raise EClassStorageException.Create( 'Unknown class "' + Id + '" in family "' + ClassFamilyId + '".');
end
end
else raise EClassStorageException.Create( 'Unknown class family "' + ClassFamilyId + '".');
finally
LeaveCriticalSection( fLock );
end;
end;
function TNativeClassStorage.GetClassCount( ClassFamilyId : TClassFamilyId ) : integer;
var
Idx : integer;
begin
EnterCriticalSection( fLock );
try
if fFamilies.Find( ClassFamilyId, Idx )
then result := (fFamilies.Objects[Idx] as TStringList).Count
else result := 0//raise EClassStorageException.Create( 'Unknown class family "' + ClassFamilyId + '".');
finally
LeaveCriticalSection( fLock );
end;
end;
procedure TNativeClassStorage.RegisterClass( ClassFamilyId : TClassFamilyId; TheClassId : TClassId; TheClass : TObject );
var
Family : TStringList;
FamIdx : integer;
begin
EnterCriticalSection( fLock );
if fFamilies.Find( ClassFamilyId, FamIdx )
then Family := fFamilies.Objects[FamIdx] as TStringList
else
begin
Family := TStringList.Create;
Family.Sorted := true;
Family.Duplicates := dupError;
fFamilies.AddObject( ClassFamilyId, Family );
end;
Family.AddObject( TheClassId, TheClass );
LeaveCriticalSection( fLock );
end;
procedure TNativeClassStorage.RegisterEqv( ClassFamilyId : TClassFamilyId; OldId, NewId : TClassId );
begin
fEqvList.Add( ClassFamilyId + '.' + OldId + '=' + NewId );
end;
end.
|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uLogEventImpl.pas }
{ Описание: Реализация ILogEvent }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uLogEventImpl;
interface
uses
SysUtils, Classes, uServices;
function CreateLogEvent: ILogEvent;
implementation
uses
uInterfaceFactory, JclSysInfo;
type
TLogEvent = class(TInterfacedObject, ILogEvent)
private
FApplicationName: string;
FApplicationUserName: string;
FComputerName: string;
FComputerUserName: string;
FEventDateTime: TDateTime;
FEventKind: TEventKind;
FEventText: string;
public
constructor Create;
function GetApplicationName: string; stdcall;
function GetApplicationUserName: string; stdcall;
function GetComputerName: string; stdcall;
function GetComputerUserName: string; stdcall;
function GetEventDateTime: TDateTime; stdcall;
function GetEventKind: TEventKind; stdcall;
function GetEventText: string; stdcall;
procedure SetApplicationName(const Value: string); stdcall;
procedure SetApplicationUserName(const Value: string); stdcall;
procedure SetComputerName(const Value: string); stdcall;
procedure SetComputerUserName(const Value: string); stdcall;
procedure SetEventDateTime(Value: TDateTime); stdcall;
procedure SetEventKind(Value: TEventKind); stdcall;
procedure SetEventText(const Value: string); stdcall;
property ApplicationName: string read GetApplicationName write
SetApplicationName;
property ApplicationUserName: string read GetApplicationUserName write
SetApplicationUserName;
property ComputerName: string read GetComputerName write SetComputerName;
property ComputerUserName: string read GetComputerUserName write
SetComputerUserName;
property EventDateTime: TDateTime read GetEventDateTime write
SetEventDateTime;
property EventKind: TEventKind read GetEventKind write SetEventKind;
property EventText: string read GetEventText write SetEventText;
end;
{
********************************** TLogEvent ***********************************
}
constructor TLogEvent.Create;
var
SecurityService: ISecurityService;
begin
inherited Create;
FApplicationName := ExtractFileName(ParamStr(0));
FComputerName := GetLocalComputerName;
FComputerUserName := GetLocalUserName;
FEventDateTime := TimeService.CurrentDateTime;
FApplicationUserName := 'Неаутентифицированный пользователь';
if Services.TryGetService(ISecurityService, SecurityService) then
begin
FApplicationUserName := SecurityService.CurrentUserFio;
end;
end;
function TLogEvent.GetApplicationName: string;
begin
Result := FApplicationName;
end;
function TLogEvent.GetApplicationUserName: string;
begin
Result := FApplicationUserName;
end;
function TLogEvent.GetComputerName: string;
begin
Result := FComputerName;
end;
function TLogEvent.GetComputerUserName: string;
begin
Result := FComputerUserName;
end;
function TLogEvent.GetEventDateTime: TDateTime;
begin
Result := FEventDateTime;
end;
function TLogEvent.GetEventKind: TEventKind;
begin
Result := FEventKind;
end;
function TLogEvent.GetEventText: string;
begin
Result := FEventText;
end;
procedure TLogEvent.SetApplicationName(const Value: string);
begin
if FApplicationName <> Value then
begin
FApplicationName := Value;
end;
end;
procedure TLogEvent.SetApplicationUserName(const Value: string);
begin
if FApplicationUserName <> Value then
begin
FApplicationUserName := Value;
end;
end;
procedure TLogEvent.SetComputerName(const Value: string);
begin
if FComputerName <> Value then
begin
FComputerName := Value;
end;
end;
procedure TLogEvent.SetComputerUserName(const Value: string);
begin
if FComputerUserName <> Value then
begin
FComputerUserName := Value;
end;
end;
procedure TLogEvent.SetEventDateTime(Value: TDateTime);
begin
if FEventDateTime <> Value then
begin
FEventDateTime := Value;
end;
end;
procedure TLogEvent.SetEventKind(Value: TEventKind);
begin
if FEventKind <> Value then
begin
FEventKind := Value;
end;
end;
procedure TLogEvent.SetEventText(const Value: string);
begin
if FEventText <> Value then
begin
FEventText := Value;
end;
end;
function CreateLogEvent: ILogEvent;
begin
Result := TLogEvent.Create;
end;
end.
|
{ *************************************************************************** }
{ }
{ This file is part of the XPde project }
{ }
{ Copyright (c) 2002 Jose Leon Serna <ttm@xpde.com> }
{ }
{ This program is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU General Public }
{ License as published by the Free Software Foundation; either }
{ version 2 of the License, or (at your option) any later version. }
{ }
{ This program is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ General Public License for more details. }
{ }
{ You should have received a copy of the GNU General Public License }
{ along with this program; see the file COPYING. If not, write to }
{ the Free Software Foundation, Inc., 59 Temple Place - Suite 330, }
{ Boston, MA 02111-1307, USA. }
{ }
{ *************************************************************************** }
unit main;
interface
uses
SysUtils, Types, Classes,
Variants, QTypes, QGraphics,
QControls, QForms, QDialogs,
QStdCtrls, uXPDesktop, QButtons,
uCommon, QMenus, Libc;
type
TMainform = class(TForm)
desktop_properties: TPopupMenu;
Exit1: TMenuItem;
N1: TMenuItem;
Properties1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure Properties1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure createDesktop;
end;
var
Mainform: TMainform;
desktop: TXPDesktop;
implementation
{$R *.xfm}
//Creates the desktop object
procedure TMainform.createDesktop;
begin
desktop:=TXPDesktop.create(self);
desktop.Font.assign(self.font);
desktop.parent:=self;
desktop.font.color:=clWhite;
desktop.align:=alClient;
desktop.popupmenu:=desktop_properties;
application.Font.assign(self.font);
desktop.setup;
end;
procedure TMainform.FormCreate(Sender: TObject);
begin
//Stores the app dir and creates the desktop
storeAppDir;
BorderStyle:=fbsNone;
left:=0;
top:=0;
width:=screen.width;
height:=screen.height;
createDesktop;
desktop.SendToBack;
end;
procedure TMainform.Exit1Click(Sender: TObject);
begin
application.terminate;
end;
procedure TMainform.Properties1Click(Sender: TObject);
var
applet: string;
begin
//Executes the properties applet
{ TODO : Develop a common way to execute apps }
applet:=getSystemInfo(XP_APP_DIR)+'applets/desktop_properties &';
libc.system(PChar(applet));
end;
procedure TMainform.FormShow(Sender: TObject);
begin
sendtoback;
end;
end.
|
unit DocStack;
{ $Id: DocStack.pas,v 1.14 2016/06/16 05:38:41 lukyanets Exp $ }
interface
Uses l3Base, l3ObjectStringList, DT_Const, daTypes, l3DatLst,
l3LongintList,
l3ProtoObject
;
type
TDocStackItem = class(Tl3ProtoObject)
public
DocFam : TdaFamilyID;
DocID : Longint;
AnchorID : Longint;
Positions : Tl3LongintList;
constructor Create(aDocFam: TdaFamilyID; aDocID: Longint; aAnchorID: Longint; aPositions: Tl3LongintList);
procedure Cleanup; override;
end;
TOnCurrentChanged = procedure(aNewCurrent : Integer) of object;
TDocStack = class(Tl3ObjectStringList)
private
f_CurrentItem: Integer;
f_OnCurrentChanged: TOnCurrentChanged;
function GetDocRecord(Index: Longint) : TDocStackItem;
procedure pm_SetCurrentItem(const Value: Integer);
public
constructor Create; override;
procedure AddDoc(Const DocName : String; DocFam : TdaFamilyID;
DocID : Longint; aAnchorID : Longint; aPositions: Tl3LongintList; aDoCutTail: Boolean = True);
procedure ReplaceData(aIndex: Integer; aAnchorID : Longint; aPositions: Tl3LongintList);
procedure PrepareForPair;
procedure FillStringList(aList: Tl3StringDataList);
property CurrentItem: Integer read f_CurrentItem write pm_SetCurrentItem;
property DocRec[Index: Longint] : TDocStackItem read GetDocRecord;
property OnCurrentChanged: TOnCurrentChanged read f_OnCurrentChanged write f_OnCurrentChanged;
end;
implementation
uses
l3String
;
constructor TDocStack.Create;
begin
inherited Create;
end;
procedure TDocStack.AddDoc(Const DocName : String; DocFam : TdaFamilyID;
DocID : Longint; aAnchorID : Longint;
aPositions: Tl3LongintList; aDoCutTail: Boolean = True);
var
l_Item : TDocStackItem;
begin
l_Item := TDocStackItem.Create(DocFam, DocID, aAnchorID, aPositions);
try
f_CurrentItem := Add(DocName, l_Item);
finally
l3Free(l_Item);
end;
If Assigned(f_OnCurrentChanged) then f_OnCurrentChanged(f_CurrentItem);
end;
procedure TDocStack.FillStringList(aList: Tl3StringDataList);
var
I: Integer;
begin
aList.Clear;
aList.AddStr(Strings[0]);
I := 1;
while I < Count do
begin
aList.AddStr(Strings[I]);
I := I + 2;
end;
end;
function TDocStack.GetDocRecord(Index: Longint) : TDocStackItem;
begin
Result := TDocStackItem(Objects[Index]);
end;
procedure TDocStack.pm_SetCurrentItem(const Value: Integer);
begin
if f_CurrentItem <> Value then
begin
f_CurrentItem := Value;
if Assigned(f_OnCurrentChanged) then
f_OnCurrentChanged(Value);
end;
end;
procedure TDocStack.PrepareForPair;
begin
// лечим рассогласование. Как это происходит до конца не понятно, как-то умудрился не вовремя полузагруженное окно редактора выключить
if f_CurrentItem > pred(Count) then
f_CurrentItem := pred(Count);
// подготовка к принятию в историю следующей пары документов...
while pred(Count) > f_CurrentItem do
Delete(f_CurrentItem+1);
if (Count > 0) and (f_CurrentItem mod 2 = 0) then
Delete(f_CurrentItem);
end;
procedure TDocStack.ReplaceData(aIndex: Integer; aAnchorID : Longint; aPositions: Tl3LongintList);
var
l_Temp: TDocStackItem;
begin
l_Temp := DocRec[aIndex];
l3Free(l_Temp.Positions);
l_Temp.AnchorID := aAnchorID;
l_Temp.Positions := aPositions;
end;
constructor TDocStackItem.Create(aDocFam: TdaFamilyID; aDocID: Longint; aAnchorID: Longint; aPositions: Tl3LongintList);
begin
inherited Create;
DocFam := aDocFam;
DocID := aDocID;
AnchorID := aAnchorID;
Positions := aPositions;
end;
procedure TDocStackItem.Cleanup;
begin
if Assigned(Positions) then
l3Free(Positions);
inherited;
end;
end.
|
unit UserLicenseRequestUnit;
interface
uses
REST.Json.Types,
GenericParametersUnit, CommonTypesUnit, EnumsUnit;
type
TUserLicenseRequest = class(TGenericParameters)
private
[JSONName('member_id')]
FMemberId: integer;
[JSONName('session_guid')]
FSessionId: integer;
[JSONName('device_id')]
FDeviceId: String;
[JSONName('device_type')]
FDeviceType: String;
[JSONName('subscription_name')]
FSubscription: String;
[JSONName('token')]
FToken: String;
[JSONName('payload')]
FPayload: String;
[JSONName('format')]
FFormat: String;
public
constructor Create(MemberId, SessionId: integer; DeviceId: String;
DeviceType: TDeviceType; Subscription: String; Token: String;
Payload: String; Format: String = 'json'); reintroduce;
end;
implementation
constructor TUserLicenseRequest.Create(MemberId, SessionId: integer;
DeviceId: String; DeviceType: TDeviceType; Subscription: String;
Token: String; Payload: String; Format: String = 'json');
begin
Inherited Create;
FMemberId := MemberId;
FSessionId := SessionId;
FDeviceId := DeviceId;
FDeviceType := TDeviceTypeDescription[DeviceType];
FSubscription := Subscription;
FToken := Token;
FPayload := Payload;
FFormat := Format;
end;
end.
|
unit sdsMainWindow;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "MainWindowControllers$BaseOperations"
// Автор: Люлин А.В.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/MainWindowControllers/sdsMainWindow.pas"
// Начат: 03.05.2011 18:29
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UseCaseControllerImp::Class>> F1 Core::Base Operations::MainWindowControllers$BaseOperations::MainWindowControllersRealization::TsdsMainWindow
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
l3Interfaces
{$If not defined(NoVCM)}
,
vcmControllers
{$IfEnd} //not NoVCM
,
l3StringIDEx,
MainWindowInterfaces
{$If not defined(NoVCM)}
,
vcmInterfaces
{$IfEnd} //not NoVCM
,
l3ProtoObjectWithCOMQI,
l3NotifyPtrList
{$If not defined(NoVCM)}
,
vcmExternalInterfaces
{$IfEnd} //not NoVCM
,
DocumentAndListInterfaces {a},
nevBase
{$If not defined(NoVCM)}
,
vcmUserControls
{$IfEnd} //not NoVCM
,
nsTypes,
DocumentInterfaces
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
_SetType_ = IsdsMainWindow;
{$Include w:\common\components\gui\Garant\VCM\implementation\vcmTinyUseCaseController.imp.pas}
TsdsMainWindow = {ucc} class(_vcmTinyUseCaseController_, IsdsMainWindow, InsWarningGenerator {from IsdsMainWindow})
private
// private fields
f_OldBaseWarning : Il3CString;
f_dsBaloonWarning : IvcmViewAreaControllerRef;
{* Поле для области вывода dsBaloonWarning}
protected
// property methods
function pm_GetOldBaseWarning: Il3CString; virtual;
protected
// realized methods
function pm_GetDsBaloonWarning: IdsWarning;
function DoGet_dsBaloonWarning: IdsWarning;
public
// realized methods
function Generate(const aWarning: IdsWarning;
const aGen: InevTagGenerator;
aUserType: TvcmUserType): TWarningTypeSet;
{* Результат сообщает о том, какие предупреждения есть у документа. Если нет ни одного предупреждения, то вернется cEmptyWarning }
protected
// overridden protected methods
{$If not defined(NoVCM)}
procedure ClearAreas; override;
{* Очищает ссылки на области ввода }
{$IfEnd} //not NoVCM
procedure ClearFields; override;
private
// private properties
property OldBaseWarning: Il3CString
read pm_GetOldBaseWarning;
protected
// Методы преобразования к реализуемым интерфейсам
function As_InsWarningGenerator: InsWarningGenerator;
end;//TsdsMainWindow
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
uses
dsWarning,
WarningUserTypes_Warning_UserType,
Document_Const,
bsUtils,
DataAdapter,
l3String,
l3Base,
l3Chars,
evdTypes,
k2Tags,
BaloonWarningUserTypes_Fake_UserType,
BaloonWarningUserTypes_WarnJuror_UserType,
BaloonWarningUserTypes_WarnPreActive_UserType,
BaloonWarningUserTypes_WarnIsAbolished_UserType,
BaloonWarningUserTypes_WarnOnControl_UserType,
BaloonWarningUserTypes_WarnInactualDocument_UserType,
BaloonWarningUserTypes_WarnTimeMachineOn_UserType,
BaloonWarningUserTypes_WarnRedaction_UserType,
BaloonWarningUserTypes_WarnTimeMachineWarning_UserType,
BaloonWarningUserTypes_WarnTimeMachineException_UserType,
BaloonWarningUserTypes_remListModified_UserType,
BaloonWarningUserTypes_remListFiltered_UserType,
BaloonWarningUserTypes_remTimeMachineWarning_UserType,
BaloonWarningUserTypes_remUnreadConsultations_UserType,
BaloonWarningUserTypes_remOnlineDead_UserType,
BaloonWarningUserTypes_TrialModeWarning_UserType,
BaloonWarningUserTypes_OldBaseWarning_UserType,
BaloonWarningUserTypes_ControlledChangingWarning_UserType,
l3MessageID
{$If not defined(NoVCM)}
,
vcmLocalInterfaces
{$IfEnd} //not NoVCM
,
SysUtils,
vcmFormDataSourceRef {a}
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type _Instance_R_ = TsdsMainWindow;
{$Include w:\common\components\gui\Garant\VCM\implementation\vcmTinyUseCaseController.imp.pas}
var
{ Локализуемые строки Local }
str_mwUnreadConsultations : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mwUnreadConsultations'; rValue : 'Получены ответы или уведомления от службы Правовой поддержки онлайн. Перейти к тексту ответа.');
{ 'Получены ответы или уведомления от службы Правовой поддержки онлайн. Перейти к тексту ответа.' }
str_mwUnreadConsultationsLink : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mwUnreadConsultationsLink'; rValue : 'Перейти к тексту ответа');
{ 'Перейти к тексту ответа' }
str_mwOnlineDead : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mwOnlineDead'; rValue : 'С момента последнего обновления Вашего информационного банка прошло более 6 месяцев. ' +
'Онлайн-проверка актуальности документов отключена.' + #13#10 +
'Для обновления системы ГАРАНТ обратитесь в обслуживающую Вас организацию:' + #13#10 +
'%s');
{ 'С момента последнего обновления Вашего информационного банка прошло более 6 месяцев. ' +
'Онлайн-проверка актуальности документов отключена.' + #13#10 +
'Для обновления системы ГАРАНТ обратитесь в обслуживающую Вас организацию:' + #13#10 +
'%s' }
str_mwTrialModeWarning : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mwTrialModeWarning'; rValue : 'Вы работаете с ознакомительной версией системы ГАРАНТ.' +
' До окончания срока ее действия осталось дней: %s.' + #13#10 + #13#10 +
'Чтобы стать зарегистрированным пользователем системы ГАРАНТ и получать полный комплекс информационно-правового обеспечения, обращайтесь в компанию "Гарант" или к ее региональным партнерам:' + #13#10 + #13#10 +
'%s');
{ 'Вы работаете с ознакомительной версией системы ГАРАНТ.' +
' До окончания срока ее действия осталось дней: %s.' + #13#10 + #13#10 +
'Чтобы стать зарегистрированным пользователем системы ГАРАНТ и получать полный комплекс информационно-правового обеспечения, обращайтесь в компанию "Гарант" или к ее региональным партнерам:' + #13#10 + #13#10 +
'%s' }
str_mwControlledChangingWarning : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'mwControlledChangingWarning'; rValue : 'Внимание! Документы на контроле изменились.');
{ 'Внимание! Документы на контроле изменились.' }
// start class TsdsMainWindow
function TsdsMainWindow.pm_GetOldBaseWarning: Il3CString;
//#UC START# *4DC03F5B00A1_4DC011350154get_var*
//#UC END# *4DC03F5B00A1_4DC011350154get_var*
begin
//#UC START# *4DC03F5B00A1_4DC011350154get_impl*
if (f_OldBaseWarning = nil) then
f_OldBaseWarning := l3CStr(l3RTrim(defDataAdapter.GetOldBaseWarning.AsWStr,
cc_NonReadable));
Result := f_OldBaseWarning;
//#UC END# *4DC03F5B00A1_4DC011350154get_impl*
end;//TsdsMainWindow.pm_GetOldBaseWarning
function TsdsMainWindow.Generate(const aWarning: IdsWarning;
const aGen: InevTagGenerator;
aUserType: TvcmUserType): TWarningTypeSet;
//#UC START# *493E4F7E039B_4DC011350154_var*
//#UC END# *493E4F7E039B_4DC011350154_var*
begin
//#UC START# *493E4F7E039B_4DC011350154_impl*
Result := [];
if (aGen <> nil) then
begin
aGen.Start;
try
aGen.StartChild(k2_idDocument);
try
aGen.AddIntegerAtom(k2_tiSpaceBefore, 0);
Case aUserType of
remUnreadConsultations:
bsEditorAddPara(aGen, str_mwUnreadConsultations.AsWStr, true,
cNoneWarningSub,
cNone_LinkHandle,
0,
0,
str_mwUnreadConsultationsLink.AsCStr,
cUnreadConsultations_LinkHandle);
BaloonWarningUserTypes_OldBaseWarning_UserType.OldBaseWarning:
bsEditorAddPara(aGen, l3PCharLen(Self.OldBaseWarning), true,
ev_itLeft, true);
remOnlineDead:
bsEditorAddPara(aGen,
l3Fmt(str_mwOnlineDead.AsCStr,
[DefDataAdapter.GetDealerInfo]).AsWStr,
true);
TrialModeWarning:
bsEditorAddPara(aGen,
l3Fmt(str_mwTrialModeWarning.AsCStr,
[DefDataAdapter.TrialDaysLeft,
DefDataAdapter.GetDealerInfo]).AsWStr,
true);
ControlledChangingWarning:
bsEditorAddPara(aGen, str_mwControlledChangingWarning.AsWStr, true);
else
Assert(false);
end;//Case aUserType
finally
aGen.Finish;
end;//try..finally
finally
aGen.Finish;
end;//try..finally
end;//aGen <> nil
//#UC END# *493E4F7E039B_4DC011350154_impl*
end;//TsdsMainWindow.Generate
function TsdsMainWindow.pm_GetDsBaloonWarning: IdsWarning;
//#UC START# *4DC010300124_4DC011350154get_var*
//#UC END# *4DC010300124_4DC011350154get_var*
begin
if (f_dsBaloonWarning = nil) then
begin
f_dsBaloonWarning := TvcmViewAreaControllerRef.Make;
//#UC START# *4DC010300124_4DC011350154get_init*
// - код инициализации ссылки на ViewArea
//#UC END# *4DC010300124_4DC011350154get_init*
end;//f_dsBaloonWarning = nil
if f_dsBaloonWarning.IsEmpty
//#UC START# *4DC010300124_4DC011350154get_need*
// - условие создания ViewArea
//#UC END# *4DC010300124_4DC011350154get_need*
then
f_dsBaloonWarning.Referred := DoGet_dsBaloonWarning;
Result := IdsWarning(f_dsBaloonWarning.Referred);
end;
function TsdsMainWindow.DoGet_dsBaloonWarning: IdsWarning;
//#UC START# *4DC010300124_4DC011350154area_var*
//#UC END# *4DC010300124_4DC011350154area_var*
begin
//#UC START# *4DC010300124_4DC011350154area_impl*
Result := TdsWarning.Make(Self);
//#UC END# *4DC010300124_4DC011350154area_impl*
end;//TsdsMainWindow.DoGet_dsBaloonWarning
{$If not defined(NoVCM)}
procedure TsdsMainWindow.ClearAreas;
{-}
begin
if (f_dsBaloonWarning <> nil) then f_dsBaloonWarning.Referred := nil;
inherited;
end;//TsdsMainWindow.ClearAreas
{$IfEnd} //not NoVCM
procedure TsdsMainWindow.ClearFields;
{-}
begin
f_OldBaseWarning := nil;
f_dsBaloonWarning := nil;
inherited;
end;//TsdsMainWindow.ClearFields
// Методы преобразования к реализуемым интерфейсам
function TsdsMainWindow.As_InsWarningGenerator: InsWarningGenerator;
begin
Result := Self;
end;
{$IfEnd} //not Admin AND not Monitorings
initialization
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_mwUnreadConsultations
str_mwUnreadConsultations.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_mwUnreadConsultationsLink
str_mwUnreadConsultationsLink.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_mwOnlineDead
str_mwOnlineDead.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_mwTrialModeWarning
str_mwTrialModeWarning.Init;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
// Инициализация str_mwControlledChangingWarning
str_mwControlledChangingWarning.Init;
{$IfEnd} //not Admin AND not Monitorings
end. |
unit RealState.Agent.Repository;
interface
uses
Data.DB,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
FireDAC.Stan.Async,
FireDAC.DApt,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
System.Classes,
System.SysUtils,
RealState.Repository;
type
TAgentRepository = class(TDataModule)
AgentQuery: TFDQuery;
AgentQueryID: TLargeintField;
AgentQueryName: TWideStringField;
AgentQueryPhone: TWideStringField;
AgentQueryPicture: TWideStringField;
procedure DataModuleCreate(Sender: TObject);
private
fRepository: TRepository;
procedure BindConnection;
protected
function Connection: TFDConnection;
public
function GetAgents: TDataSet;
end;
var
AgentRepository: TAgentRepository;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TAgentRepository.BindConnection;
begin
AgentQuery.Connection := Connection;
end;
function TAgentRepository.Connection: TFDConnection;
begin
Result := fRepository.Connection;
end;
procedure TAgentRepository.DataModuleCreate(Sender: TObject);
begin
fRepository := TRepository.Create(Self);
BindConnection;
end;
function TAgentRepository.GetAgents: TDataSet;
begin
Result := TFDMemTable.Create(nil);
AgentQuery.Open;
TFDTable(Result).CopyDataSet(AgentQuery, [coStructure, coRestart, coAppend]);
end;
end.
|
unit clEnderecoEntregador;
interface
uses
clEndereco, System.Classes, clConexao;
type
TEnderecoEntregador = class(TEndereco)
private
function getCodigo: Integer;
function getSequencia: Integer;
function getTipo: String;
function getCorrespondencia: Integer;
procedure setCodigo(const Value: Integer);
procedure setSequencia(const Value: Integer);
procedure setTipo(const Value: String);
procedure setCorrespondencia(const Value: Integer);
constructor Create;
destructor Destroy;
protected
// declaração de atributos
_codigo: Integer;
_sequencia: Integer;
_tipo: String;
_correspondencia: Integer;
_conexao: TConexao;
public
// declaração das propriedades da classe, encapsulamento de atributos
property Codigo: Integer read getCodigo write setCodigo;
property Sequencia: Integer read getSequencia write setSequencia;
property Tipo: String read getTipo write setTipo;
property Correspondencia: Integer read getCorrespondencia
write setCorrespondencia;
// na linha acima antes do ponto e virgula (setCidade) pressione Ctrl + Shift + C
// para gerar os métodos acessores getter e setter automaticamente
// declaração de métodos
procedure MaxSeq;
function Validar(): Boolean;
function Merge(): Boolean;
function Delete(Filtro: String): Boolean;
function getObject(Id: String; Filtro: String): Boolean;
function Insert(): Boolean;
function Update(): Boolean;
function EnderecoJaExiste(): Boolean;
function PopulaLocal(Filtro: String): TStringList;
end;
const
TABLENAME = 'TBENDERECOSENTREGADORES';
implementation
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
{ TEnderecoEntregador }
constructor TEnderecoEntregador.Create;
begin
_conexao := TConexao.Create;
if (not _conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados (' +
Self.ClassName + ') !', mtError, [mbCancel], 0);
end;
end;
destructor TEnderecoEntregador.Destroy;
begin
_conexao.Free;
end;
function TEnderecoEntregador.getCodigo: Integer;
begin
Result := _codigo;
end;
function TEnderecoEntregador.getSequencia: Integer;
begin
Result := _sequencia;
end;
function TEnderecoEntregador.getTipo: String;
begin
Result := _tipo;
end;
function TEnderecoEntregador.getCorrespondencia: Integer;
begin
Result := _correspondencia;
end;
function TEnderecoEntregador.Delete(Filtro: String): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if Filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_ENTREGADOR =:CODIGO');
ParamByName('CODIGO').AsString := IntToStr(Self.Codigo);
end
else if Filtro = 'TIPO' then
begin
SQL.Add('WHERE COD_ENTREGADOR =:CODIGO AND DES_TIPO = :TIPO');
ParamByName('CODIGO').AsString := IntToStr(Self.Codigo);
ParamByName('TIPO').AsString := Self.Tipo;
end;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoEntregador.getObject(Id, Filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(Id) then
Exit;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if Filtro = 'TIPO' then
begin
SQL.Add(' WHERE COD_ENTREGADOR =:CODIGO AND DES_TIPO =:TIPO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('TIPO').AsString := Id;
end
else if Filtro = 'CODIGO' then
begin
SQL.Add(' WHERE COD_ENTREGADOR =:CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(Id);
end;
dm.ZConn.PingServer;
Open;
if not IsEmpty then
First;
end;
if dm.QryGetObject.RecordCount > 0 then
begin
Self.Codigo := dm.QryGetObject.FieldByName('COD_ENTREGADOR').AsInteger;
Self.Sequencia := dm.QryGetObject.FieldByName('SEQ_ENDERECO').AsInteger;
Self.Tipo := dm.QryGetObject.FieldByName('DES_TIPO').AsString;
Self.Endereco := dm.QryGetObject.FieldByName('DES_LOGRADOURO').AsString;
Self.Numero := dm.QryGetObject.FieldByName('NUM_LOGRADOURO').AsString;
Self.Complemento := dm.QryGetObject.FieldByName
('DES_COMPLEMENTO').AsString;
Self.Bairro := dm.QryGetObject.FieldByName('DES_BAIRRO').AsString;
Self.Cidade := dm.QryGetObject.FieldByName('NOM_CIDADE').AsString;
Self.Cep := dm.QryGetObject.FieldByName('NUM_CEP').AsString;
Self.Referencia := dm.QryGetObject.FieldByName('DES_REFERENCIA').AsString;
Self.UF := dm.QryGetObject.FieldByName('UF_ESTADO').AsString;
Self.Correspondencia := dm.QryGetObject.FieldByName('DOM_CORRESPONDENCIA')
.AsInteger;
end
else
begin
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Exit;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoEntregador.Insert(): Boolean;
begin
try
Result := False;
MaxSeq;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' + 'COD_ENTREGADOR, ' +
'SEQ_ENDERECO, ' + 'DES_TIPO, ' + 'DOM_CORRESPONDENCIA, ' +
'DES_LOGRADOURO, ' + 'NUM_LOGRADOURO, ' + 'DES_COMPLEMENTO, ' +
'DES_BAIRRO, ' + 'NOM_CIDADE, ' + 'UF_ESTADO, ' + 'NUM_CEP, ' +
'DES_REFERENCIA ' + ') ' + 'VALUES(' + ':CODIGO, ' + ':SEQUENCIA, ' +
':TIPO, ' + ':CORRESPONDENCIA, ' + ':ENDERECO, ' + ':NUMERO, ' +
':COMPLEMENTO, ' + ':BAIRRO, ' + ':CIDADE, ' + ':UF, ' + ':CEP, ' +
':REFERENCIA ' + ') ';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('TIPO').AsString := Self.Tipo;
ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia;
ParamByName('ENDERECO').AsString := Self.Endereco;
ParamByName('NUMERO').AsString := Self.Numero;
ParamByName('COMPLEMENTO').AsString := Self.Complemento;
ParamByName('BAIRRO').AsString := Self.Bairro;
ParamByName('CIDADE').AsString := Self.Cidade;
ParamByName('UF').AsString := Self.UF;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('REFERENCIA').AsString := Self.Referencia;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoEntregador.Merge: Boolean;
begin
// nada implementado aqui, INSERT e UPDATE executados diretamente
// o modificador de acesso deste método pode ser definido como private!
// ou sua declaração pode ser até mesmo removida,
// não foi removida para manter a padronização de código.
Result := False;
end;
function TEnderecoEntregador.Update(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'DES_TIPO_ENDERECO = :TIPO, ' +
'DOM_CORRESPONDENCIA = :CORRESPONDENCIA, ' +
'DES_LOGRADOURO = :ENDERECO, ' + 'NUM_LOGRADOURO = :NUMERO, ' +
'DES_COMPLEMENTO = :COMPLEMENTO, ' + 'DES_BAIRRO = :BAIRRO, ' +
'NOM_CIDADE = :CIDADE, ' + 'UF_ESTADO = :UF, ' + 'NUM_CEP = :CEP, ' +
'DES_REFERENCIA = :REFERENCIA ' +
'WHERE COD_ENTREGADOR = :CODIGO AND SEQ_ENDERECO = :SEQUENCIA';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('TIPO').AsString := Self.Tipo;
ParamByName('CORRESPONDENCIA').AsInteger := Self.Correspondencia;
ParamByName('ENDERECO').AsString := Self.Endereco;
ParamByName('NUMERO').AsString := Self.Numero;
ParamByName('COMPLEMENTO').AsString := Self.Complemento;
ParamByName('BAIRRO').AsString := Self.Bairro;
ParamByName('CIDADE').AsString := Self.Cidade;
ParamByName('UF').AsString := Self.UF;
ParamByName('CEP').AsString := Self.Cep;
ParamByName('REFERENCIA').AsString := Self.Referencia;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoEntregador.Validar: Boolean;
begin
// Na validação de dados podemos colocar qualquer atributo para ser validado
// codigo abaixo deve ser customizado por cada leitor!
Result := True;
end;
function TEnderecoEntregador.EnderecoJaExiste(): Boolean;
begin
try
Result := False;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
SQL.Add(' WHERE COD_ENTREGADOR = :CODIGO AND DES_TIPO = :TIPO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('TIPO').AsString := Self.Tipo;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
Result := True;
end;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TEnderecoEntregador.MaxSeq;
begin
Try
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT MAX(SEQ_ENDERECO) AS SEQUENCIA FROM ' + TABLENAME +
' WHERE COD_ENTREGADOR = :CODIGO';
ParamByName('CODIGO').AsInteger := Self.Codigo;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
First;
end;
Self.Sequencia := (dm.QryGetObject.FieldByName('SEQUENCIA').AsInteger) + 1;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TEnderecoEntregador.PopulaLocal(Filtro: string): TStringList;
var
lista: TStringList;
campo: String;
begin
lista := TStringList.Create;
Result := lista;
if Filtro = 'BAIRRO' then
begin
campo := 'DES_BAIRRO';
end
else if Filtro = 'CIDADE' then
begin
campo := 'NOM_CIDADE';
end
else
begin
Exit;
end;
dm.qryPesquisa.Close;
dm.qryPesquisa.SQL.Clear;
dm.qryPesquisa.SQL.Text := 'SELECT DISTINCT(' + campo + ') FROM ' + TABLENAME;
dm.ZConn.PingServer;
dm.qryPesquisa.Open;
while (not dm.qryPesquisa.Eof) do
begin
lista.Add(dm.qryPesquisa.FieldByName(campo).AsString);
dm.qryPesquisa.Next;
end;
dm.qryPesquisa.Close;
dm.qryPesquisa.SQL.Clear;
Result := lista;
end;
procedure TEnderecoEntregador.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
procedure TEnderecoEntregador.setTipo(const Value: String);
begin
_tipo := Value;
end;
procedure TEnderecoEntregador.setSequencia(const Value: Integer);
begin
_sequencia := Value;
end;
procedure TEnderecoEntregador.setCorrespondencia(const Value: Integer);
begin
_correspondencia := Value;
end;
end.
|
unit LandSurfaces;
interface
uses
Land, Surfaces;
type
TLandValueArray = array[TLandClass] of single;
type
TLandSurface =
class( TSurface )
public
constructor Create( anId : TSurfaceId; aName : string; aValues : array of single );
private
fLand : ILandInfo;
fValues : TLandValueArray;
public
property Land : ILandInfo write fLand;
protected
function GetValue( x, y : integer ) : TSurfaceValue; override;
end;
implementation
constructor TLandSurface.Create( anId : TSurfaceId; aName : string; aValues : array of single );
var
i : TLandClass;
begin
inherited Create( anId, aName );
for i := low(i) to high(i) do
fValues[i] := aValues[ord(i)];
end;
function TLandSurface.GetValue( x, y : integer ) : TSurfaceValue;
begin
result := inherited GetValue( x, y );
if fLand <> nil
then result := result + fValues[fLand.LandClassAt( x, y )];
end;
end.
|
unit uFilm;
interface
uses uKata;
const Nmax = 1000;
type Film = record
Nama:string;
Genre:string;
Rating:string;
Durasi:string;
Sin:ansistring;
hDay:longint;
hEnd:longint;
end;
type dbFilm = record
Film : array[1..Nmax] of Film;
Neff : integer;
end;
procedure loadFilm(var dF: dbFilm);
{* procedure untuk me-load data dari File external dataFilm.txt
dan dimasukkan kedalam variable internal
I.S : variable dataFilm internal kosong, dataFilm.txt sudah ada
F.S : dataFilm.txt sudah masuk ke File Internal, dataFilm *}
procedure genreFilter(dF: dbFilm); //F5-genreFilter
{* procedure untuk menampilkan List Judul Film berdasarkan Genre.
I.S : dataFilm sudah siap dipilih dan dipilah berdasarkan Genre, Genre di Input oleh User
F.S : menampilkan List Judul Film yang sesuai dengan Genre Input dari User *}
procedure ratingFilter(dF: dbFilm); //F6-ratingFilter
{* procedure untuk menampilkan List Judul Film berdasarkan RatingViewer.
I.S : dataFilm sudah Siap. RatingViewer di Input oleh User
F.S : menampilkan List Judul Film yang sesuai dengan RatingViewer Input dari User *}
procedure searchMovie(dF : dbFilm); //F7-searchMovie
{* procedure untuk mencari keyword berdasarkan Nama Film, Genre Film, Sinopsis.
I.S : dataFilm sudah terdefinisi, input dan f telah terdefinisi
F.S : menampilkan Nama Film yang sesuai dengan keyword yang dimasukkan *}
procedure showMovie(TFilm : dbFilm); //F8-showMovie
{* procedure untuk menampilkan data film berupa genre, rating, durasi, dan sinopsis film
I.S : TFilm telah terdefinisi
F.S : menampilkan Nama, Genre, Rating, Durasi, dan Sinopsis Film yang dicari *}
implementation
// -------------- Load untuk dataFilm.txt --------------- //
procedure loadFilm(var dF: dbFilm);
var
dfilm: text;
f:ansistring;
pos1,l,i,j:integer;
begin
j:=1;
assign(dfilm,'database\datafilm.txt');
reset(dfilm);
while not Eof(dfilm) do
begin
readln(dfilm,f);
for i:=1 to 7 do
begin
pos1:=pos('|',f);
l:=length(copy(f,1,pos1+1));
case i of
1:dF.Film[j].Nama:=copy(f,1,pos1-2);
2:dF.Film[j].Genre:=copy(f,1,pos1-2);
3:dF.Film[j].Rating:=copy(f,1,pos1-2);
4:dF.Film[j].Durasi:=copy(f,1,pos1-2);
5:dF.Film[j].Sin:=copy(f,1,pos1-2);
6:val(copy(f,1,pos1-2),dF.Film[j].hDay);
7:val(copy(f,1,pos1-2),dF.Film[j].hEnd);
end;
delete(f,1,l);
end;
j:=j+1;
end;
dF.Neff:=j-1;
close(dfilm);
end;
//F5-genreFilter
procedure genreFilter(dF: dbFilm);
var
pilihan: string;
i: integer;
found: boolean;
begin
found:=false;
write('> Genre: ');readln(pilihan);
for i:=1 to dF.Neff do
begin
if lowAll(pilihan)=lowAll(dF.Film[i].Genre) then
begin
writeln('> ',dF.Film[i].nama);
found:=true;
end;
end;
if found=false then
begin
writeln('> Ganre yang di input tidak ada yang sesuai.');
end;
end;
//F6-ratingFilter
procedure ratingFilter(dF: dbFilm);
var
pilihan: string;
i: integer;
found: boolean;
begin
found:=false;
write('> Rating Viewer: ');readln(pilihan);
for i:=1 to dF.Neff do
begin
if lowAll(pilihan)=lowAll(dF.Film[i].Rating) then
begin
writeln('> ',dF.Film[i].nama);
found := true;
end;
end;
if found=false then
begin
writeln('> Rating Viewer yang di input tidak ada yang sesuai.');
end;
end;
//F7-searchMovie
procedure searchMovie(dF : dbFilm);
{Kamus}
var
i,idx1, idx2, idx3 : integer;
input : string;
{Algoritma}
begin
writeln('> Masukkan pencarian berdasarkan sinopsis, judul, atau genre : ');
readln(input);
writeln('> Daftar film yang sesuai dengan pencarian : ');
//Mekanisme Pencarian Daftar Film
for i:= 1 to dF.Neff do
begin
idx1 := pos(lowAll(input), lowAll(dF.Film[i].Nama));
idx2 := pos(lowAll(input), lowAll(dF.Film[i].Genre));
idx3 := pos(lowAll(input), lowAll(dF.Film[i].Sin));
if ( idx1<>0 ) or ( idx2<>0 ) or ( idx3<>0 ) then
writeln('> ',dF.Film[i].Nama);
end;
end;
//F8-showMovie
Procedure showMovie(TFilm : dbFilm);
var
judul : string;
i : integer;
found : boolean;
begin
repeat
write('> Judul Film : ');
readln(judul);
i := 1;
found := False;
while (i <= TFilm.Neff) and (found=False) do
begin
if (lowAll(judul)=lowAll(TFilm.Film[i].Nama)) then
found := True
else
i := i + 1;
end;
if (found = False) then
begin
writeln('> Masukkan judul film salah');
end else
begin
writeln('> ', TFilm.Film[i].Nama);
writeln('> ', TFilm.Film[i].Genre);
writeln('> ', TFilm.Film[i].Rating);
writeln('> ', TFilm.Film[i].Durasi);
writeln('> ', TFilm.Film[i].Sin);
end;
until (found=True);
end;
end.
|
{OBJECTS.PAS - version 4.0}
{$A+,B-,D+,E+,F-,G-,I+,L+,N-,O-,P-,Q-,R-,S+,T-,V+,X+}
{$M 16384,0,10360}
Unit Objects;
Interface
Procedure SetButtonTexture(FileName:string);
Procedure SetWindowTexture(FileName:string);
Procedure SetLabelTexture(FileName:string);
Procedure SetEditTexture(FileName:string);
function GetButtonTexture: string;
function GetWindowTexture: string;
function GetLabelTexture: string;
function GetEditTexture: string;
Procedure DrawButton(x1,y1,x2,y2:word;s:string;Press,Focus:boolean);
procedure DrawPicButton(x1,y1,x2,y2:word;s:string;Press,Focus:boolean; Pic: pointer; sx, sy: integer);
Procedure DrawWindow(x1,y1,x2,y2:integer);
Procedure ShowWindow(x1,y1,x2,y2:integer);
Procedure Ramka(x1,y1,x2,y2:integer);
Procedure DrawLabel(x1,y1,x2,y2:word;s:string);
Procedure DrawEdit(x1,y1,x2,y2:word;s:string);
Procedure DrawScreen(X1,Y1,X2,Y2: integer;const Name: string);
Implementation
Uses
VESA;
type
TTextureColorCorrect = array [0 .. 255, -5 .. 5] of byte;
Var
ButtonTexture, WindowTexture, LabelTexture, EditTexture: string;
TCC: TTextureColorCorrect;
Procedure SetButtonTexture(FileName:string);
Begin
ButtonTexture:=FileName
End;
Procedure SetWindowTexture(FileName:string);
Begin
WindowTexture:=FileName
End;
Procedure SetLabelTexture(FileName:string);
Begin
LabelTexture:=FileName
End;
Procedure SetEditTexture(FileName:string);
Begin
EditTexture:=FileName
End;
function GetButtonTexture: string;
begin
GetButtonTexture := ButtonTexture
end;
function GetWindowTexture: string;
begin
GetWindowTexture := WindowTexture
end;
function GetLabelTexture: string;
begin
GetLabelTexture := LabelTexture
end;
function GetEditTexture: string;
begin
GetEditTexture := EditTexture
end;
procedure ReadFromFile(var Source: file; x, y, XSize: longint; rx, ry: longint; Buf: pointer);
var
MaxSize: longint;
begin
x := x mod rx;
y := y mod ry;
repeat
Seek(Source, 10 + x + y * rx);
MaxSize := rx - x;
x := 0;
if MaxSize > XSize
then
MaxSize := XSize;
BlockRead(Source, Buf^, MaxSize);
XSize := XSize - MaxSize;
word(Buf) := word(Buf) + MaxSize;
until XSize = 0;
end;
procedure DrawButton(x1,y1,x2,y2:word;s:string;Press,Focus:boolean);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
Len: integer;
X3,Y3: integer;
begin
Rectangle(X1+2,Y1+2,X2-2,Y2-2,36,36);
X1:=X1+3;
X2:=X2-3;
Y1:=Y1+3;
Y2:=Y2-3;
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,ButtonTexture);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
{ if not Focus
then} for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
if Index=0+Byte(press)
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -3];
if Index=YSize-1
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
if Index=1+Byte(press)
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -1];
if Index=YSize-2
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +3];
If Index<YSize-1
Then
Begin
TPixels(SprBufer^)[0+Byte(press)]:=TCC[TPixels(SprBufer^)[0+Byte(press)], -3];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], +5];
TPixels(SprBufer^)[1+Byte(press)]:=TCC[TPixels(SprBufer^)[1+Byte(press)], -1];
TPixels(SprBufer^)[XSize-2]:=TCC[TPixels(SprBufer^)[XSize-2], +3]
End;
if Press
then begin
for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
If Index<YSize-1
Then
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], +5];
end;
PutSprite(X1,Y1+Index,MemLine);
end;
Close(Source);
FreeMem(MemLine, GetMaxX + 1);
Len:=Length(s);
X3:=(x1+x2-Len*8) div 2;
Y3:=(y1+y2-16) div 2;
SetColor(8);
OutTextXY(x3+Byte(press),y3+1+Byte(press),s);
OutTextXY(x3+1+Byte(press),y3+Byte(press),s);
OutTextXY(x3+1+Byte(press),y3+1+Byte(press),s);
if Not (Press) and not Focus
then SetColor(15)
else SetColor(119);
OutTextXY((x3)+Byte(press),Y3+Byte(press),s);
end;
procedure DrawPicButton(x1,y1,x2,y2:word;s:string;Press,Focus:boolean; Pic: pointer; sx, sy: integer);
begin
DrawButton(x1,y1,x2,y2,s,Press,Focus);
PutSprite(x1 + sx + byte(Press), y1 + sy + byte(Press), Pic)
end;
procedure Ramka(x1,y1,x2,y2:integer);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
begin
{}
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,WindowTexture);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to 9 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
if Index=0
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -4];
if Index=9
then for SubIndex:=9 to XSize-10 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +4];
TPixels(SprBufer^)[0]:= TCC[TPixels(SprBufer^)[0], -4];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], +4];
PutSprite(X1,Y1+Index,MemLine);
end;
for Index:=0 to 9 do begin
ReadFromFile(Source, X1, Y2 - 9 + Index, XSize, SHead.X, SHead.Y, SprBufer);
if Index=0
then for SubIndex:=9 to XSize-10 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -4];
if Index=9
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +4];
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], -4];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], +4];
PutSprite(X1,Y2-9+Index,MemLine);
end;
TSpriteHeader(MemLine^).X:=10;
for Index:=Y1+10 to Y2-10 do begin
{Left}
ReadFromFile(Source, X1, Index, 10, SHead.X, SHead.Y, SprBufer);
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], -4];
TPixels(SprBufer^)[9]:=TCC[TPixels(SprBufer^)[9], +4];
PutSprite(X1,Index,MemLine);
{Right}
ReadFromFile(Source, X2 - 9, Index, 10, SHead.X, SHead.Y, SprBufer);
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], -4];
TPixels(SprBufer^)[9]:=TCC[TPixels(SprBufer^)[9], +4];
PutSprite(X2-9,Index,MemLine);
end;
Close(Source);
FreeMem(MemLine, GetMaxX + 1);
end;
Procedure DrawWindow(x1,y1,x2,y2:integer);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
begin
Ramka(X1,Y1,X2,Y2);
{}
X1:=X1+10;
X2:=X2-10;
Y1:=Y1+10;
Y2:=Y2-10;
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,WindowTexture);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
if Index<2
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -4];
if Index>YSize-3
then for SubIndex:=0 to XSize-3 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], -4];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], +5];
TPixels(SprBufer^)[1]:= TCC[TPixels(SprBufer^)[1], -4];
TPixels(SprBufer^)[XSize-2]:=TCC[TPixels(SprBufer^)[XSize-2], +5];
PutSprite(X1,Y1+Index,MemLine);
end;
Close(Source);
FreeMem(MemLine, GetMaxX + 1);
end;
Procedure ShowWindow(x1,y1,x2,y2:integer);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
begin
Ramka(x1,y1,x2,y2);
{}
X1:=X1+10;
X2:=X2-10;
Y1:=Y1+10;
Y2:=Y2-10;
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
FillChar(MemLine^,1024,1);
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
PutImage(X1,Y1+Index,MemLine,ShadowPut);
end;
FreeMem(MemLine, GetMaxX + 1)
end;
Procedure DrawLabel(x1,y1,x2,y2:word;s:string);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
Len: integer;
X3,Y3: integer;
begin
X1:=X1+2;
X2:=X2-2;
Y1:=Y1+2;
Y2:=Y2-2;
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,LabelTexture);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
if Index=0
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -3];
if Index=YSize-1
then for SubIndex:=0 to XSize-2 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
if Index=1
then for SubIndex:=0 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -1];
if Index=YSize-2
then for SubIndex:=0 to XSize-2 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +3];
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], -3];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], +5];
TPixels(SprBufer^)[1]:=TCC[TPixels(SprBufer^)[1], -1];
TPixels(SprBufer^)[XSize-2]:=TCC[TPixels(SprBufer^)[XSize-2], +3];
PutSprite(X1,Y1+Index,MemLine);
end;
Close(Source);
FreeMem(MemLine, GetMaxX + 1);
SetColor(8);
Len:=Length(s);
X3:=(x1+x2-Len*8) div 2;
Y3:=(y1+y2-16) div 2;
OutTextXY(x3,y3+1,s);
OutTextXY(x3+1,y3,s);
OutTextXY(x3+1,y3+1,s);
SetColor(114);
OutTextXY((x3),Y3,s)
end;
Procedure DrawScreen(X1,Y1,X2,Y2: integer;const Name: string);
type
TSpriteHeader = record
X,Y: word;
end;
TPixels = array [0..65000] of byte;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
begin
{}
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,Name);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
PutSprite(X1,Y1+Index,MemLine);
end;
Close(Source);
FreeMem(MemLine, GetMaxX + 1);
end;
procedure DrawEdit(x1,y1,x2,y2:word;s:string);
type
TPixels = array [0..65000] of byte;
tSpriteHeader=record
x,y:word;
end;
var
Source: File;
MemLine: pointer;
SprBufer: pointer;
SHead: TSpriteHeader;
XSize, YSize: integer;
Index: integer;
SubIndex: integer;
Len: integer;
X3,Y3: integer;
TextPart: integer;
begin
X1:=X1+2;
X2:=X2-2;
Y1:=Y1+2;
Y2:=Y2-2;
XSize:=X2-X1+1;
YSize:=Y2-Y1+1;
Assign(Source,EditTexture);
{Insert a check}
Reset(Source,1);
{Read sprite header}
BlockRead(Source,SHead,SizeOf(SHead));
{Get memory}
GetMem(MemLine, GetMaxX + 1);
SprBufer:=MemLine;
Inc(Longint(SprBufer),4);
{Vertical part}
TSpriteHeader(MemLine^).X:=XSize;
TSpriteHeader(MemLine^).Y:=1;
for Index:=0 to YSize-1 do begin
ReadFromFile(Source, X1, Y1 + Index, XSize, SHead.X, SHead.Y, SprBufer);
if Index=0
then for SubIndex:=1 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +5];
if Index=YSize-1
then for SubIndex:=1 to XSize-2 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -3];
if Index=1
then for SubIndex:=1 to XSize-1 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], +3];
if Index=YSize-2
then for SubIndex:=1 to XSize-2 do
TPixels(SprBufer^)[SubIndex]:=TCC[TPixels(SprBufer^)[SubIndex], -1];
TPixels(SprBufer^)[0]:=TCC[TPixels(SprBufer^)[0], +5];
TPixels(SprBufer^)[XSize-1]:=TCC[TPixels(SprBufer^)[XSize-1], -3];
TPixels(SprBufer^)[1]:=TCC[TPixels(SprBufer^)[1], +3];
TPixels(SprBufer^)[XSize-2]:=TCC[TPixels(SprBufer^)[XSize-2], -1];
PutSprite(X1,Y1+Index,MemLine);
end;
FreeMem(MemLine, GetMaxX + 1);
TextPart:=(Abs(X2-X1)-10) div 8;
Len:=Length(s);
X3:=X1+5;
Y3:=y1+2;
SetColor(114);
while S<>'' do begin
OutTextXY(x3,Y3,Copy(s,1,TextPart));
Delete(S,1,TextPart);
Y3:=Y3+16;
end;
Close(Source)
end;
procedure ReadTCC;
var
f: file;
begin
Assign(f, 'vesa.tcc');
Reset(f, 1);
BlockRead(f, TCC, SizeOf(TCC));
Close(f)
end;
Begin
ButtonTexture := 'buttons.dat';
WindowTexture := 'texture.dat';
EditTexture := 'labels.dat';
LabelTexture := 'labels.dat';
ReadTCC;
End. |
unit vgBounds;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VGScene"
// Модуль: "w:/common/components/rtl/external/VGScene/NOT_FINISHED_vgBounds.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VGScene::Impl::TvgBounds
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include w:\common\components\rtl\external\VGScene\vg_define.inc}
interface
{$IfNDef NoVGScene}
uses
Classes,
vgTypes,
vgPersistent
;
type
{$IfDef Nemesis}
{$Define vgNoDefaults}
{$EndIf Nemesis}
TvgBounds = class(TvgPersistent)
private
FRight: single;
FBottom: single;
FTop: single;
FLeft: single;
FOnChange: TNotifyEvent;
{$IfNDef vgNoDefaults}
FDefaultValue: TvgRect;
{$EndIf vgNoDefaults}
function GetRect: TvgRect;
procedure SetRect(const Value: TvgRect);
procedure SetBottom(const Value: single);
procedure SetLeft(const Value: single);
procedure SetRight(const Value: single);
procedure SetTop(const Value: single);
protected
procedure DefineProperties(Filer: TFiler); override;
procedure ReadRect(Reader: TReader);
procedure WriteRect(Writer: TWriter);
{$IfNDef DesignTimeLibrary}
class function IsCacheable : Boolean; override;
{$EndIf DesignTimeLibrary}
public
constructor Create(const ADefaultValue: TvgRect); virtual;
procedure Cleanup; override;
procedure Assign(Source: TPersistent); override;
function MarginRect(const R: TvgRect): TvgRect;
function PaddinRect(const R: TvgRect): TvgRect;
function Width: single;
function Height: single;
property Rect: TvgRect read GetRect write SetRect;
{$IfNDef vgNoDefaults}
property DefaultValue: TvgRect read FDefaultValue write FDefaultValue;
{$EndIf vgNoDefaults}
property OnChange: TNotifyEvent read FOnChange write FOnChange;
function Empty: boolean;
function MarginEmpty: boolean;
published
property Left: single read FLeft write SetLeft stored false;
property Top: single read FTop write SetTop stored false;
property Right: single read FRight write SetRight stored false;
property Bottom: single read FBottom write SetBottom stored false;
end;
{$EndIf NoVGScene}
implementation
{$IfNDef NoVGScene}
uses
vg_Scene
;
{ TvgBounds }
constructor TvgBounds.Create(const ADefaultValue: TvgRect);
begin
inherited Create;
{$IfNDef vgNoDefaults}
FDefaultValue := ADefaultValue;
{$EndIf vgNoDefaults}
Rect := ADefaultValue;
end;
procedure TvgBounds.Cleanup;
begin
FOnChange := nil;
inherited;
end;
procedure TvgBounds.Assign(Source: TPersistent);
begin
if Source is TvgBounds then
begin
Rect := TvgBounds(Source).Rect;
end
else
inherited
end;
function TvgBounds.GetRect: TvgRect;
begin
Result := vgRect(FLeft, FTop, FRight, FBottom);
end;
function TvgBounds.MarginRect(const R: TvgRect): TvgRect;
begin
Result := vgRect(R.Left + FLeft, R.Top + FTop, R.Right - FRight, R.Bottom - FBottom);
end;
function TvgBounds.PaddinRect(const R: TvgRect): TvgRect;
begin
Result := vgRect(R.Left - FLeft, R.Top - FTop, R.Right + FRight, R.Bottom + FBottom);
end;
function TvgBounds.Width: single;
begin
Result := vgRectWidth(Rect);
end;
function TvgBounds.Height: single;
begin
Result := vgRectHeight(Rect);
end;
function TvgBounds.MarginEmpty: boolean;
begin
Result := (FLeft = 0) and (FTop = 0) and (FRight = 0) and (FBottom = 0);
end;
function TvgBounds.Empty: boolean;
begin
Result := vgIsRectEmpty(Rect)
end;
procedure TvgBounds.SetBottom(const Value: single);
begin
if FBottom <> Value then
begin
FBottom := Value;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TvgBounds.SetLeft(const Value: single);
begin
if FLeft <> Value then
begin
FLeft := Value;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TvgBounds.SetRight(const Value: single);
begin
if FRight <> Value then
begin
FRight := Value;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TvgBounds.SetTop(const Value: single);
begin
if FTop <> Value then
begin
FTop := Value;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TvgBounds.SetRect(const Value: TvgRect);
begin
if (FLeft <> Value.Left) or (FTop <> Value.Top) or (FRight <> Value.Right) or (FBottom <> Value.Bottom) then
begin
FLeft := Value.Left;
FTop := Value.Top;
FRight := Value.Right;
FBottom := Value.Bottom;
if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TvgBounds.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('Rect', ReadRect, WriteRect,
{$IfNDef vgNoDefaults}
(FLeft <> DefaultValue.Left) or (FTop <> DefaultValue.Top) or
(FRight <> DefaultValue.Right) or (FBottom <> DefaultValue.Bottom)
{$Else vgNoDefaults}
true
{$EndIf vgNoDefaults}
);
end;
procedure TvgBounds.ReadRect(Reader: TReader);
begin
Rect := vgStringToRect(Reader.ReadString);
end;
procedure TvgBounds.WriteRect(Writer: TWriter);
begin
Writer.WriteString(vgRectToString(Rect));
end;
{$IfNDef DesignTimeLibrary}
class function TvgBounds.IsCacheable : Boolean;
begin
Result := true;
end;
{$EndIf DesignTimeLibrary}
{$EndIf NoVGScene}
end. |
Program Diario_de_Notas;
(*Programa de um diário de notas que armazenam dados de alunos, por turma, que são o DRE, nota de duas provas, média e número de faltas; Responsável: Felipe Botelho Nunes da Silva; Data:28/02/2016 *)
Uses crt,digDados,sysutils;
Type
regAluno = record
nome:string;
dre:integer;
notas:array[1..2] of real;
media:real;
faltas:integer;
end;
arqTurma = file of regAluno;
ptrTurma = ^regTurma;
regTurma = record
desc:string;
prox,ant:ptrTurma;
end;
Function buscaPtrNomeTm(primeiro:ptrTurma;alvo:string):ptrTurma;
(*Procedimento para achar o ponteiro de uma turma pelo nome*)
Var
achou:boolean;
atual:ptrTurma;
begin
new(atual);
atual:=primeiro;
achou:=false;
if (atual<>nil) then {Se o primeiro ponteiro for diferente de nil, existe no mínimo um ponteiro na lista, então a busca pode ser feita}
begin
repeat
if (atual^.desc=alvo) then
begin
achou:=true;
writeln('A turma ',alvo,' foi achada.');
end
else
begin
atual:=atual^.prox;
end;
until ((atual=nil) or (achou));
if not(achou) then
begin
clrscr;
buscaPtrNomeTm:=nil; {Se não achar o ponteiro, igualar a busca como nil}
end
else
begin
buscaPtrNomeTm:=atual;
end;
end
else
begin
buscaPtrNomeTm:=nil; {Busca não pode ser realizada, e assume o valor nil}
end
end;
Procedure abrirTurma(var primeiro,ultimo:ptrTurma);
(*Procedimento para abrir uma turma, inserindo-a ordenadamente na lista de turmas ativas.*)
Var
turma:arqTurma;
novo,atual,busca:ptrTurma;
opcao:char;
nomeTm:string;
parar:boolean;
begin
clrscr;
new(busca);
writeln('Informe o nome da turma.');
readln(nomeTm);
assign(turma,nomeTm);
{$i-}
reset(turma);
{$i+}
if ioresult =2 then
begin
clrscr;
opcao:=funConfirmar('Não existe arquivo dessa turma. Deseja criar um?<s/n> ');
if opcao='S' then
begin
rewrite(turma);
end;
end;
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar se existe o ponteiro com o nome informado}
if (busca=nil) then
begin
new(novo);
new(atual);
novo^.desc:=nomeTm;
if (((primeiro=nil)and(ioresult=0))or((opcao='S')and(primeiro=nil))) then {Caso em que não há nenhuma turma ativa}
begin
primeiro:=novo;
ultimo:=novo;
novo^.ant:=nil;
novo^.prox:=nil;
end
else if (((primeiro<>nil)and(ioresult=0)) or ((opcao='S')and(primeiro<>nil))) then {Caso em que já existe alguma turam ativa}
begin
parar:=false;
atual:=primeiro;
repeat {Iteração para descobrir onde o ponteiro será inserido ordenadamente}
if (novo^.desc<atual^.desc) then
begin
parar:=true;
end
else
begin
atual:=atual^.prox;
end;
until ((parar)or(atual=nil));
if (parar) then
begin
if (atual=primeiro) then {Se o atual for o primeiro, o novo ponteiro passa a ser o primeiro}
begin
novo^.prox:=atual;
novo^.ant:=nil;
atual^.ant:=novo;
primeiro:=novo;
end
else
begin
novo^.prox:=atual;
novo^.ant:=atual^.ant;
atual^.ant^.prox:=novo;
atual^.ant:=novo;
end;
end
else {O novo ponteiro será inserido como último}
begin
novo^.prox:=nil;
novo^.ant:=ultimo;
ultimo^.prox:=novo;
ultimo:=novo;
end;
end;
end;
clrscr;
end;
Procedure retirarTurma(var primeiro,ultimo:ptrTurma;alvo:ptrTurma);
(*Procedimento que retira uma turma da lista de turmas ativas*)
begin
if (alvo=primeiro) then
begin
if (alvo=ultimo) then {Se o ponteiro que deseja tirar for primeiro e o último, os ponteiros primeiro e último passarão a ser nil}
begin
primeiro:=nil;
ultimo:=nil;
end
else {Se o ponteiro a ser tirado for só o primeiro, o posterior a ele passa a ser o primeiro}
begin
primeiro:=alvo^.prox;
primeiro^.ant:=nil;
end;
end
else if (alvo=ultimo) then {Se o ponteiro a ser retirado for só o último, o anterior a ele passa a ser o último}
begin
ultimo:=alvo^.ant;
ultimo^.prox:=nil;
end
else
begin
alvo^.ant^.prox:=alvo^.prox;
alvo^.prox^.ant:=alvo^.ant;
end;
end;
Procedure fecharTurma(var primeiro,ultimo:ptrTurma);
(*Procedimento que fecha uma turma, tirando-a da lista de turmas ativas, perguntando primeiramente ao usuário o nome da turma*)
Var
busca:ptrTurma;
nomeTm:string;
resposta:char;
Begin
if primeiro=nil then
begin
writeln('Não existe turma aberta!');
end
else
begin
new(busca);
digStr('Informe o nome da turma que quer fechar:',30,1,nomeTm);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome informado}
if busca=nil then
begin
writeln('Não foi achada turma com esse nome na lista de turmas ativas.');
end
else
begin
resposta:=funConfirmar('Deseja mesmo fechar essa turma e retirá-la da lista de turmas ativas?<s/n> ');
if resposta='S' then
begin
retirarTurma(primeiro,ultimo,busca); {Retirar a turma da lista de turmas abertas}
clrscr;
writeln('Turma fechada!');
writeln();
writeln();
end;
end;
end;
End;
Function procuraDREigual(numDre:integer;primeiro:ptrTurma):boolean;
(*Função que assume valor verdadeiro se encontrar entre os arquivos das turmas ativas algum aluno com dre igual ao informado na inclusão de um aluno*)
Var
turma:arqTurma;
atual:ptrTurma;
aux:regAluno;
achou:boolean;
Begin
achou:=false;
atual:=primeiro;
repeat {Iteração que percorre a lista de turmas}
assign(turma,atual^.desc);
reset(turma);
if (filesize(turma)<>0) then
begin
repeat {Iteração que percorre o arquivo e busca se a algum aluno com dre semelhante ao informado}
read(turma,aux);
if (aux.dre=numDre) then
begin
achou:=true;
end;
until ((achou)or(eof(turma)));
end;
atual:=atual^.prox;
until ((achou)or(atual=nil));
procuraDREigual:=achou;
End;
Procedure incluirAluno(primeiro:ptrTurma);
(*Procedimento que inclui um aluno e todos os seus dados, ordenadamente pelo seu nome, no arquivo referente a turma do aluno*)
Var
turma:arqTurma;
busca:ptrTurma;
aux,novo:regAluno;
nomeTm:string;
cont,posicao:integer;
incluiu,igual:boolean;
Begin
if primeiro=nil then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
clrscr;
digStr('Informe o nome da turma do aluno que será incluido.',30,1,nomeTm);
new(busca);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Busca o ponteiro referente ao nome da turma}
if busca=nil then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
clrscr;
incluiu:=false;
assign(turma,nomeTm);
reset(turma);
digStr('Informe o nome do aluno',30,1,novo.nome);
repeat
digInt('Informe o DRE do aluno',1000,1,novo.dre);
igual:=procuraDREigual(novo.dre,primeiro);
if (igual) then
begin
writeln('Já existe aluno com esse mesmo DRE nessa turma ou em outra turma aberta. Informe outro valor.');
writeln();
end;
until (not(igual));
digReal('Informe a nota 1 do aluno.',10,0,novo.notas[1]);
digReal('Informe a nota 2 do aluno.',10,0,novo.notas[2]);
digInt('Informe o número de faltas do aluno.',30,0,novo.faltas);
novo.media:=(novo.notas[1]+novo.notas[2])/2;
if filesize(turma)=0 then {Caso em que não há nada no arquivo}
begin
seek(turma,filesize(turma));
write(turma,novo);
incluiu:=true;
end
else
begin
seek(turma,0);
repeat {Iteração para incluir os dados ordenados pelo nome}
posicao:=filepos(turma);
read(turma,aux);
if (novo.nome<aux.nome) then {Foi achada a posição em que será incluido}
begin
for cont:=filesize(turma)-1 downto posicao do {Iteração para "empurrar para baixo" todos os dados após a posição achada}
begin
seek(turma,cont);
read(turma,aux);
write(turma,aux);
end;
seek(turma,posicao);
write(turma,novo); {Inclusão}
incluiu:=true
end;
until (incluiu) or (eof(turma));
end;
if (not(incluiu)) then {Se não foi incluido ainda, será incluido no final do arquivo}
begin
seek(turma,filesize(turma));
write(turma,novo);
end;
clrscr;
writeln('Dados incluidos!');
writeln();
writeln();
end;
end;
end;
Procedure removerAluno(primeiro:ptrTurma);
(*Procedimento para remover todos os dados de um aluno de uma turma*)
Var
turma:arqTurma;
busca:ptrTurma;
aux:regAluno;
nomeTm,alvo:string;
posicao:integer;
achou:boolean;
Begin
if primeiro=nil then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
clrscr;
digStr('Informe o nome da turma da qual o aluno pertence.',30,1,nomeTm);
new(busca);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome da turma informado}
if busca=nil then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
assign(turma,busca^.desc);
reset(turma);
if filesize(turma)=0 then
begin
clrscr;
writeln('Não há dados cadastrados nessa turma.');
writeln();
writeln();
end
else
begin
achou:=false;
clrscr;
digStr('Informe o nome do aluno que deseja remover. Serão removidos todos os dados.',50,1,alvo);
seek(turma,0);
repeat {Iteração para achar a posição no arquivo do aluno que deseja remover}
posicao:=filepos(turma);
read(turma,aux);
if (aux.nome=alvo) then
begin
achou:=true;
end;
until ((achou) or (eof(turma)));
if achou then {Caso em que foi achado o aluno no arquivo}
begin
aux.nome:=' '; {Atribuir espaço vazio (' ') nome, que é um nome não válido}
aux.dre:=0; {Atribuir 0 ao DRE, que é um valor não válido}
seek(turma,posicao);
write(turma,aux);
clrscr;
writeln('Dados removidos!');
writeln();
writeln();
end
else
begin
clrscr;
writeln('Não existe aluno com esse nome na turma informada.');
writeln();
writeln();
end;
end;
end;
end;
End;
Procedure apagarTurma(var primeiro,ultimo:ptrTurma);
(*Procedimento para apagar o arquivo de uma turma, e posteriormente removendo-a da lista de turmas ativas*)
Var
turma:arqTurma;
busca:ptrTurma;
opcao:char;
nomeTm:string;
Begin
if primeiro=nil then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
clrscr;
digStr('Informe o nome da turma que deseja apagar os dados.',30,1,nomeTm);
new(busca);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome da turma informado}
if (busca=nil) then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
clrscr;
opcao:=funConfirmar('Deseja mesmo apagar o arquivo que contém todos os dados dessa turma?<s/n>');
if (opcao='S') then
begin
assign(turma,busca^.desc);
erase(turma); {Apagar o arquivo}
retirarTurma(primeiro,ultimo,busca); {Retirar a turma da lista de turmas ativas}
clrscr;
writeln('Arquivo da turma apagado!');
writeln();
writeln();
end;
end;
end;
End;
Procedure buscarPosAluno(nomeTm:string;var achou:boolean;var posicao:integer);
(*Procedimento para achar a posição de um aluno no arquivo da turma, através da solicitação do nome do aluno ou DRE, e indicar se achou ou não*)
Var
turma:arqTurma;
alvoStr:string;
alvoInt,cont:integer;
soNumero:boolean;
aux:regAluno;
Begin
cont:=1;
soNumero:=true;
clrscr;
digStr('Informe o nome ou dre do aluno que deseja alterar o dado.',30,1,alvoStr);
// Verificar se o dado informado é o nome ou dre
repeat {Iteração para verificar se o dado informado é formado apenas por número ou não}
if not(alvoStr[cont] in ['0'..'9']) then
begin
soNumero:=false; {O dado não é formado apenas por números}
end;
cont:=cont+1;
until ((cont=length(alvoStr))or(not(soNumero)));
if (soNumero) then {Se o dado informado for formado apenas por números, o usuário informou o dre, que é inteiro}
begin
alvoInt:=StrToInt(alvoStr); {O dado(dre) que estava como string é convertido para integer}
end;
//Achar a posição correspondente no arquivo
assign(turma,nomeTm);
reset(turma);
if (filesize(turma)=0) then
begin
clrscr;
writeln('Não há dados cadastrados nessa turma.');
achou:=false;
writeln();
writeln();
end
else
begin
achou:=false;
seek(turma,0);
repeat {Verificar se o nome ou dre informado está no arquivo da turma}
posicao:=filepos(turma);
read(turma,aux);
if ((alvoStr=aux.nome)or(alvoInt=aux.dre)) then
begin
achou:=true; {Foi achado o aluno e a posição dele no arquivO}
end
until ((achou)or(eof(turma))); {Repetir até achar ou até teminar o arquivo}
if not(achou) then
begin
clrscr;
writeln('Não foi achado esse aluno nessa turma.');
writeln();
writeln();
end;
end;
End;
Procedure editarNota(primeiro:ptrTurma);
(*Procedimento para editar as notas de um aluno de uma turma*)
Var
turma:arqTurma;
nomeTm:string;
busca:ptrTurma;
posicao:integer;
achou:boolean;
aux:regAluno;
novaNota1,novaNota2,novaMedia:real;
Begin
if (primeiro=nil) then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
new(busca);
clrscr;
digStr('Informe o nome da turma do aluno que deseja alterar a nota:',30,1,nomeTm);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome da turma informada}
if (busca=nil) then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
buscarPosAluno(nomeTm,achou,posicao); {Verificar se o aluno existe no arquivo, e se sim buscar a posição no arquivo}
if achou then
begin
clrscr;
digReal('Informe a nova nota 1.',10,0,novaNota1);
digReal ('Informe a nova nota 2.',10,0,novaNota2);
novaMedia:=(novaNota1+novaNota2)/2;
assign(turma,nomeTm);
reset(turma);
seek(turma,posicao);
read(turma,aux);
aux.notas[1]:=novaNota1;
aux.notas[2]:=novaNota2;
aux.media:=novaMedia;
seek(turma,posicao);
write(turma,aux);
clrscr;
writeln('Notas alteradas!');
writeln();
writeln();
end;
end;
end;
End;
Procedure editarFaltas(primeiro:ptrTurma);
(*Procedimento para editar as faltas de um aluno de uma turma*)
Var
turma:arqTurma;
nomeTm:string;
busca:ptrTurma;
posicao:integer;
achou:boolean;
aux:regAluno;
novaFalta:integer;
Begin
if (primeiro=nil) then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
new(busca);
clrscr;
digStr('Informe o nome da turma do aluno que deseja alterar o número de faltas:',30,1,nomeTm);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome da turma informado}
if (busca=nil) then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
buscarPosAluno(nomeTm,achou,posicao); {Verificar se o aluno existe no arquivo, e se sim achar a posição}
if achou then
begin
clrscr;
digInt('Informe o novo número de faltas.',30,0,novaFalta);
assign(turma,nomeTm);
reset(turma);
seek(turma,posicao);
read(turma,aux);
aux.faltas:=novaFalta;
seek(turma,posicao);
write(turma,aux);
clrscr;
writeln('Faltas alteradas!');
writeln();
writeln();
end;
end;
end;
End;
Procedure consultarDados(primeiro:ptrTurma;opcao:integer);
(*Procedimento que, dependendo da opção que é informada no menu principal, consulta dados de um aluno específico de uma turma, dados dos alunos aprovados em uma turma, dados dos alunos reprovados por nota de uma turma, dados dos alunos reprovados por falta de uma turma, ou lista todos os alunos de uma turma e seus dados.*)
Var
turma:arqTurma;
nomeTm,nomeAl:string;
busca:ptrTurma;
aux:regAluno;
achou,vazio:boolean;
cont:integer;
Begin
if (primeiro=nil) then
begin
clrscr;
writeln('Não existe turma aberta!');
writeln();
writeln();
end
else
begin
new(busca);
clrscr;
digStr('Informe o nome da turma.',30,1,nomeTm);
busca:=buscaPtrNomeTm(primeiro,nomeTm); {Buscar o ponteiro referente ao nome da turma informado}
if (busca=nil) then
begin
clrscr;
writeln('Não existe turma com esse nome na lista de turmas abertas.');
writeln();
writeln();
end
else
begin
assign(turma,nomeTm);
reset(turma);
seek(turma,0);
vazio:=true; {Assume que o arquivo turma está vazio}
if (filesize(turma))<>0 then {Se o arquivo tiver algo, verificar se é válido}
begin
repeat {Iteração para verificar se há algum registro válido no arquivo}
read(turma,aux);
if (aux.nome<>' ')then {Se a condição for feita, existe registro válido}
begin
vazio:=false; {Assume que o arquivo não está vazio, e há registro válido}
end;
until ((not(vazio))or(eof(turma)));
end;
if (vazio) then
begin
clrscr;
writeln('Não há dados cadastrados nessa turma.');
writeln();writeln();
end
else
begin
achou:=false;
case opcao of {Opção informada no menu principal}
8: begin {Consultar dados de um aluno específico}
digStr('Informe o nome do aluno buscado.',30,1,nomeAl);
seek(turma,0);
repeat
read(turma,aux);
if (aux.nome=nomeAl) then {Se achar, informar os dados}
begin
achou:=true;
clrscr;
gotoxy(1,1);write('NOME');gotoxy(13,1);write('DRE');gotoxy(26,1);write('NOTA 1');gotoxy(39,1);write('NOTA 2');gotoxy(52,1);write('MEDIA');gotoxy(65,1);writeln('FALTAS');
write(aux.nome);gotoxy(13,2);write(aux.dre);gotoxy(26,2);write(aux.notas[1]:5:2);gotoxy(39,2);write(aux.notas[2]:5:2);gotoxy(52,2);write(aux.media:5:2);gotoxy(65,2);writeln(aux.faltas);
writeln();writeln();
end;
until ((achou)or(eof(turma))); {Repetir até achar ou até terminar o arquivo}
if not(achou) then
begin
clrscr;
writeln('Não foi achado aluno com esse nome nessa turma.');
writeln();writeln();
end;
end;
9: begin {Consultar dados dos alunos aprovados de uma turma}
seek(turma,0);
cont:=4;
clrscr;
writeln(' ALUNOS APROVADOS');
writeln();
write('NOME');gotoxy(13,3);write('DRE');gotoxy(26,3);writeln('MEDIA');
repeat
read(turma,aux);
if ((aux.media>=7)and(aux.faltas<=4)) then {Listar alunos aprovados, que devem ter media maior ou igual a 7 e nº de faltas menor ou igual 4}
begin
achou:=true;
gotoxy(1,cont);write(aux.nome);gotoxy(13,cont);write(aux.dre);gotoxy(26,cont);writeln(aux.media:5:2);
cont:=cont+1;
end;
until (eof(turma));
writeln();writeln();
if (not(achou)) then
begin
clrscr;
writeln('Não há alunos aprovados nessa turma.');
writeln();writeln();
end;
end;
10: begin {Consultar dados dos alunos reprovados por nota de uma turma}
seek(turma,0);
cont:=4;
clrscr;
writeln(' ALUNOS REPROVADOS POR NOTA');
writeln();
write('NOME');gotoxy(13,3);write('DRE');gotoxy(26,3);writeln('MEDIA');
repeat
read(turma,aux);
if (aux.media<7) then {Listar alunos reprovados por nota, com media menor que 7 }
begin
achou:=true;
gotoxy(1,cont);write(aux.nome);gotoxy(13,cont);write(aux.dre);gotoxy(26,cont);writeln(aux.media:5:2);
cont:=cont+1;
end;
until (eof(turma));
writeln();writeln();
if (not(achou)) then
begin
clrscr;
writeln('Não há alunos reprovados por nota nessa turma.');
writeln();writeln();
end;
end;
11: begin {Consultar dados dos alunos reprovados por falta de uma turma}
seek(turma,0);
cont:=4;
clrscr;
writeln(' ALUNOS REPROVADOS POR FALTA');
writeln();
write('NOME');gotoxy(13,3);write('DRE');gotoxy(26,3);writeln('FALTAS');
repeat
read(turma,aux);
if (aux.faltas>4) then {Listar alunos com número de faltas maior que 4}
begin
achou:=true;
gotoxy(1,cont);write(aux.nome);gotoxy(13,cont);write(aux.dre);gotoxy(26,cont);writeln(aux.faltas);
cont:=cont+1;
end;
until (eof(turma));
writeln();writeln();
if (not(achou)) then
begin
clrscr;
writeln('Não há alunos reprovados por falta.');
writeln();writeln();
end;
end;
12: begin {Listar todos os alunos}
seek(turma,0);
cont:=4;
clrscr;
writeln(' TURMA ',nomeTm);
writeln();
write('NOME');gotoxy(13,3);write('DRE');gotoxy(26,3);write('NOTA 1');gotoxy(39,3);write('NOTA 2');gotoxy(52,3);write('MÉDIA');gotoxy(65,3);writeln('FALTAS');
repeat
read(turma,aux);
if (aux.nome<>' ') then
begin
gotoxy(1,cont);write(aux.nome);gotoxy(13,cont);write(aux.dre);gotoxy(26,cont);write(aux.notas[1]:5:2);gotoxy(39,cont);write(aux.notas[2]:5:2);gotoxy(52,cont);write(aux.media:5:2);gotoxy(65,cont);writeln(aux.faltas);
cont:=cont+1;
end;
until (eof(turma));
writeln();writeln();
end;
end;
end;
end;
end;
End;
//****************************************************PROGRAMA PRINCIPAL********************************************
Var
opcao:integer;
primeiro,ultimo:ptrTurma;
Begin
new(primeiro);
new(ultimo);
primeiro:=nil;
clrscr;
writeln(' BEM VINDO AO DIÁRIO DE ALUNOS.');
writeln();
repeat
writeln('MENU PRINCIPAL:');
writeln();
writeln('Digite 1 para abrir uma turma a partir do nome.');
writeln('Digite 2 para fechar uma turma e retirá-la da lista de turmas ativas. ');
writeln('Digite 3 para apagar o arquivo que contem os dados de uma turma.');
writeln('Digite 4 para incluir dados de um aluno de uma turma.');
writeln('Digite 5 para remover um aluno de uma turma e todos seus dados.');
writeln('Digite 6 para editar as notas de um aluno de uma turma.');
writeln('Digite 7 para alterar o número de faltas de um aluno de uma turma.');
writeln('Digite 8 para consultar os dados de um aluno específico de uma turma.');
writeln('Digite 9 para consultar dados de todos os alunos aprovados de uma turma.');
writeln('Digite 10 para consultar dados de todos os alunos reprovados por nota de uma turma.');
writeln('Digite 11 para consultar dados de todos os alunos reprovados por falta de uma turma.');
writeln('Digite 12 para listar todos os dados de todos os alunos de uma turma.');
writeln('Digite 13 para sair do programa.');
writeln();
digInt('Informe a opção escolhida:',13,1,opcao);
case opcao of
1: abrirTurma(primeiro,ultimo);
2: fecharTurma(primeiro,ultimo);
3: apagarTurma(primeiro,ultimo);
4: incluirAluno(primeiro);
5: removerAluno(primeiro);
6: editarNota(primeiro);
7: editarFaltas(primeiro);
8: consultarDados(primeiro,opcao); {Consultar dados de um aluno específico}
9: consultarDados(primeiro,opcao); {Consultar dados de todos os alunos aprovados}
10:consultarDados(primeiro,opcao); {Consultar dados de todos os alunos reprovados por nota}
11:consultarDados(primeiro,opcao); {Consultar dados de todos os alunos reprovados por falta}
12:consultarDados(primeiro,opcao); {Listar dados de todos os alunos}
end;
until(opcao=13);
dispose(primeiro);
dispose(ultimo);
End.
|
unit ClipboardViewerForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Clipbrd, clipbrdfunctions;
type
TClipboardViewer = class(TForm)
private
FCVActive: Boolean;
FNextClipboardViewer: HWND;
procedure WMChangeCBChain(var Msg : TWMChangeCBChain); message WM_CHANGECBCHAIN;
procedure WMDrawClipboard(var Msg : TWMDrawClipboard); message WM_DRAWCLIPBOARD;
protected
procedure SetCVActive(B: Boolean); virtual;
public
OnClipboardContentChanged: TNotifyEvent;
property CVActive: Boolean read FCVActive write SetCVActive;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Start;
procedure Stopp;
function GetClipboardText: String;
function OpenClipboard: Boolean;
procedure CloseClipboard;
function GetClipboardHtml: String;
function GetClipboardHtml_utf8: AnsiString;
function ClipboardHasText: Boolean;
function GetClipboardText_utf8: AnsiString;
end;
implementation
procedure TClipboardViewer.Start;
begin
if not FCVActive then
begin
{ Add to clipboard chain }
FNextClipboardViewer := SetClipboardViewer(Handle);
FCVActive := True;
end;
end;
procedure TClipboardViewer.Stopp;
begin
if FCVActive then
begin
{ Remove from clipboard chain }
ChangeClipboardChain(Handle, FNextClipboardViewer);
FNextClipboardViewer := 0;
FCVActive := False;
end;
end;
procedure TClipboardViewer.WMDrawClipboard(var Msg : TWMDrawClipboard);
begin
inherited;
{ Clipboard content has changed }
try
if Assigned(OnClipboardContentChanged) then OnClipboardContentChanged(Self);
finally
{ Inform the next window in the clipboard viewer chain }
SendMessage(FNextClipboardViewer, WM_DRAWCLIPBOARD, 0, 0);
end;
end;
procedure TClipboardViewer.WMChangeCBChain(var Msg : TWMChangeCBChain);
begin
inherited;
{ mark message as done }
Msg.Result := 0;
{ the chain has changed }
if Msg.Remove = FNextClipboardViewer then
{ The next window in the clipboard viewer chain had been removed. We recreate it. }
FNextClipboardViewer := Msg.Next
else
{ Inform the next window in the clipboard viewer chain }
SendMessage(FNextClipboardViewer, WM_CHANGECBCHAIN, Msg.Remove, Msg.Next);
end;
constructor TClipboardViewer.Create(AOwner: TComponent);
begin
inherited;
{ Initialize variable }
FCVActive := False;
end;
destructor TClipboardViewer.Destroy;
begin
if FCVActive then
begin
{ Remove from clipboard chain }
Stopp;
end;
inherited;
end;
procedure TClipboardViewer.SetCVActive(B: Boolean);
begin
if B then Start else Stopp;
end;
function TClipboardViewer.GetClipboardText: String;
begin
Result := clipbrdfunctions.GetClipboardText;
end;
function TClipboardViewer.GetClipboardText_utf8: AnsiString;
begin
Result := clipbrdfunctions.GetClipboardTextUTF8;
end;
function TClipboardViewer.OpenClipboard: Boolean;
begin
Result := True;
try
Clipboard.Open;
except
Result := False;
end;
end;
procedure TClipboardViewer.CloseClipboard;
begin
Clipboard.Close;
end;
function TClipboardViewer.GetClipboardHtml: String;
begin
Result := clipbrdfunctions.ReadClipboardHtml;
end;
function TClipboardViewer.GetClipboardHtml_utf8: AnsiString;
begin
Result := clipbrdfunctions.ReadClipboardHtmlUTF8;
end;
function TClipboardViewer.ClipboardHasText: Boolean;
begin
Result := Clipboard.HasFormat(CF_TEXT);
end;
end.
|
program cpf;
uses crt;
var i,n: integer;
vet: array [1..11] of integer; {vetor único para todas as operações / single vector for all operations}
procedure primeirodigito; {primeiro procedimento para o primeiro dígito / first procedure for the first digit}
var soma,d,i,x,digito1: integer;
begin
soma:=0; {variável soma realiza a soma dos novos numeros / variable soma performs the sum of the new numbers}
d:=10; {variável d aplica pesos às posições / variable d applies weight to the positions}
for i:=1 to 9 do
begin
x:= vet[i];
soma:=soma+(d*x);
d:=d-1;
end;
writeln;
if (soma mod 11)< 2 then {comparação do resultado da divisão da soma por 11 / comparison of the result of dividing the sum by 11}
digito1:= 0 {caso menor que 2 assume-se o zero como digito / if less than 2 assumes zero as digit}
else
digito1:= 11- (soma mod 11); {caso contrário subtrai-se a soma de 11 e obtém o digito / otherwise subtract the sum of 11 and get the digit}
writeln;
writeln('Primeiro Digito: ',digito1);
vet[10]:= digito1;
writeln;
for i:=1 to 9 do
begin
write(vet[i],'.');
end;
write(vet[10]);
writeln;
end;
procedure segundodigito; {procedimento para o segundo dígito / procedure for the second digit}
var soma,d,i,x,digito2: integer;
begin
soma:=0; {igual o do primeiro, mas com o peso iniciando em 11 / same as the first but with the weight starting at 11}
d:=11;
for i:=1 to 10 do
begin
x:= vet[i];
soma:= soma+(d*x);
d:= d-1;
end;
writeln;
if (soma mod 11)< 2 then
digito2:= 0
else
digito2:= 11 - (soma mod 11);
writeln('Segundo Digito: ',digito2);
vet[11]:= digito2;
end;
begin
textbackground(white);
textcolor(blue);
writeln('Digite os nove primeiros numeros do C.P.F. [digite um numero e aperte Espaco, ao terminar aperte Enter]');
for i:=1 to 9 do {programa pedindo para você digitar os números / program asking you to enter the numbers}
begin {números sendo escritos e formatados / numbers being written and formatted}
read(n);
vet[i]:= n;
end;
writeln;
for i:=1 to 3 do
begin
write(vet[i]);
end;
write('.');
for i:=4 to 6 do
begin
write(vet[i]);
end;
write('.');
for i:=7 to 9 do
begin
write(vet[i]);
end;
primeirodigito; {chamando os dois procedimentos / calling both procedures}
segundodigito;
writeln;
writeln('Digitos Verificadores: ',vet[10],' e ',vet[11]);
writeln;
for i:=1 to 10 do {o C.P.F. aparece com os dígitos / C.P.F. appears with the digits}
begin
write(vet[i],'.');
end;
write(vet[11]);
writeln;
writeln;
writeln('O C.P.F. valido e: ');
writeln;
for i:=1 to 3 do {Agora o C.P.F. escrito em seu padrão / Now C.P.F. written in your standard form}
begin
write(vet[i]);
end;
write('.');
for i:=4 to 6 do
begin
write(vet[i]);
end;
write('.');
for i:=7 to 9 do
begin
write(vet[i]);
end;
write('-');
write(vet[10],vet[11]);
readkey;
end.
|
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ 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 Storage;
interface
uses
System.Classes, System.SysUtils, System.JSON, System.Hash, System.NetEncoding,
DUnitX.TestFramework,
REST.Types,
FB4D.Interfaces, FB4D.Response, FB4D.Request, FB4D.Storage;
{$M+}
type
[TestFixture]
UT_FirebaseStorage = class
strict private
fStorage: TFirebaseStorage;
public
[Setup]
procedure SetUp;
[TearDown]
procedure TearDown;
published
[TestCase]
procedure TestSynchronousUploadDownload;
end;
implementation
{$I FBConfig.inc}
procedure UT_FirebaseStorage.SetUp;
begin
fStorage := TFirebaseStorage.Create(cBucket, nil);
end;
procedure UT_FirebaseStorage.TearDown;
begin
FreeAndNil(fStorage);
end;
procedure UT_FirebaseStorage.TestSynchronousUploadDownload;
const
cObjName = 'TestObj.ini';
var
FileStream: TFileStream;
MemoryStream: TMemoryStream;
Obj, Obj2, Obj3: IStorageObject;
begin
FileStream := TFileStream.Create(ChangeFileExt(ParamStr(0), '.ini'), fmOpenRead);
try
Obj := fStorage.UploadSynchronousFromStream(FileStream, cObjName, ctTEXT_PLAIN);
finally
FileStream.Free;
end;
Assert.AreEqual(Obj.ObjectName(false), cObjName);
Assert.AreEqual(Obj.Path, '');
Obj2 := fStorage.GetSynchronous(cObjName);
Assert.AreEqual(Obj.ObjectName, Obj2.ObjectName);
Assert.AreEqual(Obj.ContentType, Obj2.ContentType);
Assert.AreEqual(Obj.MD5HashCode, Obj2.MD5HashCode);
Status('Download URL: ' + Obj.DownloadUrl);
MemoryStream := TMemoryStream.Create;
try
Obj3 := fStorage.GetAndDownloadSynchronous(cObjName, MemoryStream);
MemoryStream.Position := 0;
Assert.AreEqual(Obj.MD5HashCode, TNetEncoding.Base64.EncodeBytesToString(THashMD5.GetHashBytes(MemoryStream)), 'MD5 Hash not identical');
Status('MD5 Hash code compared between uploaded and downloaded object');
finally
MemoryStream.Free;
end;
Assert.AreEqual(Obj.ObjectName, Obj3.ObjectName);
Assert.AreEqual(Obj.ContentType, Obj3.ContentType);
Assert.AreEqual(Obj.MD5HashCode, Obj3.MD5HashCode);
fStorage.DeleteSynchronous(cObjName);
Status(cObjName + ' deleted');
Assert.WillRaise(
procedure
begin
fStorage.GetSynchronous(cObjName);
end,
EFirebaseResponse, 'Not Found. Could not get object');
end;
initialization
TDUnitX.RegisterTestFixture(UT_FirebaseStorage);
end.
|
unit EmployeeTypes;
interface
type
TEmployee = class(TObject)
private
FFullName : string;
FPhone : string;
FEmail : string;
FId : string;
FDepartment: string;
public
property Id : string read FId write FId;
property FullName: string read FFullName write FFullName;
property Department: string read FDepartment write FDepartment;
property Phone: string read FPhone write FPhone;
property Email: string read FEmail write FEmail;
end;
TEmployeeMetaData = record
public
const
BackendType = 'Employees';
FullNameColumn = 'fullname';
end;
implementation
end.
|
unit uFrmConfig;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, qjson, Vcl.ExtCtrls;
type
TfrmConfig = class(TForm)
Label7: TLabel;
edtServerIP: TEdit;
Label8: TLabel;
Label9: TLabel;
edtGroupName: TEdit;
btnSave: TButton;
btnClose: TButton;
edtServerPort: TSpinEdit;
chkSync: TCheckBox;
Bevel1: TBevel;
Bevel2: TBevel;
cmbBaudRate: TComboBox;
Label1: TLabel;
procedure btnSaveClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure Data2UI;
end;
function fnOpenCfg: Boolean;
//var
//frmConfig: TfrmConfig;
implementation
uses uData;
{$R *.dfm}
function fnOpenCfg: Boolean;
var
f: TfrmConfig;
begin
f := TfrmConfig.Create(nil);
try
f.Data2UI;
Result := f.ShowModal = mrOk;
finally
FreeAndNil(f);
end;
end;
function fnInitCfg: Boolean;
var
sCfg: string;
vJson: TQJson;
begin
Result := False;
sCfg := ExtractFilePath(ParamStr(0)) + 'Config\Cfg.Json';
if not FileExists(sCfg) then Exit;
vJson := TQJson.Create;
try
vJson.LoadFromFile(sCfg);
vJson.ToRecord<TConfig>(GConfig);
Result := True;
finally
FreeAndNil(vJson);
end;
end;
procedure TfrmConfig.btnSaveClick(Sender: TObject);
var
sCfg: string;
vJson: TQJson;
begin
vJson := TQJson.Create;
try
if Trim(edtServerIP.Text) = '' then
begin
Application.MessageBox('请填写服务地址!', '提示', MB_ICONWARNING);
Exit;
end;
if edtServerPort.Value < 1024 then
begin
Application.MessageBox('请服务端口填写有误!', '提示', MB_ICONWARNING);
Exit;
end;
if Trim(edtGroupName.Text) = '' then
begin
Application.MessageBox('请设置猫池组名称!', '提示', MB_ICONWARNING);
Exit;
end;
if cmbBaudRate.ItemIndex = -1 then
begin
Application.MessageBox('请选择波特率!', '提示', MB_ICONWARNING);
Exit;
end;
vJson.Clear;
GConfig.Host := Trim(edtServerIP.Text);
GConfig.Port := edtServerPort.Value;
GConfig.GroupName := Trim(edtGroupName.Text);
GConfig.SyncSocket := chkSync.Checked;
GConfig.BaudRate := StrToIntDef(cmbBaudRate.Text, 9600);
sCfg := ExtractFilePath(ParamStr(0)) + 'Config\Cfg.Json';
vJson.FromRecord<TConfig>(GConfig);
vJson.SaveToFile(sCfg);
Self.ModalResult := mrOk;
finally
FreeAndNil(vJson);
end;
end;
procedure TfrmConfig.Data2UI;
begin
//
edtServerIP.Text := GConfig.Host;
edtServerPort.Value := GConfig.Port;
edtGroupName.Text := GConfig.GroupName;
chkSync.Checked := GConfig.SyncSocket;
cmbBaudRate.ItemIndex := cmbBaudRate.Items.IndexOf(IntToStr(GConfig.BaudRate)) ;
end;
initialization
fnInitCfg;
finalization
end.
|
unit UFaceBookAlbumDemo;
interface
uses
FMX.Forms, FMX.TMSCloudBase, SysUtils, FMX.TMSCloudFacebook, FMX.Controls, FMX.Dialogs,
FMX.Edit, FMX.Grid, FMX.Layouts, FMX.TMSCloudListView, FMX.Objects,
FMX.TMSCloudImage, FMX.StdCtrls, System.Classes, FMX.Types,
FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomFacebook;
type
TForm1 = class(TForm)
StyleBook1: TStyleBook;
TMSFMXCloudFacebook1: TTMSFMXCloudFacebook;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Button1: TButton;
GroupBox3: TGroupBox;
SpeedButton2: TSpeedButton;
Label1: TLabel;
TMSFMXCloudCloudImage1: TTMSFMXCloudImage;
CloudListView1: TTMSFMXCloudListView;
CloudListView2: TTMSFMXCloudListView;
btAdd: TButton;
edAdd: TEdit;
Image1: TImage;
btRemove: TButton;
procedure Button1Click(Sender: TObject);
procedure ToggleControls;
procedure LoadAlbums;
procedure LoadPictures;
procedure Init;
procedure TMSFMXCloudFacebook1ReceivedAccessToken(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btAddClick(Sender: TObject);
procedure btRemoveClick(Sender: TObject);
procedure CloudListView2Change(Sender: TObject);
procedure CloudListView1Change(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Connected: boolean;
LVInit: boolean;
end;
var
Form1: TForm1;
implementation
{$R *.FMX}
// PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET
// FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE
// STRUCTURE OF THIS .INC FILE SHOULD BE
//
// const
// FacebookAppkey = 'xxxxxxxxx';
// FacebookAppSecret = 'yyyyyyyy';
{$I APPIDS.INC}
procedure TForm1.btAddClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
TMSFMXCloudFacebook1.PostImage(edAdd.Text, OpenDialog1.FileName, CloudListView2.Items[CloudListView2.ItemIndex].Data);
LoadPictures;
end;
end;
procedure TForm1.btRemoveClick(Sender: TObject);
begin
TMSFMXCloudFacebook1.ClearTokens;
Connected := false;
ToggleControls;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
acc: boolean;
begin
TMSFMXCloudFacebook1.App.Key := FacebookAppkey;
TMSFMXCloudFacebook1.App.Secret := FacebookAppSecret;
if TMSFMXCloudFacebook1.App.Key <> '' then
begin
TMSFMXCloudFacebook1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'facebook.ini';
TMSFMXCloudFacebook1.PersistTokens.Section := 'tokens';
TMSFMXCloudFacebook1.LoadTokens;
acc := TMSFMXCloudFacebook1.TestTokens;
if not acc then
begin
TMSFMXCloudFacebook1.RefreshAccess;
TMSFMXCloudFacebook1.DoAuth;
end
else
Init;
end
else
ShowMessage('Please provide a valid application ID for the client component');
end;
procedure TForm1.CloudListView1Change(Sender: TObject);
var
Picture: TFacebookPicture;
begin
if LVInit then
exit;
if CloudListView1.ItemIndex >= 0 then
begin
Picture := CloudListView1.Items[CloudListView1.ItemIndex].Data;
TMSFMXCloudCloudImage1.URL := Picture.ImageURL;
end;
end;
procedure TForm1.CloudListView2Change(Sender: TObject);
begin
if LVInit then
exit;
LoadPictures;
end;
procedure TForm1.TMSFMXCloudFacebook1ReceivedAccessToken(Sender: TObject);
begin
TMSFMXCloudFacebook1.SaveTokens;
Init;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
LVInit := false;
Connected := false;
ToggleControls;
end;
procedure TForm1.Init;
begin
Connected := true;
ToggleControls;
TMSFMXCloudFacebook1.GetUserInfo;
LoadAlbums;
end;
procedure TForm1.LoadAlbums;
var
I: integer;
Profile: TFacebookProfile;
li: TListItem;
begin
LVInit := true;
TMSFMXCloudFacebook1.GetAlbums(TMSFMXCloudFacebook1.Profile);
CloudListView2.Items.Clear;
Profile := TMSFMXCloudFacebook1.Profile;
for I := 0 to Profile.Albums.Count - 1 do
begin
li := CloudListView2.Items.Add;
li.Text := Profile.Albums[I].Title;
li.SubItems.Add(DateToStr(Profile.Albums[I].UpdatedTime));
li.Data := Profile.Albums[I];
end;
LVInit := false;
end;
procedure TForm1.LoadPictures;
var
AlbumItem: TFacebookAlbum;
li: TListItem;
I: Integer;
begin
if CloudListView2.ItemIndex >= 0 then
begin
LVInit := true;
edAdd.Enabled := true;
btAdd.Enabled := true;
AlbumItem := CloudListView2.Items[CloudListView2.ItemIndex].Data;
TMSFMXCloudCloudImage1.URL := TMSFMXCloudFacebook1.GetImageURL(AlbumItem.CoverPhotoID);
CloudListView1.Items.Clear;
TMSFMXCloudFacebook1.GetPictures(AlbumItem);
for I := 0 to AlbumItem.Pictures.Count - 1 do
begin
li := CloudListView1.Items.Add;
li.Text := AlbumItem.Pictures[I].Caption;
if li.Text = '' then
li.Text := 'No Description';
li.SubItems.Add(DateToStr(AlbumItem.Pictures[I].CreatedTime));
li.Data := AlbumItem.Pictures[I];
end;
LVInit := false;
end;
end;
procedure TForm1.SpeedButton2Click(Sender: TObject);
begin
LoadAlbums;
end;
procedure TForm1.ToggleControls;
begin
GroupBox3.Enabled := Connected;
SpeedButton2.Enabled := Connected;
CloudListView2.Enabled := Connected;
CloudListView1.Enabled := Connected;
btRemove.Enabled := Connected;
Button1.Enabled := not Connected;
end;
end.
|
unit FormEventos;
interface
uses
UCalendario,
DateUtils,
Umodconexion,
URegistros,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Buttons, StdCtrls, DBCtrls,
ExtCtrls, ComCtrls, JvExControls, JvSpeedButton, DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset;
type
CLCalendario=class(CGenerarCalendario)
public
procedure HacerClick(Sender: TObject); override;
end;
TFEventos = class(TForm)
Label1: TLabel;
Cmes: TComboBox;
cano: TComboBox;
QSQL: TZQuery;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
GenenrarCalendario : CLCalendario;
pk_condominio, pk_usuario:string;
procedure Iniciar;
end;
var
FEventos: TFEventos;
implementation
uses UFAgregarEvento, UFConfiguracionEvento;
{$R *.dfm}
function NombreMes(mes: Integer): string;
const
MESES: array[1..12] of string = ('Enero','Febrero','Marzo','Abril','Mayo',
'Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');
begin
Result:= MESES[mes];
end;
function ObtenerNumeroMes(mes:string):Integer;
const
{}
MESES: array[1..12] of string = ('Enero','Febrero','Marzo','Abril','Mayo',
'Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre');
var i:integer;
begin
for i := 1 to 12 do
if MESES[i]=mes then
Result:=i;
end;
procedure TFEventos.FormCreate(Sender: TObject);
begin
GenenrarCalendario := CLCalendario.Crear(FEventos,FEventos);
end;
procedure TFEventos.FormShow(Sender: TObject);
var
aNo, Mes, Dia:Word;
begin
DecodeDate(now(), aNo, Mes, Dia);
Cmes.Text:=NombreMes(mes);
cano.Text:=inttostr(ano);
Iniciar;
end;
procedure TFEventos.Iniciar;
var
anio,mes:Integer;
dia,numero:integer;
begin
mes:=(ObtenerNumeroMes( Cmes.Text));
anio:=StrToInt(cano.Text);
GenenrarCalendario.EliminarComponentes;
GenenrarCalendario.SetDimencion(anio,mes);
//GenenrarCalendario.Generar;
with QSQL do
begin
SQL.Text:='SELECT pk_evento,fecha,anio,mes,dia,horainicio,'+
'horafin,fk_contrato,fk_propietario,'+
'fk_persona,disponible'+
',numero FROM evento where mes='+IntToStr(mes)+' and anio='+IntToStr(anio);
Open;
Active:=True;
while not(eof) do
begin
dia :=FieldByName('dia').AsInteger;
GenenrarCalendario.Lista[dia].Anio := StrToInt(cano.Text);
GenenrarCalendario.Lista[dia].Mes:=mes;
GenenrarCalendario.Lista[dia].Dia:=FieldByName('dia').Value;
GenenrarCalendario.Lista[dia].Numero:=FieldByName('numero').AsString;
numero := FieldByName('numero').AsInteger;
if FieldByName('disponible').AsString='Libre' then
begin
GenenrarCalendario.Lista[dia].Parrillas[numero].Color:= ColorLibre;
GenenrarCalendario.Lista[dia].Parrillas[numero].Numero := FieldByName('numero').Value;
GenenrarCalendario.Lista[dia].Parrillas[numero].Codigo:= FieldByName('pk_evento').value;
end;
if FieldByName('disponible').AsString='Solicitada' then
begin
GenenrarCalendario.Lista[dia].Parrillas[numero].Color:=ColorPendiente;
GenenrarCalendario.Lista[dia].Parrillas[numero].Numero := FieldByName('numero').Value;
GenenrarCalendario.Lista[dia].Parrillas[numero].Codigo:= FieldByName('pk_evento').value; end;
if FieldByName('disponible').AsString='Reservada' then
begin
GenenrarCalendario.Lista[dia].Parrillas[numero].Color:=ColorReservado;
GenenrarCalendario.Lista[dia].Parrillas[numero].Numero := FieldByName('numero').Value;
GenenrarCalendario.Lista[dia].Parrillas[numero].Codigo:= FieldByName('pk_evento').value;
end;
QSQL.Next;
end;
end;
GenenrarCalendario.Construir;
end;
procedure TFEventos.SpeedButton1Click(Sender: TObject);
begin
FConfiguracionEvento.ShowModal;
end;
procedure TFEventos.SpeedButton2Click(Sender: TObject);
begin
Iniciar;
end;
{ CCalendario }
procedure CLCalendario.HacerClick(Sender: TObject);
begin
inherited;
//ShowMessage('Hola');
with (Sender as TPanel) do
begin
FAgregarEvento.Dato:=Hint;
FAgregarEvento.ShowModal;
end;
FEventos.Iniciar;
end;
end.
|
unit DAO.Usuarios;
interface
uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Usuarios, Dialogs;
type
TUsuariosDAO = class
private
FConexao : TConexao;
public
constructor Create;
function GetId(): Integer;
function Inserir(AUsuarios: TUsuarios): Boolean;
function Alterar(AUsuarios: TUsuarios): Boolean;
function Excluir(AUsuarios: TUsuarios): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
function ValidaLogin(sLogin: String; sSenha: String): Boolean;
function AlteraSenha(AUsuarios: TUsuarios): Boolean;
function LoginExiste(sLogin: String): Boolean;
function EMailExiste(sEMail: String): Boolean;
function ValidaLoginEMail(sEMail: String; sSenha: String): Boolean;
end;
const
TABLENAME = 'tbusuarios';
CHAVE = 'ABCDEFGHIJ0987654321KLMNOPQRSTUVXZ0123456789';
implementation
{ TUsuariosDAO }
uses Control.Sistema;
function TUsuariosDAO.Alterar(AUsuarios: TUsuarios): Boolean;
var
FDQuery : TFDQuery;
begin
try
REsult := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET '+
'NOM_USUARIO = :pNOM_USUARIO, DES_LOGIN = :pDES_LOGIN, DES_EMAIL = :pDES_EMAIL, ' +
'DES_SENHA = AES_ENCRYPT(:pDES_SENHA,' + QuotedStr(CHAVE) + '), COD_GRUPO = :pCOD_GRUPO, ' +
'DOM_PRIVILEGIO = :pDOM_PRIVILEGIO, DOM_EXPIRA = :pDOM_EXPIRA, QTD_DIAS_EXPIRA = :pQTD_DIAS_EXPIRA, ' +
'DOM_PRIMEIRO_ACESSO = :pDOM_PRIMEIRO_ACESSO, DOM_ATIVO = :pDOM_ATIVO, ' +
'DAT_SENHA = :pDAT_SENHA, COD_NIVEL = :pCOD_NIVEL, NOM_EXECUTOR = :pNOM_EXECUTOR, ' +
'DAT_MANUTENCAO = :pDAT_MANUTENCAO ' +
'WHERE COD_USUARIO = :pCOD_USUARIO;', [aUsuarios.Nome, aUsuarios.Login, aUsuarios.EMail, aUsuarios.Senha,
aUsuarios.Grupo, aUsuarios.Privilegio, aUsuarios.Expira, aUsuarios.DiasExpira, aUsuarios.PrimeiroAcesso,
aUsuarios.Ativo, FloatToDateTime(aUsuarios.DataSenha), aUsuarios.Nivel, aUsuarios.Executor, aUsuarios.Manutencao,
aUsuarios.Codigo]);
Result := True;
finally
FDQuery.Connection.Close;
FConexao.Free;
end;
end;
function TUsuariosDAO.AlteraSenha(AUsuarios: TUsuarios): Boolean;
var
FDQuery : TFDQuery;
begin
try
REsult := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET '+
'DES_SENHA = AES_ENCRYPT(:pDES_SENHA,' + QuotedStr(CHAVE) + '), ' +
'DOM_PRIMEIRO_ACESSO = :pDOM_PRIMEIRO_ACESSO, ' +
'DAT_SENHA = :pDAT_SENHA, NOM_EXECUTOR = :pNOM_EXECUTOR, DAT_MANUTENCAO = :pDAT_MANUTENCAO ' +
'WHERE COD_USUARIO = :pCOD_USUARIO;', [aUsuarios.Senha, aUsuarios.PrimeiroAcesso,
FloatToDateTime(aUsuarios.DataSenha), aUsuarios.Executor, aUsuarios.Manutencao, aUsuarios.Codigo]);
Result := True;
finally
FDQuery.Connection.Close;
FConexao.Free;
end;
end;
constructor TUsuariosDAO.Create;
begin
FConexao := TConexao.Create;
end;
function TUsuariosDAO.EMailExiste(sEMail: String): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE DES_EMAIL = :pDES_EMAIL');
FDQuery.ParamByName('pDES_EMAIL').AsString := sEMail;
FDQuery.Open();
Result := (not FDQuery.IsEmpty);
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TUsuariosDAO.Excluir(AUsuarios: TUsuarios): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE COD_USUARIO = :COD_USUARIO', [AUsuarios.Codigo]);
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TUsuariosDAO.GetId: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery;
FDQuery.Open('select coalesce(max(COD_USUARIO),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TUsuariosDAO.Inserir(AUsuarios: TUsuarios): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery;
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' '+
'(NOM_USUARIO, DES_LOGIN, DES_EMAIL, DES_SENHA, COD_GRUPO, DOM_PRIVILEGIO, ' +
'DOM_EXPIRA, QTD_DIAS_EXPIRA, DOM_PRIMEIRO_ACESSO, DOM_ATIVO, DAT_SENHA, COD_NIVEL, ' +
'NOM_EXECUTOR, DAT_MANUTENCAO) ' +
'VALUES ' +
'(:pNOM_USUARIO, :pDES_LOGIN, :pDES_EMAIL, AES_ENCRYPT(:pDES_SENHA,' + QuotedStr(CHAVE) + '), ' +
':pCOD_GRUPO, :pDOM_PRIVILEGIO, :pDOM_EXPIRA, :pQTD_DIAS_EXPIRA, :pDOM_PRIMEIRO_ACESSO, ' +
':pDOM_ATIVO, :pDAT_SENHA, :pCOD_NIVEL, :pNOM_EXECUTOR, :pDAT_MANUTENCAO);' ,
[aUsuarios.Nome, aUsuarios.Login, aUsuarios.EMail, aUsuarios.Senha,
aUsuarios.Grupo, aUsuarios.Privilegio, aUsuarios.Expira, aUsuarios.DiasExpira, aUsuarios.PrimeiroAcesso,
aUsuarios.Ativo, FloatToDateTime(aUsuarios.DataSenha), aUsuarios.Nivel, aUsuarios.Executor, aUsuarios.Manutencao]);
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
function TUsuariosDAO.LoginExiste(sLogin: String): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE DES_LOGIN = :pDES_LOGIN');
FDQuery.ParamByName('pDES_LOGIN').AsString := sLogin;
FDQuery.Open();
Result := (not FDQuery.IsEmpty);
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TUsuariosDAO.Pesquisar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery;
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT COD_USUARIO, NOM_USUARIO, DES_LOGIN, DES_EMAIL, DES_SENHA, AES_DECRYPT(DES_SENHA, ' + QuotedStr(CHAVE) +
') as PWD, '+
'COD_GRUPO, DOM_PRIVILEGIO, DOM_EXPIRA, QTD_DIAS_EXPIRA, DOM_PRIMEIRO_ACESSO, DOM_ATIVO, DAT_SENHA, ' +
'COD_NIVEL, NOM_EXECUTOR, DAT_MANUTENCAO FROM ' + TABLENAME);
if aParam[0] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE COD_USUARIO = :COD_USUARIO');
FDQuery.ParamByName('COD_USUARIO').AsInteger := aParam[1];
end;
if aParam[0] = 'LOGIN' then
begin
FDQuery.SQL.Add('WHERE DES_LOGIN = :DES_LOGIN');
FDQuery.ParamByName('DES_LOGIN').AsString := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('WHERE NOM_USUARIO LIKE :NOM_USUARIO');
FDQuery.ParamByName('NOM_USUARIO').AsString := aParam[1];
end;
if aParam[0] = 'EMAIL' then
begin
FDQuery.SQL.Add('WHERE DES_EMAIL = :DES_EMAIL');
FDQuery.ParamByName('DES_EMAIL').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('WHERE ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open();
Result := FDQuery;
end;
function TUsuariosDAO.ValidaLogin(sLogin, sSenha: String): Boolean;
var
FDquery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT AES_DECRYPT(DES_SENHA,:pCHAVE) AS SENHA FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE DES_LOGIN = :pDES_LOGIN');
FDQuery.ParamByName('pDES_LOGIN').AsString := sLogin;
FDQuery.ParamByName('pCHAVE').AsString := CHAVE;
FDQuery.Open();
if FDquery.IsEmpty then Exit;
if not FDquery.FieldByName('SENHA').AsString.Equals(sSenha) then Exit;
Result := True;
finally
FDquery.Connection.Close;
FDquery.Free;
end;
end;
function TUsuariosDAO.ValidaLoginEMail(sEMail, sSenha: String): Boolean;
var
FDquery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT AES_DECRYPT(DES_SENHA,:pCHAVE) AS SENHA FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE DES_EMAIL = :pDES_EMAIL');
FDQuery.ParamByName('pDES_EMAIL').AsString := sEMail;
FDQuery.ParamByName('pCHAVE').AsString := CHAVE;
FDQuery.Open();
if FDquery.IsEmpty then Exit;
if not FDquery.FieldByName('SENHA').AsString.Equals(sSenha) then Exit;
Result := True;
finally
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
end.
|
unit TextReader;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
BufSize = 8192;
type
TTextReader = class(TComponent)
private
DataFile: file;
Buffer: array[1..BufSize] of char;
FSizeOfFile: int64;
CharsRead: integer;
BytesRead: integer;
BufPtr: integer;
FFileName: TFileName;
FEof: boolean;
FLineCount: integer;
FCharCount: integer;
FErrorString: string;
procedure SetFileName(const Value: TFileName);
procedure SetEof(const Value: boolean);
function GetNextChar: char;
procedure AddErrorChar(s: string; c: char);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
procedure OpenDataFile;
function ReadLine:string;
procedure CloseDataFile;
property Eof:boolean read FEof write SetEof;
property LineCount:integer read FLineCount;
property CharCount:integer read FCharCount;
property ErrorString:string read FErrorString;
function PercentRead:integer;
property SizeOfFile:int64 read FSizeOfFile;
published
{ Published declarations }
property FileName:TFileName read FFileName write SetFileName;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TTextReader]);
end;
{ TTextReader }
procedure TTextReader.CloseDataFile;
begin
CloseFile(DataFile);
end;
procedure TTextReader.OpenDataFile;
begin
AssignFile(DataFile, FileName);
Reset(DataFile, 1);
BytesRead := 0;
BufPtr := 0;
FLineCount := 0;
CharsRead := 0;
FSizeOfFile := filesize(DataFile);
if FSizeOfFile > 0 then Eof := false
else Eof := true;
end;
function TTextReader.GetNextChar:char;
begin
inc(CharsRead);
if CharsRead = FSizeOfFile then Eof := true;
inc(BufPtr);
if BufPtr > BytesRead then
begin
fillchar(Buffer, sizeof(Buffer), 0);
BlockRead(DataFile, Buffer, BufSize, BytesRead);
BufPtr := 1;
end;
// first test gave it a chance to read more data, Second test kicks it out if there's still nothing
if BufPtr > BytesRead then result := #0
else begin
if Buffer[BufPtr] = #0 then result := ' '
else result := Buffer[BufPtr];
end;
inc(FCharCount);
end;
procedure TTextReader.AddErrorChar(s:string;c:char);
var x : integer;
begin
x := ord(c);
s := s + ' ';
if FErrorString > '' then FErrorString := FErrorString + #13#10;
FErrorString := FErrorString + 'Bad character: #' + inttostr(x) + ' in line ' + inttostr(LineCount) + ' at position ' + inttostr(charcount) + '.';
end;
function TTextReader.ReadLine: string;
var s : string;
c : char;
nc : char;
done : boolean;
begin
FErrorString := '';
FCharCount := 0;
inc(FLineCount);
s := '';
done := false;
nc := #0;
while not done do
begin
if nc = #0 then c := GetNextChar
else c := nc;
nc := #0;
case c of
#0 : begin
done := true;
Eof := true;
end;
#1..#12 : AddErrorChar(s,c);
#13 : begin
nc := GetNextChar;
if nc = #10 then done := true
else AddErrorChar(s,c);
end;
#14..#31 : AddErrorChar(s,c);
#32..#126 : s := s + c;
#127..#255 : AddErrorChar(s,c);
end;
end;
result := s;
end;
procedure TTextReader.SetEof(const Value: boolean);
begin
FEof := Value;
end;
procedure TTextReader.SetFileName(const Value: TFileName);
begin
FFileName := Value;
end;
function TTextReader.PercentRead: integer;
begin
if FSizeOfFile = 0 then result := 0
else result := Integer((100 * Int64(CharsRead)) div FSizeOfFile);
end;
end.
|
{ RegisterRxTools unit
Copyright (C) 2005-2013 Lagunov Aleksey alexs@hotbox.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit RegisterRxTools;
{$I rx.inc}
interface
uses
Classes, SysUtils, LResources, LazarusPackageIntf;
procedure Register;
implementation
uses RxSystemServices, RxLogin, RxVersInfo, RxCloseFormValidator, RxIniPropStorage;
const
sRxToolsPage = 'RX Tools';
procedure RegisterRxSystemServices;
begin
RegisterComponents(sRxToolsPage, [TRxSystemServices]);
end;
procedure RegisterRxLogin;
begin
RegisterComponents(sRxToolsPage, [TRxLoginDialog]);
end;
procedure RegisterRxVersInfo;
begin
RegisterComponents(sRxToolsPage, [TRxVersionInfo]);
end;
procedure RegisterCloseFormValidator;
begin
RegisterComponents(sRxToolsPage,[TRxCloseFormValidator]);
end;
procedure RegisterRxIniPropStorage;
begin
RegisterComponents(sRxToolsPage,[TRxIniPropStorage]);
end;
procedure Register;
begin
RegisterUnit('RxLogin', @RegisterRxLogin);
RegisterUnit('RxVersInfo', @RegisterRxVersInfo);
RegisterUnit('RxSystemServices', @RegisterRxSystemServices);
RegisterUnit('RxCloseFormValidator', @RegisterCloseFormValidator);
RegisterUnit('RxIniPropStorage', @RegisterRxIniPropStorage);
end;
end.
|
(*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Initial Developer of this code is John Hansen.
* Portions created by John Hansen are Copyright (C) 2009 John Hansen.
* All Rights Reserved.
*
*)
unit uNBCCommon;
interface
uses
Parser10, uNXTConstants, Classes, SysUtils;
type
TLangName = (lnNBC, lnNXC, lnNXCHeader, lnRICScript, lnUnknown);
TNBCExpParser = class(TExpParser)
private
fStandardDefs: boolean;
fExtraDefs: boolean;
fFirmwareVersion: word;
procedure SetStandardDefs(const aValue: boolean);
procedure SetExtraDefs(const aValue: boolean);
procedure SetFirmwareVersion(const Value: word);
public
constructor Create(AOwner: TComponent); override;
procedure InitializeCalc;
property StandardDefines : boolean read fStandardDefs write SetStandardDefs;
property ExtraDefines : boolean read fExtraDefs write SetExtraDefs;
property FirmwareVersion : word read fFirmwareVersion write SetFirmwareVersion;
end;
TStatementType = (stUnsigned, stSigned, stFloat);
TSymbolType = (stUnknown, stParam, stLocal, stGlobal, stAPIFunc, stAPIStrFunc);
TOnCompilerMessage = procedure(const msg : string; var stop : boolean) of object;
TFuncParamType = (fptUBYTE, fptSBYTE, fptUWORD, fptSWORD, fptULONG, fptSLONG, fptUDT, fptString, fptMutex, fptFloat);
TFunctionParameter = class(TCollectionItem)
private
fName: string;
fProcName: string;
fIsReference: boolean;
fIsArray: boolean;
fIsConstant: boolean;
fParamType: TFuncParamType;
fParamIndex: integer;
fDim: integer;
fConstValue : string;
fPTName: string;
fFuncIsInline: boolean;
fHasDefault: boolean;
fDefaultValue: string;
function GetParamDataType: char;
function GetIsConstReference: boolean;
function GetIsVarReference: boolean;
function GetConstValue: string;
procedure SetConstValue(const Value: string);
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(ACollection: TCollection); override;
property ProcName : string read fProcName write fProcName;
property Name : string read fName write fName;
property ParamIndex : integer read fParamIndex write fParamIndex;
property ParamType : TFuncParamType read fParamType write fParamType;
property ParamTypeName : string read fPTName write fPTName;
property IsReference : boolean read fIsReference write fIsReference;
property IsConstant : boolean read fIsConstant write fIsConstant;
property IsArray : boolean read fIsArray write fIsArray;
property ArrayDimension : integer read fDim write fDim;
property ParameterDataType : char read GetParamDataType;
property IsVarReference : boolean read GetIsVarReference;
property IsConstReference : boolean read GetIsConstReference;
property ConstantValue : string read GetConstValue write SetConstValue;
property FuncIsInline : boolean read fFuncIsInline write fFuncIsInline;
property HasDefault : boolean read fHasDefault write fHasDefault;
property DefaultValue : string read fDefaultValue write fDefaultValue;
end;
TFunctionParameters = class(TCollection)
private
function GetItem(Index: Integer): TFunctionParameter;
procedure SetItem(Index: Integer; const Value: TFunctionParameter);
public
constructor Create; virtual;
function Add: TFunctionParameter;
function Insert(Index: Integer): TFunctionParameter;
property Items[Index: Integer]: TFunctionParameter read GetItem write SetItem; default;
function IndexOf(const procname : string; const idx : integer) : integer; overload;
function ParamCount(const name : string) : integer;
function RequiredParamCount(const name : string) : integer;
end;
TVariable = class(TCollectionItem)
private
fIsConst: boolean;
fDataType: char;
fName: string;
fValue: string;
fTypeName: string;
fLenExpr: string;
fUseSafeCall: boolean;
fLevel: integer;
fHasDef: boolean;
fDefValue: string;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create(ACollection: TCollection); override;
property Name : string read fName write fName;
property DataType : char read fDataType write fDataType;
property IsConstant : boolean read fIsConst write fIsConst;
property UseSafeCall : boolean read fUseSafeCall write fUseSafeCall;
property Value : string read fValue write fValue;
property TypeName : string read fTypeName write fTypeName;
property LenExpr : string read fLenExpr write fLenExpr;
property Level : integer read fLevel write fLevel;
property HasDefault : boolean read fHasDef write fHasDef;
property DefaultValue : string read fDefValue write fDefValue;
end;
TVariableList = class(TCollection)
private
function GetItem(Index: Integer): TVariable;
procedure SetItem(Index: Integer; const Value: TVariable);
public
constructor Create; virtual;
function Add: TVariable;
function Insert(Index: Integer): TVariable;
function IndexOfName(const name : string) : integer;
property Items[Index: Integer]: TVariable read GetItem write SetItem; default;
end;
TInlineFunction = class(TCollectionItem)
private
fName: string;
fCode: TStrings;
fEmitCount : integer;
fVariables: TVariableList;
fCallers: TStrings;
fParams: TFunctionParameters;
fCurrentCaller: string;
procedure SetCode(const Value: TStrings);
procedure SetParams(const Value: TFunctionParameters);
function GetEndLabel: string;
function FixupLabels(const tmpCode : string) : string;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure Emit(aStrings : TStrings);
property Name : string read fName write fName;
property Code : TStrings read fCode write SetCode;
property LocalVariables : TVariableList read fVariables;
property Callers : TStrings read fCallers;
property Parameters : TFunctionParameters read fParams write SetParams;
property CurrentCaller : string read fCurrentCaller write fCurrentCaller;
property EndLabel : string read GetEndLabel;
end;
TInlineFunctions = class(TCollection)
private
function GetItem(Index: Integer): TInlineFunction;
procedure SetItem(Index: Integer; const Value: TInlineFunction);
public
constructor Create; virtual;
function Add: TInlineFunction;
function Insert(Index: Integer): TInlineFunction;
function IndexOfName(const name : string) : integer;
property Items[Index: Integer]: TInlineFunction read GetItem write SetItem; default;
end;
TArrayHelperVar = class(TCollectionItem)
private
fThreadName: string;
fUDType : string;
fDataType: char;
fIndex : integer;
fLocked : boolean;
function GetName : string;
public
constructor Create(ACollection: TCollection); override;
property ThreadName : string read fThreadName write fThreadName;
property DataType : char read fDataType write fDataType;
property UserDefinedType : string read fUDType write fUDType;
property Index : integer read fIndex;
property Locked : boolean read fLocked;
property Name : string read GetName;
end;
TArrayHelperVars = class(TCollection)
private
function GetItem(Index: Integer): TArrayHelperVar;
procedure SetItem(Index: Integer; const Value: TArrayHelperVar);
public
constructor Create; virtual;
function Add: TArrayHelperVar;
function Insert(Index: Integer): TArrayHelperVar;
function IndexOfName(const name : string) : integer;
function GetHelper(const tname, udType : string; const dt : char) : TArrayHelperVar;
procedure ReleaseHelper(aHelper : TArrayHelperVar);
property Items[Index: Integer]: TArrayHelperVar read GetItem write SetItem; default;
end;
const
LABEL_PREFIX = '__NXC_Label_';
const
STR_NA = 'NA';
STR_TRUE = 'TRUE';
STR_FALSE = 'FALSE';
STR_OUT_A = 'OUT_A';
STR_OUT_B = 'OUT_B';
STR_OUT_C = 'OUT_C';
OUT_A = $00;
OUT_B = $01;
OUT_C = $02;
OUT_AB = $03;
OUT_AC = $04;
OUT_BC = $05;
OUT_ABC = $06;
STR_IN_1 = 'IN_1';
STR_IN_2 = 'IN_2';
STR_IN_3 = 'IN_3';
STR_IN_4 = 'IN_4';
IN_1 = $00;
IN_2 = $01;
IN_3 = $02;
IN_4 = $03;
STR_IO_BASE = 'IO_BASE';
STR_MOD_INPUT = 'MOD_INPUT';
STR_MOD_OUTPUT = 'MOD_OUTPUT';
STR_IO_IN_FPP = 'IO_IN_FPP';
STR_IO_OUT_FPP = 'IO_OUT_FPP';
IO_BASE = $c000;
MOD_INPUT = $0000;
MOD_OUTPUT = $0200;
IO_IN_FPP = 6;
IO_OUT_FPP = 15;
type
CCEncoding = record
Encoding : Byte;
Group : Byte;
Mode : String;
Symbol : String;
end;
const
CCEncodingsCount = 6;
CCEncodings : array[0..CCEncodingsCount-1] of CCEncoding =
(
( Encoding: 0; Group: 1; Mode: 'LT' ; Symbol: '<'; ),
( Encoding: 1; Group: 1; Mode: 'GT' ; Symbol: '>'; ),
( Encoding: 2; Group: 1; Mode: 'LTEQ'; Symbol: '<='; ),
( Encoding: 3; Group: 1; Mode: 'GTEQ'; Symbol: '>='; ),
( Encoding: 4; Group: 1; Mode: 'EQ' ; Symbol: '=='; ),
( Encoding: 5; Group: 1; Mode: 'NEQ' ; Symbol: '!='; )
);
type
IDRec = record
ID : integer;
Name : string;
end;
const
UFCount = 8;
UFRecords : array[0..UFCount-1] of IDRec =
(
( ID: UF_UPDATE_MODE; Name: 'UF_UPDATE_MODE'; ),
( ID: UF_UPDATE_SPEED; Name: 'UF_UPDATE_SPEED'; ),
( ID: UF_UPDATE_TACHO_LIMIT; Name: 'UF_UPDATE_TACHO_LIMIT'; ),
( ID: UF_UPDATE_RESET_COUNT; Name: 'UF_UPDATE_RESET_COUNT'; ),
( ID: UF_UPDATE_PID_VALUES; Name: 'UF_UPDATE_PID_VALUES'; ),
( ID: UF_UPDATE_RESET_BLOCK_COUNT; Name: 'UF_UPDATE_RESET_BLOCK_COUNT'; ),
( ID: UF_UPDATE_RESET_ROTATION_COUNT; Name: 'UF_UPDATE_RESET_ROTATION_COUNT'; ),
( ID: UF_PENDING_UPDATES; Name: 'UF_PENDING_UPDATES'; )
);
const
OutModeCount = 5;
OutModeRecords : array[0..OutModeCount-1] of IDRec =
(
( ID: OUT_MODE_COAST; Name: 'OUT_MODE_COAST'; ),
( ID: OUT_MODE_MOTORON; Name: 'OUT_MODE_MOTORON'; ),
( ID: OUT_MODE_BRAKE; Name: 'OUT_MODE_BRAKE'; ),
( ID: OUT_MODE_REGULATED; Name: 'OUT_MODE_REGULATED'; ),
( ID: OUT_MODE_REGMETHOD; Name: 'OUT_MODE_REGMETHOD'; )
);
const
OutRunStateCount = 4;
OutRunStateRecords : array[0..OutRunStateCount-1] of IDRec =
(
( ID: OUT_RUNSTATE_IDLE; Name: 'OUT_RUNSTATE_IDLE'; ),
( ID: OUT_RUNSTATE_RAMPUP; Name: 'OUT_RUNSTATE_RAMPUP'; ),
( ID: OUT_RUNSTATE_RUNNING; Name: 'OUT_RUNSTATE_RUNNING'; ),
( ID: OUT_RUNSTATE_RAMPDOWN; Name: 'OUT_RUNSTATE_RAMPDOWN'; )
);
const
OutRegModeCount = 3;
OutRegModeRecords : array[0..OutRegModeCount-1] of IDRec =
(
( ID: OUT_REGMODE_IDLE; Name: 'OUT_REGMODE_IDLE'; ),
( ID: OUT_REGMODE_SPEED; Name: 'OUT_REGMODE_SPEED'; ),
( ID: OUT_REGMODE_SYNC; Name: 'OUT_REGMODE_SYNC'; )
);
const
InTypeCount = 18;
InTypeRecords : array[0..InTypeCount-1] of IDRec =
(
( ID: IN_TYPE_NO_SENSOR; Name: 'IN_TYPE_NO_SENSOR'; ),
( ID: IN_TYPE_SWITCH; Name: 'IN_TYPE_SWITCH'; ),
( ID: IN_TYPE_TEMPERATURE; Name: 'IN_TYPE_TEMPERATURE'; ),
( ID: IN_TYPE_REFLECTION; Name: 'IN_TYPE_REFLECTION'; ),
( ID: IN_TYPE_ANGLE; Name: 'IN_TYPE_ANGLE'; ),
( ID: IN_TYPE_LIGHT_ACTIVE; Name: 'IN_TYPE_LIGHT_ACTIVE'; ),
( ID: IN_TYPE_LIGHT_INACTIVE; Name: 'IN_TYPE_LIGHT_INACTIVE'; ),
( ID: IN_TYPE_SOUND_DB; Name: 'IN_TYPE_SOUND_DB'; ),
( ID: IN_TYPE_SOUND_DBA; Name: 'IN_TYPE_SOUND_DBA'; ),
( ID: IN_TYPE_CUSTOM; Name: 'IN_TYPE_CUSTOM'; ),
( ID: IN_TYPE_LOWSPEED; Name: 'IN_TYPE_LOWSPEED'; ),
( ID: IN_TYPE_LOWSPEED_9V; Name: 'IN_TYPE_LOWSPEED_9V'; ),
( ID: IN_TYPE_HISPEED; Name: 'IN_TYPE_HISPEED'; ),
( ID: IN_TYPE_COLORFULL; Name: 'IN_TYPE_COLORFULL'; ),
( ID: IN_TYPE_COLORRED; Name: 'IN_TYPE_COLORRED'; ),
( ID: IN_TYPE_COLORGREEN; Name: 'IN_TYPE_COLORGREEN'; ),
( ID: IN_TYPE_COLORBLUE; Name: 'IN_TYPE_COLORBLUE'; ),
( ID: IN_TYPE_COLORNONE; Name: 'IN_TYPE_COLORNONE'; )
);
const
InModeCount = 10;
InModeRecords : array[0..InModeCount-1] of IDRec =
(
( ID: IN_MODE_RAW; Name: 'IN_MODE_RAW'; ),
( ID: IN_MODE_BOOLEAN; Name: 'IN_MODE_BOOLEAN'; ),
( ID: IN_MODE_TRANSITIONCNT; Name: 'IN_MODE_TRANSITIONCNT'; ),
( ID: IN_MODE_PERIODCOUNTER; Name: 'IN_MODE_PERIODCOUNTER'; ),
( ID: IN_MODE_PCTFULLSCALE; Name: 'IN_MODE_PCTFULLSCALE'; ),
( ID: IN_MODE_CELSIUS; Name: 'IN_MODE_CELSIUS'; ),
( ID: IN_MODE_FAHRENHEIT; Name: 'IN_MODE_FAHRENHEIT'; ),
( ID: IN_MODE_ANGLESTEP; Name: 'IN_MODE_ANGLESTEP'; ),
( ID: IN_MODE_SLOPEMASK; Name: 'IN_MODE_SLOPEMASK'; ),
( ID: IN_MODE_MODEMASK; Name: 'IN_MODE_MODEMASK'; )
);
const
OutputFieldIDsCount = 18;
NumOutputs = 3;
OutputFieldIDs : array[0..OutputFieldIDsCount-1] of IDRec =
(
( ID: UpdateFlags; Name: 'UpdateFlags'; ),
( ID: OutputMode; Name: 'OutputMode'; ),
( ID: Power; Name: 'Power'; ),
( ID: ActualSpeed; Name: 'ActualSpeed'; ),
( ID: TachoCount; Name: 'TachoCount'; ),
( ID: TachoLimit; Name: 'TachoLimit'; ),
( ID: RunState; Name: 'RunState'; ),
( ID: TurnRatio; Name: 'TurnRatio'; ),
( ID: RegMode; Name: 'RegMode'; ),
( ID: Overloaded; Name: 'Overload'; ),
( ID: RegPValue; Name: 'RegPValue'; ),
( ID: RegIValue; Name: 'RegIValue'; ),
( ID: RegDValue; Name: 'RegDValue'; ),
( ID: BlockTachoCount; Name: 'BlockTachoCount'; ),
( ID: RotationCount; Name: 'RotationCount'; ),
( ID: OutputOptions; Name: 'OutputOptions'; ),
( ID: MaxSpeed; Name: 'MaxSpeed'; ),
( ID: MaxAcceleration; Name: 'MaxAcceleration'; )
);
const
InputFieldIDsCount = 6;
NumInputs = 4;
InputFieldIDs : array[0..InputFieldIDsCount-1] of IDRec =
(
( ID: InputType; Name: 'Type'; ),
( ID: InputMode; Name: 'InputMode'; ),
( ID: RawValue; Name: 'RawValue'; ),
( ID: NormalizedValue; Name: 'NormalizedValue'; ),
( ID: ScaledValue; Name: 'ScaledValue'; ),
( ID: InvalidData; Name: 'InvalidData'; )
);
const
IOMapFieldIDsCount = (InputFieldIDsCount*NumInputs)+((OutputFieldIDsCount-3)*NumOutputs);
IOMapFieldIDs : array[0..IOMapFieldIDsCount-1] of IDRec =
(
// input IO Map addresses
( ID: IO_BASE+$000; Name: 'InputIOType0'; ),
( ID: IO_BASE+$001; Name: 'InputIOInputMode0'; ),
( ID: IO_BASE+$002; Name: 'InputIORawValue0'; ),
( ID: IO_BASE+$003; Name: 'InputIONormalizedValue0'; ),
( ID: IO_BASE+$004; Name: 'InputIOScaledValue0'; ),
( ID: IO_BASE+$005; Name: 'InputIOInvalidData0'; ),
( ID: IO_BASE+$006; Name: 'InputIOType1'; ),
( ID: IO_BASE+$007; Name: 'InputIOInputMode1'; ),
( ID: IO_BASE+$008; Name: 'InputIORawValue1'; ),
( ID: IO_BASE+$009; Name: 'InputIONormalizedValue1'; ),
( ID: IO_BASE+$00a; Name: 'InputIOScaledValue1'; ),
( ID: IO_BASE+$00b; Name: 'InputIOInvalidData1'; ),
( ID: IO_BASE+$00c; Name: 'InputIOType2'; ),
( ID: IO_BASE+$00d; Name: 'InputIOInputMode2'; ),
( ID: IO_BASE+$00e; Name: 'InputIORawValue2'; ),
( ID: IO_BASE+$00f; Name: 'InputIONormalizedValue2'; ),
( ID: IO_BASE+$010; Name: 'InputIOScaledValue2'; ),
( ID: IO_BASE+$011; Name: 'InputIOInvalidData2'; ),
( ID: IO_BASE+$012; Name: 'InputIOType3'; ),
( ID: IO_BASE+$013; Name: 'InputIOInputMode3'; ),
( ID: IO_BASE+$014; Name: 'InputIORawValue3'; ),
( ID: IO_BASE+$015; Name: 'InputIONormalizedValue3'; ),
( ID: IO_BASE+$016; Name: 'InputIOScaledValue3'; ),
( ID: IO_BASE+$017; Name: 'InputIOInvalidData3'; ),
// output IO Map addresses
( ID: IO_BASE+$200; Name: 'OutputIOUpdateFlags0'; ),
( ID: IO_BASE+$201; Name: 'OutputIOOutputMode0'; ),
( ID: IO_BASE+$202; Name: 'OutputIOPower0'; ),
( ID: IO_BASE+$203; Name: 'OutputIOActualSpeed0'; ),
( ID: IO_BASE+$204; Name: 'OutputIOTachoCount0'; ),
( ID: IO_BASE+$205; Name: 'OutputIOTachoLimit0'; ),
( ID: IO_BASE+$206; Name: 'OutputIORunState0'; ),
( ID: IO_BASE+$207; Name: 'OutputIOTurnRatio0'; ),
( ID: IO_BASE+$208; Name: 'OutputIORegMode0'; ),
( ID: IO_BASE+$209; Name: 'OutputIOOverload0'; ),
( ID: IO_BASE+$20a; Name: 'OutputIORegPValue0'; ),
( ID: IO_BASE+$20b; Name: 'OutputIORegIValue0'; ),
( ID: IO_BASE+$20c; Name: 'OutputIORegDValue0'; ),
( ID: IO_BASE+$20d; Name: 'OutputIOBlockTachoCount0'; ),
( ID: IO_BASE+$20e; Name: 'OutputIORotationCount0'; ),
( ID: IO_BASE+$20f; Name: 'OutputIOUpdateFlags1'; ),
( ID: IO_BASE+$210; Name: 'OutputIOOutputMode1'; ),
( ID: IO_BASE+$211; Name: 'OutputIOPower1'; ),
( ID: IO_BASE+$212; Name: 'OutputIOActualSpeed1'; ),
( ID: IO_BASE+$213; Name: 'OutputIOTachoCount1'; ),
( ID: IO_BASE+$214; Name: 'OutputIOTachoLimit1'; ),
( ID: IO_BASE+$215; Name: 'OutputIORunState1'; ),
( ID: IO_BASE+$216; Name: 'OutputIOTurnRatio1'; ),
( ID: IO_BASE+$217; Name: 'OutputIORegMode1'; ),
( ID: IO_BASE+$218; Name: 'OutputIOOverload1'; ),
( ID: IO_BASE+$219; Name: 'OutputIORegPValue1'; ),
( ID: IO_BASE+$21a; Name: 'OutputIORegIValue1'; ),
( ID: IO_BASE+$21b; Name: 'OutputIORegDValue1'; ),
( ID: IO_BASE+$21c; Name: 'OutputIOBlockTachoCount1'; ),
( ID: IO_BASE+$21d; Name: 'OutputIORotationCount1'; ),
( ID: IO_BASE+$21e; Name: 'OutputIOUpdateFlags2'; ),
( ID: IO_BASE+$21f; Name: 'OutputIOOutputMode2'; ),
( ID: IO_BASE+$220; Name: 'OutputIOPower2'; ),
( ID: IO_BASE+$221; Name: 'OutputIOActualSpeed2'; ),
( ID: IO_BASE+$222; Name: 'OutputIOTachoCount2'; ),
( ID: IO_BASE+$223; Name: 'OutputIOTachoLimit2'; ),
( ID: IO_BASE+$224; Name: 'OutputIORunState2'; ),
( ID: IO_BASE+$225; Name: 'OutputIOTurnRatio2'; ),
( ID: IO_BASE+$226; Name: 'OutputIORegMode2'; ),
( ID: IO_BASE+$227; Name: 'OutputIOOverload2'; ),
( ID: IO_BASE+$228; Name: 'OutputIORegPValue2'; ),
( ID: IO_BASE+$229; Name: 'OutputIORegIValue2'; ),
( ID: IO_BASE+$22a; Name: 'OutputIORegDValue2'; ),
( ID: IO_BASE+$22b; Name: 'OutputIOBlockTachoCount2'; ),
( ID: IO_BASE+$22c; Name: 'OutputIORotationCount2'; )
);
const
SysCallMethodIDsCount1x = 48;
SysCallMethodIDs1x : array[0..SysCallMethodIDsCount1x-1] of IDRec =
(
( ID: 0; Name: 'FileOpenRead'; ),
( ID: 1; Name: 'FileOpenWrite'; ),
( ID: 2; Name: 'FileOpenAppend'; ),
( ID: 3; Name: 'FileRead'; ),
( ID: 4; Name: 'FileWrite'; ),
( ID: 5; Name: 'FileClose'; ),
( ID: 6; Name: 'FileResolveHandle'; ),
( ID: 7; Name: 'FileRename'; ),
( ID: 8; Name: 'FileDelete'; ),
( ID: 9; Name: 'SoundPlayFile'; ),
( ID: 10; Name: 'SoundPlayTone'; ),
( ID: 11; Name: 'SoundGetState'; ),
( ID: 12; Name: 'SoundSetState'; ),
( ID: 13; Name: 'DrawText'; ),
( ID: 14; Name: 'DrawPoint'; ),
( ID: 15; Name: 'DrawLine'; ),
( ID: 16; Name: 'DrawCircle'; ),
( ID: 17; Name: 'DrawRect'; ),
( ID: 18; Name: 'DrawGraphic'; ),
( ID: 19; Name: 'SetScreenMode'; ),
( ID: 20; Name: 'ReadButton'; ),
( ID: 21; Name: 'CommLSWrite'; ),
( ID: 22; Name: 'CommLSRead'; ),
( ID: 23; Name: 'CommLSCheckStatus'; ),
( ID: 24; Name: 'RandomNumber'; ),
( ID: 25; Name: 'GetStartTick'; ),
( ID: 26; Name: 'MessageWrite'; ),
( ID: 27; Name: 'MessageRead'; ),
( ID: 28; Name: 'CommBTCheckStatus'; ),
( ID: 29; Name: 'CommBTWrite'; ),
( ID: 30; Name: 'CommBTRead'; ),
( ID: 31; Name: 'KeepAlive'; ),
( ID: 32; Name: 'IOMapRead'; ),
( ID: 33; Name: 'IOMapWrite'; ),
( ID: 34; Name: 'IOMapReadByID'; ),
( ID: 35; Name: 'IOMapWriteByID'; ),
( ID: 36; Name: 'DisplayExecuteFunction'; ),
( ID: 37; Name: 'CommExecuteFunction'; ),
( ID: 38; Name: 'LoaderExecuteFunction'; ),
( ID: 39; Name: 'FileFindFirst'; ),
( ID: 40; Name: 'FileFindNext'; ),
( ID: 41; Name: 'FileOpenWriteLinear'; ),
( ID: 42; Name: 'FileOpenWriteNonLinear'; ),
( ID: 43; Name: 'FileOpenReadLinear'; ),
( ID: 44; Name: 'CommHSControl'; ),
( ID: 45; Name: 'CommHSCheckStatus'; ),
( ID: 46; Name: 'CommHSWrite'; ),
( ID: 47; Name: 'CommHSRead'; )
);
const
SysCallMethodIDsCount2x = 100;
SysCallMethodIDs2x : array[0..SysCallMethodIDsCount2x-1] of IDRec =
(
( ID: 0; Name: 'FileOpenRead'; ),
( ID: 1; Name: 'FileOpenWrite'; ),
( ID: 2; Name: 'FileOpenAppend'; ),
( ID: 3; Name: 'FileRead'; ),
( ID: 4; Name: 'FileWrite'; ),
( ID: 5; Name: 'FileClose'; ),
( ID: 6; Name: 'FileResolveHandle'; ),
( ID: 7; Name: 'FileRename'; ),
( ID: 8; Name: 'FileDelete'; ),
( ID: 9; Name: 'SoundPlayFile'; ),
( ID: 10; Name: 'SoundPlayTone'; ),
( ID: 11; Name: 'SoundGetState'; ),
( ID: 12; Name: 'SoundSetState'; ),
( ID: 13; Name: 'DrawText'; ),
( ID: 14; Name: 'DrawPoint'; ),
( ID: 15; Name: 'DrawLine'; ),
( ID: 16; Name: 'DrawCircle'; ),
( ID: 17; Name: 'DrawRect'; ),
( ID: 18; Name: 'DrawGraphic'; ),
( ID: 19; Name: 'SetScreenMode'; ),
( ID: 20; Name: 'ReadButton'; ),
( ID: 21; Name: 'CommLSWrite'; ),
( ID: 22; Name: 'CommLSRead'; ),
( ID: 23; Name: 'CommLSCheckStatus'; ),
( ID: 24; Name: 'RandomNumber'; ),
( ID: 25; Name: 'GetStartTick'; ),
( ID: 26; Name: 'MessageWrite'; ),
( ID: 27; Name: 'MessageRead'; ),
( ID: 28; Name: 'CommBTCheckStatus'; ),
( ID: 29; Name: 'CommBTWrite'; ),
( ID: 30; Name: 'CommBTRead'; ),
( ID: 31; Name: 'KeepAlive'; ),
( ID: 32; Name: 'IOMapRead'; ),
( ID: 33; Name: 'IOMapWrite'; ),
( ID: 34; Name: 'ColorSensorRead'; ),
( ID: 35; Name: 'CommBTOnOff'; ),
( ID: 36; Name: 'CommBTConnection'; ),
( ID: 37; Name: 'CommHSWrite'; ),
( ID: 38; Name: 'CommHSRead'; ),
( ID: 39; Name: 'CommHSCheckStatus'; ),
( ID: 40; Name: 'ReadSemData'; ),
( ID: 41; Name: 'WriteSemData'; ),
( ID: 42; Name: 'ComputeCalibValue'; ),
( ID: 43; Name: 'UpdateCalibCacheInfo'; ),
( ID: 44; Name: 'DatalogWrite'; ),
( ID: 45; Name: 'DatalogGetTimes'; ),
( ID: 46; Name: 'SetSleepTimeoutVal'; ),
( ID: 47; Name: 'ListFiles'; ),
( ID: 48; Name: 'syscall48'; ),
( ID: 49; Name: 'syscall49'; ),
( ID: 50; Name: 'syscall50'; ),
( ID: 51; Name: 'syscall51'; ),
( ID: 52; Name: 'syscall52'; ),
( ID: 53; Name: 'syscall53'; ),
( ID: 54; Name: 'syscall54'; ),
( ID: 55; Name: 'syscall55'; ),
( ID: 56; Name: 'syscall56'; ),
( ID: 57; Name: 'syscall57'; ),
( ID: 58; Name: 'syscall58'; ),
( ID: 59; Name: 'syscall59'; ),
( ID: 60; Name: 'syscall60'; ),
( ID: 61; Name: 'syscall61'; ),
( ID: 62; Name: 'syscall62'; ),
( ID: 63; Name: 'syscall63'; ),
( ID: 64; Name: 'syscall64'; ),
( ID: 65; Name: 'syscall65'; ),
( ID: 66; Name: 'syscall66'; ),
( ID: 67; Name: 'syscall67'; ),
( ID: 68; Name: 'syscall68'; ),
( ID: 69; Name: 'syscall69'; ),
( ID: 70; Name: 'syscall70'; ),
( ID: 71; Name: 'syscall71'; ),
( ID: 72; Name: 'syscall72'; ),
( ID: 73; Name: 'syscall73'; ),
( ID: 74; Name: 'syscall74'; ),
( ID: 75; Name: 'syscall75'; ),
( ID: 76; Name: 'syscall76'; ),
( ID: 77; Name: 'syscall77'; ),
( ID: 78; Name: 'IOMapReadByID'; ),
( ID: 79; Name: 'IOMapWriteByID'; ),
( ID: 80; Name: 'DisplayExecuteFunction'; ),
( ID: 81; Name: 'CommExecuteFunction'; ),
( ID: 82; Name: 'LoaderExecuteFunction'; ),
( ID: 83; Name: 'FileFindFirst'; ),
( ID: 84; Name: 'FileFindNext'; ),
( ID: 85; Name: 'FileOpenWriteLinear'; ),
( ID: 86; Name: 'FileOpenWriteNonLinear'; ),
( ID: 87; Name: 'FileOpenReadLinear'; ),
( ID: 88; Name: 'CommHSControl'; ),
( ID: 89; Name: 'CommLSWriteEx'; ),
( ID: 90; Name: 'FileSeek'; ),
( ID: 91; Name: 'FileResize'; ),
( ID: 92; Name: 'DrawGraphicArray'; ),
( ID: 93; Name: 'DrawPolygon'; ),
( ID: 94; Name: 'DrawEllipse'; ),
( ID: 95; Name: 'DrawFont'; ),
( ID: 96; Name: 'MemoryManager'; ),
( ID: 97; Name: 'ReadLastResponse'; ),
( ID: 98; Name: 'FileTell'; ),
( ID: 99; Name: 'syscall99'; )
);
const
MSCount = 45;
MSRecords : array[0..MSCount-1] of IDRec =
(
( ID: 1; Name: 'MS_1'; ),
( ID: 2; Name: 'MS_2'; ),
( ID: 3; Name: 'MS_3'; ),
( ID: 4; Name: 'MS_4'; ),
( ID: 5; Name: 'MS_5'; ),
( ID: 6; Name: 'MS_6'; ),
( ID: 7; Name: 'MS_7'; ),
( ID: 8; Name: 'MS_8'; ),
( ID: 9; Name: 'MS_9'; ),
( ID: 10; Name: 'MS_10'; ),
( ID: 20; Name: 'MS_20'; ),
( ID: 30; Name: 'MS_30'; ),
( ID: 40; Name: 'MS_40'; ),
( ID: 50; Name: 'MS_50'; ),
( ID: 60; Name: 'MS_60'; ),
( ID: 70; Name: 'MS_70'; ),
( ID: 80; Name: 'MS_80'; ),
( ID: 90; Name: 'MS_90'; ),
( ID: 100; Name: 'MS_100'; ),
( ID: 150; Name: 'MS_150'; ),
( ID: 200; Name: 'MS_200'; ),
( ID: 250; Name: 'MS_250'; ),
( ID: 300; Name: 'MS_300'; ),
( ID: 350; Name: 'MS_350'; ),
( ID: 400; Name: 'MS_400'; ),
( ID: 450; Name: 'MS_450'; ),
( ID: 500; Name: 'MS_500'; ),
( ID: 600; Name: 'MS_600'; ),
( ID: 700; Name: 'MS_700'; ),
( ID: 800; Name: 'MS_800'; ),
( ID: 900; Name: 'MS_900'; ),
( ID: 1000; Name: 'SEC_1'; ),
( ID: 2000; Name: 'SEC_2'; ),
( ID: 3000; Name: 'SEC_3'; ),
( ID: 4000; Name: 'SEC_4'; ),
( ID: 5000; Name: 'SEC_5'; ),
( ID: 6000; Name: 'SEC_6'; ),
( ID: 7000; Name: 'SEC_7'; ),
( ID: 8000; Name: 'SEC_8'; ),
( ID: 9000; Name: 'SEC_9'; ),
( ID: 10000; Name: 'SEC_10'; ),
( ID: 15000; Name: 'SEC_15'; ),
( ID: 20000; Name: 'SEC_20'; ),
( ID: 30000; Name: 'SEC_30'; ),
( ID: 60000; Name: 'MIN_1'; )
);
const
ToneCount = 60;
ToneRecords : array[0..ToneCount-1] of IDRec =
(
( ID: 131; Name: 'TONE_C3'; ),
( ID: 139; Name: 'TONE_CS3'; ),
( ID: 147; Name: 'TONE_D3'; ),
( ID: 156; Name: 'TONE_DS3'; ),
( ID: 165; Name: 'TONE_E3'; ),
( ID: 175; Name: 'TONE_F3'; ),
( ID: 185; Name: 'TONE_FS3'; ),
( ID: 196; Name: 'TONE_G3'; ),
( ID: 208; Name: 'TONE_GS3'; ),
( ID: 220; Name: 'TONE_A3'; ),
( ID: 233; Name: 'TONE_AS3'; ),
( ID: 247; Name: 'TONE_B3'; ),
( ID: 262; Name: 'TONE_C4'; ),
( ID: 277; Name: 'TONE_CS4'; ),
( ID: 294; Name: 'TONE_D4'; ),
( ID: 311; Name: 'TONE_DS4'; ),
( ID: 330; Name: 'TONE_E4'; ),
( ID: 349; Name: 'TONE_F4'; ),
( ID: 370; Name: 'TONE_FS4'; ),
( ID: 392; Name: 'TONE_G4'; ),
( ID: 415; Name: 'TONE_GS4'; ),
( ID: 440; Name: 'TONE_A4'; ),
( ID: 466; Name: 'TONE_AS4'; ),
( ID: 494; Name: 'TONE_B4'; ),
( ID: 523; Name: 'TONE_C5'; ),
( ID: 554; Name: 'TONE_CS5'; ),
( ID: 587; Name: 'TONE_D5'; ),
( ID: 622; Name: 'TONE_DS5'; ),
( ID: 659; Name: 'TONE_E5'; ),
( ID: 698; Name: 'TONE_F5'; ),
( ID: 740; Name: 'TONE_FS5'; ),
( ID: 784; Name: 'TONE_G5'; ),
( ID: 831; Name: 'TONE_GS5'; ),
( ID: 880; Name: 'TONE_A5'; ),
( ID: 932; Name: 'TONE_AS5'; ),
( ID: 988; Name: 'TONE_B5'; ),
( ID: 1047; Name: 'TONE_C6'; ),
( ID: 1109; Name: 'TONE_CS6'; ),
( ID: 1175; Name: 'TONE_D6'; ),
( ID: 1245; Name: 'TONE_DS6'; ),
( ID: 1319; Name: 'TONE_E6'; ),
( ID: 1397; Name: 'TONE_F6'; ),
( ID: 1480; Name: 'TONE_FS6'; ),
( ID: 1568; Name: 'TONE_G6'; ),
( ID: 1661; Name: 'TONE_GS6'; ),
( ID: 1760; Name: 'TONE_A6'; ),
( ID: 1865; Name: 'TONE_AS6'; ),
( ID: 1976; Name: 'TONE_B6'; ),
( ID: 2093; Name: 'TONE_C7'; ),
( ID: 2217; Name: 'TONE_CS7'; ),
( ID: 2349; Name: 'TONE_D7'; ),
( ID: 2489; Name: 'TONE_DS7'; ),
( ID: 2637; Name: 'TONE_E7'; ),
( ID: 2794; Name: 'TONE_F7'; ),
( ID: 2960; Name: 'TONE_FS7'; ),
( ID: 3136; Name: 'TONE_G7'; ),
( ID: 3322; Name: 'TONE_GS7'; ),
( ID: 3520; Name: 'TONE_A7'; ),
( ID: 3729; Name: 'TONE_AS7'; ),
( ID: 3951; Name: 'TONE_B7'; )
);
(*
const
IOMapOffsetCount = 244;
IOMapOffsetRecords : array[0..IOMapOffsetCount-1] of IDRec =
(
( ID: CommandOffsetFormatString; Name: 'CommandOffsetFormatString'; ),
( ID: CommandOffsetPRCHandler; Name: 'CommandOffsetPRCHandler'; ),
( ID: CommandOffsetTick; Name: 'CommandOffsetTick'; ),
( ID: CommandOffsetOffsetDS; Name: 'CommandOffsetOffsetDS'; ),
( ID: CommandOffsetOffsetDVA; Name: 'CommandOffsetOffsetDVA'; ),
( ID: CommandOffsetProgStatus; Name: 'CommandOffsetProgStatus'; ),
( ID: CommandOffsetAwake; Name: 'CommandOffsetAwake'; ),
( ID: CommandOffsetActivateFlag; Name: 'CommandOffsetActivateFlag'; ),
( ID: CommandOffsetDeactivateFlag; Name: 'CommandOffsetDeactivateFlag'; ),
( ID: CommandOffsetFileName; Name: 'CommandOffsetFileName'; ),
( ID: CommandOffsetMemoryPool; Name: 'CommandOffsetMemoryPool'; ),
( ID: IOCtrlOffsetPowerOn; Name: 'IOCtrlOffsetPowerOn'; ),
( ID: LoaderOffsetPFunc; Name: 'LoaderOffsetPFunc'; ),
( ID: LoaderOffsetFreeUserFlash; Name: 'LoaderOffsetFreeUserFlash'; ),
( ID: SoundOffsetFreq; Name: 'SoundOffsetFreq'; ),
( ID: SoundOffsetDuration; Name: 'SoundOffsetDuration'; ),
( ID: SoundOffsetSampleRate; Name: 'SoundOffsetSampleRate'; ),
( ID: SoundOffsetSoundFilename; Name: 'SoundOffsetSoundFilename'; ),
( ID: SoundOffsetFlags; Name: 'SoundOffsetFlags'; ),
( ID: SoundOffsetState; Name: 'SoundOffsetState'; ),
( ID: SoundOffsetMode; Name: 'SoundOffsetMode'; ),
( ID: SoundOffsetVolume; Name: 'SoundOffsetVolume'; ),
( ID: ButtonOffsetPressedCnt0; Name: 'ButtonOffsetPressedCnt0'; ),
( ID: ButtonOffsetLongPressCnt0; Name: 'ButtonOffsetLongPressCnt0'; ),
( ID: ButtonOffsetShortRelCnt0; Name: 'ButtonOffsetShortRelCnt0'; ),
( ID: ButtonOffsetLongRelCnt0; Name: 'ButtonOffsetLongRelCnt0'; ),
( ID: ButtonOffsetRelCnt0; Name: 'ButtonOffsetRelCnt0'; ),
( ID: ButtonOffsetSpareOne0; Name: 'ButtonOffsetSpareOne0'; ),
( ID: ButtonOffsetSpareTwo0; Name: 'ButtonOffsetSpareTwo0'; ),
( ID: ButtonOffsetSpareThree0; Name: 'ButtonOffsetSpareThree0'; ),
( ID: ButtonOffsetPressedCnt1; Name: 'ButtonOffsetPressedCnt1'; ),
( ID: ButtonOffsetLongPressCnt1; Name: 'ButtonOffsetLongPressCnt1'; ),
( ID: ButtonOffsetShortRelCnt1; Name: 'ButtonOffsetShortRelCnt1'; ),
( ID: ButtonOffsetLongRelCnt1; Name: 'ButtonOffsetLongRelCnt1'; ),
( ID: ButtonOffsetRelCnt1; Name: 'ButtonOffsetRelCnt1'; ),
( ID: ButtonOffsetSpareOne1; Name: 'ButtonOffsetSpareOne1'; ),
( ID: ButtonOffsetSpareTwo1; Name: 'ButtonOffsetSpareTwo1'; ),
( ID: ButtonOffsetSpareThree1; Name: 'ButtonOffsetSpareThree1'; ),
( ID: ButtonOffsetPressedCnt2; Name: 'ButtonOffsetPressedCnt2'; ),
( ID: ButtonOffsetLongPressCnt2; Name: 'ButtonOffsetLongPressCnt2'; ),
( ID: ButtonOffsetShortRelCnt2; Name: 'ButtonOffsetShortRelCnt2'; ),
( ID: ButtonOffsetLongRelCnt2; Name: 'ButtonOffsetLongRelCnt2'; ),
( ID: ButtonOffsetRelCnt2; Name: 'ButtonOffsetRelCnt2'; ),
( ID: ButtonOffsetSpareOne2; Name: 'ButtonOffsetSpareOne2'; ),
( ID: ButtonOffsetSpareTwo2; Name: 'ButtonOffsetSpareTwo2'; ),
( ID: ButtonOffsetSpareThree2; Name: 'ButtonOffsetSpareThree2'; ),
( ID: ButtonOffsetPressedCnt3; Name: 'ButtonOffsetPressedCnt3'; ),
( ID: ButtonOffsetLongPressCnt3; Name: 'ButtonOffsetLongPressCnt3'; ),
( ID: ButtonOffsetShortRelCnt3; Name: 'ButtonOffsetShortRelCnt3'; ),
( ID: ButtonOffsetLongRelCnt3; Name: 'ButtonOffsetLongRelCnt3'; ),
( ID: ButtonOffsetRelCnt3; Name: 'ButtonOffsetRelCnt3'; ),
( ID: ButtonOffsetSpareOne3; Name: 'ButtonOffsetSpareOne3'; ),
( ID: ButtonOffsetSpareTwo3; Name: 'ButtonOffsetSpareTwo3'; ),
( ID: ButtonOffsetSpareThree3; Name: 'ButtonOffsetSpareThree3'; ),
( ID: ButtonOffsetState0; Name: 'ButtonOffsetState0'; ),
( ID: ButtonOffsetState1; Name: 'ButtonOffsetState1'; ),
( ID: ButtonOffsetState2; Name: 'ButtonOffsetState2'; ),
( ID: ButtonOffsetState3; Name: 'ButtonOffsetState3'; ),
( ID: UIOffsetPMenu; Name: 'UIOffsetPMenu'; ),
( ID: UIOffsetBatteryVoltage; Name: 'UIOffsetBatteryVoltage'; ),
( ID: UIOffsetLMSfilename; Name: 'UIOffsetLMSfilename'; ),
( ID: UIOffsetFlags; Name: 'UIOffsetFlags'; ),
( ID: UIOffsetState; Name: 'UIOffsetState'; ),
( ID: UIOffsetButton; Name: 'UIOffsetButton'; ),
( ID: UIOffsetRunState; Name: 'UIOffsetRunState'; ),
( ID: UIOffsetBatteryState; Name: 'UIOffsetBatteryState'; ),
( ID: UIOffsetBluetoothState; Name: 'UIOffsetBluetoothState'; ),
( ID: UIOffsetUsbState; Name: 'UIOffsetUsbState'; ),
( ID: UIOffsetSleepTimeout; Name: 'UIOffsetSleepTimeout'; ),
( ID: UIOffsetSleepTimer; Name: 'UIOffsetSleepTimer'; ),
( ID: UIOffsetRechargeable; Name: 'UIOffsetRechargeable'; ),
( ID: UIOffsetVolume; Name: 'UIOffsetVolume'; ),
( ID: UIOffsetError; Name: 'UIOffsetError'; ),
( ID: UIOffsetOBPPointer; Name: 'UIOffsetOBPPointer'; ),
( ID: UIOffsetForceOff; Name: 'UIOffsetForceOff'; ),
( ID: InputOffsetCustomZeroOffset0; Name: 'InputOffsetCustomZeroOffset0'; ),
( ID: InputOffsetADRaw0; Name: 'InputOffsetADRaw0'; ),
( ID: InputOffsetSensorRaw0; Name: 'InputOffsetSensorRaw0'; ),
( ID: InputOffsetSensorValue0; Name: 'InputOffsetSensorValue0'; ),
( ID: InputOffsetSensorType0; Name: 'InputOffsetSensorType0'; ),
( ID: InputOffsetSensorMode0; Name: 'InputOffsetSensorMode0'; ),
( ID: InputOffsetSensorBoolean0; Name: 'InputOffsetSensorBoolean0'; ),
( ID: InputOffsetDigiPinsDir0; Name: 'InputOffsetDigiPinsDir0'; ),
( ID: InputOffsetDigiPinsIn0; Name: 'InputOffsetDigiPinsIn0'; ),
( ID: InputOffsetDigiPinsOut0; Name: 'InputOffsetDigiPinsOut0'; ),
( ID: InputOffsetCustomPctFullScale0; Name: 'InputOffsetCustomPctFullScale0'; ),
( ID: InputOffsetCustomActiveStatus0; Name: 'InputOffsetCustomActiveStatus0'; ),
( ID: InputOffsetInvalidData0; Name: 'InputOffsetInvalidData0'; ),
( ID: InputOffsetSpare10; Name: 'InputOffsetSpare10'; ),
( ID: InputOffsetSpare20; Name: 'InputOffsetSpare20'; ),
( ID: InputOffsetSpare30; Name: 'InputOffsetSpare30'; ),
( ID: InputOffsetCustomZeroOffset1; Name: 'InputOffsetCustomZeroOffset1'; ),
( ID: InputOffsetADRaw1; Name: 'InputOffsetADRaw1'; ),
( ID: InputOffsetSensorRaw1; Name: 'InputOffsetSensorRaw1'; ),
( ID: InputOffsetSensorValue1; Name: 'InputOffsetSensorValue1'; ),
( ID: InputOffsetSensorType1; Name: 'InputOffsetSensorType1'; ),
( ID: InputOffsetSensorMode1; Name: 'InputOffsetSensorMode1'; ),
( ID: InputOffsetSensorBoolean1; Name: 'InputOffsetSensorBoolean1'; ),
( ID: InputOffsetDigiPinsDir1; Name: 'InputOffsetDigiPinsDir1'; ),
( ID: InputOffsetDigiPinsIn1; Name: 'InputOffsetDigiPinsIn1'; ),
( ID: InputOffsetDigiPinsOut1; Name: 'InputOffsetDigiPinsOut1'; ),
( ID: InputOffsetCustomPctFullScale1; Name: 'InputOffsetCustomPctFullScale1'; ),
( ID: InputOffsetCustomActiveStatus1; Name: 'InputOffsetCustomActiveStatus1'; ),
( ID: InputOffsetInvalidData1; Name: 'InputOffsetInvalidData1'; ),
( ID: InputOffsetSpare11; Name: 'InputOffsetSpare11'; ),
( ID: InputOffsetSpare21; Name: 'InputOffsetSpare21'; ),
( ID: InputOffsetSpare31; Name: 'InputOffsetSpare31'; ),
( ID: InputOffsetCustomZeroOffset2; Name: 'InputOffsetCustomZeroOffset2'; ),
( ID: InputOffsetADRaw2; Name: 'InputOffsetADRaw2'; ),
( ID: InputOffsetSensorRaw2; Name: 'InputOffsetSensorRaw2'; ),
( ID: InputOffsetSensorValue2; Name: 'InputOffsetSensorValue2'; ),
( ID: InputOffsetSensorType2; Name: 'InputOffsetSensorType2'; ),
( ID: InputOffsetSensorMode2; Name: 'InputOffsetSensorMode2'; ),
( ID: InputOffsetSensorBoolean2; Name: 'InputOffsetSensorBoolean2'; ),
( ID: InputOffsetDigiPinsDir2; Name: 'InputOffsetDigiPinsDir2'; ),
( ID: InputOffsetDigiPinsIn2; Name: 'InputOffsetDigiPinsIn2'; ),
( ID: InputOffsetDigiPinsOut2; Name: 'InputOffsetDigiPinsOut2'; ),
( ID: InputOffsetCustomPctFullScale2; Name: 'InputOffsetCustomPctFullScale2'; ),
( ID: InputOffsetCustomActiveStatus2; Name: 'InputOffsetCustomActiveStatus2'; ),
( ID: InputOffsetInvalidData2; Name: 'InputOffsetInvalidData2'; ),
( ID: InputOffsetSpare12; Name: 'InputOffsetSpare12'; ),
( ID: InputOffsetSpare22; Name: 'InputOffsetSpare22'; ),
( ID: InputOffsetSpare32; Name: 'InputOffsetSpare32'; ),
( ID: InputOffsetCustomZeroOffset3; Name: 'InputOffsetCustomZeroOffset3'; ),
( ID: InputOffsetADRaw3; Name: 'InputOffsetADRaw3'; ),
( ID: InputOffsetSensorRaw3; Name: 'InputOffsetSensorRaw3'; ),
( ID: InputOffsetSensorValue3; Name: 'InputOffsetSensorValue3'; ),
( ID: InputOffsetSensorType3; Name: 'InputOffsetSensorType3'; ),
( ID: InputOffsetSensorMode3; Name: 'InputOffsetSensorMode3'; ),
( ID: InputOffsetSensorBoolean3; Name: 'InputOffsetSensorBoolean3'; ),
( ID: InputOffsetDigiPinsDir3; Name: 'InputOffsetDigiPinsDir3'; ),
( ID: InputOffsetDigiPinsIn3; Name: 'InputOffsetDigiPinsIn3'; ),
( ID: InputOffsetDigiPinsOut3; Name: 'InputOffsetDigiPinsOut3'; ),
( ID: InputOffsetCustomPctFullScale3; Name: 'InputOffsetCustomPctFullScale3'; ),
( ID: InputOffsetCustomActiveStatus3; Name: 'InputOffsetCustomActiveStatus3'; ),
( ID: InputOffsetInvalidData3; Name: 'InputOffsetInvalidData3'; ),
( ID: InputOffsetSpare13; Name: 'InputOffsetSpare13'; ),
( ID: InputOffsetSpare23; Name: 'InputOffsetSpare23'; ),
( ID: InputOffsetSpare33; Name: 'InputOffsetSpare33'; ),
( ID: OutputOffsetTachoCnt0; Name: 'OutputOffsetTachoCnt0'; ),
( ID: OutputOffsetBlockTachoCount0; Name: 'OutputOffsetBlockTachoCount0'; ),
( ID: OutputOffsetRotationCount0; Name: 'OutputOffsetRotationCount0'; ),
( ID: OutputOffsetTachoLimit0; Name: 'OutputOffsetTachoLimit0'; ),
( ID: OutputOffsetMotorRPM0; Name: 'OutputOffsetMotorRPM0'; ),
( ID: OutputOffsetFlags0; Name: 'OutputOffsetFlags0'; ),
( ID: OutputOffsetMode0; Name: 'OutputOffsetMode0'; ),
( ID: OutputOffsetSpeed0; Name: 'OutputOffsetSpeed0'; ),
( ID: OutputOffsetActualSpeed0; Name: 'OutputOffsetActualSpeed0'; ),
( ID: OutputOffsetRegPParameter0; Name: 'OutputOffsetRegPParameter0'; ),
( ID: OutputOffsetRegIParameter0; Name: 'OutputOffsetRegIParameter0'; ),
( ID: OutputOffsetRegDParameter0; Name: 'OutputOffsetRegDParameter0'; ),
( ID: OutputOffsetRunState0; Name: 'OutputOffsetRunState0'; ),
( ID: OutputOffsetRegMode0; Name: 'OutputOffsetRegMode0'; ),
( ID: OutputOffsetOverloaded0; Name: 'OutputOffsetOverloaded0'; ),
( ID: OutputOffsetSyncTurnParameter0; Name: 'OutputOffsetSyncTurnParameter0'; ),
( ID: OutputOffsetSpareOne0; Name: 'OutputOffsetSpareOne0'; ),
( ID: OutputOffsetSpareTwo0; Name: 'OutputOffsetSpareTwo0'; ),
( ID: OutputOffsetSpareThree0; Name: 'OutputOffsetSpareThree0'; ),
( ID: OutputOffsetTachoCnt1; Name: 'OutputOffsetTachoCnt1'; ),
( ID: OutputOffsetBlockTachoCount1; Name: 'OutputOffsetBlockTachoCount1'; ),
( ID: OutputOffsetRotationCount1; Name: 'OutputOffsetRotationCount1'; ),
( ID: OutputOffsetTachoLimit1; Name: 'OutputOffsetTachoLimit1'; ),
( ID: OutputOffsetMotorRPM1; Name: 'OutputOffsetMotorRPM1'; ),
( ID: OutputOffsetFlags1; Name: 'OutputOffsetFlags1'; ),
( ID: OutputOffsetMode1; Name: 'OutputOffsetMode1'; ),
( ID: OutputOffsetSpeed1; Name: 'OutputOffsetSpeed1'; ),
( ID: OutputOffsetActualSpeed1; Name: 'OutputOffsetActualSpeed1'; ),
( ID: OutputOffsetRegPParameter1; Name: 'OutputOffsetRegPParameter1'; ),
( ID: OutputOffsetRegIParameter1; Name: 'OutputOffsetRegIParameter1'; ),
( ID: OutputOffsetRegDParameter1; Name: 'OutputOffsetRegDParameter1'; ),
( ID: OutputOffsetRunState1; Name: 'OutputOffsetRunState1'; ),
( ID: OutputOffsetRegMode1; Name: 'OutputOffsetRegMode1'; ),
( ID: OutputOffsetOverloaded1; Name: 'OutputOffsetOverloaded1'; ),
( ID: OutputOffsetSyncTurnParameter1; Name: 'OutputOffsetSyncTurnParameter1'; ),
( ID: OutputOffsetSpareOne1; Name: 'OutputOffsetSpareOne1'; ),
( ID: OutputOffsetSpareTwo1; Name: 'OutputOffsetSpareTwo1'; ),
( ID: OutputOffsetSpareThree1; Name: 'OutputOffsetSpareThree1'; ),
( ID: OutputOffsetTachoCnt2; Name: 'OutputOffsetTachoCnt2'; ),
( ID: OutputOffsetBlockTachoCount2; Name: 'OutputOffsetBlockTachoCount2'; ),
( ID: OutputOffsetRotationCount2; Name: 'OutputOffsetRotationCount2'; ),
( ID: OutputOffsetTachoLimit2; Name: 'OutputOffsetTachoLimit2'; ),
( ID: OutputOffsetMotorRPM2; Name: 'OutputOffsetMotorRPM2'; ),
( ID: OutputOffsetFlags2; Name: 'OutputOffsetFlags2'; ),
( ID: OutputOffsetMode2; Name: 'OutputOffsetMode2'; ),
( ID: OutputOffsetSpeed2; Name: 'OutputOffsetSpeed2'; ),
( ID: OutputOffsetActualSpeed2; Name: 'OutputOffsetActualSpeed2'; ),
( ID: OutputOffsetRegPParameter2; Name: 'OutputOffsetRegPParameter2'; ),
( ID: OutputOffsetRegIParameter2; Name: 'OutputOffsetRegIParameter2'; ),
( ID: OutputOffsetRegDParameter2; Name: 'OutputOffsetRegDParameter2'; ),
( ID: OutputOffsetRunState2; Name: 'OutputOffsetRunState2'; ),
( ID: OutputOffsetRegMode2; Name: 'OutputOffsetRegMode2'; ),
( ID: OutputOffsetOverloaded2; Name: 'OutputOffsetOverloaded2'; ),
( ID: OutputOffsetSyncTurnParameter2; Name: 'OutputOffsetSyncTurnParameter2'; ),
( ID: OutputOffsetSpareOne2; Name: 'OutputOffsetSpareOne2'; ),
( ID: OutputOffsetSpareTwo2; Name: 'OutputOffsetSpareTwo2'; ),
( ID: OutputOffsetSpareThree2; Name: 'OutputOffsetSpareThree2'; ),
( ID: OutputOffsetPwnFreq; Name: 'OutputOffsetPwnFreq'; ),
( ID: LowSpeedOffsetInBufBuf0; Name: 'LowSpeedOffsetInBufBuf0'; ),
( ID: LowSpeedOffsetInBufInPtr0; Name: 'LowSpeedOffsetInBufInPtr0'; ),
( ID: LowSpeedOffsetInBufOutPtr0; Name: 'LowSpeedOffsetInBufOutPtr0'; ),
( ID: LowSpeedOffsetInBufBytesToRx0; Name: 'LowSpeedOffsetInBufBytesToRx0'; ),
( ID: LowSpeedOffsetInBufBuf1; Name: 'LowSpeedOffsetInBufBuf1'; ),
( ID: LowSpeedOffsetInBufInPtr1; Name: 'LowSpeedOffsetInBufInPtr1'; ),
( ID: LowSpeedOffsetInBufOutPtr1; Name: 'LowSpeedOffsetInBufOutPtr1'; ),
( ID: LowSpeedOffsetInBufBytesToRx1; Name: 'LowSpeedOffsetInBufBytesToRx1'; ),
( ID: LowSpeedOffsetInBufBuf2; Name: 'LowSpeedOffsetInBufBuf2'; ),
( ID: LowSpeedOffsetInBufInPtr2; Name: 'LowSpeedOffsetInBufInPtr2'; ),
( ID: LowSpeedOffsetInBufOutPtr2; Name: 'LowSpeedOffsetInBufOutPtr2'; ),
( ID: LowSpeedOffsetInBufBytesToRx2; Name: 'LowSpeedOffsetInBufBytesToRx2'; ),
( ID: LowSpeedOffsetInBufBuf3; Name: 'LowSpeedOffsetInBufBuf3'; ),
( ID: LowSpeedOffsetInBufInPtr3; Name: 'LowSpeedOffsetInBufInPtr3'; ),
( ID: LowSpeedOffsetInBufOutPtr3; Name: 'LowSpeedOffsetInBufOutPtr3'; ),
( ID: LowSpeedOffsetInBufBytesToRx3; Name: 'LowSpeedOffsetInBufBytesToRx3'; ),
( ID: LowSpeedOffsetOutBufBuf0; Name: 'LowSpeedOffsetOutBufBuf0'; ),
( ID: LowSpeedOffsetOutBufInPtr0; Name: 'LowSpeedOffsetOutBufInPtr0'; ),
( ID: LowSpeedOffsetOutBufOutPtr0; Name: 'LowSpeedOffsetOutBufOutPtr0'; ),
( ID: LowSpeedOffsetOutBufBytesToRx0; Name: 'LowSpeedOffsetOutBufBytesToRx0'; ),
( ID: LowSpeedOffsetOutBufBuf1; Name: 'LowSpeedOffsetOutBufBuf1'; ),
( ID: LowSpeedOffsetOutBufInPtr1; Name: 'LowSpeedOffsetOutBufInPtr1'; ),
( ID: LowSpeedOffsetOutBufOutPtr1; Name: 'LowSpeedOffsetOutBufOutPtr1'; ),
( ID: LowSpeedOffsetOutBufBytesToRx1; Name: 'LowSpeedOffsetOutBufBytesToRx1'; ),
( ID: LowSpeedOffsetOutBufBuf2; Name: 'LowSpeedOffsetOutBufBuf2'; ),
( ID: LowSpeedOffsetOutBufInPtr2; Name: 'LowSpeedOffsetOutBufInPtr2'; ),
( ID: LowSpeedOffsetOutBufOutPtr2; Name: 'LowSpeedOffsetOutBufOutPtr2'; ),
( ID: LowSpeedOffsetOutBufBytesToRx2; Name: 'LowSpeedOffsetOutBufBytesToRx2'; ),
( ID: LowSpeedOffsetOutBufBuf3; Name: 'LowSpeedOffsetOutBufBuf3'; ),
( ID: LowSpeedOffsetOutBufInPtr3; Name: 'LowSpeedOffsetOutBufInPtr3'; ),
( ID: LowSpeedOffsetOutBufOutPtr3; Name: 'LowSpeedOffsetOutBufOutPtr3'; ),
( ID: LowSpeedOffsetOutBufBytesToRx3; Name: 'LowSpeedOffsetOutBufBytesToRx3'; ),
( ID: LowSpeedOffsetMode0; Name: 'LowSpeedOffsetMode0'; ),
( ID: LowSpeedOffsetMode1; Name: 'LowSpeedOffsetMode1'; ),
( ID: LowSpeedOffsetMode2; Name: 'LowSpeedOffsetMode2'; ),
( ID: LowSpeedOffsetMode3; Name: 'LowSpeedOffsetMode3'; ),
( ID: LowSpeedOffsetChannelState0; Name: 'LowSpeedOffsetChannelState0'; ),
( ID: LowSpeedOffsetChannelState1; Name: 'LowSpeedOffsetChannelState1'; ),
( ID: LowSpeedOffsetChannelState2; Name: 'LowSpeedOffsetChannelState2'; ),
( ID: LowSpeedOffsetChannelState3; Name: 'LowSpeedOffsetChannelState3'; ),
( ID: LowSpeedOffsetErrorType0; Name: 'LowSpeedOffsetErrorType0'; ),
( ID: LowSpeedOffsetErrorType1; Name: 'LowSpeedOffsetErrorType1'; ),
( ID: LowSpeedOffsetErrorType2; Name: 'LowSpeedOffsetErrorType2'; ),
( ID: LowSpeedOffsetErrorType3; Name: 'LowSpeedOffsetErrorType3'; ),
( ID: LowSpeedOffsetState; Name: 'LowSpeedOffsetState'; ),
( ID: LowSpeedOffsetSpeed; Name: 'LowSpeedOffsetSpeed'; ),
( ID: LowSpeedOffsetSpare1; Name: 'LowSpeedOffsetSpare1'; )
);
*)
// miscellaneous IOMap-related constants
const
INPUT_DIGI0 = $1;
INPUT_DIGI1 = $2;
INPUT_CUSTOMINACTIVE = $00;
INPUT_CUSTOM9V = $01;
INPUT_CUSTOMACTIVE = $02;
INPUT_INVALID_DATA = $01;
BTN1 = $0;
BTN2 = $1;
BTN3 = $2;
BTN4 = $3;
NO_OF_BTNS = $4;
BTNSTATE_PRESSED_EV = $01;
BTNSTATE_SHORT_RELEASED_EV = $02;
BTNSTATE_LONG_PRESSED_EV = $04;
BTNSTATE_LONG_RELEASED_EV = $08;
BTNSTATE_PRESSED_STATE = $80;
SOUND_FLAGS_UPDATE = $01;
SOUND_FLAGS_RUNNING = $02;
SOUND_STATE_IDLE = $00;
SOUND_STATE_BUSY = $02;
SOUND_STATE_FREQ = $03;
SOUND_STATE_STOP = $04;
SOUND_MODE_ONCE = $00;
SOUND_MODE_LOOP = $01;
SOUND_MODE_TONE = $02;
UI_FLAGS_UPDATE = $01;
UI_FLAGS_DISABLE_LEFT_RIGHT_ENTER = $02;
UI_FLAGS_DISABLE_EXIT = $04;
UI_FLAGS_REDRAW_STATUS = $08;
UI_FLAGS_RESET_SLEEP_TIMER = $10;
UI_FLAGS_EXECUTE_LMS_FILE = $20;
UI_FLAGS_BUSY = $40;
UI_FLAGS_ENABLE_STATUS_UPDATE = $80;
UI_STATE_INIT_DISPLAY = $0;
UI_STATE_INIT_LOW_BATTERY = $1;
UI_STATE_INIT_INTRO = $2;
UI_STATE_INIT_WAIT = $3;
UI_STATE_INIT_MENU = $4;
UI_STATE_NEXT_MENU = $5;
UI_STATE_DRAW_MENU = $6;
UI_STATE_TEST_BUTTONS = $7;
UI_STATE_LEFT_PRESSED = $8;
UI_STATE_RIGHT_PRESSED = $9;
UI_STATE_ENTER_PRESSED = $0a;
UI_STATE_EXIT_PRESSED = $0b;
UI_STATE_CONNECT_REQUEST = $0c;
UI_STATE_EXECUTE_FILE = $0d;
UI_STATE_EXECUTING_FILE = $0e;
UI_STATE_LOW_BATTERY = $0f;
UI_STATE_BT_ERROR = $10;
UI_BUTTON_NONE = $1;
UI_BUTTON_LEFT = $2;
UI_BUTTON_ENTER = $3;
UI_BUTTON_RIGHT = $4;
UI_BUTTON_EXIT = $5;
UI_BT_STATE_VISIBLE = $01;
UI_BT_STATE_CONNECTED = $02;
UI_BT_STATE_OFF = $04;
UI_BT_ERROR_ATTENTION = $08;
UI_BT_CONNECT_REQUEST = $40;
UI_BT_PIN_REQUEST = $80;
LS_DEVTYPE_ULTRA_SONIC = $2;
LS_DEVTYPE_CUSTOM_LS_DEVICE = $3;
COM_CHANNEL_NONE_ACTIVE = $00;
COM_CHANNEL_ONE_ACTIVE = $01;
COM_CHANNEL_TWO_ACTIVE = $02;
COM_CHANNEL_THREE_ACTIVE = $04;
COM_CHANNEL_FOUR_ACTIVE = $08;
LOWSPEED_IDLE = $0;
LOWSPEED_INIT = $1;
LOWSPEED_LOAD_BUFFER = $2;
LOWSPEED_COMMUNICATING = $3;
LOWSPEED_ERROR = $4;
LOWSPEED_DONE = $5;
LOWSPEED_TRANSMITTING = $1;
LOWSPEED_RECEIVING = $2;
LOWSPEED_DATA_RECEIVED = $3;
LOWSPEED_NO_ERROR = $0;
LOWSPEED_CH_NOT_READY = $1;
LOWSPEED_TX_ERROR = $2;
LOWSPEED_RX_ERROR = $3;
(*
IOMapMiscCount = 81;
IOMapMiscRecords : array[0..IOMapMiscCount-1] of IDRec =
(
( ID: INPUT_DIGI0; Name: 'INPUT_DIGI0'; ),
( ID: INPUT_DIGI1; Name: 'INPUT_DIGI1'; ),
( ID: INPUT_CUSTOMINACTIVE; Name: 'INPUT_CUSTOMINACTIVE'; ),
( ID: INPUT_CUSTOM9V; Name: 'INPUT_CUSTOM9V'; ),
( ID: INPUT_CUSTOMACTIVE; Name: 'INPUT_CUSTOMACTIVE'; ),
( ID: INPUT_INVALID_DATA; Name: 'INPUT_INVALID_DATA'; ),
( ID: BTN1 ; Name: 'BTN1'; ),
( ID: BTN2 ; Name: 'BTN2'; ),
( ID: BTN3 ; Name: 'BTN3'; ),
( ID: BTN4 ; Name: 'BTN4'; ),
( ID: NO_OF_BTNS ; Name: 'NO_OF_BTNS'; ),
( ID: BTNSTATE_PRESSED_EV ; Name: 'BTNSTATE_PRESSED_EV'; ),
( ID: BTNSTATE_SHORT_RELEASED_EV ; Name: 'BTNSTATE_SHORT_RELEASED_EV'; ),
( ID: BTNSTATE_LONG_PRESSED_EV ; Name: 'BTNSTATE_LONG_PRESSED_EV'; ),
( ID: BTNSTATE_LONG_RELEASED_EV ; Name: 'BTNSTATE_LONG_RELEASED_EV'; ),
( ID: BTNSTATE_PRESSED_STATE ; Name: 'BTNSTATE_PRESSED_STATE'; ),
( ID: SOUND_FLAGS_UPDATE ; Name: 'SOUND_FLAGS_UPDATE'; ),
( ID: SOUND_FLAGS_RUNNING ; Name: 'SOUND_FLAGS_RUNNING'; ),
( ID: SOUND_STATE_IDLE ; Name: 'SOUND_STATE_IDLE'; ),
( ID: SOUND_STATE_BUSY ; Name: 'SOUND_STATE_BUSY'; ),
( ID: SOUND_STATE_FREQ ; Name: 'SOUND_STATE_FREQ'; ),
( ID: SOUND_STATE_STOP ; Name: 'SOUND_STATE_STOP'; ),
( ID: SOUND_MODE_ONCE ; Name: 'SOUND_MODE_ONCE'; ),
( ID: SOUND_MODE_LOOP ; Name: 'SOUND_MODE_LOOP'; ),
( ID: SOUND_MODE_TONE ; Name: 'SOUND_MODE_TONE'; ),
( ID: UI_FLAGS_UPDATE ; Name: 'UI_FLAGS_UPDATE'; ),
( ID: UI_FLAGS_DISABLE_LEFT_RIGHT_ENTER ; Name: 'UI_FLAGS_DISABLE_LEFT_RIGHT_ENTER'; ),
( ID: UI_FLAGS_DISABLE_EXIT ; Name: 'UI_FLAGS_DISABLE_EXIT'; ),
( ID: UI_FLAGS_REDRAW_STATUS ; Name: 'UI_FLAGS_REDRAW_STATUS'; ),
( ID: UI_FLAGS_RESET_SLEEP_TIMER ; Name: 'UI_FLAGS_RESET_SLEEP_TIMER'; ),
( ID: UI_FLAGS_EXECUTE_LMS_FILE ; Name: 'UI_FLAGS_EXECUTE_LMS_FILE'; ),
( ID: UI_FLAGS_BUSY ; Name: 'UI_FLAGS_BUSY'; ),
( ID: UI_FLAGS_ENABLE_STATUS_UPDATE ; Name: 'UI_FLAGS_ENABLE_STATUS_UPDATE'; ),
( ID: UI_STATE_INIT_DISPLAY ; Name: 'UI_STATE_INIT_DISPLAY'; ),
( ID: UI_STATE_INIT_LOW_BATTERY ; Name: 'UI_STATE_INIT_LOW_BATTERY'; ),
( ID: UI_STATE_INIT_INTRO ; Name: 'UI_STATE_INIT_INTRO'; ),
( ID: UI_STATE_INIT_WAIT ; Name: 'UI_STATE_INIT_WAIT'; ),
( ID: UI_STATE_INIT_MENU ; Name: 'UI_STATE_INIT_MENU'; ),
( ID: UI_STATE_NEXT_MENU ; Name: 'UI_STATE_NEXT_MENU'; ),
( ID: UI_STATE_DRAW_MENU ; Name: 'UI_STATE_DRAW_MENU'; ),
( ID: UI_STATE_TEST_BUTTONS ; Name: 'UI_STATE_TEST_BUTTONS'; ),
( ID: UI_STATE_LEFT_PRESSED ; Name: 'UI_STATE_LEFT_PRESSED'; ),
( ID: UI_STATE_RIGHT_PRESSED ; Name: 'UI_STATE_RIGHT_PRESSED'; ),
( ID: UI_STATE_ENTER_PRESSED ; Name: 'UI_STATE_ENTER_PRESSED'; ),
( ID: UI_STATE_EXIT_PRESSED ; Name: 'UI_STATE_EXIT_PRESSED'; ),
( ID: UI_STATE_CONNECT_REQUEST ; Name: 'UI_STATE_CONNECT_REQUEST'; ),
( ID: UI_STATE_EXECUTE_FILE ; Name: 'UI_STATE_EXECUTE_FILE'; ),
( ID: UI_STATE_EXECUTING_FILE ; Name: 'UI_STATE_EXECUTING_FILE'; ),
( ID: UI_STATE_LOW_BATTERY ; Name: 'UI_STATE_LOW_BATTERY'; ),
( ID: UI_STATE_BT_ERROR ; Name: 'UI_STATE_BT_ERROR'; ),
( ID: UI_BUTTON_NONE ; Name: 'UI_BUTTON_NONE'; ),
( ID: UI_BUTTON_LEFT ; Name: 'UI_BUTTON_LEFT'; ),
( ID: UI_BUTTON_ENTER ; Name: 'UI_BUTTON_ENTER'; ),
( ID: UI_BUTTON_RIGHT ; Name: 'UI_BUTTON_RIGHT'; ),
( ID: UI_BUTTON_EXIT ; Name: 'UI_BUTTON_EXIT'; ),
( ID: UI_BT_STATE_VISIBLE ; Name: 'UI_BT_STATE_VISIBLE'; ),
( ID: UI_BT_STATE_CONNECTED ; Name: 'UI_BT_STATE_CONNECTED'; ),
( ID: UI_BT_STATE_OFF ; Name: 'UI_BT_STATE_OFF'; ),
( ID: UI_BT_ERROR_ATTENTION ; Name: 'UI_BT_ERROR_ATTENTION'; ),
( ID: UI_BT_CONNECT_REQUEST ; Name: 'UI_BT_CONNECT_REQUEST'; ),
( ID: UI_BT_PIN_REQUEST ; Name: 'UI_BT_PIN_REQUEST'; ),
( ID: LS_DEVTYPE_ULTRA_SONIC ; Name: 'LS_DEVTYPE_ULTRA_SONIC'; ),
( ID: LS_DEVTYPE_CUSTOM_LS_DEVICE ; Name: 'LS_DEVTYPE_CUSTOM_LS_DEVICE'; ),
( ID: COM_CHANNEL_NONE_ACTIVE ; Name: 'COM_CHANNEL_NONE_ACTIVE'; ),
( ID: COM_CHANNEL_ONE_ACTIVE ; Name: 'COM_CHANNEL_ONE_ACTIVE'; ),
( ID: COM_CHANNEL_TWO_ACTIVE ; Name: 'COM_CHANNEL_TWO_ACTIVE'; ),
( ID: COM_CHANNEL_THREE_ACTIVE ; Name: 'COM_CHANNEL_THREE_ACTIVE'; ),
( ID: COM_CHANNEL_FOUR_ACTIVE ; Name: 'COM_CHANNEL_FOUR_ACTIVE'; ),
( ID: LOWSPEED_IDLE ; Name: 'LOWSPEED_IDLE'; ),
( ID: LOWSPEED_INIT ; Name: 'LOWSPEED_INIT'; ),
( ID: LOWSPEED_LOAD_BUFFER ; Name: 'LOWSPEED_LOAD_BUFFER'; ),
( ID: LOWSPEED_COMMUNICATING ; Name: 'LOWSPEED_COMMUNICATING'; ),
( ID: LOWSPEED_ERROR ; Name: 'LOWSPEED_ERROR'; ),
( ID: LOWSPEED_DONE ; Name: 'LOWSPEED_DONE'; ),
( ID: LOWSPEED_TRANSMITTING ; Name: 'LOWSPEED_TRANSMITTING'; ),
( ID: LOWSPEED_RECEIVING ; Name: 'LOWSPEED_RECEIVING'; ),
( ID: LOWSPEED_DATA_RECEIVED ; Name: 'LOWSPEED_DATA_RECEIVED'; ),
( ID: LOWSPEED_NO_ERROR ; Name: 'LOWSPEED_NO_ERROR'; ),
( ID: LOWSPEED_CH_NOT_READY ; Name: 'LOWSPEED_CH_NOT_READY'; ),
( ID: LOWSPEED_TX_ERROR ; Name: 'LOWSPEED_TX_ERROR'; ),
( ID: LOWSPEED_RX_ERROR ; Name: 'LOWSPEED_RX_ERROR'; )
);
*)
function IsAlpha(c: char): boolean;
function IsCharWhiteSpace(C: Char): Boolean;
function StrContains(const SubStr, Str: string): Boolean;
function InlineName(const tname, name: string): string;
function StripInline(const name: string): string;
function InlineThreadName(const name: string): string;
function IsInlined(const name: string) : boolean;
function StripAllInlineDecoration(const name: string): string;
function StripDecoration(const name : string) : string;
function PrettyNameStrip(const name : string) : string;
function ApplyDecoration(const pre, val: string; const level : integer): string;
function Replace(const str : string; const src, rep : string) : string;
function NBCStrToFloat(const AValue: string): Double;
function NBCStrToFloatDef(const AValue: string; const aDef : Double): Double;
function NBCTextToFloat(Buffer: PChar; var Value; ValueType: TFloatValue): Boolean;
function NBCFormat(const FmtStr: string; const theArgs: array of const) : string;
function NBCFloatToStr(const AValue: Double): string;
function StripQuotes(const str : string) : string;
function JCHExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar;
Strings: TStrings): Integer;
function ValueToDataType(const value : integer) : char;
function DataTypeToTypeName(const dt : char) : string;
function BoolToString(aValue : boolean) : string;
const
TOK_SEMICOLON = ';';
TOK_OPENPAREN = '(';
TOK_CLOSEPAREN = ')';
TOK_COMMA = ',';
TOK_IDENTIFIER = 'x';
TOK_IF = 'i';
TOK_ELSE = 'l';
TOK_DO = 'd';
TOK_ASM = 'a';
TOK_REPEAT = 'r';
TOK_SWITCH = 's';
TOK_DEFAULT = 'D';
TOK_CASE = 'c';
TOK_WHILE = 'w';
TOK_FOR = 'f';
TOK_ENUM = 'm';
TOK_END = '}';
TOK_APISTRFUNC = 'E';
TOK_APIFUNC = 'F';
TOK_PROCEDURE = 'R';
TOK_TASK = 'K';
TOK_BEGIN = '{';
TOK_DIRECTIVE = '#';
TOK_API = 'Z';
TOK_LABEL = 'B';
TOK_TYPEDEF = 't';
TOK_STRUCT = 'T';
TOK_CONST = 'k';
TOK_INLINE = 'n';
TOK_START = 'A';
TOK_STOP = 'X';
TOK_PRIORITY = 'p';
TOK_NUM = 'N';
TOK_HEX = 'H';
TOK_UNSIGNED = 'U';
TOK_CHARDEF = 'C';
TOK_SHORTDEF = 'I';
TOK_LONGDEF = 'L';
TOK_BYTEDEF = 'b';
TOK_USHORTDEF = #06;
TOK_ULONGDEF = #05;
TOK_MUTEXDEF = 'M';
TOK_FLOATDEF = 'O';
TOK_STRINGDEF = 'S';
TOK_STRINGLIT = 'G';
TOK_SAFECALL = #218;
TOK_USERDEFINEDTYPE = #219;
TOK_ARRAYFLOAT = #220;
TOK_ARRAYFLOAT4 = #223;
TOK_ARRAYSTRING = #224;
TOK_ARRAYSTRING4 = #227;
TOK_ARRAYUDT = #228;
TOK_ARRAYUDT4 = #231;
TOK_ARRAYCHARDEF = #232;
TOK_ARRAYCHARDEF4 = #235;
TOK_ARRAYSHORTDEF = #236;
TOK_ARRAYSHORTDEF4 = #239;
TOK_ARRAYLONGDEF = #240;
TOK_ARRAYLONGDEF4 = #243;
TOK_ARRAYBYTEDEF = #244;
TOK_ARRAYBYTEDEF4 = #247;
TOK_ARRAYUSHORTDEF = #248;
TOK_ARRAYUSHORTDEF4 = #251;
TOK_ARRAYULONGDEF = #252;
TOK_ARRAYULONGDEF4 = #255;
TOK_BLOCK_COMMENT = #01;
TOK_LINE_COMMENT = #02;
const
REGVARS_ARRAY : array[0..11] of string = (
'__tmpsbyte%s',
'__tmpsword%s',
'__tmpslong%s',
'__tmplong%s',
'__D0%s',
'__DU0%s',
'__zf%s',
'__strtmpbuf%s',
'__strbuf%s',
'__strretval%s',
'__tmpfloat%s',
'__DF0%s'
);
REGVARTYPES_ARRAY : array[0..11] of string = (
'sbyte',
'sword',
'slong',
'long',
'slong',
'long',
'byte',
'byte[]',
'byte[]',
'byte[]',
'float',
'float'
);
const
DECOR_SEP = '_7qG2_';
var
MaxStackDepth : integer;
implementation
uses
{$IFDEF FAST_MM}
FastStrings,
{$ENDIF}
strutils,
uCommonUtils;
function IsAlpha(c: char): boolean;
begin
Result := c in ['A'..'Z', 'a'..'z', '_'];
end;
function IsCharWhiteSpace(C: Char): Boolean;
begin
Result := C in [#9, #10, #11, #12, #13, #32];
end;
function StrContains(const SubStr, Str: string): Boolean;
begin
Result := Pos(SubStr, Str) > 0;
end;
const
INLINE_DECOR_SEP = '_inline_'{ + DECOR_SEP};
// INLINE_DECORATION = '__%s_inline_%s';
INLINE_DECORATION = '%1:s' + INLINE_DECOR_SEP + '%0:s';
function InlineName(const tname, name: string): string;
begin
Result := Format(INLINE_DECORATION, [tname, name]);
// Result := name;
end;
function RPos(Substr: string ; S: string ): Integer;
begin
Result := Pos(ReverseString(Substr), ReverseString(S));
if Result <> 0 then
Result := Length(S) - (Result - 1) - (Length(Substr) - 1);
end;
function StripInline(const name: string): string;
var
i : integer;
begin
Result := name;
i := RPos(INLINE_DECOR_SEP, Result);
if i > 0 then
Result := Copy(Result, 1, i-1);
end;
function InlineThreadName(const name: string): string;
var
i : integer;
begin
Result := name;
i := RPos(INLINE_DECOR_SEP, Result);
if i > 0 then
Result := Copy(Result, i+Length(INLINE_DECOR_SEP), MaxInt);
end;
function IsInlined(const name: string) : boolean;
begin
Result := Pos(INLINE_DECOR_SEP, name) > 0;
end;
function StripAllInlineDecoration(const name: string): string;
var
i : integer;
begin
Result := name;
i := Pos(INLINE_DECOR_SEP, Result);
if i > 0 then
Result := Copy(Result, 1, i-1);
end;
function StripDecoration(const name : string) : string;
var
i : integer;
varName : string;
begin
Result := StripInline(name);
// a decorated name has this pattern:
// __threadnameDECOR_SEPvariablenameDECOR_SEPNNNetc
i := Pos(DECOR_SEP, Result);
if i > 0 then
begin
System.Delete(Result, 1, i+Length(DECOR_SEP)-1);
i := Pos(DECOR_SEP, Result);
if i > 0 then
begin
varName := Copy(Result, 1, i-1);
System.Delete(Result, 1, i+Length(DECOR_SEP)+2);
Result := varName + Result;
end;
end;
end;
function PrettyNameStrip(const name : string) : string;
var
i : integer;
begin
Result := name;
// a decorated name has this pattern:
// __threadnameDECOR_SEPvariablenameDECOR_SEPNNNetc
i := Pos(DECOR_SEP, Result);
if i > 0 then
begin
System.Delete(Result, 1, 2); // drop the underscores
Result := Replace(Result, DECOR_SEP, '.');
end;
end;
function ApplyDecoration(const pre, val: string; const level : integer): string;
var
p : integer;
first, last : string;
begin
// if val contains dots then separate it into two pieces
p := Pos('.', val);
if p > 0 then
begin
first := Copy(val, 1, p-1);
last := Copy(val, p, MaxInt);
Result := Format('__%s%s%s%s%3.3d%s', [pre, DECOR_SEP, first, DECOR_SEP, level, last]);
// Result := Format('__%s_%s_%3.3d%s', [pre, first, level, last]);
end
else
begin
Result := Format('__%s%s%s%s%3.3d', [pre, DECOR_SEP, val, DECOR_SEP, level]);
// Result := Format('__%s_%s_%3.3d', [pre, val, level]);
end;
end;
function Replace(const str : string; const src, rep : string) : string;
begin
{$IFDEF FAST_MM}
Result := FastReplace(str, src, rep);
{$ELSE}
Result := StringReplace(str, src, rep, [rfReplaceAll]);
{$ENDIF}
end;
procedure NBCFormatSettings(var aFS : TFormatSettings; const aDS : Char);
begin
aFS.DecimalSeparator := aDS;
aFS.ThousandSeparator := ThousandSeparator;
aFS.CurrencyFormat := CurrencyFormat;
aFS.NegCurrFormat := NegCurrFormat;
aFS.CurrencyDecimals := CurrencyDecimals;
aFS.CurrencyString := CurrencyString;
end;
function NBCFloatToStr(const AValue: Double): string;
begin
Result := StripTrailingZeros(NBCFormat('%.10f', [AValue]));
end;
function NBCStrToFloat(const AValue: string): Double;
var
FS : TFormatSettings;
begin
FS.DecimalSeparator := DecimalSeparator;
NBCFormatSettings(FS, '.');
Result := StrToFloat(AValue, FS);
end;
function NBCStrToFloatDef(const AValue: string; const aDef : Double): Double;
var
FS : TFormatSettings;
begin
FS.DecimalSeparator := DecimalSeparator;
NBCFormatSettings(FS, '.');
Result := StrToFloatDef(AValue, aDef, FS);
end;
function NBCTextToFloat(Buffer: PChar; var Value; ValueType: TFloatValue): Boolean;
var
FS : TFormatSettings;
val : Extended;
begin
FS.DecimalSeparator := DecimalSeparator;
NBCFormatSettings(FS, '.');
Result := TextToFloat(Buffer, val, fvExtended, FS);
end;
function NBCFormat(const FmtStr: string; const theArgs: array of const) : string;
var
FS : TFormatSettings;
begin
FS.DecimalSeparator := DecimalSeparator;
NBCFormatSettings(FS, '.');
Result := Format(FmtStr, theArgs, FS);
end;
function StripQuotes(const str : string) : string;
begin
Result := Copy(str, 2, Length(str)-2);
end;
{$IFDEF FPC}
function JCHExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar;
Strings: TStrings): Integer;
var
Head, Tail: PChar;
EOS, InQuote: Boolean;
QuoteChar: Char;
Item: string;
begin
Item := '';
Result := 0;
if (Content = nil) or (Content^=#0) or (Strings = nil) then Exit;
Tail := Content;
InQuote := False;
QuoteChar := #0;
Strings.BeginUpdate;
try
repeat
while Tail^ in WhiteSpace + [#13, #10] do inc(Tail);
Head := Tail;
while True do
begin
while (InQuote and not (Tail^ in [QuoteChar, #0])) or
not (Tail^ in Separators + [#0, #13, #10, '''', '"']) do
inc(Tail);
if Tail^ in ['''', '"'] then
begin
if (QuoteChar <> #0) and (QuoteChar = Tail^) then
QuoteChar := #0
else if QuoteChar = #0 then
QuoteChar := Tail^;
InQuote := QuoteChar <> #0;
inc(Tail);
end else Break;
end;
EOS := Tail^ = #0;
if (Head <> Tail) and (Head^ <> #0) then
begin
if Strings <> nil then
begin
SetString(Item, Head, Tail - Head);
Strings.Add(Item);
end;
Inc(Result);
end;
inc(Tail);
until EOS;
finally
Strings.EndUpdate;
end;
end;
{$ELSE}
function JCHExtractStrings(Separators, WhiteSpace: TSysCharSet; Content: PChar;
Strings: TStrings): Integer;
begin
Result := ExtractStrings(Separators, WhiteSpace, Content, Strings);
end;
{$ENDIF}
function ValueToDataType(const value : integer) : char;
begin
if value < 0 then begin
Result := TOK_CHARDEF;
if value < Low(Shortint) then
begin
Result := TOK_SHORTDEF;
if value < Low(Smallint) then
Result := TOK_LONGDEF;
end;
end
else begin
Result := TOK_BYTEDEF;
if value > High(Byte) then
begin
Result := TOK_USHORTDEF;
if value > High(Word) then
Result := TOK_ULONGDEF;
end;
end;
end;
function DataTypeToTypeName(const dt : char) : string;
begin
case dt of
TOK_CHARDEF : Result := 'char';
TOK_SHORTDEF : Result := 'int';
TOK_LONGDEF : Result := 'long';
TOK_BYTEDEF : Result := 'byte';
TOK_USHORTDEF : Result := 'unsigned int';
TOK_ULONGDEF : Result := 'unsigned long';
else
Result := 'unexpected type';
end;
end;
function BoolToString(aValue : boolean) : string;
begin
if aValue then
Result := 'TRUE'
else
Result := 'FALSE';
end;
{ TNBCExpParser }
constructor TNBCExpParser.Create(AOwner: TComponent);
begin
inherited;
fFirmwareVersion := MAX_FW_VER1X;
end;
procedure TNBCExpParser.InitializeCalc;
var
i : integer;
begin
ClearVariables;
if StandardDefines then
begin
SetVariable(STR_NA, NOT_AN_ELEMENT);
SetVariable(STR_FALSE, Ord(false));
SetVariable(STR_TRUE, Ord(true));
// add comparison codes
for i := Low(CCEncodings) to High(CCEncodings) do
SetVariable(CCEncodings[i].Mode, CCEncodings[i].Encoding);
// add output field IDs
for i := Low(OutputFieldIDs) to High(OutputFieldIDs) do
SetVariable(OutputFieldIDs[i].Name, OutputFieldIDs[i].ID);
// add input field IDs
for i := Low(InputFieldIDs) to High(InputFieldIDs) do
SetVariable(InputFieldIDs[i].Name, InputFieldIDs[i].ID);
if FirmwareVersion > MAX_FW_VER1X then
begin
// add syscall method IDs
for i := Low(SysCallMethodIDs2x) to High(SysCallMethodIDs2x) do
SetVariable(SysCallMethodIDs2x[i].Name, SysCallMethodIDs2x[i].ID);
end
else
begin
// add syscall method IDs
for i := Low(SysCallMethodIDs1x) to High(SysCallMethodIDs1x) do
SetVariable(SysCallMethodIDs1x[i].Name, SysCallMethodIDs1x[i].ID);
end;
// add IOMap field IDs
for i := Low(IOMapFieldIDs) to High(IOMapFieldIDs) do
SetVariable(IOMapFieldIDs[i].Name, IOMapFieldIDs[i].ID);
{
// add IOMap Offset IDs
for i := Low(IOMapOffsetRecords) to High(IOMapOffsetRecords) do
SetVariable(IOMapOffsetRecords[i].Name, IOMapOffsetRecords[i].ID);
}
end;
if ExtraDefines then
begin
SetVariable(STR_OUT_A, OUT_A);
SetVariable(STR_OUT_B, OUT_B);
SetVariable(STR_OUT_C, OUT_C);
SetVariable(STR_IN_1, IN_1);
SetVariable(STR_IN_2, IN_2);
SetVariable(STR_IN_3, IN_3);
SetVariable(STR_IN_4, IN_4);
SetVariable(STR_IO_BASE, IO_BASE);
SetVariable(STR_MOD_OUTPUT, MOD_OUTPUT);
SetVariable(STR_MOD_INPUT, MOD_INPUT);
SetVariable(STR_IO_IN_FPP, IO_IN_FPP);
SetVariable(STR_IO_OUT_FPP, IO_OUT_FPP);
// add Update Flag IDs
for i := Low(UFRecords) to High(UFRecords) do
SetVariable(UFRecords[i].Name, UFRecords[i].ID);
// add Output Mode IDs
for i := Low(OutModeRecords) to High(OutModeRecords) do
SetVariable(OutModeRecords[i].Name, OutModeRecords[i].ID);
// add Output RunState IDs
for i := Low(OutRunStateRecords) to High(OutRunStateRecords) do
SetVariable(OutRunStateRecords[i].Name, OutRunStateRecords[i].ID);
// add Output RegMode IDs
for i := Low(OutRegModeRecords) to High(OutRegModeRecords) do
SetVariable(OutRegModeRecords[i].Name, OutRegModeRecords[i].ID);
// add Input Type IDs
for i := Low(InTypeRecords) to High(InTypeRecords) do
SetVariable(InTypeRecords[i].Name, InTypeRecords[i].ID);
// add Input Mode IDs
for i := Low(InModeRecords) to High(InModeRecords) do
SetVariable(InModeRecords[i].Name, InModeRecords[i].ID);
// add MS_X IDs
for i := Low(MSRecords) to High(MSRecords) do
SetVariable(MSRecords[i].Name, MSRecords[i].ID);
// add TONE_X IDs
for i := Low(ToneRecords) to High(ToneRecords) do
SetVariable(ToneRecords[i].Name, ToneRecords[i].ID);
{
// add miscellaneous IOMap constants
for i := Low(IOMapMiscRecords) to High(IOMapMiscRecords) do
SetVariable(IOMapMiscRecords[i].Name, IOMapMiscRecords[i].ID);
}
end;
end;
procedure TNBCExpParser.SetExtraDefs(const aValue: boolean);
begin
if fExtraDefs <> aValue then
begin
fExtraDefs := aValue;
InitializeCalc;
end;
end;
procedure TNBCExpParser.SetFirmwareVersion(const Value: word);
begin
fFirmwareVersion := Value;
end;
procedure TNBCExpParser.SetStandardDefs(const aValue: boolean);
begin
if fStandardDefs <> aValue then
begin
fStandardDefs := aValue;
InitializeCalc;
end;
end;
{ TInlineFunction }
constructor TInlineFunction.Create(ACollection: TCollection);
begin
inherited;
fCode := TStringList.Create;
fVariables := TVariableList.Create;
fCallers := TStringList.Create;
TStringList(fCallers).Sorted := True;
TStringList(fCallers).Duplicates := dupError;
fParams := TFunctionParameters.Create;
fEmitCount := 0;
end;
destructor TInlineFunction.Destroy;
begin
FreeAndNil(fCode);
FreeAndNil(fVariables);
FreeAndNil(fCallers);
FreeAndNil(fParams);
inherited;
end;
procedure TInlineFunction.Emit(aStrings: TStrings);
var
tmpSL : TStringList;
tmpCode, oldname, newname, NameInline : string;
i : integer;
fp : TFunctionParameter;
begin
inc(fEmitCount);
// adjust labels
tmpSL := TStringList.Create;
try
tmpCode := FixupLabels(fCode.Text);
tmpCode := Replace(tmpCode, 'return', Format('jmp %s', [EndLabel]));
// do all the variable replacing that is needed
for i := 0 to Parameters.Count - 1 do
begin
fp := Parameters[i];
oldname := ApplyDecoration(fp.ProcName, fp.Name, 0);
newname := InlineName(CurrentCaller, oldname);
// is this parameter a constant?
if fp.IsConstant and not fp.IsReference then
tmpCode := Replace(tmpCode, oldname, fp.ConstantValue)
else
tmpCode := Replace(tmpCode, oldname, newname);
end;
for i := 0 to LocalVariables.Count - 1 do
begin
oldname := LocalVariables[i].Name;
newname := InlineName(CurrentCaller, oldname);
tmpCode := Replace(tmpCode, oldname, newname);
end;
// need to fix string return buffer name, string temp buffer name,
// register name, and all the stack variable names.
// YUCKY !!!!!!!
NameInline := InlineName(CurrentCaller, Name);
for i := Low(REGVARS_ARRAY) to High(REGVARS_ARRAY) do
begin
oldname := Format(REGVARS_ARRAY[i], [Name]);
newname := Format(REGVARS_ARRAY[i], [NameInline]);
tmpCode := Replace(tmpCode, oldName, newName);
end;
oldname := Format('__result_%s', [Name]);
newname := Format('__result_%s', [NameInline]);
tmpCode := Replace(tmpCode, oldName, newName);
for i := 1 to MaxStackDepth do
begin
oldname := Format('__signed_stack_%3.3d%s', [i, Name]);
newname := Format('__signed_stack_%3.3d%s', [i, NameInline]);
tmpCode := Replace(tmpCode, oldName, newName);
end;
for i := 1 to MaxStackDepth do
begin
oldname := Format('__unsigned_stack_%3.3d%s', [i, Name]);
newname := Format('__unsigned_stack_%3.3d%s', [i, NameInline]);
tmpCode := Replace(tmpCode, oldName, newName);
end;
for i := 1 to MaxStackDepth do
begin
oldname := Format('__float_stack_%3.3d%s', [i, Name]);
newname := Format('__float_stack_%3.3d%s', [i, NameInline]);
tmpCode := Replace(tmpCode, oldName, newName);
end;
if Pos(EndLabel, tmpCode) > 0 then
tmpCode := tmpCode + #13#10 + EndLabel + ':';
tmpSL.Text := tmpCode;
aStrings.AddStrings(tmpSL);
finally
tmpSL.Free;
end;
end;
function TInlineFunction.FixupLabels(const tmpCode: string): string;
{
var
tmp, values : TStringList;
i, j : integer;
line : string;
}
begin
// NXC-generated labels are fixed-up here
Result := Replace(tmpCode, LABEL_PREFIX, Format('__%3.3d%s', [fEmitCount, LABEL_PREFIX]));
// also need to fix any other user-defined labels in the code so that
// emitting this code more than once will not cause duplicate label
// problems
{
tmp := TStringList.Create;
try
tmp.Text := Result;
for i := 0 to tmp.Count - 1 do
begin
line := tmp[i];
// does this line contain a label?
values := TStringList.Create;
try
j := JCHExtractStrings([' ', #9], [], PChar(line), values);
finally
values.Free;
end;
end;
finally
tmp.Free;
end;
}
end;
function TInlineFunction.GetEndLabel: string;
begin
Result := Format(LABEL_PREFIX+'%s_inline_%s_%3.3d_end_lbl', [CurrentCaller, Name, fEmitCount]);
end;
procedure TInlineFunction.SetCode(const Value: TStrings);
begin
fCode.Assign(Value);
end;
procedure TInlineFunction.SetParams(const Value: TFunctionParameters);
var
i : integer;
fp, newFP : TFunctionParameter;
begin
// copy into fParams the parameters in Value that are for this function
fParams.Clear;
for i := 0 to Value.Count - 1 do
begin
fp := Value[i];
if fp.ProcName = Self.Name then
begin
newFP := Self.Parameters.Add;
newFP.Assign(fp);
end;
end;
end;
{ TInlineFunctions }
function TInlineFunctions.Add: TInlineFunction;
begin
Result := TInlineFunction(inherited Add);
end;
constructor TInlineFunctions.Create;
begin
inherited Create(TInlineFunction);
end;
function TInlineFunctions.GetItem(Index: Integer): TInlineFunction;
begin
Result := TInlineFunction(inherited GetItem(Index));
end;
function TInlineFunctions.IndexOfName(const name: string): integer;
var
i : integer;
begin
Result := -1;
for i := 0 to Count - 1 do
begin
if Items[i].Name = name then
begin
Result := Items[i].Index;
break;
end;
end;
end;
function TInlineFunctions.Insert(Index: Integer): TInlineFunction;
begin
result := TInlineFunction(inherited Insert(Index));
end;
procedure TInlineFunctions.SetItem(Index: Integer; const Value: TInlineFunction);
begin
inherited SetItem(Index, Value);
end;
{ TFunctionParameters }
function TFunctionParameters.Add: TFunctionParameter;
begin
Result := TFunctionParameter(inherited Add);
end;
constructor TFunctionParameters.Create;
begin
inherited Create(TFunctionParameter);
end;
function TFunctionParameters.GetItem(Index: Integer): TFunctionParameter;
begin
Result := TFunctionParameter(inherited GetItem(Index));
end;
function TFunctionParameters.IndexOf(const procname: string;
const idx: integer): integer;
var
i : integer;
fp : TFunctionParameter;
begin
Result := -1;
for i := 0 to Count - 1 do
begin
fp := Items[i];
if (fp.ProcName = procname) and (fp.ParamIndex = idx) then
begin
Result := fp.Index;
break;
end;
end;
end;
function TFunctionParameters.Insert(Index: Integer): TFunctionParameter;
begin
result := TFunctionParameter(inherited Insert(Index));
end;
function TFunctionParameters.ParamCount(const name: string): integer;
var
i : integer;
begin
Result := 0;
for i := 0 to Count - 1 do begin
if Items[i].ProcName = name then
inc(Result);
end;
end;
function TFunctionParameters.RequiredParamCount(const name: string): integer;
var
i : integer;
fp : TFunctionParameter;
begin
Result := 0;
for i := 0 to Count - 1 do begin
fp := Items[i];
if (fp.ProcName = name) and not fp.HasDefault then
inc(Result);
end;
end;
procedure TFunctionParameters.SetItem(Index: Integer; const Value: TFunctionParameter);
begin
inherited SetItem(Index, Value);
end;
{ TFunctionParameter }
procedure TFunctionParameter.AssignTo(Dest: TPersistent);
var
fp : TFunctionParameter;
begin
if Dest is TFunctionParameter then
begin
fp := TFunctionParameter(Dest);
fp.ProcName := ProcName;
fp.Name := Name;
fp.ParamType := ParamType;
fp.ParamTypeName := ParamTypeName;
fp.ParamIndex := ParamIndex;
fp.IsArray := IsArray;
fp.IsConstant := IsConstant;
fp.IsReference := IsReference;
fp.ArrayDimension := ArrayDimension;
fp.ConstantValue := ConstantValue;
fp.FuncIsInline := FuncIsInline;
fp.HasDefault := HasDefault;
fp.DefaultValue := DefaultValue;
end
else
inherited;
end;
constructor TFunctionParameter.Create(ACollection: TCollection);
begin
inherited;
fProcName := '';
fName := '';
fParamIndex := 0;
fIsConstant := False;
fIsReference := False;
fIsArray := False;
fDim := 0;
fParamType := fptUBYTE;
fFuncIsInline := False;
fHasDefault := False;
fDefaultValue := '';
end;
function TFunctionParameter.GetConstValue: string;
begin
Result := fConstValue;
end;
function TFunctionParameter.GetIsConstReference: boolean;
begin
Result := IsConstant and IsReference;
end;
function TFunctionParameter.GetIsVarReference: boolean;
begin
Result := not IsConstant and IsReference;
end;
function TFunctionParameter.GetParamDataType: char;
begin
case ParamType of
fptSBYTE : begin
if not IsArray then
Result := TOK_CHARDEF
else
Result := Char(Ord(TOK_ARRAYCHARDEF) + ArrayDimension-1);
end;
fptUBYTE : begin
if not IsArray then
Result := TOK_BYTEDEF
else
Result := Char(Ord(TOK_ARRAYBYTEDEF) + ArrayDimension-1);
end;
fptSWORD : begin
if not IsArray then
Result := TOK_SHORTDEF
else
Result := Char(Ord(TOK_ARRAYSHORTDEF) + ArrayDimension-1);
end;
fptUWORD : begin
if not IsArray then
Result := TOK_USHORTDEF
else
Result := Char(Ord(TOK_ARRAYUSHORTDEF) + ArrayDimension-1);
end;
fptSLONG : begin
if not IsArray then
Result := TOK_LONGDEF
else
Result := Char(Ord(TOK_ARRAYLONGDEF) + ArrayDimension-1);
end;
fptULONG : begin
if not IsArray then
Result := TOK_ULONGDEF
else
Result := Char(Ord(TOK_ARRAYULONGDEF) + ArrayDimension-1);
end;
fptString : begin
if not IsArray then
Result := TOK_STRINGDEF
else
Result := Char(Ord(TOK_ARRAYSTRING) + ArrayDimension-1);
end;
fptUDT : begin
if not IsArray then
Result := TOK_USERDEFINEDTYPE
else
Result := Char(Ord(TOK_ARRAYUDT) + ArrayDimension-1);
end;
fptMutex : Result := TOK_MUTEXDEF;
fptFloat : begin
if not IsArray then
Result := TOK_FLOATDEF
else
Result := Char(Ord(TOK_ARRAYFLOAT) + ArrayDimension-1);
end;
else
Result := TOK_BYTEDEF;
end;
end;
procedure TFunctionParameter.SetConstValue(const Value: string);
begin
fConstValue := Value;
end;
{ TVariable }
procedure TVariable.AssignTo(Dest: TPersistent);
var
V : TVariable;
begin
if Dest is TVariable then
begin
V := TVariable(Dest);
V.Name := Name;
V.DataType := DataType;
V.IsConstant := IsConstant;
V.TypeName := TypeName;
V.LenExpr := LenExpr;
V.Level := Level;
V.HasDefault := HasDefault;
V.DefaultValue := DefaultValue;
end
else
inherited;
end;
constructor TVariable.Create(ACollection: TCollection);
begin
inherited;
fName := '';
fValue := '';
fTypeName := '';
fDataType := TOK_BYTEDEF;
fIsConst := False;
fLevel := 0;
fHasDef := False;
fDefValue := '';
end;
{ TVariableList }
function TVariableList.Add: TVariable;
begin
Result := TVariable(inherited Add);
end;
constructor TVariableList.Create;
begin
inherited Create(TVariable);
end;
function TVariableList.GetItem(Index: Integer): TVariable;
begin
Result := TVariable(inherited GetItem(Index));
end;
function TVariableList.IndexOfName(const name: string): integer;
var
i : integer;
begin
Result := -1;
for i := 0 to Count - 1 do
begin
if Items[i].Name = name then
begin
Result := Items[i].Index;
break;
end;
end;
end;
function TVariableList.Insert(Index: Integer): TVariable;
begin
Result := TVariable(inherited Insert(Index));
end;
procedure TVariableList.SetItem(Index: Integer; const Value: TVariable);
begin
inherited SetItem(Index, Value);
end;
{ TArrayHelperVar }
constructor TArrayHelperVar.Create(ACollection: TCollection);
begin
inherited;
fThreadName := 'main';
fDataType := #0;
fUDType := '';
fIndex := 0;
fLocked := False;
end;
function TArrayHelperVar.GetName: string;
begin
Result := Format('__ArrHelper__%s%s_%d_%d', [fThreadName, fUDType, Ord(fDataType), fIndex]);
end;
{ TArrayHelperVars }
function TArrayHelperVars.Add: TArrayHelperVar;
begin
Result := TArrayHelperVar(inherited Add);
end;
constructor TArrayHelperVars.Create;
begin
inherited Create(TArrayHelperVar);
end;
function TArrayHelperVars.GetHelper(const tname, udType: string; const dt: char): TArrayHelperVar;
var
i, newIdx : integer;
X : TArrayHelperVar;
begin
Result := nil;
// look for existing helper. If not found, create one.
for i := 0 to Count - 1 do
begin
X := Items[i];
if (X.ThreadName = tname) and (X.DataType = dt) and
(X.UserDefinedType = udType) and not X.Locked then
begin
Result := X;
Break;
end;
end;
if Result = nil then
begin
newIdx := 0;
for i := Count - 1 downto 0 do
begin
X := Items[i];
if (X.ThreadName = tname) and (X.DataType = dt) and (X.UserDefinedType = udType) then
begin
// duplicate item
newIdx := X.Index + 1;
break;
end;
end;
// create new helper
Result := Add;
Result.ThreadName := tname;
Result.DataType := dt;
Result.UserDefinedType := udType;
Result.fIndex := newIdx;
end;
Result.fLocked := True;
end;
function TArrayHelperVars.GetItem(Index: Integer): TArrayHelperVar;
begin
Result := TArrayHelperVar(inherited GetItem(Index));
end;
function TArrayHelperVars.IndexOfName(const name: string): integer;
var
i : integer;
begin
Result := -1;
for i := 0 to Count - 1 do
begin
if Items[i].Name = name then
begin
Result := Items[i].Index;
break;
end;
end;
end;
function TArrayHelperVars.Insert(Index: Integer): TArrayHelperVar;
begin
Result := TArrayHelperVar(inherited Insert(Index));
end;
procedure TArrayHelperVars.ReleaseHelper(aHelper: TArrayHelperVar);
begin
aHelper.fLocked := False;
end;
procedure TArrayHelperVars.SetItem(Index: Integer; const Value: TArrayHelperVar);
begin
inherited SetItem(Index, Value);
end;
end.
|
unit TestdCucuberList;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Classes, dCucuberListIntf, dCucuberList, dSpec, TestBaseClasses;
type
// Test methods for class TDcucumberList
TestTDcucumberList = class(TParseContext)
strict private
FCucumberList: ICucumberList;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure DeveriaSerValidoSeFuncaoDeValidacaoEh;
procedure DeveriaSerValidaSeNaoInformeiNenhumaFuncaoDeValidacao;
procedure DeveriaSerValidaSeTemAoMenosUmItemNaLista;
end;
implementation
uses
ValidationRuleIntf;
procedure TestTDcucumberList.SetUp;
begin
FCucumberList := TCucumberList.Create;
end;
procedure TestTDcucumberList.TearDown;
begin
FCucumberList := nil;
end;
procedure TestTDcucumberList.DeveriaSerValidaSeNaoInformeiNenhumaFuncaoDeValidacao;
begin
Specify.That((FCucumberList as IValidationRule).Valid).Should.Be.True;
end;
procedure TestTDcucumberList.DeveriaSerValidaSeTemAoMenosUmItemNaLista;
begin
FCucumberList.Add(TCucumberList.Create);
(FCucumberList as IValidationRule).ValidateFunction := function: Boolean
begin
Result := FCucumberList.Count > 0;
end;
Specify.That((FCucumberList as IValidationRule).Valid).Should.Be.True;
end;
procedure TestTDcucumberList.DeveriaSerValidoSeFuncaoDeValidacaoEh;
begin
(FCucumberList as IValidationRule).ValidateFunction := function: Boolean
begin
Result := True;
end;
Specify.That((FCucumberList as IValidationRule).Valid).Should.Be.True;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTDcucumberList.Suite);
end.
|
unit WpcScriptParser;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
Fgl, StrUtils,
WpcScript,
WpcStatements,
WpcStatementProperties,
WpcScriptCommons,
WpcCommonTypes,
WpcWallpaperStyles,
WpcExceptions,
OSUtils;
const
WHITESPACE_SET = [ #32, #9 ];
ALLOWED_NAME_SYMBOLS = [ 'A'..'Z', 'a'..'z', '0'..'9', '_' ];
END_OF_SCRIPT = '_END_OF_WPC_SCRIPT_';
VARIABLE_START_SYMBOL = '$';
COMMENTARY_SYMBOL = '#';
QUOTE_SYMBOL = '"';
DIRECTORIES_KEYWORD = 'DIRECTORIES';
DIRECTORY_KEYWORD = 'DIRECTORY';
IMAGES_KEYWORD = 'IMAGES';
DELAYS_KEYWORD = 'DELAYS';
DELAY_KEYWORD = 'DELAY';
DEFAULTS_KEYWORD = 'DEFAULTS';
BRANCH_KEYWORD = 'BRANCH';
END_KEYWORD = 'END';
WAIT_KEYWORD = 'WAIT';
STOP_KEYWORD = 'STOP';
CHOOSE_KEYWORD = 'CHOOSE';
BY_KEYWORD = 'BY';
FROM_KEYWORD = 'FROM';
SWITCH_KEYWORD = 'SWITCH';
USE_KEYWORD = 'USE';
SET_KEYWORD = 'SET';
WALLPAPER_KEYWORD = 'WALLPAPER';
STYLE_KEYWORD = 'STYLE';
WITH_KEYWORD = 'WITH';
PROBABILITY_KEYWORD = 'PROBABILITY';
FOR_KEYWORD = 'FOR';
TIMES_KEYWORD = 'TIMES';
WEIGHT_KEYWORD = 'WEIGHT';
SEASON_KEYWORD = 'SEASON';
WEEKDAY_KEYWORD = 'WEEKDAY';
MONTH_KEYWORD = 'MONTH';
DATE_KEYWORD = 'DATE';
TIME_KEYWORD = 'TIME';
DATETIME_KEYWORD = 'DATETIME';
TO_KEYWORD = 'TO';
WPC_DATE_SEPARATOR = '.';
WPC_TIME_SEPARATOR = ':';
WPC_DATE_TIME_SEPARATOR = '-';
type
{ TWpcScriptParser }
TWpcScriptParser = class(TObject)
private
type
TMapStringString = specialize TFPGMap<String, String>;
TMapStringLongWord = specialize TFPGMap<String, LongWord>;
TStatementPropertiesSet = set of TWpcStatementPropertyId;
TStatementProperties = record
Times : LongWord;
Probability : Byte;
Delay : LongWord;
Style : TWallpaperStyle;
end;
private
FScript : TWpcScript;
FLines : TStringList;
FCurrentLine : Integer;
FCheckScriptResources : Boolean;
FDirsVariables : TMapStringString;
FImagesVariables : TMapStringString;
FDelaysVariables : TMapStringLongWord;
FDefaultDelay : LongWord;
FDefaultDelayUnits : TWpcTimeMeasurementUnits;
FDefaultWallpaperStyle : TWallpaperStyle;
FDefaultImagesDirectory : String;
FComputedDefaultDelay : LongWord;
public
property CheckScriptResources : Boolean read FCheckScriptResources write FCheckScriptResources;
public
constructor Create(ScriptLines : TStringList);
destructor Destroy(); override;
public
function Parse() : TWpcScript;
function GetDirPath(DirVariableName : String) : String;
function GetImage(ImageVariableName : String) : String;
function GetDelay(DelayVariableName : String) : LongWord;
function GetDefaultDelay() : LongWord;
function GetDefaultDelayUnits() : TWpcTimeMeasurementUnits;
function GetDefaultWallpaperStyle() : TWallpaperStyle;
function GetDefaultImagesDirectory() : String;
private
procedure ParseHeaders();
procedure ParseDirsVariables();
procedure ParseImagesVariables();
procedure ParseDaleyVariables();
procedure ParseDefaults();
procedure ParseBranches();
procedure Validate();
procedure ParseVariableDefinition(Line : String; var VariableName : String; var VariableValue : String);
function ApplyParsedDirectoriesVariables(VariableValue : String) : String;
function ApplyParsedImagesVariables(Image : String) : String;
function ApplyParsedDelayVariables(Delay : String) : String;
function ParseNextBranch() : TWpcBranchStatement;
function ParseWaitStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseWallpaperStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseStopStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseSwitchBranchStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseUseBranchStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseWallpaperChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseBranchToUseChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseBranchToSwitchChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function ParseWallpaperStatementData(LineWords : TStringList; Index : Integer) : TWpcWallpaperStatement;
function ParseSwitchBranchStatementData(LineWords : TStringList; Index : Integer) : TWpcSwitchBranchStatement;
function ParseUseBranchStatementData(LineWords : TStringList; Index : Integer) : TWpcUseBranchStatement;
function ParseDirectory(LineWords : TStringList; var Index : Integer) : String;
function ParseImage(LineWords : TStringList; var Index : Integer) : TWpcImage;
function GetDefaultStatementProperties() : TStatementProperties;
function ParseStatementProperties(AllowedProperties : TStatementPropertiesSet; LineWords : TStringList; var Index : Integer) : TStatementProperties;
function ParseStatementPropertiesAndEnsureEndOfLine(AllowedProperties : TStatementPropertiesSet; LineWords : TStringList; Index : Integer) : TStatementProperties;
function ParseDelayProperty(LineWords : TStringList; WordIndex : Integer) : Integer;
function ParseTimesProperty(LineWords : TStringList; WordIndex : Integer) : Integer;
function ParseProbabilityProperty(LineWords : TStringList; WordIndex : Integer) : Byte;
function ParseWallpaperStyleProperty(LineWords : TStringList; WordIndex : Integer) : TWallpaperStyle;
function ParseAndRemoveSelector(LineWords : TStringList; Selector : TWpcSelector) : TWpcSelectorValueHolder;
function ParseSequentialNumberWithAlias(Value : String; Aliases : Array of String) : Integer;
function ParseDelayValue(Delay : String) : LongWord;
function ParseDelayMeasurmentUnitsValue(MeasurementUnits : String) : TWpcTimeMeasurementUnits;
function ParseProbabilityValue(Probability : String) : Byte;
function ParseTimesValue(Times : String) : LongWord;
function ParseWallpaperStyleValue(Style : String) : TWallpaperStyle;
function ParseSelectorValue(Selector : String) : TWpcSelector;
function ParseWeightValue(Weight : String) : LongWord;
function ParseSeasonValue(Season : String) : Integer;
function ParseWeekdayValue(Weekday : String) : Integer;
function ParseMonthValue(Month : String) : Integer;
function ParseDateValue(Date : String) : TDateTime;
function ParseTimeValue(Time : String) : TDateTime;
function ParseDateTimeValue(DateTime : String) : TDateTime;
function ValidateName(Name : String) : Boolean;
procedure ValidateBranchNames();
function GetLine(LineNumber : Integer) : String;
function GetNextLine() : String;
function SplitLine(Line : String) : TStringList;
function ProbeStatementType(LineWords : TStringList) : TWpcStatemetId;
function ProbePropertyType(LineWords : TStringList; WordIndex : Integer) : TWpcStatementPropertyId;
function IsWordANumber(AWord : String) : Boolean;
function CheckKeyWord(Given : String; Expected : String) : Boolean;
procedure EnsureKeyWord(LineWords : TStringList; Index : Integer; ExpectedKeyWord : String);
procedure EnsureKeyWordsLine(GivenKeyWords : TStringList; ExpectedKeyWords : Array of String);
procedure EnsureKeyWordsLineAndFreeResources(GivenKeyWords : TStringList; ExpectedKeyWords : Array of String);
procedure EnsureSelectorKeyword(LineWords : TStringList; SelectorKeyword : String);
procedure EnsureEndOfLine(LineWords : TStringList; WordIndex : Integer);
function SafeGet(LineWords : TStringList; Index : Integer) : String;
procedure SearchWordInScript(TheWord : String; CaseSensitive : Boolean; var Line : Integer; var Index : Integer);
end;
implementation
{ TWpcScriptParser }
constructor TWpcScriptParser.Create(ScriptLines : TStringList);
begin
FLines := ScriptLines;
FScript := TWpcScript.Create();
FDirsVariables := TMapStringString.Create();
FImagesVariables := TMapStringString.Create();
FDelaysVariables := TMapStringLongWord.Create();
FDefaultDelay := 5;
FDefaultDelayUnits := MINUTES;
FDefaultWallpaperStyle := CENTER;
FDefaultImagesDirectory := ''; // TODO implement respecting of this value.
FComputedDefaultDelay := TWpcDelayStatementProperty.ConvertToMilliseconds(FDefaultDelay, FDefaultDelayUnits);
FCheckScriptResources := True;
end;
destructor TWpcScriptParser.Destroy();
begin
FDirsVariables.Free();
FImagesVariables.Free();
FDelaysVariables.Free();
inherited Destroy();
end;
{
Parses Wallpaper Changer script.
The script has following format:
<Headers section>
<Branches section>
Where:
- headers section is optional.
- branches section must have Main branch.
Comments are allowed. A comment line has to start with # symbol.
Syntax:
# Headers section
# Each part of headers section isn't mandatory.
DIRECTORIES
[<key> <value>]
...
END DIRECTORIES
IMAGES
[<key> <value>]
...
END IMAGES
DELAYS
[<key> <value>]
...
END DELAYS
DEFAULTS
[<key> <value>]
...
END DEFAULTS
# Branches section
BRANCH Main
<Statement>
...
END BRANCH
# Other branches are optional
BRANCH <name>
<Statement>
...
END BRANCH
}
function TWpcScriptParser.Parse() : TWpcScript;
begin
FCurrentLine := -1;
ParseHeaders();
ParseBranches();
Validate();
Result := FScript;
end;
{
Returns directory variable value or empty string if variable with given name doesn't exist.
}
function TWpcScriptParser.GetDirPath(DirVariableName : String) : String;
var
Index : Integer;
begin
Index := FDirsVariables.IndexOf(DirVariableName);
if (Index <> -1) then
Result := FDirsVariables.Data[Index]
else
Result := '';
end;
{
Returns image variable value or empty string if variable with given name doesn't exist.
}
function TWpcScriptParser.GetImage(ImageVariableName : String) : String;
var
Index : Integer;
begin
Index := FImagesVariables.IndexOf(ImageVariableName);
if (Index <> -1) then
Result := FImagesVariables.Data[Index]
else
Result := '';
end;
{
Returns delay variable value or 0 if variable with given name doesn't exist.
}
function TWpcScriptParser.GetDelay(DelayVariableName : String) : LongWord;
var
Index : Integer;
begin
Index := FDelaysVariables.IndexOf(DelayVariableName);
if (Index <> -1) then
Result := FDelaysVariables.Data[Index]
else
Result := 0;
end;
function TWpcScriptParser.GetDefaultDelay() : LongWord;
begin
Result := FDefaultDelay;
end;
function TWpcScriptParser.GetDefaultDelayUnits() : TWpcTimeMeasurementUnits;
begin
Result := FDefaultDelayUnits;
end;
function TWpcScriptParser.GetDefaultWallpaperStyle() : TWallpaperStyle;
begin
Result := FDefaultWallpaperStyle;
end;
{
Returns empty string if no value is set.
}
function TWpcScriptParser.GetDefaultImagesDirectory() : String;
begin
Result := FDefaultImagesDirectory;
end;
{
Parses script headers i.e. directories, images, delays, default settings.
}
procedure TWpcScriptParser.ParseHeaders();
var
LineWords : TStringList;
AWord : String;
ParseSettingsFlag : Boolean;
begin
ParseSettingsFlag := True;
while (ParseSettingsFlag) do begin
LineWords := SplitLine(GetNextLine());
AWord := UpperCase(SafeGet(LineWords, 0));
LineWords.Free();
Dec(FCurrentLine); // Returns current line into queue for future analyzing
case (AWord) of
DIRECTORIES_KEYWORD:
ParseDirsVariables();
IMAGES_KEYWORD:
ParseImagesVariables();
DELAYS_KEYWORD:
ParseDaleyVariables();
DEFAULTS_KEYWORD:
ParseDefaults();
BRANCH_KEYWORD:
ParseSettingsFlag := False; // End of settings sections, branches section is reached.
else
raise TWpcScriptParseException.Create('Unexpected word "' + AWord + '".', FCurrentLine, 0);
end;
end;
end;
{
Syntax:
DIRECTORIES
[<Directory name> <Path>]
...
END DIRECTORIES
Note, path could be absolute or relative, but result value is always absolete path.
Also path could contain previous directories variable at the begining.
}
procedure TWpcScriptParser.ParseDirsVariables();
var
Line : String;
LineWords : TStringList;
Key : String;
Value : String;
ParseDirectoriesFlag : Boolean;
begin
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [DIRECTORIES_KEYWORD]);
ParseDirectoriesFlag := True;
while (ParseDirectoriesFlag) do begin
try
Line := GetNextLine();
LineWords := SplitLine(Line);
if (not CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseVariableDefinition(Line, Key, Value);
Value := ApplyParsedDirectoriesVariables(Value);
Value := GetAbsolutePath(Value);
FDirsVariables.Add(Key, Value);
end
else begin
EnsureKeyWordsLine(LineWords, [END_KEYWORD, DIRECTORIES_KEYWORD]);
ParseDirectoriesFlag := False;
end;
finally
LineWords.Free();
end;
end;
end;
{
Syntax:
IMAGES
[<Image name> <Path to image>]
...
END IMAGES
Note, path to image could be absolute or relative, but result value is always absolete path.
Also path to image could contain directory variable at the begining.
}
procedure TWpcScriptParser.ParseImagesVariables();
var
Line : String;
LineWords : TStringList;
Key : String;
Value : String;
ParseImagesFlag : Boolean;
begin
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [IMAGES_KEYWORD]);
ParseImagesFlag := True;
while (ParseImagesFlag) do begin
try
Line := GetNextLine();
LineWords := SplitLine(Line);
if (not CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseVariableDefinition(Line, Key, Value);
Value := ApplyParsedDirectoriesVariables(Value);
Value := GetAbsolutePath(Value);
FImagesVariables.Add(Key, Value);
end
else begin
EnsureKeyWordsLine(LineWords, [END_KEYWORD, IMAGES_KEYWORD]);
ParseImagesFlag := False;
end;
finally
LineWords.Free();
end;
end;
end;
{
Syntax:
DELAYS
<Delay name> <Time>
END DELAYS
Where:
- Time: <n[Time unit]>
- Time unit: <ms|s|m|h|d>
}
procedure TWpcScriptParser.ParseDaleyVariables();
var
Line : String;
LineWords : TStringList;
Key : String;
Value : String;
ParseDelaysFlag : Boolean;
begin
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [DELAYS_KEYWORD]);
ParseDelaysFlag := True;
while (ParseDelaysFlag) do begin
try
Line := GetNextLine();
LineWords := SplitLine(Line);
if (not CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseVariableDefinition(Line, Key, Value);
FDelaysVariables.Add(Key, ParseDelayValue(Value));
end
else begin
EnsureKeyWordsLine(LineWords, [END_KEYWORD, DELAYS_KEYWORD]);
ParseDelaysFlag := False;
end;
finally
LineWords.Free();
end;
end;
end;
{
Syntax:
DEFAULTS
[DELAY <Time>]
[DELAY UNITS <Time unit>]
[WALLPAPER STYLE <Style>]
[IMAGES DIRECTORY <Path>]
END DEFAULTS
Where:
- Time: <n[Time unit]>
- Time unit: <ms|s|m|h|d>
- Style: one of styles from TWallpaperStyle
Note, that each system has support for some subset of the styles.
In case when a style is not supported by system, default style should be used.
- Images directory: absolute or ralative path to base images dir, e.g. C:\Wallpapers
Note, this prefix path is added only for relative paths.
If relative value given, base path is the path to the executable.
Note, that:
- Each value has its default in constructor.
- Default delay is used in case of WAIT
- Default delay units is used in case of WAIT X
}
procedure TWpcScriptParser.ParseDefaults();
var
LineWords : TStringList;
AWord : String;
CurrentWordIndex : Integer;
ParseDefaultsFlag : Boolean;
begin
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [DEFAULTS_KEYWORD]);
try
ParseDefaultsFlag := True;
while (ParseDefaultsFlag) do begin
LineWords := SplitLine(GetNextLine());
CurrentWordIndex := 0;
case (SafeGet(LineWords, CurrentWordIndex)) of
DELAY_KEYWORD:
begin
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), 'UNITS')) then begin
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Delay measurment unit is expected, but nothing found.', FCurrentLine, CurrentWordIndex);
FDefaultDelayUnits := ParseDelayMeasurmentUnitsValue(AWord);
end
else begin
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Default delay is expected, but nothing found.', FCurrentLine, CurrentWordIndex);
FDefaultDelay := ParseDelayValue(AWord);
end;
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
end;
WALLPAPER_KEYWORD:
begin
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), STYLE_KEYWORD)) then
raise TWpcScriptParseException.Create(STYLE_KEYWORD + ' keyword expected, but got "' + SafeGet(LineWords, CurrentWordIndex) + '".', FCurrentLine, CurrentWordIndex);
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Wallpaper style is expected, but nothing found.', FCurrentLine, CurrentWordIndex);
FDefaultWallpaperStyle := ParseWallpaperStyleValue(AWord);
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
end;
IMAGES_KEYWORD:
begin
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), DIRECTORY_KEYWORD)) then
raise TWpcScriptParseException.Create(DIRECTORY_KEYWORD + ' keyword expected, but got "' + SafeGet(LineWords, CurrentWordIndex) + '".', FCurrentLine, CurrentWordIndex);
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Path to images directory is expected, but nothing found.', FCurrentLine, CurrentWordIndex);
FDefaultImagesDirectory := ParseDirectory(LineWords, CurrentWordIndex);
if (FDefaultImagesDirectory.EndsWith(PATH_SEPARATOR)) then
Delete(FDefaultImagesDirectory, Length(FDefaultImagesDirectory), 1);
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
end;
END_KEYWORD:
begin
EnsureKeyWordsLine(LineWords, [END_KEYWORD, DEFAULTS_KEYWORD]);
ParseDefaultsFlag := False;
end
else
raise TWpcScriptParseException.Create('Unexpected word "' + SafeGet(LineWords, CurrentWordIndex) + '".', FCurrentLine);
end;
FreeAndNil(LineWords);
end;
finally
if (LineWords <> nil) then
LineWords.Free();
end;
end;
procedure TWpcScriptParser.ParseBranches();
var
Branch : TWpcBranchStatement;
NextBranch : Boolean;
begin
NextBranch := True;
while (NextBranch) do begin
Branch := ParseNextBranch();
if (Branch <> nil) then
FScript.AddBranch(Branch.GetName(), Branch)
else
NextBranch := False;
end;
end;
{
Checks that references in the script are valid.
}
procedure TWpcScriptParser.Validate();
begin
if (FScript.GetBranch(MAIN_BARNCH) = nil) then
raise TWpcScriptParseException.Create('Entry point "' + MAIN_BARNCH + '" branch not found.');
if (FScript.GetBranch(MAIN_BARNCH).GetBranchStatements().Count = 0) then
raise TWpcScriptParseException.Create('Entry point branch "' + MAIN_BARNCH + '" cannot be empty.');
ValidateBranchNames();
end;
{
Syntax:
<Variable name> <Variable value>
Note, that:
- Variable value could contain spaces.
- Variable name and Variable value could be separated with many whitespaces.
}
procedure TWpcScriptParser.ParseVariableDefinition(Line : String; var VariableName : String; var VariableValue : String);
var
ParsedVariableName : String;
ParsedVarialeValue : String;
i : Integer;
Len : Integer;
begin
Line := TrimSet(FLines[FCurrentLine], WHITESPACE_SET);
Len := Length(Line);
i := 0;
while ((i < Len) and (not (Line[i] in WHITESPACE_SET))) do
Inc(i);
ParsedVariableName := copy(Line, 0, i-1);
if (not ValidateName(ParsedVariableName)) then
raise TWpcScriptParseException.Create('Valid variable name is expectd, but "' + ParsedVariableName + '" found.', FCurrentLine);
while ((i < Len) and (Line[i] in WHITESPACE_SET)) do
Inc(i);
if (i = Len) then
raise TWpcScriptParseException.Create('Variable "' + ParsedVariableName + '" should have a value', FCurrentLine);
ParsedVarialeValue := copy(Line, i, Len - i + 1);
VariableName := ParsedVariableName;
VariableValue := ParsedVarialeValue;
end;
{
Replaces Directory variable with its value if a variable exists in the given value.
Syntax:
<[$<Directory variable>]Rest of variable value>
Example:
$WALLPAPERS/lake.png
will be translated in
/home/user/Pictures/Wallpapers/lake.png
Note, that end of variable name is file separator (e.g. / or \)
}
function TWpcScriptParser.ApplyParsedDirectoriesVariables(VariableValue : String) : String;
var
i : Integer;
VariableNameStartPos : Integer;
Len : Integer;
DirectoryVariableName : String;
ResolvedVariableValue : String;
begin
if (VariableValue[1] <> VARIABLE_START_SYMBOL) then begin
Result := VariableValue;
exit;
end;
i := Length(VARIABLE_START_SYMBOL) + 1;
Len := Length(VariableValue);
if (i > Len) then
raise TWpcScriptParseException.Create('Variable name is expected.', FCurrentLine);
VariableNameStartPos := i;
while ((i <= Len) and (VariableValue[i] <> PATH_SEPARATOR)) do begin
Inc(i);
end;
DirectoryVariableName := copy(VariableValue, VariableNameStartPos, i - VariableNameStartPos);
ResolvedVariableValue := GetDirPath(DirectoryVariableName);
if (ResolvedVariableValue = '') then
raise TWpcScriptParseException.Create('Unknown directory variable "' + DirectoryVariableName + '".', FCurrentLine);
if (i = Len) then
Result := ResolvedVariableValue
else
Result := Concat(ResolvedVariableValue, copy(VariableValue, i, Len - i + 1));
end;
{
Returns images variable value or given value if no variable found.
}
function TWpcScriptParser.ApplyParsedImagesVariables(Image : String) : String;
var
ResolvedImage : String;
begin
if (Image[1] <> VARIABLE_START_SYMBOL) then begin
Result := Image;
exit;
end;
Delete(Image, 1, Length(VARIABLE_START_SYMBOL));
ResolvedImage := GetImage(Image);
if (Image = '') then
raise TWpcScriptParseException.Create('Unknown image variable "' + Image + '".', FCurrentLine);
Result := ResolvedImage;
end;
{
Returns delay variable value or given value if no variable found.
}
function TWpcScriptParser.ApplyParsedDelayVariables(Delay : String) : String;
begin
if (Delay[1] <> VARIABLE_START_SYMBOL) then begin
Result := Delay;
exit;
end;
Delete(Delay, 1, Length(VARIABLE_START_SYMBOL));
Delay := GetDirPath(Delay);
if (Delay = '') then
raise TWpcScriptParseException.Create('Unknown delay variable "' + Delay + '".', FCurrentLine);
Result := Delay;
end;
{
Syntax:
BRANCH <Name>
[Statements]
END BRANCH
Returns branch or nil if end of script reached.
}
function TWpcScriptParser.ParseNextBranch() : TWpcBranchStatement;
var
Branch : TWpcBranchStatement;
BranchHeader : TStringList;
BranchName : String;
Line : String;
LineWords : TStringList;
StatementId : TWpcStatemetId;
BranchStatement : IWpcBaseScriptStatement;
begin
Line := GetNextLine();
if (Line = END_OF_SCRIPT) then begin
Result := nil;
exit;
end;
BranchHeader := SplitLine(Line);
try
EnsureKeyWord(BranchHeader, 0, BRANCH_KEYWORD);
if (BranchHeader.Count < 2) then
raise TWpcScriptParseException.Create('Branch name expected.', FCurrentLine);
BranchName := BranchHeader[1];
if (not ValidateName(BranchName)) then
raise TWpcScriptParseException.Create('Branch name contains not allowed characters.', FCurrentLine, 2);
if (FScript.GetBranch(BranchName) <> nil) then
raise TWpcScriptParseException.Create('Duplicate branch name "' + BranchName + '".', FCurrentLine, 2);
if (BranchHeader.Count > 2) then
raise TWpcScriptParseException.Create('Unexpected word "' + BranchHeader[2] + '" after branch name.', FCurrentLine, 3);
finally
BranchHeader.Free();
end;
Branch := TWpcBranchStatement.Create(BranchName);
try
while (True) do begin
LineWords := SplitLine(GetNextLine());
StatementId := ProbeStatementType(LineWords);
case (StatementId) of
WPC_WAIT_STATEMENT_ID:
BranchStatement := ParseWaitStatement(LineWords);
WPC_WALLPAPER_STATEMENT_ID:
BranchStatement := ParseWallpaperStatement(LineWords);
WPC_STOP_STATEMENT_ID:
BranchStatement := ParseStopStatement(LineWords);
WPC_SWITCH_BRANCH_STATEMENT_ID:
BranchStatement := ParseSwitchBranchStatement(LineWords);
WPC_USE_BRANCH_STATEMENT_ID:
BranchStatement := ParseUseBranchStatement(LineWords);
WPC_WALLPAPER_CHOOSER_STATEMENT_ID:
BranchStatement := ParseWallpaperChooserStatement(LineWords);
WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID:
BranchStatement := ParseBranchToUseChooserStatement(LineWords);
WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID:
BranchStatement := ParseBranchToSwitchChooserStatement(LineWords);
WPC_END_OF_BLOCK_STATEMENT:
break;
else
raise TWpcScriptParseException.Create('Unknown statement: ' + LineWords.CommaText, FCurrentLine);
end;
LineWords.Free();
Branch.AddStatement(BranchStatement);
end;
except
LineWords.Free();
Branch.Free();
raise;
end;
Result := Branch;
end;
{
Syntax:
WAIT [FOR <Time> | <Time>] [WITH PROBABILITY <0-100>] [<1-n> TIMES]
Note:
- when Time unit and/or Time isn't set, then default values should be used.
- Time could be a delay variable
}
function TWpcScriptParser.ParseWaitStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
function CheckAndParseDelayValue(LineWords : TStringList; Index : Integer) : LongWord;
var
AWord : String;
begin
AWord := SafeGet(LineWords, Index);
if (AWord = '') then
raise TWpcScriptParseException.Create('Delay value is expected.', FCurrentLine, Index);
Result := ParseDelayValue(ApplyParsedDelayVariables(AWord));
end;
var
WaitStatement : TWpcWaitStatement;
Delay : LongWord;
StatementProperties : TStatementProperties;
CurrentWordIndex : Integer;
begin
Delay := FComputedDefaultDelay;
StatementProperties := GetDefaultStatementProperties();
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, WAIT_KEYWORD);
if (LineWords.Count <> 1) then begin
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), FOR_KEYWORD)) then begin
Inc(CurrentWordIndex);
Delay := CheckAndParseDelayValue(LineWords, CurrentWordIndex);
end
else begin
// Handle case: WAIT <A property> (default delay is supposed)
if (ProbePropertyType(LineWords, CurrentWordIndex) = WPC_UNKNOWN_STATEMENT_PROPERTY) then
Delay := CheckAndParseDelayValue(LineWords, CurrentWordIndex)
else
Dec(CurrentWordIndex); // Push back a property word
end;
Inc(CurrentWordIndex);
StatementProperties := ParseStatementPropertiesAndEnsureEndOfLine(
[WPC_PROBABILITY_STATEMENT_PROPERY_ID, WPC_TIMES_STATEMENT_PROPERY_ID],
LineWords, CurrentWordIndex);
end;
WaitStatement := TWpcWaitStatement.Create(Delay);
WaitStatement.SetProbability(StatementProperties.Probability);
WaitStatement.SetTimes(StatementProperties.Times);
Result := WaitStatement;
end;
{
Syntax:
SET WALLPAPER <File> [STYLE <Style>] [FOR <Time>] [WITH PROBABILITY <0-100>]
Where:
- File could be:
* absolute or relative path to an image
* $DirVariable/path/image.ext
* $ImageVariable
- Style: a value from TWallpaperStyle
When Time property is not set, then no delay.
}
function TWpcScriptParser.ParseWallpaperStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
CurrentWordIndex : Integer;
begin
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, SET_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, WALLPAPER_KEYWORD);
Inc(CurrentWordIndex);
Result := ParseWallpaperStatementData(LineWords, CurrentWordIndex);
end;
{
Syntax:
STOP [WITH PROBABILITY <0-100>]
}
function TWpcScriptParser.ParseStopStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
StopStatement : TWpcStopStatement;
StatementProperties : TStatementProperties;
CurrentWordIndex : Integer;
begin
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, STOP_KEYWORD);
Inc(CurrentWordIndex);
StatementProperties := ParseStatementPropertiesAndEnsureEndOfLine(
[WPC_PROBABILITY_STATEMENT_PROPERY_ID],
LineWords, CurrentWordIndex);
StopStatement := TWpcStopStatement.Create();
StopStatement.SetProbability(StatementProperties.Probability);
Result := StopStatement;
end;
{
Syntax:
SWITCH TO BRANCH <Name> [WITH PROBABILITY <0-100>]
}
function TWpcScriptParser.ParseSwitchBranchStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
CurrentWordIndex : Integer;
begin
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, SWITCH_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, TO_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, BRANCH_KEYWORD);
Inc(CurrentWordIndex);
Result := ParseSwitchBranchStatementData(LineWords, CurrentWordIndex);
end;
{
Syntax:
USE BRANCH <Name> [WITH PROBABILITY <0-100>] [<1-n> TIMES]
}
function TWpcScriptParser.ParseUseBranchStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
CurrentWordIndex : Integer;
begin
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, USE_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, BRANCH_KEYWORD);
Inc(CurrentWordIndex);
Result := ParseUseBranchStatementData(LineWords, CurrentWordIndex);
end;
{
Syntax:
CHOOSE WALLPAPER [BY <Selector>] FROM
<Wallpaper 1 properties> <Selector> <Selector Value 1>
<Wallpaper 2 properties> <Selector> <Selector Value 2>
...
END CHOOSE
Where:
- Wallpaper n properties: the same as in Wallpaper statement, but without SET WALLPAPER prefix.
- Selectors and its values:
* WEIGHT <1-n>
* SEASON <WINTER|SPRING|SAMMER|AUTUMN>
* MOUNTH <JANUARY|...|DECEMBER | 1|...|12>
* DATE <1-31>.<1-12>
* TIME <0-23:0-59[:0-59]>
* DATETIME <1-31>.<1-12>-<0-23:0-59[:0-59]>
Note, that:
- A chooser has to have at least two options.
- Default selector is WEIGHT.
- In case of WEIGHT selector (only) the WEIGHT keyword and its value is not mandatory. Default weight is 1
Example of an option with WEIGHT selector:
$MyWallpapers/nature/forest.jpg STYLE STRETCH FOR 8m
- In case of non WEIGHT selector options are circled, for example, for chooser:
CHOOSE WALLPAPER BY TIME FROM
$RushHourCity TIME 6:30
$NightCity TIME 21:00
END CHOOSE
which was invoked at 2:00 the second option will be executed.
}
function TWpcScriptParser.ParseWallpaperChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
WallpaperChooserStatement : TWpcWallpaperChooserStatement;
WallpaperChooserStatementItem : TWpcWallpaperStatement;
Selector : TWpcSelector;
SelectorValue : TWpcSelectorValueHolder;
AWord : String;
ParseChooserItemFlag : Boolean;
ChooserItemsCounter : Integer;
CurrentWordIndex : Integer;
begin
Selector := S_WEIGHT;
// Parse chooser header
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, CHOOSE_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, WALLPAPER_KEYWORD);
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), BY_KEYWORD)) then begin
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Chooser selector expected, but nothing found.', FCurrentLine, CurrentWordIndex);
Selector := ParseSelectorValue(AWord);
end
else
Dec(CurrentWordIndex);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, FROM_KEYWORD);
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
WallpaperChooserStatement := TWpcWallpaperChooserStatement.Create(Selector);
try
// Parse chooser items
ChooserItemsCounter := 0;
try
ParseChooserItemFlag := True;
while (ParseChooserItemFlag) do begin
LineWords := SplitLine(GetNextLine());
if (CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseChooserItemFlag := False;
Dec(FCurrentLine); // Push back for future analyzing.
end
else begin
SelectorValue := ParseAndRemoveSelector(LineWords, Selector);
WallpaperChooserStatementItem := ParseWallpaperStatementData(LineWords, 0);
try
WallpaperChooserStatement.AddItem(WallpaperChooserStatementItem, SelectorValue);
except
on E : TWpcException do
raise TWpcScriptParseException.Create(E.Message, FCurrentLine);
end;
Inc(ChooserItemsCounter);
end;
FreeAndNil(LineWords);
end;
finally
if (LineWords <> nil) then
LineWords.Free();
end;
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [END_KEYWORD, CHOOSE_KEYWORD]);
if (ChooserItemsCounter < 2) then
raise TWpcScriptParseException.Create('Chooser should contain at least 2 options.', FCurrentLine);
except
WallpaperChooserStatement.Free();
raise;
end;
Result := WallpaperChooserStatement;
end;
{
Syntax:
CHOOSE BARNCH TO USE [BY <Selector>] FROM
<Use branch 1 properties> <Selector> <Selector Value 1>
<Use branch 2 properties> <Selector> <Selector Value 2>
...
END CHOOSE
Where:
- Use branch properties: the same as in Use Branch statement but without USE BRANCH prefix.
- Selectors and its values: the same as in Wallpaper Chooser statement.
}
function TWpcScriptParser.ParseBranchToUseChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
UseBranchChooserStatement : TWpcUseBranchChooserStatement;
UseBranchChooserStatementItem : TWpcUseBranchStatement;
Selector : TWpcSelector;
SelectorValue : TWpcSelectorValueHolder;
AWord : String;
ParseChooserItemFlag : Boolean;
ChooserItemsCounter : Integer;
CurrentWordIndex : Integer;
begin
Selector := S_WEIGHT;
// Parse chooser header
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, CHOOSE_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, BRANCH_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, TO_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, USE_KEYWORD);
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), BY_KEYWORD)) then begin
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Chooser selector expected, but nothing found.', FCurrentLine, CurrentWordIndex);
Selector := ParseSelectorValue(AWord);
end
else
Dec(CurrentWordIndex);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, FROM_KEYWORD);
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
UseBranchChooserStatement := TWpcUseBranchChooserStatement.Create(Selector);
try
// Parse chooser items
ChooserItemsCounter := 0;
try
ParseChooserItemFlag := True;
while (ParseChooserItemFlag) do begin
LineWords := SplitLine(GetNextLine());
if (CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseChooserItemFlag := False;
Dec(FCurrentLine); // Push back for future analyzing.
end
else begin
SelectorValue := ParseAndRemoveSelector(LineWords, Selector);
UseBranchChooserStatementItem := ParseUseBranchStatementData(LineWords, 0);
try
UseBranchChooserStatement.AddItem(UseBranchChooserStatementItem, SelectorValue);
except
on E : TWpcException do
raise TWpcScriptParseException.Create(E.Message, FCurrentLine);
end;
Inc(ChooserItemsCounter);
end;
FreeAndNil(LineWords);
end;
finally
if (LineWords <> nil) then
LineWords.Free();
end;
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [END_KEYWORD, CHOOSE_KEYWORD]);
if (ChooserItemsCounter < 2) then
raise TWpcScriptParseException.Create('Chooser should contain at least 2 options.', FCurrentLine);
except
UseBranchChooserStatement.Free();
raise;
end;
Result := UseBranchChooserStatement;
end;
{
Syntax:
CHOOSE BARNCH TO SWITCH [BY <Selector>] FROM
<Switch branch 1 properties> <Selector> <Selector Value 1>
<Switch branch 2 properties> <Selector> <Selector Value 2>
...
END CHOOSE
Where:
- Switch branch properties: the same as in Switch Branch statement but without SWITCH TO BRANCH prefix.
- Selectors and its values: the same as in Wallpaper Chooser statement.
}
function TWpcScriptParser.ParseBranchToSwitchChooserStatement(LineWords : TStringList) : IWpcBaseScriptStatement;
var
SwitchBranchChooserStatement : TWpcSwitchBranchChooserStatement;
SwitchBranchChooserStatementItem : TWpcSwitchBranchStatement;
Selector : TWpcSelector;
SelectorValue : TWpcSelectorValueHolder;
AWord : String;
ParseChooserItemFlag : Boolean;
ChooserItemsCounter : Integer;
CurrentWordIndex : Integer;
begin
Selector := S_WEIGHT;
// Parse chooser header
CurrentWordIndex := 0;
EnsureKeyWord(LineWords, CurrentWordIndex, CHOOSE_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, BRANCH_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, TO_KEYWORD);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, SWITCH_KEYWORD);
Inc(CurrentWordIndex);
if (CheckKeyWord(SafeGet(LineWords, CurrentWordIndex), BY_KEYWORD)) then begin
Inc(CurrentWordIndex);
AWord := SafeGet(LineWords, CurrentWordIndex);
if (AWord = '') then
raise TWpcScriptParseException.Create('Chooser selector expected, but nothing found.', FCurrentLine, CurrentWordIndex);
Selector := ParseSelectorValue(AWord);
end
else
Dec(CurrentWordIndex);
Inc(CurrentWordIndex);
EnsureKeyWord(LineWords, CurrentWordIndex, FROM_KEYWORD);
Inc(CurrentWordIndex);
EnsureEndOfLine(LineWords, CurrentWordIndex);
SwitchBranchChooserStatement := TWpcSwitchBranchChooserStatement.Create(Selector);
try
// Parse chooser items
ChooserItemsCounter := 0;
try
ParseChooserItemFlag := True;
while (ParseChooserItemFlag) do begin
LineWords := SplitLine(GetNextLine());
if (CheckKeyWord(SafeGet(LineWords, 0), END_KEYWORD)) then begin
ParseChooserItemFlag := False;
Dec(FCurrentLine); // Push back for future analyzing.
end
else begin
SelectorValue := ParseAndRemoveSelector(LineWords, Selector);
SwitchBranchChooserStatementItem := ParseSwitchBranchStatementData(LineWords, 0);
try
SwitchBranchChooserStatement.AddItem(SwitchBranchChooserStatementItem, SelectorValue);
except
on E : TWpcException do
raise TWpcScriptParseException.Create(E.Message, FCurrentLine);
end;
Inc(ChooserItemsCounter);
end;
FreeAndNil(LineWords);
end;
finally
if (LineWords <> nil) then
LineWords.Free();
end;
EnsureKeyWordsLineAndFreeResources(SplitLine(GetNextLine()), [END_KEYWORD, CHOOSE_KEYWORD]);
if (ChooserItemsCounter < 2) then
raise TWpcScriptParseException.Create('Chooser should contain at least 2 options.', FCurrentLine);
except
SwitchBranchChooserStatement.Free();
raise;
end;
Result := SwitchBranchChooserStatement;
end;
{
Parses Wallpaper statement data.
Syntax the same as for Wallpaper statement, but without SET WALLPAPER keywords:
<File> [STYLE <Style>] [FOR <Time>] [WITH PROBABILITY <0-100>]
}
function TWpcScriptParser.ParseWallpaperStatementData(LineWords : TStringList; Index : Integer) : TWpcWallpaperStatement;
var
WallpaperStatement : TWpcWallpaperStatement;
Image : TWpcImage;
StatementProperties : TStatementProperties;
CurrentWordIndex : Integer;
begin
CurrentWordIndex := Index;
Image := ParseImage(LineWords, CurrentWordIndex);
try
StatementProperties := ParseStatementPropertiesAndEnsureEndOfLine(
[WPC_WALLPAPER_STYLE_PROPERTY_ID, WPC_PROBABILITY_STATEMENT_PROPERY_ID, WPC_DELAY_STATEMENT_PROPERY_ID],
LineWords, CurrentWordIndex);
except
Image.Free();
raise;
end;
WallpaperStatement := TWpcWallpaperStatement.Create(Image);
WallpaperStatement.SetStyle(StatementProperties.Style);
WallpaperStatement.SetProbability(StatementProperties.Probability);
WallpaperStatement.SetDelay(StatementProperties.Delay);
Result := WallpaperStatement;
end;
{
Parses Switch Branch statement data.
Syntax the same as for Switch Branch statement, but without SWITCH BRANCH keywords:
<Name> [WITH PROBABILITY <0-100>]
}
function TWpcScriptParser.ParseSwitchBranchStatementData(LineWords : TStringList; Index : Integer) : TWpcSwitchBranchStatement;
var
SwitchBranchStatement : TWpcSwitchBranchStatement;
BranchName : String;
StatementProperties : TStatementProperties;
CurrentWordIndex : Integer;
begin
CurrentWordIndex := Index;
BranchName := SafeGet(LineWords, CurrentWordIndex);
if (BranchName = '') then
raise TWpcScriptParseException.Create('Branch name expected.', FCurrentLine, CurrentWordIndex);
if (not ValidateName(BranchName)) then
raise TWpcScriptParseException.Create('Branch name contains not allowed characters.', FCurrentLine, CurrentWordIndex);
Inc(CurrentWordIndex);
StatementProperties := ParseStatementPropertiesAndEnsureEndOfLine(
[WPC_PROBABILITY_STATEMENT_PROPERY_ID],
LineWords, CurrentWordIndex);
SwitchBranchStatement := TWpcSwitchBranchStatement.Create(BranchName);
SwitchBranchStatement.SetProbability(StatementProperties.Probability);
Result := SwitchBranchStatement;
end;
{
Parses Use Branch statement data.
Syntax the same as for Use Branch statement, but without USE BRANCH keywords:
<Name> [WITH PROBABILITY <0-100>] [<1-n> TIMES]
}
function TWpcScriptParser.ParseUseBranchStatementData(LineWords : TStringList; Index : Integer) : TWpcUseBranchStatement;
var
UseBranchStatement : TWpcUseBranchStatement;
BranchName : String;
StatementProperties : TStatementProperties;
CurrentWordIndex : Integer;
begin
CurrentWordIndex := Index;
BranchName := SafeGet(LineWords, CurrentWordIndex);
if (BranchName = '') then
raise TWpcScriptParseException.Create('Branch name expected.', FCurrentLine, CurrentWordIndex);
if (not ValidateName(BranchName)) then
raise TWpcScriptParseException.Create('Branch name contains not allowed characters.', FCurrentLine, CurrentWordIndex);
Inc(CurrentWordIndex);
StatementProperties := ParseStatementPropertiesAndEnsureEndOfLine(
[WPC_PROBABILITY_STATEMENT_PROPERY_ID, WPC_TIMES_STATEMENT_PROPERY_ID],
LineWords, CurrentWordIndex);
UseBranchStatement := TWpcUseBranchStatement.Create(BranchName);
UseBranchStatement.SetProbability(StatementProperties.Probability);
UseBranchStatement.SetTimes(StatementProperties.Times);
Result := UseBranchStatement;
end;
{
Parses directory path.
Syntax:
<Path> | "<Path>"
Where Path is absolute or relative path to a directory.
Note, that, Path could contain spaces, but in that case it should be contained into double quotes.
}
function TWpcScriptParser.ParseDirectory(LineWords : TStringList; var Index : Integer): String;
var
PathReference : String;
begin
PathReference := SafeGet(LineWords, Index);
if (PathReference = '') then
raise TWpcScriptParseException.Create('Path to a directory is expected.', FCurrentLine, Index);
// Split keeps quoted words as single one, but with its quotes.
if (PathReference[1] = QUOTE_SYMBOL) then begin
if (PathReference[Length(PathReference)] <> QUOTE_SYMBOL) then
raise TWpcScriptParseException.Create('End of quote is expexted, but end of line found.', FCurrentLine, Index);
// Remove quotes
PathReference := Copy(PathReference, 2, Length(PathReference) - 2);
end;
Inc(Index);
if (FCheckScriptResources and (not DirectoryExists(PathReference))) then
raise TWpcScriptParseException.Create('Directory "' + PathReference + '" does not exist.', FCurrentLine);
Result := PathReference;
end;
{
Parses image path for wallpaper.
Syntax:
<File> | "<File>"
Where File could be:
- absolute or relative path to an image
- $DirVariable/path/image.ext
- $ImageVariable
Note, that:
- Path could contain spaces, but in that case it should be contained into double quotes.
Example:
"$Mywallpapers/some dir/"
- After function execution Index is set to the next word after path (could be out of range).
}
function TWpcScriptParser.ParseImage(LineWords : TStringList; var Index : Integer) : TWpcImage;
var
ImageReference : String;
begin
ImageReference := SafeGet(LineWords, Index);
if (ImageReference = '') then
raise TWpcScriptParseException.Create('Reference to an image is expected.', FCurrentLine, Index);
// Split keeps quoted words as single one, but with its quotes.
if (ImageReference[1] = QUOTE_SYMBOL) then begin
if (ImageReference[Length(ImageReference)] <> QUOTE_SYMBOL) then
raise TWpcScriptParseException.Create('End of quote is expexted, but end of line found.', FCurrentLine, Index);
// Remove quotes
ImageReference := Copy(ImageReference, 2, Length(ImageReference) - 2);
end;
Inc(Index);
if (ImageReference[1] = VARIABLE_START_SYMBOL) then begin
if (Pos(PATH_SEPARATOR, ImageReference) = 0) then
// Image variable
ImageReference := ApplyParsedImagesVariables(ImageReference)
else
// Directory variable and path
ImageReference := ApplyParsedDirectoriesVariables(ImageReference);
end
else
ImageReference := GetAbsolutePath(ImageReference);
if (FCheckScriptResources and (not FileExists(ImageReference))) then
raise TWpcScriptParseException.Create('Image with "' + ImageReference + '" path does not exist.', FCurrentLine);
Result := TWpcImage.Create(ImageReference);
end;
function TWpcScriptParser.GetDefaultStatementProperties() : TStatementProperties;
var
StatementProperties : TStatementProperties;
begin
StatementProperties.Delay := 0;
StatementProperties.Probability := 100;
StatementProperties.Times := 1;
StatementProperties.Style := FDefaultWallpaperStyle;
Result := StatementProperties;
end;
{
Parses the given statement properties from the given index.
Sets index value to the next position after last recognized option.
Allowed statement properties shouldn't be empty and shouldn't contain unknown statement property.
Returns parsed values over defaults.
}
function TWpcScriptParser.ParseStatementProperties(AllowedProperties : TStatementPropertiesSet; LineWords : TStringList; var Index : Integer) : TStatementProperties;
var
StatementProperties : TStatementProperties;
AssumedNextProperty : TWpcStatementPropertyId;
begin
StatementProperties := GetDefaultStatementProperties();
while (Index < LineWords.Count) do begin
AssumedNextProperty := ProbePropertyType(LineWords, Index);
if (not (AssumedNextProperty in AllowedProperties)) then
raise TWpcScriptParseException.Create('Unexpected word "' + LineWords[Index] + '".', FCurrentLine, Index);
case (AssumedNextProperty) of
WPC_DELAY_STATEMENT_PROPERY_ID:
begin
StatementProperties.Delay := ParseDelayProperty(LineWords, Index);
Index := Index + 2;
end;
WPC_TIMES_STATEMENT_PROPERY_ID:
begin
StatementProperties.Times := ParseTimesProperty(LineWords, Index);
Index := Index + 2;
end;
WPC_PROBABILITY_STATEMENT_PROPERY_ID:
begin
StatementProperties.Probability := ParseProbabilityProperty(LineWords, Index);
Index := Index + 3;
end;
WPC_WALLPAPER_STYLE_PROPERTY_ID:
begin
StatementProperties.Style := ParseWallpaperStyleProperty(LineWords, Index);
Index := Index + 2;
end;
WPC_UNKNOWN_STATEMENT_PROPERTY:
raise TWpcUseErrorException.Create('Cannot parse unknown property. Unknown properties is not allowed.');
else
// Should never happen
raise TWpcException.Create('Cannot handle property: ' + StatementPropertyIdToStr(AssumedNextProperty));
end;
end;
Result := StatementProperties;
end;
{
The same as ParseStatementProperties, but also checks for end of line after last property.
}
function TWpcScriptParser.ParseStatementPropertiesAndEnsureEndOfLine(AllowedProperties : TStatementPropertiesSet; LineWords : TStringList; Index : Integer) : TStatementProperties;
var
StatementProperties : TStatementProperties;
begin
StatementProperties := ParseStatementProperties(AllowedProperties, LineWords, Index);
EnsureEndOfLine(LineWords, Index);
Result := StatementProperties;
end;
{
Syntax:
FOR <Time>
}
function TWpcScriptParser.ParseDelayProperty(LineWords : TStringList; WordIndex : Integer) : Integer;
var
DelayString : String;
begin
EnsureKeyWord(LineWords, WordIndex, FOR_KEYWORD);
Inc(WordIndex);
DelayString := SafeGet(LineWords, WordIndex);
if (DelayString = '') then
raise TWpcScriptParseException.Create('Valid delay expected, but nothing found.', FCurrentLine, WordIndex);
Result := ParseDelayValue(DelayString);
end;
{
Syntax:
<n> TIMES
Where n > 0
}
function TWpcScriptParser.ParseTimesProperty(LineWords : TStringList; WordIndex : Integer) : Integer;
var
TimesString : String;
begin
TimesString := SafeGet(LineWords, WordIndex);
if (TimesString = '') then
raise TWpcScriptParseException.Create(TIMES_KEYWORD + ' property expected, but nothing found.', FCurrentLine, WordIndex);
Inc(WordIndex);
EnsureKeyWord(LineWords, WordIndex, TIMES_KEYWORD);
Result := ParseTimesValue(TimesString);
end;
{
Syntax:
WITH PROBABILITY <0-100>
}
function TWpcScriptParser.ParseProbabilityProperty(LineWords : TStringList; WordIndex : Integer) : Byte;
var
ProbabilityString : String;
begin
EnsureKeyWord(LineWords, WordIndex, WITH_KEYWORD);
Inc(WordIndex);
EnsureKeyWord(LineWords, WordIndex, PROBABILITY_KEYWORD);
Inc(WordIndex);
ProbabilityString := SafeGet(LineWords, WordIndex);
if (ProbabilityString = '') then
raise TWpcScriptParseException.Create(PROBABILITY_KEYWORD + ' property expected, but value not found.', FCurrentLine, WordIndex);
Result := ParseProbabilityValue(ProbabilityString);
end;
{
Syntax:
STYLE <Style>
Where:
- Style: one of TWallpaperStyle
}
function TWpcScriptParser.ParseWallpaperStyleProperty(LineWords : TStringList; WordIndex : Integer) : TWallpaperStyle;
var
WallpaperStyleString : String;
begin
EnsureKeyWord(LineWords, WordIndex, STYLE_KEYWORD);
Inc(WordIndex);
WallpaperStyleString := SafeGet(LineWords, WordIndex);
if (WallpaperStyleString = '') then
raise TWpcScriptParseException.Create(STYLE_KEYWORD + ' property expected, but value not found.', FCurrentLine, WordIndex);
Result := ParseWallpaperStyleValue(WallpaperStyleString);
end;
{
Parses selector of given type at the end of the line.
Syntax:
<*+>+ <Selector type> <Selector value>
Note, that WEIGHT selector with default value (1) could be ommited.
}
function TWpcScriptParser.ParseAndRemoveSelector(LineWords : TStringList; Selector : TWpcSelector) : TWpcSelectorValueHolder;
function GetSelectorKeywordBySelector(Selector : TWpcSelector) : String;
begin
case (Selector) of
S_WEIGHT: Result := WEIGHT_KEYWORD;
S_SEASON: Result := SEASON_KEYWORD;
S_WEEKDAY: Result := WEEKDAY_KEYWORD;
S_MONTH: Result := MONTH_KEYWORD;
S_DATE: Result := DATE_KEYWORD;
S_TIME: Result := TIME_KEYWORD;
S_DATETIME: Result := DATETIME_KEYWORD;
end;
end;
var
Len : Integer;
SelectorValue : TWpcSelectorValueHolder;
begin
Len := LineWords.Count;
// Minimal option should consist from at least 3 words: Item value and Selector type and Selector value.
// Exception is only default WEIGHT selector which could be ommited.
if (Len < 3) then begin
if (Selector = S_WEIGHT) then begin
SelectorValue.Weight := 1; // Supposed default WEIGHT keyword and its value ommited
Result := SelectorValue;
exit;
end;
raise TWpcScriptParseException.Create('Chooser item value and valid selector expected.', FCurrentLine, Len-1);
end;
// Handle selector keyword without a value
if (SafeGet(LineWords, Len-1) = GetSelectorKeywordBySelector(Selector)) then
raise TWpcScriptParseException.Create('Selector value expected.', FCurrentLine, Len-1);
// Handle ommited WEIGHT selector and its default value.
if ((Selector = S_WEIGHT) and (SafeGet(LineWords, Len-1 - 1) <> WEIGHT_KEYWORD)) then begin
SelectorValue.Weight := 1; // Supposed default WEIGHT keyword and its value omitted
Result := SelectorValue;
exit;
end;
case (Selector) of
S_WEIGHT:
begin
EnsureSelectorKeyword(LineWords, WEIGHT_KEYWORD);
SelectorValue.Weight := ParseWeightValue(SafeGet(LineWords, Len - 1));
end;
S_SEASON:
begin
EnsureSelectorKeyword(LineWords, SEASON_KEYWORD);
SelectorValue.Sequential := ParseSeasonValue(SafeGet(LineWords, Len - 1));
end;
S_WEEKDAY:
begin
EnsureSelectorKeyword(LineWords, WEEKDAY_KEYWORD);
SelectorValue.Sequential := ParseWeekdayValue(SafeGet(LineWords, Len - 1));
end;
S_MONTH:
begin
EnsureSelectorKeyword(LineWords, MONTH_KEYWORD);
SelectorValue.Sequential := ParseMonthValue(SafeGet(LineWords, Len - 1));
end;
S_DATE:
begin
EnsureSelectorKeyword(LineWords, DATE_KEYWORD);
SelectorValue.DateTime := ParseDateValue(SafeGet(LineWords, Len - 1));
end;
S_TIME:
begin
EnsureSelectorKeyword(LineWords, TIME_KEYWORD);
SelectorValue.DateTime := ParseTimeValue(SafeGet(LineWords, Len - 1));
end;
S_DATETIME:
begin
EnsureSelectorKeyword(LineWords, DATETIME_KEYWORD);
SelectorValue.DateTime := ParseDateTimeValue(SafeGet(LineWords, Len - 1));
end;
end;
// Delete 2 last words: selector and its value. This is safe because of Len >= 3 check.
LineWords.Delete(Len - 1);
LineWords.Delete(Len - 2);
Result := SelectorValue;
end;
{
Parses sequential selector value by number or alias.
Example:
ParseSequentialNumberWithAlias('B', ('A', 'B', 'C'))
will return 2
Note, non-empty upper-case array is mandatory.
}
function TWpcScriptParser.ParseSequentialNumberWithAlias(Value : String; Aliases : Array of String) : Integer;
var
AliasesNumber : Integer;
ParsedSequentialValue : Integer;
ApperCaseAliasValue : String;
i : Integer;
begin
AliasesNumber := Length(Aliases);
if (TryStrToInt(Value, ParsedSequentialValue)) then
// Argument is just a number. Check range.
if (ParsedSequentialValue in [1..AliasesNumber]) then begin
Result := ParsedSequentialValue;
exit;
end
else
raise TWpcScriptParseException.Create('Value "' + Value + '" is out of range.', FCurrentLine);
// Value is an alias.
ApperCaseAliasValue := UpperCase(Value);
for i:=0 to (AliasesNumber - 1) do
if (ApperCaseAliasValue = Aliases[i]) then begin
Result := i + 1; // Count from 1
exit;
end;
raise TWpcScriptParseException.Create('Unknown value "' + Value + '".', FCurrentLine);
end;
{
Syntax:
<n[ms|s|m|h|d]>
Where total dalay shouldn't exceed 32 days.
Returns parsed delay in milliseconds.
Note, no spaces alowed.
}
function TWpcScriptParser.ParseDelayValue(Delay : String) : LongWord;
var
ParsedDelayValueMilliseconds : LongWord;
ParsedDelayValue : LongWord;
ParsedDelayUnits : TWpcTimeMeasurementUnits;
DelayNumberString : String;
MeasurementUnitsString : String;
i : Integer;
Len : Integer;
begin
Len := Length(Delay);
i := 1;
while ((i <= Len) and (Delay[i] in ['0'..'9'])) do
Inc(i);
DelayNumberString := copy(Delay, 1, i-1);
if (Length(DelayNumberString) < 1) then
raise TWpcScriptParseException.Create('Failed to parse delay: "' + Delay + '". A positive number is expected', FCurrentLine);
if (not TryStrToDWord(DelayNumberString, ParsedDelayValue)) then
raise TWpcScriptParseException.Create('Failed to parse delay value: "' + DelayNumberString + '".', FCurrentLine);
if (i <= Len) then begin
MeasurementUnitsString := copy(Delay, i, Len - i + 1);
ParsedDelayUnits := ParseDelayMeasurmentUnitsValue(MeasurementUnitsString);
end
else
ParsedDelayUnits := GetDefaultDelayUnits();
ParsedDelayValueMilliseconds := TWpcDelayStatementProperty.ConvertToMilliseconds(ParsedDelayValue, ParsedDelayUnits);
if (ParsedDelayValueMilliseconds > TWpcDelayStatementProperty.MAX_DELAY_VALUE) then
raise TWpcScriptParseException.Create('Too big delay: ' + Delay, FCurrentLine);
Result := ParsedDelayValueMilliseconds;
end;
{
Syntax:
<ms|s|m|h|d>
}
function TWpcScriptParser.ParseDelayMeasurmentUnitsValue(MeasurementUnits : String) : TWpcTimeMeasurementUnits;
begin
case (MeasurementUnits) of
's' : Result := SECONDS;
'm' : Result := MINUTES;
'h' : Result := HOURS;
'd' : Result := DAYS;
'ms': result := MILLISECONDS;
else
raise TWpcScriptParseException.Create('Failed to parse delay measurment units: "' + MeasurementUnits + '".', FCurrentLine);
end;
end;
{
Syntax:
<n>
Where n in 0-100
}
function TWpcScriptParser.ParseProbabilityValue(Probability : String) : Byte;
var
ParsedProbabilityValue : Integer;
begin
if (not TryStrToInt(Probability, ParsedProbabilityValue)) then
raise TWpcScriptParseException.Create('Failed to parse probability value: "' + Probability + '".', FCurrentLine);
if ((ParsedProbabilityValue < 0) or (ParsedProbabilityValue > 100)) then
raise TWpcScriptParseException.Create('Probability value should be in [0-100]', FCurrentLine);
Result := ParsedProbabilityValue;
end;
{
Syntax:
<n>
Where n >= 0
}
function TWpcScriptParser.ParseTimesValue(Times : String) : LongWord;
var
ParsedTimesValue : Integer;
begin
if (not TryStrToInt(Times, ParsedTimesValue)) then
raise TWpcScriptParseException.Create('Failed to parse times value: "' + Times + '".', FCurrentLine);
if (ParsedTimesValue < 1) then
raise TWpcScriptParseException.Create('Times value should be positive', FCurrentLine);
Result := ParsedTimesValue;
end;
{
Syntax:
<Style>
Where Style is string from TWallpaperStyle.
}
function TWpcScriptParser.ParseWallpaperStyleValue(Style : String) : TWallpaperStyle;
var
WallpaperStyle : TWallpaperStyle;
begin
WallpaperStyle := StrToWallpaperStyle(Style);
if (WallpaperStyle = UNKNOWN) then
raise TWpcScriptParseException.Create('Unknown wallpaper style "' + Style + '".', FCurrentLine);
Result := WallpaperStyle;
end;
{
Syntax:
<Selector>
Where selector is TWpcSelector.
}
function TWpcScriptParser.ParseSelectorValue(Selector : String) : TWpcSelector;
begin
case (Selector) of
WEIGHT_KEYWORD: Result := S_WEIGHT;
SEASON_KEYWORD: Result := S_SEASON;
WEEKDAY_KEYWORD: Result := S_WEEKDAY;
MONTH_KEYWORD: Result := S_MONTH;
DATE_KEYWORD: Result := S_DATE;
TIME_KEYWORD: Result := S_TIME;
DATETIME_KEYWORD: Result := S_DATETIME;
else
raise TWpcScriptParseException.Create('Unknown selector type "' + Selector + '".', FCurrentLine);
end;
end;
{
Syntax:
<n>
Where n > 0
}
function TWpcScriptParser.ParseWeightValue(Weight : String) : LongWord;
var
ParsedWeightValue : LongWord;
begin
if (not TryStrToDWord(Weight, ParsedWeightValue)) then
raise TWpcScriptParseException.Create('Failed to parse weight value: "' + Weight + '".', FCurrentLine);
if (ParsedWeightValue < 1) then
raise TWpcScriptParseException.Create('Weight selector value should be positive, bot got "' + Weight + '".', FCurrentLine);
Result := ParsedWeightValue;
end;
{
Syntax:
<1-4>|<Season name>
Where Winter is season with index 1
}
function TWpcScriptParser.ParseSeasonValue(Season : String) : Integer;
const
SEASONS : Array[1..4] of String = (
'WINTER', 'SPRING', 'SUMMER', 'AUTUMN'
);
begin
Result := ParseSequentialNumberWithAlias(Season, SEASONS);
end;
{
Syntax:
<1-7>|<Day name>
Where Sunday is day with index 1
}
function TWpcScriptParser.ParseWeekdayValue(Weekday : String) : Integer;
const
DAYS_OF_WEEK : Array[1..7] of String = (
'SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'
);
begin
Result := ParseSequentialNumberWithAlias(Weekday, DAYS_OF_WEEK);
end;
{
Syntax:
<1-12>|<Month name>
Where January is month with index 1
}
function TWpcScriptParser.ParseMonthValue(Month : String) : Integer;
const
MONTHS : Array[1..12] of String = (
'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'
);
begin
Result := ParseSequentialNumberWithAlias(Month, MONTHS);
end;
{
Syntax:
<dd.mm>
}
function TWpcScriptParser.ParseDateValue(Date : String) : TDateTime;
var
ParsedDateValue : TDateTime;
begin
if (Date.StartsWith(WPC_DATE_SEPARATOR) or Date.EndsWith(WPC_DATE_SEPARATOR)) then
raise TWpcScriptParseException.Create('Cannot parse date selector value: "' + Date + '". Both day and month should be specified.', FCurrentLine);
if (Date.CountChar(WPC_DATE_SEPARATOR) <> 1) then
raise TWpcScriptParseException.Create('Cannot parse date selector value: "' + Date + '". Date value should have only one separator', FCurrentLine);
if (not TryStrToDate(Date, ParsedDateValue)) then
raise TWpcScriptParseException.Create('Cannot parse date selector value: "' + Date + '". Invalid format.', FCurrentLine);
Result := ParsedDateValue;
end;
{
Syntax:
<hh:mm[:ss]>
}
function TWpcScriptParser.ParseTimeValue(Time : String) : TDateTime;
var
ParsedTimeValue : TDateTime;
begin
if (not TryStrToTime(Time, ParsedTimeValue)) then
raise TWpcScriptParseException.Create('Cannot parse time selector value: "' + Time + '". Invalid format.', FCurrentLine);
Result := ParsedTimeValue;
end;
{
Syntax:
<dd.mm>-<hh:mm[:ss]>
}
function TWpcScriptParser.ParseDateTimeValue(DateTime : String) : TDateTime;
var
CanonicalDateTime : String;
ParsedDateTimeValue : TDateTime;
DashIndex : Integer;
begin
// This checks is needed to prevent parsion of logically incorrect strings.
// For example '10. 10:12:53' will be parsed as 10.10.** 10:12:53
if (DateTime.CountChar(WPC_DATE_TIME_SEPARATOR) <> 1) then
raise TWpcScriptParseException.Create('Cannot parse date-time selector value: "' + DateTime + '". Date-time value should have separator', FCurrentLine);
DashIndex := Pos(WPC_DATE_TIME_SEPARATOR, DateTime);
if ((DashIndex = 1) or (DashIndex = Length(DateTime))) then
raise TWpcScriptParseException.Create('Invalid date-time selector value: "' + DateTime + '"', FCurrentLine);
if ((DateTime[DashIndex-1] = WPC_DATE_SEPARATOR) or (DateTime[DashIndex+1] = WPC_DATE_SEPARATOR) or
(DateTime[DashIndex-1] = WPC_TIME_SEPARATOR) or (DateTime[DashIndex+1] = WPC_TIME_SEPARATOR)) then
raise TWpcScriptParseException.Create('Invalid date-time selector value: "' + DateTime + '"', FCurrentLine);
CanonicalDateTime := StringReplace(DateTime, WPC_DATE_TIME_SEPARATOR, ' ', []); // To be able to use StrToDateTime function
if (not TryStrToDateTime(CanonicalDateTime, ParsedDateTimeValue)) then
raise TWpcScriptParseException.Create('Cannot parse date and time selector value: "' + DateTime + '". Invalid format.', FCurrentLine);
Result := ParsedDateTimeValue;
end;
{
Returns true if name is valid, false otherwise.
}
function TWpcScriptParser.ValidateName(Name : String) : Boolean;
var
c : Char;
begin
for c in Name do
if (not (c in ALLOWED_NAME_SYMBOLS)) then begin
Result := False;
exit;
end;
Result := True;
end;
{
Checks that all Switch Branch and Use Branch statements use existing branches.
}
procedure TWpcScriptParser.ValidateBranchNames();
procedure EnsureBranchExists(BranchName : String; BranchesNames : TStringList);
var
Line : Integer;
Index : Integer;
begin
if (BranchesNames.IndexOf(BranchName) = -1) then begin
Line := 0;
Index := 0;
SearchWordInScript(BranchName, True, Line, Index);
raise TWpcScriptParseException.Create('Specified branch "' + BranchName + '" doesn''t exist.', Line, Index);
end;
end;
var
BranchesNames : TStringList;
Statement : IWpcBaseScriptStatement;
ChooserItem : TWpcChooserItem;
i : Integer;
begin
BranchesNames := FScript.GetBranchNames();
try
for i:=0 to (BranchesNames.Count - 1) do
for Statement in FScript.GetBranch(BranchesNames[i]).GetBranchStatements() do begin
if (Statement.InheritsFrom(IWpcBranchReferrer.ClassType)) then begin
EnsureBranchExists(IWpcBranchReferrer(Statement).GetBranchName(), BranchesNames);
end
else if ((Statement.ClassType = TWpcSwitchBranchChooserStatement.ClassType) or
(Statement.ClassType = TWpcUseBranchChooserStatement.ClassType)) then begin
for ChooserItem in IWpcChooserItems(Statement).GetItems() do
EnsureBranchExists(IWpcBranchReferrer(ChooserItem.Statement).GetBranchName(), BranchesNames);
end;
end;
finally
BranchesNames.Free();
end;
end;
{
Returns specified line of the script.
In case of commentary or empty line empty string will be returned.
In case if given line number is out of range END_OF_SCRIPT will be returned.
}
function TWpcScriptParser.GetLine(LineNumber : Integer) : String;
var
Line : String;
begin
if (FCurrentLine >= FLines.Count) then begin
Result := END_OF_SCRIPT;
exit;
end;
Line := TrimSet(FLines[LineNumber], WHITESPACE_SET);
if ((Line <> '') and (Line[1] = COMMENTARY_SYMBOL)) then
Line := '';
Result := Line;
end;
{
Returns next significant (i.e. non-empty and not comment) line of the script
or END_OF_SCRIPT if end of the script is reached.
}
function TWpcScriptParser.GetNextLine() : String;
var
Line : String;
begin
repeat
Inc(FCurrentLine);
Line := GetLine(FCurrentLine);
until (Line <> '');
Result := Line;
end;
{
Returns list of words in the given line.
If incoming line is nil or empty TWpcUseErrorException will be rised.
The list contains at least one word.
A word from the list cannot be empty or nil.
The list should be freed by invoker.
}
function TWpcScriptParser.SplitLine(Line : String) : TStringList;
var
LineWords : TStringList;
begin
if ((Line = '') or (@Line = nil)) then
raise TWpcUseErrorException.Create('Cannot split empty line. Line number: ' + IntToStr(FCurrentLine));
if (Line = END_OF_SCRIPT) then
raise TWpcScriptParseException.Create('Unxpected end of script.', FCurrentLine);
LineWords := TStringList.Create();
ExtractStrings(WHITESPACE_SET, WHITESPACE_SET, PChar(Line), LineWords);
Result := LineWords;
end;
{
Probes statement from given line words.
Returns:
- Statement ID if statement detected
- WPC_END_OF_BLOCK_STATEMENT if the line starts with END key word
- WPC_UNKNOWN_STATEMENT if unknown
}
function TWpcScriptParser.ProbeStatementType(LineWords : TStringList) : TWpcStatemetId;
begin
case (UpperCase(SafeGet(LineWords, 0))) of
SET_KEYWORD:
Result := WPC_WALLPAPER_STATEMENT_ID;
WAIT_KEYWORD:
Result := WPC_WAIT_STATEMENT_ID;
SWITCH_KEYWORD:
Result := WPC_SWITCH_BRANCH_STATEMENT_ID;
USE_KEYWORD:
Result := WPC_USE_BRANCH_STATEMENT_ID;
STOP_KEYWORD:
Result := WPC_STOP_STATEMENT_ID;
CHOOSE_KEYWORD:
begin
case (UpperCase(SafeGet(LineWords, 1))) of
WALLPAPER_KEYWORD:
Result := WPC_WALLPAPER_CHOOSER_STATEMENT_ID;
BRANCH_KEYWORD:
case (UpperCase(SafeGet(LineWords, 3))) of
SWITCH_KEYWORD:
Result := WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID;
USE_KEYWORD:
Result := WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID;
else
Result := WPC_UNKNOWN_STATEMENT;
end
else
Result := WPC_UNKNOWN_STATEMENT;
end
end;
END_KEYWORD:
Result := WPC_END_OF_BLOCK_STATEMENT;
else
Result := WPC_UNKNOWN_STATEMENT;
end;
end;
{
Probes statement property type at given index.
Returns:
- Property ID if property recognized
- WPC_UNKNOWN_STATEMENT_PROPERTY if unknown
}
function TWpcScriptParser.ProbePropertyType(LineWords : TStringList; WordIndex : Integer) : TWpcStatementPropertyId;
begin
case (UpperCase(SafeGet(LineWords, WordIndex))) of
FOR_KEYWORD:
Result := WPC_DELAY_STATEMENT_PROPERY_ID;
WITH_KEYWORD:
Result := WPC_PROBABILITY_STATEMENT_PROPERY_ID;
STYLE_KEYWORD:
Result := WPC_WALLPAPER_STYLE_PROPERTY_ID;
else begin
case (UpperCase(SafeGet(LineWords, WordIndex + 1))) of
TIMES_KEYWORD:
Result := WPC_TIMES_STATEMENT_PROPERY_ID;
else
Result := WPC_UNKNOWN_STATEMENT_PROPERTY;
end;
end;
end;
end;
function TWpcScriptParser.IsWordANumber(AWord : String) : Boolean;
var
i : Integer;
begin
for i:=1 to Length(AWord) do
if (not (AWord[i] in ['0'..'9'])) then begin
Result := False;
exit;
end;
Result := True;
end;
{
Helper method to check mandatory keywords.
The first parameter is a value to check.
The second parameter have to be in upper case.
}
function TWpcScriptParser.CheckKeyWord(Given : String; Expected : String) : Boolean;
begin
Result := UpperCase(Given) = Expected;
end;
{
Checks that line has specified keyword at given index.
Note, resources should be freed by invoker.
}
procedure TWpcScriptParser.EnsureKeyWord(LineWords : TStringList; Index : Integer; ExpectedKeyWord : String);
var
AWord : String;
begin
AWord := SafeGet(LineWords, Index);
if (AWord = '') then
raise TWpcScriptParseException.Create(ExpectedKeyWord + '" keyword expected, but nothing found', FCurrentLine, Index);
if (UpperCase(AWord) <> ExpectedKeyWord) then
raise TWpcScriptParseException.Create(ExpectedKeyWord + '" keyword expected, but got "' + AWord + '".', FCurrentLine, Index);
end;
{
Checks that line consists only from given keywords.
Note, resources should be freed by invoker.
}
procedure TWpcScriptParser.EnsureKeyWordsLine(GivenKeyWords: TStringList;
ExpectedKeyWords: array of String);
var
i : Integer;
begin
for i:=0 to (Length(ExpectedKeyWords) - 1) do begin
EnsureKeyWord(GivenKeyWords, i, ExpectedKeyWords[i]);
end;
EnsureEndOfLine(GivenKeyWords, i+1);
end;
{
Checks that line consists only from given keywords.
Note, this method free resources despite check result.
}
procedure TWpcScriptParser.EnsureKeyWordsLineAndFreeResources(
GivenKeyWords: TStringList; ExpectedKeyWords: array of String);
begin
try
EnsureKeyWordsLine(GivenKeyWords, ExpectedKeyWords);
finally
GivenKeyWords.Free();
end;
end;
{
Checks second from the line end keyword.
}
procedure TWpcScriptParser.EnsureSelectorKeyword(LineWords : TStringList; SelectorKeyword : String);
var
SecondWordFromLineEndIndex : Integer;
i : Integer;
begin
SecondWordFromLineEndIndex := LineWords.Count-1 - 1; // -1 because indexes are counted from 0
if (not CheckKeyWord(SafeGet(LineWords, SecondWordFromLineEndIndex), SelectorKeyword)) then begin
// syntax error
for i:=SecondWordFromLineEndIndex downto 1 do
if (CheckKeyWord(SafeGet(LineWords, i), SelectorKeyword)) then
raise TWpcScriptParseException.Create('Selector keyword "' + SelectorKeyword + '" should be second from the end of an option line.', FCurrentLine, i);
// no selector keyword found
raise TWpcScriptParseException.Create(SelectorKeyword + ' selector expected, but "' + SafeGet(LineWords, SecondWordFromLineEndIndex + 1) + '" found.', FCurrentLine, SecondWordFromLineEndIndex + 1); // +1 to point on the last word in line
end;
end;
{
Checks that index points after the last word of the given line, i.e. no more words in the line.
Note, resources should be freed by invoker.
}
procedure TWpcScriptParser.EnsureEndOfLine(LineWords : TStringList; WordIndex : Integer);
begin
if (SafeGet(LineWords, WordIndex) <> '') then
raise TWpcScriptParseException.Create('Unexpected word "' + SafeGet(LineWords, WordIndex) + '".', FCurrentLine, WordIndex);
end;
{
Returns item with specified index from the given list
or empty string if the list doesn't have a word under given index.
}
function TWpcScriptParser.SafeGet(LineWords : TStringList; Index : Integer) : String;
begin
if ((Index < LineWords.Count) and (Index >= 0)) then
Result := LineWords[Index]
else
Result := '';
end;
{
Searches for specified word in whole script.
Line and Index parameters sets start search point.
Returns first occurrence or (-1,-1) if the given word not found.
}
procedure TWpcScriptParser.SearchWordInScript(TheWord : String; CaseSensitive : Boolean; var Line : Integer; var Index : Integer);
var
LineString : String;
LineWords : TStringList;
AWord : String;
begin
if (not CaseSensitive) then
TheWord := UpperCase(TheWord);
while (True) do begin
LineString := GetLine(Line);
if (LineString = END_OF_SCRIPT) then
break;
if (LineString <> '') then begin
LineWords := SplitLine(LineString);
try
while (Index < (LineWords.Count - 1)) do begin
if (CaseSensitive) then
AWord := LineWords[Index]
else
AWord := UpperCase(LineWords[Index]);
if (AWord = TheWord) then
// Specified word found, current values of Line and Index points to it.
exit;
Inc(index);
end;
finally
LineWords.Free();
end;
end;
// Prepare for the next iteration
Inc(Line);
Index := 0;
end;
// End of script is reached, given word not found.
Line := -1;
Index := -1;
end;
initialization
// Set default date and time format
DefaultFormatSettings.DateSeparator := WPC_DATE_SEPARATOR;
DefaultFormatSettings.TimeSeparator := WPC_TIME_SEPARATOR;
end.
|
unit Write810File;
interface
uses SysUtils, DB, Dialogs, Classes,EDI810Object,DataModule;
type
T810EDIFile = class(TObject)
private
fedi810:T810EDI;
public
constructor Create(EDI810:T810EDI); overload;
procedure Execute();
end;
implementation
constructor T810EDIFile.Create(EDI810:T810EDI);
begin
fedi810:=EDI810;
end;
procedure T810EDIFile.Execute();
var
EDI810:T810EDI;
i:integer;
fcf:TextFile;
line:string;
begin
// Do Invoice Process
try
if Data_Module.fiGenerateEDI.AsBoolean then
begin
{
// Generate True EDI files
//
// Check for Normal 810 Creates (ASN complete)
//
Data_Module.EDI810DataSet.Close;
Data_Module.EDI810DataSet.CommandText:='REPORT_EDI810';
Data_Module.EDI810DataSet.Parameters.Clear;
Data_Module.EDI810DataSet.Open;
if Data_Module.EDI810DataSet.RecordCount > 0 then
begin
if MessageDlg('Create INVOICE Files now?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
ProcessPanel.Visible:=TRUE;
application.ProcessMessages;
while not Data_Module.EDI810DataSet.Eof do
begin
Data_Module.ASN:=Data_Module.EDI810DataSet.FieldByName('ASNid').AsInteger;
EDI810:=T810EDI.Create;
EDI810.EIN:=-1;
if EDI810.Execute then
begin
Data_Module.SiteDataSet.Close;
Data_Module.SiteDataSet.Open;
Data_Module.EIN:=Data_Module.SiteDataSet.fieldByName('SiteEIN').AsInteger;
AssignFile(fcf, Data_Module.fiEDIOut.AsString+'\810'+copy(EDI810.PickUpDate,5,4)+'.txt');
Rewrite(fcf);
// Loop through report and save
for i:=0 to EDI810.EDIRecord.Count-1 do
begin
line:=EDI810.EDIRecord[i];
Writeln(fcf,line);
end;
CloseFile(fcf);
try
Data_Module.UpdateReportCommand.CommandType:=cmdStoredProc;
Data_Module.UpdateReportCommand.CommandText:='AD_UpdateEIN';
Data_Module.UpdateReportCommand.Execute;
if not Data_Module.InsertINVInfo then
ShowMessage('Failed on EIN update after EDI810 create');
except
on e:exception do
begin
ShowMessage('Failed on create status after EDI810 create'+e.Message);
end;
end;
end
else
ShowMessage('Unable to create EDI810 for ('+EDI810.PickUpDate+')');
EDI810.Free;
end;
ProcessPanel.Visible:=FALSE;
ShowMessage('Create EDI 810 files complete');
end;
end
else
begin
ShowMessage('No Invoice files to create');
end;
end
else
begin
// Generate TAI EDI files
DateSelectDlg:=TDateSelectDlg.Create(self);
DateSelectDlg.DoSupplier:=FALSE;
DateSelectDlg.DoLogistics:=FALSE;
DateSelectDlg.DoPartNumber:=FALSE;
DateSelectDlg.execute;
if not DateSelectDlg.Cancel then
begin
DailyBuildtotalForm:=TDailyBuildtotalForm.Create(self);
DailyBuildTotalForm.FormMode:=fmINVOICE;
DailyBuildTotalForm.FromDate:=DateSelectDlg.FromDate;
DailyBuildTotalForm.ToDate:=DateSelectDlg.ToDate;
DailyBuildtotalForm.Execute;
DailyBuildtotalForm.Free;
end;}
end;
except
on e:exception do
begin
ShowMessage('Unable to create INVOICE, '+e.Message);
end;
end;
end;
end.
|
unit BCEditor.Consts;
interface {********************************************************************}
uses
Graphics;
type
TBCEditorAnsiCharSet = set of AnsiChar;
const
BCEDITOR_BOOKMARKS = 10;
BCEDITOR_CODEFOLDING_COLLAPSEDMARK: PChar = '...';
{ Characters }
BCEDITOR_UNDERSCORE = '_';
BCEDITOR_CODE_FOLDING_VALID_CHARACTERS = ['\', '@', '_'];
BCEDITOR_REAL_NUMBER_CHARS = ['0' .. '9', 'e', 'E', '.'];
BCEDITOR_NONE_CHAR = #0;
BCEDITOR_BACKSPACE_CHAR = #8;
BCEDITOR_TAB_CHAR = #9;
BCEDITOR_LINEFEED = #10;
BCEDITOR_CARRIAGE_RETURN = #13;
BCEDITOR_CARRIAGE_RETURN_KEY = 13;
BCEDITOR_ESCAPE_KEY = 27;
BCEDITOR_SPACE_CHAR = #32;
BCEDITOR_EXCLAMATION_MARK = #33;
BCEDITOR_CTRL_BACKSPACE = #127;
BCEDITOR_WORD_BREAK_CHARACTERS = ['.', ',', ';', ':', '"', '''', '!', '?', '[', ']', '(', ')', '{', '}', '^',
'=', '+', '-', '*', '/', '\', '|', ' '];
BCEDITOR_EXTRA_WORD_BREAK_CHARACTERS = ['´', '`', '°', '&', '$', '@', '§', '%', '#', '~', '<', '>'];
BCEDITOR_EMPTY_CHARACTERS = [BCEDITOR_NONE_CHAR, BCEDITOR_TAB_CHAR, BCEDITOR_SPACE_CHAR];
BCEDITOR_DEFAULT_DELIMITERS: TBCEditorAnsiCharSet = ['*', '/', '+', '-', '=', '\', '|', '&', '(', ')', '[', ']', '{', '}',
'`', '~', '!', '@', ',', '$', '%', '^', '?', ':', ';', '''', '"', '.', '>', '<', '#'];
BCEDITOR_ABSOLUTE_DELIMITERS: TBCEditorAnsiCharSet = [BCEDITOR_NONE_CHAR, BCEDITOR_TAB_CHAR, BCEDITOR_LINEFEED,
BCEDITOR_CARRIAGE_RETURN, BCEDITOR_SPACE_CHAR];
{ Unicode control characters }
BCEditor_UCC_RS = #$001E;
BCEditor_UCC_US = #$001F;
BCEditor_UCC_LRE = #$202A;
BCEditor_UCC_RLE = #$202B;
BCEditor_UCC_ZWNJ = #$200C;
BCEditor_UCC_ZWJ = #$200D;
BCEditor_UCC_LRM = #$200E;
BCEditor_UCC_RLM = #$200F;
BCEditor_UCC_ISS = #$206A;
BCEditor_UCC_ASS = #$206B;
BCEditor_UCC_PDF = #$202C;
BCEditor_UCC_LRO = #$202D;
BCEditor_UCC_RLO = #$202E;
BCEditor_UCC_IAFS = #$206C;
BCEditor_UCC_AAFS = #$206D;
BCEditor_UCC_NADS = #$206E;
BCEditor_UCC_NODS = #$206F;
{ Highlighter attribute elements }
BCEDITOR_ATTRIBUTE_ELEMENT_EDITOR = 'Editor';
BCEDITOR_ATTRIBUTE_ELEMENT_COMMENT = 'Comment';
BCEDITOR_ATTRIBUTE_ELEMENT_STRING = 'String';
{ Resource file icons }
BCEDITOR_SYNCEDIT = 'BCEDITORSYNCEDIT';
var
BCEditor_UCCs: array of Char;
implementation {***************************************************************}
initialization
SetLength(BCEditor_UCCs, 17);
BCEditor_UCCs[0] := BCEditor_UCC_RS;
BCEditor_UCCs[1] := BCEditor_UCC_US;
BCEditor_UCCs[2] := BCEditor_UCC_LRE;
BCEditor_UCCs[3] := BCEditor_UCC_RLE;
BCEditor_UCCs[4] := BCEditor_UCC_ZWNJ;
BCEditor_UCCs[5] := BCEditor_UCC_ZWJ;
BCEditor_UCCs[6] := BCEditor_UCC_LRM;
BCEditor_UCCs[7] := BCEditor_UCC_RLM;
BCEditor_UCCs[8] := BCEditor_UCC_ISS;
BCEditor_UCCs[9] := BCEditor_UCC_ASS;
BCEditor_UCCs[10] := BCEditor_UCC_PDF;
BCEditor_UCCs[11] := BCEditor_UCC_LRO;
BCEditor_UCCs[12] := BCEditor_UCC_RLO;
BCEditor_UCCs[13] := BCEditor_UCC_IAFS;
BCEditor_UCCs[14] := BCEditor_UCC_AAFS;
BCEditor_UCCs[15] := BCEditor_UCC_NADS;
BCEditor_UCCs[16] := BCEditor_UCC_NODS;
end.
|
unit disk_file_format;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}main_engine,misc_functions,dialogs;
function dsk_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
procedure clear_disk(drvnum:byte);
procedure check_protections(drvnum:byte;hay_multi:boolean);
function oric_dsk_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
type
disc_header_type=record
nbof_tracks:byte;
nbof_heads:byte;
track_size_table:array[0..1,0..$cb] of byte;
end;
sector_info_type=record
track:byte;
head:byte;
sector:byte;
sector_size:byte;
status1:byte;
status2:byte;
data_length:word;
posicion_data:word;
multi:boolean;
end;
track_type=record
track_number:byte;
side_number:byte;
data_rate:byte;
recording_mode:byte;
sector_size:byte;
number_sector:byte;
GAP3:byte;
filler:byte;
track_lenght:word;
data:pbyte;
sector:array[0..63] of sector_info_type;
end;
DskImg=record
ImageName:string;
abierto:boolean;
track_actual:byte;
cara_actual:byte;
sector_actual:byte;
sector_read_track:byte;
protegido:boolean;
DiskHeader:disc_header_type;
extended:boolean;
Tracks:array[0..1,0..82] of track_type;
cont_multi,max_multi:byte;
end;
var
dsk:array[0..1] of DskImg;
implementation
uses principal,sysutils,lenslock;
type
tdsk_header=packed record
magic:array[0..7] of ansichar; //Realmente son mas, pero solo hay que mirar el 'EXTENDED' (no siempre se sigue el estandar)
unused:array[0..25] of byte;
creator:array[0..13] of ansichar;
tracks:byte;
sides:byte;
track_size:word;
track_size_map:array[0..203] of byte;
end;
tdsk_track=packed record
magic:array[0..9] of ansichar; //El estandar termina con chr(13)+chr(10), pero no lo siguen algunos...
unused1:array[0..5] of byte;
track:byte; //No siempre ponen el numero de track correcto... WTF???
side:byte;
data_rate:byte;
record_mode:byte;
sector_size:byte;
number_of_sectors:byte;
gap:byte;
filler:byte;
end;
tdsk_sector=packed record
track:byte;
side:byte;
id:byte;
size:byte;
status1:byte;
status2:byte;
length:word;
end;
function dsk_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
var
puntero,ptemp:pbyte;
posicion,tempw:word;
estandar,primer_sector,salir,hay_multi:boolean;
dsk_header:^tdsk_header;
dsk_track:^tdsk_track;
dsk_sector:^tdsk_sector;
f,side_num,track_num:byte;
longi,track_long,long_temp:dword;
sector_count:integer;
begin
dsk_format:=false;
if datos=nil then exit;
getmem(dsk_header,sizeof(tdsk_header));
getmem(dsk_track,sizeof(tdsk_track));
getmem(dsk_sector,sizeof(tdsk_sector));
clear_disk(drvnum);
puntero:=datos;
longi:=0;
hay_multi:=false;
copymemory(dsk_header,datos,$100);
inc(puntero,$100);inc(longi,$100);
dsk[DrvNum].protegido:=false;
//Disk Header
if dsk_header.magic='MV - CPC' then estandar:=true
else if dsk_header.magic='EXTENDED' then estandar:=false
else begin
freemem(dsk_track);
freemem(dsk_header);
freemem(dsk_sector);
exit;
end;
dsk[drvnum].DiskHeader.nbof_tracks:=dsk_header.tracks;
dsk[drvnum].DiskHeader.nbof_heads:=dsk_header.sides;
f:=0;
for track_num:=0 to (dsk_header.tracks-1) do begin
for side_num:=0 to (dsk_header.sides-1) do begin
dsk[DrvNum].DiskHeader.track_size_table[side_num,track_num]:=dsk_header.track_size_map[f];
f:=f+1;
end;
end;
//Disk Tracks
while longi<longi_ini do begin
//Me posiciono en los datos, la cabecera del track siempre ocupa 256bytes
ptemp:=puntero;
copymemory(dsk_track,ptemp,24);
inc(ptemp,24);
if dsk_track.magic<>'Track-Info' then begin
clear_disk(drvnum);
freemem(dsk_track);
freemem(dsk_header);
freemem(dsk_sector);
exit;
end;
primer_sector:=true;
posicion:=0;
//Sectores
for sector_count:=0 to (dsk_track.number_of_sectors-1) do begin
copymemory(dsk_sector,ptemp,8);
inc(ptemp,8);
//Comprobar el track que es...
if primer_sector then begin
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].track_number:=dsk_track.track;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].side_number:=dsk_track.side;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].data_rate:=dsk_track.data_rate;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].recording_mode:=dsk_track.record_mode;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].sector_size:=dsk_track.sector_size;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].number_sector:=dsk_track.number_of_sectors;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].GAP3:=dsk_track.gap;
dsk[DrvNum].Tracks[dsk_track.side,dsk_track.track].filler:=dsk_track.filler;
primer_sector:=false;
end;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].track:=dsk_sector.track;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].head:=dsk_sector.side;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].sector:=dsk_sector.id;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].sector_size:=dsk_sector.size;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].status1:=dsk_sector.status1;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].status2:=dsk_sector.status2;
//Calcular la longitud del sector
if not(estandar) then dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].data_length:=dsk_sector.length
else dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].data_length:=1 shl (dsk_sector.size+7);
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].posicion_data:=posicion;
inc(posicion,dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].data_length);
//Weak sectors
tempw:=dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].data_length div (1 shl (dsk_sector.size+7));
if (tempw>1) then begin
if tempw>4 then tempw:=4;
dsk[drvnum].Tracks[dsk_track.side,dsk_track.track].sector[sector_count].multi:=true;
dsk[drvnum].cont_multi:=tempw;
dsk[drvnum].max_multi:=tempw;
hay_multi:=true;
end;
end; //sectors
//Primero muevo el puntero hasta el final de la cabecera, que siempre ocupa 256bytes
inc(puntero,$100);inc(longi,$100);
//Me guardo la cara y el track del disco, que ahora los voy a borrar...
side_num:=dsk_track.side;
track_num:=dsk_track.track;
//Ahora la longitud del track... No encuentro una forma decente de cuadrar la longitud del fichero con lo que dicen los datos... busco directemente
ptemp:=puntero;
salir:=false;
track_long:=0;
long_temp:=longi;
while not(salir) do begin
copymemory(dsk_track,ptemp,24);
if dsk_track.magic='Track-Info' then begin
salir:=true;
end else begin
if long_temp=longi_ini then begin
salir:=true
end else begin
track_long:=track_long+1;
long_temp:=long_temp+1;
inc(ptemp);
end;
end;
end;
if dsk[DrvNum].DiskHeader.track_size_table[side_num,track_num]<>0 then begin
dsk[drvnum].Tracks[side_num,track_num].track_lenght:=256*(dsk[DrvNum].DiskHeader.track_size_table[side_num,track_num]-1);
end else begin
if not(estandar) then dsk[drvnum].Tracks[side_num,track_num].track_lenght:=track_long
else dsk[drvnum].Tracks[side_num,track_num].track_lenght:=dsk_header.track_size;
end;
getmem(dsk[drvnum].Tracks[side_num,track_num].data,track_long);
copymemory(dsk[drvnum].Tracks[side_num,track_num].data,puntero,track_long);
inc(puntero,track_long);
inc(longi,track_long);
end; //del while
check_protections(drvnum,hay_multi);
dsk[drvnum].abierto:=true;
dsk_format:=true;
freemem(dsk_sector);
freemem(dsk_track);
freemem(dsk_header);
end;
procedure clear_disk(drvnum:byte);
var
f,h,g:byte;
begin
if not(dsk[drvnum].abierto) then exit;
dsk[drvnum].cont_multi:=0;
dsk[drvnum].max_multi:=0;
for g:=0 to 1 do begin
for f:=0 to dsk[drvnum].DiskHeader.nbof_tracks do begin
dsk[drvnum].Tracks[g,f].track_number:=0;
dsk[drvnum].Tracks[g,f].side_number:=0;
dsk[drvnum].Tracks[g,f].data_rate:=0;
dsk[drvnum].Tracks[g,f].sector_size:=0;
dsk[drvnum].Tracks[g,f].GAP3:=0;
dsk[drvnum].Tracks[g,f].track_lenght:=0;
if dsk[drvnum].Tracks[g,f].data<>nil then begin
freemem(dsk[drvnum].Tracks[g,f].data);
dsk[drvnum].Tracks[g,f].data:=nil;
end;
for h:=0 to dsk[drvnum].Tracks[g,f].number_sector do begin
dsk[drvnum].Tracks[g,f].sector[h].track:=0;
dsk[drvnum].Tracks[g,f].sector[h].head:=0;
dsk[drvnum].Tracks[g,f].sector[h].sector_size:=0;
dsk[drvnum].Tracks[g,f].sector[h].status1:=0;
dsk[drvnum].Tracks[g,f].sector[h].status2:=0;
dsk[drvnum].Tracks[g,f].sector[h].data_length:=0;
dsk[drvnum].Tracks[g,f].sector[h].posicion_data:=0;
dsk[drvnum].Tracks[g,f].sector[h].sector:=0;
dsk[drvnum].Tracks[g,f].sector[h].multi:=false;
dsk[drvnum].Tracks[g,f].sector[h].posicion_data:=0;
end;
dsk[drvnum].Tracks[g,f].number_sector:=0;
end;
end;
dsk[drvnum].abierto:=false;
dsk[drvnum].DiskHeader.nbof_tracks:=0;
dsk[drvnum].DiskHeader.nbof_heads:=0;
dsk[drvnum].track_actual:=0;
dsk[drvnum].cara_actual:=0;
dsk[drvnum].sector_actual:=0;
fillchar(dsk[drvnum].DiskHeader.track_size_table,408,0);
end;
procedure check_protections(drvnum:byte;hay_multi:boolean);
var
tempdw:dword;
puntero,ptemp,ptemp2,ptemp3:pbyte;
h,cont:word;
cadena,cadena2:string;
sp3_presente:boolean;
f:byte;
begin
case main_vars.tipo_maquina of
8,9:begin //Comprobar algunas protecciones para poder parchearlas...
if dsk[drvnum].Tracks[0,0].data<>nil then tempdw:=calc_crc(dsk[drvnum].Tracks[0,0].data,dsk[drvnum].Tracks[0,0].sector[0].data_length)
else exit;
case tempdw of
$8c817e25,$4b616c83:dsk[drvnum].Tracks[0,40].sector[6].sector_size:=2; //Titus the fox
$57a3276f:dsk[drvnum].Tracks[0,39].sector[10].sector_size:=0; //Prehistorik
$f05fe06e:dsk[drvnum].Tracks[0,39].sector[0].sector_size:=2; //Prehistorik alt
$31388451:begin // Tomahawk
lenslok.indice:=5;
lenslock1.Show;
end;
$23a68c26:begin //Graphic Adventure Creator
lenslok.indice:=7;
lenslock1.Show;
end;
$4c23dda4:begin // Art Studio
lenslok.indice:=1;
lenslock1.Show;
end;
end;
if lenslock1.Showing then lenslock1.combobox1.ItemIndex:=lenslok.indice;
end;
2:begin //Comprobar SpeedLock +3
puntero:=dsk[drvnum].Tracks[0,0].data;
cadena2:='SPEEDLOCK';
cadena:='';
for h:=0 to (dsk[drvnum].Tracks[0,0].sector[0].data_length-1) do begin
cadena:=cadena+char(puntero^);
inc(puntero);
end;
sp3_presente:=pos(cadena2,cadena)<>0;
if ((sp3_presente) and not(hay_multi)) then begin
//main_vars.mensaje_general:='SpeedLock +3 Simulated';
dsk[drvnum].Tracks[0,0].sector[1].multi:=true;
dsk[drvnum].cont_multi:=3;
dsk[drvnum].max_multi:=3;
//Ahora reago todos los datos
getmem(ptemp3,dsk[drvnum].Tracks[0,0].track_lenght);
ptemp:=ptemp3;
//Guardo los viejos
copymemory(ptemp,dsk[drvnum].Tracks[0,0].data,dsk[drvnum].Tracks[0,0].track_lenght);
//Libero los datos antiguos
freemem(dsk[drvnum].Tracks[0,0].data);
dsk[drvnum].Tracks[0,0].data:=nil;
//Creo los nuevos
getmem(dsk[drvnum].Tracks[0,0].data,dsk[drvnum].Tracks[0,0].track_lenght+(dsk[drvnum].Tracks[0,0].sector[1].data_length*2));
//Muevo el primer sector
cont:=0;
ptemp2:=dsk[drvnum].Tracks[0,0].data;
copymemory(ptemp2,ptemp,dsk[drvnum].Tracks[0,0].sector[0].data_length);
inc(ptemp,dsk[drvnum].Tracks[0,0].sector[0].data_length);
inc(ptemp2,dsk[drvnum].Tracks[0,0].sector[0].data_length);
inc(cont,dsk[drvnum].Tracks[0,0].sector[0].data_length);
//Arreglo el segundo
//Lo copio, pero dejo el puntero a los datos para copiar los 256 primeros bytes
copymemory(ptemp2,ptemp,dsk[drvnum].Tracks[0,0].sector[1].data_length);
inc(ptemp2,dsk[drvnum].Tracks[0,0].sector[1].data_length);
inc(cont,dsk[drvnum].Tracks[0,0].sector[1].data_length);
for f:=0 to 1 do begin
//Copio los 256 primeros datos
copymemory(ptemp2,ptemp,256);
inc(ptemp2,256);
//Me invento el resto
for h:=0 to 255 do begin
ptemp2^:=random(256);
inc(ptemp2);
end;
inc(cont,dsk[drvnum].Tracks[0,0].sector[1].data_length);
end;
//Paso al sector 2
inc(ptemp,dsk[drvnum].Tracks[0,0].sector[1].data_length);
//Y los ultimos sectores arreglando la pos relativa dentro del track
for f:=2 to (dsk[drvnum].Tracks[0,0].number_sector-1) do begin
dsk[drvnum].Tracks[0,0].sector[f].posicion_data:=cont;
copymemory(ptemp2,ptemp,dsk[drvnum].Tracks[0,0].sector[f].data_length);
inc(ptemp,dsk[drvnum].Tracks[0,0].sector[f].data_length);
inc(ptemp2,dsk[drvnum].Tracks[0,0].sector[f].data_length);
inc(cont,dsk[drvnum].Tracks[0,0].sector[f].data_length);
end;
freemem(ptemp3);
end;
end;
end;
end;
type
tmfm_header=record
firma:array[0..7] of ansichar;
side:dword;
track:dword;
sec_geo:dword;
trash:array[0..235] of byte;
end;
tmfm_sector=record
sync:array[0..14] of byte;
info:byte;
ntrack:byte;
nside:byte;
nsector:byte;
nsector_size:byte;
crc:word;
sync2:array[0..21] of byte;
end;
function oric_dsk_format(DrvNum:byte;longi_ini:dword;datos:pbyte):boolean;
var
mfm_header:^tmfm_header;
mfm_sector:^tmfm_sector;
puntero:pbyte;
longi,track_long:integer;
f,h,g:byte;
wtemp:word;
datos_track:array[0..6399] of byte;
ptemp,ptemp2:pbyte;
begin
oric_dsk_format:=false;
if datos=nil then exit;
getmem(mfm_header,sizeof(tmfm_header));
getmem(mfm_sector,sizeof(tmfm_sector));
clear_disk(drvnum);
puntero:=datos;
longi:=0;
copymemory(mfm_header,datos,$100);
inc(puntero,$100);inc(longi,$100);
dsk[DrvNum].protegido:=false;
if mfm_header.firma='MFM_DISK' then begin
if mfm_header.sec_geo<>1 then begin
MessageDlg('Geometria del disco<>1', mtInformation,[mbOk], 0);
exit;
end else begin
dsk[drvnum].DiskHeader.nbof_tracks:=mfm_header.track;
dsk[drvnum].DiskHeader.nbof_heads:=mfm_header.side;
getmem(ptemp,6400);
f:=0;
g:=0;
while (longi<longi_ini) do begin
//pillo los datos del track, con sus sectores...
wtemp:=0;
copymemory(@datos_track,puntero,6400);
inc(puntero,6400);
inc(longi,6400);
ptemp2:=ptemp;
track_long:=0;
h:=0;
//La informacion del track
if datos_track[40+wtemp]=0 then inc(wtemp,96) //formato Sedoric
else inc(wtemp,146); //formato IBM
//Leo los sectores
while (wtemp<6400) do begin
copymemory(mfm_sector,@datos_track[wtemp],44);
wtemp:=wtemp+44;
//Algunos checks...
if mfm_sector.nside>mfm_header.side then exit;
if mfm_sector.ntrack>mfm_header.track then exit;
//Status del sector (borrado, normal, etc)
dsk[drvnum].Tracks[f,g].sector[h].status1:=mfm_sector.info;
dsk[drvnum].Tracks[f,g].sector[h].track:=mfm_sector.ntrack;
dsk[drvnum].Tracks[f,g].sector[h].head:=mfm_sector.nside;
dsk[drvnum].Tracks[f,g].sector[h].sector:=mfm_sector.nsector;
dsk[drvnum].Tracks[f,g].sector[h].sector_size:=mfm_sector.nsector_size;
dsk[drvnum].Tracks[f,g].sector[h].data_length:=mfm_sector.crc;
//Le aņado 16 bytes y ya estoy en los datos...
wtemp:=wtemp+16;
//Posicion de los datos...
dsk[drvnum].Tracks[f,g].sector[h].posicion_data:=track_long;
case mfm_sector.nsector_size of
1:begin //256b
copymemory(ptemp2,@datos_track[wtemp],256);
wtemp:=wtemp+256;
track_long:=track_long+256;
end;
2:begin //512b
copymemory(ptemp2,@datos_track[wtemp],512);
wtemp:=wtemp+512;
track_long:=track_long+512;
end;
end;
wtemp:=wtemp+2;
while datos_track[wtemp]=$4e do wtemp:=wtemp+1;
h:=h+1;
end;
dsk[drvnum].Tracks[f,g].number_sector:=h;
dsk[drvnum].Tracks[f,g].track_lenght:=track_long;
getmem(dsk[drvnum].Tracks[f,g].data,track_long);
copymemory(dsk[drvnum].Tracks[f,g].data,ptemp,track_long);
g:=g+1;
if g=mfm_header.track then begin
g:=0;
f:=f+1;
end;
end;
freemem(ptemp);
end;
end else if mfm_header.firma='ORICDISK' then begin
//Este es fijo... Todo va segido y se asume que cada sector es de 256bytes
dsk[drvnum].DiskHeader.nbof_tracks:=mfm_header.track;
dsk[drvnum].DiskHeader.nbof_heads:=mfm_header.side;
//caras
for f:=0 to mfm_header.side-1 do begin
//pistas
for g:=0 to mfm_header.track-1 do begin
track_long:=256*mfm_header.sec_geo;
dsk[drvnum].Tracks[f,g].track_lenght:=track_long;
getmem(dsk[drvnum].Tracks[f,g].data,track_long);
copymemory(dsk[drvnum].Tracks[f,g].data,puntero,track_long);
inc(puntero,track_long);
inc(longi,track_long);
dsk[drvnum].Tracks[f,g].number_sector:=mfm_header.sec_geo;
//sectores
for h:=0 to (mfm_header.sec_geo-1) do begin
dsk[drvnum].Tracks[f,g].sector[h].track:=g;
dsk[drvnum].Tracks[f,g].sector[h].head:=f;
dsk[drvnum].Tracks[f,g].sector[h].sector:=h;
dsk[drvnum].Tracks[f,g].sector[h].sector_size:=1;
dsk[drvnum].Tracks[f,g].sector[h].posicion_data:=256*h;
end;
end;
end;
end else exit;
freemem(mfm_header);
freemem(mfm_sector);
dsk[drvnum].abierto:=true;
oric_dsk_format:=true;
end;
end.
|
unit UABMArticulos;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UDatosDB, UABMGeneral, DB, IBCustomDataSet, IBQuery, Grids,
DBGrids, StdCtrls, Buttons, jpeg, ExtCtrls, cxCurrencyEdit, cxControls,
cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, cxButtons,
cxLabel;
type
TFABMArticulos = class(TFABMGeneral)
cxNombre: TcxTextEdit;
cxPrecio: TcxCurrencyEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
TECantidad: TcxTextEdit;
cxLabel1: TcxLabel;
procedure FormCreate(Sender: TObject);
procedure BModificarClick(Sender: TObject);
procedure BGuardarClick(Sender: TObject);
procedure BInsertarClick(Sender: TObject);
procedure BEliminarClick(Sender: TObject);
private
procedure CargarParametrosInsertar(); override;
procedure CargarParametrosModificacion(); override;
public
{ Public declarations }
end;
var
FABMArticulos: TFABMArticulos;
implementation
{$R *.dfm}
procedure TFABMArticulos.FormCreate(Sender: TObject);
begin
inherited;
DMGimnasio.IBTArticulos.Active := true;
end;
procedure TFABMArticulos.CargarParametrosInsertar();
begin
IBQInsert.ParamByName('nombre').AsString := Trim(cxNombre.Text);
IBQInsert.ParamByName('precio').AsFloat := cxPrecio.Value;
if (TECantidad.Text = '') then
IBQInsert.ParamByName('cantidad').AsInteger := 0
else
IBQInsert.ParamByName('cantidad').AsInteger := StrToInt(TECantidad.Text);
end;
procedure TFABMArticulos.CargarParametrosModificacion();
begin
IBQModificar.ParamByName('nombre').AsString := Trim(cxNombre.Text);
IBQModificar.ParamByName('precio').AsFloat:= cxPrecio.Value;
if (TECantidad.Text = '') then
IBQmodificar.ParamByName('cantidad').AsInteger := 0
else
IBQmodificar.ParamByName('cantidad').AsInteger := StrToInt(TECantidad.Text);
IBQModificar.ParamByName('id').AsInteger := DMGimnasio.IBTArticulos.FieldValues['id_articulo'];
end;
procedure TFABMArticulos.BModificarClick(Sender: TObject);
begin
inherited;
cxNombre.Text := DMGimnasio.IBTArticulos.FieldValues['nombre'];
cxPrecio.Value := DMGimnasio.IBTArticulos.FieldValues['precio'];
TECantidad.Text := DMGimnasio.IBTArticulos.FieldValues['cantidad'];
end;
procedure TFABMArticulos.BGuardarClick(Sender: TObject);
begin
inherited;
DMGimnasio.IBTArticulos.Active := false;
DMGimnasio.IBTArticulos.Active := true;
end;
procedure TFABMArticulos.BInsertarClick(Sender: TObject);
begin
inherited;
cxNombre.Clear;
cxPrecio.Clear;
end;
procedure TFABMArticulos.BEliminarClick(Sender: TObject);
begin
inherited;
try
DMGimnasio.IBTArticulos.Delete;
DMGimnasio.IBTGimnasio.CommitRetaining;
except
DMGimnasio.IBTGimnasio.RollbackRetaining;
MessageDlg('El Articulo tiene datos relacionados y no se puede borrar',mtError,[mbOk],0);
end;
end;
end.
|
program code;
{$H+}
var equation : string;
const list = ['0'..'9', 'E', 'e', '+', '.'];
procedure removeZerosAndSpace(var s: string);
var i : integer;
begin
i := Length(s);
while (i > 0) and (s[i] = '0') do
i := i - 1;
s := copy(s, 1, i);
if s[1] = ' ' then
s := copy(s, 2, length(s)-1);
if s[Length(s)]='.' then
s := copy(s, 1, length(s)-1);
end;
function find(eq : string;pos : integer):integer;
var layer : integer;
begin
layer := 0;
find := -1;
while pos <= length(eq) do
begin
if eq[pos] = '(' then
layer := layer + 1
else if eq[pos] = ')' then
layer := layer - 1;
if layer = 0 then
begin
find := pos;
exit
end
else pos := pos + 1
end
end;
procedure cheat(character : char; var eq : string);
var a, b, c, err : integer;
tmp1, tmp2 : string;
m, n : real;
begin
a := pos(character, eq);
write('a = ', a);readln;
while a <> 0 do
begin
tmp1 := '';
tmp2 := '';
b := a - 1;
c := a + 1;
while (b > 0) and (eq[b] in list) do
begin
tmp1 := eq[b] + tmp1;
b := b - 1
end;
while (c <= length(eq)) and (eq[c] in list) do
begin
tmp2 := tmp2 + eq[c];
c := c + 1
end;
write('tmp1 = ', tmp1);readln;
write('tmp2 = ', tmp2);readln;
val(tmp1, m, err);
val(tmp2, n, err);
if character = '|' then
str(1/(1/m+1/n):0:10, tmp1)
else str(m+n:0:10, tmp1);
removeZerosAndSpace(tmp1);
removeZerosAndSpace(tmp2);
write('tmp1 = ', tmp1);readln;
eq := copy(eq, 1, b) + tmp1 + copy(eq, c, length(eq)-c+1);
write('eq = ', eq);readln;
a := pos(character, eq);
write('a = ', a);readln;
end
end;
function calculateResistance(eq : string):real;
var a, b, err : integer;
tmp1 : string;
begin
calculateResistance := -1;
a := pos('(', eq);
while a <> 0 do
begin
b := find(eq, a);
str(calculateResistance(copy(eq, a+1, b-a-1)):0:10, tmp1);
removeZerosAndSpace(tmp1);
eq := copy(eq, 1, a-1) + tmp1 + copy(eq, b+1, length(eq)-b);
a := pos('(', eq)
end;
write(eq);readln;
cheat('|', eq);
cheat('-', eq);
val(eq, calculateResistance, err)
end;
begin
readln(equation);
write(calculateResistance(equation));
readln
end. |
unit BackupConsts;
interface
const
LineBreak = #13#10;
IndentInc = ' ';
EqualSign = ' = ';
BeginMark = '{';
EndMark = '}';
NilValue = 'nil';
implementation
end.
|
unit fmGroupMemeberSelection;
interface
uses
Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList,
Winapi.UxTheme, System.StrUtils, ADC.Types, ADC.ADObject, ADC.ADObjectList,
ADC.ImgProcessor, ADC.Common, Vcl.Imaging.pngimage, ADC.GlobalVar;
type
TForm_GroupMemberSelection = class(TForm)
ListView_Objects: TListView;
ImageList_ToolBar: TImageList;
Edit_Search: TButtonedEdit;
ToolBar: TToolBar;
ToolButton_SelectNone: TToolButton;
ToolButton_SelectAll: TToolButton;
Button_OK: TButton;
Button_Cancel: TButton;
Label_Search: TLabel;
Label_Description: TLabel;
Edit_GroupName: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Edit_SearchChange(Sender: TObject);
procedure Edit_SearchRightButtonClick(Sender: TObject);
procedure ToolButton_SelectNoneClick(Sender: TObject);
procedure ToolButton_SelectAllClick(Sender: TObject);
procedure ListView_ObjectsData(Sender: TObject; Item: TListItem);
procedure ListView_ObjectsDrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
procedure ListView_ObjectsResize(Sender: TObject);
procedure ListView_ObjectsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ListView_ObjectsMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ListView_ObjectsClick(Sender: TObject);
procedure Button_CancelClick(Sender: TObject);
procedure Button_OKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FGroup: TADObject;
FCallingForm: TForm;
FObjects: TADGroupMemberList;
FObjectList: TADGroupMemberList;
FStateImages: TImageList;
FListViewWndProc: TWndMethod;
FOnAddMembers: TSelectGroupMemberProc;
procedure ListViewWndProc(var Msg: TMessage);
procedure SetCallingForm(const Value: TForm);
procedure ClearFields;
public
procedure Initialize(AGroup: TADObject; AObjects: TADObjectList<TADObject>);
property CallingForm: TForm write SetCallingForm;
property OnAddMembers: TSelectGroupMemberProc read FOnAddMembers write FOnAddMembers;
end;
var
Form_GroupMemberSelection: TForm_GroupMemberSelection;
implementation
{$R *.dfm}
uses dmDataModule;
{ TForm_GroupMemberSelection }
function SortObjectsByName(Item1, Item2: Pointer): Integer;
var
m1, m2: TADGroupMember;
begin
m1 := PADGroupMember(Item1)^;
m2 := PADGroupMember(Item2)^;
if m1.SortKey > m2.SortKey
then Result := 1
else if m1.SortKey < m2.SortKey
then Result := -1
else Result := AnsiCompareText(m1.name, m2.name);
end;
procedure TForm_GroupMemberSelection.Button_CancelClick(Sender: TObject);
begin
Close;
end;
procedure TForm_GroupMemberSelection.Button_OKClick(Sender: TObject);
var
i: Integer;
ResultList: TADGroupMemberList;
m: PADGroupMember;
MsgBoxParam: TMsgBoxParams;
begin
ResultList := TADGroupMemberList.Create;
for i := FObjectList.Count - 1 downto 0 do
begin
m := FObjectList[i];
if m^.Selected then
try
case apAPI of
ADC_API_LDAP: FGroup.AddGroupMember(LDAPBinding, m^.distinguishedName);
ADC_API_ADSI: FGroup.AddGroupMember(m^.distinguishedName);
end;
FObjects.Remove(m);
ResultList.Add(FObjectList.Extract(m));
ListView_Objects.Items.Count := FObjects.Count
except
on E: Exception do
begin
with MsgBoxParam do
begin
cbSize := SizeOf(MsgBoxParam);
hwndOwner := Self.Handle;
hInstance := 0;
case apAPI of
ADC_API_LDAP: lpszCaption := PChar('LDAP Exception');
ADC_API_ADSI: lpszCaption := PChar('ADSI Exception');
end;
lpszIcon := MAKEINTRESOURCE(32513);
dwStyle := MB_OK or MB_ICONHAND;
dwContextHelpId := 0;
lpfnMsgBoxCallback := nil;
dwLanguageId := LANG_NEUTRAL;
lpszText := PChar(E.Message);
end;
MessageBoxIndirect(MsgBoxParam);
ResultList.Free;
ListView_Objects.Invalidate;
Exit;
end;
end;
end;
if (ResultList.Count > 0) and (Assigned(FOnAddMembers))
then FOnAddMembers(Self, ResultList);
ResultList.Free;
Close;
end;
procedure TForm_GroupMemberSelection.ClearFields;
begin
Edit_GroupName.Text := '';
ListView_Objects.Clear;
FObjects.Clear;
FObjectList.Clear;
Edit_Search.Clear;
FOnAddMembers := nil;
end;
procedure TForm_GroupMemberSelection.Edit_SearchChange(Sender: TObject);
var
m: PADGroupMember;
begin
Edit_Search.RightButton.Visible := Edit_Search.Text <> '';
ListView_Objects.Clear;
FObjects.Clear;
if Edit_Search.Text = '' then
begin
for m in FObjectList do
FObjects.Add(m);
end else
for m in FObjectList do
begin
if ContainsText(m^.name, Edit_Search.Text)
or ContainsText(m^.sAMAccountName, Edit_Search.Text)
then FObjects.Add(m);
end;
ListView_Objects.Items.Count := FObjects.Count;
end;
procedure TForm_GroupMemberSelection.Edit_SearchRightButtonClick(
Sender: TObject);
begin
Edit_Search.Clear;
end;
procedure TForm_GroupMemberSelection.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ClearFields;
if FCallingForm <> nil then
begin
FCallingForm.Enabled := True;
FCallingForm.Show;
FCallingForm := nil;
end;
end;
procedure TForm_GroupMemberSelection.FormCreate(Sender: TObject);
begin
FObjects := TADGroupMemberList.Create(False);
FObjectList := TADGroupMemberList.Create;
FStateImages := TImageList.Create(Self);
FStateImages.ColorDepth := cd32Bit;
TImgProcessor.GetThemeButtons(
Self.Handle,
ListView_Objects.Canvas.Handle,
BP_CHECKBOX,
ListView_Objects.Color,
FStateImages
);
ListView_Objects.StateImages := FStateImages;
FListViewWndProc := ListView_Objects.WindowProc;
ListView_Objects.WindowProc := ListViewWndProc;
end;
procedure TForm_GroupMemberSelection.FormDestroy(Sender: TObject);
begin
FObjects.Free;
FObjectList.Free;
end;
procedure TForm_GroupMemberSelection.FormShow(Sender: TObject);
begin
Edit_Search.SetFocus;
end;
procedure TForm_GroupMemberSelection.Initialize(AGroup: TADObject;
AObjects: TADObjectList<TADObject>);
var
l: TADGroupMemberList;
o: TADObject;
m: PADGroupMember;
begin
l := TADGroupMemberList.Create;
FGroup := AGroup;
case apAPI of
ADC_API_LDAP: FGroup.GetGroupMembers(LDAPBinding, l, False);
ADC_API_ADSI: FGroup.GetGroupMembers(l, False);
end;
Edit_GroupName.Text := FGroup.name;
for o in AObjects do
if o.IsUser and not l.ContainsMember(o.distinguishedName) then
begin
New(m);
m^.Selected := False;
if o.IsGroup then m^.SortKey := 1 else m^.SortKey := 2;
m^.name := o.name;
m^.sAMAccountName := o.sAMAccountName;
m^.distinguishedName := o.distinguishedName;
FObjectList.Add(m);
end;
FObjectList.SortList(SortObjectsByName);
Edit_SearchChange(Self);
end;
procedure TForm_GroupMemberSelection.ListViewWndProc(var Msg: TMessage);
begin
ShowScrollBar(ListView_Objects.Handle, SB_HORZ, False);
// ShowScrollBar(ListView_MemberOf.Handle, SB_VERT, True);
FListViewWndProc(Msg);
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsClick(Sender: TObject);
var
hts : THitTests;
lvCursosPos : TPoint;
li : TListItem;
R: TRect;
Key: Word;
begin
inherited;
Key := VK_SPACE;
//position of the mouse cursor related to ListView
lvCursosPos := ListView_Objects.ScreenToClient(Mouse.CursorPos) ;
//click where?
hts := ListView_Objects.GetHitTestInfoAt(lvCursosPos.X, lvCursosPos.Y);
//locate the state-clicked item
if htOnItem in hts then
begin
li := ListView_Objects.GetItemAt(lvCursosPos.X, lvCursosPos.Y);
if li <> nil then
begin
ListView_GetItemRect(ListView_Objects.Handle, li.Index, R, LVIR_BOUNDS);
{ Величины R.Width и R.Offset см. в отрисовке значка состояния атрибута }
{ в процедуре ListView_AttributesDrawItem }
R.Width := 16;
R.Offset(6, 0);
if PtInRect(R, lvCursosPos)
then ListView_ObjectsKeyDown(ListView_Objects, Key, []);
end;
end;
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsData(Sender: TObject;
Item: TListItem);
begin
while Item.SubItems.Count < 2 do Item.SubItems.Add('');
if FObjects[Item.Index]^.Selected
then Item.StateIndex := 1
else Item.StateIndex := 0;
Item.Caption := FObjects[Item.Index]^.name;
case FObjects[Item.Index]^.SortKey of
1: begin
Item.ImageIndex := 6;
end;
2: begin
Item.ImageIndex := 0;
Item.SubItems[0] := FObjects[Item.Index]^.sAMAccountName;
end;
end;
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsDrawItem(
Sender: TCustomListView; Item: TListItem; Rect: TRect;
State: TOwnerDrawState);
var
C: TCanvas;
R: TRect;
S: string;
ColOrder: array of Integer;
SubIndex: Integer;
txtAlign: UINT;
i: Integer;
attr: PADAttribute;
begin
C := Sender.Canvas;
if (odSelected in State) or (FObjects[Item.Index].Selected)
then C.Brush.Color := IncreaseBrightness(COLOR_SELBORDER, 95);
C.FillRect(Rect);
{ Выводим CheckBox }
R := Rect;
R.Width := 16;
R.Offset(5, 0);
ListView_Objects.StateImages.Draw(c, R.TopLeft.X, R.TopLeft.Y, Item.StateIndex);
{ Выводим значек объекта AD }
R.Offset(R.Width + 6, 0);
if Item.ImageIndex > -1
then DM1.ImageList_Accounts.Draw(c, R.TopLeft.X, R.TopLeft.Y + 1, Item.ImageIndex);
{ Выводим name }
R.Offset(R.Width + 6, 0);
R.Right := R.Left + (Sender.Column[0].Width - R.Left - 6);
C.Font.Style := C.Font.Style - [fsBold];
C.Refresh;
S := Item.Caption;
DrawText(
C.Handle,
S,
Length(S),
R,
DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS
);
{ Выводим description }
ListView_GetSubItemRect(Sender.Handle, Item.Index, 1, 0, @R);
R.Inflate(-6, 0);
C.Refresh;
S := Item.SubItems[0];
DrawText(
C.Handle,
S,
Length(S),
R,
DT_LEFT or DT_VCENTER or DT_SINGLELINE or DT_END_ELLIPSIS
);
{ Отрисовываем рамку вокруг записи }
R := Rect;
R.Height := R.Height - 1;
R.Width := R.Width - 1;
if odFocused in State then
begin
C.Pen.Color := COLOR_SELBORDER;
C.Pen.Width := 1;
C.Refresh;
C.Polyline(
[
R.TopLeft,
Point(R.BottomRight.X, R.TopLeft.Y),
R.BottomRight,
Point(R.TopLeft.X, R.BottomRight.Y),
R.TopLeft
]
);
end else
begin
C.Pen.Color := IncreaseBrightness(clBtnFace, 35);
C.Pen.Width := 1;
C.Refresh;
C.Polyline(
[
Point(R.TopLeft.X, R.BottomRight.Y),
R.BottomRight
]
)
end;
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
li: TListItem;
begin
case Key of
VK_SPACE: begin
li := ListView_Objects.Selected;
if li <> nil then
begin
FObjects.SetSelected(li.Index, not FObjects[li.Index].Selected);
ListView_Objects.Invalidate
end;
end;
end;
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
k: Word;
li: TListItem;
HitPoint: TPoint;
HitInfo: TLVHitTestInfo;
MsgRes: Integer;
begin
if (Button = mbLeft) and (ssDouble in Shift)
or (Button = mbLeft) and (ssCtrl in Shift) then
begin
HitPoint := ListView_Objects.ScreenToClient(Mouse.Cursorpos);
FillChar(HitInfo, SizeOf(TLVHitTestInfo), 0);
HitInfo.pt := HitPoint;
MsgRes := ListView_Objects.Perform(LVM_SUBITEMHITTEST, 0, LPARAM(@HitInfo));
if MsgRes <> -1 then
begin
ListView_Objects.Selected := ListView_Objects.Items[HitInfo.iItem];
k := VK_SPACE;
ListView_ObjectsKeyDown(Sender, k, []);
end;
end;
end;
procedure TForm_GroupMemberSelection.ListView_ObjectsResize(Sender: TObject);
var
w: Integer;
begin
w := ListView_Objects.ClientWidth;
ListView_Objects.Columns[0].Width := Round(w * 55 / 100);
ListView_Objects.Columns[1].Width := w - ListView_Objects.Columns[0].Width;
end;
procedure TForm_GroupMemberSelection.SetCallingForm(const Value: TForm);
begin
FCallingForm := Value;
end;
procedure TForm_GroupMemberSelection.ToolButton_SelectAllClick(Sender: TObject);
var
m: PADGroupMember;
begin
for m in FObjects do
m^.Selected := True;
ListView_Objects.Invalidate;
end;
procedure TForm_GroupMemberSelection.ToolButton_SelectNoneClick(
Sender: TObject);
var
m: PADGroupMember;
begin
for m in FObjects do
m^.Selected := False;
ListView_Objects.Invalidate;
end;
end.
|
unit PlayerAnim;
// Copyright (c) 1996 Jorge Romero Gomez, Merchise.
// Things left:
// - Implement & make use of Keyframed
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
SpeedBmp, TimerUtils, SharedTimer;
type
TByteSet = set of byte;
type
TPlayFromWhatMedia = ( pfStream, pfMemory, pfAuto );
type
TPaintFlag = ( pfFullUpdate, pfUseIdentityPalette, pfIgnorePalette );
TPaintFlags = set of TPaintFlag;
type
TAnimPlayer =
class( TGraphicControl, ITickeable )
public
constructor Create( AOwner : TComponent ); override;
destructor Destroy; override;
procedure SetBounds( aLeft, aTop, aWidth, aHeight : integer ); override;
function GetPalette : HPALETTE; override;
procedure Paint; override;
procedure Loaded; override;
protected
FrameCounter : integer;
DestRect : TRect;
QueueCount : integer;
DontUpdateScreen : boolean;
fLockedPalEntries : TByteSet; // These entries will not be changed by fli palette chunks
fPlayFrom : TPlayFromWhatMedia; // This has effect only in the loading process...
fAnimRect : TRect;
fAnimBuffer : TSpeedBitmap;
fPaused : boolean;
fAutoSize : boolean;
fCenter : boolean;
fStretch : boolean;
fOnFrameCountPlayed : TNotifyEvent;
fOnFramePlayed : TNotifyEvent;
fOnFinished : TNotifyEvent;
fOnFatalException : TNotifyEvent;
fFilename : string;
fPaintFlags : TPaintFlags;
fLoop : boolean;
fShareTimer : boolean;
fTicker : TTicker;
fTimerInterval : integer;
fAutoDelay : boolean;
procedure LockPalEntries( Indx, Count : integer );
procedure UnlockPalEntries( Indx, Count : integer );
procedure ResetPalette; virtual;
procedure SetPaused( Value : boolean ); virtual;
procedure SetAutoSize( Value : boolean ); virtual;
procedure SetCenter( Value : boolean ); virtual;
procedure SetStretch( Value : boolean ); virtual;
procedure SetPaintFlags( Value : TPaintFlags ); virtual;
procedure Finished( Sender : TObject ); virtual;
procedure Changed; virtual;
procedure FatalException; virtual;
procedure SetStartingFrame( aStartingFrame : integer ); virtual;
procedure SetEndingFrame( aEndingFrame : integer ); virtual;
function GetKeyframed : boolean; virtual; abstract;
function GetStartingFrame : integer; virtual; abstract;
function GetEndingFrame : integer; virtual; abstract;
procedure SetShareTimer( Shared : boolean );
procedure ReserveTimer; virtual;
procedure ReleaseTimer; virtual;
procedure UpdateTimer( IntervalChanged : boolean ); virtual;
procedure PlayFrames( Count : integer ); virtual;
procedure SeekFrame( Index : integer ); virtual;
procedure FrameChanged; virtual;
procedure SetAutoDelay( UseAutoDelay : boolean ); virtual; abstract;
procedure SetTimerInterval( Interval : integer); virtual;
procedure InitPlayer; virtual;
procedure DonePlayer; virtual;
function GetAnimFrame : integer; virtual; abstract;
function GetAnimFrameCount : integer; virtual; abstract;
function GetUpdateRect : PRect; virtual;
procedure UpdateFrame; virtual;
protected
// IUnknown for ITickeable
fRefCount : integer;
function QueryInterface( const iid : TGUID; out obj ) : integer; stdcall;
function _AddRef : integer; stdcall;
function _Release : integer; stdcall;
// ITickeable
function ITickeable.Enabled = Active;
procedure ITickeable.Tick = TimerTick;
function Interval : integer;
public
procedure SetFrameRange( aStartingFrame, aEndingFrame : integer ); virtual;
procedure ResetFrameRange; virtual;
class function TimerResolution : integer; virtual;
procedure LoadFromFile( aFilename : string );
procedure LoadFromResourceName( Instance : THandle; const ResourceName : string );
procedure LoadFromResourceID( Instance : THandle; ResourceId : Integer );
procedure LoadFromStream( aStream : TStream ); virtual; abstract;
function Active : boolean; virtual;
function Empty : boolean; virtual;
function GetColor( indx : integer ) : TColor; virtual;
procedure SetColor( indx : integer; aColor : TColor); virtual;
procedure ResetTints;
procedure TintColors( Indx, Count : integer; TintColor, BaseColor : TColor ); virtual;
procedure TimerTick; virtual;
procedure Pause; virtual;
procedure Resume; virtual;
procedure Next; virtual;
property Color[indx : integer] : TColor read GetColor write SetColor;
property AnimBuffer : TSpeedBitmap read fAnimBuffer;
property AnimRect : TRect read fAnimRect;
property AnimSize : TPoint read fAnimRect.BottomRight;
property AnimWidth : integer read fAnimRect.Right;
property AnimHeight : integer read fAnimRect.Bottom;
property AnimFrame : integer read GetAnimFrame write SeekFrame;
property AnimFrameCount : integer read GetAnimFrameCount;
property LockedPalEntries : TByteSet read fLockedPalEntries;
property UpdateRect : PRect read GetUpdateRect;
public
property OnFramePlayed : TNotifyEvent read fOnFramePlayed write fOnFramePlayed;
property OnFinished : TNotifyEvent read fOnFinished write fOnFinished;
property OnFrameCountPlayed : TNotifyEvent read fOnFrameCountPlayed write fOnFrameCountPlayed;
property OnFatalException : TNotifyEvent read fOnFatalException write fOnFatalException;
property AutoSize : boolean read fAutoSize write SetAutoSize default true;
property Paused : boolean read fPaused write SetPaused default false;
property Center : boolean read fCenter write SetCenter default false;
property Stretch : boolean read fStretch write SetStretch default false;
property Loop : boolean read fLoop write fLoop default true;
property Filename : string read fFilename write LoadFromFile;
property StartingFrame : integer read GetStartingFrame write SetStartingFrame default 1;
property EndingFrame : integer read GetEndingFrame write SetEndingFrame default -1;
property Keyframed : boolean read GetKeyFramed default false;
property PlayFrom : TPlayFromWhatMedia read fPlayFrom write fPlayFrom default pfAuto;
property ShareTimer : boolean read fShareTimer write SetShareTimer default true;
property PaintFlags : TPaintFlags read fPaintFlags write SetPaintFlags default [];
property TimerInterval : integer read fTimerInterval write SetTimerInterval default 0;
property AutoDelay : boolean read fAutoDelay write SetAutoDelay default true;
end;
var
fSharedTimer : TSharedTimer = nil;
implementation
uses
WinUtils, GDI, ColorSpaces, Dibs, MemUtils, ViewUtils;
// TSharedAnimTimer
// TAnimPlayer
constructor TAnimPlayer.Create( AOwner : TComponent );
begin
inherited;
ControlStyle := ControlStyle + [csReplicatable];
Height := 60;
Width := 60;
fPaused := false;
fLoop := true;
fAutoSize := true;
fAutoDelay := true;
fShareTimer := true;
end;
destructor TAnimPlayer.Destroy;
begin
DonePlayer;
inherited;
end;
procedure TAnimPlayer.Loaded;
begin
inherited;
if not (csDesigning in ComponentState)
then ReserveTimer;
end;
procedure TAnimPlayer.InitPlayer;
begin
if not ( csLoading in ComponentState )
then ResetTints;
if csDesigning in ComponentState
then DontUpdateScreen := true;
end;
procedure TAnimPlayer.DonePlayer;
begin
fFilename := '';
if Assigned( AnimBuffer )
then
begin
if not (csDesigning in ComponentState)
then ReleaseTimer;
FreeObject( fAnimBuffer );
end;
end;
function TAnimPlayer.GetPalette : HPALETTE;
begin
if Assigned( AnimBuffer )
then Result := AnimBuffer.Palette
else Result := 0;
end;
function TAnimPlayer.GetUpdateRect : PRect;
begin
Result := nil; // Update the whole rect...
end;
procedure TAnimPlayer.UpdateFrame;
var
RectPtr : PRect;
Rect : TRect;
begin
if Assigned( AnimBuffer )
then
begin
RectPtr := UpdateRect;
if RectPtr = nil
then AnimBuffer.StretchDraw( Canvas, DestRect )
else
begin
Rect := RectPtr^;
with Rect do
begin
// Since the clipping rectangle is supposed to use the same coordinates as DestRect
// we must first convert the UpdateRect
Left := Left * DestRect.Right div AnimWidth;
Right := Right * DestRect.Right div AnimWidth;
Top := Top * DestRect.Bottom div AnimHeight;
Bottom := Bottom * DestRect.Bottom div AnimHeight;
AnimBuffer.ClipStretchDraw( Canvas, DestRect, Rect );
end;
end;
end;
end;
procedure TAnimPlayer.Paint;
begin
if Assigned( AnimBuffer )
then AnimBuffer.StretchDraw( inherited Canvas, DestRect )
else
if csDesigning in ComponentState
then
with inherited Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle( 0, 0, Width, Height );
end;
end;
const
QueueThreshold = 1;
// IUnknown for ITickeable
function TAnimPlayer.QueryInterface( const iid : TGUID; out obj ) : integer;
const
E_NOINTERFACE = $80004002;
begin
if GetInterface( iid, Obj )
then Result := 0
else Result := E_NOINTERFACE;
end;
function TAnimPlayer._AddRef : integer;
begin
inc( fRefCount );
Result := fRefCount;
end;
function TAnimPlayer._Release : integer;
begin
dec( fRefCount );
Result := fRefCount;
end;
// ITickeable
function TAnimPlayer.Active : boolean;
begin
Result := (not Empty) and (not Paused);
end;
function TAnimPlayer.Interval : integer;
begin
Result := fTimerInterval;
end;
procedure TAnimPlayer.TimerTick;
var
bakDontUpdateScreen : boolean;
begin
if ThreadHasTheseMessagesWaiting( QS_IMPORTANT )
then
begin
inc( QueueCount );
if QueueCount = QueueThreshold
then
begin
QueueCount := 0;
bakDontUpdateScreen := DontUpdateScreen;
DontUpdateScreen := true;
Next;
DontUpdateScreen := bakDontUpdateScreen;
end
else Next;
end
else
begin
QueueCount := 0;
Next;
end;
end;
// TAnimPlayer (cont)
procedure TAnimPlayer.SetShareTimer( Shared : boolean );
begin
if (Shared <> ShareTimer)
then
if ( csDesigning in ComponentState ) or (csLoading in ComponentState )
then fShareTimer := Shared
else
begin
ReleaseTimer;
fShareTimer := Shared;
ReserveTimer;
end;
end;
class function TAnimPlayer.TimerResolution : integer;
begin
Result := 10;
end;
type
TProcOfObject =
record
Addr : pointer;
Self : pointer;
end;
procedure TAnimPlayer.ReserveTimer;
begin
if ShareTimer
then
begin
if not Assigned( fSharedTimer )
then fSharedTimer := TSharedTimer.Create( TimerResolution );
fSharedTimer.InsertClient( Self );
end
else
begin
fTicker := TSimpleTimer.Create;//TEnhancedTimer.Create; //TEnhancedTimer
with fTicker do
begin
PostTicks := true;
OnTimer := TimerTick;
Resolution := TimerResolution div 2;
Interval := TimerInterval;
Enabled := Active;
end;
end;
end;
procedure TAnimPlayer.ReleaseTimer;
begin
if ShareTimer
then
begin
if Assigned( fSharedTimer ) and ( not Paused )
then fSharedTimer.DeleteClient( Self );
end
else FreeObject( fTicker );
end;
procedure TAnimPlayer.UpdateTimer( IntervalChanged : boolean );
begin
if not (csDesigning in ComponentState)
then
if ShareTimer and Assigned( fSharedTimer )
then
with fSharedTimer do
if IntervalChanged
then RefreshClient( Self )
else
if Paused
then DeleteClient( Self )
else InsertClient( Self )
else
if Assigned( fTicker )
then
begin
fTicker.Enabled := not Paused;
if IntervalChanged
then fTicker.Interval := TimerInterval;
end;
end;
procedure TAnimPlayer.Pause;
begin
Paused := true;
end;
procedure TAnimPlayer.Resume;
begin
Paused := false;
end;
procedure TAnimPlayer.SetPaused( Value : boolean );
begin
if Paused <> Value //
then
begin
fPaused := Value;
UpdateTimer( false );
end;
end;
procedure TAnimPlayer.PlayFrames( Count : integer );
begin
FrameCounter := Count;
end;
procedure TAnimPlayer.SeekFrame( Index : integer );
begin
if Assigned( AnimBuffer )
then FrameChanged;
end;
procedure TAnimPlayer.SetFrameRange( aStartingFrame, aEndingFrame : integer );
begin
StartingFrame := aStartingFrame;
EndingFrame := aEndingFrame;
end;
procedure TAnimPlayer.ResetFrameRange;
begin
StartingFrame := 1;
EndingFrame := AnimFrameCount;
end;
procedure TAnimPlayer.SetStartingFrame( aStartingFrame : integer );
begin
if AnimFrame < aStartingFrame
then AnimFrame := aStartingFrame;
end;
procedure TAnimPlayer.SetEndingFrame( aEndingFrame : integer );
begin
if AnimFrame > aEndingFrame
then AnimFrame := StartingFrame;
end;
procedure TAnimPlayer.FrameChanged;
begin
with AnimBuffer do
if PaletteModified
then
begin
if not IgnorePalette
then PaletteChanged( false );
PaletteModified := false;
end;
if not DontUpdateScreen and Visible
then UpdateFrame;
if Assigned( fOnFramePlayed )
then fOnFramePlayed( Self );
end;
procedure TAnimPlayer.Next;
begin
FrameChanged;
if FrameCounter > 0
then
begin
dec( FrameCounter );
if (FrameCounter = 0) and Assigned( fOnFrameCountPlayed )
then fOnFrameCountPlayed( Self );
end;
end;
procedure TAnimPlayer.SetAutoSize( Value : boolean );
begin
fAutoSize := Value;
if fAutoSize
then Align := alNone;
Changed;
end;
procedure TAnimPlayer.SetCenter( Value : boolean );
begin
if fCenter <> Value
then
begin
fCenter := Value;
Changed;
end;
end;
procedure TAnimPlayer.SetStretch( Value : boolean );
begin
if Value <> fStretch
then
begin
fStretch := Value;
Changed;
end;
end;
procedure TAnimPlayer.SetBounds( aLeft, aTop, aWidth, aHeight : integer );
begin
if (aWidth = Width) or (aHeight = Height)
then inherited
else
begin
inherited;
fAutoSize := false;
Changed;
end;
end;
procedure TAnimPlayer.Changed;
begin
if AutoSize and not Empty
then inherited SetBounds( Left, Top, AnimWidth, AnimHeight );
if Assigned( AnimBuffer )
then
begin
if Stretch
then DestRect := ClientRect
else
if Center
then DestRect := Bounds( (Width - AnimBuffer.Width) div 2, (Height - AnimBuffer.Height) div 2,
AnimBuffer.Width, AnimBuffer.Height )
else DestRect := Rect( 0, 0, AnimBuffer.Width, AnimBuffer.Height );
with DestRect do
if (Right - Left >= Width) and (Bottom - Top >= Height)
then ControlStyle := ControlStyle + [csOpaque]
else ControlStyle := ControlStyle - [csOpaque];
end
else
ControlStyle := ControlStyle - [csOpaque];
Invalidate;
end;
function TAnimPlayer.Empty : boolean;
begin
Result := AnimBuffer = nil;
end;
procedure TAnimPlayer.LoadFromFile( aFilename : string );
begin
if aFilename <> ''
then
begin
LoadFromStream( TFileStream.Create( aFilename, fmOpenRead or fmShareDenyWrite) );
if not Empty
then fFilename := aFilename;
end
else DonePlayer;
Changed;
end;
procedure TAnimPlayer.LoadFromResourceName( Instance : THandle; const ResourceName : string );
begin
LoadFromStream( TResourceStream.Create( Instance, ResourceName, RT_BITMAP ) )
end;
procedure TAnimPlayer.LoadFromResourceID( Instance : THandle; ResourceId : Integer );
begin
LoadFromStream( TResourceStream.CreateFromID( Instance, ResourceId, RT_BITMAP ) )
end;
procedure TAnimPlayer.Finished( Sender : TObject );
begin
if not Loop
then Pause;
if Assigned( fOnFinished )
then fOnFinished( Self );
end;
procedure TAnimPlayer.FatalException;
begin
if Assigned( fOnFatalException )
then fOnFatalException( Self );
end;
function TAnimPlayer.GetColor( indx : integer ) : TColor;
begin
Result := TColor( AnimBuffer.RgbEntries[indx] )
end;
procedure TAnimPlayer.LockPalEntries( Indx, Count : integer );
begin
fLockedPalEntries := fLockedPalEntries + [Indx..Indx + Count - 1];
end;
procedure TAnimPlayer.UnlockPalEntries( Indx, Count : integer );
begin
fLockedPalEntries := fLockedPalEntries - [Indx..Indx + Count];
end;
procedure TAnimPlayer.SetColor( Indx : integer; aColor : TColor);
begin
if Assigned( AnimBuffer )
then
with AnimBuffer do
begin
LockPalEntries( Indx, 1 );
longint( RgbEntries[indx] ) := ColorToRGB( aColor );
ChangePaletteEntries( 0, DibHeader.biBitCount, RgbEntries^ );
end;
end;
procedure TAnimPlayer.ResetTints;
begin
UnlockPalEntries( low(byte), high(byte) );
if not Empty
then ResetPalette;
end;
procedure TAnimPlayer.ResetPalette;
begin
// Do nothing...
end;
procedure TAnimPlayer.TintColors( Indx, Count : integer; TintColor, BaseColor : TColor );
begin
assert( Assigned( AnimBuffer ), 'Empty buffer in AnimPlayer.TAnimPlayer.TintColors!!' );
with AnimBuffer do
begin
LockPalEntries( Indx, Count );
TintRgbEntries( Indx, Count, RgbEntries^, ColorToRgb( TintColor ), ColorToRgb( BaseColor ) );
ChangePaletteEntries( 0, DibHeader.biClrUsed, RgbEntries^ );
if not IgnorePalette
then PaletteChanged( true );
end;
end;
procedure TAnimPlayer.SetPaintFlags( Value : TPaintFlags );
var
UseIdentity : boolean;
IgnorePalette : boolean;
begin
UseIdentity := pfUseIdentityPalette in Value;
if UseIdentity <> (pfUseIdentityPalette in PaintFlags)
then
begin
if UseIdentity
then Include( fPaintFlags, pfUseIdentityPalette )
else Exclude( fPaintFlags, pfUseIdentityPalette );
if Assigned( AnimBuffer )
then AnimBuffer.ForcePaletteIdentity( UseIdentity, true );
end;
IgnorePalette := pfIgnorePalette in Value;
if IgnorePalette <> (pfIgnorePalette in PaintFlags)
then
begin
if IgnorePalette
then Include( fPaintFlags, pfIgnorePalette )
else Exclude( fPaintFlags, pfIgnorePalette );
if Assigned( AnimBuffer )
then AnimBuffer.IgnorePalette := IgnorePalette;
end;
end;
procedure TAnimPlayer.SetTimerInterval( Interval : integer );
begin
assert( Interval >= 0, 'Invalid interval specified in TAnimPlayer.SetTimerInterval!!' );
if not (csReading in ComponentState)
then fAutoDelay := false;
if Interval <> TimerInterval
then
begin
fTimerInterval := Interval;
if not (csDesigning in ComponentState)
then UpdateTimer( true );
end;
end;
initialization
finalization
fSharedTimer.Free;
end.
|
unit USpeedTest;
interface
uses Classes;
type
TMeasureEvent = procedure(const text:string) of Object;
TFileSpeedTest = class(TObject)
private
FStream: THandleStream;
FBuffer : string;
FOnMeasureResult: TMeasureEvent;
FFileSize: Integer;
procedure ReadFile(count, blocksize: Integer);
procedure ReadFileAPI(count, blocksize: Integer);
procedure WriteFile(count, blocksize: Integer);
procedure WriteFileAPI(count, blocksize: Integer);
procedure SeekBegin;
procedure AddMsg(const s:string);
procedure SetFileSize(const Value: Integer);
public
constructor Create(AStream:THandleStream);
procedure DoSpeedTest(UseAPI, FlushCache:Boolean);
property OnMeasureResult:TMeasureEvent read FOnMeasureResult write FOnMeasureResult;
property FileSize:Integer read FFileSize write SetFileSize;
end;
implementation
uses Windows, SysUtils, UStopWatch;
{ TFileSpeedTest }
constructor TFileSpeedTest.Create(AStream: THandleStream);
begin
inherited Create;
FStream := AStream;
FileSize := $4000000;
end;
procedure TFileSpeedTest.WriteFile(count, blocksize:Integer);
var
i : Integer;
begin
for i := 1 to count do
begin
FStream.WriteBuffer(Fbuffer[1], blocksize);
end;
end;
procedure TFileSpeedTest.ReadFile(count, blocksize: Integer);
var
i : Integer;
begin
for i := 1 to count do
begin
FStream.ReadBuffer(Fbuffer[1], blocksize);
end;
end;
procedure TFileSpeedTest.WriteFileAPI(count, blocksize: Integer);
var
i : Integer;
h : THandle;
written : Cardinal;
begin
h := FStream.Handle;
for i := 1 to count do
begin
windows.WriteFile(h, Fbuffer[1], blocksize, written, nil);
end;
end;
procedure TFileSpeedTest.ReadFileAPI(count, blocksize: Integer);
var
i : Integer;
h : THandle;
readed : Cardinal;
begin
h := FStream.Handle;
for i := 1 to count do
begin
windows.ReadFile(h, Fbuffer[1], blocksize, readed, nil);
end;
end;
procedure TFileSpeedTest.DoSpeedTest(UseAPI, FlushCache:Boolean);
var
timer : IStopWatch;
blocksize, count : Integer;
i : Integer;
begin
Assert(Assigned(FStream));
SetLength(Fbuffer, 1 shl 18);
for i := 3 to 18 do
begin
blocksize := 1 shl i;
count := FileSize div blocksize;
SeekBegin;
timer := CreateStopWatch(True);
if useAPI then
WriteFileAPI(count, blocksize)
else
WriteFile(count, blocksize);
if FlushCache then
FlushFileBuffers(FStream.Handle);
timer.Stop;
AddMsg(Format('write %d blocks à %d bytes: %.1f ms', [count, blocksize, timer.MilliSeconds]));
end;
AddMsg('');
for i := 3 to 18 do
begin
blocksize := 1 shl i;
count := FileSize div blocksize;
SeekBegin;
timer := CreateStopWatch(True);
if useAPI then
ReadFileAPI(count, blocksize)
else
ReadFile(count, blocksize);
timer.Stop;
AddMsg(Format('read %d blocks à %d bytes: %.1f ms', [count, blocksize, timer.MilliSeconds]));
end;
end;
procedure TFileSpeedTest.SeekBegin;
begin
FStream.Seek(0, soFromBeginning);
end;
procedure TFileSpeedTest.AddMsg(const s: string);
begin
if Assigned(FOnMeasureResult) then
FOnMeasureResult(s);
end;
procedure TFileSpeedTest.SetFileSize(const Value: Integer);
begin
FFileSize := Value;
FFileSize := (FFileSize shr 18) shl 18;
end;
end.
|
unit aeLoggingManager;
interface
uses windows, types, sysutils, classes, aeConst;
type
TaeLogMessageEntryType = (AE_LOG_MESSAGE_ENTRY_TYPE_NORMAL, AE_LOG_MESSAGE_ENTRY_TYPE_NOTICE,
AE_LOG_MESSAGE_ENTRY_TYPE_ERROR);
type
TaeLoggingManager = class
private
_log: TStringList;
_log_path: string;
_critsect: TRTLCriticalSection;
_lastMessageHashCode: integer;
public
Constructor Create;
Procedure AddEntry(entryMsg: String; entryType: TaeLogMessageEntryType);
destructor Destroy; override;
end;
var
AE_LOGGING: TaeLoggingManager; // singleton, blarghhh
implementation
{ TaeLoggingManager }
procedure TaeLoggingManager.AddEntry(entryMsg: String; entryType: TaeLogMessageEntryType);
var
currentHashCode: integer;
begin
try
EnterCriticalSection(self._critsect);
if (entryMsg = '') then
exit;
currentHashCode := entryMsg.GetHashCode();
if (currentHashCode = self._lastMessageHashCode) then
exit;
case entryType of
AE_LOG_MESSAGE_ENTRY_TYPE_NORMAL:
self._log.Add('AE_NORMAL : ' + entryMsg);
AE_LOG_MESSAGE_ENTRY_TYPE_NOTICE:
self._log.Add('AE_NOTICE : ' + entryMsg);
AE_LOG_MESSAGE_ENTRY_TYPE_ERROR:
self._log.Add('***AE_ERROR*** : ' + entryMsg);
end;
self._lastMessageHashCode := currentHashCode;
self._log.SaveToFile(self._log_path);
finally
LeaveCriticalSection(self._critsect);
end;
end;
constructor TaeLoggingManager.Create;
begin
self._lastMessageHashCode := 0;
self._log := TStringList.Create;
self._log_path := GetCurrentDir + '\' + AE_LOGGING_LOG_PATH;
InitializeCriticalSection(self._critsect);
end;
destructor TaeLoggingManager.Destroy;
begin
DeleteCriticalSection(self._critsect);
self._log.Free;
inherited;
end;
initialization
AE_LOGGING := TaeLoggingManager.Create;
finalization
AE_LOGGING.Free;
end.
|
unit AutoLog;
interface
procedure Log( LogId, Info : string );
procedure InitLogs;
implementation
uses
SyncObjs, SysUtils;
var
LogLock : TCriticalSection = nil;
procedure InitLogs;
begin
LogLock := TCriticalSection.Create;
end;
procedure DoneLogs;
begin
LogLock.Free;
end;
procedure Log( LogId, Info : string );
var
filename : string;
LogFile : Text;
begin
LogLock.Acquire;
try
filename := 'c:\' + LogId + '.log';
AssignFile( LogFile, filename );
try
Append( LogFile );
except
Rewrite( LogFile );
end;
try
writeln( LogFile, Info );
finally
CloseFile( LogFile );
end;
finally
LogLock.Release
end;
end;
initialization
//InitLogs;
finalization
//DoneLogs;
end.
|
unit ntvThemes;
{$mode objfpc}{$H+}
{**
* This file is part of the "Mini Library"
*
* @url http://www.sourceforge.net/projects/minilib
* @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html)
* See the file COPYING.MLGPL, included in this distribution,
* @author Zaher Dirkey
*}
interface
uses
Classes, Controls, SysUtils, Contnrs, Graphics, ImgList, GraphType,
mnClasses, ColorUtils,
LCLType, LCLIntf;
type
TdrawState = (pdsFocused, pdsSelected, pdsActive, pdsDisabled, pdsDown, pdsMultiLine);
TdrawStates = set of TdrawState;
TdrawButtonKind = (kndNone, kndNext, kndLeft, kndRight, kndFirst, kndLast, kndUp, kndDown, kndEllipsis,
kndPin, kndPlus, kndOK, kndCheck, kndMinus, kndCross, kndStar, kndDiv, kndPoint);
TdrawCorner = (crnTopLeft, crnTopRight, crnBottomRight, crnBottomLeft);
TdrawCorners = set of TdrawCorner;
TdrawSide = (sidTop, sidLeft, sidBottom, sidRight);
TdrawSides = set of TdrawSide;
TntvThemeEngine = class;
TntvTheme = class;
{ TThemeAttribute }
TThemeAttribute = class(TPersistent)
private
FBackground: TColor;
FDescription: string;
FForeground: TColor;
FIndex: Integer;
FParent: TntvTheme;
FTitle: string;
protected
public
constructor Create;
procedure Assign(Source: TPersistent); override;
procedure Reset;
property Index: Integer read FIndex;
property Title: string read FTitle write FTitle;
property Description: string read FDescription write FDescription;
published
property Background: TColor read FBackground write FBackground default clNone;
property Foreground: TColor read FForeground write FForeground default clNone;
end;
{ TntvTheme }
TntvTheme = class (specialize TmnObjectList<TThemeAttribute>)
private
FActive: TThemeAttribute;
FButton: TThemeAttribute;
FOdd: TThemeAttribute;
FDefault: TThemeAttribute;
FEngine: TntvThemeEngine;
FHeader: TThemeAttribute;
FHighlighted: TThemeAttribute;
FLink: TThemeAttribute;
FPanel: TThemeAttribute;
FName: string;
FSelected: TThemeAttribute;
FSeparator: TThemeAttribute;
FStub: TThemeAttribute;
FTitle: TThemeAttribute;
procedure SetName(const AValue: string);
public
constructor Create(AEngine: TntvThemeEngine; AName: string); virtual;
procedure Correct;
function GetEdgeColor: TColor;
function GetLineColor: TColor; //for grids
function GetUnactiveColor: TColor;
procedure DrawText(Canvas: TCanvas; Text: string; Rect: TRect; Style: TTextStyle; UseRightToLeft: Boolean); virtual;
procedure DrawText(Canvas: TCanvas; Text: string; Rect: TRect; UseRightToLeft: Boolean = False);
procedure DrawRect(Canvas: TCanvas; const Rect: TRect; Color, BorderColor: TColor); virtual;
procedure DrawButtonText(Canvas: TCanvas; Text: string; ImageWidth: Integer; Rect: TRect; States: TdrawStates; UseRightToLeft: Boolean); virtual;
procedure DrawButtonEdge(Canvas: TCanvas; Rect: TRect; States: TdrawStates); virtual;
procedure DrawButton(Canvas: TCanvas; Text: string; ImageWidth: Integer; Rect: TRect; States: TdrawStates; UseRightToLeft: Boolean); virtual;
procedure DrawImage(Canvas: TCanvas; ImageList:TImageList; ImageIndex: TImageIndex; Rect: TRect; States: TdrawStates); virtual;
property Name: string read FName write SetName;
published
property Default: TThemeAttribute read FDefault; //ListBox, Grid
property Odd: TThemeAttribute read FOdd; //alternate ListBox, Grid colors
property Panel: TThemeAttribute read FPanel; //Forms and Panels
property Button: TThemeAttribute read FButton;
property Title: TThemeAttribute read FTitle;
property Header: TThemeAttribute read FHeader;
property Stub: TThemeAttribute read FStub;
property Separator: TThemeAttribute read FSeparator;
property Link: TThemeAttribute read FLink;
property Selected: TThemeAttribute read FSelected;
property Highlighted: TThemeAttribute read FHighlighted;
property Active: TThemeAttribute read FActive;
end;
TntvThemes = class(specialize TmnNamedObjectList<TntvTheme>)
end;
IThemeNotify = interface(IInterface)
['{9F320814-3CEA-4106-8CCC-22C04DDCED53}']
procedure InvalidateTheme;
end;
{ TntvThemeEngine }
TntvThemeEngine = class(TObject)
private
FTheme: TntvTheme;
FThemes: TntvThemes;
FShowButtonImages: Boolean;
FNotifyComponents: TComponentList;
protected
procedure Switched;
public
constructor Create;
destructor Destroy; override;
procedure AddNotification(AComponent: TComponent);
procedure RemoveNotification(AComponent: TComponent);
procedure Correct;
procedure Notify;
//function Switch(NewPainter: TntvTheme):Boolean;// use Painter class
//function Switch(NewPainter: string):Boolean; //use Painter name
property Theme: TntvTheme read FTheme;
property ShowButtonImages: Boolean read FShowButtonImages write FShowButtonImages;
end;
function ThemeEngine: TntvThemeEngine;
function Theme: TntvTheme;
function DrawStates(Enabled, Down, Focused: Boolean): TdrawStates;
function DrawStates(ADrawStates: TdrawStates; Enabled, Down, Focused: Boolean): TdrawStates;
implementation
uses
Types, ntvStdThemes;
var
FThemeEngine: TntvThemeEngine = nil;
function Theme: TntvTheme;
begin
Result := ThemeEngine.Theme;
end;
function ThemeEngine: TntvThemeEngine;
begin
if FThemeEngine = nil then
FThemeEngine := TntvThemeEngine.Create;
Result := FThemeEngine;
end;
function DrawStates(Enabled, Down, Focused: Boolean): TdrawStates;
begin
Result := DrawStates([], Enabled, Down, Focused);
end;
function DrawStates(ADrawStates: TdrawStates; Enabled, Down, Focused: Boolean): TdrawStates;
begin
Result := ADrawStates;
if Down then
Result := Result + [pdsDown];
if Focused then
Result := Result + [pdsFocused];
if not Enabled then
Result := Result + [pdsDisabled];
end;
{ TThemeAttribute }
constructor TThemeAttribute.Create;
begin
inherited;
FBackground := clNone;
FForeground := clNone;
end;
procedure TThemeAttribute.Assign(Source: TPersistent);
begin
if Source is TThemeAttribute then
begin
Foreground := (Source as TThemeAttribute).Foreground;
Background := (Source as TThemeAttribute).Background;
end
else
inherited;
end;
procedure TThemeAttribute.Reset;
begin
FBackground := clNone;
FForeground := clNone;
end;
{ TntvTheme }
procedure TntvTheme.SetName(const AValue: string);
begin
if FName =AValue then exit;
FName :=AValue;
end;
constructor TntvTheme.Create(AEngine: TntvThemeEngine; AName: string);
procedure Add(var Item: TThemeAttribute; Title, Description: string; Foreground, Background: TColor);
begin
Item := TThemeAttribute.Create;
Item.Title := Title;
Item.Description := Description;
Item.Foreground := Foreground;
Item.Background := Background;
Item.FParent := Self;
Item.FIndex := inherited Add(Item);
end;
begin
inherited Create;
FEngine:= AEngine;
FName := AName;
Add(FDefault, 'Default', 'Default colors', clWindowText, clWindow);
Add(FPanel, 'Panel', 'GUI Panel', clBtnText, clBtnFace);
Add(FButton, 'Button', 'Buttons', clBtnText, clBtnFace);
Add(FSelected, 'Selected', 'Selected text', clHighlightText, clHighlight);
Add(FTitle, 'Title', 'Title', clCaptionText, clActiveCaption);
Add(FSeparator, 'Separator', 'Seperators, between Stub of Editor and Line numbers', $00D8D8D8, $00CDCDCD);
Add(FLink, 'Link', 'URL Links of follow defines highlight', clWhite, $002A190F);
Add(FHighlighted, 'Highlighted', 'Highlighted important line, like running line', $00150FFF, clNone);
Add(FActive, 'Active', 'Hover', clBlack, $008585CB);
Add(FHeader, 'Header', 'Header', clBlack, $00E9E9E9);
Add(FStub, 'Stub', 'Stub', clBlack, $00E9E9E9);
Add(FOdd, 'Odd', 'Odd', clBlack, clMoneyGreen);
Correct;
end;
procedure TntvTheme.Correct;
begin
end;
function TntvTheme.GetEdgeColor: TColor;
begin
Result := MixColors(Default.Foreground, Theme.Panel.Background, 100);
end;
function TntvTheme.GetLineColor: TColor;
begin
Result := MixColors(Default.Foreground, Theme.Default.Background, 100);
end;
function TntvTheme.GetUnactiveColor: TColor;
begin
Result := MixColors(Theme.Default.Background, Theme.Panel.Background, 100);
end;
procedure TntvTheme.DrawText(Canvas: TCanvas; Text: string; Rect: TRect; Style: TTextStyle; UseRightToLeft: Boolean);
begin
Style.RightToLeft := UseRightToLeft;
Rect.Top := Rect.Top + 1; //idk why
Canvas.TextRect(Rect, Rect.Left, Rect.Top, Text, Style);
end;
procedure TntvTheme.DrawText(Canvas: TCanvas; Text: string; Rect: TRect; UseRightToLeft: Boolean);
var
TS: TTextStyle;
begin
Initialize(TS);
with TS do
begin
Alignment := BidiFlipAlignment(Alignment, UseRightToLeft);
WordBreak := False;
SingleLine:= True;
Clipping := True;
ShowPrefix := False;
SystemFont := False;
RightToLeft := UseRightToLeft;
ExpandTabs := True;
end;
DrawText(Canvas, Text, Rect, TS, UseRightToLeft);
end;
procedure TntvTheme.DrawButtonText(Canvas: TCanvas; Text: string; ImageWidth: Integer; Rect: TRect; States: TdrawStates; UseRightToLeft: Boolean);
var
TS: TTextStyle;
begin
with Canvas do
begin
Brush.Style := bsClear;
Initialize(TS);
with TS do
begin
if ImageWidth = 0 then
Alignment := BidiFlipAlignment(taCenter)
else
Alignment := BidiFlipAlignment(taLeftJustify, UseRightToLeft);
WordBreak := False;
SingleLine:= True;
Clipping := True;
ShowPrefix := False;
SystemFont := False;
RightToLeft := UseRightToLeft;
ExpandTabs := True;
end;
if pdsDisabled in States then
Font.Color := clBtnShadow;
if pdsDown in States then
OffsetRect(Rect, 1 , 1);
DrawText(Canvas, Text, Rect, TS, UseRightToLeft);
end;
end;
procedure TntvTheme.DrawButtonEdge(Canvas: TCanvas; Rect: TRect; States: TdrawStates);
begin
if not (pdsDown in States) then
begin
Canvas.Pen.Color := Separator.Foreground;
Canvas.MoveTo(Rect.Left, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Top);
Canvas.LineTo(Rect.Right - 1, Rect.Top);
Canvas.Pen.Color := Separator.Background;
Canvas.LineTo(Rect.Right - 1, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Bottom - 1);
end
else
begin
Canvas.Pen.Color := Separator.Foreground;
Canvas.MoveTo(Rect.Left, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Top);
Canvas.LineTo(Rect.Right - 1, Rect.Top);
Canvas.Pen.Color := Separator.Background;
Canvas.LineTo(Rect.Right - 1, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Bottom - 1);
end;
end;
procedure TntvTheme.DrawButton(Canvas: TCanvas; Text: string; ImageWidth: Integer; Rect: TRect; States: TdrawStates; UseRightToLeft: Boolean);
begin
DrawButtonEdge(Canvas, Rect, States);
InflateRect(Rect, -1 , -1);
DrawButtonText(Canvas, Text, ImageWidth, Rect, States, UseRightToLeft);
end;
procedure TntvTheme.DrawImage(Canvas: TCanvas; ImageList: TImageList; ImageIndex: TImageIndex; Rect: TRect; States: TdrawStates);
var
X, Y: integer;
begin
x := Rect.Left + ((Rect.Right - Rect.Left) div 2) - (ImageList.Width div 2);
y := Rect.Top + ((Rect.Bottom - Rect.Top) div 2) - (ImageList.Height div 2);
ImageList.Draw(Canvas, x, y, ImageIndex, gdeNormal);
end;
procedure TntvTheme.DrawRect(Canvas: TCanvas; const Rect: TRect; Color, BorderColor: TColor);
begin
Canvas.Pen.Color := BorderColor;
Canvas.MoveTo(Rect.Left, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Top);
Canvas.LineTo(Rect.Right - 1, Rect.Top);
Canvas.LineTo(Rect.Right - 1, Rect.Bottom - 1);
Canvas.LineTo(Rect.Left, Rect.Bottom - 1);
end;
{ TntvThemeEngine }
procedure TntvThemeEngine.Switched;
begin
Notify;
end;
constructor TntvThemeEngine.Create;
begin
inherited;
FNotifyComponents := TComponentList.Create(False);
FThemes := TntvThemes.Create;
FThemes.Add(TntvTheme.Create(Self, 'Standard'));
FTheme := FThemes[0];
Switched;
end;
destructor TntvThemeEngine.Destroy;
begin
FreeAndNil(FThemes);
FreeAndNil(FNotifyComponents);
inherited Destroy;
end;
procedure TntvThemeEngine.AddNotification(AComponent: TComponent);
begin
FNotifyComponents.Add(AComponent);
end;
procedure TntvThemeEngine.RemoveNotification(AComponent: TComponent);
begin
FNotifyComponents.Remove(AComponent);
end;
procedure TntvThemeEngine.Correct;
begin
Theme.Correct;
end;
procedure TntvThemeEngine.Notify;
var
i: Integer;
begin
for i := 0 to FNotifyComponents.Count -1 do
begin
if FNotifyComponents[i] is IThemeNotify then
begin
(FNotifyComponents[i] as IThemeNotify).InvalidateTheme;
end;
end;
end;
finalization
FreeAndNil(FThemeEngine);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.