text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit BindCompProperties;
interface
uses
System.SysUtils, System.Classes, Data.Bind.Components,
System.Rtti, System.Generics.Collections, System.TypInfo;
type
TEnumeratePropertyProc = function(LProperty: TRttiProperty; AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var AEnumChildren: Boolean): Boolean of object;
TDataBindingComponentPropertyNames = class
private
FList: TList<string>;
FHasProperties: Boolean;
FComponent: TObject;
procedure UpdatePropertyNames;
function ListEnumeratePropertyCallback(AProperty: TRttiProperty;
AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
function HasEnumeratePropertyCallback(AProperty: TRttiProperty;
AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
function GetPropertyNames: TArray<string>;
function FilterProperty(AProperty: TRttiProperty): Boolean;
function GetHasProperties: Boolean;
function FindObjectPropertyInstance(AProperty: TRttiProperty;
AParentType: TRttiType; AParentProperties: TList<TRttiProperty>): TObject;
function CanAccessObjectProperties(AInstance: TObject): Boolean;
public
constructor Create(AComponent: TObject);
destructor Destroy; override;
property PropertyNames: TArray<string> read GetPropertyNames;
property HasProperties: Boolean read GetHasProperties;
end;
//procedure EnumeratePropertyNames(AType: TRttiType; AProc: TEnumeratePropertyProc); overload; forward;
//procedure EnumeratePropertyNames(AObject: TObject; AProc: TEnumeratePropertyProc); overload; forward;
implementation
uses Vcl.Graphics;
procedure EnumeratePropertyNames(AType: TRttiType; AParentProperty: TRttiProperty; AParentTypes: TList<TRttiType>;
AParentProperties: TList<TRttiProperty>;
AProc: TEnumeratePropertyProc); overload;
var
LProperties: TArray<TRttiProperty>;
LField: TRttiProperty;
LParentTypes: TList<TRttiType>;
LParentProperties: TList<TRttiProperty>;
LEnumChildren: Boolean;
begin
LProperties := AType.GetProperties;
if Length(LProperties) > 0 then
begin
if AParentTypes.Contains(AType) then
begin
// Recursive
Exit;
end;
if AParentProperty <> nil then
AParentProperties.Add(AParentProperty);
AParentTypes.Add(AType);
for LField in LProperties do
begin
LParentTypes := TList<TRttiType>.Create(AParentTypes);
LParentProperties := TList<TRttiProperty>.Create(AParentProperties);
try
LEnumChildren := True;
if not AProc(LField, LParentTypes[0], LParentProperties, LEnumChildren) then
break;
if LEnumChildren then
EnumeratePropertyNames(LField.PropertyType, LField, LParentTypes, LParentProperties, AProc);
finally
LParentTypes.Free;
LParentProperties.Free;
end;
end;
end;
end;
procedure EnumeratePropertyNames(AType: TRttiType; AProc: TEnumeratePropertyProc); overload;
var
LParentTypes: TList<TRttiType>;
LParentProperties: TList<TRttiProperty>;
begin
LParentTypes := TList<TRttiType>.Create;
LParentProperties := TList<TRttiProperty>.Create;
try
EnumeratePropertyNames(AType, nil, LParentTypes, LParentProperties, AProc);
finally
LParentTypes.Free;
LParentProperties.Free;
end;
end;
procedure EnumeratePropertyNames(AObject: TObject; AProc: TEnumeratePropertyProc); overload;
var
LContext: TRttiContext;
LType: TRttiInstanceType;
begin
if AObject <> nil then
begin
LType := LContext.GetType(AObject.ClassType) as TRttiInstanceType;
EnumeratePropertyNames(LType, AProc);
end;
end;
constructor TDataBindingComponentPropertyNames.Create(AComponent: TObject);
var
LScopeComponent: IScopeComponent;
begin
Assert(AComponent <> nil);
if Supports(AComponent, IScopeComponent, LScopeComponent) then
FComponent := LScopeComponent.GetScopeObject
else
FComponent := AComponent;
end;
destructor TDataBindingComponentPropertyNames.Destroy;
begin
FList.Free;
inherited;
end;
function TDataBindingComponentPropertyNames.FilterProperty(AProperty: TRttiProperty): Boolean;
function GetEnumBaseType(ATypeInfo: PTypeInfo): PTypeInfo;
var
pResult: PPTypeInfo;
begin
if (ATypeInfo = nil) or (ATypeInfo^.Kind <> tkEnumeration) then
Exit(nil);
Result := ATypeInfo;
while True do
begin
pResult := GetTypeData(Result)^.BaseType;
if (pResult <> nil) and (pResult^ <> nil) and (pResult^ <> Result) then
Result := pResult^
else
Break;
end;
end;
function IsBoolType(ATypeInfo: PTypeInfo): Boolean;
begin
ATypeInfo := GetEnumBaseType(ATypeInfo);
Result := (ATypeInfo = System.TypeInfo(Boolean)) or
(ATypeInfo = System.TypeInfo(ByteBool)) or
(ATypeInfo = System.TypeInfo(WordBool)) or
(ATypeInfo = System.TypeInfo(LongBool));
end;
begin
Result := False;
if not AProperty.IsWritable then
Exit;
if AProperty.Visibility = TMemberVisibility.mvPrivate then
Exit;
if AProperty.Visibility = TMemberVisibility.mvProtected then
Exit;
case AProperty.PropertyType.TypeKind of
tkUnknown: ;
tkInteger: Result := True;
tkChar: Result := True;
tkEnumeration: Result := IsBoolType(AProperty.PropertyType.Handle); // Only boolean enumeration supported
tkFloat: Result := True;
tkString: Result := True;
tkSet: Result := False; // Sets not supported
tkClass: Result := True; // Caller is responsible for filtering object types
tkMethod: ;
tkWChar: Result := True;
tkLString: Result := True;
tkWString: Result := True;
tkVariant: Result := True;
tkArray: ;
tkRecord,
tkMRecord: ;
tkInterface: ;
tkInt64: Result := True;
tkDynArray: ;
tkUString: Result := True;
tkClassRef: ;
tkPointer: ;
tkProcedure: ;
end;
end;
function TDataBindingComponentPropertyNames.HasEnumeratePropertyCallback(
AProperty: TRttiProperty; AParentType: TRttiType;
AParentProperties: TList<TRttiProperty>; var LEnumChildren: Boolean): Boolean;
begin
LEnumChildren := False;
if not FilterProperty(AProperty) then
Exit(True);
FHasProperties := True;
Exit(False);
end;
function TDataBindingComponentPropertyNames.CanAccessObjectProperties(AInstance: TObject): Boolean;
begin
Result := True;
if AInstance is TPicture then
Result := False;
end;
function TDataBindingComponentPropertyNames.FindObjectPropertyInstance(AProperty: TRttiProperty; AParentType: TRttiType; AParentProperties: TList<TRttiProperty>): TObject;
var
LParentProperty: TRttiProperty;
LInstance: TObject;
LValue: TValue;
begin
Result := nil;
try
LInstance := Self.FComponent;
for LParentProperty in AParentProperties do
begin
LValue := LParentProperty.GetValue(LInstance);
if LValue.IsObject then
LInstance := LValue.AsObject
else
LInstance := nil;
if LInstance = nil then
break;
end;
if LInstance <> nil then
begin
if not CanAccessObjectProperties(LInstance) then
Result := nil
else
begin
LValue := AProperty.GetValue(LInstance);
if LValue.IsObject then
Result := LValue.AsObject
end;
end;
except
// Ignore exceptions while retreiving. Some
// objects raise exception when property getter is called.
// Such as VCL TImage.Bitmap
end;
end;
function TDataBindingComponentPropertyNames.ListEnumeratePropertyCallback(AProperty: TRttiProperty; AParentType: TRttiType; AParentProperties: TList<TRttiProperty>;
var LEnumChildren: Boolean): Boolean;
var
LName: string;
LParentProperty: TRttiProperty;
LInstance: TObject;
LSkipProperty: Boolean;
LParentInstance: TObject;
begin
// Only go one level deep for child properties
LEnumChildren := (AParentProperties.Count < 1) and (AProperty.PropertyType.TypeKind = tkClass);
if LEnumChildren then
begin
LParentInstance := FindObjectPropertyInstance(AProperty, AParentType, AParentProperties);
LEnumChildren := LParentInstance <> nil;
end;
LSkipProperty := False;
if not FilterProperty(AProperty) then
LSkipProperty := True
else if AProperty.PropertyType.TypeKind = tkClass then
begin
LInstance := FindObjectPropertyInstance(AProperty, AParentType, AParentProperties);
if LInstance = nil then
LSkipProperty := True
else
begin
if Supports(LInstance, IStreamPersist) // Support bitmaps and TStrings
// or (LInstance is TPersistent)
then
begin
// Allow
end
else
LSkipProperty := True;
end;
end;
if LSkipProperty then
Exit(True);
try
for LParentProperty in AParentProperties do
if LName <> '' then
LName := LName + '.' + LParentProperty.Name
else
LName := LParentProperty.Name;
if LName <> '' then
LName := LName + '.' + AProperty.Name
else
LName := AProperty.Name;
except
LName := AProperty.Name;
end;
if not FList.Contains(LName) then
FList.Add(LName);
Result := True;
end;
function TDataBindingComponentPropertyNames.GetHasProperties: Boolean;
begin
FHasProperties := False;
EnumeratePropertyNames(FComponent, HasEnumeratePropertyCallback);
Result := FHasProperties;
end;
function TDataBindingComponentPropertyNames.GetPropertyNames: TArray<string>;
begin
if FList = nil then
begin
FList := TList<string>.Create;
UpdatePropertyNames;
end;
Result := FList.ToArray;
end;
procedure TDataBindingComponentPropertyNames.UpdatePropertyNames;
begin
FList.Clear;
EnumeratePropertyNames(FComponent, ListEnumeratePropertyCallback);
end;
end.
|
unit importprops;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, EditBtn, StdCtrls,
Grids, ExtCtrls, Spin, ComCtrls, Inifiles,
main, gozgraph;
const
NEW_ITEM = 'Element hinzufügen...';
type
{ TImportItemPropertiesForm }
TImportItemPropertiesForm = class(TForm)
Button1: TButton;
Button2: TButton;
ButtonImportProperty: TButton;
ButtonDeleteProperty: TButton;
CheckBoxHasHeaders: TCheckBox;
ComboBoxDelimiter: TComboBox;
ComboBoxItem: TComboBox;
EditProperty: TEdit;
FileNameEdit1: TFileNameEdit;
Label1: TLabel;
Label10: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label7: TLabel;
ListBoxProperty: TListBox;
ListView1: TListView;
Panel1: TPanel;
Panel2: TPanel;
StringGrid1: TStringGrid;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ButtonImportPropertyClick(Sender: TObject);
procedure ButtonDeletePropertyClick(Sender: TObject);
procedure CheckBoxHasHeadersChange(Sender: TObject);
procedure ComboBoxDelimiterChange(Sender: TObject);
procedure FileNameEdit1AcceptFileName(Sender: TObject; var Value: String);
procedure FileNameEdit1Change(Sender: TObject);
procedure ListBoxPropertyClick(Sender: TObject);
private
FGozGraph : TGozIntoGraph;
public
function ShowModal: Integer; override;
published
property GozGraph : TGozIntoGraph read FGozGraph write FGozGraph;
end;
var
ImportItemPropertiesForm: TImportItemPropertiesForm;
implementation
{$R *.lfm}
uses gozfunc;
{ TImportItemPropertiesForm }
function TImportItemPropertiesForm.ShowModal: Integer;
var
Ini : TInifile;
s : string;
item : TListitem;
begin
if FGozGraph=nil then exit;
try
Ini:=TInifile.Create(ConfigFilename);
s:='Import CSV Props';
ComboBoxDelimiter.Text:=Ini.ReadString(s,'Delimiter',';');
ComboBoxItem.Text:=Ini.ReadString(s,'Item','');
CheckBoxHasHeaders.Checked:=Ini.ReadBool(s,'HasHeaders',false);
Ini.Free;
except
end;
Listview1.Items.Clear;
FGozGraph.Properties.UpdateListview(Listview1);
item:=Listview1.Items.Add;
item.ImageIndex:=-1;
item.caption:=NEW_ITEM;
Result:=inherited ShowModal;
end;
procedure TImportItemPropertiesForm.Button2Click(Sender: TObject);
begin
Close;
end;
procedure TImportItemPropertiesForm.ButtonImportPropertyClick(Sender: TObject);
var
item : TListitem;
begin
if Listview1.Selected=nil then
begin
MessageDlg('Vorher eine Eigenschaft in der Liste auswählen!',mtInformation,[mbOk],0);
exit;
end;
item:=Listview1.Selected;
if item.Caption=NEW_ITEM then
begin
if ListBoxProperty.ItemIndex=-1 then
begin
MessageDlg('Vorher eine Spalte auswählen.',mtInformation,[mbOk],0);
exit;
end;
if EditProperty.Text='' then
begin
MessageDlg('Vorher eine Spaltennamen vergeben.',mtInformation,[mbOk],0);
exit;
end;
item:=Listview1.Items.Insert(Listview1.Items.Count-1);
item.ImageIndex:=2; //new
item.Caption:=EditProperty.Text;
item.SubItems.Add(ListBoxProperty.Items[ListBoxProperty.ItemIndex]);
if ListBoxProperty.ItemIndex<ListBoxProperty.Items.Count-1 then
begin
ListBoxProperty.ItemIndex:=ListBoxProperty.ItemIndex+1;
ListBoxPropertyClick(Sender);
end;
end
else
begin
item.ImageIndex:=1; //update
if item.SubItems.Count=0 then item.SubItems.Add('');
item.SubItems[0]:=ListBoxProperty.Items[ListBoxProperty.ItemIndex];
end;
end;
procedure TImportItemPropertiesForm.ButtonDeletePropertyClick(Sender: TObject);
var
item : TListitem;
begin
if Listview1.Selected=nil then
begin
MessageDlg('Vorher einen Eintrag in der Liste auswählen!',mtInformation,[mbOk],0);
exit;
end;
item:=Listview1.Selected;
if item.ImageIndex=1 then
begin
item.ImageIndex:=0;
item.SubItems[0]:='';
end
else if item.ImageIndex=2 then item.Delete;
end;
procedure TImportItemPropertiesForm.CheckBoxHasHeadersChange(Sender: TObject);
begin
FileNameEdit1Change(Sender);
end;
procedure TImportItemPropertiesForm.ComboBoxDelimiterChange(Sender: TObject);
begin
FileNameEdit1Change(Sender);
end;
procedure TImportItemPropertiesForm.FileNameEdit1AcceptFileName(
Sender: TObject; var Value: String);
begin
FileNameEdit1Change(Sender);
end;
procedure TImportItemPropertiesForm.FileNameEdit1Change(Sender: TObject);
var
sl : TStringList;
sr : TStringArray;
i,j,k : integer;
begin
if FileExists(FileNameEdit1.FileName)=false then exit;
sl:=TStringList.Create;
sl.LoadFromFile(FileNameEdit1.FileName);
if sl.Count>5 then j:=5
else sl.Count;
StringGrid1.RowCount:=j+1;
StringGrid1.ColCount:=1;
if CheckBoxHasHeaders.Checked then StringGrid1.FixedRows:=2
else StringGrid1.FixedRows:=1;
for i:=0 to j-1 do
begin
sr:=sl[i].Split(ComboBoxDelimiter.Text);
if length(sr)>StringGrid1.ColCount then StringGrid1.ColCount:=length(sr);
for k:=0 to length(sr)-1 do
StringGrid1.Cells[k,i+1]:=sr[k];
end;
ComboBoxItem.Items.Clear;
for k:=0 to StringGrid1.ColCount-1 do
begin
StringGrid1.Cells[k,0]:=IntToStr(k+1);
ComboBoxItem.Items.Add(IntToStr(k+1));
end;
ListBoxProperty.Items.Assign(ComboBoxItem.Items);
sl.Free;
end;
procedure TImportItemPropertiesForm.ListBoxPropertyClick(Sender: TObject);
var
index : integer;
begin
if ListBoxProperty.ItemIndex=-1 then exit;
index:=StrInt(ListBoxProperty.Items[ListBoxProperty.ItemIndex]);
if CheckBoxHasHeaders.Checked and (index>0)then
EditProperty.Text:=StringGrid1.Cells[index-1,1];
end;
procedure TImportItemPropertiesForm.Button1Click(Sender: TObject);
var
PosItem : integer;
s : string;
begin
if ComboBoxItem.Text='' then
begin
MessageDlg('Achtung','Bitte vorher Element eintragen.',mtInformation,[mbOK],0);
exit;
end;
if ComboBoxDelimiter.Text='' then
begin
MessageDlg('Achtung','Bitte vorher Trennzeichen eintragen.',mtInformation,[mbOK],0);
exit;
end;
if not FileExists(FileNameEdit1.FileName) then
begin
MessageDlg('Achtung','Bitte vorher eine gültige CSV-Datei auswählen.',mtInformation,[mbOK],0);
exit;
end;
if ComboBoxItem.Text='' then PosItem:=-1
else PosItem:=StrInt(ComboBoxItem.Text);
FGozGraph.ImportPropsFromCsvFile(
FileNameEdit1.FileName,
ComboBoxDelimiter.Text,
CheckboxHasHeaders.Checked,
PosItem,
Listview1);
Close;
end;
end.
|
{===================================================================
NPC Schematics 2016
Tutorial: Pirito in a Pinch
by Baharuddin Aziz
September 3, 2016
===================================================================}
program pirito_in_a_pinch;
{ DEKLARASI VARIABEL }
var
// input
m : integer; // jarak Pirito dan kota
n : integer; // kecepatan jalan per menit
x : integer; // berhenti setiap jarak x
// output
durasi : real; // durasi utk berjalan ke kota
begin
{ INISIALISASI VARIABEL }
// membaca masukan user
read(m,n,x);
{ ALGORITMA }
if (m mod x <> 0) then
begin
durasi := (m div n) + (m div x) * 0.5;
writeln(durasi:0:3);
end
else
begin
durasi := (m div n) + (m div x - 1) * 0.5;
writeln(durasi:0:3);
end;
end.
|
unit uCliente;
interface
type
TCliente = class
private
FIdCliente: integer;
FNome: string;
FCNPJ: string;
procedure SetCNPJ(const Value: string);
procedure SetIdCliente(const Value: integer);
procedure SetNome(const Value: string);
protected
public
constructor Create;
destructor Destroy; override;
property IdCliente: integer read FIdCliente write SetIdCliente;
property Nome: string read FNome write SetNome;
property CNPJ: string read FCNPJ write SetCNPJ;
published
end;
implementation
{ TCliente }
constructor TCliente.Create;
begin
inherited;
end;
destructor TCliente.Destroy;
begin
inherited;
end;
procedure TCliente.SetCNPJ(const Value: string);
begin
FCNPJ := Value;
end;
procedure TCliente.SetIdCliente(const Value: integer);
begin
FIdCliente := Value;
end;
procedure TCliente.SetNome(const Value: string);
begin
FNome := Value;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 22 O(N3)? Trivial Method
}
program
BiPartiteSpanningSubGraph;
const
MaxN = 100;
var
N : Integer;
A : array [1 .. MaxN, 1 .. MaxN] of Integer;
P, D, Dp : array [1 .. MaxN] of Integer;
I, J : Integer;
Fl : Boolean;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, A[I, J]); A[J, I] := A[I, J];
Inc(D[I], A[I, J]); Inc(D[J], A[I, J]);
end;
Readln(F);
end;
Close(F);
end;
procedure BipSpanTree;
begin
repeat
Fl := True;
for I := 1 to N do
if Dp[I] < D[I] / 2 then
begin
for J := 1 to N do
if A[I, J] = 1 then
if P[J] + P[I] = 1 then
Dec(Dp[J])
else
Inc(Dp[J]);
P[I] := 1 - P[I]; Dp[I] := D[I] - Dp[I];
Fl := False;
end;
until Fl;
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
Writeln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
if P[I] + P[J] = 1 then
Write(F, A[I, J], ' ')
else
Write(F, 0, ' ');
Writeln(F);
end;
Close(F);
end;
begin
ReadInput;
BipSpanTree;
WriteOutput;
end.
|
unit agmapxmltotable_classes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TagMapTable = class;
TagMapTableField = class;
TagMapTableFields = class;
{ TagMapTable }
TagMapTable = class(TPersistent)
private
FBaseClassName: string;
Foid_type: string;
FPK: String;
Fpk_field: String;
FTableName: String;
FMapTableFields: TagMapTableFields;
function GetMapTableFields(Index: Integer): TagMapTableFields;
procedure SetBaseClassName(AValue: string);
procedure SetMapTableFields(Index: Integer; AValue: TagMapTableFields);
procedure Setoid_type(AValue: string);
procedure SetPK(AValue: String);
procedure Setpk_field(AValue: String);
procedure SetTableName(AValue: String);
protected
public
constructor Create; override;
destructor Destroy; override;
published
property BaseClassName: string read FBaseClassName write SetBaseClassName;
property TableName: String read FTableName write SetTableName;
property PK: String read FPK write SetPK;
property pk_field: String read Fpk_field write Setpk_field;
property oid_type: string read Foid_type write Setoid_type;
property MapTableFields[Index: Integer]: TagMapTableFields read GetMapTableFields write SetMapTableFields;
end;
implementation
{ TagMapTable }
procedure TagMapTable.SetBaseClassName(AValue: string);
begin
if FBaseClassName=AValue then Exit;
FBaseClassName:=AValue;
end;
function TagMapTable.GetMapTableFields(Index: Integer): TagMapTableFields;
begin
end;
procedure TagMapTable.SetMapTableFields(Index: Integer;
AValue: TagMapTableFields);
begin
end;
procedure TagMapTable.Setoid_type(AValue: string);
begin
if Foid_type=AValue then Exit;
Foid_type:=AValue;
end;
procedure TagMapTable.SetPK(AValue: String);
begin
if FPK=AValue then Exit;
FPK:=AValue;
end;
procedure TagMapTable.Setpk_field(AValue: String);
begin
if Fpk_field=AValue then Exit;
Fpk_field:=AValue;
end;
procedure TagMapTable.SetTableName(AValue: String);
begin
if FTableName=AValue then Exit;
FTableName:=AValue;
end;
constructor TagMapTable.Create;
begin
inherited Create;
FMapTableFields := TagMapTableFields.Create;
end;
destructor TagMapTable.Destroy;
begin
inherited Destroy;
FMapTableFields.Free;
end;
end.
|
Unit MainForm;
Interface
Uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, WLanAPI,
WlanAPIClient, WlanInterface, wlanNetwork, Vcl.ComCtrls,
WlanBssEntry, Vcl.OleCtrls, SHDocVw;
Type
TForm1 = Class (TForm)
Panel1: TPanel;
ComboBox1: TComboBox;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
ListView1: TListView;
CardListTimer: TTimer;
Panel2: TPanel;
Button1: TButton;
Button2: TButton;
Label1: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure RefreshNetworks(Sender: TObject);
procedure ListView1Deletion(Sender: TObject; Item: TListItem);
procedure RefreshNetworkCards(Sender: TObject);
Procedure RefreshAll(Sender:TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ListView1SelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
Private
FWlanClient : TWlanAPICLient;
Function BooleanToStr(X:Boolean):WideSTring;
end;
Var
Form1: TForm1;
Implementation
{$R *.DFM}
Uses
APSelectionForm;
Procedure TForm1.RefreshAll(Sender:TObject);
begin
RefreshNetworkCards(ComboBox1);
RefreshNetworks(Nil);
end;
Function TForm1.BooleanToStr(X:Boolean):WideSTring;
begin
If X Then
Result := 'Ano'
Else Result := 'Ne';
end;
Procedure TForm1.RefreshNetworkCards(Sender: TObject);
Var
CardList : TList;
Card : TWlanInterface;
Ret : Boolean;
I : Integer;
ItemGuid : TGUID;
LastState : TWlanInterfaceState;
SelectedSurvived : Boolean;
begin
CardList := TList.Create;
If FWlanClient.EnumInterfaces(CardList) Then
begin
SelectedSurvived := False;
If ComboBox1.ItemIndex > -1 Then
begin
Card := TWlanInterface(ComboBox1.Items.Objects[ComboBox1.ItemIndex]);
ItemGuid := Card.Guid^;
LastState := Card.State;
end;
For I := 0 To CardList.Count - 1 Do
begin
Card := CardList[I];
If I < ComboBox1.Items.Count Then
begin
ComboBox1.Items.Strings[I] := Format('%s (%s)', [Card.Description, TWlanInterface.StateToStr(Card.State)]);
ComboBox1.Items.Objects[I].Free;
ComboBox1.Items.Objects[I] := Card;
If ItemGuid = Card.Guid^ Then
begin
SelectedSurvived := True;
ComboBox1.ItemIndex := I;
end;
If Card.State <> LastState Then
RefreshNetworks(Nil);
end
Else ComboBox1.AddItem(Format('%s (%s)', [Card.Description, TWlanInterface.StateToStr(Card.State)]), Card);
end;
While ComboBox1.Items.Count > CardList.Count Do
ComboBox1.Items.Delete(ComboBox1.Items.Count - 1);
If Not SelectedSurvived Then
ComboBox1.ItemIndex := 0;
ComboBox1.Invalidate;
end;
CardList.Free;
end;
Procedure TForm1.RefreshNetworks(Sender: TObject);
Var
I : Integer;
NetworkList : TList;
WlanInterface : TWlanInterface;
WlanNetwork : TWlanNetwork;
L : TListItem;
begin
If ComboBox1.ItemIndex > -1 Then
begin
WlanInterface := TWlanInterface(ComboBox1.Items.Objects[ComboBox1.ItemIndex]);
NetworkList := TList.Create;
If WlanInterface.EnumNetworks(NetworkList) Then
begin
ListView1.Items.BeginUpdate;
For I := 0 To NetworkList.Count - 1 Do
begin
WlanNetwork := NetworkList[I];
If I < ListView1.Items.Count Then
begin
L := ListVIew1.Items[I];
With L Do
begin
TWlanNetwork(Data).Free;
Data := WlanNetwork;
Caption := WlanNetwork.SSID;
SubItems[0] := TWlanNetwork.AuthAlgoToStr(WlanNetwork.AuthenticationAlgo);
SubItems[1] := TWlanNetwork.CipherAlgoToSTr(WLanNetwork.CipherAlgo);
SubItems[2] := TWlanNetwork.BSSTypeToSTr(WlanNetwork.BSSType);
SubItems[3] := Format('%d', [WlanNetwork.NumberOfBSSIDs]);
SubItems[4] := Format('%d %%', [WlanNetwork.SignalQuality]);
SubItems[5] := BooleanToStr(WlanNetwork.Connected);
end;
end
Else begin
L := ListView1.Items.Add;
With L Do
begin
Data := WlanNetwork;
Caption := WlanNetwork.SSID;
SubItems.Add(TWlanNetwork.AuthAlgoToStr(WlanNetwork.AuthenticationAlgo));
SubItems.Add(TWlanNetwork.CipherAlgoToSTr(WLanNetwork.CipherAlgo));
SubItems.Add(TWlanNetwork.BSSTypeToSTr(WlanNetwork.BSSType));
SubItems.Add(Format('%d', [WlanNetwork.NumberOfBSSIDs]));
SubItems.Add(Format('%d %%', [WlanNetwork.SignalQuality]));
SubItems.Add(BooleanToStr(WlanNetwork.Connected));
end;
end;
end;
While ListView1.Items.Count > NetworkList.Count Do
ListView1.Items.Delete(ListView1.Items.Count - 1);
ListView1.Items.EndUpdate;
end
Else ListView1.Clear;
NetworkList.Free;
end
Else ListView1.Clear;
end;
Procedure TForm1.Button1Click(Sender: TObject);
Var
I : Integer;
L : TListItem;
N : TWlanNetwork;
begin
CardListTimer.Enabled := False;
L := ListView1.Selected;
If Assigned(L) Then
begin
ListView1.Selected := Nil;
N := TWlanNetwork(L.Data);
With TForm2.Create(Application, N) Do
begin
ShowModal;
If Not Cancelled Then
begin
N.Connect(MacList);
For I := 0 To MacList.Count - 1 Do
TWlanBssEntry(MacList[I]).Free;
MacList.Clear;
MacList.Free;
end;
Free;
end;
end;
CardListTimer.Enabled := True;
end;
Procedure TForm1.Button2Click(Sender: TObject);
Var
L : TListItem;
N : TWlanNetwork;
begin
CardListTimer.Enabled := False;
L := ListView1.Selected;
If Assigned(L) Then
begin
N := TWlanNetwork(L.Data);
ListView1.Selected := Nil;
N.Disconnect;
end;
CardListTimer.Enabled := True;
end;
Procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CardListTimer.Enabled := False;
If Assigned(FWlanClient) Then
FreeAndNil(FWlanClient);
end;
Procedure TForm1.FormCreate(Sender: TObject);
Var
I : Integer;
CardList : TList;
Tmp : TWlanInterface;
begin
FWlanClient := TWlanAPIClient.NewInstance;
If Not Assigned(FWlanClient) THen
Raise Exception.Create('Nepodařilo se připojit ke slubě Automatická konfigurace bezdrátových sítí');
CardList := TList.Create;
If Not FWlanClient.EnumInterfaces(CardList) Then
begin
CardList.Free;
FreeAndNil(FWlanClient);
Raise Exception.Create('Nepodařilo se získat seznam dostupných síových karet');
end;
For I := 0 To CardList.Count - 1 Do
begin
Tmp := CardList[I];
ComboBox1.AddItem(Format('%s (%s)', [Tmp.Description, TWlanInterface.StateToStr(Tmp.State)]), Tmp);
end;
CardList.Free;
ComboBox1.ItemIndex := 0;
RefreshNetworks(Nil);
CardListTimer.Enabled := True;
end;
Procedure TForm1.ListView1Deletion(Sender: TObject; Item: TListItem);
begin
If Assigned(Item.Data) Then
TWlanNetwork(Item.Data).Free;
Item.Data := Nil;
end;
Procedure TForm1.ListView1SelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
Var
Net : TWlanNetwork;
begin
Net := Item.Data;
Button1.Enabled := (Selected) And (Not Net.Connected);
Button2.Enabled := (Selected) And (Net.Connected);
end;
End.
|
unit BuyStoreSelect;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, ComCtrls, ToolWin;
type
TBuyStoreSelectForm = class(TForm)
Panel1: TPanel;
CancelButton: TButton;
OKButton: TButton;
DBGridEh1: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Edit1: TEdit;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
BuyStoreSelectForm: TBuyStoreSelectForm;
implementation
uses StoreDM, BuyStoreItem;
{$R *.dfm}
procedure TBuyStoreSelectForm.FormCreate(Sender: TObject);
begin
with StoreDataModule do
begin
BuyStoreDataSet.Locate('StoreID', BuyStructureDataSet['StoreID'], []);
end;
end;
procedure TBuyStoreSelectForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
{ with StoreDataModule do
begin
end;{}
end;
procedure TBuyStoreSelectForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TBuyStoreSelectForm.OKButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TBuyStoreSelectForm.InsertButtonClick(Sender: TObject);
begin
StoreDataModule.BuyStoreDataSet.Append;
StoreDataModule.BuyStoreDataSet['DivisionID'] := StoreDataModule.DivisionSelectQuery['DivisionID'];
StoreDataModule.BuyStoreDataSet['DivisionName'] := StoreDataModule.DivisionSelectQuery['DivisionName'];
StoreDataModule.BuyStoreDataSet['ProductID'] := StoreDataModule.BuyStructureDataSet['ProductID'];
BuyStoreItemForm := TBuyStoreItemForm.Create(Self);
BuyStoreItemForm.ShowModal;
end;
procedure TBuyStoreSelectForm.EditButtonClick(Sender: TObject);
begin
StoreDataModule.BuyStoreDataSet.Edit;
BuyStoreItemForm := TBuyStoreItemForm.Create(Self);
BuyStoreItemForm.ShowModal;
end;
procedure TBuyStoreSelectForm.DeleteButtonClick(Sender: TObject);
var
StoreStr : String;
begin
StoreStr := StoreDataModule.BuyStoreDataSet['StoreID'];
if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' +
StoreStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
StoreDataModule.BuyStoreDataSet.Delete;
except
Application.MessageBox(PChar('Запись "' + StoreStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end;
end;
procedure TBuyStoreSelectForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
postmessage(OKButton.handle,cn_command,bn_clicked,0);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.Midas;
interface
{$IFDEF MSWINDOWS}
uses Winapi.ActiveX;
{$ENDIF}
const
LIBID_Midas: TGUID = '{83F57D68-CA9A-11D2-9088-00C04FA35CFA}';
IID_IAppServer: TGUID = '{1AEFCC20-7A24-11D2-98B0-C69BEB4B5B6D}';
type
{$M+}
IAppServer = interface(IDispatch)
['{1AEFCC20-7A24-11D2-98B0-C69BEB4B5B6D}']
function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall;
function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer;
Options: Integer; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant): OleVariant; safecall;
function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall;
function AS_GetProviderNames: OleVariant; safecall;
function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall;
function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer;
var OwnerData: OleVariant): OleVariant; safecall;
procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant); safecall;
end;
{$M-}
{$IFDEF WIN32}
{ Raw C++ version of IAppServer for C++Builder [235941 ] }
(*$HPPEMIT'#if !defined(NO_CPP_IAPPSERVER)' *)
(*$HPPEMIT'namespace Datasnap {' *)
(*$HPPEMIT' namespace Midas {' *)
(*$HPPEMIT' __interface INTERFACE_UUID("{1AEFCC20-7A24-11D2-98B0-C69BEB4B5B6D}") ICppAppServer : public IDispatch' *)
(*$HPPEMIT' {' *)
(*$HPPEMIT' public:' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_ApplyUpdates(BSTR ProviderName, VARIANT Delta, long MaxErrors, int* ErrorCount, VARIANT* OwnerData, VARIANT* AS_ApplyUpdates_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_GetRecords(BSTR ProviderName, long Count, int* RecsOut, long Options, BSTR CommandText, VARIANT* Params, VARIANT* OwnerData, VARIANT* AS_GetRecords_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_DataRequest(BSTR ProviderName, VARIANT Data, VARIANT* AS_DataRequest_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_GetProviderNames(VARIANT* AS_GetProviderNames_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_GetParams(BSTR ProviderName, VARIANT* OwnerData, VARIANT* AS_GetParams_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_RowRequest(BSTR ProviderName, VARIANT Row, long RequestType, VARIANT* OwnerData, VARIANT* AS_RowRequest_result) = 0 ;' *)
(*$HPPEMIT' virtual HRESULT __stdcall AS_Execute(BSTR ProviderName, BSTR CommandText, VARIANT* Params, VARIANT* OwnerData) = 0 ;' *)
(*$HPPEMIT' };' *)
(*$HPPEMIT' }' *)
(*$HPPEMIT'}' *)
(*$HPPEMIT'#endif' *)
{$ENDIF}
IAppServerDisp = dispinterface
['{1AEFCC20-7A24-11D2-98B0-C69BEB4B5B6D}']
function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; dispid 20000000;
function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer;
Options: Integer; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant): OleVariant; dispid 20000001;
function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; dispid 20000002;
function AS_GetProviderNames: OleVariant; dispid 20000003;
function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; dispid 20000004;
function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer;
var OwnerData: OleVariant): OleVariant; dispid 20000005;
procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString;
var Params: OleVariant; var OwnerData: OleVariant); dispid 20000006;
end;
implementation
end.
|
(*
* (c) Copyright 1995, MAP Ltd., Veldhoven
*
* Function : SLV21.PAS
*
* Abstract : Source Lister Version 2.1
*
* Description : see Summary
*
* History : MV ð Menno A.P.J. Vogels
*
* Version 1.9 source, 93-11
*
* 940122, added the headers and comment, MV
* 940123, added comment, MV
* 940124, added comment, I-option and UpStr, MV
* 940125, added 'WAIT' indicators, MV
*
* Version 2.0 source, 94-01
*
* 940423, split up copyright string, MV
* 940509, changed help screen, MV
* 940526, added UNIX switch indicator '-', MV
* 940529, changed function 'IncludeIn',
* added conditional compilation directives, MV
* 940607, added perforation skip option (partly !!), MV
* 940611, added date & time for debugging log-file, MV
* 940617, added the StripZeroParam function, MV
* 940720, changed perforation skip implementation
* (CheckCurrentRow function), MV
* 940727, changed Help procedure for new header implementation,
* changed Replace function, MV
* 940728, added tabsize option, MV
* 940729, changed ProcessLine procedure, MV
*
* Version 2.1 source, 95-mm
*
* Summary :
*)
program
Source__Lister (input,output);
(*--- USED UNITS ---*)
uses
Crt, Dos;
(*--- GLOBAL TYPES, see forward too ---*)
type
LPT_TYPE = (LPT1, LPT2, LPT3);
(*--- GLOBAL CONSTANTS ---*)
{$IFDEF DEBUG}
const
DebugFileName = 'DEBUG.LOG';
{$ENDIF}
const
PathLength = 127;
WorkStringLength = 240;
ProgramName : array[1..13] of Byte =
{ S o u r c e L i s t e r }
( 83,111,117,114, 99,101, 32, 76,105,115,116,101,114);
Version : array[1..12] of Byte =
{ V e r s i o n 2 . 1 á }
( 86,101,114,115,105,111,110, 32, 50, 46, 49,225);
Company : array[1..8] of Byte =
{ M A P L t d . }
( 77, 65, 80, 32, 76,116,100, 46);
Year : array[1..3] of Byte =
{ ' 9 4 }
( 39, 57, 52);
{ Number of new lines for -one- vertical tab }
VerticalTabLength = 3;
{ Horizontal positions in relation to current cursor position }
InitPrinterStrX = 2;
InitPrinterIndX = 0;
ProcessStrX = 2;
ProcessIndX = 0;
{ Vertical positions in relation to current cursor position }
InitPrinterStrY = 2;
InitPrinterIndY = 2;
ProcessStrY = 2;
ProcessIndY = 2;
{ Default values }
DefLeftMargin = 10;
DefRightMargin = 90;
DefPrintLength = 60;
DefTabSize = 8;
{ Character indicators }
LeftMarginChar = '[';
RightMarginChar = ']';
PrintLengthChar = '=';
{ Minimum values }
LeftMarginMin = 5;
RightMarginMin = LeftMarginMin +2;
PrintLengthMin = 5;
TabSizeMin = 1;
{ Maximum values }
RightMarginMax = 255;
LeftMarginMax = RightMarginMax -2;
PrintLengthMax = 255;
TabSizeMax = 255;
{ Different forms that the include compiler directive can take }
IncludeSearch : array[1..4] of String[5] =
('{$'+'I',
'{$'+'i',
'(*$'+'I',
'(*$'+'i'
);
{ Option switch indicators }
SwitchInd = ['/','-'];
{ Status phase indicators }
StatusStr : array[0..4] of String[51] =
(' ',
'ADD PAPER TO THE OUTPUT DEVICE !!! ',
'PRESS THE -ON LINE- BUTTON ON THE OUTPUT DEVICE !!!',
'THE OUTPUT DEVICE IS BUSY, PLEASE WAIT !!! ',
'Undetermined ERROR, CHECK IT OUT !!! '
);
{ Process phase indicators }
ProcessStr : array[1..2] of String[15] =
('Printing file ',
' completed '
);
{ Output device identifiers }
LPTByte : array[LPT_TYPE] of Byte = (0,1,2);
LPTString : array[LPT_TYPE] of String[4] =
('LPT1',
'LPT2',
'LPT3'
);
(*--- GLOBAL TYPES ---*)
type
WORK_STRING = String[WorkStringLength];
(*--- GLOBAL VARIABLES ---*)
var
CurrentRow,
CurrentY,
RightMargin,
LeftMargin,
PageWidth,
PrintLength,
TabSize,
ProcessStage : Byte;
MainFileName : ComStr;
MainFile : Text;
LPT : LPT_TYPE;
SkipPerforation,
Quality,
Include : Boolean;
(*--- FUNCTION AND PROCEDURE DEFINITIONS ---*)
{$IFDEF DEBUG}
(*
* Function : LeadingZero
* Abstract : Converts a word type identifier to a string type
* identifier and adds a zero to give the string a
* length of two characters
* Decisions :
*)
function LeadingZero(W: Word): String;
var S: String;
begin
Str(W:0, S);
if Length(S) = 1 then S := '0' +S;
LeadingZero := S;
end; { of LeadingZero }
(*
* Function : DateAndTime
* Abstract : Composes a string containing the name of the day (three
* characters), the date and the time of the operating system
* Decisions :
*)
function DateAndTime: String;
const Days: String[21] = 'SunMonTueWedThuFriSat';
TimeDelimiter = ':';
DateDelimiter = '-';
var hour, min, sec, hund, year, mon, day, dow: Word;
DayName, Date, Time: String;
begin
GetTime(hour, min, sec, hund);
Time := LeadingZero(hour) +TimeDelimiter +
LeadingZero(min) +TimeDelimiter +
LeadingZero(sec) +TimeDelimiter +
LeadingZero(hund);
GetDate(year, mon, day, dow);
Date := LeadingZero(day) +DateDelimiter +
LeadingZero(mon) +DateDelimiter +
LeadingZero(year);
DayName := Copy(Days, (3 *dow) +1, 3);
DateAndTime := DayName +' ' +Date +' ' +Time;
end; { of DateAndTime }
{$ENDIF}
(*
* Function : CursorOff
* Abstract : Disable cursor display on the screen
* Decisions :
*)
procedure CursorOff;
var Register: Registers;
begin
Register.Ax := 1 SHL 8;
Register.Cx := 14 SHL 8 +0;
Intr($10, Register);
end; { of CursorOff }
(*
* Function : CursorOn
* Abstract : Enable cursor display on the screen
* Decisions :
*)
procedure CursorOn;
var Register: Registers;
begin
Register.Ax := 1 SHL 8;
Register.Cx := 6 SHL 8 +7;
Intr($10, Register);
end; { of CursorOn }
(*
* Function : Replicate
* Abstract : Repeat the input character a number of times
* Decisions :
*)
function Replicate(C:Char; N:Byte): String;
var TempStr: String;
begin
if N = 0 then
TempStr := ''
else
begin
if (N > 255) then N := 1;
FillChar(TempStr, N+1, C);
TempStr[0] := Chr(N);
end;
Replicate := Tempstr;
end; { of Replicate }
(*
* Function : Replace
* Abstract : Replaces every 'OldStr' in the source-string by 'NewStr',
* if the source-string is shorter or there is no match, then
* the source-string will not be changed
* Decisions :
*)
procedure Replace(var Src: String; OldStr, NewStr: String);
var TempStr,S: String;
P: Word;
begin
TempStr := Src;
(* 94-07-27, MV
* for P := (Length(Src)-Length(OldStr) +1) downto 1 do begin
* if Src[P] = OldStr[1] then begin
* S := Copy(Src, P, Length(OldStr));
* if S = OldStr then begin
* Delete(TempStr, P, Length(OldStr));
* Insert(NewStr, TempStr, P);
* end;
* end;
* end;
*)
repeat
P := Pos(OldStr, TempStr);
if P <> 0 then begin
Delete(TempStr, P, Length(OldStr));
Insert(NewStr, TempStr, P);
end;
until P = 0;
(*
*)
Src := TempStr;
end; { of Replace }
(*
* Function : InProcess
* Abstract : Display a process-indicator on the screen
* Decisions :
*)
procedure InProcess(X,Y,B: Byte);
const Process: array[1..10] of Char = ('Ä','\','³','/', { Process indicators }
'*', { End of process }
'>',' ','>',' ', { Wait indicators }
' ' { End of wait }
);
Wait = 500;
begin
GotoXY(X,Y);
case B of
1: ProcessStage := 1; { Begin of the process }
2: begin { In the middle of the process }
if ProcessStage < 4 then
Inc(ProcessStage)
else
ProcessStage := 1;
end;
3: ProcessStage := 5; { End of the process }
4: ProcessStage := 6; { Begin of the wait }
5: begin { In the middle of the wait }
if ProcessStage < 9 then
Inc(ProcessStage)
else
ProcessStage := 6;
Delay(Wait);
end;
6: ProcessStage := 10; { End of the wait }
end; {of case}
Write(Process[ProcessStage]);
end; { of InProcess }
(*
* Function : Initialize
* Abstract :
* Decisions :
*)
procedure Initialize;
begin
CurrentRow := 0;
CurrentY := WhereY;
{ Start with a clear screen when the current screen is almost full }
if CurrentY > 20 then begin
ClrScr;
CurrentY := WhereY;
end;
LeftMargin := DefLeftMargin;
RightMargin := DefRightMargin;
PageWidth := RightMargin -LeftMargin;
PrintLength := DefPrintLength;
TabSize := DefTabSize;
{ Default: skip the perforation of pinfeed paper }
SkipPerforation := TRUE;
{ Default: print in Near Letter Quality }
Quality := TRUE;
{ Default: include the include-file source }
Include := TRUE;
{ Default: output device LPT1 }
LPT := LPT1;
end; { of initialize }
(*
* Function : WriteLPT
* Abstract : Write a string to the output device,
* excluding (without) a carriage return
* Decisions :
*)
procedure WriteLPT(S: String);
var F: Text;
begin
{$IFNDEF DEBUG}
Assign(F, LPTString[LPT]);
Rewrite(F);
Write(F, S);
Close(F);
{$ELSE}
Assign(F, DebugFileName);
{$I-}
Append(F);
{$I+}
if IOResult <> 0 then ReWrite(F); { file not found -> create it }
if S <> Chr(12) then Write(F, S); { write string unless formfeed }
Close(F);
{$ENDIF}
end; { of WriteLPT }
(*
* Function : WriteLnLPT
* Abstract : Write a string to the output device,
* including a carriage return
* Decisions :
*)
procedure WriteLnLPT(S: String);
var F: Text;
begin
{$IFNDEF DEBUG}
Assign(F, LPTString[LPT]);
Rewrite(F);
WriteLn(F, S);
Close(F);
{$ELSE}
Assign(F, DebugFileName);
{$I-}
Append(F);
{$I+}
if IOResult <> 0 then Rewrite(F); { file not found -> create it }
if S <> Chr(12) then WriteLn(F, S); { write string unless formfeed }
Close(F);
{$ENDIF}
end; { of WriteLnLPT }
(*
* Function : PrinterStatus
* Abstract : Get the status of the connected output device
* Decisions :
*)
function PrinterStatus: Byte;
var Register: Registers;
begin
with Register do begin
Ah := 2;
Dx := LPTByte[LPT];
Intr($17, Register);
if (Ah AND $B8) = $90 then PrinterStatus := 0 { all is well }
else
if (Ah AND $20) = $20 then PrinterStatus := 1 { device out of paper }
else
if (Ah AND $10) = $00 then PrinterStatus := 2 { device off line }
else
if (Ah AND $80) = $00 then PrinterStatus := 3 { device is busy }
else
if (Ah AND $08) = $08 then PrinterStatus := 4; { undetermined error }
end;
end; { of PrinterStatus }
(*
* Function : InitializePrinter
* Abstract : Initialize the connected output device
* Decisions :
*)
procedure InitializePrinter;
const Draft = #27+'x'+'0'; { EPSON }
NLQ = #27+'x'+'1'; { EPSON }
Elite = #27+'M'; { EPSON }
PrinterReady: Boolean = FALSE;
begin
InProcess(1 +InitPrinterIndX, CurrentY +InitPrinterIndY, 4);
repeat
GotoXY(1 +InitPrinterStrX, CurrentY +InitPrinterStrY);
case PrinterStatus of
0: begin
PrinterReady := TRUE;
Write(StatusStr[0]);
end;
1: Write(StatusStr[1]);
2: Write(StatusStr[2]);
3: Write(StatusStr[3]);
4: begin
Write(StatusStr[4]);
CursorOn;
Halt(0);
end;
end; { of case }
InProcess(1 +InitPrinterIndX, CurrentY +InitPrinterIndY, 5);
until PrinterReady;
InProcess(1 +InitPrinterIndX, CurrentY +InitPrinterIndY, 6);
if PrinterReady then begin
if Quality then
WriteLPT(NLQ +Elite)
else
WriteLPT(Draft +Elite);
end;
end; { of InitializePrinter }
(*
* Function : Open
* Abstract : Open a file
* Decisions :
*)
function Open(var fp:Text; Name:ComStr): Boolean;
begin
Assign(fp, Name);
{$I-}
Reset(fp);
{$I+}
Open := IOResult = 0;
end; { of Open }
(*
* Function : UpStr
* Abstract : Converts all lower case characters of
* the input string to upper case
* Decisions :
*)
function UpStr(S: String): String;
var i: Word;
begin
for i := 1 to Length(S) do begin
S[i] := UpCase(S[i]);
end;
UpStr := S;
end; { of UpStr }
(*
* Function : Int2Str
* Abstract : Convert an integer-type to a string-type
* Decisions :
*)
function Int2Str(I: Integer): String;
var S: String;
begin
Str(I:3, S);
Int2Str := S;
end; { of Int2Str }
(*
* Function : Str2Int
* Abstract : Convert a string type to an integer-type
* Decisions :
*)
function Str2Int(Str:ComStr; FirstPos,LastPos:Byte; Option:Char): Integer;
var Int, ErrorCode: Integer;
begin
Inc(FirstPos);
Int := FirstPos;
While (Int <= LastPos) AND (Str[Int] in ['0'..'9']) do Inc(Int);
Str := Copy(Str, FirstPos, Int -FirstPos);
Val(Str, Int, ErrorCode);
case Option of
LeftMarginChar :
begin
if Int < LeftMarginMin then Int := LeftMarginMin;
if Int > LeftMarginMax then Int := LeftMarginMax;
end;
RightMarginChar:
begin
if Int < RightMarginMin then Int := RightMarginMin;
if Int > RightMarginMax then Int := RightMarginMax;
end;
PrintLengthChar:
begin
if Int < PrintLengthMin then Int := PrintLengthMin;
if Int > PrintLengthMax then Int := PrintLengthMax;
end;
'T':
begin
if Int < TabSizeMin then Int := TabSizeMin;
if Int > TabSizeMax then Int := TabSizeMax;
end;
end;
if ErrorCode = 0 then Str2Int := Int;
end; { of Str2Int }
(*
* Function : DefDrive
* Abstract : Get the default drive of the current system
* Decisions :
*)
function DefDrive: String;
var P: String;
begin
GetDir(0, P);
DefDrive := P[1] +':';
end; { of DefDrive }
(*
* Function : StripZeroParam
* Abstract : Strip the first commandline parameter-string
* Decisions : The first parameter-string from the commandline
* contains the full path and name of the program
* that is executed. Strip the path and the extension
* of the executable so that its name remains.
*)
function StripZeroParam: String;
var TempStr: String;
begin
TempStr := ParamStr(0);
while Pos('\', TempStr) <> 0 do Delete(TempStr, 1, Pos('\', TempStr));
if Pos('.', TempStr) <> 0 then
Delete(TempStr, Pos('.', TempStr), Length(TempStr)-(Pos('.', TempStr)-1));
StripZeroParam := TempStr;
end; { of StripZeroParam }
(*
* Function : Help
* Abstract : Display a 'help'-page on the screen
* Decisions :
*)
procedure Help;
var NumberOfSpaces,b: Byte;
TempStr: String;
begin
TempStr := StripZeroParam;
NumberOfSpaces :=
80 - { screen width }
(2 + { left margin }
SizeOf(ProgramName) + { size of the ProgramName array }
2 + { space between ProgamName & Version }
SizeOf(Version) + { size of the Version array }
1 + { min. space between Version & Company }
SizeOf(Company) + { size of the Company array }
1 + { space between Company & Year }
SizeOf(Year) + { size of the Year array }
2 { rigth margin }
);
WriteLn;
Write (' ');
for b := 1 to SizeOf(ProgramName) do Write(Chr(ProgramName[b]));
Write (' ');
for b := 1 to SizeOf(Version) do Write(Chr(Version[b]));
Write (' '+Replicate(' ',NumberOfSpaces));
for b := 1 to SizeOf(Company) do Write(Chr(Company[b]));
Write (' ');
for b := 1 to SizeOf(Year) do Write(Chr(Year[b]));
WriteLn;
WriteLn;
WriteLn(' Usage : '+TempStr+' [/|-][options] [drive:][path]file');
WriteLn(' Options :');
Write (' '+LeftMarginChar +'nnn Leftmargin, default = '+Int2Str(DefLeftMargin) +' ');
WriteLn(' Q NLQ printing -off-');
Write (' '+RightMarginChar+'nnn Rightmargin, default = '+Int2Str(DefRightMargin)+' ');
WriteLn(' I Exclude the include-file source');
Write (' '+PrintLengthChar+'nn Pagelength, default = '+Int2Str(DefPrintLength)+' ');
WriteLn(' S Skip paper perforation -off-');
Write (' Pn Printer port, default = '+Int2Str(LPTByte[LPT]+1)+' ');
WriteLn(' (1 = LPT1, 2 = LPT2, 3 = LPT3)');
WriteLn(' Tnnn Tabsize, default = '+Int2Str(DefTabSize)+' ');
WriteLn(' Examples: '+TempStr+' /'+LeftMarginChar+'30qI'+RightMarginChar+'75'+PrintLengthChar+'66 c:\demo.pas');
WriteLn(' '+TempStr+' -'+LeftMarginChar+'30 -Q /i /'+PrintLengthChar+'66 c:\demo.pas');
WriteLn(' '+TempStr+' c:\demo.pas');
WriteLn;
CursorOn;
Halt(0);
end; { of Help }
(*
* Function : GetCommand
* Abstract : Get the arguments from the command-line
* Decisions :
*)
procedure GetCommand(var Path: ComStr);
var ParCnt,ParStrPos,LenParStr: Byte;
ParStr: ComStr;
begin
for ParCnt := 1 to ParamCount do begin
ParStr := UpStr(ParamStr(ParCnt));
LenParStr := Length(ParStr);
if ParStr[1] in SwitchInd then
for ParStrPos := 2 to LenParStr do begin
case ParStr[ParStrPos] of
'I': Include := FALSE;
'P': case ParStr[ParStrPos+1] of
'2': LPT := LPT2;
'3': LPT := LPT3;
else LPT := LPT1;
end; {of case}
'Q': Quality := FALSE;
'S': SkipPerforation := FALSE;
'T':
TabSize := Str2Int(ParStr,ParStrPos,LenParStr,'T');
LeftMarginChar:
LeftMargin := Str2Int(ParStr,ParStrPos,LenParStr,LeftMarginChar);
RightMarginChar:
RightMargin := Str2Int(ParStr,ParStrPos,LenParStr,RightMarginChar);
PrintLengthChar:
PrintLength := Str2Int(ParStr,ParStrPos,LenParStr,PrintLengthChar);
'0'..'9': { Skip all digits };
else begin
WriteLn('Invalid option: ',ParStr[ParStrPos]);
CursorOn;
Halt(1);
end;
end; {of case}
end {of for StrPos}
else
Path := ParStr;
end; {of for Count}
if RightMargin <= LeftMargin then begin
LeftMargin := DefLeftMargin;
RightMargin := DefRightMargin;
end;
PageWidth := RightMargin -LeftMargin;
end; { of GetCommand }
(*
* Function : OpenMain
* Abstract : Open the main file to be sent to the output device
* Decisions :
*)
procedure OpenMain;
begin
if ParamCount = 0 then
Help
else
begin
MainFileName := Chr(0);
GetCommand(MainFileName);
end;
if (MainFileName = Chr(0)) OR NOT Open(MainFile,MainFileName) then begin
WriteLn('ERROR: file not found ('+MainFileName+')');
CursorOn;
Halt(2);
end;
end; { of OpenMain }
(*
* Function : HorizontalTab
* Abstract : Tabulate horizontal
* Decisions : Write a given amount of spaces
*)
procedure HorizontalTab;
var w: Word;
begin
for w := 1 to LeftMargin do begin
WriteLPT(' ');
if (w MOD 2) = 0 then
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 2);
end;
end; { of HorizontalTab }
(*
* Function : VerticalTab
* Abstract : Tabulate vertical
* Decisions : Write a given amount of new-lines
*)
procedure VerticalTab;
var w: Word;
begin
for w := 1 to VerticalTabLength do begin
WriteLnLPT('');
if (w MOD 2) = 0 then
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 2);
end;
end; { of VerticalTab }
(*
* Function : CheckCurrentRow
* Abstract : Check the current (present) row
* Decisions : Go to a new page if the max number of lines on the present
* page has been reached
*)
procedure CheckCurrentRow;
begin
if CurrentRow >= PrintLength then begin
if SkipPerforation then
begin
{$IFDEF DEBUG}
WriteLnLPT('*** FORMFEED (PERFORATION SKIP) ***');
{$ENDIF}
WriteLPT(Chr(12)); { Formfeed }
VerticalTab;
{$IFDEF DEBUG}
end
else
begin
WriteLnLPT('*** NO PERFORATION SKIP ***');
{$ENDIF}
end;
CurrentRow := 0;
end;
end; { of CheckCurrentRow }
(*
* Function : ProcessLine
* Abstract : Process the present line
* Decisions : Write the string from the buffer to the output device
*)
procedure ProcessLine(PrintStr: WORK_STRING);
const TabChr= Chr(9);
var TempStr: String;
begin
TempStr := PrintStr;
Replace(TempStr, TabChr, Replicate(' ',TabSize));
{ replace every tab-character by a }
{ given amount of spaces }
CheckCurrentRow;
Inc(CurrentRow); { indicate which line is processed }
HorizontalTab;
while Length(TempStr) > PageWidth do begin
WriteLnLPT(Copy(TempStr, 1, PageWidth));
Delete(TempStr, 1, PageWidth);
CheckCurrentRow; { check if the page is full }
Inc(CurrentRow); { indicate that next line will be processed }
HorizontalTab;
end;
WriteLnLPT(TempStr); { the full line or the remaining part }
if TempStr = Chr(12) then begin
VerticalTab;
CurrentRow := 0;
end;
end; { of ProcessLine }
(*
* Function : IncludeIn
* Abstract : Check if include file definition in main file source
* Decisions :
*)
function IncludeIn(var CurStr: WORK_STRING): Boolean;
var Column,Number: Byte;
ChkChar: Char;
begin
Number := 0;
repeat
Inc(Number);
Column := Pos(IncludeSearch[Number], CurStr)
until (Number = 4) OR (Column <> 0);
if (Column <> 0) AND
(CurStr[Column +Length(IncludeSearch[Number])] = ' ') then
IncludeIn := TRUE
else
IncludeIn := FALSE;
end; { of IncludeIn }
(*
* Function : Parse
* Abstract : Get the include-filename from the line-buffer
* Decisions :
*)
procedure Parse(IncStr: WORK_STRING;var IncludeFileName: ComStr);
var NameStart, NameEnd: Integer;
begin
NameStart := Pos('$I', IncStr) +2;
while IncStr[NameStart] = ' ' do NameStart := Succ(NameStart);
NameEnd := NameStart;
while (NOT (IncStr[NameEnd] in [' ','}','*'])) AND
((NameEnd -NameStart) <= PathLength) do Inc(NameEnd);
Dec(NameEnd);
IncludeFileName := Copy(IncStr,NameStart,(NameEnd -NameStart +1));
end; { of Parse }
(*
* Function : ProcessIncludeFile
* Abstract : Process the present include-file
* Decisions : If include-file found then put it to the output device and
* check if the include-file includes a file
*)
procedure ProcessIncludeFile(var IncStr: WORK_STRING);
var IncludeFile: Text;
IncludeFileName: ComStr;
LineBuffer: WORK_STRING;
begin
Parse(IncStr, IncludeFileName);
if NOT Open(IncludeFile,IncludeFileName) then
begin
LineBuffer := 'ERROR: include file not found ('+IncludeFileName+ ')';
ProcessLine(LineBuffer);
end
else
begin
while NOT EOF(IncludeFile) do begin
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 2);
ReadLn(IncludeFile,LineBuffer);
if IncludeIn(LineBuffer) then
ProcessIncludeFile(LineBuffer)
else
ProcessLine(LineBuffer);
end;
Close(IncludeFile);
end;
end; { of ProcessIncludeFile }
(*
* Function : ProcessFile
* Abstract : Process the present (main-) file
* Decisions : Put the file to the output device and
* check for include-files
*)
procedure ProcessFile;
var LineBuffer: WORK_STRING;
begin
{$IFDEF DEBUG}
WriteLnLPT('*** '+DateAndTime+' '+Replicate('*',40));
{$ENDIF}
VerticalTab;
GotoXY(1 +ProcessStrX, CurrentY +ProcessStrY);
Write(ProcessStr[1] +UpStr(MainFileName));
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 1);
while NOT EOF(MainFile) do begin
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 2);
ReadLn(MainFile,LineBuffer);
if (IncludeIn(LineBuffer) AND (Include = TRUE)) then
ProcessIncludeFile(LineBuffer)
else
ProcessLine(LineBuffer);
end;
Close(MainFile);
InProcess(1 +ProcessIndX, CurrentY +ProcessIndY, 3);
GotoXY(1 +ProcessStrX, CurrentY +ProcessStrY);
WriteLn(ProcessStr[1] +UpStr(MainFileName) +ProcessStr[2]);
WriteLPT(Chr(12)); { Formfeed }
{$IFDEF DEBUG}
WriteLnLPT('*** FORMFEED (END OF FILE) ***');
{$ENDIF}
end; { of ProcessFile }
(*
* Function : MAIN
* Abstract :
* Decisions :
*)
BEGIN
CursorOff; { Disable cursor display on screen }
Initialize; { Initialize some global variables }
OpenMain; { Open the file to print }
{$IFNDEF DEBUG}
InitializePrinter; { Initialize the output device (printer) }
{$ENDIF}
ProcessFile; { Put the read file to the output device }
CursorOn; { Enable cursor display on screen }
END. { of Main } |
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QFileDialog;
interface
uses
SysUtils, Types, Classes, Variants, QGraphics, QControls, QForms, QDialogs,
QExtCtrls, QComCtrls, QStdCtrls, QFileCtrls, QActnList, QImgList, QTypes,
QMenus, Qt;
const
QEventType_FDSelect = QEventType(Integer(QEventType_ClxBase) + $100);
type
TFileDialogForm = class;
TFileDlgViewStyle = (fvsIcon, fvsSmallIcon, fvsList, fvsReport);
TPreviewScrollBox = class(TScrollBox)
private
FCanvas: TCanvas;
FBitmap: TBitmap;
function GetCanvas: TCanvas;
protected
procedure BoundsChanged; override;
procedure CanvasChanged(Sender: TObject);
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure InitWidget; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Canvas: TCanvas read GetCanvas;
end;
TFileDialogForm = class(TDialogForm, IFileDialogForm)
BottomPanel: TPanel;
Label2: TLabel;
Label3: TLabel;
OpenButton: TButton;
CancelButton: TButton;
FileEdit: TFileEdit;
FilterCombo: TFilterComboBox;
ActionList1: TActionList;
FormAction: TAction;
ImageList1: TImageList;
ViewPopup: TPopupMenu;
LargeIcons1: TMenuItem;
SmallIcons1: TMenuItem;
List1: TMenuItem;
Details1: TMenuItem;
FileIcons: TFileIconView;
Panel2: TPanel;
ToolBar1: TToolBar;
ListButton: TToolButton;
ToolButton3: TToolButton;
NewDirButton: TToolButton;
UpButton: TToolButton;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
Label1: TLabel;
UpAction: TAction;
BackAction: TAction;
ForwardAction: TAction;
FileHistoryCombo: TFileHistoryComboBox;
HomeAction: TAction;
ReloadAction: TAction;
ViewIconAction: TAction;
ViewSmallIconAction: TAction;
ViewListAction: TAction;
ViewDetailAction: TAction;
HelpROPanel: TPanel;
ReadOnlyCheckbox: TCheckBox;
HelpButton: TButton;
HelpAction: TAction;
PreviewPanel: TPanel;
AutoPreviewCheckbox: TCheckBox;
PreviewButton: TButton;
Panel3: TPanel;
PreviewProgress: TProgressBar;
PreviewLabel: TLabel;
NewDirAction: TAction;
ItemPopup: TPopupMenu;
DeleteAction: TAction;
DeleteAction1: TMenuItem;
RenameAction: TAction;
Rename1: TMenuItem;
N1: TMenuItem;
ListPopup: TPopupMenu;
NewDirectory1: TMenuItem;
Reload1: TMenuItem;
OpenAction: TAction;
Open1: TMenuItem;
HiddenAction: TAction;
ShowHiddenFiles1: TMenuItem;
N3: TMenuItem;
Back1: TMenuItem;
Forward1: TMenuItem;
Uponedirectory1: TMenuItem;
N2: TMenuItem;
Home1: TMenuItem;
Splitter: TSplitter;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActionUpdate(Sender: TObject);
procedure FileListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure FilterComboClick(Sender: TObject);
procedure FileIconsSelectItem(Sender: TObject; Item: TIconViewItem;
Selected: Boolean);
procedure FileHistoryComboClick(Sender: TObject);
procedure UpActionUpdate(Sender: TObject);
procedure UpActionExecute(Sender: TObject);
procedure BackActionUpdate(Sender: TObject);
procedure BackActionExecute(Sender: TObject);
procedure ForwardActionUpdate(Sender: TObject);
procedure ForwardActionExecute(Sender: TObject);
procedure HomeActionExecute(Sender: TObject);
procedure ReloadActionExecute(Sender: TObject);
procedure ViewIconActionExecute(Sender: TObject);
procedure HelpActionExecute(Sender: TObject);
procedure HelpActionUpdate(Sender: TObject);
procedure FileEditReturnPressed(Sender: TObject);
procedure AutoPreviewCheckboxClick(Sender: TObject);
procedure PreviewButtonClick(Sender: TObject);
procedure FileIconsDirectoryChange(Sender: TObject;
const NewDir: WideString);
procedure FileEditDirectoryChange(Sender: TObject;
const NewDir: WideString);
procedure FileEditMaskChange(Sender: TObject; const NewMask: WideString);
procedure NewDirActionUpdate(Sender: TObject);
procedure NewDirActionExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DeleteActionUpdate(Sender: TObject);
procedure DeleteActionExecute(Sender: TObject);
procedure RenameActionExecute(Sender: TObject);
procedure OpenActionUpdate(Sender: TObject);
procedure HiddenActionExecute(Sender: TObject);
procedure FileIconsContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure FileListContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure FileIconsDblClick(Sender: TObject);
procedure FileListDblClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FileListFileFound(Sender: TObject; const AFile: TSearchRec;
var CanAdd: Boolean);
procedure FileIconsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FileIconsMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ImagePanelResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PreviewPanelResize(Sender: TObject);
procedure FormLoaded(Sender: TObject);
private
FAutoPreview: Boolean;
FDirSelected: Boolean;
FDefaultExt: WideString;
FFileList: TFileListView;
FViewStyle: TFileDlgViewStyle;
FOpenDialog: IOpenDialog;
PreviewScroll: TPreviewScrollBox;
procedure ClearPreview;
function GetDirectory: WideString;
function GetSelections(Viewer: TObject): TFileInfos;
procedure SetDirectory(const Directory: WideString);
protected
function CurrentFiles: TDirectory;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
function FileList: TFileListView;
procedure ItemSelected(Sender: TObject; FileInfo: PFileInfo;
Selected: Boolean); virtual;
procedure Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: WideString; var Continue: Boolean); virtual;
procedure SetViewStyle(const Value: TFileDlgViewStyle);
procedure UpdateSelectionState(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
property Directory: WideString read GetDirectory write SetDirectory;
//IFileDialogForm
procedure GetOptions(OpenDlg: TOpenDialog; Accepted: Boolean);
function GetSelected: TFileInfos;
procedure ListFiles(List: TStrings); virtual;
procedure ResizePreview(const NewSize: TSize);
procedure SetOptions(OpenDlg: TOpenDialog);
end;
var
FileDialogForm: TFileDialogForm;
implementation
{$R *.xfm}
uses
{$IFDEF LINUX}
Libc,
{$ENDIF}
QConsts;
var
GraphicPreviewer: TGraphicPreviewer = nil;
{ TFileDialogForm }
procedure TFileDialogForm.SetDirectory(const Directory: WideString);
begin
if CurrentFiles.Location <> IncludeTrailingPathDelimiter(Directory) then
begin
CurrentFiles.Location := Directory;
if Showing then
FileHistoryCombo.Add(Directory);
end;
end;
procedure TFileDialogForm.FormShow(Sender: TObject);
const
Titles: array[Boolean] of string = (SOpen, SSave);
begin
if Caption = '' then
Caption := Titles[Dialog is TSaveDialog];
FileHistoryCombo.Add(Directory);
ActiveControl := FileEdit;
FileEdit.SelectAll;
PreviewLabel.Top := PreviewScroll.Top + PreviewScroll.Height + 10;
PreviewLabel.Caption := '';
PreviewProgress.Visible := False;
PreviewProgress.Top := PreviewLabel.Top + PreviewLabel.Height + 5;
end;
procedure TFileDialogForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caHide; //TFileDialog controls this form's lifetime.
end;
function TFileDialogForm.GetDirectory: WideString;
begin
Result := CurrentFiles.Location;
end;
procedure TFileDialogForm.FormActionUpdate(Sender: TObject);
begin
OpenButton.Caption := OpenAction.Caption;
OpenButton.Enabled := (FileEdit.Text <> '') or FDirSelected;
OpenAction.Enabled := OpenButton.Enabled;
end;
procedure TFileDialogForm.ListFiles(List: TStrings);
function IsRegisteredExtension(const Ext: WideString): Boolean;
var
RE: QRegExpH;
I: Integer;
Pattern: WideString;
Masks: TStringList;
begin
Result := False;
RE := QRegExp_create;
Masks := TStringList.Create;
try
FilterCombo.ListMasks(Masks);
begin
QRegExp_setCaseSensitive(RE, True);
for I := 0 to Masks.Count - 1 do
if Masks[I] <> AllMask then
begin
Pattern := '^.' + Masks[I] +'$';
QRegExp_setPattern(RE, @Pattern);
Result := (QRegExp_find(RE, @Ext, 0) > -1);
if Result then Exit;
end;
end;
finally
Masks.Free;
QRegExp_destroy(RE);
end;
end;
function GetFirstExtension(const Mask: string): string;
var
P: Integer;
begin
Result := Mask;
P := Pos(';', Result);
if P > 0 then
SetString(Result, PChar(@Mask[1]), P-1);
Result := ExtractFileExt(Result);
if (Pos('*', Result) <> 0) or (Pos('?', Result) <> 0) then
Result := '';
end;
function GetFilterExtension(const Index: Integer): WideString;
var
Masks: TStrings;
begin
Result := '';
Masks := TStringList.Create;
try
FilterCombo.ListMasks(Masks);
if (Index < 0) or (Index >= Masks.Count) then
Exit;
Result := GetFirstExtension(Masks[Index]);
finally
Masks.Free;
end;
end;
function FileExtension(const Filename: WideString): WideString;
var
ThisExt,
DefExt: WideString;
begin
Result := '';
{$IFDEF MSWINDOWS}
if (Length(Filename) = 2) and (Filename[2] = ':') then
Exit;
{$ENDIF}
if FileExists(Filename) then Exit;
DefExt := FDefaultExt;
begin
if Dialog is TSaveDialog then
begin
ThisExt := ExtractFileExt(Filename);
if ThisExt <> '' then
begin
if (ThisExt = '.' + DefExt) or (DefExt = '') then
Exit;
if not IsRegisteredExtension(ThisExt) then
begin
Result := GetFilterExtension(FilterCombo.ItemIndex);
if (Pos('?', Result) > 0) then
Result := DefExt;
end;
end
else
if (Length(DefExt) > 0) then
Result := GetFilterExtension(FilterCombo.ItemIndex);
end
else begin
ThisExt := ExtractFileExt(Filename);
if ThisExt <> '' then
begin
if not IsRegisteredExtension(ThisExt) then
begin
Result := GetFirstExtension(FilterCombo.Mask);
if (Pos('?', Result) > 0) then
Result := DefExt;
end;
end
else
if (DefExt <> #0) and (Length(DefExt) > 0) then
begin
Result := GetFirstExtension(FilterCombo.Mask);
if (Result = '') then
Result := '.' + DefExt;
end;
end;
end;
end;
function MakeAbsolute(const Filename: WideString): WideString;
var
Tmp: WideString;
begin
Tmp := Filename;
if IsRelativePath(Tmp) then
Tmp := FileEdit.CurrentDir + Tmp;
if Tmp <> '' then
begin
{$IFDEF LINUX}
// Backslashes are treated as escape characters in ExpandDirectoryName.
Tmp := StringReplace(Tmp, '\', '\\', [rfReplaceAll]);
{$ENDIF}
Result := ExpandDirectoryName(Tmp)
end
else
Result := Filename;
end;
var
SaveQuote: Char;
I: Integer;
F: WideString;
begin
List.Clear;
if Length(FileEdit.Text) = 0 then Exit;
if Pos('"', FileEdit.Text) = 0 then
begin
F := MakeAbsolute(FileEdit.Text);
F := F + FileExtension(F);
List.Add(F);
end
else begin
SaveQuote := List.QuoteChar;
try
List.QuoteChar := '"';
List.DelimitedText := FileEdit.Text;
for I := 0 to List.Count - 1 do
List[I] := MakeAbsolute(List[I] + FileExtension(List[I]));
finally
List.QuoteChar := SaveQuote;
end;
end;
end;
procedure TFileDialogForm.SetViewStyle(const Value: TFileDlgViewStyle);
begin
case Value of
fvsList:
begin
FileList.ViewStyle := vsList;
if CurrentFiles <> FileList.Directory then
FileList.Directory.Assign(CurrentFiles);
FileList.Visible := True;
FileIcons.Visible := False;
ViewListAction.Checked := True;
end;
fvsReport:
begin
FileList.ViewStyle := vsReport;
if CurrentFiles <> FileList.Directory then
FileList.Directory.Assign(CurrentFiles);
FileList.Visible := True;
FileIcons.Visible := False;
ViewDetailAction.Checked := True;
end;
fvsSmallIcon:
begin
FileIcons.TextPosition := itpRight;
FileIcons.IconOptions.Arrangement := iaTop;
if CurrentFiles <> FileIcons.Directory then
FileIcons.Directory.Assign(CurrentFiles);
FileIcons.IconSize := isSmall;
FileIcons.Visible := True;
if Assigned(FFileList) then
FileList.Visible := False;
ViewSmallIconAction.Checked := True;
end;
fvsIcon:
begin
FileIcons.IconOptions.Arrangement := iaTop;
FileIcons.TextPosition := itpBottom;
FileIcons.IconSize := isLarge;
if CurrentFiles <> FileIcons.Directory then
FileIcons.Directory.Assign(CurrentFiles);
FileIcons.Visible := True;
if Assigned(FFileList) then
FileList.Visible := False;
ViewIconAction.Checked := True;
end;
end;
FViewStyle := Value;
end;
constructor TFileDialogForm.Create(AOwner: TComponent);
begin
FOpenDialog := AOwner as IOpenDialog;
inherited Create(AOwner);
FViewStyle := fvsSmallIcon;
if not Assigned(GraphicPreviewer) then
begin
GraphicPreviewer := TGraphicPreviewer.Create;
RegisterFilePreviewer(GraphicPreviewer);
end;
end;
procedure TFileDialogForm.FilterComboClick(Sender: TObject);
begin
CurrentFiles.FileMask := FilterCombo.Mask;
FOpenDialog.FilterChanged(FilterCombo.ItemIndex);
end;
function TFileDialogForm.GetSelections(Viewer: TObject): TFileInfos;
begin
if Viewer = FileIcons then
Result := FileIcons.Selections
else
Result := FFileList.Selections;
end;
procedure TFileDialogForm.FileIconsSelectItem(Sender: TObject;
Item: TIconViewItem; Selected: Boolean);
begin
if (FileIcons.Items.UpdateCount = 0) and not FileIcons.IsEditing then
ItemSelected(Sender, PFileInfo(Item.Data), Selected);
end;
procedure TFileDialogForm.FileListSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if (FileList.Items.UpdateCount = 0) and not FileList.IsEditing then
ItemSelected(Sender, PFileInfo(Item.Data), Selected);
end;
procedure TFileDialogForm.ItemSelected(Sender: TObject;
FileInfo: PFileInfo; Selected: Boolean);
begin
if (FileInfo <> nil) then
FOpenDialog.FileSelected(FileInfo, Selected);
end;
function TFileDialogForm.CurrentFiles: TDirectory;
begin
if FViewStyle in [fvsList, fvsReport] then
Result := FileList.Directory
else
Result := FileIcons.Directory;
end;
procedure TFileDialogForm.FileHistoryComboClick(Sender: TObject);
begin
with Sender as TFileHistoryComboBox do
if ItemIndex > -1 then
CurrentFiles.Location := Items[ItemIndex];
end;
procedure TFileDialogForm.UpActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := CurrentFiles.Location <> PathDelim;
end;
procedure TFileDialogForm.UpActionExecute(Sender: TObject);
begin
CurrentFiles.Location := CurrentFiles.Location + PathDelim + UpDir;
end;
procedure TFileDialogForm.BackActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := FileHistoryCombo.CanGoBack;
end;
procedure TFileDialogForm.BackActionExecute(Sender: TObject);
begin
FileHistoryCombo.GoBack;
end;
procedure TFileDialogForm.ForwardActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := FileHistoryCombo.CanGoForward;
end;
procedure TFileDialogForm.ForwardActionExecute(Sender: TObject);
begin
FileHistoryCombo.GoForward;
end;
procedure TFileDialogForm.HomeActionExecute(Sender: TObject);
begin
CurrentFiles.Location := '$HOME';
end;
procedure TFileDialogForm.ReloadActionExecute(Sender: TObject);
begin
CurrentFiles.ListFiles(True);
end;
procedure TFileDialogForm.ViewIconActionExecute(Sender: TObject);
begin
with Sender as TAction do
begin
SetViewStyle(TFileDlgViewStyle(Tag));
ViewListAction.Checked := Sender = ViewListAction;
ViewIconAction.Checked := Sender = ViewIconAction;
ViewDetailAction.Checked := Sender = ViewDetailAction;
ViewSmallIconAction.Checked := Sender = ViewSmallIconAction;
end;
end;
procedure TFileDialogForm.HelpActionExecute(Sender: TObject);
begin
FOpenDialog.Help;
end;
procedure TFileDialogForm.HelpActionUpdate(Sender: TObject);
begin
// (Sender as TAction).Enabled := ofShowHelp in TFileDialog(Dialog).Options;
end;
procedure TFileDialogForm.GetOptions(OpenDlg: TOpenDialog; Accepted: Boolean);
begin
if ReadOnlyCheckbox.Checked then
OpenDlg.Options := OpenDlg.Options + [ofReadOnly];
OpenDlg.FilterIndex := FilterCombo.ItemIndex + 1;
if AutoPreviewCheckbox.Checked then
OpenDlg.Options := OpenDlg.Options + [ofAutoPreview]
else
OpenDlg.Options := OpenDlg.Options - [ofAutoPreview];
case FViewStyle of
fvsIcon:
OpenDlg.Options := OpenDlg.Options + [ofViewIcon];
fvsList:
OpenDlg.Options := OpenDlg.Options + [ofViewList];
fvsReport:
OpenDlg.Options := OpenDlg.Options + [ofViewDetail];
end;
if PreviewPanel.Visible then
Width := Width - PreviewPanel.Width;
end;
procedure TFileDialogForm.SetOptions(OpenDlg: TOpenDialog);
var
Save: Boolean;
StartDir: WideString;
begin
Save := OpenDlg is TSaveDialog;
FDefaultExt := OpenDlg.DefaultExt;
if ofEnableSizing in OpenDlg.Options then
BorderStyle := fbsSizeable
else
BorderStyle := fbsDialog;
FormAction.Caption := OpenDlg.Title;
if Save then
OpenButton.Caption := SSave
else
OpenButton.Caption := SOpen;
HelpROPanel.Visible := not (ofHideReadOnly in OpenDlg.Options) or
(ofShowHelp in OpenDlg.Options);
if HelpROPanel.Visible then
HelpROPanel.Top := BottomPanel.Top + BottomPanel.Height;
PreviewPanel.Visible := ofPreview in OpenDlg.Options;
Splitter.Visible := PreviewPanel.Visible;
if PreviewPanel.Visible then
Width := Width + PreviewPanel.Width;
ReadOnlyCheckbox.Visible := not (ofHideReadOnly in OpenDlg.Options);
ReadOnlyCheckbox.Checked := ofReadOnly in OpenDlg.Options;
AutoPreviewCheckbox.Checked := ofAutoPreview in OpenDlg.Options;
HelpButton.Visible := ofShowHelp in OpenDlg.Options;
StartDir := OpenDlg.InitialDir;
if StartDir = '' then
begin
StartDir := ExtractFilePath(OpenDlg.Filename);
if StartDir = '' then
StartDir := GetCurrentDir;
end;
try
Directory := StartDir;
except
Directory := GetCurrentDir;
end;
if OpenDlg.Filter <> '' then
FilterCombo.Filter := OpenDlg.Filter;
if (OpenDlg.FilterIndex <= FilterCombo.Items.Count)
and (OpenDlg.FilterIndex > 0) then
FilterCombo.ItemIndex := OpenDlg.FilterIndex - 1
else
FilterCombo.ItemIndex := 0;
CurrentFiles.FileMask := FilterCombo.Mask;
FileEdit.Text := ExtractFileName(OpenDlg.Filename);
FileIcons.MultiSelect := (ofAllowMultiSelect in OpenDlg.Options)
and not Save;
if ofViewDetail in OpenDlg.Options then
SetViewStyle(fvsReport)
else if ofViewIcon in OpenDlg.Options then
SetViewStyle(fvsIcon)
else if ofViewList in OpenDlg.Options then
SetViewStyle(fvsList)
else
SetViewStyle(fvsSmallIcon);
if ofShowHidden in OpenDlg.Options then
CurrentFiles.FileType := CurrentFiles.FileType + [ftHidden];
PreviewScroll.Height := FileIcons.Height;
end;
procedure TFileDialogForm.FileEditReturnPressed(Sender: TObject);
var
CanClose: Boolean;
begin
if (Pos('*', FileEdit.Text) <> 0) or (Pos('?', FileEdit.Text) <> 0) then
Exit;
CanClose := OpenButton.Enabled and (ActiveControl <> FileHistoryCombo);
if not FDirSelected then
begin
FOpenDialog.CanClose(CanClose);
if CanClose then
ModalResult := mrOk;
end else
case FViewStyle of
fvsIcon, fvsSmallIcon:
FileIcons.GoDown;
fvsList, fvsReport:
FileList.GoDown;
end;
end;
procedure TFileDialogForm.AutoPreviewCheckboxClick(Sender: TObject);
begin
FAutoPreview := (Sender as TCheckbox).Checked;
PreviewButton.Enabled := not FAutoPreview;
if not FAutoPreview then
ClearPreview
else
PreviewButtonClick(nil);
end;
procedure TFileDialogForm.PreviewButtonClick(Sender: TObject);
var
Selected: TFileInfos;
Filename: string;
Handled: Boolean;
ARect: TRect;
begin
ClearPreview;
Selected := GetSelected;
if High(Selected) <> 0 then Exit;
Filename := ExpandDirectoryName(IncludeTrailingPathDelimiter(
CurrentFiles.Location)) + Selected[0].SR.Name;
Handled := False;
ARect := Rect(1, 1, PreviewScroll.ClientWidth-5,
PreviewScroll.ClientHeight-5);
FOpenDialog.FilePreview(Filename, PreviewScroll.Canvas, ARect,
Self.Progress, Handled);
PreviewScroll.Repaint;
end;
function TFileDialogForm.GetSelected: TFileInfos;
begin
case FViewStyle of
fvsIcon, fvsSmallIcon: Result := FileIcons.Selections;
fvsList, fvsReport: Result := FileList.Selections;
end;
end;
procedure TFileDialogForm.Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect;
const Msg: WideString; var Continue: Boolean);
begin
if (Stage = psStarting) and not PreviewProgress.Visible then
PreviewProgress.Visible := True;
PreviewLabel.Caption := Msg;
if Stage = psEnding then
PreviewProgress.Visible := False
else
PreviewProgress.Position := PercentDone;
if RedrawNow then
PreviewScroll.Repaint;
end;
procedure TFileDialogForm.ClearPreview;
begin
if not Assigned(PreviewScroll) then
Exit;
with PreviewScroll do
begin
HorzScrollBar.Range := 0;
VertScrollBar.Range := 0;
Canvas.Brush.Bitmap := nil;
Canvas.Brush.Color := PreviewPanel.Color;
Canvas.Font.Assign(Self.Font);
Canvas.FillRect(Rect(0, 0, PreviewScroll.FBitmap.Width, PreviewScroll.FBitmap.Height));
end;
end;
procedure TFileDialogForm.FileIconsDirectoryChange(Sender: TObject;
const NewDir: WideString);
begin
if csLoading in ComponentState then Exit;
FileEdit.Directory.Location := ExpandDirectoryName(NewDir);
if Showing then
FileHistoryCombo.Add(Directory);
ClearPreview;
FDirSelected := False;
if Dialog is TSaveDialog then
OpenAction.Caption := SSave
else
OpenAction.Caption := SOpen;
FOpenDialog.DirChanged(NewDir);
end;
procedure TFileDialogForm.FileEditDirectoryChange(Sender: TObject;
const NewDir: WideString);
begin
Directory := NewDir;
end;
procedure TFileDialogForm.FileEditMaskChange(Sender: TObject;
const NewMask: WideString);
begin
CurrentFiles.FileMask := NewMask;
end;
procedure TFileDialogForm.NewDirActionUpdate(Sender: TObject);
{$IFDEF LINUX}
var
Dir: string;
{$ENDIF}
begin
{$IFDEF LINUX}
Dir := CurrentFiles.Location;
(Sender as TAction).Enabled := access(PChar(Dir), W_OK) = 0;
{$ENDIF}
end;
procedure TFileDialogForm.NewDirActionExecute(Sender: TObject);
begin
if FViewStyle in [fvsList, fvsReport] then
FileList.CreateDirectory(SNewFolder)
else
FileIcons.CreateDirectory(SNewFolder)
end;
procedure TFileDialogForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = []) and ((ActiveControl = FFileList)
or (ActiveControl = FileIcons)) then
case Key of
Key_F5:
ReloadActionExecute(Self);
Key_Delete:
DeleteActionExecute(Self);
end;
end;
procedure TFileDialogForm.DeleteActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := ((ActiveControl = FileIcons) and
(FileIcons.Selected <> nil)) or ((ActiveControl = FFileList) and
(FileList.Selected <> nil));
end;
procedure TFileDialogForm.DeleteActionExecute(Sender: TObject);
var
Selections: TFileInfos;
I: Integer;
Result: Integer;
ConfirmMsg: WideString;
begin
Selections := nil;
if ((ActiveControl = FileIcons) or (ActiveControl = FFileList)) then
begin
if (ActiveControl = FileIcons) then
Selections := FileIcons.Selections
else
Selections := FileList.Selections;
if High(Selections) > 0 then
ConfirmMsg := Format(SConfirmDeleteMany, [High(Selections) + 1])
else if High(Selections) = 0 then
ConfirmMsg := Format(SConfirmDeleteOne, [Selections[0].SR.Name])
else Exit;
if MessageDlg(SConfirmDeleteTitle, ConfirmMsg,
mtConfirmation, [mbYes, mbNo], 0, mbYes) = mrYes then
begin
if (ActiveControl = FileIcons) then
FileIcons.Items.BeginUpdate
else
FileList.Items.BeginUpdate;
try
FileEdit.Text := '';
for I := 0 to High(Selections) do
begin
Result := CurrentFiles.Delete(Selections[I]);
case Result of
RESULT_ACCESS_DENIED:
begin
if I < High(Selections) then
begin
if MessageDlg(SMsgDlgError, Format(SAccessDeniedTo,
[CurrentFiles.Location + Selections[I].SR.Name]) +
#10 + SContinueDelete, mtError, [mbYes, mbNo],
0, mbYes) = mrYes then
Result := RESULT_OK;
end else
MessageDlg(SMsgDlgError, Format(SAccessDeniedTo,
[CurrentFiles.Location + Selections[I].SR.Name]),
mtError, [mbOk], 0);
end;
RESULT_DIR_NOT_EMPTY:
MessageDlg(SMsgDlgError, Format(SDirectoryNotEmpty,
[CurrentFiles.Location + Selections[I].SR.Name]),
mtError, [mbOk], 0);
RESULT_FILE_NOT_FOUND:
if MessageDlg(SMsgDlgError, Format(SFileNameNotFound,
[CurrentFiles.Location + Selections[I].SR.Name]) +
#10 + SContinueDelete, mtError, [mbYes, mbNo],
0, mbYes) = mrYes then
Result := RESULT_OK;
end;
if Result <> RESULT_OK then
Exit;
end;
CurrentFiles.ListFiles(True);
finally
if (ActiveControl = FileIcons) then
FileIcons.Items.EndUpdate
else
FileList.Items.EndUpdate;
end;
end;
end;
end;
procedure TFileDialogForm.RenameActionExecute(Sender: TObject);
begin
if (ActiveControl = FileIcons) and (FileIcons.Selected <> nil) then
FileIcons.Selected.EditText
else if (ActiveControl = FFileList) and (FileList.Selected <> nil) then
FileList.Selected.EditText;
end;
procedure TFileDialogForm.OpenActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := OpenButton.Enabled;
end;
procedure TFileDialogForm.HiddenActionExecute(Sender: TObject);
begin
(Sender as TAction).Checked := not (Sender as TAction).Checked;
if (Sender as TAction).Checked then
CurrentFiles.FileType := CurrentFiles.FileType + [ftHidden]
else
CurrentFiles.FileType := CurrentFiles.FileType - [ftHidden];
end;
procedure TFileDialogForm.FileIconsContextPopup(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
var
Item: TIconViewItem;
begin
Handled := True;
Item := FileIcons.FindItemByPoint(MousePos);
MousePos := FileIcons.ClientToScreen(MousePos);
if Item = nil then
ListPopup.Popup(MousePos.X, MousePos.Y)
else
ItemPopup.Popup(MousePos.X, MousePos.Y);
end;
procedure TFileDialogForm.FileListContextPopup(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
var
Item: TListItem;
begin
Handled := True;
Item := FileList.GetItemAt(MousePos.X, MousePos.Y);
MousePos := FileList.ClientToScreen(MousePos);
if Item = nil then
ListPopup.Popup(MousePos.X, MousePos.Y)
else
ItemPopup.Popup(MousePos.X, MousePos.Y);
end;
procedure TFileDialogForm.FileIconsDblClick(Sender: TObject);
begin
if (FileIcons.Selected <> nil) and (PFileInfo(FileIcons.Selected.Data).SR.Attr and faDirectory = 0) then
FileEditReturnPressed(Sender);
end;
procedure TFileDialogForm.FileListDblClick(Sender: TObject);
begin
if (FileList.Selected <> nil) and (PFileInfo(FileList.Selected.Data).SR.Attr and faDirectory = 0) then
FileEditReturnPressed(Sender);
end;
procedure TFileDialogForm.FormActivate(Sender: TObject);
begin
QWidget_setEnabled(Handle, True);
end;
procedure TFileDialogForm.FileListFileFound(Sender: TObject;
const AFile: TSearchRec; var CanAdd: Boolean);
var
Filename: string;
begin
{$IFDEF MSWINDOWS}
Filename := AFile.FindData.cFileName;
//TODO: get mode/permissions on Windows
{$ENDIF}
{$IFDEF LINUX}
Filename := AFile.PathOnly + AFile.Name;
CanAdd := FOpenDialog.FileAdd(Filename, access(PChar(Filename), R_OK) = 0,
access(PChar(Filename), W_OK) = 0, access(PChar(Filename), X_OK) = 0);
{$ENDIF}
end;
procedure TFileDialogForm.FileIconsKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if not FileIcons.IsEditing and (Key <> Key_Shift) and (Key <> Key_Control)
and (Key <> Key_Return) and (Key <> Key_Enter) then
QApplication_postEvent(Handle, QCustomEvent_create(QEventType_FDSelect, nil));
end;
procedure TFileDialogForm.FileIconsMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
QApplication_postEvent(Handle, QCustomEvent_create(QEventType_FDSelect, nil));
end;
procedure TFileDialogForm.UpdateSelectionState(Sender: TObject);
var
Selections: TFileInfos;
I: Integer;
Filenames: WideString;
begin
Selections := nil;
if (Sender <> FileIcons) and (Sender <> FFileList) then Exit;
if not AutoPreviewCheckbox.Checked then
ClearPreview;
Selections := GetSelections(Sender);
if High(Selections) < 0 then
begin
if Dialog is TSaveDialog then
OpenAction.Caption := SSave
else
OpenAction.Caption := SOpen;
FDirSelected := False;
end
else if (High(Selections) = 0) and (Selections[0].SR.Attr and faDirectory <> 0) then
begin
OpenAction.Caption := SOpen;
FDirSelected := True;
end
else
begin
if Dialog is TSaveDialog then
OpenAction.Caption := SSave
else
OpenAction.Caption := SOpen;
FDirSelected := False;
FileEdit.ClearSelection;
if High(Selections) = 0 then
FileEdit.Text := Selections[0].SR.Name
else begin
ClearPreview;
for I := 0 to High(Selections) do
if Selections[I].SR.Attr and faDirectory = 0 then
Filenames := Filenames + '"' + Selections[I].SR.Name + '" ';
if Filenames <> '' then
FileEdit.Text := Trim(Filenames);
end;
OpenButton.Enabled := FileEdit.Text <> '';
if FAutoPreview then
PreviewButtonClick(Self);
end;
end;
function TFileDialogForm.EventFilter(Sender: QObjectH;
Event: QEventH): Boolean;
begin
Result := False;
if QEvent_type(Event) = QEventType_FDSelect then
begin
UpdateSelectionState(ActiveControl);
end else
Result := inherited EventFilter(Sender, Event);
end;
procedure TFileDialogForm.ImagePanelResize(Sender: TObject);
begin
ClearPreview;
end;
procedure TFileDialogForm.FormCreate(Sender: TObject);
begin
PreviewScroll := TPreviewScrollBox.Create(PreviewPanel);
PreviewScroll.Parent := PreviewPanel;
PreviewScroll.SetBounds(3, Panel2.Height, PreviewPanel.Width - 6,
FileIcons.Height);
PreviewScroll.Anchors := [akLeft, akTop, akRight, akBottom];
end;
procedure TFileDialogForm.ResizePreview(const NewSize: TSize);
begin
with PreviewScroll do
begin
HorzScrollBar.Range := NewSize.cx;
VertScrollBar.Range := NewSize.cy;
HorzScrollBar.Position := 0;
VertScrollBar.Position := 0;
FBitmap.Width := NewSize.cx;
FBitmap.Height := NewSize.cy;
Canvas.Brush.Color := PreviewPanel.Color;
Canvas.FillRect(Rect(0, 0, PreviewScroll.FBitmap.Width,
PreviewScroll.FBitmap.Height));
end;
end;
function TFileDialogForm.FileList: TFileListView;
begin
if FFileList = nil then
begin
FFileList := TFileListView.Create(Self);
with FFileList do
begin
Parent := FileIcons.Parent;
Left := FileIcons.Left;
Top := FileIcons.Top;
Align := alClient;
FFileList.HandleNeeded;
Directory.Assign(FileIcons.Directory);
MultiSelect := FileIcons.MultiSelect;
ReadOnly := False;
TabOrder := 1;
ViewStyle := vsList;
Visible := False;
OnContextPopup := FileListContextPopup;
OnDblClick := FileListDblClick;
OnDirectoryChanged := FileIconsDirectoryChange;
OnFileFound := FileListFileFound;
OnKeyUp := FileIconsKeyUp;
OnMouseUp := FileIconsMouseUp;
OnSelectItem := FileListSelectItem;
end;
end;
Result := FFileList;
end;
{ TPreviewScrollBox }
procedure TPreviewScrollBox.BoundsChanged;
begin
inherited BoundsChanged;
if Assigned(FBitmap) then
begin
FBitmap.Width := ClientWidth;
FBitmap.Height := ClientHeight;
end;
end;
procedure TPreviewScrollBox.CanvasChanged(Sender: TObject);
begin
Repaint;
end;
constructor TPreviewScrollBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FBitmap := TBitmap.Create;
FBitmap.Height := 100;
FBitmap.Width := 100;
FBitmap.Canvas.OnChange := CanvasChanged;
end;
destructor TPreviewScrollBox.Destroy;
begin
FBitmap.Free;
FCanvas.Free;
inherited;
end;
function TPreviewScrollBox.EventFilter(Sender: QObjectH;
Event: QEventH): Boolean;
var
ScrollRect: TRect;
begin
Result := False;
if QEvent_type(Event) = QEventType_Paint then
begin
if not (csWidgetPainting in ControlState) then
begin
inherited EventFilter(Sender, Event);
TControlCanvas(FCanvas).StartPaint;
try
ScrollRect := Rect(-HorzScrollBar.Position, -VertScrollBar.Position,
-HorzScrollBar.Position + ClientWidth, -VertScrollBar.Position + ClientHeight);
FCanvas.CopyRect(ScrollRect, FBitmap.Canvas, Rect(0, 0, FBitmap.Width,
FBitmap.Height));
finally
TControlCanvas(FCanvas).StopPaint;
end;
end else
Result := False;
end
else Result := inherited EventFilter(Sender, Event);
end;
function TPreviewScrollBox.GetCanvas: TCanvas;
begin
Result := FBitmap.Canvas;
end;
procedure TPreviewScrollBox.InitWidget;
begin
inherited InitWidget;
BorderStyle := bsEtched;
end;
procedure TFileDialogForm.PreviewPanelResize(Sender: TObject);
begin
ClearPreview;
end;
procedure TFileDialogForm.FormLoaded(Sender: TObject);
begin
FileIconsDirectoryChange(FileIcons, FileIcons.Directory.Location);
end;
initialization
finalization
end.
|
unit IdTCPConnection;
interface
uses
Classes, IdException,
IdComponent, IdGlobal, IdSocketHandle, IdIntercept;
const
GRecvBufferSizeDefault = 32768;
GSendBufferSizeDefault = 32768;
type
TIdBuffer = class(TMemoryStream)
public
procedure RemoveXBytes(const AByteCount: integer);
end;
TIdTCPConnection = class(TIdComponent)
protected
FASCIIFilter: boolean;
FBinding: TIdSocketHandle;
FBuffer: TIdBuffer;
FClosedGracefully: boolean;
FCmdResultDetails: TStrings;
FIntercept: TIdConnectionIntercept;
FInterceptEnabled: Boolean;
FOnDisconnected: TNotifyEvent;
FReadLnTimedOut: Boolean;
FRecvBuffer: TIdBuffer;
FResultNo: SmallInt;
FSendBufferSize: Integer;
FWriteBuffer: TIdBuffer;
FWriteBufferThreshhold: Integer;
//
procedure DoOnDisconnected; virtual;
function GetCmdResult: string;
function GetRecvBufferSize: Integer;
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure ResetConnection; virtual;
procedure SetIntercept(AValue: TIdConnectionIntercept);
procedure SetInterceptEnabled(AValue: Boolean);
procedure SetRecvBufferSize(const Value: Integer);
public
function AllData: string; virtual;
procedure CancelWriteBuffer;
procedure Capture(ADest: TObject; const ADelim: string = '.'; const
AIsRFCMessage: Boolean = False);
procedure CheckForDisconnect(const ARaiseExceptionIfDisconnected: boolean =
true;
const AIgnoreBuffer: boolean = false); virtual;
procedure CheckForGracefulDisconnect(const ARaiseExceptionIfDisconnected:
boolean = true);
virtual;
function CheckResponse(const AResponse: SmallInt; const AAllowedResponses:
array of SmallInt)
: SmallInt; virtual;
procedure ClearWriteBuffer;
procedure CloseWriteBuffer;
function Connected: boolean; virtual;
constructor Create(AOwner: TComponent); override;
function CurrentReadBuffer: string;
function CurrentReadBufferSize: integer;
destructor Destroy; override;
procedure Disconnect; virtual;
procedure DisconnectSocket; virtual;
function ExtractXBytesFromBuffer(const AByteCount: Integer): string;
virtual;
procedure FlushWriteBuffer(const AByteCount: Integer = -1);
function GetResponse(const AAllowedResponses: array of SmallInt): SmallInt;
virtual;
function InputLn(const AMask: string = ''): string;
procedure OpenWriteBuffer(const AThreshhold: Integer = -1);
procedure RaiseExceptionForCmdResult; overload; virtual;
procedure RaiseExceptionForCmdResult(axException: TClassIdException);
overload; virtual;
procedure ReadBuffer(var ABuffer; const AByteCount: Longint);
function ReadCardinal(const AConvert: boolean = true): Cardinal;
function ReadFromStack(const ARaiseExceptionIfDisconnected: boolean = true;
const ATimeout: integer = IdTimeoutInfinite; const AUseBuffer: boolean =
true;
ADestStream: TIdBuffer = nil): integer;
virtual;
function ReadInteger(const AConvert: boolean = true): Integer;
function ReadLn(const ATerminator: string = '';
const ATimeout: integer = IdTimeoutInfinite): string; virtual;
function ReadLnWait: string;
function ReadSmallInt(const AConvert: boolean = true): SmallInt;
procedure ReadStream(AStream: TStream; AByteCount: LongInt = -1;
const AReadUntilDisconnect: boolean = false);
function ReadString(const ABytes: integer): string;
procedure RemoveXBytesFromBuffer(const AByteCount: Integer); virtual;
function SendCmd(const AOut: string; const AResponse: SmallInt = -1):
SmallInt; overload;
function SendCmd(const AOut: string; const AResponse: array of SmallInt):
SmallInt; overload;
virtual;
function WaitFor(const AString: string): string;
procedure Write(AOut: string); virtual;
procedure WriteBuffer(const ABuffer; AByteCount: Longint; const AWriteNow:
boolean = false);
procedure WriteCardinal(AValue: Cardinal; const AConvert: boolean = true);
procedure WriteHeader(axHeader: TStrings);
procedure WriteInteger(AValue: Integer; const AConvert: boolean = true);
procedure WriteLn(const AOut: string = ''); virtual;
procedure WriteSmallInt(AValue: SmallInt; const AConvert: boolean = true);
procedure WriteStream(AStream: TStream; const AAll: boolean = true;
const AWriteByteCount: Boolean = false); virtual;
procedure WriteStrings(AValue: TStrings);
function WriteFile(AFile: string; const AEnableTransferFile: boolean =
false): cardinal;
virtual;
property Binding: TIdSocketHandle read FBinding;
property ClosedGracefully: boolean read FClosedGracefully;
property CmdResult: string read GetCmdResult;
property CmdResultDetails: TStrings read FCmdResultDetails;
property ReadLnTimedOut: Boolean read FReadLnTimedOut;
property ResultNo: SmallInt read FResultNo;
published
property ASCIIFilter: boolean read FASCIIFilter write FASCIIFilter default
False;
property Intercept: TIdConnectionIntercept read FIntercept write
SetIntercept;
property InterceptEnabled: Boolean read FInterceptEnabled write
SetInterceptEnabled default False;
property OnDisconnected: TNotifyEvent read FOnDisconnected write
FOnDisconnected;
property OnWork;
property OnWorkBegin;
property OnWorkEnd;
property RecvBufferSize: Integer read GetRecvBufferSize write
SetRecvBufferSize default GRecvBufferSizeDefault;
property SendBufferSize: Integer read FSendBufferSize write FSendBufferSize
default GSendBufferSizeDefault;
end;
EIdTCPConnectionError = class(EIdException);
EIdObjectTypeNotSupported = class(EIdTCPConnectionError);
EIdNotEnoughDataInBuffer = class(EIdTCPConnectionError);
EIdInterceptPropIsNil = class(EIdTCPConnectionError);
EIdInterceptPropInvalid = class(EIdTCPConnectionError);
EIdNoDataToRead = class(EIdTCPConnectionError);
implementation
uses
IdAntiFreezeBase,
IdStack, IdStackConsts, IdResourceStrings,
SysUtils;
function TIdTCPConnection.AllData: string;
begin
BeginWork(wmRead);
try
result := '';
while Connected do
begin
Result := Result + CurrentReadBuffer;
end;
finally EndWork(wmRead);
end;
end;
procedure TIdTCPConnection.Capture(ADest: TObject; const ADelim: string = '.';
const AIsRFCMessage: Boolean = False);
var
s: string;
begin
BeginWork(wmRead);
try
repeat
s := ReadLn;
if s = ADelim then
begin
exit;
end;
if AIsRFCMessage and (Copy(s, 1, 2) = '..') then
begin
Delete(s, 1, 1);
end;
if ADest is TStrings then
begin
TStrings(ADest).Add(s);
end
else
if ADest is TStream then
begin
TStream(ADest).WriteBuffer(s[1], Length(s));
s := EOL;
TStream(ADest).WriteBuffer(s[1], Length(s));
end
else
if ADest <> nil then
begin
raise EIdObjectTypeNotSupported.Create(RSObjectTypeNotSupported);
end;
until false;
finally EndWork(wmRead);
end;
end;
procedure TIdTCPConnection.CheckForDisconnect(const
ARaiseExceptionIfDisconnected: boolean = true;
const AIgnoreBuffer: boolean = false);
begin
if ClosedGracefully or (Binding.HandleAllocated = false) then
begin
if Binding.HandleAllocated then
begin
DisconnectSocket;
end;
if ((CurrentReadBufferSize = 0) or AIgnoreBuffer) and
ARaiseExceptionIfDisconnected then
begin
(* ************************************************************* //
------ If you receive an exception here, please read. ----------
If this is a SERVER
-------------------
The client has disconnected the socket normally and this exception is used to notify the
server handling code. This exception is normal and will only happen from within the IDE, not
while your program is running as an EXE. If you do not want to see this, add this exception
or EIdSilentException to the IDE options as exceptions not to break on.
From the IDE just hit F9 again and Indy will catch and handle the exception.
Please see the FAQ and help file for possible further information.
The FAQ is at http://www.nevrona.com/Indy/FAQ.html
If this is a CLIENT
-------------------
The server side of this connection has disconnected normaly but your client has attempted
to read or write to the connection. You should trap this error using a try..except.
Please see the help file for possible further information.
// ************************************************************* *)
raise EIdConnClosedGracefully.Create(RSConnectionClosedGracefully);
end;
end;
end;
function TIdTCPConnection.Connected: boolean;
begin
CheckForDisconnect(False);
result := Binding.HandleAllocated;
end;
constructor TIdTCPConnection.Create(AOwner: TComponent);
begin
inherited;
FBinding := TIdSocketHandle.Create(nil);
FCmdResultDetails := TStringList.Create;
FRecvBuffer := TIdBuffer.Create;
RecvBufferSize := GRecvBufferSizeDefault;
FSendBufferSize := GSendBufferSizeDefault;
FBuffer := TIdBuffer.Create;
end;
function TIdTCPConnection.CurrentReadBuffer: string;
begin
result := '';
if Connected then
begin
ReadFromStack(False);
result := ExtractXBytesFromBuffer(FBuffer.Size);
end;
end;
function TIdTCPConnection.CurrentReadBufferSize: integer;
begin
result := FBuffer.Size;
end;
destructor TIdTCPConnection.Destroy;
begin
FreeAndNil(FBuffer);
FreeAndNil(FRecvBuffer);
FreeAndNil(FCmdResultDetails);
FreeAndNil(FBinding);
inherited;
end;
procedure TIdTCPConnection.Disconnect;
begin
DisconnectSocket;
end;
procedure TIdTCPConnection.DoOnDisconnected;
begin
if assigned(OnDisconnected) then
begin
OnDisconnected(Self);
end;
end;
function TIdTCPConnection.ExtractXBytesFromBuffer(const AByteCount: Integer):
string;
begin
if AByteCount > FBuffer.Size then
begin
raise EIdNotEnoughDataInBuffer.Create(RSNotEnoughDataInBuffer);
end;
SetString(result, PChar(FBuffer.Memory), AByteCount);
RemoveXBytesFromBuffer(AByteCount);
end;
function TIdTCPConnection.GetCmdResult: string;
begin
result := '';
if CmdResultDetails.Count > 0 then
begin
result := CmdResultDetails[CmdResultDetails.Count - 1];
end;
end;
function TIdTCPConnection.GetRecvBufferSize: Integer;
begin
result := FRecvBuffer.Size;
end;
function TIdTCPConnection.GetResponse(const AAllowedResponses: array of
SmallInt): SmallInt;
var
sLine, sTerm: string;
begin
CmdResultDetails.Clear;
sLine := ReadLnWait;
CmdResultDetails.Add(sLine);
if length(sLine) > 3 then
begin
if sLine[4] = '-' then
begin
sTerm := Copy(sLine, 1, 3) + ' ';
repeat
sLine := ReadLnWait;
CmdResultDetails.Add(sLine);
until (Length(sLine) < 4) or (AnsiSameText(Copy(sLine, 1, 4), sTerm));
end;
end;
if AnsiSameText(Copy(CmdResult, 1, 3), '+OK') then
begin
FResultNo := wsOK;
end
else
if AnsiSameText(Copy(CmdResult, 1, 4), '-ERR') then
begin
FResultNo := wsErr;
end
else
begin
FResultNo := StrToIntDef(Copy(CmdResult, 1, 3), 0);
end;
Result := CheckResponse(ResultNo, AAllowedResponses);
end;
procedure TIdTCPConnection.RaiseExceptionForCmdResult(axException:
TClassIdException);
begin
raise axException.Create(CmdResult);
end;
procedure TIdTCPConnection.RaiseExceptionForCmdResult;
begin
raise EIdProtocolReplyError.CreateError(ResultNo, CmdResult);
end;
procedure TIdTCPConnection.ReadBuffer(var ABuffer; const AByteCount: Integer);
begin
if (AByteCount > 0) and (@ABuffer <> nil) then
begin
while CurrentReadBufferSize < AByteCount do
begin
ReadFromStack;
end;
Move(PChar(FBuffer.Memory)[0], ABuffer, AByteCount);
RemoveXBytesFromBuffer(AByteCount);
end;
end;
function TIdTCPConnection.ReadFromStack(const ARaiseExceptionIfDisconnected:
boolean = true;
const ATimeout: integer = IdTimeoutInfinite; const AUseBuffer: boolean = true;
ADestStream: TIdBuffer = nil): integer;
var
nByteCount, j: Integer;
procedure DefaultRecv;
begin
nByteCount := Binding.Recv(ADestStream.Memory^, ADestStream.Size, 0);
end;
begin
result := 0;
CheckForDisconnect(ARaiseExceptionIfDisconnected);
if Connected then
begin
if ADestStream = nil then
begin
ADestStream := FRecvBuffer;
end;
if Binding.Readable(ATimeout) then
begin
if InterceptEnabled then
begin
if Intercept.RecvHandling then
begin
nByteCount := Intercept.Recv(ADestStream.Memory^, ADestStream.Size);
end
else
begin
DefaultRecv;
end;
end
else
begin
DefaultRecv;
end;
FClosedGracefully := nByteCount = 0;
if not ClosedGracefully then
begin
if GStack.CheckForSocketError(nByteCount, [Id_WSAESHUTDOWN]) then
begin
nByteCount := 0;
if Binding.HandleAllocated then
begin
DisconnectSocket;
end;
if CurrentReadBufferSize = 0 then
begin
GStack.RaiseSocketError(Id_WSAESHUTDOWN);
end;
end;
if ASCIIFilter then
begin
for j := 1 to nByteCount do
begin
PChar(ADestStream.Memory)[j] := Chr(Ord(PChar(ADestStream.Memory)[j])
and $7F);
end;
end;
end;
if AUseBuffer then
begin
FBuffer.Position := FBuffer.Size;
FBuffer.WriteBuffer(ADestStream.Memory^, nByteCount);
end
else
begin
DoWork(wmRead, nByteCount);
end;
if InterceptEnabled then
begin
Intercept.DataReceived(ADestStream.Memory^, nByteCount);
end;
CheckForDisconnect(ARaiseExceptionIfDisconnected);
result := nByteCount;
end;
end;
end;
function TIdTCPConnection.ReadInteger(const AConvert: boolean = true): Integer;
begin
ReadBuffer(Result, SizeOf(Result));
if AConvert then
begin
Result := Integer(GStack.WSNToHL(LongWord(Result)));
end;
end;
function TIdTCPConnection.ReadLn(const ATerminator: string = '';
const ATimeout: integer = IdTimeoutInfinite): string;
var
i: Integer;
s: string;
LTerminator: string;
begin
if Length(ATerminator) = 0 then
begin
LTerminator := LF;
end
else
begin
LTerminator := ATerminator;
end;
FReadLnTimedOut := False;
i := 0;
repeat
if CurrentReadBufferSize > 0 then
begin
SetString(s, PChar(FBuffer.Memory), FBuffer.Size);
i := Pos(LTerminator, s);
end;
if i = 0 then
begin
CheckForDisconnect(True, True);
FReadLnTimedOut := ReadFromStack(True, ATimeout) = 0;
if ReadLnTimedout then
begin
result := '';
exit;
end;
end;
until i > 0;
Result := ExtractXBytesFromBuffer(i + Length(LTerminator) - 1);
SetLength(Result, i - 1);
if (Length(ATerminator) = 0) and (Copy(Result, Length(Result), 1) = CR) then
begin
SetLength(Result, Length(Result) - 1);
end;
end;
function TIdTCPConnection.ReadLnWait: string;
begin
Result := '';
while length(Result) = 0 do
begin
Result := Trim(ReadLn);
end;
end;
procedure TIdTCPConnection.ReadStream(AStream: TStream; AByteCount: Integer =
-1;
const AReadUntilDisconnect: boolean = false);
var
i: integer;
LBuffer: TIdBuffer;
LBufferCount: integer;
LWorkCount: integer;
procedure AdjustStreamSize(AStream: TStream; const ASize: integer);
var
LStreamPos: LongInt;
begin
LStreamPos := AStream.Position;
AStream.Size := ASize;
if AStream.Position <> LStreamPos then
begin
AStream.Position := LStreamPos;
end;
end;
begin
if (AByteCount = -1) and (AReadUntilDisconnect = False) then
begin
AByteCount := ReadInteger;
end;
if AByteCount > -1 then
begin
AdjustStreamSize(AStream, AStream.Position + AByteCount);
end;
if AReadUntilDisconnect then
begin
LWorkCount := High(LWorkCount);
BeginWork(wmRead);
end
else
begin
LWorkCount := AByteCount;
BeginWork(wmRead, LWorkCount);
end;
try
LBufferCount := Min(CurrentReadBufferSize, LWorkCount);
Dec(LWorkCount, LBufferCount);
AStream.WriteBuffer(FBuffer.Memory^, LBufferCount);
FBuffer.RemoveXBytes(LBufferCount);
LBuffer := TIdBuffer.Create;
try
while Connected and (LWorkCount > 0) do
begin
i := Min(LWorkCount, RecvBufferSize);
if LBuffer.Size <> i then
begin
LBuffer.Size := i;
end;
i := ReadFromStack(not AReadUntilDisconnect, IdTimeoutInfinite, False,
LBuffer);
if AStream.Position + i > AStream.Size then
begin
AdjustStreamSize(AStream, AStream.Size + 4 * CurrentReadBufferSize);
end;
AStream.WriteBuffer(LBuffer.Memory^, i);
Dec(LWorkCount, i);
end;
finally LBuffer.Free;
end;
finally EndWork(wmRead);
end;
if AStream.Size > AStream.Position then
begin
AStream.Size := AStream.Position;
end;
end;
procedure TIdTCPConnection.RemoveXBytesFromBuffer(const AByteCount: Integer);
begin
FBuffer.RemoveXBytes(AByteCount);
DoWork(wmRead, AByteCount);
end;
procedure TIdTCPConnection.ResetConnection;
begin
Binding.Reset;
FBuffer.Clear;
FClosedGracefully := False;
end;
function TIdTCPConnection.SendCmd(const AOut: string; const AResponse: array of
SmallInt): SmallInt;
begin
if AOut <> #0 then
begin
WriteLn(AOut);
end;
Result := GetResponse(AResponse);
end;
procedure TIdTCPConnection.Notification(AComponent: TComponent; Operation:
TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if (AComponent = FIntercept) then
begin
Intercept := nil;
end;
end;
end;
procedure TIdTCPConnection.SetIntercept(AValue: TIdConnectionIntercept);
begin
FIntercept := AValue;
if FIntercept = nil then
begin
FInterceptEnabled := false;
end
else
begin
if assigned(FIntercept) then
begin
FIntercept.FreeNotification(self);
end;
end;
end;
procedure TIdTCPConnection.SetInterceptEnabled(AValue: Boolean);
begin
if (Intercept = nil) and (not (csLoading in ComponentState)) and AValue then
begin
raise EIdInterceptPropIsNil.Create(RSInterceptPropIsNil);
end;
FInterceptEnabled := AValue;
end;
procedure TIdTCPConnection.SetRecvBufferSize(const Value: Integer);
begin
FRecvBuffer.Size := Value;
end;
procedure TIdTCPConnection.Write(AOut: string);
begin
if Length(AOut) > 0 then
begin
WriteBuffer(AOut[1], length(AOut));
end;
end;
procedure TIdTCPConnection.WriteBuffer(const ABuffer; AByteCount: Integer;
const AWriteNow: boolean = false);
var
nPos, nByteCount: Integer;
procedure DefaultSend;
begin
nByteCount := Binding.Send(PChar(@ABuffer)[nPos - 1], AByteCount - nPos + 1,
0);
TIdAntiFreezeBase.DoProcess(False);
end;
begin
if (AByteCount > 0) and (@ABuffer <> nil) then
begin
CheckForDisconnect(True, True);
if (FWriteBuffer = nil) or AWriteNow then
begin
nPos := 1;
repeat
if InterceptEnabled then
begin
if Intercept.SendHandling then
begin
nByteCount := Intercept.Send(PChar(@ABuffer)[nPos - 1], AByteCount -
nPos + 1);
end
else
begin
DefaultSend;
end;
end
else
begin
DefaultSend;
end;
FClosedGracefully := nByteCount = 0;
CheckForDisconnect;
if GStack.CheckForSocketError(nByteCount, [ID_WSAESHUTDOWN]) then
begin
DisconnectSocket;
GStack.RaiseSocketError(ID_WSAESHUTDOWN);
end;
DoWork(wmWrite, nByteCount);
if InterceptEnabled then
begin
Intercept.DataSent(PChar(@ABuffer)[nPos - 1], AByteCount - nPos + 1);
end;
nPos := nPos + nByteCount
until nPos > AByteCount;
end
else
begin
FWriteBuffer.WriteBuffer(ABuffer, AByteCount);
if (FWriteBuffer.Size >= FWriteBufferThreshhold) and
(FWriteBufferThreshhold > 0) then
begin
FlushWriteBuffer(FWriteBufferThreshhold);
end;
end;
end;
end;
function TIdTCPConnection.WriteFile(AFile: string; const AEnableTransferFile:
boolean = false)
: cardinal;
var
LFileStream: TFileStream;
begin
if assigned(GServeFileProc) and (InterceptEnabled = false) and
AEnableTransferFile then
begin
result := GServeFileProc(Binding.Handle, AFile);
end
else
begin
LFileStream := TFileStream.Create(AFile, fmOpenRead or fmShareDenyNone);
try
WriteStream(LFileStream);
result := LFileStream.Size;
finally LFileStream.free;
end;
end;
end;
procedure TIdTCPConnection.WriteHeader(axHeader: TStrings);
var
i: Integer;
begin
for i := 0 to axHeader.Count - 1 do
begin
WriteLn(StringReplace(axHeader[i], '=', ': ', []));
end;
WriteLn('');
end;
procedure TIdTCPConnection.WriteInteger(AValue: Integer; const AConvert: boolean
= true);
begin
if AConvert then
begin
AValue := Integer(GStack.WSHToNl(LongWord(AValue)));
end;
WriteBuffer(AValue, SizeOf(AValue));
end;
procedure TIdTCPConnection.WriteLn(const AOut: string = '');
begin
Write(AOut + EOL);
end;
procedure TIdTCPConnection.WriteStream(AStream: TStream; const AAll: boolean =
true;
const AWriteByteCount: Boolean = false);
var
LSize: integer;
LBuffer: TMemoryStream;
begin
if AAll then
begin
AStream.Position := 0;
end;
LSize := AStream.Size - AStream.Position;
if AWriteByteCount then
begin
WriteInteger(LSize);
end;
BeginWork(wmWrite, LSize);
try
LBuffer := TMemoryStream.Create;
try
LBuffer.SetSize(FSendBufferSize);
while true do
begin
LSize := Min(AStream.Size - AStream.Position, FSendBufferSize);
if LSize = 0 then
begin
Break;
end;
LSize := AStream.Read(LBuffer.Memory^, LSize);
if LSize = 0 then
begin
raise EIdNoDataToRead.Create(RSIdNoDataToRead);
end;
WriteBuffer(LBuffer.Memory^, LSize);
end;
finally FreeAndNil(LBuffer);
end;
finally EndWork(wmWrite);
end;
end;
procedure TIdTCPConnection.WriteStrings(AValue: TStrings);
var
i: Integer;
begin
for i := 0 to AValue.Count - 1 do
begin
WriteLn(AValue.Strings[i]);
end;
end;
function TIdTCPConnection.SendCmd(const AOut: string; const AResponse:
SmallInt): SmallInt;
begin
if AResponse = -1 then
begin
result := SendCmd(AOut, []);
end
else
begin
result := SendCmd(AOut, [AResponse]);
end;
end;
procedure TIdTCPConnection.DisconnectSocket;
begin
if Binding.HandleAllocated then
begin
DoStatus(hsDisconnecting, [Binding.PeerIP]);
Binding.CloseSocket;
FClosedGracefully := True;
DoStatus(hsDisconnected, [Binding.PeerIP]);
DoOnDisconnected;
end;
if InterceptEnabled then
begin
Intercept.Disconnect;
end;
end;
procedure TIdTCPConnection.OpenWriteBuffer(const AThreshhold: Integer = -1);
begin
FWriteBuffer := TIdBuffer.Create;
FWriteBufferThreshhold := AThreshhold;
end;
procedure TIdTCPConnection.CloseWriteBuffer;
begin
FlushWriteBuffer;
FreeAndNil(FWriteBuffer);
end;
procedure TIdTCPConnection.FlushWriteBuffer(const AByteCount: Integer = -1);
begin
if FWriteBuffer.Size > 0 then
begin
if (AByteCount = -1) or (FWriteBuffer.Size < AByteCount) then
begin
WriteBuffer(PChar(FWriteBuffer.Memory)[0], FWriteBuffer.Size, True);
ClearWriteBuffer;
end
else
begin
WriteBuffer(PChar(FWriteBuffer.Memory)[0], AByteCount, True);
FWriteBuffer.RemoveXBytes(AByteCount);
end;
end;
end;
procedure TIdTCPConnection.ClearWriteBuffer;
begin
FWriteBuffer.Clear;
end;
function TIdTCPConnection.InputLn(const AMask: string = ''): string;
var
s: string;
begin
result := '';
while true do
begin
s := ReadString(1);
if s = BACKSPACE then
begin
if length(result) > 0 then
begin
SetLength(result, Length(result) - 1);
Write(BACKSPACE);
end;
end
else
if s = CR then
begin
ReadString(1);
WriteLn;
exit;
end
else
begin
result := result + s;
if Length(AMask) = 0 then
begin
Write(s);
end
else
begin
Write(AMask);
end;
end;
end;
end;
function TIdTCPConnection.ReadString(const ABytes: integer): string;
begin
SetLength(result, ABytes);
if ABytes > 0 then
begin
ReadBuffer(Result[1], Length(Result));
end;
end;
procedure TIdTCPConnection.CancelWriteBuffer;
begin
ClearWriteBuffer;
CloseWriteBuffer;
end;
function TIdTCPConnection.ReadSmallInt(const AConvert: boolean = true):
SmallInt;
begin
ReadBuffer(Result, SizeOf(Result));
if AConvert then
begin
Result := SmallInt(GStack.WSNToHs(Word(Result)));
end;
end;
procedure TIdTCPConnection.WriteSmallInt(AValue: SmallInt; const AConvert:
boolean = true);
begin
if AConvert then
begin
AValue := SmallInt(GStack.WSHToNs(Word(AValue)));
end;
WriteBuffer(AValue, SizeOf(AValue));
end;
procedure TIdTCPConnection.CheckForGracefulDisconnect(
const ARaiseExceptionIfDisconnected: boolean);
begin
ReadFromStack(ARaiseExceptionIfDisconnected, 1);
end;
procedure TIdBuffer.RemoveXBytes(const AByteCount: integer);
begin
if AByteCount > Size then
begin
raise EIdNotEnoughDataInBuffer.Create(RSNotEnoughDataInBuffer);
end;
if AByteCount = Size then
begin
Clear;
end
else
begin
Move(PChar(Memory)[AByteCount], PChar(Memory)[0], Size - AByteCount);
SetSize(Size - AByteCount);
end;
end;
function TIdTCPConnection.WaitFor(const AString: string): string;
begin
result := '';
while Pos(AString, result) = 0 do
begin
Result := Result + CurrentReadBuffer;
CheckForDisconnect;
end;
end;
function TIdTCPConnection.ReadCardinal(const AConvert: boolean): Cardinal;
begin
ReadBuffer(Result, SizeOf(Result));
if AConvert then
begin
Result := GStack.WSNToHL(Result);
end;
end;
procedure TIdTCPConnection.WriteCardinal(AValue: Cardinal; const AConvert:
boolean);
begin
if AConvert then
begin
AValue := GStack.WSHToNl(AValue);
end;
WriteBuffer(AValue, SizeOf(AValue));
end;
function TIdTCPConnection.CheckResponse(const AResponse: SmallInt;
const AAllowedResponses: array of SmallInt): SmallInt;
var
i: integer;
LResponseFound: boolean;
begin
if High(AAllowedResponses) > -1 then
begin
LResponseFound := False;
for i := Low(AAllowedResponses) to High(AAllowedResponses) do
begin
if AResponse = AAllowedResponses[i] then
begin
LResponseFound := True;
Break;
end;
end;
if not LResponseFound then
begin
RaiseExceptionForCmdResult;
end;
end;
Result := AResponse;
end;
end.
|
unit UMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.ExtCtrls,
Vcl.Menus, Vcl.Buttons, Vcl.Imaging.pngimage, Vcl.XPMan, UArrayList;
type
TForm1 = class(TForm)
Panel1: TPanel;
Memo1: TMemo;
StringGrid1: TStringGrid;
ComboBox1: TComboBox;
Panel2: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
MainMenu1: TMainMenu;
N1: TMenuItem;
tht1: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
N8: TMenuItem;
N9: TMenuItem;
N10: TMenuItem;
N11: TMenuItem;
Panel3: TPanel;
Button6: TButton;
Button7: TButton;
Button8: TButton;
Button1: TButton;
ComboBox2: TComboBox;
Label4: TLabel;
Label5: TLabel;
BitBtn1: TBitBtn;
StringGrid2: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox2Change(Sender: TObject);
procedure Button7Click(Sender: TObject);
function Add: integer;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
List: TArrayList;
implementation
{$R *.dfm}
function TForm1.Add: integer;
var
i, j, row: integer;
flag: boolean;
begin
// with StringGrid1 do
// for i := 0 to RowCount - 1 do
// begin
// flag := true;
// for j := 0 to ColCount - 1 do
// if Cells[j, i] <> '' then
// begin
// flag := false;
// break;
// end;
// if flag = true then
// begin
// break;
// end;
// end;
// if flag = true then
// begin
// row := i;
// result := row;
// end
// else
// result := -1;
end;
procedure TForm1.Button7Click(Sender: TObject);
var
t: integer;
var
rowIndex, j: integer;
k: string;
El: TArrayList;
a, m, n: integer;
begin
// rowIndex := Add;
// if rowIndex = -1 then
// begin
// showMessage('Отсутствуют свободные строки!');
// exit;
// end;
//
// a := 0;
// with StringGrid1 do
// for j := 0 to ColCount - 1 do
//
// begin
// a := a + 1;
// k := InputBox('Новый элемент', 'Введите значение элемента:', '1');
// El := TArrayList.Create(k);
// LElement[a] := El;
// Cells[j, rowIndex] := LElement[a].GetInfo;
//
// end;
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
if ComboBox1.ItemIndex = 0 then
ComboBox2.Enabled := true;
end;
procedure TForm1.ComboBox2Change(Sender: TObject);
begin
if ComboBox2.ItemIndex = 0 then
Button1.Enabled := true;
Button7.Enabled := true;
Button8.Enabled := true;
Button6.Enabled := true;
BitBtn1.Enabled := true;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
myRect: TGridRect;
begin
List := TArrayList.Create;
Button1.Enabled := false;
Button7.Enabled := false;
Button8.Enabled := false;
Button6.Enabled := false;
BitBtn1.Enabled := false;
ComboBox2.Enabled := false;
StringGrid2.Cells[0, 0] := '1';
StringGrid2.Cells[1, 0] := '2';
StringGrid2.Cells[2, 0] := '3';
StringGrid2.Cells[3, 0] := '4';
StringGrid2.Cells[4, 0] := '5';
StringGrid2.Cells[5, 0] := '6';
StringGrid1.Options := StringGrid1.Options - [goEditing];
StringGrid2.Options := StringGrid1.Options - [goEditing];
StringGrid2.Options := StringGrid1.Options - [goDrawFocusSelected,
goRowMoving, goColMoving, goRowSelect];
with myRect do
begin
Left := -1;
Top := -1;
Right := -1;
Bottom := -1;
end;
StringGrid2.Selection := myRect;
StringGrid1.Selection := myRect;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLShaderCombiner<p>
Allows to combine shaders in different sequences.
Note, that can't just take 2 random shaders and combine them, because
shaders often override the objects material and vertex data with a total
disregard to what existed before it. But in some cases, especially with
multipass shaders, this unit does magic and allows to reuse and upgrade
previously written shaders.<p>
<b>History : </b><font size=-1><ul>
<li>23/02/07 - DaStr - Initial version (contributed to GLScene)
Previous version history:
v1.0 02 November '2006 Creation
}
unit GLShaderCombiner;
interface
{$I GLScene.inc}
uses
//VCL
Classes,
//GLScene
GLMaterial, GLScene, GLVectorGeometry, GLStrings, GLRenderContextInfo;
type
{: MP - multipass, SP-singlepass, AP - anypass (single or multi)
One-Two or Two-One determines the order of how the shaders should be applied
For example, sctTwoMPOneSP means that first one will be applied Shader Two,
which can be a multipass shader, then Shader One is applied, which should be
a singlepass shader.
sctOneMPTwoSP and sctTwoMPOneSP modes are actualy quite Str@nge,
because... well look at the code yourself
TODO: Add more modes here, including sctOneAPTwoAP, which should be the
default one.
By the way, I admit - the names do look stupid, and if someone gives them
proper names, I will be only glad.
}
TGLShaderCombinerType = (sctOneSPTwoAP, sctTwoSPOneAP,
sctOneMPTwoSP, sctTwoMPOneSP
);
TGLCustomShaderCombiner = class(TGLShader)
private
FCurrentPass: Integer;
FCombinerType: TGLShaderCombinerType;
FShaderOne: TGLShader;
FShaderTwo: TGLShader;
procedure SetShaderOne(const Value: TGLShader);
procedure SetShaderTwo(const Value: TGLShader);
protected
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property CombinerType: TGLShaderCombinerType read FCombinerType write FCombinerType default sctOneSPTwoAP;
property ShaderOne: TGLShader read FShaderOne write SetShaderOne;
property ShaderTwo: TGLShader read FShaderTwo write SetShaderTwo;
property CurrentPass : Integer read FCurrentPass stored False;
public
constructor Create(AOwner: TComponent); override;
function ShaderSupported: Boolean; override;
procedure Assign(Source: TPersistent); override;
end;
TGLShaderCombiner = class(TGLCustomShaderCombiner)
published
property CombinerType;
property ShaderOne;
property ShaderTwo;
property ShaderStyle;
end;
implementation
{ TGLCustomShaderCombiner }
procedure TGLCustomShaderCombiner.Assign(Source: TPersistent);
begin
inherited;
if Source is TGLCustomShaderCombiner then
begin
SetShaderOne(TGLCustomShaderCombiner(Source).FShaderOne);
SetShaderTwo(TGLCustomShaderCombiner(Source).FShaderTwo);
end;
end;
constructor TGLCustomShaderCombiner.Create(AOwner: TComponent);
begin
inherited;
FCombinerType := sctOneSPTwoAP;
end;
procedure TGLCustomShaderCombiner.DoApply(var rci: TRenderContextInfo;
Sender: TObject);
begin
if (csDesigning in ComponentState) then Exit;
Assert((FShaderOne <> nil) and (FShaderTwo <> nil));
FCurrentPass:=1;
case FCombinerType of
sctOneMPTwoSP:
begin
FShaderOne.Apply(rci, Self);
FShaderTwo.Apply(rci, Self);
end;
sctTwoMPOneSP:
begin
FShaderTwo.Apply(rci, Self);
FShaderOne.Apply(rci, Self);
end;
sctOneSPTwoAP:
begin
FShaderOne.Apply(rci, Self);
end;
sctTwoSPOneAP:
begin
FShaderTwo.Apply(rci, Self);
end;
else
Assert(False, glsErrorEx + glsUnknownType);
end;
end;
function TGLCustomShaderCombiner.DoUnApply(var rci: TRenderContextInfo): Boolean;
begin
case FCombinerType of
sctOneMPTwoSP:
begin
if FShaderOne.UnApply(rci) then
Result := True
else
Result := FShaderTwo.UnApply(rci);
end;
sctTwoMPOneSP:
begin
if FShaderTwo.UnApply(rci) then
Result := True
else
Result := FShaderOne.UnApply(rci);
end;
sctOneSPTwoAP:
begin
if FCurrentPass = 1 then
begin
FShaderOne.UnApply(rci);
FShaderTwo.Apply(rci, Self);
Result := True;
end
else
Result := FShaderTwo.UnApply(rci);
end;
sctTwoSPOneAP:
begin
if FCurrentPass = 1 then
begin
FShaderTwo.UnApply(rci);
FShaderOne.Apply(rci, Self);
Result := True;
end
else
Result := FShaderOne.UnApply(rci);
end;
else
begin
Result := False;
Assert(False, glsErrorEx + glsUnknownType);
end;
end;
Inc(FCurrentPass);
end;
procedure TGLCustomShaderCombiner.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FShaderOne then
FShaderOne := nil
else if AComponent = FShaderTwo then
FShaderTwo := nil;
end;
end;
procedure TGLCustomShaderCombiner.SetShaderOne(const Value: TGLShader);
begin
if FShaderOne <> nil then
FShaderOne.RemoveFreeNotification(Self);
FShaderOne := Value;
if FShaderOne <> nil then
FShaderOne.FreeNotification(Self);
end;
procedure TGLCustomShaderCombiner.SetShaderTwo(const Value: TGLShader);
begin
if FShaderTwo <> nil then
FShaderTwo.RemoveFreeNotification(Self);
FShaderTwo := Value;
if FShaderTwo <> nil then
FShaderTwo.FreeNotification(Self);
end;
function TGLCustomShaderCombiner.ShaderSupported: Boolean;
begin
Result := (FShaderOne <> nil) and (FShaderTwo <> nil) and
FShaderOne.ShaderSupported and FShaderTwo.ShaderSupported;
end;
initialization
RegisterClasses([TGLCustomShaderCombiner, TGLShaderCombiner]);
end.
|
unit proc_type_obj_4;
interface
implementation
uses System;
type
TProc = procedure(V: Int32) of object;
TC = class
private
FData: Int32;
FProc: TProc;
procedure Test;
procedure SetData(Value: Int32);
end;
procedure TC.Test;
begin
FProc := SetData;
FProc(15);
end;
procedure TC.SetData(Value: Int32);
begin
FData := Value;
end;
var
obj: TC;
G: Int32;
procedure Test;
begin
obj := TC.Create();
obj.Test();
G := obj.FData;
end;
initialization
Test();
finalization
Assert(G = 15);
end. |
unit XMlToDataSet;
interface
uses
System.Win.ComObj, Winapi.msxml, System.SysUtils, System.IOUtils,
Datasnap.DBClient, Data.DB, InterfaceConversor;
type
EvalidationError = class(Exception);
TXMLToDataSet = class(TConversor)
private
DataSet: TClientDataSet;
CaminhoDoArqv: String;
public
function Converter: string; override;
constructor Create(const Arquivo: string; ClientDataSet: TClientDataSet); override;
end;
implementation
uses
UnitConversor;
{ TXMLToDataSet }
constructor TXMLToDataSet.Create(const Arquivo: string; ClientDataSet: TClientDataSet);
begin
inherited;
CaminhoDoArqv := Arquivo;
DataSet := ClientDataSet;
end;
function TXMLToDataSet.Converter: string;
var
XML: IXMLDOMDocument;
RowNode: IXMLDOMNode;
ChildNode: IXMLDOMNode;
NodeRow: IXMLDOMNodeList;
Field: TField;
begin
inherited;
DataSet.Close;
DataSet.Fields.Clear;
XML := CreateOleObject('Microsoft.XMLDOM') as IXMLDOMDocument;
XML.load(CaminhoDoArqv);
if XML.parseError.errorCode <> 0 then
raise EvalidationError.Create('Error :' + XML.parseError.reason);
NodeRow := XML.selectNodes('/root/row');
if NodeRow.length = 0 then
Exit;
RowNode := NodeRow.item[0];
while RowNode <> nil do
begin
ChildNode := RowNode.childNodes.item[0];
while ChildNode <> nil do
begin
Field := TWideStringField.Create(DataSet);
Field.Name := '';
Field.FieldName := ChildNode.nodeName;
Field.DataSet := DataSet;
ChildNode := ChildNode.nextSibling;
end;
Break;
end;
DataSet.CreateDataSet;
while RowNode <> nil do
begin
ChildNode := RowNode.childNodes.item[0];
DataSet.Insert;
while ChildNode <> nil do
begin
DataSet.FieldByName(ChildNode.nodeName).Value := ChildNode.text;
Form1.rchTextos.Lines.Add(ChildNode.nodeName + ChildNode.text);
ChildNode := ChildNode.nextSibling;
end;
RowNode := RowNode.nextSibling;
if RowNode <> nil then
DataSet.Insert;
end;
end;
end.
|
unit SIP_Thread;
interface
uses pjsua,logger,SysUtils,SyncObjs,Classes,SIP_Call, SIP_Sound;
type
TAccountInfo=record
id,uri,host,scheme,account:String;
end;
TSIPThread=class(TThread)
private
config:pjconfig;
logconfig:pjlogconfig;
transport:pjtransport;
media:pjmediaconfig;
mediatransport:pjtransport;
TransportID:Integer;
pjpcmu:pjstring;
CallList:TThreadList;
CallLock:TEvent;
FAccountStart:Integer;
FHost:String;
AccountInfo:array of TAccountInfo;
Accounts:array of Integer;
FPacketTime:Integer;
FCodec:string;
procedure InitPJSUA;
procedure DestroyPJSUA;
function CheckCalls:Boolean;
protected
procedure Execute;override;
public
SIPPool:pointer;
CallDelay:Integer;
constructor Create(AccountStart,AccountCount,PacketTime:Integer;Host,Codec:String);
destructor Destroy;override;
class procedure CheckStatus(Status: Integer; F: String;Channel:TSIPCall=nil);
procedure Terminate;
procedure AddCall(Call:TSIPCall);
procedure MakeCall(Call:TSIPCall);
class procedure Hangup(Call:TSIPCall);
procedure WaitDTMF(Call:TSIPCall);
class procedure PlayWave(Call:TSIPCall;FileName:String);
procedure PlaySound(Call:TSIPCall;Sound:TSIPAnnouncement);
procedure AddPort(Port:ppjmedia_port;Channel:TSIPCall);
end;
ESIPException=class(Exception);
const
SIP_CLOCK_RATE=8000;
SIP_DTMF_RATE=10;
SIP_DTMF_FRAME=SIP_CLOCK_RATE div SIP_DTMF_RATE;
implementation
uses StrUtils, SIP_Monitor;
procedure TSIPThread.AddCall(Call:TSIPCall);
begin
CallList.Add(Call);
CallLock.SetEvent;
end;
procedure TSIPThread.AddPort(Port: ppjmedia_port;channel:TSIPCall);
begin
CheckStatus(pjsua_conf_add_port(SIPpool,port,port.port_data_l),'pjsua_conf_add_port',Channel);
end;
function TSIPThread.CheckCalls;
var L:TList;
C:TSIPCall;
begin
L:=CallList.LockList;
try
if L.Count=0 then
begin
CallLock.ResetEvent;
Result:=False;
end
else
begin
C:=L[0];
L.Delete(0);
C.StartSIP;
Result:=True;
end;
finally
CallList.UnlockList;
end;
if not Result then CallLock.WaitFor(5000);
end;
class procedure TSIPThread.CheckStatus(Status:Integer;F:String;Channel:TSIPCall);
begin
// debug tests
// if SameText(F,'pjsua_call_get_info') then Status:=-1;
// if SameText(F,'pjsua_create') then Status:=-1;
// if SameText(F,'pjsua_call_make_call') then Status:=-1;
// if SameText(F,'pjmedia_mem_player_create') then Status:=-1;
if Channel<>nil then
begin
if Status=0 then
Channel.LogDebug(F+' : 0')
else
begin
Channel.LogError(F+' : '+IntToStr(Status));
raise ESIPException.Create(F+' : '+IntToStr(Status));
end;
end else
begin
if Status=0 then
begin
if Log<>nil then Log.Debug(F+' : 0')
end
else
begin
if Log<>nil then Log.Error(F+' : '+IntToStr(Status));
raise ESIPException.Create(F+' : '+IntToStr(Status));
end;
end;
end;
constructor TSIPThread.Create;
begin
inherited Create(False);
CallList:=TThreadList.Create;
CallList.Duplicates:=dupIgnore;
CallLock:=TEvent.Create();
CallDelay:=200;
SetLength(Accounts,AccountCount);
SetLength(AccountInfo,AccountCount);
FAccountStart:=AccountStart;
FHost:=Host;
FPacketTime:=PacketTime;
FCodec:=Codec;
if FCodec='' then
FCodec:='PCMA';
//(info:(name:(s:'memplayer'; sz:9); signature:1297116281; mediatype:1;
// has_info:1; need_info:0; payload_type:255; encoding_name:(s:'pcm'; sz:3);
// clock_rate:8000; channel_count:1; bits_per_sample:16; samples_per_frame:80;
// bytes_per_fram:160); port_data_p:nil; podr_data_l:0)
end;
destructor TSIPThread.Destroy;
begin
inherited;
FreeAndNil(CallLock);
FreeAndNil(CallList);
end;
procedure TSIPThread.DestroyPJSUA;
begin
try
pjsua_call_hangup_all;
if SIPPool<>nil then pjsua_pool_release(SIPPool);
pjsua_set_no_snd_dev;
finally
pjsua_destroy;
end;
end;
procedure TSIPThread.Execute;
begin
try
InitPJSUA;
except
on E:Exception do
begin
try
if not (E is ESIPException) then
if (Log<>nil) then Log.Error(E.Message,E);
finally
Terminate;
end;
end;
end;
try
try
while not Terminated do
begin
CheckCalls;
end;
except
on E:Exception do if Log<>nil then Log.Error(E.Message,E);
end;
finally
DestroyPJSUA;
end;
end;
class procedure TSIPThread.Hangup(Call: TSIPCall);
var X:Integer;
begin
X:=Call.CallID;
if X<0 then Exit;
Call.LogInfo(Format('[%10.10d] Ending Call to %s',[X,Call.Phone]));
Call.InHangup:=False;
TSIPThread.CheckStatus(pjsua_call_hangup(X,0,nil,nil),'pjsua_call_hangup',Call);
end;
//info.state
//PJSIP_INV_STATE_NULL Before INVITE is sent or received
//PJSIP_INV_STATE_CALLING After INVITE is sent
//PJSIP_INV_STATE_INCOMING After INVITE is received.
//PJSIP_INV_STATE_EARLY After response with To tag.
//PJSIP_INV_STATE_CONNECTING After 2xx is sent/received.
//PJSIP_INV_STATE_CONFIRMED After ACK is sent/received.
//PJSIP_INV_STATE_DISCONNECTED Session is terminated.
//http://www.pjsip.org/pjsip/docs/html/structpjsip__event.htm
procedure call_state(call_id:integer;event:pointer);cdecl;
var info:pjcallinfo;
data:TObject;
S:String;
begin
data:=pjsua_call_get_user_data(call_id);
if data is TSIPCall then
begin
try
TSIPThread.CheckStatus(pjsua_call_get_info(call_id,info),'pjsua_call_get_info',TSIPCall(data));
if info.state=6 then
TSIPCall(data).CallID:=-1;
if info.last_status_text.sz>0 then
begin
SetLength(S,info.last_status_text.sz);
Move(info.last_status_text.s^,S[1],info.last_status_text.sz);
end
else
S:='';
TSIPCall(data).LogDebug(Format('CallID:%d, State:%d, SIP: %d %s',[call_id,info.state,info.last_status,s]));
case info.state of
5:begin
SIPMonitor.Status_SIP:=GetTick64;
TSIPCall(data).InitDTMF;
TSIPCall(data).Signal;
end;
6:begin
TSIPCall(data).CallID:=-1;
TSIPCall(data).Retry(info.last_status);
TSIPCall(data).Signal;
end;
end;
except
on E:Exception do
begin
try
if not (E is ESIPException) then TSIPCall(data).LogError(E.Message,E);
finally
TSIPCall(data).SignalFailure;
end;
end;
end;
end;
end;
//info.media_state
//PJSUA_CALL_MEDIA_NONE Call currently has no media
//PJSUA_CALL_MEDIA_ACTIVE The media is active
//PJSUA_CALL_MEDIA_LOCAL_HOLD The media is currently put on hold by local endpoint
//PJSUA_CALL_MEDIA_REMOTE_HOLD The media is currently put on hold by remote endpoint
//PJSUA_CALL_MEDIA_ERROR The media has reported error (e.g. ICE negotiation)
procedure media_state(call_id:integer);cdecl;
var info:pjcallinfo;
data:TObject;
begin
data:=pjsua_call_get_user_data(call_id);
if data is TSIPCall then
begin
try
TSIPThread.CheckStatus(pjsua_call_get_info(call_id,info),'pjsua_call_get_info',TSIPCall(data));
case info.media_status of
//1:TSIPCall(data).Signal;
2,3,4:begin
TSIPCall(data).InHangup:=True;
end;
//TSIPThread.CheckStatus(pjsua_call_hangup(call_id,0,nil,nil),'pjsua_call_hangup',TSIPCall(data));
end;
except
on E:Exception do
begin
try
if not (E is ESIPException) then TSIPCall(data).LogError(E.Message,E);
finally
TSIPCall(data).SignalFailure;
end;
end;
end;
end;
end;
procedure rx(call_id:integer;packet:pointer;bytesread:integer;stream:pointer);cdecl;
var
data:TObject;
begin
data:=pjsua_call_get_user_data(call_id);
if data is TSIPCall then
begin
try
if bytesread<0 then
begin
TSIPCall(Data).LogError('CallID:'+IntToStr(call_id)+',rx error:'+IntToStr(-bytesread));
TSIPCall(Data).StopCurrent;
end else
TSIPCall(data).Received(packet,bytesread);
except
on E:Exception do
begin
try
if not (E is ESIPException) then TSIPCall(data).LogError(E.Message,E);
finally
TSIPCall(data).SignalFailure;
end;
end;
end;
end else
begin
if bytesread<0 then
begin
if Log<>nil then Log.Error('CallID:'+IntToStr(call_id)+',rx error:'+IntToStr(-bytesread));
TSIPThread.CheckStatus(pjsua_call_hangup(call_id,0,nil,nil),'pjsua_call_hangup');
end;
end;
end;
procedure tx(call_id:integer;packet:pointer;bytesread:integer;stream:pointer);cdecl;
var
data:TObject;
begin
data:=pjsua_call_get_user_data(call_id);
if data is TSIPCall then
begin
try
TSIPCall(data).Sent(packet,bytesread);
except
on E:Exception do
begin
try
if not (E is ESIPException) then TSIPCall(data).LogError(E.Message,E);
finally
TSIPCall(data).SignalFailure;
end;
end;
end;
end;
end;
procedure pjlog(level:integer;msg:pointer;msg_len:integer);cdecl;
var S:String;
begin
if msg_len>0 then
begin
SetLength(S,msg_len);
Move(msg^,s[1],msg_len);
if Log<>nil then Log.Debug(trim(s));
end;
end;
procedure TSIPThread.InitPJSUA;
var I:Integer;
AccountID:Integer;
AccCfg:pjsua_acc_config;
begin
CheckStatus(pjsua_create,'pjsua_create');
SIPpool:=pjsua_pool_create('SIPThread',1024,1024);
if SIPpool=nil then
TSIPThread.CheckStatus(-1,'pjsua_pool_create returned nil');
pjsua_config_default(config);
config.max_calls:=64;
pjsua_logging_config_default(logconfig);
logconfig.log_sip_msg:=0;
logconfig.callback:=@pjlog;
config.callback.call_media_state:=@media_state;
config.callback.call_state:=@call_state;
config.callback.rx:=@rx;
config.callback.tx:=@tx;
pjsua_media_config_default(media);
media.clock_rate:=SIP_CLOCK_RATE;
media.audio_frame_ptime:=FPacketTime;
media.ptime:=FPacketTime;
media.max_media_ports:=1000;
media.no_vad:=1;
CheckStatus(pjsua_init(@config,@logconfig,@media),'pjsua_init');
pjsua_transport_config_default(transport);
transport.port:=5000;
CheckStatus(pjsua_transport_create(1,transport,TransportID),'pjsua_transport_create');
CheckStatus(pjsua_acc_add_local(TransportID,1,AccountID),'pjsua_acc_add_local');
for I := 0 to Length(Accounts)-1 do
Accounts[I]:=AccountID;
if FAccountStart>0 then
for I := 0 to Length(Accounts) - 1 do
begin
AccountInfo[I].id:='sip:'+IntToStr(FAccountStart+I)+'@'+FHost;
AccountInfo[I].uri:='sip:'+FHost;
AccountInfo[I].host:=FHost;
AccountInfo[I].scheme:='digest';
AccountInfo[I].account:=IntToStr(FAccountStart+I);
pjsua_acc_config_default(AccCfg);
AccCfg.id.s:=@AccountInfo[I].id[1];
AccCfg.id.sz:=Length(AccountInfo[I].id);
AccCfg.reg_uri.s:=@AccountInfo[I].uri[1];
AccCfg.reg_uri.sz:=Length(AccountInfo[I].uri);
AccCfg.cred_count:=1;
AccCfg.cred_info[1].realm.s:=@AccountInfo[I].host[1];
AccCfg.cred_info[1].realm.sz:=Length(AccountInfo[I].host);
AccCfg.cred_info[1].scheme.s:=@AccountInfo[I].scheme[1];
AccCfg.cred_info[1].scheme.sz:=Length(AccountInfo[I].scheme);
AccCfg.cred_info[1].username.s:=@AccountInfo[I].account[1];
AccCfg.cred_info[1].username.sz:=Length(AccountInfo[I].account);
AccCfg.cred_info[1].data_type:=0;
AccCfg.cred_info[1].data.s:=@AccountInfo[I].account[1];
AccCfg.cred_info[1].data.sz:=Length(AccountInfo[I].account);
CheckStatus(pjsua_acc_add(AccCfg,0,Accounts[I]),'pjsua_acc_add');
end;
pjsua_transport_config_default(mediatransport);
mediatransport.port:=6000;
CheckStatus(pjsua_media_transports_create(mediatransport),'pjsua_media_transports_create');
pjpcmu.s:=@fcodec[1];
pjpcmu.sz:=length(fcodec);
CheckStatus(pjsua_codec_set_priority(pjpcmu,255),'pjsua_codec_set_priority');
CheckStatus(pjsua_set_ec(0,0),'pjsua_set_ec');
CheckStatus(pjsua_set_null_snd_dev,'pjsua_set_null_snd_dev');
//Test;
CheckStatus(pjsua_start,'pjsua_start');
end;
procedure TSIPThread.MakeCall(Call: TSIPCall);
var Phone:pjstring;
begin
Call.LogInfo(Format('Calling %s',[Call.Phone]));
Phone.s:=@Call.Phone[1];
Phone.sz:=Length(Call.Phone);
CheckStatus(pjsua_call_make_call(Accounts[Call.ChannelIndex-1],Phone,0,Call,nil,Call.CallID),'pjsua_call_make_call',Call);
Sleep(CallDelay);
end;
type
TSoundData=class(TObject)
Sound:TSIPAnnouncement;
PortID:Integer;
Call:TSIPCall;
end;
function endsound(port:pointer;userdata:TSoundData):integer;cdecl;
begin
result:=-1;
try
try
if userdata<>nil then
begin
TSIPThread.CheckStatus(pjsua_conf_remove_port(userdata.PortID),'pjsua_conf_remove_port',userdata.Call);
TSIPThread.CheckStatus(pjmedia_port_destroy(port),'pjmedia_port_destroy',userdata.Call);
end else
TSIPThread.CheckStatus(pjmedia_port_destroy(port),'pjmedia_port_destroy');
if userdata<>nil then userdata.Call.Signal;
except
on E:Exception do
begin
try
if not (E is ESIPException) then if Log<>nil then Log.Error(E.Message,E);
finally
if (userdata<>nil) and (userdata.Call<>nil) then userdata.Call.SignalFailure;
end;
end;
end;
finally
userdata.free;
end;
end;
procedure TSIPThread.PlaySound(Call: TSIPCall; Sound: TSIPAnnouncement);
var port:pointer;
portid:integer;
Data:TSoundData;
CallPort:Integer;
begin
if Call.CallID<0 then
begin
Call.LogError(Format('PlaySound:call to %s is terminated',[Call.Phone]));
Call.Signal;
Exit;
end;
if Sound=nil then
begin
Call.LogError(Format('[%10.10d] Skipping unknown message to %s',[Call.CallID,Call.Phone]));
Call.Signal;
Exit;
end;
if Sound.Size<=0 then
begin
Call.LogInfo(Format('[%10.10d] Skipping empty message %s to %s',[Call.CallID,Sound.Name,Call.Phone]));
Call.Signal;
Exit;
end;
CallPort:=pjsua_call_get_conf_port(Call.CallID);
if CallPort>0 then
begin
Call.LogInfo(Format('[%10.10d] Playing %s to %s',[Call.CallID,Sound.Name,Call.Phone]));
TSIPThread.CheckStatus(pjmedia_mem_player_create(SIPpool,Sound.Buffer,Sound.Size,8000,1,80,16,0,port),'pjmedia_mem_player_create',Call);
TSIPThread.CheckStatus(pjsua_conf_add_port(SIPpool,port,portid),'pjsua_conf_add_port',Call);
Data:=TSoundData.Create;
Data.Sound:=Sound;
Data.PortID:=PortID;
Data.Call:=Call;
TSIPThread.CheckStatus(pjmedia_mem_player_set_eof_cb(port,data,@endsound),'pjmedia_mem_player_set_eof_cb',Call);
TSIPThread.CheckStatus(pjsua_conf_connect(portid,CallPort),'pjsua_conf_connect',Call);
end else
begin
Call.LogInfo(Format('[%10.10d] Missing port for call %d',[Call.CallID,Call.CallID]));
Call.Signal;
Exit;
end;
end;
class procedure TSIPThread.PlayWave(Call: TSIPCall; FileName: String);
var
pjwav:pjstring;
PlayerID,PortID:Integer;
begin
Call.LogInfo(Format('[%10.10d] Playing %s to %s',[Call.CallID,FileName,Call.Phone]));
pjwav.s:=@FileName[1];
pjwav.sz:=length(FileName);
TSIPThread.CheckStatus(pjsua_player_create(pjwav,0,PlayerID),'pjsua_player_create',Call);
PortID:=pjsua_player_get_conf_port(PlayerID);
TSIPThread.CheckStatus(pjsua_conf_connect(PortID,pjsua_call_get_conf_port(Call.CallID)),'pjsua_conf_connect',Call);
end;
procedure TSIPThread.Terminate;
begin
CallLock.SetEvent;
inherited;
end;
procedure TSIPThread.WaitDTMF(Call:TSIPCall);
var CallPort:Integer;
begin
if Call.CallID<0 then
begin
Call.LogError(Format('WaitDTMF:call to %s is terminated',[Call.Phone]));
Call.Signal;
Exit;
end;
if Call.DTMF_Port.port_data_l<0 then
AddPort(@Call.DTMF_Port,Call);
CallPort:=pjsua_call_get_conf_port(Call.CallID);
if CallPort>0 then
begin
Call.LogInfo(Format('[%10.10d] Waiting DTMF from %s',[Call.CallID,Call.Phone]));
TSIPThread.CheckStatus(pjsua_conf_connect(CallPort,Call.DTMF_Port.port_data_l),'pjsua_conf_connect',Call)
end
else
begin
Call.LogInfo(Format('[%10.10d] Missing port for call %d',[Call.CallID,Call.CallID]));
Call.DTMFTimeout;
end;
end;
end.
|
unit ncDebCredValidator;
interface
uses Variants;
type
TncDebCredValidator = class
private
FOldCli: Integer;
FOldCliDebitoAtual: Currency;
FOldCliCreditoAtual: Currency;
FOldCliCredUsado: Currency;
FOldCliCreditado: Currency;
FNewCli: Integer;
FNewCliDebitoAtual: Currency;
FNewCliMaxDeb: Variant;
FNewCliCreditoAtual: Currency;
FOldDebito: Currency;
FNewDebito: Currency;
FOldCredito: Currency;
FNewCredito: Currency;
public
constructor Create;
procedure Assign(aFrom: TncDebCredValidator);
function Selecionar: Boolean;
function DebitoOk: Boolean;
function CreditoOk: Boolean;
function CalcCredDisp: Currency;
function TudoOk: Boolean;
function MaxDeb: Currency;
procedure SetOldCli(aOldCli: Integer; aDebAtual, aCredAtual, aCredUsado, aCreditado: Currency);
procedure SetNewCli(aNewCli: Integer; aDebAtual, aCredAtual: Currency; aMaxDeb: Variant);
property NewCli: Integer read FNewCli;
property OldCliCreditado: Currency read FOldCliCreditado;
property OldDebito: Currency read FOldDebito write FOldDebito;
property NewDebito: Currency read FNewDebito write FNewDebito;
property OldCredito: Currency read FOldCredito write FOldCredito;
property NewCredito: Currency read FNewCredito write FNewCredito;
end;
implementation
uses ncClassesBase;
{ TncDebCredValidator }
procedure TncDebCredValidator.Assign(aFrom: TncDebCredValidator);
begin
FOldCli := aFrom.FOldCli;
FOldCliDebitoAtual := aFrom.FOldCliDebitoAtual;
FOldCliCreditoAtual := aFrom.FOldCliCreditoAtual;
FOldCliCredUsado := aFrom.FOldCliCredUsado;
FOldCliCreditado := aFrom.FOldCliCreditado;
FNewCli := aFrom.FNewCli;
FNewCliDebitoAtual := aFrom.FNewCliDebitoAtual;
FNewCliMaxDeb := aFrom.FNewCliMaxDeb;
FNewCliCreditoAtual := aFrom.FNewCliCreditoAtual;
FOldDebito := aFrom.OldDebito;
FNewDebito := aFrom.NewDebito;
FOldCredito := aFrom.OldCredito;
FNewCredito := aFrom.NewCredito;
end;
function TncDebCredValidator.CalcCredDisp: Currency;
begin
if FNewCli=FOldCli then begin
Result := (FNewCliCreditoAtual-FOldCliCreditado) + FOldCliCredUsado;
if Result < FOldCliCredUsado then Result := FOldCliCredUsado;
end else begin
Result := FNewCliCreditoAtual;
if Result<0 then Result := 0;
end;
end;
constructor TncDebCredValidator.Create;
begin
FOldCli := 0;
FOldCliDebitoAtual := 0;
FOldCliCreditoAtual := 0;
FOldCliCredUsado := 0;
FOldCliCreditado := 0;
FNewCli := 0;
FNewCliDebitoAtual := 0;
FNewCliMaxDeb := null;
FNewCliCreditoAtual := 0;
FOldDebito := 0;
FNewDebito := 0;
FOldCredito := 0;
FNewCredito := 0;
end;
function TncDebCredValidator.CreditoOk: Boolean;
var Creditar: Currency;
begin
if FNewCli=FOldCli then
Creditar := FNewCredito - FOldCredito else
Creditar := FNewCredito;
if (Creditar>=0) or ((FNewCliCreditoAtual + Creditar) > 0) then
Result := True else
Result := False;
end;
function TncDebCredValidator.DebitoOk: Boolean;
var Debitar: Currency;
begin
if FNewCli=FOldCli then
Debitar := FNewDebito - FOldDebito else
Debitar := FNewDebito;
if (Debitar<0.001) or ((MaxDeb-FNewCliDebitoAtual)>=Debitar) then
Result := True else
Result := False;
end;
function TncDebCredValidator.MaxDeb: Currency;
begin
if VarIsNull(FNewCliMaxDeb) then
Result := gConfig.LimitePadraoDebito else
Result := FNewCliMaxDeb;
end;
function TncDebCredValidator.Selecionar: Boolean;
begin
Result := (FNewCli=0) and ((FNewCredito>0.001) or (FNewDebito>0.001));
end;
procedure TncDebCredValidator.SetNewCli(aNewCli: Integer; aDebAtual, aCredAtual: Currency;
aMaxDeb: Variant);
begin
FNewCli := aNewCli;
FNewCliDebitoAtual := aDebAtual;
FNewCliCreditoAtual := aCredAtual;
FNewCliMaxDeb := aMaxDeb;
end;
procedure TncDebCredValidator.SetOldCli(aOldCli: Integer; aDebAtual,
aCredAtual, aCredUsado, aCreditado: Currency);
begin
FOldCli := aOldCli;
FOldCliDebitoAtual := aDebAtual;
FOldCliCreditoAtual := aCredAtual;
FOldCliCredUsado := aCredUsado;
FOldCliCreditado := aCreditado;
end;
function TncDebCredValidator.TudoOk: Boolean;
begin
Result := (not Selecionar) and DebitoOk and CreditoOk;
end;
end.
|
unit FrmVectorMapInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Spin, U_VECTOR_CONTROL, U_VECTOR_LIEN_INFO,
Math, System.Types;
type
TfVectorMapInfo = class(TForm)
pnl2: TPanel;
pnl3: TPanel;
spltr1: TSplitter;
grp1: TGroupBox;
lblColor: TLabel;
lblAngle: TLabel;
lbl1: TLabel;
lblType: TLabel;
cbbName: TComboBox;
btnAdd: TButton;
edtValue: TEdit;
btnDel: TButton;
mmoShow: TMemo;
btnModify: TButton;
pnlClr: TPanel;
cbbAngle: TComboBox;
lbl2: TLabel;
cbbType: TComboBox;
imgMap: TImage;
dlgColor: TColorDialog;
btnSave: TButton;
procedure FormCreate(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure pnlClrClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure imgMapMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure cbbNameChange(Sender: TObject);
procedure imgMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure edtValueChange(Sender: TObject);
procedure btnDelClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
FMapControl: TVECTOR_CONTROL;
FVLSelectMain : TVECTOR_LIEN_INFO;
FIsAutoSave : Boolean;
procedure SaveInfo(AVLInfo : TVECTOR_LIEN_INFO);
procedure ShowInfo(AVLInfo : TVECTOR_LIEN_INFO);
procedure RefurshMap;
public
{ Public declarations }
/// <summary>
/// 添加向量图
/// </summary>
procedure NewVMap(AMapControl : TVECTOR_CONTROL );
/// <summary>
/// 修改向量图
/// </summary>
procedure EditVMap(AMapControl : TVECTOR_CONTROL);
end;
var
fVectorMapInfo: TfVectorMapInfo;
implementation
{$R *.dfm}
{ TfVectorMapInfo }
procedure TfVectorMapInfo.btnAddClick(Sender: TObject);
var
AVLInfo : TVECTOR_LIEN_INFO;
begin
if Assigned(FMapControl) then
begin
AVLInfo := FMapControl.AddVector;
SaveInfo(AVLInfo);
FMapControl.SetNoSelect;
FVLSelectMain := nil;
RefurshMap;
end;
end;
procedure TfVectorMapInfo.btnDelClick(Sender: TObject);
begin
if Assigned(FMapControl) then
begin
FMapControl.DelSelect;
RefurshMap;
end;
end;
procedure TfVectorMapInfo.btnSaveClick(Sender: TObject);
begin
if FIsAutoSave then
begin
if Assigned(FVLSelectMain) then
SaveInfo(FVLSelectMain);
RefurshMap;
end;
end;
procedure TfVectorMapInfo.cbbNameChange(Sender: TObject);
function GetIn(s: string; asarray :array of string) : Boolean;
var
i: Integer;
begin
Result := False;
for i := 0 to Length(asarray) - 1 do
begin
if asarray[i] = s then
begin
Result := True;
Break;
end;
end;
end;
begin
if GetIn(cbbName.Text,['Ua', 'Ia', 'Uab', 'Uac', 'Uba']) then
pnlClr.Color := C_COLOR_A
else if GetIn(cbbName.Text, ['Ub', 'Ib', 'Uab', 'Uac', 'Uba']) then
pnlClr.Color := C_COLOR_B
else
pnlClr.Color := C_COLOR_C;
if GetIn(cbbName.Text, ['Ia', 'Ib', 'Ic']) then
cbbType.Text := GetVTStr(vtCurrent)
else
cbbType.Text := GetVTStr(vtVol);
if cbbName.Text = 'Ua' then
cbbAngle.Text := '90'
else if cbbName.Text = 'Ub' then
cbbAngle.Text := '210'
else if cbbName.Text = 'Uc' then
cbbAngle.Text := '330'
else if cbbName.Text = 'Ia' then
cbbAngle.Text := '70'
else if cbbName.Text = 'Ib' then
cbbAngle.Text := '190'
else if cbbName.Text = 'Ic' then
cbbAngle.Text := '310'
else if cbbName.Text = 'Uab' then
cbbAngle.Text := '120'
else if cbbName.Text = 'Ucb' then
cbbAngle.Text := '180'
else if cbbName.Text = 'Uac' then
cbbAngle.Text := '60'
else if cbbName.Text = 'Ubc' then
cbbAngle.Text := '0'
else if cbbName.Text = 'Uba' then
cbbAngle.Text := '300'
else if cbbName.Text = 'Uca' then
cbbAngle.Text := '240';
if GetIn(cbbName.Text, ['Ia', 'Ib', 'Ic']) then
edtValue.Text := '5'
else if GetIn(cbbName.Text, ['Ua', 'Ub', 'Uc']) then
edtValue.Text := '220'
else
edtValue.Text := '380';
end;
procedure TfVectorMapInfo.EditVMap(AMapControl: TVECTOR_CONTROL);
begin
FMapControl := AMapControl;
if not Assigned(FMapControl) then
Exit;
FMapControl.Canvas := imgMap.Canvas;
FMapControl.Rect := Rect(0,0,imgMap.Width-1, imgMap.Height-1);
RefurshMap;
end;
procedure TfVectorMapInfo.edtValueChange(Sender: TObject);
begin
btnSaveClick(nil);
end;
procedure TfVectorMapInfo.FormCreate(Sender: TObject);
begin
cbbType.Items.Text := GetVTAllStr;
cbbType.ItemIndex := 0;
FIsAutoSave := True;
cbbNameChange(nil);
end;
procedure TfVectorMapInfo.FormResize(Sender: TObject);
begin
if Assigned(FMapControl) then
begin
FMapControl.Rect := Rect(0,0,imgMap.Width-1, imgMap.Height-1);
RefurshMap;
end;
end;
procedure TfVectorMapInfo.imgMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
AVLInfo : TVECTOR_LIEN_INFO;
bSelect : Boolean;
begin
if not Assigned(FMapControl) then
Exit;
AVLInfo := FMapControl.PointInVLine(Point(x, y));
FMapControl.SetNoSelect;
FVLSelectMain := nil;
bSelect := Assigned(AVLInfo);
btnDel.Enabled := bSelect;
if bSelect then
begin
AVLInfo.IsSelected := True;
AVLInfo.IsMainSelect := True;
FVLSelectMain := AVLInfo;
ShowInfo(AVLInfo);
end;
RefurshMap;
end;
procedure TfVectorMapInfo.imgMapMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
dX, dY : Double;
APoint : TPoint;
dValue : Double;
begin
if not Assigned(FMapControl) then
Exit;
FMapControl.MouseMove(Point(x, y));
if Shift = [ssLeft] then
begin
if Assigned(FVLSelectMain) then
begin
APoint := FVLSelectMain.CenterPoint;
dX := X - APoint.X;
dY := APoint.Y - Y;
if dX = 0 then
dValue := 0
else
dValue := dY/dX;
if x > APoint.X then
begin
FVLSelectMain.VAngle := RadToDeg(ArcTan(dValue));
end
else
begin
if x = APoint.X then
begin
if y > APoint.y then
FVLSelectMain.VAngle := 270
else
FVLSelectMain.VAngle := 90;
end
else
begin
FVLSelectMain.VAngle := RadToDeg(ArcTan(dValue)) - 180;
end;
end;
ShowInfo(FVLSelectMain);
end;
end;
RefurshMap;
end;
procedure TfVectorMapInfo.NewVMap(AMapControl: TVECTOR_CONTROL);
begin
FMapControl := AMapControl;
if not Assigned(FMapControl) then
Exit;
FMapControl.ClearList;
FMapControl.Canvas := imgMap.Canvas;
FMapControl.Rect := Rect(0,0,imgMap.Width-1, imgMap.Height-1);
RefurshMap;
end;
procedure TfVectorMapInfo.pnlClrClick(Sender: TObject);
begin
dlgColor.Color := pnlClr.Color;
if dlgColor.Execute then
begin
pnlClr.Color := dlgColor.Color;
btnSaveClick(nil);
end;
end;
procedure TfVectorMapInfo.RefurshMap;
begin
if Assigned(FMapControl) then
begin
FMapControl.Draw;
imgMap.Refresh;
mmoShow.Lines.Text := FMapControl.VectorStr;
end;
end;
procedure TfVectorMapInfo.SaveInfo(AVLInfo : TVECTOR_LIEN_INFO);
function GetValue(s : string):Double;
begin
TryStrToFloat(s, Result);
end;
begin
AVLInfo.VName := cbbName.Text;
AVLInfo.VColor := pnlClr.Color;
AVLInfo.VTypeStr := cbbType.Text;
AVLInfo.VValue := GetValue(edtValue.Text);
AVLInfo.VAngle := GetValue(cbbAngle.Text);
cbbAngle.Text := FormatFloat('0.00', AVLInfo.VAngle);
end;
procedure TfVectorMapInfo.ShowInfo(AVLInfo : TVECTOR_LIEN_INFO);
begin
FIsAutoSave := False;
cbbName.Text := AVLInfo.VName;
pnlClr.Color := AVLInfo.VColor;
cbbType.Text := AVLInfo.VTypeStr;
edtValue.Text := FormatFloat('0.00', AVLInfo.VValue);
cbbAngle.Text := FormatFloat('0.00', AVLInfo.VAngle);
FIsAutoSave := True;
end;
end.
|
unit uEncrypt;
interface
uses
SysUtils;
type TEncryption = class
private
password : string;
public
constructor Create();
function getPassword() : string;
procedure setPassword(pas : string);
end;
implementation
{ TEncryption }
{When constructed, the class sets the global password variable to blank.}
constructor TEncryption.Create;
begin
password := '';
end;
{The getPassword function checks if the password storage file exists, reads
the text from it and assignes it to a string. It then performs a -2 shift
cipher operation to unencrypt the password and returns the unencrypted string.}
function TEncryption.getPassword: string;
var
inFile : textFile;
line : string;
pass : string;
i : integer;
begin
if FileExists('admin.txt') = True then
begin
Assign(inFile, 'admin.txt');
Reset(inFile);
ReadLn(inFile, line);
pass := line;
CloseFile(inFile);
end;
password := '';
for i := 1 to length(pass) do
begin
password := password + char(ord(pass[i])-2);
end;
Result := password;
end;
{The setPassword procedure performs a +2 shift cipher operation on the entered
string. A text file is then accessed or created in the project folder to which
the encrypted password is written.}
procedure TEncryption.setPassword(pas: string);
var
inFile : textFile;
line : string;
pass : string;
i : integer;
begin
password := pas;
pass := '';
for i := 1 to Length(password) do
begin
pass := pass + char(ord(password[i]) + 2);
end;
if FileExists('admin.txt') = True then
begin
Assign(inFile, 'admin.txt');
Rewrite(inFile);
WriteLn(inFile,pass);
CloseFile(inFile);
end;
end;
end.
|
{
Heap Sort Algorithm
O(NLgN)
Input:
A: array of integer
N: number of integers
Output:
Ascending Sorted list
Notes:
Heap is MaxTop
Reference:
FCS
By Behdad
}
program
HeapSort;
const
MaxN = 32000;
var
N : Integer;
A : array [1 .. MaxN] of Integer;
HSize : Integer;
function BubbleUp (V : Integer) : Integer;
var
Te : Integer;
begin
while (V > 1) and (A[V] > A[V div 2]) do
begin
Te := A[V]; A[V] := A[V div 2]; A[V div 2] := Te;
V := V div 2;
end;
BubbleUp := V;
end;
function BubbleDown (V : Integer) : Integer;
var
Te : Integer;
C : Integer;
begin
while 2 * V <= HSize do
begin
C := 2 * V;
if (C < HSize) and (A[C] < A[C + 1]) then
Inc(C);
if A[V] < A[C] then
begin
Te := A[V]; A[V] := A[C]; A[C] := Te;
V := C;
end
else
Break;
end;
BubbleDown := V;
end;
function Insert (K : Integer) : Integer;
begin
Inc(HSize);
A[HSize] := K;
Insert := BubbleUp(HSize);
end;
function Delete (V : Integer) : Integer;
begin
Delete := A[V];
A[V] := A[HSize];
Dec(HSize);
if BubbleUp(V) = V then
BubbleDown(V);
end;
function DeleteMax : Integer;
var
Te : Integer;
begin
DeleteMax := A[1];
Te := A[1]; A[1] := A[HSize]; A[HSize] := Te;
Dec(HSize);
BubbleDown(1);
end;
function ChangeKey (V, K : Integer) : Integer;
begin
A[V] := K;
ChangeKey := BubbleDown(BubbleUp(V));
end;
procedure Heapify (Count : Integer);
var
I : Integer;
begin
HSize := Count;
for I := N div 2 downto 1 do
BubbleDown(I);
end;
procedure Sort (Count : Integer);
begin
Heapify(Count);
while HSize > 0 do
DeleteMax;
end;
begin
Sort(N);
end.
|
unit StdHandlers;
interface
uses SysUtils, Entities, Rx;
var
PrintString: TOnNext<TZip<LongWord, string>>;
WriteLn: TOnNext<string>;
PressEnter: TOnCompleted;
RandomPersons: TOnSubscribe<TPerson>;
implementation
initialization
WriteLn := procedure(const Line: string)
begin
System.WriteLn(Line);
end;
PrintString := procedure(const Data: TZip<LongWord, string>)
begin
WriteLn('');
WriteLn('Timestamp: ' + TimeToStr(Now));
WriteLn(Format('iter: %d value: %s', [Data.A, Data.B]))
end;
PressEnter := procedure
begin
WriteLn('');
WriteLn('Press ENTER to Exit');
Readln;
end;
RandomPersons := procedure(O: IObserver<TPerson>)
begin
O.OnNext(
TPerson.Create('David', 'Snow', '')
);
O.OnNext(
TPerson.Create('Helen', 'Peterson', '')
);
O.OnNext(
TPerson.Create('Helga', 'Yensen', '')
);
O.OnNext(
TPerson.Create('Djohn', 'Petrucchi', '')
);
O.OnNext(
TPerson.Create('Tom', 'Soyer', '')
);
O.OnNext(
TPerson.Create('Lev', 'Tolstoy', '')
);
O.OnNext(
TPerson.Create('Pavel', 'Minenkov', '')
);
O.OnCompleted;
end;
end.
|
unit dmMainDM;
interface
uses
System.SysUtils, System.Classes, Data.DB, DBAccess, Uni, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Comp.Client, MemDS, clsTDBUtils;
type
TMainDM = class(TDataModule)
conn: TUniConnection;
usuarios: TUniQuery;
usuariosid_usuario: TLargeintField;
usuariosnome: TStringField;
usuariosnasc: TDateField;
usuariosemail: TStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
FDBUtils: TDBUtils;
FStringDeConexao: String;
procedure SetDBUtils(const Value: TDBUtils);
procedure SetStringDeConexao(const Value: String);
public
{ Public declarations }
property DBUtils: TDBUtils read FDBUtils write SetDBUtils;
property StringDeConexao: String read FStringDeConexao write SetStringDeConexao;
end;
var
MainDM: TMainDM;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TMainDM }
procedure TMainDM.DataModuleCreate(Sender: TObject);
begin
Self.DBUtils := TDBUtils.Create(TComponent(Self), Self.StringDeConexao);
end;
procedure TMainDM.SetDBUtils(const Value: TDBUtils);
begin
FDBUtils := Value;
end;
procedure TMainDM.SetStringDeConexao(const Value: String);
begin
FStringDeConexao := Value;
Self.DBUtils.Conexao.Connected := False;
Self.DBUtils.Conexao.ConnectString := Self.StringDeConexao;
try
Self.DBUtils.Conexao.Connect;
except
raise Exception.Create('Error Message');
Self.StringDeConexao := '';
Self.DBUtils.Conexao.Connected := False;
end;
end;
end.
|
unit task_unit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, Contnrs, memoryBlock_unit, Dialogs;
type Task = class
TaskName: string;
TaskSize: integer;
TaskStartTime: string;
TaskTotalTime: integer;
TaskStatus: string;
TaskTimer: TTimer;
TaskUsedMemoryBlock: integer;
constructor Create(Name: string; Size: integer; TotalTime: integer);
destructor Free;
function isInQueue(): boolean;
function isComplete(): boolean;
procedure onTimerTick(Sender: TObject);
procedure TaskStart(fromTimer: integer; MemBlock: MemoryBlock);
procedure FreeMemoryBlock(MemBlock: MemoryBlock);
end;
implementation
constructor Task.Create(Name: string; Size: integer; TotalTime: integer);
begin
TaskName := Name;
TaskSize := Size;
TaskStartTime := '-';
TaskTotalTime := TotalTime;
TaskStatus := 'В очереди';
TaskTimer := TTimer.Create(nil);
TaskTimer.Interval := 1000;
TaskTimer.OnTimer := @OnTimerTick;
TaskTimer.Enabled := False;
end;
destructor Task.Free;
var i: integer;
begin
TaskTimer.Free;
end;
procedure Task.onTimerTick(Sender: TObject);
begin
if TaskStatus = 'Завершена' then Exit;
dec(TaskTotalTime);
if (TaskTotalTime = 0) then
begin
TaskTimer.Enabled := False;
TaskStatus := 'Завершена';
end;
end;
procedure Task.TaskStart(fromTimer: integer; MemBlock: MemoryBlock);
var i, place: integer;
begin
place := MemBlock.findPlace(TaskSize);
if place <> -1 then begin
TaskUsedMemoryBlock := place;
i := 0;
while (i < TaskSize) do begin
MemBlock.MbBytes[place + i] := '1';
i := i + 1;
end;
TaskTimer.Enabled := True;
TaskStartTime := IntToStr(fromTimer);
TaskStatus := 'Выполняется';
end;
end;
function Task.isInQueue(): boolean;
begin
if TaskStatus = 'В очереди' then
isInQueue := True
else
isInQueue := False;
end;
function Task.isComplete(): boolean;
begin
if TaskStatus='Завершена' then
isComplete := True
else
isComplete := False;
end;
procedure Task.FreeMemoryBlock(MemBlock: MemoryBlock);
var i:integer;
begin
if TaskUsedMemoryBlock = -1 then Exit;
i := 0;
while (i < TaskSize) do begin
MemBlock.MbBytes[TaskUsedMemoryBlock + i] := '0';
i := i + 1;
end;
TaskUsedMemoryBlock := -1;
end;
end.
|
UNIT ZeichenkettenUnit;
INTERFACE
type CharNodePtr = ^CharNode;
CharNode = record
ch: char;
next: CharNodePtr;
end;
CharListPtr = CharNodePtr;
FUNCTION NewCharList: CharListPtr;
(* returns empty CharList *)
PROCEDURE DisposeCharList(var cl: CharListPtr);
(* disposes all nodes and sets cl to empty CharList *)
FUNCTION CLLength(cl: CharListPtr): integer;
(* returns the number of characters in cl *)
FUNCTION CLConcat(cl1, cl2: CharListPtr): CharListPtr;
(* returns concatenation of cl1 and cl2 by copying the nodes of both lists *)
FUNCTION CharListOf(s: string): CharListPtr;
(* returns CharList representation of STRING *)
FUNCTION StringOf(cl: CharListPtr): string;
(* returns STRING representation of CharList, may result in truncatation *)
IMPLEMENTATION
FUNCTION NewCharList: CharListPtr;
var node: CharListPtr;
BEGIN
New(node);
node := NIL;
NewCharList := node;
END;
FUNCTION NewNode(x: Char): CharNodePtr;
var node: CharNodePtr;
BEGIN
New(node);
node^.ch := x;
node^.next := NIL;
NewNode := node;
END;
PROCEDURE DisposeCharList(var cl: CharListPtr);
var next: CharListPtr;
BEGIN
while cl <> NIL do begin
next := cl^.next;
Dispose(cl);
cl := next;
end; (* WHILE *)
END;
FUNCTION CLLength(cl: CharListPtr): integer;
var count: longint;
BEGIN
count := 0;
while cl <> NIL do begin
Inc(count);
cl := cl^.next;
end; (* WHILE *)
CLLength := count;
END;
FUNCTION CopyNode(n: CharNodePtr): CharNodePtr;
var node: CharNodePtr;
BEGIN
node := NewNode(n^.ch);
node^.next := n^.next;
CopyNode := node;
END;
FUNCTION CopyCharList(cl: CharListPtr): CharListPtr;
var newCl: CharListPtr;
currentNode, prevNode: CharNodePtr;
BEGIN
newCl := NewCharList;
currentNode := CopyNode(cl);
newCl := currentNode;
while currentNode^.next <> NIL do begin
prevNode := currentNode;
currentNode := CopyNode(currentNode^.next);
prevNode^.next := currentNode;
end; (* WHILE *)
CopyCharList := newCl;
END;
FUNCTION CLConcat(cl1, cl2: CharListPtr): CharListPtr;
var cl1New, cl2New, cl3: CharListPtr;
next: CharNodePtr;
BEGIN
cl1New := CopyCharList(cl1);
cl2New := CopyCharList(cl2);
cl3 := cl1New;
next := cl3;
while next^.next <> NIL do
next := next^.next;
next^.next := cl2New;
CLConcat := cl3;
END;
FUNCTION CharListOf(s: string): CharListPtr;
var list: CharListPtr;
node, currNode: CharNodePtr;
i: integer;
BEGIN
list := NewCharList;
for i := 1 to Length(s) do begin
node := NewNode(s[i]);
if i = 1 then begin
list := node;
currNode := node;
end else begin
currNode^.next := node;
currNode := node;
end; (* IF *)
end; (* FOR *)
CharListOf := list;
END;
FUNCTION StringOf(cl: CharListPtr): string;
var s: string;
node: CharNodePtr;
BEGIN
s := '';
node := cl;
while node <> NIL do begin
s := s + node^.ch;
node := node^.next;
end; (* WHILE *)
StringOf := s;
END;
BEGIN
END. |
{
ID: a2peter1
PROG: fracdec
LANG: PASCAL
}
{$B-,I-,Q-,R-,S-}
const
problem = 'fracdec';
MaxA = 100000;
var
A,B,r : longint;
st,t : string;
len : byte absolute st;
pos : array[0..MaxA] of longint;
begin
assign(input,problem + '.in'); reset(input);
assign(output,problem + '.out'); rewrite(output);
readln(A,B);
str(A div B,st); st := st + '.';
r := A mod B; A := r * 10;
repeat
pos[r] := len + 1;
str(A div B,t); st := st + t;
r := A mod B; A := r * 10;
until (r = 0) or (pos[r] <> 0);
if r <> 0 then
begin
insert('(',st,pos[r]);
st := st + ')';
end;{then}
writeln(st);
close(output);
end.{main}
|
unit hashUnit;
{-------------------------------------------------------------------------------
線形リストを用いた汎用ハッシュ
作 者:クジラ飛行机(web@kujirahand.com)
作成日:2002/02/16
--------------------------------------------------------------------------------
使い方:
var
hash: TPtrHash;
str: string;
begin
str := 'test success!';
hash := TPtrHash.Create ; // 生成
hash['abc'] := PChar(str); // 追加
ShowMessage(PChar(hash['abc'])); // 参照
hash.Free; // 破棄
end;
-------------------------------------------------------------------------------}
interface
uses
SysUtils, Classes;
const
HASH_TABLE_SIZE = 256;
type
//----------------------------------------------------------------------------
//THash, THashNode を、継承させてクラスを作る
THashNode = class(TObject) //実際使う場合は、これを継承して、データ型を作る
public
Key: string;
LinkNext: THashNode;
constructor Create(Key: string);
end;
THashNodeTable = array of THashNode;
THash = class
private
FCount: Integer;
NodeTable: THashNodeTable;
function MakeHashKeyNo(key: string): Integer;//keyを整数化する
function subLet(node: THashNode; RewriteMode: Boolean): Boolean;//Add, Let の下請け
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Add(node: THashNode): Boolean; // HASHへ追加:二重追加は出来ない
procedure Let(node: THashNode); // HASHへ代入:NODEを上書き
function Delete(key: string): Boolean;
function Find(key: string): THashNode;
function EnumKey: TStringList;
property Count: Integer read FCount;
end;
//----------------------------------------------------------------------------
//Pointer 型の ハッシュ
TPtrHashNode = class(THashNode)
public
Ptr: Pointer;
constructor Create(key: string; ptr: Pointer);
end;
TPtrHash = class(THash)
private
function GetValue(key: string): Pointer;
procedure SetValue(key: string; ptr: Pointer);
public
property Items[key: string]:Pointer read GetValue write SetValue; default;
end;
implementation
{ THash }
function THash.Add(node: THashNode): Boolean;
begin
Result := subLet(node, False);
end;
procedure THash.Clear;
var
i: Integer;
node: THashNode;
procedure FreeLinkNode(n: THashNode);
begin
if n=nil then Exit;
FreeLinkNode(n.LinkNext);
n.Free;
end;
begin
for i:=0 to High(nodeTable) do
begin
node := nodeTable[i];
if node<>nil then FreeLinkNode(node);
nodeTable[i] := nil;
end;
end;
constructor THash.Create;
var
i:Integer;
begin
SetLength(nodeTable, HASH_TABLE_SIZE);
for i:=0 to High(nodeTable) do
begin
nodeTable[i] := nil;
end;
FCount := 0;
end;
function THash.Delete(key: string): Boolean;
var
no: Integer;
n, prev: THashNode;
begin
Result := False;
if key='' then Exit;
no := MakeHashKeyNo(key);
n := nodeTable[no];
if n = nil then Exit;
//top?
if n.Key = key then
begin
n.Free;
nodeTable[no] := nil;
Result := True;
Exit;
end;
//Find Loop
while n.LinkNext <> nil do
begin
prev := n; n := n.LinkNext ;
if n.Key = key then
begin // Find!
prev.LinkNext := n.LinkNext ;
n.Free;
Result := True;
Exit;
end;
end;
end;
destructor THash.Destroy;
begin
inherited;
Clear;
end;
function THash.EnumKey: TStringList;
var
i: Integer;
n: THashNode;
begin
Result := TStringList.Create;
for i:=0 to High(nodeTable) do
begin
n := nodeTable[i];
if n=nil then Continue;
while n<>nil do
begin
Result.Add( n.Key );
n := n.LinkNext ;
end;
end;
end;
function THash.Find(key: string): THashNode;
var
n: THashNode;
begin
Result := nil;
if key='' then Exit;
n := nodeTable[MakeHashKeyNo(key)];
if n = nil then Exit;
//Find Loop
while n<>nil do
begin
if n.Key = key then
begin
Result := n;
Break;
end;
n := n.LinkNext ;
end;
end;
procedure THash.Let(node: THashNode);
begin
subLet(node, True);
end;
function THash.MakeHashKeyNo(key: string): Integer;
var
i,len: Integer;
begin
len := Length(key) and $F;
Result := 0;
for i:=1 to len do
begin
Result := Result + Ord(key[i]) + i;
end;
Result := Result mod HASH_TABLE_SIZE;
end;
function THash.subLet(node: THashNode; RewriteMode: Boolean): Boolean;
var
n, nn: THashNode;
no: Integer;
begin
Result := False;
if node.Key = '' then Exit;
no := MakeHashKeyNo(node.key);
n := nodeTable[ no ];
if n=nil then //Tableへ初めて追加するとき
begin
nodeTable[no] := node;
node.LinkNext := nil;
end else
begin //以下のノードへ追加
if n.Key = node.Key then // TOP で、キーがダブり
begin
if RewriteMode = False then Exit; //上書き禁止なら失敗
n.Free;
nodeTable[no] := node;
Result := True;
Exit;
end;
//ノードの一番下まで
while (n.LinkNext <> nil) do
begin
nn := n; n := n.LinkNext; // nn -> n の関係
if n.Key = node.Key then
begin
if RewriteMode = False then Exit; //上書き禁止なら失敗
// nn -> n -> n.Next を、nn-> node -> n.Next に書き換え
nn.LinkNext := node;
node.LinkNext := n.LinkNext ;
Result := True;
Exit;
end;
end;
//一番下まで来たときは、追加
n.LinkNext := node;
node.LinkNext := nil;
end;
Result := True;
Inc(FCount);
end;
{ THashNode }
constructor THashNode.Create(Key: string);
begin
Self.Key := Key;
LinkNext := nil;
end;
{ TPtrHashNode }
constructor TPtrHashNode.Create(key: string; ptr: Pointer);
begin
inherited Create(key);
Self.Ptr := ptr;
end;
{ TPtrHash }
function TPtrHash.GetValue(key: string): Pointer;
var
node: THashNode;
begin
node := Find(key);
if node=nil then
begin
Result := nil; Exit;
end;
Result := TPtrHashNode( node ).Ptr ;
end;
procedure TPtrHash.SetValue(key: string; ptr: Pointer);
var
node: THashNode;
begin
node := TPtrHashNode.Create(key, ptr);
Let(node);
end;
end.
|
(*
Exemplo captura de erro onde toda exceção do sistema entra em CatchError,
podendo por exemplo, personalizar a mensagem de erro para tornar mais
amigável para o usuário ou gravar em um log.
*)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure CatchError(Sender: TObject; E: Exception);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CatchError(Sender: TObject; E: Exception);
var
Msg: string;
begin
Msg := 'Erro capturado:';
Msg := Msg + #10 + E.message;
Msg := Msg + #10 + 'Tela: ' + Screen.ActiveForm.name;
Msg := Msg + #10 + 'Controle: ' + Screen.ActiveControl.name;
ShowMessage(Msg);
end;
procedure TForm1.Button1Click(Sender: TObject);
var s:tStringList;
begin
s.Add('');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnException := CatchError;
end;
end.
|
unit cam_cprf;
{Variable-length key Camellia CMAC Pseudo-Random Function-128}
{$i STD.INC}
interface
uses
CAM_Base, CAM_OMAC;
(*************************************************************************
DESCRIPTION : Variable-length key Camellia CMAC Pseudo-Random Function-128
REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : [1] The Camellia-CMAC-96 and Camellia-CMAC-PRF-128 Algorithms
and Its Use with IPsec, available from
http://tools.ietf.org/html/draft-kato-ipsec-camellia-cmac96and128-02}
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 17.06.08 W.Ehrhardt Initial version analog aes_cprf
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
function CAM_CPRF128({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word;
msg: pointer; msglen: longint; var PRV: TCAMBlock): integer;
{-Calculate variable-length key Camellia CMAC Pseudo-Random Function-128 for msg}
{ returns CAM_OMAC error and 128-bit pseudo-random value PRV}
{$ifdef DLL} stdcall; {$endif}
function CAM_CPRF128_selftest: boolean;
{-Selftest with ipsec-camellia-cmac96and128 test vectors}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
function CAM_CPRF128({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word;
msg: pointer; msglen: longint; var PRV: TCAMBlock): integer;
{-Calculate variable-length key Camellia CMAC Pseudo-Random Function-128 for msg}
{ returns CAM_OMAC error and 128-bit pseudo-random value PRV}
var
LK : TCAMBlock; {local 128 bit key}
ctx: TCAMContext;
err: integer;
const
ZB: TCAMBlock = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
begin
if KeyBytes=16 then begin
{If the key, is exactly 128 bits, then we use it as-is (copy to local)}
move(Key, LK, 16);
err := 0;
end
else begin
{If key length is not 128 bits, then we derive the local key LK by
applying the CAM-CMAC algorithm using a 128-bit zero as the CMAC key
and Key as the input message: LK := CAM-CMAC(0, Key, KeyBytes)}
err := CAM_OMAC_Init(ZB, 128, ctx);
if err=0 then err := CAM_OMAC_Update(@Key, KeyBytes, ctx);
if err=0 then CAM_OMAC_Final(LK, ctx);
end;
{PRV := CAM-CMAC(LK, msg, msglen)}
if err=0 then err := CAM_OMAC_Init(LK, 128, ctx);
if err=0 then err := CAM_OMAC_Update(msg, msglen, ctx);
if err=0 then CAM_OMAC_Final(PRV, ctx);
CAM_CPRF128 := err;
end;
{---------------------------------------------------------------------------}
function CAM_CPRF128_selftest: boolean;
{-Selftest with ipsec-camellia-cmac96and128 test vectors}
const
{TV from http://tools.ietf.org/html/draft-kato-ipsec-camellia-cmac96and128-02}
Msg: array[0..39] of byte = ($6b,$c1,$be,$e2,$2e,$40,$9f,$96,
$e9,$3d,$7e,$11,$73,$93,$17,$2a,
$ae,$2d,$8a,$57,$1e,$03,$ac,$9c,
$9e,$b7,$6f,$ac,$45,$af,$8e,$51,
$30,$c8,$1c,$46,$a3,$5c,$e4,$11);
vk1: array[0..31] of byte = ($60,$3d,$eb,$10,$15,$ca,$71,$be,
$2b,$73,$ae,$f0,$85,$7d,$77,$81,
$1f,$35,$2c,$07,$3b,$61,$08,$d7,
$2d,$98,$10,$a3,$09,$14,$df,$f4);
vk2: array[0..23] of byte = ($8e,$73,$b0,$f7,$da,$0e,$64,$52,
$c8,$10,$f3,$2b,$80,$90,$79,$e5,
$62,$f8,$ea,$d2,$52,$2c,$6b,$7b);
vk3: array[0..15] of byte = ($2b,$7e,$15,$16,$28,$ae,$d2,$a6,
$ab,$f7,$15,$88,$09,$cf,$4f,$3c);
t1: TCAMBlock = ($2d,$36,$84,$e9,$1c,$b1,$b3,$03,$a7,$db,$86,$48,$f2,$5e,$e1,$6c);
t2: TCAMBlock = ($42,$b9,$d4,$7f,$4f,$58,$bc,$29,$85,$b6,$f8,$2c,$23,$b1,$21,$cb);
t3: TCAMBlock = ($5c,$18,$d1,$19,$cc,$d6,$76,$61,$44,$ac,$18,$66,$13,$1d,$9f,$22);
function Test1({$ifdef CONST} const {$else} var {$endif}Key; nk: word; tag: TCAMBlock): boolean;
var
PRV: TCAMBlock;
j: integer;
begin
Test1 := false;
if CAM_CPRF128(Key, nk, @msg, sizeof(msg), PRV)<>0 then exit;
for j:=0 to 15 do if PRV[j]<>tag[j] then exit;
Test1 := true;
end;
begin
CAM_CPRF128_selftest := Test1(vk1,32,t1) and Test1(vk2,24,t2) and Test1(vk3,16,t3);
end;
end.
|
unit MediaProcessing.Convertor.RGB.H264;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,AVC,
MediaProcessing.Common.Processor.CustomSettings,MediaProcessing.Convertor.RGB.H264.SettingsDialog;
type
TMediaProcessor_Convertor_Rgb_H264=class (TMediaProcessor_CustomSettings<TfmMediaProcessingSettingsRgb_H264>,IMediaProcessor_Convertor_Rgb_H264)
protected
FKeyFrameInterval: integer; // интервал между ключевыми кадрами (NAL_SEI вроде, но надо уточнить)
FPreset: TEncoderPreset;
FCRF: integer;
FMaxBitrateKbit: integer; //Кбит
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
procedure OnLoadPropertiesToDialog(aDialog: TfmMediaProcessingSettingsRgb_H264); override;
procedure OnSavePropertiesFromDialog(aDialog: TfmMediaProcessingSettingsRgb_H264);override;
public
constructor Create; override;
destructor Destroy; override;
property H264Preset: TEncoderPreset read FPreset write FPreset;
end;
implementation
uses Controls,uBaseClasses;
{ TMediaProcessor_Convertor_Rgb_H264 }
constructor TMediaProcessor_Convertor_Rgb_H264.Create;
begin
inherited;
FKeyFrameInterval:=25;
FPreset:=epmedium;
FCRF:=23;
FMaxBitrateKbit:=500;
end;
destructor TMediaProcessor_Convertor_Rgb_H264.Destroy;
begin
inherited;
end;
class function TMediaProcessor_Convertor_Rgb_H264.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_Rgb_H264;
result.Name:='Конвертор BMP->H.264';
result.Description:='Преобразует видеокадры формата BMP в формат H.264';
result.SetInputStreamType(stRGB);
result.OutputStreamType:=stH264;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_Convertor_Rgb_H264.OnLoadPropertiesToDialog(
aDialog: TfmMediaProcessingSettingsRgb_H264);
begin
inherited;
aDialog.edKeyFrameInterval.Value := FKeyFrameInterval;
aDialog.Preset:=FPreset;
aDialog.edCRF.Value:=FCRF;
aDialog.edMaxRate.Value:=FMaxBitrateKbit;
end;
procedure TMediaProcessor_Convertor_Rgb_H264.OnSavePropertiesFromDialog(
aDialog: TfmMediaProcessingSettingsRgb_H264);
begin
inherited;
FKeyFrameInterval := aDialog.edKeyFrameInterval.Value;
FPreset:=aDialog.Preset;
FCRF:=aDialog.edCRF.Value;
FMaxBitrateKbit:=aDialog.edMaxRate.Value;
end;
procedure TMediaProcessor_Convertor_Rgb_H264.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FKeyFrameInterval:=aReader.ReadInteger('KeyFrameInterval',FKeyFrameInterval);
FPreset:=TEncoderPreset(aReader.ReadInteger('Preset',integer(FPreset)));
FCRF:=aReader.ReadInteger('CRF',FCRF);
FMaxBitrateKbit:=aReader.ReadInteger('MaxBitrate',FMaxBitrateKbit);
end;
procedure TMediaProcessor_Convertor_Rgb_H264.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteInteger('KeyFrameInterval',FKeyFrameInterval);
aWriter.WriteInteger('Preset',integer(FPreset));
aWriter.WriteInteger('CRF',FCRF);
aWriter.WriteInteger('MaxBitrate',FMaxBitrateKbit);
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_Rgb_H264);
end.
|
{
Copyright (c) 2010, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit HTMLGlobal;
interface
uses
Windows, Messages, Classes, SysUtils, SHDocVw, MSHTML, Graphics, Forms,
Dialogs, ExtCtrls, Controls;
type
TElemDesc = record
edTagName: string; // Оригинальное имя тэга
edNiceTagName: string; // Имя тэга на родном языке
edElem: IHTMLElement;
end;
TElemDescArray = array of TElemDesc;
THTMLAttribType = (
atNone, // Неизвестный
atColor, //+ Цвет элемента
atPxSize, //+ Размер в пикселях
atCount, //+ Количество
atCount1, //+ Количество с 1-цы
atCountFromMinus1,// Количество, начиная от -1
atFontSize, // Размер шрифта. Изменяется от 1 до 7. Также может иметь "+" и "-"
atFontName, // Имя шрифта
atLink, // Ссылка
atLinkTarget, //+ атрибут TARGET
atText, // Произвольный текст
atCharSet, //+ Кодировка страницы
atHAlign, //+ Выравнивание по горизонтали
atVAlign, //+ Выравнивание по вертикали
atCSSVAlign, //+ Выравнивание по вертикали с расширенными возможностями CSS
atImgAlign, //+ Выравнивание картинки
atULType, //+ TYPE для простого списка
atOLType, //+ TYPE Для нумерованного списка
atBoolean, //+ Значения, подразумевающие 2 варианта: ДА/НЕТ (ДА = 65535)
atTextBoolean, //- Возможные значения: On/Off
atEncType, //- Параметр формы ENCTYPE
atMethod, //+ Параметр формы Method
atInputType, //+ Тип элемента "INPUT" (тип элемента изменять нельзя!)
atCSSSize, //+ Толщина элемента. Измеряется в пикселя и других единицах px
atCSSBorderStyle, //+ CSSСтиль рамки
atCSSFontStyle, //+ Стиль шрифта
//atCSSFontSize, // Размер шрифта Может быть как целым, так и дробным.
atCSSFontWeight, //+ Насыщенность
atCSSWritingMode, // Направление текста
atCSSPageBreak, // Разрыв страницы
atMrqDir, // Направление бегущей строки
atMrqBehav, // Поведение бегущей строки
atSize // Размер элемента. Может быть как целым, так и дробным. Может измеряться в px, %, cm и т.д.
);
// Информацию об атрибутах HTML-тэга
THTMLTagAttribs = class
private
public
// Список атрибутов
AttrList: TStringList;
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure AddAttrib(AttrName: string; AttrType: THTMLAttribType);
end;
THTMLEditorInfo = class
Disp: IDispatch;
Editor: IHTMLDocument2;
ElemDescArray: TElemDescArray;
ActiveElement: IHTMLElement;
ActiveElementColor: Variant;
CurrentIndex: Integer;
CurrentCell: IHTMLElement; // Текущая ячейка
FileName: string;
CanUseZoom: Boolean;
panCursor: TPanel;
EditorControl: TWinControl;
end;
var
TagTranslatesList: TStringList;
AttribTranslatesList: TStringList;
StyleTranslatesList: TStringList;
HTMLColorDialog: TColorDialog;
const
SSelectColor = 'Выбрать...';
SUserColor = 'Заданный';
SNoneColor = 'Не задан';
SNoFont = 'Не известно';
SNoFontSize = 'Не известно';
SNoColor = 'no color';
SErrorColor = 'error';
SSelectionColor = '#FFFF66';
SNonBreakableSpace = 'NonBreakableSpace';
procedure ListFillColorNames(Items: TStrings);
procedure ListFillFontNames(Items: TStrings);
function GetStyleType(StyleName: string): THTMLAttribType;
function HTMLColorBoxGetColor(ColBox: TColorBox;
ColDlg: TColorDialog; var IsCancel: Boolean): TColor;
function ConvertColorToHtml(AColor: TColor): string;
function GetDocRange(Inf: THTMLEditorInfo): IHTMLTxtRange;
implementation
function GetDocRange(Inf: THTMLEditorInfo): IHTMLTxtRange;
var
SelType: string;
begin
Result := nil;
SelType := Inf.editor.selection.type_; // None / Text / Control
if SelType <> 'Control' then
Result := (Inf.editor.selection.createRange as IHTMLTxtRange);
end;
function ConvertColorToHtml(AColor: TColor): string;
begin
Result := Format('#%s%s%s', [IntToHex(GetRValue(AColor), 2),
IntToHex(GetGValue(AColor), 2), IntToHex(GetBValue(AColor), 2)]);
end;
function HTMLColorBoxGetColor(ColBox: TColorBox;
ColDlg: TColorDialog; var IsCancel: Boolean): TColor;
var
Index, ChooseIndex: Integer;
AColor: TColor;
begin
IsCancel := False;
Result := 0;
if ColBox.ItemIndex >= 0 then
begin
if ColBox.Items[ColBox.ItemIndex] = SSelectColor then
begin
ChooseIndex := ColBox.ItemIndex;
// Устанавливаем последний цвет, заданный пользователем
ColDlg.Color := TColor(ColBox.Items.Objects[ChooseIndex]);
if ColDlg.Execute then
begin
AColor := ColDlg.Color;
ColBox.Items.Objects[ChooseIndex] := TObject(AColor);
// Пытаемся найти выбранный цвет в списке стандартных цветов
Index := ColBox.Items.IndexOfObject(TObject(AColor));
if (Index >= 0) and (Index <> ChooseIndex) then
ColBox.ItemIndex := Index // Такой цвет уже есть
else
begin
// Такого цвета еще нет. Добавляем его
Index := ColBox.Items.IndexOf(SUserColor);
if Index < 0 then
ColBox.Items.Insert(0, SUserColor);
Index := ColBox.Items.IndexOf(SUserColor);
if Index >= 0 then
begin
ColBox.Items.Objects[Index] := TObject(AColor);
ColBox.ItemIndex := Index;
end;
end;
end else
IsCancel := True;
end;
Result := TColor(ColBox.Items.Objects[ColBox.ItemIndex]);
end;
end;
procedure ListFillColorNames(Items: TStrings);
begin
Items.Clear;
Items.AddObject('Черный', TObject(clBlack));
Items.AddObject('Малиновый', TObject(clMaroon));
Items.AddObject('Зелёный', TObject(clGreen));
Items.AddObject('Оливковый', TObject(clOlive));
Items.AddObject('Темно-синий', TObject(clNavy));
Items.AddObject('Пурпурный', TObject(clPurple));
Items.AddObject('Бирюзовый', TObject(clTeal));
Items.AddObject('Серый', TObject(clGray));
Items.AddObject('Серебряный', TObject(clSilver));
Items.AddObject('Красный', TObject(clRed));
Items.AddObject('Лайм', TObject(clLime));
Items.AddObject('Желтый', TObject(clYellow));
Items.AddObject('Синий', TObject(clBlue));
Items.AddObject('Розовый', TObject(clFuchsia));
Items.AddObject('Морская волна', TObject(clAqua));
Items.AddObject('Белый', TObject(clWhite));
Items.AddObject('Цвет денег', TObject(clMoneyGreen));
Items.AddObject('Цвет неба', TObject(clSkyBlue));
Items.AddObject('Кремовый', TObject(clCream));
Items.AddObject('Светло-серый', TObject(clMedGray));
Items.AddObject(SSelectColor, TObject(clBlack));
end;
procedure ListFillFontNames(Items: TStrings);
begin
Items.Assign(Screen.Fonts);
// Размещаем популярный шрифт в начале списка
Items.Insert(1, 'Times New Roman');
Items.Add(SNoFont);
end;
{ THTMLTagAttribs }
procedure THTMLTagAttribs.AddAttrib(AttrName: string; AttrType: THTMLAttribType);
begin
AttrList.Values[AttrName] := IntToStr(Byte(AttrType));
end;
procedure THTMLTagAttribs.Clear;
begin
end;
constructor THTMLTagAttribs.Create;
begin
AttrList := TStringList.Create;
AddAttrib('ID', atText);
AddAttrib('TITLE', atText);
end;
destructor THTMLTagAttribs.Destroy;
begin
AttrList.Free;
inherited;
end;
function GetStyleType(StyleName: string): THTMLAttribType;
var
Index: Integer;
begin
Result := atNone;
Index := StyleTranslatesList.IndexOfName(StyleName);
if Index >= 0 then
Result := THTMLAttribType(StyleTranslatesList.Objects[Index]);
end;
procedure FillStyleTranslatesList;
procedure Add(AName, ANiceName: string; atype: THTMLAttribType);
begin
StyleTranslatesList.AddObject(AName + '=' + ANiceName, TObject(atype))
end;
begin
Add('width', 'Ширина', atCSSSize);
Add('height', 'Высота', atCSSSize);
Add('borderLeftColor', 'Левая рамка: цвет', atColor);
Add('borderLeftWidth', 'Левая рамка: толщина', atCSSSize);
Add('borderLeftStyle', 'Левая рамка: стиль', atCSSBorderStyle);
Add('borderTopColor', 'Верхняя рамка: цвет', atColor);
Add('borderTopWidth', 'Верхняя рамка: толщина', atCSSSize);
Add('borderTopStyle', 'Верхняя рамка: стиль', atCSSBorderStyle);
Add('borderRightColor', 'Правая рамка: цвет', atColor);
Add('borderRightWidth', 'Правая рамка: толщина', atCSSSize);
Add('borderRightStyle', 'Правая рамка: стиль', atCSSBorderStyle);
Add('borderBottomColor', 'Нижняя рамка: цвет', atColor);
Add('borderBottomWidth', 'Нижняя рамка: толщина', atCSSSize);
Add('borderBottomStyle', 'Нижняя рамка: стиль', atCSSBorderStyle);
Add('paddingLeft', 'Внутреннее поле слева', atCSSSize);
Add('paddingTop', 'Внутреннее поле сверху', atCSSSize);
Add('paddingRight', 'Внутреннее поле справа', atCSSSize);
Add('paddingBottom', 'Внутреннее поле снизу', atCSSSize);
Add('marginLeft', 'Отступ от элемента слева', atCSSSize);
Add('marginTop', 'Отступ от элемента сверху', atCSSSize);
Add('marginRight', 'Отступ от элемента справа', atCSSSize);
Add('marginBottom', 'Отступ от элемента снизу', atCSSSize);
Add('lineHeight', 'Межстрочный интервал', atCSSSize);
Add('textIndent', 'Отступ первой строки абзаца', atCSSSize);
Add('textAlign', 'Выравнивание по горизонтали', atHAlign);
Add('verticalAlign', 'Выравнивание по вертикали', atCSSVAlign);
Add('backgroundColor', 'Цвет фона', atColor);
Add('color', 'Цвет текста', atColor);
Add('fontStyle', 'Стиль шрифта', atCSSFontStyle);
Add('fontWeight', 'Насыщенность шрифта', atCSSFontWeight);
Add('fontSize', 'Размер шрифта', atCSSSize);
Add('fontFamily', 'Используемые шрифты', atText);
Add('writingMode', 'Направление текста', atCSSWritingMode);
Add('pageBreakAfter', 'Вставить разрыв страницы после', atCSSPageBreak);
Add('pageBreakBefore', 'Вставить разрыв страницы до', atCSSPageBreak);
end;
procedure FillTagTranslatesList;
var
attr: THTMLTagAttribs;
begin
attr := THTMLTagAttribs.Create;
attr.AddAttrib('SIZE', atFontSize);
attr.AddAttrib('COLOR', atColor);
attr.AddAttrib('FACE', atFontName);
TagTranslatesList.AddObject('FONT=Шрифт', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('B=Жирный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('I=Курсив', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('U=Подчеркнутый', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('STRIKE=Зачеркнутый', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('S=Зачеркнутый', attr);
//TagTranslatesList.Add('EM=Ударение');
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('EM=Курсив', attr);
//TagTranslatesList.Add('STRONG=Выделение');
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('STRONG=Жирный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('CITE=Цитата', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('Q=Цитата', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('DEL=Удаленный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('INS=Добавленный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('DFN=Термин', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('TT=Моноширинный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('BIG=Увеличенный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('SMALL=Уменьшенный', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('SUP=Верхний', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('SUB=Нижний', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('TYPE', atULType);
TagTranslatesList.AddObject('UL=Простой список', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('TYPE', atOLType);
attr.AddAttrib('START', atCount);
TagTranslatesList.AddObject('OL=Номерованный список', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('DIR=Папки', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('MENU=Папки', attr);
attr := THTMLTagAttribs.Create;
//attr.AddAttrib('TYPE', atOLType); // Значения TYPE зависят от контекста
//attr.AddAttrib('START', atOLType);
TagTranslatesList.AddObject('LI=Элемент списка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('TABLECAPTION', atText);
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('ALIGN', atHAlign);
//attr.AddAttrib('VALIGN', atVAlign); //- не поддерживается!
attr.AddAttrib('BORDER', atPxSize);
attr.AddAttrib('BORDERCOLLAPSE', atBoolean);
attr.AddAttrib('CELLPADDING', atPxSize);
attr.AddAttrib('CELLSPACING', atPxSize);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('BORDERCOLOR', atColor);
attr.AddAttrib('BACKGROUND', atLink);
//attr.AddAttrib('NAME', atText);
//attr.AddAttrib('CLASS', atText);
TagTranslatesList.AddObject('TABLE=Таблица', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
TagTranslatesList.AddObject('CAPTION=Заголовок', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
attr.AddAttrib('COLSPAN', atCount1);
attr.AddAttrib('ROWSPAN', atCount1);
attr.AddAttrib('BACKGROUND', atLink);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('BORDERCOLOR', atColor);
attr.AddAttrib('NOWRAP', atBoolean);
TagTranslatesList.AddObject('TD=Ячейка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
attr.AddAttrib('COLSPAN', atCount1);
attr.AddAttrib('ROWSPAN', atCount1);
attr.AddAttrib('BACKGROUND', atLink);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('BORDERCOLOR', atColor);
attr.AddAttrib('NOWRAP', atBoolean);
TagTranslatesList.AddObject('TH=Ячейка-заголовок', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('BORDERCOLOR', atColor);
TagTranslatesList.AddObject('TR=Строка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
attr.AddAttrib('BGCOLOR', atColor);
TagTranslatesList.AddObject('TFOOT=Подвал', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('VALIGN', atVAlign);
attr.AddAttrib('BGCOLOR', atColor);
TagTranslatesList.AddObject('THEAD=Заголовочная часть', attr);
TagTranslatesList.Add('COL=Настройки колонок'); // Выделить нельзя
TagTranslatesList.Add('COLGROUP=Настройки колонок');
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('DIV=Блок', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('SPAN=Группа', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('NOBR=Не переносить', attr);
attr := THTMLTagAttribs.Create;
//attr.AddAttrib('MARGINHEIGHT', atPxSize); // в IE - не поддерживается
attr.AddAttrib('TOPMARGIN', atPxSize);
//attr.AddAttrib('MARGINWIDTH', atPxSize); // в IE - не поддерживается
attr.AddAttrib('LEFTMARGIN', atPxSize);
attr.AddAttrib('BACKGROUND', atLink);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('TEXT', atColor);
attr.AddAttrib('LINK', atColor);
attr.AddAttrib('ALINK', atColor);
attr.AddAttrib('VLINK', atColor);
TagTranslatesList.AddObject('BODY=Страница', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('HTML=Документ', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('HREF', atLink);
attr.AddAttrib('NAME', atText);
attr.AddAttrib('TARGET', atLinkTarget);
TagTranslatesList.AddObject('A=Ссылка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('P=Абзац', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('CENTER=По центру', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H1=Заголовок 1', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H2=Заголовок 2', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H3=Заголовок 3', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H4=Заголовок 4', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H5=Заголовок 5', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('H6=Заголовок 6', attr);
TagTranslatesList.Add('BR=Разрыв строки'); // Настройка свойств невозможна
attr := THTMLTagAttribs.Create;
attr.AddAttrib('SIZE', atPxSize);
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('NOSHADE', atBoolean);
TagTranslatesList.AddObject('HR=Гориз. линия', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('PRE=Без форматирования', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('XMP=Исходный текст', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ACTION', atLink);
//attr.AddAttrib('AUTOCOMPLETE', atTextBoolean); // почему-то не поддерживается
//attr.AddAttrib('ENCTYPE', atEncType); // почему-то не поддерживается
attr.AddAttrib('METHOD', atMethod);
attr.AddAttrib('NAME', atText);
attr.AddAttrib('TARGET', atLinkTarget);
TagTranslatesList.AddObject('FORM=Форма', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('FIELDSET=Группировка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('ALIGN', atHAlign);
TagTranslatesList.AddObject('LEGEND=Заголовок группы', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('NAME', atText);
attr.AddAttrib('COLS', atCount1);
attr.AddAttrib('ROWS', atCount1);
attr.AddAttrib('DISABLED', atBoolean);
attr.AddAttrib('READONLY', atBoolean);
TagTranslatesList.AddObject('TEXTAREA=Многострочный текст', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('TYPE', atInputType);
attr.AddAttrib('NAME', atText);
attr.AddAttrib('VALUE', atText);
attr.AddAttrib('SIZE', atSize);
attr.AddAttrib('DISABLED', atBoolean);
attr.AddAttrib('READONLY', atBoolean);
attr.AddAttrib('MAXLENGTH', atCount);
// Зачем нужны следующие параметры - непонятно
attr.AddAttrib('BORDER', atPxSize);
attr.AddAttrib('ALIGN', atHAlign);
attr.AddAttrib('ALT', atText);
//attr.AddAttrib('AUTOCOMPLETE', atTextBoolean); // Не поддерживается в IE
attr.AddAttrib('SRC', atLink);
TagTranslatesList.AddObject('INPUT=Элемент ввода', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('NAME', atText);
attr.AddAttrib('DISABLED', atBoolean);
attr.AddAttrib('SIZE', atSize);
attr.AddAttrib('MULTIPLE', atBoolean);
TagTranslatesList.AddObject('SELECT=Выпадающий список', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('OPTION=Элемент списка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('NAME', atText);
TagTranslatesList.AddObject('BUTTON=Кнопка', attr); // Нестандартный тэг
attr := THTMLTagAttribs.Create;
attr.AddAttrib('NAME', atText);
TagTranslatesList.AddObject('MAP=Карта изображения', attr);
TagTranslatesList.Add('AREA=Область'); // Настройка свойств невозможна
attr := THTMLTagAttribs.Create;
attr.AddAttrib('DIR', atText);
TagTranslatesList.AddObject('BDO=Справа-налево', attr);
attr := THTMLTagAttribs.Create;
TagTranslatesList.AddObject('BLOCKQUOTE=Цитата', attr);
TagTranslatesList.Add('EMBED=Объект');
TagTranslatesList.Add('FRAMESET=Структура фреймов');
{attr := THTMLTagAttribs.Create;
attr.AddAttrib('BORDERCOLOR', atColor);
attr.AddAttrib('FRAMEBORDER', atText);
attr.AddAttrib('NAME', atText);
attr.AddAttrib('NORESIZE', atBoolean);
attr.AddAttrib('SCROLLING', atText);
attr.AddAttrib('SRC', atLink);}
TagTranslatesList.Add('FRAME=Фрейм'); // Настройка свойств невозможна
attr := THTMLTagAttribs.Create;
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('DIRECTION', atMrqDir);
attr.AddAttrib('BEHAVIOR', atMrqBehav);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('HSPACE', atPxSize);
attr.AddAttrib('VSPACE', atPxSize);
attr.AddAttrib('LOOP', atCountFromMinus1);
attr.AddAttrib('SCROLLAMOUNT', atPxSize);
attr.AddAttrib('SCROLLDELAY', atCount);
attr.AddAttrib('TRUESPEED', atBoolean);
TagTranslatesList.AddObject('MARQUEE=Бегущая строка', attr);
attr := THTMLTagAttribs.Create;
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('ALT', atText);
attr.AddAttrib('BORDER', atPxSize);
attr.AddAttrib('ALIGN', atImgAlign);
attr.AddAttrib('HSPACE', atPxSize);
attr.AddAttrib('VSPACE', atPxSize);
attr.AddAttrib('ISMAP', atText);
attr.AddAttrib('SRC', atLink);
attr.AddAttrib('USEMAP', atText);
TagTranslatesList.AddObject('IMG=Картинка', attr);
// Тэг для описания новой таблицы
attr := THTMLTagAttribs.Create;
attr.AddAttrib('TABLECAPTION', atText);
attr.AddAttrib('TABCOLS', atCount1);
attr.AddAttrib('TABROWS', atCount1);
attr.AddAttrib('WIDTH', atSize);
attr.AddAttrib('HEIGHT', atSize);
attr.AddAttrib('ALIGN', atHAlign);
//attr.AddAttrib('VALIGN', atVAlign); //- не поддерживается!
attr.AddAttrib('BORDER', atPxSize);
attr.AddAttrib('BORDERCOLLAPSE', atBoolean); // Сделать рамки одинарными
attr.AddAttrib('CELLPADDING', atPxSize);
attr.AddAttrib('CELLSPACING', atPxSize);
attr.AddAttrib('BGCOLOR', atColor);
attr.AddAttrib('BORDERCOLOR', atColor);
attr.AddAttrib('BACKGROUND', atLink);
//- св-ва ячеек, необходимые при содании таблицы
attr.AddAttrib('TDWIDTH', atSize);
attr.AddAttrib('TDWIDTHROWNUM', atCount); // Устанавливать ширину только для указанной строки
attr.AddAttrib('TDHEIGHT', atSize);
attr.AddAttrib('TDALIGN', atHAlign);
attr.AddAttrib('TDVALIGN', atVAlign);
attr.AddAttrib('TDBACKGROUND', atLink);
attr.AddAttrib('TDBGCOLOR', atColor);
attr.AddAttrib('TDBORDERCOLOR', atColor);
attr.AddAttrib('NOWRAP', atBoolean);
//-
TagTranslatesList.AddObject('ADDNEWTABLE=Таблица и ячейки', attr); // Фиктивный тэг
end;
procedure ClearTagTranslatesList;
var
I: Integer;
begin
for I := 0 to TagTranslatesList.Count - 1 do
TagTranslatesList.Objects[I].Free;
end;
procedure FillAttribTranslatesList;
begin
AttribTranslatesList.Add('SIZE=Размер');
AttribTranslatesList.Add('COLOR=Цвет');
AttribTranslatesList.Add('FACE=Шрифт');
AttribTranslatesList.Add('TITLE=Подсказка');
AttribTranslatesList.Add('ALIGN=Выравнивание (гориз)');
AttribTranslatesList.Add('VALIGN=Выравнивание (верт)');
AttribTranslatesList.Add('BORDER=Толщина рамки');
AttribTranslatesList.Add('CELLPADDING=Отступ текста');
AttribTranslatesList.Add('CELLSPACING=Интервал между ячейками');
AttribTranslatesList.Add('WIDTH=Ширина');
AttribTranslatesList.Add('HEIGHT=Высота');
AttribTranslatesList.Add('BGCOLOR=Цвет фона');
AttribTranslatesList.Add('BORDERCOLOR=Цвет рамки');
AttribTranslatesList.Add('BACKGROUND=Фоновый рисунок (файл)');
AttribTranslatesList.Add('MARGINHEIGHT=Ширина верх. и нижн. полей (Netscape)');
AttribTranslatesList.Add('TOPMARGIN=Ширина верхнего поля');
AttribTranslatesList.Add('MARGINWIDTH=Ширина лев. и прав. полей (Netscape)');
AttribTranslatesList.Add('LEFTMARGIN=Ширина левого поля');
AttribTranslatesList.Add('TEXT=Цвет текста');
AttribTranslatesList.Add('LINK=Цвет гиперссылок');
AttribTranslatesList.Add('ALINK=Цвет гиперссылок под курсором');
AttribTranslatesList.Add('VLINK=Цвет посещенных гиперссылок');
AttribTranslatesList.Add('HREF=Адрес гиперссылки');
AttribTranslatesList.Add('NAME=Имя');
AttribTranslatesList.Add('ID=Идентификатор');
AttribTranslatesList.Add('CLASS=Класс');
AttribTranslatesList.Add('TARGET=Поведение при открытии');
AttribTranslatesList.Add('TYPE=Тип');
AttribTranslatesList.Add('START=Начать с');
AttribTranslatesList.Add('NOWRAP=Перенос строк запрещен');
AttribTranslatesList.Add('COLSPAN=Объединенных ячеек по гориз.');
AttribTranslatesList.Add('ROWSPAN=Объединенных ячеек по верт.');
AttribTranslatesList.Add('ACTION=Адрес страницы-обработчика');
AttribTranslatesList.Add('ENCTYPE=Тип содержимого запроса');
AttribTranslatesList.Add('METHOD=Метод отправки запроса');
AttribTranslatesList.Add('FRAMEBORDER=Отображать рамку');
AttribTranslatesList.Add('NORESIZE=Запретить изменение размеров');
AttribTranslatesList.Add('SCROLLING=Способ прокрутки');
AttribTranslatesList.Add('SRC=URL-адрес элемента');
AttribTranslatesList.Add('BEHAVIOR=Тип движения');
AttribTranslatesList.Add('DIRECTION=Направление движения');
AttribTranslatesList.Add('HSPACE=Отступ по горизонтали');
AttribTranslatesList.Add('VSPACE=Отступ по вертикали');
AttribTranslatesList.Add('LOOP=Количество проходов');
AttribTranslatesList.Add('SCROLLAMOUNT=Шаг движения');
AttribTranslatesList.Add('SCROLLDELAY=Задержка в миллисекундах');
AttribTranslatesList.Add('TRUESPEED=Не органичивать скорость');
AttribTranslatesList.Add('ALT=Альтернативный текст');
AttribTranslatesList.Add('ISMAP=Взаимодействовать с сервером');
AttribTranslatesList.Add('USEMAP=Имя карты изображения');
AttribTranslatesList.Add('AUTOCOMPLETE=Автозаполнение');
AttribTranslatesList.Add('DISABLED=Заблокирован');
AttribTranslatesList.Add('MAXLENGTH=Максимальная длина');
AttribTranslatesList.Add('READONLY=Только чтение');
AttribTranslatesList.Add('VALUE=Значение');
AttribTranslatesList.Add('COLS=Длина строки');
AttribTranslatesList.Add('ROWS=Число строк');
AttribTranslatesList.Add('MULTIPLE=Множественный выбор');
AttribTranslatesList.Add('NOSHADE=Плоская линия');
AttribTranslatesList.Add('DOCTITLE=Заголовок страницы');
AttribTranslatesList.Add('DOCCHARSET=Кодировка страницы');
AttribTranslatesList.Add('DOCLANG=Язык страницы');
//AttribTranslatesList.Add('CAPTION=Заголовок таблицы');
AttribTranslatesList.Add('TABLECAPTION=Заголовок таблицы');
AttribTranslatesList.Add('TABCOLS=Число столбцов таблицы');
AttribTranslatesList.Add('TABROWS=Число строк таблицы');
AttribTranslatesList.Add('BORDERCOLLAPSE=Тонкая граница между ячейками');
AttribTranslatesList.Add('TDWIDTH=Ширина ячеек');
AttribTranslatesList.Add('TDWIDTHROWNUM=Уст. ширину только для строки №');
AttribTranslatesList.Add('TDHEIGHT=Высота ячеек');
AttribTranslatesList.Add('TDALIGN=Ячейки: выравн. по гориз.');
AttribTranslatesList.Add('TDVALIGN=Ячейки: выравн. по верт.');
AttribTranslatesList.Add('TDBACKGROUND=Ячейки: фоновый рисунок (файл)');
AttribTranslatesList.Add('TDBGCOLOR=Ячейки: цвет фона');
AttribTranslatesList.Add('TDBORDERCOLOR=Ячейки: цвет рамки');
end;
initialization
TagTranslatesList := TStringList.Create;
AttribTranslatesList := TStringList.Create;
StyleTranslatesList := TStringList.Create;
FillTagTranslatesList;
FillAttribTranslatesList;
FillStyleTranslatesList;
finalization
ClearTagTranslatesList;
TagTranslatesList.Free;
AttribTranslatesList.Free;
StyleTranslatesList.Free;
end.
|
unit uROR_ListView;
{$I Components.inc}
interface
uses
ComCtrls, Controls, Classes, Variants, uROR_Utilities, uROR_CustomListView;
type
TCCRListView = class;
//------------------------------ TCCRListItem(s) -----------------------------
TCCRListItem = class(TCCRCustomListItem)
private
function getListView: TCCRListView;
protected
function getFieldValue(const aFieldIndex: Integer;
var anInternalValue: Variant): String; override;
public
property ListView: TCCRListView read getListView;
end;
TCCRListItems = class(TCCRCustomListItems)
private
function getItem(anIndex: Integer): TCCRListItem;
procedure setItem(anIndex: Integer; const aValue: TCCRListItem);
public
function Add: TCCRListItem;
function AddItem(anItem: TCCRListItem; anIndex: Integer = -1): TCCRListItem;
function AddObject(const aCaption: String; anObject: TObject): TCCRListItem;
function Insert(anIndex: Integer): TCCRListItem;
property Item[anIndex: Integer]: TCCRListItem read getItem
write setItem;
default;
end;
//-------------------------------- TCCRListView ------------------------------
TCCRGetFieldValueEvent = procedure(Sender: TCCRCustomListView;
anItem: TCCRCustomListItem; const aFieldIndex: Integer;
var anExternalValue: String; var anInternalValue: Variant) of object;
TCCRListView = class(TCCRCustomListView)
private
fOnFieldValueGet: TCCRGetFieldValueEvent;
function getItemFocused: TCCRListItem;
function getItems: TCCRListItems;
function getSelected: TCCRListItem;
procedure setItemFocused(aValue: TCCRListItem);
procedure setSelected(aValue: TCCRListItem);
protected
function CreateListItem: TListItem; override;
function CreateListItems: TListItems; override;
public
constructor Create(anOwner: TComponent); override;
procedure AddItem(aCaption: String; anObject: TObject); override;
function GetNextItem(StartItem: TCCRCustomListItem;
Direction: TSearchDirection; States: TItemStates): TCCRListItem;
property ItemFocused: TCCRListItem read getItemFocused
write setItemFocused;
property Items: TCCRListItems read getItems;
property Selected: TCCRListItem read getSelected
write setSelected;
property SortColumn;
published
property Action;
property Align;
property AllocBy;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelKind default bkNone;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property Checkboxes;
property Color;
property ColumnClick;
property Columns;
property Constraints;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FlatScrollBars;
property Font;
//property FullDrag;
property GridLines default False;
property HideSelection;
property HotTrack;
property HotTrackStyles;
property HoverTime;
property IconOptions;
property LargeImages;
property MultiSelect;
property OwnerData;
property OwnerDraw;
property ParentBiDiMode;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly default False;
property RowSelect;
property ShowColumnHeaders default True;
property ShowHint;
property ShowWorkAreas;
property SmallImages;
//property SortType;
property StateImages;
property TabOrder;
property TabStop default True;
property ViewStyle;
property Visible;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnAdvancedCustomDrawSubItem;
property OnChange;
property OnChanging;
property OnClick;
property OnColumnClick;
//property OnColumnDragged;
property OnColumnRightClick;
//property OnCompare;
property OnContextPopup;
property OnCustomDraw;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnData;
property OnDataFind;
property OnDataHint;
property OnDataStateChange;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEdited;
property OnEditing;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnGetSubItemImage;
property OnInfoTip;
property OnInsert;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSelectItem;
property OnStartDock;
property OnStartDrag;
property OnFieldValueGet: TCCRGetFieldValueEvent read fOnFieldValueGet
write fOnFieldValueGet;
property SortDescending default False;
property SortField default -1;
end;
implementation
///////////////////////////////// TCCRListItem \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function TCCRListItem.getFieldValue(const aFieldIndex: Integer;
var anInternalValue: Variant): String;
begin
Result := '';
anInternalValue := Unassigned;
if (aFieldIndex >= 0) and (aFieldIndex < ListView.Columns.Count) then
if Assigned(ListView.OnFieldValueGet) then
ListView.OnFieldValueGet(ListView, Self, aFieldIndex, Result, anInternalValue)
else
begin
Result := StringValues[aFieldIndex];
//--- By default, internal value = external value
anInternalValue := Result;
end;
end;
function TCCRListItem.getListView: TCCRListView;
begin
Result := inherited ListView as TCCRListView;
end;
////////////////////////////////// TCCRListItems \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function TCCRListItems.Add: TCCRListItem;
begin
Result := TCCRListItem(inherited Add);
end;
function TCCRListItems.AddItem(anItem: TCCRListItem; anIndex: Integer): TCCRListItem;
begin
Result := TCCRListItem(inherited AddItem(anItem, anIndex));
end;
function TCCRListItems.AddObject(const aCaption: String; anObject: TObject): TCCRListItem;
begin
Result := Add;
with Result do
begin
Caption := aCaption;
Data := anObject;
UpdateStringValues;
end;
end;
function TCCRListItems.getItem(anIndex: Integer): TCCRListItem;
begin
Result := inherited Item[anIndex] as TCCRListItem;
end;
function TCCRListItems.Insert(anIndex: Integer): TCCRListItem;
begin
Result := TCCRListItem(inherited Insert(anIndex));
end;
procedure TCCRListItems.setItem(anIndex: Integer; const aValue: TCCRListItem);
begin
Item[anIndex].Assign(aValue);
end;
////////////////////////////////// TCCRListView \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRListView.Create(anOwner: TComponent);
begin
inherited;
BevelKind := bkNone;
GridLines := False;
ParentColor := False;
ReadOnly := False;
ShowColumnHeaders := True;
TabStop := True;
end;
procedure TCCRListView.AddItem(aCaption: String; anObject: TObject);
begin
Items.AddObject(aCaption, anObject);
end;
function TCCRListView.CreateListItem: TListItem;
var
LClass: TListItemClass;
begin
LClass := TCCRListItem;
if Assigned(OnCreateItemClass) then
OnCreateItemClass(Self, LClass);
Result := LClass.Create(Items);
end;
function TCCRListView.CreateListItems: TListItems;
begin
Result := TCCRListItems.Create(self);
end;
function TCCRListView.getItemFocused: TCCRListItem;
begin
Result := TCCRListItem(inherited ItemFocused);
end;
function TCCRListView.getItems: TCCRListItems;
begin
Result := inherited Items as TCCRListItems;
end;
function TCCRListView.GetNextItem(StartItem: TCCRCustomListItem;
Direction: TSearchDirection; States: TItemStates): TCCRListItem;
begin
Result := TCCRListItem(inherited GetNextItem(StartItem, Direction, States));
end;
function TCCRListView.getSelected: TCCRListItem;
begin
Result := TCCRListItem(inherited Selected);
end;
procedure TCCRListView.setItemFocused(aValue: TCCRListItem);
begin
inherited ItemFocused := aValue;
end;
procedure TCCRListView.setSelected(aValue: TCCRListItem);
begin
inherited Selected := aValue;
end;
end.
|
unit testtrfacunit;
interface
uses Math, Sysutils, Ap, reflections, creflections, hqrnd, matgen, ablasf, ablas, trfac;
function TestTRFAC(Silent : Boolean):Boolean;
function testtrfacunit_test_silent():Boolean;
function testtrfacunit_test():Boolean;
implementation
procedure TestCLUProblem(const A : TComplex2DArray;
M : AlglibInteger;
N : AlglibInteger;
Threshold : Double;
var Err : Boolean;
var PropErr : Boolean);forward;
procedure TestRLUProblem(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
Threshold : Double;
var Err : Boolean;
var PropErr : Boolean);forward;
function TestTRFAC(Silent : Boolean):Boolean;
var
RA : TReal2DArray;
RAL : TReal2DArray;
RAU : TReal2DArray;
CA : TComplex2DArray;
CAL : TComplex2DArray;
CAU : TComplex2DArray;
M : AlglibInteger;
N : AlglibInteger;
MX : AlglibInteger;
MaxMN : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
MinIJ : AlglibInteger;
Pass : AlglibInteger;
VC : Complex;
VR : Double;
WasErrors : Boolean;
SPDErr : Boolean;
HPDErr : Boolean;
RErr : Boolean;
CErr : Boolean;
PropErr : Boolean;
Threshold : Double;
i_ : AlglibInteger;
begin
RErr := False;
SPDErr := False;
CErr := False;
HPDErr := False;
PropErr := False;
WasErrors := False;
MaxMN := 4*ABLASBlockSize(RA)+1;
Threshold := 1000*MachineEpsilon*MaxMN;
//
// test LU
//
MX:=1;
while MX<=MaxMN do
begin
//
// Initialize N/M, both are <=MX,
// at least one of them is exactly equal to MX
//
N := 1+RandomInteger(MX);
M := 1+RandomInteger(MX);
if AP_FP_Greater(RandomReal,0.5) then
begin
N := MX;
end
else
begin
M := MX;
end;
//
// First, test on zero matrix
//
SetLength(RA, M, N);
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
RA[I,J] := 0;
CA[I,J] := C_Complex(0);
Inc(J);
end;
Inc(I);
end;
TestCLUProblem(CA, M, N, Threshold, CErr, PropErr);
TestRLUProblem(RA, M, N, Threshold, RErr, PropErr);
//
// Second, random matrix with moderate condition number
//
SetLength(RA, M, N);
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
RA[I,J] := 0;
CA[I,J] := C_Complex(0);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=Min(M, N)-1 do
begin
RA[I,I] := 1+10*RandomReal;
CA[I,I] := C_Complex(1+10*RandomReal);
Inc(I);
end;
CMatrixRndOrthogonalFromTheLeft(CA, M, N);
CMatrixRndOrthogonalFromTheRight(CA, M, N);
RMatrixRndOrthogonalFromTheLeft(RA, M, N);
RMatrixRndOrthogonalFromTheRight(RA, M, N);
TestCLUProblem(CA, M, N, Threshold, CErr, PropErr);
TestRLUProblem(RA, M, N, Threshold, RErr, PropErr);
Inc(MX);
end;
//
// Test Cholesky
//
N:=1;
while N<=MaxMN do
begin
//
// Load CA (HPD matrix with low condition number),
// CAL and CAU - its lower and upper triangles
//
HPDMatrixRndCond(N, 1+50*RandomReal, CA);
SetLength(CAL, N, N);
SetLength(CAU, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
CAL[I,J] := C_Complex(I);
CAU[I,J] := C_Complex(J);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
for i_ := 0 to I do
begin
CAL[I,i_] := CA[I,i_];
end;
for i_ := I to N-1 do
begin
CAU[I,i_] := CA[I,i_];
end;
Inc(I);
end;
//
// Test HPDMatrixCholesky:
// 1. it must leave upper (lower) part unchanged
// 2. max(A-L*L^H) must be small
//
if HPDMatrixCholesky(CAL, N, False) then
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if J>I then
begin
HPDErr := HPDErr or C_NotEqualR(CAL[I,J],I);
end
else
begin
VC := C_Complex(0.0);
for i_ := 0 to J do
begin
VC := C_Add(VC,C_Mul(CAL[I,i_],Conj(CAL[J,i_])));
end;
HPDErr := HPDErr or AP_FP_Greater(AbsComplex(C_Sub(CA[I,J],VC)),Threshold);
end;
Inc(J);
end;
Inc(I);
end;
end
else
begin
HPDErr := True;
end;
if HPDMatrixCholesky(CAU, N, True) then
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if J<I then
begin
HPDErr := HPDErr or C_NotEqualR(CAU[I,J],J);
end
else
begin
VC := C_Complex(0.0);
for i_ := 0 to I do
begin
VC := C_Add(VC,C_Mul(Conj(CAU[i_,I]),CAU[i_,J]));
end;
HPDErr := HPDErr or AP_FP_Greater(AbsComplex(C_Sub(CA[I,J],VC)),Threshold);
end;
Inc(J);
end;
Inc(I);
end;
end
else
begin
HPDErr := True;
end;
//
// Load RA (SPD matrix with low condition number),
// RAL and RAU - its lower and upper triangles
//
SPDMatrixRndCond(N, 1+50*RandomReal, RA);
SetLength(RAL, N, N);
SetLength(RAU, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
RAL[I,J] := I;
RAU[I,J] := J;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
APVMove(@RAL[I][0], 0, I, @RA[I][0], 0, I);
APVMove(@RAU[I][0], I, N-1, @RA[I][0], I, N-1);
Inc(I);
end;
//
// Test SPDMatrixCholesky:
// 1. it must leave upper (lower) part unchanged
// 2. max(A-L*L^H) must be small
//
if SPDMatrixCholesky(RAL, N, False) then
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if J>I then
begin
SPDErr := SPDErr or AP_FP_Neq(RAL[I,J],I);
end
else
begin
VR := APVDotProduct(@RAL[I][0], 0, J, @RAL[J][0], 0, J);
SPDErr := SPDErr or AP_FP_Greater(AbsReal(RA[I,J]-VR),Threshold);
end;
Inc(J);
end;
Inc(I);
end;
end
else
begin
SPDErr := True;
end;
if SPDMatrixCholesky(RAU, N, True) then
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if J<I then
begin
SPDErr := SPDErr or AP_FP_Neq(RAU[I,J],J);
end
else
begin
VR := 0.0;
for i_ := 0 to I do
begin
VR := VR + RAU[i_,I]*RAU[i_,J];
end;
SPDErr := SPDErr or AP_FP_Greater(AbsReal(RA[I,J]-VR),Threshold);
end;
Inc(J);
end;
Inc(I);
end;
end
else
begin
SPDErr := True;
end;
Inc(N);
end;
//
// report
//
WasErrors := RErr or SPDErr or CErr or HPDErr or PropErr;
if not Silent then
begin
Write(Format('TESTING TRIANGULAR FACTORIZATIONS'#13#10'',[]));
Write(Format('* REAL: ',[]));
if RErr then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* SPD: ',[]));
if SPDErr then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* COMPLEX: ',[]));
if CErr then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* HPD: ',[]));
if HPDErr then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* OTHER PROPERTIES: ',[]));
if PropErr then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
procedure TestCLUProblem(const A : TComplex2DArray;
M : AlglibInteger;
N : AlglibInteger;
Threshold : Double;
var Err : Boolean;
var PropErr : Boolean);
var
CA : TComplex2DArray;
CL : TComplex2DArray;
CU : TComplex2DArray;
CA2 : TComplex2DArray;
CT : TComplex1DArray;
I : AlglibInteger;
J : AlglibInteger;
MinMN : AlglibInteger;
V : Complex;
P : TInteger1DArray;
i_ : AlglibInteger;
begin
MinMN := Min(M, N);
//
// PLU test
//
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
for i_ := 0 to N-1 do
begin
CA[I,i_] := A[I,i_];
end;
Inc(I);
end;
CMatrixPLU(CA, M, N, P);
I:=0;
while I<=MinMN-1 do
begin
if (P[I]<I) or (P[I]>=M) then
begin
PropErr := False;
Exit;
end;
Inc(I);
end;
SetLength(CL, M, MinMN);
J:=0;
while J<=MinMN-1 do
begin
I:=0;
while I<=J-1 do
begin
CL[I,J] := C_Complex(0.0);
Inc(I);
end;
CL[J,J] := C_Complex(1.0);
I:=J+1;
while I<=M-1 do
begin
CL[I,J] := CA[I,J];
Inc(I);
end;
Inc(J);
end;
SetLength(CU, MinMN, N);
I:=0;
while I<=MinMN-1 do
begin
J:=0;
while J<=I-1 do
begin
CU[I,J] := C_Complex(0.0);
Inc(J);
end;
J:=I;
while J<=N-1 do
begin
CU[I,J] := CA[I,J];
Inc(J);
end;
Inc(I);
end;
SetLength(CA2, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
V := C_Complex(0.0);
for i_ := 0 to MinMN-1 do
begin
V := C_Add(V,C_Mul(CL[I,i_],CU[i_,J]));
end;
CA2[I,J] := V;
Inc(J);
end;
Inc(I);
end;
SetLength(CT, N);
I:=MinMN-1;
while I>=0 do
begin
if I<>P[I] then
begin
for i_ := 0 to N-1 do
begin
CT[i_] := CA2[I,i_];
end;
for i_ := 0 to N-1 do
begin
CA2[I,i_] := CA2[P[I],i_];
end;
for i_ := 0 to N-1 do
begin
CA2[P[I],i_] := CT[i_];
end;
end;
Dec(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Err := Err or AP_FP_Greater(AbsComplex(C_Sub(A[I,J],CA2[I,J])),Threshold);
Inc(J);
end;
Inc(I);
end;
//
// LUP test
//
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
for i_ := 0 to N-1 do
begin
CA[I,i_] := A[I,i_];
end;
Inc(I);
end;
CMatrixLUP(CA, M, N, P);
I:=0;
while I<=MinMN-1 do
begin
if (P[I]<I) or (P[I]>=N) then
begin
PropErr := False;
Exit;
end;
Inc(I);
end;
SetLength(CL, M, MinMN);
J:=0;
while J<=MinMN-1 do
begin
I:=0;
while I<=J-1 do
begin
CL[I,J] := C_Complex(0.0);
Inc(I);
end;
I:=J;
while I<=M-1 do
begin
CL[I,J] := CA[I,J];
Inc(I);
end;
Inc(J);
end;
SetLength(CU, MinMN, N);
I:=0;
while I<=MinMN-1 do
begin
J:=0;
while J<=I-1 do
begin
CU[I,J] := C_Complex(0.0);
Inc(J);
end;
CU[I,I] := C_Complex(1.0);
J:=I+1;
while J<=N-1 do
begin
CU[I,J] := CA[I,J];
Inc(J);
end;
Inc(I);
end;
SetLength(CA2, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
V := C_Complex(0.0);
for i_ := 0 to MinMN-1 do
begin
V := C_Add(V,C_Mul(CL[I,i_],CU[i_,J]));
end;
CA2[I,J] := V;
Inc(J);
end;
Inc(I);
end;
SetLength(CT, M);
I:=MinMN-1;
while I>=0 do
begin
if I<>P[I] then
begin
for i_ := 0 to M-1 do
begin
CT[i_] := CA2[i_,I];
end;
for i_ := 0 to M-1 do
begin
CA2[i_,I] := CA2[i_,P[I]];
end;
for i_ := 0 to M-1 do
begin
CA2[i_,P[I]] := CT[i_];
end;
end;
Dec(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Err := Err or AP_FP_Greater(AbsComplex(C_Sub(A[I,J],CA2[I,J])),Threshold);
Inc(J);
end;
Inc(I);
end;
end;
procedure TestRLUProblem(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
Threshold : Double;
var Err : Boolean;
var PropErr : Boolean);
var
CA : TReal2DArray;
CL : TReal2DArray;
CU : TReal2DArray;
CA2 : TReal2DArray;
CT : TReal1DArray;
I : AlglibInteger;
J : AlglibInteger;
MinMN : AlglibInteger;
V : Double;
P : TInteger1DArray;
i_ : AlglibInteger;
begin
MinMN := Min(M, N);
//
// PLU test
//
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
APVMove(@CA[I][0], 0, N-1, @A[I][0], 0, N-1);
Inc(I);
end;
RMatrixPLU(CA, M, N, P);
I:=0;
while I<=MinMN-1 do
begin
if (P[I]<I) or (P[I]>=M) then
begin
PropErr := False;
Exit;
end;
Inc(I);
end;
SetLength(CL, M, MinMN);
J:=0;
while J<=MinMN-1 do
begin
I:=0;
while I<=J-1 do
begin
CL[I,J] := 0.0;
Inc(I);
end;
CL[J,J] := 1.0;
I:=J+1;
while I<=M-1 do
begin
CL[I,J] := CA[I,J];
Inc(I);
end;
Inc(J);
end;
SetLength(CU, MinMN, N);
I:=0;
while I<=MinMN-1 do
begin
J:=0;
while J<=I-1 do
begin
CU[I,J] := 0.0;
Inc(J);
end;
J:=I;
while J<=N-1 do
begin
CU[I,J] := CA[I,J];
Inc(J);
end;
Inc(I);
end;
SetLength(CA2, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
V := 0.0;
for i_ := 0 to MinMN-1 do
begin
V := V + CL[I,i_]*CU[i_,J];
end;
CA2[I,J] := V;
Inc(J);
end;
Inc(I);
end;
SetLength(CT, N);
I:=MinMN-1;
while I>=0 do
begin
if I<>P[I] then
begin
APVMove(@CT[0], 0, N-1, @CA2[I][0], 0, N-1);
APVMove(@CA2[I][0], 0, N-1, @CA2[P[I]][0], 0, N-1);
APVMove(@CA2[P[I]][0], 0, N-1, @CT[0], 0, N-1);
end;
Dec(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Err := Err or AP_FP_Greater(AbsReal(A[I,J]-CA2[I,J]),Threshold);
Inc(J);
end;
Inc(I);
end;
//
// LUP test
//
SetLength(CA, M, N);
I:=0;
while I<=M-1 do
begin
APVMove(@CA[I][0], 0, N-1, @A[I][0], 0, N-1);
Inc(I);
end;
RMatrixLUP(CA, M, N, P);
I:=0;
while I<=MinMN-1 do
begin
if (P[I]<I) or (P[I]>=N) then
begin
PropErr := False;
Exit;
end;
Inc(I);
end;
SetLength(CL, M, MinMN);
J:=0;
while J<=MinMN-1 do
begin
I:=0;
while I<=J-1 do
begin
CL[I,J] := 0.0;
Inc(I);
end;
I:=J;
while I<=M-1 do
begin
CL[I,J] := CA[I,J];
Inc(I);
end;
Inc(J);
end;
SetLength(CU, MinMN, N);
I:=0;
while I<=MinMN-1 do
begin
J:=0;
while J<=I-1 do
begin
CU[I,J] := 0.0;
Inc(J);
end;
CU[I,I] := 1.0;
J:=I+1;
while J<=N-1 do
begin
CU[I,J] := CA[I,J];
Inc(J);
end;
Inc(I);
end;
SetLength(CA2, M, N);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
V := 0.0;
for i_ := 0 to MinMN-1 do
begin
V := V + CL[I,i_]*CU[i_,J];
end;
CA2[I,J] := V;
Inc(J);
end;
Inc(I);
end;
SetLength(CT, M);
I:=MinMN-1;
while I>=0 do
begin
if I<>P[I] then
begin
for i_ := 0 to M-1 do
begin
CT[i_] := CA2[i_,I];
end;
for i_ := 0 to M-1 do
begin
CA2[i_,I] := CA2[i_,P[I]];
end;
for i_ := 0 to M-1 do
begin
CA2[i_,P[I]] := CT[i_];
end;
end;
Dec(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Err := Err or AP_FP_Greater(AbsReal(A[I,J]-CA2[I,J]),Threshold);
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testtrfacunit_test_silent():Boolean;
begin
Result := TestTRFAC(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testtrfacunit_test():Boolean;
begin
Result := TestTRFAC(False);
end;
end. |
{******************************************************************
JEDI-VCL Demo
Copyright (C) 2002 Project JEDI
Original author:
Contributor(s):
You may retrieve the latest version of this file at the JEDI-JVCL
home page, located at http://jvcl.delphi-jedi.org
The contents of this file are used with permission, 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/MPL-1_1Final.html
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.
******************************************************************}
unit tfMain;
{$mode objfpc}{$H+}
interface
uses
LCLIntf,
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
db, sqldb, sqlite3conn,
ComCtrls, StdCtrls, Buttons, ExtCtrls, ImgList, DateTimePicker, PrintersDlgs,
JvTFManager, JvTFDays, JvTFGlance, JvTFGlanceTextViewer, JvTFMonths,
JvTFWeeks, JvTFAlarm;
type
{ TMainForm }
TMainForm = class(TForm)
JvTFAlarm1: TJvTFAlarm;
NewSchedButton: TBitBtn;
TodayButton: TSpeedButton;
WeeksCombo: TComboBox;
StrokeImages: TImageList;
JvTFDaysPrinter1: TJvTFDaysPrinter;
IconsProvidedLabel: TLabel;
IconsLink: TLabel;
Panel2: TPanel;
SettingsButton: TBitBtn;
PrintDialog: TPrintDialog;
utfScheduleManager1: TJvTFScheduleManager;
ColoredImages: TImageList;
NeedApptsQuery: TSQLQuery;
ApptSchedulesQuery: TSQLQuery;
GetApptQuery: TSQLQuery;
DeleteApptLinkQuery: TSQLQuery;
DeleteApptQuery: TSQLQuery;
SchedulesQuery: TSQLQuery;
PageControl1: TPageControl;
pgDays: TTabSheet;
pgWeeks: TTabSheet;
pgMonths: TTabSheet;
JvTFDays1: TJvTFDays;
JvTFWeeks1: TJvTFWeeks;
JvTFMonths1: TJvTFMonths;
GlanceTextViewer1: TJvTFGlanceTextViewer;
GlanceTextViewer2: TJvTFGlanceTextViewer;
Panel1: TPanel;
ResourceCombo: TComboBox;
PrevDateButton: TBitBtn;
NextDateButton: TBitBtn;
NewApptButton: TBitBtn;
EditApptButton: TBitBtn;
DeleteApptButton: TBitBtn;
ViewSchedsButton: TBitBtn;
HideSchedButton: TBitBtn;
ShareButton: TBitBtn;
TimeIncCombo: TComboBox;
GotoDatePicker: TDateTimePicker;
ModeCombo: TComboBox;
DaysCombo: TComboBox;
PrintButton: TBitBtn;
dbUTF: TSQLite3Connection;
SQLTransaction: TSQLTransaction;
procedure IconsLinkClick(Sender: TObject);
procedure IconsLinkMouseEnter(Sender: TObject);
procedure IconsLinkMouseLeave(Sender: TObject);
procedure JvTFAlarm1Alarm(Sender: TObject; AAppt: TJvTFAppt;
var SnoozeMins: Integer; var Dismiss: Boolean);
procedure ModeComboChange(Sender: TObject);
procedure NewSchedButtonClick(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure SettingsButtonClick(Sender: TObject);
procedure TodayButtonClick(Sender: TObject);
procedure ViewSchedsButtonClick(Sender: TObject);
procedure HideSchedButtonClick(Sender: TObject);
procedure ResourceComboChange(Sender: TObject);
procedure DaysComboChange(Sender: TObject);
procedure ShareButtonClick(Sender: TObject);
procedure PrevDateButtonClick(Sender: TObject);
procedure NextDateButtonClick(Sender: TObject);
procedure GotoDatePickerChange(Sender: TObject);
procedure GotoDatePickerUserInput(Sender: TObject;
const UserString: String; var DateAndTime: TDateTime;
var AllowChange: Boolean);
procedure TimeIncComboChange(Sender: TObject);
procedure NewApptButtonClick(Sender: TObject);
procedure EditApptButtonClick(Sender: TObject);
procedure DeleteApptButtonClick(Sender: TObject);
procedure JvTFDays1DateChanging(Sender: TObject; var NewDate: TDate);
procedure JvTFDays1DateChanged(Sender: TObject);
procedure JvTFDays1GranularityChanged(Sender: TObject);
procedure JvTFDays1DblClick(Sender: TObject);
procedure JvTFDaysPrinter1ApptProgress(Sender: TObject; Current,
Total: Integer);
procedure JvTFDaysPrinter1AssembleProgress(Sender: TObject; Current,
Total: Integer);
procedure JvTFDaysPrinter1PrintProgress(Sender: TObject; Current,
Total: Integer);
procedure utfScheduleManager1LoadBatch(Sender: TObject; BatchName: String;
BatchStartDate, BatchEndDate: TDate);
procedure utfScheduleManager1DeleteAppt(Sender: TObject; Appt: TJvTFAppt);
procedure utfScheduleManager1PostAppt(Sender: TObject; Appt: TJvTFAppt);
procedure utfScheduleManager1RefreshAppt(Sender: TObject; Appt: TJvTFAppt);
procedure CreateDatabase(const AFileName: String);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure PrintButtonClick(Sender: TObject);
procedure WeeksComboChange(Sender: TObject);
private
FNewDatabase: Boolean;
{ Private declarations }
procedure ApplySettings;
procedure ReadIni;
procedure WriteIni;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses
IniFiles,
tfVisibleResources, tfShare, tfApptEdit, tfPrintProgress, tfSettings, tfAlarm;
{$R *.lfm}
procedure TMainForm.ApplySettings;
var
images: Array[0..1] of TImageList;
begin
with GlobalSettings do begin
JvTFDays1.FancyRowHdrAttr.Hr2400 := Hr2400;
JvTFDays1.SelFancyRowHdrAttr.Hr2400 := Hr2400;
JvTFDaysPrinter1.FancyRowHdrAttr.Hr2400 := Hr2400;
JvTFWeeks1.StartOfWeek := FirstDayOfWeek;
JvTFMonths1.StartOfWeek := FirstDayOfWeek;
JvTFDays1.PrimeTime.StartTime := PrimeTimeStart;
JvTFDays1.PrimeTime.EndTime := PrimeTimeEnd;
JvTFDays1.PrimeTime.Color := PrimeTimeColor;
images[0] := ColoredImages;
images[1] := StrokeImages;
PrevDateButton.Images := images[IconSet];
NextDateButton.Images := images[IconSet];
TodayButton.Images := images[IconSet];
NewApptButton.Images := images[IconSet];
EditApptButton.Images := images[IconSet];
DeleteApptButton.Images := images[IconSet];
PrintButton.Images := images[IconSet];
SettingsButton.Images := images[IconSet];
ViewSchedsButton.Images := images[IconSet];
HideSchedButton.Images := images[IconSet];
ShareButton.Images := images[IconSet];
NewSchedButton.Images := images[IconSet];
utfScheduleManager1.StateImages := images[IconSet];
if StartToday then
GotoDatePicker.Date := Date()
else
GotoDatePicker.Date := StartDate;
GotoDatePickerChange(nil);
end;
end;
procedure TMainForm.utfScheduleManager1PostAppt(Sender: TObject;
Appt: TJvTFAppt);
var
I : Integer;
begin
With GetApptQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
Open;
If RecordCount > 0 Then // SQL RecordCount not reliable except on local tables
Edit
Else
Begin
Insert;
FieldByName('ApptID').AsString := Appt.ID;
End;
FieldByName('StartDate').AsDateTime := Appt.StartDate;
FieldByName('StartTime').AsDateTime := Appt.StartTime;
FieldByName('EndDate').AsDateTime := Appt.EndDate;
FieldByName('EndTime').AsDateTime := Appt.EndTime;
FieldByName('Description').AsString := Appt.Description;
FieldByName('AlarmEnabled').AsBoolean := Appt.AlarmEnabled;
FieldByName('AlarmAdvance').AsInteger := Appt.AlarmAdvance;
Post;
Close;
End;
// Now update the Appt --> Schedule relationship
// First delete all entries in the Link table
With DeleteApptLinkQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
ExecSQL;
End;
// Now "refresh" the link table by adding a record for each of the names
// in Appt.Schedules. We will use the ApptSchedulesQuery to update the table.
With ApptSchedulesQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
Open;
For I := 0 to Appt.ScheduleCount - 1 do
Begin
Insert;
FieldByName('ApptID').AsString := Appt.ID;
FieldByName('SchedName').AsString := Appt.Schedules[I];
Post;
End;
Close;
End;
end;
procedure TMainForm.utfScheduleManager1DeleteAppt(Sender: TObject;
Appt: TJvTFAppt);
begin
// First delete the appointment from the appointment table
With DeleteApptQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
ExecSQL;
End;
// Next, delete the related records from the link table
With DeleteApptLinkQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
ExecSQL;
End;
end;
procedure TMainForm.utfScheduleManager1RefreshAppt(Sender: TObject;
Appt: TJvTFAppt);
begin
With GetApptQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
Open;
If RecordCount = 1 Then
Begin
Appt.SetStartEnd(FieldByName('StartDate').AsDateTime,
FieldByName('StartTime').AsDateTime,
FieldByName('EndDate').AsDateTime,
FieldByName('EndTime').AsDateTime);
Appt.Description := FieldByName('Description').AsString;
Appt.AlarmEnabled := FieldByName('AlarmEnabled').AsBoolean;
Appt.AlarmAdvance := FieldByName('AlarmAdvance').AsInteger;
End;
Close;
End;
// Now update the Appt --> Schedule(s) relationship
Appt.ClearSchedules;
With ApptSchedulesQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
Open;
First;
While not EOF do
Begin
Appt.AddSchedule(FieldByName('SchedName').AsString);
Next;
End;
Close; // ApptSchedulesQuery
End;
end;
procedure TMainForm.ModeComboChange(Sender: TObject);
begin
ResourceCombo.Visible := ModeCombo.ItemIndex = 0;
DaysCombo.Visible := (ModeCombo.ItemIndex = 0) and (PageControl1.ActivePage = pgDays);
WeeksCombo.Visible := (ModeCombo.ItemIndex = 0) and (PageControl1.ActivePage = pgWeeks);
NewSchedButton.Visible := ModeCombo.ItemIndex = 1;
ViewSchedsButton.Visible := ModeCombo.ItemIndex = 1;
HideSchedButton.Visible := ModeCombo.ItemIndex = 1;
ShareButton.Visible := ModeCombo.ItemIndex = 1;
If ModeCombo.ItemIndex = 0 Then
// Single mode
Begin
// synchronize the date
JvTFDays1.Template.LinearStartDate := GotoDatePicker.Date;
// "activate" the Linear template
JvTFDays1.Template.ActiveTemplate := agtLinear;
// set the column grouping
JvTFDays1.Grouping := grResource;
End
Else
// Group mode
Begin
// synchronize the date
JvTFDays1.Template.CompDate := GotoDatePicker.Date;
// "activate" the Comparative template
JvTFDays1.Template.ActiveTemplate := agtComparative;
// set the column grouping
JvTFDays1.Grouping := grDate;
End;
end;
procedure TMainForm.ViewSchedsButtonClick(Sender: TObject);
begin
VisibleResources.ShowModal;
end;
procedure TMainForm.WeeksComboChange(Sender: TObject);
begin
JvTFWeeks1.WeekCount := WeeksCombo.ItemIndex + 1;
end;
procedure TMainForm.HideSchedButtonClick(Sender: TObject);
var
I,
NameIndex : Integer;
NameList : TStringList;
begin
NameList := TStringList.Create;
Try
With JvTFDays1 do
Begin
If ValidSelection Then
Begin
For I := SelStart.X to SelEnd.X do
NameList.Add(Cols[I].SchedName);
For I := 0 to NameList.Count - 1 do
Begin
NameIndex := Template.CompNames.IndexOf(NameList[I]);
If NameIndex > -1 Then
Template.CompNames.Delete(NameIndex);
End;
End
Else
MessageDlg('Please select a schedule to hide.', mtInformation, [mbOK], 0);
End;
Finally
NameList.Free;
End;
end;
procedure TMainForm.ResourceComboChange(Sender: TObject);
begin
JvTFDays1.Template.LinearName := ResourceCombo.Text;
JvTFWeeks1.SchedNames.Clear;
JvTFWeeks1.SchedNames.Add(ResourceCombo.Text);
JvTFWeeks1.Refresh;
JvTFMonths1.SchedNames.Clear;
JvTFMonths1.SchedNames.Add(ResourceCombo.Text);
JvTFMonths1.Refresh;
end;
procedure TMainForm.SettingsButtonClick(Sender: TObject);
begin
if SettingsForm.ShowModal = mrOK then
ApplySettings;
end;
procedure TMainForm.DaysComboChange(Sender: TObject);
var
s: String;
begin
Case DaysCombo.ItemIndex of
0 : JvTFDays1.Template.LinearDayCount := 1;
1 : JvTFDays1.Template.LinearDayCount := 2;
2 : JvTFDays1.Template.LinearDayCount := 3;
3 : JvTFDays1.Template.LinearDayCount := 5;
4 : JvTFDays1.Template.LinearDayCount := 7;
5 : JvTFDays1.Template.LinearDayCount := 14;
6 : JvTFDays1.Template.LinearDayCount := 31;
End;
if JvTFDays1.Template.LinearDayCount <= 2 then
JvTFDays1.DateFormat := DefaultFormatSettings.LongDateFormat
else
if JvTFDays1.Template.LinearDayCount <= 5 then
JvTFDays1.DateFormat := DefaultFormatSettings.ShortDateFormat
else begin
s := StringReplace(DefaultFormatSettings.ShortDateFormat, 'yyyy', 'yy', [rfIgnoreCase]);
JvTFDays1.DateFormat := s;
end;
end;
procedure TMainForm.ShareButtonClick(Sender: TObject);
begin
If JvTFDays1.SelAppt <> nil Then
Share.ShowModal
Else
MessageDlg('Please select an appointment.', mtInformation, [mbOK], 0);
end;
procedure TMainForm.PrevDateButtonClick(Sender: TObject);
begin
JvTFDays1.PrevDate;
JvTFMonths1.DisplayDate := JvTFDays1.CurrentDate;
JvTFWeeks1.DisplayDate := JvTFDays1.CurrentDate;
end;
procedure TMainForm.NextDateButtonClick(Sender: TObject);
begin
JvTFDays1.NextDate;
JvTFMonths1.DisplayDate := JvTFDays1.CurrentDate;
JvTFWeeks1.DisplayDate := JvTFDays1.CurrentDate;
end;
procedure TMainForm.PageControl1Change(Sender: TObject);
begin
WeeksCombo.BoundsRect := DaysCombo.BoundsRect;
WeeksCombo.Visible := PageControl1.ActivePage = pgWeeks;
DaysCombo.Visible := PageControl1.ActivePage = pgDays;
end;
procedure TMainForm.GotoDatePickerChange(Sender: TObject);
begin
// GotoDatePicker.OnCloseUp should also point to this handler
JvTFDays1.GotoDate(GotoDatePicker.Date);
JvTFWeeks1.DisplayDate := GotoDatePicker.Date;
JvTFMonths1.DisplayDate := GotoDatePicker.Date;
end;
procedure TMainForm.GotoDatePickerUserInput(Sender: TObject;
const UserString: String; var DateAndTime: TDateTime;
var AllowChange: Boolean);
begin
AllowChange := True;
GotoDatePicker.OnChange(nil);
end;
procedure TMainForm.TimeIncComboChange(Sender: TObject);
begin
Case TimeIncCombo.ItemIndex of
0 : JvTFDays1.Granularity := 60;
1 : JvTFDays1.Granularity := 30;
2 : JvTFDays1.Granularity := 20;
3 : JvTFDays1.Granularity := 15;
4 : JvTFDays1.Granularity := 12;
5 : JvTFDays1.Granularity := 10;
6 : JvTFDays1.Granularity := 6;
7 : JvTFDays1.Granularity := 5;
8 : JvTFDays1.Granularity := 4;
9 : JvTFDays1.Granularity := 3;
10 : JvTFDays1.Granularity := 2;
11 : JvTFDays1.Granularity := 1;
End;
end;
procedure TMainForm.TodayButtonClick(Sender: TObject);
begin
JvTFDays1.GotoDate(Date());
JvTFMonths1.DisplayDate := JvTFDays1.CurrentDate;
JvTFWeeks1.DisplayDate := JvTFDays1.CurrentDate;
end;
procedure TMainForm.NewApptButtonClick(Sender: TObject);
begin
// Simply open the EditAppt window. The Appt var of the
// EditAppt form will already be nil (which indicates
// that the appoinment is being created).
ApptEdit.ShowModal;
end;
procedure TMainForm.NewSchedButtonClick(Sender: TObject);
var
s: String;
n: Integer;
begin
s := InputBox('Add User', 'User name', '');
if s <> '' then begin
ResourceCombo.Items.Add(s);
n := VisibleResources.ResourcesCheckList.Items.Add(s);
Share.ResourcesCheckList.Items.Add(s);
VisibleResources.ResourcesCheckList.Checked[n] := True;
end;
end;
procedure TMainForm.EditApptButtonClick(Sender: TObject);
begin
If Assigned(JvTFDays1.SelAppt) Then
Begin
// Set EditAppt's Appt var to the selected appointment to
// indicate that the appointment should be edited.
ApptEdit.Appt := JvTFDays1.SelAppt;
ApptEdit.ShowModal;
End
else
MessageDlg('Please select an appointment to edit.', mtInformation, [mbOK], 0);
end;
procedure TMainForm.DeleteApptButtonClick(Sender: TObject);
var
Appt : TJvTFAppt;
dbDel : Boolean;
SelSchedName : String;
begin
// This routine employs a simple business that asks the user what to
// do in the case where the user is attempting to delete a shared appt.
// NOTE: This is NOT required. You are completely free to implement
// any business rules you see fit.
// Another shortcut to save typing
Appt := JvTFDays1.SelAppt;
If Assigned(Appt) Then
Begin
dbDel := True;
If Appt.Shared Then
If MessageDlg('This appointment is shared with other schedules.' + #13#10 +
'Do you want to delete the appointment from ' +
'all schedules?' + #13#10#13#10 +
'Choose ''No'' to delete the appointment from the ' +
'selected schedule only.' + #13#10 +
'Choose ''All'' to delete the appointment from all schedules.',
mtConfirmation, [mbNo, mbAll], 0) = mrNo Then
Begin
// Don't delete the appointment, but remove it from the schedule
// of the selected resource.
dbDel := False;
With JvTFDays1 do
Begin
SelSchedName := '';
If ValidSelection and Cols[SelStart.X].Connected Then
SelSchedName := Cols[SelStart.X].Schedule.SchedName;
End;
If SelSchedName <> '' Then
Appt.RemoveSchedule(SelSchedName)
Else
MessageDlg('No schedule is selected.' + #13#10 +
'Could not remove appointment from schedule.',
mtInformation, [mbOK], 0);
End;
If dbDel Then
If MessageDlg('Are you sure you want to delete the selected appointment?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes Then
// Delete the appointment (removes it from the db)
// Note: Could substitute Appt.Delete; for the line below
JvTFDays1.ScheduleManager.dbDeleteAppt(JvTFDays1.SelAppt);
End
Else
MessageDlg('Please select an appointment to delete.',
mtInformation, [mbOK], 0);
end;
procedure TMainForm.JvTFDays1DateChanging(Sender: TObject;
var NewDate: TDate);
begin
// Make sure all appts are posted before moving on.
JvTFDays1.ScheduleManager.PostAppts;
end;
procedure TMainForm.JvTFDays1DateChanged(Sender: TObject);
begin
// Synchronize the tool bar
With JvTFDays1.Template do
If ActiveTemplate = agtLinear Then
GotoDatePicker.Date := LinearStartDate
Else
GotoDatePicker.Date := CompDate;
end;
procedure TMainForm.JvTFDays1GranularityChanged(Sender: TObject);
begin
// Update the TimeIncCombo when the granularity is changed.
// (This can be done by <Ctrl> + <Insert> and <Ctrl> + <Delete>)
Case JvTFDays1.Granularity of
60 : TimeIncCombo.ItemIndex := 0;
30 : TimeIncCombo.ItemIndex := 1;
20 : TimeIncCombo.ItemIndex := 2;
15 : TimeIncCombo.ItemIndex := 3;
12 : TimeIncCombo.ItemIndex := 4;
10 : TimeIncCombo.ItemIndex := 5;
6 : TimeIncCombo.ItemIndex := 6;
5 : TimeIncCombo.ItemIndex := 7;
4 : TimeIncCombo.ItemIndex := 8;
3 : TimeIncCombo.ItemIndex := 9;
2 : TimeIncCombo.ItemIndex := 10;
Else
TimeIncCombo.ItemIndex := 11;
End;
end;
procedure TMainForm.JvTFDays1DblClick(Sender: TObject);
begin
With JvTFDays1 do
If ValidSelection Then
If Assigned(SelAppt) Then
EditApptButtonClick(nil)
Else
NewApptButtonClick(nil);
end;
procedure TMainForm.FormShow(Sender: TObject);
var
ResName : String;
begin
// Initialize the date
ReadIni;
// GotoDatePicker.Date := EncodeDate(2002, 1, 1);
if FNewDatabase then
NewSchedButtonClick(nil);
// Populate the resource related controls
With SchedulesQuery do
try
Open;
First;
While not EOF do
Begin
ResName := SchedulesQuery.FieldByName('SchedName').AsString;
ResourceCombo.Items.Add(ResName);
VisibleResources.ResourcesCheckList.Items.Add(ResName);
Share.ResourcesCheckList.Items.Add(ResName);
Next;
End;
Close;
except
//on E:EDBEngineError do
on E: EDatabaseError do
begin
ShowMessageFmt('%s:'#13#10'Try moving the database to a shorter path.',[E.Message]);
Application.Terminate;
Exit;
end;
end;
// Initialize the resource related controls
ResourceCombo.ItemIndex := 0;
if VisibleResources.ResourcesCheckList.Items.Count > 0 then begin
VisibleResources.ResourcesCheckList.Checked[0] := True;
// Initialize the comparative template
JvTFDays1.Template.CompNames.Add(VisibleResources.ResourcesCheckList.Items[0]);
end;
// Now run the events to synchronize JvTFDays, etc.
ResourceComboChange(nil);
DaysComboChange(nil);
ModeComboChange(nil);
if GlobalSettings.StartToday then
GotoDatePicker.Date := Date()
else
GotoDatePicker.Date := GlobalSettings.StartDate;
GotoDatePickerChange(nil);
TimeIncComboChange(nil);
end;
procedure TMainForm.PrintButtonClick(Sender: TObject);
begin
if not PrintDialog.Execute then
exit;
with JvTFDaysPrinter1 do
begin
// "Copy" the display properties from the JvTFDays control
SetProperties(JvTFDays1);
// Set gridline color to black for sharp display on printed page
GridLineColor := clBlack;
// print 48 rows on each page
PageLayout.RowsPerPage := 48;
// fit all the columns onto one page wide
PageLayout.ColsPerPage := 0;
// "Copy" the schedules from the JvTFDays control
Cols.Assign(JvTFDays1.Cols);
PrintProgress.Show;
Application.ProcessMessages;
// print the document
PrintDirect;
PrintProgress.Close;
end;
end;
procedure TMainForm.JvTFDaysPrinter1ApptProgress(Sender: TObject;
Current, Total: Integer);
begin
If Current > Total Then
Total := Current;
PrintProgress.Label2.Caption := 'Processing appointment ' + IntToStr(Current) +
' of ' + IntToStr(Total) + ' (estimated)';
PrintProgress.ProgressBar1.Max := Total;
PrintProgress.ProgressBar1.Position := Current;
end;
procedure TMainForm.JvTFDaysPrinter1AssembleProgress(Sender: TObject;
Current, Total: Integer);
begin
PrintProgress.Label2.Caption := 'Assembling page ' + IntToStr(Current) +
' of ' + IntToStr(Total);
PrintProgress.ProgressBar1.Max := Total;
PrintProgress.ProgressBar1.Position := Current;
end;
procedure TMainForm.JvTFDaysPrinter1PrintProgress(Sender: TObject;
Current, Total: Integer);
begin
PrintProgress.Label2.Caption := 'Printing page ' + IntToStr(Current) +
' of ' + IntToStr(Total);
PrintProgress.ProgressBar1.Max := Total;
PrintProgress.ProgressBar1.Position := Current;
end;
procedure TMainForm.IconsLinkClick(Sender: TObject);
begin
OpenURL('https://icons8.com');
end;
procedure TMainForm.IconsLinkMouseEnter(Sender: TObject);
begin
IconsLink.Font.Style := IconsLink.Font.Style + [fsUnderline];
Screen.Cursor := crHandPoint;
end;
procedure TMainForm.IconsLinkMouseLeave(Sender: TObject);
begin
IconsLink.Font.Style := IconsLink.Font.Style - [fsUnderline];
Screen.Cursor := crDefault;
end;
procedure TMainForm.JvTFAlarm1Alarm(Sender: TObject; AAppt: TJvTFAppt;
var SnoozeMins: Integer; var Dismiss: Boolean);
var
F: TAlarmForm;
begin
F := TAlarmForm.Create(nil);
try
F.SetAppt(AAppt);
F.SnoozeMins := SnoozeMins;
F.ShowModal;
Dismiss := not F.Snooze;
SnoozeMins := F.SnoozeMins;
finally
F.Free;
end;
end;
{
var
msg: String;
res: Integer;
s: String;
begin
msg := Format('The event "%s" is due', [AAppt.Description]);
if AAppt.StartDate = Date then
msg := msg + ' at ' + TimeToStr(AAppt.StartTime)
else
msg := msg + ' on ' + FormatDateTime('dddddd', AAppt.StartTime);
msg := msg + LineEnding + 'Remind in ' + IntToStr(SnoozeMins) + ' minutes?';
res := MessageDlg(msg, mtInformation, [mbYes, mbNo], 0);
Dismiss := res = mrYes;
end;
}
procedure TMainForm.utfScheduleManager1LoadBatch(Sender: TObject;
BatchName: String; BatchStartDate, BatchEndDate: TDate);
var
Appt : TJvTFAppt;
NewAppt : Boolean;
begin
With NeedApptsQuery do
Begin
// Set the query parameters so the query will return
// all appointments for the given resource that fall
// on the given date.
ParamByName('D1').AsDate := BatchStartDate;
ParamByName('D2').AsDate := BatchEndDate;
ParamByName('SchedName').AsString := BatchName;
// Next, loop through the returned records to add the data
Open;
First;
While not EOF do
Begin
// Request an appointment object from the server
utfScheduleManager1.RequestAppt(FieldByName('ApptID').AsString,
Appt, NewAppt);
// If it is a newly loaded appt we want to set its properties
If NewAppt Then
Begin
Appt.SetStartEnd(FieldByName('StartDate').AsDateTime,
FieldByName('StartTime').AsDateTime,
FieldByName('EndDate').AsDateTime,
FieldByName('EndTime').AsDateTime);
Appt.Description := FieldByName('Description').AsString;
Appt.AlarmEnabled := FieldByName('AlarmEnabled').AsBoolean;
Appt.AlarmAdvance := FieldByName('AlarmAdvance').AsInteger;
// Now manage the Appt --> Schedule(s) relationship
With ApptSchedulesQuery do
Begin
ParamByName('ApptID').AsString := Appt.ID;
Open;
First;
While not EOF do
Begin
Appt.AddSchedule(FieldByName('SchedName').AsString);
Next;
End;
Close; // ApptSchedulesQuery
End;
End;
Next; // NeedApptsQuery record
End;
Close; // NeedApptsQuery
End;
end;
procedure TMainForm.CreateDatabase(const AFileName: String);
var
sql: String;
begin
dbUTF.Open;
SQLTransaction.Active := true;
sql := 'CREATE TABLE "GroupAppt" (' +
'"ApptID" STRING PRIMARY KEY,'+
'"StartDate" DATE,'+
'"StartTime" TIME,'+
'"EndDate" DATE,'+
'"EndTime" TIME,'+
'"Description" TEXT,'+
'"AlarmEnabled" BOOL,'+
'"AlarmAdvance" REAL);';
dbUTF.ExecuteDirect(sql);
SQLTransaction.Commit;
sql := 'CREATE TABLE "GroupLink" ('+
'"SchedName" String,'+
'"ApptID" String);';
dbUTF.ExecuteDirect(sql);
SQLTransaction.Commit;
FNewDatabase := true;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
fn: String;
begin
with FormatSettings do begin
ThousandSeparator := ',';
DecimalSeparator := '.';
DateSeparator := '/';
TimeSeparator := ':';
ShortDateFormat := 'd/mm/yyyy';
LongDateFormat := 'dd" "mmmm" "yyyy';
TimeAMString := 'AM';
TimePMString := 'PM';
ShortTimeFormat := 'hh:nn';
LongTimeFormat := 'hh:nn:ss';
ShortMonthNames[1] := 'Jan';
ShortMonthNames[2] := 'Feb';
ShortMonthNames[3] := 'Mar';
ShortMonthNames[4] := 'Apr';
ShortMonthNames[5] := 'May';
ShortMonthNames[6] := 'Jun';
ShortMonthNames[7] := 'Jul';
ShortMonthNames[8] := 'Aug';
ShortMonthNames[9] := 'Sep';
ShortMonthNames[10] := 'Oct';
ShortMonthNames[11] := 'Nov';
ShortMonthNames[12] := 'Dec';
LongMonthNames[1] := 'January';
LongMonthNames[2] := 'February';
LongMonthNames[3] := 'March';
LongMonthNames[4] := 'April';
LongMonthNames[5] := 'May';
LongMonthNames[6] := 'June';
LongMonthNames[7] := 'July';
LongMonthNames[8] := 'August';
LongMonthNames[9] := 'September';
LongMonthNames[10] := 'October';
LongMonthNames[11] := 'November';
LongMonthNames[12] := 'December';
ShortDayNames[1] := 'Sun';
ShortDayNames[2] := 'Mon';
ShortDayNames[3] := 'Tue';
ShortDayNames[4] := 'Wed';
ShortDayNames[5] := 'Thu';
ShortDayNames[6] := 'Fri';
ShortDayNames[7] := 'Sat';
LongDayNames[1] := 'Sunday';
LongDayNames[2] := 'Monday';
LongDayNames[3] := 'Tuesday';
LongDayNames[4] := 'Wednesday';
LongDayNames[5] := 'Thursday';
LongDayNames[6] := 'Friday';
LongDayNames[7] := 'Saturday';
end;
fn := Application.Location + 'data.sqlite';
dbUTF.DatabaseName := fn;
if FileExists(fn) then begin
dbUTF.Open;
SQLTransaction.Active := true;
end else
CreateDatabase(fn);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
WriteIni;
end;
procedure TMainForm.ReadIni;
var
ini: TCustomIniFile;
begin
ini := TMemIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
try
ModeCombo.ItemIndex := ini.ReadInteger('MainForm', 'ModeCombo', 0);
TimeIncCombo.ItemIndex := ini.ReadInteger('MainForm', 'TimeIncCombo', 1);
DaysCombo.ItemIndex := ini.ReadInteger('MainForm', 'DaysCombo', 0);
WeeksCombo.ItemIndex := ini.ReadInteger('MainForm', 'WeeksCombo', 0);
PageControl1.ActivePageIndex := ini.ReadInteger('MainForm', 'PageIndex', 0);
PageControl1Change(nil);
GlobalSettings.StartToday := ini.ReadBool('Settings', 'StartToday', GlobalSettings.StartToday);
GlobalSettings.StartDate := ini.ReadDate('Settings', 'StartDate', GlobalSettings.StartDate);
GlobalSettings.Hr2400 := ini.ReadBool('Settings', 'Hr2400', GlobalSettings.Hr2400);
GlobalSettings.FirstDayOfWeek := TTFDayofWeek(ini.ReadInteger('Settings', 'FirstDayOfWeek', ord(GlobalSettings.FirstDayOfWeek)));
GlobalSettings.PrimeTimeStart := ini.ReadTime('Settings', 'PrimeTimeStart', GlobalSettings.PrimeTimeStart);
GlobalSettings.PrimeTimeEnd := ini.ReadTime('Settings', 'PrimeTimeEnd', GlobalSettings.PrimeTimeEnd);
GlobalSettings.PrimeTimeColor := TColor(ini.ReadInteger('Settings', 'PrimeTimeColor', Integer(GlobalSettings.PrimeTimeColor)));
GlobalSettings.IconSet := ini.ReadInteger('Settings', 'IconSet', GlobalSettings.IconSet);
ApplySettings;
finally
ini.Free;
end;
end;
procedure TMainForm.WriteIni;
var
ini: TCustomIniFile;
begin
ini := TMemIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
try
ini.WriteInteger('MainForm', 'PageIndex', PageControl1.ActivePageIndex);
ini.WriteInteger('MainForm', 'ModeCombo', ModeCombo.ItemIndex);
ini.WriteInteger('MainForm', 'TimeIncCombo', TimeIncCombo.ItemIndex);
ini.WriteInteger('MainForm', 'DaysCombo', DaysCombo.ItemIndex);
ini.WriteInteger('MainForm', 'WeeksCombo', WeeksCombo.ItemIndex);
ini.WriteBool('Settings', 'StartToday', GlobalSettings.StartToday);
ini.WriteDate('Settings', 'StartDate', GlobalSettings.StartDate);
ini.WriteBool('Settings', 'Hr2400', GlobalSettings.Hr2400);
ini.WriteInteger('Settings', 'FirstDayOfWeek', ord(GlobalSettings.FirstDayOfWeek));
ini.WriteTime('Settings', 'PrimeTimeStart', GlobalSettings.PrimeTimeStart);
ini.WriteTime('Settings', 'PrimeTimeEnd', GlobalSettings.PrimeTimeEnd);
ini.WriteInteger('Settings', 'PrimeTimeColor', GlobalSettings.PrimeTimeColor);
ini.WriteInteger('Settings', 'IconSet', GlobalSettings.IconSet);
finally
ini.Free;
end;
end;
end.
|
unit wcrypt_lite;
interface
uses
Windows;
{Описания для Windows Crypto-API}
const
PROV_RSA_FULL = 1;
CRYPT_VERIFYCONTEXT = $F0000000;
ALG_CLASS_HASH = (4 shl 13);
ALG_TYPE_ANY = 0;
ALG_SID_SHA = 4;
CALG_SHA = (ALG_CLASS_HASH or ALG_TYPE_ANY or ALG_SID_SHA);
HP_HASHVAL = $0002; // Hash value
type
HCRYPTPROV = ULONG;
PHCRYPTPROV = ^HCRYPTPROV;
HCRYPTHASH = ULONG;
PHCRYPTHASH = ^HCRYPTHASH;
HCRYPTKEY = ULONG;
{$IFDEF UNICODE}
LPAWSTR = PWideChar;
{$ELSE}
LPAWSTR = PAnsiChar;
{$ENDIF}
ALG_ID = ULONG;
function CryptAcquireContextA(phProv :PHCRYPTPROV;
pszContainer :PAnsiChar;
pszProvider :PAnsiChar;
dwProvType :DWORD;
dwFlags :DWORD) :BOOL;stdcall;
function CryptAcquireContext(phProv :PHCRYPTPROV;
pszContainer :LPAWSTR;
pszProvider :LPAWSTR;
dwProvType :DWORD;
dwFlags :DWORD) :BOOL;stdcall;
function CryptAcquireContextW(phProv :PHCRYPTPROV;
pszContainer :PWideChar;
pszProvider :PWideChar;
dwProvType :DWORD;
dwFlags :DWORD) :BOOL ;stdcall;
function CryptCreateHash(hProv :HCRYPTPROV;
Algid :ALG_ID;
hKey :HCRYPTKEY;
dwFlags :DWORD;
phHash :PHCRYPTHASH) :BOOL;stdcall;
function CryptHashData(hHash :HCRYPTHASH;
const pbData :PBYTE;
dwDataLen :DWORD;
dwFlags :DWORD) :BOOL;stdcall;
function CryptGetHashParam(hHash :HCRYPTHASH;
dwParam :DWORD;
pbData :PBYTE;
pdwDataLen :PDWORD;
dwFlags :DWORD) :BOOL;stdcall;
function CryptDestroyHash(hHash :HCRYPTHASH) :BOOL;stdcall;
function CryptReleaseContext(hProv :HCRYPTPROV;
dwFlags :DWORD) :BOOL;stdcall;
implementation
function CryptAcquireContextA ;external ADVAPI32 name 'CryptAcquireContextA';
{$IFDEF UNICODE}
function CryptAcquireContext ;external ADVAPI32 name 'CryptAcquireContextW';
{$ELSE}
function CryptAcquireContext ;external ADVAPI32 name 'CryptAcquireContextA';
{$ENDIF}
function CryptAcquireContextW ;external ADVAPI32 name 'CryptAcquireContextW';
function CryptCreateHash ;external ADVAPI32 name 'CryptCreateHash';
function CryptHashData ;external ADVAPI32 name 'CryptHashData';
function CryptGetHashParam ;external ADVAPI32 name 'CryptGetHashParam';
function CryptDestroyHash ;external ADVAPI32 name 'CryptDestroyHash';
function CryptReleaseContext ;external ADVAPI32 name 'CryptReleaseContext';
end. |
unit ClassMapa;
interface
uses ExtCtrls, Classes, Controls, Windows, Graphics, Forms, ClassData,
ClassHladanie;
type TBackground = record
Src, Dest : TRect;
Bitmap : TBitmap;
end;
TMapa = class
private
Mapa : TImage;
ScrollBox : TScrollBox;
Povodny : TBitmap;
ImageList : TImageList;
PodZastavkou : TBackground;
PodStart, PodFinish : TBackground;
AllowLookAt : boolean;
FShowSpoj : PSpoj;
FLookAt : TPoint;
FShowZast : PZastavka;
FShowRes : PVysledok;
FStart : TPoint;
FFinish : TPoint;
procedure SetShowSpoj( Value : PSpoj );
procedure SetLookAt( Value : TPoint );
procedure SetShowZast( Value : PZastavka );
procedure SetShowRes( Value : PVysledok );
procedure SetStart( Value : TPoint );
procedure SetFinish( Value : TPoint );
procedure Repaint( Clear : boolean );
procedure PaintSpoj;
procedure PaintZastavka( PZast : PZastavka );
public
constructor Create( iMapa : TImage; iScrollBox : TScrollBox; iImageList : TImageList );
destructor Destroy; override;
procedure LookAtNearest( Point : TPoint );
property ShowZast : PZastavka read FShowZast write SetShowZast;
property ShowSpoj : PSpoj read FShowSpoj write SetShowSpoj;
property ShowRes : PVysledok read FShowRes write SetShowRes;
property LookAt : TPoint read FLookAt write SetLookAt;
property Start : TPoint read FStart write SetStart;
property Finish : TPoint read FFinish write SetFinish;
end;
var Mapa : TMapa;
implementation
uses Konstanty;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TMapa.Create( iMapa : TImage; iScrollBox : TScrollBox; iImageList : TImageList );
begin
inherited Create;
Mapa := iMapa;
ScrollBox := iScrollBox;
ImageList := iImageList;
// Mapa
Mapa.Picture.Bitmap.LoadFromFile( MAP_FILE );
Mapa.Width := Mapa.Picture.Width;
Mapa.Height := Mapa.Picture.Height;
Povodny := TBitmap.Create;
Povodny.Assign( Mapa.Picture.Bitmap );
PodZastavkou.Bitmap := TBitmap.Create;
AllowLookAt := True;
FShowSpoj := nil;
FShowRes := nil;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TMapa.Destroy;
begin
Povodny.Free;
PodZastavkou.Bitmap.Free;
if (PodStart.Bitmap <> nil) then
PodStart.Bitmap.Free;
inherited;
end;
//==============================================================================
//==============================================================================
//
// Private
//
//==============================================================================
//==============================================================================
procedure TMapa.PaintZastavka( PZast : PZastavka );
begin
if PZast = nil then exit;
with Mapa.Canvas do
begin
if (PZast = FShowZast) then
begin
Pen.Color := clWhite;
Pen.Width := 1;
Brush.Color := clBlack;
Font.Color := clWhite;
end
else
begin
Pen.Color := clBlack;
Pen.Width := 1;
Brush.Color := clWhite;
Font.Color := clBlack;
end;
Font.Style := [fsBold];
Ellipse( PZast^.Sur.X - 3 ,
PZast^.Sur.Y - 3 ,
PZast^.Sur.X + 3 ,
PZast^.Sur.Y + 3 );
Rectangle( PZast^.Sur.X + 5 ,
PZast^.Sur.Y - 5 ,
PZast^.Sur.X + 15 +
TextWidth( PZast^.Nazov ) ,
PZast^.Sur.Y + 10 );
TextOut( PZast^.Sur.X + 10 ,
PZast^.Sur.Y - 4 ,
PZast^.Nazov );
end;
end;
procedure TMapa.PaintSpoj;
var Spoj : PSpoj;
begin
with Mapa.Canvas do
begin
Pen.Color := clBlack;
Pen.Width := 3;
end;
Spoj := ShowSpoj;
while Spoj <> nil do
begin
if Spoj = ShowSpoj then
Mapa.Canvas.MoveTo( Spoj^.NaZastavke^.Sur.X , Spoj^.NaZastavke^.Sur.Y )
else
Mapa.Canvas.LineTo( Spoj^.NaZastavke^.Sur.X , Spoj^.NaZastavke^.Sur.Y );
Spoj := Spoj^.Next;
end;
Spoj := ShowSpoj;
while Spoj <> nil do
begin
PaintZastavka( Spoj^.NaZastavke );
Spoj := Spoj^.Next;
end;
end;
procedure TMapa.Repaint( Clear : boolean );
begin
Screen.Cursor := crHourGlass;
try
// Zmazanie obrazovky
if Clear then
Mapa.Picture.Bitmap.Assign( Povodny );
// Nakreslenie vybraneho spoja
if ShowSpoj <> nil then
PaintSpoj;
finally
Screen.Cursor := crDefault;
end;
end;
//==============================================================================
//==============================================================================
//
// Properties
//
//==============================================================================
//==============================================================================
procedure TMapa.SetShowSpoj( Value : PSpoj );
var NeedClear : boolean;
begin
if (FShowSpoj = Value) then exit;
if (FShowSpoj = nil) then NeedClear := False
else NeedClear := True;
FShowSpoj := Value;
if ShowZast <> nil then
ShowZast := nil;
Repaint( NeedClear );
if (FShowSpoj <> nil) then
LookAt := FShowSpoj^.NaZastavke^.Sur;
end;
procedure TMapa.SetLookAt( Value : TPoint );
begin
FLookAt := Value;
ScrollBox.HorzScrollBar.Position := FLookAt.X - (ScrollBox.ClientWidth div 2);
ScrollBox.VertScrollBar.Position := FLookAt.Y - (ScrollBox.ClientHeight div 2);
end;
procedure TMapa.SetShowZast( Value : PZastavka );
begin
if (FShowZast = Value) then exit;
Screen.Cursor := crHourGlass;
try
if (FShowZast <> nil) then
Mapa.Canvas.CopyRect( PodZastavkou.Src , PodZastavkou.Bitmap.Canvas , PodZastavkou.Dest );
FShowZast := Value;
if (FShowZast = nil) then exit;
PodZastavkou.Bitmap.Canvas.Font.Style := [fsBold];
with PodZastavkou.Src do
begin
Left := FShowZast^.Sur.X-3;
Top := FShowZast^.Sur.Y-5;
Right := FShowZast^.Sur.X+15+PodZastavkou.Bitmap.Canvas.TextWidth( FShowZast^.Nazov );
Bottom := FShowZast^.Sur.Y+10;
end;
with PodZastavkou.Dest do
begin
Left := 0;
Top := 0;
Right := PodZastavkou.Src.Right - PodZastavkou.Src.Left;
Bottom := PodZastavkou.Src.Bottom - PodZastavkou.Src.Top;
end;
PodZastavkou.Bitmap.Width := PodZastavkou.Dest.Right;
PodZastavkou.Bitmap.Height := PodZastavkou.Dest.Bottom;
PodZastavkou.Bitmap.Canvas.CopyRect( PodZastavkou.Dest , Mapa.Canvas , PodZastavkou.Src );
PaintZastavka( FShowZast );
if AllowLookAt then
LookAt := FShowZast^.Sur;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TMapa.SetShowRes( Value : PVysledok );
const C : array[0..2] of TColor = (clNavy,clOlive,clAqua);
var I, J : integer;
Z : PZastavka;
S : PSpoj;
procedure Spoj( A, B : TPoint; Farba : TColor; PenStyle : TPenStyle );
begin
with Mapa.Canvas do
begin
Pen.Width := 3;
Pen.Color := Farba;
Pen.Style := PenStyle;
Brush.Color := Farba;
if not ((A.X = B.X) and (A.Y = B.Y)) then
begin
MoveTo( A.X , A.Y );
LineTo( B.X , B.Y );
end;
Ellipse( A.X-2 , A.Y-2 , A.X+2 , A.Y+2 );
Pen.Style := psSolid;
end;
end;
begin
if (Value = FShowRes) then exit;
FShowRes := Value;
Screen.Cursor := crHourGlass;
try
ShowZast := nil;
if (ShowSpoj = nil) then Mapa.Picture.Bitmap.Assign( Povodny )
else ShowSpoj := nil;
if (FShowRes = nil) then exit;
if FShowRes^.FreePoint then Spoj( FShowRes^.A , FShowRes^.Zaciatok^.Sur , C[2] , psDot );
Z := nil;
for I := 0 to Length( FShowRes^.Prestupy )-1 do
begin
if (Z <> nil) and
(Z <> FShowRes^.Prestupy[I].Zaciatok^.NaZastavke) then
Spoj( Z^.Sur , FShowRes^.Prestupy[I].Zaciatok^.NaZastavke^.Sur , C[2] , psDot );
S := FShowRes^.Prestupy[I].Zaciatok;
J := 1;
while (S <> nil) and (J <= FShowRes^.Prestupy[I].Zastavky) do
begin
if (S^.Next <> nil) then
Spoj( S^.NaZastavke^.Sur , S^.Next^.NaZastavke^.Sur , C[I mod 2] , psSolid )
else
Spoj( S^.NaZastavke^.Sur , S^.NaZastavke^.Sur , C[I mod 2] , psSolid );
PaintZastavka( S^.NaZastavke );
S := S^.Next;
Inc( J );
end;
end;
PaintZastavka( FShowRes^.Koniec );
if FShowRes^.FreePoint then Spoj( FShowRes^.B , FShowRes^.Koniec^.Sur , C[2] , psDot );
LookAt := FShowRes^.Zaciatok^.Sur;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TMapa.LookAtNearest( Point : TPoint );
var I, Min : integer;
R : integer;
Zast : PZastavka;
begin
Screen.Cursor := crHourGlass;
try
Min := -1;
Zast := nil;
for I := 0 to Data.Zastavky.Count-1 do
begin
R := Round( Sqrt( Sqr(Point.X-TZastavka(Data.Zastavky[I]^).Sur.X) + Sqr(Point.Y-TZastavka(Data.Zastavky[I]^).Sur.Y) ) );
if (I = 0) or
(R < Min) then
begin
Min := R;
Zast := Data.Zastavky[I];
end;
end;
if Zast <> nil then
begin
AllowLookAt := False;
ShowZast := Zast;
AllowLookAt := True;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TMapa.SetStart( Value : TPoint );
var BMP : TBitmap;
begin
FStart := Value;
// Zmaz zobrazenu zastavku
ShowZast := nil;
// Zmaz zobrazeny rozvrh
ShowSpoj := nil;
// Zmaz zobrazeny vysledok
ShowRes := nil;
// Zmaz predchadzajuci start
if (PodStart.Bitmap <> nil) then
Mapa.Canvas.CopyRect( PodStart.Dest , PodStart.Bitmap.Canvas , PodStart.Src );
if (FStart.X = -1) and
(FStart.Y = -1) then
begin
if (PodStart.Bitmap <> nil) then
begin
PodStart.Bitmap.Free;
PodStart.Bitmap := nil;
end;
exit;
end;
BMP := TBitmap.Create;
try
ImageList.GetBitmap( 4 , BMP );
BMP.TransparentColor := BMP.Canvas.Pixels[0,0];
with PodStart.Src do
begin
Left := 0;
Right := BMP.Width;
Top := 0;
Bottom := BMP.Height;
end;
with PodStart.Dest do
begin
Left := FStart.X - (BMP.Width div 2);
Right := FStart.X + (BMP.Width div 2);
Top := FStart.Y - (BMP.Height div 2);
Bottom := FStart.Y + (BMP.Height div 2);
end;
if (PodStart.Bitmap = nil) then
PodStart.Bitmap := TBitmap.Create;
PodStart.Bitmap.Width := BMP.Width;
PodStart.Bitmap.Height := BMP.Height;
PodStart.Bitmap.Canvas.CopyRect( PodStart.Src , Povodny.Canvas , PodStart.Dest );
Mapa.Canvas.Draw( PodStart.Dest.Left , PodStart.Dest.Top , BMP );
finally
BMP.Free;
end;
end;
procedure TMapa.SetFinish( Value : TPoint );
var BMP : TBitmap;
begin
FFinish := Value;
// Zmaz zobrazenu zastavku
ShowZast := nil;
// Zmaz zobrazeny rozvrh
ShowSpoj := nil;
// Zmaz zobrazeny vysledok
ShowRes := nil;
// Zmaz predchadzajuci Finish
if (PodFinish.Bitmap <> nil) then
Mapa.Canvas.CopyRect( PodFinish.Dest , PodFinish.Bitmap.Canvas , PodFinish.Src );
if (FFinish.X = -1) and
(FFinish.Y = -1) then
begin
if (PodFinish.Bitmap <> nil) then
begin
PodFinish.Bitmap.Free;
PodFinish.Bitmap := nil;
end;
exit;
end;
BMP := TBitmap.Create;
try
ImageList.GetBitmap( 5 , BMP );
with PodFinish.Src do
begin
Left := 0;
Right := BMP.Width;
Top := 0;
Bottom := BMP.Height;
end;
with PodFinish.Dest do
begin
Left := FFinish.X - (BMP.Width div 2);
Right := FFinish.X + (BMP.Width div 2);
Top := FFinish.Y - (BMP.Height div 2);
Bottom := FFinish.Y + (BMP.Height div 2);
end;
if (PodFinish.Bitmap = nil) then
PodFinish.Bitmap := TBitmap.Create;
PodFinish.Bitmap.Width := BMP.Width;
PodFinish.Bitmap.Height := BMP.Height;
PodFinish.Bitmap.Canvas.CopyRect( PodFinish.Src , Povodny.Canvas , PodFinish.Dest );
Mapa.Canvas.CopyRect( PodFinish.Dest , BMP.Canvas , PodFinish.Src );
finally
BMP.Free;
end;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls,
TAGraph, {TASources,} TAExpressionSeries, TASeries, ImportPolynomial, TADrawUtils, TACustomSeries;
type
{ TForm1 }
TForm1 = class(TForm)
Chart: TChart;
SecantSeries: TLineSeries;
PolynomialSeries: TLineSeries;
DerivationSeries: TLineSeries;
TangentSeries: TLineSeries;
Memo1: TMemo;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
procedure ChartLineSeries2CustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
procedure TangentSeriesCustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
procedure PolynomialSeriesCustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
XMin, XMax, DX, TangentPos: Extended;
procedure CalculatePolynomial;
public
Polynomial: TPolynomial;
end;
var
Form1: TForm1;
implementation
uses FormEx;
{$R *.lfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
FormAdjust(Self);
with Memo1.Lines do begin
Clear;
Add(Format('CreatePolynomial %p', [CreatePolynomial]));
Add(Format('CreateCopy %p', [CreateCopy]));
Add(Format('DestroyPolynomial %p', [DestroyPolynomial]));
Add(Format('GetDegree %p', [GetDegree]));
Add(Format('SetDegree %p', [SetDegree]));
Add(Format('GetCoefficient %p', [GetCoefficient]));
Add(Format('SetCoefficient %p', [SetCoefficient]));
Add(Format('GetPolynomialValue %p', [GetPolynomialValue]));
Add(Format('GetDerivation %p', [GetDerivation]));
Add(Format('GetSecant %p', [GetSecant]));
Add(Format('GetTangent %p', [GetTangent]))
end;
Xmin := -5; Xmax := 5; DX := 0.1; TangentPos := -2;
Polynomial := CreatePolynomial();
SetDegree(Polynomial, 3);
SetCoefficient(Polynomial, 0, 4);
SetCoefficient(Polynomial, 1, -6);
SetCoefficient(Polynomial, 2, -4);
SetCoefficient(Polynomial, 3, 1);
CalculatePolynomial;
end;
procedure TForm1.PolynomialSeriesCustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
begin
end;
procedure TForm1.ChartLineSeries2CustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
begin
end;
procedure TForm1.TangentSeriesCustomDrawPointer(ASender: TChartSeries;
ADrawer: IChartDrawer; AIndex: Integer; ACenter: TPoint);
begin
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
DestroyPolynomial(Polynomial)
end;
procedure TForm1.CalculatePolynomial;
var
x, y: Double;
D, S, T: TPolynomial;
begin
x := XMin;
D := GetDerivation(Polynomial, 1); {first Derivation}
S := GetSecant(Polynomial, -3, 0);
T := GetTangent(Polynomial, TangentPos); {Tangent at x = TangentPos}
while x < Xmax do begin
y := GetPolynomialValue(Polynomial, x);
PolynomialSeries.AddXY(x, y);
y := GetPolynomialValue(D, x);
DerivationSeries.AddXY(x, y);
y := GetPolynomialValue(S, x);
SecantSeries.AddXY(x, y);
y := GetPolynomialValue(T, x);
TangentSeries.AddXY(x, y);
x := x + DX
end;
end;
end.
|
unit servmain;
{ This program represents the "Application Server" portion of the
distributed datasets demo. The other part is the client which will access
the data provided by this server. You must compile and run this program
once before running the EmpEdit project. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Grids, DBGrids, Db;
type
TMainForm = class(TForm)
Panel1: TPanel;
QueryCount: TLabel;
ClientCount: TLabel;
private
FQueryCount: Integer;
FClientCount: Integer;
public
procedure UpdateClientCount(Incr: Integer);
procedure IncQueryCount;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
{ These procedures update the display of the application server form for
the purposes of this demo. A typical Application Server would probably
not have any visible UI. You can add a line of to the project file to
prevent the application server icon from being displayed on the taskbar. }
procedure TMainForm.UpdateClientCount(Incr: Integer);
begin
FClientCount := FClientCount + Incr;
ClientCount.Caption := IntToStr(FClientCount);
end;
procedure TMainForm.IncQueryCount;
begin
Inc(FQueryCount);
QueryCount.Caption := IntToStr(FQueryCount);
end;
end.
|
unit PropertyObj;
interface
uses
PropertyStyle;
type TProperty = class
private
FName: string;
FStyle: TPropertyStyle;
function getName: string;
procedure setName(const aName: string);
function getStyle: TPropertyStyle;
procedure setStyle(const aStyle: TPropertyStyle);
published
property name: string read getName write setName;
property style: TPropertyStyle read getStyle write setStyle;
public
constructor Create; overload;
constructor Create(const aName: string; const aStyle: TPropertyStyle); overload;
destructor Destroy; override;
end;
implementation
{ TProperty }
constructor TProperty.Create;
begin
inherited Create;
name := '';
style := TPropertyStyle.psInteger;
end;
constructor TProperty.Create(const aName: string; const aStyle: TPropertyStyle);
begin
inherited Create;
name := aName;
style := aStyle;
end;
destructor TProperty.Destroy;
begin
inherited Destroy;
end;
function TProperty.getName: string;
begin
result := FName;
end;
function TProperty.getStyle: TPropertyStyle;
begin
result := FStyle;
end;
procedure TProperty.setName(const aName: string);
begin
FName := aName;
end;
procedure TProperty.setStyle(const aStyle: TPropertyStyle);
begin
FStyle := aStyle;
end;
end.
|
unit FMXColors.Main;
interface
uses
System.SysUtils, Winapi.Windows, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types,
FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Colors, FMX.Controls.Presentation, FMX.Layouts,
FMX.ListBox, FMX.Objects, FMX.Effects, FMX.TabControl, FMX.Edit, System.ImageList, FMX.ImgList;
type
TMagnify = array[0..256, 0..256] of TAlphaColor;
TFormMain = class(TForm)
LayoutLeftSide: TLayout;
Rectangle5: TRectangle;
LayoutHead: TLayout;
Rectangle6: TRectangle;
LayoutRightSide: TLayout;
Rectangle7: TRectangle;
LayoutTabs: TLayout;
StyleBook1: TStyleBook;
ListBoxPins: TListBox;
ListBoxItem1: TListBoxItem;
Rectangle8: TRectangle;
LayoutClient: TLayout;
Rectangle9: TRectangle;
ListBoxItem2: TListBoxItem;
Rectangle10: TRectangle;
Path1: TPath;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
Layout5: TLayout;
ShadowEffect1: TShadowEffect;
ColorQuad: TColorQuad;
Layout6: TLayout;
HueTrackBar: THueTrackBar;
AlphaTrackBar: TAlphaTrackBar;
GradientEdit1: TGradientEdit;
Layout1: TLayout;
Layout2: TLayout;
ColorBox: TColorBox;
Layout3: TLayout;
Layout4: TLayout;
Layout7: TLayout;
Line1: TLine;
Label1: TLabel;
EditResHEX: TEdit;
Layout8: TLayout;
Rectangle1: TRectangle;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
SpeedButton4: TSpeedButton;
SpeedButtonQuit: TSpeedButton;
Line2: TLine;
SpeedButton5: TSpeedButton;
SpeedButton6: TSpeedButton;
SpeedButton7: TSpeedButton;
Label2: TLabel;
EditRGB_R: TEdit;
EditRGB_G: TEdit;
EditRGB_B: TEdit;
SpinEditButton1: TSpinEditButton;
SpinEditButton2: TSpinEditButton;
SpinEditButton3: TSpinEditButton;
SpinEditButton4: TSpinEditButton;
Label3: TLabel;
EditCMYK_C: TEdit;
SpinEditButton5: TSpinEditButton;
EditCMYK_M: TEdit;
SpinEditButton6: TSpinEditButton;
EditCMYK_Y: TEdit;
SpinEditButton7: TSpinEditButton;
EditCMYK_K: TEdit;
SpinEditButton8: TSpinEditButton;
SpeedButtonMenu: TSpeedButton;
SpeedButton9: TSpeedButton;
Label4: TLabel;
EditRGB: TEdit;
SpinEditButton9: TSpinEditButton;
Label5: TLabel;
EditResTColor: TEdit;
SpinEditButton10: TSpinEditButton;
Label6: TLabel;
EditHSV_H: TEdit;
SpinEditButton11: TSpinEditButton;
EditHSV_S: TEdit;
SpinEditButton12: TSpinEditButton;
EditHSV_V: TEdit;
SpinEditButton13: TSpinEditButton;
Label7: TLabel;
EditResTAlphaColor: TEdit;
SpinEditButton14: TSpinEditButton;
ListBoxItem3: TListBoxItem;
Rectangle2: TRectangle;
ListBoxItem4: TListBoxItem;
Rectangle3: TRectangle;
ListBoxItem5: TListBoxItem;
Rectangle4: TRectangle;
ListBoxItem6: TListBoxItem;
Rectangle11: TRectangle;
ListBoxItem7: TListBoxItem;
Rectangle12: TRectangle;
ListBoxItem8: TListBoxItem;
Rectangle13: TRectangle;
TimerPXUC: TTimer;
PaintBoxMagnify: TPaintBox;
Layout9: TLayout;
procedure Rectangle6MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure HueTrackBarChange(Sender: TObject);
procedure AlphaTrackBarChange(Sender: TObject);
procedure SpeedButtonQuitClick(Sender: TObject);
procedure EditCMYK_KValidating(Sender: TObject; var Text: string);
procedure SpeedButton5Click(Sender: TObject);
procedure SpeedButton6Click(Sender: TObject);
procedure ColorQuadChange(Sender: TObject);
procedure EditRGBValidating(Sender: TObject; var Text: string);
procedure TimerPXUCTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditHSV_HValidating(Sender: TObject; var Text: string);
procedure PaintBoxMagnifyPaint(Sender: TObject; Canvas: TCanvas);
procedure ListBoxPinsViewportPositionChange(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
procedure FormDestroy(Sender: TObject);
private
FDataColor: TAlphaColor;
FMagnifyPoint: TPointF;
FMagnifySize: TSize;
FKeepColor: Boolean;
FMgEmpty: Boolean;
FMagnify: TBitmap;
FSettingColor: Boolean;
procedure SetDataColor(const Value: TAlphaColor);
function GetPixelUnderCursor: TColor;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses
System.Math, HGM.Utils.Color, HGM.Screenshot, System.UIConsts;
{$R *.fmx}
function CtrlDown: Boolean;
begin
Result := GetKeyState(VK_CONTROL) < 0;
end;
function ShiftDown: Boolean;
begin
Result := GetKeyState(VK_SHIFT) < 0;
end;
function TFormMain.GetPixelUnderCursor: TColor;
var
DC: HDC;
Cur: TPoint;
Stream: TMemoryStream;
begin
DC := GetDC(0);
GetCursorPos(Cur);
FMagnifyPoint := Cur;
Result := GetPixel(DC, Cur.X, Cur.Y);
Stream := TMemoryStream.Create;
try
TakeScreenshot(Stream);
finally
FMagnify.LoadFromStream(Stream);
Stream.Free;
end;
FMgEmpty := False;
PaintBoxMagnify.Repaint;
end;
procedure TFormMain.AlphaTrackBarChange(Sender: TObject);
begin
ColorQuad.Alpha := AlphaTrackBar.Value;
end;
procedure TFormMain.ColorQuadChange(Sender: TObject);
begin
SetDataColor(ColorBox.Color);
end;
procedure TFormMain.EditCMYK_KValidating(Sender: TObject; var Text: string);
var
I: Integer;
begin
if not TryStrToInt(Text, I) then
Text := (Sender as TEdit).Text
else
Text := Max(0, Min(I, 255)).ToString;
end;
procedure TFormMain.EditHSV_HValidating(Sender: TObject; var Text: string);
var
I: Integer;
begin
if not TryStrToInt(Text, I) then
Text := (Sender as TEdit).Text
else
Text := Max(0, Min(I, 360)).ToString;
end;
procedure TFormMain.EditRGBValidating(Sender: TObject; var Text: string);
var
I: Integer;
begin
if not TryStrToInt(Text, I) then
Text := (Sender as TEdit).Text
else
Text := Max(0, Min(I, MaxLongInt)).ToString;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
FMagnify := TBitmap.Create;
FMagnifySize := TSize.Create(5, 5);
FKeepColor := False;
FMgEmpty := True;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
FMagnify.Free;
end;
procedure TFormMain.HueTrackBarChange(Sender: TObject);
begin
ColorQuad.Hue := HueTrackBar.Value;
end;
procedure TFormMain.ListBoxPinsViewportPositionChange(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
var
i: Integer;
begin
if ListBoxPins.ContentBounds.Bottom - (NewViewportPosition.Y + ListBoxPins.Height) <= 0 then
begin
for i := 1 to 20 do
ListBoxPins.Items.Add('');
end;
end;
procedure TFormMain.PaintBoxMagnifyPaint(Sender: TObject; Canvas: TCanvas);
var
PixW: Single;
R: TRectF;
S: string;
x, y: Integer;
begin
Canvas.BeginScene;
if FMgEmpty then
begin
R := PaintBoxMagnify.ClipRect;
S := 'Ctrl+Shift';
Canvas.FillText(R, S, False, 1, [], TTextAlign.Center, TTextAlign.Center);
end
else
begin
Canvas.DrawBitmap(FMagnify,
TRectF.Create(TPointF.Create(FMagnifyPoint.X - FMagnifySize.Width div 2,
FMagnifyPoint.Y - FMagnifySize.Height div 2),
FMagnifySize.Width, FMagnifySize.Height),
TRectF.Create(0, 0, PaintBoxMagnify.Width, PaintBoxMagnify.Height),
1, True);
PixW := PaintBoxMagnify.Width / FMagnifySize.Width;
R.Width := Ceil(PixW);
R.Height := Ceil(PixW);
R.Location := Point(Round((PixW * FMagnifySize.Width / 2) - (PixW / 2)), Round((PixW * FMagnifySize.Width / 2) - (PixW / 2)));
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.Stroke.Color := TAlphaColorRec.Black;
Canvas.DrawRect(R, 0, 0, [], 1);
end;
Canvas.EndScene;
end;
procedure TFormMain.Rectangle6MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
StartWindowDrag;
end;
procedure TFormMain.SpeedButton5Click(Sender: TObject);
begin
TabControl1.ActiveTab := TabItem1;
end;
procedure TFormMain.SpeedButton6Click(Sender: TObject);
begin
TabControl1.ActiveTab := TabItem2;
end;
procedure TFormMain.SpeedButtonQuitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFormMain.TimerPXUCTimer(Sender: TObject);
var
AC: TAlphaColorF;
begin
if (CtrlDown and ShiftDown) or FKeepColor then
begin
AC := TAlphaColorF.Create(RGBtoBGR(GetPixelUnderCursor));
AC.A := 1;
SetDataColor(AC.ToAlphaColor);
end;
end;
procedure TFormMain.SetDataColor(const Value: TAlphaColor);
var
C, M, Y, K, R, G, B: Byte;
H, V, S: Double;
nH, nL, nS: Single;
FColor: TColor;
begin
if FSettingColor then
Exit;
FSettingColor := True;
FDataColor := Value;
FColor := AlphaColorToColor(Value);
R := ColorToRGB(FColor).R;
G := ColorToRGB(FColor).G;
B := ColorToRGB(FColor).B;
//TrackBarL.Position := 100;
EditRGB_R.Text := R.ToString;
EditRGB_G.Text := G.ToString;
EditRGB_B.Text := B.ToString;
EditRGB.Text := ColorToRGB(RGBToColor(R, G, B));
//
EditResHEX.Text := ColorToHtml(FColor);
EditResTColor.Text := ColorToString(FColor);
EditResTAlphaColor.Text := AlphaColorToString(FDataColor);
RGBToCMYK(R, G, B, C, M, Y, K);
EditCMYK_C.Text := C.ToString;
EditCMYK_M.Text := M.ToString;
EditCMYK_Y.Text := Y.ToString;
EditCMYK_K.Text := K.ToString;
RGBToHSV(R, G, B, H, S, V);
EditHSV_H.Text := Round(H).ToString;
EditHSV_S.Text := Round(S).ToString;
EditHSV_V.Text := Round(V).ToString;
RGBtoHSL(FDataColor, nH, nS, nL);
HueTrackBar.Value := nH;
ColorQuad.Sat := nS;
ColorQuad.Lum := nL;
ColorBox.Color := FDataColor;
//HexaColorPicker1.SelectedColor := FDataColor;
//HSColorPicker1.SelectedColor := FDataColor;
//HSVColorPicker1.SelectedColor := FDataColor;
//if Assigned(FActiveShape) then
// FActiveShape.Brush.Color := FDataColor;
FSettingColor := False;
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Performance;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf,
ADAPT.Collections.Intf,
ADAPT.Performance.Intf;
{$I ADAPT_RTTI.inc}
type
{ Class Forward Declarations }
TADPerformanceCounter = class;
/// <summary><c>Non-Threadsafe Performance Counter Type.</c></summary>
/// <remarks>
/// <para><c>Keeps track of Performance both Instant and Average, in units of Things Per Second.</c></para>
/// <para><c>Note that this does NOT operate like a "Stopwatch", it merely takes the given Time Difference (Delta) Values to calculate smooth averages.</c></para>
/// <para><c>CAUTION - THIS CLASS IS NOT THREADSAFE.</c></para>
/// </remarks>
TADPerformanceCounter = class(TADObject, IADPerformanceCounter)
protected
FAverageOver: Cardinal;
FAverageRate: ADFloat;
FInstantRate: ADFloat;
/// <summary><c>A humble Dynamic Array, fixed to the specified "Average Over" value, containing each Sample used to determine the Average Rate.</c></summary>
FSamples: IADCircularList<ADFloat>;
{ Getters }
function GetAverageOver: Cardinal; virtual;
function GetAverageRate: ADFloat; virtual;
function GetInstantRate: ADFloat; virtual;
{ Setters }
procedure SetAverageOver(const AAverageOver: Cardinal = 10); virtual;
public
constructor Create(const AAverageOver: Cardinal); reintroduce; virtual;
procedure AfterConstruction; override;
procedure RecordSample(const AValue: ADFloat); virtual;
procedure Reset; virtual;
/// <summary><c>The number of Samples over which to calculate the Average</c></summary>
property AverageOver: Cardinal read GetAverageOver write SetAverageOver;
/// <summary><c>The Average Rate (based on the number of Samples over which to calculate it)</c></summary>
property AverageRate: ADFloat read GetAverageRate;
/// <summary><c>The Instant Rate (based only on the last given Sample)</c></summary>
property InstantRate: ADFloat read GetInstantRate;
end;
/// <summary><c>Non-Threadsafe Performance Limiter Type.</c></summary>
/// <remarks>
/// <para><c>Enforces a given Performance Limit, handling all of the Delta Extrapolation Mathematics.</c></para>
/// <para><c>CAUTION - THIS CLASS IS NOT THREADSAFE.</c></para>
/// </remarks>
TADPerformanceLimiter = class(TADAggregatedObject, IADPerformanceLimiter)
private
FNextDelta: ADFloat;
FRateDesired: ADFloat;
FRateLimit: ADFloat;
FThrottleInterval: Cardinal;
protected
{ IADPerformanceLimiter Getters }
function GetNextDelta: ADFloat; virtual;
function GetRateDesired: ADFloat; virtual;
function GetRateLimit: ADFloat; virtual;
function GetThrottleInterval: Cardinal; virtual;
{ IADPerformanceLimiter Setters }
procedure SetRateDesired(const ARateDesired: ADFloat); virtual;
procedure SetRateLimit(const ARateLimit: ADFloat); virtual;
procedure SetThrottleInterval(const AThrottleInterval: Cardinal); virtual;
public
{ IADPerformanceLimiter Properties }
property NextDelta: ADFloat read GetNextDelta;
property RateDesired: ADFloat read GetRateDesired write SetRateDesired;
property RateLimit: ADFloat read GetRateLimit write SetRateLimit;
property ThrottleInterval: Cardinal read GetThrottleInterval write SetThrottleInterval;
end;
implementation
uses
ADAPT.Math.Averagers,
ADAPT.Collections;
{ TADPerformanceCounter }
procedure TADPerformanceCounter.AfterConstruction;
begin
inherited;
Reset;
end;
constructor TADPerformanceCounter.Create(const AAverageOver: Cardinal);
begin
inherited Create;
FAverageOver := AAverageOver;
FSamples := TADCircularList<ADFloat>.Create(AAverageOver);
end;
function TADPerformanceCounter.GetAverageOver: Cardinal;
begin
Result := FAverageOver;
end;
function TADPerformanceCounter.GetAverageRate: ADFloat;
begin
Result := FAverageRate;
end;
function TADPerformanceCounter.GetInstantRate: ADFloat;
begin
Result := FInstantRate;
end;
procedure TADPerformanceCounter.RecordSample(const AValue: ADFloat);
begin
FInstantRate := AValue; // Calculate Instant Rate
FSamples.Add(AValue);
FAverageRate := ADAveragerFloatMean.CalculateAverage(FSamples);
end;
procedure TADPerformanceCounter.Reset;
begin
FSamples.Clear;
FInstantRate := 0;
FAverageRate := 0;
end;
procedure TADPerformanceCounter.SetAverageOver(const AAverageOver: Cardinal);
begin
FAverageOver := AAverageOver;
FSamples.Capacity := AAverageOver;
end;
{ TADPerformanceLimiter }
function TADPerformanceLimiter.GetNextDelta: ADFloat;
begin
Result := FNextDelta;
end;
function TADPerformanceLimiter.GetRateDesired: ADFloat;
begin
Result := FRateDesired;
end;
function TADPerformanceLimiter.GetRateLimit: ADFloat;
begin
Result := FRateLimit;
end;
function TADPerformanceLimiter.GetThrottleInterval: Cardinal;
begin
Result := FThrottleInterval;
end;
procedure TADPerformanceLimiter.SetRateDesired(const ARateDesired: ADFloat);
begin
FRateDesired := ARateDesired;
end;
procedure TADPerformanceLimiter.SetRateLimit(const ARateLimit: ADFloat);
begin
FRateLimit := ARateLimit;
end;
procedure TADPerformanceLimiter.SetThrottleInterval(const AThrottleInterval: Cardinal);
begin
FThrottleInterval := AThrottleInterval;
end;
end.
|
unit uConexaoIntegracao;
interface
uses Data.DB, System.SysUtils, System.Classes, Datasnap.DBClient, Vcl.Forms,
FireDAC.Phys.FB, FireDAC.Phys.MySQL, FireDAC.Comp.UI, FireDAC.DApt, FireDAC.Comp.Client, Datasnap.Provider,
Dialogs, FireDAC.Comp.DataSet, uConexao;
type TConexaoIntegracao = class
private
_FdConn : TFDConnection;
_fdCursor : TFDGUIxWaitCursor;
_fdDriverFB : TFDPhysFBDriverLink;
_FdDriverMySql : TFDPhysMySQLDriverLink;
_fdQuery : TFDQuery;
_dsProvider : TDataSetProvider;
function trataException(AException: Exception): Boolean;
public
procedure configuraConexao(
ATipoConexao: TTipoConexao;
AServidor : string;
AAlias : string;
AUsuario : string;
ASenha : string;
APorta : String
);
procedure StartTransaction;
procedure Commit;
procedure RollBack;
function GetDataPacket(ASql: string): OleVariant;
function GetDataPacketFD(ASql: string): IFDDataSetReference;
function ExecSql(ASql: String): Boolean;
function ExecSqlAndCommit(ASql: String): Boolean;
function LeUltimoRegistro(TableName, FieldKey: String): Integer;
constructor create;
destructor destroy;
end;
var
Conexao : TConexaoIntegracao;
implementation
{ TConexaoPadrao }
procedure TConexaoIntegracao.Commit;
begin
_FdConn.Commit;
end;
procedure TConexaoIntegracao.configuraConexao(ATipoConexao: TTipoConexao; AServidor, AAlias, AUsuario, ASenha, APorta: String);
var
con : TConexao;
begin
try
try
con := TConexao.Create(ATipoConexao, AServidor, AAlias, AUsuario, ASenha, APorta, taIni, '');
con.configuraFDConnection(_FdConn);
except
on e: Exception do
raise Exception.Create('Erro ao configurar Conexão de integração: ' + e.Message);
end;
finally
FreeAndNil(con);
end;
end;
constructor TConexaoIntegracao.create;
begin
_FdConn := TFDConnection.Create(nil);
_fdCursor := TFDGUIxWaitCursor.Create(nil);
_fdDriverFB := TFDPhysFBDriverLink.Create(nil);
_FdDriverMySql := TFDPhysMySQLDriverLink.Create(nil);
_fdQuery := TFDQuery.Create(nil);
_fdQuery.FormatOptions.DataSnapCompatibility := True;
_fdQuery.Connection := _FdConn;
_dsProvider := TDataSetProvider.Create(nil);
_dsProvider.DataSet := _fdQuery;
_FdDriverMySql.VendorLib := ExtractFilePath(Application.ExeName) + '\libmysql.dll';
end;
destructor TConexaoIntegracao.destroy;
begin
if _fdQuery.Active then
_fdQuery.Close;
FreeAndNil(_dsProvider);
FreeAndNil(_fdQuery);
FreeAndNil(_fdDriverFB);
FreeAndNil(_fdCursor);
FreeAndNil(_FdConn);
end;
function TConexaoIntegracao.ExecSql(ASql: String): Boolean;
begin
result := False;
try
_fdQuery.SQL.Clear;
_fdQuery.SQL.Text := ASql;
_fdQuery.ExecSQL;
Result := True;
except
on e : Exception do
result := trataException(e);
end;
end;
function TConexaoIntegracao.ExecSqlAndCommit(ASql: String): Boolean;
begin
Result := False;
StartTransaction;
Result := ExecSql(ASql);
if Result then
Commit
else
RollBack;
end;
function TConexaoIntegracao.GetDataPacket(ASql: string): OleVariant;
begin
try
_fdQuery.Close;
_fdQuery.SQL.Text := ASql;
_fdQuery.Active := True;
result := _dsProvider.Data;
except
on e : Exception do
raise Exception.Create('Erro ao executar a instrução SQL: ' + Chr(13) + ASql + Chr(13) + e.Message);
end;
end;
function TConexaoIntegracao.GetDataPacketFD(ASql: string): IFDDataSetReference;
begin
try
_fdQuery.Close;
_fdQuery.SQL.Text := ASql;
_fdQuery.Active := True;
result := _fdQuery.Data;
except
on e : Exception do
raise Exception.Create('Erro ao executar a instrução SQL: ' + Chr(13) + ASql + Chr(13) + e.Message);
end;
end;
function TConexaoIntegracao.LeUltimoRegistro(TableName, FieldKey: String): Integer;
var
cds: TClientDataSet;
begin
try
cds := TClientDataSet.Create(nil);
cds.Data := GetDataPacket('SELECT MAX(' + FieldKey + ') AS CODIGO FROM ' + TableName );
if cds.FieldByName('CODIGO').AsString = '' then
result := 0
else
Result := cds.FieldByName('CODIGO').AsInteger;
cds.Free;
except
on e : Exception do
raise Exception.Create('Erro ao buscar Ultimo Registro. ' + e.Message);
end;
end;
procedure TConexaoIntegracao.RollBack;
begin
_FdConn.Rollback;
end;
procedure TConexaoIntegracao.StartTransaction;
begin
_FdConn.StartTransaction
end;
function TConexaoIntegracao.trataException(AException: Exception): Boolean;
begin
raise Exception.Create(AException.Message);
end;
end.
|
unit uDMNexLicGen;
interface
uses
SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPServer, SyncObjs,
IdCustomHTTPServer, IdHTTPServer, EXECryptorKeyGen, ncDebug;
type
TdmKeyGen = class(TDataModule)
H: TIdHTTPServer;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure HCommandGet(AThread: TIdPeerThread;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
private
{ Private declarations }
KG : TKeyGen;
public
{ Public declarations }
end;
var
dmKeyGen: TdmKeyGen;
CS : TCriticalSection;
implementation
{$R *.dfm}
function DataBaseLic: TDateTime;
begin
Result := EncodeDate(2003, 1, 1);
end;
function IsPremiumDateChar(C: Char): Boolean;
begin
Result := (C in ['G'..'V']);
end;
function HexToPremium(C: Char): Char;
begin
case C of
'0': Result := 'G';
'1': Result := 'H';
'2': Result := 'I';
'3': Result := 'J';
'4': Result := 'K';
'5': Result := 'L';
'6': Result := 'M';
'7': Result := 'N';
'8': Result := 'O';
'9': Result := 'P';
'A': Result := 'Q';
'B': Result := 'R';
'C': Result := 'S';
'D': Result := 'T';
'E': Result := 'U';
'F': Result := 'V';
else
Result := C;
end;
end;
function PremiumToHex(C: Char): Char;
begin
case C of
'G': Result := '0';
'H': Result := '1';
'I': Result := '2';
'J': Result := '3';
'K': Result := '4';
'L': Result := '5';
'M': Result := '6';
'N': Result := '7';
'O': Result := '8';
'P': Result := '9';
'Q': Result := 'A';
'R': Result := 'B';
'S': Result := 'C';
'T': Result := 'D';
'U': Result := 'E';
'V': Result := 'F';
else
Result := C;
end;
end;
function IsPremiumDate(D: String): Boolean;
begin
if Length(D)<4 then
Result := False
else begin
D := UpperCase(D);
Result := IsPremiumDateChar(D[1]) and
IsPremiumDateChar(D[2]) and
IsPremiumDateChar(D[3]) and
IsPremiumDateChar(D[4]);
end;
end;
function IsFreeDate(D: String): Boolean;
begin
Result := SameText(Copy(D, 1, 4), 'FREE'); // do not localize
end;
function IsPremiumOrFree(D: String): Boolean;
begin
Result := SameText(Copy(D, 1, 4), 'FREE') or IsPremiumDate(D); // do not localize
end;
function PremiumDateToDateLic(D: String): String;
begin
if IsPremiumDate(D) then
Result := PremiumToHex(D[1]) + PremiumToHex(D[2]) + PremiumToHex(D[3]) + PremiumToHex(D[4]) else
Result := D;
end;
function DateLicToPremiumDate(D: String): String;
begin
if Length(D)<4 then
Result := D else
Result := HexToPremium(D[1]) + HexToPremium(D[2]) + HexToPremium(D[3]) + HexToPremium(D[4]);
end;
function DateLicToDate(D: String): TDateTime;
begin
if SameText(Copy(D, 1, 4), 'FREE') then // do not localize
Result := 0 else
Result := DataBaseLic +
StrToIntDef('$'+PremiumDateToDateLic(D), 0);
end;
function DateToDateLic(D: TDateTime; aFreePremium: Boolean): String;
begin
if D<=DataBaseLic then
Result := '0000' // do not localize
else
Result := IntToHex(Trunc(D-DataBaseLic), 4);
if aFreePremium then
if (D=0) then
Result := 'FREE' else // do not localize
Result := DateLicToPremiumDate(Result);
end;
procedure TdmKeyGen.DataModuleCreate(Sender: TObject);
begin
KG := TKeyGen.Create(ExtractFilePath(ParamStr(0)));
H.Active := True;
end;
procedure TdmKeyGen.DataModuleDestroy(Sender: TObject);
begin
H.Active := False;
KG.Free;
end;
function DMAtoDate(S: String): TDateTime;
var D, M, A: Word;
begin
Result := 0;
if pos('/', S)<1 then Exit;
D := StrToIntDef(copy(S, 1, Pos('/', S)-1), 0);
Delete(S, 1, Pos('/', S));
M := StrToIntDef(copy(S, 1, Pos('/', S)-1), 0);
Delete(S, 1, Pos('/', S));
A := StrToIntDef(S, 0);
if (D<1) or (D>31) or (M<1) or (M>12) or (A<2000) or (A>9999) then Exit;
Result := EncodeDate(A, M, D);
end;
procedure TdmKeyGen.HCommandGet(AThread: TIdPeerThread;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
iTipo, iMaq, I : Integer;
Venc : TDateTime;
S, S2, sDebug : String;
begin
if ARequestInfo.Params.Count=0 then Exit;
try
iTipo := StrToIntDef(ARequestInfo.Params.Values['tipo'], 5);
if (iTipo<>5) and (iTipo<>2) then
iTipo := 5;
iMaq := StrToIntDef(ARequestInfo.Params.Values['maquinas'], 1);
Venc := DMAToDate(ARequestInfo.Params.Values['vencimento']);
with aRequestInfo do
if iTipo=5 then begin
S := DateToDateLic(Venc, True);
S2 := S;
iMaq := 1;
end else begin
if Venc=0 then Venc := DataBaseLic+1;
S := Trim(Params.Values['loja'])+'-'+FormatDateTime('dd/mm/yyyy', Venc);
S2 := DateToDateLic(Venc, False);
end;
CS.Enter;
try
S := S2 + '-' + KG.CreateSerialNumberEx(
ExtractFilePath(ParamStr(0))+'nexcafe.ep2', S,
False, False, False, False, False, False,
iTipo, iMaq, ARequestInfo.Params.Values['codequip']);
finally
CS.Leave;
end;
AResponseInfo.ContentText := S;
sDebug := '';
with aRequestInfo do
for I := 0 to Params.Count - 1 do begin
sDebug := sDebug + ', ';
sDebug := sDebug + Params.Names[I] + '=' + Params.ValueFromIndex[I];
end;
DebugMsgEsp('IP: '+ARequestInfo.RemoteIP+sDebug+', Resposta='+S, False, True);
except
on E: Exception do DebugMsgEsp('Exception: ' + E.Message, False, True);
end;
end;
initialization
CurrencyString := 'R$';
ThousandSeparator := '.';
DecimalSeparator := ',';
ShortDateFormat := 'dd/mm/yyyy';
nomearqdebug := 'NexLicGen_Debug.txt';
DebugAtivo := True;
CS := TCriticalSection.Create;
finalization
CS.Free;
end.
|
unit ncaFrmConfigNFE;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseOpcao, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, Vcl.StdCtrls, cxButtons,
LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxImageComboBox, cxDBEdit, cxLabel, Data.DB, kbmMemTable,
cxCheckBox, dxGDIPlusClasses, Vcl.ExtCtrls, cxButtonEdit, ncaFrmNCMPesq,
dxLayoutcxEditAdapters, dxLayoutContainer, dxLayoutControl, Vcl.Mask,
Vcl.DBCtrls, cxSpinEdit, dxLayoutLookAndFeels, cxClasses,
dxLayoutControlAdapters, dxBarBuiltInMenu, cxPC, ncaDocEdit, cxMemo, nxdb, ncClassesBase,
LMDBaseControl, LMDBaseGraphicControl, LMDBaseLabel, LMDCustomLabel, LMDLabel,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP;
type
TFrmConfigNFE = class(TFrmBaseOpcao)
panTopo: TLMDSimplePanel;
edEmitirNFCe: TcxDBCheckBox;
MT: TkbmMemTable;
MTEmitirNFCe: TBooleanField;
MTEmitirNFE: TBooleanField;
MTAutoPrintNFCe: TBooleanField;
MTCRT: TByteField;
MTModeloNFE: TStringField;
MTModeloNFCe: TStringField;
MTSerieNFCe: TStringField;
MTSerieNFe: TStringField;
MTInicioNFe: TLongWordField;
MTInicioNFCe: TLongWordField;
MTRazaoSocial: TStringField;
MTNomeFantasia: TStringField;
MTCNPJ: TStringField;
MTIE: TStringField;
MTEnd_Logradouro: TStringField;
MTEnd_Numero: TStringField;
MTEnd_Bairro: TStringField;
MTEnd_UF: TStringField;
MTEnd_CEP: TStringField;
MTEnd_Municipio: TStringField;
MTEnd_CodMun: TStringField;
MTEnd_CodUF: TByteField;
MTTelefone: TStringField;
DS: TDataSource;
btnPremium: TcxButton;
MTMostrarDadosNFE: TBooleanField;
MTPedirEmail: TByteField;
MTPedirCPF: TByteField;
img: TImage;
edSerieNFCE: TcxDBTextEdit;
lcSerieNFCE: TdxLayoutItem;
edInicioNFCE: TcxDBSpinEdit;
lcInicioNFCE: TdxLayoutItem;
edLogr: TcxDBTextEdit;
LCItem1: TdxLayoutItem;
edNumero: TcxDBTextEdit;
LCItem3: TdxLayoutItem;
edBairro: TcxDBTextEdit;
LCItem4: TdxLayoutItem;
edCEP: TcxDBTextEdit;
LCItem6: TdxLayoutItem;
edMun: TcxDBTextEdit;
LCItem7: TdxLayoutItem;
edTel: TcxDBTextEdit;
LCItem10: TdxLayoutItem;
edCodMun: TcxDBButtonEdit;
lcCodMun: TdxLayoutItem;
MTEnd_Complemento: TStringField;
edComplemento: TcxDBTextEdit;
LCItem2: TdxLayoutItem;
dxLayoutLookAndFeelList1: TdxLayoutLookAndFeelList;
llfUltraFlat: TdxLayoutCxLookAndFeel;
MTCertificadoDig: TStringField;
MTtpAmb: TByteField;
MTCSC: TStringField;
MTIdCSC: TStringField;
edCSC: TcxDBTextEdit;
lcTokenCSC: TdxLayoutItem;
edIDCSC: TcxDBTextEdit;
lcIDCSC: TdxLayoutItem;
btnAvancadas: TcxButton;
LCItem5: TdxLayoutItem;
llfFlat: TdxLayoutCxLookAndFeel;
Paginas: TcxPageControl;
tsSefaz: TcxTabSheet;
tsEndereco: TcxTabSheet;
tsOpcoes: TcxTabSheet;
panSefaz: TLMDSimplePanel;
lc1: TdxLayoutControl;
lc1Group_Root: TdxLayoutGroup;
panEnd: TLMDSimplePanel;
lc3: TdxLayoutControl;
lc3Group_Root: TdxLayoutGroup;
panOpcoes: TLMDSimplePanel;
lc4: TdxLayoutControl;
lc4Group_Root: TdxLayoutGroup;
lc3Group2: TdxLayoutAutoCreatedGroup;
lc3Group3: TdxLayoutAutoCreatedGroup;
edPedirCPF: TcxDBCheckBox;
lc4Item1: TdxLayoutItem;
edPedirEmail: TcxDBCheckBox;
lc4Item2: TdxLayoutItem;
lcgr_avancado: TdxLayoutGroup;
edHom: TcxDBCheckBox;
lctpAmb: TdxLayoutItem;
cxLabel1: TcxLabel;
lc4Item4: TdxLayoutItem;
MTTipoCert: TByteField;
tsEmail: TcxTabSheet;
lc5Group_Root: TdxLayoutGroup;
lc5: TdxLayoutControl;
edFromEmail: TcxDBTextEdit;
lcFromEmail: TdxLayoutItem;
MTFromEmail: TStringField;
MTFromName: TStringField;
edCorpoEmail: TcxDBMemo;
lcCorpoEmail: TdxLayoutItem;
edAssunto: TcxDBTextEdit;
lcAssunto: TdxLayoutItem;
MTAssuntoEmail: TStringField;
cxLabel2: TcxLabel;
lc5Item1: TdxLayoutItem;
lcModEmailNFCE: TdxLayoutItem;
edModEmailNFCE: TncDocEdit;
MTCorpoEmail: TMemoField;
btnInstalaDepend: TcxButton;
lc4Item3: TdxLayoutItem;
lc4Group3: TdxLayoutAutoCreatedGroup;
MTPinCert: TStringField;
cxLabel3: TcxLabel;
lc1Item1: TdxLayoutItem;
Timer1: TTimer;
tsCert: TcxTabSheet;
lcCD: TdxLayoutControl;
edCertificado: TcxDBComboBox;
edTipoCert: TcxDBImageComboBox;
edPin: TcxDBTextEdit;
lcCDGroup_Root: TdxLayoutGroup;
lcCertificado: TdxLayoutItem;
lcTipoCert: TdxLayoutItem;
lcPIN: TdxLayoutItem;
edModEmailSAT: TncDocEdit;
lcModEmailSAT: TdxLayoutItem;
tsSAT: TcxTabSheet;
lcSATGroup_Root: TdxLayoutGroup;
lcSAT: TdxLayoutControl;
MTCodigoAtivacao: TStringField;
MTNomeDLLSat: TStringField;
edCodAtivacao: TcxDBTextEdit;
lcCodAtivacao: TdxLayoutItem;
edSignAC: TcxDBMemo;
dxLayoutItem1: TdxLayoutItem;
lbInfoCSC: TLMDLabel;
lcInfoCSC: TdxLayoutItem;
panEstado: TLMDSimplePanel;
cxLabel4: TcxLabel;
edEstado: TcxDBImageComboBox;
dxLayoutItem3: TdxLayoutItem;
edIE: TcxDBTextEdit;
dxLayoutItem4: TdxLayoutItem;
edCNPJ: TcxDBMaskEdit;
dxLayoutItem5: TdxLayoutItem;
edFantasia: TcxDBTextEdit;
dxLayoutItem6: TdxLayoutItem;
edRazao: TcxDBTextEdit;
dxLayoutItem7: TdxLayoutItem;
edCRT: TcxDBImageComboBox;
dxLayoutAutoCreatedGroup2: TdxLayoutAutoCreatedGroup;
MTAssociarSignAC: TBooleanField;
edAssociarAC: TcxDBCheckBox;
lcAssociarAC: TdxLayoutItem;
GerarSignAC: TcxButton;
dxLayoutItem2: TdxLayoutItem;
OpenDlg: TOpenDialog;
cxLabel5: TcxLabel;
dxLayoutItem9: TdxLayoutItem;
dxLayoutGroup1: TdxLayoutGroup;
IdHTTP1: TIdHTTP;
MTSignACSat: TStringField;
grCSC: TdxLayoutGroup;
dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup;
edsat_modelo: TcxDBImageComboBox;
lcsat_modelo: TdxLayoutItem;
MTsat_modelo: TByteField;
MTsat_config: TStringField;
edsat_porta: TcxDBComboBox;
lcsat_porta: TdxLayoutItem;
dxLayoutAutoCreatedGroup3: TdxLayoutAutoCreatedGroup;
edNomeDLLSat: TcxDBButtonEdit;
lcNomeDllSat: TdxLayoutItem;
procedure edEmitirNFCePropertiesChange(Sender: TObject);
procedure edMostrarNCMPropertiesChange(Sender: TObject);
procedure edMostrarSitTribPropertiesChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edCRTPropertiesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edCodMunPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edCodMunPropertiesChange(Sender: TObject);
procedure btnAvancadasClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure PaginasDrawTabEx(AControl: TcxCustomTabControl; ATab: TcxTab;
Font: TFont);
procedure btnPremiumClick(Sender: TObject);
procedure PaginasChange(Sender: TObject);
procedure btnInstalaDependClick(Sender: TObject);
procedure edTipoCertPropertiesChange(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure edEstadoPropertiesChange(Sender: TObject);
procedure GerarSignACClick(Sender: TObject);
procedure edsat_modeloPropertiesChange(Sender: TObject);
procedure edsat_modeloPropertiesCloseUp(Sender: TObject);
procedure edNomeDLLSatPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
FFrmNCM : TFrmNCMPesq;
FEditModelo : Boolean;
FDisableSetFocus : Boolean;
FAtivar : Boolean;
FCNPJ : String;
FSignAC : String;
FSignACCNPJ : String;
{ Private declarations }
procedure Atualiza;
function ESAT: Boolean;
procedure Valida;
procedure EnableDisable;
procedure SetEditModelo(const Value: Boolean);
procedure wmAtualizaDireitosConfig(var Msg: TMessage);
message wm_atualizadireitosconfig;
public
{ Public declarations }
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure AtualizaMun;
procedure Renumera; override;
property Ativar: Boolean read FAtivar write FAtivar;
class procedure Mostrar(aAtivar : Boolean);
function NumItens: Integer; override;
property EditModelo: Boolean read FEditModelo write SetEditModelo;
end;
var
FrmConfigNFE: TFrmConfigNFE;
implementation
{$R *.dfm}
uses ncaFrmPri, ncaDM, ncaFrmMunBr, ncEspecie,
ncaFrmConfigEspecies, ncaFrmRecursoPremium, ncaFrmNFCeDepend,
ncaProgressoDepend, ncaFrmAlertaPIN, ufmImagens, md5, ncHttp;
{ TFrmConfigNFE }
resourcestring
rsNFCePremium = 'A emissão de NF é um recurso exclusivo para assinantes do plano PREMIUM.';
function Chave(aLoja, aCNPJ: string): string;
begin
aLoja := Trim(aLoja);
aCNPJ := SoDig(aCNPJ);
Result := getmd5str('piLKHerASD17IUywefd7kdsfTkjhasfdkxzxxx778213zxcnbv'+LowerCase(aLoja)+aCNPJ); // do not localize
end;
function TFrmConfigNFE.Alterou: Boolean;
begin
Result := True;
with Dados do begin
if edEmitirNFCe.Checked <> tNFConfigEmitirNFCe.Value then Exit;
if edEstado.EditValue <> tNFConfigEnd_UF.Value then Exit;
if edIDCSC.Text <> tNFConfigIdCSC.Value then Exit;
if edCSC.Text <> tNFConfigCSC.Value then Exit;
if edCertificado.Text <> tNFConfigCertificadoDig.Value then Exit;
if edCRT.EditValue <> tNFConfigCRT.Value then Exit;
if edRazao.Text <> tNFConfigRazaoSocial.Value then Exit;
if edFantasia.Text <> tNFConfigNomeFantasia.Value then Exit;
if edCNPJ.Text <> tNFConfigCNPJ.Value then Exit;
if edIE.Text <> tNFConfigIE.Value then Exit;
if edLogr.Text <> tNFConfigEnd_Logradouro.Value then Exit;
if edNumero.Text <> tNFConfigEnd_Numero.Value then Exit;
if edComplemento.Text <> tNFConfigEnd_Complemento.Value then Exit;
if edBairro.Text <> tNFConfigEnd_Bairro.Value then Exit;
if edCEP.Text <> tNFConfigEnd_CEP.Value then Exit;
if edTel.Text <> tNFConfigTelefone.Value then Exit;
if edCodMun.Text <> tNFConfigEnd_CodMun.Value then Exit;
if MTPedirCPF.Value <> tNFConfigPedirCPF.Value then Exit;
if MTPedirEmail.Value <> tNFConfigPedirEmail.Value then Exit;
if edSerieNFCe.Text <> tNFConfigSerieNFCe.Value then Exit;
if edInicioNFCe.Value <> tNFConfigInicioNFCe.Value then Exit;
if edHom.EditValue <> tNFConfigtpAmb.Value then Exit;
if edModEmailNFCE.IDDoc <> tNFConfigModeloNFCe_Email.Value then Exit;
if edModEmailSAT.IDDoc <> TNFConfigModeloSAT_Email.Value then Exit;
if edAssunto.Text <> TNFConfigAssuntoEmail.Value then Exit;
if edFromEmail.Text <> tNFConfigFromEmail.Value then Exit;
if edTipoCert.EditValue <> tNFConfigTipoCert.Value then Exit;
if edPin.Text <> tNFConfigPinCert.Value then Exit;
if edAssociarAC.Checked <> tNFConfigAssociarSignAC.Value then Exit;
if edsat_modelo.EditValue <> tNFConfigsat_modelo.AsVariant then Exit;
if edsat_porta.Text <> tNFConfigsat_config.Value then Exit;
if edNomeDLLSat.Text <> TNFConfigNomeDllSat.Value then Exit;
end;
Result := False;
end;
function TFrmConfigNFE.ESAT: Boolean;
begin
Result := (not VarIsNull(edEstado.EditValue)) and SameText(edEstado.EditValue, 'SP');
end;
procedure TFrmConfigNFE.Atualiza;
var
aSAT: Boolean;
begin
lcPIN.Visible := False; //(edTipoCert.ItemIndex=1);
aSAT := ESAT;
grCSC.Visible := not ESAT;
tsCert.TabVisible := (not aSAT);
tsSAT.TabVisible := aSAT;
lcSerieNFCE.Visible := (not aSAT);
lcInicioNFCE.Visible := (not aSAT);
lctpAmb.Visible := (not aSAT);
lcAssociarAC.Visible := aSAT;
lcModEmailSat.Visible := aSAT;
lcModEmailNFCE.Visible := not aSat;
lcsat_porta.Visible := (MTsat_modelo.Value=sat_bematech);
lcNomeDllSat.Visible := (MTsat_modelo.Value=sat_outros) and (not MTsat_modelo.IsNull);
if ESAT then
edEmitirNFCe.Caption := 'Emitir CF-e SAT' else
edEmitirNFCe.Caption := 'Emitir NFC-e';
end;
procedure TFrmConfigNFE.AtualizaMun;
begin
with Dados do
if tbMun.FindKey([edCodMun.Text]) then begin
edMun.Text := tbMunNome.Value;
MTEnd_Municipio.Value := tbMunNome.Value;
MTEnd_CodUF.Value := StrToInt(Copy(edCodMun.Text, 1, 2));
end else begin
edMun.Text := '';
MTEnd_Municipio.Value := '';
MTEnd_CodUF.Value := 0;
end;
end;
procedure TFrmConfigNFE.btnAvancadasClick(Sender: TObject);
begin
inherited;
lcgr_Avancado.Visible := btnAvancadas.Down;
end;
procedure TFrmConfigNFE.btnInstalaDependClick(Sender: TObject);
begin
inherited;
NotifySucessoDepend := True;
ncaDM.NotityErroDepend := True;
if Assigned(panProgressoDepend) then
ShowMessage('Já existe uma instalação em andamento') else
Dados.CM.InstalaNFCeDepend;
end;
procedure TFrmConfigNFE.btnOkClick(Sender: TObject);
begin
if edEmitirNFCe.Checked then begin
Paginas.ActivePageIndex := 0;
edRazao.SetFocus;
edFantasia.SetFocus;
end;
if Alterou then Salvar;
Close;
end;
procedure TFrmConfigNFE.btnPremiumClick(Sender: TObject);
begin
inherited;
TFrmRecursoPremium.Create(Self).Mostrar(rsNFCePremium, 'nfce');
end;
procedure TFrmConfigNFE.edCodMunPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
aUF,
aCod: String;
P : TFrmMunPesq;
begin
inherited;
aUF := MTEnd_UF.Value;
if aUF='' then begin
Paginas.ActivePageIndex := 0;
raise exception.Create('É necessário selecionar um estado');
end;
aCod := edCodMun.Text;
P := TFrmMunPesq.Create(self);
try
if P.Pesquisar(aUF, aCod) then begin
edCodMun.Text := aCod;
MTEnd_CodMun.Value := aCod;
MTEnd_Municipio.Value := P.TabNome.Value;
MTEnd_CodUF.Value := StrToInt(copy(aCod, 1, 2));
end;
finally
P.Free;
end;
end;
procedure TFrmConfigNFE.edCodMunPropertiesChange(Sender: TObject);
begin
inherited;
AtualizaMun;
end;
procedure TFrmConfigNFE.edCRTPropertiesChange(Sender: TObject);
begin
inherited;
if edCRT.Focused and (edCRT.ItemIndex=2) then begin
ShowMessage('O NEX ainda não está preparado para emitir NFC-e para empresas que trabalham em Regime Normal');
edCRT.ItemIndex := 0;
end;
Atualiza;
end;
procedure TFrmConfigNFE.edEmitirNFCePropertiesChange(Sender: TObject);
begin
inherited;
Atualiza;
EnableDisable;
end;
procedure TFrmConfigNFE.edEstadoPropertiesChange(Sender: TObject);
begin
inherited;
EnableDisable;
Atualiza;
end;
procedure TFrmConfigNFE.edMostrarNCMPropertiesChange(Sender: TObject);
begin
inherited;
Atualiza;
end;
procedure TFrmConfigNFE.edMostrarSitTribPropertiesChange(Sender: TObject);
begin
inherited;
Atualiza;
end;
procedure TFrmConfigNFE.edNomeDLLSatPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
inherited;
if OpenDlg.Execute(Handle) then begin
edNomeDLLSat.Text := OpenDlg.FileName;
MTNomeDllSat.Value := OpenDlg.FileName;
edNomeDLLSat.Refresh;
end;
end;
procedure TFrmConfigNFE.edsat_modeloPropertiesChange(Sender: TObject);
begin
inherited;
if edsat_modelo.Focused then Atualiza;
end;
procedure TFrmConfigNFE.edsat_modeloPropertiesCloseUp(Sender: TObject);
begin
inherited;
Atualiza;
end;
procedure TFrmConfigNFE.edTipoCertPropertiesChange(Sender: TObject);
begin
inherited;
Atualiza;
end;
procedure TFrmConfigNFE.EnableDisable;
var aEnable: Boolean;
begin
lcPIN.Visible := False; //(edTipoCert.ItemIndex=1);
btnPremium.Visible := not ((gConfig.IsPremium) and (not gConfig.Pro));
edEmitirNFCe.Enabled := not btnPremium.Visible;
aEnable := edEmitirNFCe.Checked and edEmitirNFCe.Enabled and (edEstado.ItemIndex>=0);
lc1Group_Root.Enabled := aEnable;
lcCDGroup_Root.Enabled := aEnable;
lcSATGroup_Root.Enabled := aEnable;
lc3Group_Root.Enabled := aEnable;
lc4Group_Root.Enabled := aEnable;
lc5Group_Root.Enabled := aEnable;
btnOk.Enabled := Dados.CM.UA.Admin and edEmitirNFCe.Enabled;
end;
procedure TFrmConfigNFE.FormCreate(Sender: TObject);
begin
inherited;
FSignACCNPJ := '';
FDisableSetFocus := True;
FAtivar := False;
FFrmNCM := nil;
FEditModelo := False;
Paginas.ActivePageIndex := 0;
btnInstalaDepend.Enabled := Dados.CM.UA.Admin;
lctpAmb.Visible := (Dados.tNFConfigtpAmb.Value=1);
end;
procedure TFrmConfigNFE.FormDestroy(Sender: TObject);
begin
inherited;
if Assigned(FFrmNCM) then gNCMPesqList.ReleaseFrm(FFrmNCM);
end;
procedure TFrmConfigNFE.FormShow(Sender: TObject);
begin
inherited;
FDisableSetFocus := False;
Dados.CM.ObtemCertificados(edCertificado.Properties.Items);
EnableDisable;
Timer1.Enabled := True;
end;
procedure TFrmConfigNFE.GerarSignACClick(Sender: TObject);
var
S: String;
begin
inherited;
if Length(SoDig(edCNPJ.Text))=0 then
raise exception.Create('É necessário preencher o CNPJ antes de gerar a assinatura');
if Length(SoDig(edCNPJ.Text))<>14 then
raise exception.Create('O CNPJ da sua empresa não está correto. Tem que ter 14 dígitos');
S := 'http://docserver.nextar.com.br:8080/?cnpj='+SoDig(edCNPJ.Text)+'&loja='+gConfig.Conta+'&chave='+chave(gConfig.Conta, edCNPJ.Text);
S := httpGet(S);
if Pos('erro=', S)=1 then
raise Exception.Create(Copy(S, 6, 1000));
MTSignACSat.Value := S;
edSignAC.Text := S;
edSignAC.Refresh;
end;
procedure TFrmConfigNFE.Ler;
begin
inherited;
MT.Active := False;
MT.Active := True;
MT.Append;
TransfDados(Dados.tNFConfig, MT);
FCNPJ := Dados.tNFConfigCNPJ.Value;
FSignAC := Dados.tNFConfigSignACSat.Value;
if FAtivar then
MTEmitirNFCe.Value := True;
if Dados.tNFConfigModeloNFCe_Email.IsNull then
edModEmailNFCE.IDDoc := '' else
edModEmailNFCE.IDDoc := Dados.tNFConfigModeloNFCe_Email.Value;
if Dados.tNFConfigModeloSAT_Email.IsNull then
edModEmailSAT.IDDoc := '' else
edModEmailSAT.IDDoc := Dados.tNFConfigModeloSAT_Email.Value;
Atualiza;
end;
class procedure TFrmConfigNFE.Mostrar(aAtivar: Boolean);
begin
inherited;
Dados.GravaFlag('acessou_config_nfce', '1');
if (not gConfig.IsPremium) or gConfig.Pro then
TFrmRecursoPremium.Create(nil).ShowModal;
if gConfig.IsPremium and (not gConfig.Pro) then
with TFrmConfigNFE.Create(nil) do begin
Ativar := aAtivar;
ShowModal;
end;
end;
function TFrmConfigNFE.NumItens: Integer;
begin
Result := 3;
end;
procedure TFrmConfigNFE.PaginasChange(Sender: TObject);
begin
inherited;
if lc1Group_Root.Enabled and (not FDisableSetFocus) then
case Paginas.ActivePageIndex of
0 : edEstado.SetFocus;
1 : edCertificado.SetFocus;
2 : edCodAtivacao.SetFocus;
3 : edLogr.SetFocus;
4 : edPedirCPF.SetFocus;
5 : edFromEmail.SetFocus;
end;
end;
procedure TFrmConfigNFE.PaginasDrawTabEx(AControl: TcxCustomTabControl;
ATab: TcxTab; Font: TFont);
begin
inherited;
if btnPremium.Visible then
Font.Color := clSilver;
end;
procedure TFrmConfigNFE.Renumera;
begin
// RenumCB(edEmitirNFCe, 0);
// RenumLB(lbCRT, 2);
end;
procedure TFrmConfigNFE.Salvar;
var
aEmissaoAntes : Boolean;
aCNPJAnt, aRazaoAnt : String;
begin
inherited;
Valida;
with Dados do begin
if tNFConfig.IsEmpty then
tNFConfig.Append else
tNFConfig.Edit;
aEmissaoAntes := tNFConfigEmitirNFCe.Value;
aCNPJAnt := tNFConfigCNPJ.Value;
aRazaoAnt := tNFConfigRazaoSocial.Value;
TransfDados(MT, tNFConfig);
tNFConfigPinCert.Value := Trim(edPin.Text);
if edModEmailNFCE.IDDoc='' then
tNFConfigModeloNFCe_Email.Clear else
tNFConfigModeloNFCe_Email.Value := edModEmailNFCE.IDDoc;
if edModEmailSAT.IDDoc='' then
tNFConfigModeloSAT_Email.Clear else
tNFConfigModeloSAT_Email.Value := edModEmailSAT.IDDoc;
if SameText(tNFConfigEnd_UF.Value, 'SP') then
tNFConfigTipo.Value := nfcfg_sat else
tNFConfigTipo.Value := nfcfg_nfce;
if ESAT and (edSignAC.Text<>FSignAC) then
tNFConfigAssociarSignAC.Value := True;
tNFConfig.Post;
if tNFConfigEmitirNFCe.Value and (not aEmissaoAntes) then begin
if ESAT then begin
if (not tNFConfigDependSATOk.Value) then NotityErroDepend := True;
Dados.GravaFlag('acessou_config_sat', '1');
Dados.GravaFlag('ativou_sat', '1');
end else begin
Dados.GravaFlag('acessou_config_nfce', '1');
Dados.GravaFlag('ativou_nfce', '1');
if (not tNFConfigDependNFCEOk.Value) then NotityErroDepend := True;
end;
Dados.EnviaEmailAtivacaoNFCe('', '');
end else
if tNFConfigEmitirNFCe.Value then begin
if (aCNPJAnt=tNFConfigCNPJ.Value) then aCNPJAnt := '';
if aRazaoAnt=tNFConfigRazaoSocial.Value then aRazaoAnt := '';
if (aRazaoAnt>'') or (aCNPJAnt>'') then
Dados.EnviaEmailAtivacaoNFCe(aCNPJAnt, aRazaoAnt);
end;
end;
end;
procedure TFrmConfigNFE.SetEditModelo(const Value: Boolean);
begin
Paginas.ActivePageIndex := 3;
FEditModelo := Value;
end;
procedure TFrmConfigNFE.Timer1Timer(Sender: TObject);
begin
inherited;
Timer1.Enabled := False;
if edEmitirNFCe.Enabled and FEditModelo then begin
Paginas.ActivePage := tsEmail;
if ESAT then
edModEmailSAT.SetFocus else
edModEmailNFCE.SetFocus;
end else
if lc1Group_Root.Enabled then begin
Paginas.ActivePageIndex := 0;
edEstado.SetFocus;
end;
end;
procedure TFrmConfigNFE.Valida;
begin
if not edEmitirNFCe.Checked then Exit;
if edEstado.EditValue='' then
begin
Paginas.ActivePageIndex := 0;
edEstado.SetFocus;
raise exception.Create('É necessário infomar o estado');
end;
if edMun.Text='' then begin
Paginas.ActivePageIndex := 3;
edCodMun.SetFocus;
if Trim(edCodMun.Text)='' then
raise exception.Create('É necessário informar o código do município') else
raise Exception.Create('O código de municipio informado não existe');
end;
{ if lcPin.Visible and (Trim(edPin.Text)>'') then begin
Paginas.ActivePageIndex := 0;
edPin.SetFocus;
raise Exception.Create('É necessário informar o PIN do certificado A3');
end; }
with Dados do
if tbMun.FindKey([MTEnd_CodMun.Value]) then
if tbMunUF.Value <> MTEnd_UF.Value then
raise exception.Create('O município informado no endereço não é do mesmo estado selecionado.');
if (not ESAT) and (Trim(MTIDCSC.Value)='') then begin
Paginas.ActivePageIndex := 0;
edIdCSC.SetFocus;
raise exception.Create('É necessário informar o ID CSC');
end;
if (not ESAT) and (Length(SoDig(MTIDCSC.Value))<>6) then begin
Paginas.ActivePageIndex := 0;
raise Exception.Create('O ID CSC deve conter obrigatoriamente 6 dígitos numéricos');
end;
if (not ESAT) and (Trim(MTCSC.Value)='') then begin
Paginas.ActivePageIndex := 0;
edCSC.SetFocus;
raise Exception.Create('É necessário informar o Token do CSC');
end;
if (not ESAT) and (Trim(edCertificado.Text)='') then begin
Paginas.ActivePageIndex := 1;
edCertificado.SetFocus;
raise Exception.Create('É necessário selecionar o certificado digital a ser usado');
end;
if (Trim(edRazao.Text)='') then begin
Paginas.ActivePageIndex := 0;
edRazao.SetFocus;
raise Exception.Create('A razão social deve ser informada');
end;
if (Trim(edFantasia.Text)='') then begin
Paginas.ActivePageIndex := 0;
edFantasia.SetFocus;
raise Exception.Create('O nome fantasia deve ser informado');
end;
if (Trim(edCNPJ.Text)='') then begin
Paginas.ActivePageIndex := 0;
edCNPJ.SetFocus;
raise Exception.Create('O CNPJ deve ser informado');
end;
if not IsCNPJ(edCNPJ.Text) then begin
Paginas.ActivePageIndex := 0;
edCNPJ.SetFocus;
raise Exception.Create('O CNPJ informado não é válido');
end;
if Trim(edFantasia.Text)='' then begin
Paginas.ActivePageIndex := 0;
edIE.SetFocus;
raise Exception.Create('A Inscrição Estadual deve ser informada');
end;
if Trim(edLogr.Text)='' then begin
Paginas.ActivePageIndex := 3;
edLogr.SetFocus;
raise Exception.Create('O endereço deve ser informado');
end;
if Trim(edNumero.Text)='' then begin
Paginas.ActivePageIndex := 3;
edNumero.SetFocus;
raise Exception.Create('O número do endereço deve ser informado');
end;
if Trim(edBairro.Text)='' then begin
Paginas.ActivePageIndex := 3;
edBairro.SetFocus;
raise Exception.Create('O bairro deve ser informado');
end;
if Trim(edCEP.Text)='' then begin
Paginas.ActivePageIndex := 3;
edCEP.SetFocus;
raise Exception.Create('O CEP deve ser informado');
end;
if Length(SoDig(edCEP.Text))<8 then begin
Paginas.ActivePageIndex := 3;
edCEP.SetFocus;
raise Exception.Create('O CEP deve ter 8 dígitos');
end;
if (not ESAT) and (Trim(edSerieNFCe.Text)='') then begin
btnAvancadas.Down := True;
lcgr_Avancado.Visible := True;
Paginas.ActivePageIndex := 4;
edSerieNFCe.SetFocus;
raise Exception.Create('É necessário informar a série da NFC-e');
end;
if ESAT and (Length(edSignAC.Text)<>344) then begin
Paginas.ActivePageIndex := 2;
edSignAC.SetFocus;
if Trim(edSignAC.Text)='' then
raise Exception.Create('É necessário informar a assinatura do aplicativo comercial') else
raise Exception.Create('A assinatura do aplicativo comercial está incorreta. Ela tem que ter 344 dígitos');
end;
if ESAT and (Trim(edCodAtivacao.Text)='') then begin
Paginas.ActivePageIndex := 2;
edCodAtivacao.SetFocus;
raise Exception.Create('É necessário informar o Código de Ativação do Seu SAT');
end;
if ESAT and MTsat_modelo.IsNull then begin
Paginas.ActivePageIndex := 2;
edsat_modelo.SetFocus;
raise Exception.Create('É necessário informar o equipamento SAT utilizado em sua loja');
end;
if ESAT and (MTsat_modelo.Value=sat_bematech) and (Trim(MTsat_config.Value)='') then begin
Paginas.ActivePageIndex := 2;
edsat_porta.SetFocus;
raise Exception.Create('É necessário informar a porta de comunicação do equipamento SAT');
end;
if ESAT and (MTsat_modelo.Value=sat_outros) and (Trim(MTNomeDllSAT.Value)='') then begin
Paginas.ActivePageIndex := 2;
edNomeDllSat.SetFocus;
raise Exception.Create('É necessário informar o arquivo da DLL do equipamento SAT');
end;
if not gEspecies.TipoPagNFE_Ok then begin
Beep;
ShowMessage('Para cada Meio de Pagamento que você configurou no NEX para sua loja é necessário configurar o meio de pagamento correspondente na NF');
TFrmConfigEspecies.Create(Self).Mostrar(True, False);
raise EAbort.Create('');
end;
{ if lcPin.Visible and (not TFrmAlertaPIN.Create(Self).Ciente((Trim(edPin.Text)=''))) then
raise EAbort.Create('');}
end;
procedure TFrmConfigNFE.wmAtualizaDireitosConfig(var Msg: TMessage);
var I : Integer;
B : Boolean;
begin
B := edEmitirNFCe.Enabled;
EnableDisable;
if (not B) and edEmitirNFCe.Enabled then begin
I := Paginas.ActivePageIndex;
Paginas.ActivePageIndex := 0;
Paginas.ActivePageIndex := 1;
Paginas.ActivePageIndex := I;
end;
end;
end.
|
{ Copyright (C) 1998-2006, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization
freeware SMComponent library
}
unit SMCnst;
interface
{Italian strings}
const
strMessage = 'Stampa...';
strSaveChanges = 'Salvare le modifiche?';
strErrSaveChanges = 'Impossibile salvare i dati! Controllare la connessione al server o il metodo di verifica dei dati.';
strDeleteWarning = 'Candellare la tabella %s?';
strEmptyWarning = 'Svuotare la tabella %s?';
const
PopUpCaption: array [0..24] of string[33] =
('Aggiungi record',
'Inserisci record',
'Modifica record',
'Cancella record',
'-',
'Stampa ...',
'Esporta ...',
'Filtra ...',
'Cerca ...',
'-',
'Salva modifiche',
'Annulla modifiche',
'Rileggi',
'-',
'Seleziona / Deseleziona record',
'Seleziona record',
'Seleziona tutti i record',
'-',
'Deseleziona record',
'Deseleziona tutti i record',
'-',
'Salva colonne',
'Ripristina colonne',
'-',
'Impostazioni...');
const //for TSMSetDBGridDialog
SgbTitle = 'Titolo';
SgbData = ' Dati ';
STitleCaption = 'Intestazione:';
STitleAlignment = 'Allineamento:';
STitleColor = 'Sfondo:';
STitleFont = 'Primo piano:';
SWidth = 'Altezza:';
SWidthFix = 'Caratteri';
SAlignLeft = 'Sinistra';
SAlignRight = 'Destra';
SAlignCenter = 'Centro';
const //for TSMDBFilterDialog
strEqual = 'uguale';
strNonEqual = 'diverso';
strNonMore = 'minore o uguale';
strNonLess = 'maggiore o uguale';
strLessThan = 'minore';
strLargeThan = 'maggiore';
strExist = 'vuoto';
strNonExist = 'non vuoto';
strIn = 'nella lista';
strBetween = 'compreso tra';
strLike = 'contiene';
strOR = 'OR';
strAND = 'AND';
strField = 'Campo';
strCondition = 'Condizione';
strValue = 'Valore';
strAddCondition = ' Imposta altre condizioni:';
strSelection = ' Seleziona i record in base alle seguenti condizioni:';
strAddToList = 'Aggiungi';
strEditInList = 'Modifica';
strDeleteFromList = 'Elimina';
strTemplate = 'Finestra filtri';
strFLoadFrom = 'Carica da...';
strFSaveAs = 'Salva in..';
strFDescription = 'Descrizione';
strFFileName = 'Nome file';
strFCreate = 'Creato: %s';
strFModify = 'Modificato: %s';
strFProtect = 'Protetto da modifiche';
strFProtectErr = 'Il file e protetto!';
const //for SMDBNavigator
SFirstRecord = 'Primo record';
SPriorRecord = 'Record precedente';
SNextRecord = 'Record successivo';
SLastRecord = 'Ultimo record';
SInsertRecord = 'Inserisci record';
SCopyRecord = 'Copia record';
SDeleteRecord = 'Cancella record';
SEditRecord = 'Modifica record';
SFilterRecord = 'Filtri';
SFindRecord = 'Ricerca';
SPrintRecord = 'Stampa record';
SExportRecord = 'Esporta i records';
SImportRecord = 'Importa i records';
SPostEdit = 'Salva modifiche';
SCancelEdit = 'Annulla modifiche';
SRefreshRecord = 'Aggiorna';
SChoice = 'Scegli un record';
SClear = 'Annulla la scelta di un record';
SDeleteRecordQuestion = 'Cancella il record?';
SDeleteMultipleRecordsQuestion = 'Cancellare i record selezionati?';
SRecordNotFound = 'Record non trovato';
SFirstName = 'Primo';
SPriorName = 'Precedente';
SNextName = 'Successivo';
SLastName = 'Ultimo';
SInsertName = 'Nuovo';
SCopyName = 'Copia';
SDeleteName = 'Elimina';
SEditName = 'Modifica';
SFilterName = 'Filtro';
SFindName = 'Trova';
SPrintName = 'Stampa';
SExportName = 'Esporta';
SImportName = 'Importa';
SPostName = 'Salva';
SCancelName = 'Annulla';
SRefreshName = 'Aggiorna';
SChoiceName = 'Scegli';
SClearName = 'Cancella';
SBtnOk = '&OK';
SBtnCancel = '&Annulla';
SBtnLoad = 'Apri';
SBtnSave = 'Salva';
SBtnCopy = 'Copia';
SBtnPaste = 'Incolla';
SBtnClear = 'Svuota';
SRecNo = 'rec.';
SRecOf = ' di ';
const //for EditTyped
etValidNumber = 'numero valido';
etValidInteger = 'numero intero valido';
etValidDateTime = 'data/ora valida';
etValidDate = 'data valida';
etValidTime = 'ora valida';
etValid = 'valido';
etIsNot = 'non e un';
etOutOfRange = 'Il valore %s non e compreso in %s..%s';
SApplyAll = 'Applica a tutti';
SNoDataToDisplay = '<Nessun dato da visualizzare>';
implementation
end.
|
unit ufrmSysGridColColor;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils, Vcl.Menus, Vcl.Samples.Spin,
Vcl.AppEvnts,
Ths.Erp.Helper.Edit,
Ths.Erp.Helper.Memo,
Ths.Erp.Helper.ComboBox,
ufrmBase, ufrmBaseInputDB
,Ths.Erp.Database.Table.View.SysViewTables
;
type
TfrmSysGridColColor = class(TfrmBaseInputDB)
cbbColumnName: TComboBox;
cbbTableName: TComboBox;
edtMaxColor: TEdit;
edtMaxValue: TEdit;
edtMinColor: TEdit;
edtMinValue: TEdit;
lblColumnName: TLabel;
lblMaxColor: TLabel;
lblMaxValue: TLabel;
lblMinColor: TLabel;
lblMinValue: TLabel;
lblTableName: TLabel;
procedure FormCreate(Sender: TObject);override;
procedure RefreshData();override;
procedure btnAcceptClick(Sender: TObject);override;
procedure cbbTableNameChange(Sender: TObject);
procedure edtMinColorDblClick(Sender: TObject);
procedure edtMaxColorDblClick(Sender: TObject);
private
vSysViewTables: TSysViewTables;
procedure SetColor(color: TColor; editColor: TEdit);
public
destructor Destroy; override;
protected
published
procedure FormShow(Sender: TObject); override;
end;
implementation
uses
Ths.Erp.Database.Table.SysGridColColor
, Ths.Erp.Database.Singleton
, Ths.Erp.Functions
, Ths.Erp.Constants
;
{$R *.dfm}
procedure TfrmSysGridColColor.cbbTableNameChange(Sender: TObject);
var
lst: TStringList;
n1: Integer;
begin
lst := TSingletonDB.GetInstance.GetDistinctColumnName(cbbTableName.Text);
try
cbbColumnName.Clear;
for n1 := 0 to lst.Count-1 do
cbbColumnName.Items.Add(lst.Strings[n1]);
finally
lst.Free;
end;
end;
destructor TfrmSysGridColColor.Destroy;
begin
if Assigned(vSysViewTables) then
vSysViewTables.Free;
inherited;
end;
procedure TfrmSysGridColColor.edtMaxColorDblClick(Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtMaxColor.Text, 0)), edtMaxColor);
end;
procedure TfrmSysGridColColor.edtMinColorDblClick(Sender: TObject);
begin
SetColor(TFunctions.GetDialogColor(StrToIntDef(edtMinColor.Text, 0)), edtMinColor);
end;
procedure TfrmSysGridColColor.FormCreate(Sender: TObject);
begin
TSysGridColColor(Table).TableName1.SetControlProperty(Table.TableName, cbbTableName);
TSysGridColColor(Table).ColumnName.SetControlProperty(Table.TableName, cbbColumnName);
TSysGridColColor(Table).MinValue.SetControlProperty(Table.TableName, edtMinValue);
TSysGridColColor(Table).MinColor.SetControlProperty(Table.TableName, edtMinColor);
TSysGridColColor(Table).MaxValue.SetControlProperty(Table.TableName, edtMaxValue);
TSysGridColColor(Table).MaxColor.SetControlProperty(Table.TableName, edtMaxColor);
inherited;
cbbTableName.CharCase := ecNormal;
cbbColumnName.CharCase := ecNormal;
vSysViewTables := TSysViewTables.Create(Table.Database);
fillComboBoxData(cbbTableName, vSysViewTables, vSysViewTables.TableName1.FieldName, '');
cbbTableNameChange(cbbTableName);
end;
procedure TfrmSysGridColColor.FormShow(Sender: TObject);
begin
inherited;
edtMinColor.ReadOnly := True;
edtMaxColor.ReadOnly := True;
end;
procedure TfrmSysGridColColor.RefreshData();
begin
cbbTableName.ItemIndex := cbbTableName.Items.IndexOf( VarToStr(TSysGridColColor(Table).TableName1.Value) );
cbbTableNameChange(cbbTableName);
cbbColumnName.ItemIndex := cbbColumnName.Items.IndexOf( VarToStr(TSysGridColColor(Table).ColumnName.Value) );
edtMinValue.Text := TSysGridColColor(Table).MinValue.Value;
edtMinColor.Text := TSysGridColColor(Table).MinColor.Value;
SetColor(StrToIntDef(edtMinColor.Text, 0), edtMinColor);
edtMaxValue.Text := TSysGridColColor(Table).MaxValue.Value;
edtMaxColor.Text := TSysGridColColor(Table).MaxColor.Value;
SetColor(StrToIntDef(edtMaxColor.Text, 0), edtMaxColor);
end;
procedure TfrmSysGridColColor.SetColor(color: TColor; editColor: TEdit);
begin
editColor.Text := IntToStr(color);
editColor.Color := color;
editColor.thsColorActive := color;
editColor.thsColorRequiredInput := color;
editColor.Repaint;
end;
procedure TfrmSysGridColColor.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
if cbbTableName.Items.IndexOf(cbbTableName.Text) = -1 then
raise Exception.Create( TranslateText('Listede olmayan bir Tablo Adư giremezsiniz!', '#1', LngMsgError, LngSystem) );
if cbbColumnName.Items.IndexOf(cbbColumnName.Text) = -1 then
raise Exception.Create(TranslateText('Listede olmayan bir Kolon Adư giremezsiniz!', '#1', LngMsgError, LngSystem) );
TSysGridColColor(Table).TableName1.Value := cbbTableName.Text;
TSysGridColColor(Table).ColumnName.Value := cbbColumnName.Text;
TSysGridColColor(Table).MinValue.Value := edtMinValue.Text;
TSysGridColColor(Table).MinColor.Value := edtMinColor.Text;
TSysGridColColor(Table).MaxValue.Value := edtMaxValue.Text;
TSysGridColColor(Table).MaxColor.Value := edtMaxColor.Text;
inherited;
end;
end
else
begin
inherited;
edtMinColor.ReadOnly := True;
edtMaxColor.ReadOnly := True;
end;
end;
end.
|
namespace RemObjects.Elements.System;
interface
type
IEquatable<T> = public interface
method Equals(rhs: T): Boolean;
end;
IComparable< {in} T> = public interface
method CompareTo(rhs: T): Integer;
end;
IDisposable = public interface
method Dispose;
end;
implementation
end. |
unit SMARTSupport.Factory;
interface
uses
SysUtils,
BufferInterpreter, Device.SMART.List, SMARTSupport,
SMARTSupport.Seagate.NotSSD, SMARTSupport.Seagate.SSD, SMARTSupport.WD,
SMARTSupport.Mtron, SMARTSupport.JMicron60x, SMARTSupport.JMicron61x,
SMARTSupport.Indilinx, SMARTSupport.Intel, SMARTSupport.Samsung,
SMARTSupport.Micron.New, SMARTSupport.Micron.Old, SMARTSupport.Sandforce,
SMARTSupport.OCZ, SMARTSupport.OCZ.Vector, SMARTSupport.Plextor,
SMARTSupport.Sandisk, SMARTSupport.Sandisk.GB, SMARTSupport.Kingston,
SMARTSupport.Toshiba, SMARTSupport.Corsair, SMARTSupport.Fallback.SSD,
SMARTSupport.Fallback, SMARTSupport.NVMe.Intel, SMARTSupport.NVMe;
type
TMetaSMARTSupport = class of TSMARTSupport;
TSMARTSupportFactory = class
public
function GetSuitableSMARTSupport(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): TSMARTSupport;
private
FIdentifyDevice: TIdentifyDeviceResult;
FSMARTList: TSMARTValueList;
function TrySMARTSupportAndGetRightSMARTSupport: TSMARTSupport;
function TestSMARTSupportCompatibility(
TSMARTSupportToTry: TMetaSMARTSupport; LastResult: TSMARTSupport):
TSMARTSupport;
function TryFallbackSMARTSupports(
const LastResult: TSMARTSupport): TSMARTSupport;
function TryNVMeSMARTSupports(
const LastResult: TSMARTSupport): TSMARTSupport;
function TryATASMARTSupports(
const LastResult: TSMARTSupport): TSMARTSupport;
end;
implementation
{ TSMARTSupportFactory }
function TSMARTSupportFactory.GetSuitableSMARTSupport(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): TSMARTSupport;
begin
FIdentifyDevice := IdentifyDevice;
FSMARTList := SMARTList;
result := TrySMARTSupportAndGetRightSMARTSupport;
end;
function TSMARTSupportFactory.TrySMARTSupportAndGetRightSMARTSupport:
TSMARTSupport;
begin
result := nil;
result := TryNVMeSMARTSupports(result);
result := TryATASMARTSupports(result);
result := TryFallbackSMARTSupports(result);
end;
function TSMARTSupportFactory.TryNVMeSMARTSupports(
const LastResult: TSMARTSupport):
TSMARTSupport;
begin
result := LastResult;
result := TestSMARTSupportCompatibility(
TIntelNVMeSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TNVMeSMARTSupport, result);
end;
function TSMARTSupportFactory.TryATASMARTSupports(
const LastResult: TSMARTSupport):
TSMARTSupport;
begin
result := LastResult;
result := TestSMARTSupportCompatibility(
TSeagateSSDSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TSeagateNotSSDSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TWDSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TMtronSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TJMicron60xSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TJMicron61xSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TIndilinxSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TIntelSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TSamsungSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TNewMicronSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TOldMicronSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TSandforceSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TOCZSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TOCZVectorSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TPlextorSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TSandiskSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TSandiskGBSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TKingstonSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TToshibaSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TCorsairSMARTSupport, result);
end;
function TSMARTSupportFactory.TryFallbackSMARTSupports(
const LastResult: TSMARTSupport):
TSMARTSupport;
begin
result := LastResult;
result := TestSMARTSupportCompatibility(
TSSDFallbackSMARTSupport, result);
result := TestSMARTSupportCompatibility(
TFallbackSMARTSupport, result);
end;
function TSMARTSupportFactory.TestSMARTSupportCompatibility(
TSMARTSupportToTry: TMetaSMARTSupport; LastResult: TSMARTSupport):
TSMARTSupport;
begin
if LastResult <> nil then
exit(LastResult);
result := TSMARTSupportToTry.Create;
if not result.IsThisStorageMine(FIdentifyDevice, FSMARTList) then
FreeAndNil(result);
end;
end.
|
program Maximum (input, output);
{ bestimmt das Maximum einer Zahlenfolge von einzulesenden integer-Zahlen.
Dabei wird die letzte 0 nicht berücksichtigt! }
var
i: integer; {Laufvariable, wird nur hochgezählt}
Zahl, Max : integer;
{Eingegebene Integer-Zahlen und das Maximum aller eingegeben Zahlen}
begin
writeln ('Geben Sie beliebig viele ganze Zahlen ein,');
writeln ('deren Maximum bestimmt werden soll.');
writeln ('Sie können die Zahlenfolge mit 0 beenden!');
i := 1;
{Liest die erste Eingabe ein!}
write(i, '. Wert: ');
readln (Zahl);
Max := Zahl;
if(Zahl = 0) then
writeln('Leere Eingabefolge!')
else
begin
repeat
if (Zahl <> 0) then
begin
if (Zahl > Max) then
Max := Zahl;
{Liest ab der 2.ten Eingabe ein!}
i := i+1;
write(i, '. Wert: ');
readln (Zahl);
end; {Zahl <> 0}
until (Zahl = 0); {repeat-schleife-ENDE} {sobald Zahl = 0}
writeln ('Das Maximum ist: ', Max, '.');
end;
end.
|
unit ComponentsSearchQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls,
ApplyQueryFrame, BaseComponentsQuery, DSWrap, SearchFamOrCompoQuery;
type
TQueryComponentsSearch = class(TQueryBaseComponents)
private
FqSearchFamilyOrComp: TQuerySearchFamilyOrComp;
function GetqSearchFamilyOrComp: TQuerySearchFamilyOrComp;
{ Private declarations }
protected
procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override;
property qSearchFamilyOrComp: TQuerySearchFamilyOrComp
read GetqSearchFamilyOrComp;
public
procedure AfterConstruction; override;
procedure ClearSearchResult;
procedure SearchByValue(AValues: TArray<String>; ALike: Boolean);
{ Public declarations }
end;
implementation
{$R *.dfm}
uses NotifyEvents, StrHelper;
procedure TQueryComponentsSearch.AfterConstruction;
begin
inherited;
// Подставляем заведомо ложное условие чтобы очистить список
FDQuery.SQL.Text := ReplaceInSQL(SQL, '0=1', 0);
end;
procedure TQueryComponentsSearch.ApplyInsert(ASender: TDataSet;
ARequest: TFDUpdateRequest; var AAction: TFDErrorAction;
AOptions: TFDUpdateRowOptions);
begin
// Не разрешаем добавление записи
end;
procedure TQueryComponentsSearch.ClearSearchResult;
begin
// Подставляем заведомо ложное условие чтобы очистить список
FDQuery.SQL.Text := ReplaceInSQL(SQL, '0=1', 0);
W.RefreshQuery;
end;
function TQueryComponentsSearch.GetqSearchFamilyOrComp
: TQuerySearchFamilyOrComp;
begin
if FqSearchFamilyOrComp = nil then
FqSearchFamilyOrComp := TQuerySearchFamilyOrComp.Create(Self);
Result := FqSearchFamilyOrComp;
end;
procedure TQueryComponentsSearch.SearchByValue(AValues: TArray<String>;
ALike: Boolean);
var
AStipulation: string;
AStipulation1: string;
AStipulation2: string;
begin
// Готовим SQL запрос для поиска семейств
qSearchFamilyOrComp.PrepareSearchByValue(AValues, ALike, True);
AStipulation1 := Format('%s in (%s)', [W.ParentProductID.FullName,
qSearchFamilyOrComp.FDQuery.SQL.Text]);
// Готовим SQL запрос для поиска компонентов
qSearchFamilyOrComp.PrepareSearchByValue(AValues, ALike, False);
AStipulation2 := Format('%s in (%s)', [W.ID.FullName,
qSearchFamilyOrComp.FDQuery.SQL.Text]);
AStipulation := Format('%s or %s', [AStipulation1, AStipulation2]);
FDQuery.SQL.Text := ReplaceInSQL(SQL, AStipulation, 0);
W.RefreshQuery;
end;
end.
|
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program QBMAX;
Uses Math;
Const
minValue =-maxInt;
Var
n,m :Byte;
A :Array[1..100,1..100] of SmallInt;
F :Array[0..101,1..100] of SmallInt;
procedure Enter;
var
i,j :Byte;
begin
Read(n,m);
for i:=1 to n do
for j:=1 to m do Read(A[i,j]);
end;
procedure Optimize;
var
i,j :Byte;
begin
for i:=1 to n do F[i,1]:=A[i,1];
for i:=1 to m-1 do
begin
F[0,i]:=minValue; F[n+1,i]:=minValue;
end;
for j:=2 to m do
for i:=1 to n do
F[i,j]:=Max(F[i+1,j-1],Max(F[i,j-1],F[i-1,j-1]))+A[i,j];
end;
procedure Escape;
var
i :Byte;
res :Integer;
begin
res:=F[1,m];
for i:=2 to n do
if (F[i,m]>res) then res:=F[i,m];
Write(res);
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
Optimize;
Escape;
Close(Input); Close(Output);
End. |
unit ExpenseDataMethodsIntf;
interface
uses
AccountTitle, Generics.Collections, Expense;
type
IExpenseDataMethods = interface
['{B2E108E2-E95C-4BF4-A247-E29CD56EC27B}']
procedure Save(AExpense: TExpense);
procedure Add;
function GetAccountTitles: TObjectList<TAccountTitle>;
end;
implementation
end.
|
unit Serv_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ AdHoc Query Demo Server Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_Serv: TGUID = '{85C677A0-F92F-11D0-9FFC-00A0248E4B9A}';
const
{ Component class GUIDs }
Class_AdHocQueryDemo: TGUID = '{85C677A2-F92F-11D0-9FFC-00A0248E4B9A}';
type
{ Forward declarations: Interfaces }
IAdHocQueryDemo = interface;
IAdHocQueryDemoDisp = dispinterface;
{ Forward declarations: CoClasses }
AdHocQueryDemo = IAdHocQueryDemo;
{ Dispatch interface for AdHocQueryDemo Object }
IAdHocQueryDemo = interface(IDataBroker)
['{85C677A1-F92F-11D0-9FFC-00A0248E4B9A}']
function Get_AdHocQuery: IProvider; safecall;
function GetDatabaseNames: OleVariant; safecall;
procedure SetDatabaseName(const DBName, Password: WideString); safecall;
property AdHocQuery: IProvider read Get_AdHocQuery;
end;
{ DispInterface declaration for Dual Interface IAdHocQueryDemo }
IAdHocQueryDemoDisp = dispinterface
['{85C677A1-F92F-11D0-9FFC-00A0248E4B9A}']
function GetProviderNames: OleVariant; dispid 22929905;
property AdHocQuery: IProvider readonly dispid 1;
function GetDatabaseNames: OleVariant; dispid 2;
procedure SetDatabaseName(const DBName, Password: WideString); dispid 3;
end;
{ AdHocQueryDemoObject }
CoAdHocQueryDemo = class
class function Create: IAdHocQueryDemo;
class function CreateRemote(const MachineName: string): IAdHocQueryDemo;
end;
implementation
uses ComObj;
class function CoAdHocQueryDemo.Create: IAdHocQueryDemo;
begin
Result := CreateComObject(Class_AdHocQueryDemo) as IAdHocQueryDemo;
end;
class function CoAdHocQueryDemo.CreateRemote(const MachineName: string): IAdHocQueryDemo;
begin
Result := CreateRemoteComObject(MachineName, Class_AdHocQueryDemo) as IAdHocQueryDemo;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Ani,
FMX.Objects, FMX.StdCtrls, FMX.Controls.Presentation, System.Beacon,
System.Beacon.Components;
type
TForm1 = class(TForm)
ToolBar1: TToolBar;
Label1: TLabel;
Switch1: TSwitch;
StatusBar1: TStatusBar;
Text1: TText;
Image1: TImage;
Rectangle1: TRectangle;
Text2: TText;
FloatAnimation1: TFloatAnimation;
Beacon1: TBeacon;
Timer1: TTimer;
procedure Switch1Switch(Sender: TObject);
procedure Beacon1BeaconEnter(const Sender: TObject; const ABeacon: IBeacon;
const CurrentBeaconList: TBeaconList);
procedure Beacon1BeaconExit(const Sender: TObject; const ABeacon: IBeacon;
const CurrentBeaconList: TBeaconList);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FBeacon: IBeacon;
procedure StartAlert;
procedure StopAlert; // Ctrl + Shift + C
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Beacon1BeaconEnter(const Sender: TObject;
const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
begin
FBeacon := ABeacon;
end;
procedure TForm1.Beacon1BeaconExit(const Sender: TObject;
const ABeacon: IBeacon; const CurrentBeaconList: TBeaconList);
begin
FBeacon := nil;
end;
procedure TForm1.StartAlert;
begin
FloatAnimation1.Start;
Rectangle1.Visible := True;
end;
procedure TForm1.StopAlert;
begin
FloatAnimation1.Stop;
Rectangle1.Visible := False;
end;
procedure TForm1.Switch1Switch(Sender: TObject);
begin
Beacon1.Enabled := Switch1.IsChecked;
if not Beacon1.Enabled then
StopAlert;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if Assigned(FBeacon) then
begin
Text1.Text :=
Format('위험지역과의 거리: %0.2f m', [FBeacon.Distance]);
if FBeacon.Distance < 1 then
begin
StartAlert;
end
else
begin
StopAlert;
end;
end;
end;
end.
|
{
"Local Heap Manager" - Copyright (c) Danijel Tkalcec
@exclude
}
unit memLocalHeap;
{$INCLUDE rtcDefs.inc}
interface
type
TLocalHeapManager = class
public
Total_Alloc:cardinal;
class function UsesLocalHeap:boolean;
constructor Create;
destructor Destroy; override;
function Clear:boolean;
function Check_Mem(p: Pointer): Cardinal;
function Get_Mem(size: Cardinal): Pointer;
function Free_Mem(p: Pointer): Integer;
function Realloc_Mem(p: Pointer; size: Cardinal): Pointer;
function Get_HeapStatus: THeapStatus;
end;
implementation
{ The next lines were copied from Borland's Memory Manager definition file.
Start copy ->> }
type
PUsed = ^TUsed;
TUsed = packed record
sizeFlags: Integer;
end;
const
cAlign = 4;
cThisUsedFlag = 2;
cPrevFreeFlag = 1;
cFillerFlag = Integer($80000000);
cFlags = cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
function TLocalHeapManager.Check_Mem(p: Pointer): Cardinal;
begin
Result := (PUsed(PChar(p)-sizeof(PUsed)).sizeFlags and not cFlags) - sizeof(TUsed);
end;
{ <<- end copy. }
function TLocalHeapManager.Get_Mem(size: Cardinal): Pointer;
begin
Result:=SysGetMem(size);
Total_Alloc := Total_Alloc + size;
end;
function TLocalHeapManager.Free_Mem(p: Pointer): Integer;
begin
Total_Alloc := Total_Alloc - Check_Mem(p);
Result:=SysFreeMem(p);
end;
function TLocalHeapManager.Realloc_Mem(p: Pointer; size: Cardinal): Pointer;
begin
Total_Alloc := Total_Alloc - Check_Mem(p);
Result:=SysReallocMem(p,size);
if Result<>nil then
Total_Alloc := Total_Alloc + size
else
Total_Alloc := Total_Alloc + Check_Mem(p);
end;
function TLocalHeapManager.Get_HeapStatus: THeapStatus;
begin
Result:=GetHeapStatus;
end;
constructor TLocalHeapManager.Create;
begin
inherited Create;
end;
destructor TLocalHeapManager.Destroy;
begin
inherited;
end;
function TLocalHeapManager.Clear:boolean;
begin
result:=False;
end;
class function TLocalHeapManager.UsesLocalHeap:boolean;
begin
Result:=False;
end;
var
OldExitProc:procedure;
procedure DeInitMem;
begin
if assigned(OldExitProc) then
OldExitProc;
end;
initialization
finalization
{$IFDEF IDE_1}
OldExitProc:=ExitProc;
ExitProc:=@DeInitMem;
{$ELSE}
OldExitProc:=ExitProcessProc;
ExitProcessProc:=DeInitMem;
{$ENDIF}
end.
|
unit Vigilante.DataSet.Compilacao;
interface
uses
System.Classes, System.Generics.Collections, Data.DB, FireDac.Comp.Client,
Vigilante.Compilacao.Model, Vigilante.ChangeSetItem.Model,
Vigilante.Aplicacao.SituacaoBuild,
Module.DataSet.VigilanteBase;
type
TCompilacaoDataSet = class(TVigilanteDataSetBase<ICompilacaoModel>)
private
FChangeSet: TStringList;
FoNumero: TField;
FoSituacaoBuild: TField;
FoChangeSet: TMemoField;
function GetChangeSet: string;
function GetNumero: integer;
procedure SetNumero(const Value: integer);
procedure CarregarChangeSet(const AChangeSet: TObjectList<TChangeSetItem>);
protected
procedure ConfigurarCampos; override;
procedure MapearCampos; override;
procedure ImportarDetalhes(const AModel: ICompilacaoModel); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExportarRegistro: ICompilacaoModel; override;
procedure CreateDataSet; override;
property Numero: integer read GetNumero write SetNumero;
property ChangeSet: string read GetChangeSet;
end;
implementation
uses
System.SysUtils, Vigilante.Compilacao.Model.Impl, Module.ValueObject.URL.Impl;
constructor TCompilacaoDataSet.Create(AOwner: TComponent);
begin
inherited;
FChangeSet := TStringList.Create;
end;
destructor TCompilacaoDataSet.Destroy;
begin
FreeAndNil(FChangeSet);
inherited;
end;
function TCompilacaoDataSet.ExportarRegistro: ICompilacaoModel;
begin
Result := TCompilacaoModel.Create(Numero, Nome, TURL.Create(Self.URL),
Situacao, Building, nil);
Result.DefinirID(ID);
end;
procedure TCompilacaoDataSet.CreateDataSet;
begin
FieldDefs.Add('Numero', ftInteger);
FieldDefs.Add('ChangeSet', ftMemo);
inherited;
ConfigurarCampos;
LogChanges := False;
end;
procedure TCompilacaoDataSet.ConfigurarCampos;
begin
inherited;
FoChangeSet.Visible := False;
end;
procedure TCompilacaoDataSet.ImportarDetalhes(const AModel: ICompilacaoModel);
begin
inherited;
Atualizar := not(AModel.Situacao in [sbSucesso, sbFalhou, sbAbortado,
sbFalhouInfra]);
CarregarChangeSet(AModel.ChangeSet);
end;
procedure TCompilacaoDataSet.MapearCampos;
begin
inherited;
FoNumero := FindField('Numero');
FoSituacaoBuild := FindField('SituacaoBuild');
FoChangeSet := FindField('ChangeSet') as TMemoField;
end;
procedure TCompilacaoDataSet.CarregarChangeSet(const AChangeSet
: TObjectList<TChangeSetItem>);
const
AUTOR = 'Autor: %s - %s';
ARQUIVO = ' - %s';
var
_changeSetItem: TChangeSetItem;
_arquivo: string;
_str: TStringList;
begin
if AChangeSet.Count = 0 then
Exit;
_str := TStringList.Create;
try
FChangeSet.Clear;
for _changeSetItem in AChangeSet do
begin
_str.Add(Format(AUTOR, [_changeSetItem.AUTOR, _changeSetItem.Descricao]));
for _arquivo in _changeSetItem.ArquivosAlterados do
_str.Add(Format(ARQUIVO, [_arquivo]));
_str.Add('');
end;
FoChangeSet.AsString := _str.Text;
finally
FreeAndNil(_str);
end;
end;
function TCompilacaoDataSet.GetNumero: integer;
begin
Result := FoNumero.AsInteger;
end;
procedure TCompilacaoDataSet.SetNumero(const Value: integer);
begin
FoNumero.AsInteger := Value;
end;
function TCompilacaoDataSet.GetChangeSet: string;
begin
Result := FoChangeSet.AsString;
end;
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.11.18
* @Brief:
* @References:
* Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility
*}
unit org.algorithms.time;
interface
uses
Winapi.Windows,
org.algorithms,
org.algorithms.queue,
org.utilities.thread;
type
TExpireRoutine<T> = procedure (Waiter: T) of object;
TTimer<T> = class
Waiter: T;
ExpireTime: Int64;
Canceled: Boolean;
ExpireRoutine: TExpireRoutine<T>;
end;
TTimeWheel<T> = class(TSingleThread)
public const
DAY_MICROSECONDS: Int64 = 24 * 60 * 60 * 1000;
HOUR_MICROSECONDS: Int64 = 60 * 60 * 1000;
MINUTE_MICROSECONDS: Int64 = 60 * 1000;
SECONDS_MICROSECONDS: Int64 = 1000;
public type
PTick = ^TTick;
TTick = record
Tick: Integer;
Second: Integer;
Minute: Integer;
Hour: Integer;
Day: Integer;
Timer: TTimer<T>
end;
TArrayDay = array of TFlexibleQueue<PTick>;
TArrayHour = array [0..23] of TFlexibleQueue<PTick>;
TArrayMinute = array [0..59] of TFlexibleQueue<PTick>;
TArraySecond = array [0..59] of TFlexibleQueue<PTick>;
TArrayTick = array of TFlexibleQueue<PTick>;
private
FArrayDay: TArrayDay;
FArrayHour: TArrayHour;
FArrayMinute: TArrayMinute;
FArraySecond: TArraySecond;
FArrayTick: TArrayTick;
FAvaliablePTick: TFlexibleQueue<PTick>;
FAvaliableTimer: TFlexibleQueue<TTimer<T>>;
FTick: Integer; // 定时器精度,(FTick - Ftick div 2, FTick + Ftick div 2)
FTicksPerSecond: Integer;
FDays: Integer;
FCurrentDay: Integer;
FCurrentHour: Integer;
FCurrentMinute: Integer;
FCurrentSecond: Integer;
FCurrentTick: Integer;
procedure PerTickBookKeeping;
procedure SetDays(const Value: Integer);
procedure SetTick(const Value: Integer);
procedure OnPTickNotify(const Value: PTick; Action: TActionType);
procedure OnTimerNotify(const Value: TTimer<T>; Action: TActionType);
function DequeuePTick: PTick;
function DequeueTimer: TTimer<T>;
procedure EnqueuePTick(ATick: PTick);
procedure EnqueueTimer(ATimer: TTimer<T>);
public
constructor Create;
destructor Destroy; override;
function StartTimer(AWaiter: T; ExpireTime: Int64; ExpireRoutine: TExpireRoutine<T>): TTimer<T>;
procedure StopTimer(ATimer: TTimer<T>);
procedure Execute; override;
procedure Start; override;
procedure Stop; override;
property Tick: Integer read FTick write SetTick;
property Days: Integer read FDays write SetDays;
end;
implementation
{ TTimeWheel<T> }
constructor TTimeWheel<T>.Create;
begin
FTick := TIME_WHEEL_TICK;
FTicksPerSecond := 1000 div FTick;
FDays := TIME_WHEEL_DAY;
FCurrentDay := 0;
FCurrentHour := 0;
FCurrentMinute := 0;
FCurrentSecond := 0;
FCurrentTick := 0;
FAvaliablePTick := TFlexibleQueue<PTick>.Create(64);
FAvaliablePTick.OnItemNotify := OnPTickNotify;
FAvaliableTimer := TFlexibleQueue<TTimer<T>>.Create(64);
FAvaliableTimer.OnItemNotify := OnTimerNotify;
inherited;
end;
destructor TTimeWheel<T>.Destroy;
begin
FAvaliablePTick.Free();
FAvaliableTimer.Free();
inherited;
end;
procedure TTimeWheel<T>.EnqueuePTick(ATick: PTick);
begin
ATick^.Tick := 0;
ATick^.Second := 0;
ATick^.Minute := 0;
ATick^.Hour := 0;
ATick^.Day := 0;
ATick^.Timer := nil;
FAvaliablePTick.Enqueue(ATick);
end;
procedure TTimeWheel<T>.EnqueueTimer(ATimer: TTimer<T>);
begin
ATimer.Waiter := Default(T);
ATimer.ExpireTime := 0;
ATimer.Canceled := False;
ATimer.ExpireRoutine := nil;
FAvaliableTimer.Enqueue(ATimer);
end;
procedure TTimeWheel<T>.Execute;
begin
Sleep(FTick);
while not FTerminated do begin
PerTickBookKeeping();
Sleep(FTick);
end;
end;
function TTimeWheel<T>.DequeuePTick: PTick;
begin
Result := FAvaliablePTick.Dequeue();
if Result = nil then begin
Result := AllocMem(SizeOf(TTick));
Result^.Tick := 0;
Result^.Second := 0;
Result^.Minute := 0;
Result^.Hour := 0;
Result^.Day := 0;
Result^.Timer := nil;
end;
end;
function TTimeWheel<T>.DequeueTimer: TTimer<T>;
begin
Result := FAvaliableTimer.Dequeue();
if Result = nil then begin
Result := TTimer<T>.Create();
Result.Waiter := Default(T);
Result.ExpireTime := 0;
Result.Canceled := False;
Result.ExpireRoutine := nil;
end;
end;
procedure TTimeWheel<T>.OnPTickNotify(const Value: PTick; Action: TActionType);
begin
if Action = atDelete then
FreeMem(Value);
end;
procedure TTimeWheel<T>.OnTimerNotify(const Value: TTimer<T>;
Action: TActionType);
begin
if Action = atDelete then
Value.Free();
end;
procedure TTimeWheel<T>.PerTickBookKeeping;
var
ATick: PTick;
ATimer: TTimer<T>;
begin
Inc(FCurrentTick);
FCurrentTick := FCurrentTick mod FTicksPerSecond;
if FCurrentTick = 0 then begin // 下一秒
Inc(FCurrentSecond);
FCurrentSecond := FCurrentSecond mod 60;
if FCurrentSecond = 0 then begin {$region 下一分}
Inc(FCurrentMinute);
FCurrentMinute := FCurrentMinute mod 60;
if FCurrentMinute = 0 then begin {$Region 下一时}
Inc(FCurrentHour);
FCurrentHour := FCurrentHour mod 24;
if FCurrentHour = 0 then begin {$Region 下一天}
Inc(FCurrentDay);
FCurrentDay := FCurrentDay mod FDays;
// 1.将当天缓存的定时器分发到FArrayHour中去
// 2.将FArrayHour[FCurrentHour]中的定时器分发到FArrayMinute中去
// 3.将FArrayMinute[FCurrentMinute]中的定时器分发到FArraySecond中去
// 4.将FArraySecond[FCurrentSecond]中的定时器分发到FArrayTick中去
// 5.处理FArrayTick[FCurrentTick]中的定时器
while not FArrayDay[FCurrentDay].Empty() do begin
ATick := FArrayDay[FCurrentDay].DequeueEx();
FArrayHour[ATick^.Hour].Enqueue(ATick);
end;
while not FArrayHour[FCurrentHour].Empty() do begin
ATick := FArrayHour[FCurrentHour].DequeueEx();
FArrayMinute[ATick^.Minute].Enqueue(ATick);
end;
while not FArrayMinute[FCurrentMinute].Empty() do begin
ATick := FArrayMinute[FCurrentMinute].DequeueEx();
FArraySecond[ATick^.Second].Enqueue(ATick);
end;
while not FArraySecond[FCurrentSecond].Empty() do begin
ATick := FArraySecond[FCurrentSecond].DequeueEx();
FArrayTick[ATick^.Tick].Enqueue(ATick);
end;
// 处理FArrayTick[FCurrentTick]
//
end
{$endregion}
else begin
// 1.将FArrayHour[FCurrentHour]中的定时器分发到FArrayMinute中去
// 2.将FArrayMinute[FCurrentMinute]中的定时器分发到FArraySecond中去
// 3.将FArraySecond[FCurrentSecond]中的定时器分发到FArrayTick中去
// 4.处理FArrayTick[FCurrentTick]中的定时器
while not FArrayHour[FCurrentHour].Empty() do begin
ATick := FArrayHour[FCurrentHour].DequeueEx();
FArrayMinute[ATick^.Minute].Enqueue(ATick);
end;
while not FArrayMinute[FCurrentMinute].Empty() do begin
ATick := FArrayMinute[FCurrentMinute].DequeueEx();
FArraySecond[ATick^.Second].Enqueue(ATick);
end;
while not FArraySecond[FCurrentSecond].Empty() do begin
ATick := FArraySecond[FCurrentSecond].DequeueEx();
FArrayTick[ATick^.Tick].Enqueue(ATick);
end;
// 处理FArrayTick[FCurrentTick]
//
end;
end
{$endregion}
else begin
// 1. 将当前FArrayMinute[FCurrentMinute]中缓存的定时器分发到FArraySecond中
// 2. 将当前FArraySecond[FCurrentSecond]中缓存的定时器分发到FArrayTick中
// 3. 处理当前FArrayTick[FCurrentTick]
while not FArrayMinute[FCurrentMinute].Empty() do begin
ATick := FArrayMinute[FCurrentMinute].DequeueEx();
FArraySecond[ATick^.Second].Enqueue(ATick);
end;
while not FArraySecond[FCurrentSecond].Empty() do begin
ATick := FArraySecond[FCurrentSecond].DequeueEx();
FArrayTick[ATick^.Tick].Enqueue(ATick);
end;
// 处理FArrayTick[FCurrentTick]
//
end;
end
{$endregion}
else begin
// 1.将FArraySecond[FCurrentSecond]中的定时器分发到FArrayTick中去
// 2.处理FArrayTick[FCurrentTick]中的定时器
while not FArraySecond[FCurrentSecond].Empty() do begin
ATick := FArraySecond[FCurrentSecond].DequeueEx();
FArrayTick[ATick^.Tick].Enqueue(ATick);
end;
// 处理FArrayTick[FCurrentTick]
//
end;
end;
begin
// 处理FArrayTick[FCurrentTick]
//
while not FArrayTick[FCurrentTick].Empty() do begin
ATick := FArrayTick[FCurrentTick].DequeueEx();
ATimer := ATick^.Timer;
EnqueuePTick(ATick);
if not ATimer.Canceled then
ATimer.ExpireRoutine(ATimer.Waiter);
EnqueueTimer(ATimer);
end;
end;
end;
procedure TTimeWheel<T>.SetDays(const Value: Integer);
begin
FDays := Value;
end;
procedure TTimeWheel<T>.SetTick(const Value: Integer);
begin
FTick := Value;
end;
procedure TTimeWheel<T>.Start;
var
I: Integer;
begin
SetLength(FArrayDay, FDays);
for I := 0 to FDays - 1 do begin
FArrayDay[I] := TFlexibleQueue<PTick>.Create(64);
FArrayDay[I].OnItemNotify := OnPTickNotify;
end;
for I := 0 to 24 - 1 do begin
FArrayHour[I] := TFlexibleQueue<PTick>.Create(64);
FArrayHour[I].OnItemNotify := OnPTickNotify;
end;
for I := 0 to 60 - 1 do begin
FArrayMinute[I] := TFlexibleQueue<PTick>.Create(64);
FArrayMinute[I].OnItemNotify := OnPTickNotify;
end;
for I := 0 to 60 - 1 do begin
FArraySecond[I] := TFlexibleQueue<PTick>.Create(64);
FArraySecond[I].OnItemNotify := OnPTickNotify;
end;
SetLength(FArrayTick, FTicksPerSecond);
for I := 0 to FTicksPerSecond - 1 do begin
FArrayTick[I] := TFlexibleQueue<PTick>.Create(64);
FArrayTick[I].OnItemNotify := OnPTickNotify;
end;
inherited;
end;
function TTimeWheel<T>.StartTimer(AWaiter: T; ExpireTime: Int64; ExpireRoutine: TExpireRoutine<T>): TTimer<T>;
var
Day: Integer;
Hour: Integer;
Minute: Integer;
Second: Integer;
Tick: Integer;
ATimer: TTimer<T>;
ATick: PTick;
begin
// 1. 检查超时限是否在指定范围内,FTick < ExpireTime < FDays * DAY_MICROSECONDS
// 2. 计算CurrentTick + ExpireTimed对应的绝对时间[dd:hh:mm:ss]
// dxm 2018.11.20
// 如果Day = FCurrentDay,在满足1.的情况下,只能说明ExpireTime小于1天
// 如果Hour = FCurrentHour,说明ExpireTime小于1小时
// 如果Minute = FCurrentMinute,说明ExpireTime小于1分钟
// 如果Second = FCurrentSecond,说明ExpireTime小于1秒钟
// //如果Tick = FCurrentTick,说明ExpireTime小于1个Tick // 不允许此种情形
// ATimer := FAvaliableTimer.Dequeue();
// ATick := FAvaliablePTick.Dequeue();
// ATick^.Tick := Tick;
// ATick^.Timer := ATick;
// FArrayTick[ATick] := ATick;
// ......
//
//
Result := nil;
if (ExpireTime > FTick) and (ExpireTime < FDays * DAY_MICROSECONDS) then begin
Day := (FCurrentDay + ExpireTime div DAY_MICROSECONDS) mod FDays;
Hour := (FCurrentHour + ExpireTime div HOUR_MICROSECONDS) mod 24;
Minute := (FCurrentMinute + ExpireTime div MINUTE_MICROSECONDS) mod 60;
Second := (FCurrentSecond + ExpireTime div SECONDS_MICROSECONDS) mod 60;
Tick := (FCurrentTick + ExpireTime div FTick) mod FTicksPerSecond;
ATimer := DequeueTimer();
ATimer.Waiter := AWaiter;
ATimer.ExpireTime := ExpireTime;
ATimer.Canceled := False;
ATimer.ExpireRoutine := ExpireRoutine;
ATick := DequeuePTick();
ATick^.Tick := Tick;
ATick^.Second := Second;
ATick^.Minute := Minute;
ATick^.Hour := Hour;
ATick^.Day := Day;
ATick^.Timer := ATimer;
if (Day = FCurrentDay) or
((Day = ((FCurrentDay + 1) mod FDays)) and (Day < FCurrentDay)) then begin
if (Hour = FCurrentHour) or
((Hour = ((FCurrentHour + 1) mod 24)) and (Minute < FCurrentMinute)) then begin
if (Minute = FCurrentMinute) or
((Minute = ((FCurrentMinute + 1) mod 60)) and (Second < FCurrentSecond)) then begin
if (Second = FCurrentSecond) or
((Second = ((FCurrentSecond + 1) mod 60)) and (Tick < FCurrentTick)) then begin
FArrayTick[Tick].Enqueue(ATick);
end
else begin
FArraySecond[Second].Enqueue(ATick);
end;
end
else begin
FArrayMinute[Minute].Enqueue(ATick);
end;
end
else begin
FArrayHour[Hour].Enqueue(ATick);
end;
end
else begin
FArrayDay[Day].Enqueue(ATick);
end;
Result := ATimer;
end;
end;
procedure TTimeWheel<T>.Stop;
var
I: Integer;
begin
inherited;
for I := 0 to FDays - 1 do
FArrayDay[I].Free();
for I := 0 to 24 - 1 do
FArrayHour[I].Free();
for I := 0 to 60 - 1 do
FArrayMinute[I].Free();
for I := 0 to 60 - 1 do
FArraySecond[I].Free();
for I := 0 to FTicksPerSecond - 1 do
FArrayTick[I].Free();
end;
procedure TTimeWheel<T>.StopTimer(ATimer: TTimer<T>);
begin
ATimer.Canceled := True;
end;
end.
|
unit Regi1632;
{**************************************************************************
TRegistry1632
This unit provides access to the registry in Delphi 1.0 AND Delphi 2.0
Author: Hannes Danzl (e9026733@stud3.tuwien.ac.at)
FREEWARE
If you change it, please send me a copy!!
When running the Application in Windows 3.x the registry-functions do
nothing!
************************************************************************** }
{$R-}
interface
uses Classes, SysUtils,
{$ifdef win32}Windows{$else}Wintypes, Winprocs, Reginc{$endif};
const keynotfoundvalue='xyxyxyxyxyxyxyxyxyxyxyxyxyx';
type
TRegistry1632 = class(TComponent)
private
fRunningWin31:Boolean;
fIniFileName:String;
fWasError:Boolean;
fErrorMessage:String;
function ReadKey(Where:LongInt;Key, Path:String):string;
procedure WriteKey(Where:LongInt;Key, Path, Value:String);
protected
public
constructor Create(AOwner:TComponent);override;
destructor Destroy; override;
{ Reads a Value from the registry in HKEY_LOCAL_MACHINE }
function ReadString(Path, Key:String): string;
{ Reads a Value from the registry in HKEY_CURRENT_USER }
function ReadUserString(Path, Key:string): string;
{ Writes a Value to the registry in HKEY_LOCAL_MACHINE }
procedure WriteString(Path, Key, Value:String);
{ Writes a Value from the registry in HKEY_CURRENT_USER }
procedure WriteUserString(Path, Key, Value:String);
property WasError:boolean read fWasError;
property ErrorMessage:string read fErrorMessage;
published
property RunningWin31:Boolean read FRunningWin31 write FRunningWin31;
property IniFileName:string read fIniFileName write fIniFileName;
end;
procedure Register;
implementation
uses dialogs, inifiles;
procedure Register;
begin
RegisterComponents('Samples', [TRegistry1632]);
end;
constructor TRegistry1632.Create;
var along1,along2,along:longint;
mainversion, subversion:longint;
begin
inherited Create(AOwner);
IniFileName:='registry.ini';
fWasError:=false;
fErrorMessage:='';
frunningwin31:=false;
{$ifndef win32}
{ check for windowsnt or wind95 }
{ thanks to Per Bak (Per.Bak@post3.tele.dk), who corrected the bug! }
if (GetWinFlags and $4000 {WF_WINNT} ) = 0 then
if lobyte(loword(getversion))<4 then
if hibyte(loword(getversion))<95 then
frunningwin31:=true;
{$endif}
end;
destructor TRegistry1632.Destroy;
begin
inherited Destroy;
end;
procedure TRegistry1632.WriteString(Path, Key, Value:String);
begin
WriteKey(HKEY_LOCAL_MACHINE,Key,path, Value);
end;
procedure TRegistry1632.WriteUserString(Path, Key, Value:String);
begin
WriteKey(HKEY_CURRENT_USER,Key,path, Value);
end;
procedure TRegistry1632.WriteKey(Where:LongInt;Key, Path, Value:String);
var
aValue:array[0..256] of char;
aname:array[0..256] of char;
DataType:Longint;
DataLen:longint;
QueryResult:LongInt;
aIniFile:TInifile;
{$ifdef win32}
KeyHandle: HKEY;
{$else}
KeyHandle: LongInt;
{$endif}
begin
fwaserror:=false;
if runningwin31 then
begin
try
aIniFile:=TIniFile.Create(IniFileName);
if where=HKEY_LOCAL_MACHINE then
path:='LM_'+path
else
path:='CU_'+path;
aIniFile.WriteString(path,key,value);
except
ainifile.free;
ferrormessage:=Format('Writekey to Inifile failed: %s set to %s in file %s',
[Path+Key, Value, IniFileName]);
fwaserror:=true;
end;
ainifile.free;
exit;
end;
strpcopy(aname,Path);
if RegOpenKeyEx(where,aname,0,KEY_ALL_ACCESS, keyHandle)<>error_success then
begin
ferrormessage:=Format('Openkey failed for path "%s"', [Path]);
fwaserror:=true;
exit;
end;
strpcopy(avalue,value);
DataType := REG_SZ;
DataLen:=strlen(avalue);
strpcopy(aname,key);
QueryResult:=RegSetValueEx(KeyHandle, @aName, 0, DataType, PByte(@aValue),
DataLen);
if QueryResult <> ERROR_SUCCESS then
begin
ferrormessage:=Format('RegSetValueEX failed for path "%s" key "%s"', [Path, Key]);
fwaserror:=true;
exit;
end;
if Keyhandle<>0 then
RegCloseKey(Keyhandle);
end;
function TRegistry1632.ReadString(Path: string; Key:String): string;
begin
Result:=ReadKey(HKEY_LOCAL_MACHINE,Key, path);
end;
function TRegistry1632.ReadUserString(Path: string; Key:string): string;
begin
Result:=ReadKey(HKEY_CURRENT_USER,Key, path);
end;
function TRegistry1632.ReadKey(Where:LongInt;Key, Path:String):string;
var
aresult:array[0..256] of char;
aname:array[0..256] of char;
{$ifdef win32}
bufsize:Integer;
DataType:Integer;
KeyHandle: HKEY;
{$else}
bufsize:Longint;
DataType:Longint;
KeyHandle: LongInt;
{$endif}
QueryResult:longint;
aIniFile:TIniFile;
begin
fWasError:=false;
if runningwin31 then
begin
try
aIniFile:=TIniFile.Create(IniFileName);
if where=HKEY_LOCAL_MACHINE then
path:='LM_'+path
else
path:='CU_'+path;
result:=aIniFile.ReadString(path,key,keynotfoundvalue);
if result=keynotfoundvalue then
begin
result:='';
ferrormessage:=Format('Key "%s" not found in pathh "%s"; FileName: "%s"', [Path, Key, IniFileName]);
fwaserror:=true;
exit;
end;
except
ainifile.free;
result:='';
ferrormessage:=Format('Key "%s" not found in path "%s"; FileName: "%s"', [Path, Key, IniFileName]);
fwaserror:=true;
exit;
end;
ainifile.free;
exit;
end;
strpcopy(aname,Path);
result:='';
if RegOpenKeyEx(where,aname,0,KEY_ALL_ACCESS, keyHandle)<>error_success then
begin
ferrormessage:=Format('Openkey failed for path "%s"', [Path]);
fwaserror:=true;
exit;
end;
DataType := REG_SZ;
BufSize:=255;
strpcopy(aname,key);
{$ifndef win32}
QueryResult:=RegQueryValueEx(KeyHandle, @aName, nil, @DataType, PByte(@aresult),
BufSize);
{$else}
QueryResult:=RegQueryValueEx(KeyHandle, @aName, nil, pDWord(@DataType), PByte(@aresult),
pDWord(@BufSize));
{$endif}
if QueryResult <> ERROR_SUCCESS then
begin
ferrormessage:=Format('Key "%s" not found in path "%s"; FileName: "%s"', [Path, Key, IniFileName]);
fwaserror:=true;
end
else
result:=strpas(aresult);
if Keyhandle<>0 then
RegCloseKey(Keyhandle);
end;
end.
|
unit UCfop;
interface
uses DateUtils, SysUtils;
type Cfop = class
protected
Id : Integer;
Nome : string[100];
Numero : string[5];
DataCadastro : TDateTime;
DataAlteracao : TDateTime;
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setId (vId : Integer);
Procedure setNome (vNome : string);
Procedure setNumero (vNumero : string);
Procedure setDataCadastro (vDataCadastro : TDateTime);
Procedure setDataAlteracao (vDataAlteracao : TDateTime);
Function getId : integer;
Function getNome : String;
Function getNumero : string;
Function getDataCadastro :TDateTime;
Function getDataAlteracao : TDateTime;
end;
implementation
{ Cfop }
constructor Cfop.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
Id := 0;
Nome := '';
Numero := '';
DataCadastro := dataAtual;
DataAlteracao := dataAtual;
end;
destructor Cfop.Destrua_Se;
begin
end;
function Cfop.getDataAlteracao: TDateTime;
begin
Result := DataAlteracao;
end;
function Cfop.getDataCadastro: TDateTime;
begin
Result := DataCadastro;
end;
function Cfop.getId: integer;
begin
Result := Id;
end;
function Cfop.getNome: String;
begin
Result := Nome;
end;
function Cfop.getNumero: String;
begin
Result := Numero;
end;
procedure Cfop.setDataAlteracao(vDataAlteracao: TDateTime);
begin
DataAlteracao := vDataAlteracao;
end;
procedure Cfop.setDataCadastro(vDataCadastro: TDateTime);
begin
DataCadastro := vDataCadastro;
end;
procedure Cfop.setId(vId: Integer);
begin
Id := vId;
end;
procedure Cfop.setNome(vNome: string);
begin
Nome := vNome;
end;
procedure Cfop.setNumero(vNumero: string);
begin
Numero := vNumero;
end;
end.
|
unit Vigilante.Compilacao.Service.Impl;
interface
uses
System.StrUtils, System.JSON, System.SysUtils, Vigilante.Compilacao.Service,
Vigilante.Compilacao.Model, Vigilante.Compilacao.Repositorio,
Vigilante.Compilacao.Event;
type
TCompilacaoService = class(TInterfacedObject, ICompilacaoService)
private
FCompilacaoEvent: ICompilacaoEvent;
FCompilacaoRepositorio: ICompilacaoRepositorio;
function TratarURL(const AURL: string): string;
function PegarRepositorio: ICompilacaoRepositorio;
procedure LancarEvento(const ACompilacaoModel: ICompilacaoModel);
public
constructor Create(const ACompilacaoRepositorio: ICompilacaoRepositorio;
const ACompilacaoEvent: ICompilacaoEvent);
function AtualizarCompilacao(const ACompilacaoModel: ICompilacaoModel)
: ICompilacaoModel;
end;
implementation
uses
ContainerDI;
constructor TCompilacaoService.Create(const ACompilacaoRepositorio
: ICompilacaoRepositorio; const ACompilacaoEvent: ICompilacaoEvent);
begin
FCompilacaoRepositorio := ACompilacaoRepositorio;
FCompilacaoEvent := ACompilacaoEvent;
end;
function TCompilacaoService.AtualizarCompilacao(const ACompilacaoModel
: ICompilacaoModel): ICompilacaoModel;
var
_repositorio: ICompilacaoRepositorio;
_url: string;
_novaCompilacao: ICompilacaoModel;
begin
Result := nil;
_repositorio := PegarRepositorio;
_url := ACompilacaoModel.URL;
_url := TratarURL(_url);
_novaCompilacao := _repositorio.BuscarCompilacao(_url);
if not Assigned(_novaCompilacao) then
Exit;
_novaCompilacao.DefinirID(ACompilacaoModel.Id);
if not _novaCompilacao.Equals(ACompilacaoModel) then
LancarEvento(_novaCompilacao);
Result := _novaCompilacao;
end;
function TCompilacaoService.PegarRepositorio: ICompilacaoRepositorio;
begin
Result := FCompilacaoRepositorio;
end;
procedure TCompilacaoService.LancarEvento(const ACompilacaoModel
: ICompilacaoModel);
begin
if not Assigned(FCompilacaoEvent) then
Exit;
FCompilacaoEvent.Notificar(ACompilacaoModel);
end;
function TCompilacaoService.TratarURL(const AURL: string): string;
begin
Result := AURL;
if not AURL.EndsWith('api/json', True) then
Result := AURL + '/api/json';
end;
end.
|
{*******************************************************}
{ }
{ Midas Socket Server Intercepor Demo }
{ }
{*******************************************************}
unit Intrcptu;
{
NOTE: This demo requires the ZLib units found in the extras directory on the
CD.
The Socket Server has the ability to install an interception COM object that
can be called whenever it receives or sends data. Using this feature, you
can encrypt or compress data using any method you wish. This demo uses the
ZLib compression units that ship on the CD to compress/uncompress all data
going over the wire.
To use this demo;
1) Make sure you have copied the ZLib units from the CD to a directory and
have added that directory to this projects search path.
2) Compile Intrcpt.dpr.
3) Register Intrcpt.DLL using REGSVR32 or TREGSVR on both the client and the
server.
4) On the Server: Bring up the properties for the Socket Server (right click
on the icon in the task bar and select properties) and put the GUID for
Intrcpt.DLL in the Interceptor GUID edit control. The GUID is defined
below as Class_DataCompressor.
5) On the Client: Set the TSocketConnection.InterceptorGUID property to the
Class_DataCompressor GUID and recompile your client.
}
interface
uses
Windows, ActiveX, ComObj, SConnect;
type
{
The interception object needs to implement IDataIntercept defined in
SConnect.pas. This interface has 2 procedures DataIn and DataOut described
below.
}
TDataCompressor = class(TComObject, IDataIntercept)
protected
procedure DataIn(const Data: IDataBlock); stdcall;
procedure DataOut(const Data: IDataBlock); stdcall;
end;
const
Class_DataCompressor: TGUID = '{B249776C-E429-11D1-AAA4-00C04FA35CFA}';
implementation
uses ComServ, SysUtils, ZLib, Classes;
{
DataIn is called whenever data is coming into the client or server. Use this
procedure to uncompress or decrypt data.
}
procedure TDataCompressor.DataIn(const Data: IDataBlock);
var
Size: Integer;
InStream, OutStream: TMemoryStream;
ZStream: TDecompressionStream;
p: Pointer;
begin
InStream := TMemoryStream.Create;
try
{ Skip BytesReserved bytes of data }
p := Pointer(Integer(Data.Memory) + Data.BytesReserved);
Size := PInteger(p)^;
p := Pointer(Integer(p) + SizeOf(Size));
InStream.Write(p^, Data.Size - SizeOf(Size));
OutStream := TMemoryStream.Create;
try
InStream.Position := 0;
ZStream := TDecompressionStream.Create(InStream);
try
OutStream.CopyFrom(ZStream, Size);
finally
ZStream.Free;
end;
{ Clear the datablock, then write the uncompressed data back into the
datablock }
Data.Clear;
Data.Write(OutStream.Memory^, OutStream.Size);
finally
OutStream.Free;
end;
finally
InStream.Free;
end;
end;
{
DataOut is called whenever data is leaving the client or server. Use this
procedure to compress or encrypt data.
}
procedure TDataCompressor.DataOut(const Data: IDataBlock);
var
InStream, OutStream: TMemoryStream;
ZStream: TCompressionStream;
Size: Integer;
begin
InStream := TMemoryStream.Create;
try
{ Skip BytesReserved bytes of data }
InStream.Write(Pointer(Integer(Data.Memory) + Data.BytesReserved)^, Data.Size);
Size := InStream.Size;
OutStream := TMemoryStream.Create;
try
ZStream := TCompressionStream.Create(clFastest, OutStream);
try
ZStream.CopyFrom(InStream, 0);
finally
ZStream.Free;
end;
{ Clear the datablock, then write the compressed data back into the
datablock }
Data.Clear;
Data.Write(Size, SizeOf(Integer));
Data.Write(OutStream.Memory^, OutStream.Size);
finally
OutStream.Free;
end;
finally
InStream.Free;
end;
end;
initialization
TComObjectFactory.Create(ComServer, TDataCompressor, Class_DataCompressor,
'DataCompressor', 'SampleInterceptor', ciMultiInstance, tmApartment);
end.
|
unit Zlib.FunctionsProcedures;
interface
uses SysUtils, Classes, zlib;
procedure Decompress(SourcePath, DestPath:string);
procedure DecompressToMemory(Source: TMemoryStream; var Memory:TMemoryStream);
procedure DecompressFileToMemory(Source: TFileStream; var Memory:TMemoryStream);
procedure Compress(SourcePath, DestPath:string);
procedure CompressFileFromMemory(Source: TMemoryStream; var Dest:TFileStream);
procedure CompressMemoryFromMemory(Source: TMemoryStream; var Memory:TMemoryStream);
implementation
procedure Compress(SourcePath, DestPath:string);
var Source, Dest:TFileStream; CompressStream:TCompressionStream; bytesread:integer; mainbuffer:array[0..1023] of char;
begin
source:=TFileStream.Create(SourcePath,fmOpenReadWrite);
dest:=TFileStream.Create(DestPath,fmCreate);
CompressStream:=TCompressionStream.Create(clMax,dest);
try
repeat
bytesread:=source.Read(mainbuffer,1024);
CompressStream.Write(mainbuffer,bytesread);
until bytesread<1024;
except
CompressStream.free;
source.Free;
dest.Free;
exit;
end;
CompressStream.free;
source.Free;
dest.Free;
end;
procedure CompressFileFromMemory(Source: TMemoryStream; var Dest:TFileStream);
var
CompressStream: TCompressionStream;
bytesread:integer;
mainbuffer:array[0..1023] of char;
begin
CompressStream:=TCompressionStream.Create(clMax,dest);
try
repeat
bytesread:=source.Read(mainbuffer,1024);
CompressStream.Write(mainbuffer,bytesread);
until bytesread<1024;
except
CompressStream.free;
exit;
end;
CompressStream.free;
end;
procedure Decompress(SourcePath, DestPath:string);
var Source,Dest:TFileStream; decompressStream:TDecompressionStream; bytesread:integer; mainbuffer:array[0..1023] of char;
begin
source:=TFileStream.Create(SourcePath,fmOpenReadWrite);
dest:=TFileStream.Create(DestPath,fmCreate);
decompressStream:=TDecompressionStream.Create(source);
try
repeat
bytesread:=decompressStream.Read(mainbuffer,1024);
dest.Write(mainbuffer,bytesread);
until bytesread<1024;
except
decompressStream.Free;
source.Free;
dest.Free;
exit;
end;
decompressStream.Free;
source.Free;
dest.Free;
end;
procedure DecompressToMemory(Source: TMemoryStream; var Memory:TMemoryStream);
var
decompressStream:TDecompressionStream;
bytesread:integer; mainbuffer:array[0..1023] of char;
begin
Memory.Seek(0,0);
decompressStream:=TDecompressionStream.Create(source);
repeat
bytesread:=decompressStream.Read(mainbuffer,1024);
Memory.Write(mainbuffer,bytesread);
until bytesread<1024;
decompressStream.Free;
end;
procedure DecompressFileToMemory(Source: TFileStream; var Memory:TMemoryStream);
var
decompressStream:TDecompressionStream;
bytesread:integer; mainbuffer:array[0..1023] of char;
begin
Memory.Seek(0,0);
decompressStream:=TDecompressionStream.Create(source);
repeat
bytesread:=decompressStream.Read(mainbuffer,1024);
Memory.Write(mainbuffer,bytesread);
until bytesread<1024;
decompressStream.Free;
end;
procedure CompressMemoryFromMemory(Source: TMemoryStream; var Memory:TMemoryStream);
var
CompressStream: TCompressionStream;
bytesread:integer;
mainbuffer:array[0..1023] of char;
begin
Memory.Seek(0, 0);
CompressStream:=TCompressionStream.Create(clMax, Memory);
Source.Seek(0, 0);
try
repeat
bytesread:=source.Read(mainbuffer,1024);
CompressStream.Write(mainbuffer,bytesread);
until bytesread<1024;
except
CompressStream.free;
exit;
end;
CompressStream.free;
end;
end.
|
UNIT MorseTreeUnit;
INTERFACE
TYPE
NodePtr = ^Node;
Node = RECORD
left, right: NodePtr;
letter: CHAR;
fullCode: STRING;
END;
Tree = NodePtr;
PROCEDURE DisposeTree(var t: Tree);
FUNCTION FindNode(t: Tree; x: CHAR): NodePtr;
FUNCTION FindNodeByCode(t: Tree; x: STRING; count: INTEGER): NodePtr;
PROCEDURE Insert(VAR t: Tree; n: NodePtr);
FUNCTION NewNode(x: CHAR; c: STRING): NodePtr;
PROCEDURE WriteTreePreOrder(t: Tree);
IMPLEMENTATION
PROCEDURE DisposeTree(var t: Tree);
BEGIN
IF t <> NIL THEN begin
DisposeTree(t^.left);
DisposeTree(t^.right);
Dispose(t);
t := NIL;
END; (* IF *)
END; (* DisposeTree *)
FUNCTION FindNode(t: Tree; x: CHAR): NodePtr;
VAR n: NodePtr;
BEGIN
IF t = NIL THEN
FindNode := NIL
ELSE IF x = t^.letter THEN
FindNode := t
ELSE BEGIN
n := FindNode(t^.left, x);
IF (n = NIL) THEN BEGIN
n := FindNode(t^.right, x);
END; (* IF *)
FindNode := n;
END; (* IF *)
END; (* FindNode *)
FUNCTION FindNodeByCode(t: Tree; x: STRING; count: INTEGER): NodePtr;
BEGIN (* FindNodeByCode *)
IF t = NIL THEN
FindNodeByCode := NIL
ELSE IF x = t^.fullCode THEN
FindNodeByCode := t
ELSE IF x[count] = '.' THEN
FindNodeByCode := FindNodeByCode(t^.left, x, count + 1)
ELSE
FindNodeByCode := FindNodeByCode(t^.right, x, count + 1);
END; (* FindNodeByCode *)
PROCEDURE Insert(VAR t: Tree; n: NodePtr);
VAR count: INTEGER;
curr: NodePtr;
BEGIN (* Insert *)
count := 1;
curr := t;
WHILE ((count < Length(n^.fullCode))) DO BEGIN
IF (n^.fullCode[count] = '.') THEN BEGIN
curr := curr^.left;
END ELSE BEGIN
curr := curr^.right;
END; (* IF *)
Inc(count);
END; (* WHILE *)
IF (n^.fullCode[count] = '.') THEN BEGIN
curr^.left := n;
END ELSE BEGIN
curr^.right := n;
END; (* IF *)
END; (* Insert *)
FUNCTION NewNode(x: CHAR; c: STRING): NodePtr;
VAR n: NodePtr;
BEGIN (* NewNode *)
New(n);
n^.letter := x;
n^.fullCode := c;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END; (* NewNode *)
PROCEDURE WriteTreePreOrder(t: Tree);
BEGIN
if t <> NIL then begin
Write(t^.letter, '=', t^.fullCode, ' | ');
WriteTreePreOrder(t^.left);
WriteTreePreOrder(t^.right);
end;
END; (* WriteTreePreOrder *)
BEGIN (* MorseTreeUnit *)
END. (* MorseTreeUnit *) |
object frm_EditSQLBtns: Tfrm_EditSQLBtns
Left = 0
Top = 0
Caption = 'Add - Edit - Move SQL Buttons'
ClientHeight = 896
ClientWidth = 1248
Color = clBtnFace
Constraints.MinHeight = 680
Constraints.MinWidth = 980
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnClose = FormClose
OnCreate = FormCreate
OnShow = FormShow
DesignSize = (
1248
896)
PixelsPerInch = 96
TextHeight = 13
object jvspdbtn_CloseProgram: TJvSpeedButton
Left = 2
Top = 4
Width = 41
Height = 38
Hint = 'Close the SQL Btns Editor'
Glyph.Data = {
360C0000424D360C000000000000360000002800000020000000200000000100
180000000000000C0000232E0000232E00000000000000000001FFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFAFAEFEFEFE9E9E9E9E9E9E9E9
E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9E9EFEFEFFA
FAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFAFAE6E6E6CACACABDBDBDBCBCBCBCBC
BCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBCBDBDBDCACACAE6
E6E6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFAFAFAE6E6E6C5C5C53B49C32E3EC32E3EC32E3E
C32E3EC32E3EC32E3EC32E3EC32F3FC32F3FC32F3FC32F3FC32F3FC33C4AC3C5
C5C5E6E6E6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFAFAFAE6E6E6C6C6C63D4BC03747C43A49C43948C33846
C23745C23644C03341C03240BF2F3FBF2D3DBF2C3BBE2C3CBE2D3DBF2F3FC23E
4CC0C6C6C6E6E6E6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFAFAFAE6E6E6C6C6C63C4BC03B49C44756D0687AFF697CFF697C
FF697CFF697CFF697CFF697DFF697DFF6A7DFF6A7DFF6A7DFF687AFF3748CB2E
3EC13E4CC0C6C6C6E6E6E6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFAFAFAE6E6E6C6C6C63C4BBF3E4DC54C5BD16476FF6477FF6376FE6376
FE6376FE6376FE6376FE6376FE6376FE6376FE6376FE6376FE6478FF6476FF37
48CB2E3EC13E4CC0C6C6C6E6E6E6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FAFAFAE6E6E6C6C6C63C4BBF4351C7515FD26174FE6275FE6073FC6073FC6073
FC6073FC6073FC6073FC6073FC6073FC6073FC6073FC6073FC6073FC6275FE62
74FF3746CB2E3EC13E4CC0C6C6C6E6E6E6FAFAFAFFFFFFFFFFFFFFFFFFFAFAFA
E6E6E6C6C6C63B4BBF4754C85663D35E72FD5E72FD5D71FB5D71FB5D71FB5D71
FB5D71FB5D71FB5D71FB5D71FB5D71FB5D71FB5D71FB5D71FB5D71FB5D71FB5F
73FD5F73FE3647CB2F3EC13E4CC0C6C6C6E6E6E6FAFAFAFFFFFFFAFAFAE6E6E6
C5C5C53B4ABF4958C95A68D55D70FC5C70FC5B6FFA5B6FFA5B6FFA5B6FFA5B6F
FA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B6FFA5B
6FFA5D71FC5C71FD3647CB2F3EC13E4CC0C5C5C5E6E6E6FAFAFAEFEFEFCACACA
3B4ABF4D5ACA5F6CD65A6FFA596EFB596DF9596DF9596DF9596DF9596DF9596D
F9596DF9596DF9596DF9596DF9596DF9596DF9596DF9596DF9596DF9596DF959
6DF9596DF95B6FFB5A6EFB3647CA2F3FC13E4CC1CACACAEFEFEFE9E9E93A49C2
505DCC626FD8576CF9566BFA566BF8566BF8566BF8566BF8566BF8566BF8566B
F8566BF8566BF8566BF8566BF8566BF8566BF8566BF8566BF8566BF8566BF856
6BF8566BF8566BF8586DFA586CFA3646CB2F3FC23D4BC3E9E9E9E9E9E92B3BC2
6B75D1556AF95469F95469F75469F75469F75469F75469F75469F75469F75469
F75469F75469F75469F75469F75469F75469F75469F75469F75469F75469F754
69F75469F75469F75469F7566BF9576CFB2F3FC02F3FC4E9E9E9E9E9E92A3BC2
707BD25067FA5267F75267F65267F65267F65267F65267F65267F65267F65267
F65267F65267F65267F65267F65267F65267F65267F65267F65267F65267F652
67F65267F65267F65267F65368F7556BFC3141C02F3FC3E9E9E9E9E9E92A3AC2
7881D34D64F94E65F54F65F54F65F54F65F54F65F54F65F54F65F54F65F54F65
F54F65F54F65F54F65F54F65F54F65F54F65F54F65F54F65F54F65F54F65F54F
65F54F65F54F65F54F65F54F65F65168FA3645C12F3FC3E9E9E9E9E9E92A3AC1
7E86D64A61F74C63F44D63F44D63F44D63F44D63F44D63F44D63F44D63F44D63
F44D63F44D63F44D63F44D63F44D63F44D63F44D63F44D63F44D63F44D63F44D
63F44D63F44D63F44D63F44D63F54F66F93A48C22E3EC3E9E9E9E9E9E9293AC1
848CD7485FF64A61F34B61F34B61F34B61F34B61F34B61F34B61F34B61F34B61
F34B61F34B61F34B61F34B61F34B61F34B61F34B61F34B61F34B61F34B61F34B
61F34B61F34B61F34B61F34B61F44D63F83E4CC42E3EC3E9E9E9E9E9E92939C1
8991DA445CF4475EF1485FF1485FF1485FF1485FF1485FF1485FF1485FF1485F
F1485FF1485FF1485FF1485FF1485FF1485FF1485FF1485FF1485FF1485FF148
5FF1485FF1485FF1485FF1485FF24961F5424FC52E3EC3E9E9E9E9E9E92839C1
9097DB415BF3455DF0465EF0465EF0465EF0465EF0465EF0465EF0465EF0465E
F0465EF0465EF0465EF0465EF0465EF0465EF0465EF0465EF0465EF0465EF046
5EF0465EF0465EF0465EF0465EF14760F44553C52E3EC3E9E9E9E9E9E92838C1
969DDE3F58F1435BEF445CEF445CEF445CEF445CEF445CEF445CEF445CEF445C
EF445CEF445CEF445CEF445CEF445CEF445CEF445CEF445CEF445CEF445CEF44
5CEF445CEF445CEF445CEF445CF0445DF34755C72E3EC3E9E9E9E9E9E92838C1
9BA3DF3B55F04059EE415AEE415AEE415AEE415AEE415AEE415AEE415AEE415A
EE415AEE415AEE415AEE415AEE415AEE415AEE415AEE415AEE415AEE415AEE41
5AEE415AEE415AEE415AEE415AEF415BF24B58C72E3EC3E9E9E9E9E9E92738C1
A2A8E13853EF3E57ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58
ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F58ED3F
58ED3F58ED3F58ED3F58ED3F58ED3E58F14E5BC82D3DC3E9E9E9E9E9E92737C1
A6ADE23550EE3B54EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56
EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D56EC3D
56EC3D56EC3D56EC3D56EC3D56ED3C56F0515DCA2D3DC2E9E9E9EFEFEF2738C1
ACB3E53752EC3551EB3953EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54
EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A54EB3A
54EB3A54EB3A54EB3A54EB3954ED3A53ED535FCC2D3DC3EFEFEFFAFAFA3C4AC5
7C86D89CA5E73750EA334FEA3751EA3852EA3852EA3852EA3852EA3852EA3852
EA3852EA3852EA3852EA3852EA3852EA3852EA3852EA3852EA3852EA3852EA38
52EA3852EA3852EA3651EB3852EB5461D24654C93F4EC6FAFAFAFFFFFFFAFAFA
3D4BC5828AD9A3ACE9344FEA314CE9354FE93650E93650E93650E93650E93650
E93650E93650E93650E93650E93650E93650E93650E93650E93650E93650E936
50E93650E9344FEA354FE95A68D44B58CA4250C7FAFAFAFFFFFFFFFFFFFFFFFF
FAFAFA3C4BC58890DBAAB1EB314CE92E4AE8324DE8334EE8334EE8334EE8334E
E8334EE8334EE8334EE8334EE8334EE8334EE8334EE8334EE8334EE8334EE832
4EE8314CE9324EE95F6DD5505DCB4250C6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFAFAFA3B4AC58C95DCB1B9ED2F4AE72B47E7304BE7314CE7314CE7314C
E7314CE7314CE7314CE7314CE7314CE7314CE7314CE7314CE7314CE7314CE72F
4AE8314BE76573D75560CC414FC6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFAFAFA3B49C4939ADFB9BFEE2D48E62945E62E49E62F4AE62F4A
E62F4AE62F4AE62F4AE62F4AE62F4AE62F4AE62F4AE62F4AE62F4AE62C48E72E
49E76A78D95865CD404EC6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFAFAFA3B49C499A0E0BDC3F02B45E52643E52A46E52A46
E52A47E52A47E52A47E52A47E52A47E52A47E52B47E52A47E52945E62B46E66F
7CDA5D69CF404EC6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFAFAFA3B49C499A0E0B8BEEF2642E41F3DE4213E
E4213FE4223FE42240E42240E52340E52341E52441E52341E52744E57480DC60
6CD0404EC6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFAFA3B49C4949DE0BDC3EEA2ACEB9FA8
EA9AA5E895A0E7919BE68D98E58893E2838EE37E8BE17985DF808BDD6470D140
4DC6FAFAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFAFA3B4AC62737C12737C02838
C12838C12939C12939C1293AC12A3AC12A3AC12A3AC12B3BC12B3BC23E4DC6FA
FAFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF}
OnClick = jvspdbtn_CloseProgramClick
end
object grp_DataBase: TGroupBox
Left = 0
Top = 630
Width = 1240
Height = 258
Anchors = [akLeft, akBottom]
Caption = 'Button Definitions:'
Color = clMoneyGreen
ParentBackground = False
ParentColor = False
TabOrder = 2
object lbl_SQLText: TLabel
Left = 912
Top = 10
Width = 125
Height = 13
Caption = 'SQL Extended Statement:'
end
object gmshpbtn_SelectedUp: TgemShapeBtn
Left = 852
Top = 42
Width = 31
Height = 40
ShapeStyle.TextStyle = txNone
ShapeStyle.LineColor = clGray
ShapeStyle.LineStyle = fmRelief
ShapeStyle.LineWidth = 3
ShapeStyle.FillColor = clBtnFace
ShapeStyle.ShadowColor = clBlue
ShapeStyle.XRadius = 5
ShapeStyle.YRadius = 5
ShapeStyle.MouseDownLuma = 35
Shape = drUpArrow
Border = True
Caption = 'Up'
OnClick = gmshpbtn_SelectedUpClick
end
object gmshpbtn_SelectedDown: TgemShapeBtn
Left = 852
Top = 88
Width = 31
Height = 40
ShapeStyle.TextStyle = txNone
ShapeStyle.LineColor = clGray
ShapeStyle.LineStyle = fmRelief
ShapeStyle.LineWidth = 3
ShapeStyle.FillColor = clBtnFace
ShapeStyle.ShadowColor = clBlue
ShapeStyle.XRadius = 5
ShapeStyle.YRadius = 5
ShapeStyle.MouseDownLuma = 35
Shape = drDownArrow
Border = True
Caption = 'Down'
OnClick = gmshpbtn_SelectedDownClick
end
object gmshpbtn_SelectedMove: TgemShapeBtn
Left = 233
Top = 187
Width = 191
Height = 55
Hint = 'Move selected btn definition to different column'
ShapeStyle.TextStyle = txNone
ShapeStyle.LineColor = clGray
ShapeStyle.LineStyle = fmRelief
ShapeStyle.LineWidth = 3
ShapeStyle.FillColor = clBtnFace
ShapeStyle.ShadowColor = clBlue
ShapeStyle.XRadius = 5
ShapeStyle.YRadius = 5
ShapeStyle.MouseDownLuma = 35
Shape = drRightArrow
Border = True
Caption = 'Click to Move Selected Btn to Col:'
ShowHint = True
ParentShowHint = False
OnClick = gmshpbtn_SelectedMoveClick
end
object shp1: TShape
Left = 224
Top = 186
Width = 3
Height = 63
end
object shp_1: TShape
Left = 901
Top = 14
Width = 4
Height = 228
end
object dbnvgr_SQLBtns: TDBNavigator
Left = 5
Top = 184
Width = 210
Height = 18
VisibleButtons = [nbFirst, nbPrior, nbNext, nbLast, nbRefresh]
TabOrder = 0
end
object jvdbltmgrd_SQLBtnDataGrd: TJvDBUltimGrid
Left = 3
Top = 12
Width = 837
Height = 169
TabOrder = 1
TitleFont.Charset = DEFAULT_CHARSET
TitleFont.Color = clWindowText
TitleFont.Height = -11
TitleFont.Name = 'Tahoma'
TitleFont.Style = []
OnCellClick = jvdbltmgrd_SQLBtnDataGrdCellClick
IniStorage = jvfrmstrg_SQLBtns
TitleArrow = True
SelectColumnsDialogStrings.Caption = 'Select columns'
SelectColumnsDialogStrings.OK = '&OK'
SelectColumnsDialogStrings.NoSelectionWarning = 'At least one column must be visible!'
EditControls = <
item
ControlName = 'cb_SpaceAfterCursor'
FieldName = 'SpaceAfterCursor'
FitCell = fcCellSize
LeaveOnEnterKey = True
LeaveOnUpDownKey = True
end
item
ControlName = 'cb_UseExtendedSQL'
FieldName = 'UseExtenedSQL'
FitCell = fcCellSize
LeaveOnEnterKey = True
LeaveOnUpDownKey = True
end>
RowsHeight = 17
TitleRowHeight = 17
Columns = <
item
Expanded = False
FieldName = 'BtnOrder'
Title.Caption = 'Btn Order'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'BtnWidth'
Title.Caption = 'Btn Width'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'Caption'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'ExtraText'
Title.Caption = 'Add Text'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'CursorBeforeLastChar'
Title.Caption = 'Cursor Before Last Char'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'SpaceAfterCursor'
Title.Caption = 'Space After Cursor'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end
item
Expanded = False
FieldName = 'UseExtenedSQL'
Title.Caption = 'Use Extened SQL'
Title.Font.Charset = DEFAULT_CHARSET
Title.Font.Color = clWindowText
Title.Font.Height = -11
Title.Font.Name = 'Tahoma'
Title.Font.Style = [fsBold]
Visible = True
end>
end
object dbmmo_SQLtext: TDBMemo
Left = 909
Top = 25
Width = 320
Height = 193
DataField = 'SQLCode'
ScrollBars = ssBoth
TabOrder = 2
end
object cb_SpaceAfterCursor: TJvDBCheckBox
Left = 50
Top = 96
Width = 97
Height = 17
DataField = 'SpaceAfterCursor'
TabOrder = 3
Visible = False
end
object cb_UseExtendedSQL: TJvDBCheckBox
Left = 50
Top = 136
Width = 97
Height = 17
DataField = 'UseExtenedSQL'
TabOrder = 4
Visible = False
end
object rg_ColsMoveBtnTo: TRadioGroup
Left = 430
Top = 187
Width = 109
Height = 46
Columns = 2
ItemIndex = 0
Items.Strings = (
'Col 1'
'Col 2'
'Col 3'
'Col 4')
TabOrder = 5
end
object btn_EditDelAddBtn: TJvXPButton
Left = 32
Top = 216
Width = 145
Caption = 'Edit Delete Add SQL Btn'
TabOrder = 6
OnClick = btn_EditDelAddBtnClick
end
end
object grp_DefSQLBtns: TGroupBox
Left = 627
Top = 8
Width = 637
Height = 177
Caption = 'Button Defaults:'
Color = clGradientInactiveCaption
ParentBackground = False
ParentColor = False
TabOrder = 0
object lbl_Height: TLabel
Left = 221
Top = 24
Width = 35
Height = 13
Caption = 'Height:'
end
object lbl_Spacing: TLabel
Left = 120
Top = 24
Width = 41
Height = 13
Caption = 'Spacing:'
end
object lbl_TopMargin: TLabel
Left = 3
Top = 18
Width = 57
Height = 13
Caption = 'Top Margin:'
end
object Label1: TLabel
Left = 319
Top = 25
Width = 98
Height = 13
Caption = 'Col 1&&3 Left Margin:'
end
object Label2: TLabel
Left = 474
Top = 25
Width = 98
Height = 13
Caption = 'Col 2&&4 Left Margin:'
end
object lbl1: TLabel
Left = 10
Top = 53
Width = 283
Height = 13
Caption = 'Click btn or btn definition in data grid to dispaly btn results:'
end
object jvspndt_TopMargin: TJvSpinEdit
Left = 65
Top = 21
Width = 49
Height = 21
MaxValue = 50.000000000000000000
Value = 15.000000000000000000
TabOrder = 0
end
object jvspndt_SpaceBtween: TJvSpinEdit
Left = 164
Top = 21
Width = 49
Height = 21
MaxValue = 50.000000000000000000
Value = 5.000000000000000000
TabOrder = 1
end
object jvspndt_BtnHeight: TJvSpinEdit
Left = 259
Top = 21
Width = 49
Height = 21
MaxValue = 50.000000000000000000
Value = 20.000000000000000000
TabOrder = 2
end
object jvspndt_DefCol1: TJvSpinEdit
Left = 416
Top = 23
Width = 49
Height = 21
MaxValue = 100.000000000000000000
Value = 10.000000000000000000
TabOrder = 3
end
object jvspndt_DefCol2: TJvSpinEdit
Left = 577
Top = 21
Width = 49
Height = 21
MaxValue = 120.000000000000000000
Value = 50.000000000000000000
TabOrder = 4
end
end
object grp_BtnLayout: TGroupBox
Left = 72
Top = 8
Width = 557
Height = 592
Anchors = [akLeft, akTop, akBottom]
Caption = 'SQL Button Layout Display'
Color = clGradientInactiveCaption
ParentBackground = False
ParentColor = False
TabOrder = 1
DesignSize = (
557
592)
object lbl_Panel1: TLabel
Left = 63
Top = 18
Width = 116
Height = 13
Caption = 'SQL Statement Btns:'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
end
object lb_location: TLabel
Left = 21
Top = 37
Width = 54
Height = 13
Caption = ' Column: 1'
end
object lbl_Panel2: TLabel
Left = 368
Top = 18
Width = 103
Height = 13
Caption = 'SQL Function Btns:'
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = [fsBold]
ParentFont = False
end
object lbl3: TLabel
Left = 289
Top = 40
Width = 44
Height = 13
Caption = 'Column 3'
end
object lbl4: TLabel
Left = 152
Top = 37
Width = 51
Height = 13
Caption = ' Column: 2'
end
object lbl5: TLabel
Left = 449
Top = 40
Width = 44
Height = 13
Caption = 'Column 4'
end
object jvpnl2: TJvPanel
Left = 161
Top = 542
Width = 57
Height = 41
Anchors = [akLeft, akTop, akBottom]
TabOrder = 0
Visible = False
end
object jvpnl11: TJvPanel
Left = 87
Top = 536
Width = 68
Height = 41
Anchors = [akLeft, akTop, akBottom]
TabOrder = 1
Visible = False
end
object jvpnl1: TRzPanel
Left = 21
Top = 51
Width = 215
Height = 454
TabOrder = 2
end
object RzPanel2: TRzPanel
Left = 289
Top = 56
Width = 215
Height = 454
TabOrder = 3
end
end
object rg_SelectBtnColumnToDisplay: TRadioGroup
Left = 2
Top = 597
Width = 391
Height = 37
Anchors = [akLeft, akBottom]
Caption = 'Filter For Buttons In Data Grid'
Color = clMoneyGreen
Columns = 4
ItemIndex = 0
Items.Strings = (
'Btn Column 1'
'Btn Column 2'
'Btn Column 3'
'Btn Column 4')
ParentBackground = False
ParentColor = False
TabOrder = 3
OnClick = rg_SelectBtnColumnToDisplayClick
end
object grp1: TGroupBox
Left = 734
Top = 191
Width = 328
Height = 430
Anchors = [akLeft, akTop, akBottom]
Caption = 'Function names to highlight in the SQL editor'
Color = 10930928
ParentBackground = False
ParentColor = False
TabOrder = 4
DesignSize = (
328
430)
object lbl2: TLabel
Left = 121
Top = 24
Width = 127
Height = 13
Caption = 'Function List For Highlight:'
end
object btn_DeleteFunctionName: TJvXPButton
Left = 10
Top = 160
Width = 104
Caption = 'Delete Selected'
TabOrder = 0
OnClick = btn_DeleteFunctionNameClick
end
object btn_EditFunctionNames: TJvXPButton
Left = 10
Top = 133
Width = 104
Caption = 'Edit Selected'
TabOrder = 1
OnClick = btn_EditFunctionNamesClick
end
object lst_Functions: TListBox
Left = 121
Top = 43
Width = 205
Height = 384
Anchors = [akLeft, akTop, akBottom]
ItemHeight = 13
TabOrder = 2
end
object btn_AddFunctionName: TJvXPButton
Left = 10
Top = 106
Width = 104
Caption = 'Add Function Name'
TabOrder = 3
OnClick = btn_AddFunctionNameClick
end
object jvxpbtn_btn_GetFunctionNamesFromCaptions: TJvXPButton
Left = 11
Top = 40
Width = 104
Height = 49
Caption = 'Get All Function Names from Function button captions'
TabOrder = 4
OnClick = jvxpbtn_btn_GetFunctionNamesFromCaptionsClick
end
end
object synm_SQLBtnTest: TSynMemo
Left = 734
Top = 80
Width = 416
Height = 101
Color = 14024701
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -13
Font.Name = 'Courier New'
Font.Style = []
TabOrder = 5
CodeFolding.CollapsedLineColor = clGrayText
CodeFolding.FolderBarLinesColor = clGrayText
CodeFolding.ShowCollapsedLine = False
CodeFolding.IndentGuidesColor = clGray
CodeFolding.IndentGuides = True
UseCodeFolding = False
Gutter.Font.Charset = DEFAULT_CHARSET
Gutter.Font.Color = clWindowText
Gutter.Font.Height = -11
Gutter.Font.Name = 'Courier New'
Gutter.Font.Style = []
Highlighter = SynSQLSyn
Lines.Strings = (
'Click Button diffinition, result '
'displayed here.')
ReadOnly = True
FontSmoothing = fsmNone
end
object btn_CreateTestBtns: TButton
Left = 1
Top = 59
Width = 65
Height = 105
Hint = 'Create, in the panels below a layout of the btn definitions.'
Caption = 'Show / Refresh Test Btns Locations'
ParentShowHint = False
ShowHint = True
TabOrder = 6
WordWrap = True
OnClick = btn_CreateTestBtnsClick
end
object jvfrmstrg_SQLBtns: TJvFormStorage
AppStorage = frm_NxToolsMain.jvpxmlflstrg_NxDbToolsPrefs
AppStoragePath = '%FORM_NAME%\'
StoredValues = <>
Left = 968
Top = 512
end
object SynSQLSyn: TSynSQLSyn
Options.AutoDetectEnabled = False
Options.AutoDetectLineLimit = 0
Options.Visible = False
CommentAttri.Foreground = clGreen
DataTypeAttri.Foreground = clPurple
FunctionAttri.Foreground = clOlive
KeyAttri.Foreground = clRed
NumberAttri.Foreground = clPurple
SQLPlusAttri.Foreground = clRed
TableNameAttri.Foreground = clBlue
TableNameAttri.Style = [fsBold]
FunctionNames.Strings = (
'')
VariableAttri.Foreground = clLime
SQLDialect = sqlNexus
Left = 1048
Top = 416
end
end
|
unit cTelefone;
interface
type
Telefone = class (TOBject)
protected
codTel : integer;
telcont1 : String;
telcont2 : String;
public
Constructor Create (codTel:integer; telcont1:String; telcont2:String);
Procedure setCodTel(codTel:integer);
Function getCodTel:integer;
Procedure setTelCont1(telcont1:String);
Function getTelCont1:String;
Procedure setTelCont2(telcont2:String);
Function getTelCont2:String;
end;
implementation
Constructor Telefone.Create(codTel:integer; telcont1:String; telcont2:String);
begin
self.codTel := codTel;
self.telcont1 := telcont1;
self.telcont2 := telcont2;
end;
Procedure Telefone.setCodTel(codTel:integer);
begin
self.codTel := codTel;
end;
Function Telefone.getCodTel:integer;
begin
result := codTel;
end;
Procedure Telefone.setTelCont1(telcont1:String);
begin
self.telcont1 := telcont1;
end;
Function Telefone.getTelCont1:String;
begin
result := telcont1;
end;
Procedure Telefone.setTelCont2(telcont2:String);
begin
self.telcont2 := telcont2;
end;
Function Telefone.getTelCont2:String;
begin
result := telcont2;
end;
end.
|
unit GestionarCuentaDebito;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UnitCuentaDebito;
type
TFormGestionarCuentaDebito = class(TForm)
Button3: TButton;
Button1: TButton;
Atrás: TButton;
Label1: TLabel;
labelNumeroCuenta: TLabel;
procedure onClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure clicCancelar(Sender: TObject);
procedure clicCerrarCuenta(Sender: TObject);
procedure clicCongelarCuenta(Sender: TObject);
procedure verEstadodeCuenta(Sender: TObject);
procedure regresarAgestionar();
private
{ Private declarations }
public
numeroDecuenta: string;
idCuentaDebito : integer;
cuentaDebito: TCuentaDebito;
{ Public declarations }
end;
var
FormGestionarCuentaDebito: TFormGestionarCuentaDebito;
implementation
uses GestionarCuentasDebito, MenuGerente;
{$R *.dfm}
procedure TFormGestionarCuentaDebito.clicCancelar(Sender: TObject);
begin
regresarAgestionar;
end;
procedure TFormGestionarCuentaDebito.clicCerrarCuenta(Sender: TObject);
begin
numeroDecuenta :=GestionarCuentasDebito.FormCuestionarCuentasDebito.numeroDeCuenta;
cuentaDebito.Destroy;
cuentaDebito := TCuentaDebito.Create;
cuentaDebito.numeroDeCuenta := numeroDeCuenta;
cuentaDebito.actualizarEstado('cerrada', numeroDeCuenta);
//TODO CERRAR CUENTA
//actualizarCuenta('cerrada');
showmessage('Cuenta cerrada exitósamente');
regresarAgestionar;
end;
procedure TFormGestionarCuentaDebito.clicCongelarCuenta(Sender: TObject);
begin
//TODO CONGELAR CUENTA
numeroDecuenta :=GestionarCuentasDebito.FormCuestionarCuentasDebito.numeroDeCuenta;
cuentaDebito.Destroy;
cuentaDebito := TCuentaDebito.Create;
cuentaDebito.numeroDeCuenta := numeroDeCuenta;
cuentaDebito.actualizarEstado('congelada', numeroDeCuenta);
showmessage('Cuenta congelada exitósamente');
regresarAgestionar;
end;
procedure TFormGestionarCuentaDebito.FormShow(Sender: TObject);
begin
numeroDecuenta :=GestionarCuentasDebito.FormCuestionarCuentasDebito.numeroDeCuenta;
labelNumeroCuenta.Caption := numeroDeCuenta;
cuentaDebito := TCuentaDebito.Create;
//recuperarIdCuenta;
//ONSHOW
end;
procedure TFormGestionarCuentaDebito.onClose(Sender: TObject; var Action: TCloseAction);
begin
Application.Terminate;
end;
procedure TFormGestionarCuentaDebito.regresarAgestionar;
begin
GestionarCuentasDebito.FormCuestionarCuentasDebito.Show;
FormGestionarCuentaDebito.Visible := False;
end;
procedure TFormGestionarCuentaDebito.verEstadodeCuenta(Sender: TObject);
begin
//todoVerestado de cuenta
end;
end.
|
unit UdpSocket;
interface
uses
SysUtils, Windows, Classes, WinSock;
type
IDrtpSocket = interface
function GetActive: Boolean;
function GetLastRecvAddr: string;
function GetLastRecvPort: Integer;
function GetLocalIP: string;
function GetLocalPort: Integer;
function GetHandle: Integer; stdcall;
function GetStopTransfer: Boolean; stdcall;
function GetTimeout: Integer;
function RecvBuffer(ABuffer: Pointer; ASize: Integer): Integer;
function ReplyBuffer(ABuffer: Pointer; ASize: Integer): Integer;
function SendBuffer(ABuffer: Pointer; ASize: Integer; Addr: string; APort:
Integer): Integer;
procedure SetActive(const Value: Boolean);
procedure SetLocalIP(const Value: string);
procedure SetLocalPort(const Value: Integer);
procedure SetStopTransfer(const Value: Boolean); stdcall;
procedure SetTimeout(const Value: Integer);
function WaitForData(ATimeOut: Integer): Boolean;
property Active: Boolean read GetActive write SetActive;
property LastRecvAddr: string read GetLastRecvAddr;
property LastRecvPort: Integer read GetLastRecvPort;
property LocalIP: string read GetLocalIP write SetLocalIP;
property LocalPort: Integer read GetLocalPort write SetLocalPort;
property Handle: Integer read GetHandle;
property StopTransfer: Boolean read GetStopTransfer write SetStopTransfer;
property Timeout: Integer read GetTimeout write SetTimeout;
end;
TDRtpUdpSocket = class(TInterfacedObject, IDrtpSocket)
private
FActive: Boolean;
FBufferSize: Integer;
FLastRecvAddress: TSockAddr;
FLastRecvAddressLen: Integer;
FLocalIP: string;
FLocalPort: Integer;
FSocket: TSocket;
FStopTransfer: Boolean;
FTimeOut: Integer;
procedure Close;
function GetActive: Boolean;
function GetLastRecvAddr: string;
function GetLastRecvPort: Integer;
function GetLocalIP: string;
function GetLocalPort: Integer;
function GetReuseAddress: Boolean;
function GetHandle: Integer; stdcall;
function GetTimeOut: Integer;
procedure Open;
procedure SetActive(const Value: Boolean);
procedure SetBufferSize(const Value: Integer);
procedure SetLocalIP(const Value: string);
procedure SetLocalPort(const Value: Integer);
procedure SetReuseAddress(const Value: Boolean);
procedure SetTimeOut(const Value: Integer);
protected
function GetStopTransfer: Boolean; stdcall;
procedure SetStopTransfer(const Value: Boolean); stdcall;
public
constructor Create;
destructor Destroy; override;
function RecvBuffer(ABuffer: Pointer; ASize: Integer): Integer;
function ReplyBuffer(ABuffer: Pointer; ASize: Integer): Integer;
function SendBuffer(ABuffer: Pointer; ASize: Integer; Addr: string; APort:
Integer): Integer;
function WaitForData(ATimeOut: Integer): Boolean;
property Active: Boolean read GetActive write SetActive;
property BufferSize: Integer read FBufferSize write SetBufferSize;
property LastRecvAddr: string read GetLastRecvAddr;
property LastRecvPort: Integer read GetLastRecvPort;
property LocalIP: string read GetLocalIP write SetLocalIP;
property LocalPort: Integer read GetLocalPort write SetLocalPort;
property ReuseAddress: Boolean read GetReuseAddress write SetReuseAddress;
property Handle: Integer read GetHandle;
property TimeOut: Integer read GetTimeOut write SetTimeOut;
property StopTransfer: Boolean read GetStopTransfer write SetStopTransfer;
end;
procedure DebugMsg(valMsg: string; Aarg: array of const);
implementation
function Select(H: THandle; ReadReady, WriteReady, ExceptFlag: PBoolean;
TimeOut: Integer): Boolean;
var
ReadFds: TFDset;
ReadFdsptr: PFDset;
WriteFds: TFDset;
WriteFdsptr: PFDset;
ExceptFds: TFDset;
ExceptFdsptr: PFDset;
tv: timeval;
Timeptr: PTimeval;
begin
if Assigned(ReadReady) then
begin
ReadFdsptr := @ReadFds;
FD_ZERO(ReadFds);
FD_SET(H, ReadFds);
end else
ReadFdsptr := nil;
if Assigned(WriteReady) then
begin
WriteFdsptr := @WriteFds;
FD_ZERO(WriteFds);
FD_SET(H, WriteFds);
end else
WriteFdsptr := nil;
if Assigned(ExceptFlag) then
begin
ExceptFdsptr := @ExceptFds;
FD_ZERO(ExceptFds);
FD_SET(H, ExceptFds);
end else
ExceptFdsptr := nil;
if TimeOut >= 0 then
begin
tv.tv_sec := TimeOut div 1000;
tv.tv_usec := 1000 * (TimeOut mod 1000);
Timeptr := @tv;
end else
Timeptr := nil;
Try
Result := WinSock.select(H + 1, ReadFdsptr, WriteFdsptr, ExceptFdsptr, Timeptr) > 0;
except
Result := False;
end;
if Assigned(ReadReady) then
ReadReady^ := FD_ISSET(H, ReadFds);
if Assigned(WriteReady) then
WriteReady^ := FD_ISSET(H, WriteFds);
if Assigned(ExceptFlag) then
ExceptFlag^ := FD_ISSET(H, ExceptFds);
end;
function GetSocketAddr(h: String; p: Integer): TSockAddr;
function LookupHostAddr(const hn: string): string;
var
h: PHostEnt;
begin
Result := '';
if hn <> '' then
begin
if hn[1] in ['0'..'9'] then
begin
if inet_addr(pansichar(hn)) <> INADDR_NONE then
Result := hn;
end
else
begin
h := gethostbyname(pansichar(hn));
if h <> nil then
with h^ do
Result := format('%d.%d.%d.%d', [ord(h_addr^[0]), ord(h_addr^[1]),
ord(h_addr^[2]), ord(h_addr^[3])]);
end;
end
else Result := '0.0.0.0';
end;
function LookupPort(const sn: string; pn: pchar = nil): word;
var
se: PServent;
begin
Result := 0;
if sn <> '' then
begin
se := getservbyname(pansichar(sn), pansichar(pn));
if se <> nil then
Result := ntohs(se^.s_port)
else
Result := StrToInt(sn);
end;
end;
begin
Result.sin_family := AF_INET;
Result.sin_addr.s_addr := inet_addr(pansichar(LookupHostAddr(h)));
Result.sin_port := htons(LookupPort(IntToStr(p)));
end;
function BindFreePort(hSocket: THandle; Address: string; MinPort: integer =
10000; MaxPort: integer = 20000): Integer;
var
tmpAddr: TSockAddr;
begin
Randomize;
MinPort := MinPort + Random(5)*Random(100)+Random(10);
Result := MinPort;
while Result <= MaxPort do
begin
tmpAddr := GetSocketAddr(Address, Result);
if bind(hSocket, tmpAddr, SizeOf(tmpAddr)) <> SOCKET_ERROR then
Exit;
Inc(Result);
end;
Result := -1;
end;
function InAddrToString(AInAddr: TInAddr): string;
begin
with AInAddr.S_un_b do
begin
Result := IntToStr(Byte(s_b1)) + '.' + IntToStr(Byte(s_b2)) + '.' +
IntToStr(Byte(s_b3)) + '.' + IntToStr(Byte(s_b4));
end;
end;
var
WSAData: TWSAData;
procedure Startup;
var
ErrorCode: Integer;
begin
ErrorCode := WSAStartup($0101, WSAData);
if ErrorCode <> 0 then
raise Exception.Create('init socket error');
end;
procedure Cleanup;
var
ErrorCode: Integer;
begin
ErrorCode := WSACleanup;
if ErrorCode <> 0 then
raise Exception.Create('cleanup socket error');
end;
procedure DebugMsg(valMsg: string; Aarg: array of const);
begin
OutputDebugString(PChar(Format('UDP SOCKET: ' + valMsg, Aarg)));
end;
{TUdpSendChannel}
constructor TDRtpUdpSocket.Create;
begin
inherited Create;
FTimeOut := 100;
FBufferSize := 64 * 1024;
FSocket := 0;
FStopTransfer := False;
end;
destructor TDRtpUdpSocket.Destroy;
begin
if Active then
Active := False;
inherited;
end;
procedure TDRtpUdpSocket.Close;
begin
if FSocket <> 0 then
begin
shutdown(FSocket, SD_BOTH);
closesocket(FSocket);
FSocket := 0;
end;
end;
function TDRtpUdpSocket.GetActive: Boolean;
begin
Result := FActive;
end;
function TDRtpUdpSocket.GetLastRecvAddr: string;
begin
Result := inet_ntoa(FLastRecvAddress.sin_addr);
end;
function TDRtpUdpSocket.GetLastRecvPort: Integer;
begin
Result := ntohs(FLastRecvAddress.sin_port);
end;
function TDRtpUdpSocket.GetLocalIP: string;
begin
Result := FLocalIP;
end;
function TDRtpUdpSocket.GetLocalPort: Integer;
begin
Result := FLocalPort;
end;
function TDRtpUdpSocket.GetReuseAddress: Boolean;
var
bReListen, tmpLen: Integer;
begin
Result := False;
if FSocket = 0 then Exit;
GetSockOpt(FSocket, SOL_SOCKET, SO_REUSEADDR, @bReListen, tmpLen);
Result := bReListen <> 0;
end;
function TDRtpUdpSocket.GetHandle: Integer;
begin
Result := FSocket;
end;
function TDRtpUdpSocket.GetStopTransfer: Boolean;
begin
Result := FStopTransfer;
end;
function TDRtpUdpSocket.GetTimeOut: Integer;
begin
Result := FTimeOut;
end;
procedure TDRtpUdpSocket.Open;
var
tmpAddr: TSockAddr;
begin
FSocket := socket(AF_INET, SOCK_DGRAM, 0);
if FLocalPort <> 0 then
begin
tmpAddr := GetSocketAddr(FLocalIP, FLocalPort);
if bind(FSocket, tmpAddr, SizeOf(tmpAddr)) = SOCKET_ERROR then
begin
DebugMsg('bind error: ' + SysErrorMessage(GetLastError), []);
RaiseLastWin32Error;
end;
end else
FLocalPort := BindFreePort(FSocket, FLocalIP);
TimeOut := FTimeOut;
BufferSize := FBufferSize;
end;
function TDRtpUdpSocket.RecvBuffer(ABuffer: Pointer; ASize: Integer): Integer;
begin
Result := 0;
if not Active then Exit;
if FStopTransfer then Exit;
DebugMsg('Recv udp packet', []);
FLastRecvAddressLen := SizeOf(FLastRecvAddress);
FillChar(FLastRecvAddress, SizeOf(FLastRecvAddress), #0);
Result := recvfrom(FSocket, ABuffer^, ASize, 0, FLastRecvAddress,
FLastRecvAddressLen);
{ if Result = SOCKET_ERROR then
DebugMsg('recv error: ' + SysErrorMessage(GetLastError) + ' size = ' + IntToStr(ASize), []); }
end;
function TDRtpUdpSocket.ReplyBuffer(ABuffer: Pointer; ASize: Integer): Integer;
begin
Result := -1;
if not Active then Exit;
if FStopTransfer then Exit;
DebugMsg('Reply udp packet', []);
if FLastRecvAddressLen <> 0 then
Result := sendto(FSocket, ABuffer^, ASize, 0,
FLastRecvAddress, SizeOf(FLastRecvAddress));
end;
function TDRtpUdpSocket.SendBuffer(ABuffer: Pointer; ASize: Integer; Addr:
string; APort: Integer): Integer;
var
tmpAddr: TSockAddr;
begin
Result := -1;
if not Active then Exit;
if FStopTransfer then Exit;
DebugMsg('send udp packet to %s %d', [Addr, APort]);
tmpAddr := GetSocketAddr(Addr, APort);
Result := sendto(FSocket, ABuffer^, ASize, 0, tmpAddr, SizeOf(tmpAddr));
if Result = SOCKET_ERROR then
DebugMsg('send error [%s:%d] ' + SysErrorMessage(GetLastError), [Addr,
APort]);
end;
procedure TDRtpUdpSocket.SetActive(const Value: Boolean);
begin
if FActive = Value then Exit;
FActive := Value;
if FActive then
Open
else
Close;
end;
procedure TDRtpUdpSocket.SetBufferSize(const Value: Integer);
begin
FBufferSize := Value;
if not Active then Exit;
setsockopt(FSocket, SOL_SOCKET, SO_RCVBUF,
@FBufferSize, SizeOf(FBufferSize));
end;
procedure TDRtpUdpSocket.SetLocalIP(const Value: string);
begin
FLocalIP := Value;
end;
procedure TDRtpUdpSocket.SetLocalPort(const Value: Integer);
begin
FLocalPort := Value;
end;
procedure TDRtpUdpSocket.SetReuseAddress(const Value: Boolean);
begin
if FSocket = 0 then Exit;
SetSockOpt(FSocket, SOL_SOCKET, SO_REUSEADDR, @Value, SizeOf(Value));
end;
procedure TDRtpUdpSocket.SetStopTransfer(const Value: Boolean);
begin
FStopTransfer := Value;
end;
procedure TDRtpUdpSocket.SetTimeOut(const Value: Integer);
begin
FTimeOut := Value;
if not Active then Exit;
setsockopt(FSocket, SOL_SOCKET, SO_RCVTIMEO,
@FTimeOut, SizeOf(FTimeOut));
end;
function TDRtpUdpSocket.WaitForData(ATimeOut: Integer): Boolean;
var
ReadReady, ExceptFlag: Boolean;
begin
Result := False;
if Select(FSocket, @ReadReady, nil, @ExceptFlag, ATimeOut) then
Result := ReadReady and not ExceptFlag;
end;
end.
|
unit Menu;
interface
{Процедура инциализации меню }
procedure InitMenu();
{Процедура отлова нажатия клавиш в меню }
procedure HandleInputInMenu();
{Процедура обновления логики меню }
procedure UpdateMenu(dt : integer);
{Процедура отрисовки меню }
procedure RenderMenu();
implementation
uses
GlobalVars, GraphABC, UIAssets;
const
MaxOptions = 5; //Максимальное кол-во кнопок в данном состоянии
var
Options : array[1..MaxOptions] of string; //Кнопки
CurrentOp : byte; //Текущая кнопка
Time : real; //Вспомогательная переменная для отрисовки имени создателя
procedure InitMenu;
begin
Options[1] := 'Играть';
Options[2] := 'Редактор';
Options[3] := 'Рекорды';
Options[4] := 'Справка';
Options[5] := 'Выход';
CurrentOp := 1;
SetWindowSize(960, 768);
Time := 0;
end;
procedure HandleInputInMenu;
begin
if (inputKeys[VK_DOWN] or inputKeys[VK_S]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp + 1 > MaxOptions) then
begin
CurrentOp := 1;
end
else
begin
CurrentOp := CurrentOp + 1;
end;
end;
end;
if (inputKeys[VK_UP] or inputKeys[VK_W]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp - 1 < 1) then
begin
CurrentOp := MaxOptions;
end
else
begin
CurrentOp := CurrentOp - 1;
end;
end;
end;
if (inputKeys[VK_ENTER]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp = 1) then
begin
ChangeState(ChooseMapState);
end;
if (CurrentOp = 2) then
begin
ChangeState(EditorState);
end;
if (CurrentOp = 3) then
begin
ChangeState(HighscoreState);
end;
if (CurrentOp = 4) then
begin
ChangeState(HelpState);
end;
if (CurrentOp = 5) then
begin
IsQuit := true;
end;
end;
end;
if (inputKeys[VK_ESCAPE]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds;
IsQuit := true;
end;
end;
end;
procedure UpdateMenu;
begin
HandleInputInMenu();
Time := Time + 0.985;
end;
procedure RenderMenu;
begin
Window.Clear();
SetBrushStyle(bsSolid);
Background.Draw(0, 0);
Title.Draw(94, 87);
Logo.Draw(440, 216 + Round(10 * Sin(RadToDeg(Time))));
for var i:=1 to MaxOptions do
begin
var isActive :=false;
if (CurrentOp = i) then
begin
isActive := true;
end;
DrawButton(Window.Width div 2, 322 + 94 * (i - 1), Options[i], defaultSize, isActive);
end;
end;
begin
end. |
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
ComCtrls, JvPicClip;
type
{ TForm1 }
TForm1 = class(TForm)
CombinedImage: TImage;
Label1: TLabel;
SplitImage: TImage;
JvPicClip1: TJvPicClip;
Trackbar: TTrackBar;
procedure CombinedImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure TrackbarChange(Sender: TObject);
private
procedure CreateCombinedImage(ABitmap: TBitmap;
out ANumCols, ANumRows: Integer);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
procedure TForm1.FormCreate(Sender: TObject);
var
bmp: TBitmap;
nCols, nRows: Integer;
begin
bmp := TBitmap.Create;
try
CreateCombinedImage(bmp, nCols, nRows);
// Image for combined bitmap
CombinedImage.Width := bmp.Width;
CombinedImage.Height := bmp.Height;
CombinedImage.Picture.Assign(bmp);
// Image for separated bitmaps
SplitImage.Width := bmp.Width div nCols;
SplitImage.Height := bmp.Height div nRows;
JvPicClip1.Picture := CombinedImage.Picture;
JvPicClip1.Cols := nCols;
JvPicClip1.Rows := nRows;
Trackbar.Min := 0;
Trackbar.Max := nCols * nRows - 1;
Trackbar.Position := 0;
TrackbarChange(nil);
finally
bmp.Free;
end;
end;
procedure TForm1.CombinedImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
r, c: Integer;
begin
c := X div SplitImage.Width;
r := Y div SplitImage.Height;
Trackbar.Position := JvPicClip1.GetIndex(c, r);
end;
procedure TForm1.TrackbarChange(Sender: TObject);
begin
SplitImage.Picture.Assign(JvPicClip1.GraphicCell[Trackbar.Position]);
Label1.Caption := 'Index ' + IntToStr(Trackbar.Position);
end;
procedure TForm1.CreateCombinedImage(ABitmap: TBitmap;
out ANumCols, ANumRows: Integer);
const
FOLDER = '../../design/';
var
pic: TPicture;
c, r, i: Integer;
L: TStrings;
W, H: Integer;
begin
L := TStringList.Create;
try
L.Add(FOLDER + 'JvMM/images/tjvbmpanimator.png'); //0
L.Add(FOLDER + 'JvMM/images/tjvfullcoloraxiscombo.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorcircle.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorcircledialog.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorgroup.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorlabel.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorpanel.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolorspacecombo.png');
L.Add(FOLDER + 'JvMM/images/tjvfullcolortrackbar.png');
L.Add(FOLDER + 'JvMM/images/tjvgradient.png');
L.Add(FOLDER + 'JvMM/images/tjvgradientheaderpanel.png'); // 10
L.Add(FOLDER + 'JvMM/images/tjvid3v2.png');
L.Add(FOLDER + 'JvMM/images/tjvpicclip.png');
L.Add(FOLDER + 'JvMM/images/tjvspecialprogress.png');
L.Add(FOLDER + 'JvHMI/images/tjvdialbutton.bmp');
L.Add(FOLDER + 'JvHMI/images/tjvled.bmp');
L.Add(FOLDER + 'JvDB/images/tjvdbcalcedit.bmp');
L.Add(FOLDER + 'JvDB/images/tjvdbhtlabel.bmp');
L.Add(FOLDER + 'JvDB/images/tjvdbsearchcombobox.bmp');
L.Add(FOLDER + 'JvDB/images/tjvdbsearchedit.bmp');
L.Add(FOLDER + 'JvDB/images/tjvdbtreeview.bmp'); // 20
L.Add(FOLDER + 'JvPageComps/images/tjvtabbar.bmp');
L.Add(FOLDER + 'JvPageComps/images/tjvmoderntabbarpainter.bmp');
L.Add(FOLDER + 'JvCustomControls/images/tjvownerdrawviewer.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvimagelistviewer.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvimagesviewer.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvoutlookbar.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvthumbimage.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvthumbnail.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvthumbview.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvtimeline.png'); // 30
L.Add(FOLDER + 'JvCustomControls/images/tjvtmtimeline.png');
L.Add(FOLDER + 'JvCustomControls/images/tjvvalidateedit.png'); // 32
ANumCols := 8;
ANumRows := 4;
pic := TPicture.Create;
try
pic.LoadFromFile(L[0]);
W := pic.Width;
H := pic.Height;
finally
pic.Free;
end;
ABitmap.SetSize(ANumCols * W, ANumRows * H);
ABitmap.Canvas.Brush.Color := clWhite;
Abitmap.Canvas.FillRect(0, 0, ABitmap.Width, ABitmap.Height);
c := 0;
r := 0;
pic := TPicture.Create;
try
for i:=0 to L.Count-1 do begin
pic.LoadFromFile(L[i]);
ABitmap.Canvas.Draw(c * W, r * H, pic.Bitmap);
inc(c);
if c = ANumCols then begin
c := 0;
inc(r);
end;
end;
finally
pic.Free;
end;
finally
L.Free;
end;
end;
end.
|
unit Model.Email;
interface
type
TEmail=class
private
FNome: string;
FTipo: string;
procedure SetNome(const Value: string);
procedure SetTipo(const Value: string);
published
property Nome:string read FNome write SetNome;
property Tipo:string read FTipo write SetTipo;
end;
implementation
{ TEmail }
procedure TEmail.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TEmail.SetTipo(const Value: string);
begin
FTipo := Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
// This version of ComApp.pas is used with Delphi6 built WebAppDebugger executables. It
// allows them to work with a new version of the WebAppDebugger without changing any
// source code. The new version of the WebAppDebugger uses sockets rather
// than COM for interprocess communication between the WebAppDebugger and WebAppDebugger
// executables.
unit ComApp;
interface
uses
SockApp;
type
TWebAppAutoObjectFactory = class(TWebAppSockObjectFactory)
public
constructor Create(AClassID: TGuid; const AClassName, ADescription: string);
end;
implementation
{ TWebAppAutoObjectFactory }
constructor TWebAppAutoObjectFactory.Create(AClassID: TGuid;
const AClassName, ADescription: string);
begin
inherited Create(AClassName);
end;
end.
|
{*******************************************************}
{ }
{ YxdMemPool 内存池 }
{ }
{ 版权所有 (C) 2013 YangYxd }
{ }
{*******************************************************}
{
--------------------------------------------------------------------
更新记录
--------------------------------------------------------------------
2015.07.21 ver 1.0.1
--------------------------------------------------------------------
- 增加TAutoSyncMemPool自动内存池,线程安全
2015.06.29 ver 1.0.0
--------------------------------------------------------------------
- 内存池: TMemPool 为非线程完全的内存池。
TSyncMemPool 为线程安全的内存池
自动内存管理:TAutoMemPool 非线程安全
对象池: TObjectPool 线程安全
}
unit YxdMemPool;
interface
{$IF RTLVersion>=24}
{$LEGACYIFEND ON}
{$IFEND}
{$IF defined(FPC) or defined(VER170) or defined(VER180) or defined(VER190) or defined(VER200) or defined(VER210)}
{$DEFINE USEINLINE}
{$IFEND}
uses
{$IFDEF MSWINDOWS}Windows, {$ENDIF}
SysUtils, Classes, SyncObjs, Types;
{$if CompilerVersion < 23}
type
NativeUInt = Cardinal;
NativeInt = Integer;
IntPtr = Cardinal;
{$ifend}
const
MemoryDelta = $2000; { Must be a power of 2 }
MaxListSize = MaxInt div 16;
type
MAddrList = array of Pointer;
PMAddrList = ^MAddrList;
type
TMemPoolNotify = procedure(Sender: TObject; const AData: Pointer) of object;
TMemPoolNew = procedure(Sender: TObject; var AData: Pointer) of object;
type
/// <summary>
/// 固定大小内存池,非线程安全
/// 注意事项:Push 时并不会检查压入的数据是否已经Push过。
/// 重复Push必将产生AV等异常和严重后果
/// </summary>
TMemPool = class(TObject)
private
FPool: MAddrList;
FCount: Integer;
FMaxSize: Integer;
FBlockSize: Cardinal;
FOnFree: TMemPoolNotify;
FOnNew: TMemPoolNew;
FOnReset: TMemPoolNotify;
protected
procedure DoFree(const AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoReset(const AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoNew(var AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
public
constructor Create(BlockSize: Cardinal; MaxSize: Integer = 64);
destructor Destroy; override;
procedure Clear;
function Pop(): Pointer;
procedure Push(const V: Pointer);
property BlockSize: Cardinal read FBlockSize;
property MaxSize: Integer read FMaxSize;
property Count: Integer read FCount;
property OnFree: TMemPoolNotify read FOnFree write FOnFree;
property OnNew: TMemPoolNew read FOnNew write FOnNew;
property OnReset: TMemPoolNotify read FOnReset write FOnReset;
end;
type
/// <summary>
/// 固定大小内存池, 线程安全
/// 注意事项:Push 时并不会检查压入的数据是否已经Push过。
/// 重复Push必将产生AV等异常和严重后果
/// </summary>
TSyncMemPool = class(TObject)
private
FPool: MAddrList;
FCount: Integer;
FMaxSize: Integer;
FBlockSize: Cardinal;
FLocker: TCriticalSection;
FOnFree: TMemPoolNotify;
FOnNew: TMemPoolNew;
FOnReset: TMemPoolNotify;
protected
procedure DoFree(const AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoReset(const AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure DoNew(var AData: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
public
constructor Create(BlockSize: Cardinal; MaxSize: Integer = 64);
destructor Destroy; override;
procedure Clear;
procedure Lock; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure Unlock; {$IFDEF USEINLINE}inline;{$ENDIF}
function Pop(): Pointer;
procedure Push(const V: Pointer);
property BlockSize: Cardinal read FBlockSize;
property MaxSize: Integer read FMaxSize;
property Count: Integer read FCount;
property OnFree: TMemPoolNotify read FOnFree write FOnFree;
property OnNew: TMemPoolNew read FOnNew write FOnNew;
property OnReset: TMemPoolNotify read FOnReset write FOnReset;
end;
type
PPMemPoolHashItem = ^PMemPoolHashItem;
PMemPoolHashItem = ^TMemPoolHashItem;
TMemPoolHashItem = record
Next: PMemPoolHashItem;
Key: Cardinal;
Value: TMemPool;
end;
type
/// <summary>
/// 自动内存池,非线程安全
/// </summary>
TAutoMemPool = class(TObject)
private
Buckets: array of PMemPoolHashItem;
FBucketsSize: Cardinal;
FBucketsPool: TMemPool;
FPool_4: TMemPool;
FPool_8: TMemPool;
FPool_12: TMemPool;
FPool_16: TMemPool;
FPool_24: TMemPool;
FPool_32: TMemPool;
FPool_48: TMemPool;
FPool_64: TMemPool;
FPool_96: TMemPool;
FPool_128: TMemPool;
FPool_256: TMemPool;
FPool_320: TMemPool;
FPool_512: TMemPool;
FPool_640: TMemPool;
FPool_768: TMemPool;
FPool_1024: TMemPool;
FPool_1280: TMemPool;
FPool_2048: TMemPool;
FPool_4096: TMemPool;
FPool_5120: TMemPool;
FPool_8192: TMemPool;
FPoolList: array of TMemPool;
FPoolListSize: Cardinal;
protected
function GetMinMemPool(const ASize: Cardinal): TMemPool;
function GetMemPool(const ASize: Cardinal): TMemPool;
procedure AddItem(const V: Pointer; const Pool: TMemPool);
function FindItem(const V: Pointer): TMemPool;
procedure ClearBuckets;
public
constructor Create(ARefBuckets: Integer = 999983);
destructor Destroy; override;
function Pop(const ASize: Cardinal): Pointer; virtual;
procedure Push(const V: Pointer); virtual;
function GetMem(const ASize: Cardinal): Pointer; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure FreeMem(var V: Pointer); {$IFDEF USEINLINE}inline;{$ENDIF}
procedure Clear; virtual;
function GetRealPopSize(const ASize: Cardinal): Cardinal;
end;
type
/// <summary>
/// 自动内存池,线程安全
/// </summary>
TAutoSyncMemPool = class(TAutoMemPool)
private
FLocker: TCriticalSection;
public
constructor Create(ARefBuckets: Integer = 99991);
destructor Destroy; override;
function Pop(const ASize: Cardinal): Pointer; override;
procedure Push(const V: Pointer); override;
procedure Clear; override;
end;
type
/// <summary>
/// 数据环形缓存
/// <code>
/// 默认分配1M空间,分配到最后从头继续分配,不考虑释放问题(假设处理速度足够,不会滞留那么多数据)
/// </code>
/// </summary>
TCircleBuffer = class(TObject)
private
FDataBuf: Pointer;
FBufIndex: Integer;
FBufSize: Integer;
private
procedure SetBufSize(const Value: Integer);
public
constructor Create(ASize: Integer = 1024 * 1024);
destructor Destroy; override;
function GetBuffer(ASize: integer): Pointer;
property BufferSize: Integer read FBufSize write SetBufSize;
end;
type
TObjectPool = class;
TOnNotifyObject = procedure(Sender: TObjectPool; var Obj: TObject) of Object;
TOnResetObject = procedure(Sender: TObjectPool; Obj: TObject) of Object;
/// <summary>
/// 对象池, 线程安全
/// </summary>
TObjectPool = class(TObject)
private
FUses, FUnUses: TList;
FObjClass: TClass;
FMaxObjCount: Integer;
FLocker: TCriticalSection;
FOnCreate: TOnNotifyObject;
FOnReset: TOnResetObject;
FOnFree: TOnNotifyObject;
protected
procedure DoFree(var Obj: TObject); {$IFDEF USEINLINE}inline;{$ENDIF}
public
constructor Create(AMaxCount: Integer); overload;
constructor Create(AMaxCount: Integer; ObjClass: TClass);overload;
destructor Destroy; override;
function GetObject: TObject;
procedure FreeObject(Obj: TObject);
function Pop: TObject; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure Push(Obj: TObject); {$IFDEF USEINLINE}inline;{$ENDIF}
property OnCreateObject: TOnNotifyObject read FOnCreate write FOnCreate;
property OnResetObject: TOnResetObject read FOnReset write FOnReset;
property OnFreeObject: TOnNotifyObject read FOnFree write FOnFree;
end;
implementation
resourcestring
sErrorGetBufFailed = 'Gain buffer failed. Want to apply to the Cache size exceed range.';
function ClacBlockSize(const V: Cardinal): Cardinal;
begin
Result := V;
if Result > 64 then begin
// 块大小以64字节对齐,这样的执行效率最高
if Result mod 64 > 0 then
Result := (Result div 64 + 1) * 64;
end;
end;
{ TMemPool }
procedure TMemPool.Clear;
var
I: Integer;
begin
I := 0;
while I < FCount do begin
DoFree(FPool[I]);
Inc(I);
end;
FCount := 0;
end;
constructor TMemPool.Create(BlockSize: Cardinal; MaxSize: Integer);
begin
FCount := 0;
if MaxSize < 4 then
FMaxSize := 4
else
FMaxSize := MaxSize;
SetLength(FPool, FMaxSize);
FBlockSize := ClacBlockSize(BlockSize);
end;
destructor TMemPool.Destroy;
begin
Clear;
inherited;
end;
procedure TMemPool.DoFree(const AData: Pointer);
begin
if Assigned(FOnFree) then
FOnFree(Self, AData)
else
FreeMem(AData);
end;
procedure TMemPool.DoNew(var AData: Pointer);
begin
if Assigned(FOnNew) then
FOnNew(Self, AData)
else
GetMem(AData, FBlockSize);
end;
procedure TMemPool.DoReset(const AData: Pointer);
begin
if Assigned(FOnReset) then
FOnReset(Self, AData);
end;
function TMemPool.Pop: Pointer;
begin
if FCount > 0 then begin
Dec(FCount);
Result := FPool[FCount];
if Result = nil then
DoNew(Result);
end else
DoNew(Result);
if Result <> nil then
DoReset(Result);
end;
procedure TMemPool.Push(const V: Pointer);
begin
if V = nil then Exit;
if FCount < FMaxSize then begin
FPool[FCount] := V;
Inc(FCount);
end else
DoFree(V);
end;
{ TSyncMemPool }
procedure TSyncMemPool.Clear;
var
I: Integer;
begin
FLocker.Enter;
try
I := 0;
while I < FCount do begin
DoFree(FPool[I]);
Inc(I);
end;
finally
FLocker.Leave;
end;
end;
constructor TSyncMemPool.Create(BlockSize: Cardinal; MaxSize: Integer);
begin
FLocker := TCriticalSection.Create;
FCount := 0;
if MaxSize < 4 then
FMaxSize := 4
else
FMaxSize := MaxSize;
SetLength(FPool, FMaxSize);
FBlockSize := ClacBlockSize(BlockSize);
end;
destructor TSyncMemPool.Destroy;
begin
try
Clear;
finally
FreeAndNil(FLocker);
inherited;
end;
end;
procedure TSyncMemPool.DoFree(const AData: Pointer);
begin
if Assigned(FOnFree) then
FOnFree(Self, AData)
else
FreeMem(AData);
end;
procedure TSyncMemPool.DoNew(var AData: Pointer);
begin
if Assigned(FOnNew) then
FOnNew(Self, AData)
else
GetMem(AData, FBlockSize);
end;
procedure TSyncMemPool.DoReset(const AData: Pointer);
begin
if Assigned(FOnReset) then
FOnReset(Self, AData);
end;
procedure TSyncMemPool.Lock;
begin
FLocker.Enter;
end;
function TSyncMemPool.Pop: Pointer;
begin
Result := nil;
FLocker.Enter;
if FCount > 0 then begin
Dec(FCount);
Result := FPool[FCount];
end;
FLocker.Leave;
if Result = nil then
DoNew(Result);
if Result <> nil then
DoReset(Result);
end;
procedure TSyncMemPool.Push(const V: Pointer);
var
ADoFree: Boolean;
begin
if V = nil then Exit;
ADoFree := True;
FLocker.Enter;
if FCount < FMaxSize then begin
FPool[FCount] := V;
Inc(FCount);
ADoFree := False;
end;
FLocker.Leave;
if ADoFree then
DoFree(V);
end;
procedure TSyncMemPool.Unlock;
begin
FLocker.Leave;
end;
{ TAutoMemPool }
procedure TAutoMemPool.AddItem(const V: Pointer; const Pool: TMemPool);
var
Hash: Integer;
Bucket: PMemPoolHashItem;
begin
Hash := Cardinal(V) mod FBucketsSize;
Bucket := FBucketsPool.Pop;
Bucket^.Key := Cardinal(V);
Bucket^.Value := Pool;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
end;
procedure TAutoMemPool.Clear;
begin
FPool_4.Clear;
FPool_8.Clear;
FPool_12.Clear;
FPool_16.Clear;
FPool_24.Clear;
FPool_32.Clear;
FPool_48.Clear;
FPool_64.Clear;
FPool_96.Clear;
FPool_128.Clear;
FPool_256.Clear;
FPool_320.Clear;
FPool_512.Clear;
FPool_640.Clear;
FPool_768.Clear;
FPool_1024.Clear;
FPool_1280.Clear;
FPool_2048.Clear;
FPool_4096.Clear;
FPool_5120.Clear;
FPool_8192.Clear;
ClearBuckets();
end;
procedure TAutoMemPool.ClearBuckets;
var
I: Integer;
P, P1: PMemPoolHashItem;
begin
for I := 0 to High(Buckets) do begin
P := Buckets[I];
while P <> nil do begin
P1 := P.Next;
FBucketsPool.Push(P);
P := P1;
end;
end;
FillChar(Buckets[0], Length(Buckets) * SizeOf(PMemPoolHashItem), 0);
FBucketsPool.Clear;
end;
constructor TAutoMemPool.Create(ARefBuckets: Integer);
var
I: Integer;
begin
FBucketsPool := TMemPool.Create(SizeOf(TMemPoolHashItem), 8192);
FPool_4 := TMemPool.Create(4, 2048);
FPool_8 := TMemPool.Create(8, 2048);
FPool_12 := TMemPool.Create(12, 1024);
FPool_16 := TMemPool.Create(16, 1024);
FPool_24 := TMemPool.Create(24, 1024);
FPool_32 := TMemPool.Create(32, 1024);
FPool_48 := TMemPool.Create(48, 1024);
FPool_64 := TMemPool.Create(64, 1024);
FPool_96 := TMemPool.Create(96, 1024);
FPool_128 := TMemPool.Create(128, 1024);
FPool_256 := TMemPool.Create(256, 1024);
FPool_320 := TMemPool.Create(320, 1024);
FPool_512 := TMemPool.Create(512, 1024);
FPool_640 := TMemPool.Create(640, 1024);
FPool_768 := TMemPool.Create(768, 1024);
FPool_1024 := TMemPool.Create(1024, 512);
FPool_1280 := TMemPool.Create(1280, 512);
FPool_2048 := TMemPool.Create(2048, 512);
FPool_4096 := TMemPool.Create(4096, 256);
FPool_5120 := TMemPool.Create(5120, 128);
FPool_8192 := TMemPool.Create(8192, 128);
SetLength(FPoolList, 8192);
for I := 0 to Length(FPoolList) - 1 do
FPoolList[I] := GetMinMemPool(I);
FPoolListSize := Length(FPoolList);
SetLength(Buckets, ARefBuckets);
FBucketsSize := Length(Buckets);
end;
destructor TAutoMemPool.Destroy;
begin
ClearBuckets();
FreeAndNil(FPool_4);
FreeAndNil(FPool_8);
FreeAndNil(FPool_12);
FreeAndNil(FPool_16);
FreeAndNil(FPool_24);
FreeAndNil(FPool_32);
FreeAndNil(FPool_48);
FreeAndNil(FPool_64);
FreeAndNil(FPool_96);
FreeAndNil(FPool_128);
FreeAndNil(FPool_256);
FreeAndNil(FPool_320);
FreeAndNil(FPool_512);
FreeAndNil(FPool_640);
FreeAndNil(FPool_768);
FreeAndNil(FPool_1024);
FreeAndNil(FPool_1280);
FreeAndNil(FPool_2048);
FreeAndNil(FPool_4096);
FreeAndNil(FPool_5120);
FreeAndNil(FPool_8192);
FreeAndNil(FBucketsPool);
inherited;
end;
function TAutoMemPool.FindItem(const V: Pointer): TMemPool;
var
P: PMemPoolHashItem;
Prev: PPMemPoolHashItem;
begin
Prev := @Buckets[Cardinal(V) mod FBucketsSize];
while Prev^ <> nil do begin
if Prev^.Key = Cardinal(V) then begin
P := Prev^;
Result := P.Value;
Prev^ := P^.Next;
FBucketsPool.Push(P);
Exit;
end else
Prev := @Prev^.Next;
end;
Result := nil;
end;
procedure TAutoMemPool.FreeMem(var V: Pointer);
begin
Push(V);
end;
function TAutoMemPool.GetMem(const ASize: Cardinal): Pointer;
begin
Result := Pop(ASize);
end;
function TAutoMemPool.GetMemPool(const ASize: Cardinal): TMemPool;
begin
if ASize < FPoolListSize then
Result := FPoolList[ASize]
else
Result := nil;
end;
function TAutoMemPool.GetMinMemPool(const ASize: Cardinal): TMemPool;
begin
if ASize <= 4 then
Result := FPool_4
else if ASize <= 8 then
Result := FPool_8
else if ASize <= 12 then
Result := FPool_12
else if ASize <= 16 then
Result := FPool_16
else if ASize <= 24 then
Result := FPool_24
else if ASize <= 32 then
Result := FPool_32
else if ASize <= 48 then
Result := FPool_48
else if ASize <= 64 then
Result := FPool_64
else if ASize <= 96 then
Result := FPool_96
else if ASize <= 128 then
Result := FPool_128
else if ASize <= 256 then
Result := FPool_256
else if ASize <= 320 then
Result := FPool_320
else if ASize <= 512 then
Result := FPool_512
else if ASize <= 640 then
Result := FPool_640
else if ASize <= 768 then
Result := FPool_768
else if ASize <= 1024 then
Result := FPool_1024
else if ASize <= 1280 then
Result := FPool_1280
else if ASize <= 2048 then
Result := FPool_2048
else if ASize <= 4096 then
Result := FPool_4096
else if ASize <= 5120 then
Result := FPool_5120
else
Result := FPool_8192;
end;
function TAutoMemPool.GetRealPopSize(const ASize: Cardinal): Cardinal;
begin
if ASize < FPoolListSize then
Result := FPoolList[ASize].FBlockSize
else
Result := ASize;
end;
function TAutoMemPool.Pop(const ASize: Cardinal): Pointer;
var
Pool: TMemPool;
begin
Pool := GetMemPool(ASize);
if Pool <> nil then begin
Result := Pool.Pop;
AddItem(Result, Pool);
end else
System.GetMem(Result, ASize);
end;
procedure TAutoMemPool.Push(const V: Pointer);
var
Pool: TMemPool;
begin
Pool := FindItem(V);
if Pool <> nil then
Pool.Push(V)
else
System.FreeMem(V);
end;
{ TCircleBuffer }
constructor TCircleBuffer.Create(ASize: Integer);
begin
FBufSize := ASize;
FDataBuf := nil;
FBufIndex := 0;
end;
destructor TCircleBuffer.Destroy;
begin
if FDataBuf <> nil then
FreeMem(FDataBuf);
inherited;
end;
function TCircleBuffer.GetBuffer(ASize: integer): Pointer;
begin
if ASize > FBufSize then
raise Exception.Create(sErrorGetBufFailed);
if FBufIndex + ASize >= FBufSize then
FBufIndex:= 0;
if FDataBuf = nil then
FDataBuf := AllocMem(FBufSize);
Result := Pointer(NativeInt(FDataBuf) + NativeInt(FBufIndex));
Inc(FBufIndex, ASize);
end;
procedure TCircleBuffer.SetBufSize(const Value: Integer);
begin
if FBufSize <> Value then begin
FBufIndex := 0;
if FDataBuf <> nil then
FreeMem(FDataBuf);
FBufSize := Value;
end;
end;
{ TObjectPool }
constructor TObjectPool.Create(AMaxCount: Integer);
begin
FUses := TList.Create;
FUnUses := TList.Create;
FMaxObjCount := AMaxCount;
FLocker := TCriticalSection.Create;
end;
constructor TObjectPool.Create(AMaxCount: Integer; ObjClass: TClass);
begin
Create(AMaxCount);
FObjClass := ObjClass;
end;
destructor TObjectPool.Destroy;
var
I: Integer;
begin
FLocker.Enter;
try
for i := 0 to FUses.Count - 1 do
TObject(FUses[I]).Free;
for i := 0 to FUnUses.Count - 1 do
TObject(FUnUses[I]).Free;
finally
FLocker.Leave;
FLocker.Free;
FUses.Free;
FUnUses.Free;
end;
inherited;
end;
procedure TObjectPool.DoFree(var Obj: TObject);
begin
if Assigned(FOnFree) then
FOnFree(Self, Obj)
else
Obj.Free;
end;
procedure TObjectPool.FreeObject(Obj: TObject);
begin
if Obj = nil then Exit;
FLocker.Enter;
try
FUses.Remove(obj);
if FUnUses.Count + 1 > FMaxObjCount then begin
DoFree(Obj)
end else begin
if Assigned(FOnReset) then
FOnReset(Self, Obj);
FUnUses.Add(Obj);
end;
finally
FLocker.Leave;
end;
end;
function TObjectPool.GetObject: TObject;
begin
FLocker.Enter;
if FUnUses.Count = 0 then begin
try
if Assigned(FOnCreate) then
FOnCreate(Self, Result)
else if FObjClass.InheritsFrom(TComponent) then
Result := TComponentClass(FObjClass).Create(nil)
else if FObjClass <> nil then
Result := FObjClass.Create
else
Result := nil;
if Result <> nil then
FUses.Add(Result);
finally
FLocker.Leave;
end;
end else begin
Result := TObject(FUnUses[FUnUses.Count - 1]);
FUnUses.Delete(FUnUses.Count - 1);
FUses.Add(Result);
FLocker.Leave;
end;
end;
function TObjectPool.Pop: TObject;
begin
Result := GetObject;
end;
procedure TObjectPool.Push(Obj: TObject);
begin
FreeObject(Obj);
end;
{ TAutoSyncMemPool }
procedure TAutoSyncMemPool.Clear;
begin
FLocker.Enter;
inherited Clear;
FLocker.Leave;
end;
constructor TAutoSyncMemPool.Create(ARefBuckets: Integer);
begin
inherited Create(ARefBuckets);
FLocker := TCriticalSection.Create;
end;
destructor TAutoSyncMemPool.Destroy;
begin
FreeAndNil(FLocker);
inherited Destroy;
end;
function TAutoSyncMemPool.Pop(const ASize: Cardinal): Pointer;
begin
FLocker.Enter;
Result := inherited Pop(ASize);
FLocker.Leave;
end;
procedure TAutoSyncMemPool.Push(const V: Pointer);
begin
FLocker.Enter;
inherited Push(V);
FLocker.Leave;
end;
initialization
finalization
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : FRFaceEditor<p>
Editor frame for a TGLFaceProperties.<p>
<b>Historique : </b><font size=-1><ul>
<li>05/09/08 - DanB - Removed Kylix support
<li>29/03/07 - DaStr - Renamed LINUX to KYLIX (BugTrackerID=1681585)
<li>19/12/06 - DaStr - TRFaceEditor.SetGLFaceProperties bugfixed - Shiness and
PoligonMode are now updated when FaceProperties are assigned
<li>03/07/04 - LR - Make change for Linux
<li>06/02/00 - Egg - Creation
</ul></font>
}
unit FRFaceEditor;
interface
{$I GLScene.inc}
uses
WinApi.Windows, System.Classes, VCL.Forms, VCL.ComCtrls, VCL.StdCtrls,
VCL.ImgList, VCL.Controls, VCL.Graphics,
FRTrackBarEdit, FRColorEditor,
GLTexture, GLMaterial, GLState;
type
TRFaceEditor = class(TFrame)
PageControl: TPageControl;
TSAmbient: TTabSheet;
TSDiffuse: TTabSheet;
TSEmission: TTabSheet;
TSSpecular: TTabSheet;
CEAmbiant: TRColorEditor;
Label1: TLabel;
TBEShininess: TRTrackBarEdit;
ImageList: TImageList;
CEDiffuse: TRColorEditor;
CEEmission: TRColorEditor;
CESpecular: TRColorEditor;
procedure TBEShininessTrackBarChange(Sender: TObject);
private
{ Private declarations }
FOnChange: TNotifyEvent;
Updating: Boolean;
FFaceProperties: TGLFaceProperties;
procedure SetGLFaceProperties(const val: TGLFaceProperties);
procedure OnColorChange(Sender: TObject);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property FaceProperties: TGLFaceProperties read FFaceProperties
write SetGLFaceProperties;
end;
implementation
{$R *.dfm}
constructor TRFaceEditor.Create(AOwner: TComponent);
begin
inherited;
FFaceProperties := TGLFaceProperties.Create(nil);
CEAmbiant.OnChange := OnColorChange;
CEDiffuse.OnChange := OnColorChange;
CEEmission.OnChange := OnColorChange;
CESpecular.OnChange := OnColorChange;
PageControl.DoubleBuffered := True;
end;
destructor TRFaceEditor.Destroy;
begin
FFaceProperties.Free;
inherited;
end;
procedure TRFaceEditor.OnColorChange(Sender: TObject);
var
bmp: TBitmap;
bmpRect: TRect;
procedure AddBitmapFor(ce: TRColorEditor);
begin
with bmp.Canvas do
begin
Brush.Color := ce.PAPreview.Color;
FillRect(bmpRect);
end;
ImageList.Add(bmp, nil);
end;
begin
if not updating then
begin
// Update imageList
bmp := TBitmap.Create;
try
bmp.Width := 16;
bmp.Height := 16;
bmpRect := Rect(0, 0, 16, 16);
ImageList.Clear;
AddBitmapFor(CEAmbiant);
FFaceProperties.Ambient.Color := CEAmbiant.Color;
AddBitmapFor(CEDiffuse);
FFaceProperties.Diffuse.Color := CEDiffuse.Color;
AddBitmapFor(CEEmission);
FFaceProperties.Emission.Color := CEEmission.Color;
AddBitmapFor(CESpecular);
FFaceProperties.Specular.Color := CESpecular.Color;
finally
bmp.Free;
end;
// Trigger onChange
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
procedure TRFaceEditor.TBEShininessTrackBarChange(Sender: TObject);
begin
if not Updating then
begin
TBEShininess.TrackBarChange(Sender);
FFaceProperties.Shininess := TBEShininess.Value;
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
// SetGLFaceProperties
//
procedure TRFaceEditor.SetGLFaceProperties(const val: TGLFaceProperties);
begin
Updating := True;
try
CEAmbiant.Color := val.Ambient.Color;
CEDiffuse.Color := val.Diffuse.Color;
CEEmission.Color := val.Emission.Color;
CESpecular.Color := val.Specular.Color;
TBEShininess.Value := val.Shininess;
finally
updating := False;
end;
OnColorChange(Self);
TBEShininessTrackBarChange(Self);
end;
end.
|
unit IntelHEX;
interface
uses
SysUtils, Math, Classes, Contnrs, Windows, Graphics;
type
EIntelHex = class(Exception)
end;
type
TReportMode = set of (rmVerbose, rmHexData, rmStrData);
TOverlapMode = set of (ovlNone, ovlUnmodified, ovlOverwrite, ovlAlways);
TOverflowMode = set of (ovfIgnore, ovfSplit, ovfCut, ovfAlways);
TOverlapEvent = procedure(Sender : TObject; Address : cardinal; var ExistingData; const DataSource; Count : integer;
var OverlapMode : TOverlapMode) of object;
TOverflowEvent = procedure(Sender : TObject; Address : cardinal; const Data; Count : integer;
const SectionName : string; RangeMin, RangeMax : cardinal;
var OverflowMode : TOverflowMode) of object;
type
TIntelHexFile = class;
TIntelHexRecord = class
private
FByteCount : byte;
FAddress : cardinal;
PData : PByteArray;
public
constructor Create(Address : cardinal; const Data; Count : integer);
destructor Destroy; override;
procedure ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
procedure DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
public
property Address : cardinal read FAddress;
property ByteCount : byte read FByteCount;
property DataPtr : PByteArray read PData;
end;
TIntelHexSection = class
private
FItems : TObjectList;
FSectionName : string;
FRangeMin : cardinal;
FRangeMax : cardinal;
FAddressMin : cardinal;
FAddressMax : cardinal;
FIgnore : boolean;
function GetItem(Index : integer) : TIntelHexRecord;
function GetCount : integer;
public
constructor Create(SectionName : string; RangeMin, RangeMax : cardinal);
destructor Destroy; override;
function FindFirst(Offset : cardinal; Count : integer; var Rec : TIntelHexRecord) : boolean;
function FindNext(Const Rec : TIntelHexRecord; var NextRec : TIntelHexRecord) : boolean;
procedure Sort;
procedure AddData(Offset : cardinal; const Buffer; Count : integer);
procedure CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
procedure ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
procedure DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
function GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte = $FF) : boolean;
public
property Item[Index : integer] : TIntelHexRecord read GetItem;
property Count : integer read GetCount;
property SectionName : string read FSectionName write FSectionName;
property RangeMin : cardinal read FRangeMin;
property RangeMax : cardinal read FRangeMax;
property AddressMin : cardinal read FAddressMin;
property AddressMax : cardinal read FAddressMax;
property Ignore : boolean read FIgnore write FIgnore;
end;
TIntelHexSections = class
private
FItems : TObjectList;
function GetItem(Index : Integer) : TIntelHexSection;
function GetCount : integer;
public
constructor Create;
destructor Destroy; override;
function Add(SectionName : string; RangeMin, RangeMax : cardinal) : TIntelHexSection;
function FindSectionIndex(Address : cardinal) : integer;
function FindSection(Address : cardinal) : TIntelHexSection;
function FindSectionByName(const SectionName : string; var Dest : TIntelHexSection) : boolean;
procedure IgnoreSection(const SectionName : string);
procedure CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
procedure ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
procedure DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
function GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte = $FF) : boolean;
public
property Item[Index : integer] : TIntelHexSection read GetItem;
property Count : integer read GetCount;
end;
TIntelHexFile = class(TComponent)
private
FFileName : string;
FStartAddress : cardinal;
FSections : TIntelHexSections;
FOverlapMode : TOverlapMode;
FOnOverlap : TOverlapEvent;
FOverflowMode : TOverflowMode;
FOnOverflow : TOverflowEvent;
FLog : TStrings;
FEOL : string;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddData(Offset : cardinal; Nibbles : string); overload;
procedure AddData(Offset : cardinal; const Buffer; Count : integer); overload;
procedure CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
function CopySectionTo(const SectionName : string; HexFile : TIntelHexFile; RelocateOffset : integer) : boolean;
procedure LoadFromFile(const FileName: string);
procedure LoadFromResource(const ResourceName: string);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(const FileName : string);
procedure SaveToStream(Stream : TStream);
procedure ReportStats(S : TStrings; ReportMode : TReportMode);
procedure DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
function GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte = $FF) : boolean;
public
property FileName : string read FFileName;
property HexSections : TIntelHexSections read FSections;
property Log : TStrings read FLog;
published
property EOL : string read FEOL write FEOL;
property OverlapMode : TOverlapMode read FOverlapMode write FOverlapMode;
property OverflowMode : TOverflowMode read FOverflowMode write FOverflowMode;
property OnOverlap : TOverlapEvent read FOnOverlap write FOnOverlap;
property OnOverflow : TOverflowEvent read FOnOverflow write FOnOverflow;
end;
procedure DrawMemoryBlockOnMap(ABitMap : TBitMap; BytesOnLine : integer; Address : cardinal; Count : integer);
function BufferToHex(const Buffer; Count : integer) : string;
function BufferToString(const Buffer; Count : integer) : string;
implementation
constructor TIntelHexRecord.Create(Address : cardinal; const Data; Count : integer);
begin
inherited Create;
FAddress := Address;
FByteCount := Count;
GetMem(PData, Count);
Move(Data, PData^, Count);
end;
destructor TIntelHexRecord.Destroy;
begin
FreeMem(PData);
inherited Destroy;
end;
procedure TIntelHexRecord.ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
var
Str : string;
begin
Inc(TotalBytes, ByteCount);
if not (rmVerbose in ReportMode) then exit;
Str := Format('[0x%8.8x:0x%8.8x] (%3u bytes)',[Address, Address+ByteCount-1, ByteCount]);
if rmHexData in ReportMode then Str := Str+' '+BufferToHex(DataPtr^, ByteCount);
if rmStrData in ReportMode then Str := Str+' '+BufferToString(DataPtr^, ByteCount);
S.Add(Str);
end;
procedure TIntelHexRecord.DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
begin
DrawMemoryBlockOnMap(ABitmap, BytesOnLine, FAddress, FByteCount);
end;
{--------------------------------------------------------------------------------------------------------}
constructor TIntelHexSection.Create(SectionName : string; RangeMin, RangeMax : cardinal);
begin
Inherited Create;
FSectionName := SectionName;
FRangeMin := Min(RangeMin, RangeMax);
FRangeMax := Max(RangeMin, RangeMax);
FAddressMin := High(FAddressMin);
FAddressMax := Low(FAddressMax);
FIgnore := false;
FItems := TObjectList.Create;
end;
destructor TIntelHexSection.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
function TIntelHexSection.GetItem(Index : integer) : TIntelHexRecord;
begin
result := TIntelHexRecord(FItems[Index]);
end;
function TIntelHexSection.GetCount : integer;
begin
result := FItems.Count;
end;
function TIntelHexSection.FindFirst(Offset : cardinal; Count : integer; var Rec : TIntelHexRecord) : boolean;
var
i : integer;
begin
result := false;
Rec := nil;
Sort;
i := 0;
while i < FItems.Count do begin
if Item[i].Address >= Offset+Count then exit;
if Item[i].Address+Item[i].ByteCount-1 >= Offset then begin
Rec := Item[i];
result := true;
exit;
end;
inc(i);
end;
end;
function TIntelHexSection.FindNext(Const Rec : TIntelHexRecord; var NextRec : TIntelHexRecord) : boolean;
var
i : integer;
begin
result := false;
NextRec := nil;
Sort;
i := FItems.IndexOf(Rec);
if (i = -1) or (i = Count-1) then exit;
NextRec := Item[i+1];
result := true;
end;
function CompareFunc(Item1, Item2: Pointer): Integer;
begin
if TIntelHexRecord(Item1).Address = TIntelHexRecord(Item2).Address then
result := 0
else if TIntelHexRecord(Item1).Address < TIntelHexRecord(Item2).Address then
result := -1
else
result := +1;
end;
procedure TIntelHexSection.Sort;
begin
FItems.Sort(CompareFunc);
end;
procedure TIntelHexSection.AddData(Offset : cardinal; const Buffer; Count : integer);
begin
FAddressMin := Min(Offset, FAddressMin);
FAddressMax := Max(Offset+Count-1, FAddressMax);
FItems.Add(TIntelHexRecord.Create(Offset, Buffer, Count));
end;
procedure TIntelHexSection.CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
var
i : integer;
TotalBytes : cardinal;
begin
TotalBytes := 0;
i := 0;
while i<Count do begin
HexFile.AddData(Item[i].Address+RelocateOffset, Item[i].DataPtr^, Item[i].ByteCount);
inc(TotalBytes, Item[i].ByteCount);
inc(i);
end;
if TotalBytes>0 then
if RelocateOffset = 0 then
HexFile.Log.Add(Format('Copy %s, %u bytes', [SectionName, TotalBytes]))
else if RelocateOffset > 0 then
HexFile.Log.Add(Format('Relocate %s RelocateOffset = 0x%x, %u bytes', [SectionName, RelocateOffset, TotalBytes]))
else
HexFile.Log.Add(Format('Relocate %s RelocateOffset = -0x%x, %u bytes', [SectionName, -RelocateOffset, TotalBytes]));
end;
procedure TIntelHexSection.ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
var
i : integer;
SectionBytes : cardinal;
Report : string;
ReportPos : integer;
begin
ReportPos := S.Count; // keep position in S to insert report Title
SectionBytes := 0;
i := 0;
while i<Count do begin
Item[i].ReportStats(S, SectionBytes, ReportMode);
inc(i);
end;
Report := Format('[%8.8x:%8.8x] %s ', [RangeMin, RangeMax, SectionName]);
if Count>0 then begin
report := report + Format('[%8.8x..%8.8x] : %u blocks, %u bytes', [AddressMin, AddressMax, Count, SectionBytes]);
S.Insert(ReportPos, report);
end else
if rmVerbose in ReportMode then S.Insert(ReportPos, Report+'Empty section');
Inc(TotalBytes, SectionBytes);
end;
procedure TIntelHexSection.DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
var
i : integer;
begin
i := 0;
while i < FItems.Count do begin
Item[i].DrawMemoryMap(ABitmap, BytesOnLine);
Inc(i);
end;
end;
function TIntelHexSection.GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte = $FF) : boolean;
var
Rec : TIntelHexRecord;
Diff : integer; // différence entre le début du record et l'offset
Count : integer; // nombre de bytes à copier
Index : integer; // position dans le Buffer;
begin
result := false;
FillChar(Buffer, BufferSize, Fill);
if not FindFirst(Offset, BufferSize, Rec) then exit;
result := true;
Index := 0; // début du buffer
// while (Rec <> nil) and (Rec.Address <= Offset+Index) and (Index < BufferSize) do begin
while (Rec <> nil) and (Index < BufferSize) do begin
Diff := Offset+Index-Rec.Address;
if Diff < 0 then begin
Index := Index-Diff;
Diff := 0;
end;
Count := Min(Rec.ByteCount-Diff, BufferSize-Index);
if Count >0 then begin
Move(Rec.DataPtr^[Diff], TByteArray(Buffer)[Index], Count);
Inc(Index, Count);
end;
FindNext(Rec, Rec);
end;
end;
{--------------------------------------------------------------------------------------------------------}
constructor TIntelHexSections.Create;
begin
inherited Create;
FItems := TObjectList.Create;
FItems.Add(TIntelHexSection.Create('N/A', 0, 0));
end;
destructor TIntelHexSections.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
function TIntelHexSections.GetItem(Index : Integer) : TIntelHexSection;
begin
result := TIntelHexSection(FItems[Index]);
end;
function TIntelHexSections.GetCount : integer;
begin
result := FItems.Count;
end;
function TIntelHexSections.Add(SectionName : string; RangeMin, RangeMax : cardinal) : TIntelHexSection;
begin
result := nil;
if RangeMin = RangeMax then begin
raise EIntelHex.CreateFmt('IntelHexSections error : range overlap %u..%u', [RangeMin, RangeMax]);
exit;// Only one default section
end;
if (FItems.Count=0) or ((FindSectionIndex(RangeMin)=0)and (FindSectionIndex(RangeMax)=0)) then
result := TIntelHexSection(FItems.Add(TIntelHexSection.Create(SectionName, RangeMin, RangeMax)))
else
raise EIntelHex.CreateFmt('IntelHexSections error : range overlap 0x%x .. 0x%x', [RangeMin, RangeMax]);
end;
function TIntelHexSections.FindSectionIndex(Address : cardinal) : integer;
begin
result := FItems.Count-1;
if result <= 0 then exit; // Default section
repeat
with Item[result] do
if (Address >= RangeMin) and (Address <= RangeMax) then exit; // Found
Dec(result);
until result=0;
end;
function TIntelHexSections.FindSection(Address : cardinal) : TIntelHexSection;
begin
result := Item[FindSectionIndex(Address)];
end;
function TIntelHexSections.FindSectionByName(const SectionName : string; var Dest : TIntelHexSection) : boolean;
var
i : integer;
begin
result := false;
i := 0;
while i<Count do begin
if CompareText(Item[i].SectionName, SectionName) = 0 then begin
Dest := Item[i];
result := true;
exit;
end;
inc(i);
end;
end;
procedure TIntelHexSections.IgnoreSection(const SectionName : string);
var
Section : TIntelHexSection;
begin
if FindSectionByName(SectionName, Section) then Section.Ignore := true;
end;
procedure TIntelHexSections.CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
var
i : integer;
begin
i := 0;
while i < Count do begin
if not Item[i].Ignore then Item[i].CopyTo(HexFile, RelocateOffset);
Inc(i);
end;
end;
procedure TIntelHexSections.ReportStats(S : TStrings; var TotalBytes : cardinal; ReportMode : TReportMode);
var
i : integer;
begin
i := 0;
while i < Count do begin
Item[i].ReportStats(S, TotalBytes, ReportMode);
Inc(i);
end;
end;
procedure TIntelHexSections.DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
var
i : integer;
begin
i := 0;
while i < FItems.Count do begin
Case i of
0 : ABitmap.Canvas.Pen.Color := clRed;
1 : ABitmap.Canvas.Pen.Color := clLime;
2 : ABitmap.Canvas.Pen.Color := clGreen;
3 : ABitmap.Canvas.Pen.Color := clBlue;
else
ABitmap.Canvas.Brush.Color := clBlack;
end;
Item[i].DrawMemoryMap(ABitmap, BytesOnLine);
Inc(i);
end;
end;
function TIntelHexSections.GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte) : boolean;
var
i : integer;
begin
result := false;
i := FindSectionIndex(Offset);
if i < 0 then exit;
result := Item[i].GetData(Offset, Buffer, BufferSize, Fill);
end;
{--------------------------------------------------------------------------------------------------------}
constructor TIntelHexFile.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFileName := 'NoName.hex';
FStartAddress := 0;
FSections := TIntelHexSections.Create;
FOverlapMode := [ovlNone];
FOverflowMode := [ovfSplit];
FOnOverlap := nil;
FOnOverflow := nil;
FLog := TStringList.Create;
FEOL := #13#10;
end;
destructor TIntelHexFile.Destroy;
begin
FLog.Free;
FSections.Free;
inherited Destroy;
end;
procedure TIntelHexFile.LoadFromFile(const FileName: string);
var
Stream : TFileStream;
begin
FFileName := FileName;
Log.Add('LoadFromFile : '+FFileName);
Stream := TFileStream.Create(FileName, fmOpenRead);
LoadFromStream(Stream);
Stream.Free;
end;
procedure TIntelHexFile.LoadFromResource(const ResourceName: string);
var
Stream : TResourceStream;
begin
if FindResource(HInstance, PChar(ResourceName), RT_RCDATA)<>0 then begin
FFileName := ResourceName;
Log.Add('LoadFromResource : '+FFileName);
Stream := TResourceStream.Create(HInstance, ResourceName, RT_RCDATA);
LoadFromStream(Stream);
Stream.Free;
end;
end;
procedure TIntelHexFile.LoadFromStream(Stream: TStream);
const
EOF_Found = -1;
IllegalChar = -2;
CheckSumWrong = -3;
BadRecord = -4;
var
Offset : cardinal;
LineCounter : integer;
RecStr : string;
function ReadRecordStr : integer;
var
Nibble : char;
i : integer;
Chk : word;
begin
result := EOF_Found;
RecStr := '';
// Find start code ':'
repeat
if Stream.Read(Nibble, 1) < 1 then exit; // EOF
until Nibble = ':';
// Read the record until end of record
while true do begin
if Stream.Read(Nibble, 1) < 1 then break; // EOF, we will see if record is coorect...
if Nibble in [#13, #10, #0] then begin
Inc(LineCounter);
break; // we are at End of line
end;
if Nibble = ':' then begin
Stream.Seek(-1, soFromCurrent); // we are at begining of next record
break;
end;
if Nibble in ['0'..'9', 'A'..'F', 'a'..'f'] then
RecStr := RecStr + Nibble
else begin
result := IllegalChar;
exit;
end;
end; // while
// Now check if record size is correct...
if (Length(RecStr)< 10) or Odd(Length(RecStr)) then begin
result := BadRecord;
exit;
end;
if Length(RecStr) - (StrToInt('$'+Copy(RecStr, 1, 2)) * 2) <> 10 then begin
result := BadRecord;
exit;
end;
// Now check checksum...
Chk := 0;
i := 1;
repeat
Chk := Chk + StrToInt('$'+Copy(RecStr, i, 2));
i := i+2;
until (i = Length(RecStr) -1 );
Chk := ($0100 - (Chk and $00FF)) and $00FF;
if Chk <> StrToInt('$'+Copy(RecStr, i, 2)) then begin
result := CheckSumWrong;
exit;
end;
// Finally extract Record type
result := StrToInt('$'+Copy(RecStr, 7, 2));
end;
function GetWordAt(Index : integer) : word;
begin
result := StrToInt('$'+ Copy(RecStr, Index, 4));
end;
begin
Offset := 0;
LineCounter := 1;
while true do begin
Case ReadRecordStr of
EOF_Found : begin
raise EIntelHex.Create('IntelHex read error : EOF ');
exit;
end;
IllegalChar : begin
raise EIntelHex.CreateFmt('IntelHex read error : Illegal char in line %u %s', [LineCounter, RecStr]);
exit;
end;
CheckSumWrong : begin
raise EIntelHex.CreateFmt('IntelHex read error : CheckSum in line %u %s', [LineCounter, RecStr]);
exit;
end;
BadRecord : begin
raise EIntelHex.CreateFmt('IntelHex read error : Bad record in line %u %s', [LineCounter, RecStr]);
exit;
end;
$00 : begin // Data record
AddData(Offset+GetWordAt(3), Copy(RecStr, 9, Length(RecStr)-10));
end;
$01 : begin // EOF record
FStartAddress := GetWordAt(3);
exit;
end;
$02 : begin // Extended Segement
MessageBox(0, PChar(RecStr), 'Extended Segment', MB_OK);
end;
$03 : begin // Start Segment Address
MessageBox(0, PChar(RecStr), 'Start Segment Address', MB_OK);
end;
$04 : begin // Extended Linear Address
Offset := GetWordAt(9) shl 16;
// MessageBox(0, PChar('0x'+IntToHex(Offset, 8)), 'Extended Linear Address', MB_OK);
end;
$05 : begin // Start Linear Address
MessageBox(0, PChar(RecStr), 'Start Linear Address', MB_OK);
end;
else begin
raise EIntelHex.CreateFmt('IntelHex read error : Bad record type in line %u %s', [LineCounter, RecStr]);
exit;
end;
end;
end;
end;
procedure TIntelHexFile.SaveToFile(const FileName : string);
var
Stream : TFileStream;
begin
FFileName := FileName;
Log.Add('SaveFromFile : '+FFileName);
Stream := TFileStream.Create(FileName, fmCreate);
SaveToStream(Stream);
Stream.Free;
end;
procedure TIntelHexFile.SaveToStream(Stream : TStream);
var
i, j : integer;
Offset : word;
SwapedOffset : word;
Buffer : ShortString;
function HexRecord(ByteCount : byte; Address : word; RecType : byte; PData : PByteArray) : string;
var
Chk : word;
i : integer;
begin
Chk := 0;
result := Format(':%2.2x%4.4x%2.2x', [ByteCount, Address, RecType]);
Chk := ByteCount+Lo(Address)+Hi(Address)+RecType;
i := 0;
while i<ByteCount do begin
result := result+IntToHex(PData^[i], 2);
Inc(Chk, PData^[i]);
inc(i);
end;
Chk := ($0100 - (Chk and $00FF)) and $00FF;
result := Uppercase(result + IntToHex(Chk, 2));
end;
begin
Offset := $FFFF; // Force Extended Linear Addres record
i := 0;
while i < HexSections.Count do begin
HexSections.Item[i].Sort;
j := 0;
while j < HexSections.Item[i].Count do begin
with HexSections.Item[i].Item[j] do begin
if (Address shr 16) <> Offset then begin
// Change Extended Linear Address
Offset := Address shr 16;
SwapedOffset := Swap(Offset);
Buffer := HexRecord(2, 0, $04, @SwapedOffset)+EOL;
Stream.WriteBuffer(Buffer[1], Length(Buffer));
end;
Buffer := HexRecord(ByteCount, Address and $FFFF, $00, DataPtr)+EOL;
Stream.WriteBuffer(Buffer[1], Length(Buffer));
end;
inc(j);
end;
inc(i);
end;
Buffer := HexRecord(0, 0, $01, nil)+EOL;
Stream.WriteBuffer(Buffer[1], Length(Buffer));
end;
procedure TIntelHexFile.AddData(Offset : cardinal; Nibbles : string);
var
Buffer : array[0..255] of byte;
i : integer;
begin
i := 0;
while i < Length(Nibbles) div 2 do begin
Buffer[i] := StrToInt('$'+Copy(Nibbles, Succ(i*2), 2));
inc(i);
end;
AddData(Offset, Buffer, Length(Nibbles) div 2);
end;
procedure TIntelHexFile.AddData(Offset : cardinal; const Buffer; Count : integer);
var
Section : TIntelHexSection;
HexRec : TIntelHexRecord;
Count1, Remainder : integer;
begin
if Count = 0 then exit;
Section := FSections.FindSection(Offset);
if Section = FSections.FindSection(Offset+Count-1) then begin
// Check if overlapping...
if Section.FindFirst(Offset, Count, HexRec) then begin
if Assigned(FOnOverlap) and not (ovlAlways in FOverlapMode) then
FOnOverlap(self, Offset, HexRec.DataPtr^, Buffer, Count, FOverlapMode);
end else begin
Section.AddData(Offset, Buffer, Count);
// Log.Add(Format('Add %3u bytes [0x%8x..0x%8x] %s %s', [Count, Offset, Offset+Count-1, BufferToHex(Buffer, Count), BufferToString(Buffer, Count)]));
end;
end else begin // Split Data to fit in section
if Assigned(FOnOverflow) and not (ovfAlways in FOverflowMode) then
FOnOverflow(self, Offset, Buffer, Count,
Section.SectionName, Section.RangeMin, Section.RangeMax, FOverflowMode);
Count1 := Section.RangeMax-Offset;
Remainder := Count-Count1;
if ovfSplit in FOverflowMode then begin
// Split
Log.Add('==> Split Data Begin');
AddData(Offset, Buffer, Count1);
AddData(Offset+Count1+1, TByteArray(Buffer)[Count1], Remainder);
Log.Add('==> Split Data End');
end else if ovfCut in FOverflowMode then begin
// Cut
AddData(Offset, Buffer, Count1);
Log.Add(Format('==> Drop out %u bytes', [Remainder]));
end else begin
// Ignore
Log.Add(Format('==> Drop out %u bytes', [Count]));
end;
end;
end;
procedure TIntelHexFile.CopyTo(HexFile : TIntelHexFile; RelocateOffset : integer);
begin
HexSections.CopyTo(HexFile, RelocateOffset);
end;
function TIntelHexFile.CopySectionTo(const SectionName : string; HexFile : TIntelHexFile; RelocateOffset : integer) : boolean;
var
Section : TIntelHexSection;
begin
result := HexSections.FindSectionByName(SectionName, Section);
if not result then exit;
Section.CopyTo(HexFile, RelocateOffset);
end;
procedure TIntelHexFile.ReportStats(S : TStrings; ReportMode : TReportMode);
var
TotalBytes : cardinal;
begin
TotalBytes := 0;
S.Add(Format('Stats "%s"', [FFileName]));
HexSections.ReportStats(S, TotalBytes, ReportMode);
S.Add(Format('%u bytes in "%s"', [TotalBytes, ExtractFileName(FFileName)]));
S.Add('');
end;
procedure TIntelHexFile.DrawMemoryMap(ABitMap : TBitMap; BytesOnLine : integer);
begin
FSections.DrawMemoryMap(ABitmap, BytesOnLine);
end;
function TIntelHexFile.GetData(Offset : cardinal; var Buffer; BufferSize : integer; Fill : byte = $FF) : boolean;
begin
result := FSections.GetData(Offset, Buffer, BufferSize, Fill);
end;
{--------------------------------------------------------------------------------------------------------}
procedure DrawMemoryBlockOnMap(ABitmap : TBitmap; BytesOnLine : integer; Address : cardinal; Count : integer);
const
XMult = 1;
YMult = 2;
var
X1, Y1 : Integer; // From
FirstLineLeft : integer;
i : integer;
begin
Y1 := (ABitmap.Height-1) - (Address div BytesOnLine)*YMult; // inverted
FirstLineLeft := (Address mod BytesOnLine);
X1 := FirstLineLeft * XMult;
if FirstLineLeft+Count <= BytesOnLine then
// Just one segment on the line
for i := 0 to pred(YMult) do begin
ABitmap.Canvas.MoveTo(X1, Y1-i);
ABitmap.Canvas.LineTo(X1+(Count*XMult), Y1-i);
end
else begin
// First line
for i := 0 to pred(YMult) do begin
ABitmap.Canvas.MoveTo(X1, Y1-i);
ABitmap.Canvas.LineTo(BytesOnLine*XMult, Y1-i);
end;
Dec(Y1, YMult); // Next Line
Dec(Count, BytesOnLine-FirstLineLeft); // We have already drawn that...
while Count div BytesOnLine > 0 do begin // Full lines
for i := 0 to pred(YMult) do begin
ABitmap.Canvas.MoveTo(0, Y1-i);
ABitmap.Canvas.LineTo(BytesOnLine*XMult, Y1-i);
end;
Dec(Y1, YMult); // Next Line
Dec(Count, BytesOnLine); // We have already drawn that...
end;
// Last line
for i := 0 to pred(YMult) do begin
ABitmap.Canvas.MoveTo(0, Y1-i);
ABitmap.Canvas.LineTo(Count*XMult, Y1-i);
end;
end;
end;
function BufferToHex(const Buffer; Count : integer) : string;
var
i : integer;
begin
result := '';
i := 0;
while i < Count do begin
if i = 0 then
result := Format('0x%2x', [TByteArray(Buffer)[0]])
else
result := result + Format(' 0x%2x', [TByteArray(Buffer)[i]]);
inc(i);
end;
end;
function BufferToString(const Buffer; Count : integer) : string;
var
i : integer;
begin
result := '';
i := 0;
while i < Count do begin
if char(TByteArray(Buffer)[i]) in [' '..'}'] then
result := result + char(TByteArray(Buffer)[i])
else
result := result + '~';
inc(i);
end;
end;
end.
|
unit uDocument;
interface
uses SysUtils, Windows, Classes, XMLIntf, XMLDoc, uStrings, XMLUtils;
type TOmgDocument = class
type tOmgDocType = (dtUnknown, dtXML, dtCrypted);
type TCryFileHeader = record
Magic: array[0..3] of AnsiChar;
docVersion: Byte;
rsrvdByte1: Byte;
rsrvdByte2: Byte;
rsrvdByte3: Byte;
firstHeader: array[0..$3F] of Byte;
secondHeader: array[0..63] of Byte;
end;
const
ActualDocVersion: Byte = 1;
cryMagicSig: String = 'OMG!';
EmptyXML: AnsiString = '<?xml version="1.0" encoding="UTF-8"?>'
+ CrLf + '<Root><Header/><Data/></Root>';
var
docFilePath: String;
docType: tOmgDocType;
XML: iXMLDocument;
docPages: IXMLNodeList;
CurrentPage: Integer; //Текущая страничка
CurrentRecord: Integer; //...и запись
private
docHeader: TCryFileHeader;
docPassword: String;
fileStream: TFileStream;
procedure LoadPosition;
procedure SavePosition;
function OpenXMLfromStream(xmlMainStream: TStream): Boolean;
function OpenCrypted(Password: String): Boolean;
public
constructor Create; overload;
constructor Create(FilePath: String; Password: String); overload;
constructor CreateNew(FilePath: String; dType: tOmgDocType; Password: String = ''); overload;
destructor Destroy; override;
function Open(Path: String; Password: String): Boolean;
function OpenByPass(FilePath: String): Boolean;
//function Save: Boolean;
function Close: Boolean;
function GetProperty(PropertyName: String; DefValue: Variant): Variant;
function SetProperty(PropertyName: String; Value: Variant): Boolean;
function IsEmpty: Boolean;
class function CreateHeader(sPassword: String): TCryFileHeader; //Аналог static в шарпе
procedure SaveAsCrypted;
function Save(FilePath: String = ''): Boolean;
function CheckThisPassword(Password: String): Boolean;
function ChangePassword(Password: String): Boolean;
end;
implementation
uses uLog, uCrypt;
constructor TOmgDocument.Create;
begin
//inherited Create;
XML:=TXMLDocument.Create(nil);
XML.Options :=[doAttrNull, doAutoSave];
XML.ParseOptions:=[poValidateOnParse];
end;
constructor TOmgDocument.Create(FilePath: String; Password: String);
begin
Self.Create;
if not Self.Open(filePath, Password) then raise Exception.Create('Error opening file');
end;
constructor TOmgDocument.CreateNew(filePath: String; dType: tOmgDocType; Password: String = '');
//var
// fStream: TFileStream;
begin
try
Self.Create;
fileStream:= TFileStream.Create(FilePath, fmOpenReadWrite or fmCreate);
Self.docFilePath:= filePath;
Self.docType:= dType;
if dType = dtCrypted then begin
docPassword:=Password;
docHeader:=CreateHeader(Password);
end;
XML.LoadFromXML(EmptyXML);
XML.Active:=True;
except
on e: Exception do ErrorLog(e, 'Document.CreateNew');
end;
end;
function TOmgDocument.Open(Path: String; Password: String): Boolean;
begin
try
fileStream:= TFileStream.Create(Path, fmOpenReadWrite);
Self.docFilePath:= Path;
docPassword:=Password;
if ExtractFileExt(Path) = strDefaultExt then begin
Self.OpenXMLfromStream(fileStream);
docType:= dtXML;
end else begin
Self.OpenCrypted(Password);
docType:=dtCrypted;
end;
XML.Active:=True;
Result:=True;
except
Result:=False;
end;
end;
function TOmgDocument.OpenXMLfromStream(xmlMainStream: TStream): Boolean;
begin
try
XML.LoadFromStream(xmlMainStream);
docPages:= NodeByPath(XML, 'Root|Data').ChildNodes;
LoadPosition;
Result:=True;
except
on e: Exception do begin
ErrorLog(e, 'OpenXMLfromStream');
Result:=False;
end;
end;
end;
function TOmgDocument.OpenCrypted(Password: String): Boolean;
var
cryStream, xmlStream: TMemoryStream;
begin
try
try
fileStream.Read(docHeader, SizeOf(TCryFileHeader));
cryStream:=TMemoryStream.Create;
xmlStream:=TMemoryStream.Create;
cryStream.CopyFrom(fileStream, fileStream.Size - SizeOf(TCryFileHeader));
//Log(cryStream, 50, '>');
UnCryptStream(cryStream, xmlStream, Password, 1024);
Result:= Self.OpenXmlfromStream(xmlStream);
except
on e: Exception do begin
ErrorLog(e, 'OpenCrypted');
Result:=False;
end;
end;
finally
FreeAndNil(cryStream);
FreeAndNil(xmlStream);
end;
end;
procedure TOmgDocument.SaveAsCrypted();
var fName: String;
Header: TCryFileHeader;
fStream: TFileStream;
cStream, xStream: TMemoryStream;
begin
if Self.docType = dtCrypted then Exit; //Already crypted
try
fName:= ChangeFileExt(Self.docFilePath, strCryptedExt);
Header:= TOmgDocument.CreateHeader(String.Empty);
fStream:=TFileStream.Create(fName, fmOpenWrite or fmCreate);
xStream:=TMemoryStream.Create;
cStream:=TMemoryStream.Create;
fStream.Write(Header, SizeOf(Header));
XML.SaveToStream(xStream);
CryptStream(xStream, cStream, String.Empty, $100);
fStream.CopyFrom(cStream, cStream.Size);
finally
FreeAndNil(fStream);
FreeAndNil(xStream);
FreeAndNil(cStream);
end;
end;
function TOmgDocument.Save(FilePath: String= ''): Boolean;
var
xStream, cStream, fStream: TMemoryStream;
begin
try
Self.SavePosition;
fStream:=TMemoryStream.Create;
xStream:=TMemoryStream.Create; //Position:=0; xmlStream.Size:=0;
Self.XML.SaveToStream(xStream);
xStream.Position:=0;
fStream.Position:=0;
fileStream.Position:=0;
if Self.docType = dtCrypted then begin
cStream:=TMemoryStream.Create;
fStream.WriteBuffer(docHeader, sizeOf(TCryFileHeader));
cryptStream(xStream, cStream, docPassword, $100);
fStream.CopyFrom(cStream, cStream.Size);
fStream.Size:= cStream.Size + sizeOf(TCryFileHeader);
cStream.Free;
end else begin
xStream.SaveToStream(fStream);
fStream.Size:= xStream.Size;
xStream.Free;
end;
if FilePath <> '' then
fStream.SaveToFile(FilePath)
else begin
fileStream.CopyFrom(fStream, 0);
fileStream.Size:= fStream.Size;
end;
fStream.Free;
Result:=True;
except
on e: Exception do begin
ErrorLog(e, 'TOmgDocument.SaveAs');
Result:=False;
end;
end;
end;
//function TOmgDocument.Save: Boolean;
//var
// xStream, cStream: TMemoryStream;
//begin
// try
// Self.SavePosition;
// xStream:=TMemoryStream.Create; //Position:=0; xmlStream.Size:=0;
// Self.XML.SaveToStream(xStream);
// xStream.Position:=0;
// fileStream.Position:=0;
// if Self.docType = dtCrypted then begin
// cStream:=TMemoryStream.Create;
// fileStream.WriteBuffer(docHeader, sizeOf(TCryFileHeader));
// cryptStream(xStream, cStream, docPassword, $100);
// fileStream.CopyFrom(cStream, cStream.Size);
// fileStream.Size:= cStream.Size + sizeOf(TCryFileHeader);
// end else begin
// xStream.SaveToStream(fileStream);
// fileStream.Size:= xStream.Size;
// end;
// Result:=True;
// except
// on e: Exception do begin
// ErrorLog(e, 'TOmgDocument.Save');
// Result:=False;
// end;
// end;
//end;
function TOmgDocument.Close;
begin
try
docFilePath:='';
docType:=dtXML;
docPages:=nil;
XML.XML.Clear;
XML.Active:=False;
docPassword:='';
CurrentPage:=0; //Текущая страничка
CurrentRecord:=0;
ZeroMemory(@docHeader, SizeOf(TCryFileHeader));
FreeAndNil(fileStream);
Result:=True;
except
on e: Exception do begin
ErrorLog(e, 'TOmgDocument.Close');
Result:=False;
end;
end;
end;
destructor TOmgDocument.Destroy;
begin
//Self.Close;
inherited Destroy;
end;
procedure TOmgDocument.LoadPosition;
begin
Self.CurrentPage:= Self.GetProperty('SelectedPage', 0);
Self.CurrentRecord:= Self.GetProperty('Selected', 0);
end;
procedure TOmgDocument.SavePosition;
begin
Self.SetProperty('SelectedPage', Self.CurrentPage);
Self.SetProperty('Selected', Self.CurrentRecord);
end;
function TOmgDocument.IsEmpty: Boolean;
begin
Result:= (Self.docPages.Count= 0);
end;
class function TOmgDocument.CreateHeader(sPassword: String): TCryFileHeader;
begin
with Result do begin
Magic:= 'OMG!';
rsrvdByte1:=$00;
rsrvdByte2:=$00;
rsrvdByte3:=$00;
docVersion := ActualDocVersion;
getHeader(sPassword).ReadBuffer(firstHeader, $40);
getSecondHeader(sPassword).ReadBuffer(secondHeader, $40);
// Log(firstHeader, 0, 'HirstHeader');
// Log(secondHeader, 0, 'SecondHeader');
end;
end;
function TOmgDocument.CheckThisPassword(Password: String): Boolean;
begin
try
Result:= CompareMem(GetHeader(Password).Memory, @docHeader.firstHeader[0], $40);
except
on e: Exception do begin
ErrorLog(e, 'TOmgDocument.CheckPassword');
Result:=False;
end;
end;
end;
function TOmgDocument.ChangePassword(Password: String): Boolean;
begin
try
Self.docHeader:=CreateHeader(Password);
Self.docPassword:=Password;
Result:= Self.Save;
except
on e: Exception do begin
ErrorLog(e, 'TOmgDocument.ChangePassword');
Result:=False;
end;
end;
end;
function TOmgDocument.OpenByPass(FilePath: String): Boolean;
var
tempStream: TFileStream;
cStream, xStream: TMemoryStream;
begin
try
tempStream:= TFileStream.Create(FilePath, fmOpenReadWrite);
tempStream.Read(docHeader, SizeOf(TCryFileHeader));
cStream:=TMemoryStream.Create;
xStream:=TMemoryStream.Create;
cStream.CopyFrom(tempStream, tempStream.Size - SizeOf(TCryFileHeader));
UnCryptStreamByKey(cStream, xStream, docHeader.secondHeader, $400);
Result:= Self.OpenXmlfromStream(xStream);
docFilePath:=ChangeFileExt(FilePath, strDefaultExt);
fileStream:= TFileStream.Create(docFilePath, fmCreate);
docType:=dtXML;
Self.Save;
XML.Active:=True;
except
on e: exception do begin ErrorLog(e, 'Document.OpenByPass');
Result:=False;
end;
end;
end;
{$REGION '#DocProperty'}
function TOmgDocument.GetProperty(PropertyName: String; DefValue: Variant): Variant;
//Установка и чтение свойств документа
//Все свойства хранятся в ntHeader
//Функции удаления нет.. нужна
begin
if (xml.ChildNodes[strRootNode].ChildNodes.FindNode(strHeaderNode) = nil)
or (xml.ChildNodes[strRootNode].ChildNodes[strHeaderNode].ChildNodes.FindNode(PropertyName) = nil)
then Result:=DefValue
else Result:=xml.ChildNodes[strRootNode].ChildNodes[strHeaderNode].ChildValues[PropertyName];;
end;
function TOmgDocument.SetProperty(PropertyName: String; Value: Variant): Boolean;
var hNode: IXMLNode;
begin
hNode:= xml.ChildNodes[strRootNode].ChildNodes.FindNode(strHeaderNode);
if hNode = nil then
hNode:=xml.ChildNodes[strRootNode].AddChild(strHeaderNode);
if hNode.ChildNodes.FindNode(PropertyName) = nil then
hNode.AddChild(PropertyName);
hNode.ChildValues[PropertyName]:=Value;
Result:=True;
end;
{$ENDREGION}
end.
|
{*********************************}
{********* P R O C _ A G *******}
{*********************************}
function sign(a : real) : integer;
begin if a<0 then sign:= -1 else sign:= 1; end; {sign}
{*************}
function max(a,b : real) : real;
begin if a>=b then max:= a else max:= b; end; {max}
{*************}
function min(a,b : real) : real;
begin if a<=b then min:= a else min:= b; end; {min}
{*************}
procedure put2d(x,y : real; var v: vt2d);
begin v.x:= x; v.y:= y; end;
{*************}
procedure put3d(x,y,z : real; var v: vt3d);
begin v.x:= x; v.y:= y; v.z:= z; end;
{*************}
procedure get3d(v : vt3d; var x,y,z: real);
begin x:= v.x; y:= v.y; z:= v.z; end;
{*************}
procedure scale2d(r : real; v: vt2d; var vs: vt2d);
begin vs.x:= r*v.x; vs.y:= r*v.y; end;
{*************}
procedure scale3d(r : real; v: vt3d; var vs: vt3d);
begin vs.x:= r*v.x; vs.y:= r*v.y; vs.z:= r*v.z; end;
{*************}
procedure scaleco2d(r1,r2 : real; v: vt2d; var vs: vt2d);
begin vs.x:= r1*v.x; vs.y:= r2*v.y; end;
{*************}
procedure scaleco3d(r1,r2,r3 : real; v: vt3d; var vs: vt3d);
begin vs.x:= r1*v.x; vs.y:= r2*v.y; vs.z:= r3*v.z; end;
{*************}
procedure sum2d(v1,v2 : vt2d; var vs : vt2d);
begin vs.x:= v1.x + v2.x; vs.y:= v1.y + v2.y; end;
{*************}
procedure sum3d(v1,v2 : vt3d; var vs : vt3d);
begin vs.x:= v1.x + v2.x; vs.y:= v1.y + v2.y; vs.z:= v1.z + v2.z; end;
{*************}
procedure diff2d(v1,v2 : vt2d; var vs : vt2d);
begin vs.x:= v1.x - v2.x; vs.y:= v1.y - v2.y; end;
{*************}
procedure diff3d(v1,v2 : vt3d; var vs : vt3d);
begin vs.x:= v1.x - v2.x; vs.y:= v1.y - v2.y; vs.z:= v1.z - v2.z; end;
{*************}
procedure lcomb2vt2d(r1: real; v1: vt2d; r2: real; v2: vt2d; var vlc : vt2d);
begin vlc.x:= r1*v1.x + r2*v2.x; vlc.y:= r1*v1.y + r2*v2.y; end;
{*************}
procedure lcomb2vt3d(r1: real; v1: vt3d; r2: real; v2: vt3d; var vlc : vt3d);
begin
vlc.x:= r1*v1.x + r2*v2.x; vlc.y:= r1*v1.y + r2*v2.y; vlc.z:= r1*v1.z + r2*v2.z;
end;
{*************}
procedure lcomb3vt2d(r1: real; v1: vt2d; r2: real; v2: vt2d;
r3: real; v3: vt2d; var vlc : vt2d);
begin
vlc.x:= r1*v1.x + r2*v2.x + r3*v3.x;
vlc.y:= r1*v1.y + r2*v2.y + r3*v3.y;
end;
{*************}
procedure lcomb3vt3d(r1: real; v1: vt3d; r2: real; v2: vt3d;
r3: real; v3: vt3d; var vlc : vt3d);
begin
vlc.x:= r1*v1.x + r2*v2.x + r3*v3.x;
vlc.y:= r1*v1.y + r2*v2.y + r3*v3.y;
vlc.z:= r1*v1.z + r2*v2.z + r3*v3.z;
end;
{*************}
procedure lcomb4vt3d(r1: real; v1: vt3d; r2: real; v2: vt3d;
r3: real; v3: vt3d; r4: real; v4: vt3d; var vlc : vt3d);
begin
vlc.x:= r1*v1.x + r2*v2.x + r3*v3.x + r4*v4.x;
vlc.y:= r1*v1.y + r2*v2.y + r3*v3.y + r4*v4.y;
vlc.z:= r1*v1.z + r2*v2.z + r3*v3.z + r4*v4.z;
end;
{*************}
function abs2d(v : vt2d) : real;
begin abs2d:= abs(v.x) + abs(v.y); end;
{*************}
function abs3d(v : vt3d) : real;
begin abs3d:= abs(v.x) + abs(v.y) + abs(v.z); end;
{*************}
function length2d(v : vt2d) : real;
begin length2d:= sqrt( sqr(v.x) + sqr(v.y) ); end;
{*************}
function length3d(v : vt3d) : real;
begin length3d:= sqrt( sqr(v.x) + sqr(v.y) + sqr(v.z)); end;
{*************}
procedure normalize2d(var p: vt2d);
var c : real;
begin c:= 1/length2d(p); p.x:= c*p.x; p.y:= c*p.y; end;
{************}
procedure normalize3d(var p: vt3d);
var c : real;
begin c:= 1/length3d(p); p.x:= c*p.x; p.y:= c*p.y; p.z:= c*p.z end;
{************}
function scalarp2d(p1,p2 : vt2d) : real;
begin scalarp2d:= p1.x*p2.x + p1.y*p2.y; end;
{*************}
function scalarp3d(p1,p2 : vt3d) : real;
begin scalarp3d:= p1.x*p2.x + p1.y*p2.y + p1.z*p2.z; end;
{*************}
function distance2d(p,q : vt2d): real;
begin distance2d:= sqrt( sqr(p.x-q.x) + sqr(p.y-q.y) ); end;
{*************}
function distance3d(p,q : vt3d): real;
begin distance3d:= sqrt( sqr(p.x-q.x) + sqr(p.y-q.y) + sqr(p.z-q.z) ); end;
{*************}
function distance2d_square(p,q : vt2d) : real;
begin distance2d_square:= sqr(p.x-q.x) + sqr(p.y-q.y); end;
{**************}
function distance3d_square(p,q : vt3d) : real;
begin distance3d_square:= sqr(p.x-q.x) + sqr(p.y-q.y) + sqr(p.z-q.z); end;
{**************}
procedure vectorp(v1,v2 : vt3d; var vp : vt3d);
{Berechnet das Kreuzprodukt von (x1,y1,z1) und (x2,y2,z2). }
begin
vp.x:= v1.y*v2.z - v1.z*v2.y ;
vp.y:= -v1.x*v2.z + v2.x*v1.z ;
vp.z:= v1.x*v2.y - v2.x*v1.y ;
end; {vectorp}
{*************}
function determ3d(v1,v2,v3: vt3d) : real;
{Berechnet die Determinante einer 3x3-Matrix.}
begin
determ3d:= v1.x*v2.y*v3.z + v1.y*v2.z*v3.x + v1.z*v2.x*v3.y
- v1.z*v2.y*v3.x - v1.x*v2.z*v3.y - v1.y*v2.x*v3.z;
end; {determ3d}
{*************}
procedure rotor2d(cos_rota,sin_rota : real; p : vt2d; var pr: vt2d);
begin
pr.x:= p.x*cos_rota - p.y*sin_rota;
pr.y:= p.x*sin_rota + p.y*cos_rota;
end; {rotor2d}
{*************}
procedure rotp02d(cos_rota,sin_rota : real; p0,p : vt2d; var pr: vt2d);
begin
pr.x:= p0.x + (p.x-p0.x)*cos_rota - (p.y-p0.y)*sin_rota;
pr.y:= p0.y + (p.x-p0.x)*sin_rota + (p.y-p0.y)*cos_rota;
end; {rotor2d}
{*************}
procedure rotorz(cos_rota,sin_rota : real; p : vt3d; var pr: vt3d);
begin
pr.x:= p.x*cos_rota - p.y*sin_rota;
pr.y:= p.x*sin_rota + p.y*cos_rota; pr.z:= p.z;
end; {rotorz}
{*************}
procedure rotp0z(cos_rota,sin_rota : real; p0,p: vt3d; var pr: vt3d);
begin
pr.x:= p0.x + (p.x-p0.x)*cos_rota - (p.y-p0.y)*sin_rota;
pr.y:= p0.y + (p.x-p0.x)*sin_rota + (p.y-p0.y)*cos_rota; pr.z:= p.z;
end; {rotp0z}
{*************}
procedure rotp0x(cos_rota,sin_rota : real; p0,p: vt3d; var pr: vt3d);
{Rotation um eine zur x-Achse parallele Achse durch p0}
begin
pr.y:= p0.y + (p.y-p0.y)*cos_rota - (p.z-p0.z)*sin_rota;
pr.z:= p0.z + (p.y-p0.y)*sin_rota + (p.z-p0.z)*cos_rota; pr.x:= p.x;
end; {rotp0x}
{*************}
procedure rotp0y(cos_rota,sin_rota : real; p0,p: vt3d; var pr: vt3d);
{Rotation um eine zur y-Achse parallele Achse durch p0}
begin
pr.x:= p0.x + (p.x-p0.x)*cos_rota - (p.z-p0.z)*sin_rota;
pr.z:= p0.z + (p.x-p0.x)*sin_rota + (p.z-p0.z)*cos_rota; pr.y:= p.y;
end; {rotp0y}
{*************}
procedure change1d(var a,b: real);
var aa: real;
begin aa:= a; a:= b; b:= aa; end;
{*********}
procedure change2d(var v1,v2: vt2d);
var vv: vt2d;
begin vv:= v1; v1:= v2; v2:= vv; end;
{**********}
procedure change3d(var v1,v2: vt3d);
var vv: vt3d;
begin vv:= v1; v1:= v2; v2:= vv; end;
{**********}
{polar_angles fuer altes p2c: (SUSE 6.4)}
function polar_angle(x,y : real) : real;
var w : real;
begin
if (x=0) and (y=0) then w:= 0
else
begin
if abs(y)<=abs(x) then
begin
w:= arctan(y/x);
if x<0 then w:=pi+w
else if (y<0) and( w<>0) then w:= pi2+w;
end
else
begin
w:= pih-arctan(x/y);
if y<0 then w:= pi+w;
end; {if}
end; {if}
polar_angle:= w;
end; { polar_angle }
{******************}
procedure equation_degree1(a,b :real; var x : real ; var ns : integer);
{Gleichung 1.Grades: a*x + b = 0 }
begin
if abs(a)=0 {<eps8} then ns:= -1
else begin x:=-b/a; ns:= 1; end;
end; { equation_degree1 }
{***************}
procedure equation_degree2(a,b,c:real; var x1,x2:real ;var ns:integer);
{Berechnet die REELLEN Loesungen einer Gleichnung 2.Grades: a*x*x+b*x+c = 0.}
var dis,wu2,xx1 : real;
begin
ns:=0;
if abs(a)=0 {<eps8} then
equation_degree1(b,c,x1,ns)
else
begin
dis:= b*b-4*a*c;
if (dis<0) and (dis>-eps6*abs(b)) then dis:=0;
if dis<0 then ns:= 0
else
begin
if abs(dis)<eps8 then
begin ns:= 1; x1:= -b/(2*a); x2:= x1; end
else
begin
ns:= 2; wu2:= sqrt(dis);
x1:= (-b+wu2)/(2*a); x2:= (-b-wu2)/(2*a);
end;
end; {dis>=0}
end; {a<>0}
{Umordnen nach Groesse:}
if ns=2 then if x2<x1 then change1d(x1,x2);
end; { equation_degree2 }
{*****************}
procedure is_line_line(a1,b1,c1, a2,b2,c2 : real; var xs,ys : real;
var nis : integer);
{Schnittpunkt (xs,ys) (ns=1) der Geraden a1*x+b1*y=c1, a2*x+b2*y=c2 .}
var det : real;
begin
det:= a1*b2 - a2*b1;
if abs(det)<eps8 then nis:= 0
else
begin
nis:= 1; xs:= (c1*b2 - c2*b1)/det; ys:= (a1*c2 - a2*c1)/det;
end;
end; { is_line_line }
{************}
procedure is_unitcircle_line(a,b,c: real; var x1,y1,x2,y2 : real;
var nis : integer);
{Schnitt Kreis-Gerade: sqr(x)+sqr(y)=1, a*x+b*y=c,
Schnittpkte: (x1,y1),(x2,y2).Es ist x1<=x2, nis Anzahl der Schnittpunkte}
var ab2,wu,dis : real;
begin
nis:= 0; ab2:= a*a + b*b; dis:= ab2 - c*c;
if dis>=0 then
begin
nis:= 2;
wu:= sqrt(dis); if abs(wu)<eps8 then nis:= 1;
x1:= (a*c-b*wu)/ab2; y1:= (b*c+a*wu)/ab2;
x2:= (a*c+b*wu)/ab2; y2:= (b*c-a*wu)/ab2;
if x2<x1 then begin change1d(x1,x2); change1d(y1,y2); end;
end;
end; { is_unitcircle_line }
{************}
procedure is_circle_line(xm,ym,r, a,b,c: real; var x1,y1,x2,y2 : real;
var nis : integer);
{Schnitt Kreis-Gerade: sqr(x-xm)+sqr(y-ym)=r*r, a*x+b*y=c,
Schnittpkte: (x1,y1),(x2,y2).Es ist x1<=x2, nis Anzahl der Schnittpunkte}
var ab2,wu,dis,cc : real;
begin
nis := 0;
ab2:= a*a + b*b; cc:=c - a*xm - b*ym; dis:= r*r*ab2 - cc*cc;
if dis>=0 then
begin
nis:= 2;
wu:= sqrt(dis); if abs(wu)<eps8 then nis:= 1;
x1:= xm + (a*cc-b*wu)/ab2; y1:= ym + (b*cc+a*wu)/ab2;
x2:= xm + (a*cc+b*wu)/ab2; y2:= ym + (b*cc-a*wu)/ab2;
if x2<x1 then begin change1d(x1,x2); change1d(y1,y2); end;
end;
end; { is_circle_line }
{************}
procedure is_circle_circle(xm1,ym1,r1,xm2,ym2,r2: real;
var x1,y1,x2,y2: real; var nis: integer);
{Schnitt Kreis-Kreis. Es ist x1<x2. nis = Anzahl der Schnittpunkte }
var a,b,c : real;
begin
a:= 2*(xm2 - xm1); b:= 2*(ym2 - ym1);
c:= r1*r1 - sqr(xm1) -sqr(ym1) - r2*r2 + sqr(xm2) + sqr(ym2);
if (abs(a)+abs(b)<eps8) then nis:= 0
else is_circle_line(xm1,ym1,r1,a,b,c,x1,y1,x2,y2,nis);
end; { is_circle_circle }
{************}
function pt_before_plane(p,nv: vt3d; d: real) : boolean;
{...stellt fest, ob der Punkt p "vor" der Ebene nv*x-d=0 liegt.}
begin if (scalarp3d(p,nv)-d) >=0 then pt_before_plane:= true
else pt_before_plane:= false; end;
{*************}
procedure plane_equ(p1,p2,p3 : vt3d; var nv : vt3d; var d: real;
var error : boolean);
{Berechnet die Gleichung nv*x=d der Ebene durch die Punkte p1,p2,p3.
error=true: die Punkte spannen keine Ebene auf.}
var p21,p31 : vt3d;
begin
diff3d(p2,p1,p21); diff3d(p3,p1,p31);
vectorp(p21,p31,nv); d:= scalarp3d(nv,p1);
if abs3d(nv)<eps8 then error:= true else error:= false;
end; { plane_coeff }
{*************}
procedure is_line_plane(p,rv,nv: vt3d; d : real; var pis : vt3d;
var nis : integer);
{Schnitt Gerade-Ebene. Gerade: Punkt p, Richtung r. Ebene: nv*x = d .
nis=0: kein Schnitt ,nis=1: Schnittpunkt, nis=2: Gerade liegt in der Ebene.}
var t,sp,pd : real;
begin
sp:= scalarp3d(nv,rv); pd:= scalarp3d(nv,p) - d;
if abs(sp)<eps8 then
begin nis:= 0; if abs(pd)<eps8 then nis:= 2; end
else
begin
t:= -pd/sp; lcomb2vt3d(1,p ,t,rv ,pis); nis:= 1;
end;
end; { is_line_plane }
{*************}
procedure is_3_planes(nv1: vt3d; d1: real; nv2: vt3d; d2: real;
nv3: vt3d; d3: real;
var pis : vt3d; var error: boolean);
{Schnitt der Ebenen nv1*x=d1, nv2*x=d2, nv3*x=d3.
error= true: Schnitt besteht nicht aus einem Punkt.}
var det,dd1,dd2,dd3 : real; n12,n23,n31 : vt3d;
begin
vectorp(nv1,nv2, n12); vectorp(nv2,nv3, n23); vectorp(nv3,nv1, n31);
det:= scalarp3d(nv1,n23);
if abs(det)<eps8 then error:= true
else
begin
dd1:= d1/det; dd2:= d2/det; dd3:= d3/det;
lcomb3vt3d(dd1,n23, dd2,n31, dd3,n12 ,pis);
end;
end; { is_3_planes }
{*************}
procedure is_plane_plane(nv1: vt3d; d1: real; nv2: vt3d; d2: real;
var p,rv : vt3d; var error: boolean);
{Schnitt der Ebenen nv1*x=d1, nv2*x=d2. Schnittgerade: x = p + t*rv .
error= true: Schnitt besteht nicht aus einem Punkt.}
var det,c11,c22,c12,s1,s2: real;
begin
c11:= scalarp3d(nv1,nv1); c22:= scalarp3d(nv2,nv2);
c12:= scalarp3d(nv1,nv2); det:= c11*c22-sqr(c12);
if abs(det)=0 {<eps8} then error:= true
else
begin
s1:= (d1*c22-d2*c12)/det; s2:= (d2*c11-d1*c12)/det;
lcomb2vt3d(s1,nv1, s2,nv2, p); vectorp(nv1,nv2, rv);
error:= false;
end;
end; { is_plane_plane }
{***********}
procedure ptco_plane3d(p0,v1,v2,p: vt3d; var xi,eta: real; var error: boolean);
{v1,v2 sind linear unabhaengig, p-p0 linear abhaengig von v1,v2.
Es werden Zahlen xi,eta berechnet mit p = p0 + xi*v1 + eta*v2. }
var det,s11,s12,s22,s13,s23 : real; v3 : vt3d;
begin
diff3d(p,p0, v3);
s11:= scalarp3d(v1,v1); s12:= scalarp3d(v1,v2); s13:= scalarp3d(v1,v3);
s22:= scalarp3d(v2,v2); s23:= scalarp3d(v2,v3);
det := s11*s22 - s12*s12;
if abs(det)=0 {<eps8} then error:= true
else
begin
error:= false;
xi := (s13*s22 - s23*s12)/det;
eta:= (s11*s23 - s13*s12)/det;
end;
end; { ptco_plane3d }
{*****************}
procedure newcoordinates3d(p,b0,b1,b2,b3: vt3d; var pnew: vt3d);
{Berechnet die Koordinaten von p bzgl. der Basis b1,b2,b3 mit Nullpkt. b0.}
var det : real; p0: vt3d;
begin
diff3d(p,b0, p0); det:= determ3d(b1,b2,b3);
pnew.x:= determ3d(p0,b2,b3)/det;
pnew.y:= determ3d(b1,p0,b3)/det;
pnew.z:= determ3d(b1,b2,p0)/det;
end; { newcoordinates3d }
{***}
|
unit uConfig;
interface
const
__APP__ = ''; // 应用名称 ,可当做虚拟目录使用
template = 'view'; // 模板根目录
template_type = '.html'; // 模板文件类型
session_start = true; // 启用session
session_timer = 30; // session过期时间分钟
config = 'resources\config.json'; // 配置文件地址
mime = 'resources\mime.json'; // mime配置文件地址
open_log = true; // 开启日志;open_debug=true并开启日志将在UI显示
open_cache = true; // 开启缓存模式open_debug=false时有效
cache_max_age='315360000'; // 缓存超期时长秒
open_interceptor = true; // 开启拦截器
document_charset = 'utf-8'; // 字符集
password_key = ''; // 配置文件秘钥设置,为空时不启用秘钥,结合加密工具使用.
auto_free_memory = false; //自动释放内存
auto_free_memory_timer = 10; //默认10分钟释放内存
show_sql = false; //日志打印sql
open_debug = false; // 开发者模式缓存功能将会失效,开启前先清理浏览器缓存
implementation
end.
|
(* ArrayStackUnit: MM, 2020-05-27 *)
(* ------ *)
(* A stack which stores its elemts in an array *)
(* ========================================================================= *)
UNIT ArrayStackUnit;
INTERFACE
USES StackUnit;
TYPE
IntArray = ARRAY [0..0] OF INTEGER;
ArrayStack = ^ArrayStackObj;
ArrayStackObj = OBJECT(StackObj)
PUBLIC
CONSTRUCTOR Init(size: INTEGER);
DESTRUCTOR Done;
PROCEDURE Push(e: INTEGER); VIRTUAL;
PROCEDURE Pop(VAR e: INTEGER); VIRTUAL;
FUNCTION IsEmpty: BOOLEAN; VIRTUAL;
FUNCTION IsFull: BOOLEAN; VIRTUAL;
//FUNCTION NewArrayStack(size: INTEGER): ArrayStack;
PRIVATE
size: INTEGER;
top: INTEGER;
data: ^IntArray;
END; (* ArrayStackObj *)
FUNCTION NewArrayStack(size: INTEGER): ArrayStack;
IMPLEMENTATION
CONSTRUCTOR ArrayStackObj.Init(size: INTEGER);
BEGIN
SELF.size := size;
SELF.top := 0;
GetMem(SELF.data, size * SizeOf(INTEGER));
END;
DESTRUCTOR ArrayStackObj.Done;
BEGIN
FreeMem(SELF.data, SELF.size * SizeOf(INTEGER));
INHERITED Done;
END;
PROCEDURE ArrayStackObj.Push(e: INTEGER);
BEGIN
{$R-}data^[top] := e;{$R+}
Inc(top);
END;
PROCEDURE ArrayStackObj.Pop(VAR e: INTEGER);
BEGIN
Dec(top);
{$R-} e := data^[top]; {$R+}
END;
FUNCTION ArrayStackObj.IsEmpty: BOOLEAN;
BEGIN (* ArrayStackObj.IsEmpty *)
IsEmpty := top = 0;
END; (* ArrayStackObj.IsEmpty *)
FUNCTION ArrayStackObj.IsFull: BOOLEAN;
BEGIN (* ArrayStackObj.IsEmpty *)
IsFull := top = size;
END; (* ArrayStackObj.IsEmpty *)
FUNCTION NewArrayStack(size: INTEGER): ArrayStack;
VAR a: ArrayStack;
BEGIN (* NewArrayStack *)
New(a, Init(size));
NewArrayStack := a;
END; (* NewArrayStack *)
END. (* ArrayStackUnit *) |
unit Vigilante.Infra.Compilacao.Repositorio.Impl;
interface
uses
System.JSON, Vigilante.Compilacao.Repositorio, Vigilante.Compilacao.Model;
type
TCompilacaoRepositorio = class(TInterfacedObject, ICompilacaoRepositorio)
private
function BuscarJSON(const AURL: string): TJSONObject;
public
function BuscarCompilacao(const AURL: string): ICompilacaoModel;
end;
implementation
uses
System.SysUtils, ContainerDI, Vigilante.Infra.Compilacao.Builder,
Vigilante.Conexao.JSON;
function TCompilacaoRepositorio.BuscarCompilacao(const AURL: string): ICompilacaoModel;
var
_json: TJSONObject;
_compilacaoBuilder: ICompilacaoBuilder;
begin
Result := nil;
_json := BuscarJSON(AURL);
if not Assigned(_json) then
Exit;
try
_compilacaoBuilder := CDI.Resolve<ICompilacaoBuilder>([_json]);
Result := _compilacaoBuilder.PegarCompilacao;
finally
FreeAndNil(_json);
end;
end;
function TCompilacaoRepositorio.BuscarJSON(const AURL: string): TJSONObject;
var
_conexaoJSON: IConexaoJSON;
begin
_conexaoJSON := CDI.Resolve<IConexaoJSON>([AURL]);
Result := _conexaoJSON.PegarCompilacao;
end;
end.
|
unit untDmPrincipal;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL,
FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Datasnap.Provider, Datasnap.DBClient, System.IniFiles, Vcl.Dialogs, System.StrUtils, Vcl.Forms;
type
TDmPrincipal = class(TDataModule)
FDConnection1: TFDConnection;
cdsLocUsuario: TClientDataSet;
dspLocUsuario: TDataSetProvider;
sqlLocUsuario: TFDQuery;
sqlLocUsuarioID_USUARIO: TFDAutoIncField;
sqlLocUsuarioNOME_COMPLETO: TStringField;
sqlLocUsuarioDATA_NASC: TDateField;
sqlLocUsuarioCPF: TStringField;
sqlLocUsuarioID_CONTATO: TIntegerField;
sqlLocUsuarioLOGIN: TStringField;
cdsLocUsuarioID_USUARIO: TAutoIncField;
cdsLocUsuarioNOME_COMPLETO: TStringField;
cdsLocUsuarioDATA_NASC: TDateField;
cdsLocUsuarioCPF: TStringField;
cdsLocUsuarioID_CONTATO: TIntegerField;
cdsLocUsuarioLOGIN: TStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DmPrincipal: TDmPrincipal;
implementation
uses
untPrincipal;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDmPrincipal.DataModuleCreate(Sender: TObject);
begin
FDConnection1.Connected := False;
//FDConnection1.DriverName := 'MSSQL';
//FDConnection1.Params.Values['DriverID'] := 'MSSQL';
FDConnection1.Params.Values['HostName'] := 'localhost\SQLEXPRESS';
FDConnection1.Params.Values['Database'] := 'DBDELPHI-PROTOTIPO';
try
FDConnection1.Connected := True;
except
ShowMessage('Erro ao conectar no banco de dados!');
end;
end;
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ 版权所有 (C) 2019 苏兴迎(PRSoft) }
{ }
{*******************************************************}
unit View;
interface
uses
System.SysUtils, System.Classes, Web.HTTPApp, Web.HTTPProd, System.StrUtils,
FireDAC.Comp.Client, Page, superobject, uConfig, Web.ReqMulti, Vcl.Imaging.jpeg,
Vcl.Graphics, Data.DB, System.RegularExpressions, HTMLParser, SimpleXML,
uDBConfig;
type
TView = class
private
sessionid: string;
htmlpars: THTMLParser;
url: string; // 当前模板路径
params: TStringList;
function GetGUID: string;
procedure CreateSession(); // 创建获取session
procedure makeSession;
public
Db: TDBConfig;
// Db2: TDB2; //第2个数据源
ActionP: string;
Response: TWebResponse;
Request: TWebRequest;
function Q(str: string): string;
procedure SessionSet(key, value: string); // session控制 value传入json字符串作为对象存储
procedure SessionSetJSON(key: string; json: ISuperObject);
function SessionGet(key: string): string; // session 值获取
function SessionGetJSON(key: string): ISuperObject; // session 值获取
function SessionRemove(key: string): Boolean;
function Cookies(): TCookie; // cookies 操作
function CookiesValue(key: string): string; // cookies 操作
procedure CookiesSet(key, value: string); // cookies 操作
function Input(param: string): string; // 返回参数值,get post
function InputInt(param: string): Integer; // 返回参数值,get post
function CDSToJSON(cds: TFDQuery): string;
procedure setAttr(key, value: string); // 设置视图标记显示内容 ,如果 value是 json 数组可以在 table 标记中显示
procedure setAttrJSON(key: string; json: ISuperObject);
procedure ShowHTML(html: string); // 显示模板
procedure ShowText(text: string); // 显示文本,json格式需转换后显示
procedure ShowJSON(jo: ISuperObject); // 显示 json
procedure ShowXML(xml: IXmlDocument); // 显示 xml 数据
procedure ShowPage(count: Integer; data: ISuperObject); //渲染分页数据
procedure Redirect(action: string; path: string = ''); // 跳转 action 路由,path 路径
procedure ShowVerifyCode(num: string); // 显示验证码
procedure Success(code: Integer = 0; msg: string = '');
procedure Fail(code: Integer = -1; msg: string = '');
constructor Create(Response_: TWebResponse; Request_: TWebRequest; ActionPath: string);
destructor Destroy; override;
end;
implementation
uses
SessionList, command, LogUnit;
{ TView }
function TView.CDSToJSON(cds: TFDQuery): string;
var
ja, jo: ISuperObject;
i: Integer;
ret: string;
begin
if not cds.Active then
cds.OpenOrExecute;
ja := SA([]);
ret := '';
with cds do
begin
First;
while not Eof do
begin
jo := SO();
for i := 0 to Fields.Count - 1 do
begin
jo.S[Fields[i].DisplayLabel] := Fields[i].AsString;
end;
ja.AsArray.Add(jo);
Next;
end;
ret := ja.AsString;
end;
result := ret;
end;
procedure TView.setAttr(key, value: string);
begin
params.Values[key] := value;
end;
procedure TView.setAttrJSON(key: string; json: ISuperObject);
begin
if json <> nil then
setAttr(key, json.AsString);
end;
procedure TView.ShowText(text: string);
begin
Response.ContentType := 'text/html; charset=' + document_charset;
Response.Content := text;
Response.SendResponse;
end;
procedure TView.ShowXML(xml: IXmlDocument);
begin
Response.ContentType := 'application/xml; charset=' + document_charset;
Response.Content := xml.XML;
Response.SendResponse;
end;
procedure TView.Success(code: Integer; msg: string);
var
jo: ISuperObject;
begin
jo := SO();
jo.I['code'] := code;
if Trim(msg) = '' then
msg := '操作成功';
jo.S['message'] := msg;
ShowJSON(jo);
end;
procedure TView.ShowHTML(html: string);
var
p: string;
S: string;
page: TPage;
htmlcontent: string;
begin
p := '';
Response.Content := '';
Response.ContentType := 'text/html; charset=' + document_charset;
if (Trim(html) <> '') then
begin
S := url + html + template_type;
if (not FileExists(S)) then
begin
S := '<html><body><div style="text-align: left;">';
S := S + '<div><h1>Error 404</h1></div>';
S := S + '<hr><div>[ ' + html + template_type + ' ] Not Find Template';
S := S + '</div></div></body></html>';
Response.Content := S;
end
else
begin
try
page := TPage.Create(S, params, self.url);
htmlcontent := page.HTML;
finally
FreeAndNil(page);
end;
htmlpars.Parser(htmlcontent, params, self.url);
Response.Content := htmlcontent;
end;
end
else
begin
Response.Content := '未指定模板文件';
end;
Response.SendResponse;
end;
procedure TView.ShowJSON(jo: ISuperObject);
begin
Response.ContentType := 'application/json; charset=' + document_charset;
Response.Content := jo.AsJSon();
Response.SendResponse;
end;
procedure TView.ShowPage(count: Integer; data: ISuperObject);
var
json: ISuperObject;
begin
json := SO();
json.I['code'] := 0;
json.S['msg'] := '';
json.I['count'] := count;
json.O['data'] := data;
ShowJSON(json);
end;
procedure TView.ShowVerifyCode(num: string);
var
bmp_t: TBitmap;
jp: TJPEGImage;
m: TMemoryStream;
i: integer;
s: string;
begin
jp := TJPEGImage.Create;
bmp_t := TBitmap.Create;
m := TMemoryStream.Create;
try
bmp_t.SetSize(90, 35);
bmp_t.Transparent := True;
for i := 1 to length(num) do
begin
s := num[i];
bmp_t.Canvas.Rectangle(0, 0, 90, 35);
bmp_t.Canvas.Pen.Style := psClear;
bmp_t.Canvas.Brush.Style := bsClear;
bmp_t.Canvas.Font.Color := Random(256) and $C0; // 新建个水印字体颜色
bmp_t.Canvas.Font.Size := Random(6) + 11;
bmp_t.Canvas.Font.Style := [fsBold];
bmp_t.Canvas.Font.Name := 'Verdana';
bmp_t.Canvas.TextOut(i * 15, 5, s); // 加入文字
end;
jp.Assign(bmp_t);
jp.CompressionQuality := 100;
jp.Compress;
// jp.SaveToFile('img.jpg');
jp.SaveToStream(m);
m.Position := 0;
Response.ContentType := 'application/binary;';
self.Response.ContentStream := m;
Response.SendResponse;
finally
FreeAndNil(bmp_t);
FreeAndNil(jp);
end;
end;
function TView.Cookies: TCookie;
begin
result := Response.Cookies.Add;
end;
procedure TView.CookiesSet(key, value: string);
begin
Request.CookieFields.Values[key] := value;
end;
function TView.CookiesValue(key: string): string;
begin
result := Request.CookieFields.Values[key];
end;
constructor TView.Create(Response_: TWebResponse; Request_: TWebRequest; ActionPath: string);
begin
Db := TDBConfig.Create();
params := TStringList.Create;
htmlpars := THTMLParser.Create(Db);
self.ActionP := ActionPath;
if (Trim(self.ActionP) <> '') then
begin
self.ActionP := self.ActionP + '\';
end;
url := WebApplicationDirectory + template + '\' + self.ActionP;
self.Response := Response_;
self.Request := Request_;
if (session_start) then
CreateSession();
end;
procedure TView.CreateSession;
begin
sessionid := CookiesValue(SessionName);
if sessionid = '' then
begin
sessionid := GetGUID();
with Cookies() do
begin
Path := '/';
Name := SessionName;
value := sessionid;
end;
end;
end;
function TView.GetGUID: string;
var
LTep: TGUID;
sGUID: string;
begin
CreateGUID(LTep);
sGUID := GUIDToString(LTep);
sGUID := StringReplace(sGUID, '-', '', [rfReplaceAll]);
sGUID := Copy(sGUID, 2, Length(sGUID) - 2);
result := sGUID;
end;
destructor TView.Destroy;
begin
FreeAndNil(htmlpars);
FreeAndNil(params);
FreeAndNil(Db);
inherited;
end;
procedure TView.Fail(code: Integer; msg: string);
var
jo: ISuperObject;
begin
jo := SO();
jo.I['code'] := code;
if Trim(msg) = '' then
msg := '操作成功';
jo.S['message'] := msg;
ShowJSON(jo);
end;
function TView.Input(param: string): string;
begin
if (Request.MethodType = mtPost) then
begin
result := Request.ContentFields.Values[param];
end
else if (Request.MethodType = mtGet) then
begin
result := Request.QueryFields.Values[param];
end;
end;
function TView.InputInt(param: string): Integer;
begin
Result := StrToInt(Input(param));
end;
procedure TView.makeSession;
var
timerout: TDateTime;
begin
if (session_timer <> 0) then
timerout := Now + (1 / 24 / 60) * session_timer
else
timerout := Now + (1 / 24 / 60) * 60 * 24; //24小时过期
SessionListMap.setValueByKey(sessionid, '{}');
SessionListMap.setTimeroutByKey(sessionid, DateTimeToStr(timerout));
// log('创建Session:' + sessionid);
end;
function TView.Q(str: string): string;
begin
result := '''' + str + '''';
end;
procedure TView.Redirect(action: string; path: string = '');
var
S: string;
begin
S := '';
if action.Trim <> '' then
S := '/' + action;
if path.Trim <> '' then
S := S + '/' + path;
if S.Trim = '' then
S := '/';
Response.SendRedirect(S);
end;
procedure TView.SessionSet(key, value: string);
var
s: string;
jo: ISuperObject;
begin
if (not session_start) then
exit;
s := SessionListMap.getValueByKey(sessionid);
if (s = '') then
begin
makeSession;
s := '{}';
end;
jo := SO(s);
jo.S[key] := value;
SessionListMap.setValueByKey(sessionid, jo.AsString);
end;
procedure TView.SessionSetJSON(key: string; json: ISuperObject);
begin
if json <> nil then
SessionSet(key, json.AsString);
end;
function TView.SessionGet(key: string): string;
var
s: string;
jo: ISuperObject;
begin
if (not session_start) then
exit;
s := SessionListMap.getValueByKey(sessionid);
if s = '' then
begin
Result := '';
end
else
begin
jo := SO(s);
Result := jo.S[key];
end;
// result := SessionListMap.get(sessionid).jo.Values[key];
end;
function TView.SessionGetJSON(key: string): ISuperObject;
begin
Result := SO(SessionGet(key));
end;
function TView.SessionRemove(key: string): Boolean;
var
s: string;
jo: ISuperObject;
begin
Result := true;
if (not session_start) then
exit;
try
s := SessionListMap.getValueByKey(sessionid);
if s = '' then
begin
Result := false;
exit;
end;
jo := SO(s);
jo.Delete(key);
SessionListMap.setValueByKey(sessionid, jo.AsString);
except
Result := false;
end;
end;
end.
|
unit ncaFrmConfigCaixaAbertura;
{
ResourceString: Dario 11/03/13
Nada para para fazer
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ncaFrmBaseOpcao, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Menus, cxControls, cxContainer, cxEdit, StdCtrls, cxRadioGroup, cxLabel,
LMDPNGImage, ExtCtrls, cxButtons, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel;
type
TFrmConfigCaixaAbertura = class(TFrmBaseOpcao)
img: TImage;
lbDescr: TcxLabel;
rbUsuario: TcxRadioButton;
rbZero: TcxRadioButton;
rbSaldoAnterior: TcxRadioButton;
private
{ Private declarations }
function Op: Integer;
function OpConfig: Integer;
public
procedure Ler; override;
procedure Salvar; override;
function Alterou: Boolean; override;
procedure Renumera; override;
{ Public declarations }
end;
var
FrmConfigCaixaAbertura: TFrmConfigCaixaAbertura;
implementation
uses ncClassesBase;
{$R *.dfm}
{ TFrmConfigCaixaAbertura }
function TFrmConfigCaixaAbertura.Alterou: Boolean;
begin
Result := (Op<>OpConfig);
end;
procedure TFrmConfigCaixaAbertura.Ler;
begin
inherited;
case OPConfig of
0 : rbUsuario.Checked := True;
1 : rbZero.Checked := True;
2 : rbSaldoAnterior.Checked := True;
end;
end;
function TFrmConfigCaixaAbertura.Op: Integer;
begin
if rbUsuario.Checked then
Result := 0
else
if rbZero.Checked then
Result := 1
else
Result := 2;
end;
function TFrmConfigCaixaAbertura.OpConfig: Integer;
begin
if gConfig.ManterSaldoCaixa then
Result := 2
else
if gConfig.PedirSaldoI then
Result := 0
else
Result := 1;
end;
procedure TFrmConfigCaixaAbertura.Renumera;
begin
inherited;
lbDescr.Caption := IntToStr(InicioNumItem) + '. ' + lbDescr.Caption;
end;
procedure TFrmConfigCaixaAbertura.Salvar;
begin
inherited;
gConfig.ManterSaldoCaixa := (Op=2);
gConfig.PedirSaldoI := (Op=0);
end;
end.
|
unit Client;
interface
uses
SysUtils, ClientData, DB, Entity, ADODB, LandLord, ImmediateHead,
Referee, Employer, BankAccount, IdentityDoc, Reference, RefData,
DBUtil;
type
TClientGroup = class
strict private
FId: string;
FName: string;
FEmployerGroup: boolean;
public
property Id: string read FId write FId;
property Name: string read FName write FName;
property EmployerGroup: boolean read FEmployerGroup write FEmployerGroup;
end;
TClient = class(TEntity)
private
FDisplayId: string;
FName: string;
FBirthdate: TDate;
FReferee: TReferee;
FLandlordPres: TLandLord;
FLandLordProv: TLandLord;
FImmediateHead: TImmediateHead;
FEmployer: TEmployer;
FIdentityDocs: array of TIdentityDoc;
FReferences: array of TReference;
FPhoto: string;
FBankAccounts: array of TBankAccount;
FGroups: array of TClientGroup;
function CheckId: boolean;
function GetIdentityDoc(const i: integer): TIdentityDoc;
function GetReference(const i: integer): TReference;
function GetBankAccount(const i: integer): TBankAccount;
function GetAdding: boolean;
function GetGroup(const i: integer): TClientGroup;
function GetGroupCount: integer;
function GetIdentityDocsCount: integer;
function GroupExists(const groupId: string): boolean;
public
procedure Add; override;
procedure Save; override;
procedure Edit; override;
procedure Cancel; override;
procedure Retrieve(const closeDataSources: boolean = false);
procedure CopyAddress;
procedure AddIdentityDoc(identDoc: TIdentityDoc);
procedure AddReference(reference: TReference);
procedure RemoveIdentityDoc(const idType: string);
procedure RemoveReference(const id: string);
procedure AddBankAccount(const bkAcct: TBankAccount);
procedure RemoveBankAccountByAccountNo(const acctNo: string);
procedure ClearBankAccounts;
procedure GetGroups;
procedure RemoveGroup(const group: TClientGroup; const removeFromDb: boolean = false);
function IdentityDocExists(const idType: string): boolean;
function ReferenceExists(const reference: TReference): boolean;
function AccountNoExists(const accountNo: string): boolean;
function CardNoExists(const cardNo: string): boolean;
function AddGroup(const group: TClientGroup; const saveToDb: boolean = false): boolean;
property DisplayId: string read FDisplayId write FDisplayId;
property Name: string read FName write FName;
property Birthdate: TDate read FBirthdate write FBirthdate;
property Referee: TReferee read FReferee write FReferee;
property LandlordPres: TLandLord read FLandlordPres write FLandlordPres;
property LandLordProv: TLandLord read FLandLordProv write FLandLordProv;
property ImmediateHead: TImmediateHead read FImmediateHead write FImmediateHead;
property Employer: TEmployer read FEmployer write FEmployer;
property IdentityDocs[const i: integer]: TIdentityDoc read GetIdentityDoc;
property References[const i: integer]: TReference read GetReference;
property HasId: boolean read CheckId;
property Photo: string read FPhoto write FPhoto;
property BankAccounts[const i: integer]: TBankAccount read GetBankAccount;
property Adding: boolean read GetAdding;
property Groups[const i: integer]: TClientGroup read GetGroup;
property GroupCount: integer read GetGroupCount;
property IdentityDocsCount: integer read GetIdentityDocsCount;
constructor Create;
destructor Destroy; reintroduce;
end;
var
cln: TClient;
implementation
uses
IFinanceDialogs;
{ TClient }
constructor TClient.Create;
begin
if cln <> nil then
Abort
else
cln := self;
end;
destructor TClient.Destroy;
begin
if cln = self then
cln := nil;
end;
procedure TClient.Add;
var
i: integer;
begin
with dmClient do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
begin
if (Components[i] as TADODataSet).Tag <> 0 then
begin
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).Append;
end;
end;
end;
end;
end;
procedure TClient.Cancel;
var
i: integer;
begin
with dmClient do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Active then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Cancel;
end;
with dmRef do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Active then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
(Components[i] as TADODataSet).Cancel;
end;
end;
procedure TClient.Edit;
var
i: integer;
begin
with dmClient do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
begin
(Components[i] as TADODataSet).Open;
if (Components[i] as TADODataSet).Tag in [1,2] then
if (Components[i] as TADODataSet).RecordCount > 0 then
(Components[i] as TADODataSet).Edit;
end;
end;
end;
end;
procedure TClient.Save;
var
i: integer;
begin
try
with dmClient do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).State in [dsInsert,dsEdit] then
begin
(Components[i] as TADODataSet).Post;
if (Components[i] as TADODataSet).Tag = 1 then
(Components[i] as TADODataSet).Edit; // set to edit mode to trigger BeforePost event during save routine
end;
end;
with dmRef do
begin
for i:=0 to ComponentCount - 1 do
if Components[i] is TADODataSet then
if ((Components[i] as TADODataSet).State in [dsInsert,dsEdit]) then
if ((Components[i] as TADODataSet).Modified) then
(Components[i] as TADODataSet).Post
else
(Components[i] as TADODataSet).Cancel;
end;
except
on E: Exception do
begin
ShowErrorBox(E.Message);
Abort;
end;
end;
end;
procedure TClient.Retrieve(const closeDataSources: boolean = false);
var
i: integer;
begin
with dmClient do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in [1,2] then
begin
if closeDataSources then
(Components[i] as TADODataSet).Close;
(Components[i] as TADODataSet).DisableControls;
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).EnableControls;
if (Components[i] as TADODataSet).RecordCount > 0 then
(Components[i] as TADODataSet).Edit;
end;
end;
end;
end;
procedure TClient.AddBankAccount(const bkAcct: TBankAccount);
begin
if not AccountNoExists(bkAcct.AccountNo) then
begin
SetLength(FBankAccounts,Length(FBankAccounts) + 1);
FBankAccounts[Length(FBankAccounts) - 1] := bkAcct;
end;
end;
procedure TClient.RemoveBankAccountByAccountNo(const acctNo: string);
var
i, len: integer;
acct: TBankAccount;
begin
len := Length(FBankAccounts);
for i := 0 to len - 1 do
begin
acct := FBankAccounts[i];
if acct.AccountNo <> acctNo then
FBankAccounts[i] := acct;
end;
SetLength(FBankAccounts,Length(FBankAccounts) - 1);
end;
procedure TClient.RemoveGroup(const group: TClientGroup;
const removeFromDb: boolean);
var
i, len: integer;
gp: TClientGroup;
begin
len := Length(FGroups);
for i := 0 to len - 1 do
begin
gp := FGroups[i];
if gp.Id <> group.Id then
FGroups[i] := gp;
end;
SetLength(FGroups,Length(FGroups) - 1);
if removeFromDb then
ExecuteSql('DELETE FROM ENTITYGROUP WHERE'
+ ' ENTITY_ID = ''' + cln.Id + ''''
+ ' AND GRP_ID = ''' + group.Id + '''');
end;
function TClient.CheckId: boolean;
begin
Result := FId <> '';
end;
procedure TClient.CopyAddress;
var
i: integer;
begin
with dmClient, dmClient.dstAddressInfo do
begin
if dstAddressInfo2.RecordCount > 0 then
dstAddressInfo2.Edit
else if dstAddressInfo2.State <> dsInsert then
dstAddressInfo2.Append;
for i := 0 to FieldCount - 1 do
if dstAddressInfo2.Fields.FindField(Fields[i].FieldName) <> nil then
if not dstAddressInfo2.Fields[i].ReadOnly then
dstAddressInfo2.FieldByName(Fields[i].FieldName).Value := FieldByName(Fields[i].FieldName).Value;
end;
end;
procedure TClient.AddIdentityDoc(identDoc: TIdentityDoc);
begin
if not IdentityDocExists(identDoc.IdType) then
begin
SetLength(FIdentityDocs,Length(FIdentityDocs) + 1);
FIdentityDocs[Length(FIdentityDocs) - 1] := identDoc;
end;
end;
function TClient.GetIdentityDoc(const i: Integer): TIdentityDoc;
begin
Result := FIdentityDocs[i];
end;
function TClient.GetIdentityDocsCount: integer;
begin
Result := Length(FIdentityDocs);
end;
function TClient.IdentityDocExists(const idType: string): boolean;
var
i, len: integer;
doc: TIdentityDoc;
begin
Result := false;
len := Length(FIdentityDocs);
for i := 0 to len - 1 do
begin
doc := FIdentityDocs[i];
if doc.IdType = idType then
begin
Result := true;
Exit;
end;
end;
end;
function TClient.ReferenceExists(const reference: TReference): boolean;
var
i, len: integer;
rf: TReference;
begin
Result := false;
len := Length(FReferences);
for i := 0 to len - 1 do
begin
rf := FReferences[i];
if rf.Id = reference.Id then
begin
Result := true;
Exit;
end;
end;
end;
procedure TClient.AddReference(reference: TReference);
begin
if not ReferenceExists(reference) then
begin
SetLength(FReferences,Length(FReferences) + 1);
FReferences[Length(FReferences) - 1] := reference;
end;
end;
procedure TClient.ClearBankAccounts;
begin
FBankAccounts := [];
end;
function TClient.GetReference(const i: Integer): TReference;
begin
Result := FReferences[i];
end;
function TClient.GroupExists(const groupId: string): boolean;
var
i, len: integer;
group: TClientGroup;
begin
Result := false;
len := Length(FGroups);
for i := 0 to len - 1 do
begin
group := FGroups[i];
if group.Id = groupId then
begin
Result := true;
Exit;
end;
end;
end;
procedure TClient.RemoveIdentityDoc(const idType: string);
var
i, len: integer;
idoc: TIdentityDoc;
begin
len := Length(FIdentityDocs);
for i := 0 to len - 1 do
begin
idoc := FIdentityDocs[i];
if idoc.IdType <> idType then
FIdentityDocs[i] := idoc;
end;
SetLength(FIdentityDocs,Length(FIdentityDocs) - 1);
end;
procedure TClient.RemoveReference(const id: string);
var
i, len: integer;
rf: TReference;
begin
len := Length(FReferences);
for i := 0 to len - 1 do
begin
rf := FReferences[i];
if rf.Id <> id then
FReferences[i] := rf;
end;
SetLength(FReferences,Length(FReferences) - 1);
end;
function TClient.AccountNoExists(const accountNo: string): boolean;
var
i, len: integer;
acct: TBankAccount;
begin
Result := false;
if dmClient.dstAcctInfo.State = dsInsert then
begin
len := Length(FBankAccounts);
for i := 0 to len - 1 do
begin
acct := FBankAccounts[i];
if acct.AccountNo = accountNo then
begin
Result := true;
Exit;
end;
end;
end;
end;
function TClient.CardNoExists(const cardNo: string): boolean;
var
i, len: integer;
acct: TBankAccount;
begin
Result := false;
if dmClient.dstAcctInfo.State = dsInsert then
begin
len := Length(FBankAccounts);
for i := 0 to len - 1 do
begin
acct := FBankAccounts[i];
if acct.CardNo = cardNo then
begin
Result := true;
Exit;
end;
end;
end;
end;
function TClient.GetAdding: boolean;
begin
Result := not CheckId;
end;
function TClient.GetBankAccount(const i: integer): TBankAccount;
begin
Result := FBankAccounts[i];
end;
function TClient.GetGroup(const i: integer): TClientGroup;
begin
Result := FGroups[i];
end;
function TClient.GetGroupCount: integer;
begin
Result := Length(FGroups);
end;
procedure TClient.GetGroups;
var
group: TClientGroup;
begin
FGroups := [];
with dmClient.dstGroups do
begin
Open;
while not Eof do
begin
group := TClientGroup.Create;
group.Id := FieldByName('grp_id').AsString;
group.Name := FieldByName('grp_name').AsString;
group.EmployerGroup := FieldByName('emp_id').AsString <> '';
AddGroup(group);
Next;
end;
Close;
end;
end;
function TClient.AddGroup(const group: TClientGroup; const saveToDb: boolean): boolean;
begin
Result := false;
if not GroupExists(group.Id) then
begin
SetLength(FGroups,Length(FGroups) + 1);
FGroups[Length(FGroups) - 1] := group;
if saveToDb then
ExecuteSql('INSERT INTO ENTITYGROUP VALUES ('''
+ cln.Id + ''','''
+ group.Id + ''')');
Result := true;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Notification Center implementation for iOS }
{ }
{ Copyright(c) 2013-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.iOS.Notification;
interface
{$SCOPEDENUMS ON}
uses
System.Notification;
type
/// <summary>Common ancestor used to instantiate platform implementation</summary>
TPlatformNotificationCenter = class(TBaseNotificationCenter)
protected
class function GetInstance: TBaseNotificationCenter; override;
end;
implementation
uses
System.Classes,
System.SysUtils,
System.Generics.Collections,
System.Messaging,
System.DateUtils,
System.SysConst,
Macapi.ObjectiveC,
Macapi.Helpers,
iOSapi.Foundation,
iOSapi.CocoaTypes,
iOSapi.UIKit;
{ iOSApi.UserNotification }
const
UNAuthorizationOptionBadge = 1;
UNAuthorizationOptionSound = 2;
UNAuthorizationOptionAlert = 4;
type
UNNotification = interface;
UNNotificationAction = interface;
UNNotificationCategory = interface;
UNNotificationContent = interface;
UNMutableNotificationContent = interface;
UNNotificationRequest = interface;
UNNotificationResponse = interface;
UNNotificationSettings = interface;
UNNotificationSound = interface;
UNNotificationTrigger = interface;
UNPushNotificationTrigger = interface;
UNTimeIntervalNotificationTrigger = interface;
UNCalendarNotificationTrigger = interface;
UNUserNotificationCenter = interface;
PNSError = ^NSError; // Added manually
UNErrorCode = NSInteger;
UNNotificationActionOptions = NSInteger;
UNNotificationCategoryOptions = NSInteger;
UNAuthorizationStatus = NSInteger;
UNShowPreviewsSetting = NSInteger;
UNNotificationSetting = NSInteger;
UNAlertStyle = NSInteger;
UNNotificationSoundName = NSString;
UNAuthorizationOptions = NSInteger;
UNNotificationPresentationOptions = NSInteger;
TUNUserNotificationCenterBlockMethod1 = procedure(granted: Boolean; error: NSError) of object;
TUNUserNotificationCenterBlockMethod2 = procedure(categories: NSSet) of object;
TUNUserNotificationCenterBlockMethod3 = procedure(settings: UNNotificationSettings) of object;
TUNUserNotificationCenterBlockMethod4 = procedure(error: NSError) of object;
TUNUserNotificationCenterBlockMethod5 = procedure(requests: NSArray) of object;
TUNUserNotificationCenterBlockMethod6 = procedure(notifications: NSArray) of object;
UNNotificationClass = interface(NSObjectClass)
['{6D4428D5-18A3-4913-AD3D-99398B6A89CB}']
end;
UNNotification = interface(NSObject)
['{AFEE6151-57D2-4811-B5E8-3CDF1DDFBE57}']
function date: NSDate; cdecl;
function request: UNNotificationRequest; cdecl;
end;
TUNNotification = class(TOCGenericImport<UNNotificationClass, UNNotification>) end;
UNNotificationActionClass = interface(NSObjectClass)
['{3A506339-56AB-4579-A1B2-F08E7A2D6C9A}']
[MethodName('actionWithIdentifier:title:options:')]
{class} function actionWithIdentifier(identifier: NSString; title: NSString; options: UNNotificationActionOptions): UNNotificationAction; cdecl;
end;
UNNotificationAction = interface(NSObject)
['{5B3E600A-3DB8-4257-9397-A2590D0B134D}']
function identifier: NSString; cdecl;
function options: UNNotificationActionOptions; cdecl;
function title: NSString; cdecl;
end;
TUNNotificationAction = class(TOCGenericImport<UNNotificationActionClass, UNNotificationAction>) end;
UNNotificationCategoryClass = interface(NSObjectClass)
['{34B7ADD9-3404-436E-82C5-47E368E6DC17}']
[MethodName('categoryWithIdentifier:actions:intentIdentifiers:hiddenPreviewsBodyPlaceholder:categorySummaryFormat:options:')]
{class} function categoryWithIdentifier(identifier: NSString; actions: NSArray; intentIdentifiers: NSArray; hiddenPreviewsBodyPlaceholder: NSString; categorySummaryFormat: NSString; options: UNNotificationCategoryOptions): UNNotificationCategory; cdecl; overload;
[MethodName('categoryWithIdentifier:actions:intentIdentifiers:hiddenPreviewsBodyPlaceholder:options:')]
{class} function categoryWithIdentifier(identifier: NSString; actions: NSArray; intentIdentifiers: NSArray; hiddenPreviewsBodyPlaceholder: NSString; options: UNNotificationCategoryOptions): UNNotificationCategory; cdecl; overload;
[MethodName('categoryWithIdentifier:actions:intentIdentifiers:options:')]
{class} function categoryWithIdentifier(identifier: NSString; actions: NSArray; intentIdentifiers: NSArray; options: UNNotificationCategoryOptions): UNNotificationCategory; cdecl; overload;
end;
UNNotificationCategory = interface(NSObject)
['{26B3E2D1-4E43-42CF-8AB3-344E2455D75F}']
function actions: NSArray; cdecl;
function categorySummaryFormat: NSString; cdecl;
function hiddenPreviewsBodyPlaceholder: NSString; cdecl;
function identifier: NSString; cdecl;
function intentIdentifiers: NSArray; cdecl;
function options: UNNotificationCategoryOptions; cdecl;
end;
TUNNotificationCategory = class(TOCGenericImport<UNNotificationCategoryClass, UNNotificationCategory>) end;
UNNotificationContentClass = interface(NSObjectClass)
['{51114586-06DF-4F81-89EE-A596F73F170A}']
end;
UNNotificationContent = interface(NSObject)
['{BDF46729-F7A4-4780-8699-424E5A342426}']
function attachments: NSArray; cdecl;
function badge: NSNumber; cdecl;
function body: NSString; cdecl;
function categoryIdentifier: NSString; cdecl;
function launchImageName: NSString; cdecl;
function sound: UNNotificationSound; cdecl;
function subtitle: NSString; cdecl;
function summaryArgument: NSString; cdecl;
function summaryArgumentCount: NSUInteger; cdecl;
function threadIdentifier: NSString; cdecl;
function title: NSString; cdecl;
function userInfo: NSDictionary; cdecl;
end;
TUNNotificationContent = class(TOCGenericImport<UNNotificationContentClass, UNNotificationContent>) end;
UNMutableNotificationContentClass = interface(UNNotificationContentClass)
['{D9F80BFC-AE7B-4186-9FC7-63FF96694C99}']
end;
UNMutableNotificationContent = interface(UNNotificationContent)
['{C97A9AB7-D2BE-479C-A737-B12B05B35496}']
function attachments: NSArray; cdecl;
function badge: NSNumber; cdecl;
function body: NSString; cdecl;
function categoryIdentifier: NSString; cdecl;
function launchImageName: NSString; cdecl;
procedure setAttachments(attachments: NSArray); cdecl;
procedure setBadge(badge: NSNumber); cdecl;
procedure setBody(body: NSString); cdecl;
procedure setCategoryIdentifier(categoryIdentifier: NSString); cdecl;
procedure setLaunchImageName(launchImageName: NSString); cdecl;
procedure setSound(sound: UNNotificationSound); cdecl;
procedure setSubtitle(subtitle: NSString); cdecl;
procedure setSummaryArgument(summaryArgument: NSString); cdecl;
procedure setSummaryArgumentCount(summaryArgumentCount: NSUInteger); cdecl;
procedure setThreadIdentifier(threadIdentifier: NSString); cdecl;
procedure setTitle(title: NSString); cdecl;
procedure setUserInfo(userInfo: NSDictionary); cdecl;
function sound: UNNotificationSound; cdecl;
function subtitle: NSString; cdecl;
function summaryArgument: NSString; cdecl;
function summaryArgumentCount: NSUInteger; cdecl;
function threadIdentifier: NSString; cdecl;
function title: NSString; cdecl;
function userInfo: NSDictionary; cdecl;
end;
TUNMutableNotificationContent = class(TOCGenericImport<UNMutableNotificationContentClass, UNMutableNotificationContent>) end;
UNNotificationRequestClass = interface(NSObjectClass)
['{85DD088D-EECD-4F62-B4D4-A77297CB8C68}']
[MethodName('requestWithIdentifier:content:trigger:')]
{class} function requestWithIdentifier(identifier: NSString; content: UNNotificationContent; trigger: UNNotificationTrigger): UNNotificationRequest; cdecl;
end;
UNNotificationRequest = interface(NSObject)
['{77D79B65-2B67-4255-B40E-7E98F2C91D8C}']
function content: UNNotificationContent; cdecl;
function identifier: NSString; cdecl;
function trigger: UNNotificationTrigger; cdecl;
end;
TUNNotificationRequest = class(TOCGenericImport<UNNotificationRequestClass, UNNotificationRequest>) end;
UNNotificationResponseClass = interface(NSObjectClass)
['{822F3160-ED9B-401A-B770-ED0E745C67A9}']
end;
UNNotificationResponse = interface(NSObject)
['{12B346C3-E55B-4A93-81D3-01699EBAEA43}']
function actionIdentifier: NSString; cdecl;
function notification: UNNotification; cdecl;
end;
TUNNotificationResponse = class(TOCGenericImport<UNNotificationResponseClass, UNNotificationResponse>) end;
UNNotificationSettingsClass = interface(NSObjectClass)
['{F6CC36AB-6F7D-4F0D-AA01-F604086FD698}']
end;
UNNotificationSettings = interface(NSObject)
['{98352662-F2B4-443A-83C3-F839AD9FFADC}']
function alertSetting: UNNotificationSetting; cdecl;
function alertStyle: UNAlertStyle; cdecl;
function authorizationStatus: UNAuthorizationStatus; cdecl;
function badgeSetting: UNNotificationSetting; cdecl;
function carPlaySetting: UNNotificationSetting; cdecl;
function criticalAlertSetting: UNNotificationSetting; cdecl;
function lockScreenSetting: UNNotificationSetting; cdecl;
function notificationCenterSetting: UNNotificationSetting; cdecl;
function providesAppNotificationSettings: Boolean; cdecl;
function showPreviewsSetting: UNShowPreviewsSetting; cdecl;
function soundSetting: UNNotificationSetting; cdecl;
end;
TUNNotificationSettings = class(TOCGenericImport<UNNotificationSettingsClass, UNNotificationSettings>) end;
UNNotificationSoundClass = interface(NSObjectClass)
['{DE409993-FA94-4455-B5E1-E19B9999BD00}']
[MethodName('criticalSoundNamed:withAudioVolume:')]
{class} function criticalSoundNamed(name: UNNotificationSoundName; volume: Single): UNNotificationSound; cdecl; overload;
{class} function criticalSoundNamed(name: UNNotificationSoundName): UNNotificationSound; cdecl; overload;
{class} function defaultCriticalSound: UNNotificationSound; cdecl;
{class} function defaultCriticalSoundWithAudioVolume(volume: Single): UNNotificationSound; cdecl;
{class} function defaultSound: UNNotificationSound; cdecl;
{class} function soundNamed(name: UNNotificationSoundName): UNNotificationSound; cdecl;
end;
UNNotificationSound = interface(NSObject)
['{8C29C92A-EE23-423F-8F97-38735D4E2544}']
end;
TUNNotificationSound = class(TOCGenericImport<UNNotificationSoundClass, UNNotificationSound>) end;
UNNotificationTriggerClass = interface(NSObjectClass)
['{209BB768-F422-478F-AC5F-F2EB4856F30C}']
end;
UNNotificationTrigger = interface(NSObject)
['{274B049C-A4B1-4BB2-BD89-57DB452C626A}']
function repeats: Boolean; cdecl;
end;
TUNNotificationTrigger = class(TOCGenericImport<UNNotificationTriggerClass, UNNotificationTrigger>) end;
UNPushNotificationTriggerClass = interface(UNNotificationTriggerClass)
['{73252166-B928-4E81-A6DE-C0F7E22B93FF}']
end;
UNPushNotificationTrigger = interface(UNNotificationTrigger)
['{D5E464F5-4FEC-4A26-BE0B-1643B92408BA}']
end;
TUNPushNotificationTrigger = class(TOCGenericImport<UNPushNotificationTriggerClass, UNPushNotificationTrigger>) end;
UNTimeIntervalNotificationTriggerClass = interface(UNNotificationTriggerClass)
['{65B02DB4-95F6-436E-9DE1-DDE82B8B4E9B}']
[MethodName('triggerWithTimeInterval:repeats:')]
{class} function triggerWithTimeInterval(timeInterval: NSTimeInterval; repeats: Boolean): UNTimeIntervalNotificationTrigger; cdecl;
end;
UNTimeIntervalNotificationTrigger = interface(UNNotificationTrigger)
['{52D4250D-9E69-468B-B73C-840099D60361}']
function nextTriggerDate: NSDate; cdecl;
function timeInterval: NSTimeInterval; cdecl;
end;
TUNTimeIntervalNotificationTrigger = class(TOCGenericImport<UNTimeIntervalNotificationTriggerClass, UNTimeIntervalNotificationTrigger>) end;
UNCalendarNotificationTriggerClass = interface(UNNotificationTriggerClass)
['{0D70BDA0-5C5C-412D-98A2-80CBBC21AABB}']
[MethodName('triggerWithDateMatchingComponents:repeats:')]
{class} function triggerWithDateMatchingComponents(dateComponents: NSDateComponents; repeats: Boolean): UNCalendarNotificationTrigger; cdecl;
end;
UNCalendarNotificationTrigger = interface(UNNotificationTrigger)
['{59EDD126-D15F-40D9-B632-A249AE77E127}']
function dateComponents: NSDateComponents; cdecl;
function nextTriggerDate: NSDate; cdecl;
end;
TUNCalendarNotificationTrigger = class(TOCGenericImport<UNCalendarNotificationTriggerClass, UNCalendarNotificationTrigger>) end;
UNUserNotificationCenterClass = interface(NSObjectClass)
['{499732CA-F14F-4A91-82F9-903E1B0C125C}']
{class} function currentNotificationCenter: UNUserNotificationCenter; cdecl;
end;
UNUserNotificationCenter = interface(NSObject)
['{23C1DA35-7D1A-483F-ACE5-872CA4068EFF}']
[MethodName('addNotificationRequest:withCompletionHandler:')]
procedure addNotificationRequest(request: UNNotificationRequest; completionHandler: TUNUserNotificationCenterBlockMethod4); cdecl;
procedure getDeliveredNotificationsWithCompletionHandler(completionHandler: TUNUserNotificationCenterBlockMethod6); cdecl;
procedure getNotificationCategoriesWithCompletionHandler(completionHandler: TUNUserNotificationCenterBlockMethod2); cdecl;
procedure getNotificationSettingsWithCompletionHandler(completionHandler: TUNUserNotificationCenterBlockMethod3); cdecl;
procedure getPendingNotificationRequestsWithCompletionHandler(completionHandler: TUNUserNotificationCenterBlockMethod5); cdecl;
procedure removeAllDeliveredNotifications; cdecl;
procedure removeAllPendingNotificationRequests; cdecl;
procedure removeDeliveredNotificationsWithIdentifiers(identifiers: NSArray); cdecl;
procedure removePendingNotificationRequestsWithIdentifiers(identifiers: NSArray); cdecl;
[MethodName('requestAuthorizationWithOptions:completionHandler:')]
procedure requestAuthorizationWithOptions(options: UNAuthorizationOptions; completionHandler: TUNUserNotificationCenterBlockMethod1); cdecl;
procedure setNotificationCategories(categories: NSSet); cdecl;
function supportsContentExtensions: Boolean; cdecl;
end;
TUNUserNotificationCenter = class(TOCGenericImport<UNUserNotificationCenterClass, UNUserNotificationCenter>) end;
TNotificationCenterIOS = class abstract(TPlatformNotificationCenter)
private
FDelayedNotifications: TObjectList<TNotification>;
FIsApplicationLoaded: Boolean;
{ Global External event }
procedure ReceiveLocalNotification(const Sender: TObject; const M: TMessage);
{ Delayed notifications }
procedure NotifyDelayedNotifications;
procedure ClearDelayedNotifications;
procedure DidFormsLoad;
protected
procedure DoLoaded; override;
{ Channels }
procedure DoCreateOrUpdateChannel(const AChannel: TChannel); override;
procedure DoDeleteChannel(const AChannelId: string); override;
procedure DoGetAllChannels(const AChannels: TChannels); override;
{ Application Icon Badge Number }
procedure DoSetIconBadgeNumber(const ACount: Integer); override;
function DoGetIconBadgeNumber: Integer; override;
procedure DoResetIconBadgeNumber; override;
function ConvertNativeToDelphiNotification(const ANotification: Pointer): TNotification; virtual; abstract;
public
constructor Create;
destructor Destroy; override;
function SharedApplication: UIApplication; inline;
end;
{ TNotificationCenterCocoa4 }
TNotificationCenterCocoa4 = class(TNotificationCenterIOS)
private
class var FInstance: TNotificationCenterCocoa4;
class function GetDefaultInstance: TNotificationCenterCocoa4; static;
class destructor Destroy;
{ Creation and manipulation with notifications }
function CreateNativeNotification(const ANotification: TNotification): UILocalNotification;
function FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean;
protected
procedure DoScheduleNotification(const ANotification: TNotification); override;
procedure DoPresentNotification(const ANotification: TNotification); override;
procedure DoCancelNotification(const AName: string); overload; override;
procedure DoCancelNotification(const ANotification: TNotification); overload; override;
procedure DoCancelAllNotifications; override;
function ConvertNativeToDelphiNotification(const ANotification: Pointer): TNotification; override;
public
class property Instance: TNotificationCenterCocoa4 read GetDefaultInstance;
end;
TNotificationCenterCocoa10 = class(TNotificationCenterIOS)
private type
TPermissionState = (Unknown, Granted, Denied);
private
class var FInstance: TNotificationCenterCocoa10;
class function GetDefaultInstance: TNotificationCenterCocoa10; static;
class destructor Destroy;
private
FPermissionsState: TPermissionState;
{ Creation and manipulation with notifications }
function CreateNotificationRequest(const ANotification: TNotification; const AIsScheduled: Boolean): UNNotificationRequest;
function RepeatIntervalToNSDateComponents(const ADate: TDate; const ARepeatInterval: TRepeatInterval): NSDateComponents;
function GetNotificationSound(const ANotification: TNotification): UNNotificationSound;
function GetNotificationTrigger(const ANotification: TNotification): UNNotificationTrigger;
{ Handler }
procedure RequestAuthorizationHandler(granted: Boolean; error: NSError);
procedure AddNotificationRequestHandler(error: NSError);
protected
procedure RequestPermission;
procedure DoScheduleNotification(const ANotification: TNotification); override;
procedure DoPresentNotification(const ANotification: TNotification); override;
procedure DoCancelNotification(const AName: string); overload; override;
procedure DoCancelNotification(const ANotification: TNotification); overload; override;
procedure DoCancelAllNotifications; override;
function ConvertNativeToDelphiNotification(const ANotification: Pointer): TNotification; override;
public
constructor Create;
procedure CheckPermissions;
class property Instance: TNotificationCenterCocoa10 read GetDefaultInstance;
end;
function RepeatIntervalToNSCalendarUnit(const AInterval: TRepeatInterval): NSCalendarUnit;
begin
case AInterval of
TRepeatInterval.None:
Result := 0;
TRepeatInterval.Second:
Result := NSSecondCalendarUnit;
TRepeatInterval.Minute:
Result := NSMinuteCalendarUnit;
TRepeatInterval.Hour:
Result := NSHourCalendarUnit;
TRepeatInterval.Day:
Result := NSDayCalendarUnit;
TRepeatInterval.Weekday:
Result := NSWeekdayCalendarUnit;
TRepeatInterval.Week:
Result := NSWeekCalendarUnit;
TRepeatInterval.Month:
Result := NSMonthCalendarUnit;
TRepeatInterval.Quarter:
Result := NSQuarterCalendarUnit;
TRepeatInterval.Year:
Result := NSYearCalendarUnit;
TRepeatInterval.Era:
Result := NSEraCalendarUnit;
else
Result := 0;
end;
end;
function NSCalendarUnitToRepeatInterval(const AInterval: NSCalendarUnit): TRepeatInterval;
begin
case AInterval of
NSEraCalendarUnit:
Result := TRepeatInterval.Era;
NSYearCalendarUnit:
Result := TRepeatInterval.Year;
NSQuarterCalendarUnit:
Result := TRepeatInterval.Quarter;
NSMonthCalendarUnit:
Result := TRepeatInterval.Month;
NSWeekCalendarUnit:
Result := TRepeatInterval.Week;
NSWeekdayCalendarUnit:
Result := TRepeatInterval.Weekday;
NSDayCalendarUnit:
Result := TRepeatInterval.Day;
NSHourCalendarUnit:
Result := TRepeatInterval.Hour;
NSMinuteCalendarUnit:
Result := TRepeatInterval.Minute;
NSSecondCalendarUnit:
Result := TRepeatInterval.Second;
else
Result := TRepeatInterval.None;
end;
end;
{$REGION 'TNotificationCenterCocoa4'}
procedure TNotificationCenterCocoa4.DoCancelAllNotifications;
begin
SharedApplication.cancelAllLocalNotifications;
end;
function TNotificationCenterCocoa4.FindNativeNotification(const AID: string; var ANotification: UILocalNotification): Boolean;
function FindInScheduledNotifications: UILocalNotification;
var
Notifications: NSArray;
NativeNotification: UILocalNotification;
Found: Boolean;
I: NSUInteger;
UserInfo: NSDictionary;
begin
Notifications := SharedApplication.scheduledLocalNotifications;
Found := False;
if Notifications <> nil then
begin
I := 0;
while (I < Notifications.count) and not Found do
begin
NativeNotification := TUILocalNotification.Wrap(Notifications.objectAtIndex(I));
UserInfo := NativeNotification.userInfo;
if (UserInfo <> nil) and (UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String) = AID) then
Found := True
else
Inc(I);
end;
end;
if Found then
Result := NativeNotification
else
Result := nil;
end;
begin
// We are searching notification in two list:
// 1. Notifications, which have not displayed in Notification Center
// 2. Notifications, which already displayed
ANotification := FindInScheduledNotifications;
Result := ANotification <> nil;
end;
procedure TNotificationCenterCocoa4.DoCancelNotification(const AName: string);
var
NativeNotification: UILocalNotification;
begin
if not AName.IsEmpty and FindNativeNotification(AName, NativeNotification) then
SharedApplication.cancelLocalNotification(NativeNotification);
end;
procedure TNotificationCenterCocoa4.DoCancelNotification(const ANotification: TNotification);
begin
if ANotification <> nil then
DoCancelNotification(ANotification.Name);
end;
function TNotificationCenterCocoa4.CreateNativeNotification(const ANotification: TNotification): UILocalNotification;
var
NativeNotification: UILocalNotification;
UserInfo: NSDictionary;
GMTDateTime: TDateTime;
begin
NativeNotification := TUILocalNotification.Create;
if not ANotification.Name.IsEmpty then
begin
// Set unique identificator
UserInfo := TNSDictionary.Wrap(TNSDictionary.OCClass.dictionaryWithObject(
(StrToNSStr(ANotification.Name) as ILocalObject).GetObjectID, (StrToNSStr('id') as ILocalObject).GetObjectID));
NativeNotification.setUserInfo(UserInfo);
end;
// Get GMT time and set notification fired date
GMTDateTime := GetGMTDateTime(ANotification.FireDate);
NativeNotification.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone));
NativeNotification.setFireDate(DateTimeToNSDate(GMTDateTime));
NativeNotification.setApplicationIconBadgeNumber(ANotification.Number);
NativeNotification.setAlertBody(StrToNSStr(ANotification.AlertBody));
NativeNotification.setAlertAction(StrToNSStr(ANotification.AlertAction));
NativeNotification.setHasAction(ANotification.HasAction);
NativeNotification.setRepeatInterval(RepeatIntervalToNSCalendarUnit(ANotification.RepeatInterval));
if ANotification.EnableSound then
if ANotification.SoundName.IsEmpty then
NativeNotification.setSoundName(UILocalNotificationDefaultSoundName)
else
NativeNotification.setSoundName(StrToNSStr(ANotification.SoundName))
else
NativeNotification.setSoundName(nil);
Result := NativeNotification;
end;
class destructor TNotificationCenterCocoa4.Destroy;
begin
FInstance.Free;
end;
function TNotificationCenterCocoa4.ConvertNativeToDelphiNotification(const ANotification: Pointer): TNotification;
var
UserInfo: NSDictionary;
NotificationTmp: TNotification;
LocalNotification: UILocalNotification;
begin
NotificationTmp := nil;
if ANotification <> nil then
begin
LocalNotification := TUILocalNotification.Wrap(ANotification);
NotificationTmp := TNotification.Create;
UserInfo := LocalNotification.userInfo;
if UserInfo <> nil then
NotificationTmp.Name := UTF8ToString(TNSString.Wrap(UserInfo.valueForKey(StrToNSStr('id'))).UTF8String);
if LocalNotification.AlertBody <> nil then
NotificationTmp.AlertBody := UTF8ToString(LocalNotification.AlertBody.UTF8String);
if LocalNotification.AlertAction <> nil then
NotificationTmp.AlertAction := UTF8ToString(LocalNotification.AlertAction.UTF8String);;
NotificationTmp.Number := LocalNotification.ApplicationIconBadgeNumber;
NotificationTmp.FireDate := NSDateToDateTime(LocalNotification.FireDate);
NotificationTmp.EnableSound := LocalNotification.SoundName <> nil;
if (LocalNotification.soundName = nil) or (LocalNotification.soundName.compare(UILocalNotificationDefaultSoundName) = NSOrderedSame) then
NotificationTmp.SoundName := ''
else
NotificationTmp.SoundName := NSStrToStr(LocalNotification.soundName);
NotificationTmp.HasAction := LocalNotification.HasAction;
NotificationTmp.RepeatInterval := NSCalendarUnitToRepeatInterval(LocalNotification.repeatInterval);
end;
Result := NotificationTmp;
end;
procedure TNotificationCenterCocoa4.DoPresentNotification(const ANotification: TNotification);
var
NativeNotification: UILocalNotification;
begin
DoCancelNotification(ANotification);
NativeNotification := CreateNativeNotification(ANotification);
SharedApplication.presentLocalNotificationNow(NativeNotification);
end;
procedure TNotificationCenterCocoa4.DoScheduleNotification(const ANotification: TNotification);
var
NativeNotification: UILocalNotification;
begin
CancelNotification(ANotification.Name);
NativeNotification := CreateNativeNotification(ANotification);
SharedApplication.scheduleLocalNotification(NativeNotification);
end;
class function TNotificationCenterCocoa4.GetDefaultInstance: TNotificationCenterCocoa4;
begin
if FInstance = nil then
FInstance := TNotificationCenterCocoa4.Create;
Result := FInstance;
end;
{$ENDREGION}
{ TPlatformNotificationCenter }
class function TPlatformNotificationCenter.GetInstance: TBaseNotificationCenter;
begin
if TOsVersion.Check(10) then
Result := TBaseNotificationCenter(TNotificationCenterCocoa10.Instance)
else
Result := TBaseNotificationCenter(TNotificationCenterCocoa4.Instance)
end;
{ TNotificationCenterCocoa10 }
procedure TNotificationCenterCocoa10.AddNotificationRequestHandler(error: NSError);
begin
if error <> nil then
NSLog(NSObjectToID(error.localizedDescription));
end;
procedure TNotificationCenterCocoa10.CheckPermissions;
begin
case FPermissionsState of
TPermissionState.Unknown:
NSLog(NSObjectToId(StrToNSStr('User didn''t response on permission request.')));
TPermissionState.Denied:
NSLog(NSObjectToId(StrToNSStr('User rejected access to using notifications. Cannot process operation.')));
end;
end;
function TNotificationCenterCocoa10.ConvertNativeToDelphiNotification(const ANotification: Pointer): TNotification;
var
Response: UNNotificationResponse;
Request: UNNotificationRequest;
NativeNotification: UNNotification;
begin
Response := TUNNotificationResponse.Wrap(ANotification);
NativeNotification := Response.notification;
Request := NativeNotification.request;
Result := TNotification.Create;
Result.Name := NSStrToStr(Request.identifier);
Result.Title := NSStrToStr(Request.content.title);
Result.AlertBody := NSStrToStr(Request.content.body);
Result.Number := Request.content.badge.intValue;
Result.EnableSound := Request.content.sound <> nil;
Result.FireDate := NSDateToDateTime(NativeNotification.date);
Result.RepeatInterval := TRepeatInterval.None;
end;
constructor TNotificationCenterCocoa10.Create;
begin
inherited;
FPermissionsState := TPermissionState.Unknown;
RequestPermission;
end;
function TNotificationCenterCocoa10.CreateNotificationRequest(const ANotification: TNotification; const AIsScheduled: Boolean): UNNotificationRequest;
var
NotificationContent: UNMutableNotificationContent;
Trigger: UNNotificationTrigger;
Id: string;
begin
NotificationContent := TUNMutableNotificationContent.Create;
NotificationContent.setTitle(StrToNSStr(ANotification.Title));
NotificationContent.setBody(StrToNSStr(ANotification.AlertBody));
NotificationContent.setBadge(TNSNumber.Wrap(TNSNumber.OCClass.numberWithInt(ANotification.Number)));
NotificationContent.setSound(GetNotificationSound(ANotification));
if AIsScheduled then
Trigger := GetNotificationTrigger(ANotification)
else
Trigger := nil;
if ANotification.Name.IsEmpty then
Id := DateTimeToStr(Now)
else
Id := ANotification.Name;
Result := TUNNotificationRequest.OCClass.requestWithIdentifier(StrToNSStr(Id), NotificationContent, Trigger);
end;
class destructor TNotificationCenterCocoa10.Destroy;
begin
FreeAndNil(FInstance);
end;
procedure TNotificationCenterCocoa10.DoCancelAllNotifications;
begin
CheckPermissions;
TUNUserNotificationCenter.OCClass.currentNotificationCenter.removeAllDeliveredNotifications;
TUNUserNotificationCenter.OCClass.currentNotificationCenter.removeAllPendingNotificationRequests;
end;
procedure TNotificationCenterCocoa10.DoCancelNotification(const ANotification: TNotification);
begin
if ANotification <> nil then
DoCancelNotification(ANotification.Name);
end;
procedure TNotificationCenterCocoa10.DoCancelNotification(const AName: string);
var
NotificationIds: NSMutableArray;
begin
CheckPermissions;
NotificationIds := TNSMutableArray.Wrap(TNSMutableArray.OCClass.arrayWithObject(StringToId(AName)));
TUNUserNotificationCenter.OCClass.currentNotificationCenter.removeDeliveredNotificationsWithIdentifiers(NotificationIds);
TUNUserNotificationCenter.OCClass.currentNotificationCenter.removePendingNotificationRequestsWithIdentifiers(NotificationIds);
end;
procedure TNotificationCenterCocoa10.DoPresentNotification(const ANotification: TNotification);
var
NotificationRequest: UNNotificationRequest;
begin
CheckPermissions;
NotificationRequest := CreateNotificationRequest(ANotification, False);
TUNUserNotificationCenter.OCClass.currentNotificationCenter.addNotificationRequest(NotificationRequest, AddNotificationRequestHandler);
end;
procedure TNotificationCenterCocoa10.RequestPermission;
begin
TUNUserNotificationCenter.OCClass.currentNotificationCenter.requestAuthorizationWithOptions(
UNAuthorizationOptionBadge or UNAuthorizationOptionSound or UNAuthorizationOptionAlert, RequestAuthorizationHandler);
end;
procedure TNotificationCenterCocoa10.DoScheduleNotification(const ANotification: TNotification);
var
NotificationRequest: UNNotificationRequest;
begin
CheckPermissions;
DoCancelNotification(ANotification);
NotificationRequest := CreateNotificationRequest(ANotification, True);
TUNUserNotificationCenter.OCClass.currentNotificationCenter.addNotificationRequest(NotificationRequest, AddNotificationRequestHandler);
end;
class function TNotificationCenterCocoa10.GetDefaultInstance: TNotificationCenterCocoa10;
begin
if FInstance = nil then
FInstance := TNotificationCenterCocoa10.Create;
Result := FInstance;
end;
function TNotificationCenterCocoa10.GetNotificationSound(const ANotification: TNotification): UNNotificationSound;
begin
if not ANotification.EnableSound then
Exit(nil);
if ANotification.SoundName.IsEmpty then
Result := TUNNotificationSound.OCClass.defaultSound
else
Result := TUNNotificationSound.OCClass.soundNamed(StrToNSStr(ANotification.SoundName))
end;
function TNotificationCenterCocoa10.GetNotificationTrigger(const ANotification: TNotification): UNNotificationTrigger;
var
DateComponents: NSDateComponents;
begin
DateComponents := RepeatIntervalToNSDateComponents(ANotification.FireDate, ANotification.RepeatInterval);
DateComponents.setTimeZone(TNSTimeZone.Wrap(TNSTimeZone.OCClass.defaultTimeZone));
Result := TUNCalendarNotificationTrigger.OCClass.triggerWithDateMatchingComponents(DateComponents, ANotification.RepeatInterval <> TRepeatInterval.None);
end;
function TNotificationCenterCocoa10.RepeatIntervalToNSDateComponents(const ADate: TDate;
const ARepeatInterval: TRepeatInterval): NSDateComponents;
begin
Result := TNSDateComponents.Create;
case ARepeatInterval of
TRepeatInterval.None:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
Result.setHour(HourOf(ADate));
Result.setDay(DayOf(ADate));
Result.setMonth(MonthOf(ADate));
Result.setYear(YearOf(ADate));
end;
TRepeatInterval.Second:
Result.setNanosecond(MilliSecondOf(ADate));
TRepeatInterval.Minute:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
end;
TRepeatInterval.Hour:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
end;
TRepeatInterval.Day:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
Result.setHour(HourOf(ADate));
end;
TRepeatInterval.Week:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
Result.setHour(HourOf(ADate));
Result.setWeekday(DayOfTheWeek(ADate));
end;
TRepeatInterval.Month:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
Result.setHour(HourOf(ADate));
Result.setDay(DayOf(ADate));
end;
TRepeatInterval.Year:
begin
Result.setNanosecond(MilliSecondOf(ADate));
Result.setSecond(SecondOf(ADate));
Result.setMinute(MinuteOf(ADate));
Result.setHour(HourOf(ADate));
Result.setDay(DayOf(ADate));
Result.setMonth(MonthOf(ADate));
end;
TRepeatInterval.Weekday:
raise Exception.Create('Feature is not supported: (TRepeatInterval.Weekday)');
TRepeatInterval.Era:
raise Exception.Create('Feature is not supported: (TRepeatInterval.Era)');
TRepeatInterval.Quarter:
raise Exception.Create('Feature is not supported: (TRepeatInterval.Quarter)');
end;
end;
procedure TNotificationCenterCocoa10.RequestAuthorizationHandler(granted: Boolean; error: NSError);
begin
if granted then
FPermissionsState := TPermissionState.Granted
else
FPermissionsState := TPermissionState.Denied;
end;
{ TNotificationCenterIOS }
procedure TNotificationCenterIOS.ClearDelayedNotifications;
begin
FDelayedNotifications.Clear;
end;
constructor TNotificationCenterIOS.Create;
begin
TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedNotification, ReceiveLocalNotification);
TMessageManager.DefaultManager.SubscribeToMessage(TMessage<Pointer>, ReceiveLocalNotification); // UNNotificationResponse
FDelayedNotifications := TObjectList<TNotification>.Create;
FIsApplicationLoaded := False;
end;
destructor TNotificationCenterIOS.Destroy;
begin
{ Unsibscribe }
TMessageManager.DefaultManager.Unsubscribe(TMessage<UNNotificationResponse>, ReceiveLocalNotification);
TMessageManager.DefaultManager.Unsubscribe(TMessageReceivedNotification, ReceiveLocalNotification);
{ Destroying }
ClearDelayedNotifications;
FDelayedNotifications.Free;
inherited;
end;
procedure TNotificationCenterIOS.DidFormsLoad;
begin
FIsApplicationLoaded := True;
NotifyDelayedNotifications;
end;
procedure TNotificationCenterIOS.DoCreateOrUpdateChannel(const AChannel: TChannel);
begin
// Relevant only for Android
end;
procedure TNotificationCenterIOS.DoDeleteChannel(const AChannelId: string);
begin
// Relevant only for Android
end;
procedure TNotificationCenterIOS.DoGetAllChannels(const AChannels: TChannels);
begin
// Relevant only for Android
end;
function TNotificationCenterIOS.DoGetIconBadgeNumber: Integer;
begin
Result := SharedApplication.ApplicationIconBadgeNumber;
end;
procedure TNotificationCenterIOS.DoLoaded;
begin
inherited;
// DoLoaded is invoked before TForm.OnCreate. However, we have to process receiving of the Local Notification
// strictly after the form is fully loaded, because we need to invoke TNotificationCenter.OnReceiveLocalNotification
// after TForm.OnCreate.
TThread.ForceQueue(nil, procedure begin
DidFormsLoad;
end);
end;
procedure TNotificationCenterIOS.DoResetIconBadgeNumber;
begin
SharedApplication.setApplicationIconBadgeNumber(0);
end;
procedure TNotificationCenterIOS.DoSetIconBadgeNumber(const ACount: Integer);
begin
SharedApplication.setApplicationIconBadgeNumber(ACount);
end;
procedure TNotificationCenterIOS.ReceiveLocalNotification(const Sender: TObject; const M: TMessage);
procedure SendNotification(const Notification: TNotification);
begin
TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification));
// Sending Delayed notifications
if FDelayedNotifications.Count > 0 then
NotifyDelayedNotifications;
end;
var
NativeNotification: Pointer;
Notification: TNotification;
begin
if M is TMessageReceivedNotification then
NativeNotification := NSObjectToID((M as TMessageReceivedNotification).Value)
else
NativeNotification := (M as TMessage<Pointer>).Value; // Pointer = id of UNNotificationResponse
// iOS doesn't provide list of presented notification. So we need to store it
// in our list for cancelling in future with using ID
Notification := ConvertNativeToDelphiNotification(NativeNotification);
try
if not FIsApplicationLoaded then
FDelayedNotifications.Add(Notification)
else
SendNotification(Notification);
finally
Notification.Free;
end;
end;
procedure TNotificationCenterIOS.NotifyDelayedNotifications;
var
Notification: TNotification;
begin
for Notification in FDelayedNotifications do
TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification));
ClearDelayedNotifications;
end;
function TNotificationCenterIOS.SharedApplication: UIApplication;
var
App: Pointer;
begin
Result := nil;
App := TUIApplication.OCClass.sharedApplication;
if App <> nil then
Result := TUIApplication.Wrap(App);
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, pngimage, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Image1: TImage;
Image2: TImage;
Button1: TButton;
procedure FormCreate(Sender: TObject);
function ppf(imx: TImage; height, width: Uint64): Boolean;
procedure Button1Click(Sender: TObject);
function btw(cx: TColor): Boolean;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
h, w: Uint64;
implementation
{$R *.dfm}
function TForm1.btw(cx: TColor): Boolean;
var
colorx: $0 .. $FFFFFFFF;
r, g, b: Byte;
begin
{ colorx := ColorToRGB(cx);
r := ($000000FF and colorx);
g := ($0000FF00 and colorx) Shr 8;
b := ($00FF0000 and colorx) Shr 16; }
r := GetRValue(cx);
g := GetGValue(cx);
b := GetBValue(cx);
if (r <= 123) and (g <= 123) and (b <= 123) then
result := True
else
result := False;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
ppf(Image1, h, w);
Screen.Cursor := crDefault;
showmessage('Job Done!');
Application.Terminate;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
ix, jx: Integer;
begin
// rename the image file to yda and place it into the same directory as the EXE
Image1.Picture.LoadFromFile(GetCurrentDir + '\yda.bmp'); //must be a BMP file or it will throw an error
Image1.width := Image1.Picture.width;
Image1.height := Image1.Picture.height;
h := Image1.height;
w := Image1.width;
Image2.height := h;
Image2.width := w;
ShowMessage('Place the Image you want to use in the same folder as the EXE. It should be a BMP file. Works best with B&W Images.');
end;
function TForm1.ppf(imx: TImage; height, width: Uint64): Boolean;
var
i: Integer;
j: Integer;
str: String;
strs: TStringList;
pix: Array of Array of String;
sx : String;
rx : Integer;
begin
strs := TStringList.Create;
setlength(pix, height, width);
sx := 'Plato o Plomo';
for i := 0 to width - 1 do
begin
//rx := Random(100);
for j := 0 to height - 1 do
if {NOT}(btw(imx.Canvas.Pixels[i, j])) then
pix[i, j] := {sx[ (sx.Length+i) mod sx.Length ]} ( Char(Random(40)+48)) //characters you want to place at a black pixel
else
pix[i, j] := ' '; //character you want to place in a white pixel
end;
for i := 0 to width - 1 do
begin
str := '';
for j := 0 to width - 1 do
begin
str := str + (pix[j, i]);
end;
strs.Add(str);
end;
strs.SaveToFile(GetCurrentDir + '\yda.txt'); //the output will be in the same directory as the EXE
end;
end.
|
// ==============================================================================
//
// Unit uBluePhantom.pas
//
// This class contains the information about some pve Dark Souls player
// Note: the "White Phantom" definition is not really associated with the real
// summoned friend. It's just a definition for implementation
//
// Esta classe contém as informações sobre qualquer jogador (pve)
// Nota: a definição de "White Phantom" não é realmente de um amigo "summonado".
// Só foi definido esse nome para título de implementação.
//
// ==============================================================================
unit uWhitePhantom;
interface
uses
uWarrior;
type
// Class inherited from TWarrir
// Classe herdade de TWarrior
TWhitePhantom = class(TWarrior)
public
constructor Create; override;
procedure UpdateStatus; override;
procedure UpdateStaminaHPStatus; override;
end;
implementation
{ TWhitePhantom }
// Just the most important here: setting the pointers and offsets addresses for reading memory
// Apenas o mais importante: definindo os endereços de ponteiro e offsets para leitura de memória
constructor TWhitePhantom.Create;
const
DEFAULT_POINTER = $1349020;
DEFAULT_STATS_POINTER = $1349020;
begin
Self.FPointer := DEFAULT_POINTER;
Self.FInfoPointer := DEFAULT_STATS_POINTER;
Self.FLevelOffsets[0] := $40; Self.FLevelOffsets[1] := $60C; Self.FLevelOffsets[2] := $4; Self.FLevelOffsets[3] := $3C; Self.FLevelOffsets[4] := $88;
Self.FVitalityOffsets[0] := $40; Self.FVitalityOffsets[1] := $60C; Self.FVitalityOffsets[2] := $4; Self.FVitalityOffsets[3] := $3C; Self.FVitalityOffsets[4] := $38;
Self.FAttunementOffsets[0] := $40; Self.FAttunementOffsets[1] := $60C; Self.FAttunementOffsets[2] := $4; Self.FAttunementOffsets[3] := $3C; Self.FAttunementOffsets[4] := $40;
Self.FEnduranceOffsets[0] := $40; Self.FEnduranceOffsets[1] := $60C; Self.FEnduranceOffsets[2] := $4; Self.FEnduranceOffsets[3] := $3C; Self.FEnduranceOffsets[4] := $48;
Self.FStrengthOffsets[0] := $40; Self.FStrengthOffsets[1] := $60C; Self.FStrengthOffsets[2] := $4; Self.FStrengthOffsets[3] := $3C; Self.FStrengthOffsets[4] := $50;
Self.FDexterityOffsets[0] := $40; Self.FDexterityOffsets[1] := $60C; Self.FDexterityOffsets[2] := $4; Self.FDexterityOffsets[3] := $3C; Self.FDexterityOffsets[4] := $58;
Self.FResistanceOffsets[0] := $40; Self.FResistanceOffsets[1] := $60C; Self.FResistanceOffsets[2] := $4; Self.FResistanceOffsets[3] := $3C; Self.FResistanceOffsets[4] := $80;
Self.FIntelligenceOffsets[0] := $40; Self.FIntelligenceOffsets[1] := $60C; Self.FIntelligenceOffsets[2] := $4; Self.FIntelligenceOffsets[3] := $3C; Self.FIntelligenceOffsets[4] := $60;
Self.FFaithOffsets[0] := $40; Self.FFaithOffsets[1] := $60C; Self.FFaithOffsets[2] := $4; Self.FFaithOffsets[3] := $3C; Self.FFaithOffsets[4] := $68;
Self.FActualStaminaOffsets[0] := $40; Self.FActualStaminaOffsets[1] := $60C; Self.FActualStaminaOffsets[2] := $4; Self.FActualStaminaOffsets[3] := $3C; Self.FActualStaminaOffsets[4] := $1C;
Self.FMaxHPOffSets[0] := $40; Self.FMaxHPOffSets[1] := $60c; Self.FMaxHPOffSets[2] := $4; Self.FMaxHPOffSets[3] := $3C; Self.FMaxHPOffSets[4] := $10;
Self.FActualHPOffsets[0] := $40; Self.FActualHPOffsets[1] :=$60C; Self.FActualHPOffsets[2] := $4; Self.FActualHPOffsets[3] := $3C; Self.FActualHPOffsets[4] := $C;
inherited;
end;
procedure TWhitePhantom.UpdateStaminaHPStatus;
begin
inherited;
end;
procedure TWhitePhantom.UpdateStatus;
begin
inherited;
end;
end.
|
unit GUI;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SDL2, BaseTypes, Utility, Options;
type
{ tUIElement }
tUIElement = class
Top, Left,
Height, Width: integer;
Enabled: boolean;
procedure Draw; virtual;
end;
tUIEvent = procedure(Sender: tUIElement) of object;
{ tButton }
tButton = class(tUIElement)
private
FOnPress: tUIEvent;
procedure SetOnPress(AValue: tUIEvent);
published
property OnPress: tUIEvent read FOnPress write SetOnPress;
end;
{ tPanel }
tPanel = class(tUIElement)
Elements: array of tUIElement;
Caption: string;
destructor Destroy; override;
function GetControlAtPos(p: rInt2): tUIElement;
procedure Draw; override;
end;
{ tUIScreen }
tUIScreen = class
Panels: array of tPanel;
Level: integer;
constructor Create;
destructor Destroy; override;
function LoadContents(FileName: string): integer;
function GetControlAtPos(p: rInt2): tUIElement;
procedure Draw;
end;
rUIMouse = record
c: rInt2;
PressedOver: tUIElement;
LMB, RMB, MMB, MB1, MB2: boolean;
end;
{ tGUI }
tGUI = class
private
Event: tSDL_Event;
public
Screens: array of tUIScreen;
ActiveScreen: integer;
Options: tOptions;
Mouse: rUIMouse;
Transparent: boolean;
Back: boolean;
constructor Create;
destructor Destroy; override;
function LoadContents(FileName: string): integer;
procedure ProcessInput;
procedure Render;
end;
implementation
uses
app;
{ tGUI }
constructor tGUI.Create;
begin
end;
destructor tGUI.Destroy;
var
i: integer;
begin
for i:= 0 to high(Screens) do
Screens[i].Destroy;
setlength(Screens, 0);
inherited Destroy;
end;
function tGUI.LoadContents(FileName: string): integer;
begin
Result:= 0; { TODO : implement menu load }
setlength(Screens, 1);
Screens[0]:= tUIScreen.Create;
end;
procedure tGUI.ProcessInput;
var
Element: tUIElement;
begin
with Mouse, Options.Graphics do
begin
Back:= false;
while SDL_PollEvent(@Event) = 1 do
with Event do
begin
case type_ of
SDL_MOUSEBUTTONDOWN: LMB:= true; // Mouse button pressed
SDL_MOUSEBUTTONUP: LMB:= false;
SDL_MouseMotion:
begin
c.x:= motion.x;
c.y:= motion.y;
end;
SDL_KeyDown:
begin
case key.keysym.scancode of
SDL_SCANCODE_P: Toggle(Wireframe);
SDL_SCANCODE_N: DrawFrame:= true;
SDL_SCANCODE_1: GameApp.State:= sGameLoop;
SDL_SCANCODE_2: GameApp.State:= sShutDown;
SDL_SCANCODE_ESCAPE: Back:= true;
end;
{if Paused then
State:= sPaused; }
end;
SDL_KeyUp:
begin
end;
SDL_QuitEv: GameApp.State:= sShutDown;
end;
end;
if Back then
if ActiveScreen = 0 then
begin
GameApp.Player.Action.Paused:= false;
end
else
begin
ActiveScreen:= 0;
end;
if LMB and (PressedOver = nil) then
begin
Element:= Screens[ActiveScreen].GetControlAtPos(c);
if Element is tButton then
PressedOver:= Element;
end;
if not LMB and (PressedOver <> nil) then
begin
Element:= Screens[ActiveScreen].GetControlAtPos(c);
if PressedOver = Element then
with tButton(Element) do
if Assigned(OnPress) then
OnPress(Element);
PressedOver:= nil;
end;
end;
end;
procedure tGUI.Render;
begin
Screens[ActiveScreen].Draw;
end;
{ tUIElement }
procedure tUIElement.Draw;
begin
end;
{ tButton }
procedure tButton.SetOnPress(AValue: tUIEvent);
begin
if FOnPress=AValue then Exit;
FOnPress:=AValue;
end;
{ tUIScreen }
constructor tUIScreen.Create;
begin
end;
destructor tUIScreen.Destroy;
var
i: integer;
begin
for i:= 0 to high(Panels) do
Panels[i].Destroy;
setlength(Panels, 0);
inherited Destroy;
end;
function tUIScreen.LoadContents(FileName: string): integer;
begin
Result:= 0;
end;
function tUIScreen.GetControlAtPos(p: rInt2): tUIElement;
var
i: integer;
Found: boolean = false;
begin
for i:= 0 to high(Panels) do
with Panels[i] do
if (p.x >= Left) and (p.y >= Top) and
(p.x <= Left + Width) and (p.y <= Top + Height) then
begin
Found:= true;
break
end;
if Found then
Result:= Panels[i].GetControlAtPos(p)
else
Result:= nil;
end;
procedure tUIScreen.Draw;
var
i: integer;
begin
for i:= 0 to high(Panels) do
Panels[i].Draw;
end;
{ tPanel }
destructor tPanel.Destroy;
var
i: integer;
begin
for i:= 0 to high(Elements) do
Elements[i].Destroy;
setlength(Elements, 0);
inherited Destroy;
end;
function tPanel.GetControlAtPos(p: rInt2): tUIElement;
var
i: integer;
Found: boolean;
begin
for i:= 0 to high(Elements) do
with Elements[i] do
if (p.x >= Left) and (p.y >= Top) and
(p.x <= Left + Width) and (p.y <= Top + Height) then
begin
Found:= true;
break
end;
if Found then
begin
if Elements[i] is tPanel then
Result:= tPanel(Elements[i]).GetControlAtPos(p)
else
Result:= Elements[i];
end
else
Result:= nil;
end;
procedure tPanel.Draw;
var
i: integer;
begin
for i:= 0 to high(Elements) do
Elements[i].Draw;
inherited Draw;
end;
end.
|
program tema8_2017;
uses crt;
const
DIM = 6;
type Tmat = array[1..DIM,1..DIM] of Integer;
Tvec = array[1..DIM] of Integer;
procedure CargarMatriz(var M: Tmat; LimInf,LimSup: Integer);
var
i,j: Integer;
begin
for i := 1 to DIM do
begin
for j := 1 to DIM do
begin
if i=j then
begin
M[i,j]:=1;
end
else
begin
repeat
M[i,j]:=LimInf+random(LimSup+1-LimInf);
until M[i,j] mod 5 = 0;
end;
end;
end;
end;
function sumaFila(M: Tmat; i: Integer): Integer;
var
j,a: Integer;
begin
a:=0;
for j := 1 to DIM do
begin
a:=a+M[i,j];
end;
sumaFila:=a;
end;
procedure generarVector(var Vect: Tvec; M: Tmat);
var
i: Integer;
begin
for i := 1 to DIM do
begin
Vect[i]:=sumaFila(M,i);
end;
end;
procedure Mostrar(M: Tmat; Vect: Tvec);
var
i,j: Integer;
begin
for i := 1 to DIM do
begin
writeln;
for j := 1 to DIM do
begin
write(M[i,j]:5);
end;
write(Vect[i]:10);
end;
end;
var
M: Tmat;
Vect: Tvec;
BEGIN{MAIN}
randomize;
highvideo;
CargarMatriz(M,1,50);
generarVector(Vect,M);
Mostrar(M,Vect);
END.
|
unit set_in_1;
interface
implementation
type
TEnum = (i1, i2, i3, i4);
var
S: set of TEnum;
G1, G2: Boolean;
procedure Test;
begin
S := [i1, i3];
G1 := i3 in S;
G2 := i2 in S;
end;
initialization
Test();
finalization
Assert(G1 = true);
Assert(G2 = false);
end. |
unit ORExtensions;
interface
uses
ORCtrls,
System.Classes,
Vcl.Clipbrd,
Vcl.ComCtrls,
Vcl.Forms,
Vcl.StdCtrls,
Winapi.Messages,
Winapi.Windows,
TLHelp32,
System.SysUtils,
Vcl.Dialogs,
System.UITypes;
type
TEdit = class(Vcl.StdCtrls.TEdit)
public
procedure WMPaste(var Message: TMessage); message WM_PASTE;
end;
TMemo = class(Vcl.StdCtrls.TMemo)
public
procedure WMPaste(var Message: TMessage); message WM_PASTE;
end;
TRichEdit = class(Vcl.ComCtrls.TRichEdit)
public
procedure WMPaste(var Message: TMessage); message WM_PASTE;
procedure WMKeyDown(var Message: TMessage); message WM_KEYDOWN;
end;
TCaptionEdit = class(ORCtrls.TCaptionEdit)
public
procedure WMPaste(var Message: TMessage); message WM_PASTE;
end;
TCaptionMemo = class(ORCtrls.TCaptionMemo)
public
procedure WMPaste(var Message: TMessage); message WM_PASTE;
end;
procedure ScrubTheClipboard;
implementation
procedure ScrubTheClipboard;
Type
tClipInfo = record
AppName: string;
AppClass: string;
AppHwnd: HWND;
AppPid: Cardinal;
AppTitle: String;
ObjectHwnd: HWND;
end;
const
ATabWidth = 8;
Max_Retry = 3;
Hlp_Msg = 'System Error: %s' + #13#10 +
'There was a problem accessing the clipboard please try again.' + #13#10 +
#13#10 + 'The following application has a lock on the clipboard:' + #13#10 +
'App Title: %s' + #13#10 + 'App Name: %s' + #13#10 + #13#10 +
'If this problem persists please close %s and then try again. If you are still experiencing issues please contact your local CPRS help desk.';
var
i, X, J, RetryCnt: integer;
aAnsiValue: integer;
aAnsiString: AnsiString;
TryPst: Boolean;
ClpLckInfo: tClipInfo;
TmpStr: string;
TmpStrLst: TStringList;
function GetClipSource(): tClipInfo;
function GetAppByPID(PID: Cardinal): String;
var
snapshot: THandle;
ProcEntry: TProcessEntry32;
begin
snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot <> INVALID_HANDLE_VALUE) then
begin
ProcEntry.dwSize := SizeOf(ProcessEntry32);
if (Process32First(snapshot, ProcEntry)) then
begin
// check the first entry
if ProcEntry.th32ProcessID = PID then
Result := ProcEntry.szExeFile
else
begin
while Process32Next(snapshot, ProcEntry) do
begin
if ProcEntry.th32ProcessID = PID then
begin
Result := ProcEntry.szExeFile;
Break;
end;
end;
end;
end;
end;
CloseHandle(snapshot);
end;
function GetHandleByPID(PID: Cardinal): HWND;
type
TEInfo = record
PID: DWORD;
HWND: THandle;
end;
var
EInfo: TEInfo;
function CallBack(Wnd: DWORD; var EI: TEInfo): Bool; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessID(Wnd, @PID);
Result := (PID <> EI.PID) or (not IsWindowVisible(Wnd)) or
(not IsWindowEnabled(Wnd));
if not Result then
EI.HWND := Wnd;
end;
begin
EInfo.PID := PID;
EInfo.HWND := 0;
EnumWindows(@CallBack, integer(@EInfo));
Result := EInfo.HWND;
end;
begin
with Result do
begin
ObjectHwnd := 0;
AppHwnd := 0;
AppPid := 0;
// Get the owners handle (TEdit, etc...)
ObjectHwnd := GetOpenClipboardWindow;
if ObjectHwnd <> 0 then
begin
// Get its running applications Process ID
GetWindowThreadProcessID(ObjectHwnd, AppPid);
if AppPid <> 0 then
begin
// Get the applciation name from the Process ID
AppName := GetAppByPID(AppPid);
// Get the main applications hwnd
AppHwnd := GetHandleByPID(AppPid);
SetLength(AppClass, 256);
SetLength(AppClass, GetClassName(AppHwnd, PChar(AppClass),
Length(AppClass)- 1));
SetLength(AppTitle, 256);
SetLength(AppTitle, GetWindowText(AppHwnd, PChar(AppTitle),
Length(AppTitle) - 1));
end
else
AppName := 'No Process Found';
end
else
AppName := 'No Source Found';
end;
end;
// Scrub clipboard but keep all formats
procedure AddToClipBoard(aValue: AnsiString);
var
gMem: HGLOBAL;
lp: Pointer;
WS: String;
ErrorCode: integer;
ErrorMessage: String;
begin
{$WARN SYMBOL_PLATFORM OFF}
Clipboard.Open;
try
if Clipboard.HasFormat(CF_TEXT) then
begin
// now add the text to the clipboard
gMem := GlobalAlloc(GHND, (Length(aValue) + 1));
// Combines GMEM_MOVEABLE and GMEM_ZEROINIT - GMEM_DDESHARE is obsolete and ignored
try
if gMem = 0 then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
lp := GlobalLock(gMem);
if not assigned(lp) then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
CopyMemory(lp, Pointer(PAnsiChar(@aValue[1])), (Length(aValue) + 1));
// We should look at changing this to memcpy_s
{
Note: The Delphi import of GlobalUnlock() is incorrect in Winapi.Windows.
Per https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-globalunlock
If the memory object is still locked after decrementing the lock count,
the return value is a nonzero value. If the memory object is unlocked
after decrementing the lock count, the function returns zero and GetLastError
returns NO_ERROR.
Since a non-zero is interpreted as true and zero is interpreted as false, the
result of the API call is actually inverted.
}
if GlobalUnlock(gMem) then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
SetClipboardData(CF_TEXT, gMem);
except
on E: Exception do
begin
GlobalFree(gMem)
end;
end;
end;
if Clipboard.HasFormat(CF_UNICODETEXT) then
begin
WS := UnicodeString(aValue);
gMem := GlobalAlloc(GMEM_DDESHARE + GMEM_MOVEABLE, ((Length(WS) + 1) * 2));
try
if gMem = 0 then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
lp := GlobalLock(gMem);
if not assigned(lp) then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
CopyMemory(lp, Pointer(PChar(@WS[1])), ((Length(WS) + 1) * 2));
{
Note: The Delphi import of GlobalUnlock() is incorrect in Winapi.Windows.
Per https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-globalunlock
If the memory object is still locked after decrementing the lock count,
the return value is a nonzero value. If the memory object is unlocked
after decrementing the lock count, the function returns zero and GetLastError
returns NO_ERROR.
Since a non-zero is interpreted as true and zero is interpreted as false, the
result of the API call is actually inverted.
}
if GlobalUnlock(gMem) then
begin
ErrorCode := GetLastError;
ErrorMessage := SysErrorMessage(ErrorCode);
raise Exception.Create(ErrorMessage);
end;
SetClipboardData(CF_UNICODETEXT, gMem);
except
on E: Exception do
begin
GlobalFree(gMem);
end;
end;
end;
finally
Clipboard.Close;
end;
{$WARN SYMBOL_PLATFORM ON}
end;
begin
// try
RetryCnt := 1;
TryPst := true;
// Grab our data from the clipboard, Try Three times
while TryPst do
begin
while (RetryCnt <= Max_Retry) and TryPst do
begin
Try
if Clipboard.HasFormat(CF_TEXT) then
begin
// Load text line by line
TmpStrLst := TStringList.Create;
try
// Load from clipboard
TmpStrLst.Text := Clipboard.AsText;
// loop line by line
for i := 0 to TmpStrLst.Count - 1 do
begin
// convert line to ansi
aAnsiString := AnsiString(TmpStrLst.strings[i]);
TmpStr := '';
// Loop character by character
for X := 1 to Length(aAnsiString) do
begin
aAnsiValue := Ord(aAnsiString[X]);
if (aAnsiValue < 32) or (aAnsiValue > 126) then
begin
case aAnsiValue of
9:
for J := 1 to
(ATabWidth - (Length(TmpStr) mod ATabWidth)) do
TmpStr := TmpStr + ' ';
10:
TmpStr := TmpStr + #10;
13:
TmpStr := TmpStr + #13;
145, 146:
TmpStr := TmpStr + '''';
147, 148:
TmpStr := TmpStr + '"';
149:
TmpStr := TmpStr + '*';
else
TmpStr := TmpStr + '?';
end;
end
else
TmpStr := TmpStr + String(aAnsiString[X]);
end;
// Reset the line with the filtered string
TmpStrLst.strings[i] := TmpStr;
end;
// Set the anisting to the full filtered results
aAnsiString := '';
for X := 0 to TmpStrLst.Count - 1 do
begin
if X > 0 then
aAnsiString := aAnsiString + #13#10;
aAnsiString := aAnsiString + AnsiString(TmpStrLst[X]);
end;
finally
TmpStrLst.Free;
end;
// Clipboard.AsText := String(aAnsiString);
AddToClipBoard(aAnsiString);
end;
TryPst := false;
Except
inc(RetryCnt);
Sleep(100);
If RetryCnt > Max_Retry then
ClpLckInfo := GetClipSource;
End;
end;
// If our retry count is greater than the max we were unable to grab the paste
if RetryCnt > Max_Retry then
begin
TmpStr := Format(Hlp_Msg, [SysErrorMessage(GetLastError),
ClpLckInfo.AppTitle, ClpLckInfo.AppName, ClpLckInfo.AppName]);
if TaskMessageDlg('Clipboard Locked', TmpStr, mtError,
[mbRetry, mbCancel], -1) = mrRetry then
begin
// reset the loop variables
RetryCnt := 1;
TryPst := true;
end
else
Exit;
end;
end;
// Except
// Swallow the exception for the tim being
// End;
end;
{ TEdit }
procedure TEdit.WMPaste(var Message: TMessage);
begin
ScrubTheClipboard;
inherited;
end;
{ TMemo }
procedure TMemo.WMPaste(var Message: TMessage);
begin
ScrubTheClipboard;
inherited;
end;
{ TRichEdit }
procedure TRichEdit.WMKeyDown(var Message: TMessage);
var
aShiftState: TShiftState;
begin
aShiftState := KeyDataToShiftState(message.WParam);
if (ssCtrl in aShiftState) and (message.WParam = Ord('V')) then
ScrubTheClipboard;
if (ssShift in aShiftState) and (message.WParam = VK_INSERT) then
ScrubTheClipboard;
inherited;
end;
procedure TRichEdit.WMPaste(var Message: TMessage);
begin
ScrubTheClipboard;
inherited;
end;
{ TCaptionEdit }
procedure TCaptionEdit.WMPaste(var Message: TMessage);
begin
ScrubTheClipboard;
inherited;
end;
{ TCaptionMemo }
procedure TCaptionMemo.WMPaste(var Message: TMessage);
begin
ScrubTheClipboard;
inherited;
end;
end.
|
unit ServerConst1;
interface
resourcestring
sPortInUse = '- Erro: Porta %s já em uso';
sPortSet = '- Porta configurada para %s';
sServerRunning = '- O servidor já está rodando.';
sStartingServer = '- Iniciando servidor na porta %d';
sStoppingServer = '- Parando servidor...';
sServerStopped = '- Servidor encerrado!';
sServerNotRunning = '- O servidor não está rodando';
sInvalidCommand = '- Erro: Comando inválido.';
sIndyVersion = '- Versão do Indy: ';
sActive = '- Ativo: ';
sPort = '- Porta: ';
sSessionID = '- Id da seção: ';
sCommands = 'Servidor Meus Contatos - versão 1.1' + slineBreak + slineBreak +
'Digite o comando: ' + slineBreak +
' - "Iniciar" para iniciar o servidor'+ slineBreak +
' - "Parar" para parar o servidor'+ slineBreak +
' - "Configurar porta" para alterar porta padrão'+ slineBreak +
' - "Status" para exibir status do servidor'+ slineBreak +
' - "Ajuda" para mostrar comandos'+ slineBreak +
' - "Sair" para encerrar o aplicativo servidor';
const
cArrow = '->';
cCommandStart = 'Iniciar';
cCommandStop = 'Parar';
cCommandStatus = 'Status';
cCommandHelp = 'Ajuda';
cCommandSetPort = 'Configurar porta';
cCommandExit = 'Sair';
implementation
end.
|
unit MasterMind.View.Form;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, MasterMind.API, stdctrls;
type
TBoardRow = record
Panel: TPanel;
Colors: array[0..CODE_SIZE - 1] of TShape;
Hints: array[0..CODE_SIZE - 1] of TShape;
end;
TFormMasterMind = class(TForm, IGameView)
pnlBoard: TPanel;
procedure FormCreate(Sender: TObject);
private
btnCommitGuess: TButton;
FPresenter: IGamePresenter;
FBoardRows: array[0..MAX_GUESSES - 1] of TBoardRow;
FCurrentInputRow: Integer;
FMasterRow: TBoardRow;
procedure CreateBoard;
function CreateRowPanel(const RowIndex: Integer): TPanel;
procedure AddShapesToRowPanel(const RowPanel: TPanel; const RowIndex: Integer);
procedure AddCodeShapes(const RowPanel: TPanel; var BoardRow: TBoardRow; const RowIndex: Integer);
procedure AddHintShapes(const RowPanel: TPanel; const RowIndex: Integer);
function CreateCodeShape(const CodeColorIndex, RowIndex: Integer; const RowPanel: TPanel): TShape;
procedure AddHintShape(const HintIndex, RowIndex: Integer; const RowPanel: TPanel);
procedure ColorShapeClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
function GetNextColor(const CodeShape: TShape): TColor;
procedure CreateStartGameButton;
procedure BtnNewGameClick(Sender: TObject);
procedure BtnCommitGuessClick(Sender: TObject);
procedure CreateBtnCommitGuess;
function TryGetPlayersGuess(out Guess: TMasterMindCode): Boolean;
function TryGetCodeColorFromShape(out Color: TMasterMindCodeColor; const ColorIndex: Integer): Boolean;
procedure EnableGuessInput(const CurrentGuessIndex: Integer);
procedure DisableGuessInput;
procedure PaintEvaluatedGuess(const PreviousGuesses: TEvaluatedGuess; const RowIndex: Integer);
procedure ResetBoardRow(const RowIndex: Integer);
procedure CreateRows;
procedure CreateMasterCodeRow;
procedure EndGame(const EndMessage: String);
procedure ShowCorrectCode;
procedure ClearCorrectCode;
private
const
CODE_COLOR_MAPPING: array[TMasterMindCodeColor] of TColor = (
clGreen,
clYellow,
clBlue,
clRed,
clWhite,
clMaroon
);
HINT_COLOR_MAPPING: array[TMasterMindHint] of TColor = (
clBlack,
clWhite,
clRed
);
public
procedure Start;
procedure StartRequestGuess(const PreviousGuesses: TPreviousGuesses);
procedure ShowGuesses(const PreviousGuesses: TPreviousGuesses);
procedure ShowPlayerWinsMessage(const PreviousGuesses: TPreviousGuesses);
procedure ShowPlayerLosesMessage(const PreviousGuesses: TPreviousGuesses);
end;
implementation
uses
MasterMind.PresenterFactory;
procedure TFormMasterMind.FormCreate(Sender: TObject);
begin
Caption := 'MasterMind';
FPresenter := TMasterMindPresenterFactory.CreatePresenter(Self);
CreateBoard;
CreateStartGameButton;
CreateBtnCommitGuess;
Start;
end;
procedure TFormMasterMind.CreateBoard;
begin
CreateRows;
CreateMasterCodeRow;
end;
procedure TFormMasterMind.CreateRows;
var
I: Integer;
begin
for I := Low(FBoardRows) to High(FBoardRows) do
begin
FBoardRows[I].Panel := CreateRowPanel(I);
AddShapesToRowPanel(FBoardRows[I].Panel, I);
end;
end;
function TFormMasterMind.CreateRowPanel(const RowIndex: Integer): TPanel;
const
ROW_HEIGHT = 40;
begin
Result := TPanel.Create(pnlBoard);
Result.Parent := pnlBoard;
Result.Width := pnlBoard.Width;
Result.Height := ROW_HEIGHT;
Result.Top := pnlBoard.Height - ((RowIndex + 1) * ROW_HEIGHT);
end;
procedure TFormMasterMind.AddShapesToRowPanel(const RowPanel: TPanel; const RowIndex: Integer);
begin
AddCodeShapes(RowPanel, FBoardRows[RowIndex], RowIndex);
AddHintShapes(RowPanel, RowIndex);
end;
procedure TFormMasterMind.AddCodeShapes(const RowPanel: TPanel; var BoardRow: TBoardRow; const RowIndex: Integer);
var
I: Integer;
begin
for I := 0 to CODE_SIZE - 1 do
BoardRow.Colors[I] := CreateCodeShape(I, RowIndex, RowPanel);
end;
function TFormMasterMind.CreateCodeShape(const CodeColorIndex, RowIndex: Integer; const RowPanel: TPanel): TShape;
const
CODE_SHAPE_START_LEFT = 150;
CODE_SHAPE_SPACING = 20;
CODE_SHAPE_SIZE = 20;
begin
Result := TShape.Create(RowPanel);
Result.Parent := RowPanel;
Result.Shape := stCircle;
Result.Width := CODE_SHAPE_SIZE;
Result.Height := CODE_SHAPE_SIZE;
Result.Top := (RowPanel.Height - CODE_SHAPE_SIZE) div 2;
Result.Left := CODE_SHAPE_START_LEFT + (CodeColorIndex * (CODE_SHAPE_SIZE + CODE_SHAPE_SPACING));
Result.Brush.Color := clBlack;
Result.Tag := RowIndex;
Result.OnMouseDown := ColorShapeClick;
end;
procedure TFormMasterMind.AddHintShapes(const RowPanel: TPanel; const RowIndex: Integer);
var
I: Integer;
begin
for I := 0 to CODE_SIZE - 1 do
AddHintShape(I, RowIndex, RowPanel);
end;
procedure TFormMasterMind.AddHintShape(const HintIndex, RowIndex: Integer; const RowPanel: TPanel);
const
HINT_SHAPE_START_LEFT = 10;
HINT_SHAPE_SPACING = 12;
HINT_SHAPE_SIZE = 10;
var
Shape: TShape;
RowMid, Column: Integer;
begin
Shape := TShape.Create(RowPanel);
Shape.Parent := RowPanel;
Shape.Shape := stCircle;
Shape.Width := HINT_SHAPE_SIZE;
Shape.Height := HINT_SHAPE_SIZE;
RowMid := (RowPanel.Height - HINT_SHAPE_SIZE) div 2;
if HintIndex > 1 then
Shape.Top := RowMid + (HINT_SHAPE_SPACING div 2)
else
Shape.Top := RowMid - (HINT_SHAPE_SPACING div 2);
if Odd(HintIndex) then
Column := 1
else
Column := 0;
Shape.Left := HINT_SHAPE_START_LEFT + (Column * (HINT_SHAPE_SPACING));
Shape.Brush.Color := clBlack;
FBoardRows[RowIndex].Hints[HintIndex] := Shape;
end;
procedure TFormMasterMind.CreateMasterCodeRow;
begin
FMasterRow.Panel := CreateRowPanel(MAX_GUESSES);
AddCodeShapes(FMasterRow.Panel, FMasterRow, MAX_GUESSES);
end;
procedure TFormMasterMind.ColorShapeClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Shape: TShape;
Guess: TMasterMindCode;
begin
Shape := Sender as TShape;
if Shape.Tag = FCurrentInputRow then
Shape.Brush.Color := GetNextColor(Shape);
btnCommitGuess.Enabled := TryGetPlayersGuess(Guess);
end;
function TFormMasterMind.GetNextColor(const CodeShape: TShape): TColor;
var
ColorFound: Boolean;
Color: TColor;
begin
ColorFound := False;
for Color in CODE_COLOR_MAPPING do
if ColorFound then
Exit(Color)
else
if CodeShape.Brush.Color = Color then
ColorFound := True;
Exit(CODE_COLOR_MAPPING[TMasterMindCodeColor(0)]);
end;
procedure TFormMasterMind.CreateStartGameButton;
var
Button: TButton;
begin
Button := TButton.Create(Self);
Button.Parent := Self;
Button.Caption := 'New Game';
Button.Top := 20;
Button.Left := Width - Button.Width - 10;
Button.OnClick := BtnNewGameClick;
end;
procedure TFormMasterMind.BtnNewGameClick(Sender: TObject);
begin
FPresenter.NewGame;
end;
procedure TFormMasterMind.CreateBtnCommitGuess;
begin
btnCommitGuess := TButton.Create(Self);
btnCommitGuess.Parent := Self;
btnCommitGuess.Caption := 'Commit guess';
btnCommitGuess.Width := 90;
btnCommitGuess.Top := Height - btnCommitGuess.Height - 10;
btnCommitGuess.Left := Width - btnCommitGuess.Width - 10;
btnCommitGuess.OnClick := BtnCommitGuessClick;
end;
procedure TFormMasterMind.BtnCommitGuessClick(Sender: TObject);
var
Guess: TMasterMindCode;
begin
if TryGetPlayersGuess(Guess) then
FPresenter.TakeGuess(Guess);
end;
function TFormMasterMind.TryGetPlayersGuess(out Guess: TMasterMindCode): Boolean;
var
I: Integer;
begin
if FCurrentInputRow < 0 then
Exit(False);
for I := Low(Guess) to High(Guess) do
if not TryGetCodeColorFromShape(Guess[I], I) then
Exit(False);
Exit(True);
end;
function TFormMasterMind.TryGetCodeColorFromShape(out Color: TMasterMindCodeColor; const ColorIndex: Integer): Boolean;
var
Shape: TShape;
CurrentColor: TMasterMindCodeColor;
begin
Shape := FBoardRows[FCurrentInputRow].Colors[ColorIndex];
for CurrentColor := Low(TMasterMindCodeColor) to High(TMasterMindCodeColor) do
begin
if Shape.Brush.Color = CODE_COLOR_MAPPING[CurrentColor] then
begin
Color := CurrentColor;
Exit(True);
end;
end;
Exit(False);
end;
procedure TFormMasterMind.Start;
begin
DisableGuessInput;
FPresenter.NewGame;
end;
procedure TFormMasterMind.StartRequestGuess(const PreviousGuesses: TPreviousGuesses);
var
CurrentGuessIndex: Integer;
begin
CurrentGuessIndex := Length(PreviousGuesses);
EnableGuessInput(CurrentGuessIndex);
end;
procedure TFormMasterMind.ShowGuesses(const PreviousGuesses: TPreviousGuesses);
var
I: Integer;
begin
DisableGuessInput;
ClearCorrectCode;
for I := Low(PreviousGuesses) to High(PreviousGuesses) do
PaintEvaluatedGuess(PreviousGuesses[I], I);
for I := Length(PreviousGuesses) to High(FBoardRows) do
ResetBoardRow(I);
end;
procedure TFormMasterMind.PaintEvaluatedGuess(const PreviousGuesses: TEvaluatedGuess; const RowIndex: Integer);
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
FBoardRows[RowIndex].Hints[I].Brush.Color := HINT_COLOR_MAPPING[PreviousGuesses.GuessResult[I]];
end;
procedure TFormMasterMind.ResetBoardRow(const RowIndex: Integer);
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
begin
FBoardRows[RowIndex].Hints[I].Brush.Color := HINT_COLOR_MAPPING[mmhNoMatch];
FBoardRows[RowIndex].Colors[I].Brush.Color := clBlack;
end;
end;
procedure TFormMasterMind.ShowPlayerWinsMessage(const PreviousGuesses: TPreviousGuesses);
begin
EndGame('You win!');
end;
procedure TFormMasterMind.ShowPlayerLosesMessage(const PreviousGuesses: TPreviousGuesses);
begin
EndGame('You lose!');
end;
procedure TFormMasterMind.EndGame(const EndMessage: String);
begin
ShowCorrectCode;
ShowMessage(EndMessage);
end;
procedure TFormMasterMind.ShowCorrectCode;
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
FMasterRow.Colors[I].Brush.Color := CODE_COLOR_MAPPING[FPresenter.CodeToBeGuessed[I]];
end;
procedure TFormMasterMind.ClearCorrectCode;
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
FMasterRow.Colors[I].Brush.Color := clBlack;
end;
procedure TFormMasterMind.EnableGuessInput(const CurrentGuessIndex: Integer);
var
I: Integer;
begin
FCurrentInputRow := CurrentGuessIndex;
for I := Low(FBoardRows) to High(FBoardRows) do
if I = CurrentGuessIndex then
FBoardRows[I].Panel.Color := clHighlight
else
FBoardRows[I].Panel.Color := clWindow;
end;
procedure TFormMasterMind.DisableGuessInput;
begin
FCurrentInputRow := -1;
btnCommitGuess.Enabled := False;
end;
{$R *.lfm}
end. |
{**********************************************}
{ TeeChart Tools }
{ Copyright (c) 1999-2004 by David Berneda }
{**********************************************}
unit TeeTools;
{$I TeeDefs.inc}
interface
// This unit defines and implements several "Chart Tools".
// Tools appear at the Chart editor "Tools" tab and can be added
// both at design-time and run-time.
// The purpose of a "tool" is to perform some generic functionality
// outside the Chart or Series code. Chart Tools are notified of
// chart drawing (repaints) and chart mouse events (move, up, down).
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls,
{$ELSE}
Graphics, Controls,
{$ENDIF}
{$IFDEF D6}
Types,
{$ENDIF}
TeCanvas, TeeProcs, TeEngine, Chart;
// Default number of pixels to consider a line is "clicked"
// (ie: when the mouse is more or less 3 pixels from a line)
Const TeeClickTolerance = 3;
Type
// Style of cursor tool
TCursorToolStyle=(cssHorizontal,cssVertical,cssBoth);
TCursorTool=class;
TCursorClicked=(ccNone,ccHorizontal,ccVertical,ccBoth);
TCursorToolChangeEvent=procedure( Sender:TCursorTool;
x,y:Integer;
Const XValue,YValue:Double;
Series:TChartSeries;
ValueIndex:Integer) of object;
TCursorToolGetAxisRect=procedure(Sender:TCursorTool; Var Rect:TRect) of object;
// Cursor tool, use it to draw a draggable line (cursor)
TCursorTool=class(TTeeCustomToolSeries)
private
FFollowMouse : Boolean;
FOnChange : TCursorToolChangeEvent;
FOnGetAxisRect : TCursorToolGetAxisRect;
FOnSnapChange : TCursorToolChangeEvent;
FSnap : Boolean;
FStyle : TCursorToolStyle;
FUseChartRect : Boolean;
FUseSeriesZ : Boolean; // 7.0
IDragging : TCursorClicked;
IOldSnap : Integer;
Procedure CalcValuePositions(X,Y:Integer);
procedure DoChange;
Function GetAxisRect:TRect;
Function InAxisRectangle(x,y:Integer):Boolean;
Procedure SetStyle(Value:TCursorToolStyle);
procedure SetUseChartRect(const Value: Boolean);
procedure SetUseSeriesZ(const Value: Boolean);
procedure SetXValue(const Value: Double);
procedure SetYValue(const Value: Double);
Function Z:Integer;
protected
IXValue : Double; { 5.01 }
IYValue : Double;
IPoint : TPoint;
Procedure CalcScreenPositions; { 5.01 }
Procedure Changed(SnapPoint:Integer); virtual;
Procedure ChartEvent(AEvent:TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class Function GetEditorClass:String; override;
procedure SetSeries(const Value: TChartSeries); override;
public
Constructor Create(AOwner:TComponent); override;
Function Clicked(x,y:Integer):TCursorClicked;
class Function Description:String; override;
Function NearestPoint(AStyle:TCursorToolStyle; Var Difference:Double):Integer;
Function SnapToPoint:Integer;
procedure RedrawCursor;
property UseChartRect:Boolean read FUseChartRect write SetUseChartRect default False;
property XValue:Double read IXValue write SetXValue;
property YValue:Double read IYValue write SetYValue;
property OnGetAxisRect:TCursorToolGetAxisRect read FOnGetAxisRect write FOnGetAxisRect;
published
property Active;
property FollowMouse:Boolean read FFollowMouse write FFollowMouse default False;
property Pen;
property Series;
property Snap:Boolean read FSnap write FSnap default False;
property Style:TCursorToolStyle read FStyle write SetStyle default cssBoth;
property UseSeriesZ:Boolean read FUseSeriesZ write SetUseSeriesZ default False;
{ events }
property OnChange:TCursorToolChangeEvent read FOnChange write FOnChange;
property OnSnapChange:TCursorToolChangeEvent read FOnSnapChange write FOnSnapChange; // 7.0
end;
// Drag Marks tool, use it to allow the end-user to drag series Marks
TDragMarksTool=class(TTeeCustomToolSeries)
private
{ internal }
IOldX : Integer;
IOldY : Integer;
IPosition: TSeriesMarkPosition;
ISeries : TChartSeries;
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class Function GetEditorClass:String; override;
public
class Function Description:String; override;
published
property Active;
property Series;
end;
TAxisArrowTool=class;
TAxisArrowClickEvent=procedure(Sender:TAxisArrowTool; AtStart:Boolean) of object;
TAxisArrowToolPosition=(aaStart,aaEnd,aaBoth);
// Axis Arrow tool, use it to display small "arrows" at start and end
// positions of an axis. These arrows can be clicked to scroll the axis.
TAxisArrowTool=class(TTeeCustomToolAxis)
private
FLength : Integer;
FPosition : TAxisArrowToolPosition;
FScrollPercent : Integer;
FScrollInverted: Boolean;
FOnClick : TAxisArrowClickEvent;
Function ClickedArrow(x,y:Integer):Integer;
procedure SetLength(const Value: Integer);
procedure SetPosition(const Value: TAxisArrowToolPosition);
protected
Procedure ChartEvent(AEvent:TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
published
property Active;
property Position:TAxisArrowToolPosition read FPosition write SetPosition default aaBoth;
property Axis;
property Brush;
property Length:Integer read FLength write SetLength default 16;
property Pen;
property ScrollInverted:Boolean read FScrollInverted write FScrollInverted default False;
property ScrollPercent:Integer read FScrollPercent write FScrollPercent default 10;
{ events }
property OnClick:TAxisArrowClickEvent read FOnClick write FOnClick;
end;
TAxisScrollTool=class(TTeeCustomToolAxis)
private
FScrollInverted : Boolean;
OldX,
OldY : Integer;
InAxis : TChartAxis;
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
public
class Function Description:String; override;
published
property Active;
property Axis;
property ScrollInverted:Boolean read FScrollInverted write FScrollInverted default False;
end;
TDrawLineTool=class;
TDrawLineStyle=(dlLine,dlHorizParallel,dlVertParallel); { 5.03 }
// Element of Lines collection in TDrawLineTool class
TDrawLine=class(TCollectionItem)
private
FStyle : TDrawLineStyle;
Function GetParent:TDrawLineTool;
Function GetPen:TChartPen;
function GetX0: Double;
function GetX1: Double;
function GetY0: Double;
function GetY1: Double;
Procedure SetStyle(Value:TDrawLineStyle);
procedure SetX0(const Value: Double);
procedure SetX1(const Value: Double);
procedure SetY0(const Value: Double);
procedure SetY1(const Value: Double);
public
EndPos : TFloatPoint;
StartPos : TFloatPoint;
Constructor CreateXY(Collection:TCollection; Const X0,Y0,X1,Y1:Double);
Destructor Destroy; override;
Procedure Assign(Source:TPersistent); override; { 5.01 }
Procedure DrawHandles;
Function EndHandle:TRect;
Function StartHandle:TRect;
property Parent : TDrawLineTool read GetParent;
property Pen : TChartPen read GetPen;
published
property Style:TDrawLineStyle read FStyle write SetStyle default dlLine;
property X0:Double read GetX0 write SetX0;
property Y0:Double read GetY0 write SetY0;
property X1:Double read GetX1 write SetX1;
property Y1:Double read GetY1 write SetY1;
end;
// Collection of lines (TDrawLine) used in TDrawLineTool
TDrawLines=class(TOwnedCollection)
private
Function Get(Index:Integer):TDrawLine;
Procedure Put(Index:Integer; Const Value:TDrawLine);
public
Function Last:TDrawLine;
property Line[Index:Integer]:TDrawLine read Get write Put; default;
end;
TDrawLineHandle=(chNone,chStart,chEnd,chSeries);
TDrawLineSelecting=procedure( Sender:TDrawLineTool; Line:TDrawLine;
var AllowSelect:Boolean) of object;
// Draw Line tool, use it to allow the end-user to draw, drag, select
// and move lines.
TDrawLineTool=class(TTeeCustomToolSeries)
private
FButton : TMouseButton;
FEnableDraw : Boolean;
FEnableSelect : Boolean;
FLines : TDrawLines;
FOnDraggedLine: TNotifyEvent;
FOnDragLine : TNotifyEvent;
FOnNewLine : TNotifyEvent;
FOnSelect : TNotifyEvent;
FOnSelecting : TDrawLineSelecting;
IDrawing : Boolean;
IPoint : TPoint;
ISelected : TDrawLine;
Procedure DrawLine(Const StartPos,EndPos:TPoint; AStyle:TDrawLineStyle);
Function InternalClicked(X,Y:Integer; AHandle:TDrawLineHandle):TDrawLine;
Procedure SetEnableSelect(Value:Boolean);
Procedure SetLines(Const Value:TDrawLines);
Procedure SetSelected(Value:TDrawLine);
Procedure RedrawLine(ALine:TDrawLine);
protected
IHandle : TDrawLineHandle;
Procedure ChartEvent(AEvent:TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
AButton:TMouseButton;
AShift: TShiftState; X, Y: Integer); override;
Procedure ClipDrawingRegion; virtual;
class function GetEditorClass: String; override;
public
FromPoint : TPoint;
ToPoint : TPoint;
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Function AxisPoint(Const P:TFloatPoint):TPoint;
Function Clicked(X,Y:Integer):TDrawLine;
Procedure DeleteSelected;
Function ScreenPoint(P:TPoint):TFloatPoint;
class Function Description:String; override;
property Selected:TDrawLine read ISelected write SetSelected;
published
property Active;
property Button:TMouseButton read FButton write FButton default mbLeft;
property EnableDraw:Boolean read FEnableDraw write FEnableDraw default True;
property EnableSelect:Boolean read FEnableSelect write SetEnableSelect default True;
property Lines:TDrawLines read FLines write SetLines;
property Pen;
property Series;
{ events }
property OnDraggedLine:TNotifyEvent read FOnDraggedLine write FOnDraggedLine; { 5.01 }
property OnDragLine:TNotifyEvent read FOnDragLine write FOnDragLine;
property OnNewLine:TNotifyEvent read FOnNewLine write FOnNewLine;
property OnSelect:TNotifyEvent read FOnSelect write FOnSelect;
property OnSelecting:TDrawLineSelecting read FOnSelecting write FOnSelecting; { 5.03 }
end;
{ This variable can be used to set the default "DrawLine" class used by
TDrawLineTool when creating new lines }
TDrawLineClass=class of TDrawLine;
Var
TeeDrawLineClass:TDrawLineClass=TDrawLine; { 5.02 }
type
TMarkToolMouseAction = (mtmMove, mtmClick);
TMarksTipTool=class;
TMarksTipGetText=procedure(Sender:TMarksTipTool; Var Text:String) of object;
// Marks tip tool, use it to display "tips" or "hints" when the end-user
// moves or clicks the mouse over a series point.
TMarksTipTool=class(TTeeCustomToolSeries)
private
FMouseAction : TMarkToolMouseAction;
FOnGetText : TMarksTipGetText;
FStyle : TSeriesMarksStyle;
Procedure SetMouseAction(Value:TMarkToolMouseAction);
function GetMouseDelay: Integer;
procedure SetMouseDelay(const Value: Integer);
protected
Function Chart:TCustomChart;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
Procedure SetActive(Value:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
published
property Active;
property MouseAction:TMarkToolMouseAction read FMouseAction
write SetMouseAction default mtmMove;
property MouseDelay:Integer read GetMouseDelay
write SetMouseDelay default 500; { 5.02 }
property Series;
property Style:TSeriesMarksStyle read FStyle write FStyle default smsLabel;
property OnGetText:TMarksTipGetText read FOnGetText write FOnGetText;
end;
TNearestToolStyle=(hsNone,hsCircle,hsRectangle,hsDiamond);
// Nearest tool, use it to display a graphical signal when the mouse is
// moving near a series point.
TNearestTool=class(TTeeCustomToolSeries)
private
FFullRepaint: Boolean;
FLinePen : TChartPen;
FSize : Integer;
FStyle : TNearestToolStyle;
FOnChange : TNotifyEvent;
IMouse : TPoint;
Function GetDrawLine:Boolean;
procedure PaintHint;
procedure SetDrawLine(const Value: Boolean);
procedure SetLinePen(const Value: TChartPen);
procedure SetSize(const Value: Integer);
procedure SetStyle(const Value: TNearestToolStyle);
function ZAxisCalc(const Value:Double):Integer;
protected
procedure ChartEvent(AEvent: TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
public
Point : Integer;
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
class Function GetNearestPoint(Series:TChartSeries; X,Y:Integer):Integer; overload;
class Function GetNearestPoint(Series:TChartSeries; X,Y:Integer; IncludeNulls:Boolean):Integer; overload;
class Function Description:String; override;
published
property Active;
property Brush;
property DrawLine:Boolean read GetDrawLine write SetDrawLine default True;
property FullRepaint:Boolean read FFullRepaint write FFullRepaint default True;
property LinePen:TChartPen read FLinePen write SetLinePen; // 7.0
property Pen;
property Series;
property Size:Integer read FSize write SetSize default 20;
property Style:TNearestToolStyle read FStyle write SetStyle default hsCircle;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
end;
TColorLineTool=class;
// Color band tool, use it to display a coloured rectangle (band)
// at the specified axis and position.
TColorBandTool=class(TTeeCustomToolAxis)
private
FColor : TColor;
FCursor : TCursor; // 7.0
FDrawBehind : Boolean;
FDrawBehindAxes: Boolean;
FEnd : Double;
FGradient : TChartGradient;
FOnClick : TMouseEvent;
FStart : Double;
FTransparency : TTeeTransparency;
FLineEnd : TColorLineTool;
FLineStart : TColorLineTool;
procedure DragLine(Sender:TColorLineTool);
procedure EndDragLine(Sender:TColorLineTool);
function GetEndLinePen: TChartPen;
function GetResizeEnd: Boolean;
function GetResizeStart: Boolean;
function GetStartLinePen: TChartPen;
Function NewColorLine:TColorLineTool;
procedure PaintBand;
Procedure SetColor(Value:TColor);
procedure SetDrawBehind(const Value: Boolean);
procedure SetDrawBehindAxes(const Value: Boolean);
procedure SetEnd(const Value: Double);
procedure SetEndLinePen(const Value: TChartPen);
procedure SetGradient(const Value: TChartGradient);
procedure SetLines;
procedure SetResizeEnd(const Value: Boolean);
procedure SetResizeStart(const Value: Boolean);
procedure SetStart(const Value: Double);
procedure SetStartLinePen(const Value: TChartPen);
procedure SetTransparency(const Value: TTeeTransparency);
protected
procedure ChartEvent(AEvent: TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
procedure Loaded; override;
procedure SetAxis(const Value: TChartAxis); override;
procedure SetParentChart(const Value: TCustomAxisPanel); override;
Function ZPosition:Integer;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Function BoundsRect:TRect; // 6.02
Function Clicked(X,Y:Integer):Boolean; // 6.02
class Function Description:String; override;
property StartLine:TColorLineTool read FLineStart;
property EndLine:TColorLineTool read FLineEnd;
published
property Active;
property Axis;
property Brush;
property Color:TColor read FColor write SetColor default clWhite;
property Cursor:TCursor read FCursor write FCursor default crDefault; // 7.0
property DrawBehind:Boolean read FDrawBehind write SetDrawBehind default True;
property DrawBehindAxes:Boolean read FDrawBehindAxes write SetDrawBehindAxes default False; // 7.0
property EndLinePen:TChartPen read GetEndLinePen write SetEndLinePen;
property EndValue:Double read FEnd write SetEnd;
property Gradient:TChartGradient read FGradient write SetGradient;
property Pen;
property ResizeEnd:Boolean read GetResizeEnd write SetResizeEnd default False;
property ResizeStart:Boolean read GetResizeStart write SetResizeStart default False;
property StartLinePen:TChartPen read GetStartLinePen write SetStartLinePen;
property StartValue:Double read FStart write SetStart;
property Transparency:TTeeTransparency read FTransparency
write SetTransparency default 0;
// Events
property OnClick:TMouseEvent read FOnClick write FOnClick; // 6.02
end;
TGridBandBrush=class(TChartBrush)
private
FBackColor : TColor;
FTransp : TTeeTransparency;
procedure SetBackColor(const Value: TColor);
procedure SetTransp(const Value: TTeeTransparency);
published
property BackColor:TColor read FBackColor write SetBackColor default clNone;
property Transparency:TTeeTransparency read FTransp write SetTransp default 0;
end;
// TGridBandTool
// Draws alternate color bands on axis grid space.
TGridBandTool=class(TTeeCustomToolAxis)
private
FBand1 : TGridBandBrush;
FBand2 : TGridBandBrush;
Procedure DrawGrids(Sender:TChartAxis);
Procedure SetBand1(Value:TGridBandBrush);
Procedure SetBand2(Value:TGridBandBrush);
protected
class function GetEditorClass: String; override;
procedure SetAxis(const Value: TChartAxis); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
Function BandBackColor(ABand:TGridBandBrush):TColor;
class Function Description:String; override;
published
property Active;
property Axis;
property Band1:TGridBandBrush read FBand1 write SetBand1;
property Band2:TGridBandBrush read FBand2 write SetBand2;
end;
TColorLineStyle=(clCustom,clMaximum,clCenter,clMinimum);
TColorLineToolOnDrag=procedure(Sender:TColorLineTool) of object;
// Color line tool, use it to display a vertical or horizontal line
// at the specified axis and position.
// The line can be optionally dragged at runtime.
TColorLineTool=class(TTeeCustomToolAxis)
private
FAllowDrag : Boolean;
FDragRepaint : Boolean;
FDraw3D : Boolean;
FDrawBehind : Boolean;
FNoLimitDrag : Boolean;
FOnBeginDragLine: TColorLineToolOnDrag;
FOnDragLine : TColorLineToolOnDrag;
FOnEndDragLine : TColorLineToolOnDrag;
FStyle : TColorLineStyle;
FValue : Double;
IDragging : Boolean;
IParent : TCustomAxisPanel;
InternalOnEndDragLine : TColorLineToolOnDrag;
Function Chart:TCustomAxisPanel;
Procedure DrawColorLine(Back:Boolean); { 5.02 }
procedure SetDraw3D(const Value: Boolean);
procedure SetDrawBehind(const Value: Boolean);
procedure SetStyle(const Value: TColorLineStyle);
procedure SetValue(const AValue: Double);
protected
Function CalcValue:Double;
procedure ChartEvent(AEvent: TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
procedure DoEndDragLine; virtual; { 5.02 }
class function GetEditorClass: String; override;
procedure InternalDrawLine(Back:Boolean);
public
Constructor Create(AOwner:TComponent); override;
Procedure Assign(Source:TPersistent); override;
Function Clicked(x,y:Integer):Boolean;
class Function Description:String; override;
Function LimitValue(const AValue:Double):Double; // 7.0 moved from private
published
property Active;
property Axis;
property AllowDrag:Boolean read FAllowDrag write FAllowDrag default True;
property DragRepaint:Boolean read FDragRepaint write FDragRepaint default False;
property Draw3D:Boolean read FDraw3D write SetDraw3D default True;
property DrawBehind:Boolean read FDrawBehind write SetDrawBehind default False;
property NoLimitDrag:Boolean read FNoLimitDrag write FNoLimitDrag default False;
property Pen;
property Style:TColorLineStyle read FStyle write SetStyle default clCustom;
property Value:Double read FValue write SetValue;
property OnBeginDragLine:TColorLineToolOnDrag read FOnBeginDragLine write FOnBeginDragLine; // 7.0
property OnDragLine:TColorLineToolOnDrag read FOnDragLine write FOnDragLine;
property OnEndDragLine:TColorLineToolOnDrag read FOnEndDragLine write FOnEndDragLine;
end;
// Rotate tool, use it to allow the end-user to do 3D rotation of the chart
// at runtime by dragging the chart using the specified mouse button.
TRotateToolStyles = ( rsAll, rsRotation, rsElevation );
TRotateTool=class(TTeeCustomTool)
private
FButton : TMouseButton;
FInverted : Boolean;
FOnRotate : TNotifyEvent;
FStyle : TRotateToolStyles;
IOldX : Integer;
IOldY : Integer;
IDragging : Boolean;
IFirstTime : Boolean;
IOldRepaint: Boolean;
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
AButton:TMouseButton;
AShift: TShiftState; X, Y: Integer); override;
class function GetEditorClass: String; override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
class function ElevationChange(FullRotation:Boolean; AAngle,AChange:Integer):Integer;
class function RotationChange(FullRotation:Boolean; AAngle,AChange:Integer):Integer;
published
property Active;
property Button:TMouseButton read FButton write FButton default mbLeft;
property Inverted:Boolean read FInverted write FInverted default False;
property Pen;
property Style:TRotateToolStyles read FStyle write FStyle default rsAll;
property OnRotate:TNotifyEvent read FOnRotate write FOnRotate;
end;
// Chart Image tool, use it to display a picture using the specified
// Series axes as boundaries. When the axis are zoomed or scrolled,
// the picture will follow the new boundaries.
TChartImageTool=class(TTeeCustomToolSeries)
private
FPicture : TPicture;
procedure SetPicture(const Value: TPicture);
protected
procedure ChartEvent(AEvent: TChartToolEvent); override;
class function GetEditorClass: String; override;
procedure SetSeries(const Value: TChartSeries); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
class Function Description:String; override;
published
property Active;
property Picture:TPicture read FPicture write SetPicture;
property Series;
end;
// A Shape object (with Left and Top), publishing all properties.
TTeeShapePosition=class(TTeeCustomShapePosition)
published
property Bevel;
property BevelWidth;
property Brush;
property Color;
property CustomPosition;
property Font;
property Frame;
property Gradient;
property Left;
property Shadow;
property ShapeStyle;
property Top;
property Transparency;
property Transparent;
property Visible default True;
end;
TAnnotationTool=class;
TAnnotationPosition=(ppLeftTop,ppLeftBottom,ppRightTop,ppRightBottom);
TAnnotationClick=procedure( Sender:TAnnotationTool;
Button:TMouseButton;
Shift: TShiftState;
X, Y: Integer) of object;
TAnnotationCallout=class(TCallout)
private
FX : Integer;
FY : Integer;
FZ : Integer;
Function CloserPoint(const R:TRect; const P:TPoint):TPoint;
procedure SetX(const Value:Integer);
procedure SetY(const Value:Integer);
procedure SetZ(const Value:Integer);
public
constructor Create(AOwner: TChartSeries);
Procedure Assign(Source:TPersistent); override;
published
property Visible default False;
property XPosition:Integer read FX write SetX default 0;
property YPosition:Integer read FY write SetY default 0;
property ZPosition:Integer read FZ write SetZ default 0;
end;
// Annotation tool, use it to display text anywhere on the chart.
TAnnotationTool=class(TTeeCustomTool)
private
FAutoSize : Boolean; // 7.0
FCallout : TAnnotationCallout;
FCursor : TCursor;
FOnClick : TAnnotationClick; // 5.03
FPosition : TAnnotationPosition;
FPositionUnits: TTeeUnits;
FShape : TTeeShapePosition;
FText : String;
FTextAlign : TAlignment;
function GetHeight: Integer;
function GetWidth: Integer;
function IsNotAutoSize: Boolean;
procedure SetAutoSize(const Value: Boolean);
procedure SetCallout(const Value: TAnnotationCallout);
procedure SetHeight(const Value: Integer);
procedure SetPosition(const Value: TAnnotationPosition);
procedure SetPositionUnits(const Value: TTeeUnits);
procedure SetShape(const Value: TTeeShapePosition);
procedure SetTextAlign(const Value: TAlignment);
procedure SetWidth(const Value: Integer);
protected
Procedure ChartEvent(AEvent:TChartToolEvent); override;
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
Procedure DrawText;
Function GetBounds(var NumLines,x,y:Integer):TRect;
class Function GetEditorClass:String; override;
Function GetText:String; virtual;
procedure SetParentChart(const Value: TCustomAxisPanel); override;
Procedure SetText(Const Value:String);
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Function Clicked(x,y:Integer):Boolean;
class Function Description:String; override;
published
property Active;
property AutoSize:Boolean read FAutoSize write SetAutoSize default True; // 7.0
property Callout:TAnnotationCallout read FCallout write SetCallout;
property Cursor:TCursor read FCursor write FCursor default crDefault;
property Position:TAnnotationPosition read FPosition write SetPosition
default ppLeftTop;
property PositionUnits:TTeeUnits read FPositionUnits write SetPositionUnits // 7.0
default muPixels;
property Shape:TTeeShapePosition read FShape write SetShape;
property Text:String read FText write SetText;
property TextAlignment:TAlignment read FTextAlign
write SetTextAlign default taLeftJustify;
property Height: Integer read GetHeight write SetHeight stored IsNotAutoSize; // 7.0
property Width: Integer read GetWidth write SetWidth stored IsNotAutoSize; // 7.0
property OnClick:TAnnotationClick read FOnClick write FOnClick; // 5.03
end;
TSeriesAnimationTool=class;
TSeriesAnimationStep=procedure(Sender:TSeriesAnimationTool; Step:Integer) of object;
TSeriesAnimationLoop=(salNo, salOneWay, salCircular);
TSeriesAnimationTool=class(TTeeCustomToolSeries)
private
FBackup : TChartSeries;
FDrawEvery : Integer;
FLoop : TSeriesAnimationLoop;
FStartValue : Double;
FSteps : Integer;
FStartAtMin : Boolean;
{ events }
FOnStep : TSeriesAnimationStep;
{ internal }
IStopped : Boolean;
protected
class Function GetEditorClass:String; override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
procedure Execute; virtual;
function Running:Boolean;
procedure Stop;
published
property DrawEvery:Integer read FDrawEvery write FDrawEvery default 0;
property Loop:TSeriesAnimationLoop read FLoop write FLoop default salNo;
property Series;
property StartAtMin:Boolean read FStartAtMin write FStartAtMin default True;
property StartValue:Double read FStartValue write FStartValue;
property Steps:Integer read FSteps write FSteps default 100;
{ events }
property OnStep:TSeriesAnimationStep read FOnStep write FOnStep;
end;
TRectangleTool=class(TAnnotationTool)
private
FOnDragging : TNotifyEvent;
FOnResizing : TNotifyEvent;
P : TPoint;
IDrag : Boolean;
IEdge : Integer;
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
public
Constructor Create(AOwner:TComponent); override;
Function Bitmap(ChartOnly:Boolean=False):TBitmap;
Function ClickedEdge(x,y:Integer):Integer;
class Function Description:String; override;
published
property OnDragging:TNotifyEvent read FOnDragging write FOnDragging;
property OnResizing:TNotifyEvent read FOnResizing write FOnResizing;
end;
TClipSeriesTool=class(TTeeCustomToolSeries)
private
IActive : Boolean;
procedure AddClip(Sender: TObject);
procedure RemoveClip(Sender: TObject);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetSeries(const Value: TChartSeries); override;
public
class Function Description:String; override;
published
property Active;
property Series;
end;
implementation
Uses {$IFDEF CLX}
QForms,
{$ELSE}
Forms,
{$ENDIF}
Math, TeeConst, TeeProCo;
{ TCursorTool }
Constructor TCursorTool.Create(AOwner:TComponent);
begin
inherited;
FStyle:=cssBoth;
IPoint.X:=-1;
IPoint.Y:=-1;
IOldSnap:=-1;
end;
Procedure TCursorTool.CalcValuePositions(X,Y:Integer);
begin
if UseSeriesZ then
ParentChart.Canvas.Calculate2DPosition(x,y,Z);
Case IDragging of
ccVertical : IXValue:=GetHorizAxis.CalcPosPoint(X);
ccHorizontal: IYValue:=GetVertAxis.CalcPosPoint(Y);
else
begin
IXValue:=GetHorizAxis.CalcPosPoint(X);
IYValue:=GetVertAxis.CalcPosPoint(Y);
end;
end;
end;
Procedure TCursorTool.CalcScreenPositions;
var tmpSnap : Integer;
begin
if (IPoint.X=-1) or (IPoint.Y=-1) then
begin
With GetHorizAxis do IPoint.X:=(IStartPos+IEndPos) div 2;
With GetVertAxis do IPoint.Y:=(IStartPos+IEndPos) div 2;
CalcValuePositions(IPoint.X,IPoint.Y);
tmpSnap:=SnapToPoint;
CalcScreenPositions;
Changed(tmpSnap);
end
else
begin
IPoint.X:=GetHorizAxis.CalcPosValue(IXValue);
IPoint.Y:=GetVertAxis.CalcPosValue(IYValue);
end;
end;
Procedure TCursorTool.Changed(SnapPoint:Integer);
begin
if Assigned(FOnChange) then
FOnChange(Self,IPoint.X,IPoint.Y,IXValue,IYValue,Series,SnapPoint);
end;
class Function TCursorTool.GetEditorClass:String;
begin
result:='TCursorToolEditor';
end;
class Function TCursorTool.Description:String;
begin
result:=TeeMsg_CursorTool;
end;
Function TeeGetFirstLastSeries(Series:TChartSeries;
Var AMin,AMax:Integer):Boolean; { 5.01 }
begin
AMin:=Series.FirstValueIndex;
if AMin<0 then AMin:=0;
AMax:=Series.LastValueIndex;
if AMax<0 then AMax:=Series.Count-1
else
if AMax>=Series.Count then AMax:=Series.Count-1; { 5.03 }
result:=(Series.Count>0) and (AMin<=Series.Count) and (AMax<=Series.Count);
end;
Function TCursorTool.NearestPoint(AStyle:TCursorToolStyle;
Var Difference:Double):Integer;
var t : Integer;
tmpDif : Double;
tmpMin : Integer;
tmpMax : Integer;
begin
result:=-1;
Difference:=-1;
if TeeGetFirstLastSeries(Series,tmpMin,tmpMax) then
for t:=tmpMin to tmpMax do
begin
With Series do
Case AStyle of
cssHorizontal: tmpDif:=Abs(IYValue-YValues.Value[t]);
cssVertical : tmpDif:=Abs(IXValue-XValues.Value[t]);
else
tmpDif:=Sqrt(Sqr(IXValue-XValues.Value[t])+Sqr(IYValue-YValues.Value[t]));
end;
if (Difference=-1) or (tmpDif<Difference) then
begin
Difference:=tmpDif;
result:=t;
end;
end;
end;
Function TCursorTool.SnapToPoint:Integer;
var Difference : Double;
begin
if Assigned(Series) and FSnap then result:=NearestPoint(FStyle,Difference)
else result:=-1;
if result<>-1 then
Case FStyle of
cssHorizontal: IYValue:=Series.YValues.Value[result];
cssVertical : IXValue:=Series.XValues.Value[result];
else
begin
IXValue:=Series.XValues.Value[result];
IYValue:=Series.YValues.Value[result]
end;
end;
end;
Function TCursorTool.GetAxisRect:TRect;
begin
if UseChartRect then result:=ParentChart.ChartRect
else
begin
With GetHorizAxis do
begin
result.Left:=IStartPos;
result.Right:=IEndPos;
end;
With GetVertAxis do
begin
result.Top:=IStartPos;
result.Bottom:=IEndPos;
end;
if Assigned(FOnGetAxisRect) then FOnGetAxisRect(Self,result);
end;
end;
Function TCursorTool.Z:Integer;
begin
if UseSeriesZ and Assigned(Series) then
result:=Series.StartZ
else
result:=0;
end;
procedure TCursorTool.RedrawCursor;
Procedure DrawCursorLines(Draw3D:Boolean; Const R:TRect; X,Y:Integer);
Procedure DrawHorizontal;
begin
With ParentChart.Canvas do
if Draw3D then HorizLine3D(R.Left,R.Right,Y,Z)
else DoHorizLine(R.Left,R.Right,Y);
end;
Procedure DrawVertical;
begin
With ParentChart.Canvas do
if Draw3D then VertLine3D(X,R.Top,R.Bottom,Z)
else DoVertLine(X,R.Top,R.Bottom);
end;
begin
Case FStyle of
cssHorizontal: DrawHorizontal;
cssVertical : DrawVertical;
else
begin
DrawHorizontal;
DrawVertical;
end;
end;
end;
var tmpColor : TColor;
begin
if Assigned(ParentChart) then
begin
tmpColor:=ParentChart.Color;
if tmpColor=clTeeColor then tmpColor:=clBtnFace;
With ParentChart.Canvas do
begin
AssignVisiblePenColor(Self.Pen,Self.Pen.Color xor ColorToRGB(tmpColor));
Brush.Style:=bsClear;
Pen.Mode:=pmXor;
DrawCursorLines(ParentChart.View3D,GetAxisRect,IPoint.X,IPoint.Y);
Pen.Mode:=pmCopy;
ParentChart.Canvas.Invalidate;
end;
end;
end;
Function TCursorTool.InAxisRectangle(x,y:Integer):Boolean;
begin
if UseSeriesZ then
ParentChart.Canvas.Calculate2DPosition(x,y,Z);
result:=PointInRect(GetAxisRect,x,y);
end;
Procedure TCursorTool.ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer);
Procedure MouseMove;
var tmpSnap : Integer;
tmp : TCursorClicked;
begin
{ if mouse button is pressed and dragging then... }
if ((IDragging<>ccNone) or FollowMouse) and InAxisRectangle(X,Y) then
begin
RedrawCursor; { hide the cursor }
CalcValuePositions(X,Y);
tmpSnap:=SnapToPoint; { snap to the nearest point of SnapSeries }
{ draw again the cursor at the new position }
CalcScreenPositions;
RedrawCursor;
Changed(tmpSnap);
if Assigned(FOnSnapChange) and (IOldSnap<>tmpSnap) then // 7.0
FOnSnapChange(Self,IPoint.X,IPoint.Y,IXValue,IYValue,Series,tmpSnap);
IOldSnap:=tmpSnap;
end
else
begin { mouse button is not pressed, user is not dragging the cursor }
{ change the mouse cursor when passing over the Cursor }
tmp:=Clicked(x,y);
case tmp of
ccHorizontal : ParentChart.Cursor:=crVSplit;
ccVertical : ParentChart.Cursor:=crHSplit;
ccBoth : ParentChart.Cursor:=crSizeAll;
end;
ParentChart.CancelMouse:=tmp<>ccNone;
end;
end;
begin
Case AEvent of
cmeUp: IDragging:=ccNone;
cmeMove: MouseMove;
cmeDown: if not FFollowMouse then
begin
IDragging:=Clicked(x,y);
if IDragging<>ccNone then ParentChart.CancelMouse:=True;
end;
end;
end;
Function TCursorTool.Clicked(x,y:Integer):TCursorClicked;
var tmp : TPoint;
begin
result:=ccNone;
if InAxisRectangle(x,y) then
begin
tmp:=IPoint;
if UseSeriesZ then
ParentChart.Canvas.Calculate2DPosition(x,y,Z);
if (FStyle=cssBoth) and (Abs(Y-tmp.Y)<TeeClickTolerance)
and (Abs(X-tmp.X)<TeeClickTolerance) then
result:=ccBoth
else
if ((FStyle=cssHorizontal) or (FStyle=cssBoth))
and (Abs(Y-tmp.Y)<TeeClickTolerance) then
result:=ccHorizontal
else
if ((FStyle=cssVertical) or (FStyle=cssBoth))
and (Abs(X-tmp.X)<TeeClickTolerance) then
result:=ccVertical
end;
end;
Procedure TCursorTool.SetStyle(Value:TCursorToolStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
SnapToPoint;
Repaint;
end;
end;
procedure TCursorTool.SetSeries(const Value: TChartSeries);
begin
inherited;
if Assigned(Series) and (not (csLoading in ComponentState)) then
begin
SnapToPoint;
Repaint;
end;
end;
procedure TCursorTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if (AEvent=cteAfterDraw) then
begin
CalcScreenPositions;
RedrawCursor;
end;
end;
procedure TCursorTool.SetXValue(const Value: Double);
begin
if IXValue<>Value then
begin
IXValue:=Value;
DoChange;
end;
end;
procedure TCursorTool.DoChange;
begin
CalcScreenPositions;
Changed(-1);
Repaint;
end;
procedure TCursorTool.SetYValue(const Value: Double);
begin
if IYValue<>Value then
begin
IYValue:=Value;
DoChange;
end;
end;
procedure TCursorTool.SetUseChartRect(const Value: Boolean);
begin
SetBooleanProperty(FUseChartRect,Value);
end;
procedure TCursorTool.SetUseSeriesZ(const Value: Boolean);
begin
SetBooleanProperty(FUseSeriesZ,Value);
end;
{ TDragMarksTool }
class function TDragMarksTool.Description: String;
begin
result:=TeeMsg_DragMarksTool;
end;
Procedure TDragMarksTool.ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer);
Procedure MouseMove;
Procedure CheckCursor;
Function CheckCursorSeries(ASeries:TChartSeries):Boolean;
begin
result:=ASeries.Active and ASeries.Marks.Visible and
(ASeries.Marks.Clicked(x,y)<>-1);
end;
var tmp : Boolean;
t : Integer;
begin
tmp:=False;
if Assigned(Series) then tmp:=CheckCursorSeries(Series)
else
With ParentChart do
for t:=SeriesCount-1 downto 0 do
begin
tmp:=CheckCursorSeries(Series[t]);
if tmp then break;
end;
if tmp then
begin
ParentChart.Cursor:=crHandPoint;
ParentChart.CancelMouse:=True;
end;
end;
var DifX : Integer;
DifY : Integer;
begin
if not Assigned(IPosition) then CheckCursor
else
With IPosition do
begin
DifX:=X-IOldX;
DifY:=Y-IOldY;
Custom:=True;
Inc(LeftTop.X,DifX);
Inc(LeftTop.Y,DifY);
Inc(ArrowTo.X,DifX);
Inc(ArrowTo.Y,DifY);
IOldX:=X;
IOldY:=Y;
ParentChart.CancelMouse:=True;
Repaint;
end;
end;
Procedure MouseDown;
Function CheckSeries(ASeries:TChartSeries):Integer;
begin
result:=-1;
if ASeries.Active then
begin
result:=ASeries.Marks.Clicked(x,y);
if result<>-1 then
begin
ISeries:=ASeries;
IPosition:=ISeries.Marks.Positions.Position[result];
Exit;
end;
end;
end;
var t : Integer;
begin
if Assigned(Series) then CheckSeries(Series)
else
With ParentChart do
for t:=SeriesCount-1 downto 0 do
if CheckSeries(Series[t])<>-1 then break;
if Assigned(IPosition) then
begin
IOldX:=X;
IOldY:=Y;
end;
end;
begin
Case AEvent of
cmeUp : IPosition:=nil;
cmeDown: begin
MouseDown;
if Assigned(IPosition) then ParentChart.CancelMouse:=True;
end;
cmeMove: MouseMove;
end;
end;
class function TDragMarksTool.GetEditorClass: String;
begin
result:='TDragMarksToolEditor';
end;
{ TAxisArrowTool }
Constructor TAxisArrowTool.Create(AOwner: TComponent);
begin
inherited;
FLength:=16;
FPosition:=aaBoth;
FScrollPercent:=10;
end;
procedure TAxisArrowTool.ChartEvent(AEvent: TChartToolEvent);
Var tmpZ : Integer;
Procedure DrawArrow(APos,ALength:Integer);
var P0 : TPoint;
P1 : TPoint;
begin
With Axis do
if Horizontal then
begin
P0:=TeePoint(APos+ALength,PosAxis);
P1:=TeePoint(APos,PosAxis)
end
else
begin
P0:=TeePoint(PosAxis,APos+ALength);
P1:=TeePoint(PosAxis,APos);
end;
ParentChart.Canvas.Arrow(True,P0,P1,8,8,tmpZ);
end;
begin
inherited;
if (AEvent=cteAfterDraw) and Assigned(Axis) then
begin
ParentChart.Canvas.AssignBrush(Self.Brush,Self.Brush.Color);
ParentChart.Canvas.AssignVisiblePen(Self.Pen);
if ParentChart.View3D and Axis.OtherSide then
tmpZ:=ParentChart.Width3D
else
tmpZ:=0;
if (FPosition=aaStart) or (FPosition=aaBoth) then
DrawArrow(Axis.IStartPos,Length);
if (FPosition=aaEnd) or (FPosition=aaBoth) then
DrawArrow(Axis.IEndPos,-Length);
end;
end;
class function TAxisArrowTool.Description: String;
begin
result:=TeeMsg_AxisArrowTool;
end;
procedure TAxisArrowTool.SetLength(const Value: Integer);
begin
SetIntegerProperty(FLength,Value);
end;
Function TAxisArrowTool.ClickedArrow(x,y:Integer):Integer;
Procedure Check(Pos1,Pos2:Integer);
begin
{ to-do: right/top axis Z ! }
With Axis do
if (Abs(Pos1-PosAxis)<TeeClickTolerance) then
begin
if (FPosition=aaStart) or (FPosition=aaBoth) then
if (Pos2>IStartPos) and (Pos2<IStartPos+Length) then
begin
result:=0;
exit;
end;
if (FPosition=aaEnd) or (FPosition=aaBoth) then
if (Pos2<IEndPos) and (Pos2>IEndPos-Length) then
begin
result:=1;
exit;
end;
end;
end;
begin
result:=-1;
if Axis.Horizontal then Check(y,x) else Check(x,y);
end;
Procedure TAxisArrowTool.ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer);
Procedure DoScroll(const ADelta:Double);
// Returns True when there is at least on series in the chart,
// that has "both" axis associated (left and right, or top and bottom).
// The OtherAxis parameter returns the "other" axis (right axis if
// series axis is left, left axis if series axis is right, and so on).
Function AnySeriesBothAxis(Axis:TChartAxis; Var OtherAxis:TChartAxis):Boolean;
var t : Integer;
begin
result:=False;
for t:=0 to ParentChart.SeriesCount-1 do
if ParentChart[t].AssociatedToAxis(Axis) then
begin
if Axis.Horizontal then
begin
if ParentChart[t].HorizAxis=aBothHorizAxis then
begin
if Axis=ParentChart.TopAxis then OtherAxis:=ParentChart.BottomAxis
else OtherAxis:=ParentChart.TopAxis;
result:=True;
end;
end
else
begin
if ParentChart[t].VertAxis=aBothVertAxis then
begin
if Axis=ParentChart.LeftAxis then OtherAxis:=ParentChart.RightAxis
else OtherAxis:=ParentChart.LeftAxis;
result:=True;
end;
end;
end;
end;
var tmp : Boolean;
tmpMin : Double;
tmpMax : Double;
tmpAxis2 : TChartAxis;
begin
tmp:=True;
if Assigned(TCustomChart(ParentChart).OnAllowScroll) then
begin
tmpMin:=Axis.Minimum+ADelta;
tmpMax:=Axis.Maximum+ADelta;
TCustomChart(ParentChart).OnAllowScroll(Axis,tmpMin,tmpMax,tmp);
end;
if tmp then
begin
Axis.Scroll(ADelta,False);
if AnySeriesBothAxis(Axis,tmpAxis2) then
tmpAxis2.Scroll(ADelta,False);
With TCustomChart(Axis.ParentChart) do
if Assigned(OnScroll) then OnScroll(Axis.ParentChart); { 5.01 }
end;
end;
var tmp : Integer;
Delta : Double;
begin
if Assigned(Axis) and Axis.Visible then
Case AEvent of
cmeDown: if ScrollPercent<>0 then
With Axis do
begin
tmp:=ClickedArrow(x,y);
Delta:=(Maximum-Minimum)*ScrollPercent/100.0; // 5.02
if ScrollInverted then Delta:=-Delta; // 5.02
if tmp=0 then DoScroll(Delta)
else
if tmp=1 then DoScroll(-Delta);
if (tmp=0) or (tmp=1) then ParentChart.CancelMouse:=True;
if Assigned(FOnClick) and (tmp<>-1) then
FOnClick(Self,tmp=0); // 6.0
end;
cmeMove: begin
if ClickedArrow(x,y)<>-1 then
begin
ParentChart.Cursor:=crHandPoint;
ParentChart.CancelMouse:=True;
end;
end;
end;
end;
class function TAxisArrowTool.GetEditorClass: String;
begin
result:='TAxisArrowToolEditor';
end;
procedure TAxisArrowTool.SetPosition(const Value: TAxisArrowToolPosition);
begin
if FPosition<>Value then
begin
FPosition:=Value;
Repaint;
end;
end;
{ TDrawLine }
Function TDrawLine.StartHandle:TRect;
begin
With Parent.AxisPoint(StartPos) do result:=TeeRect(X-3,Y-3,X+3,Y+3);
end;
Function TDrawLine.EndHandle:TRect;
begin
With Parent.AxisPoint(EndPos) do result:=TeeRect(X-3,Y-3,X+3,Y+3);
end;
Procedure TDrawLine.DrawHandles;
begin
With Parent.ParentChart.Canvas do
begin
Brush.Style:=bsSolid;
if Parent.ParentChart.Color=clBlack then Brush.Color:=clSilver
else Brush.Color:=clBlack;
Pen.Style:=psClear;
RectangleWithZ(StartHandle,0);
RectangleWithZ(EndHandle,0);
end;
end;
{ TDrawLines }
function TDrawLines.Get(Index: Integer): TDrawLine;
begin
result:=TDrawLine(inherited Items[Index]);
end;
function TDrawLines.Last: TDrawLine;
begin
if Count=0 then result:=nil else result:=Get(Count-1);
end;
procedure TDrawLines.Put(Index: Integer; const Value: TDrawLine);
begin
Items[Index].Assign(Value);
end;
{ TDrawLine }
Constructor TDrawLine.CreateXY(Collection:TCollection; const X0, Y0, X1, Y1: Double);
begin
Create(Collection);
StartPos.X:=X0;
StartPos.Y:=Y0;
EndPos.X:=X1;
EndPos.Y:=Y1;
end;
Destructor TDrawLine.Destroy; { 5.02 }
begin
if Self=Parent.ISelected then Parent.ISelected:=nil;
inherited;
end;
function TDrawLine.GetPen: TChartPen;
begin
result:=Parent.Pen;
end;
procedure TDrawLine.Assign(Source: TPersistent);
begin
if Source is TDrawLine then
With TDrawLine(Source) do
Begin
Self.StartPos :=StartPos;
Self.EndPos :=EndPos;
Self.FStyle :=FStyle;
end
else inherited;
end;
type TOwnedCollectionAccess=class(TOwnedCollection);
function TDrawLine.GetParent: TDrawLineTool;
begin
result:=TDrawLineTool(TOwnedCollectionAccess(Collection).GetOwner);
end;
function TDrawLine.GetX0: Double;
begin
result:=StartPos.X;
end;
function TDrawLine.GetX1: Double;
begin
result:=EndPos.X;
end;
function TDrawLine.GetY0: Double;
begin
result:=StartPos.Y;
end;
function TDrawLine.GetY1: Double;
begin
result:=EndPos.Y;
end;
Procedure TDrawLine.SetStyle(Value:TDrawLineStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Parent.Repaint;
end;
end;
procedure TDrawLine.SetX0(const Value: Double);
begin
Parent.SetDoubleProperty(StartPos.X,Value);
end;
procedure TDrawLine.SetX1(const Value: Double);
begin
Parent.SetDoubleProperty(EndPos.X,Value);
end;
procedure TDrawLine.SetY0(const Value: Double);
begin
Parent.SetDoubleProperty(StartPos.Y,Value);
end;
procedure TDrawLine.SetY1(const Value: Double);
begin
Parent.SetDoubleProperty(EndPos.Y,Value);
end;
{ TDrawLineTool }
Constructor TDrawLineTool.Create(AOwner: TComponent);
begin
inherited;
FButton:=mbLeft;
FLines:=TDrawLines.Create(Self,TDrawLine);
FEnableDraw:=True;
FEnableSelect:=True;
ISelected:=nil;
IHandle:=chNone;
end;
Destructor TDrawLineTool.Destroy;
begin
ISelected:=nil;
FLines.Free;
inherited;
end;
Procedure TDrawLineTool.DrawLine( Const StartPos,EndPos:TPoint;
AStyle:TDrawLineStyle);
begin
With ParentChart.Canvas do
if ParentChart.View3D then
begin
Case AStyle of
dlLine: begin
MoveTo3D(StartPos.X,StartPos.Y,0);
LineTo3D(EndPos.X,EndPos.Y,0);
end;
dlHorizParallel: begin
HorizLine3D(StartPos.X,EndPos.X,StartPos.Y,0);
HorizLine3D(StartPos.X,EndPos.X,EndPos.Y,0);
end;
else
begin
VertLine3D(StartPos.X,StartPos.Y,EndPos.Y,0);
VertLine3D(EndPos.X,StartPos.Y,EndPos.Y,0);
end
end;
end
else
Case AStyle of
dlLine: Line(StartPos.X,StartPos.Y,EndPos.X,EndPos.Y);
dlHorizParallel: begin
DoHorizLine(StartPos.X,EndPos.X,StartPos.Y);
DoHorizLine(StartPos.X,EndPos.X,EndPos.Y);
end;
else
begin
DoVertLine(StartPos.X,StartPos.Y,EndPos.Y);
DoVertLine(EndPos.X,StartPos.Y,EndPos.Y);
end
end;
end;
procedure TDrawLineTool.ChartEvent(AEvent: TChartToolEvent);
var t : Integer;
begin
inherited;
if (AEvent=cteAfterDraw) and (Lines.Count>0) then
begin
with ParentChart do
begin
Canvas.BackMode:=cbmTransparent;
ClipDrawingRegion;
end;
for t:=0 to Lines.Count-1 do
With Lines[t] do
begin
ParentChart.Canvas.AssignVisiblePen(Pen);
DrawLine(AxisPoint(StartPos),AxisPoint(EndPos),Style);
end;
if Assigned(ISelected) then ISelected.DrawHandles;
ParentChart.Canvas.UnClipRectangle;
end;
end;
Procedure TDrawLineTool.ClipDrawingRegion;
var R : TRect;
begin
if Assigned(Series) then
With Series do
R:=TeeRect(GetHorizAxis.IStartPos,GetVertAxis.IStartPos,
GetHorizAxis.IEndPos,GetVertAxis.IEndPos)
else
R:=ParentChart.ChartRect;
With ParentChart do
if CanClip then Canvas.ClipCube(R,0,Width3D);
end;
Function TDrawLineTool.InternalClicked(X,Y:Integer; AHandle:TDrawLineHandle):TDrawLine;
var P : TPoint;
Function ClickedLine(ALine:TDrawLine):Boolean;
var tmpStart : TPoint;
tmpEnd : TPoint;
begin
With ALine do
begin
tmpStart:=AxisPoint(StartPos);
tmpEnd:=AxisPoint(EndPos);
Case AHandle of
chStart: result:=PointInRect(StartHandle,P.X,P.Y);
chEnd : result:=PointInRect(EndHandle,P.X,P.Y);
else
Case Style of
dlLine : result:=PointInLine(P,tmpStart,tmpEnd,4);
dlHorizParallel : begin
result:=PointInLine(P,tmpStart.X,tmpStart.Y,
tmpEnd.X,tmpStart.Y,4);
if not result then
result:=PointInLine( P,tmpStart.X,tmpEnd.Y,
tmpEnd.X,tmpEnd.Y,4);
end;
else
begin
result:=PointInLine( P,tmpStart.X,tmpStart.Y,
tmpStart.X,tmpEnd.Y,4);
if not result then
result:=PointInLine( P,tmpEnd.X,tmpStart.Y,
tmpEnd.X,tmpEnd.Y,4);
end
end;
end;
end;
end;
var t : Integer;
begin
result:=nil;
// convert from 3D to 2D...
ParentChart.Canvas.Calculate2DPosition(X,Y,0);
// first, find if clicked the selected line...
P:=TeePoint(X,Y);
if Assigned(ISelected) and ClickedLine(ISelected) then
begin
result:=ISelected;
exit;
end;
// find which clicked line...
for t:=0 to Lines.Count-1 do
if ClickedLine(Lines[t]) then
begin
result:=Lines[t];
break;
end;
end;
Function TDrawLineTool.Clicked(X,Y:Integer):TDrawLine;
begin
// try first with whole line...
result:=InternalClicked(X,Y,chNone);
// try then at start and end line points...
if not Assigned(result) then result:=InternalClicked(X,Y,chStart);
if not Assigned(result) then result:=InternalClicked(X,Y,chEnd);
end;
Procedure TDrawLineTool.ChartMouseEvent( AEvent: TChartMouseEvent;
AButton:TMouseButton;
AShift: TShiftState; X, Y: Integer);
{ returns True if the mouse is over selected line ending points or over
any non-selected line.
If True, the Chart cursor is changed.
}
Function CheckCursor:Boolean;
begin
if Assigned(ISelected) and
((InternalClicked(X,Y,chStart)=ISelected) or
(InternalClicked(X,Y,chEnd)=ISelected)) then { ending points }
begin
ParentChart.Cursor:=crCross;
result:=True;
end
else
if Assigned(Clicked(X,Y)) then { over a line }
begin
ParentChart.Cursor:=crHandPoint; // set cursor
result:=True;
end
else result:=False;
end;
var tmpLine : TDrawLine;
tmpAllow : Boolean;
begin
Case AEvent of
cmeDown: if AButton=FButton then
begin
if FEnableSelect then tmpLine:=Clicked(X,Y)
else tmpLine:=nil;
if Assigned(tmpLine) then { clicked line, do select }
begin
FromPoint:=AxisPoint(tmpLine.StartPos);
ToPoint:=AxisPoint(tmpLine.EndPos);
IHandle:=chSeries;
IPoint:=TeePoint(X,Y);
if tmpLine<>ISelected then
begin
tmpAllow:=True;
if Assigned(FOnSelecting) then
FOnSelecting(Self,tmpLine,tmpAllow); { 5.03 }
if tmpAllow then
begin
{ change selected line }
if Assigned(ISelected) then
begin
ISelected:=tmpLine;
Repaint;
end
else
begin
ISelected:=tmpLine;
ISelected.DrawHandles;
end;
{ call event }
if Assigned(FOnSelect) then FOnSelect(Self);
end;
end
else
begin
{ check if clicked on ending points }
if Assigned(InternalClicked(X,Y,chStart)) then
IHandle:=chStart
else
if Assigned(InternalClicked(X,Y,chEnd)) then
IHandle:=chEnd;
end;
ParentChart.CancelMouse:=True;
end
else
begin
{ un-select }
ISelected:=nil;
if EnableDraw then
begin
IDrawing:=True;
FromPoint:=TeePoint(X,Y);
ToPoint:=FromPoint;
RedrawLine(ISelected);
ParentChart.CancelMouse:=True;
end;
end;
end;
cmeMove: if IDrawing or (IHandle<>chNone) then // drawing or dragging
begin
RedrawLine(ISelected); // hide previous line
if IDrawing then ToPoint:=TeePoint(X,Y)
else
begin
if IHandle=chStart then FromPoint:=TeePoint(X,Y)
else
if IHandle=chEnd then ToPoint:=TeePoint(X,Y)
else
if IHandle=chSeries then
begin
Inc(FromPoint.X,X-IPoint.X);
Inc(FromPoint.Y,Y-IPoint.Y);
Inc(ToPoint.X,X-IPoint.X);
Inc(ToPoint.Y,Y-IPoint.Y);
IPoint:=TeePoint(X,Y);
end;
end;
RedrawLine(ISelected); // show line at new position
ParentChart.CancelMouse:=True;
// call event
if Assigned(FOnDragLine) then FOnDragLine(Self);
end
else
if FEnableSelect then { change the cursor if mouse is over lines }
ParentChart.CancelMouse:=CheckCursor;
cmeUp: if AButton=FButton then
begin
if IHandle<>chNone then // if dragging...
begin
if (IHandle=chStart) or (IHandle=chSeries) then
ISelected.StartPos:=ScreenPoint(FromPoint);
if (IHandle=chEnd) or (IHandle=chSeries) then
ISelected.EndPos:=ScreenPoint(ToPoint);
IHandle:=chNone;
// stop dragging, repaint
Repaint;
// call event
if Assigned(FOnDraggedLine) then FOnDraggedLine(Self); { 5.01 }
end
else
if IDrawing then // drawing a new line...
begin
if (FromPoint.X<>ToPoint.X) or (FromPoint.Y<>ToPoint.Y) then
begin
// create the new drawn line...
with TeeDrawLineClass.Create(Lines) do // 5.02
begin
StartPos:=ScreenPoint(FromPoint);
EndPos :=ScreenPoint(ToPoint);
end;
// repaint chart
Repaint;
// call event
if Assigned(FOnNewLine) then FOnNewLine(Self);
end;
IDrawing:=False;
end;
end;
end;
end;
class function TDrawLineTool.Description: String;
begin
result:=TeeMsg_DrawLineTool
end;
type TCustomTeePanelAccess=class(TCustomTeePanel);
procedure TDrawLineTool.RedrawLine(ALine:TDrawLine);
var tmp : TColor;
begin
// draw current selected or dragged line with "not xor" pen mode
With ParentChart.Canvas do
begin
tmp:=ColorToRGB(TCustomTeePanelAccess(ParentChart).GetBackColor);
AssignVisiblePenColor(Self.Pen,(clWhite-tmp) xor Self.Pen.Color);
Pen.Mode:=pmNotXor;
if Assigned(ALine) then
DrawLine(FromPoint,ToPoint,ALine.Style)
else
DrawLine(FromPoint,ToPoint,dlLine);
Pen.Mode:=pmCopy;
end;
end;
class function TDrawLineTool.GetEditorClass: String;
begin
result:='TDrawLineEdit';
end;
function TDrawLineTool.AxisPoint(const P: TFloatPoint): TPoint;
begin
// convert from axis double XY to screen pixels XY
result.X:=GetHorizAxis.CalcPosValue(P.X);
result.Y:=GetVertAxis.CalcPosValue(P.Y);
end;
function TDrawLineTool.ScreenPoint(P: TPoint): TFloatPoint;
begin
// convert from screen pixels XY position to axis double XY
result.X:=GetHorizAxis.CalcPosPoint(P.X);
result.Y:=GetVertAxis.CalcPosPoint(P.Y);
end;
procedure TDrawLineTool.SetEnableSelect(Value: Boolean);
begin
if FEnableSelect<>Value then
begin
FEnableSelect:=Value;
if not FEnableSelect then
begin
if Assigned(ISelected) then
begin
ISelected:=nil;
Repaint;
end;
end;
end;
end;
procedure TDrawLineTool.DeleteSelected;
begin
if Assigned(ISelected) then
begin
IDrawing:=False; // 5.02
IHandle:=chNone; // 5.02
FreeAndNil(ISelected);
Repaint;
end;
end;
procedure TDrawLineTool.SetSelected(Value: TDrawLine);
begin
ISelected:=Value;
Repaint;
end;
procedure TDrawLineTool.SetLines(const Value: TDrawLines);
begin
FLines.Assign(Value);
end;
{ TNearestTool }
Constructor TNearestTool.Create(AOwner: TComponent);
begin
inherited;
FLinePen:=CreateChartPen;
Point:=-1;
FullRepaint:=True;
Brush.Style:=bsClear;
Pen.Style:=psDot;
Pen.Color:=clWhite;
FSize:=20;
FStyle:=hsCircle;
end;
Destructor TNearestTool.Destroy;
begin
FLinePen.Free;
inherited;
end;
function TNearestTool.ZAxisCalc(const Value:Double):Integer;
begin
result:=Series.ParentChart.Axes.Depth.CalcPosValue(Value);
end;
Function TNearestTool.GetDrawLine:Boolean;
begin
result:=LinePen.Visible;
end;
procedure TNearestTool.SetDrawLine(const Value: Boolean);
begin
LinePen.Visible:=Value;
end;
procedure TNearestTool.SetLinePen(const Value: TChartPen);
begin
FLinePen.Assign(Value);
end;
procedure TNearestTool.PaintHint;
var x : Integer;
y : Integer;
R : TRect;
P : TFourPoints;
tmpZ : Integer;
begin
if Assigned(Series) and (Point<>-1) and (Series.Count>Point) then // 6.01
With ParentChart.Canvas do
begin
AssignVisiblePen(Self.Pen);
if not FullRepaint then Pen.Mode:=pmNotXor;
x:=Series.CalcXPos(Point);
y:=Series.CalcYPos(Point);
if Series.HasZValues then // 7.0
tmpZ:=ZAxisCalc(Series.GetYValueList('Z').Value[Point])
else
tmpZ:=Series.StartZ;
if Self.Style<>hsNone then
begin
AssignBrush(Self.Brush,clBlack);
Case Self.Style of
hsCircle: if ParentChart.View3D then
EllipseWithZ(x-FSize,y-FSize,x+FSize,y+FSize,tmpZ)
else
Ellipse(x-FSize,y-FSize,x+FSize,y+FSize);
hsRectangle: begin
R:=TeeRect(x-FSize,y-FSize,x+FSize,y+FSize);
if ParentChart.View3D then RectangleWithZ(R,tmpZ)
else Rectangle(R);
end;
hsDiamond: begin
P[0]:=TeePoint(x,y-FSize);
P[1]:=TeePoint(x+FSize,y);
P[2]:=TeePoint(x,y+FSize);
P[3]:=TeePoint(x-FSize,y);
PolygonWithZ(P,tmpZ);
end;
end;
end;
if DrawLine then
begin
AssignVisiblePen(Self.LinePen);
if not FullRepaint then Pen.Mode:=pmNotXor;
MoveTo(IMouse.X,IMouse.Y);
if ParentChart.View3D then
LineTo3D(x,y,tmpZ) // 7.0
else
LineTo(x,y);
end;
if not FullRepaint then Pen.Mode:=pmCopy;
end;
end;
type
TSeriesAccess=class(TChartSeries);
class Function TNearestTool.GetNearestPoint(Series:TChartSeries; X,Y:Integer):Integer;
begin
result:=GetNearestPoint(Series,X,Y,False);
end;
class Function TNearestTool.GetNearestPoint(Series:TChartSeries; X,Y:Integer; IncludeNulls:Boolean):Integer;
var t : Integer;
Dif : Integer;
Dist : Integer;
tmpMin : Integer;
tmpMax : Integer;
tmpX : Integer;
tmpY : Integer;
tmpZList : TChartValueList;
tmpZ : Integer;
begin
result:=-1;
Dif:=10000;
if TeeGetFirstLastSeries(Series,tmpMin,tmpMax) then
begin
tmpZList:=Series.GetYValueList('Z'); // 7.0
for t:=tmpMin to tmpMax do { <-- traverse all points in a Series... }
if IncludeNulls or (not Series.IsNull(t)) then // 7.0
begin
{ calculate position in pixels }
tmpX:=Series.CalcXPos(t);
tmpY:=Series.CalcYPos(t);
if Series.HasZValues then
begin
tmpZ:=Series.ParentChart.Axes.Depth.CalcPosValue(tmpZList.Value[t]);
with Series.ParentChart.Canvas.Calculate3DPosition(tmpX,tmpY,tmpZ) do
begin
tmpX:=X;
tmpY:=Y;
end;
end;
if PointInRect(Series.ParentChart.ChartRect,tmpX,tmpY) then { 5.01 }
begin
{ calculate distance in pixels... }
Dist:=Round(TeeDistance(X-tmpX,Y-tmpY));
if Dist<Dif then { store if distance is lower... }
begin
Dif:=Dist;
result:=t; { <-- set this point to be the nearest... }
end;
end;
end;
end;
end;
procedure TNearestTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
if (AEvent=cmeMove) and Assigned(Series) then
begin
if not FullRepaint then PaintHint;
Point:=GetNearestPoint(Series,X,Y);
IMouse:=TeePoint(x,y);
if not FullRepaint then PaintHint;
if Assigned(FOnChange) then FOnChange(Self);
if FullRepaint then Repaint;
end;
end;
procedure TNearestTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if AEvent=cteAfterDraw then PaintHint
else
if AEvent=cteMouseLeave then
begin
if not FullRepaint then PaintHint;
Point:=-1;
if FullRepaint then Repaint;
end;
end;
class Function TNearestTool.Description:String;
begin
result:=TeeMsg_NearestTool
end;
procedure TNearestTool.SetSize(const Value: Integer);
begin
SetIntegerProperty(FSize,Value);
end;
class function TNearestTool.GetEditorClass: String;
begin
result:='TNearestToolEdit';
end;
procedure TNearestTool.SetStyle(const Value: TNearestToolStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Repaint;
end;
end;
{ TColorBandTool }
Constructor TColorBandTool.Create(AOwner: TComponent);
begin
inherited;
FGradient:=TChartGradient.Create(CanvasChanged);
FColor:=clWhite;
FCursor:=crDefault;
FDrawBehind:=True;
FLineStart:=NewColorLine;
FLineStart.Active:=False;
FLineEnd:=NewColorLine;
FLineEnd.Active:=False;
end;
Destructor TColorBandTool.Destroy;
begin
FreeAndNil(FLineStart);
FreeAndNil(FLineEnd);
FGradient.Free;
inherited;
end;
Function TColorBandTool.NewColorLine:TColorLineTool;
begin
result:=TColorLineTool.Create(nil);
result.Active:=False;
result.DragRepaint:=True;
result.OnDragLine:=Self.DragLine;
result.InternalOnEndDragLine:=Self.EndDragLine;
result.Pen.OnChange:=CanvasChanged;
end;
procedure TColorBandTool.DragLine(Sender:TColorLineTool);
begin
if Sender.DragRepaint then
if Sender=FLineStart then StartValue:=Sender.Value
else EndValue:=Sender.Value
end;
procedure TColorBandTool.EndDragLine(Sender:TColorLineTool);
begin
if not Sender.DragRepaint then
if Sender=FLineStart then StartValue:=Sender.Value
else EndValue:=Sender.Value
end;
Function TColorBandTool.BoundsRect:TRect;
var tmp0 : Double;
tmp1 : Double;
tmpDraw : Boolean;
begin
if Assigned(Axis) then
begin
result:=ParentChart.ChartRect;
tmp0:=FStart;
tmp1:=FEnd;
With Axis do
begin
if Inverted then
begin
if tmp0<tmp1 then SwapDouble(tmp0,tmp1);
tmpDraw:=(tmp1<=Maximum) and (tmp0>=Minimum);
end
else
begin
if tmp0>tmp1 then SwapDouble(tmp0,tmp1);
tmpDraw:=(tmp0<=Maximum) and (tmp1>=Minimum);
end;
if tmpDraw then
begin
if Horizontal then
begin
result.Left:=Math.Max(IStartPos,CalcPosValue(tmp0));
result.Right:=Math.Min(IEndPos,CalcPosValue(tmp1));
if Self.Pen.Visible then Inc(result.Right);
end
else
begin
result.Top:=Math.Max(IStartPos,CalcPosValue(tmp1));
result.Bottom:=Math.Min(IEndPos,CalcPosValue(tmp0));
Inc(result.Left);
Inc(result.Bottom);
if not Self.Pen.Visible then
begin
Inc(result.Bottom);
Inc(result.Right);
end;
end;
end
else result:=TeeRect(0,0,0,0);
end;
end
else result:=TeeRect(0,0,0,0);
end;
Function TColorBandTool.ZPosition:Integer;
begin
if DrawBehind then result:=ParentChart.Width3D else result:=0; // 5.03
end;
procedure TColorBandTool.PaintBand;
var R : TRect;
tmpR : TRect;
tmpRectBlend : TRect;
tmpZ : Integer;
tmpBlend : TTeeBlend;
begin
if Assigned(Axis) then
begin
R:=BoundsRect;
if ((R.Right-R.Left)>0) and ((R.Bottom-R.Top)>0) then
begin
With ParentChart,Canvas do
begin
AssignBrush(Self.Brush,Self.Color);
AssignVisiblePen(Self.Pen);
tmpZ:=ZPosition;
if Self.Gradient.Visible and View3DOptions.Orthogonal then
begin
tmpR:=R;
Dec(tmpR.Right);
Dec(tmpR.Bottom);
Self.Gradient.Draw(Canvas,CalcRect3D(tmpR,tmpZ));
Brush.Style:=bsClear;
end;
if Transparency=0 then
begin
if View3D then RectangleWithZ(R,tmpZ)
else Rectangle(R);
end
else
begin
if View3D then tmpRectBlend:=RectFromRectZ(R,tmpZ)
else tmpRectBlend:=R;
tmpBlend:=ParentChart.Canvas.BeginBlending(tmpRectBlend,Transparency);
if View3D then RectangleWithZ(R,tmpZ)
else Rectangle(R);
ParentChart.Canvas.EndBlending(tmpBlend);
end;
end;
if FLineEnd.Active then
begin
FLineEnd.Value:=EndValue;
FLineEnd.InternalDrawLine(DrawBehind);
end;
if FLineStart.Active then
begin
FLineStart.Value:=StartValue;
FLineStart.InternalDrawLine(DrawBehind);
end;
end;
end;
end;
procedure TColorBandTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
case AEvent of
cteBeforeDrawAxes: if DrawBehindAxes then PaintBand;
cteBeforeDrawSeries: if DrawBehind and (not DrawBehindAxes) then PaintBand;
cteAfterDraw: if (not DrawBehind) and (not DrawBehindAxes) then PaintBand;
end;
end;
class function TColorBandTool.Description: String;
begin
result:=TeeMsg_ColorBandTool
end;
class function TColorBandTool.GetEditorClass: String;
begin
result:='TColorBandToolEditor';
end;
procedure TColorBandTool.SetEnd(const Value: Double);
begin
SetDoubleProperty(FEnd,Value);
SetLines;
end;
procedure TColorBandTool.SetStart(const Value: Double);
begin
SetDoubleProperty(FStart,Value);
SetLines;
end;
procedure TColorBandTool.SetGradient(const Value: TChartGradient);
begin
FGradient.Assign(Value);
end;
procedure TColorBandTool.SetColor(Value: TColor);
begin
SetColorProperty(FColor,Value);
end;
procedure TColorBandTool.SetTransparency(const Value: TTeeTransparency);
begin
if FTransparency<>Value then
begin
FTransparency:=Value;
Repaint;
end;
end;
procedure TColorBandTool.SetDrawBehind(const Value: Boolean);
begin
SetBooleanProperty(FDrawBehind,Value);
end;
procedure TColorBandTool.SetDrawBehindAxes(const Value: Boolean);
begin
SetBooleanProperty(FDrawBehindAxes,Value);
end;
Function TColorBandTool.Clicked(X,Y:Integer):Boolean;
var P : TFourPoints;
begin
P:=ParentChart.Canvas.FourPointsFromRect(BoundsRect,ZPosition);
result:=PointInPolygon(TeePoint(X,Y),P);
end;
procedure TColorBandTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if FLineStart.Active then
FLineStart.ChartMouseEvent(AEvent,Button,Shift,X,Y);
if FLineEnd.Active and (not ParentChart.CancelMouse) then
FLineEnd.ChartMouseEvent(AEvent,Button,Shift,X,Y);
Case AEvent of
cmeDown:
if Assigned(FOnClick) and Clicked(X,Y) then
FOnClick(Self,Button,Shift,X,Y);
cmeMove:
if (Cursor<>crDefault) and (not ParentChart.CancelMouse) then
if Clicked(x,y) then
begin
ParentChart.Cursor:=FCursor;
ParentChart.CancelMouse:=(not ParentChart.IPanning.Active) and (not ParentChart.Zoom.Active);
end;
end;
end;
function TColorBandTool.GetResizeEnd: Boolean;
begin
result:=EndLine.Active;
end;
function TColorBandTool.GetResizeStart: Boolean;
begin
result:=StartLine.Active;
end;
procedure TColorBandTool.SetResizeEnd(const Value: Boolean);
begin
EndLine.Active:=Value;
Repaint;
end;
procedure TColorBandTool.SetResizeStart(const Value: Boolean);
begin
StartLine.Active:=Value;
Repaint;
end;
procedure TColorBandTool.SetAxis(const Value: TChartAxis);
begin
inherited;
FLineEnd.Axis:=Value;
FLineEnd.ParentChart:=nil;
FLineStart.Axis:=Value;
FLineStart.ParentChart:=nil;
end;
procedure TColorBandTool.SetLines;
begin
FLineEnd.Value:=FEnd;
FLineStart.Value:=FStart;
end;
procedure TColorBandTool.Loaded;
begin
inherited;
SetLines;
end;
procedure TColorBandTool.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if Assigned(FLineStart) then FLineStart.IParent:=ParentChart;
if Assigned(FLineEnd) then FLineEnd.IParent:=ParentChart;
end;
function TColorBandTool.GetEndLinePen: TChartPen;
begin
result:=EndLine.Pen;
end;
function TColorBandTool.GetStartLinePen: TChartPen;
begin
result:=StartLine.Pen;
end;
procedure TColorBandTool.SetEndLinePen(const Value: TChartPen);
begin
EndLine.Pen:=Value;
end;
procedure TColorBandTool.SetStartLinePen(const Value: TChartPen);
begin
StartLine.Pen:=Value;
end;
{ TColorLineTool }
Constructor TColorLineTool.Create(AOwner: TComponent);
begin
inherited;
FAllowDrag:=True;
FDraw3D:=True;
end;
Procedure TColorLineTool.Assign(Source:TPersistent);
begin
if Source is TColorLineTool then
with TColorLineTool(Source) do
begin
Self.FAllowDrag:=AllowDrag;
Self.FDragRepaint:=DragRepaint;
Self.FDraw3D:=Draw3D;
Self.FDrawBehind:=DrawBehind;
Self.FNoLimitDrag:=NoLimitDrag;
Self.FStyle:=Style;
Self.FValue:=Value;
end;
inherited;
end;
Function TColorLineTool.CalcValue:Double;
begin
Case Self.FStyle of
clMaximum: result:=Axis.Maximum;
clCenter: result:=(Axis.Maximum+Axis.Minimum)*0.5;
clMinimum: result:=Axis.Minimum;
else
result:=FValue; // clCustom
end;
end;
// Returns the same AValue parameter if it points to
// inside the axes limits.
// If AValue is outside the limits, it will return the closest
// point value of the ultrapassed edge.
Function TColorLineTool.LimitValue(const AValue:Double):Double;
var tmpLimit : Double;
tmpStart : Integer;
tmpEnd : Integer;
begin
result:=AValue;
tmpStart:=Axis.IEndPos; // 6.01 Fix for Inverted axes
tmpEnd:=Axis.IStartPos;
if Axis.Horizontal then SwapInteger(tmpStart,tmpEnd);
if Axis.Inverted then SwapInteger(tmpStart,tmpEnd);
// do not use Axis Minimum & Maximum, we need the "real" min and max
tmpLimit:=Axis.CalcPosPoint(tmpStart);
if result<tmpLimit then result:=tmpLimit
else
begin
tmpLimit:=Axis.CalcPosPoint(tmpEnd);
if result>tmpLimit then result:=tmpLimit;
end;
end;
Function TColorLineTool.Chart:TCustomAxisPanel;
begin
result:=IParent;
if not Assigned(result) then
result:=ParentChart;
end;
Procedure TColorLineTool.DrawColorLine(Back:Boolean);
var tmp : Integer;
begin
{ check inside axis limits, only when dragging }
if AllowDrag and (not NoLimitDrag) then // 7.0 fix
FValue:=LimitValue(FValue);
tmp:=Axis.CalcPosValue(CalcValue);
With Chart,Canvas do
begin
if Back then
begin
if Axis.Horizontal then
begin
if Draw3D then ZLine3D(tmp,ChartRect.Bottom,0,Width3D);
if DrawBehind or Draw3D then
VertLine3D(tmp,ChartRect.Top,ChartRect.Bottom,Width3D);
end
else
begin
if Draw3D then ZLine3D(ChartRect.Left,tmp,0,Width3D);
if DrawBehind or Draw3D then
HorizLine3D(ChartRect.Left,ChartRect.Right,tmp,Width3D);
end;
end
else
if View3D or ((not IDragging) or FDragRepaint) then
if Axis.Horizontal then
begin
if Draw3D then ZLine3D(tmp,ChartRect.Top,0,Width3D);
if not DrawBehind then
VertLine3D(tmp,ChartRect.Top,ChartRect.Bottom,0);
end
else
begin
if Draw3D then ZLine3D(ChartRect.Right,tmp,0,Width3D);
if not DrawBehind then
HorizLine3D(ChartRect.Left,ChartRect.Right,tmp,0);
end;
end;
end;
procedure TColorLineTool.InternalDrawLine(Back:Boolean);
begin
Chart.Canvas.AssignVisiblePen(Pen);
Chart.Canvas.BackMode:=cbmTransparent; // 5.03
DrawColorLine(Back);
end;
procedure TColorLineTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if Assigned(Axis) and
((AEvent=cteBeforeDrawSeries) or (AEvent=cteAfterDraw)) then
InternalDrawLine(AEvent=cteBeforeDrawSeries);
end;
procedure TColorLineTool.DoEndDragLine;
begin
if Assigned(InternalOnEndDragLine) then InternalOnEndDragLine(Self);
if Assigned(FOnEndDragLine) then FOnEndDragLine(Self);
end;
procedure TColorLineTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var tmp : Integer;
tmpNew : Double;
tmpDoDraw : Boolean;
begin
tmpDoDraw:=False;
if AllowDrag and Assigned(Axis) then
Case AEvent of
cmeUp: if IDragging then // 7.0
begin
{ force repaint }
if not FDragRepaint then Repaint;
{ call event }
DoEndDragLine;
IDragging:=False;
end;
cmeMove: if IDragging then
begin
if Axis.Horizontal then tmp:=x else tmp:=y;
{ calculate new position }
tmpNew:=Axis.CalcPosPoint(tmp);
{ check inside axis limits }
if not NoLimitDrag then // (already implicit AllowDrag=True)
tmpNew:=LimitValue(tmpNew);
if FDragRepaint then { 5.02 }
Value:=tmpNew { force repaint whole chart }
else
begin
tmpDoDraw:=CalcValue<>tmpNew;
if tmpDoDraw then
begin
{ draw line in xor mode, to avoid repaint the whole chart }
with Chart.Canvas do
begin
AssignVisiblePen(Self.Pen);
Pen.Mode:=pmNotXor;
end;
{ hide previous line }
DrawColorLine(True);
DrawColorLine(False);
{ set new value }
FStyle:=clCustom;
FValue:=tmpNew;
end;
end;
Chart.CancelMouse:=True;
{ call event, allow event to change Value }
if Assigned(FOnDragLine) then FOnDragLine(Self);
if tmpDoDraw then { 5.02 }
begin
{ draw at new position }
DrawColorLine(True);
DrawColorLine(False);
{ reset pen mode }
Chart.Canvas.Pen.Mode:=pmCopy;
end;
end
else
begin
{ is mouse on line? }
if Clicked(x,y) then { 5.02 }
begin
{ show appropiate cursor }
if Axis.Horizontal then
Chart.Cursor:=crHSplit
else
Chart.Cursor:=crVSplit;
Chart.CancelMouse:=True;
end;
end;
cmeDown: if Button=mbLeft then
begin
{ is mouse over line ? }
IDragging:=Clicked(x,y);
Chart.CancelMouse:=IDragging;
if IDragging and Assigned(FOnBeginDragLine) then // 7.0
FOnBeginDragLine(Self);
end;
end;
end;
function TColorLineTool.Clicked(x, y: Integer): Boolean;
var tmp : Integer;
begin
if Axis.Horizontal then tmp:=x else tmp:=y;
result:=Abs(tmp-Axis.CalcPosValue(CalcValue))<TeeClickTolerance;
if result then { 5.02 }
with Chart do
if Axis.Horizontal then
result:=(y>=ChartRect.Top) and (y<=ChartRect.Bottom)
else
result:=(x>=ChartRect.Left) and (x<=ChartRect.Right)
end;
class function TColorLineTool.Description: String;
begin
result:=TeeMsg_ColorLineTool;
end;
class function TColorLineTool.GetEditorClass: String;
begin
result:='TColorLineToolEditor';
end;
procedure TColorLineTool.SetValue(const AValue: Double);
begin
if not (csReading in ComponentState) then
FStyle:=clCustom;
if (not IDragging) or FDragRepaint then { 5.02 }
SetDoubleProperty(FValue,AValue)
else
FValue:=AValue;
end;
procedure TColorLineTool.SetDraw3D(const Value: Boolean);
begin
SetBooleanProperty(FDraw3D,Value);
end;
procedure TColorLineTool.SetDrawBehind(const Value: Boolean);
begin
SetBooleanProperty(FDrawBehind,Value);
end;
procedure TColorLineTool.SetStyle(const Value: TColorLineStyle);
begin
if FStyle<>Value then
begin
FStyle:=Value;
Repaint;
end;
end;
type TChartPenAccess=class(TChartPen);
{ TRotateTool }
constructor TRotateTool.Create(AOwner: TComponent);
begin
inherited;
FButton:=mbLeft;
IDragging:=False;
FInverted:=False;
FStyle:=rsAll;
Pen.Hide;
TChartPenAccess(Pen).DefaultVisible:=False;
Pen.Mode:=pmXor;
Pen.Color:=clWhite;
end;
class Function TRotateTool.RotationChange(FullRotation:Boolean; AAngle,AChange:Integer):Integer;
begin
result:=AAngle;
if AChange=0 then exit;
if AChange>0 then
begin
Inc(result,AChange);
if result>360 then
Dec(result,360)
(*
else
if (result<270) and (result>90) then
result:=90;
*)
end
else
begin
if FullRotation then
result:=Math.Max(0,AAngle+AChange)
else
begin
result:=AAngle+AChange;
if result<0 then result:=360+result
(*
else
if (result>90) and (result<270) then result:=270;
*)
end;
end;
end;
class Function TRotateTool.ElevationChange(FullRotation:Boolean; AAngle,AChange:Integer):Integer;
var tmpMinAngle : Integer;
begin
result:=AAngle;
if AChange=0 then exit;
if AChange>0 then
result:=Math.Min(360,AAngle+AChange)
else
begin
if FullRotation then tmpMinAngle:=0
else tmpMinAngle:=TeeMinAngle;
result:=Math.Max(tmpMinAngle,AAngle+AChange);
end;
end;
type TCanvasAccess=class(TTeeCanvas3D);
procedure TRotateTool.ChartMouseEvent(AEvent: TChartMouseEvent;
AButton: TMouseButton; AShift: TShiftState; X, Y: Integer);
Procedure MouseMove;
Function CorrectAngle(Const AAngle:Integer):Integer;
begin
result:=AAngle;
if result>360 then result:=result-360 else
if result<0 then result:=360+result;
end;
Procedure DrawCubeOutline;
var w : Integer;
begin
with ParentChart.Canvas do
begin
Brush.Style:=bsClear;
AssignVisiblePen(Self.Pen);
w:=ParentChart.Width3D;
RectangleWithZ(ParentChart.ChartRect,0);
RectangleWithZ(ParentChart.ChartRect,w);
with ParentChart.ChartRect do
begin
MoveTo3D(Left,Top,0);
LineTo3D(Left,Top,W);
MoveTo3D(Right,Top,0);
LineTo3D(Right,Top,W);
MoveTo3D(Left,Bottom,0);
LineTo3D(Left,Bottom,W);
MoveTo3D(Right,Bottom,0);
LineTo3D(Right,Bottom,W);
end;
end;
end;
Var tmpX : Integer;
tmpY : Integer;
begin
tmpX:=Round(90.0*(X-IOldX)/ParentChart.Width);
if FInverted then tmpX:=-tmpX;
tmpY:=Round(90.0*(IOldY-Y)/ParentChart.Height);
if FInverted then tmpY:=-tmpY;
if Pen.Visible then
begin
if IFirstTime then
begin
IOldRepaint:=ParentChart.AutoRepaint;
ParentChart.AutoRepaint:=False;
IFirstTime:=False;
end
else DrawCubeOutline;
end;
ParentChart.View3D:=True;
With ParentChart.View3DOptions do
begin
Orthogonal:=False;
if ParentChart.Canvas.SupportsFullRotation then
begin
if (FStyle=rsRotation) or (FStyle=rsAll) then
Rotation:=CorrectAngle(Rotation+tmpX);
if (FStyle=rsElevation) or (FStyle=rsAll) then
Elevation:=CorrectAngle(Elevation+tmpY);
end
else
begin
if (FStyle=rsRotation) or (FStyle=rsAll) then
begin
// FirstSeriesPie
Rotation:=RotationChange(ParentChart.Canvas.SupportsFullRotation,Rotation,tmpX);
end;
if (FStyle=rsElevation) or (FStyle=rsAll) then
Elevation:=ElevationChange(ParentChart.Canvas.SupportsFullRotation,Elevation,tmpY);
end;
end;
IOldX:=X;
IOldY:=Y;
ParentChart.CancelMouse:=True;
if Pen.Visible then
begin
with TCanvasAccess(ParentChart.Canvas) do
begin
FIsOrthogonal:=False; // 6.01
CalcTrigValues;
CalcPerspective(ParentChart.ChartRect);
end;
DrawCubeOutline;
end;
if Assigned(FOnRotate) then FOnRotate(Self);
end;
begin
inherited;
Case AEvent of
cmeUp: if IDragging then // 6.01
begin
IDragging:=False;
if Pen.Visible then
begin
ParentChart.AutoRepaint:=IOldRepaint;
Repaint;
end;
end;
cmeMove: if IDragging then MouseMove;
cmeDown: if AButton=Self.Button then
begin
IDragging:=True;
IOldX:=X;
IOldY:=Y;
IFirstTime:=True;
ParentChart.CancelMouse:=True;
end;
end;
end;
class function TRotateTool.Description: String;
begin
result:=TeeMsg_RotateTool;
end;
class function TRotateTool.GetEditorClass: String;
begin
result:='TRotateToolEditor';
end;
{ TChartImageTool }
Constructor TChartImageTool.Create(AOwner: TComponent);
begin
inherited;
FPicture:=TPicture.Create;
FPicture.OnChange:=CanvasChanged;
end;
Destructor TChartImageTool.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure TChartImageTool.ChartEvent(AEvent: TChartToolEvent);
var R : TRect;
begin
inherited;
if (AEvent=cteBeforeDrawSeries) and Assigned(FPicture) then
begin
if Assigned(Series) then
With Series do
begin
R.Left:=CalcXPosValue(MinXValue);
R.Right:=CalcXPosValue(MaxXValue);
R.Top:=CalcYPosValue(MaxYValue);
R.Bottom:=CalcYPosValue(MinYValue);
end
else
begin
With GetHorizAxis do
begin
R.Left:=CalcPosValue(Minimum);
R.Right:=CalcPosValue(Maximum);
end;
With GetVertAxis do
begin
R.Top:=CalcYPosValue(Maximum);
R.Bottom:=CalcYPosValue(Minimum);
end;
end;
With ParentChart,Canvas do
begin
if CanClip then ClipCube(ChartRect,0,Width3D);
if View3D and (not View3DOptions.Orthogonal) then
StretchDraw(R,FPicture.Graphic,Width3D)
else
StretchDraw(CalcRect3D(R,Width3D),FPicture.Graphic);
UnClipRectangle;
end;
end;
end;
class function TChartImageTool.Description: String;
begin
result:=TeeMsg_ImageTool;
end;
class function TChartImageTool.GetEditorClass: String;
begin
result:='TChartImageToolEditor';
end;
procedure TChartImageTool.SetPicture(const Value: TPicture);
begin
FPicture.Assign(Value);
end;
procedure TChartImageTool.SetSeries(const Value: TChartSeries);
begin
inherited;
Repaint;
end;
{ TMarksToolTip }
constructor TMarksTipTool.Create(AOwner: TComponent);
begin
inherited;
FStyle:=smsLabel;
end;
procedure TMarksTipTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var tmp : Integer;
tmpSeries : TChartSeries;
Procedure FindClickedSeries;
var t : Integer;
begin
for t:=ParentChart.SeriesCount-1 downto 0 do // 6.01
begin
tmp:=ParentChart[t].Clicked(x,y);
if tmp<>-1 then
begin
tmpSeries:=ParentChart[t];
break;
end;
end;
end;
var tmpStyle : TSeriesMarksStyle;
tmpOld : Boolean;
tmpText : String;
t : Integer;
tmpCancel : Boolean;
begin
inherited;
if ((MouseAction=mtmMove) and (AEvent=cmeMove)) or
((MouseAction=mtmClick) and (AEvent=cmeDown)) then
begin
tmpSeries:=nil;
tmp:=-1;
{ find which series is under XY }
if Assigned(Series) then
begin
tmpSeries:=Series;
tmp:=tmpSeries.Clicked(x,y);
end
else FindClickedSeries; { 5.02 }
{ if not ok then cancel hint... }
if tmp=-1 then
begin
tmpCancel:=True;
{ do not cancel if other MarkTipTools exist... }
for t:=0 to Chart.Tools.Count-1 do
if (Chart.Tools[t]<>Self) and
(Chart.Tools[t] is TMarksTipTool) then { 5.01 }
begin
tmpCancel:=False;
break;
end;
if tmpCancel then
begin
Chart.Hint:='';
Application.CancelHint;
end;
end
else
begin
{ show hint ! }
tmpStyle:=tmpSeries.Marks.Style;
tmpOld:=Chart.AutoRepaint;
Chart.AutoRepaint:=False;
tmpSeries.Marks.Style:=FStyle;
try
tmpText:=tmpSeries.ValueMarkText[tmp];
if Assigned(FOnGetText) then FOnGetText(Self,tmpText);
if Chart.Hint<>tmpText then
begin
Chart.ShowHint:=True; { 5.02 }
Chart.Hint:=tmpText;
{$IFDEF D5}
Application.ActivateHint(Chart.ClientToScreen(TeePoint(X,Y)));
{$ENDIF}
end;
finally
tmpSeries.Marks.Style:=tmpStyle;
Chart.AutoRepaint:=tmpOld;
end;
end;
end;
end;
class function TMarksTipTool.Description: String;
begin
result:=TeeMsg_MarksTipTool;
end;
class function TMarksTipTool.GetEditorClass: String;
begin
result:='TMarksTipToolEdit';
end;
Function TMarksTipTool.Chart:TCustomChart;
begin
if Assigned(Series) then result:=TCustomChart(Series.ParentChart)
else result:=TCustomChart(ParentChart);
end;
procedure TMarksTipTool.SetActive(Value: Boolean);
begin
inherited;
if not Active then Chart.Hint:='';
end;
procedure TMarksTipTool.SetMouseAction(Value: TMarkToolMouseAction);
begin
FMouseAction:=Value;
Chart.Hint:='';
end;
function TMarksTipTool.GetMouseDelay: Integer;
begin
result:=Application.HintPause;
end;
procedure TMarksTipTool.SetMouseDelay(const Value: Integer);
begin
Application.HintPause:=Value;
end;
{ TAnnotationCallout }
Constructor TAnnotationCallout.Create(AOwner: TChartSeries);
begin
inherited;
Arrow.Hide;
Visible:=False;
end;
procedure TAnnotationCallout.Assign(Source: TPersistent);
begin
if Source is TAnnotationCallout then
With TAnnotationCallout(Source) do
begin
Self.FX:=XPosition;
Self.FY:=YPosition;
Self.FZ:=ZPosition;
end;
inherited;
end;
procedure TAnnotationCallout.SetX(const Value: Integer);
begin
if FX<>Value then
begin
FX:=Value;
Repaint;
end;
end;
procedure TAnnotationCallout.SetY(const Value: Integer);
begin
if FY<>Value then
begin
FY:=Value;
Repaint;
end;
end;
procedure TAnnotationCallout.SetZ(const Value: Integer);
begin
if FZ<>Value then
begin
FZ:=Value;
Repaint;
end;
end;
function TAnnotationCallout.CloserPoint(const R: TRect;
const P: TPoint): TPoint;
var tmpX : Integer;
tmpY : Integer;
begin
if P.X>R.Right then tmpX:=R.Right
else
if P.X<R.Left then tmpX:=R.Left
else
tmpX:=(R.Left+R.Right) div 2;
if P.Y>R.Bottom then tmpY:=R.Bottom
else
if P.Y<R.Top then tmpY:=R.Top
else
tmpY:=(R.Top+R.Bottom) div 2;
result:=TeePoint(tmpX,tmpY);
end;
{ TAnnotationTool }
Constructor TAnnotationTool.Create(AOwner: TComponent);
begin
inherited;
FCursor:=crDefault;
FShape:=TTeeShapePosition.Create(nil);
FCallout:=TAnnotationCallout.Create(nil);
FPosition:=ppLeftTop;
FPositionUnits:=muPixels;
FAutoSize:=True;
end;
Destructor TAnnotationTool.Destroy;
begin
FreeAndNil(FCallout);
FreeAndNil(FShape);
inherited;
end;
procedure TAnnotationTool.ChartEvent(AEvent: TChartToolEvent);
begin
inherited;
if AEvent=cteAfterDraw then DrawText;
end;
Function TAnnotationTool.GetText:String;
begin
result:=FText;
end;
procedure TAnnotationTool.SetText(const Value: String);
begin
SetStringProperty(FText,Value);
end;
type TChartAccess=class(TCustomAxisPanel);
procedure TAnnotationTool.DrawText;
var x : Integer;
y : Integer;
t : Integer;
tmpN : Integer;
tmp : String;
tmpTo : TPoint;
tmpFrom : TPoint;
OldBounds : TRect;
tmpHeight : Integer;
begin
With ParentChart.Canvas do
begin
tmp:=GetText;
if tmp='' then tmp:=' '; { at least one space character... }
OldBounds:=Shape.ShapeBounds;
Shape.ShapeBounds:=GetBounds(tmpN,x,y);
if Shape.Visible then Shape.Draw;
BackMode:=cbmTransparent;
case FTextAlign of
taLeftJustify: TextAlign:=TA_LEFT;
taCenter: begin
TextAlign:=ta_Center;
with Shape.ShapeBounds do
x:=2+((Left+Right) div 2);
end;
else
begin
TextAlign:=ta_Right;
x:=Shape.ShapeBounds.Right-2;
end;
end;
tmpHeight:=FontHeight;
for t:=1 to tmpN do
TextOut(x,y+(t-1)*tmpHeight, TeeExtractField(tmp,t,TeeLineSeparator));
end;
with Callout do
if Visible or Arrow.Visible then
begin
tmpTo:=TeePoint(XPosition,YPosition);
tmpFrom:=CloserPoint(Shape.ShapeBounds,tmpTo);
if Distance<>0 then
tmpTo:=PointAtDistance(tmpFrom,tmpTo,Distance);
Draw(clNone,tmpTo,tmpFrom,ZPosition);
end;
Shape.ShapeBounds:=OldBounds;
end;
Function TAnnotationTool.GetBounds(var NumLines,x,y:Integer):TRect;
var tmpHeight : Integer;
tmpW : Integer;
tmpH : Integer;
tmp : String;
tmpX : Integer;
tmpY : Integer;
tmpWOk : Integer;
tmpHOk : Integer;
begin
ParentChart.Canvas.AssignFont(Shape.Font);
tmpHeight:=ParentChart.Canvas.FontHeight;
tmp:=GetText;
if tmp='' then tmp:=' '; { at least one space character... }
tmpW:=TChartAccess(ParentChart).MultiLineTextWidth(tmp,NumLines);
tmpH:=NumLines*tmpHeight;
if Shape.CustomPosition then
begin
if PositionUnits=muPixels then // 7.0
begin
x:=Shape.Left+4;
y:=Shape.Top+2;
end
else
begin
x:=Round(Shape.Left*ParentChart.Width*0.01);
y:=Round(Shape.Top*ParentChart.Height*0.01);
end;
end
else
begin
tmpX:=ParentChart.Width-tmpW-8;
tmpY:=ParentChart.Height-tmpH-8;
Case Position of
ppLeftTop : begin x:=10; y:=10; end;
ppLeftBottom : begin x:=10; y:=tmpY; end;
ppRightTop : begin x:=tmpX; y:=10; end;
else
begin x:=tmpX; y:=tmpY; end;
end;
end;
if AutoSize then
begin
tmpWOk:=tmpW+4+2;
tmpHOk:=tmpH+2+2;
end
else
begin
tmpWOk:=Shape.Width;
tmpHOk:=Shape.Height;
end;
{$IFDEF CLR}
result:=TRect.Create(x-4,y-2,x-4+tmpWOk,y-2+tmpHOk);
{$ELSE}
With result do
begin
Left:=x-4;
Top:=y-2;
Right:=Left+tmpWOk;
Bottom:=Top+tmpHOk;
end;
{$ENDIF}
end;
procedure TAnnotationTool.SetParentChart(const Value: TCustomAxisPanel);
begin
inherited;
if not (csDestroying in ComponentState) then
begin
if Assigned(Shape) then Shape.ParentChart:=Value;
if Assigned(Callout) then Callout.ParentChart:=Value;
if Assigned(ParentChart) then Repaint;
end;
end;
procedure TAnnotationTool.SetShape(const Value: TTeeShapePosition);
begin
FShape.Assign(Value);
end;
class function TAnnotationTool.Description: String;
begin
result:=TeeMsg_AnnotationTool;
end;
class function TAnnotationTool.GetEditorClass: String;
begin
result:='TAnnotationToolEdit';
end;
procedure TAnnotationTool.SetPosition(const Value: TAnnotationPosition);
begin
if FPosition<>Value then
begin
FPosition:=Value;
Shape.CustomPosition:=False;
Repaint;
end;
end;
Function TAnnotationTool.Clicked(x,y:Integer):Boolean; // 5.03
var tmpDummy,
tmpX,
tmpY : Integer;
begin
result:=PointInRect(GetBounds(tmpDummy,tmpX,tmpY),x,y);
end;
procedure TAnnotationTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if AEvent=cmeDown then
begin
if Assigned(FOnClick) and Clicked(x,y) then
FOnClick(Self,Button,Shift,X,Y);
end
else
if (AEvent=cmeMove) and (FCursor<>crDefault) then
begin
if Clicked(x,y) then
begin
ParentChart.Cursor:=FCursor;
ParentChart.CancelMouse:=True;
end;
end;
end;
procedure TAnnotationTool.SetTextAlign(const Value: TAlignment);
begin
if FTextAlign<>Value then
begin
FTextAlign:=Value;
Repaint;
end;
end;
procedure TAnnotationTool.SetAutoSize(const Value: Boolean);
begin
SetBooleanProperty(FAutoSize,Value);
end;
procedure TAnnotationTool.SetCallout(const Value: TAnnotationCallout);
begin
FCallout.Assign(Value);
end;
procedure TAnnotationTool.SetPositionUnits(const Value: TTeeUnits);
begin
if FPositionUnits<>Value then
begin
FPositionUnits:=Value;
Repaint;
end;
end;
function TAnnotationTool.GetHeight: Integer;
begin
result:=Shape.Height;
end;
function TAnnotationTool.GetWidth: Integer;
begin
result:=Shape.Width;
end;
function TAnnotationTool.IsNotAutoSize: Boolean;
begin
result:=not AutoSize;
end;
procedure TAnnotationTool.SetHeight(const Value: Integer);
begin
if Height<>Value then
begin
FAutoSize:=False;
Shape.Height:=Value;
Repaint;
end;
end;
procedure TAnnotationTool.SetWidth(const Value: Integer);
begin
if Width<>Value then
begin
FAutoSize:=False;
Shape.Width:=Value;
Repaint;
end;
end;
{ TSeriesAnimationTool }
constructor TSeriesAnimationTool.Create(AOwner: TComponent);
begin
inherited;
IStopped:=True;
FStartAtMin:=True;
FSteps:=100;
end;
class function TSeriesAnimationTool.Description: String;
begin
result:=TeeMsg_SeriesAnimTool;
end;
procedure TSeriesAnimationTool.Execute;
Procedure UpdateChart;
begin
Series.ParentChart.Invalidate;
Application.ProcessMessages;
end;
var tmpList : TChartValueList;
tmpBack : TChartValueList;
procedure SetInitialValues;
var t : Integer;
begin
for t:=0 to Series.Count-1 do
tmpList.Value[t]:=tmpBack.Value[t];
UpdateChart;
end;
var tmpDirection : Boolean;
Procedure DoAnimation;
var t,tt : Integer;
tmpStart : Double;
tmpSpeed : Double;
tmpSpeed2 : Double;
tmpSpeed3 : Double;
tmpPoints : Integer;
tmpPointStep : Integer;
tmpFrom : Integer;
tmpTo : Integer;
tmpSteps : Integer;
begin
tmpList:=Series.MandatoryValueList;
if StartAtMin then tmpStart:=tmpList.MinValue
else tmpStart:=StartValue;
// Clear values
for t:=0 to Series.Count-1 do tmpList.Value[t]:=tmpStart;
UpdateChart;
tmpBack:=FBackup.MandatoryValueList;
if DrawEvery=0 then tmpPoints:=0
else
begin
tmpPoints:=Series.Count div DrawEvery;
if (Series.Count mod DrawEvery)=0 then Dec(tmpPoints);
end;
for tmpPointStep:=0 to tmpPoints do
begin
tmpFrom:=tmpPointStep*DrawEvery;
if DrawEvery=0 then tmpTo:=Series.Count-1
else tmpTo:=Math.Min(Series.Count-1,tmpFrom+DrawEvery-1);
tmpSpeed:=1/Steps;
tmpSteps:=Steps;
for t:=0 to tmpSteps do
begin
tmpSpeed2:=t*tmpSpeed;
tmpSpeed3:=tmpStart-(tmpStart*tmpSpeed2);
if Loop=salCircular then
if not tmpDirection then
begin
tmpSpeed3:=0; //-tmpSpeed3;
tmpSpeed2:=(tmpSteps-t)*tmpSpeed;
end;
for tt:=tmpFrom to tmpTo do
tmpList.Value[tt]:=tmpSpeed3+(tmpSpeed2*tmpBack.Value[tt]);
if Assigned(FOnStep) then FOnStep(Self,t);
UpdateChart;
if IStopped then
begin
SetInitialValues;
Exit;
end;
end;
end;
SetInitialValues;
end;
begin
if Assigned(Series) and IStopped then
begin
FBackup:=TChartSeriesClass(Series.ClassType).Create(nil);
try
FBackup.AssignValues(Series);
Series.BeginUpdate;
IStopped:=False;
try
if Loop<>salNo then
begin
tmpDirection:=True;
while not IStopped do
begin
DoAnimation;
tmpDirection:=not tmpDirection;
end;
end
else DoAnimation;
finally
IStopped:=True;
// Series.AssignValues(FBackup); <-- not necessary
Series.EndUpdate;
end;
finally
FBackup.Free;
end;
end;
end;
class function TSeriesAnimationTool.GetEditorClass: String;
begin
result:='TSeriesAnimToolEditor';
end;
function TSeriesAnimationTool.Running: Boolean;
begin
result:=not IStopped;
end;
procedure TSeriesAnimationTool.Stop;
begin
IStopped:=True;
end;
{ TGridBandBrush }
procedure TGridBandBrush.SetBackColor(const Value: TColor);
begin
if FBackColor<>Value then
begin
FBackColor:=Value;
Changed;
end;
end;
procedure TGridBandBrush.SetTransp(const Value: TTeeTransparency);
begin
if FTransp<>Value then
begin
FTransp:=Value;
Changed;
end;
end;
{ TGridBandTool }
constructor TGridBandTool.Create(AOwner: TComponent);
begin
inherited;
FBand1:=TGridBandBrush.Create(CanvasChanged);
FBand1.BackColor:=clNone;
FBand2:=TGridBandBrush.Create(CanvasChanged);
FBand2.BackColor:=clNone;
end;
class function TGridBandTool.Description: String;
begin
result:=TeeMsg_GridBandTool;
end;
type TAxisAccess=class(TChartAxis);
Destructor TGridBandTool.Destroy;
begin
if Assigned(Axis) then TAxisAccess(Axis).OnDrawGrids:=nil;
FBand2.Free;
FBand1.Free;
inherited;
end;
Function TGridBandTool.BandBackColor(ABand:TGridBandBrush):TColor;
begin
result:=ABand.BackColor;
if result=clNone then result:=TCustomChart(ParentChart).Walls.Back.Color;
end;
Procedure TGridBandTool.DrawGrids(Sender:TChartAxis);
var tmpBand : TGridBandBrush;
tmpBlend : TTeeBlend;
Procedure DrawBand(tmpPos1,tmpPos2:Integer);
var tmpR : TRect;
begin
if tmpBand.Style<>bsClear then
with ParentChart,Canvas do
begin
AssignBrushColor(tmpBand,tmpBand.Color,BandBackColor(tmpBand));
if tmpPos1>tmpPos2 then SwapInteger(tmpPos1,tmpPos2); // 7.0
if Axis.Horizontal then
tmpR:=TeeRect(tmpPos1,ChartRect.Top+1,tmpPos2,ChartRect.Bottom)
else
tmpR:=TeeRect(ChartRect.Left+1,tmpPos1,ChartRect.Right,tmpPos2+1);
if tmpBand.Transparency>0 then
if View3D then tmpBlend.SetRectangle(CalcRect3D(tmpR,Width3D))
else tmpBlend.SetRectangle(tmpR);
Pen.Style:=psClear;
if View3D then RectangleWithZ(tmpR,Width3D)
else
begin
Inc(tmpR.Right);
Rectangle(tmpR);
end;
if tmpBand.Transparency>0 then
tmpBlend.DoBlend(tmpBand.Transparency);
end;
end;
procedure SwitchBands;
begin
if tmpBand=Band1 then tmpBand:=Band2
else tmpBand:=Band1;
end;
var t : Integer;
tmp : Integer;
begin
if not Active then exit;
tmp:=High(Sender.Tick);
if (tmp>0) and (Band1.Style<>bsClear) or (Band2.Style<>bsClear) then
begin
tmpBlend:=ParentChart.Canvas.BeginBlending(TeeRect(0,0,0,0),0);
try
ParentChart.Canvas.Pen.Style:=psClear;
tmpBand:=Band1;
with Sender do
begin
// first remainder band...
if Horizontal then
begin
if Tick[0]<IEndPos then
begin
DrawBand(IEndPos-1,Tick[0]);
SwitchBands;
end;
end
else
if Tick[0]>IStartPos then
begin
DrawBand(IStartPos+1,Tick[0]);
SwitchBands;
end;
// all bands...
for t:=1 to tmp do
begin
DrawBand(Tick[Pred(t)],Tick[t]);
SwitchBands;
end;
// last remainder band...
if Horizontal then
begin
if Tick[tmp]>IStartPos then DrawBand(Tick[tmp],IStartPos);
end
else
if Tick[tmp]<IEndPos then DrawBand(Tick[tmp],IEndPos);
end;
finally
tmpBlend.Free;
end;
end;
end;
class function TGridBandTool.GetEditorClass: String;
begin
result:='TGridBandToolEdit';
end;
procedure TGridBandTool.SetAxis(const Value: TChartAxis);
begin
if Assigned(Axis) then TAxisAccess(Axis).OnDrawGrids:=nil;
inherited;
if Assigned(Axis) then TAxisAccess(Axis).OnDrawGrids:=DrawGrids;
end;
procedure TGridBandTool.SetBand1(Value: TGridBandBrush);
begin
FBand1.Assign(Value);
end;
procedure TGridBandTool.SetBand2(Value: TGridBandBrush);
begin
FBand2.Assign(Value);
end;
{ TAxisScrollTool }
procedure TAxisScrollTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Function AxisClicked:TChartAxis;
var t : Integer;
begin
result:=nil;
if Assigned(Axis) then
begin
if Axis.Visible and Axis.Clicked(x,y) then
result:=Axis;
end
else
with ParentChart do
for t:=0 to Axes.Count-1 do
if Axes[t].Visible and Axes[t].Clicked(x,y) then
begin
result:=Axes[t];
break;
end;
end;
var Delta : Integer;
procedure DoAxisScroll(AAxis:TChartAxis);
begin
if AAxis.IAxisSize<>0 then
AAxis.Scroll(Delta*(AAxis.Maximum-AAxis.Minimum)/AAxis.IAxisSize,False);
end;
procedure CheckOtherAxes;
var t : Integer;
tt : Integer;
begin
with ParentChart do
for t:=0 to Axes.Count-1 do
if (Axes[t]<>InAxis) and (Axes[t].Horizontal=InAxis.Horizontal) then
for tt:=0 to SeriesCount-1 do
if Series[tt].AssociatedToAxis(InAxis) and
Series[tt].AssociatedToAxis(Axes[t]) then
begin
DoAxisScroll(Axes[t]);
break;
end;
end;
begin
inherited;
if Active then
Case AEvent of
cmeDown: begin
InAxis:=AxisClicked;
OldX:=X;
OldY:=Y;
end;
cmeMove: begin
if Assigned(InAxis) then
begin
if InAxis.Horizontal then Delta:=OldX-X
else Delta:=OldY-Y;
if InAxis.Inverted then Delta:=-Delta;
if InAxis.Horizontal then
begin
if ScrollInverted then Delta:=-Delta;
end
else
if not ScrollInverted then Delta:=-Delta;
DoAxisScroll(InAxis);
CheckOtherAxes;
OldX:=X;
OldY:=Y;
ParentChart.CancelMouse:=True;
end
else
if AxisClicked<>nil then
begin
ParentChart.Cursor:=crHandPoint;
ParentChart.CancelMouse:=True;
end;
end;
cmeUp: InAxis:=nil;
end;
end;
class function TAxisScrollTool.Description: String;
begin
result:=TeeMsg_AxisScrollTool;
end;
{ TMagnifyTool }
Constructor TRectangleTool.Create(AOwner:TComponent);
begin
inherited;
AutoSize:=False;
IEdge:=-1;
with Shape do
begin
FCustomPosition:=True;
Shadow.Size:=0;
Transparency:=75;
ShapeBounds.Left:=10;
ShapeBounds.Top:=10;
Width:=50;
Height:=50;
PositionUnits:=muPixels;
Cursor:=crHandPoint;
end;
end;
Function TRectangleTool.ClickedEdge(x,y:Integer):Integer;
var R : TRect;
begin
result:=-1;
if Clicked(x,y) then
begin
R:=Shape.ShapeBounds;
if Abs(x-R.Left)<4 then result:=0 else
if Abs(y-R.Top)<4 then result:=1 else
if Abs(x-R.Right)<4 then result:=2 else
if Abs(y-R.Bottom)<4 then result:=3;
end;
end;
class Function TRectangleTool.Description:String;
begin
result:=TeeMsg_RectangleTool;
end;
Procedure TRectangleTool.ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer);
Function GuessEdgeCursor:Boolean;
begin
result:=False;
case ClickedEdge(x,y) of
0,2: begin ParentChart.Cursor:=crSizeWE; result:=True; end;
1,3: begin ParentChart.Cursor:=crSizeNS; result:=True; end;
else
if Clicked(x,y) and (Cursor<>crDefault) then
begin
ParentChart.Cursor:=Cursor;
result:=True;
end;
end;
end;
var tmpW : Integer;
tmpH : Integer;
{$IFDEF CLR}
tmpR : TRect;
{$ENDIF}
begin
inherited;
if Active then
case AEvent of
cmeDown:
if Button=mbLeft then
begin
IEdge:=ClickedEdge(x,y);
if IEdge<>-1 then
begin
if IEdge=2 then P.X:=X-Shape.ShapeBounds.Right else P.X:=X-Shape.Left;
if IEdge=3 then P.Y:=Y-Shape.ShapeBounds.Bottom else P.Y:=Y-Shape.Top;
ParentChart.CancelMouse:=True;
end
else
if Clicked(x,y) then
begin
P.X:=X-Shape.Left;
P.Y:=Y-Shape.Top;
IDrag:=True;
ParentChart.CancelMouse:=True;
end;
end;
cmeUp: begin IDrag:=False; IEdge:=-1; end;
cmeMove:
if IDrag then
begin
if (X<>P.X) or (Y<>P.Y) then
begin
tmpW:=Shape.Width;
tmpH:=Shape.Height;
Shape.Left:=X-P.X;
Shape.Top:=Y-P.Y;
Shape.Width:=tmpW;
Shape.Height:=tmpH;
if Assigned(FOnDragging) then FOnDragging(Self);
end;
end
else
begin
if IEdge<>-1 then
begin
{$IFDEF CLR}
tmpR:=Shape.ShapeBounds;
case IEdge of
0: tmpR.Left:=Min(Shape.ShapeBounds.Right-3,X-P.X);
1: tmpR.Top:=Min(Shape.ShapeBounds.Bottom-3,Y-P.Y);
2: tmpR.Right:=Max(Shape.ShapeBounds.Left+3,X-P.X);
3: tmpR.Bottom:=Max(Shape.ShapeBounds.Top+3,Y-P.Y);
end;
Shape.ShapeBounds:=tmpR;
{$ELSE}
case IEdge of
0: Shape.Left:=Min(Shape.ShapeBounds.Right-3,X-P.X);
1: Shape.Top:=Min(Shape.ShapeBounds.Bottom-3,Y-P.Y);
2: Shape.ShapeBounds.Right:=Max(Shape.ShapeBounds.Left+3,X-P.X);
3: Shape.ShapeBounds.Bottom:=Max(Shape.ShapeBounds.Top+3,Y-P.Y);
end;
{$ENDIF}
Repaint;
if Assigned(FOnResizing) then FOnResizing(Self);
end
else ParentChart.CancelMouse:=GuessEdgeCursor;
end;
end;
end;
// Returns chart bitmap under rectangle shape
Function TRectangleTool.Bitmap(ChartOnly:Boolean=False):TBitmap;
Procedure CopyResult(ACanvas:TCanvas);
begin
result.Canvas.CopyRect( TeeRect(0,0,result.Width,result.Height),
ACanvas,Shape.ShapeBounds);
end;
var tmp : TTeeCanvas3D;
OldActive : Boolean;
tmpB : TBitmap;
begin
result:=TBitmap.Create;
result.Width:=Shape.Width;
result.Height:=Shape.Height;
if ChartOnly then
begin
OldActive:=Active;
Active:=False;
try
tmpB:=ParentChart.TeeCreateBitmap(ParentChart.Color,ParentChart.ChartBounds);
try
CopyResult(tmpB.Canvas);
finally
tmpB.Free;
end;
finally
Active:=OldActive;
end;
end
else
if ParentChart.Canvas is TTeeCanvas3D then
begin
tmp:=TTeeCanvas3D(ParentChart.Canvas);
if not Assigned(tmp.Bitmap) then ParentChart.Draw;
CopyResult(tmp.Bitmap.Canvas);
end;
end;
{ TClipTool }
procedure TClipSeriesTool.AddClip(Sender: TObject);
var tmpR : TRect;
begin
if Assigned(Series) and Assigned(ParentChart) and ParentChart.CanClip then
begin
tmpR.Left:=Series.GetHorizAxis.IStartPos;
tmpR.Right:=Series.GetHorizAxis.IEndPos;
tmpR.Top:=Series.GetVertAxis.IStartPos;
tmpR.Bottom:=Series.GetVertAxis.IEndPos;
ParentChart.Canvas.ClipRectangle(tmpR);
IActive:=True;
end;
end;
procedure TClipSeriesTool.RemoveClip(Sender: TObject);
begin
if IActive then ParentChart.Canvas.UnClipRectangle;
end;
procedure TClipSeriesTool.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation=opRemove) and Assigned(Series) and (AComponent=Series) then
begin
Series.BeforeDrawValues:=nil;
Series.AfterDrawValues:=nil;
end;
inherited;
end;
procedure TClipSeriesTool.SetSeries(const Value: TChartSeries);
begin
inherited;
if Assigned(Series) then
begin
Series.BeforeDrawValues:=AddClip;
Series.AfterDrawValues:=RemoveClip;
end;
end;
class Function TClipSeriesTool.Description:String;
begin
result:=TeeMsg_ClipSeries;
end;
Const T:Array[0..15] of TTeeCustomToolClass=(
TCursorTool, TDragMarksTool,
TAxisArrowTool, TDrawLineTool,
TNearestTool, TColorBandTool,
TColorLineTool, TRotateTool,
TChartImageTool, TMarksTipTool,
TAnnotationTool, TSeriesAnimationTool,
TGridBandTool, TAxisScrollTool,
TRectangleTool, TClipSeriesTool
);
initialization
RegisterTeeTools(T);
finalization
UnRegisterTeeTools(T);
end.
|
unit ufrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Samples.Spin,
IdTCPConnection, IdTCPClient, IdBaseComponent, IdComponent, IdCustomTCPServer,
IdTCPServer, IdContext, IdGlobal,
Winapi.Winsock2, System.Diagnostics, ncSockets, ncLines;
const
// We are testing the socket mechanisms here and not how fast tcp/ip is,
// therefore the buffer sent back and forth is kept at a fairly minimal size
BuffSize = 256;
type
TfrmMain = class(TForm)
ncClient: TncTCPClient;
idClient: TIdTCPClient;
pnlToolbar: TPanel;
memLog: TMemo;
btnTestSpeed: TButton;
edtIterations: TSpinEdit;
Label1: TLabel;
rbTestNetCom: TRadioButton;
rbTestIndy: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure btnTestSpeedClick(Sender: TObject);
private
BufferSend, BufferRead: TBytes;
idBufferSend, idBufferRead: TidBytes;
public
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
SetLength(BufferSend, BuffSize);
SetLength(BufferRead, BuffSize);
SetLength(idBufferSend, BuffSize);
SetLength(idBufferRead, BuffSize);
end;
procedure TfrmMain.btnTestSpeedClick(Sender: TObject);
var
i: Integer;
TimeSt: Cardinal;
TimeTaken: Cardinal;
begin
if rbTestNetCom.Checked then
ncClient.Active := True;
if rbTestIndy.Checked then
idClient.Connect;
if rbTestNetCom.Checked then
begin
memLog.Lines.Add('Testing NetCom...');
TimeSt := GetTickCount;
for i := 1 to edtIterations.Value do
begin
ncClient.Send(BufferSend);
ncClient.ReceiveRaw(BufferRead);
end;
TimeTaken := GetTickCount - TimeSt;
memLog.Lines.Add('Time taken: ' + IntToStr(TimeTaken) + ' msec');
end;
if rbTestIndy.Checked then
begin
memLog.Lines.Add('Testing Indy...');
TimeSt := GetTickCount;
for i := 1 to edtIterations.Value do
begin
idClient.Socket.Write(idBufferSend);
idClient.Socket.ReadBytes(idBufferRead, BuffSize, False);
end;
TimeTaken := GetTickCount - TimeSt;
memLog.Lines.Add('Time taken: ' + IntToStr(TimeTaken) + ' msec');
end;
if rbTestNetCom.Checked then
ncClient.Active := False;
if rbTestIndy.Checked then
idClient.Disconnect;
end;
end.
|
unit func_ccreg_set56;
interface
implementation
type
TEnum56 = (_a00,_a01,_a02,_a03,_a04,_a05,_a06,_a07,_a08,_a09,_a10,_a11,_a12,_a13,_a14,_a15,_a16,_a17,_a18,_a19,_a20,_a21,_a22,_a23,_a24,_a25,_a26,_a27,_a28,_a29,_a30,_a31,
_a32,_a33,_a34,_a35,_a36,_a37,_a38,_a39,_a40,_a41,_a42,_a43,_a44,_a45,_a46,_a47,_a48,_a49,_a50,_a51,_a52,_a53,_a54,_a55);
TSet56 = packed set of TEnum56;
function F(a: TSet56): TSet56; external 'CAT' name 'func_ccreg_set56';
var
a, r: TSet56;
procedure Test;
begin
a := [_a06];
R := F(a);
Assert(a = r);
end;
initialization
Test();
finalization
end. |
unit StatusIntf;
interface
type
IStatus = Interface(IInterface)
['{5444FA40-507A-4F5E-BB65-89025E426405}']
procedure ShowError(const error: string);
procedure ShowConfirmation(const conf: string);
End;
implementation
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/chain.h
// Bitcoin file: src/chain.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TDiskBlockIndex;
interface
type
// /** Used to marshal pointers into hashes for db storage. */
TDiskBlockIndex = class(TBlockIndex)
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = uint256();
}
explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : uint256());
}
SERIALIZE_METHODS(CDiskBlockIndex, obj)
{
int _nVersion = s.GetVersion();
if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT_MODE(_nVersion, VarIntMode::NONNEGATIVE_SIGNED));
READWRITE(VARINT_MODE(obj.nHeight, VarIntMode::NONNEGATIVE_SIGNED));
READWRITE(VARINT(obj.nStatus));
READWRITE(VARINT(obj.nTx));
if (obj.nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT_MODE(obj.nFile, VarIntMode::NONNEGATIVE_SIGNED));
if (obj.nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(obj.nDataPos));
if (obj.nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(obj.nUndoPos));
// block header
READWRITE(obj.nVersion);
READWRITE(obj.hashPrev);
READWRITE(obj.hashMerkleRoot);
READWRITE(obj.nTime);
READWRITE(obj.nBits);
READWRITE(obj.nNonce);
}
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString(),
hashPrev.ToString());
return str;
}
};
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit StdActns;
{$H+,X+}
interface
uses SysUtils, Classes, ActnList, StdCtrls, Forms, Dialogs;
type
{ Hint actions }
THintAction = class(TCustomAction)
public
constructor Create(AOwner: TComponent); override;
published
property Hint;
end;
{ Edit actions }
TEditAction = class(TAction)
private
FControl: TCustomEdit;
procedure SetControl(Value: TCustomEdit);
protected
function GetControl(Target: TObject): TCustomEdit; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
property Control: TCustomEdit read FControl write SetControl;
end;
TEditCut = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TEditCopy = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TEditPaste = class(TEditAction)
public
procedure UpdateTarget(Target: TObject); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TEditSelectAll = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TEditUndo = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TEditDelete = class(TEditAction)
public
procedure ExecuteTarget(Target: TObject); override;
{ UpdateTarget is required because TEditAction.UpdateTarget specifically
checks to see if the action is TEditCut or TEditCopy }
procedure UpdateTarget(Target: TObject); override;
end;
{ MDI Window actions }
TWindowAction = class(TAction)
private
FForm: TForm;
procedure SetForm(Value: TForm);
protected
function GetForm(Target: TObject): TForm; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
property Form: TForm read FForm write SetForm;
end;
TWindowClose = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
TWindowCascade = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowTileHorizontal = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowTileVertical = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowMinimizeAll = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
TWindowArrange = class(TWindowAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
{ Help actions }
THelpAction = class(TAction)
public
constructor Create(AOwner: TComponent); override;
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
end;
THelpContents = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
THelpTopicSearch = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
THelpOnHelp = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
end;
THelpContextAction = class(THelpAction)
public
procedure ExecuteTarget(Target: TObject); override;
procedure UpdateTarget(Target: TObject); override;
end;
{ TCommonDialogAction }
TCommonDialogClass = class of TCommonDialog;
TCommonDialogAction = class(TCustomAction)
private
FExecuteResult: Boolean;
FOnAccept: TNotifyEvent;
FOnCancel: TNotifyEvent;
FBeforeExecute: TNotifyEvent;
protected
FDialog: TCommonDialog;
function GetDialogClass: TCommonDialogClass; virtual;
public
constructor Create(AOwner: TComponent); override;
function Handlestarget(Target: TObject): Boolean; override;
procedure ExecuteTarget(Target: TObject); override;
property ExecuteResult: Boolean read FExecuteResult;
property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute;
property OnAccept: TNotifyEvent read FOnAccept write FOnAccept;
property OnCancel: TNotifyEvent read FOnCancel write FOnCancel;
end;
{ File Actions }
TFileAction = class(TCommonDialogAction)
private
function GetFileName: TFileName;
procedure SetFileName(const Value: TFileName);
protected
function GetDialog: TOpenDialog;
property FileName: TFileName read GetFileName write SetFileName;
end;
TFileOpen = class(TFileAction)
protected
function GetDialogClass: TCommonDialogClass; override;
public
constructor Create(AOwner: TComponent); override;
published
property Caption;
property Dialog: TOpenDialog read GetDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
TFileOpenWith = class(TFileOpen)
private
FFileName: TFileName;
public
procedure ExecuteTarget(Target: TObject); override;
published
property FileName: TFileName read FFileName write FFileName;
property BeforeExecute;
end;
TFileSaveAs = class(TFileAction)
private
function GetSaveDialog: TSaveDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
public
constructor Create(AOwner: TComponent); override;
published
property Caption;
property Dialog: TSaveDialog read GetSaveDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
TFilePrintSetup = class(TCommonDialogAction)
private
function GetDialog: TPrinterSetupDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
published
property Caption;
property Dialog: TPrinterSetupDialog read GetDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
TFileExit = class(TCustomAction)
public
function HandlesTarget(Target: TObject): Boolean; override;
procedure ExecuteTarget(Target: TObject); override;
published
property Caption;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property OnHint;
end;
{ Search Actions }
TSearchAction = class(TCommonDialogAction)
protected
FControl: TCustomEdit;
FFindFirst: Boolean;
public
constructor Create(AOwner: TComponent); override;
function HandlesTarget(Target: TObject): Boolean; override;
procedure Search(Sender: TObject); virtual;
procedure UpdateTarget(Target: TObject); override;
procedure ExecuteTarget(Target: TObject); override;
end;
TSearchFind = class(TSearchAction)
private
function GetFindDialog: TFindDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
published
property Caption;
property Dialog: TFindDialog read GetFindDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
TSearchReplace = class(TSearchAction)
private
procedure Replace(Sender: TObject);
function GetReplaceDialog: TReplaceDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
public
procedure ExecuteTarget(Target: TObject); override;
published
property Caption;
property Dialog: TReplaceDialog read GetReplaceDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
TSearchFindFirst = class(TSearchFind)
public
constructor Create(AOwner: TComponent); override;
end;
TSearchFindNext = class(TCustomAction)
private
FSearchFind: TSearchFind;
public
constructor Create(AOwner: TComponent); override;
function HandlesTarget(Target: TObject): Boolean; override;
procedure UpdateTarget(Target: TObject); override;
procedure ExecuteTarget(Target: TObject); override;
published
property Caption;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property SearchFind: TSearchFind read FSearchFind write FSearchFind;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property OnHint;
end;
{ TFontEdit }
TFontEdit = class(TCommonDialogAction)
private
function GetDialog: TFontDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
published
property Caption;
property Dialog: TFontDialog read GetDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
{ TColorSelect }
TColorSelect = class(TCommonDialogAction)
private
function GetDialog: TColorDialog;
protected
function GetDialogClass: TCommonDialogClass; override;
published
property Caption;
property Dialog: TColorDialog read GetDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
{ TPrintDlg }
TPrintDlg = class(TCommonDialogAction)
private
function GetDialog: TPrintDialog;
protected
function Getdialogclass: TCommonDialogClass; override;
published
property Caption;
property Dialog: TPrintDialog read GetDialog;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property SecondaryShortCuts;
property Visible;
property BeforeExecute;
property OnAccept;
property OnCancel;
property OnHint;
end;
implementation
uses Windows, Messages, Consts, Clipbrd, StrUtils, ShellAPI;
{ THintAction }
constructor THintAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DisableIfNoHandler := False;
end;
{ TEditAction }
{ TEditAction }
function TEditAction.GetControl(Target: TObject): TCustomEdit;
begin
{ We could hard cast Target as a TCustomEdit since HandlesTarget "should" be
called before ExecuteTarget and UpdateTarget, however, we're being safe. }
Result := Target as TCustomEdit;
end;
function TEditAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := ((Control <> nil) and (Target = Control) or
(Control = nil) and (Target is TCustomEdit)) and TCustomEdit(Target).Focused;
end;
procedure TEditAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Control) then Control := nil;
end;
procedure TEditAction.UpdateTarget(Target: TObject);
begin
if (Self is TEditCut) or (Self is TEditCopy) then
Enabled := GetControl(Target).SelLength > 0;
end;
procedure TEditAction.SetControl(Value: TCustomEdit);
begin
if Value <> FControl then
begin
FControl := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
end;
{ TEditCopy }
procedure TEditCopy.ExecuteTarget(Target: TObject);
begin
GetControl(Target).CopyToClipboard;
end;
{ TEditCut }
procedure TEditCut.ExecuteTarget(Target: TObject);
begin
GetControl(Target).CutToClipboard;
end;
{ TEditPaste }
procedure TEditPaste.ExecuteTarget(Target: TObject);
begin
GetControl(Target).PasteFromClipboard;
end;
procedure TEditPaste.UpdateTarget(Target: TObject);
begin
Enabled := Clipboard.HasFormat(CF_TEXT);
end;
{ TEditSelectAll }
procedure TEditSelectAll.ExecuteTarget(Target: TObject);
begin
GetControl(Target).SelectAll;
end;
procedure TEditSelectAll.UpdateTarget(Target: TObject);
begin
Enabled := Length(GetControl(Target).Text) > 0;
end;
{ TEditUndo }
procedure TEditUndo.ExecuteTarget(Target: TObject);
begin
GetControl(Target).Undo;
end;
procedure TEditUndo.UpdateTarget(Target: TObject);
begin
Enabled := GetControl(Target).CanUndo;
end;
{ TEditDelete }
procedure TEditDelete.ExecuteTarget(Target: TObject);
begin
GetControl(Target).ClearSelection;
end;
procedure TEditDelete.UpdateTarget(Target: TObject);
begin
Enabled := GetControl(Target).SelLength > 0;
end;
{ TWindowAction }
function TWindowAction.GetForm(Target: TObject): TForm;
begin
{ We could hard cast Target as a TForm since HandlesTarget "should" be called
before ExecuteTarget and UpdateTarget, however, we're being safe. }
Result := (Target as TForm);
end;
function TWindowAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := ((Form <> nil) and (Target = Form) or
(Form = nil) and (Target is TForm)) and
(TForm(Target).FormStyle = fsMDIForm);
end;
procedure TWindowAction.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Form) then Form := nil;
end;
procedure TWindowAction.UpdateTarget(Target: TObject);
begin
Enabled := GetForm(Target).MDIChildCount > 0;
end;
procedure TWindowAction.SetForm(Value: TForm);
begin
if Value <> FForm then
begin
FForm := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
end;
constructor TWindowAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DisableIfNoHandler := False;
Enabled := csDesigning in ComponentState;
end;
{ TWindowClose }
procedure TWindowClose.ExecuteTarget(Target: TObject);
begin
with GetForm(Target) do
if ActiveMDIChild <> nil then ActiveMDIChild.Close;
end;
procedure TWindowClose.UpdateTarget(Target: TObject);
begin
Enabled := GetForm(Target).ActiveMDIChild <> nil;
end;
{ TWindowCascade }
procedure TWindowCascade.ExecuteTarget(Target: TObject);
begin
GetForm(Target).Cascade;
end;
{ TWindowTileHorizontal }
procedure DoTile(Form: TForm; TileMode: TTileMode);
const
TileParams: array[TTileMode] of Word = (MDITILE_HORIZONTAL, MDITILE_VERTICAL);
begin
if (Form.FormStyle = fsMDIForm) and (Form.ClientHandle <> 0) then
SendMessage(Form.ClientHandle, WM_MDITILE, TileParams[TileMode], 0);
end;
procedure TWindowTileHorizontal.ExecuteTarget(Target: TObject);
begin
DoTile(GetForm(Target), tbHorizontal);
end;
{ TWindowTileVertical }
procedure TWindowTileVertical.ExecuteTarget(Target: TObject);
begin
DoTile(GetForm(Target), tbVertical);
end;
{ TWindowMinimizeAll }
procedure TWindowMinimizeAll.ExecuteTarget(Target: TObject);
var
I: Integer;
begin
{ Must be done backwards through the MDIChildren array }
with GetForm(Target) do
for I := MDIChildCount - 1 downto 0 do
MDIChildren[I].WindowState := wsMinimized;
end;
{ TWindowArrange }
procedure TWindowArrange.ExecuteTarget(Target: TObject);
begin
GetForm(Target).ArrangeIcons;
end;
{ THelpAction }
constructor THelpAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DisableIfNoHandler := False;
Enabled := csDesigning in ComponentState;
end;
function THelpAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := True;
end;
procedure THelpAction.UpdateTarget(Target: TObject);
begin
Enabled := Assigned(Application);
end;
{ THelpContents }
procedure THelpContents.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_FINDER, 0);
end;
{ THelpTopicSearch }
procedure THelpTopicSearch.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_FINDER, Integer(PChar('')));
end;
{ THelpOnHelp }
procedure THelpOnHelp.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_HELPONHELP, Integer(PChar('')));
end;
{ THelpContextAction }
procedure THelpContextAction.ExecuteTarget(Target: TObject);
begin
Application.HelpCommand(HELP_CONTEXT, Screen.ActiveControl.HelpContext);
end;
procedure THelpContextAction.UpdateTarget(Target: TObject);
begin
Enabled := Assigned(Screen) and Assigned(Screen.ActiveControl) and
(Screen.ActiveControl.HelpContext <> 0);
end;
{ TCommonDialogAction }
constructor TCommonDialogAction.Create(AOwner: TComponent);
var
DialogClass: TCommonDialogClass;
begin
inherited Create(AOwner);
DialogClass := GetDialogClass;
if Assigned(DialogClass) then
begin
FDialog := DialogClass.Create(Self);
FDialog.SetSubComponent(True);
end;
DisableIfNoHandler := False;
Enabled := True;
end;
procedure TCommonDialogAction.ExecuteTarget(Target: TObject);
begin
FExecuteResult := False;
if Assigned(FDialog) then
begin
if Assigned(FBeforeExecute) then
FBeforeExecute(Self);
FExecuteResult := FDialog.Execute;
if FExecuteResult then
begin
if Assigned(FOnAccept) then
FOnAccept(Self)
end
else
if Assigned(FOnCancel) then
FOnCancel(Self);
end;
end;
function TCommonDialogAction.GetDialogClass: TCommonDialogClass;
begin
Result := nil;
end;
function TCommonDialogAction.Handlestarget(Target: TObject): Boolean;
begin
Result := True;
end;
{ TFileAction }
function TFileAction.GetDialog: TOpenDialog;
begin
Result := TOpenDialog(FDialog);
end;
function TFileAction.GetFileName: TFileName;
begin
Result := GetDialog.FileName;
end;
procedure TFileAction.SetFileName(const Value: TFileName);
begin
GetDialog.FileName := Value;
end;
{ TFileOpen }
constructor TFileOpen.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDialog.Name := 'OpenDialog';
end;
function TFileOpen.GetDialogClass: TCommonDialogClass;
begin
Result := TOpenDialog;
end;
{ TFileOpenWith }
procedure TFileOpenWith.ExecuteTarget(Target: TObject);
begin
if (Length(FFileName) = 0) or not FileExists(FFileName) then
inherited;
FFileName := Dialog.FileName;
if FExecuteResult then
ShellExecute(0, 'open', 'rundll32.exe', { do not localize}
PChar(Format('shell32.dll,OpenAs_RunDLL %s', [FFileName])), nil, { do not localize}
SW_SHOW);
end;
{ TFileSaveAs }
constructor TFileSaveAs.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDialog.Name := 'SaveDialog';
end;
function TFileSaveAs.GetDialogClass: TCommonDialogClass;
begin
Result := TSaveDialog;
end;
function TFileSaveAs.GetSaveDialog: TSaveDialog;
begin
Result := TSaveDialog(FDialog);
end;
{ TFilePrintSetup }
function TFilePrintSetup.GetDialog: TPrinterSetupDialog;
begin
Result := TPrinterSetupDialog(FDialog);
end;
function TFilePrintSetup.GetDialogClass: TCommonDialogClass;
begin
Result := TPrinterSetupDialog;
end;
{ TFileExit }
procedure TFileExit.ExecuteTarget(Target: TObject);
begin
if Assigned(Application.MainForm) then
begin
Application.HelpCommand(HELP_QUIT, 0);
Application.MainForm.Close;
end;
end;
function TFileExit.HandlesTarget(Target: TObject): Boolean;
begin
Result := True;
end;
{ SearchEdit scans the text of a TCustomEdit-derived component for a given
search string. The search starts at the current caret position in the
control unless FindFirst is true then the search starts at the beginning.
The Options parameter determines whether the search runs forward
(frDown) or backward from the caret position, whether or not the text
comparison is case sensitive, and whether the matching string must be a
whole word. If text is already selected in the control, the search starts
at the 'far end' of the selection (SelStart if searching backwards, SelEnd
if searching forwards). If a match is found, the control's text selection
is changed to select the found text and the function returns True. If no
match is found, the function returns False. }
function SearchEdit(EditControl: TCustomEdit; const SearchString: String;
Options: TFindOptions; FindFirst: Boolean = False): Boolean;
var
Buffer, P: PChar;
Size: Word;
SearchOptions: TStringSearchOptions;
begin
Result := False;
if (Length(SearchString) = 0) then Exit;
Size := EditControl.GetTextLen;
if (Size = 0) then Exit;
Buffer := StrAlloc(Size + 1);
try
SearchOptions := [];
if frDown in Options then
Include(SearchOptions, soDown);
if frMatchCase in Options then
Include(SearchOptions, soMatchCase);
if frWholeWord in Options then
Include(SearchOptions, soWholeWord);
EditControl.GetTextBuf(Buffer, Size + 1);
if FindFirst then
P := SearchBuf(Buffer, Size, 0, EditControl.SelLength,
SearchString, SearchOptions)
else
P := SearchBuf(Buffer, Size, EditControl.SelStart, EditControl.SelLength,
SearchString, SearchOptions);
if P <> nil then
begin
EditControl.SelStart := P - Buffer;
EditControl.SelLength := Length(SearchString);
Result := True;
end;
finally
StrDispose(Buffer);
end;
end;
{ TSearchAction }
constructor TSearchAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
TFindDialog(FDialog).OnFind := Search;
FFindFirst := False;
end;
procedure TSearchAction.ExecuteTarget(Target: TObject);
begin
FControl := TCustomEdit(Target);
inherited ExecuteTarget(Target);
end;
function TSearchAction.HandlesTarget(Target: TObject): Boolean;
begin
Result := Screen.ActiveControl is TCustomEdit;
if not Result then
Enabled := False;
end;
procedure TSearchAction.Search(Sender: TObject);
begin
// FControl gets set in ExecuteTarget
if Assigned(FControl) then
if not SearchEdit(FControl, TFindDialog(FDialog).FindText,
TFindDialog(FDialog).Options, FFindFirst) then
ShowMessage(Format(STextNotFound, [TFindDialog(FDialog).FindText]));
FControl := nil;
end;
procedure TSearchAction.UpdateTarget(Target: TObject);
begin
Enabled := Target is TCustomEdit and
(TCustomEdit(Screen.ActiveControl).GetTextLen > 0);
end;
{ TSearchFind }
function TSearchFind.GetDialogClass: TCommonDialogClass;
begin
Result := TFindDialog;
end;
function TSearchFind.GetFindDialog: TFindDialog;
begin
Result := TFindDialog(FDialog);
end;
{ TSearchReplace }
procedure TSearchReplace.ExecuteTarget(Target: TObject);
begin
inherited ExecuteTarget(Target);
TReplaceDialog(FDialog).OnReplace := Replace;
end;
function TSearchReplace.GetDialogClass: TCommonDialogClass;
begin
Result := TReplaceDialog;
end;
function TSearchReplace.GetReplaceDialog: TReplaceDialog;
begin
Result := TReplaceDialog(FDialog);
end;
procedure TSearchReplace.Replace(Sender: TObject);
var
Found: Boolean;
begin
if Assigned(FControl) then
with Sender as TReplaceDialog do
begin
if AnsiCompareText(FControl.SelText, FindText) = 0 then
FControl.SelText := ReplaceText;
Found := SearchEdit(FControl, Dialog.FindText, Dialog.Options, FFindFirst);
while Found and (frReplaceAll in Dialog.Options) do
begin
FControl.SelText := ReplaceText;
Found := SearchEdit(FControl, Dialog.FindText, Dialog.Options, FFindFirst);
end;
if (not Found) and (frReplace in Dialog.Options) then
ShowMessage(Format(STextNotFound, [Dialog.FindText]));
end;
FControl := nil;
end;
{ TSearchFindFirst }
constructor TSearchFindFirst.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFindFirst := True;
end;
{ TSearchFindNext }
constructor TSearchFindNext.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DisableIfNoHandler := False;
Enabled := csDesigning in ComponentState;
end;
procedure TSearchFindNext.ExecuteTarget(Target: TObject);
begin
if not Assigned(FSearchFind) then exit;
FSearchFind.Search(Target);
end;
function TSearchFindNext.HandlesTarget(Target: TObject): Boolean;
begin
if Assigned(FSearchFind) then
Result := (FSearchFind.Enabled) and
(Length(TFindDialog(FSearchFind.Dialog).FindText) > 0)
else
Result := False;
end;
procedure TSearchFindNext.UpdateTarget(Target: TObject);
begin
if Assigned(FSearchFind) then
Enabled := Length(TFindDialog(FSearchFind.Dialog).FindText) > 0
else
Enabled := False;
end;
{ TFontEdit }
function TFontEdit.GetDialog: TFontDialog;
begin
Result := TFontDialog(FDialog);
end;
function TFontEdit.GetDialogClass: TCommonDialogClass;
begin
Result := TFontDialog;
end;
{ TColorSelect }
function TColorSelect.GetDialog: TColorDialog;
begin
Result := TColorDialog(FDialog);
end;
function TColorSelect.GetDialogClass: TCommonDialogClass;
begin
Result := TColorDialog;
end;
{ TPrintDlg }
function TPrintDlg.GetDialog: TPrintDialog;
begin
Result := TPrintDialog(FDialog);
end;
function TPrintDlg.Getdialogclass: TCommonDialogClass;
begin
Result := TPrintDialog;
end;
end.
|
{ ****************************************************************************** }
{ * FFMPEG video Reader by qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit FFMPEG_Reader;
{$INCLUDE zDefine.inc}
interface
uses SysUtils, Classes, CoreClasses, PascalStrings, UnicodeMixedLib, MemoryStream64, MemoryRaster, DoStatusIO, FFMPEG;
type
TFFMPEG_Reader = class;
TFFMPEG_VideoStreamReader = class;
TFFMPEG_Reader = class(TCoreClassObject)
private
FVideoSource: TPascalString;
FWorkOnGPU: Boolean;
FFormatCtx: PAVFormatContext;
FVideoCodecCtx: PAVCodecContext;
FAudioCodecCtx: PAVCodecContext;
FVideoCodec: PAVCodec;
FAudioCodec: PAVCodec;
Frame, FrameRGB: PAVFrame;
FrameRGB_buffer: PByte;
FSWS_CTX: PSwsContext;
VideoStreamIndex: integer;
AudioStreamIndex: integer;
VideoStream: PAVStream;
AVPacket_ptr: PAVPacket;
public
Current: Double;
Current_Frame: int64;
Width, Height: integer;
property VideoSource: TPascalString read FVideoSource;
property WorkOnGPU: Boolean read FWorkOnGPU;
constructor Create(const VideoSource_: TPascalString); overload;
constructor Create(const VideoSource_: TPascalString; const useGPU_: Boolean); overload;
destructor Destroy; override;
procedure OpenVideo(const VideoSource_: TPascalString; useGPU_: Boolean); overload;
procedure OpenVideo(const VideoSource_: TPascalString); overload;
procedure CloseVideo;
procedure ResetFit(NewWidth, NewHeight: integer);
function NextFrame(): Boolean;
function ReadFrame(output: TMemoryRaster; RasterizationCopy_: Boolean): Boolean;
procedure Seek(second: Double);
function Total: Double;
function CurrentStream_Total_Frame: int64;
function CurrentStream_PerSecond_Frame(): Double;
function CurrentStream_PerSecond_FrameRound(): integer;
property PSF: Double read CurrentStream_PerSecond_Frame;
property PSFRound: integer read CurrentStream_PerSecond_FrameRound;
property RoundPSF: integer read CurrentStream_PerSecond_FrameRound;
property PSF_I: integer read CurrentStream_PerSecond_FrameRound;
end;
TOnWriteBufferBefore = procedure(Sender: TFFMPEG_VideoStreamReader; var p: Pointer; var siz: NativeUInt) of object;
TOnWriteBufferAfter = procedure(Sender: TFFMPEG_VideoStreamReader; p: Pointer; siz: NativeUInt; decodeFrameNum: integer) of object;
TOnVideoFillNewRaster = procedure(Sender: TFFMPEG_VideoStreamReader; Raster: TMemoryRaster; var SaveToPool: Boolean) of object;
TFFMPEG_VideoStreamReader = class(TCoreClassObject)
private
FVideoCodecCtx: PAVCodecContext;
FVideoCodec: PAVCodec;
AVParser: PAVCodecParserContext;
AVPacket_ptr: PAVPacket;
Frame, FrameRGB: PAVFrame;
FrameRGB_buffer: PByte;
FSWS_CTX: PSwsContext;
SwapBuff: TMemoryStream64;
VideoRasterPool: TMemoryRasterList;
protected
procedure DoWriteBufferBefore(var p: Pointer; var siz: NativeUInt); virtual;
procedure DoVideoFillNewRaster(Raster: TMemoryRaster; var SaveToPool: Boolean); virtual;
procedure DoWriteBufferAfter(p: Pointer; siz: NativeUInt; decodeFrameNum: integer); virtual;
procedure InternalOpenDecodec(const codec: PAVCodec);
public
OnWriteBufferBefore: TOnWriteBufferBefore;
OnVideoFillNewRaster: TOnVideoFillNewRaster;
OnWriteBufferAfter: TOnWriteBufferAfter;
constructor Create;
destructor Destroy; override;
class procedure PrintDecodec();
procedure OpenDecodec(const codec_name: U_String); overload;
procedure OpenDecodec(const codec_id: TAVCodecID); overload;
procedure OpenDecodec(); overload; // AV_CODEC_ID_H264
procedure OpenH264Decodec();
procedure OpenMJPEGDecodec();
procedure CloseCodec;
// parser and decode frame
// return decode frame number on this step
function WriteBuffer(p: Pointer; siz: NativeUInt): integer; overload;
function WriteBuffer(stream_: TCoreClassStream): integer; overload;
function DecodedRasterNum: integer;
function LockVideoPool: TMemoryRasterList;
procedure UnLockVideoPool(freeRaster_: Boolean); overload;
procedure UnLockVideoPool(); overload;
procedure ClearVideoPool;
end;
// pascal h264
function ExtractVideoAsPasH264(VideoSource_: TPascalString; dest: TCoreClassStream): integer; overload;
function ExtractVideoAsPasH264(VideoSource_, DestH264: TPascalString): integer; overload;
// hardware h264
function ExtractVideoAsH264(VideoSource_: TPascalString; dest: TCoreClassStream; Bitrate: int64): integer; overload;
function ExtractVideoAsH264(VideoSource_: TPascalString; DestH264: TPascalString; Bitrate: int64): integer; overload;
var
// Buffer size used for online video(rtsp/rtmp/http/https), 720p 1080p 2K 4K 8K support
FFMPEG_Reader_BufferSize: integer; // default 128M
implementation
uses H264, FFMPEG_Writer, Geometry2DUnit;
function ExtractVideoAsPasH264(VideoSource_: TPascalString; dest: TCoreClassStream): integer;
var
ff: TFFMPEG_Reader;
h: TH264Writer;
Raster: TMemoryRaster;
tk: TTimeTick;
begin
DoStatus('ffmpeg open ', [VideoSource_.Text]);
try
ff := TFFMPEG_Reader.Create(VideoSource_);
DoStatus('create h264 stream %d*%d total: %d', [ff.Width, ff.Height, ff.CurrentStream_Total_Frame]);
except
Result := 0;
exit;
end;
h := TH264Writer.Create(ff.Width, ff.Height, ff.CurrentStream_Total_Frame, ff.CurrentStream_PerSecond_Frame, dest);
Raster := TMemoryRaster.Create;
tk := GetTimeTick();
while ff.ReadFrame(Raster, False) do
begin
h.WriteFrame(Raster);
if GetTimeTick() - tk > 2000 then
begin
DoStatus('%s -> h264.stream progress %d/%d', [umlGetFileName(VideoSource_).Text, h.FrameCount, ff.CurrentStream_Total_Frame]);
h.Flush;
tk := GetTimeTick();
end;
end;
Result := h.FrameCount;
disposeObject(ff);
disposeObject(h);
DoStatus('done %s -> h264 stream.', [umlGetFileName(VideoSource_).Text]);
end;
function ExtractVideoAsPasH264(VideoSource_, DestH264: TPascalString): integer;
var
ff: TFFMPEG_Reader;
h: TH264Writer;
Raster: TMemoryRaster;
tk: TTimeTick;
begin
DoStatus('ffmpeg open ', [VideoSource_.Text]);
try
ff := TFFMPEG_Reader.Create(VideoSource_);
DoStatus('create h264 stream %d*%d total: %d', [ff.Width, ff.Height, ff.CurrentStream_Total_Frame]);
except
Result := 0;
exit;
end;
h := TH264Writer.Create(ff.Width, ff.Height, ff.CurrentStream_Total_Frame, ff.CurrentStream_PerSecond_Frame, DestH264);
Raster := TMemoryRaster.Create;
tk := GetTimeTick();
while ff.ReadFrame(Raster, False) do
begin
h.WriteFrame(Raster);
if GetTimeTick() - tk > 2000 then
begin
DoStatus('%s -> %s progress %d/%d', [umlGetFileName(VideoSource_).Text, umlGetFileName(DestH264).Text, h.FrameCount, ff.CurrentStream_Total_Frame]);
h.Flush;
tk := GetTimeTick();
end;
end;
Result := h.FrameCount;
disposeObject(ff);
disposeObject(h);
DoStatus('done %s -> %s', [umlGetFileName(VideoSource_).Text, umlGetFileName(DestH264).Text]);
end;
function ExtractVideoAsH264(VideoSource_: TPascalString; dest: TCoreClassStream; Bitrate: int64): integer;
var
ff: TFFMPEG_Reader;
h: TFFMPEG_Writer;
Raster: TMemoryRaster;
tk: TTimeTick;
begin
Result := 0;
DoStatus('ffmpeg open ', [VideoSource_.Text]);
try
ff := TFFMPEG_Reader.Create(VideoSource_);
DoStatus('create h264 stream %d*%d total: %d', [ff.Width, ff.Height, ff.CurrentStream_Total_Frame]);
except
exit;
end;
h := TFFMPEG_Writer.Create(dest);
if h.OpenH264Codec(ff.Width, ff.Height, Round(ff.CurrentStream_PerSecond_Frame), Bitrate) then
begin
Raster := TMemoryRaster.Create;
tk := GetTimeTick();
while ff.ReadFrame(Raster, False) do
begin
h.EncodeRaster(Raster);
if GetTimeTick() - tk > 2000 then
begin
DoStatus('%s -> h264.stream progress %d/%d', [umlGetFileName(VideoSource_).Text, Result, ff.CurrentStream_Total_Frame]);
h.Flush;
tk := GetTimeTick();
end;
inc(Result);
end;
disposeObject(Raster);
end;
disposeObject(ff);
disposeObject(h);
DoStatus('done %s -> h264 stream.', [umlGetFileName(VideoSource_).Text]);
end;
function ExtractVideoAsH264(VideoSource_: TPascalString; DestH264: TPascalString; Bitrate: int64): integer;
var
fs: TCoreClassFileStream;
begin
try
fs := TCoreClassFileStream.Create(DestH264, fmCreate);
Result := ExtractVideoAsH264(VideoSource_, fs, Bitrate);
disposeObject(fs);
except
Result := 0;
end;
end;
constructor TFFMPEG_Reader.Create(const VideoSource_: TPascalString);
begin
inherited Create;
OpenVideo(VideoSource_);
end;
constructor TFFMPEG_Reader.Create(const VideoSource_: TPascalString; const useGPU_: Boolean);
begin
inherited Create;
OpenVideo(VideoSource_, useGPU_);
end;
destructor TFFMPEG_Reader.Destroy;
begin
CloseVideo;
inherited Destroy;
end;
procedure TFFMPEG_Reader.OpenVideo(const VideoSource_: TPascalString; useGPU_: Boolean);
var
gpu_decodec: PAVCodec;
AV_Options: PPAVDictionary;
tmp: Pointer;
i: integer;
av_st: PPAVStream;
p: Pointer;
numByte: integer;
begin
FVideoSource := VideoSource_;
FWorkOnGPU := False;
AV_Options := nil;
FFormatCtx := nil;
FVideoCodecCtx := nil;
FAudioCodecCtx := nil;
FVideoCodec := nil;
FAudioCodec := nil;
Frame := nil;
FrameRGB := nil;
AVPacket_ptr := nil;
FSWS_CTX := nil;
p := VideoSource_.BuildPlatformPChar;
// Open video file
try
tmp := TPascalString(IntToStr(FFMPEG_Reader_BufferSize)).BuildPlatformPChar;
av_dict_set(@AV_Options, 'buffer_size', tmp, 0);
av_dict_set(@AV_Options, 'stimeout', '6000000', 0);
av_dict_set(@AV_Options, 'rtsp_flags', '+prefer_tcp', 0);
av_dict_set(@AV_Options, 'rtsp_transport', '+tcp', 0);
TPascalString.FreePlatformPChar(tmp);
if (avformat_open_input(@FFormatCtx, PAnsiChar(p), nil, @AV_Options) <> 0) then
begin
RaiseInfo('Could not open source file %s', [VideoSource_.Text]);
exit;
end;
// Retrieve stream information
if avformat_find_stream_info(FFormatCtx, nil) < 0 then
begin
if FFormatCtx <> nil then
avformat_close_input(@FFormatCtx);
RaiseInfo('Could not find stream information %s', [VideoSource_.Text]);
exit;
end;
if IsConsole then
av_dump_format(FFormatCtx, 0, PAnsiChar(p), 0);
VideoStreamIndex := -1;
AudioStreamIndex := -1;
VideoStream := nil;
av_st := FFormatCtx^.streams;
for i := 0 to FFormatCtx^.nb_streams - 1 do
begin
if av_st^^.codec^.codec_type = AVMEDIA_TYPE_VIDEO then
begin
VideoStreamIndex := av_st^^.index;
FVideoCodecCtx := av_st^^.codec;
VideoStream := av_st^;
end
else if av_st^^.codec^.codec_type = AVMEDIA_TYPE_AUDIO then
begin
AudioStreamIndex := av_st^^.index;
FAudioCodecCtx := av_st^^.codec;
end;
inc(av_st);
end;
if VideoStreamIndex = -1 then
begin
RaiseInfo('Dont find a video stream');
exit;
end;
FVideoCodec := avcodec_find_decoder(FVideoCodecCtx^.codec_id);
if FVideoCodec = nil then
begin
RaiseInfo('Unsupported FVideoCodec!');
exit;
end;
if (useGPU_) and (CurrentPlatform in [epWin32, epWin64]) and (FVideoCodecCtx^.codec_id in [AV_CODEC_ID_H264, AV_CODEC_ID_HEVC]) then
begin
gpu_decodec := nil;
if FVideoCodecCtx^.codec_id = AV_CODEC_ID_H264 then
gpu_decodec := avcodec_find_decoder_by_name('h264_cuvid')
else if FVideoCodecCtx^.codec_id = AV_CODEC_ID_HEVC then
gpu_decodec := avcodec_find_decoder_by_name('hevc_cuvid');
if (avcodec_open2(FVideoCodecCtx, gpu_decodec, nil) < 0) then
begin
if avcodec_open2(FVideoCodecCtx, FVideoCodec, nil) < 0 then
begin
RaiseInfo('Could not open FVideoCodec');
exit;
end;
end
else
begin
FVideoCodec := gpu_decodec;
FWorkOnGPU := True;
end;
end
else
begin
if avcodec_open2(FVideoCodecCtx, FVideoCodec, nil) < 0 then
begin
RaiseInfo('Could not open FVideoCodec');
exit;
end;
end;
if AudioStreamIndex >= 0 then
begin
FAudioCodec := avcodec_find_decoder(FAudioCodecCtx^.codec_id);
if FAudioCodec <> nil then
avcodec_open2(FAudioCodecCtx, FAudioCodec, nil);
end;
Width := FVideoCodecCtx^.Width;
Height := FVideoCodecCtx^.Height;
Frame := av_frame_alloc();
FrameRGB := av_frame_alloc();
if (FrameRGB = nil) or (Frame = nil) then
RaiseInfo('Could not allocate AVFrame structure');
numByte := avpicture_get_size(AV_PIX_FMT_RGB32, Width, Height);
FrameRGB_buffer := av_malloc(numByte * sizeof(Cardinal));
FSWS_CTX := sws_getContext(
FVideoCodecCtx^.Width,
FVideoCodecCtx^.Height,
FVideoCodecCtx^.pix_fmt,
Width,
Height,
AV_PIX_FMT_RGB32,
SWS_FAST_BILINEAR,
nil,
nil,
nil);
avpicture_fill(PAVPicture(FrameRGB), FrameRGB_buffer, AV_PIX_FMT_RGB32, Width, Height);
AVPacket_ptr := av_packet_alloc();
Current := 0;
Current_Frame := 0;
finally
TPascalString.FreePlatformPChar(p);
end;
end;
procedure TFFMPEG_Reader.OpenVideo(const VideoSource_: TPascalString);
begin
OpenVideo(VideoSource_, True);
end;
procedure TFFMPEG_Reader.CloseVideo;
begin
if AVPacket_ptr <> nil then
av_free_packet(AVPacket_ptr);
if FrameRGB_buffer <> nil then
av_free(FrameRGB_buffer);
if FrameRGB <> nil then
av_free(FrameRGB);
if Frame <> nil then
av_free(Frame);
if FVideoCodecCtx <> nil then
avcodec_close(FVideoCodecCtx);
if FAudioCodecCtx <> nil then
avcodec_close(FAudioCodecCtx);
if FFormatCtx <> nil then
avformat_close_input(@FFormatCtx);
if FSWS_CTX <> nil then
sws_freeContext(FSWS_CTX);
FFormatCtx := nil;
FVideoCodecCtx := nil;
FAudioCodecCtx := nil;
FVideoCodec := nil;
FAudioCodec := nil;
Frame := nil;
FrameRGB := nil;
FrameRGB_buffer := nil;
AVPacket_ptr := nil;
FSWS_CTX := nil;
end;
procedure TFFMPEG_Reader.ResetFit(NewWidth, NewHeight: integer);
var
numByte: integer;
R: TRectV2;
begin
if FrameRGB_buffer <> nil then
av_free(FrameRGB_buffer);
FrameRGB_buffer := nil;
if FrameRGB <> nil then
av_free(FrameRGB);
FrameRGB := nil;
if FSWS_CTX <> nil then
sws_freeContext(FSWS_CTX);
FSWS_CTX := nil;
R := FitRect(FVideoCodecCtx^.Width, FVideoCodecCtx^.Height, RectV2(0, 0, NewWidth, NewHeight));
Width := Round(RectWidth(R));
Height := Round(RectHeight(R));
FrameRGB := av_frame_alloc();
if (FrameRGB = nil) then
RaiseInfo('Could not allocate AVFrame structure');
numByte := avpicture_get_size(AV_PIX_FMT_RGB32, Width, Height);
FrameRGB_buffer := av_malloc(numByte * sizeof(Cardinal));
FSWS_CTX := sws_getContext(
FVideoCodecCtx^.Width,
FVideoCodecCtx^.Height,
FVideoCodecCtx^.pix_fmt,
Width,
Height,
AV_PIX_FMT_RGB32,
SWS_FAST_BILINEAR,
nil,
nil,
nil);
avpicture_fill(PAVPicture(FrameRGB), FrameRGB_buffer, AV_PIX_FMT_RGB32, Width, Height);
end;
function TFFMPEG_Reader.NextFrame(): Boolean;
var
done: Boolean;
R: integer;
begin
Result := False;
done := False;
try
while (av_read_frame(FFormatCtx, AVPacket_ptr) >= 0) do
begin
if (AVPacket_ptr^.stream_index = VideoStreamIndex) then
begin
R := avcodec_send_packet(FVideoCodecCtx, AVPacket_ptr);
if R < 0 then
begin
if FWorkOnGPU then
begin
av_packet_unref(AVPacket_ptr);
CloseVideo;
OpenVideo(FVideoSource, False);
Result := NextFrame();
exit;
end;
DoStatus('Error sending a packet for decoding');
end;
done := False;
while True do
begin
R := avcodec_receive_frame(FVideoCodecCtx, Frame);
// success, a frame was returned
if R = 0 then
break;
// AVERROR(EAGAIN): output is not available in this state - user must try to send new input
if R = AVERROR_EAGAIN then
begin
av_packet_unref(AVPacket_ptr);
Result := NextFrame();
exit;
end;
// AVERROR_EOF: the decoder has been fully flushed, and there will be no more output frames
if R = AVERROR_EOF then
begin
avcodec_flush_buffers(FVideoCodecCtx);
continue;
end;
// error
if R < 0 then
begin
if FWorkOnGPU then
begin
av_packet_unref(AVPacket_ptr);
CloseVideo;
OpenVideo(FVideoSource, False);
Result := NextFrame();
exit;
end;
done := True;
break;
end;
end;
if (not done) then
inc(Current_Frame);
Result := True;
done := True;
end;
av_packet_unref(AVPacket_ptr);
if done then
break;
end;
except
end;
end;
function TFFMPEG_Reader.ReadFrame(output: TMemoryRaster; RasterizationCopy_: Boolean): Boolean;
var
done: Boolean;
R: integer;
begin
Result := False;
done := False;
try
while (av_read_frame(FFormatCtx, AVPacket_ptr) >= 0) do
begin
if (AVPacket_ptr^.stream_index = VideoStreamIndex) then
begin
R := avcodec_send_packet(FVideoCodecCtx, AVPacket_ptr);
if R < 0 then
begin
if FWorkOnGPU then
begin
av_packet_unref(AVPacket_ptr);
CloseVideo;
OpenVideo(FVideoSource, False);
Result := ReadFrame(output, RasterizationCopy_);
exit;
end;
DoStatus('Error sending a packet for decoding');
end;
done := False;
while True do
begin
R := avcodec_receive_frame(FVideoCodecCtx, Frame);
// success, a frame was returned
if R = 0 then
break;
// AVERROR(EAGAIN): output is not available in this state - user must try to send new input
if R = AVERROR_EAGAIN then
begin
av_packet_unref(AVPacket_ptr);
Result := ReadFrame(output, RasterizationCopy_);
exit;
end;
// AVERROR_EOF: the decoder has been fully flushed, and there will be no more output frames
if R = AVERROR_EOF then
begin
avcodec_flush_buffers(FVideoCodecCtx);
continue;
end;
// error
if R < 0 then
begin
if FWorkOnGPU then
begin
av_packet_unref(AVPacket_ptr);
CloseVideo;
OpenVideo(FVideoSource, False);
Result := ReadFrame(output, RasterizationCopy_);
exit;
end;
done := True;
break;
end;
end;
if (not done) then
begin
sws_scale(
FSWS_CTX,
@Frame^.data,
@Frame^.linesize,
0,
FVideoCodecCtx^.Height,
@FrameRGB^.data,
@FrameRGB^.linesize);
if RasterizationCopy_ then
begin
output.SetSize(Width, Height);
CopyPtr(FrameRGB^.data[0], @output.Bits^[0], FVideoCodecCtx^.Width * FVideoCodecCtx^.Height * 4);
end
else
output.SetWorkMemory(FrameRGB^.data[0], Width, Height);
if (AVPacket_ptr^.pts > 0) and (av_q2d(VideoStream^.time_base) > 0) then
Current := AVPacket_ptr^.pts * av_q2d(VideoStream^.time_base);
done := True;
inc(Current_Frame);
end;
Result := True;
end;
av_packet_unref(AVPacket_ptr);
if done then
exit;
end;
except
end;
output.Reset;
end;
procedure TFFMPEG_Reader.Seek(second: Double);
begin
if second = 0 then
begin
CloseVideo;
OpenVideo(FVideoSource, FWorkOnGPU);
end
else
av_seek_frame(FFormatCtx, -1, Round(second * AV_TIME_BASE), AVSEEK_FLAG_ANY);
end;
function TFFMPEG_Reader.Total: Double;
begin
Result := umlMax(FFormatCtx^.duration / AV_TIME_BASE, 0);
end;
function TFFMPEG_Reader.CurrentStream_Total_Frame: int64;
begin
Result := umlMax(VideoStream^.nb_frames, 0);
end;
function TFFMPEG_Reader.CurrentStream_PerSecond_Frame(): Double;
begin
with VideoStream^.r_frame_rate do
Result := umlMax(num / den, 0);
end;
function TFFMPEG_Reader.CurrentStream_PerSecond_FrameRound(): integer;
begin
Result := Round(CurrentStream_PerSecond_Frame());
end;
procedure TFFMPEG_VideoStreamReader.DoWriteBufferBefore(var p: Pointer; var siz: NativeUInt);
begin
if assigned(OnWriteBufferBefore) then
OnWriteBufferBefore(Self, p, siz);
end;
procedure TFFMPEG_VideoStreamReader.DoVideoFillNewRaster(Raster: TMemoryRaster; var SaveToPool: Boolean);
begin
if assigned(OnVideoFillNewRaster) then
OnVideoFillNewRaster(Self, Raster, SaveToPool);
end;
procedure TFFMPEG_VideoStreamReader.DoWriteBufferAfter(p: Pointer; siz: NativeUInt; decodeFrameNum: integer);
begin
if assigned(OnWriteBufferAfter) then
OnWriteBufferAfter(Self, p, siz, decodeFrameNum);
end;
procedure TFFMPEG_VideoStreamReader.InternalOpenDecodec(const codec: PAVCodec);
var
tmp: Pointer;
AV_Options: PPAVDictionary;
begin
FVideoCodec := codec;
if FVideoCodec = nil then
RaiseInfo('no found decoder', []);
AVParser := av_parser_init(Ord(FVideoCodec^.id));
if not assigned(AVParser) then
RaiseInfo('Parser not found');
FVideoCodecCtx := avcodec_alloc_context3(FVideoCodec);
if not assigned(FVideoCodecCtx) then
RaiseInfo('Could not allocate video Codec context');
AV_Options := nil;
tmp := TPascalString(IntToStr(FFMPEG_Reader_BufferSize)).BuildPlatformPChar;
av_dict_set(@AV_Options, 'buffer_size', tmp, 0);
TPascalString.FreePlatformPChar(tmp);
if avcodec_open2(FVideoCodecCtx, FVideoCodec, @AV_Options) < 0 then
RaiseInfo('Could not open Codec.');
AVPacket_ptr := av_packet_alloc();
Frame := av_frame_alloc();
end;
constructor TFFMPEG_VideoStreamReader.Create;
begin
inherited Create;
FVideoCodecCtx := nil;
FVideoCodec := nil;
AVParser := nil;
AVPacket_ptr := nil;
Frame := nil;
FrameRGB := nil;
FrameRGB_buffer := nil;
FSWS_CTX := nil;
SwapBuff := TMemoryStream64.CustomCreate(128 * 1024);
VideoRasterPool := TMemoryRasterList.Create;
OnWriteBufferBefore := nil;
OnVideoFillNewRaster := nil;
OnWriteBufferAfter := nil;
end;
destructor TFFMPEG_VideoStreamReader.Destroy;
begin
CloseCodec();
disposeObject(SwapBuff);
ClearVideoPool();
disposeObject(VideoRasterPool);
inherited Destroy;
end;
class procedure TFFMPEG_VideoStreamReader.PrintDecodec;
var
codec: PAVCodec;
begin
codec := av_codec_next(nil);
while codec <> nil do
begin
if av_codec_is_decoder(codec) = 1 then
DoStatus('ID[%d] Name[%s] %s', [integer(codec^.id), string(codec^.name), string(codec^.long_name)]);
codec := av_codec_next(codec);
end;
end;
procedure TFFMPEG_VideoStreamReader.OpenDecodec(const codec_name: U_String);
var
tmp: Pointer;
codec: PAVCodec;
begin
tmp := codec_name.BuildPlatformPChar();
codec := avcodec_find_decoder_by_name(tmp);
U_String.FreePlatformPChar(tmp);
if codec = nil then
RaiseInfo('no found decoder: %s', [codec_name.Text]);
InternalOpenDecodec(codec);
end;
procedure TFFMPEG_VideoStreamReader.OpenDecodec(const codec_id: TAVCodecID);
begin
InternalOpenDecodec(avcodec_find_decoder(codec_id));
end;
procedure TFFMPEG_VideoStreamReader.OpenDecodec();
begin
OpenDecodec(AV_CODEC_ID_H264);
end;
procedure TFFMPEG_VideoStreamReader.OpenH264Decodec();
begin
OpenDecodec(AV_CODEC_ID_H264);
end;
procedure TFFMPEG_VideoStreamReader.OpenMJPEGDecodec;
begin
OpenDecodec(AV_CODEC_ID_MJPEG);
end;
procedure TFFMPEG_VideoStreamReader.CloseCodec;
begin
LockObject(SwapBuff);
if AVParser <> nil then
av_parser_close(AVParser);
if FVideoCodecCtx <> nil then
avcodec_free_context(@FVideoCodecCtx);
if Frame <> nil then
av_frame_free(@Frame);
if AVPacket_ptr <> nil then
av_packet_free(@AVPacket_ptr);
if FrameRGB_buffer <> nil then
av_free(FrameRGB_buffer);
if FSWS_CTX <> nil then
sws_freeContext(FSWS_CTX);
if FrameRGB <> nil then
av_frame_free(@FrameRGB);
FVideoCodecCtx := nil;
FVideoCodec := nil;
AVParser := nil;
AVPacket_ptr := nil;
Frame := nil;
FrameRGB := nil;
FrameRGB_buffer := nil;
FSWS_CTX := nil;
SwapBuff.Clear;
UnLockObject(SwapBuff);
end;
function TFFMPEG_VideoStreamReader.WriteBuffer(p: Pointer; siz: NativeUInt): integer;
var
decodeFrameNum: integer;
function decode(): Boolean;
var
R: integer;
numByte: integer;
vr: TMemoryRaster;
SaveToPool: Boolean;
begin
Result := False;
R := avcodec_send_packet(FVideoCodecCtx, AVPacket_ptr);
if R < 0 then
begin
RaiseInfo('Error sending a packet for decoding');
exit;
end;
while R >= 0 do
begin
R := avcodec_receive_frame(FVideoCodecCtx, Frame);
if (R = AVERROR_EAGAIN) or (R = AVERROR_EOF) then
break;
if R < 0 then
begin
RaiseInfo('Error during decoding');
exit;
end;
// check ffmpeg color conversion and scaling
if (FrameRGB = nil) or (FrameRGB^.Width <> Frame^.Width) or (FrameRGB^.Height <> Frame^.Height) then
begin
if FrameRGB <> nil then
av_frame_free(@FrameRGB);
if FrameRGB_buffer <> nil then
av_free(FrameRGB_buffer);
if FSWS_CTX <> nil then
sws_freeContext(FSWS_CTX);
FrameRGB := av_frame_alloc();
numByte := avpicture_get_size(AV_PIX_FMT_RGB32, Frame^.Width, Frame^.Height);
FrameRGB_buffer := av_malloc(numByte * sizeof(Cardinal));
FSWS_CTX := sws_getContext(
Frame^.Width,
Frame^.Height,
FVideoCodecCtx^.pix_fmt,
Frame^.Width,
Frame^.Height,
AV_PIX_FMT_RGB32,
SWS_FAST_BILINEAR,
nil,
nil,
nil);
avpicture_fill(PAVPicture(FrameRGB), FrameRGB_buffer, AV_PIX_FMT_RGB32, Frame^.Width, Frame^.Height);
FrameRGB^.Width := Frame^.Width;
FrameRGB^.Height := Frame^.Height;
end;
try
sws_scale(
FSWS_CTX,
@Frame^.data,
@Frame^.linesize,
0,
Frame^.Height,
@FrameRGB^.data,
@FrameRGB^.linesize);
// extract frame to Raster
vr := NewRaster();
vr.SetSize(FrameRGB^.Width, FrameRGB^.Height);
CopyRColor(FrameRGB^.data[0]^, vr.Bits^[0], FrameRGB^.Width * FrameRGB^.Height);
SaveToPool := True;
DoVideoFillNewRaster(vr, SaveToPool);
if SaveToPool then
VideoRasterPool.Add(vr);
inc(decodeFrameNum);
except
FrameRGB := nil;
end;
end;
Result := True;
end;
var
np: Pointer;
nsiz: NativeUInt;
bufPos: int64;
R: integer;
nbuff: TMemoryStream64;
begin
decodeFrameNum := 0;
Result := 0;
if (p = nil) or (siz = 0) then
exit;
LockObject(SwapBuff);
LockObject(VideoRasterPool);
try
np := p;
nsiz := siz;
DoWriteBufferBefore(np, nsiz);
SwapBuff.Position := SwapBuff.Size;
SwapBuff.WritePtr(np, nsiz);
bufPos := 0;
while SwapBuff.Size - bufPos > 0 do
begin
R := av_parser_parse2(AVParser, FVideoCodecCtx, @AVPacket_ptr^.data, @AVPacket_ptr^.Size,
SwapBuff.PositionAsPtr(bufPos), SwapBuff.Size - bufPos, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if R < 0 then
RaiseInfo('Error while parsing');
inc(bufPos, R);
if AVPacket_ptr^.Size <> 0 then
if not decode() then
break;
end;
if SwapBuff.Size - bufPos > 0 then
begin
nbuff := TMemoryStream64.CustomCreate(SwapBuff.Delta);
SwapBuff.Position := bufPos;
nbuff.CopyFrom(SwapBuff, SwapBuff.Size - bufPos);
SwapBuff.NewParam(nbuff);
nbuff.DiscardMemory;
disposeObject(nbuff);
end
else
SwapBuff.Clear;
finally
UnLockObject(SwapBuff);
UnLockObject(VideoRasterPool);
end;
Result := decodeFrameNum;
av_packet_unref(AVPacket_ptr);
DoWriteBufferAfter(np, nsiz, decodeFrameNum);
end;
function TFFMPEG_VideoStreamReader.WriteBuffer(stream_: TCoreClassStream): integer;
const
C_Chunk_Buff_Size = 1 * 1024 * 1024;
var
tempBuff: Pointer;
chunk: NativeInt;
begin
if stream_ is TMemoryStream64 then
begin
Result := WriteBuffer(TMemoryStream64(stream_).Memory, stream_.Size);
exit;
end;
if stream_ is TMemoryStream then
begin
Result := WriteBuffer(TMemoryStream(stream_).Memory, stream_.Size);
exit;
end;
tempBuff := System.GetMemory(C_Chunk_Buff_Size);
stream_.Position := 0;
while (stream_.Position < stream_.Size) do
begin
chunk := umlMin(stream_.Size - stream_.Position, C_Chunk_Buff_Size);
if chunk <= 0 then
break;
stream_.Read(tempBuff^, chunk);
WriteBuffer(tempBuff, chunk);
end;
System.FreeMemory(tempBuff);
end;
function TFFMPEG_VideoStreamReader.DecodedRasterNum: integer;
begin
LockObject(VideoRasterPool);
Result := VideoRasterPool.Count;
UnLockObject(VideoRasterPool);
end;
function TFFMPEG_VideoStreamReader.LockVideoPool: TMemoryRasterList;
begin
LockObject(VideoRasterPool);
Result := VideoRasterPool;
end;
procedure TFFMPEG_VideoStreamReader.UnLockVideoPool(freeRaster_: Boolean);
var
i: integer;
begin
if freeRaster_ then
begin
for i := 0 to VideoRasterPool.Count - 1 do
disposeObject(VideoRasterPool[i]);
VideoRasterPool.Clear;
end;
UnLockObject(VideoRasterPool);
end;
procedure TFFMPEG_VideoStreamReader.UnLockVideoPool();
begin
UnLockVideoPool(False);
end;
procedure TFFMPEG_VideoStreamReader.ClearVideoPool;
begin
LockVideoPool();
UnLockVideoPool(True);
end;
initialization
// Buffer size used for online video(rtsp or rtmp), 720p 1080p 2K 4K 8K support
FFMPEG_Reader_BufferSize := 128 * 1024 * 1024; // default 128M
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Registration of WebBroker wizards }
{ }
{ Copyright (c) 2000-2001 Borland Software Corp. }
{ }
{*******************************************************}
unit SiteWiz;
interface
uses
Windows, SysUtils, Classes,
Dialogs, Forms, ToolsAPI, WebSess, WebDisp, WebAdapt,
WProdReg, HTTPApp, WebFact, ProdTemplateReg, NwWebPageMod, NwWebDataMod, NwPageFrame, Contnrs,
WebUsers, InetSource, InetWiz;
const
sAppServicesProperty = 'AppServices'; // do not localize
sPageDispatcherProperty = 'PageDispatcher'; // do not localize
sAdapterDispatcherProperty = 'AdapterDispatcher'; // do not localize
sDispatchActionsProperty = 'DispatchActions'; // do not localize
sSessionsProperty = 'Sessions'; // do not localize
sLocateFileServiceProperty = 'LocateFileService'; // do not localize
sApplicationAdapterProperty = 'ApplicationAdapter'; // do not localize
sEndUserAdapterProperty = 'EndUserAdapter'; // do not localize
sScriptEngineProperty = 'ScriptEngine'; // do not localize
sPageProducerProperty = 'PageProducer'; // Do not localize
sUserListProperty = 'UserListService'; // Do not localize
type
EWebWizardException = class(Exception);
TWebAppWizard = class(TNotifierObject, IOTAWizard, IOTARepositoryWizard, IOTARepositoryWizard60, IOTAProjectWizard)
private
function PageNameOfClassName(const AClassName: string): string;
public
{ IOTAWizard }
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
{ IOTARepositoryWizard }
function GetAuthor: string;
function GetComment: string;
function GetPage: string;
function GetGlyph: Cardinal;
{ IOTARepositoryWizard60 }
function GetDesigner: string;
end;
TWebModuleWizard = class(TNotifierObject, IOTAWizard, IOTARepositoryWizard, IOTARepositoryWizard60, IOTAFormWizard)
protected
FIDString: string;
FName: string;
FComment: string;
FIcon: string;
protected
{ IOTAWizard }
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
procedure ImplExecute; virtual; abstract;
{ IOTARepositoryWizard }
function GetAuthor: string;
function GetComment: string;
function GetPage: string;
function GetGlyph: Cardinal;
{ IOTARepositoryWizard60 }
function GetDesigner: string;
end;
TNewPageHelper = class
private
FSaveTemplate: string;
FSaveHaveTemplate: Boolean;
FSelectedProducerInfo: TModulePageProducerInfo;
FSelectedTemplate: TObject;
FAccess: TWebPageAccess;
FPageName: string;
FPageTitle: string;
FScriptEngine: string;
FFrame: TNewPageFrame;
FTemplate: string;
FHaveTemplate: Boolean;
FNewTemplateFile: Boolean;
FPageNameModified: Boolean;
FPageTitleModified: Boolean;
function ExtractTemplate: Boolean;
procedure ListProducers(S: TStrings);
procedure ListProducersCallback(AProducerInfo: TModulePageProducerInfo;
Info: Pointer);
procedure ListTemplates(S: TStrings; var Default: Integer);
procedure ListEngines(S: TStrings; var Default: Integer);
procedure ListTemplatesCallback(ProducerTemplate: TAbstractProducerTemplate;
Info: Pointer);
function PageNameOfClassName(const AClassName: string): string;
public
constructor Create(AFrame: TNewPageFrame);
function HaveTemplate: Boolean;
function GetTemplate: Boolean;
procedure SaveOptions;
procedure RestoreOptions;
property Template: string read FTemplate;
property Frame: TNewPageFrame read FFrame;
end;
TWebPageModuleWizard = class(TWebModuleWizard)
private
protected
procedure ImplExecute; override;
public
constructor Create;
end;
TWebDataModuleWizard = class(TWebModuleWizard)
protected
procedure ImplExecute; override;
public
constructor Create;
end;
TWebAppServiceType = (wsApplicationAdapter, wsEndUserAdapter,
wsPageDispatcher, wsAdapterDispatcher,
wsDispatchActions, wsLocateFileService,
wsSessions, wsUserList);
TWebAppServiceTypes = set of TWebAppServiceType;
TWebAppServiceClasses = array[TWebAppServiceType] of TComponentClass;
const
DefaultSelectedServices = [wsAdapterDispatcher, wsPageDispatcher,
wsApplicationAdapter];
DefaultServiceClasses: TWebAppServiceClasses = (
TApplicationAdapter, TEndUserAdapter,
TPageDispatcher, TAdapterDispatcher,
TWebDispatcher , TLocateFileService,
TSessionsService, TWebUserList
);
type
TBaseWebProjectCreator = class(TInterfacedObject, IOTACreator, IOTAProjectCreator)
private
FServiceClasses: TWebAppServiceClasses;
FSelectedServices: TWebAppServiceTypes;
function GetServices: TWebAppServiceClasses;
protected
function GetAppModuleCreator: IOTAModuleCreator; virtual; abstract;
public
{ IOTACreator }
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
property CreatorType: string read GetCreatorType;
property Existing: Boolean read GetExisting;
property FileSystem: string read GetFileSystem;
property Owner: IOTAModule read GetOwner;
property Unnamed: Boolean read GetUnnamed;
{ IOTAProjectCreator }
function GetFileName: string;
function GetOptionFileName: string;
function GetShowSource: Boolean;
procedure NewDefaultModule;
function NewOptionSource(const ProjectName: string): IOTAFile;
procedure NewProjectResource(const Project: IOTAProject);
function NewProjectSource(const ProjectName: string): IOTAFile;
property FileName: string read GetFileName;
property OptionFileName: string read GetOptionFileName;
property ShowSource: Boolean read GetShowSource;
end;
const
sHTMLComment = ' {*.%s}';
sCHTMLComment = #13#10'USEADDITIONALFILES("*.%s");';
type
TWebProjectWPageModuleCreator = class(TBaseWebProjectCreator)
private
FCacheMode: TWebModuleCacheMode;
FPageName: string;
FProducerInfo: TModulePageProducerInfo;
FAccess: TWebPageAccess;
FTemplate: string;
protected
PageTitle: string;
ScriptEngine: string;
CreateTemplateFile: Boolean;
TemplateFileExt: string;
function GetAppModuleCreator: IOTAModuleCreator; override;
public
constructor CreateProject(AProducerInfo: TModulePageProducerInfo; const ATemplate: string; const APageName: string; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess);
end;
TWebProjectWDataModuleCreator = class(TBaseWebProjectCreator)
private
FCacheMode: TWebModuleCacheMode;
protected
function GetAppModuleCreator: IOTAModuleCreator; override;
public
constructor CreateProject(ACacheMode: TWebModuleCacheMode);
end;
TFormComponentsList = class;
TComponentPropertyItem = class
public
PropertyName: string;
PropertyValue: string;
end;
TComponentObjectItem = class
public
ComponentName: string;
ComponentClassName: string;
ComponentsList: TFormComponentsList;
destructor Destroy; override;
end;
TFormComponentsList = class
private
FProperties: TObjectList;
FObjects: TObjectList;
function GetPropertyItem(I: Integer): TComponentPropertyItem;
function GetObjectItem(I: Integer): TComponentObjectItem;
public
constructor Create;
destructor Destroy; override;
function PropertyCount: Integer;
property PropertyItems[I: Integer]: TComponentPropertyItem read GetPropertyItem;
function ObjectCount: Integer;
property ObjectItems[I: Integer]: TComponentObjectItem read GetObjectItem;
procedure AddObject(const AComponentName, AComponentClassName: string;
AComponents: TFormComponentsList);
procedure AddProperty(const APropertyName, APropertyValue: string);
end;
TBaseWebModuleCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator)
private
FFileName: string;
FFormName: string;
FModuleName: string;
FAncestorName: string;
FCacheMode: TWebModuleCacheMode;
FCreateMode: TWebModuleCreateMode;
FAccess: TWebPageAccess;
FUsesUnits: string;
FComponentsList: TFormComponentsList;
FHaveComponents: Boolean;
function MinFormHeight: Integer;
function MinFormWidth: Integer;
protected
PageTitle: string;
ScriptEngine: string;
CreateTemplateFile: Boolean;
TemplateFileExt: string;
function FormatFields: string;
function FormatObjects: string;
function FormatProperties: string;
constructor CreateModule(const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess);
procedure PopulateComponentsList(AList: TFormComponentsList); virtual;
function GetComponentsList: TFormComponentsList;
property ComponentsList: TFormComponentsList read GetComponentsList;
public
destructor Destroy; override;
{ IOTACreator }
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function ImplNewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; virtual;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function ImplNewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; virtual; abstract;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function ImplNewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; virtual; abstract;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
TSiteSourceIndex = (stWebModuleSource,
stWebModuleIntf,
stWebAppPageModuleFactory,
stWebAppDataModuleFactory,
stWebPageModuleFactory,
stWebDataModuleFactory);
const
SiteSourceNames: array[TSiteSourceIndex] of string = (
'WebModuleSource',
'WebModuleIntf',
'WebAppPageModuleFactory',
'WebAppDataModuleFactory',
'WebPageModuleFactory',
'WebDataModuleFactory');
type
TBaseWebPageModuleCreator = class(TBaseWebModuleCreator, IOTAAdditionalFilesModuleCreator)
private
FSourceIndex: TSiteSourceIndex;
FIntfIndex: TSiteSourceIndex;
FFactoryIndex: TSiteSourceIndex;
FProducerTemplate: string;
FProducerInfo: TModulePageProducerInfo;
protected
procedure PopulateComponentsList(AList: TFormComponentsList); override;
public
constructor CreateModule(AProducerInfo: TModulePageProducerInfo; const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex;
const AProducerTemplate: string);
{ IOTAAdditionalFilesModuleCreator }
function GetAdditionalFilesCount: Integer;
function NewAdditionalFileSource(I: Integer; const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function GetAdditionalFileName(I: Integer): string;
function GetAdditionalFileExt(I: Integer): string;
function ImplNewHTMLSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile; virtual;
function ImplNewImplSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile; override;
function ImplNewIntfSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile; override;
end;
TBaseWebDataModuleCreator = class(TBaseWebModuleCreator)
protected
FSourceIndex: TSiteSourceIndex;
FIntfIndex: TSiteSourceIndex;
FFactoryIndex: TSiteSourceIndex;
public
constructor CreateModule(const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex);
function ImplNewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; override;
function ImplNewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile; override;
end;
TWebAppDataModuleCreator = class(TBaseWebDataModuleCreator)
private
FServices: TWebAppServiceClasses;
protected
procedure PopulateComponentsList(AList: TFormComponentsList); override;
public
constructor CreateModule(ACacheMode: TWebModuleCacheMode);
function ImplNewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; override;
end;
TWebAppPageModuleCreator = class(TBaseWebPageModuleCreator)
private
FServices: TWebAppServiceClasses;
protected
procedure PopulateComponentsList(AList: TFormComponentsList); override;
public
constructor CreateModule(AProducerInfo: TModulePageProducerInfo; const ATemplate: string; const APageName: string;
ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess);
{ IOTAModuleCreator }
function ImplNewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; override;
function GetModuleClassName: string; virtual;
end;
TWebPageModuleCreator = class(TBaseWebPageModuleCreator)
public
constructor CreateModule(AProducerInfo: TModulePageProducerInfo; const ATemplate: string; const APageName: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex);
{ IOTAModuleCreator }
function ImplNewFormFile(const FormIdent, AncestorIdent: string): IOTAFile; override;
function GetModuleClassName: string; virtual;
end;
TWebDataModuleCreator = class(TBaseWebDataModuleCreator)
public
constructor CreateModule(
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex);
end;
TWebModuleCOMFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator)
private
fFileName: string;
fFormName: string;
fModuleName: string;
public
constructor CreateModule;
{ IOTACreator }
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
{ IOTAModuleCreator }
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
TProjectFile = class(TInterfacedObject, IOTAFile)
private
fProjectName: string;
public
constructor CreateNamedProject(ProjName: string);
{ IOTAFile }
function GetSource: string;
function GetAge: TDateTime;
end;
TBaseHTMLFile = class(TInterfacedObject, IOTAFile)
{ IOTAFile }
function GetSource: string;
function ImplGetSource: string; virtual; abstract;
function GetAge: TDateTime;
end;
THTMLFile = class(TBaseHTMLFile)
protected
FTemplate: string;
public
constructor CreateModule(const ATemplate: string);
function ImplGetSource: string; override;
end;
TBaseWebFormFile = class(TInterfacedObject, IOTAFile)
protected
FFormIdent: string;
FObjects: string;
FProperties: string;
FMinWidth: Integer;
FMinHeight: Integer;
public
{ IOTAFile }
function GetSource: string;
function ImplGetSource: string; virtual;
function GetAge: TDateTime;
constructor Create(const AFormIdent, AProperties, AObjects: string;
AMinWidth, AMinHeight: Integer);
end;
TBaseWebModuleFile = class(TInterfacedObject, IOTAFile)
private
FCreateMode: TWebModuleCreateMode;
FCacheMode: TWebModuleCacheMode;
fModuleIdent: string;
fFormIdent: string;
fAncestorIdent: string;
FSourceIndex: TSiteSourceIndex;
FUsesUnits: string;
FFactoryIndex: TSiteSourceIndex;
FAccess: TWebPageAccess;
FFields: string;
function FormatFactory: string;
protected
PageTitle: string;
ScriptEngine: string;
CreateTemplateFile: Boolean;
TemplateFileExt: string;
constructor CreateModule(const AModuleIdent, AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess; AFactoryIndex: TSiteSourceIndex;
const AFields: string);
function CacheOption: string;
function CreateOption: string;
function PageInfo: string;
public
{ IOTAFile }
function GetSource: string;
function ImplGetSource: string; virtual;
function GetAge: TDateTime;
end;
TBaseWebPageModuleFile = class(TBaseWebModuleFile)
protected
constructor CreateModule(const AModuleIdent, AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex;
const AFields: string);
end;
TWebPageModuleFile = class(TBaseWebPageModuleFile)
public
constructor CreateModule(const AModuleIdent, AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex;
const AFields: string);
end;
TBaseWebDataModuleFile = class(TBaseWebModuleFile)
public
constructor CreateModule(const AModuleIdent, AAncestorIdent, AFormIdent, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex;
const AFields: string);
end;
TWebDataModuleFile = class(TBaseWebDataModuleFile);
TBaseWebModuleIntfFile = class(TInterfacedObject, IOTAFile)
private
FFields: string;
fModuleIdent: string;
fFormIdent: string;
fAncestorIdent: string;
FUsesUnits: string;
FSourceIndex: TSiteSourceIndex;
protected
constructor CreateModule(const AModuleIdent, AFormIdent, AAncestorIdent, AUsesUnits, AFields: string;
ASourceIndex: TSiteSourceIndex);
public
{ IOTAFile }
function GetSource: string;
function ImplGetIntfSource: string; virtual;
function GetAge: TDateTime;
end;
TWebModuleCOMFormFile = class(TBaseWebModuleFile, IOTAFile)
private
fModuleIdent: string;
fFormIdent: string;
fAncestorIdent: string;
public
constructor CreateModule(const ModuleIdent, FormIdent, AncestorIdent: string);
{ IOTAFile }
function ImplGetSource: string; override;
end;
TWebModuleCOMFormIntfFile = class(TBaseWebModuleIntfFile, IOTAFile)
private
fModuleIdent: string;
fFormIdent: string;
fAncestorIdent: string;
public
constructor CreateModule(const ModuleIdent, FormIdent, AncestorIdent: string);
{ IOTAFile }
function ImplGetIntfSource: string; override;
end;
TStandardProducerTemplates = class(TProducerTemplatesList)
public
constructor Create;
end;
TProducerTemplatesIndex = (prodtEndUser,
prodtPageLinks,
prodtHTMLStandard,
prodtXSLStandard,
prodtXSLDataPacket);
function GetHTMLSampleImage: string;
function GetHTMLFileExt: string;
procedure Register;
const
ProducerTemplateNames: array[TProducerTemplatesIndex] of string =
('EndUser',
'PageLinks',
'HTMLStandard',
'XSLStandard',
'XSLDataPacket');
implementation
{$R SiteWiz.res}
uses
{$IFDEF MSWINDOWS}
ActiveX, ComObj,
{$ENDIF}
WebScript,HTTPProd,
NwSiteSrv,
Controls, WebModu, SiteProd,
Registry, ComponentDesigner, SiteComp;
type
TSiteSources = class(TInetSources)
private
function GetSiteSources(SourceIndex: TSiteSourceIndex): string;
function GetProducerTemplates(TemplatesIndex: TProducerTemplatesIndex): string;
public
property SiteSources[SourceIndex: TSiteSourceIndex]: string read GetSiteSources;
property ProducerTemplates[TemplatesIndex: TProducerTemplatesIndex]: string read GetProducerTemplates;
constructor Create;
end;
var
ProjectType: TProjectType;
ProjectCoClassName: string;
SiteSources: TSiteSources;
resourcestring
sWebAppComment = 'Creates a WebSnap Application';
sWebAppName = 'WebSnap Application';
sWebSnapPageModuleComment = 'Creates a WebSnap Page Module';
sWebSnapPageModuleName = 'WebSnap Page Module';
sWebSnapDataModuleComment = 'Creates a WebSnap Data Module';
sWebSnapDataModuleName = 'WebSnap Data Module';
sNoActiveProj = 'There is currently no active project.';
sNewPage = 'WebSnap';
const
sWebAuthor = 'Borland';
sWebAppIDString = 'Borland.NewWebSnapApplication';
sWebSnapPageModuleIDString = 'Borland.NewWebSnapPageModule';
sWebSnapDataModuleIDString = 'Borland.NewWebSnapDataModule';
sWebSnapPageModuleIconName = 'SITEPAGEMODULE';
sWebSnapDataModuleIconName = 'SITEDATAMODULE';
sWebAppIconName = 'WEBAPP';
{ file scoped variables }
const sProducerTemplateNamespace = 'Borland.SiteReg';
procedure Register;
begin
RegisterPackageWizard(TWebAppWizard.Create as IOTAProjectWizard);
RegisterPackageWizard(TWebPageModuleWizard.Create);
RegisterPackageWizard(TWebDataModuleWizard.Create);
RegisterProducerTemplates(sProducerTemplateNamespace, TStandardProducerTemplates.Create);
end;
function GetWebAppServices(AServiceClasses: TWebAppServiceClasses;
ASelectedServices: TWebAppServiceTypes): TWebAppServiceClasses;
var
I: TWebAppServiceType;
begin
for I := Low(TWebAppServiceType) to High(TWebAppServiceType) do
begin
if I in ASelectedServices then
Result[I] := AServiceClasses[I]
else
Result[I] := nil;
end;
end;
function GetActiveProjectGroup: IOTAProjectGroup;
var
ModuleServices: IOTAModuleServices;
i: Integer;
begin
Result := nil;
ModuleServices := BorlandIDEServices as IOTAModuleServices;
for i := 0 to ModuleServices.ModuleCount - 1 do
if Succeeded(ModuleServices.Modules[i].QueryInterface(IOTAProjectGroup, Result)) then
Break;
end;
function GetActiveProject: IOTAProject;
var
ProjectGroup: IOTAProjectGroup;
begin
Result := nil;
ProjectGroup := GetActiveProjectGroup;
if ProjectGroup <> nil then
Result := ProjectGroup.ActiveProject;
end;
const
sWebSnapSection = 'WebSnap';
function GetRegKey: string;
begin
Result := ActiveDesigner.Environment.GetBaseRegKey + '\' + sWebSnapSection;
end;
function GetHTMLFileExt: string;
begin
if SiteComp.InternetEnvOptions <> nil then
Result := SiteComp.InternetEnvOptions.HTMLExt
else
Result := '';
if Result <> '' then
begin
if Result[1] = '.' then
Delete(Result, 1, 1);
end
else
Result := 'html'; // Do not localize
end;
function GetHTMLSampleImage: string;
begin
if SiteComp.InternetEnvOptions <> nil then
Result := SiteComp.InternetEnvOptions.SampleImageFile
else
Result := '';
end;
{ TWebAppWizard }
resourcestring
sMakeAppModuleName = 'WebAppModule';
function TWebAppWizard.PageNameOfClassName(const AClassName: string): string;
var
ModuleName: string;
FormName: string;
FileName: string;
begin
(BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName(Format(sMakeAppModuleName, [AClassName]),
ModuleName, FormName, FileName);
FileName := FileName + '';
Result := FormName;
end;
procedure RestoreWebAppDefaults(Dlg: TNewSiteSrvForm); forward;
procedure SaveWebAppDefaults(Dlg: TNewSiteSrvForm); forward;
procedure TWebAppWizard.Execute;
var
PageCreator: TWebProjectWPageModuleCreator;
DataModuleCreator: TWebProjectWDataModuleCreator;
Dlg: TNewSiteSrvForm;
begin
Dlg := TNewSiteSrvForm.Create(Application);
with Dlg do
try
PageNameOfClassNameCallback := PageNameOfClassName;
SetServiceClasses(DefaultServiceClasses);
SetSelectedServices(DefaultSelectedServices);
{$IFDEF MSWINDOWS}
RestoreWebAppDefaults(Dlg);
{$ENDIF MSWINDOWS}
if ShowModal = mrOK then
begin
SiteWiz.ProjectType := ProjectType;
if CrossPlatform then
SiteSources.SourceFlags := sfClx
else
SiteSources.SourceFlags := sfVcl;
try
if ProjectType = ptCOM then
ProjectCoClassName := CoClassName.Text;
if AppModuleType <> mtDataModule then
begin
PageCreator := TWebProjectWPageModuleCreator.CreateProject(Helper.Frame.SelectedProducerInfo, Helper.FTemplate, PageName, CacheMode,
Helper.Frame.Access);
if Helper.Frame.PageTitle <> Helper.Frame.PageName then
PageCreator.PageTitle := Helper.Frame.PageTitle;
PageCreator.ScriptEngine := Helper.Frame.ScriptEngine;
if Helper.Frame.NewTemplateFile then
begin
PageCreator.CreateTemplateFile := True;
PageCreator.TemplateFileExt := Helper.Frame.TemplateFileExt;
end
else
PageCreator.CreateTemplateFile := False;
PageCreator.FServiceClasses := GetServiceClasses;
PageCreator.FSelectedServices := GetSelectedServices;
(BorlandIDEServices as IOTAModuleServices).CreateModule(
PageCreator);
end
else
begin
DataModuleCreator := TWebProjectWDataModuleCreator.CreateProject(CacheMode);
DataModuleCreator.FServiceClasses := GetServiceClasses;
DataModuleCreator.FSelectedServices := GetSelectedServices;
(BorlandIDEServices as IOTAModuleServices).CreateModule(
DataModuleCreator);
end;
finally
SiteSources.SourceFlags := sfActiveDesigner;
end;
{$IFDEF MSWINDOWS}
if Default.Checked then
SaveWebAppDefaults(Dlg);
{$ENDIF MSWINDOWS}
end;
finally
Free;
end;
end;
function TWebAppWizard.GetAuthor: string;
begin
Result := sWebAuthor;
end;
function TWebAppWizard.GetComment: string;
begin
Result := sWebAppComment;
end;
{$IFDEF LINUX}
var
{* XPM *}
WebAppIco : array[0..44] of pchar = (
{* width height ncolors chars_per_pixel *}
'32 32 12 1',
{* colors *}
' c #000000',
'* c none',
'. c #00FFFF',
'X c #00FF00',
'o c #C0C0C0',
'O c #008080',
'+ c #808080',
'@ c #000080',
'# c #FFFFFF',
'$ c #008000',
'% c #808000',
'& c #0000FF',
{* pixels *}
'************** $$$$$$$@ ********',
'************ $$XXX$oO&@@@ ******',
'********** $$$X.X.o.oOo&@@ *****',
'********* $$$X.X...XX$$$&@@ ****',
'******** $$$X.#.#..$$$$O$$@@ ***',
'******* $$$X.#.#...$$$O$%$$@@ **',
'******* $$X.#.#.#...$$$%$$%$@@ *',
'****** $$X.#.#.#...X$$%$O$$$@@ *',
'****** $X.X.#.#.#.o$$$$$%$$$O@@ ',
'***** $O.X.......oX$$$&&%$$@&@@ ',
'***** $Xo.o.....o.$$$&&O$&@&@@@@',
'***** $O.o.o.o.o.o$$$$$%$$&@&@@@',
'***** $.O.o.o.o.oX$$O$%$%&@&@&@@',
'***** $O.O.O.O.OX$$OO%$O%$&@&@@@',
'***** $.O.O.O.OX$$$$%OO$$$$&@&@@',
'***** $O.O.O.O.$$$$$O%$$$@&$&@@@',
'***** $OO.O.O.O.O.$$$$$$$$$&@&@@',
'****** $.O.O.O.O.O.$$$$$$$&@&@@@',
'&&&&& o O.O.O.O.O.O%$$@&$&@&@&@@',
'.&.&. # .O@O$$&$&@&@&@@@',
'&o&o& # %%o###o% &@&@&@@ *',
'&&&&& # %o######o%%%%%% &@&@@ **',
'@&@&@ # %%##%%%%###+##o @&@@ % ',
'&@&@& # %o%#%% %ooooo @@@ %%% ',
'@&@&@ # %%o%#%o% %%o% *',
'@@@@@ # %%%o%#%#%% %%%#o%% *',
'@@@@@ o * %%%o#%#o%% %%o#%o%% **',
'@@@@@ + **** %%o%#o%%o%#%o%% ***',
' @ @ ******** %%o#%#%#o%% *****',
'**************** %%%%%%% *******',
'********************************',
'********************************'
);
function TWebAppWizard.GetGlyph: Cardinal;
begin
Result := Cardinal(@WebAppIco);
end;
{$ENDIF LINUX}
{$IFDEF MSWINDOWS}
function TWebAppWizard.GetGlyph: Cardinal;
begin
Result := LoadIcon(Hinstance, PChar(sWebAppIconName));
end;
{$ENDIF MSWINDOWS}
function TWebAppWizard.GetIDString: string;
begin
Result := sWebAppIDString;
end;
function TWebAppWizard.GetName: string;
begin
Result := sWebAppName;
end;
function TWebAppWizard.GetPage: string;
begin
Result := sNewPage;
end;
function TWebAppWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
function TWebAppWizard.GetDesigner: string;
begin
Result := dAny;
end;
{ TBaseWebProjectCreator }
function TBaseWebProjectCreator.GetCreatorType: string;
begin
case ProjectType of
ptCGI: Result := sConsole;
ptCOM: Result := sApplication;
{$IFDEF MSWINDOWS}
ptWinCGI: Result := sApplication;
{$ENDIF}
else
Result := sLibrary;
end;
end;
function TBaseWebProjectCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TBaseWebProjectCreator.GetFileName: string;
const
PROJ_EXT: array [Boolean] of string = ('.bpr', '.dpr'); { do not localize }
var
i: Integer;
j: Integer;
ProjGroup: IOTAProjectGroup;
Found: Boolean;
TempFileName: string;
TempFileName2: string;
begin
Result := GetCurrentDir + PathDelim + 'Project%d' + PROJ_EXT[IsPascal]; { do not localize }
ProjGroup := GetActiveProjectGroup;
if ProjGroup <> nil then
begin
for j := 0 to ProjGroup.ProjectCount-1 do
begin
Found := False;
TempFileName2 := Format(Result, [j+1]);
for i := 0 to ProjGroup.ProjectCount-1 do
begin
try
TempFileName := ProjGroup.Projects[i].FileName;
if AnsiCompareFileName(ExtractFileName(TempFileName), ExtractFileName(TempFileName2)) = 0 then
begin
Found := True;
Break;
end;
except on E: Exception do
if not (E is EIntfCastError) then
raise;
end;
end;
if not Found then
begin
Result := TempFileName2;
Exit;
end;
end;
Result := Format(Result, [ProjGroup.ProjectCount+1]);
end
else
Result := Format(Result, [1]);
end;
function TBaseWebProjectCreator.GetFileSystem: string;
begin
Result := '';
end;
function TBaseWebProjectCreator.GetOptionFileName: string;
begin
Result := '';
end;
function TBaseWebProjectCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProjectGroup;
end;
function TBaseWebProjectCreator.GetServices: TWebAppServiceClasses;
begin
Result := GetWebAppServices(FServiceClasses, FSelectedServices);
end;
function TBaseWebProjectCreator.GetShowSource: Boolean;
begin
Result := False;
end;
function TBaseWebProjectCreator.GetUnnamed: Boolean;
begin
Result := True;
end;
procedure TBaseWebProjectCreator.NewDefaultModule;
begin
case ProjectType of
ptCOM:
begin
(BorlandIDEServices as IOTAModuleServices).CreateModule(TWebModuleCOMFormCreator.CreateModule as IOTAModuleCreator);
(BorlandIDEServices as IOTAModuleServices).CreateModule(GetAppModuleCreator);
end
else
(BorlandIDEServices as IOTAModuleServices).CreateModule(GetAppModuleCreator);
end;
end;
function TBaseWebProjectCreator.NewOptionSource(
const ProjectName: string): IOTAFile;
begin
Result := nil;
end;
procedure TBaseWebProjectCreator.NewProjectResource(
const Project: IOTAProject);
begin
end;
function TBaseWebProjectCreator.NewProjectSource(
const ProjectName: string): IOTAFile;
begin
Result := TProjectFile.CreateNamedProject(ProjectName) as IOTAFile;
end;
{ TProjectFile }
constructor TProjectFile.CreateNamedProject(ProjName: string);
begin
inherited Create;
fProjectName := ProjName;
end;
function TProjectFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TProjectFile.GetSource: string;
var
AppType: string;
SourceIndex: TSourceIndex;
begin
case ProjectType of
ptCGI: SourceIndex := stCGISource;
ptCOM: SourceIndex := stCOMProjectSource;
ptApache: SourceIndex := stApache;
{$IFDEF MSWINDOWS}
ptISAPI: SourceIndex := stISAPISource;
ptWinCGI: SourceIndex := stWinCGISource;
ptApacheTwo: SourceIndex := stApacheTwo;
{$ENDIF}
else
SourceIndex := stCGISource;
end;
if ProjectType = ptCGI then
AppType := 'CONSOLE' { do not localize }
else AppType := 'GUI'; { do not localize }
if IsPascal then
Result := Format(SiteSources.InetSources[SourceIndex],
[FProjectName, AppType])
else
Result := Format(SiteSources.InetSources[SourceIndex],
[FProjectName, AppType, '' { WebInit.o no longer needed, see WebInit.h }]);
end;
{ TWebModuleWizard }
procedure TWebModuleWizard.Execute;
var
Project: IOTAProject;
begin
Project := GetActiveProject;
if Project <> nil then
begin
ImplExecute;
end
else
raise EWebWizardException.CreateRes(@sNoActiveProj);
end;
function TWebModuleWizard.GetAuthor: string;
begin
Result := sWebAuthor;
end;
function TWebModuleWizard.GetComment: string;
begin
Result := FComment;
end;
function TWebModuleWizard.GetDesigner: string;
begin
Result := (BorlandIDEServices as IOTAServices).GetActiveDesignerType;
end;
{$IFDEF LINUX}
var
(* XPM *)
WebModuleIco: array[0..41] of PChar = (
(* width height ncolors chars_per_pixel *)
'32 32 9 1',
{* colors *}
' c #000000',
'. c #00FFFF',
'X c #C0C0C0',
'o c #008080',
'O c #808080',
'+ c #000080',
'@ c #FFFFFF',
'# c #008000',
'* c None',
{* pixels *}
'*****##### *********************',
'***###....## *******************',
'**###...##### ******************',
'*###...######+ *****************',
'*#......#####+ *****************',
'#......##.####+ ****************',
'#.@.@.##..####+ ****************',
'#..@.######ooo+ ****************',
'#.@.@#XXXXXXXXO ****************',
'#.....X ',
'#.....X oooooooooooooooo X X X O',
'X#....X O',
'*##o.oX @X@X@X@X@X@X@X@X@X@X@O O',
'*X+.o.X XOOOOOOOOOOOOOOOOOOOXO O',
'**X++oX @O@@@@@@@@@@@@@@@@@X@O O',
'***XX+O XO@@@@@@@@@@@@@@@@@XXO O',
'*****XX @O@@@@@@@@@@@@@@@@@X@O O',
'******* XO@@@@@@@@@@@@@@@@@XXO O',
'******* @O@@@@@@@@@@@@@@@@@X@O O',
'******* XO@@@@@@@@@@@@@@@@@XXO O',
'******* @O@@@@@@@@@@@@@@@@@X@O O',
'******* XO@@@@@@@@@@@@@@@@@XXO O',
'******* @O@@@@@@@@@@@@@@@@@X@O O',
'******* XO@@@@@@@@@@@@@@@@@XXO O',
'******* @O@@@@@@@@@@@@@@@@@X@O O',
'******* XO@@@@@@@@@@@@@@@@@XXO O',
'******* @O@@@@@@@@@@@@@@@@@X@O O',
'******* XOXXXXXXXXXXXXXXXXXXXO O',
'******* @X@X@X@X@X@X@X@X@X@X@O O',
'******* OOOOOOOOOOOOOOOOOOOOOO O',
'******* O',
'******* OOOOOOOOOOOOOOOOOOOOOOOO'
);
var
{* XPM *}
WebPageDataIco : array[0..41]of pchar = (
{/* width height ncolors chars_per_pixel *}
'32 32 9 1',
{* colors *}
' c #000000',
'* c none',
'. c #00FFFF',
'X c #C0C0C0',
'o c #008080',
'O c #808080',
'+ c #000080',
'@ c #FFFFFF',
'# c #008000',
{* pixels *}
'*******##### *******************',
'*****###....## *****************',
'****###...##### ****************',
'***###...######+ ***************',
'***#......#####+ ***************',
'**#......##.####+ **************',
'**#.@.@.##..####+ **************',
'**#..@.######ooo+ **************',
'**#.@.@#####o.oo+ **************',
'**#......##XXXXXO **************',
'**#......##X *****',
'***#....o.#X @@@@@@@@@@@OX *****',
'***##o.o.o#X @@ooXoXo@@@OXX ****',
'***X+.o.o.#X @@@@@@@@@@@OXXX ***',
'****X++o.o.X @@oXoooo@@@O O**',
'******X++++O @@@@@@@@@@@@XXX O**',
'*******XXXXX @@@@@@@@@@@@@@@ O**',
'************ @@oXooXoo@@@@@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@ooXoooXoooo@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@oXooXooXooo@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@ooXo@@@@@@@@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@oXooXoooXoo@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@ooXoo@@@@@@@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ @@@@@@@@@@@@@@@ O**',
'************ O**',
'************ OOOOOOOOOOOOOOOOO**'
);
function TWebModuleWizard.GetGlyph: Cardinal;
begin
Result := 0;
if FIcon = sWebSnapPageModuleIconName then
Result := Cardinal(@WebPageDataIco);
if FIcon = sWebSnapDataModuleIconName then
Result := Cardinal(@WebModuleIco);
end;
{$ENDIF LINUX}
{$IFDEF MSWINDOWS}
function TWebModuleWizard.GetGlyph: Cardinal;
begin
Result := LoadIcon(Hinstance, PChar(FIcon));
end;
{$ENDIF MSWINDOWS}
function TWebModuleWizard.GetIDString: string;
begin
Result := FIDString;
end;
function TWebModuleWizard.GetName: string;
begin
Result := FName;
end;
function TWebModuleWizard.GetPage: string;
begin
Result := sNewPage;
end;
function TWebModuleWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
{ TWebPageModuleWizard }
constructor TWebPageModuleWizard.Create;
begin
inherited;
FComment := sWebSnapPageModuleComment;
FIcon := sWebSnapPageModuleIconName ;
FIDString := sWebSnapPageModuleIDString;
FName := sWebSnapPageModuleName;
end;
const
sDefaultModuleProducerName = 'DefaultModuleProducerName';
sDefaultModuleTemplateName = 'DefaultModuleTemplateName';
sDefaultModuleCreateMode = 'DefaultModuleCreateMode';
sDefaultModuleCacheMode = 'DefaultModuleCacheMode';
sDefaultModulePublished = 'DefaultModulePublished';
sDefaultModuleLoginRequired = 'DefaultModuleLoginRequired';
sDefaultModuleScriptEngine = 'DefaultModuleScriptEngine';
sDefaultModuleNewTemplateFile = 'DefaultModuleNewTemplateFile';
sMakePageModuleName = '%sPage'; { This is used as an identifier.
It shouldn't be localized }
procedure SaveWebPageDefaults(Dlg: TNewWebPageForm);
var
RegIniFile: TRegIniFile;
begin
RegIniFile := TRegIniFile.Create(GetRegKey);
with RegIniFile, Dlg do
try
WriteString('', sDefaultModuleProducerName, NewPageFrame.ProducerClassName);
WriteString('', sDefaultModuleTemplateName, NewPageFrame.SelectedTemplateName);
WriteString('', sDefaultModuleScriptEngine, NewPageFrame.ScriptEngine);
WriteBool('', sDefaultModuleLoginRequired, NewPageFrame.cbLoginRequired.Checked);
WriteBool('', sDefaultModulePublished, NewPageFrame.cbPublished.Checked);
WriteBool('', sDefaultModuleNewTemplateFile, NewPageFrame.CreateHTMLModule);
WriteInteger('', sDefaultModuleCreateMode, CreateModeIndex);
WriteInteger('', sDefaultModuleCacheMode, CacheModeIndex);
finally
RegIniFile.Free;
end;
end;
procedure RestoreWebPageDefaults(Dlg: TNewWebPageForm);
var
RegIniFile: TRegIniFile;
begin
RegIniFile := TRegIniFile.Create(GetRegKey);
with RegIniFile, Dlg do
try
NewPageFrame.ProducerClassName := ReadString('', sDefaultModuleProducerName, NewPageFrame.ProducerClassName);
NewPageFrame.SelectedTemplateName := ReadString('', sDefaultModuleTemplateName, NewPageFrame.SelectedTemplateName);
NewPageFrame.ScriptEngine := ReadString('', sDefaultModuleScriptEngine, NewPageFrame.ScriptEngine);
NewPageFrame.cbLoginRequired.Checked := ReadBool('', sDefaultModuleLoginRequired, NewPageFrame.cbLoginRequired.Checked);
NewPageFrame.cbPublished.Checked := ReadBool('', sDefaultModulePublished, NewPageFrame.cbPublished.Checked);
NewPageFrame.CreateHTMLModule := ReadBool('', sDefaultModuleNewTemplateFile, NewPageFrame.CreateHTMLModule);
CreateModeIndex := ReadInteger('', sDefaultModuleCreateMode, CreateModeIndex);
CacheModeIndex := ReadInteger('', sDefaultModuleCacheMode, CacheModeIndex);
finally
RegIniFile.Free;
end;
end;
const
sDefaultAppProducerName = 'DefaultAppProducerName';
sDefaultAppPageName = 'DefaultAppPageName';
sDefaultAppPageTitle = 'DefaultAppPageTitle';
sDefaultAppTemplateName = 'DefaultAppTemplateName';
sDefaultAppCacheMode = 'DefaultAppCacheMode';
sDefaultAppPublished = 'DefaultAppPublished';
sDefaultAppLoginRequired = 'DefaultAppLoginRequired';
sDefaultAppScriptEngine = 'DefaultAppScriptEngine';
sDefaultAppNewTemplateFile = 'DefaultAppNewTemplateFile';
sDefaultAppModuleType = 'DefaultAppModuleType';
sDefaultAppProjectType = 'DefaultAppProjectType';
sDataModuleType = 'DataModule';
sPageModuleType = 'PageModule';
sDefaultServiceClass = 'DefaultServiceClass';
sServiceChecked = 'Checked';
const
sAppModuleTypeNames: array[TWebAppModuleType] of string =
('PageModule', 'DataModule');
{$IFDEF MSWINDOWS}
sProjectTypeNames: array[TProjectType] of string =
('ISAPI', 'CGI', 'WinCGI', 'COM', 'Apache', 'ApacheTwo');
{$ENDIF}
{$IFDEF LINUX}
sProjectTypeNames: array[TProjectType] of string =
('CGI', 'Apache', 'COM');
{$ENDIF}
sWebAppServiceTypeNames: array[TWebAppServiceType] of string =
('ApplicationAdapter',
'EndUserAdapter',
'PageDispatcher',
'AdapterDispatcher',
'DispatchActions',
'LocateFileService',
'Sessions',
'UserList');
procedure SaveWebAppDefaults(Dlg: TNewSiteSrvForm);
var
RegIniFile: TRegIniFile;
I: TWebAppServiceType;
begin
RegIniFile := TRegIniFile.Create(GetRegKey);
with RegIniFile, Dlg do
try
WriteString('', sDefaultAppProjectType, sProjectTypeNames[Dlg.ProjectType]);
WriteString('', sDefaultAppModuleType, sAppModuleTypeNames[AppModuleType]);
WriteInteger('', sDefaultAppCacheMode, CacheModeIndex);
if AppModuleType <> mtDataModule then
begin
WriteString('', sDefaultAppProducerName, Helper.Frame.ProducerClassName);
WriteString('', sDefaultAppTemplateName, Helper.Frame.SelectedTemplateName);
WriteString('', sDefaultAppScriptEngine, Helper.Frame.ScriptEngine);
if not IsDefaultPageName then
WriteString('', sDefaultAppPageName, PageName)
else
WriteString('', sDefaultAppPageName, '');
if not Helper.Frame.IsDefaultPageTitle then
WriteString('', sDefaultAppPageTitle, Helper.Frame.PageTitle)
else
WriteString('', sDefaultAppPageTitle, '');
WriteBool('', sDefaultAppLoginRequired, Helper.Frame.cbLoginRequired.Checked);
WriteBool('', sDefaultAppPublished, Helper.Frame.cbPublished.Checked);
WriteBool('', sDefaultAppNewTemplateFile, Helper.Frame.CreateHTMLModule);
for I := Low(TWebAppServiceType) to High(TWebAppServiceType) do
begin
WriteString(sWebAppServiceTypeNames[I], sDefaultServiceClass, ServiceClassName[I]);
WriteBool(sWebAppServiceTypeNames[I], sServiceChecked, IncludeService[I]);
end;
end
finally
RegIniFile.Free;
end;
end;
procedure RestoreWebAppDefaults(Dlg: TNewSiteSrvForm);
var
RegIniFile: TRegIniFile;
I: TWebAppModuleType;
J: TProjectType;
K: TWebAppServiceType;
S: string;
begin
RegIniFile := TRegIniFile.Create(GetRegKey);
with RegIniFile, Dlg do
try
S := ReadString('', sDefaultAppProjectType, '');
for J := Low(TProjectType) to High(TProjectType) do
if CompareText(S, sProjectTypeNames[J]) = 0 then
Dlg.ProjectType := J;
Helper.Frame.ProducerClassName := ReadString('', sDefaultAppProducerName, Helper.Frame.ProducerClassName);
Helper.Frame.SelectedTemplateName := ReadString('', sDefaultAppTemplateName, Helper.Frame.SelectedTemplateName);
Helper.Frame.ScriptEngine := ReadString('', sDefaultAppScriptEngine, Helper.Frame.ScriptEngine);
S := ReadString('', sDefaultAppPageName, Helper.Frame.PageName);
if (S <> '') and (S <> PageName) then
begin
PageName := S;
Helper.Frame.AutoUpdatePageName := False;
end;
S := ReadString('', sDefaultAppPageTitle, Helper.Frame.PageTitle);
if (S <> '') and (S <> Helper.Frame.PageTitle) then
begin
Helper.Frame.PageTitle := S;
Helper.Frame.AutoUpdatePageTitle := False;
end;
Helper.Frame.cbLoginRequired.Checked := ReadBool('', sDefaultAppLoginRequired, Helper.Frame.cbLoginRequired.Checked);
Helper.Frame.cbPublished.Checked := ReadBool('', sDefaultAppPublished, Helper.Frame.cbPublished.Checked);
Helper.Frame.CreateHTMLModule := ReadBool('', sDefaultAppNewTemplateFile, Helper.Frame.CreateHTMLModule);
CacheModeIndex := ReadInteger('', sDefaultAppCacheMode, CacheModeIndex);
S := ReadString('', sDefaultAppModuleType, '');
for I := Low(TWebAppModuleType) to High(TWebAppModuleType) do
if CompareText(S, sAppModuleTypeNames[I]) = 0 then
AppModuleType := I;
for K := Low(TWebAppServiceType) to High(TWebAppServiceType) do
begin
ServiceClassName[K] := ReadString(sWebAppServiceTypeNames[K], sDefaultServiceClass, ServiceClassName[K]);
IncludeService[K] := ReadBool(sWebAppServiceTypeNames[K], sServiceChecked, IncludeService[K]);
end;
finally
RegIniFile.Free;
end;
end;
procedure TWebPageModuleWizard.ImplExecute;
var
ProducerInfo: TModulePageProducerInfo;
PageCreator: TWebPageModuleCreator;
Helper: TNewPageHelper;
Dlg: TNewWebPageForm;
begin
Dlg := TNewWebPageForm.Create(Application);
with Dlg do
try
Helper := TNewPageHelper.Create(NewPageFrame);
try
{$IFDEF MSWINDOWS}
RestoreWebPageDefaults(Dlg);
{$ENDIF MSWINDOWS}
if ShowModal = mrOK then
begin
ProducerInfo := NewPageFrame.SelectedProducerInfo;
PageCreator := TWebPageModuleCreator.CreateModule(ProducerInfo, Helper.FTemplate, NewPageFrame.PageName,
CreateMode, CacheMode, NewPageFrame.Access, stWebPageModuleFactory);
if NewPageFrame.PageTitle <> NewPageFrame.PageName then
PageCreator.PageTitle := NewPageFrame.PageTitle;
PageCreator.ScriptEngine := NewPageFrame.ScriptEngine;
if NewPageFrame.NewTemplateFile then
begin
PageCreator.CreateTemplateFile := True;
PageCreator.TemplateFileExt := NewPageFrame.TemplateFileExt;
end
else
PageCreator.CreateTemplateFile := False;
(BorlandIDEServices as IOTAModuleServices).CreateModule(PageCreator as IOTAModuleCreator);
{$IFDEF MSWINDOWS}
if Default.Checked then
begin
SaveWebPageDefaults(Dlg);
end;
{$ENDIF MSWINDOWS}
end;
finally
Helper.Free;
end;
finally
Free;
end;
end;
{ TBaseWebModuleCreator }
constructor TBaseWebModuleCreator.CreateModule(
const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess);
begin
inherited Create;
FComponentsList := TFormComponentsList.Create;
FAncestorName := AAncestorName;
FUsesUnits := AUsesUnits;
FCacheMode := ACacheMode;
FCreateMode := ACreateMode;
FAccess := AAccess;
(BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName(FAncestorName,
FModuleName, FFormName, FFileName);
if AFormname <> '' then
FFormName := AFormName;
end;
procedure TBaseWebModuleCreator.FormCreated(
const FormEditor: IOTAFormEditor);
begin
end;
function TBaseWebModuleCreator.GetAncestorName: string;
begin
if FAncestorName = '' then
Result := Copy(TWebModule.ClassName, 2, MaxInt)
else
Result := FAncestorName;
end;
function TBaseWebModuleCreator.GetCreatorType: string;
begin
Result := sForm;
end;
function TBaseWebModuleCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TBaseWebModuleCreator.GetFileSystem: string;
begin
Result := '';
end;
function TBaseWebModuleCreator.GetFormName: string;
begin
Result := fFormName;
end;
function TBaseWebModuleCreator.GetImplFileName: string;
begin
Result := fFileName;
end;
function TBaseWebModuleCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TBaseWebModuleCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TBaseWebModuleCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProject
end;
function TBaseWebModuleCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TBaseWebModuleCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TBaseWebModuleCreator.GetUnnamed: Boolean;
begin
Result := True;
end;
function TBaseWebModuleCreator.NewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := ImplNewFormFile(FormIdent, AncestorIdent);
end;
function TBaseWebModuleCreator.ImplNewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TBaseWebModuleCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := ImplNewImplSource(ModuleIdent, FormIdent, AncestorIdent)
end;
function TBaseWebModuleCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
if IsPascal then
Result := nil
else
Result := ImplNewIntfSource(ModuleIdent, FormIdent, AncestorIdent);
end;
destructor TBaseWebModuleCreator.Destroy;
begin
inherited;
FComponentsList.Free;
end;
function TBaseWebModuleCreator.FormatFields: string;
var
I: Integer;
begin
Result := '';
for I := 0 to ComponentsList.ObjectCount - 1 do
if IsPascal then
Result := Result + Format(#13#10' %0:s: %1:s;', [ComponentsList.ObjectItems[I].ComponentName,
ComponentsList.ObjectItems[I].ComponentClassName])
else
Result := Result + Format(#13#10#9'%0:s *%1:s;', [ComponentsList.ObjectItems[I].ComponentClassName,
ComponentsList.ObjectItems[I].ComponentName]);
end;
const
ComponentVTop = 8;
ComponentVSpace = 48;
function TBaseWebModuleCreator.MinFormWidth: Integer;
begin
Result := 215;
end;
function TBaseWebModuleCreator.MinFormHeight: Integer;
var
I: Integer;
begin
Result := 150;
I := ComponentVTop + ComponentVSpace * (ComponentsList.ObjectCount + 1);
if I > Result then
Result := I;
end;
function TBaseWebModuleCreator.FormatObjects: string;
var
Top, Left: Integer;
function FormatSubProperties(AComponents: TFormComponentsList): string;
var
I: Integer;
begin
Result := '';
if Assigned(AComponents) then
for I := 0 to AComponents.PropertyCount - 1 do
Result := Result + Format(' %0:s = %1:s'#13#10, [AComponents.PropertyItems[I].PropertyName,
AComponents.PropertyItems[I].PropertyValue]);
if Result <> '' then
Result := #13#10 + Result;
end;
function FormatSubObjects(AComponents: TFormComponentsList): string;
var
I: Integer;
begin
Result := '';
if Assigned(AComponents) then
for I := 0 to AComponents.ObjectCount - 1 do
begin
Result := Result + Format(' object %0:s: %1:s' + #13#10 + { do not localize }
' Left = %2:d' + #13#10 + { do not localize }
' Top = %3:d' + #13#10 + { do not localize }
FormatSubProperties(AComponents.ObjectItems[I].ComponentsList) +
FormatSubObjects(AComponents.ObjectItems[I].ComponentsList) +
' end' + #13#10, { do not localize }
[AComponents.ObjectItems[I].ComponentName,
AComponents.ObjectItems[I].ComponentClassName, Left, Top]);
Top := Top + ComponentVSpace;
end;
if Result <> '' then
Result := #13#10 + Result;
end;
begin
Top := ComponentVTop;
Left := 48;
Result := '';
if Assigned(ComponentsList) then
Result := FormatSubObjects(ComponentsList);
end;
function TBaseWebModuleCreator.FormatProperties: string;
var
I: Integer;
begin
Result := '';
for I := 0 to ComponentsList.PropertyCount - 1 do
Result := Result + Format(' %0:s = %1:s'#13#10, [ComponentsList.PropertyItems[I].PropertyName,
ComponentsList.PropertyItems[I].PropertyValue]);
if Result <> '' then
Result := #13#10 + Result;
end;
procedure TBaseWebModuleCreator.PopulateComponentsList(AList: TFormComponentsList);
begin
// no components
end;
function TBaseWebModuleCreator.GetComponentsList: TFormComponentsList;
begin
if not FHaveComponents then
begin
PopulateComponentsList(FComponentsList);
FHaveComponents := True;
end;
Result := FComponentsList;
end;
{ TWebModuleCOMFormCreator }
constructor TWebModuleCOMFormCreator.CreateModule;
begin
// NOTE: This is done so that the linker finds the added file _before_ any user code
// otherwise the application is not initialized correctly and the app fails.
if not IsPascal then
AddBCBAppUnits(ProjectType); // AddBCBAppUnits called elsewhere for other project types
inherited Create;
(BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName('Unit', { do not localize }
fModuleName, fFormName, fFileName); { do not localize }
FFormName := ''; // Get default form name
end;
procedure TWebModuleCOMFormCreator.FormCreated(
const FormEditor: IOTAFormEditor);
begin
end;
function TWebModuleCOMFormCreator.GetAncestorName: string;
begin
Result := '';
end;
function TWebModuleCOMFormCreator.GetCreatorType: string;
begin
Result := sForm;
end;
function TWebModuleCOMFormCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TWebModuleCOMFormCreator.GetFileSystem: string;
begin
Result := '';
end;
function TWebModuleCOMFormCreator.GetFormName: string;
begin
Result := fFormName;
end;
function TWebModuleCOMFormCreator.GetImplFileName: string;
begin
Result := fFileName;
end;
function TWebModuleCOMFormCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TWebModuleCOMFormCreator.GetMainForm: Boolean;
begin
Result := False;
end;
function TWebModuleCOMFormCreator.GetOwner: IOTAModule;
begin
Result := GetActiveProject;
end;
function TWebModuleCOMFormCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TWebModuleCOMFormCreator.GetShowSource: Boolean;
begin
Result := False;
end;
function TWebModuleCOMFormCreator.GetUnnamed: Boolean;
begin
Result := True;
end;
function TWebModuleCOMFormCreator.NewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := nil;
end;
function TWebModuleCOMFormCreator.NewImplSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := TWebModuleCOMFormFile.CreateModule(FModuleName, FormIdent, AncestorIdent) as IOTAFile
end;
function TWebModuleCOMFormCreator.NewIntfSource(const ModuleIdent, FormIdent,
AncestorIdent: string): IOTAFile;
begin
if IsPascal then
Result := nil
else
Result := TWebModuleCOMFormIntfFile.CreateModule(ModuleIdent, FormIdent, AncestorIdent) as IOTAFile;
end;
{ TBaseWebDataModuleFile }
constructor TBaseWebDataModuleFile.CreateModule(
const AModuleIdent, AAncestorIdent, AFormIdent, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex; const AFields: string);
begin
inherited CreateModule(
AModuleIdent,
AAncestorIdent,
AFormIdent,
AUsesUnits,
ACreateMode,
ACacheMode,
[], { not Published }
AFactoryIndex,
AFields);
end;
{ TBaseWebPageModuleFile }
constructor TBaseWebPageModuleFile.CreateModule(const AModuleIdent, AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess; AFactoryIndex: TSiteSourceIndex; const AFields: string);
begin
inherited CreateModule(
AModuleIdent,
AAncestorName,
AFormName,
AUsesUnits,
ACreateMode,
ACacheMode,
AAccess,
AFactoryIndex,
AFields);
end;
{ TBaseWebModuleFile }
function TBaseWebModuleFile.CacheOption: string;
begin
Result := '';
case FCacheMode of
caDestroy: Result := 'caDestroy'; { do not localize }
caCache: Result := 'caCache'; { do not localize }
else
Assert(False, 'Unknown case'); { do not localize }
end;
end;
function TBaseWebModuleFile.PageInfo: string;
var
NeedComma: Boolean;
procedure AddOption(const S: string; Include: Boolean);
var
Temp: string;
begin
Temp := '';
if NeedComma then
Temp := Temp + ', ';
Temp := Temp + S;
if Include then
begin
NeedComma := True;
Result := Result + Temp
end
else
begin
if Result <> '' then
Result := Result + ' ';
Result := Result + '{' + Temp + '}';
end;
end;
begin
NeedComma := False;
Result := '';
if IsPascal then
begin
AddOption('wpPublished', wpPublished in FAccess); { do not localize }
AddOption('wpLoginRequired', wpLoginRequired in FAccess); { do not localize }
Result := Format('[%s]', [Result]);
if CreateTemplateFile then
Result := Format('%s, ''.%s''', [Result, TemplateFileExt])
else
Result := Format('%s, ''''', [Result]);
if PageTitle <> '' then
Result := Result + ', ''''' + ', ''' + PageTitle + '''';
end
else // BCB - return only TWebPageAccess parameter other parameters are handled separately
if wpPublished in FAccess then
begin
Result := '<< wpPublished';
if wpLoginRequired in FAccess then
Result := Format('%s << wpLoginRequired', [Result])
else
Result := Format('%s /* << wpLoginRequired */', [Result])
end
else
Result := '/* << wpPublished << wpLoginRequired */'
end;
function TBaseWebModuleFile.CreateOption: string;
begin
Result := '';
case FCreateMode of
crOnDemand: Result := 'crOnDemand'; { do not localize }
crAlways: Result := 'crAlways'; { do not localize }
else
Assert(False, 'Unknown case');
end;
end;
constructor TBaseWebModuleFile.CreateModule(const AModuleIdent, AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess; AFactoryIndex: TSiteSourceIndex; const AFields: string);
begin
inherited Create;
FFields := AFields;
FAccess := AAccess;
FModuleIdent := AModuleIdent;
FAncestorIdent := AAncestorName;
FFormIdent := AFormName;
FCacheMode := ACacheMode;
FCreateMode := ACreateMode;
FUsesUnits := AUsesUnits;
FFactoryIndex := AFactoryIndex;
end;
function TBaseWebModuleFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TBaseWebModuleFile.GetSource: string;
begin
Result := ImplGetSource;
end;
function TBaseWebModuleFile.FormatFactory: string;
function GetTemplateExt: string;
begin
Result := '';
if CreateTemplateFile then
if TemplateFileExt <> '' then
Result := '.' + TemplateFileExt
end;
begin
if IsPascal then
Result := Format(SiteSources.SiteSources[FFactoryIndex],
[FFormIdent, CreateOption, CacheOption, PageInfo])
else
Result := Format(SiteSources.SiteSources[FFactoryIndex],
[FFormIdent, CreateOption, CacheOption, PageInfo, GetTemplateExt, PageTitle]);
end;
function TBaseWebModuleFile.ImplGetSource: string;
var
S: string;
begin
if CreateTemplateFile then
if IsPascal then
S := Format(sHTMLComment, [TemplateFileExt])
else
S := Format(sCHTMLComment, [TemplateFileExt])
else
S := '';
Result := Format(SiteSources.SiteSources[FSourceIndex],
[FModuleIdent, FFormIdent, FAncestorIdent, FUsesUnits,
FormatFactory, FFields, S]);
end;
{ TBaseHTMLFile }
function TBaseHTMLFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TBaseHTMLFile.GetSource: string;
begin
Result := ImplGetSource;
end;
{ TWebModuleCOMFormFile }
constructor TWebModuleCOMFormFile.CreateModule(const ModuleIdent, FormIdent,
AncestorIdent: string);
begin
inherited Create;
fModuleIdent := ModuleIdent;
fFormIdent := FormIdent;
fAncestorIdent := AncestorIdent;
end;
function TWebModuleCOMFormFile.ImplGetSource: string;
begin
Result := Format(SiteSources.InetSources[stCOMConsoleSource],
[FModuleIdent, FFormIdent, FAncestorIdent, ProjectCoClassName]);
end;
{ TWebModuleCOMFormIntfFile }
constructor TWebModuleCOMFormIntfFile.CreateModule(const ModuleIdent, FormIdent,
AncestorIdent: string);
begin
inherited Create;
fModuleIdent := ModuleIdent;
fFormIdent := FormIdent;
fAncestorIdent := AncestorIdent;
end;
function TWebModuleCOMFormIntfFile.ImplGetIntfSource: string;
begin
if IsPascal then
Result := Format(SiteSources.InetSources[stCOMConsoleSource],
[FModuleIdent, FFormIdent, FAncestorIdent])
else
Result := Format(SiteSources.InetSources[stCOMConsoleIntf],
[FModuleIdent, FFormIdent, FAncestorIdent, '', '']);
end;
{ TWebPageModuleCreator }
constructor TWebPageModuleCreator.CreateModule(
AProducerInfo: TModulePageProducerInfo;
const ATemplate: string;
const APageName: string;
ACreateMode: TWebModuleCreateMode;
ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex);
var
Units: String;
begin
if IsPascal then
Units := ', HTTPProd' { do not localize }
else
Units := '#include <HTTPProd.hpp>'; { do not localize }
inherited CreateModule(
AProducerInfo,
GetModuleClassName, // Ancestor name
APageName, // FormName
Units, // Uses Units
ACreateMode,
ACacheMode,
AAccess,
AFactoryIndex,
ATemplate);
end;
function TWebPageModuleCreator.GetModuleClassName: string;
begin
Result := Copy(TWebPageModule.ClassName, 2, MaxInt);
end;
function TWebPageModuleCreator.ImplNewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := TBaseWebFormFile.Create(FormIdent, FormatProperties, FormatObjects,
MinFormWidth, MinFormHeight);
end;
{ TWebAppPageModuleCreator }
constructor TWebAppPageModuleCreator.CreateModule(
AProducerInfo: TModulePageProducerInfo;
const ATemplate: string;
const APageName: string;
ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess);
var
Units: string;
begin
// NOTE: This is done so that the linker finds the added file _before_ any user code
// otherwise the application is not initialized correctly and the app fails.
if not IsPascal then
if ProjectType <> ptCOM then // ptCOM handled in TWebModuleCOMFormCreator.CreateModule
AddBCBAppUnits(ProjectType);
FServices := GetWebAppServices(DefaultServiceClasses, DefaultSelectedServices);
if IsPascal then
Units := ', HTTPProd, ReqMulti' { do not localize }
else
Units := '#include <HTTPProd.hpp>'#13#10'#include <ReqMulti.hpp>'; { do not localize }
inherited CreateModule(
AProducerInfo,
GetModuleClassName, // Ancestor name
APageName, // FormName
Units, // AUsesUnits
crAlways,
ACacheMode,
AAccess,
stWebAppPageModuleFactory,
ATemplate);
end;
procedure GetAppModuleComponents(AClasses: TWebAppServiceClasses; AList: TFormComponentsList);
var
SubComponentsList: TFormComponentsList;
procedure AddService(const APropertyName: string; AClass: TComponentClass);
var
S: string;
begin
S := Copy(AClass.ClassName, 2, MaxInt);
SubComponentsList.AddProperty(APropertyName, S);
AList.AddObject(S,
AClass.ClassName, nil);
end;
function ServiceToPropertyName(AValue: TWebAppServiceType): string;
begin
case AValue of
wsPageDispatcher: Result := sPageDispatcherProperty;
wsAdapterDispatcher: Result := sAdapterDispatcherProperty;
wsApplicationAdapter: Result := sApplicationAdapterProperty;
wsEndUserAdapter: Result := sEndUserAdapterProperty;
wsSessions: Result := sSessionsProperty;
wsLocateFileService: Result := sLocateFileServiceProperty;
wsDispatchActions: Result := sDispatchActionsProperty;
wsUserList: Result := sUserListProperty;
else
Assert(False);
end;
end;
var
I: TWebAppServiceType;
begin
AList.AddProperty(sAppServicesProperty, Copy(TWebAppComponents.ClassName, 2, MaxInt));
SubComponentsList := TFormComponentsList.Create;
AList.AddObject(Copy(TWebAppComponents.ClassName, 2, MaxInt),
TWebAppComponents.ClassName, SubComponentsList);
for I := Low(AClasses) to High(AClasses) do
if AClasses[I] <> nil then
AddService(ServiceToPropertyName(I), AClasses[I]);
end;
procedure TWebAppPageModuleCreator.PopulateComponentsList(
AList: TFormComponentsList);
begin
inherited;
GetAppModuleComponents(FServices, AList);
end;
function TWebAppPageModuleCreator.GetModuleClassName: string;
begin
Result := Copy(TWebAppPageModule.ClassName, 2, MaxInt);
end;
function TWebAppPageModuleCreator.ImplNewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := TBaseWebFormFile.Create(FormIdent, FormatProperties, FormatObjects,
MinFormWidth, MinFormHeight);
end;
{ TBaseWebModuleIntfFile }
constructor TBaseWebModuleIntfFile.CreateModule(const AModuleIdent,
AFormIdent, AAncestorIdent, AUsesUnits, AFields: string;
ASourceIndex: TSiteSourceIndex);
begin
FModuleIdent := AModuleIdent;
FFormIdent := AFormIdent;
FAncestorIdent := AAncestorIdent;
FUsesUnits := AUsesUnits;
FSourceIndex := ASourceIndex;
FFields := AFields;
end;
function TBaseWebModuleIntfFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TBaseWebModuleIntfFile.GetSource: string;
begin
Result := ImplGetIntfSource;
end;
function TBaseWebModuleIntfFile.ImplGetIntfSource: string;
begin
if IsPascal then
Result := Format(SiteSources.SiteSources[FSourceIndex],
[FModuleIdent, FFormIdent, FAncestorIdent, FUsesUnits])
else
Result := Format(SiteSources.SiteSources[FSourceIndex],
[FModuleIdent, FFormIdent, FAncestorIdent, FUsesUnits, FFields]);
end;
{ TBaseWebPageModuleCreator }
function TBaseWebPageModuleCreator.GetAdditionalFileName(I: Integer): string;
begin
Result := '';
end;
function TBaseWebPageModuleCreator.GetAdditionalFileExt(I: Integer): string;
begin
Result := '.' + TemplateFileExt;
end;
function TBaseWebPageModuleCreator.GetAdditionalFilesCount: Integer;
begin
if CreateTemplateFile then
Result := 1
else
Result := 0
end;
function TBaseWebPageModuleCreator.NewAdditionalFileSource(I: Integer;
const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Assert(I = 0);
Result := ImplNewHTMLSource(ModuleIdent, FormIdent, AncestorIdent);
end;
constructor TBaseWebPageModuleCreator.CreateModule(AProducerInfo: TModulePageProducerInfo; const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode; AAccess: TWebPageAccess;
AFactoryIndex: TSiteSourceIndex;
const AProducerTemplate: string);
begin
FProducerInfo := AProducerInfo;
inherited CreateModule(AAncestorName, AFormName, AUsesUnits,
ACreateMode, ACacheMode, AAccess);
FSourceIndex := stWebModuleSource;
FIntfIndex := stWebModuleIntf;
FFactoryIndex := AFactoryIndex;
FProducerTemplate := AProducerTemplate;
end;
function TBaseWebPageModuleCreator.ImplNewHTMLSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := THTMLFile.CreateModule(FProducerTemplate) as IOTAFile;
end;
function TBaseWebPageModuleCreator.ImplNewImplSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile;
var
F: TWebPageModuleFile;
begin
F := TWebPageModuleFile.CreateModule(ModuleIdent, AncestorIdent, FormIdent, FUsesUnits,
FCreateMode, FCacheMode, FAccess, FFactoryIndex, FormatFields);
F.PageTitle := PageTitle;
F.ScriptEngine := ScriptEngine;
F.CreateTemplateFile := CreateTemplateFile;
F.TemplateFileExt := TemplateFileExt;
Result := F as IOTAFile;
end;
function TBaseWebPageModuleCreator.ImplNewIntfSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TBaseWebModuleIntfFile.CreateModule(ModuleIdent, AncestorIdent, FormIdent, FUsesUnits,
FormatFields, stWebModuleIntf) as IOTAFile;
end;
procedure TBaseWebPageModuleCreator.PopulateComponentsList(AList: TFormComponentsList);
var
SubComponentsList: TFormComponentsList;
begin
inherited;
AList.AddProperty(sPageProducerProperty, Copy(FProducerInfo.ComponentClass.ClassName, 2, MaxInt));
SubComponentsList := TFormComponentsList.Create;
if FProducerInfo.ScriptEngines.Count <> 1 then
if ScriptEngine <> '' then
SubComponentsList.AddProperty(sScriptEngineProperty, Format('''%s''', [ScriptEngine]));
AList.AddObject(Copy(FProducerInfo.ComponentClass.ClassName, 2, MaxInt),
FProducerInfo.ComponentClass.ClassName, SubComponentsList);
end;
{ THTMLFile }
constructor THTMLFile.CreateModule(const ATemplate: string);
begin
FTemplate := ATemplate;
inherited Create;
end;
function THTMLFile.ImplGetSource: string;
begin
Result := FTemplate;
end;
{ TSiteSources }
constructor TSiteSources.Create;
begin
inherited;
PropValues.Add('WebSnap=TRUE'); // Do not localize
end;
function TSiteSources.GetProducerTemplates(
TemplatesIndex: TProducerTemplatesIndex): string;
begin
Result := GetSourceFromTemplate('SiteTemplates.txt', { Do not localize }
ProducerTemplateNames[TemplatesIndex], SourceFlags);
end;
function TSiteSources.GetSiteSources(
SourceIndex: TSiteSourceIndex): string;
var
SiteModulesFileName: string;
begin
if IsPascal then
SiteModulesFileName := 'SiteModules.pas' { Do not localize }
else
SiteModulesFileName := 'SiteModules.cpp'; { Do not localize }
Result := GetSourceFromTemplate(SiteModulesFileName,
SiteSourceNames[SourceIndex], SourceFlags);
end;
procedure InitWeb;
begin
{ Is Pascal now set in InetSource.pas }
SiteSources := TSiteSources.Create;
end;
procedure DoneWeb;
begin
FreeAndNil(SiteSources);
end;
{ TWebProjectWPageModuleCreator }
constructor TWebProjectWPageModuleCreator.CreateProject(AProducerInfo: TModulePageProducerInfo; const ATemplate: string; const APageName: string; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess);
begin
inherited Create;
FProducerInfo := AProducerInfo;
FAccess := AAccess;
FCacheMode := ACacheMode;
FPageName := APageName;
FTemplate := ATemplate;
end;
function TWebProjectWPageModuleCreator.GetAppModuleCreator: IOTAModuleCreator;
var
PageCreator: TWebAppPageModuleCreator;
begin
PageCreator := TWebAppPageModuleCreator.CreateModule(FProducerInfo, FTemplate, FPageName,
FCacheMode, FAccess);
PageCreator.PageTitle := PageTitle;
PageCreator.ScriptEngine := ScriptEngine;
PageCreator.CreateTemplateFile := CreateTemplateFile;
PageCreator.TemplateFileExt := TemplateFileExt;
PageCreator.FServices := GetServices;
Result := PageCreator as IOTAModuleCreator;
end;
{ TWebProjectWDataModuleCreator }
constructor TWebProjectWDataModuleCreator.CreateProject(
ACacheMode: TWebModuleCacheMode);
begin
inherited Create;
FCacheMode := ACacheMode;
end;
function TWebProjectWDataModuleCreator.GetAppModuleCreator: IOTAModuleCreator;
var
DataModuleCreator: TWebAppDataModuleCreator;
begin
DataModuleCreator := TWebAppDataModuleCreator.CreateModule(FCacheMode);
DataModuleCreator.FServices := GetServices;
Result := DataModuleCreator as IOTAModuleCreator;
end;
{ TWebAppDataModuleCreator }
constructor TWebAppDataModuleCreator.CreateModule(
ACacheMode: TWebModuleCacheMode);
var
Units: string;
begin
FServices := GetWebAppServices(DefaultServiceClasses, DefaultSelectedServices);
if IsPascal then
Units := ', ReqMulti' { do not localize }
else
Units := '#include <ReqMulti.hpp>'; { do not localize }
inherited CreateModule(Copy(TWebAppDataModule.ClassName, 2, MaxInt),
'', // Formname
Units, // AUsesUnits
crAlways,
ACacheMode,
stWebAppDataModuleFactory); // FactoryIndex
end;
procedure TWebAppDataModuleCreator.PopulateComponentsList(AList: TFormComponentsList);
begin
GetAppModuleComponents(FServices, AList);
end;
function TWebAppDataModuleCreator.ImplNewFormFile(const FormIdent,
AncestorIdent: string): IOTAFile;
begin
Result := TBaseWebFormFile.Create(FormIdent, FormatProperties, FormatObjects,
MinFormWidth, MinFormHeight);
end;
{ TBaseWebDataModuleCreator }
constructor TBaseWebDataModuleCreator.CreateModule(const AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex);
begin
inherited CreateModule(AAncestorName, AFormName, AUsesUnits,
ACreateMode, ACacheMode, []);
FSourceIndex := stWebModuleSource;
FIntfIndex := stWebModuleIntf;
FFactoryIndex := AFactoryIndex;
end;
function TBaseWebDataModuleCreator.ImplNewImplSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TWebDataModuleFile.CreateModule(ModuleIdent, AncestorIdent, FormIdent, FUsesUnits,
FCreateMode, FCacheMode, FFactoryIndex, FormatFields) as IOTAFile;
end;
function TBaseWebDataModuleCreator.ImplNewIntfSource(const ModuleIdent,
FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TBaseWebModuleIntfFile.CreateModule(ModuleIdent, AncestorIdent, FormIdent,
FUsesUnits, FormatFields,
stWebModuleIntf) as IOTAFile;
end;
{ TWebPageModuleFile }
constructor TWebPageModuleFile.CreateModule(const AModuleIdent,
AAncestorName, AFormName, AUsesUnits: string;
ACreateMode: TWebModuleCreateMode; ACacheMode: TWebModuleCacheMode;
AAccess: TWebPageAccess; AFactoryIndex: TSiteSourceIndex; const AFields: string);
begin
inherited CreateModule(
AModuleIdent,
AAncestorName,
AFormName,
AUsesUnits,
ACreateMode,
ACacheMode,
AAccess,
AFactoryIndex,
AFields);
end;
{ TWebDataModuleCreator }
constructor TWebDataModuleCreator.CreateModule(
ACreateMode: TWebModuleCreateMode;
ACacheMode: TWebModuleCacheMode;
AFactoryIndex: TSiteSourceIndex);
begin
inherited CreateModule(
Copy(TWebDataModule.ClassName, 2, MaxInt), // Ancestor name
'', // FormName
'', // UsesUnits
ACreateMode,
ACacheMode,
AFactoryIndex);
end;
{ TBaseWebFormFile }
constructor TBaseWebFormFile.Create(const AFormIdent, AProperties, AObjects: string;
AMinWidth, AMinHeight: Integer);
begin
FFormIdent := AFormIdent;
FObjects := AObjects;
FProperties := AProperties;
FProperties := AProperties;
FMinWidth := AMinWidth;
FMinHeight := AMinHeight;
inherited Create;
end;
function TBaseWebFormFile.GetAge: TDateTime;
begin
Result := -1;
end;
function TBaseWebFormFile.GetSource: string;
begin
Result := ImplGetSource;
end;
function TBaseWebFormFile.ImplGetSource: string;
begin
Result := Format(
'object %0:s: %1:s' + #13#10 + { do not localize }
' OldCreateOrder = False%2:s' + #13#10 + { do not localize }
' Left = 254' + #13#10 + { do not localize }
' Top = 107' + #13#10 + { do not localize }
' Height = %4:d' + #13#10 + { do not localize }
' Width = %5:d%3:s' + #13#10 + { do not localize }
'end', [FFormIdent, 'T' + FFormIdent, FProperties, { do not localize }
FObjects, FMinHeight, FMinWidth]);
end;
{ TNewPageHelper }
procedure TNewPageHelper.ListProducersCallback(AProducerInfo: TModulePageProducerInfo;
Info: Pointer);
var
S: TStrings;
begin
S := TStrings(Info);
// Assumes object is not temporary
S.AddObject(AProducerInfo.ProducerName, AProducerInfo);
end;
procedure TNewPageHelper.ListTemplatesCallback(ProducerTemplate: TAbstractProducerTemplate;
Info: Pointer);
var
S: TStrings;
begin
S := TStrings(Info);
// Assumes object is not temporary
S.AddObject(ProducerTemplate.Name, ProducerTemplate);
end;
procedure TNewPageHelper.ListProducers(S: TStrings);
begin
EnumRegisteredModulePageProducers(ListProducersCallback, Pointer(S));
end;
procedure TNewPageHelper.ListTemplates(S: TStrings;
var Default: Integer);
var
I: Integer;
ProducerInfo: TModulePageProducerInfo;
T: TStringList;
begin
ProducerInfo := FFrame.SelectedProducerInfo;
T := TStringList.Create;
try
EnumRegisteredProducerTemplatesOfClass(ListTemplatesCallback, ProducerInfo.ComponentClass, Pointer(T));
T.Sort;
S.Assign(T);
finally
T.Free;
end;
for I := S.Count -1 downto 0 do
with S.Objects[I] as TAbstractProducerTemplate do
if not SupportsScriptEngine(FFrame.ScriptEngine) or
not SupportsFileType(ProducerInfo.TemplateFileType) then
S.Delete(I);
for I := S.Count -1 downto 0 do
with S.Objects[I] as TAbstractProducerTemplate do
if IsDefault(ProducerInfo.ComponentClass) then
begin
Default := I;
Exit;
end;
Default := -1;
end;
resourcestring
sScriptNone = '(none)';
procedure TNewPageHelper.ListEngines(S: TStrings;
var Default: Integer);
var
I: Integer;
ProducerInfo: TModulePageProducerInfo;
L: TStrings;
begin
ProducerInfo := FFrame.SelectedProducerInfo;
L := TStringList.Create;
try
with ScriptEnginesList as TScriptEnginesList do
ListLanguageNames(L);
for I := 0 to L.Count - 1 do
begin
if ProducerInfo.SupportsScriptEngine(L[I]) then
S.AddObject(L[I], TObject(1));
end;
if ProducerInfo.SupportsScriptEngine('') then
S.InsertObject(0, sScriptNone, TObject(0));
Default := S.IndexOf('JScript'); { do not localize }
if Default = -1 then
if (S.Count > 1) and (S.Objects[0] = nil) then
Default := 1
else
Default := 0;
finally
L.Free;
end;
if ProducerInfo.RequiresScriptEngine and (S.Count = 0) then
try
ProducerInfo.RaiseMissingScriptEngine;
except
Application.HandleException(Self);
end;
end;
function TNewPageHelper.ExtractTemplate: Boolean;
var
ProducerInfo: TModulePageProducerInfo;
T: TObject;
Template: TAbstractProducerTemplate;
begin
FTemplate := '';
ProducerInfo := FFrame.SelectedProducerInfo;
T := FFrame.SelectedTemplate;
if T <> nil then
begin
Template := T as TAbstractProducerTemplate;
Result := Template.GetText(ProducerInfo.ComponentClass, FFrame.ScriptEngine, ProducerInfo.RequiredTags, FTemplate);
end
else
Result := True;
FHaveTemplate := Result;
end;
function TNewPageHelper.PageNameOfClassName(const AClassName: string): string;
var
ModuleName: string;
FormName: string;
FileName: string;
begin
(BorlandIDEServices as IOTAModuleServices).GetNewModuleAndClassName(Format(sMakePageModuleName, [AClassName]),
ModuleName, FormName, FileName);
Result := FormName;
end;
constructor TNewPageHelper.Create(AFrame: TNewPageFrame);
var
S: TStrings;
begin
FFrame := AFrame;
FFrame.PageNameOfClassNameCallback := PageNameOfClassName;
FFrame.ListTemplatesCallback := ListTemplates;
FFrame.ListEnginesCallback := ListEngines;
FFrame.ExtractTemplateCallback := ExtractTemplate;
S := TStringList.Create;
try
ListProducers(S);
FFrame.cbProducerType.Items.Assign(S);
FFrame.SelectedProducerInfo := S.Objects[0] as TModulePageProducerInfo;
finally
S.Free;
end;
FTemplate := '';
inherited Create;
end;
procedure TNewPageHelper.RestoreOptions;
begin
FFrame.SelectedProducerInfo := FSelectedProducerInfo;
FFrame.SelectedTemplate := FSelectedTemplate;
FFrame.Access := FAccess;
FFrame.PageName := FPageName;
FFrame.PageTitle := FPageTitle;
FFrame.edPageName.Modified := FPageNameModified;
FFrame.edTitle.Modified := FPageTitleModified;
FFrame.ScriptEngine := FScriptEngine;
FFrame.NewTemplateFile := FNewTemplateFile;
FHaveTemplate := FSaveHaveTemplate;
FTemplate := FSaveTemplate;
end;
procedure TNewPageHelper.SaveOptions;
begin
FSelectedProducerInfo := FFrame.SelectedProducerInfo;
FSelectedTemplate := FFrame.SelectedTemplate;
FAccess := FFrame.Access;
FPageName := FFrame.PageName;
FPageNameModified := FFrame.edPageName.Modified;
FPageTitleModified := FFrame.edTitle.Modified;
FPageTitle := FFrame.PageTitle;
FScriptEngine := FFrame.ScriptEngine;
FNewTemplateFile := FFrame.NewTemplateFile;
FSaveHaveTemplate := FHaveTemplate;
FSaveTemplate := FTemplate;
end;
function TNewPageHelper.GetTemplate: Boolean;
begin
Result := ExtractTemplate;
end;
function TNewPageHelper.HaveTemplate: Boolean;
begin
Result := FHaveTemplate;
end;
{ TFormComponentsList }
procedure TFormComponentsList.AddObject(const AComponentName,
AComponentClassName: string; AComponents: TFormComponentsList);
var
Item: TComponentObjectItem;
begin
Item := TComponentObjectItem.Create;
Item.ComponentName := AComponentName;
Item.ComponentClassName := AComponentClassName;
Item.ComponentsList := AComponents;
FObjects.Add(Item);
end;
procedure TFormComponentsList.AddProperty(const APropertyName,
APropertyValue: string);
var
Item: TComponentPropertyItem;
begin
Item := TComponentPropertyItem.Create;
Item.PropertyName := APropertyName;
Item.PropertyValue := APropertyValue;
FProperties.Add(Item);
end;
constructor TFormComponentsList.Create;
begin
FObjects := TObjectList.Create(True { Owned });
FProperties := TObjectList.Create(True { Owned });
inherited Create;
end;
destructor TFormComponentsList.Destroy;
begin
inherited;
FObjects.Free;
FProperties.Free;
end;
function TFormComponentsList.GetObjectItem(I: Integer): TComponentObjectItem;
begin
Result := FObjects[I] as TComponentObjectItem;
end;
function TFormComponentsList.GetPropertyItem(
I: Integer): TComponentPropertyItem;
begin
Result := FProperties[I] as TComponentPropertyItem;
end;
function TFormComponentsList.ObjectCount: Integer;
begin
Result := FObjects.Count;
end;
function TFormComponentsList.PropertyCount: Integer;
begin
Result := FProperties.Count;
end;
{ TWebDataModuleWizard }
constructor TWebDataModuleWizard.Create;
begin
inherited;
FComment := sWebSnapDataModuleComment;
FIcon := sWebSnapDataModuleIconName ;
FIDString := sWebSnapDataModuleIDString;
FName := sWebSnapDataModuleName;
end;
procedure TWebDataModuleWizard.ImplExecute;
begin
with TNewWebDataModForm.Create(Application) do
try
if ShowModal = mrOK then
begin
(BorlandIDEServices as IOTAModuleServices).CreateModule(TWebDataModuleCreator.CreateModule(
CreateMode, CacheMode, stWebDataModuleFactory) as IOTAModuleCreator)
end;
finally
Free;
end;
end;
{ TStandardProducerTemplates }
resourcestring
sStandardHTMLTemplateName = 'Standard';
sStandardXSLTemplateName = 'Standard';
sDataPacketXSLTemplateName = 'Data Packet';
constructor TStandardProducerTemplates.Create;
var
PageLinks: string;
EndUser: string;
begin
PageLinks := Format(SiteSources.ProducerTemplates[prodtPageLinks], ['|']);
EndUser := Format(SiteSources.ProducerTemplates[prodtEndUser], ['|']);
inherited Create;
Add(TProducerTemplateScriptString.Create(sStandardHTMLTemplateName,
Format(SiteSources.ProducerTemplates[prodtHTMLStandard], ['|',
PageLinks, EndUser]),
[], [], [sHTMLTemplateFileType], True { Default } ));
Add(TProducerTemplateScriptString.Create(sStandardXSLTemplateName,
Format(SiteSources.ProducerTemplates[prodtXSLStandard], ['|']),
[], [], [sXSLTemplateFileType], True { Default } ));
Add(TProducerTemplateScriptString.Create(sDataPacketXSLTemplateName,
Format(SiteSources.ProducerTemplates[prodtXSLDataPacket], ['|']),
[], [], [sXSLTemplateFileType], False ));
Add(TProducerTemplateString.Create(sBlankTemplateName, '%0:s',
[], [], []));
end;
{ TComponentObjectItem }
destructor TComponentObjectItem.Destroy;
begin
inherited;
ComponentsList.Free;
end;
initialization
begin
InitWeb;
{$IFDEF MSWINDOWS}
if Assigned(ComObj.CoInitializeEx) then
ComObj.CoInitializeEx(nil, COINIT_MULTITHREADED or COINIT_APARTMENTTHREADED)
else
CoInitialize(nil);
{$ENDIF}
end;
finalization
begin
DoneWeb;
UnRegisterProducerTemplates(sProducerTemplateNamespace);
{$IFDEF MSWINDOWS}
CoUninitialize;
{$ENDIF}
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.