text
stringlengths
14
6.51M
unit UnLancarDinheiroView; interface uses SysUtils, Controls, ExtCtrls, StdCtrls, Classes, Forms, JvExStdCtrls, JvEdit, JvValidateEdit, { Fluente } Util, UnModelo, Pagamentos, Componentes, UnAplicacao, UnTeclado; type TLancarDinheiroView = class(TForm, ITela) Label1: TLabel; EdtValor: TJvValidateEdit; btnOk: TPanel; Label2: TLabel; EdtDinheiro: TJvValidateEdit; Label3: TLabel; EdtTroco: TJvValidateEdit; procedure btnOkClick(Sender: TObject); procedure EdtValorEnter(Sender: TObject); procedure EdtDinheiroEnter(Sender: TObject); procedure EdtValorExit(Sender: TObject); procedure EdtDinheiroExit(Sender: TObject); private FControlador: IResposta; FModelo: TModelo; FTeclado: TTeclado; public function Controlador(const Controlador: IResposta): ITela; function Descarregar: ITela; function ExibirTela: Integer; function Modelo(const Modelo: TModelo): ITela; function Preparar: ITela; published procedure CalcularTroco(Sender: TObject); end; var LancarDinheiroView: TLancarDinheiroView; implementation {$R *.dfm} procedure TLancarDinheiroView.btnOkClick(Sender: TObject); begin if Supports(Self.FModelo, IPagamentoDinheiro) then (Self.FModelo as IPagamentoDinheiro) .RegistrarPagamentoEmDinheiro( TMap.Create .Gravar('valor', Self.EdtValor.AsFloat) .Gravar('dinheiro', Self.EdtDinheiro.Text) .Gravar('troco', Self.EdtTroco.Text) ); Self.ModalResult := mrOk; end; procedure TLancarDinheiroView.CalcularTroco(Sender: TObject); begin if (Self.EdtValor.Value > 0) and (Self.EdtDinheiro.Value) then Self.EdtTroco.Value := Self.EdtDinheiro.Value - Self.EdtValor.Value else Self.EdtTroco.Value := 0; end; function TLancarDinheiroView.Modelo( const Modelo: TModelo): ITela; begin Self.FModelo := Modelo; Result := Self; end; function TLancarDinheiroView.Descarregar: ITela; begin Self.FModelo := nil; Self.FControlador := nil; Result := Self; end; function TLancarDinheiroView.Preparar: ITela; begin Self.EdtValor.Value := Self.FModelo.Parametros.Ler('total').ComoDecimal; Result := Self; end; function TLancarDinheiroView.Controlador( const Controlador: IResposta): ITela; begin Self.FControlador := Controlador; Result := Self; end; procedure TLancarDinheiroView.EdtDinheiroEnter(Sender: TObject); begin if Self.FTeclado = nil then begin Self.FTeclado := TTeclado.Create(nil); Self.FTeclado.Top := Self.Height - Self.FTeclado.Height; Self.FTeclado.Parent := Self; end; Self.FTeclado.ControleDeEdicao(Sender as TCustomEdit); Self.FTeclado.Visible := True; end; procedure TLancarDinheiroView.EdtDinheiroExit(Sender: TObject); begin Self.CalcularTroco(Sender); if Self.FTeclado <> nil then Self.FTeclado.Visible := True; end; procedure TLancarDinheiroView.EdtValorEnter(Sender: TObject); begin if Self.FTeclado = nil then begin Self.FTeclado := TTeclado.Create(nil); Self.FTeclado.Top := Self.Height - Self.FTeclado.Height; Self.FTeclado.Parent := Self; end; Self.FTeclado.ControleDeEdicao(Sender as TCustomEdit); Self.FTeclado.Visible := True; end; procedure TLancarDinheiroView.EdtValorExit(Sender: TObject); begin Self.CalcularTroco(Sender); if Self.FTeclado <> nil then Self.FTeclado.Visible := True; end; function TLancarDinheiroView.ExibirTela: Integer; begin Result := Self.ShowModal; end; end.
unit ui100; interface // O Modelo não precisa conhecer ninguem // Ai esta o interessante do MVC. // Desta forma o modelo fica desacoplado e podendo ser utilizado por vários controles uses Contnrs, // <-- Nesta Unit está implementado TObjectList MVCInterfaces,uRegistroEmpresaContabil,uCST, uI010; type TI100 = class(TRegistroEmpresaContabil) private fID : Integer; // Toda chave primaria nossa no banco dentro do objeto vai chamar ID FOnModeloMudou: TModeloMudou; fTotalFaturamento: Real; fValorPIS: Real; fBaseCalculoCOFINS: Real; fBaseCalculoPIS: Real; fValorCOFINS: Real; fAliquotaCOFINS: Real; fAliquotaPIS: Real; fCST: TCST; fI010: TI010; procedure SetOnModeloMudou(const Value: TModeloMudou); procedure SetAliquotaCOFINS(const Value: Real); procedure SetAliquotaPIS(const Value: Real); procedure SetBaseCalculoCOFINS(const Value: Real); procedure SetBaseCalculoPIS(const Value: Real); procedure SetCST(const Value: TCST); procedure SetID(const Value: Integer); procedure SetTotalFaturamento(const Value: Real); procedure SetValorCOFINS(const Value: Real); procedure SetValorPIS(const Value: Real); procedure SetI010(const Value: TI010); public property ID : Integer read fID write SetID; property I010 : TI010 read fI010 write SetI010; property CST : TCST read fCST write SetCST; property TotalFaturamento : Real read fTotalFaturamento write SetTotalFaturamento; property AliquotaPIS : Real read fAliquotaPIS write SetAliquotaPIS; property BaseCalculoPIS : Real read fBaseCalculoPIS write SetBaseCalculoPIS; property ValorPIS : Real read fValorPIS write SetValorPIS; property AliquotaCOFINS : Real read fAliquotaCOFINS write SetAliquotaCOFINS; property BaseCalculoCOFINS : Real read fBaseCalculoCOFINS write SetBaseCalculoCOFINS; property ValorCOFINS : Real read fValorCOFINS write SetValorCOFINS; //property OnModeloMudou: TModeloMudou read GetOnModeloMudou write SetOnModeloMudou; // Precisa ver se assim funciona em versões mais novas de Delphi property OnModeloMudou: TModeloMudou read FOnModeloMudou write SetOnModeloMudou; // Assim funcionou em Delphi 7 function GetTodosdoI010 : TObjectList; function inserir : boolean; constructor create(); end; implementation uses UI100BD, UEmpresa; constructor TI100.create; begin Empresa := TEmpresa.create; fCST := TCST.create; fI010 := TI010.create; end; procedure TI100.SetAliquotaCOFINS(const Value: Real); begin fAliquotaCOFINS := Value; end; procedure TI100.SetAliquotaPIS(const Value: Real); begin fAliquotaPIS := Value; end; procedure TI100.SetBaseCalculoCOFINS(const Value: Real); begin fBaseCalculoCOFINS := Value; end; procedure TI100.SetBaseCalculoPIS(const Value: Real); begin fBaseCalculoPIS := Value; end; procedure TI100.SetCST(const Value: TCST); begin fCST := Value; end; procedure TI100.SetI010(const Value: TI010); begin fI010 := Value; end; procedure TI100.SetID(const Value: Integer); begin fID := Value; end; procedure TI100.SetOnModeloMudou(const Value: TModeloMudou); begin end; procedure TI100.SetTotalFaturamento(const Value: Real); begin fTotalFaturamento := Value; end; procedure TI100.SetValorCOFINS(const Value: Real); begin fValorCOFINS := Value; end; procedure TI100.SetValorPIS(const Value: Real); begin fValorPIS := Value; end; function TI100.GetTodosdoI010: TObjectList; var lI100BD : TI100BD; begin lI100BD := TI100BD.Create; result := lI100BD.GetTodosdoI010(self); end; function TI100.inserir: boolean; var lI100BD : TI100BD; begin lI100BD := TI100BD.Create; result := lI100BD.Inserir(self); lI100BD.Free; lI100BD := nil; end; end.
unit CachedUp; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ExtCtrls, DBCtrls, Grids, DBGrids, IBCustomDataSet, Db, IBQuery; type TCacheDemoForm = class(TForm) DBGrid1: TDBGrid; MainMenu1: TMainMenu; miAbout: TMenuItem; DBNavigator1: TDBNavigator; GroupBox1: TGroupBox; UnmodifiedCB: TCheckBox; ModifiedCB: TCheckBox; InsertedCB: TCheckBox; DeletedCB: TCheckBox; Panel2: TPanel; ApplyUpdatesBtn: TButton; CancelUpdatesBtn: TButton; RevertRecordBtn: TButton; ReExecuteButton: TButton; RadioGroup1: TRadioGroup; btnUpdateStatus: TButton; procedure ApplyUpdatesBtnClick(Sender: TObject); procedure ToggleUpdateMode(Sender: TObject); procedure miAboutClick(Sender: TObject); procedure CancelUpdatesBtnClick(Sender: TObject); procedure RevertRecordBtnClick(Sender: TObject); procedure UpdateRecordsToShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ReExecuteButtonClick(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure btnUpdateStatusClick(Sender: TObject); private { Private declarations } FDataSet: TIBCustomDataSet; procedure SetControlStates(Enabled: Boolean); public { Public declarations } end; var CacheDemoForm: TCacheDemoForm; implementation {$R *.dfm} uses About, ErrForm, DataMod, typInfo; { This method enables and disables controls when cached updates are turned on and off } procedure TCacheDemoForm.SetControlStates(Enabled: Boolean); begin ApplyUpdatesBtn.Enabled := Enabled; CancelUpdatesBtn.Enabled := Enabled; RevertRecordBtn.Enabled := Enabled; UnmodifiedCB.Enabled := Enabled; ModifiedCB.Enabled := Enabled; InsertedCB.Enabled := Enabled; DeletedCB.Enabled := Enabled; end; procedure TCacheDemoForm.FormCreate(Sender: TObject); begin FDataSet := CacheData.CacheDS.DataSet as TIBCustomDataSet; FDataset.Close; SetControlStates(true); FDataSet.Open; end; procedure TCacheDemoForm.ToggleUpdateMode(Sender: TObject); var NewState : Boolean; begin { Toggle the state of the CachedUpdates property } if IsPublishedProp(FDataset, 'CachedUpdates') then begin FDataset.Close; NewState := not Boolean(GetOrdProp(FDataset, 'CachedUpdates')); SetOrdProp(FDataSet, 'CachedUpdates', Integer(NewState)); { Enable/Disable Controls } SetControlStates(NewState); FDataset.Open; end; end; procedure TCacheDemoForm.miAboutClick(Sender: TObject); begin ShowAboutDialog; end; procedure TCacheDemoForm.ApplyUpdatesBtnClick(Sender: TObject); begin FDataSet.Database.ApplyUpdates([FDataSet]); end; procedure TCacheDemoForm.CancelUpdatesBtnClick(Sender: TObject); begin FDataSet.CancelUpdates; end; procedure TCacheDemoForm.RevertRecordBtnClick(Sender: TObject); begin FDataSet.RevertRecord; end; { This event is triggered when the user checks or unchecks one of the "Show Records" check boxes. It translates the states of the checkboxes into a set value which is required by the UpdateRecordTypes property of TDataSet. The UpdateRecordTypes property controls what types of records are included in the dataset. The default is to show only unmodified modified and inserted records. To "undelete" a record, you would check the Deleted checkbox, then position the grid to the row you want to undelete and finally click the Revert Record Button } procedure TCacheDemoForm.UpdateRecordsToShow(Sender: TObject); var UpdRecTypes : TIBUpdateRecordTypes; begin UpdRecTypes := []; if UnModifiedCB.Checked then Include(UpdRecTypes, cusUnModified); if ModifiedCB.Checked then Include(UpdRecTypes, cusModified); if InsertedCB.Checked then Include(UpdRecTypes, cusInserted); if DeletedCB.Checked then Include(UpdRecTypes, cusDeleted); FDataSet.UpdateRecordTypes := UpdRecTypes; end; procedure TCacheDemoForm.ReExecuteButtonClick(Sender: TObject); begin FDataSet.Close; FDataSet.Open; end; procedure TCacheDemoForm.RadioGroup1Click(Sender: TObject); var NewDataset : TIBCustomDataset; begin case TRadioGroup(Sender).ItemIndex of 0 : NewDataset := CacheData.IBCacheQuery; 1 : NewDataset := CacheData.IBCachedDataSet; else NewDataset := CacheData.IBCachedTable; end; if NewDataSet <> FDataset then begin if FDataset.UpdatesPending then if MessageDlg('Updates Pending. Are you certain you want to discard?', mtConfirmation, [mbYes, mbNo], 0) = IDNO then begin RadioGroup1.ItemIndex := FDataset.Tag; Exit; end; FDataset.Close; FDataset := NewDataset; CacheData.CacheDS.DataSet := FDataset; FDataset.Open; end; end; procedure TCacheDemoForm.btnUpdateStatusClick(Sender: TObject); begin case FDataset.UpdateStatus of usUnmodified : ShowMessage('Unmodified'); usModified : ShowMessage('Modified'); usInserted : ShowMessage('Inserted'); usDeleted : ShowMessage('Deleted'); end; end; end.
{----------------------------------------------------------------------------- Unit Name: ValueNamesProvider This software and source code are distributed on an as is basis, without warranty of any kind, either express or implied. This file can be redistributed, modified if you keep this header. Copyright © Erwien Saputra 2005 All Rights Reserved. Author: Erwien Saputra Purpose: IValueNamesProvider is an observer of the IDelphiSettingRegistry. Whenever it reads new names from the registry keys, it triggers OnValueNamesChanged and OnStringChanged. This class is intended to be used with a TListBox, the form is responsible to arrange the names. If the user select an item on the listbox, the TListBox should set the SelectedIndex. Whenever the SelectedIndex is changed, it will trigger OnStringChanged. The main purpose for this class is as provider for the names under a key and to manage registry value names manipulation. The form that displays the ListBox which uses IValueNameProvider as data source displays two Listboxes and synchronizes the value names. The form may inserts blank lines between the ListBox items. For that reason ListBox.ItemIndex cannot be used directly with the IValueNamesProvider.SelectedItemIndex. Currently, this interface does not support multi-select items. The ListBox.ItemIndex may not be used directly to assign History: 02/01/05 - Initial creation. 02/17/05 - Implemented ClearSelectedValue. Updated with a lot of comments. 02/19/05 - Update CopySelectedValue, it calls UpdateValue if the Name is already exist. -----------------------------------------------------------------------------} unit ValueNamesProvider; interface uses DelphiSettingRegistry, Classes; type TIntfNotifyEvent = procedure (const Intf : IInterface) of object; IValueNamesProvider = interface ['{098F1A23-0169-4812-B00E-BD6FB2F77306}'] function GetRelativePath : string; function GetSelectedIndex : integer; function GetValueNames : TStrings; function GetAsString : string; function GetOnValueNamesChanged : TIntfNotifyEvent; function GetOnAsStringChanged : TIntfNotifyEvent; procedure SetSelectedIndex (const Idx : integer); procedure SetOnValueNamesChanged (const Value : TIntfNotifyEvent); procedure SetOnAsStringChanged (const Value : TIntfNotifyEvent); function GetNameIndex (const AName : string): integer; function GetSettingPath : string; procedure SetSettingPath (const ASettingPath : string); procedure CopySelectedValue (const Source : IValueNamesProvider); procedure DeleteSelectedValue; procedure ClearSelectedValue; property RelativePath : string read GetRelativePath; property ValueNames : TStrings read GetValueNames; property AsString : string read GetAsString; property SelectedIndex : integer read GetSelectedIndex write SetSelectedIndex; property OnValueNamesChanged : TIntfNotifyEvent read GetOnValueNamesChanged write SetOnValueNamesChanged; property OnAsStringChanged : TIntfNotifyEvent read GetOnAsStringChanged write SetOnAsStringChanged; end; function GetValueNamesProvider (const Intf : IDelphiSettingRegistry) : IValueNamesProvider; implementation uses SysUtils, Registry, IntfObserver; type TValueNamesProvider = class (TInterfacedObject, IValueNamesProvider, IObserver) private FOnValueNamesChanged : TIntfNotifyEvent; FOnAsStringChanged : TIntfNotifyEvent; FSelectedIndex : integer; FValueNames : TStringList; FValue : string; FReg : TRegistry; FSettingPath : string; procedure LoadValueNames; procedure ClearValueNames; procedure SetSelectedIndex (const Idx : integer); procedure UpdateValue; protected function GetRelativePath : string; function GetSelectedIndex : integer; function GetValueNames : TStrings; function GetAsString : string; function GetOnValueNamesChanged : TIntfNotifyEvent; function GetOnAsStringChanged : TIntfNotifyEvent; procedure SetOnValueNamesChanged (const Value : TIntfNotifyEvent); procedure SetOnAsStringChanged (const Value : TIntfNotifyEvent); function GetNameIndex (const AName : string): integer; function GetSettingPath : string; procedure SetSettingPath (const ASettingPath : string); procedure CopySelectedValue (const Source : IValueNamesProvider); procedure DeleteSelectedValue; procedure ClearSelectedValue; procedure Update (const Subject : ISubject; const AIntf : IInterface = nil); public constructor Create; destructor Destroy; override; end; //Factory function. function GetValueNamesProvider (const Intf : IDelphiSettingRegistry): IValueNamesProvider; begin Result := TValueNamesProvider.Create; Result.SetSettingPath (Intf.SettingPath); (Intf as ISubject).AttachObserver (Result as IObserver); end; { TValueNamesProvider } //Returns the index of the selected value name. function TValueNamesProvider.GetSelectedIndex: integer; begin Result := self.FSelectedIndex; end; constructor TValueNamesProvider.Create; begin inherited Create; FSelectedIndex := -1; FValueNames := TStringList.Create; FValueNames.Sorted := true; FReg := TRegistry.Create; end; //Event handler setter. procedure TValueNamesProvider.SetOnAsStringChanged( const Value: TIntfNotifyEvent); begin FOnAsStringChanged := Value; end; //Retrieve all value names. function TValueNamesProvider.GetValueNames: TStrings; begin Result := FValueNames; end; //Event handler getter. function TValueNamesProvider.GetOnValueNamesChanged: TIntfNotifyEvent; begin Result := FOnValueNamesChanged; end; //Event handler setter. procedure TValueNamesProvider.SetOnValueNamesChanged( const Value: TIntfNotifyEvent); begin FOnValueNamesChanged := Value; end; //Returns the value of the selected registry value name. function TValueNamesProvider.GetAsString: string; begin Result := FValue; end; //Event handler getter. function TValueNamesProvider.GetOnAsStringChanged: TIntfNotifyEvent; begin Result := FOnAsStringChanged; end; //Returns the relative path of the current Delph Registry Setting. This function //should not be here, it is more appopriate to have it at the //IDelphiSettingRegistry. Unfortunately it has to be here for now, as this class //needs this information and this class does not have reference to the //IDelphiSettingRegistry. function TValueNamesProvider.GetRelativePath: string; begin //Returns the path after the setting path. Setting Path is string from //'\Software' to the current setting name. Result := Copy (FReg.CurrentPath, Length (self.FSettingPath) + 1, Length (FReg.CurrentPath)); end; destructor TValueNamesProvider.Destroy; begin FValueNames.Free; inherited; end; //Returns the internal list index for AName. function TValueNamesProvider.GetNameIndex(const AName: string): integer; begin Result := FValueNames.IndexOf (AName); end; //Set the currently selected index. procedure TValueNamesProvider.SetSelectedIndex(const Idx: integer); begin if (FSelectedIndex = Idx) then Exit; FSelectedIndex := Idx; UpdateValue; end; //Reads the string representatino of the selected value name. procedure TValueNamesProvider.UpdateValue; var DataType : TRegDataType; ValueName : string; ValueExist : boolean; begin ValueExist := (FSelectedIndex <> -1) and FReg.ValueExists (FValueNames [FSelectedIndex]); if ValueExist then begin ValueName := FValueNames [FSelectedIndex]; DataType := FReg.GetDataType (ValueName); //Read the value and stored it in FValue. If the key is a binary key, set //FValue as {Binary}. case DataType of rdString, rdExpandString : FValue := FReg.ReadString (ValueName); rdInteger : FValue := IntToStr (FReg.ReadInteger (ValueName)); rdBinary : FValue := '(Binary)'; else FValue := '(Unknown)'; end; end else FValue := ''; if Assigned (FOnAsStringChanged) = true then FOnAsStringChanged (self); end; //This method loads the FValueNames with the value names of the selected //selected registry key. FReg is alredy opened the 'current key'. procedure TValueNamesProvider.LoadValueNames; begin //Reset the selected index and load the value names for the current key. FSelectedIndex := -1; FReg.GetValueNames (FValueNames); if Assigned (FOnValueNamesChanged) then FOnValueNamesChanged (self); //Update the FValue. UpdateValue will trigger FOnAsStringChanged. UpdateValue; end; //Clear the value names. procedure TValueNamesProvider.ClearValueNames; begin //Clear the value names and reset the selected index. FValueNames.Clear; FSelectedIndex := -1; if Assigned (FOnValueNamesChanged) then FOnValueNamesChanged (self); //UpdateValue will clear the FValue by the virtue that FSelectedIndex is -1, //and trigger the FOnAsStringChanged. UpdateValue; end; //This method is called by the Subject, IDelphiSettingRegistry. //This method reads the current registry key from IDelphiSettingRegistry, and //then opens the same key with the internal FReg. procedure TValueNamesProvider.Update(const Subject: ISubject; const AIntf: IInterface); var Intf : IDelphiSettingRegistry; begin Intf := Subject as IDelphiSettingRegistry; if (FReg.CurrentPath = Intf.CurrentPath) then Exit; //FReg should be able to open the current path, as both points to the same //registry key. If for some reason this key cannot be opened, reset the FReg //to open the root key and clear the value names. if (FReg.OpenKey (Intf.CurrentPath, false)) = false then begin FReg.OpenKey('\', false); ClearValueNames; end else //The key is found and was opened. Load the value names and notify the form. LoadValueNames; end; //This method sets the setting path. Setting path is the path from '\Software' //to the delphi setting registry name. This information is required to get the //relative path. procedure TValueNamesProvider.SetSettingPath(const ASettingPath: string); begin FSettingPath := ASettingPath; end; //Using other IValueNamesProvider as source, copy the selected value. This is //where the GetRelativePath is needed. If the key from the source exist in this //class, this method will copy the value. procedure TValueNamesProvider.CopySelectedValue( const Source: IValueNamesProvider); var ValueName, Path : string; Reg : TRegistry; Buffer : pointer; BytesRead, DataSize : integer; ValueExist : boolean; begin if Source = nil then Exit; //The relative path of the source is different than the path of this object, //that means the source path does not exist. Create it first. if Source.RelativePath <> self.GetRelativePath then raise Exception.Create ('Relative paths must be identical.'); //Get the name of the selected key from the source provider and checks if the //same value name exist in this IValueNamesProvider. ValueExist determines //whether this class neeed to reload the value names or not. ValueName := Source.ValueNames [Source.SelectedIndex]; ValueExist := FValueNames.IndexOf (ValueName) > -1; //Get the full path of the source key. Path := IncludeTrailingBackslash (Source.GetSettingPath) + Source.RelativePath; //Use Reg to read the source and FReg will write the value. Reg := TRegistry.Create; try Reg.OpenKeyReadOnly (Path); case Reg.GetDataType (ValueName) of rdString : FReg.WriteString (ValueName, Reg.ReadString (ValueName)); rdExpandString : FReg.WriteExpandString (ValueName, Reg.ReadString (ValueName)); rdInteger : FReg.WriteInteger (ValueName, Reg.ReadInteger (ValueName)); rdBinary : begin dataSize := Reg.GetDataSize (ValueName); GetMem (Buffer, DataSize); try BytesRead := Reg.ReadBinaryData (ValueName, Buffer^, dataSize); FReg.WriteBinaryData (ValueName, Buffer^, BytesRead); finally FreeMem (Buffer, dataSize); end; end; end; finally Reg.Free; end; if ValueExist = false then begin //Load the value names, as the value did not exist before. LoadValueNames; //The SelectedIndex was -1, set it to points the newly created value. SetSelectedIndex (FValueNames.IndexOf (ValueName)); end else //The value name, it exist but the value has been modified. The form must //update itself. UpdateValue; end; //Getter for the setting path. function TValueNamesProvider.GetSettingPath: string; begin Result := FSettingPath; end; //This method delete the selected value. procedure TValueNamesProvider.DeleteSelectedValue; begin if FSelectedIndex = -1 then Exit; if FReg.ValueExists (FValueNames [FSelectedIndex]) then FReg.DeleteValue (FValueNames [FSelectedIndex]); //Reload the value names and notify the view. LoadValueNames; end; //This method clears the value of a value name. The value name itself will not //bd deleted. procedure TValueNamesProvider.ClearSelectedValue; var ValueName: string; begin if FSelectedIndex = -1 then Exit; if FReg.ValueExists (FValueNames [FSelectedIndex]) then begin ValueName := FValueNames [FSelectedIndex]; case FReg.GetDataType (ValueName) of rdString, rdExpandString : FReg.WriteExpandString (ValueName, EmptyStr); rdInteger : FReg.WriteInteger (ValueName, 0); rdBinary : FReg.WriteBinaryData (ValueName, Ptr (0)^, 0); end; //The value for the selected valuename has been changed, notify the view. UpdateValue; end; end; end.
{$N-} program Hilb; { The program performs simultaneous solution by Gauss-Jordan elimination. -------------------------------------------------- From: Pascal Programs for Scientists and Engineers Alan R. Miller, Sybex n x n inverse hilbert matrix solution is 1 1 1 1 1 double precision version -------------------------------------------------- INSTRUCTIONS 1. Compile and run the program using the $N- (Numeric Processing : Software) compiler directive. 2. if you have a math coprocessor in your computer, compile and run the program using the $N+ (Numeric Processing : Hardware) compiler directive. Compare the speed and precision of the results to those of example 1. } const maxr = 10; maxc = 10; type {$IFOPT N+} { use extended type if using 80x87 } real = extended; {$ENDIF} ary = array[1..maxr] of real; arys = array[1..maxc] of real; ary2s = array[1..maxr, 1..maxc] of real; var y : arys; coef : arys; a, b : ary2s; n, m, i, j : integer; error : boolean; procedure gaussj (var b : ary2s; (* square matrix of coefficients *) y : arys; (* constant vector *) var coef : arys; (* solution vector *) ncol : integer; (* order of matrix *) var error: boolean); (* true if matrix singular *) (* Gauss Jordan matrix inversion and solution *) (* Adapted from McCormick *) (* Feb 8, 81 *) (* B(N,N) coefficient matrix, becomes inverse *) (* Y(N) original constant vector *) (* W(N,M) constant vector(s) become solution vector *) (* DETERM is the determinant *) (* ERROR = 1 if singular *) (* INDEX(N,3) *) (* NV is number of constant vectors *) var w : array[1..maxc, 1..maxc] of real; index: array[1..maxc, 1..3] of integer; i, j, k, l, nv, irow, icol, n, l1 : integer; determ, pivot, hold, sum, t, ab, big: real; procedure swap(var a, b: real); var hold: real; begin (* swap *) hold := a; a := b; b := hold end (* procedure swap *); begin (* Gauss-Jordan main program *) error := false; nv := 1 (* single constant vector *); n := ncol; for i := 1 to n do begin w[i, 1] := y[i] (* copy constant vector *); index[i, 3] := 0 end; determ := 1.0; for i := 1 to n do begin (* search for largest element *) big := 0.0; for j := 1 to n do begin if index[j, 3] <> 1 then begin for k := 1 to n do begin if index[k, 3] > 1 then begin writeln(' ERROR: matrix singular'); error := true; exit; (* abort *) end; if index[k, 3] < 1 then if abs(b[j, k]) > big then begin irow := j; icol := k; big := abs(b[j, k]) end end (* k loop *) end end (* j loop *); index[icol, 3] := index[icol, 3] + 1; index[i, 1] := irow; index[i, 2] := icol; (* interchange rows to put pivot on diagonal *) if irow <> icol then begin determ := - determ; for l := 1 to n do swap(b[irow, l], b[icol, l]); if nv > 0 then for l := 1 to nv do swap(w[irow, l], w[icol, l]) end; (* if irow <> icol *) (* divide pivot row by pivot column *) pivot := b[icol, icol]; determ := determ * pivot; b[icol, icol] := 1.0; for l := 1 to n do b[icol, l] := b[icol, l] / pivot; if nv > 0 then for l := 1 to nv do w[icol, l] := w[icol, l] / pivot; (* reduce nonpivot rows *) for l1 := 1 to n do begin if l1 <> icol then begin t := b[l1, icol]; b[l1, icol] := 0.0; for l := 1 to n do b[l1, l] := b[l1, l] - b[icol, l] * t; if nv > 0 then for l := 1 to nv do w[l1, l] := w[l1, l] - w[icol, l] * t; end (* if l1 <> icol *) end end (* i loop *); if error then exit; (* interchange columns *) for i := 1 to n do begin l := n - i + 1; if index[l, 1] <> index[l, 2] then begin irow := index[l, 1]; icol := index[l, 2]; for k := 1 to n do swap(b[k, irow], b[k, icol]) end (* if index *) end (* i loop *); for k := 1 to n do if index[k, 3] <> 1 then begin writeln(' ERROR: matrix singular'); error := true; exit; (* abort *) end; for i := 1 to n do coef[i] := w[i, 1]; end (* procedure gaussj *); procedure get_data(var a : ary2s; var y : arys; var n, m : integer); (* setup n-by-n hilbert matrix *) var i, j : integer; begin for i := 1 to n do begin a[n,i] := 1.0/(n + i - 1); a[i,n] := a[n,i] end; a[n,n] := 1.0/(2*n -1); for i := 1 to n do begin y[i] := 0.0; for j := 1 to n do y[i] := y[i] + a[i,j] end; writeln; if n < 7 then begin for i:= 1 to n do begin for j:= 1 to m do write( a[i,j] :7:5, ' '); writeln( ' : ', y[i] :7:5) end; writeln end (* if n<7 *) end (* procedure get_data *); procedure write_data; (* print out the answers *) var i : integer; begin for i := 1 to m do write( coef[i] :13:9); writeln; end (* write_data *); begin (* main program *) a[1,1] := 1.0; n := 2; m := n; repeat get_data (a, y, n, m); for i := 1 to n do for j := 1 to n do b[i,j] := a[i,j] (* setup work array *); gaussj (b, y, coef, n, error); if not error then write_data; n := n+1; m := n until n > maxr; end. 
{ ****************************************************************************** ___ __ ____ _ _ _ ____ __ ____ ____ ____ / __)/ \( _ \( \/ ) / ) ( _ \ / _\ / ___)(_ _)( __) ( (__( O )) __/ ) / / / ) __// \\___ \ )( ) _) \___)\__/(__) (__/ (_/ (__) \_/\_/(____/ (__) (____) Common unit Type: TCPIndicator = Line indicator TPasteStatus = Status of each individual paste TCPStatus = Status of the note in reguards to Copy/Paste Records: tClipInfo = Holds information about the clipboard (if available) TCprsClipboard = Holds information about the copied/pasted text tHighlightRecord = Holds information about the identifiable text THighlightRecordArray = All the identifiable text TGroupRecord = Holds information about the grouped text TPasteText = Used when loading/displaying pasted text TCPFoundRec = This is the overall found record TCPTextRec = This array holds the lines for both the paste and the note (sepperate instances). This will be modified as the search is ran TCPFindTxtRec = Find text record. Holds the positions and is returned from FindText TCPMatchingLines = This identifies the perfect match lines between PasteText and NoteText and is returned from FindMatchingLines Events: TAllowMonitorEvent = External call to allow the copy/paste functionality TLoadEvent = External call to load the pasted text TLoadProperties = External call to load the properties TPollBuff = Call to load the buffer (timmer) TRecalculateEvent = Call to save the recalculated percentages TSaveEvent = External call to save the pasted text TVisible = External call for Onshow/OnHide TVisualMessage = procedure that should fire for the visual message TToggleEvent = Event that fires when panel button is clicked { ****************************************************************************** } unit U_CPTCommon; interface uses Winapi.Windows, Vcl.Graphics, Vcl.Controls, Winapi.Messages, Vcl.ExtCtrls, System.Classes; type TCPIndicator = (allchr, begchar, endchr, nochr, nachar); TPasteStatus = (PasteNew, PasteModify, PasteNA); TCPStatus = (AuditProc, AuditNA, AuditCom); // -------- RECORDS --------// tClipInfo = record AppName: string; AppClass: string; AppHwnd: HWND; AppPid: Cardinal; AppTitle: String; ObjectHwnd: HWND; end; TCprsClipboard = record ApplicationName: string; ApplicationPackage: string; CopiedFromIEN: Int64; CopiedFromPackage: string; CopiedText: TStringList; HashValue: String; DateTimeOfCopy: string; DateTimeOfPaste: String; OriginalText: TStringList; PasteDBID: Integer; PasteToIEN: Int64; PercentData: String; PercentMatch: Double; SaveForDocument: Boolean; SaveItemID: Integer; SaveToTheBuffer: Boolean; end; CprsClipboardArry = Array of TCprsClipboard; tHighlightRecord = record LineToHighlight: WideString; AboveWrdCnt: Boolean; Public procedure Assign(const Source: tHighlightRecord); end; THighlightRecordArray = Array of tHighlightRecord; TGroupRecord = record GroupParent: Boolean; GroupText: TStringList; ItemIEN: Int64; VisibleOnNote: Boolean; HiglightLines: THighlightRecordArray; Public procedure Assign(const Source: TGroupRecord); end; TPasteText = record CopiedFromApplication: String; CopiedFromAuthor: string; CopiedFromDocument: string; CopiedFromLocation: string; CopiedFromPatient: string; DateTimeOfPaste: string; DateTimeOfOriginalDoc: String; GroupItems: array of TGroupRecord; HiglightLines: THighlightRecordArray; IdentFired: Boolean; InfoPanelIndex: Integer; Status: TPasteStatus; OriginalText: TStringList; PasteDBID: Integer; PasteNoteIEN: Int64; //For addendums and saving modified text PastedPercentage: string; PastedText: TStringList; UserWhoPasted: string; VisibleOnList: Boolean; VisibleOnNote: Boolean; DoNotFind: Boolean; Public procedure Assign(const Source: TPasteText); end; TPasteArray = array of TPasteText; TPanelArry = Array of TPanel; // -------- Events --------// TAllowMonitorEvent = procedure(Sender: TObject; var AllowMonitor: Boolean) of object; TLoadBuffEvent = procedure(Sender: TObject; LoadList: TStrings; var ProcessLoad: Boolean) of object; TLoadEvent = procedure(Sender: TObject; LoadList: TStrings; var ProcessLoad, PreLoaded: Boolean) of object; TLoadProperties = procedure(Sender: TObject) of object; TPollBuff = procedure(Sender: TObject; var Error: Boolean) of object; TRecalculateEvent = procedure(Sender: TObject; SaveList: TStringList) of object; TSaveEvent = procedure(Sender: TObject; SaveList: TStringList; var ReturnList: TStringList) of object; TVisible = procedure(Sender: TObject) of object; TVisualMessage = procedure(Sender: TObject; const CPmsg: Cardinal; CPVars: Array of Variant; FromNewPaste: Boolean = false) of object; TToggleEvent = procedure(Sender: TObject; Toggled: Boolean) of object; TNoParamEvent = procedure() of object; TCPFoundRec = record Text: String; NoteLine: Integer; PasteLine: Integer; StartChar: Integer; EndChar: Integer; LineIndicator: TCPIndicator; end; TCPTextRec = record Text: String; InnerLine: Integer; LineNumber: Integer; InnBeg: Integer; InnEnd: Integer; Found: Boolean; end; TCPFindTxtRec = record PastedText: String; PartialNoteText: String; FullNoteText: String; NoteLine: Integer; InnerNoteLine: Integer; PosPartialLine: Integer; PosEntireLine: Integer; PosPastedLine: Integer; end; TCPMatchingLines = record NoteLineNum: Integer; PasteLineNum: Integer; end; TCPMatchingLinesArray = Array of TCPMatchingLines; TCPFindTxtRecArray = Array of TCPFindTxtRec; TCPFoundRecArray = Array of TCPFoundRec; TCpTextRecArray = array of TCPTextRec; const UM_STATUSTEXT = (WM_USER + 302); // used to send update status msg to main form implementation procedure tHighlightRecord.Assign(const Source: tHighlightRecord); begin LineToHighlight := Source.LineToHighlight; AboveWrdCnt := Source.AboveWrdCnt; end; procedure TGroupRecord.Assign(const Source: TGroupRecord); var I: Integer; begin GroupParent := Source.GroupParent; ItemIEN := Source.ItemIEN; VisibleOnNote := Source.VisibleOnNote; for I := Low(Source.HiglightLines) to High(Source.HiglightLines) do begin SetLength(HiglightLines, Length(HiglightLines) + 1); HiglightLines[High(HiglightLines)].Assign(Source.HiglightLines[I]); end; if Assigned(Source.GroupText) then begin GroupText := TStringList.Create; GroupText.Assign(Source.GroupText); end; end; procedure TPasteText.Assign(const Source: TPasteText); var I: Integer; begin CopiedFromApplication := Source.CopiedFromApplication; CopiedFromAuthor := Source.CopiedFromAuthor; CopiedFromDocument := Source.CopiedFromDocument; CopiedFromLocation := Source.CopiedFromLocation; CopiedFromPatient := Source.CopiedFromPatient; DateTimeOfPaste := Source.DateTimeOfPaste; DateTimeOfOriginalDoc := Source.DateTimeOfOriginalDoc; IdentFired := Source.IdentFired; InfoPanelIndex := Source.InfoPanelIndex; Status := Source.Status; PasteDBID := Source.PasteDBID; PasteNoteIEN := Source.PasteNoteIEN; PastedPercentage := Source.PastedPercentage; UserWhoPasted := Source.UserWhoPasted; VisibleOnList := Source.VisibleOnList; VisibleOnNote := Source.VisibleOnNote; if Assigned(Source.OriginalText) then begin OriginalText := TStringList.Create; OriginalText.Assign(Source.OriginalText); end; if Assigned(Source.PastedText) then begin PastedText := TStringList.Create; PastedText.Assign(Source.PastedText); end; for I := Low(Source.HiglightLines) to High(Source.HiglightLines) do begin SetLength(HiglightLines, Length(HiglightLines) + 1); HiglightLines[High(HiglightLines)].Assign(Source.HiglightLines[I]); end; for I := Low(Source.GroupItems) to High(Source.GroupItems) do begin SetLength(GroupItems, Length(GroupItems) + 1); GroupItems[High(GroupItems)].Assign(Source.GroupItems[I]); end; end; end.
unit uBaseDAO; interface uses FireDAC.Comp.Client, uDM, System.SysUtils, Data.DB, Vcl.Dialogs, System.Classes; type TBaseDAO = class(TObject) private protected FQry: TFDQuery; constructor Create; destructor Destroy; override; function RetornarDataSet(pSQL: string): TFDQuery; function ExecutarComando(pSQL: string): TFDQuery; end; implementation { TBaseDAO } constructor TBaseDAO.Create; begin inherited Create; FQry := TFDQuery.Create(nil); FQry.Connection := DM.FDConnection; end; destructor TBaseDAO.Destroy; begin try if Assigned(FQry) then FreeAndNil(FQry); except on e: exception do raise Exception.Create(e.Message); end; end; function TBaseDAO.ExecutarComando(pSQL: string): TFDQuery; begin try DM.FDConnection.StartTransaction; FQry.SQL.Text := pSQL; FQry.ExecSQL; // Result := FQry.RowsAffected; DM.FDConnection.Commit; except DM.FDConnection.Rollback; end end; function TBaseDAO.RetornarDataSet(pSQL: string): TFDQuery; begin FQry.SQL.Text := pSQL; FQry.Active := True; Result := FQry; end; end.
unit ExplorerFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ChildFrm, StdCtrls, FileCtrl, ComCtrls, ExtCtrls, ImgList; type TExplorerForm = class(TChildForm) pnlLeft: TPanel; pnlRight: TPanel; spl1: TSplitter; pnlTop: TPanel; lvDetail: TListView; drvcbb1: TDriveComboBox; procedure drvcbb1Change(Sender: TObject); private { Private declarations } drvChar: Char; // 存储当前选择的卷 FFileName: string; // 得到标准目录,即若字符串末尾不是'\',则在末尾加'\' function GetStdDirectory(Dir: string): string; public { Public declarations } constructor Create(AOwner: TComponent; AParent: TWinControl); override; procedure FindFiles(APath, AFileName: string); procedure RefreshListTitle(Titles: array of string; Widths: array of integer; LV: TListView; IsClearItems: Boolean = True; LastAutoSize: Boolean = True); function AddAListItem({intImgIndex: integer;} Values: array of string; SubImgIndexs: array of integer; {intStaIndex: integer; }LV: TListView; Data: Pointer = nil; InsertIndex: integer = -1): TListItem; end; var ExplorerForm: TExplorerForm; implementation {$R *.dfm} procedure TExplorerForm.drvcbb1Change(Sender: TObject); begin //inherited; drvChar := drvcbb1.Drive; FFileName := '*.xls'; RefreshListTitle(['试一试'], [100], lvDetail); FindFiles({drvChar + }'D:\AA\', FFileName); end; function TExplorerForm.GetStdDirectory(Dir: string): string; begin if Dir[Length(Dir)] <> '\' then Result := Dir + '\' else Result := Dir; end; procedure TExplorerForm.FindFiles(APath, AFileName: string); var FSearchRec, DsearchRec: TSearchRec; FindResult: Integer; i: Integer; ch: Char; wn: WideString; wh: WideChar; function IsDirNotation(ADirName: string): Boolean; begin Result := (ADirName = '.') or (ADirName = '..'); end; begin APath := GetStdDirectory(APath); FindResult := FindFirst(APath + AFileName, faAnyFile + faHidden + faSysFile + faReadOnly, FSearchRec); try while FindResult = 0 do begin //lvDetail.Columns[0].Caption := LowerCase(APath + FSearchRec.Name); AddAListItem([LowerCase(APath + FSearchRec.Name)],[],lvDetail); wn := widestring(FSearchRec.Name); showmessage(inttostr(Length(FSearchRec.Name))+#13#10+inttostr(length(wn))); for i:=1 to Length(FSearchRec.Name) do begin ch := FSearchRec.Name[i]; wh := WideChar(wn[i]); showmessage(FSearchRec.Name[i]+#13#10+inttostr(ord(FSearchRec.Name[i])) +#13#10+ch+#13#10+wh); end; FindResult := FindNext(FSearchRec); end; FindResult := FindFirst(APath + '*.*', faDirectory, DSearchRec); while FindResult = 0 do begin if ((DSearchRec.Attr and faDirectory) = faDirectory) and not IsDirNotation(DsearchRec.Name) then FindFiles(APath + DSearchRec.Name, FFileName); FindResult := FindNext(DsearchRec); end; finally FindClose(FSearchRec); end; end; procedure TExplorerForm.RefreshListTitle(Titles: array of string; Widths: array of integer; LV: TListView; IsClearItems: Boolean; LastAutoSize: Boolean); var i: integer; TmpObj: TObject; begin try LV.Hide; //注释后,检入文件会先显示 listview后面的grid,再显示listview的 // 注释这两句后,打开历史版本出现'stream read error' LockWindowUpdate(LV.handle); SendMessagew(LV.Handle, WM_SETREDRAW, integer(false), 0); with LV do begin //先清空标题 LV.Columns.Clear; for i := Low(Titles) to High(Titles) do with LV.Columns.Add do begin Caption := Titles[i]; Width := Widths[i]; //对于‘大小’项,需要右对齐 // if Titles[i] = LoadStr(sListSize) then // Alignment := taRightJustify; if LastAutosize and (i = High(Titles)) then AutoSize := True; end; //如果需要清空内容,则清空 if IsClearItems then begin Hide; LV.items.Clear; Show; end; //将宽度增加1是为了当最后一行需要自动增长时,强制列表刷新自己 //Perform(WM_SIZE,0,0); if LastAutosize then Width := Width + 1; //Perform(WM_SIZE,0,0); end; SendMessagew(LV.Handle, WM_SETREDRAW, integer(true), 0); LockWindowUpdate(0); finally LV.Show; end; end; function TExplorerForm.AddAListItem({intImgIndex: integer;} Values: array of string; SubImgIndexs: array of integer; {intStaIndex: integer; }LV: TListView; Data: Pointer = nil; InsertIndex: integer = -1): TListItem; var i: integer; bHasSubImg: Boolean; begin if High(SubImgIndexs) = -1 then bHasSubImg := False else bHasSubImg := True; if InsertIndex = -1 then result := TListItem(LV.items.Add) else result := TListItem(LV.items.Insert(InsertIndex)); with result do begin Caption := Values[Low(Values)]; //ImageIndex := intImgIndex; //StateIndex := intStaIndex; for i := Low(Values) + 1 to High(Values) do begin SubItems.Add(Values[i]); if bHasSubImg then SubItemImages[i - 1] := SubImgIndexs[i - 1]; end; end; Result.Data := Data; end; constructor TExplorerForm.Create(AOwner: TComponent; AParent: TWinControl); begin inherited; //drvcbb1.Drive := 'D'; end; end.
{**********************************************} { TTeeShadow Editor Dialog } { Copyright (c) 2002-2004 by David Berneda } {**********************************************} unit TeeShadowEditor; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, {$ENDIF} TeCanvas; type TTeeShadowEditor = class(TForm) Label1: TLabel; LTransp: TLabel; Label5: TLabel; BShadowColor: TButtonColor; Edit1: TEdit; UDShadowSize: TUpDown; EShadowTransp: TEdit; UDShadowTransp: TUpDown; EVertSize: TEdit; UDShaVert: TUpDown; BOK: TButton; CBSmooth: TCheckBox; procedure Edit1Change(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure EShadowTranspChange(Sender: TObject); procedure EVertSizeChange(Sender: TObject); procedure BOKClick(Sender: TObject); procedure CBSmoothClick(Sender: TObject); private { Private declarations } CreatingForm : Boolean; Shadow : TTeeShadow; Function CanChange:Boolean; public { Public declarations } Procedure RefreshControls(AShadow:TTeeShadow); end; Function EditTeeShadow(AOwner:TComponent; AShadow:TTeeShadow):Boolean; Function InsertTeeShadowEditor(ATab:TTabSheet):TTeeShadowEditor; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses TeeProcs, TeePenDlg; Function EditTeeShadow(AOwner:TComponent; AShadow:TTeeShadow):Boolean; begin with TeeCreateForm(TTeeShadowEditor,AOwner) as TTeeShadowEditor do try Shadow:=AShadow; BOK.Visible:=True; result:=ShowModal=mrOk; finally Free; end; end; Function InsertTeeShadowEditor(ATab:TTabSheet):TTeeShadowEditor; begin result:=TTeeShadowEditor.Create(ATab.Owner); result.BOK.Visible:=False; AddFormTo(result,ATab); end; Procedure TTeeShadowEditor.RefreshControls(AShadow:TTeeShadow); begin Shadow:=AShadow; UDShadowSize.Position :=Shadow.HorizSize; UDShaVert.Position :=Shadow.VertSize; UDShadowTransp.Position:=Shadow.Transparency; CBSmooth.Checked :=Shadow.Smooth; BShadowColor.LinkProperty(Shadow,'Color'); end; Function TTeeShadowEditor.CanChange:Boolean; begin result:=(not CreatingForm) and Assigned(Shadow); end; procedure TTeeShadowEditor.Edit1Change(Sender: TObject); begin if CanChange then Shadow.HorizSize:=UDShadowSize.Position; end; procedure TTeeShadowEditor.FormCreate(Sender: TObject); begin CreatingForm:=True; end; procedure TTeeShadowEditor.FormShow(Sender: TObject); begin if Assigned(Shadow) then RefreshControls(Shadow); TeeTranslateControl(Self); CreatingForm:=False; end; procedure TTeeShadowEditor.EShadowTranspChange(Sender: TObject); begin if CanChange then Shadow.Transparency:=UDShadowTransp.Position; end; procedure TTeeShadowEditor.EVertSizeChange(Sender: TObject); begin if CanChange then Shadow.VertSize:=UDShaVert.Position; end; procedure TTeeShadowEditor.BOKClick(Sender: TObject); begin Close; end; procedure TTeeShadowEditor.CBSmoothClick(Sender: TObject); begin Shadow.Smooth:=CBSmooth.Checked; end; end.
//Creese un programa que solicite al usuario los elementos de 2 matrices 3 × 3 de reales //y saque por pantalla la matriz resultado de sumar ambas y su traspuesta. Para ello //deben emplearse los algoritmos disenados en los problemas del tema 1. El algoritmo //intercambio debe implementarse como un procedimiento local del algoritmo que se //emplea para trasponer las matrices. program sumMat; const N=3; type miMat=array[1..N,1..N] of real; procedure intercambio(var a, b: integer); var aux:integer; begin aux:=a; a:=b; b:=aux; end; procedure leeMatriz(var mat:miMat); var i,j:integer; begin writeln(); for i:=1 to N do for j:=1 to N do begin write('Introduzca el elemento [',i,'][',j,'] de la matriz: '); readln(mat[i,j]); end; end; var matriz1, matriz2:miMat; i,j:integer; begin leeMatriz(matriz1); leeMatriz(matriz2); for i:=1 to N do begin writeln(); for j:=1 to N do begin write('[',matriz1[i,j]+matriz2[i,j]:4:2,']') end end; for i:=1 to N do begin writeln(); for j:=1 to N do begin write('[',matriz1[j,i]+matriz2[j,i]:4:2,']') end end; end.
unit inherited_2; interface uses System; type TC0 = class function GetValue: Int32; virtual; end; TC1 = class(TC0) function GetValue: Int32; override; end; TC2 = class(TC1) function GetValue: Int32; override; end; implementation function TC0.GetValue: Int32; begin Result := 1; end; function TC1.GetValue: Int32; begin Result := 5; end; function TC2.GetValue: Int32; begin Result := inherited TC0.GetValue() + 1; end; var G: Int32; procedure Test; var C: TC1; begin C := TC2.Create(); G := C.GetValue(); end; initialization Test(); finalization Assert(G = 2); end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.Jpeg, //GLS GLScene, GLObjects, GLSDLContext, SDL, GLTeapot, GLCrossPlatform, GLCoordinates, GLBaseClasses, GLColor; type TDataModule1 = class(TDataModule) GLScene1: TGLScene; GLSDLViewer1: TGLSDLViewer; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; Teapot1: TGLTeapot; procedure DataModuleCreate(Sender: TObject); procedure GLSDLViewer1EventPollDone(Sender: TObject); procedure GLSDLViewer1Resize(Sender: TObject); private { Private declarations } public { Public declarations } firstPassDone : Boolean; end; var DataModule1: TDataModule1; implementation {$R *.dfm} uses GLContext, GLTexture, GLUtils; procedure TDataModule1.DataModuleCreate(Sender: TObject); begin // When using SDL, the standard VCL message queue is no longer operational, // so you must have/make your own loop to prevent the application from // terminating immediately GLSDLViewer1.Render; while GLSDLViewer1.Active do begin // Message queue is not operational, but there may still be some messages Application.ProcessMessages; // Relinquish some of that CPU time SDL_Delay(1); // Slowly rotate the teapot Teapot1.RollAngle:=4*Frac(Now*24)*3600; end; end; procedure TDataModule1.GLSDLViewer1EventPollDone(Sender: TObject); begin SetGLSceneMediaDir(); if not firstPassDone then begin // Loads a texture map for the teapot // (see materials/cubemap for details on that) // // The odd bit is that it must be done upon first render, otherwise // SDL OpenGL support has not been initialized and things like checking // an extension support (cube maps here) would fail... // Something less clunky will be introduced, someday... firstPassDone:=True; GLSDLViewer1.Buffer.RenderingContext.Activate; try if not GL.ARB_texture_cube_map then ShowMessage('Your graphics board does not support cube maps...'#13#10 +'So, no cube maps for ya...') else begin with Teapot1.Material.Texture do begin ImageClassName:=TGLCubeMapImage.ClassName; with Image as TGLCubeMapImage do begin Picture[cmtPX].LoadFromFile('cm_left.jpg'); Picture[cmtNX].LoadFromFile('cm_right.jpg'); Picture[cmtPY].LoadFromFile('cm_top.jpg'); Picture[cmtNY].LoadFromFile('cm_bottom.jpg'); Picture[cmtPZ].LoadFromFile('cm_back.jpg'); Picture[cmtNZ].LoadFromFile('cm_front.jpg'); end; MappingMode:=tmmCubeMapReflection; Disabled:=False; end; end; finally GLSDLViewer1.Buffer.RenderingContext.Deactivate; end; end; GLSDLViewer1.Render; end; procedure TDataModule1.GLSDLViewer1Resize(Sender: TObject); begin // Zoom if SDL window gets smaller/bigger GLCamera1.SceneScale:=GLSDLViewer1.Width/160; end; end.
(****************************************************************************) (* Title: exe286.pas *) (* Description: Data structure definitions for the OS/2 old executable *) (* file format (segmented model) *) (****************************************************************************) (* (C) Copyright IBM Corp 1984-1992 *) (* (C) Copyright Microsoft Corp 1984-1987 *) (* C->Pascal conversion (c) FRIENDS software, 1996 *) (****************************************************************************) {$AlignCode-,AlignData-,AlignRec-,G3+,Speed-,Frame-,Use32+} Unit exe286; Interface uses MiscUtil; { DOS EXE file header structure } type pEXEheader = ^tEXEheader; tEXEheader = record exeMagic : Word16; { Magic number } exeCbLP : Word16; { Bytes on last page of file } exeCp : Word16; { Pages in file } exeCrlc : Word16; { Relocations } exeCparhdr : Word16; { Size of header in paragraphs } exeMinAlloc : Word16; { Minimum extra paragraphs needed } exeMaxAlloc : Word16; { Maximum extra paragraphs needed } exeSS : Word16; { Initial (relative) SS value } exeSP : Word16; { Initial SP value } exeCRC : Word16; { Checksum } exeIP : Word16; { Initial IP value } exeCS : Word16; { Initial (relative) CS value } exeLfarlc : Word16; { File address of relocation table } exeOvNo : Word16; { Overlay number } exeRes : array[1..4] of Word16;{ Reserved words } exeOEMid : Word16; { OEM identifier (for exeOEMinfo) } exeOEMinfo : Word16; { OEM information; exeOEMid specific } exeRes2 : array[1..10] of Word16;{ Reserved words } exeLFAnew : Longint; { File address of new exe header } end; (*-----------------------------------------------------------------*) (* OS/2 & WINDOWS .EXE FILE HEADER DEFINITION - 286 version *) (*-----------------------------------------------------------------*) const neMagic = $454E; { `New` magic number } neDebugMagic = $424E; { 'NB', codeview debug-info signature } neResBytes = 8; { Eight bytes reserved (now) } neCRC = 8; { Offset into new header of neCRC } type pNEheader = ^tNEheader; tNEheader = record { `New` .EXE header } neMagic : Word16; { Magic number neMAGIC } neVer : Byte; { Version number } neRev : Byte; { Revision number } neEntTab : Word16; { Offset of Entry Table } neCbEntTab : Word16; { Number of bytes in Entry Table } neCRC : Longint; { Checksum of whole file } neFlags : Word16; { Flag word } neAutoData : Word16; { Automatic data segment number } neHeap : Word16; { Initial heap allocation } neStack : Word16; { Initial stack allocation } neCSIP : Longint; { Initial CS:IP setting } neSSSP : Longint; { Initial SS:SP setting } neCSeg : Word16; { Count of file segments } neCMod : Word16; { Entries in Module Reference Table } neCbNResTab : Word16; { Size of non-resident name table } neSegTab : Word16; { Offset of Segment Table } neRsrcTab : Word16; { Offset of Resource Table } neResTab : Word16; { Offset of resident name table } neModTab : Word16; { Offset of Module Reference Table } neImpTab : Word16; { Offset of Imported Names Table } neNResTab : Longint; { Offset of Non-resident Names Table } neCMovEnt : Word16; { Count of movable entries } neAlign : Word16; { Segment alignment shift count } neCRes : Word16; { Count of resource entries } neExeTyp : Byte; { Target operating system } neFlagsOthers : Byte; { Other .EXE flags } neReserved : array[1..neResBytes] of byte;{ Pad structure to 64 bytes } end; {* Target operating systems *} const neUnknown = $0; { Unknown (any "new-format" OS) } neOS2 = $1; { OS/2 (default) } neWindows = $2; { Windows } neDos4 = $3; { DOS 4.x } neDev386 = $4; { Windows 386 } {* Format of NE_FLAGS(x): *} {* p Not-a-process *} {* x Unused *} {* e Errors in image *} {* x Unused *} {* b Bound Family/API *} {* ttt Application type *} {* f Floating-point instructions *} {* 3 386 instructions *} {* 2 286 instructions *} {* 0 8086 instructions *} {* P Protected mode only *} {* p Per-process library initialization *} {* i Instance data *} {* s Solo data *} const neNotP = $8000; { Not a process } neIerr = $2000; { Errors in image } neBound = $0800; { Bound Family/API } neAppTyp = $0700; { Application type mask } neNotWinCompat = $0100; { Not compatible with P.M. Windowing } neWinCompat = $0200; { Compatible with P.M. Windowing } neWinAPI = $0300; { Uses P.M. Windowing API } neFltP = $0080; { Floating-point instructions } neI386 = $0040; { 386 instructions } neI286 = $0020; { 286 instructions } neI086 = $0010; { 8086 instructions } neProt = $0008; { Runs in protected mode only } nePPLI = $0004; { Per-Process Library Initialization } neInst = $0002; { Instance data } neSolo = $0001; { Solo data } {* Format of NE_FLAGSOTHERS(x): *} {* *} {* 7 6 5 4 3 2 1 0 - bit no *} {* | | | | *} {* | | | +---------------- Support for long file names *} {* | | +------------------ Windows 2.x app runs in prot mode *} {* | +-------------------- Windows 2.x app gets prop. font *} {* +------------------------------ WLO appl on OS/2 (markwlo.exe) *} const neLongFileNames = $01; neWinIsProt = $02; neWinGetPropFon = $04; neWLoAppl = $80; type pNEseg = ^tNEseg; tNEseg = record { New .EXE segment table entry } Sector : Word16; { File sector of start of segment } CbSeg : Word16; { Number of bytes in file } Flags : Word16; { Attribute flags } MinAlloc : Word16; { Minimum allocation in bytes } end; {* Format of NS_FLAGS(x) *} {* *} {* Flag word has the following format: *} {* *} {* 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 - bit no *} {* | | | | | | | | | | | | | | | *} {* | | | | | | | | | | | | +-+-+--- Segment type DATA/CODE *} {* | | | | | | | | | | | +--------- Iterated segment *} {* | | | | | | | | | | +----------- Movable segment *} {* | | | | | | | | | +------------- Segment can be shared *} {* | | | | | | | | +--------------- Preload segment *} {* | | | | | | | +----------------- Execute/read-only for code/data segment*} {* | | | | | | +------------------- Segment has relocations *} {* | | | | | +--------------------- Code conforming/Data is expand down*} {* | | | +--+----------------------- I/O privilege level *} {* | | +----------------------------- Discardable segment *} {* | +-------------------------------- 32-bit code segment *} {* +----------------------------------- Huge segment/GDT allocation requested *} const nesType = $0007; { Segment type mask } nesCode = $0000; { Code segment } nesData = $0001; { Data segment } nesIter = $0008; { Iterated segment flag } nesMove = $0010; { Movable segment flag } nesShared = $0020; { Shared segment flag } nesPreload = $0040; { Preload segment flag } nesExRdOnly = $0080; { Execute-only (code segment), or read-only (data segment) } nesReloc = $0100; { Segment has relocations } nesConform = $0200; { Conforming segment } nesExpDown = $0200; { Data segment is expand down } nesDPL = $0C00; { I/O privilege level (286 DPL bits) } nesDiscard = $1000; { Segment is discardable } nes32bit = $2000; { 32-bit code segment } nesHuge = $4000; { Huge memory segment, length of } { segment and minimum allocation } { size are in segment sector units } nesGDT = $8000; { GDT allocation requested } nesPure = nesShared; { For compatibility } nesAlign = 9; { Segment data aligned on 512 byte boundaries } nesLoaded = $0004; { nesSector field contains memory addr } type tNEsegData = record case boolean of TRUE : (Iter : record nIter : Word16; { number of iterations } nBytes : Word16; { number of bytes } Data : array[0..0] of Byte;{ iterated data bytes } end); FALSE : (Data : array[0..0] of Byte); end; tNErelocInfo = record { Relocation info } nReloc : Word16; { number of relocation items that follow } end; pNEreloc = ^tNEreloc; tNEreloc = record sType : Byte; { Source type } flags : Byte; { Flag byte } soff : Word16; { Source offset } rel : record case byte of { Internal reference } 0 : (segNo : Byte; { Target segment number } Resvd : Byte; { Reserved } Entry : Word16); { Target Entry Table offset } { Import } 1 : (modIndx : Word16; { Index into Module Reference Table } Proc : Word16); { Procedure ordinal or name offset } { Operating system fixup } 2 : (osType : Word16; { OSFIXUP type } osRes : Word16); { reserved } end; end; {* Format of NR_STYPE(x) and R32_STYPE(x): *} {* *} {* 7 6 5 4 3 2 1 0 - bit no *} {* | | | | *} {* +-+-+-+--- source type *} const nerSType = $0F; { Source type mask } nerSByte = $00; { lo byte (8-bits)} nerSSeg = $02; { 16-bit segment (16-bits) } nerSPtr = $03; { 16:16 pointer (32-bits) } nerSoff = $05; { 16-bit offset (16-bits) } nerPtr48 = $06; { 16:32 pointer (48-bits) } nerOff32 = $07; { 32-bit offset (32-bits) } nerSOff32 = $08; { 32-bit self-relative offset (32-bits) } {* Format of NR_FLAGS(x) and R32_FLAGS(x): *} {* *} {* 7 6 5 4 3 2 1 0 - bit no *} {* | | | *} {* | +-+--- Reference type *} {* +------- Additive fixup *} const nerRTyp = $03; { Reference type mask } nerRInt = $00; { Internal reference } nerROrd = $01; { Import by ordinal } nerRNam = $02; { Import by name } nerROsf = $03; { Operating system fixup } nerAdd = $04; { Additive fixup } type pNEentryBundle = ^tNEentryBundle; tNEentryBundle = record Flags : Byte; Ref : record case byte of 0 : (fixOfs : Word16); 1 : (movInt3F : Word16; movSegNo : Byte; movOfs : Word16); end; end; {Type definition for resource description blocks} {(REAL ONE, NOT FROM WINDOWS EXECUTABLES!)} type tNEresource = record resType : Word16; resID : Word16; end; Implementation end.
unit BD.Settings; interface uses System.SysUtils, System.Classes, Rest.Json, System.JSON; type TSettings = class(TObject) private FServer: String; FDatabase: String; FUsername: String; FPassword: String; FPort: Integer; FDataURL: String; FPostnrURL: String; public property Server: String read FServer write FServer; property Database: String read FDatabase write FDatabase; property Username: String read FUsername write FUsername; property Password: String read FPassword write FPassword; property Port: Integer read FPort write FPort; property DataURL: String read FDataURL write FDataURL; property PostnrURL: String read FPostnrURL write FPostnrURL; constructor Create(); end; TSettingsHandler = class(TObject) published class function LoadFromFile(Path: String = ''): TSettings; class procedure SaveToFile(Settings: TSettings; Path: String = ''); end; var Settings: TSettings; implementation { TSettingsHandler } class function TSettingsHandler.LoadFromFile(Path: String): TSettings; var Strings: TStrings; begin if Path = '' then Path := ChangeFileExt(ParamStr(0), '') + '.json'; if FileExists(Path) then begin Strings := TStringList.Create; Strings.LoadFromFile(Path); Result := TJSON.JsonToObject<TSettings>(Strings.Text); Strings.Free(); end else Result := TSettings.Create(); end; class procedure TSettingsHandler.SaveToFile(Settings: TSettings; Path: String); var Strings : TStrings; AJSONObject: TJSOnObject; begin if Path = '' then Path := ChangeFileExt(ParamStr(0), '') + '.json'; AJSONObject := TJSON.ObjectToJsonObject(Settings); Strings := TStringList.Create; Strings.Add(TJSON.Format(AJSONObject)); Strings.SaveToFile(Path); Strings.Free; end; { TSettings } constructor TSettings.Create; begin FPort := 0; end; initialization Settings := TSettingsHandler.LoadFromFile(); finalization Settings.Free; end.
(** This module contains a class which represents a dynamic collection of process information. @Author David Hoyle @Version 1.0 @Date 05 Jan 2018 **) Unit ITHelper.ExternalProcessInfo; Interface Uses INIFiles, Generics.Collections; Type (** A record to describe the information required by DGHCreateProcess. **) TITHProcessInfo = Record FEnabled : Boolean; FEXE : String; FParams : String; FDir : String; FTitle : String; End; (** A class to represent a collection of TProcessInfo classes. **) TITHProcessCollection = Class Strict Private FProcesses : TList<TITHProcessInfo>; Strict Protected Function GetCount : Integer; Function GetProcess(Const iIndex : Integer) : TITHProcessInfo; Procedure SetProcess(Const iIndex : Integer; Const PInfo : TITHProcessInfo); Public Constructor Create; Destructor Destroy; Override; Procedure AddProcessInfo(Const boolEnabled : Boolean; Const strEXE, strParams, strDir, strTitle : String); Procedure Clear; Procedure LoadFromINI(Const iniFile : TMemIniFile; Const strSection : String); Procedure SaveToINI(Const iniFile : TMemIniFile; Const strSection : String); (** A property to return the number of processes in the collection. @precon None. @postcon Returns the numnber of process in the collection. @return an Integer **) Property Count : Integer Read GetCount; (** A property to return a reference to a process info record. @precon iIndex must be a valid index in the collection. @postcon Returns a reference to the indexed process info record. @param iIndex as an Integer as a constant @return a TITHProcessInfo **) Property Process[Const iIndex : Integer] : TITHProcessInfo Read GetProcess Write SetProcess; Default; End; Implementation Uses Classes, SysUtils, ITHelper.CommonFunctions; Const (** This position of the executable in a zero based string array split from the ini file. **) iProcessExe = 0; (** This position of the parameters in a zero based string array split from the ini file. **) iProcessParams = 1; (** This position of the Directory in a zero based string array split from the ini file. **) iProcessDir = 2; (** This position of the Title in a zero based string array split from the ini file. **) iProcessTitle = 3; { TProcessCollection } (** This method adds a set of process information to the collection, and grows the collection if necessary. @precon None. @postcon Adds a set of process information to the collection, and grows the collection if neceaary. @param boolEnabled as a Boolean as a constant @param strEXE as a String as a constant @param strParams as a String as a constant @param strDir as a String as a constant @param strTitle as a String as a constant **) Procedure TITHProcessCollection.AddProcessInfo(Const boolEnabled: Boolean; Const strEXE, strParams, strDir, strTitle: String); Var PI : TITHProcessInfo; Begin If strEXE <> '' Then Begin PI.FEnabled := boolEnabled; PI.FEXE := strEXE; PI.FParams := strParams; PI.FDir := strDir; PI.FTitle := strTitle; FProcesses.Add(PI); End; End; (** This method clears the existing collection and creates a new empty collection. @precon None. @postcon Clears the existing collection and creates a new empty collection. **) Procedure TITHProcessCollection.Clear; Begin FProcesses.Clear; End; (** This is the constructor method for the TProcessCollection class. @precon None. @postcon Creates the empty collection. **) Constructor TITHProcessCollection.Create; Begin FProcesses := TList<TITHProcessInfo>.Create; End; (** This is the destructor method for the TProcessCollection class. @precon None. @postcon Clears the collection. **) Destructor TITHProcessCollection.Destroy; Begin FProcesses.Free; Inherited Destroy; End; (** This is a getter method for the Count property. @precon None. @postcon Returns the number of items in the collection. @return an Integer **) Function TITHProcessCollection.GetCount: Integer; Begin Result := FProcesses.Count; End; (** This is a getter method for the Process property. @precon iIndex must eb a valid index in the collection. @postcon Returns the reference to the indexed procress info record. @param iIndex as an Integer as a constant @return a TITHProcessInfo **) Function TITHProcessCollection.GetProcess(Const iIndex: Integer): TITHProcessInfo; Begin Result := FProcesses[iIndex]; End; (** This method clears the current collection and loads a new set of process information from the inifile and section provided. @precon iniFile must be a valid instance. @postcon Clears the current collection and loads a new set of process information from the inifile and section provided. @param iniFile as a TMemIniFile as a constant @param strSection as a String as a constant **) Procedure TITHProcessCollection.LoadFromINI(Const iniFile: TMemIniFile; Const strSection: String); Var sl: TStringList; i: Integer; strTitle: String; astrProcessInfo: TDGHArrayOfString; Begin Clear; sl := TStringList.Create; Try iniFile.ReadSection(strSection, sl); For i := 0 To sl.Count - 1 Do Begin astrProcessInfo := DGHSplit(sl[i], '|'); strTitle := astrProcessInfo[iProcessTitle]; If strTitle = '' Then strTitle := ExtractFilename(astrProcessInfo[iProcessExe]); AddProcessInfo( iniFile.ReadBool(strSection, sl[i], True), astrProcessInfo[iProcessExe], astrProcessInfo[iProcessParams], astrProcessInfo[iProcessDir], strTitle ); End; Finally sl.Free; End; End; (** This method saves the collection of process information recofrds to the ini file and section provided. @precon iniFile must be a valid instance. @postcon Saves the collection of process information recofrds to the ini file and section provided. @param iniFile as a TMemIniFile as a constant @param strSection as a String as a constant **) Procedure TITHProcessCollection.SaveToINI(Const iniFile: TMemIniFile; Const strSection: String); Var i: Integer; Begin iniFile.EraseSection(strSection); For i := 0 To Count - 1 Do iniFile.WriteBool(strSection, Format('%s|%s|%s|%s', [ FProcesses[i].FEXE, FProcesses[i].FParams, FProcesses[i].FDir, FProcesses[i].FTitle ]), FProcesses[i].FEnabled); iniFile.UpdateFile; End; (** This is a setter method for the Process property. @precon iIndex must be a valid index between 0 and Count - 1. @postcon Updates the indexed process with the passed information. @param iIndex as an Integer as a constant @param PInfo as a TITHProcessInfo as a constant **) Procedure TITHProcessCollection.SetProcess(Const iIndex: Integer; Const PInfo: TITHProcessInfo); Var PI : TITHProcessInfo; Begin PI.FEnabled := PInfo.FEnabled; PI.FEXE := PInfo.FEXE; PI.FParams := PInfo.FParams; PI.FDir := PInfo.FDir; PI.FTitle := PInfo.FTitle; FProcesses[iIndex] := PI; End; End.
unit mCoverSheetDisplayPanel_CPRS_Allergies; { ================================================================================ * * Application: CPRS - Coversheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-21 * * Description: Display panel for Allergies. * * Notes: * ================================================================================ } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.UITypes, System.ImageList, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.ImgList, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, mCoverSheetDisplayPanel_CPRS, iCoverSheetIntf, oDelimitedString; type TfraCoverSheetDisplayPanel_CPRS_Allergies = class(TfraCoverSheetDisplayPanel_CPRS) private { Private declarations } fSeparator: TMenuItem; fEnterNewAllergy: TMenuItem; fMarkSelectedAsEnteredInError: TMenuItem; fMarkPtAsNKA: TMenuItem; procedure pmnEnterNewAllergy(Sender: TObject); procedure pmnMarkSelectedAsEnteredInError(Sender: TObject); procedure pmnMarkPtAsNKA(Sender: TObject); protected { Overridden events - TfraGridPanel } procedure OnPopupMenu(Sender: TObject); override; procedure OnPopupMenuInit(Sender: TObject); override; procedure OnPopupMenuFree(Sender: TObject); override; { Overridden events - TfraCoverSheetDisplayPanel_CPRS } procedure OnAddItems(aList: TStrings); override; procedure OnGetDetail(aRec: TDelimitedString; aResult: TStrings); override; public constructor Create(aOwner: TComponent); override; destructor Destroy; override; end; var fraCoverSheetDisplayPanel_CPRS_Allergies: TfraCoverSheetDisplayPanel_CPRS_Allergies; implementation { TfraCoverSheetDisplayPanel_CPRS_Allergies } uses uCore, rODAllergy, fARTAllgy, ORFn, ORNet; const NO_ASSESSMENT = 'No Allergy Assessment'; {$R *.dfm} constructor TfraCoverSheetDisplayPanel_CPRS_Allergies.Create(aOwner: TComponent); begin inherited; AddColumn(0, 'Agent'); AddColumn(1, 'Severity'); AddColumn(2, 'Signs/Symptoms'); CollapseColumns; end; destructor TfraCoverSheetDisplayPanel_CPRS_Allergies.Destroy; begin inherited; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.pmnEnterNewAllergy(Sender: TObject); begin if EnterEditAllergy(0, True, False) then begin CoverSheet.OnRefreshPanel(Self, CV_CPRS_ALLG); CoverSheet.OnRefreshPanel(Self, CV_CPRS_POST); CoverSheet.OnRefreshCWAD(Self); end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.pmnMarkPtAsNKA(Sender: TObject); begin if EnterNKAForPatient then begin CoverSheet.OnRefreshPanel(Self, CV_CPRS_ALLG); CoverSheet.OnRefreshPanel(Self, CV_CPRS_POST); CoverSheet.OnRefreshCWAD(Self); end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.pmnMarkSelectedAsEnteredInError(Sender: TObject); begin if lvData.Selected <> nil then if lvData.Selected.Data <> nil then with TDelimitedString(lvData.Selected.Data) do if GetPieceAsInteger(1) > 0 then if EnterEditAllergy(GetPieceAsInteger(1), False, True) then begin CoverSheet.OnRefreshPanel(Self, CV_CPRS_ALLG); CoverSheet.OnRefreshPanel(Self, CV_CPRS_POST); CoverSheet.OnRefreshCWAD(Sender); end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.OnAddItems(aList: TStrings); var aRec: TDelimitedString; aStr: string; begin try lvData.Items.BeginUpdate; for aStr in aList do begin aRec := TDelimitedString.Create(aStr); if lvData.Items.Count = 0 then { Executes before any item is added } if aRec.GetPieceIsNull(1) then CollapseColumns else ExpandColumns; with lvData.Items.Add do begin Caption := MixedCase(aRec.GetPiece(2)); SubItems.Add(MixedCase(aRec.GetPiece(3))); SubItems.Add(MixedCase(aRec.GetPiece(4))); Data := aRec; end; end; finally lvData.Items.EndUpdate; end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.OnGetDetail(aRec: TDelimitedString; aResult: TStrings); begin CallVistA(CPRSParams.DetailRPC, [Patient.DFN, aRec.GetPiece(1)], aResult); end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.OnPopupMenu(Sender: TObject); var aRec: TDelimitedString; aMsg: string; begin inherited; fEnterNewAllergy.Enabled := True; fMarkSelectedAsEnteredInError.Enabled := False; fMarkPtAsNKA.Enabled := False; { Edge case for Mark as NKA and nothing selected and no assessment } if lvData.Items.Count = 1 then if lvData.Items[0].Data <> nil then begin aRec := TDelimitedString(lvData.Items[0].Data); fMarkPtAsNKA.Enabled := aRec.GetPieceEquals(2, NO_ASSESSMENT); end; if lvData.Selected <> nil then if lvData.Selected.Data <> nil then begin aRec := TDelimitedString(lvData.Selected.Data); if aRec.GetPieceIsNotNull(1) and IsARTClinicalUser(aMsg) then begin fMarkSelectedAsEnteredInError.Enabled := True; end else if lvData.Selected.Index = 0 then fMarkPtAsNKA.Enabled := aRec.GetPieceEquals(2, NO_ASSESSMENT); end; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.OnPopupMenuFree(Sender: TObject); begin FreeAndNil(fSeparator); FreeAndNil(fEnterNewAllergy); FreeAndNil(fMarkSelectedAsEnteredInError); FreeAndNil(fMarkPtAsNKA); inherited; end; procedure TfraCoverSheetDisplayPanel_CPRS_Allergies.OnPopupMenuInit(Sender: TObject); begin inherited; fSeparator := NewLine; fEnterNewAllergy := NewItem('Enter New Allergy ...', 0, False, False, pmnEnterNewAllergy, 0, 'pmnEnterNewAllergy'); fMarkSelectedAsEnteredInError := NewItem('Mark Selected Allergy as Entered in Error ...', 0, False, False, pmnMarkSelectedAsEnteredInError, 0, 'pmnMarkSelectedAllergyAsEnteredInError'); fMarkPtAsNKA := NewItem('Mark Patient As Having "No Known Allergies" (NKA) ...', 0, False, False, pmnMarkPtAsNKA, 0, 'pmnPtAsNKA'); pmn.Items.Add(fSeparator); pmn.Items.Add(fEnterNewAllergy); pmn.Items.Add(fMarkSelectedAsEnteredInError); pmn.Items.Add(fMarkPtAsNKA); end; end.
{ *************************************************************************** } { SynWebEnv.pas is the 1st file of SynBroker Project } { by c5soft@189.cn Version 0.9.2.0 2018-6-7 } { *************************************************************************** } unit SynWebEnv; interface uses Classes, SysUtils, SynCommons, SynCrtSock; type TSynWebEnv = class protected FHost, FMethod, FURL, FPathInfo, FQueryString, FAnchor: RawUTF8; FSSL: Boolean; FStatusCode: Integer; FRemoteIP: string; FContext: THttpServerRequest; FQueryFields: TStrings; FContentFields: TStrings; function PrepareURL: RawUTF8; virtual; function GetContentFields: TStrings; procedure processMultiPartFormData; virtual; public property StatusCode: Integer read FStatusCode write FStatusCode; property Context: THttpServerRequest read FContext; property Host: RawUTF8 read FHost; property Method: RawUTF8 read FMethod; property URL: RawUTF8 read FURL; property SSL: Boolean read FSSL; property PathInfo: RawUTF8 read FPathInfo; property QueryString: RawUTF8 read FQueryString; property Anchor: RawUTF8 read FAnchor; property RemoteIP: string read FRemoteIP; property QueryFields: TStrings read FQueryFields; property ContentFields: TStrings read GetContentFields; function GetHeader(const AUpKey: RawUTF8; const ASource: RawUTF8 = ''; const Sep: AnsiChar = #13): RawUTF8; constructor Create(const AContext: THttpServerRequest); destructor Destroy; override; function MethodAndPathInfo: RawUTF8; procedure OutStream(const AStream: TStream; const AContentType: RawUTF8 = ''); procedure OutFile(const AFileName: string); procedure OutHeader(const ANewHeaderAppended: RawUTF8); procedure OutJSon(const AOutput: PDocVariantData); overload; procedure OutJSon(const AOutput: RawUTF8); overload; {$IFDEF UNICODE} procedure Redirect(const AURI: string); overload; procedure Redirect(const AURI: RawUTF8); overload; procedure OutHtml(const AOutput: RawUTF8); overload; procedure OutHtml(const AOutput: string); overload; procedure OutXML(const AOutput: RawUTF8); overload; procedure OutXML(const AOutput: string); overload; {$ELSE} procedure Redirect(const AURI: string); procedure OutHtml(const AOutput: string); procedure OutXML(const AOutput: string); {$ENDIF} end; TDispatchAction = function(const AEnv: TSynWebEnv): Boolean; procedure RouteMap(const Method, PathInfo: RawUTF8; const Action: TDispatchAction); function RouteDispatch(const AEnv: TSynWebEnv; AMethodAndPathInfo: RawUTF8 = ''): Boolean; implementation type TRouteMap = record MethodAndPathInfo: RawUTF8; Action: TDispatchAction; end; var RouteMapList: array of TRouteMap; procedure RouteMap(const Method, PathInfo: RawUTF8; const Action: TDispatchAction); var nLen: Integer; begin nLen := Length(RouteMapList); Inc(nLen); SetLength(RouteMapList, nLen); Dec(nLen); RouteMapList[nLen].MethodAndPathInfo := UpperCase(Method + ':' + PathInfo); RouteMapList[nLen].Action := Action; end; function RouteDispatch(const AEnv: TSynWebEnv; AMethodAndPathInfo: RawUTF8 = ''): Boolean; var i: Integer; rm: TRouteMap; cScheme: RawUTF8; bFound: Boolean; begin Result := False; if AMethodAndPathInfo = '' then AMethodAndPathInfo := PUTF8Char(AEnv.MethodAndPathInfo); for i := Length(RouteMapList) - 1 downto 0 do begin rm := RouteMapList[i]; if AEnv.SSL then cScheme := 'HTTPS ' else cScheme := 'HTTP '; bFound := IdemPChar(PUTF8Char(cScheme + AMethodAndPathInfo), PAnsiChar(rm.MethodAndPathInfo)); if not bFound then begin bFound := IdemPChar(PUTF8Char(AMethodAndPathInfo), PAnsiChar(rm.MethodAndPathInfo)); end; if bFound then begin Result := rm.Action(AEnv); break; end; end; end; { TSynWebEnv } function InferContentType(const AFileName: string): RawUTF8; var cExt: string; begin Result := ''; cExt := SysUtils.UpperCase(ExtractFileExt(AFileName)); if (cExt = '.HTML') or (cExt = '.HTM') then Result := HTML_CONTENT_TYPE else if cExt = '.JPG' then Result := JPEG_CONTENT_TYPE else if cExt = '.PNG' then Result := 'image/png' else if cExt = '.GIF' then Result := 'image/gif' else if cExt = '.ICO' then Result := 'image/x-icon' else if cExt = '.JS' then Result := 'application/x-javascript' else if cExt = '.CSS' then Result := 'text/css' else Result := 'application/octet-stream'; end; function TSynWebEnv.GetContentFields: TStrings; begin if FContentFields.Count = 0 then begin if IdemPChar(PUTF8Char(FContext.InContentType), 'APPLICATION/X-WWW-FORM-URLENCODED') then FContentFields.Text := UTF8ToString(StringReplaceAll(URLDecode(FContext.InContent), '&', #13#10)) else if IdemPChar(PUTF8Char(Context.InContentType), 'MULTIPART/FORM-DATA') then processMultiPartFormData; end; Result := FContentFields; end; function TSynWebEnv.MethodAndPathInfo: RawUTF8; begin Result := Method + ':' + PathInfo; end; {$IFDEF UNICODE} procedure TSynWebEnv.Redirect(const AURI: string); begin Redirect(StringToUTF8( AURI)); end; procedure TSynWebEnv.Redirect(const AURI: RawUTF8); begin OutHeader('Location: ' + AURI); FStatusCode := 302; end; procedure TSynWebEnv.OutHtml(const AOutput: string); begin OutHtml(StringToUTF8(AOutput)); end; procedure TSynWebEnv.OutHtml(const AOutput: RawUTF8); begin Context.OutContent := AOutput; Context.OutContentType := 'text/html; charset=utf-8'; end; procedure TSynWebEnv.OutXML(const AOutput: string); begin OutXML(StringToUTF8(AOutput)); end; procedure TSynWebEnv.OutXML(const AOutput: RawUTF8); begin Context.OutContent := AOutput; Context.OutContentType := 'text/xml; charset=utf-8'; end; {$ELSE} procedure TSynWebEnv.Redirect(const AURI: string); begin OutHeader('Location: ' +StringToUTF8( AURI)); FStatusCode := 302; end; procedure TSynWebEnv.OutHtml(const AOutput: string); begin Context.OutContent := StringToUTF8(AOutput); Context.OutContentType := 'text/html; charset=utf-8'; end; procedure TSynWebEnv.OutXML(const AOutput: string); begin Context.OutContent := StringToUTF8(AOutput); Context.OutContentType := 'text/xml; charset=utf-8'; end; {$ENDIF} procedure TSynWebEnv.OutJSon(const AOutput: PDocVariantData); begin OutJSon(AOutput.ToJson); end; procedure TSynWebEnv.OutJSon(const AOutput: RawUTF8); begin Context.OutContent := AOutput; Context.OutContentType := 'application/json; charset=utf-8'; end; procedure TSynWebEnv.OutHeader(const ANewHeaderAppended: RawUTF8); begin if Length(ANewHeaderAppended) > 0 then begin with FContext do begin if Length(OutCustomHeaders) > 0 then OutCustomHeaders := OutCustomHeaders + #13#10; OutCustomHeaders := OutCustomHeaders + ANewHeaderAppended; end; end; end; procedure TSynWebEnv.OutFile(const AFileName: string); var ContentType: RawUTF8; begin Context.OutContent := StringToUTF8(AFileName); Context.OutContentType := HTTP_RESP_STATICFILE; ContentType := InferContentType(AFileName); if Length(ContentType) > 0 then begin OutHeader(HEADER_CONTENT_TYPE + ContentType); end; end; function TSynWebEnv.GetHeader(const AUpKey: RawUTF8; const ASource: RawUTF8 = ''; const Sep: AnsiChar = #13): RawUTF8; var P, pUpKey, pSource: PUTF8Char; cVal: RawUTF8; begin pUpKey := PUTF8Char(AUpKey); if ASource = '' then pSource := PUTF8Char(FContext.InHeaders) else pSource := PUTF8Char(ASource); P := StrPosI(pUpKey, pSource); if IdemPCharAndGetNextItem(P, pUpKey, cVal, Sep) then Result := Trim(cVal) else Result := ''; end; constructor TSynWebEnv.Create(const AContext: THttpServerRequest); var nQPos, nAPos: Integer; begin FStatusCode := 200; FQueryFields := TStringList.Create; FContentFields := TStringList.Create; FContext := AContext; FHost := GetHeader('HOST:'); FRemoteIP := UTF8ToString(GetHeader('REMOTEIP:')); FMethod := FContext.Method; FURL := PrepareURL; nAPos := {$IFDEF UNICODE}SynCommons.Pos{$ELSE}Pos{$ENDIF}('#', FURL); nQPos := {$IFDEF UNICODE}SynCommons.Pos{$ELSE}Pos{$ENDIF}('?', FURL); if nQPos > 0 then begin FPathInfo := copy(FURL, 1, nQPos - 1); if nAPos > nQPos then begin FQueryString := copy(FURL, nQPos + 1, nAPos - nQPos - 1); FAnchor := copy(FURL, nAPos + 1, Length(FURL) - nAPos); end else begin FQueryString := copy(FURL, nQPos + 1, Length(FURL) - nQPos); FAnchor := ''; end; end else begin FQueryString := ''; if nAPos > 0 then begin FPathInfo := copy(FURL, 1, nAPos - 1); FAnchor := copy(FURL, nAPos + 1, Length(FURL) - nAPos); end else begin FPathInfo := FURL; FAnchor := ''; end; end; if Length(FQueryString) > 0 then FQueryFields.Text := UTF8ToString(StringReplaceAll(URLDecode(FQueryString), '&', #13#10)); end; destructor TSynWebEnv.Destroy; begin FContentFields.Free; FQueryFields.Free; inherited; end; function TSynWebEnv.PrepareURL: RawUTF8; begin Result := Context.URL; end; procedure TSynWebEnv.OutStream(const AStream: TStream; const AContentType: RawUTF8 = ''); var Buffer: SockString; begin SetLength(Buffer, AStream.Size); AStream.Read(Buffer[1], AStream.Size); Context.OutContent := Buffer; if Length(AContentType) > 0 then Context.OutContentType := AContentType; end; procedure TSynWebEnv.processMultiPartFormData; begin end; initialization finalization SetLength(RouteMapList, 0); end.
unit PascalCoin.Wallet.Interfaces; interface uses System.Classes, System.SysUtils, Spring, Spring.Container, PascalCoin.Utils.Interfaces; type /// <summary> /// current state of the wallet /// </summary> TEncryptionState = ( /// <summary> /// The wallet is not encrypted /// </summary> esPlainText, /// <summary> /// The wallet is encrypted and no valid password has been entered /// </summary> esEncrypted, /// <summary> /// The wallet is encrypted and a valid password is available /// </summary> esDecrypted); IPublicKey = Interface; IPrivateKey = interface; TPascalCoinBooleanEvent = procedure(const AValue: Boolean) of object; TPascalCoinCurrencyEvent = procedure(const AValue: Currency) of object; TPascalCoinIntegerEvent = procedure(const AValue: Integer) of object; IStreamOp = interface ['{31C56DB6-F278-44D1-97F4-CEE099597E95}'] function ReadRawBytes(Stream: TStream; var Value: TRawBytes): Integer; function WriteRawBytes(Stream: TStream; const Value: TRawBytes) : Integer; overload; function ReadString(Stream: TStream; var Value: String): Integer; function WriteAccountKey(Stream: TStream; const Value: IPublicKey): Integer; function ReadAccountKey(Stream: TStream; var Value: IPublicKey): Integer; function SaveStreamToRawBytes(Stream: TStream): TRawBytes; procedure LoadStreamFromRawBytes(Stream: TStream; const raw: TRawBytes); end; IPascalCoinWalletConfig = interface ['{6BE2425B-3C4E-4986-9A01-1725D926820C}'] function GetContainer: TContainer; procedure SetContainer(Value: TContainer); property Container: TContainer read GetContainer write SetContainer; end; IWallet = interface; IPrivateKey = Interface ['{1AD376BC-F871-4E2E-BB33-9EFF89E6D5DF}'] function GetKey: TRawBytes; procedure SetKey(Value: TRawBytes); function GetKeyType: TKeyType; procedure SetKeyType(const Value: TKeyType); function GetAsHexStr: String; property Key: TRawBytes read GetKey write SetKey; property KeyType: TKeyType read GetKeyType write SetKeyType; property AsHexStr: String read GetAsHexStr; End; IPublicKey = interface ['{95FFFBCC-F067-4FFD-8103-3EEE3C68EA92}'] function GetNID: Word; procedure SetNID(const Value: Word); function GetX: TBytes; procedure SetX(const Value: TRawBytes); function GetY: TBytes; procedure SetY(const Value: TRawBytes); function GetKeyType: TKeyType; procedure SetKeyType(const Value: TKeyType); function GetKeyTypeAsStr: string; procedure SetKeyTypeAsStr(const Value: string); function GetAsHexStr: string; function GetAsBase58: string; /// <summary> /// Key Type as integer. makes reading from wallet simpler /// </summary> property NID: Word read GetNID write SetNID; property X: TRawBytes read GetX write SetX; property Y: TRawBytes read GetY write SetY; /// <summary> /// converts NID to TKeyType /// </summary> property KeyType: TKeyType read GetKeyType write SetKeyType; property KeyTypeAsStr: String read GetKeyTypeAsStr write SetKeyTypeAsStr; property AsHexStr: string read GetAsHexStr; property AsBase58: string read GetAsBase58; end; IWalletKey = interface ['{DABC9025-971C-4A59-BCAF-558C385DA379}'] function GetName: String; procedure SetName(const Value: String); function GetKeyType: TKeyType; function GetPublicKey: IPublicKey; function GetCryptedKey: TRawBytes; procedure SetCryptedKey(const Value: TBytes); function GetState: TEncryptionState; function GetPrivateKey: IPrivateKey; Function HasPrivateKey: Boolean; property Name: String read GetName write SetName; property KeyType: TKeyType read GetKeyType; property CryptedKey: TRawBytes read GetCryptedKey write SetCryptedKey; property PublicKey: IPublicKey read GetPublicKey; property PrivateKey: IPrivateKey read GetPrivateKey; property State: TEncryptionState read GetState; end; IWallet = interface ['{A954381D-7085-46CE-82A1-87CCA6554309}'] function GetWalletKey(const Index: Integer): IWalletKey; /// <summary> /// Value is True if the new state is Locked /// </summary> function GetOnLockChange: IEvent<TPascalCoinBooleanEvent>; function ChangePassword(const Value: string): Boolean; function GetWalletFileName: String; function GetState: TEncryptionState; function GetLocked: Boolean; /// <summary> /// The result is the success of the function not the state on the lock /// </summary> function Lock: Boolean; function Unlock(const APassword: string): Boolean; function AddWalletKey(Value: IWalletKey): Integer; function Count: Integer; procedure SaveToStream; function CreateNewKey(const AKeyType: TKeyType; const AName: string): Integer; /// <summary> /// adds all encoded public keys to a TStrings /// </summary> /// <param name="AEncoding"> /// base58 or Hex /// </param> procedure PublicKeysToStrings(Value: TStrings; const AEncoding: TKeyEncoding); /// <summary> /// Finds a key based on a search for an encoded public key /// </summary> /// <param name="Value"> /// encoded public key /// </param> /// <param name="AEncoding"> /// encoding used, default is Hex /// </param> function FindKey(const Value: string; const AEncoding: TKeyEncoding = TKeyEncoding.Hex): IWalletKey; property Key[const Index: Integer]: IWalletKey read GetWalletKey; default; property State: TEncryptionState read GetState; property Locked: Boolean read GetLocked; /// <summary> /// The Value in the procedure is the current state of the wallet lock /// </summary> property OnLockChange: IEvent<TPascalCoinBooleanEvent> read GetOnLockChange; end; TPascalCoinNetType = (ntLive, ntTestNet, ntPrivate); implementation end.
unit Demo5Frm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, RVStyle, RVScroll, RichView, StdCtrls, ExtCtrls, Menus, ShellApi; type TfrmDemo5 = class(TForm) pan: TPanel; edit: TEdit; rv: TRichView; rvs: TRVStyle; pm: TPopupMenu; mitFreezescrolling: TMenuItem; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure editKeyPress(Sender: TObject; var Key: Char); procedure rvSelect(Sender: TObject); procedure pmPopup(Sender: TObject); procedure mitFreezescrollingClick(Sender: TObject); procedure rvJump(Sender: TObject; id: Integer); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var frmDemo5: TfrmDemo5; implementation {$R *.DFM} {--------------------------------------------------------------} function IsAddress(s: String): Boolean; begin // Checks for prefix. // For better results, it should check for lengths... s := UpperCase(s); Result := (Pos('HTTP://', s)=1) or (Pos('FTP://', s)=1) or (Pos('FILE://', s)=1) or (Pos('GOPHER://', s)=1) or (Pos('MAILTO://', s)=1) or (Pos('HTTPS://', s)=1) or (Pos('MAILTO:', s)=1) or (Pos('NEWS:', s)=1) or (Pos('TELNET:', s)=1) or (Pos('WAIS:', s)=1) or (Pos('WWW.', s)=1) or (Pos('FTP.', s)=1); end; {--------------------------------------------------------------} function IsEmail(const s: String): Boolean; var p1, p2: Integer; pchr: PChar; begin //'@' must exist and '.' must be after it. This is not comprehensive test, //but I think that it's ok Result := False; p1 := Pos('@', s); if p1=0 then exit; pchr := StrRScan(PChar(s),'.'); if pchr = nil then exit; p2 := pchr - PChar(s)+1; if p1>p2 then exit; Result := True; end; {--------------------------------------------------------------} procedure AddWithURLs(s: String; rv: TRichView; DefStyle, UrlStyle: Integer); var Before, CurrentWord, Space: String; p: Integer; ParaNo: Integer; begin ParaNo := 0; Before := ''; if s = '' then begin rv.AddNL('', DefStyle, ParaNo); exit; end; while s<>'' do begin p := Pos(' ', s); if p=0 then p := Length(s)+1; CurrentWord := Copy(s, 1, p-1); Space := Copy(s, p, 1); s := Copy(s, p+1, Length(s)); if IsAddress(CurrentWord) or IsEmail(CurrentWord) then begin if Before<>'' then begin rv.AddNL(Before, DefStyle, ParaNo); ParaNo := -1; Before := ''; end; rv.AddNL(CurrentWord, UrlStyle, ParaNo); ParaNo := -1; if Space<>'' then rv.Add(Space, DefStyle); end else Before := Before + CurrentWord+Space; end; if Before<>'' then rv.AddNL(Before, DefStyle, ParaNo); end; {--------------------------------------------------------------} procedure TfrmDemo5.FormCreate(Sender: TObject); begin pan.ClientHeight := edit.Height; edit.SetBounds(0,0,pan.ClientWidth,pan.ClientHeight); rv.AddNL('Use right-click menu to freeze scrolling when appending text', 2, 0); rv.AddNL('Try quick-copy: selection is copied automatically when done', 2, 0); AddWithURLs('You can use URLs and e-mail ( like www.trichview.com )', rv, 2, 1); rv.Format; end; {--------------------------------------------------------------} procedure TfrmDemo5.FormResize(Sender: TObject); begin edit.Width := pan.ClientWidth; end; {--------------------------------------------------------------} procedure TfrmDemo5.editKeyPress(Sender: TObject; var Key: Char); begin if Key=#13 then begin AddWithURLS(edit.Text,rv,0,1); rv.FormatTail; Key := #0; edit.Text := ''; end; end; {--------------------------------------------------------------} procedure TfrmDemo5.rvSelect(Sender: TObject); begin // Quick-copy if rv.SelectionExists then begin rv.CopyDef; rv.Deselect; rv.Invalidate; end; end; {--------------------------------------------------------------} procedure TfrmDemo5.pmPopup(Sender: TObject); begin mitFreezeScrolling.Checked := not (rvoScrollToEnd in rv.Options); end; {--------------------------------------------------------------} procedure TfrmDemo5.mitFreezescrollingClick(Sender: TObject); begin if (rvoScrollToEnd in rv.Options) then rv.Options := rv.Options-[rvoScrollToEnd] else rv.Options := rv.Options+[rvoScrollToEnd]; end; {--------------------------------------------------------------} procedure TfrmDemo5.rvJump(Sender: TObject; id: Integer); var ItemNo: Integer; s: String; begin ItemNo := rv.GetJumpPointItemNo(id); s := rv.GetItemText(ItemNo); if not IsAddress(s) and IsEmail(s) then s := 'mailto:'+s; ShellExecute(Application.Handle, 'open', PChar(s), nil, nil, SW_NORMAL); end; {--------------------------------------------------------------} procedure TfrmDemo5.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then Close; end; end.
unit f04_findYear; interface uses utilitas, buku_handler, f03_findCategory; // menggunakan prosedur urut dan cetak yang ada di unit f03_findCategory { KAMUS } var tahun : integer; inp : string; { DEKLARASI FUNGSI DAN PROSEDUR } procedure filter_tahun(var data_bersih : tabel_buku; data_kotor : tabel_buku; tahun : integer; inp : string); function cek_tahun(val: integer; tahun: integer;inp: string) : boolean; procedure cari_tahun(data_input : tabel_buku); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation function cek_tahun(val: integer; tahun: integer; inp: string) : boolean; { DESKRIPSI : fungsi untuk memeriksa apakah tahun val sesuai dengan kategori inp untuk tahun } { PARAMETER : val, tahun, berupa tipe integer, dan inp berupa tipe string } { RETURN : boolean } { ALGORITMA } begin case inp of '<': cek_tahun := val < tahun; '<=': cek_tahun := val <= tahun; '>': cek_tahun := val > tahun; '>=': cek_tahun := val >= tahun; else cek_tahun := val = tahun; end; end; procedure filter_tahun(var data_bersih : tabel_buku; data_kotor : tabel_buku; tahun : integer; inp : string); { DESKRIPSI : prosedur untuk memfilter data_kotor sehingga menjadi data_bersih dengan isi data sesuai dengan kategori untuk tahun } { PARAMETER : data_bersih dan data_kotor dengan tipe bentukan tabel_buku, tahun bertipe integer, dan inp bertipe string } { KAMUS LOKAL } var i : integer; { ALGORITMA } begin data_bersih.t[0] := data_kotor.t[0]; data_bersih.sz := data_bersih.sz+1; for i := 1 to data_kotor.sz-1 do begin if(cek_tahun(StringToInt(data_kotor.t[i].Tahun_Penerbit), tahun, inp)) then begin data_bersih.t[data_bersih.sz] := data_kotor.t[i]; data_bersih.sz := data_bersih.sz+1; end; end; end; procedure cari_tahun(data_input : tabel_buku); { DESKRIPSI : prosedur untuk mencari buku sesuai dengan kategori tahun dan mencetaknya ke layar } { PARAMETER : data_buku berupa tipe bentukan tabel_buku } { KAMUS LOKAL } var data_bersih : tabel_buku; { ALGORITMA } begin write('Masukkan tahun: '); readln(tahun); write('Masukkan kategori: '); readln(inp); writeln(); writeln('Buku yang terbit ', inp, ' ', tahun, ':'); filter_tahun(data_bersih, data_input, tahun, inp); if(data_bersih.sz=1) then writeln('Tidak ada buku dalam kategori ini.') else begin urutkan(data_bersih); cetak(data_bersih); end; end; end.
unit Unit1; interface var G: Int32; implementation procedure Test; const c = 10; var x, y, z, r : Int32; begin r := 0; x := 0; while x < c do begin y := 0; while y < c do begin z := 0; while z < c do begin r := r + 1; z := z + 1; end; y := y + 1; end; x := x + 1; end; G := r; end; initialization Test(); finalization Assert(G = 1000); end.
unit uLigacao; interface uses Generics.Collections, System.Bindings.Expression, System.Bindings.Helper, //FMX FMX.Edit, FMX.Memo ; type TLigacao = class protected type TExpressionList = TObjectList<TBindingExpression>; private FBindings: TExpressionList; FOwner: TObject; procedure OnChangeTracking(Sender: TObject); protected procedure Notify(const APropertyName: string = ''); property Bindings: TExpressionList read FBindings; public constructor Create(poOwner: TObject); destructor Destroy; override; procedure Ligar(const AProperty: string; const ABindToObject: TObject; const ABindToProperty: string; const ACreateOptions: TBindings.TCreateOptions = [coNotifyOutput, coEvaluate]); procedure ClearBindings; end; implementation uses SysUtils; constructor TLigacao.Create(poOwner: TObject); begin FOwner := poOwner; FBindings := TExpressionList.Create(False); end; destructor TLigacao.Destroy; begin FreeAndNil(FBindings); inherited; end; procedure TLigacao.ClearBindings; var i: TBindingExpression; begin for i in FBindings do TBindings.RemoveBinding(i); FBindings.Clear; end; procedure TLigacao.Ligar(const AProperty: string; const ABindToObject: TObject; const ABindToProperty: string; const ACreateOptions: TBindings.TCreateOptions); var oExpressaoIda, oExpressaoVolta: TBindingExpression; begin oExpressaoIda := TBindings.CreateManagedBinding( [TBindings.CreateAssociationScope([Associate(FOwner, 'src')])], 'src.' + AProperty, [TBindings.CreateAssociationScope([Associate(ABindToObject, 'dst')])], 'dst.' + ABindToProperty, nil, nil, ACreateOptions); if FBindings.IndexOf(oExpressaoIda) > 0 then begin FreeAndNil(oExpressaoIda); Exit; end; FBindings.Add(oExpressaoIda); oExpressaoVolta := TBindings.CreateManagedBinding( [TBindings.CreateAssociationScope([Associate(ABindToObject, 'src')])], 'src.' + ABindToProperty, [TBindings.CreateAssociationScope([Associate(FOwner, 'dst')])], 'dst.' + AProperty, nil, nil, ACreateOptions); FBindings.Add(oExpressaoVolta); if ABindToObject is TEdit then TEdit(ABindToObject).OnChangeTracking := OnChangeTracking; if ABindToObject is TMemo then TMemo(ABindToObject).OnChangeTracking := OnChangeTracking; end; procedure TLigacao.OnChangeTracking(Sender: TObject); begin TBindings.Notify(Sender, 'Text'); end; procedure TLigacao.Notify(const APropertyName: string); begin TBindings.Notify(FOwner, APropertyName); end; end.
// ================================================================ // // Unit uDSProcessMgmtNameUtils.pas // // This unit contains the utils functions for getting the name of // the player, single and multiplayer. // Note: For 1st player, it will get the name of the savefile title // and for pvp/pve, the name of the player in GFWL. // // Esta unit contém funções de utilidade para obter os nomes dos // jogadores. Tanto singleplayer, como multiplayer. // Nota: Para o "player 1", será exibido o nome de título do save, // e para os demais, o nick na GFWL. // // ================================================================ unit uDSProcessMgmtNameUtils; interface uses Windows, SysUtils, uDSProcessMgmtUtils; // Functions for getting the name of the player, reading some pointer address // Função para obter o nome do jogador, lendo os endereços de ponteiros function GetDefaultPlayerName: String; function GetRedPhantomName: String; function GetBluePhantomName: String; function GetWhitePhantomName: String; implementation function GetDefaultPlayerName: String; var wHandle: hwnd; hProcess: integer; pId: integer; Value: Cardinal; Read: NativeUInt; c : AnsiChar; P: Pointer; begin Result := EmptyStr; if not IsDarkSoulsRunning then Exit; wHandle := FindWindow(nil,'DARK SOULS'); GetWindowThreadProcessId(wHandle,@pId); if wHandle <> 0 then begin hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId); ReadProcessMemory(hProcess, Ptr($13DED50), @Value, 4, Read); P := Ptr(Value); ReadProcessMemory(hProcess, Pointer(Pointer(IntegeR(p) + $8)), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $A0), @c, 2, Read); P := Ptr(Value + $A0); try repeat if not ReadProcessMemory(hProcess, Pointer(P), @c, 2, Read) then raise exception.create(syserrormessage(getlasterror)); Result := Result + c; P := pointer(integer(P)+2); until (c=#0) or (Read<>2); except begin Result := EmptyStr; Exit; end; end; Result := Copy(Result, 0, Length(Result) - 1); end; end; function GetRedPhantomName: String; var wHandle: hwnd; hProcess: integer; pId: integer; Value: Cardinal; Read: NativeUInt; c : AnsiChar; P: Pointer; begin Result := EmptyStr; if not IsDarkSoulsRunning then Exit; wHandle := FindWindow(nil,'DARK SOULS'); GetWindowThreadProcessId(wHandle,@pId); if wHandle <> 0 then begin hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId); ReadProcessMemory(hProcess, Ptr($1349020), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $20), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $60C), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $4), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $3C), @Value, 4, Read); P := Ptr(Value + $A0); try repeat if not ReadProcessMemory(hProcess, Pointer(P), @c, 2, Read) then raise exception.create(syserrormessage(getlasterror)); Result := Result + c; P := pointer(integer(P)+2); until (c=#0) or (Read<>2); except begin Result := EmptyStr; Exit; end; end; Result := Copy(Result, 0, Length(Result) - 1); end; end; function GetBluePhantomName: String; var wHandle: hwnd; hProcess: integer; pId: integer; Value: Cardinal; Read: NativeUInt; c : AnsiChar; P: Pointer; begin Result := EmptyStr; if not IsDarkSoulsRunning then Exit; wHandle := FindWindow(nil,'DARK SOULS'); GetWindowThreadProcessId(wHandle,@pId); if wHandle <> 0 then begin hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId); ReadProcessMemory(hProcess, Ptr($1349020), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $60), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $60C), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $4), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $3C), @Value, 4, Read); P := Ptr(Value + $A0); try repeat if not ReadProcessMemory(hProcess, Pointer(P), @c, 2, Read) then raise exception.create(syserrormessage(getlasterror)); Result := Result + c; P := pointer(integer(P)+2); until (c=#0) or (Read<>2); except begin Result := EmptyStr; Exit; end; end; Result := Copy(Result, 0, Length(Result) - 1); end; end; function GetWhitePhantomName: String; var wHandle: hwnd; hProcess: integer; pId: integer; Value: Cardinal; Read: NativeUInt; c : AnsiChar; P: Pointer; begin Result := EmptyStr; if not IsDarkSoulsRunning then Exit; wHandle := FindWindow(nil,'DARK SOULS'); GetWindowThreadProcessId(wHandle,@pId); if wHandle <> 0 then begin hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId); ReadProcessMemory(hProcess, Ptr($1349020), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $40), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $60C), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $4), @Value, 4, Read); ReadProcessMemory(hProcess, Ptr(Value + $3C), @Value, 4, Read); P := Ptr(Value + $A0); try repeat if not ReadProcessMemory(hProcess, Pointer(P), @c, 2, Read) then raise exception.create(syserrormessage(getlasterror)); Result := Result + c; P := pointer(integer(P)+2); until (c=#0) or (Read<>2); except begin Result := EmptyStr; Exit; end; end; Result := Copy(Result, 0, Length(Result) - 1); end; end; end.
{******************************************************************************} { } { CBVCLStylePreview: to paint a Preview of a VCL Style } { based on: VCLStylePreview Vcl.Styles.Ext } { https://github.com/RRUZ/vcl-styles-utils/ } { } { Copyright (c) 2020 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { } { https://github.com/EtheaDev/VCLThemeSelector } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit CBVCLStylePreview; {$Include VCLThemeSelector.inc} interface Uses System.Classes, System.Sysutils, System.Generics.Collections, System.Types, Winapi.Windows, Vcl.Styles, Vcl.Themes, Vcl.Forms, Vcl.Graphics, Vcl.Controls, Vcl.ExtCtrls; const PREVIEW_HEIGHT = 190; //At 96 DPI PREVIEW_WIDTH = 300; //At 96 DPI type TCBVclStylesPreview = class(TCustomControl) private FCustomStyle: TCustomStyleServices; FIcon: HICON; FCaption: TCaption; FRegion : HRGN; FEditRequiredColor, FEditReadonlyColor: TColor; FMenu1Caption, FMenu2Caption, FMenu3Caption, FMenu4Caption: string; FTextEditCaption, FRequiredEditCaption, FReadOnlyEditCaption: string; FButtonNormalCaption, FButtonHotCaption, FButtonPressedCaption, FButtonDisabledCaption: string; FCheckBoxCaption: string; FScale: Double; protected procedure Paint; override; {$IFDEF D10_1+} procedure ChangeScale(M, D: Integer; isDpiChange: Boolean); override; {$ELSE} procedure ChangeScale(M, D: Integer); override; {$ENDIF} public procedure SetCaptions(const ACaptions: string); procedure SetEditColors(const ARequiredColor, AReadonlyColor: TColor); property Icon:HICON read FIcon Write FIcon; property CustomStyle: TCustomStyleServices read FCustomStyle Write FCustomStyle; property Caption : TCaption read FCaption write FCaption; constructor Create(AControl: TComponent); override; destructor Destroy; override; end; implementation { TVclStylePreview } {$IFDEF D10_1+} procedure TCBVclStylesPreview.ChangeScale(M, D: Integer; isDpiChange: Boolean); {$ELSE} procedure TCBVclStylesPreview.ChangeScale(M, D: Integer); {$ENDIF} begin inherited; FScale := FScale * (M / D); Invalidate; end; constructor TCBVclStylesPreview.Create(AControl: TComponent); begin inherited; FScale := 1; FRegion := 0; FCustomStyle := nil; FCaption := ''; FIcon := 0; FMenu1Caption := 'File'; FMenu2Caption := 'Edit'; FMenu3Caption := 'View'; FMenu4Caption := 'Help'; FTextEditCaption := 'Text edit'; FRequiredEditCaption := 'Required'; FReadOnlyEditCaption := 'ReadOnly'; FButtonNormalCaption := 'Normal'; FButtonHotCaption := 'Hot'; FButtonPressedCaption := 'Pressed'; FButtonDisabledCaption := 'Disabled'; FCheckBoxCaption := 'Check'; FEditRequiredColor := clDefault; FEditReadonlyColor := clDefault; end; destructor TCBVclStylesPreview.Destroy; begin if FRegion <> 0 then begin DeleteObject(FRegion); FRegion := 0; end; inherited; end; procedure TCBVclStylesPreview.Paint; var //i: Integer; FBitmap: TBitmap; LDetails, CaptionDetails, IconDetails: TThemedElementDetails; IconRect, BorderRect, CaptionRect, ButtonRect, TextRect: TRect; CaptionBitmap : TBitmap; ThemeTextColor: TColor; ARect, LRect: TRect; LRegion: HRgn; {$ifdef Compiler33_Plus}LDPI: Integer;{$endif} function GetBorderSize: TRect; var Size: TSize; Details: TThemedElementDetails; Detail: TThemedWindow; begin Result := Rect(0, 0, 0, 0); Detail := twCaptionActive; Details := CustomStyle.GetElementDetails(Detail); CustomStyle.GetElementSize(0, Details, esActual, Size); Result.Top := Size.cy; Detail := twFrameLeftActive; Details := CustomStyle.GetElementDetails(Detail); CustomStyle.GetElementSize(0, Details, esActual, Size); Result.Left := Size.cx; Detail := twFrameRightActive; Details := CustomStyle.GetElementDetails(Detail); CustomStyle.GetElementSize(0, Details, esActual, Size); Result.Right := Size.cx; Detail := twFrameBottomActive; Details := CustomStyle.GetElementDetails(Detail); CustomStyle.GetElementSize(0, Details, esActual, Size); Result.Bottom := Size.cy; end; function RectVCenter(var R: TRect; Bounds: TRect): TRect; begin OffsetRect(R, -R.Left, -R.Top); OffsetRect(R, 0, (Bounds.Height - R.Height) div 2); OffsetRect(R, Bounds.Left, Bounds.Top); Result := R; end; procedure DrawCaptionButton(const AButtonTheme: TThemedWindow); begin LDetails := CustomStyle.GetElementDetails(AButtonTheme); CaptionRect.Bottom := Round(CaptionRect.Bottom); if CustomStyle.GetElementContentRect(0, LDetails, CaptionRect, ButtonRect) then CustomStyle.DrawElement(CaptionBitmap.Canvas.Handle, LDetails, ButtonRect); end; procedure DrawButton(const AButtonTheme: TThemedButton; const ACaption: string; const ALeft, ALine: Integer); begin LDetails := CustomStyle.GetElementDetails(AButtonTheme); ButtonRect.Left := Round(BorderRect.Left + 5 + (ALeft * FScale)); ButtonRect.Top := Round(ARect.Height - (45 * FScale) - ((2 - ALine) * FScale * 30)); if AButtonTheme = tbCheckBoxCheckedNormal then ButtonRect.Width := Round(25 * FScale) else ButtonRect.Width := Round(75 * FScale); ButtonRect.Height := Round(25 * FScale); CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, ButtonRect); CustomStyle.GetElementColor(LDetails, ecTextColor, ThemeTextColor); if CustomStyle.name = 'Windows' then begin ButtonRect.Top := ButtonRect.Top + 5; ButtonRect.Bottom := ButtonRect.Bottom + 5; end; if AButtonTheme = tbCheckBoxCheckedNormal then begin ButtonRect.Left := ButtonRect.Left + Round(25 * FScale); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, ACaption, ButtonRect, TTextFormatFlags(DT_VCENTER or DT_LEFT), ThemeTextColor) end else CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, ACaption, ButtonRect, TTextFormatFlags(DT_VCENTER or DT_CENTER), ThemeTextColor); end; procedure DrawEdit(const ACaption: string; const ALeft: Integer; const AColor: TColor = clDefault); var LControlRect: TRect; begin //Draw Edit LDetails := CustomStyle.GetElementDetails(teEditTextNormal); ButtonRect.Left := Round(ALeft * FScale); ButtonRect.Top := Round(ARect.Height - (105 * FScale)); ButtonRect.Width := Round(80 * FScale); ButtonRect.Height := Round(25 * FScale); CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, ButtonRect); if AColor <> clDefault then begin FBitmap.Canvas.Brush.Color := AColor; LControlRect := ButtonRect; LControlRect.Left := LControlRect.Left + 2; LControlRect.Right := LControlRect.Right - 2; LControlRect.Top := LControlRect.Top + 2; LControlRect.Bottom := LControlRect.Bottom - 2; FBitmap.Canvas.FillRect(LControlRect); end; ButtonRect.Left := ButtonRect.Left + 5; //Draw text into Edit CustomStyle.GetElementColor(LDetails, ecTextColor, ThemeTextColor); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, ACaption, ButtonRect, TTextFormatFlags(DT_VCENTER or DT_LEFT), ThemeTextColor); end; begin if FCustomStyle = nil then Exit; FBitmap := TBitmap.Create; try FBitmap.PixelFormat := pf32bit; FBitmap.Canvas.Font.Height := Muldiv(FBitmap.Canvas.Font.Height, Round(96*FScale), Screen.PixelsPerInch); {$ifdef Compiler33_Plus}LDPI := Round(96 / screen.pixelsperinch * fscale * 96);{$endif} BorderRect := GetBorderSize; ARect := ClientRect; CaptionBitmap := TBitmap.Create; try CaptionBitmap.SetSize(ARect.Width, BorderRect.Top); FBitmap.Width := ClientRect.Width; FBitmap.Height := ClientRect.Height; //Draw background LDetails.Element := teWindow; LDetails.Part := 0; CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, ARect); //Draw caption border CaptionRect := Rect(0, 0, Round(CaptionBitmap.Width * FScale), Round(CaptionBitmap.Height * FScale)); LDetails := CustomStyle.GetElementDetails(twCaptionActive); LRegion := FRegion; try CustomStyle.GetElementRegion(LDetails, ARect, FRegion); SetWindowRgn(Handle, FRegion, True); finally if LRegion <> 0 then DeleteObject(LRegion); end; CustomStyle.DrawElement(CaptionBitmap.Canvas.Handle, LDetails, CaptionRect); TextRect := CaptionRect; CaptionDetails := LDetails; //Draw icon IconDetails := CustomStyle.GetElementDetails(twSysButtonNormal); if not CustomStyle.GetElementContentRect(0, IconDetails, CaptionRect, ButtonRect) then ButtonRect := Rect(0, 0, 0, 0); IconRect := Rect(0, 0, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON)); RectVCenter(IconRect, ButtonRect); if (ButtonRect.Width > 0) and (FIcon <> 0) then DrawIconEx(CaptionBitmap.Canvas.Handle, IconRect.Left, IconRect.Top, FIcon, 0, 0, 0, 0, DI_NORMAL); Inc(TextRect.Left, ButtonRect.Width + 5); //Draw buttons if CustomStyle.Name <> 'Windows' then begin //Close button DrawCaptionButton(twCloseButtonNormal); //Maximize button DrawCaptionButton(twMaxButtonNormal); //Minimize button DrawCaptionButton(twMinButtonNormal); //Help button DrawCaptionButton(twHelpButtonNormal); end; if ButtonRect.Left > 0 then TextRect.Right := ButtonRect.Left; //Draw text "Preview" CustomStyle.DrawText(CaptionBitmap.Canvas.Handle, CaptionDetails, FCaption, TextRect, [tfLeft, tfSingleLine, tfVerticalCenter], clNone{$ifdef Compiler33_Plus}, LDPI{$endif}); //Draw caption FBitmap.Canvas.Draw(0, 0, CaptionBitmap); finally CaptionBitmap.Free; end; //Draw left border CaptionRect := Rect(0, BorderRect.Top, BorderRect.Left, ARect.Height - BorderRect.Bottom); LDetails := CustomStyle.GetElementDetails(twFrameLeftActive); if CaptionRect.Bottom - CaptionRect.Top > 0 then CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, CaptionRect); //Draw right border CaptionRect := Rect(ARect.Width - BorderRect.Right, BorderRect.Top, ARect.Width, ARect.Height - BorderRect.Bottom); LDetails := CustomStyle.GetElementDetails(twFrameRightActive); CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, CaptionRect); //Draw Bottom border CaptionRect := Rect(0, ARect.Height - BorderRect.Bottom, ARect.Width, ARect.Height); LDetails := CustomStyle.GetElementDetails(twFrameBottomActive); CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, CaptionRect); //Draw Main Menu LDetails:= CustomStyle.GetElementDetails(tmMenuBarBackgroundActive); LRect := Rect(BorderRect.Left, BorderRect.Top+1, ARect.Width-BorderRect.Left,BorderRect.Top+1+Round(20*FScale)); CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, LRect); LDetails := CustomStyle.GetElementDetails(tmMenuBarItemNormal); CustomStyle.GetElementColor(LDetails, ecTextColor, ThemeTextColor); CaptionRect := Rect(LRect.Left+10,LRect.Top+3, Round(LRect.Right*FScale), Round(LRect.Bottom*FScale)); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, FMenu1Caption, CaptionRect, TTextFormatFlags(DT_LEFT), ThemeTextColor); CaptionRect := Rect(Round(CaptionRect.Left+Length(FMenu1Caption)*8*FScale), LRect.Top+3, LRect.Right , LRect.Bottom); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, FMenu2Caption, CaptionRect, TTextFormatFlags(DT_LEFT), ThemeTextColor); CaptionRect := Rect(Round(CaptionRect.Left+Length(FMenu2Caption)*8*FScale), LRect.Top+3, LRect.Right , LRect.Bottom); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, FMenu3Caption, CaptionRect, TTextFormatFlags(DT_LEFT), ThemeTextColor); CaptionRect := Rect(Round(CaptionRect.Left+Length(FMenu3Caption)*8*FScale), LRect.Top+3, LRect.Right , LRect.Bottom); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, FMenu4Caption, CaptionRect, TTextFormatFlags(DT_LEFT), ThemeTextColor); //Draw ToolButtons (* for i := 1 to 3 do begin LDetails := CustomStyle.GetElementDetails(ttbButtonNormal); ButtonRect.Left := BorderRect.Left + 5 +((i - 1) * 76); ButtonRect.Top := LRect.Top + 30; ButtonRect.Width := 75; ButtonRect.Height := 20; CustomStyle.DrawElement(FBitmap.Canvas.Handle, LDetails, ButtonRect); CustomStyle.GetElementColor(LDetails, ecTextColor, ThemeTextColor); CustomStyle.DrawText(FBitmap.Canvas.Handle, LDetails, 'ToolButton'+IntToStr(i), ButtonRect, TTextFormatFlags(DT_VCENTER or DT_CENTER), ThemeTextColor); end; *) DrawEdit(FTextEditCaption, BorderRect.Left + 5, clDefault); if FEditRequiredColor <> clDefault then DrawEdit(FRequiredEditCaption, BorderRect.Left + 5 + 85, FEditRequiredColor); if FEditReadonlyColor <> clDefault then DrawEdit(FReadOnlyEditCaption, BorderRect.Left + 5 + 85 + 85, FEditReadonlyColor); //Draw Normal Button DrawButton(tbPushButtonNormal, FButtonNormalCaption, 0, 1); //Draw Hot Button DrawButton(tbPushButtonHot, FButtonHotCaption, 80, 1); //Draw Pressed Button DrawButton(tbPushButtonPressed, FButtonPressedCaption, 0, 2); //Draw Disabled Button DrawButton(tbPushButtonDisabled, FButtonDisabledCaption, 80, 2); //Draw CheckBox DrawButton(tbCheckBoxCheckedNormal, FCheckBoxCaption, 160, 2); Canvas.Draw(0, 0, FBitmap); finally FBitmap.Free; end; end; procedure TCBVclStylesPreview.SetEditColors(const ARequiredColor, AReadonlyColor: TColor); begin FEditRequiredColor := ARequiredColor; FEditReadOnlyColor := AReadonlyColor; end; procedure TCBVclStylesPreview.SetCaptions(const ACaptions: string); var LCaptions: TStringList; begin LCaptions := TStringList.Create; LCaptions.Text := ACaptions; try if LCaptions.Count > 0 then //File FMenu1Caption := LCaptions.Strings[0]; if LCaptions.Count > 1 then //Edit FMenu2Caption := LCaptions.Strings[1]; if LCaptions.Count > 2 then //View FMenu3Caption := LCaptions.Strings[2]; if LCaptions.Count > 3 then //Help FMenu4Caption := LCaptions.Strings[3]; if LCaptions.Count > 4 then //Text editor FTextEditCaption := LCaptions.Strings[4]; if LCaptions.Count > 5 then //Normal FButtonNormalCaption := LCaptions.Strings[5]; if LCaptions.Count > 6 then //Hot FButtonHotCaption := LCaptions.Strings[6]; if LCaptions.Count > 7 then //Pressed FButtonPressedCaption := LCaptions.Strings[7]; if LCaptions.Count > 8 then //Disabled FButtonDisabledCaption := LCaptions.Strings[8]; if LCaptions.Count > 9 then //Required FRequiredEditCaption := LCaptions.Strings[9]; if LCaptions.Count > 10 then //Readonly FReadonlyEditCaption := LCaptions.Strings[10]; if LCaptions.Count > 11 then //CheckBox FCheckBoxCaption := LCaptions.Strings[11]; finally LCaptions.Free; end; end; end.
(** This module contaisn resource string for use throughout the application. @Author David Hoyle @Version 1.0 @Date 07 Jan 2018 **) Unit ITHelper.ResourceStrings; Interface ResourceString (** This is a message string to appear in the splash screen **) strSplashScreenName = 'Integrated Testing Helper %d.%d%s for %s'; {$IFDEF DEBUG} (** This is another message string to appear in the splash screen **) strSplashScreenBuild = 'Freeware by David Hoyle (Build %d.%d.%d.%d)'; {$ELSE} (** This is another message string to appear in the splash screen **) strSplashScreenBuild = 'Freeware by David Hoyle (Build %d.%d.%d.%d)'; {$ENDIF} (** This is a resourcestring for the message tab name. **) strITHelperGroup = 'ITHelper Messages'; Implementation End.
unit PureContextMenu; interface uses ActiveX; function DllGetClassObject(const CLSID: TCLSID; const IID: TIID; var Obj: Pointer): HResult; stdcall; function DllCanUnloadNow: HResult; stdcall; function DllRegisterServer: HResult; stdcall; function DllUnregisterServer: HResult; stdcall; implementation uses Windows, SysUtils, ShellAPI, ShlObj; const IID_IUnknown: TIID = '{00000000-0000-0000-C000-000000000046}'; type IUnknown = ^PIUnknownMT; PIUnknownMT = ^TIUnknownMT; TIUnknownMT = packed record { IUnknown method table } QueryInterface: function (const Self: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; AddRef: function (const Self: IUnknown): Integer; stdcall; Release: function (const Self: IUnknown): Integer; stdcall; end; const IID_IClassFactory: TIID = '{00000001-0000-0000-C000-000000000046}'; type IClassFactory = ^PIClassFactoryMT; PIClassFactoryMT = ^TIClassFactoryMT; TIClassFactoryMT = packed record { IClassFactory method table } case Integer of 0: ( { IUnknown methods } QueryInterface: function (const Self: IClassFactory; const IID: TIID; var Obj: Pointer): HResult; stdcall; AddRef: function (const Self: IClassFactory): Integer; stdcall; Release: function (const Self: IClassFactory): Integer; stdcall; { IClassFactory methods } CreateInstance: function (const Self: IClassFactory; const UnkOuter: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; LockServer: function (const Self: IClassFactory; fLock: Bool): HResult; stdcall;); 1: (IUnknownMT: TIUnknownMT); end; type IDataObject = ^PIDataObjectMT; PIDataObjectMT = ^TIDataObjectMT; TIDataObjectMT = packed record { IDataObject method table } case Integer of 0: ( { IUnknown methods } QueryInterface: function (const Self: IClassFactory; const IID: TIID; var Obj: Pointer): HResult; stdcall; AddRef: function (const Self: IClassFactory): Integer; stdcall; Release: function (const Self: IClassFactory): Integer; stdcall; { IDataObject methods } GetData: function (const Self: IDataObject; const formatetcIn: TFormatEtc; var medium: TStgMedium): HResult; stdcall; // This is cheating here, a bit. The remaining methods in IDataObject // are unused, so some work can be saved by defining only what is used. // And that's O.K. since the method table is identical to this point. {!!!-------------------------------------------------------------------- GetDataHere: function (const Self: IDataObject; const formatetc: TFormatEtc; var medium: TStgMedium): HResult; stdcall; QueryGetData: function (const Self: IDataObject; const formatetc: TFormatEtc): HResult; stdcall; GetCanonicalFormatEtc: function (const Self: IDataObject; const formatetc: TFormatEtc; var formatetcOut: TFormatEtc): HResult; stdcall; SetData: function (const Self: IDataObject; const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HResult; stdcall; EnumFormatEtc: function (const Self: IDataObject; dwDirection: Longint; var enumFormatEtc: IEnumFormatEtc): HResult; stdcall; DAdvise: function (const Self: IDataObject; const formatetc: TFormatEtc; advf: Longint; const advSink: IAdviseSink; var dwConnection: Longint): HResult; stdcall; DUnadvise: function (const Self: IDataObject; dwConnection: Longint): HResult; stdcall; EnumDAdvise: function (const Self: IDataObject; var enumAdvise: IEnumStatData): HResult; stdcall; --------------------------------------------------------------------!!!} ); 1: (IUnknownMT: TIUnknownMT); end; const IID_IShellExtInit: TIID = '{000214E8-0000-0000-C000-000000000046}'; type IShellExtInit = ^PIShellExtInitMT; PIShellExtInitMT = ^TIShellExtInitMT; TIShellExtInitMT = packed record { IShellExtInit method table } case Integer of 0: ( { IUnknown methods } QueryInterface: function (const Self: IShellExtInit; const IID: TIID; var Obj: Pointer): HResult; stdcall; AddRef: function (const Self: IShellExtInit): Integer; stdcall; Release: function (const Self: IShellExtInit): Integer; stdcall; { IShellExtInit methods } Initialize: function (const Self: IShellExtInit; pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; stdcall;); 1: (IUnknownMT: TIUnknownMT); end; const IID_IContextMenu: TIID = '{000214E4-0000-0000-C000-000000000046}'; type IContextMenu = ^PIContextMenuMT; PIContextMenuMT = ^TIContextMenuMT; TIContextMenuMT = packed record { IContextMenu method table } case Integer of 0: ( { IUnknown methods } QueryInterface: function (const Self: IContextMenu; const IID: TIID; var Obj: Pointer): HResult; stdcall; AddRef: function (const Self: IContextMenu): Integer; stdcall; Release: function (const Self: IContextMenu): Integer; stdcall; { IContextMenu methods } QueryContextMenu: function (const Self: IContextMenu; Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; stdcall; InvokeCommand: function (const Self: IContextMenu; var lpici: TCMInvokeCommandInfo): HResult; stdcall; GetCommandString: function (const Self: IContextMenu; idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; stdcall;); 1: (IUnknownMT: TIUnknownMT); end; const CLSIDString_QuickRegister = '{40E69241-5D1A-11D1-81CB-0020AF3E97A9}'; CLSIDStr = 'CLSID\' + CLSIDString_QuickRegister; CLSID_QuickRegister: TCLSID = CLSIDString_QuickRegister; type PClassFactory = ^TClassFactory; TClassFactory = PIClassFactoryMT; PContextMenu = ^TContextMenu; TContextMenu = record CMMTAddr: PIContextMenuMT; SEIMTAddr: PIShellExtInitMT; RefCount: Integer; FileName: String; end; var ClassFactoryMT: TIClassFactoryMT; ContextMenuMT: TIContextMenuMT; ShellExtInitMT: TIShellExtInitMT; ClassFactory: TClassFactory; ServerLockCount: Integer = 0; { COM Runtime support } function DllGetClassObject(const CLSID: TCLSID; const IID: TIID; var Obj: Pointer): HResult; stdcall; begin // Validate the output address. if @Obj = nil then begin Result := E_POINTER; Exit end; // Assume failure. Obj := nil; Result := CLASS_E_CLASSNOTAVAILABLE; if IsEqualCLSID(CLSID, CLSID_QuickRegister) then Result := ClassFactory^.QueryInterface(@ClassFactory, IID, Obj) end; function DllCanUnloadNow: HResult; stdcall; begin if (ServerLockCount <> 0) then Result := S_FALSE else Result := S_OK end; function DllRegisterServer: HResult; stdcall; var FileName: array [0..MAX_PATH] of Char; RootKey: HKey; procedure CreateKey(const Key, ValueName, Value: string); var Handle: HKey; Res, Disposition: Integer; begin Res := RegCreateKeyEx(RootKey, PChar(Key), 0, '', REG_OPTION_NON_VOLATILE, KEY_READ or KEY_WRITE, nil, Handle, @Disposition); if Res = 0 then begin Res := RegSetValueEx(Handle, PChar(ValueName), 0, REG_SZ, PChar(Value), Length(Value) + 1); RegCloseKey(Handle) end; if Res <> 0 then raise Exception.Create('Error updating registry') end; begin try RootKey := HKEY_CLASSES_ROOT; CreateKey(CLSIDStr, '', 'Quick Register Context Menu Shell Extension'); GetModuleFileName(HInstance, FileName, SizeOf(FileName)); CreateKey(CLSIDStr + '\InprocServer32', '', FileName); CreateKey(CLSIDStr + '\InprocServer32', 'ThreadingModel', 'Apartment'); CreateKey('dllfile\shellex', '', ''); CreateKey('dllfile\shellex\ContextMenuHandlers', '', ''); CreateKey('dllfile\shellex\ContextMenuHandlers\QuickRegister', '', CLSIDString_QuickRegister); RootKey := HKEY_LOCAL_MACHINE; CreateKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', '', ''); CreateKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved', CLSIDString_QuickRegister, 'Quick Register Context Menu Shell Extension'); Result := S_OK except DllUnregisterServer; Result := SELFREG_E_CLASS end end; function DllUnregisterServer: HResult; stdcall; procedure DeleteKey(const Key: string); begin RegDeleteKey(HKEY_CLASSES_ROOT, PChar(Key)) end; begin DeleteKey('dllfile\shellex\ContextMenuHandlers\QuickRegister'); DeleteKey('dllfile\shellex\ContextMenuHandlers'); DeleteKey('dllfile\shellex'); DeleteKey(CLSIDStr + '\InprocServer32'); DeleteKey(CLSIDStr); Result := S_OK end; { IClassFactory - IUnknown methods} function ClassFactory_QueryInterface(const Self: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; begin // Validate the output address. if @Obj = nil then begin Result := E_POINTER; Exit end; // Assume failure. Obj := nil; Result := E_NOINTERFACE; // Check for supported interfaces. if IsEqualIID(IID, IID_IUnknown) or IsEqualIID(IID, IID_IClassFactory) then begin // Return the requested interface and AddRef. Obj := Self; IUnknown(Obj)^^.AddRef(Obj); Result := S_OK end end; function ClassFactory_AddRef(const Self: IUnknown): Integer; stdcall; begin InterlockedIncrement(ServerLockCount); Result := 2 end; function ClassFactory_Release(const Self: IUnknown): Integer; stdcall; begin InterlockedDecrement(ServerLockCount); Result := 1 end; { IClassFactory - IClassFactory methods} function ClassFactory_CreateInstance(const Self: IClassFactory; const UnkOuter: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; var pcm: PContextMenu; begin // Validate the output address. if @Obj = nil then begin Result := E_POINTER; Exit end; // Assume failure. Obj := nil; // This object does not support aggregation. if Assigned(UnkOuter) then begin Result := CLASS_E_NOAGGREGATION; Exit end; pcm := nil; try // Construct a ContextMenu object. New(pcm); FillChar(pcm^, SizeOf(pcm^), 0); with pcm^do begin CMMTAddr := @ContextMenuMT; SEIMTAddr := @ShellExtInitMT; Result := CMMTAddr^.QueryInterface(@CMMTAddr, IID, Obj); if Succeeded(Result) then InterlockedIncrement(ServerLockCount) else Dispose(pcm) end except on E: EOutOfMemory do Result := E_OUTOFMEMORY else begin if Assigned(pcm) then Dispose(pcm); Result := E_FAIL end end end; function ClassFactory_LockServer(const Self: IClassFactory; fLock: Bool): HResult; stdcall; begin if fLock then InterlockedIncrement(ServerLockCount) else InterlockedDecrement(ServerLockCount); Result := S_OK end; { IContextMenu - IUnknown methods} function ContextMenu_QueryInterface(const Self: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; begin // Validate the output address. if @Obj = nil then begin Result := E_POINTER; Exit end; // Assume failure. Obj := nil; Result := E_NOINTERFACE; // Check for supported interfaces. if IsEqualIID(IID, IID_IUnknown) or IsEqualIID(IID, IID_IContextMenu) or IsEqualIID(IID, IID_IShellExtInit) then // Return the requested interface and AddRef. with PContextMenu(Self)^ do begin if IsEqualIID(IID, IID_IShellExtInit) then Obj := @SEIMTAddr else Obj := @CMMTAddr; IUnknown(Obj)^^.AddRef(Obj); Result := S_OK end end; function ContextMenu_AddRef(const Self: IUnknown): Integer; stdcall; begin with PContextMenu(Self)^ do Result := InterlockedIncrement(RefCount) end; function ContextMenu_Release(const Self: IUnknown): Integer; stdcall; begin with PContextMenu(Self)^ do begin Result := InterlockedDecrement(RefCount); if (Result = 0) then begin Dispose(PContextMenu(Self)); InterlockedDecrement(ServerLockCount) end end end; { IContextMenu - IContextMenu methods} function ContextMenu_QueryContextMenu(const Self: IContextMenu; Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; stdcall; begin Result := MakeResult(SEVERITY_SUCCESS, FACILITY_NULL, 0); if ((uFlags and $0000000F) = CMF_NORMAL) or ((uFlags and CMF_EXPLORE) <> 0) then begin InsertMenu(Menu, indexMenu, MF_SEPARATOR or MF_BYPOSITION, 0, nil); InsertMenu(Menu, indexMenu + 1, MF_STRING or MF_BYPOSITION, idCmdFirst, 'Register'); InsertMenu(Menu, indexMenu + 2, MF_STRING or MF_BYPOSITION, idCmdFirst + 1, 'Unregister'); InsertMenu(Menu, indexMenu + 3, MF_SEPARATOR or MF_BYPOSITION, 0, nil); Result := MakeResult(SEVERITY_SUCCESS, FACILITY_NULL, 2) end end; function ContextMenu_InvokeCommand(const Self: IContextMenu; var lpici: TCMInvokeCommandInfo): HResult; stdcall; const ProcNames: array [0..1] of PChar = ('DllRegisterServer', 'DllUnregisterServer'); var pcm: PContextMenu absolute Self; Cmd: Word; procedure RegisterCOMServer; var Handle: THandle; RegProc: function: HResult; stdcall; hr: HResult; begin Handle := LoadLibrary(PChar(pcm^.FileName)); if Handle = 0 then raise Exception.CreateFmt('%s: %s', [SysErrorMessage(GetLastError), pcm^.FileName]); try RegProc := GetProcAddress(Handle, ProcNames[Cmd]); if Assigned(RegProc) then begin hr := RegProc; if Failed(hr) then raise Exception.Create( ProcNames[Cmd] + ' in ' + pcm^.FileName + ' failed.') end else RaiseLastWin32Error finally FreeLibrary(Handle) end end; begin Result := E_INVALIDARG; Cmd := LoWord(Integer(lpici.lpVerb)); if (HiWord(Integer(lpici.lpVerb)) <> 0) or (not Cmd in [0..1]) then Exit; Result := E_FAIL; try RegisterCOMServer; MessageBox(lpici.hwnd, PChar(ProcNames[Cmd] + ' in ' + pcm^.FileName + ' succeeded.'), 'Quick Register', MB_ICONINFORMATION or MB_OK); Result := S_OK except on E: Exception do MessageBox(lpici.hWnd, PChar(E.Message), 'Quick Register - Error', MB_ICONERROR or MB_OK); end end; function ContextMenu_GetCommandString(const Self: IContextMenu; idCmd, uType: UINT; pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult; stdcall; const RegStr: PChar = 'Register this COM/ActiveX server.'; UnRegStr: PChar = 'Unregister this COM/ActiveX server.'; begin Result := S_OK; if uType = GCS_HELPTEXT then case idCmd of 0: StrCopy(pszName, RegStr); 1: StrCopy(pszName, UnRegStr) else Result := E_INVALIDARG end end; { IShellExtInit - IUnknown methods } function ShellExtInit_QueryInterface(const Self: IUnknown; const IID: TIID; var Obj: Pointer): HResult; stdcall; var TrueSelf: IContextMenu; begin // Fix up the pointer to the IContextMenu interface. TrueSelf := IContextMenu(Self); Dec(TrueSelf); // Delegate. Result := TrueSelf^^.QueryInterface(TrueSelf, IID, Obj) end; function ShellExtInit_AddRef(const Self: IUnknown): Integer; stdcall; var TrueSelf: IContextMenu; begin // Fix up the pointer to the IContextMenu interface. TrueSelf := IContextMenu(Self); Dec(TrueSelf); // Delegate. Result := TrueSelf^^.AddRef(TrueSelf) end; function ShellExtInit_Release(const Self: IUnknown): Integer; stdcall; var TrueSelf: IContextMenu; begin // Fix up the pointer to the IContextMenu interface. TrueSelf := IContextMenu(Self); Dec(TrueSelf); // Delegate. Result := TrueSelf^^.Release(TrueSelf) end; { IShellExtInit - IShellExtInit.Initialize} function ShellExtInit_Initialize(const Self: IShellExtInit; pidlFolder: PItemIDList; lpdobj: IDataObject; hKeyProgID: HKEY): HResult; stdcall; var pcm: PContextMenu; ContextMenu: IContextMenu absolute pcm; FormatETC: TFormatEtc; StgMedium: TStgMedium; szFile: array [0..MAX_PATH] of Char; begin if not Assigned(lpdobj) then begin Result := E_INVALIDARG; Exit end; // Fix up the pointer to the actual ContextMenu "object". ContextMenu := IContextMenu(Self); Dec(ContextMenu); with FormatETC do begin cfFormat := CF_HDROP; ptd := nil; dwAspect := DVASPECT_CONTENT; lindex := -1; tymed := TYMED_HGLOBAL end; Result := E_FAIL; if Succeeded(lpdobj^^.GetData(lpdobj, FormatETC, StgMedium)) and (DragQueryFile(StgMedium.hGlobal, $FFFFFFFF, nil, 0) = 1) then begin DragQueryFile(StgMedium.hGlobal, 0, szFile, SizeOf(szFile)); pcm^.FileName := szFile; ReleaseStgMedium(StgMedium); Result := S_OK end end; initialization // Setup the method table for each interface that is implemented. with ClassFactoryMT, IUnknownMT do begin QueryInterface := ClassFactory_QueryInterface; AddRef := ClassFactory_AddRef; Release := ClassFactory_Release; CreateInstance := ClassFactory_CreateInstance; LockServer := ClassFactory_LockServer end; with ContextMenuMT, IUnknownMT do begin QueryInterface := ContextMenu_QueryInterface; AddRef := ContextMenu_AddRef; Release := ContextMenu_Release; QueryContextMenu := ContextMenu_QueryContextMenu; InvokeCommand := ContextMenu_InvokeCommand; GetCommandString := ContextMenu_GetCommandString end; with ShellExtInitMT, IUnknownMT do begin QueryInterface := ShellExtInit_QueryInterface; AddRef := ShellExtInit_AddRef; Release := ShellExtInit_Release; Initialize := ShellExtInit_Initialize end; // "Instantiate" the classfactory. ClassFactory := @ClassFactoryMT; DisableThreadLibraryCalls(hInstance) end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit DeploymentAPI; interface uses System.SysUtils, System.Classes, ToolsAPI, PlatformAPI, System.Generics.Collections, System.Types; type // IDE Service IOTADeploymentService = interface ['{658EBC6E-E96F-45FA-934B-505D158852C7}'] procedure DeployManagerProject(const Project: IOTAProject); end; // Project module interface. Projects that support deployment may implement. // IDeployAssemblyReferences = interface; IDeployableProject = interface ['{F775F090-1966-4C65-B778-DF4CD2F7F9E6}'] // function GetHasAssemblyReferences: Boolean; // function GetAssemblyReferences: IDeployAssemblyReferences; // property HasAssemblyReferences: Boolean read GetHasAssemblyReferences; // property AssemblyReferences: IDeployAssemblyReferences read GetAssemblyReferences; end; // IDeployAssemblyReferences = interface // ['{68E7820D-5249-4E86-9024-E97A6BDC4176}'] // procedure Refresh; // function GetCount: Integer; // function GetFileName(I: Integer): string; // property Count: Integer read GetCount; // property FileNames[I: Integer]: string read GetFileName; // end; const feDeployProj = '.deployproj'; dcFile = 'File'; dcProjectOutput = 'ProjectOutput'; dcDebugSymbols = 'DebugSymbols'; dcAdditionalDebugSymbols = 'AdditionalDebugSymbols'; dcDependencyPackage = 'DependencyPackage'; dcDependencyPackageResource = 'DependencyPackageResource'; dcDependencyPackageDebugSymbols = 'DependencyPackageDebugSymbols'; dcDependencyModule = 'DependencyModule'; dcDependencyFramework = 'DependencyFramework'; dcProjectOSXResource = 'ProjectOSXResource'; dcProjectOSXInfoPList = 'ProjectOSXInfoPList'; dcProjectEntitlements = 'ProjectOSXEntitlements'; type { Make sure the ordinal values of TDeployOperation match the corresponding "put" arguments for the remote agent. Make sure doNotSpecified is always the highest ordinal value } TDeployOperation = (doCopyOnly, doSetExecBit, doUnArchive, doRun, doUnused, doExecuteScript, doNotSpecified); TDeploymentItemAction = (daAdded, daChanged, daRemoved, daReconciled); IProjectDeploymentItem = interface ['{9D9FC05C-49BD-4FD8-8425-833D16FA55E3}'] { Condition is an MSBuild condition statement which will be evaluated in the context of the deployment's project when the Deploy target is run, so that delivery can be conditionalized based on project settings. e.g., "'$(DynamicRTL)'=='true'" on the file libcgrtl.dylib will cause it to be deployed only when the project has linked with the dynamic rtl. Look in $(TP)\app\design\*Strs.pas for a list of most project setting property names } function GetCondition: string; function GetLocalCommands(const PlatformName: string): TList<string>; function GetOperation(const PlatformName: string): TDeployOperation; function GetPlatforms: TArray<string>; function GetRemoteCommands(const PlatformName: string): TList<string>; function GetRemoteDir(const PlatformName: string): string; function GetRequired: Boolean; procedure RemovePlatform(const PlatformName: string); procedure SetCondition(const Value: string); procedure SetOperation(const PlatformName: string; const Value: TDeployOperation); procedure SetRemoteDir(const PlatformName, Value: string); procedure SetRequired(Value: Boolean); property Condition: string read GetCondition write SetCondition; property LocalCommands[const PlatformName: string]: TList<string> read GetLocalCommands; property Operation[const PlatformName: string]: TDeployOperation read GetOperation write SetOperation; property RemoteCommands[const PlatformName: string]: TList<string> read GetRemoteCommands; property RemoteDir[const PlatformName: string]: string read GetRemoteDir write SetRemoteDir; property Required: Boolean read GetRequired write SetRequired; property Platforms: TArray<string> read GetPlatforms; end; IProjectDeploymentFile = interface(IProjectDeploymentItem) ['{184728B4-5713-4D50-A042-CD027A7802BA}'] function GetConfiguration: string; function GetDeploymentClass: string; function GetEnabled(const PlatformName: string): Boolean; function GetLocalName: string; function GetRemoteName(const PlatformName: string): string; procedure SetConfiguration(const Value: string); procedure SetDeploymentClass(const Value: string); procedure SetEnabled(const PlatformName: string; const Value: Boolean); procedure SetLocalName(const Value: string); procedure SetRemoteName(const PlatformName, Value: string); property Configuration: string read GetConfiguration write SetConfiguration; property DeploymentClass: string read GetDeploymentClass write SetDeploymentClass; property Enabled[const PlatformName: string]: Boolean read GetEnabled write SetEnabled; property LocalName: string read GetLocalName write SetLocalName; property RemoteName[const PlatformName: string]: string read GetRemoteName write SetRemoteName; end; IProjectDeploymentClass = interface(IProjectDeploymentItem) ['{C1FA0FD1-A0B0-4465-BE24-6C37C75B6D28}'] function GetClassId: string; function GetDescription: string; procedure SetClassId(const Value: string); procedure SetDescription(const Value: string); function ValidFor(const Filename, PlatformName: string): Boolean; property ClassId: string read GetClassId write SetClassId; property Description: string read GetDescription write SetDescription; end; IProjectDeploymentNotifier = interface ['{E3BBD079-75B6-46F6-AC61-AD4B3B793111}'] procedure Destroyed; procedure ItemChanged(const Item: IProjectDeploymentItem; Action: TDeploymentItemAction); procedure Loaded(const ClassId: string); end; TDeploymentFileArray = array of IProjectDeploymentFile; TDeploymentClassArray = array of IProjectDeploymentClass; const cAllPlatforms = 'All'; type TReconcileResult = (rrSuccess, rrNotUpToDate, rrCompileRequired, rrFailed, rrNotSupported); IProjectDeployment = interface ['{FF8F9951-52D1-40F1-8A34-A72969BEE0D6}'] { Register for notifications when project deployment data changes } function AddNotifier(const Notifier: IProjectDeploymentNotifier): Integer; procedure AddClass(const AClass: IProjectDeploymentClass); procedure AddFile(const AFile: IProjectDeploymentFile); procedure Clear; function CreateClass(const ClassId: string): IProjectDeploymentClass; function CreateFile(const LocalName: string): IProjectDeploymentFile; function FindFiles(const LocalName, Configuration, PlatformName, ClassName: string): TDeploymentFileArray; function GetClasses: TDictionary<string, IProjectDeploymentClass>.TValueCollection; function GetClass(const ClassId: string): IProjectDeploymentClass; { Returns which classes, if any, can be used with a particular file based on it's extension } function GetDefaultClasses(const Filename, PlatformName: string): TDeploymentClassArray; function GetFile(const LocalName: string): IProjectDeploymentFile; function GetFiles: TDictionary<string, IProjectDeploymentFile>.TValueCollection; { Return an array of all items with ClassId } function GetFilesOfClass(const ClassId: string): TDeploymentFileArray; { The project binary output's remote filename, relative to the remote project directory } function GetProjectOutputFile(const PlatformName: string = ''; const ConfigurationName: string = ''): string; { The root directory on the remote machine, relative to the agent's "scratch" directory, or a fully qualified path } function GetRemoteProjectDir(PlatformName: string): string; { Does the deployment have any data in it, or has ever been reconciled } function IsEmpty: Boolean; { Updates deployment to reflect current project state } function Reconcile(Configuration: string = ''; PlatformName: string = ''): TReconcileResult; { Remove a deployment class } procedure RemoveClass(const ClassId: string); { Remove all deployment data associated with a local file } procedure RemoveFile(const LocalName: string); { Remove all files with ClassId } procedure RemoveFilesOfClass(const ClassId: string); { Remove previously registered notifier } procedure RemoveNotifier(const NotifierIndex: Integer); { Remove all deployment data, reset to default } procedure Reset; { Write MSBuild script used by the Deployment MSBuild target } procedure SaveToMSBuild; { Set remote project root directory } procedure SetRemoteProjectDir(PlatformName: string; const Value: string); property Classes: TDictionary<string, IProjectDeploymentClass>.TValueCollection read GetClasses; property Files: TDictionary<string, IProjectDeploymentFile>.TValueCollection read GetFiles; property RemoteProjectDir[PlatformName: string]: string read GetRemoteProjectDir write SetRemoteProjectDir; end; { Helper functions to resolve unspecified IProjectDeploymentFile fields through the underlying Deployment Class } function GetDeploymentRemoteDir(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): string; function GetDeploymentOperation(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): TDeployOperation; function GetDeploymentClass(const AFile: IProjectDeploymentFile): string; function GetDeploymentRequired(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): Boolean; implementation function GetDeploymentRemoteDir(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): string; begin Result := AFile.RemoteDir[PlatformName]; if (Result = '') and (AFile.DeploymentClass <> '') and (Deployment.GetClass(AFile.DeploymentClass) <> nil) then begin Result := Deployment.GetClass(AFile.DeploymentClass).RemoteDir[PlatformName]; if Result <> '' then Result := IncludeTrailingPathDelimiter(Result); end; end; function GetDeploymentOperation(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): TDeployOperation; begin Result := AFile.Operation[PlatformName]; if (Result = doNotSpecified) and (AFile.DeploymentClass <> '') and (Deployment.GetClass(AFile.DeploymentClass) <> nil) then Result := Deployment.GetClass(AFile.DeploymentClass).Operation[PlatformName]; if Result = doNotSpecified then Result := doCopyOnly; end; function GetDeploymentClass(const AFile: IProjectDeploymentFile): string; begin Result := AFile.DeploymentClass; if Result = '' then Result := dcFile; end; function GetDeploymentRequired(const AFile: IProjectDeploymentFile; const PlatformName: string; const Deployment: IProjectDeployment): Boolean; begin Result := AFile.Required; if not Result and (AFile.DeploymentClass <> '') and (Deployment.GetClass(AFile.DeploymentClass) <> nil) then Result := Deployment.GetClass(AFile.DeploymentClass).Required; end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the GNU General Public License Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.gnu.org/copyleft/gpl.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code is Michael Elsdörfer. All Rights Reserved. $Id$ You may retrieve the latest version of this file at the Corporeal Website, located at http://www.elsdoerfer.info/corporeal Known Issues: -----------------------------------------------------------------------------} unit ConfigFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, JvExStdCtrls, JvGroupBox, pngimage, ExtCtrls, gnugettext; type TConfigForm = class(TForm) JvGroupBox1: TJvGroupBox; Label1: TLabel; Edit1: TEdit; Image1: TImage; TntLabel1: TLabel; procedure FormCreate(Sender: TObject); end; var ConfigForm: TConfigForm; implementation uses VistaCompat; {$R *.dfm} procedure TConfigForm.FormCreate(Sender: TObject); begin // Localize TranslateComponent(Self); // use font setting of os (mainly intended for new vista font) SetDesktopIconFonts(Self.Font); end; end.
(* AVR Basic Compiler Copyright 1997-2002 Silicon Studio Ltd. Copyright 2008 Trioflex OY http://www.trioflex.com *) unit strut; interface uses SysUtils; function RemoveQuote(param: string): string; function RemoveExt(param: string): string; function Hex2B(Hex: string): Word; implementation // Two hex chars into byte function Hex2B; var i, W: Word; C: Char; begin W := 0; for i := 1 to 2 do begin C := Hex[i]; W := W shl 4; case C of '0'..'9': W := W or (ord(C) - $30); 'a'..'f': W := W or (ord(C) - ord('a') + 10); 'A'..'F': W := W or (ord(C) - ord('A') + 10); end; Hex2B := W; end; end; function RemoveQuoteNoCheck(param: string): string; begin // Remove leader and trailer result := Copy(param, 2, length(param) - 2); end; function RemoveQuote(param: string): string; begin if param[1] = '<' then if param[length(param)] = '>' then begin result := RemoveQuoteNoCheck(param); exit; end; if param[1] = '"' then if param[length(param)] = '"' then begin result := RemoveQuoteNoCheck(param); exit; end; if param[1] = '''' then if param[length(param)] = '''' then begin result := RemoveQuoteNoCheck(param); exit; end; end; function RemoveExt(param: string): string; begin end; end.
uses crt,sysutils; const //Length of notations STANDARN_LENGTH = 1000; ROUND_NOT = 4000; WHITE_NOT = 2000; BLACK_NOT = 1000; CURVE_NOT = 500; D_CURVE_NOT = 250; T_CURVE_NOT = 125; //Frequency of notations //Option of frequency STANDARN_DOW = 512; UP = 41; DOW = 512; LO = -41; REW = 587; SPACE= 75; MIW = 662; UPO = 525; FAW = 737; SOW = 812; LAW = 887; SIW = 962; function addDot(length: integer): double; begin exit(length + length/2); end; procedure print(str: string; fore, back: integer); begin Textcolor(fore); TextBackGround(back); write(str); end; procedure trackColor; begin TextColor(white); Textbackground(black); end; procedure Bspace(n: integer); var i: integer; begin TrackColor; for i:= 1 to n do write(' '); end; procedure down; begin TrackColor; writeln; end; function ran: string; begin randomize; exit(inttostr(random(9))); end; procedure play(f,l: integer); begin randomize; print(' SYSSPK ',white, lightgreen); bspace(1); write('NOT='); print(inttostr(f),lightred,0); bspace(3); write('LEG='); print(inttostr(l),cyan,0); Bspace(3); print('datatrack: ',lightgreen,0); trackColor; write(ran + ran + ' ' + ran + ran + ' ' + ran + ran + ' '); delay(1); print(ran + ran, red, 0); down; Sound(f); Delay(l); end; procedure comment(str: string); begin print('// '+str, darkgray, 0); down; end; procedure test; begin randomize; print(' MODULE ', lightred, blue); bspace(1); print(' TEST ', white, lightblue); print(' IO ',yellow, brown);trackcolor; writeln(' NULL NULL NULL 03xh'); play(STANDARN_DOW, WHITE_NOT); comment('Standarn length and frequency notation'); play(DOW, 240); play(REW, 240); play(MIW, 240); play(FAW, 240); play(SOW, 240); play(LAW, 240); play(SIW, 240); print(' MODULE ', lightred, blue); bspace(1); writeln(' NULL '); end; begin test; nosound; randomize; comment('Play random'); repeat play(random(500)+500, random(300)+150); until keypressed; nosound; print(' MODULE ', lightred, blue); bspace(1); writeln(' NULL '); readln; end.
{******************************************************************************* Title: T2Ti ERP Description: VO transiente que representa o registro 60D do Sintegra. The MIT License Copyright: Copyright (C) 2010 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 1.0 *******************************************************************************} unit Sintegra60DVO; interface type TSintegra60DVO = class private FGTIN: String; FDescricao: String; FSiglaUnidade: String; FQuantidade: Double; FValorLiquido: Double; FBaseICMS: Double; FSituacaoTributaria: String; FValorICMS: Double; FAliquotaICMS: Double; published property GTIN: String read FGTIN write FGTIN; property Descricao: String read FDescricao write FDescricao; property SiglaUnidade: String read FSiglaUnidade write FSiglaUnidade; property Quantidade: Double read FQuantidade write FQuantidade; property ValorLiquido: Double read FValorLiquido write FValorLiquido; property BaseICMS: Double read FBaseICMS write FBaseICMS; property SituacaoTributaria: String read FSituacaoTributaria write FSituacaoTributaria; property ValorICMS: Double read FValorICMS write FValorICMS; property AliquotaICMS: Double read FAliquotaICMS write FAliquotaICMS; end; implementation end.
unit IWHTMLControls; {PUBDIST} interface uses Classes, IWHTMLTag, IWScriptEvents, IWControl; type TIWHRule = class(TIWControl) //TODO: add a percentage prop public constructor Create(AOwner: TComponent); override; function RenderHTML: TIWHTMLTag; override; published end; TIWList = class(TIWControl) protected FNumbered: Boolean; FItems: TStrings; // procedure SetItems(AValue: TStrings); procedure SetNumbered(const AValue: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; published property Font; property Items: TStrings read FItems write SetItems; property Numbered: boolean read FNumbered write SetNumbered; end; TIWLinkBase = class(TIWControl) public constructor Create(AOwner: TComponent); override; function RenderStyle: string; override; published property Color; property Caption; property Enabled; property ExtraTagParams; property Font; property ScriptEvents; end; TIWURLTarget = class(TPersistent) protected FHeight: integer; FLeft: integer; FResizable: boolean; FScrollbars: boolean; FToolbar: Boolean; FTop: integer; FWidth: integer; FWindowName: string; public constructor Create; virtual; published property Height: Integer read FHeight write FHeight; property Left: Integer read FLeft write FLeft; property Resizable: Boolean read FResizable write FResizable; property Scrollbars: boolean read FScrollbars write FScrollbars; property Toolbar: Boolean read FToolbar write FToolbar; property Top: Integer read FTop write FTop; property Width: Integer read FWidth write FWidth; property WindowName: string read FWindowName write FWindowName; end; TIWLink = class(TIWLinkBase) protected procedure Submit(const AValue: string); override; public constructor Create(AOwner: TComponent); override; function RenderHTML: TIWHTMLTag; override; procedure HookEvents(AScriptEvents: TIWScriptEvents); override; published property DoSubmitValidation; // property OnClick; end; TIWCustomURL = class(TIWLinkBase) protected FTargetOptions: TIWURLTarget; FTerminateApp: boolean; FUseTarget: boolean; FURL: string; // procedure SetTerminateApp(const AValue: boolean); procedure SetUseTarget(const AValue: boolean); procedure HookEvents(AScriptEvents: TIWScriptEvents); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; published property TargetOptions: TIWURLTarget read FTargetOptions write FTargetOptions; property TerminateApp: boolean read FTerminateApp write FTerminateApp; property UseTarget: boolean read FUseTarget write FUseTarget; end; TIWURL = class(TIWCustomURL) published property URL: string read FURL write FURL; end; TWIAppletAlignment = (aaTop, aaMiddle, aaBottom, aaLeft, aaRight); TIWApplet = class(TIWControl) protected FAlignment: TWIAppletAlignment; FAltText: string; FAppletName: string; FArchive: string; FClassFile: string; FCodeBase: string; FHorizSpace: Integer; FParams: TStrings; FVertSpace: Integer; // procedure SetParams(const AValue: TStrings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; published property Alignment: TWIAppletAlignment read FAlignment write FAlignment; property AltText: string read FAltText write FAltText; property AppletName: string read FAppletName write FAppletName; property Archive: string read FArchive write FArchive; property ClassFile: string read FClassFile write FClassFile; //@@ Specifies the code base for the applet. If CodeBase is and empty string, the applet //is assumed to be in the files directory. property CodeBase: string read FCodeBase write FCodeBase; property HorizSpace: Integer read FHorizSpace write FHorizSpace; property Params: TStrings read FParams write SetParams; property VertSpace: Integer read FVertSpace write FVertSpace; end; implementation uses {$IFDEF Linux}QGraphics, {$ELSE}Graphics, {$ENDIF} IWCompLabel, SysUtils, SWSystem{, IWHTMLTag}; { TIWHRule } constructor TIWHRule.Create(AOwner: TComponent); begin inherited; Width := 100; Height := 3; end; function TIWHRule.RenderHTML: TIWHTMLTag; begin Result := TIWHTMLTag.CreateTag('HR'); try Result.AddIntegerParam('WIDTH', Width); except FreeAndNil(Result); raise; end; end; { TIWList } constructor TIWList.Create(AOwner: TComponent); begin inherited; FItems := TStringList.Create; Height := 24; Width := 116; end; destructor TIWList.Destroy; begin FreeAndNil(FItems); inherited; end; function TIWList.RenderHTML: TIWHTMLTag; var i: Integer; begin Result := nil; if Items.Count > 0 then begin Result := TIWHTMLTag.CreateTag('table'); try for i := 0 to Items.Count - 1 do begin with Result.Contents.AddTag('TR') do begin with Contents.AddTag('TD') do begin if Numbered then begin Contents.AddText(IntToStr(i + 1) + '.'); end else begin Contents.AddText(Chr(149)); end; end; with Contents.AddTag('TD') do begin Contents.AddText(Items[i]); end; end; end; if Result.Contents.Count = 0 then Result.Contents.AddText(''); except FreeAndNil(Result); raise; end; end; end; procedure TIWList.SetItems(AValue: TStrings); begin FItems.Assign(AValue); Invalidate; end; procedure TIWList.SetNumbered(const AValue: Boolean); begin FNumbered := AValue; Invalidate; end; { TIWLink } constructor TIWLink.Create(AOwner: TComponent); begin inherited; // Default to false for links. DoSubmitValidation := False; end; procedure TIWLink.HookEvents(AScriptEvents: TIWScriptEvents); begin inherited HookEvents(AScriptEvents); if Enabled then begin AScriptEvents.HookEvent('OnClick', SubmitHandler('')); end; end; function TIWLink.RenderHTML: TIWHTMLTag; var LLabel: TIWLabel; begin if Enabled then begin Result := TIWHTMLTag.CreateTag('A'); try Result.AddStringParam('HREF', '#'); Result.Contents.AddText(Caption); except FreeAndNil(Result); raise; end; end else begin LLabel := TIWLabel.Create(self); try LLabel.Name := HTMLName; LLabel.Caption := Caption; LLabel.Font.Assign(Font); LLabel.Width := Width; LLabel.Height := Height; LLabel.Visible := true; Result := LLabel.RenderHTML; finally FreeAndNil(LLabel); end; end; end; procedure TIWLink.Submit(const AValue: string); begin if Assigned(OnClick) then begin OnClick(Self); end; end; { TIWLinkBase } constructor TIWLinkBase.Create(AOwner: TComponent); begin inherited Create(AOwner); FSupportsSubmit := True; FSupportedScriptEvents := 'OnClick,OnDblClick,OnKeyDown,OnKeyPress,OnKeyUp,OnMouseDown,OnMouseOut' + ',OnMouseUp,OnMouseOver'; Width := 65; Height := 17; Color := clNone; end; function TIWLinkBase.RenderStyle: string; begin result := inherited RenderStyle + iif(Color <> clNone, 'color: ' + ColorToRGBString(Color) + ';'); end; { TIWURLTarget } constructor TIWURLTarget.Create; begin inherited; // These are the target window coords, not TIWRURLTarget's Left := -1; Top := -1; Width := -1; Height := -1; Resizable := True; ScrollBars := True; end; { TIWCustomURL } constructor TIWCustomURL.Create(AOwner: TComponent); begin inherited; FTargetOptions := TIWURLTarget.Create; end; destructor TIWCustomURL.Destroy; begin FreeAndNil(FTargetOptions); inherited; end; procedure TIWCustomURL.HookEvents(AScriptEvents: TIWScriptEvents); begin inherited HookEvents(AScriptEvents); if Enabled then begin // TODO: Move OnClick code here end; end; function TIWCustomURL.RenderHTML: TIWHTMLTag; var LURL: string; LResult: String; begin if not Enabled then begin Result := TIWHTMLTag.CreateTag('SPAN'); try Result.Contents.AddText(Caption); except FreeAndNil(Result); raise; end; end else begin Result := TIWHTMLTag.CreateTag('A'); try // other than http or https? IE5 doesnt like mailto: (and possibly others) in LoadURL if not (AnsiSameText(Copy(FURL, 1, 7), 'http://') or AnsiSameText(Copy(FURL, 1, 8), 'https://')) then begin Result.AddStringParam('HREF', FURL); end else begin Result.AddStringParam('HREF', '#'); if UseTarget then begin LResult := ''; with TargetOptions do begin // personalbar // menubar // location - If yes, creates a Location entry field. // status - statusbar if Resizable then begin LResult := LResult + ',resizable=yes'; end else begin LResult := LResult + ',resizable=no'; end; if Toolbar then begin LResult := LResult + ',toolbar=yes'; end else begin LResult := LResult + ',toolbar=no'; end; if Scrollbars then begin LResult := LResult + ',scrollbars=yes'; end else begin LResult := LResult + ',scrollbars=no'; end; if Left > -1 then begin LResult := LResult + ',left=' + IntToStr(Left); end; if Top > -1 then begin LResult := LResult + ',top=' + IntToStr(Top); end; if Width > -1 then begin LResult := LResult + ',width=' + IntToStr(Width); end; if Height > -1 then begin LResult := LResult + ',height=' + IntToStr(Height); end; end; Result.AddStringParam('OnClick', 'NewWindow(''' + FURL + ''', ''' + TargetOptions.WindowName + ''',''' + Copy(LResult, 2, MaxInt) + ''')'); end else begin LURL := FURL; if TerminateApp then begin if SameText(Copy(LURL, 1, 7), 'http://') then begin Delete(LURL, 1, 7); end; LURL := '/STOP/' + WebApplication.AppID + '/' + LURL; end; Result.AddStringParam('OnClick', 'parent.LoadURL(''' + LURL + ''')'); end; end; HintEvents(Result, iif(Hint, Hint, FURL)); Result.Contents.AddText(Caption); except FreeAndNil(Result); raise; end; end; end; procedure TIWCustomURL.SetTerminateApp(const AValue: boolean); begin FTerminateApp := AValue; if AValue then begin FUseTarget := False; end; end; procedure TIWCustomURL.SetUseTarget(const AValue: boolean); begin FUseTarget := AValue; if AValue then begin FTerminateApp := False; end; end; { TIWApplet } constructor TIWApplet.Create(AOwner: TComponent); begin inherited; FParams := TStringList.Create; Height := 200; Width := 200; end; destructor TIWApplet.Destroy; begin FreeAndNil(FParams); inherited; end; function TIWApplet.RenderHTML: TIWHTMLTag; var i: Integer; LAlign: string; begin case Alignment of aaTop: LAlign := 'top'; aaMiddle: LAlign := 'middle'; aaBottom: LAlign := 'bottom'; aaLeft: LAlign := 'left'; aaRight: LAlign := 'right'; end; Result := TIWHTMLTag.CreateTag('APPLET'); try Result.AddStringParam('CODE', ClassFile); Result.AddIntegerParam('HEIGHT', Height); Result.AddIntegerParam('WIDTH', Width); Result.AddStringParam('ALIGN', LAlign); Result.AddStringParam('CODEBASE', iif(CodeBase, CodeBase, WebApplication.URLBase + '/Files/')); Result.Add(iif(AppletName, ' NAME=' + AppletName)); Result.Add(iif(Height > 0, ' HSPACE=' + IntToStr(HorizSpace))); Result.Add(iif(Height > 0, ' VSPACE=' + IntToStr(VertSpace))); Result.Add(iif(AltText, ' ALT=' + AltText + '')); Result.Add(iif(Archive, ' ARCHIVE=' + Archive + '')); for i := 0 to Params.Count - 1 do begin with Result.Contents.AddTag('PARAM') do begin AddStringParam('NAME', Self.Params.Names[i]); AddStringParam('VALUE', Self.Params.Values[Self.Params.Names[i]]); end; end; except FreeAndNil(Result); raise; end; end; procedure TIWApplet.SetParams(const AValue: TStrings); begin FParams.Assign(AValue); end; end.
//////////////////////////////////////////// // Заготовка под график //////////////////////////////////////////// unit DiagramImage; interface uses SysUtils, Classes, Controls, ExtCtrls, Graphics, GMGlobals, Windows, Math; type TOnMarkerMoved = procedure (Sender: TObject; MarkerPos: Int; MarkerDT: LongWord) of object; TDiagramImage = class(TImage) private { Private declarations } FOnMarkerMoved: TOnMarkerMoved; function GeMarkerDT: LongWord; function GetRightOffset: int; published { Published declarations } property OnMarkerMoved: TOnMarkerMoved read FOnMarkerMoved write FOnMarkerMoved; protected { Protected declarations } MarkerPos: int; FDStart, FDEnd: LongWord; procedure Click; override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DrawMarker(); public { Public declarations } DiagramColor: TColor; iDiagramTicks: int; iDiagramVrtTicks: int; bMarker: bool; property RightOffset: int read GetRightOffset; property DStart: LongWord read FDStart; property DEnd: LongWord read FDEnd; procedure PrepareDiagramBackground(AgmDStart: LongWord = 0; AgmDEnd: LongWord = 0); procedure PrintLastRefreshTime(bNodata: bool; LastDT: TDateTime); procedure StretchBitmap(); procedure FinalizeDraw(); constructor Create(AOwner: TComponent); override; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TDiagramImage]); end; procedure TDiagramImage.StretchBitmap; var h, w: int; begin w := Width; Picture.Bitmap.Width := w; h := Height; Picture.Bitmap.Height := h; end; procedure TDiagramImage.PrepareDiagramBackground(AgmDStart: LongWord = 0; AgmDEnd: LongWord = 0); var cnv: TCanvas; xTick: Int64; x0, y0, h, w: int; begin if (AgmDStart = 0) or (AgmDEnd = 0) then begin FDEnd := NowGM(); FDStart := FDEnd - iDiagramHrs*3600; end else begin FDEnd := AgmDEnd; FDStart := AgmDStart; end; StretchBitmap(); cnv := Picture.Bitmap.Canvas; w := Width; h := Height; // фон cnv.Brush.Color := DiagramColor; cnv.FillRect(Rect(0, 0, w, h)); // риски по времени // iDiagramTicks - промежуток в минутах if (iDiagramTicks > 0) and (FDEnd > FDStart) then begin cnv.Pen.Color := clBlack; cnv.Pen.Width := 1; xTick := (int64(FDStart) div iDiagramTicks) * iDiagramTicks; while xTick <= FDEnd do begin x0 := Round((xTick - FDStart) / (FDEnd - FDStart) * w); cnv.MoveTo(x0, h); cnv.LineTo(x0, h - 4); xTick := xTick + iDiagramTicks * 60; end; end; // риски по горизонтали // iDiagramVrtTicks - промежуток в процентах if iDiagramVrtTicks > 0 then begin cnv.Pen.Color := RGB(180, 180, 180); cnv.Pen.Width := 1; cnv.Pen.Style := psSolid; xTick := iDiagramVrtTicks; while xTick < 100 do begin y0 := Round(xTick / 100 * h); cnv.MoveTo(1, y0); cnv.LineTo(w - 1, y0); xTick := xTick + iDiagramVrtTicks; end; end; // рамка cnv.Brush.Color:=clBlack; cnv.FrameRect(Rect(0, 0, w, h)); end; procedure TDiagramImage.PrintLastRefreshTime(bNodata: bool; LastDT: TDateTime); begin // последнее время опроса Picture.Bitmap.Canvas.Font.Color := clBlack; Picture.Bitmap.Canvas.Brush.Color := IfThen(bNoData, clRed, DiagramColor); Picture.Bitmap.Canvas.TextOut(4, 2, FormatDateTime('dd.mm hh:nn', LastDT)); end; procedure TDiagramImage.Click; begin inherited; end; procedure TDiagramImage.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; end; function TDiagramImage.GeMarkerDT(): LongWord; var w: int; begin w := Width - RightOffset; if FDStart < FDEnd then Result := FDStart + Round((MarkerPos / w) * (FDEnd - FDStart)) else Result := FDStart; end; procedure TDiagramImage.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if bMarker then begin MarkerPos := X; DrawMarker(); if Assigned(FOnMarkerMoved) then FOnMarkerMoved(self, MarkerPos, GeMarkerDT()); end; inherited; end; constructor TDiagramImage.Create(AOwner: TComponent); begin inherited Create(AOwner); bMarker := false; MarkerPos := 0; end; procedure TDiagramImage.DrawMarker; begin if bMarker and (MarkerPos >= 0) and (MarkerPos < Width) then begin Picture.Bitmap.Canvas.Pen.Color := clGreen; Picture.Bitmap.Canvas.Pen.Width := 1; Picture.Bitmap.Canvas.MoveTo(MarkerPos, 0); Picture.Bitmap.Canvas.LineTo(MarkerPos, Height); end; end; procedure TDiagramImage.FinalizeDraw; begin DrawMarker(); end; function TDiagramImage.GetRightOffset: int; begin Result := Round(Min(Width / 50.0, 10)); end; end.
unit WebModuleUnit1; (* Projet : POC Notes de frais URL du projet : https://www.developpeur-pascal.fr/p/_6006-poc-notes-de-frais-une-application-multiplateforme-de-saisie-de-notes-de-frais-en-itinerance.html Auteur : Patrick Prémartin https://patrick.premartin.fr Editeur : Olf Software https://www.olfsoftware.fr Site web : https://www.developpeur-pascal.fr/ Ce fichier et ceux qui l'accompagnent sont fournis en l'état, sans garantie, à titre d'exemple d'utilisation de fonctionnalités de Delphi dans sa version Tokyo 10.2 Vous pouvez vous en inspirer dans vos projets mais n'êtes pas autorisé à rediffuser tout ou partie des fichiers de ce projet sans accord écrit préalable. *) interface uses System.SysUtils, System.Classes, Web.HTTPApp, 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.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.ConsoleUI.Wait, Data.DB, FireDAC.Comp.Client, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Stan.StorageJSON; type TWebModule1 = class(TWebModule) FDConnection1: TFDConnection; qryNotesDeFrais: TFDQuery; FDStanStorageJSONLink1: TFDStanStorageJSONLink; qryUtilisateurs: TFDQuery; procedure WebModule1DefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModuleCreate(Sender: TObject); procedure FDConnection1AfterConnect(Sender: TObject); procedure FDConnection1BeforeConnect(Sender: TObject); procedure WebModule1ActionLoginAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1ActionSynchroPhotoAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1ActionBaseVersMobileAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1UsersListAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1UsersDeleteAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1UserAddAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1UserChgAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1consultationNDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1ModerationNDFSuivanteAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); procedure WebModule1ModerationNDFDecisionAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); private { Déclarations privées } FBaseACreer: Boolean; public { Déclarations publiques } end; var WebModuleClass: TComponentClass = TWebModule1; implementation {%CLASSGROUP 'System.Classes.TPersistent'} uses uNotesDeFrais, System.IOUtils, System.JSON, System.SyncObjs, Web.ReqMulti, System.NetEncoding; {$R *.dfm} // var // SectionProtegee: TCriticalSection; procedure TWebModule1.FDConnection1AfterConnect(Sender: TObject); begin if FBaseACreer then NotesDeFrais_CreerBase(FDConnection1); end; procedure TWebModule1.FDConnection1BeforeConnect(Sender: TObject); var database: string; begin database := tpath.Combine(NotesDeFrais_BaseName, 'notesdefrais-serveur.db'); FBaseACreer := not tfile.exists(database); FDConnection1.Params.database := database; end; procedure TWebModule1.WebModule1ActionBaseVersMobileAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; erreur: integer; jso: tjsonobject; base: TStringStream; begin // writeln(Request.query); jso := tjsonobject.Create; try erreur := 0; try code := Request.QueryFields.Values['code'].trim.tointeger; except code := 0; end; if code > 0 then begin // SectionProtegee.Acquire; try if qryNotesDeFrais.active then qryNotesDeFrais.Close; qryNotesDeFrais.Open('select * from notesdefrais where utilisateur_code=:utilisateur', [code]); base := TStringStream.Create; try qryNotesDeFrais.SaveToStream(base, tfdstorageformat.sfJSON); jso.AddPair('base', base.datastring); finally freeandnil(base); end; finally // SectionProtegee.Release; end; if (code > 0) then jso.AddPair('code', code.ToString) else erreur := 4; end else erreur := 1; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModule1ActionLoginAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var user, pass: string; code: integer; erreur: integer; jso: tjsonobject; begin // writeln(Request.query); jso := tjsonobject.Create; try erreur := 0; user := Request.QueryFields.Values['user'].trim.ToLower; if (user.Length < 1) then erreur := 1; pass := Request.QueryFields.Values['pass'].trim.ToLower; if (pass.Length < 1) then if erreur = 0 then erreur := 2 else erreur := 3; if erreur = 0 then begin // SectionProtegee.Acquire; try try code := FDConnection1.ExecSQLScalar('select code from utilisateurs where email=:user and motdepasse=:pass', [user, pass]); except code := 0; end; finally // SectionProtegee.Release; end; if (code > 0) then jso.AddPair('code', code.ToString) else erreur := 4; end; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModule1ActionSynchroPhotoAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; erreur: integer; jso: tjsonobject; nom_fichier: string; i: integer; multireq: tmultipartcontentparser; begin if (tmultipartcontentparser.CanParse(Request)) then try multireq := tmultipartcontentparser.Create(Request); finally freeandnil(multireq); end; // writeln(Request.Content); jso := tjsonobject.Create; try erreur := 0; try code := Request.ContentFields.Values['code'].trim.tointeger; except code := 0; end; if (code > 0) then begin for i := 0 to Request.Files.Count - 1 do try nom_fichier := Request.Files[i].FileName; TMemoryStream(Request.Files[i].Stream).SaveToFile(tpath.Combine(NotesDeFrais_PhotosPath, nom_fichier)); // SectionProtegee.Acquire; try if (not qryNotesDeFrais.active) then qryNotesDeFrais.Open('select * from notesdefrais'); qryNotesDeFrais.Insert; try qryNotesDeFrais.fieldbyname('utilisateur_code').AsInteger := code; qryNotesDeFrais.fieldbyname('mobile_code').AsString := nom_fichier; qryNotesDeFrais.post; except qryNotesDeFrais.cancel; erreur := 3; end; finally // SectionProtegee.Release; end; except erreur := 2; end; end else // utilisateur inconnu erreur := 1; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModule1consultationNDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var erreur: integer; jso: tjsonobject; base: TStringStream; begin jso := tjsonobject.Create; try erreur := 0; // SectionProtegee.Acquire; try if qryNotesDeFrais.active then qryNotesDeFrais.Close; qryNotesDeFrais.Open ('select nom, prenom, email, datendf, lieu, montant, acceptee, dateaccord from notesdefrais,utilisateurs where notesdefrais.utilisateur_code=utilisateurs.code and avalider=''N'' order by datendf, nom'); base := TStringStream.Create; try qryNotesDeFrais.SaveToStream(base, tfdstorageformat.sfJSON); jso.AddPair('base', base.datastring); finally freeandnil(base); end; finally // SectionProtegee.Release; end; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModule1DefaultHandlerAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); begin Response.Content := '<html>' + '<head><title>POC Notes de Frais</title></head>' + '<body>POC Notes de Frais</body>' + '</html>'; end; procedure TWebModule1.WebModule1ModerationNDFDecisionAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; lieu, datendf, dateaccord, montant, decision: string; begin // writeln(Request.Content); code := Request.ContentFields.Values['code'].trim.tointeger; lieu := Request.ContentFields.Values['lieu'].trim; datendf := Request.ContentFields.Values['date'].trim; montant := Request.ContentFields.Values['montant'].trim.ToLower; decision := Request.ContentFields.Values['decision'].trim.ToLower; dateaccord := datetostr(now); // SectionProtegee.Acquire; if decision = 'ok' then FDConnection1.ExecSQL ('update notesdefrais set datendf=:datendf,lieu=:lieu,montant=:montant,avalider=''N'',acceptee=''O'',dateaccord=:date where code=:code', [date, lieu, montant, dateaccord, code]) else if decision = 'ko' then FDConnection1.ExecSQL ('update notesdefrais set datendf=:datendf,lieu=:lieu,montant=:montant,avalider=''N'',acceptee=''N'',dateaccord=:date where code=:code', [date, lieu, montant, dateaccord, code]); // SectionProtegee.Release; end; procedure TWebModule1.WebModule1ModerationNDFSuivanteAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var erreur: integer; jso: tjsonobject; begin jso := tjsonobject.Create; try erreur := 0; // SectionProtegee.Acquire; try if qryUtilisateurs.active then qryUtilisateurs.Close; qryUtilisateurs.Open ('select notesdefrais.code, nom, prenom, email, mobile_code from notesdefrais,utilisateurs where notesdefrais.utilisateur_code=utilisateurs.code and avalider=''O'' order by notesdefrais.code limit 0,1'); if qryUtilisateurs.Eof then erreur := 1 else begin jso.AddPair('code', qryUtilisateurs.fieldbyname('code').AsString); jso.AddPair('nom', qryUtilisateurs.fieldbyname('nom').AsString); jso.AddPair('prenom', qryUtilisateurs.fieldbyname('prenom').AsString); jso.AddPair('email', qryUtilisateurs.fieldbyname('email').AsString); jso.AddPair('image', tnetencoding.Base64.EncodeBytesToString(tfile.ReadAllBytes(tpath.Combine(NotesDeFrais_PhotosPath, qryUtilisateurs.fieldbyname('mobile_code').AsString)))); end; finally // SectionProtegee.Release; end; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModule1UserAddAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; nom, prenom, email, motdepasse: string; begin // writeln(Request.Content); nom := Request.ContentFields.Values['nom'].trim; prenom := Request.ContentFields.Values['prenom'].trim; email := Request.ContentFields.Values['email'].trim.ToLower; motdepasse := Request.ContentFields.Values['motdepasse'].trim.ToLower; // SectionProtegee.Acquire; FDConnection1.ExecSQL('insert into utilisateurs (nom,prenom,email,motdepasse) values (:nom,:prenom,:email,:motdepasse)', [nom, prenom, email, motdepasse]); code := FDConnection1.ExecSQLScalar('select last_insert_rowid()'); Response.Content := code.ToString; // SectionProtegee.Release; end; procedure TWebModule1.WebModule1UserChgAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; nom, prenom, email, motdepasse: string; begin // writeln(Request.Content); code := Request.ContentFields.Values['code'].trim.tointeger; nom := Request.ContentFields.Values['nom'].trim; prenom := Request.ContentFields.Values['prenom'].trim; email := Request.ContentFields.Values['email'].trim.ToLower; motdepasse := Request.ContentFields.Values['motdepasse'].trim.ToLower; // SectionProtegee.Acquire; FDConnection1.ExecSQL('update utilisateurs set nom=:nom,prenom=:prenom,email=:email,motdepasse=:motdepasse where code=:code', [nom, prenom, email, motdepasse, code]); // SectionProtegee.Release; end; procedure TWebModule1.WebModule1UsersDeleteAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var code: integer; begin // writeln(Request.query); try code := Request.QueryFields.Values['code'].tointeger; except code := 0; end; if (code > 0) then begin // SectionProtegee.Acquire; FDConnection1.ExecSQL('delete from utilisateurs where code=' + code.ToString); // SectionProtegee.Release; end; end; procedure TWebModule1.WebModule1UsersListAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var erreur: integer; jso: tjsonobject; base: TStringStream; begin jso := tjsonobject.Create; try erreur := 0; // SectionProtegee.Acquire; try if qryUtilisateurs.active then qryUtilisateurs.Close; qryUtilisateurs.Open('select code, nom, prenom, email, motdepasse from utilisateurs'); base := TStringStream.Create; try qryUtilisateurs.SaveToStream(base, tfdstorageformat.sfJSON); jso.AddPair('base', base.datastring); finally freeandnil(base); end; finally // SectionProtegee.Release; end; jso.AddPair('erreur', TJSONNumber.Create(erreur)); Response.Content := jso.ToJSON; finally freeandnil(jso); end; end; procedure TWebModule1.WebModuleCreate(Sender: TObject); begin FDConnection1.Connected := true; end; initialization // SectionProtegee := TCriticalSection.Create; finalization // freeandnil(SectionProtegee); end.
{ Module of routines for dealing with RENDlib keys. } module gui_key; define gui_key_alpha_id; define gui_key_name_id; define gui_key_names_id; define gui_event_char; %include 'gui2.ins.pas'; { ************************************************************************* * * Function GUI_KEY_ALPHA_ID (C) * * Returns the RENDlib key ID for the alphnumeric key representing the * character C. The character case of C is irrelevant. A returned value * of REND_KEY_NONE_K indicates the key was not found. } function gui_key_alpha_id ( {find RENDlib alphanumeric key ID} in c: char) {character to find key for, case-insensitive} :rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found} val_param; var lc: char; {lower case character looking for} keys_p: rend_key_ar_p_t; {pointer to array of key descriptors} nk: sys_int_machine_t; {number of keys in array} k: sys_int_machine_t; {key number} begin lc := string_downcase_char (c); {make lower case version of key char} rend_get.keys^ (keys_p, nk); {get key descriptors array info} for k := 1 to nk do begin {once for each key in the array} if {found the right key ?} (keys_p^[k].val_p <> nil) and then {key has a string value ?} (keys_p^[k].val_p^.len = 1) and {key value is exactly one character ?} (keys_p^[k].val_p^.str[1] = lc) {key character matches our character ?} then begin gui_key_alpha_id := k; {return RENDlib ID of the matching key} return; end; end; {back to check out next key in list} gui_key_alpha_id := rend_key_none_k; {indicate the key was not found} end; { ************************************************************************* * * Function GUI_KEY_NAME_ID (NAME) * * Return the RENDlib key ID of the key with NAME on the key cap. * NAME is case-insensitive. REND_KEY_NONE_K is returned if not * matching key could be found. } function gui_key_name_id ( {find RENDlib key ID from key cap name} in name: univ string_var_arg_t) {key name to find, case-insensitive} :rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found} val_param; var keys_p: rend_key_ar_p_t; {pointer to array of key descriptors} nk: sys_int_machine_t; {number of keys in array} k: sys_int_machine_t; {key number} uname: string_var80_t; {upper case search name} kn: string_var80_t; {key cap name} begin uname.max := size_char(uname.str); {init local var strings} kn.max := size_char(kn.str); string_copy (name, uname); {make local copy of key name to look for} string_upcase (uname); {make upper case for matching} rend_get.keys^ (keys_p, nk); {get key descriptors array info} for k := 1 to nk do begin {once for each key in the array} if keys_p^[k].name_p = nil then next; {no key cap name available for this key ?} string_copy (keys_p^[k].name_p^, kn); {make local copy of key name} string_upcase (kn); {make upper case for matching} if string_equal (name, kn) then begin {found the key ?} gui_key_name_id := k; {return RENDlib ID for the matching key} return; end; end; {back to examine next key descriptor} gui_key_name_id := rend_key_none_k; {indicate the key was not found} end; { ************************************************************************* * * Function GUI_KEY_NAMES_ID (NAME) * * Just like GUI_KEY_NAME_ID except that NAME is a plain string instead of * a var string. } function gui_key_names_id ( {like GUI_KEY_NAME_ID except plain string nam} in name: string) {key name to find, case-insensitive} :rend_key_id_t; {RENDlib key ID, REND_KEY_NONE_K on not found} val_param; var vname: string_var80_t; {var string version of NAME} begin vname.max := size_char(vname.str); {init local var string} string_vstring (vname, name, size_char(name)); {make var string copy of NAME} gui_key_names_id := gui_key_name_id(vname); {call vstring routine to do the work} end; { ************************************************************************* * * Function GUI_EVENT_CHAR (EVENT) * * Return the single character represented by the RENDlib key event. The * NULL character is returned if the key doesn't represent a character. } function gui_event_char ( {get char from character key event} in event: rend_event_t) {RENDlib event descriptor for key event} :char; {character, NULL for non-character event} val_param; type modk_k_t = ( {key modifiers we recognize} modk_none_k, modk_shift_k, modk_ctrl_k); var modk: modk_k_t; {our internal modifier choices} emod: rend_key_mod_t; {set of modifier keys from event} shiftlock: boolean; {TRUE if shift lock modifier active} c: char; {sratch character} label got_modk; begin gui_event_char := chr(0); {init to event was not a valid char key} if event.ev_type <> rend_ev_key_k then return; {not a key event ?} emod := event.key.modk; {make local copy of modifier keys} shiftlock := false; {init to shift lock not active} if rend_key_mod_shiftlock_k in emod then begin {SHIFT LOCK down ?} emod := emod - [rend_key_mod_shiftlock_k]; shiftlock := true; {remember shift lock was active} end; if rend_key_mod_shift_k in emod then begin {SHIFT key down ?} emod := emod - [rend_key_mod_shift_k, rend_key_mod_shiftlock_k]; if emod <> [] then return; {some other modifiers also down ?} modk := modk_shift_k; goto got_modk; end; if rend_key_mod_ctrl_k in emod then begin {CTRL down ?} emod := emod - [rend_key_mod_ctrl_k]; if emod <> [] then return; {some other modifiers also down ?} modk := modk_ctrl_k; goto got_modk; end; if emod <> [] then return; {other modifiers are active ?} modk := modk_none_k; got_modk: {MODK describes the modifier} case modk of {which modifier, if any, was active} modk_none_k: begin if event.key.key_p^.val_p^.len <> 1 then return; {not single character ?} c := event.key.key_p^.val_p^.str[1]; if shiftlock then begin c := string_upcase_char (c); end; end; modk_shift_k: begin if event.key.key_p^.val_mod[rend_key_mod_shift_k]^.len <> 1 {not 1 char ?} then return; c := event.key.key_p^.val_mod[rend_key_mod_shift_k]^.str[1]; if shiftlock then begin c := string_downcase_char (c); end; end; modk_ctrl_k: begin if event.key.key_p^.val_mod[rend_key_mod_ctrl_k]^.len <> 1 {not 1 char ?} then return; c := event.key.key_p^.val_mod[rend_key_mod_ctrl_k]^.str[1]; end; otherwise return; {internal error, should never happen} end; gui_event_char := c; {pass back final character from key event} end;
unit MediaProcessing.Global; interface uses Windows, Classes,SyncObjs, SysUtils,MediaProcessing.Definitions, Generics.Collections,Collections.Map; type IPropertiesReader = interface ['{CD76F24D-2988-4B35-8724-25E4B5213F10}'] function ReadString(const Name, Default: string): string; function ReadInteger(const Name: string; Default: Longint): Longint; function ReadDouble(const Name: string; Default: double): TDateTime; function ReadDateTime(const Name: string; Default: TDateTime): TDateTime; function ReadBool(const Name: string; Default: Boolean): Boolean; function ReadBytes(const Name: string): TBytes; end; IPropertiesWriter = interface ['{7649996B-D4F8-443B-99C0-B65BAC73632F}'] procedure WriteString(const Name, Value: String); procedure WriteInteger(const Name: string; Value: Longint); procedure WriteBool(const Name: string; Value: Boolean); procedure WriteDateTime(const Name: string; const Value: TDateTime); procedure WriteDouble(const Name: string; const Value: double); procedure WriteBytes(const Name: string;Value: TBytes); end; TMediaProcessor = class (TInterfacedObject,IMediaProcessor) private FLastError: string; FLastErrorDateTime: TDateTime; FLastErrorLock: TCriticalSection; FTraceIdentifer:string; protected procedure SaveCustomProperties(const aWriter: IPropertiesWriter); overload; virtual; procedure LoadCustomProperties(const aReader: IPropertiesReader); overload; virtual; procedure Prepare; virtual; class function MetaInfo:TMediaProcessorInfo; virtual; abstract; procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); virtual; abstract; //Набор проверок procedure CheckIfChannel0(const aFormat: TMediaStreamDataHeader); procedure SetLastError(const aError: string); procedure SetTraceIdentifier(const aIdentifier: string); procedure TraceLine(const aMessage: string); public constructor Create; virtual; destructor Destroy; override; procedure AfterConstruction; override; function Info:TMediaProcessorInfo; virtual; function HasCustomProperties: boolean; virtual; procedure ShowCustomProperiesDialog;virtual; procedure ProcessData(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); function LastError: string; procedure GetLastErrorInfo(out aMessage: string; out aDateTime: TDateTime); virtual; procedure SaveCustomProperties(aStream: TStream); overload; procedure LoadCustomProperties(aStream: TStream); overload; procedure SaveCustomProperties(var aBytes: TBytes); overload; procedure LoadCustomProperties(aBytes: TBytes); overload; end; TMediaProcessorClass = class of TMediaProcessor; TMediaProceccorFactoryItem = class MediaProcessorClass: TMediaProcessorClass; MediaImplementorClass: TMediaProcessorClass; end; TMediaProceccorFactory = class private FRegistry:TObjectList<TMediaProceccorFactoryItem>; function GetRegistryIndexByTypeID(const aTypeID: TGUID): integer; public procedure RegisterMediaProcessor(aClass: TMediaProcessorClass); procedure RegisterMediaProcessorImplementation(aClass: TMediaProcessorClass); function GetMediaProcessorInfoByTypeID(const aTypeID: TGUID): TMediaProcessorInfo; function GetMediaProcessorInfoByIndex(const aIndex: integer): TMediaProcessorInfo; function MediaProcessorCount: integer; function CreateMediaProcessor(const aTypeID: TGUID; aImplementation: boolean): TMediaProcessor; function CreateMediaProcessorsFromStream(aStream:TStream; aImplementation: boolean):TIMediaProcessorArray; function CreateMediaProcessorsImplFromStream(aStream:TStream):TIMediaProcessorImplArray; function CreateMediaProcessorsFromBytes(const aBytes: TBytes; aImplementation: boolean):TIMediaProcessorArray; function CreateMediaProcessorsImplFromBytes(const aBytes: TBytes):TIMediaProcessorImplArray; constructor Create; destructor Destroy; override; end; EMediaProcessorInvalidInputData = class (Exception); function MediaProceccorFactory: TMediaProceccorFactory; implementation uses Variants,RTLConsts, uTrace, //Подключаем все известные процессоры MediaProcessing.Convertor.HH.RGB, MediaProcessing.Convertor.H264.RGB, MediaProcessing.Convertor.HHH264.H264, MediaProcessing.Convertor.RGB.MJPEG, MediaProcessing.Convertor.RGB.H264, MediaProcessing.Convertor.RGB.VFW, MediaProcessing.Panorama.RGB, MediaProcessing.Stabilizer.RGB, MediaProcessing.Drawer.RGB, MediaProcessing.Transformer.RGB, MediaProcessing.Transformer.HH, MediaProcessing.Transformer.PCM, MediaProcessing.Convertor.HHAU.PCM, MediaProcessing.Processor.VA.Any; type TPropertiesMap = TTextKeyMap<Variant>; TPropertiesMapIt = TMapIterator<string,Variant>; TPropertiesReader = class (TInterfacedObject,IPropertiesReader) private FMap: TPropertiesMap; public constructor Create; destructor Destroy; override; function ReadString(const Name, Default: string): string; function ReadInteger(const Name: string; Default: Longint): Longint; function ReadDouble(const Name: string; Default: double): TDateTime; function ReadDateTime(const Name: string; Default: TDateTime): TDateTime; function ReadBool(const Name: string; Default: Boolean): Boolean; function ReadBytes(const Name: string): TBytes; end; TPropertiesWriter = class (TInterfacedObject,IPropertiesWriter) private FMap: TPropertiesMap; public constructor Create; destructor Destroy; override; procedure WriteString(const Name, Value: String); procedure WriteInteger(const Name: string; Value: Longint); procedure WriteBool(const Name: string; Value: Boolean); procedure WriteDateTime(const Name: string; const Value: TDateTime); procedure WriteDouble(const Name: string; const Value: double); procedure WriteBytes(const Name: string; value: TBytes); end; TReaderEx = class (TReader) private protected procedure ReadVariantInternal(aType: integer; var Value: Variant); public procedure Read(aStream: TStream; Count: Longint); overload; procedure ReadBoolean(var Value: Boolean); procedure ReadChar(var Value: Char); procedure ReadInteger(var Value: cardinal); overload; procedure ReadInteger(var Value: Longint); overload; procedure ReadInteger(var Value: Int64); overload; procedure ReadDouble(var Value: Double); procedure ReadDateTime(var Value: TDateTime); procedure ReadEnum(var Value); procedure ReadString(var Value: string); procedure ReadVariant(var Value: Variant); procedure ReadGUID(var Value: TGUID); constructor Create(Stream: TStream; BufSize: Integer); destructor Destroy; override; end; //Базовый класс писателя //AddRef/Release отключен TWriterEx = class (TWriter) protected procedure WriteVariantInternal(aType: integer; const aValue: Variant); public //from IDataWriter procedure Write(aStream: TStream; Count: Longint); overload; procedure WriteDateTime(const Value: TDateTime); procedure WriteEnum(const Value); procedure WriteVariant(const aValue: Variant); procedure WriteGUID(const aValue: TGUID); //Всегда сохраняет 4 байта вне зависимости от того, что реально хранит число procedure WriteDWORD(aValue: integer); constructor Create(Stream: TStream; BufSize: Integer); destructor Destroy; override; end; var gMediaProceccorFactory:TMediaProceccorFactory; const vaGUID = 127; //Расширение стандартных хранимых типов function MediaProceccorFactory: TMediaProceccorFactory; begin if gMediaProceccorFactory=nil then gMediaProceccorFactory:=TMediaProceccorFactory.Create; result:=gMediaProceccorFactory; end; { TReaderEx } procedure TReaderEx.ReadVariantInternal(aType: integer; var Value: Variant); var aDouble: double; begin ASSERT((aType and varArray)=0); if not (aType in [varEmpty, varNull]) then begin case aType of varSmallint, varInteger, varByte: Value:=ReadInteger; varSingle: Value:=ReadSingle; varDouble: begin ReadDouble(aDouble); Value:=aDouble; end; varCurrency: Value:=ReadCurrency; varDate : Value:=ReadDate; else Value:=inherited ReadString; end; end end; procedure TReaderEx.ReadVariant(var Value: Variant); var aType : integer; aLowBound: integer; aHighBound: integer; i : integer; aItem : variant; begin aType:=ReadInteger; if (aType and varArray)=0 then ReadVariantInternal(aType,Value) else begin aType:=(aType and not varArray); ReadInteger(aLowBound); ReadInteger(aHighBound); Value:=VarArrayCreate([aLowBound,aHighBound],aType); for i:=aLowBound to aHighBound do begin ReadVariantInternal(aType,aItem); Value[i]:=aItem; end; end; end; procedure TReaderEx.ReadGUID(var Value: TGUID); begin if ReadValue<>TValueType(vaGUID) then raise EReadError.Create(SInvalidPropertyValue); inherited Read(Value,sizeof(TGUID)); end; procedure TReaderEx.Read(aStream: TStream; Count: Integer); var a: array of byte; begin while Count>1024 do begin Read(aStream,1024); Dec(count,1024); end; if Count>0 then begin SetLength(a,Count); Read(a[0],Count); aStream.Write(a[0],Count) end; end; procedure TReaderEx.ReadBoolean(var Value: Boolean); begin Value := inherited ReadBoolean; end; procedure TReaderEx.ReadChar(var Value: Char); begin Value := inherited ReadChar; end; procedure TReaderEx.ReadInteger(var Value: Integer); begin Value := inherited ReadInteger; end; procedure TReaderEx.ReadInteger(var Value: Int64); begin Value := inherited ReadInt64; end; procedure TReaderEx.ReadInteger(var Value: cardinal); begin Value := inherited ReadInteger; end; procedure TReaderEx.ReadString(var Value: string); begin Value := inherited ReadString; end; procedure TReaderEx.ReadEnum(var Value); begin integer(Value):=inherited ReadInteger; end; constructor TReaderEx.Create(Stream: TStream; BufSize: Integer); begin inherited Create(Stream,BufSize); end; procedure TReaderEx.ReadDouble(var Value: Double); begin Value:=inherited ReadDouble; end; procedure TReaderEx.ReadDateTime(var Value: TDateTime); begin Value:=inherited ReadDate; end; destructor TReaderEx.Destroy; begin inherited; end; { TWriterEx } procedure TWriterEx.WriteEnum(const Value); begin WriteInteger(integer(Value)); end; procedure TWriterEx.WriteVariantInternal(aType: integer; const aValue: Variant); begin ASSERT(not VarIsArray(aValue)); if not (aType in [varEmpty, varNull]) then begin case aType of varSmallint, varInteger, varByte: WriteInteger(aValue); varSingle : WriteSingle(aValue); varDouble : WriteDouble(aValue); varCurrency: WriteCurrency(aValue); varDate : WriteDate(aValue); else WriteString(aValue); end; end; end; procedure TWriterEx.WriteVariant(const aValue: Variant); var aType : integer; i : integer; begin aType:=VarType(aValue); if not VarIsArray(aValue) then if aType in [varSingle,varDouble,varCurrency] then if aValue=0.0 then aType:=varInteger; WriteInteger(aType); if not VarIsArray(aValue) then begin WriteVariantInternal(aType,aValue) end else begin ASSERT(VarArrayDimCount(aValue)=1); WriteInteger(VarArrayLowBound(aValue,1)); WriteInteger(VarArrayHighBound(aValue,1)); aType:=aType and not varArray; for i:=VarArrayLowBound(aValue,1) to VarArrayHighBound(aValue,1) do WriteVariantInternal(aType,aValue[i]); end; end; procedure TWriterEx.WriteGUID(const aValue: TGUID); begin WriteValue(TValueType(vaGUID)); inherited Write(aValue,sizeof(TGUID)); end; procedure TWriterEx.WriteDWORD(aValue: integer); begin WriteValue(vaInt32); Write(aValue, SizeOf(Integer)); end; destructor TWriterEx.Destroy; begin inherited; end; constructor TWriterEx.Create(Stream: TStream; BufSize: Integer); begin inherited Create(Stream,BufSize); end; procedure TWriterEx.Write(aStream: TStream; Count: Integer); var a: array of byte; begin while Count>1024 do begin Write(aStream,1024); Dec(Count,1024); end; if Count>0 then begin SetLength(a,Count); aStream.Read(a[0],Count); Write(a[0],Count); end; end; procedure TWriterEx.WriteDateTime(const Value: TDateTime); begin WriteDouble(Value); end; { TPropertiesReader } constructor TPropertiesReader.Create; begin FMap:=TPropertiesMap.Create; end; destructor TPropertiesReader.Destroy; begin FreeAndNil(FMap); inherited; end; function TPropertiesReader.ReadBool(const Name: string;Default: Boolean): Boolean; var x: variant; begin result:=default; try if FMap.Lookup(Name,x) then result:=x; except end; end; function TPropertiesReader.ReadBytes(const Name: string): TBytes; var x: variant; begin result:=nil; try if FMap.Lookup(Name,x) then begin if VarArrayHighBound(x,1)>=0 then result:=x; end; except end; end; function TPropertiesReader.ReadDateTime(const Name: string;Default: TDateTime): TDateTime; var x: variant; begin result:=default; try if FMap.Lookup(Name,x) then result:=x; except end; end; function TPropertiesReader.ReadDouble(const Name: string;Default: double): TDateTime; var x: variant; begin result:=default; try if FMap.Lookup(Name,x) then result:=x; except end; end; function TPropertiesReader.ReadInteger(const Name: string;Default: Integer): Longint; var x: variant; begin result:=default; try if FMap.Lookup(Name,x) then result:=x; except end; end; function TPropertiesReader.ReadString(const Name, Default: string): string; var x: variant; begin result:=default; try if FMap.Lookup(Name,x) then result:=x; except end; end; { TPropertiesWriter } constructor TPropertiesWriter.Create; begin FMap:=TPropertiesMap.Create; end; destructor TPropertiesWriter.Destroy; begin FreeAndNil(FMap); inherited; end; procedure TPropertiesWriter.WriteBool(const Name: string; Value: Boolean); begin FMap.Add(Name,Value); end; procedure TPropertiesWriter.WriteBytes(const Name: string; value: TBytes); begin FMap.Add(Name,Value); end; procedure TPropertiesWriter.WriteDateTime(const Name: string; const Value: TDateTime); begin FMap.Add(Name,Value); end; procedure TPropertiesWriter.WriteDouble(const Name: string;const Value: double); begin FMap.Add(Name,Value); end; procedure TPropertiesWriter.WriteInteger(const Name: string; Value: Integer); begin FMap.Add(Name,Value); end; procedure TPropertiesWriter.WriteString(const Name, Value: String); begin FMap.Add(Name,Value); end; { TMediaProcessor } procedure TMediaProcessor.AfterConstruction; var aDataReader : TPropertiesReader; begin inherited; aDataReader:=TPropertiesReader.Create; try LoadCustomProperties(aDataReader); finally aDataReader.Free; end; end; constructor TMediaProcessor.Create; begin FLastErrorLock:=TCriticalSection.Create; end; destructor TMediaProcessor.Destroy; begin inherited; FreeAndNil(FLastErrorLock); end; procedure TMediaProcessor.GetLastErrorInfo(out aMessage: string; out aDateTime: TDateTime); begin FLastErrorLock.Enter; try aMessage:=FLastError; aDateTime:=FLastErrorDateTime; finally FLastErrorLock.Leave; end; end; function TMediaProcessor.HasCustomProperties: boolean; begin result:=false; end; function TMediaProcessor.Info: TMediaProcessorInfo; begin result:=MetaInfo; end; function TMediaProcessor.LastError: string; begin result:=FLastError; end; procedure TMediaProcessor.LoadCustomProperties(aStream: TStream); var aPropReader : TPropertiesReader; var aCount: integer; i: Integer; aKey: string; aValue: Variant; aReader : TReaderEx; begin aPropReader:=TPropertiesReader.Create; try aReader:=TReaderEx.Create(aStream,1024); try aReader.ReadInteger(aCount); for i := 0 to aCount-1 do begin aReader.ReadString(aKey); aReader.ReadVariant(aValue); aPropReader.FMap.Add(aKey,aValue); end; finally aReader.Free; end; LoadCustomProperties(aPropReader); finally aPropReader.Free; end; end; procedure TMediaProcessor.Prepare; begin end; procedure TMediaProcessor.ProcessData(aInData: pointer; aInDataSize: cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal; out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); var aMsg: string; begin if not Info.CanAcceptInputStreamType(aInFormat.biStreamType) then begin aMsg:=Format('Несовместимые типы потока: ожидался тип: %s, получен тип: %s',[StreamTypesToFourccString(Info.InputStreamTypes),GetStreamTypeName(aInFormat.biStreamType)]); SetLastError(aMsg); TraceLine(aMsg); aOutData:=nil; aOutDataSize:=0; aOutFormat.Clear; aOutInfo:=nil; aOutInfoSize:=0; exit; end; try Process(aInData,aInDataSize,aInFormat,aInfo,aInfoSize,aOutData,aOutDataSize,aOutFormat,aOutInfo,aOutInfoSize); except on E:Exception do begin SetLastError(E.Message); TraceLine('Возникло исключение: '+E.Message); aOutData:=nil; aOutDataSize:=0; aOutFormat.Clear; aOutInfo:=nil; aOutInfoSize:=0; end; end; end; procedure TMediaProcessor.SaveCustomProperties(aStream: TStream); var aDataWriter : TPropertiesWriter; aPersister : TWriterEx; it: TPropertiesMapIt; begin aDataWriter:=TPropertiesWriter.Create; try SaveCustomProperties(aDataWriter); aPersister:=TWriterEx.Create(aStream,1024); aPersister.WriteInteger(aDataWriter.FMap.Count); aDataWriter.FMap.GetFirst(it); while it.Valid do begin aPersister.WriteString(it.Key); aPersister.WriteVariant(it.Value); aDataWriter.FMap.GetNext(it); end; aPersister.Free; finally aDataWriter.Free; end; end; procedure TMediaProcessor.SetLastError(const aError: string); begin Assert(FLastErrorLock<>nil); FLastErrorLock.Enter; try FLastError:=aError; FLastErrorDateTime:=Now; finally FLastErrorLock.Leave; end; end; procedure TMediaProcessor.SetTraceIdentifier(const aIdentifier: string); begin Assert(aIdentifier<>''); FTraceIdentifer:=aIdentifier; RegisterCustomTrace(ClassName,'','.proc.'+aIdentifier); end; procedure TMediaProcessor.TraceLine(const aMessage: string); begin if FTraceIdentifer<>'' then uTrace.TraceLine(ClassName,aMessage); end; procedure TMediaProcessor.LoadCustomProperties(const aReader: IPropertiesReader); begin end; procedure TMediaProcessor.SaveCustomProperties(const aWriter: IPropertiesWriter); begin end; procedure TMediaProcessor.ShowCustomProperiesDialog; begin end; procedure TMediaProcessor.CheckIfChannel0(const aFormat: TMediaStreamDataHeader); begin if aFormat.Channel<>0 then raise EMediaProcessorInvalidInputData.CreateFmt('Поддерживается обработка только одного канала: №0. Запрос на обработку канала №%d отклонен',[aFormat.Channel]); end; procedure TMediaProcessor.LoadCustomProperties(aBytes: TBytes); var aByteStream: TBytesStream; begin aByteStream:=TBytesStream.Create(aBytes); try LoadCustomProperties(aByteStream); finally aByteStream.Free; end; end; procedure TMediaProcessor.SaveCustomProperties(var aBytes: TBytes); var aByteStream: TBytesStream; begin aByteStream:=TBytesStream.Create(); try SaveCustomProperties(aByteStream); aBytes:=Copy(aByteStream.Bytes,0,aByteStream.Position); finally aByteStream.Free; end; end; { TMediaProceccorFactory } constructor TMediaProceccorFactory.Create; begin FRegistry:=TObjectList<TMediaProceccorFactoryItem>.Create; end; function TMediaProceccorFactory.CreateMediaProcessor(const aTypeID: TGUID; aImplementation: boolean): TMediaProcessor; var aItem: TMediaProceccorFactoryItem; begin aItem:=FRegistry[GetRegistryIndexByTypeID(aTypeID)]; if (not aImplementation) then result:=aItem.MediaProcessorClass.Create else begin if aItem.MediaImplementorClass=nil then raise Exception.Create('Реализация медиа-процессора не зарегистрирована'); result:=aItem.MediaImplementorClass.Create; end; end; function TMediaProceccorFactory.CreateMediaProcessorsFromBytes(const aBytes: TBytes; aImplementation: boolean): TIMediaProcessorArray; var aByteStream: TBytesStream; begin result:=nil; if Length(aBytes)>0 then begin aByteStream:=TBytesStream.Create(aBytes); try result:=CreateMediaProcessorsFromStream(aByteStream,aImplementation); finally aByteStream.Free; end; end; end; function TMediaProceccorFactory.CreateMediaProcessorsFromStream(aStream: TStream; aImplementation: boolean): TIMediaProcessorArray; var aIID : TGUID; i: integer; aMP : IMediaProcessor; begin //Медиа процессоры aStream.ReadBuffer(i,sizeof(i)); Assert(i<1000); SetLength(result,i); for i := 0 to i-1 do begin aStream.Read(aIID,sizeof(aIID)); aMP:=MediaProcessing.Global.MediaProceccorFactory.CreateMediaProcessor(aIID,aImplementation); aMP.LoadCustomProperties(aStream); result[i]:=aMP; end; end; function TMediaProceccorFactory.CreateMediaProcessorsImplFromBytes(const aBytes: TBytes): TIMediaProcessorImplArray; var aRes: TIMediaProcessorArray; i: Integer; begin aRes:=CreateMediaProcessorsFromBytes(aBytes,true); SetLength(result,Length(aRes)); for i := 0 to High(aRes) do result[i]:=aRes[i] as IMediaProcessorImpl; end; function TMediaProceccorFactory.CreateMediaProcessorsImplFromStream(aStream: TStream): TIMediaProcessorImplArray; var aRes: TIMediaProcessorArray; i: Integer; begin aRes:=CreateMediaProcessorsFromStream(aStream,true); SetLength(result,Length(aRes)); for i := 0 to High(aRes) do result[i]:=aRes[i] as IMediaProcessorImpl; end; destructor TMediaProceccorFactory.Destroy; begin inherited; FreeAndNil(FRegistry); end; function TMediaProceccorFactory.GetMediaProcessorInfoByIndex( const aIndex: integer): TMediaProcessorInfo; begin result:=FRegistry[aIndex].MediaProcessorClass.MetaInfo; end; function TMediaProceccorFactory.GetMediaProcessorInfoByTypeID(const aTypeID: TGUID): TMediaProcessorInfo; begin result:=FRegistry[GetRegistryIndexByTypeID(aTypeID)].MediaProcessorClass.MetaInfo; end; function TMediaProceccorFactory.GetRegistryIndexByTypeID(const aTypeID: TGUID): integer; var i: integer; begin for i := 0 to FRegistry.Count - 1 do begin if IsEqualGUID(aTypeID,FRegistry[i].MediaProcessorClass.MetaInfo.TypeID) then begin result:=i; exit; end; end; raise Exception.Create('Медиа процессор не найден'); end; function TMediaProceccorFactory.MediaProcessorCount: integer; begin result:=FRegistry.Count; end; procedure TMediaProceccorFactory.RegisterMediaProcessor(aClass: TMediaProcessorClass); var aItem: TMediaProceccorFactoryItem; begin aItem:=TMediaProceccorFactoryItem.Create; aItem.MediaProcessorClass:=aClass; FRegistry.Add(aItem); end; procedure TMediaProceccorFactory.RegisterMediaProcessorImplementation( aClass: TMediaProcessorClass); begin FRegistry[GetRegistryIndexByTypeID(aClass.MetaInfo.TypeID)].MediaImplementorClass:=aClass; end; initialization finalization FreeAndNil(gMediaProceccorFactory); end.
unit FViewerForm; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ActnList, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ImgList, Vcl.ToolWin, Vcl.Menus, //GR32 GR32_Image, GR32, //GLS GLHeightTileFile, GLVectorGeometry, GLUtils; type TViewerForm = class(TForm) ToolBar: TToolBar; ImageList: TImageList; ActionList: TActionList; ToolButton1: TToolButton; LAMap: TLabel; ToolButton2: TToolButton; ACOpen: TAction; ACExit: TAction; ToolButton3: TToolButton; OpenDialog: TOpenDialog; PaintBox: TPaintBox32; ToolButton4: TToolButton; TBGrid: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ACNavMap: TAction; StatusBar: TStatusBar; ToolButton7: TToolButton; ACPalette: TAction; PMPalettes: TPopupMenu; OpenDialogPal: TOpenDialog; procedure ACExitExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ACOpenExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PaintBoxResize(Sender: TObject); procedure PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure TBGridClick(Sender: TObject); procedure ACNavMapExecute(Sender: TObject); procedure PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ACNavMapUpdate(Sender: TObject); procedure ACPaletteExecute(Sender: TObject); private { Private declarations } public { Public declarations } htf : THeightTileFile; bmpTile : TBitmap32; curX, curY, mx, my : Integer; procedure PrepareBitmap; end; var ViewerForm: TViewerForm; var heightColor : array [Low(SmallInt)..High(SmallInt)] of TColor32; implementation {$R *.dfm} uses FNavForm; { Quick'n dirty parser for palette file format '.pal', in which each line defines nodes in the color ramp palette: value:red,green,blue color is then interpolated between node values (ie. between each line in the file) } procedure PreparePal(const fileName : String); procedure ParseLine(buf : String; var n : Integer; var c : TAffineVector); var p : Integer; begin p:=Pos(':', buf); n:=StrToInt(Copy(buf, 1, p-1)); buf:=Copy(buf, p+1, MaxInt); p:=Pos(',', buf); c.X:=StrToInt(Copy(buf, 1, p-1)); buf:=Copy(buf, p+1, MaxInt); p:=Pos(',', buf); c.Y:=StrToInt(Copy(buf, 1, p-1)); buf:=Copy(buf, p+1, MaxInt); c.Z:=StrToInt(buf); end; var prev, next : Integer; pC, nC : TAffineVector; procedure Ramp; var cur : Integer; cC : TAffineVector; d : Single; begin if prev<next then d:=1/(next-prev) else d:=0; for cur:=prev to next do begin cC:=VectorLerp(pC, nC, (cur-prev)*d); heightColor[cur]:=Color32(Round(cC.V[0]), Round(cC.V[1]), Round(cC.V[2])); end; end; var i : Integer; sl : TStrings; begin sl:=TStringList.Create; try sl.LoadFromFile(fileName); prev:=0; pC:=NullVector; for i:=0 to sl.Count-1 do begin ParseLine(sl[i], next, nC); Ramp; prev:=next; pC:=nC; end; finally sl.Free; end; end; procedure TViewerForm.FormCreate(Sender: TObject); var i : Integer; sr : TSearchRec; mi : TMenuItem; sl : TStringList; AppDir : String; begin bmpTile:=TBitmap32.Create; AppDir:=ExtractFilePath(ParamStr(0)); PreparePal(appDir+'Blue-Green-Red.pal'); i:=FindFirst(appDir+'*.pal', faAnyFile, sr); sl:=TStringList.Create; try while i=0 do begin sl.Add(sr.Name); i:=FindNext(sr); end; sl.Sort; for i:=0 to sl.Count-1 do begin mi:=TMenuItem.Create(PMPalettes); mi.Caption:=Copy(sl[i], 1, Length(sl[i])-4); mi.Hint:=appDir+sl[i]; mi.OnClick:=ACPaletteExecute; PMPalettes.Items.Add(mi); end; finally sl.Free; FindClose(sr); end; end; procedure TViewerForm.FormDestroy(Sender: TObject); begin htf.Free; bmpTile.Free; end; procedure TViewerForm.ACExitExecute(Sender: TObject); begin Close; end; procedure TViewerForm.ACOpenExecute(Sender: TObject); var I : Integer; begin SetGLSceneMediaDir; OpenDialog.InitialDir := GetCurrentDir; if OpenDialog.Execute then begin htf.Free; htf:=THeightTileFile.Create(OpenDialog.FileName); Caption:='HTFViewer - '+ExtractFileName(OpenDialog.FileName); curX:=0; curY:=0; PrepareBitmap; PaintBox.Invalidate; end; end; procedure TViewerForm.PrepareBitmap; var i, sx, tx, ty : Integer; scanLine : PColor32Array; tileInfo : PHeightTileInfo; dataRow : PSmallIntArray; tile : PHeightTile; start, lap, stop, htfTime, drawTime, freq : Int64; tileList : TList; bmp : TBitmap32; begin sx:=PaintBox.Width; bmp:=PaintBox.Buffer; bmp.Clear(clBlack32); if not Assigned(htf) then Exit; drawTime:=0; tileList:=TList.Create; try QueryPerformanceCounter(start); htf.TilesInRect(curX, curY, curX+sx-1, curY+bmp.Height-1, tileList); QueryPerformanceCounter(stop); htfTime:=stop-start; for i:=0 to tileList.Count-1 do begin tileInfo:=PHeightTileInfo(tileList[i]); QueryPerformanceCounter(start); tile:=htf.GetTile(tileInfo.left, tileInfo.top); QueryPerformanceCounter(lap); bmpTile.Width:=tileinfo.width; bmpTile.Height:=tileInfo.height; for ty:=0 to tileInfo.height-1 do begin scanLine:=bmpTile.ScanLine[ty]; dataRow:=@tile.data[ty*tileInfo.width]; for tx:=0 to tileInfo.width-1 do scanLine[tx]:=heightColor[dataRow[tx]]; end; bmp.Draw(tileInfo.left-curX, tileInfo.top-curY, bmpTile); QueryPerformanceCounter(stop); htfTime:=htfTime+lap-start; drawTime:=drawTime+stop-lap; end; if TBGrid.Down then begin for i:=0 to tileList.Count-1 do with PHeightTileInfo(tileList[i])^ do begin bmp.FrameRectS(left-curX, top-curY, left+width-curX+1, top+height-curY+1, clWhite32); end; end; finally tileList.Free; end; QueryPerformanceFrequency(freq); LAMap.Caption:=Format(' %d x %d - %.1f ms HTF - %.1fms Draw ', [htf.SizeX, htf.SizeY, 1000*htfTime/freq, 1000*drawTime/freq]); end; procedure TViewerForm.PaintBoxResize(Sender: TObject); begin if Assigned(htf) then PrepareBitmap; end; procedure TViewerForm.PaintBoxMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx:=X; my:=Y; Screen.Cursor:=crSizeAll; end; procedure TViewerForm.PaintBoxMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Screen.Cursor:=crDefault; end; procedure TViewerForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var tileIdx, n : Integer; tileInfo : PHeightTileInfo; begin if Shift<>[] then begin curX:=curX-(x-mx); curY:=curY-(y-my); mx:=x; my:=y; PrepareBitmap; PaintBox.Refresh; end; if Assigned(htf) then begin x:=x+curX; y:=y+curY; StatusBar.Panels[0].Text:=' X: '+IntToStr(x); StatusBar.Panels[1].Text:=' Y: '+IntToStr(y); StatusBar.Panels[2].Text:=' H: '+IntToStr(htf.XYHeight(x, y)); tileInfo:=htf.XYTileInfo(x, y); if Assigned(tileInfo) then begin tileIdx:=htf.IndexOfTile(tileInfo); StatusBar.Panels[3].Text:=' Tile: '+IntToStr(tileIdx); n:=htf.TileCompressedSize(tileIdx)+SizeOf(THeightTileInfo); StatusBar.Panels[4].Text:=Format(' %.2f kB (%.0f %%)', [n/1024, 100-100*n/(htf.TileSize*htf.TileSize*2)]); StatusBar.Panels[5].Text:=Format(' Tile average: %d, range: [%d; %d])', [tileInfo.average, tileInfo.min, tileInfo.max]); end else begin StatusBar.Panels[3].Text:=' Tile: N/A'; StatusBar.Panels[4].Text:=' N/A'; StatusBar.Panels[5].Text:=' N/A'; end; end; end; procedure TViewerForm.TBGridClick(Sender: TObject); begin PrepareBitmap; PaintBox.Invalidate; end; procedure TViewerForm.ACNavMapExecute(Sender: TObject); begin if NavForm.Execute(htf) then begin curX:=NavForm.PickX; curY:=NavForm.PickY; PrepareBitmap; PaintBox.Invalidate; end; end; procedure TViewerForm.ACNavMapUpdate(Sender: TObject); begin ACNavMap.Enabled:=Assigned(htf); end; procedure TViewerForm.ACPaletteExecute(Sender: TObject); begin if Sender is TMenuItem then PreparePal(TMenuItem(Sender).Hint) else if OpenDialogPal.Execute then PreparePal(OpenDialogPal.FileName); PrepareBitmap; PaintBox.Invalidate; end; end.
unit toolu; interface uses Windows, jwaWindows, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Registry, ComObj, ShlObj; function IsWindowsVista: boolean; function IsWin64: boolean; function GetFont: string; function GetContentFont: string; function GetFontSize: integer; function GetContentFontSize: integer; function CreateAFont(Name: string; size: integer): HFont; function cut(itext, ch: string): string; function cutafter(itext, ch: string): string; function ReplaceEx(strSrc, strWhat, strWith: string): string; function fetch(var itext: string; delim: string; adelete: boolean = False): string; function FetchValue(itext: string; Value, delim: string): string; function PosEx(Value, atext: string; startpos: integer): integer; function cuttolast(itext, ch: string): string; function cutafterlast(itext, ch: string): string; function StringToRect(str: string): Windows.Trect; function RectToString(r: Windows.Trect): string; function StringToSize(str: string): Windows.TSize; function SizeToString(r: Windows.TSize): string; function StringToPoint(str: string): Windows.Tpoint; function SetRange(value, min, max: integer): integer; procedure searchfiles(path, mask: string; list: TStrings); procedure searchfolders(path: string; list: TStrings); procedure searchfilesrecurse(path, mask: string; list: TStrings; level: cardinal = 0; maxlevel: cardinal = 255; maxcount: integer = $7fffffff); function ReadIniString(IniFile, IniSection, KeyName, Default: string): string; function ReadIniInteger(IniFile, IniSection, KeyName: string; Default: integer): integer; function CheckAutoRun: boolean; procedure SetAutoRun(enable: boolean); function GetWinVersion: string; procedure GetFileVersion(filename: string; var maj, min, Release, build: integer); function GetEnvVar(VarName: string): string; function UnzipPath(path: string): string; function ZipPath(path: string): string; function GetSystemDir: string; function GetWinDir: string; function GetSystemPath(path: string): string; function BrowseFolder(hWnd: THandle; title, default: string): string; procedure FreeAndNil(var Obj); procedure SetClipboard(Text: string); function GetClipboard: string; function ColorToString(Color: uint): string; function StringToColor(const str: string): uint; function confirm(handle: cardinal; Text: string = ''): boolean; procedure AddLog(LogString: string); procedure TruncLog(fs: TFileStream); implementation //------------------------------------------------------------------------------ function IsWindowsVista: boolean; var VerInfo: TOSVersioninfo; begin VerInfo.dwOSVersionInfoSize := sizeof(TOSVersionInfo); GetVersionEx(@VerInfo); Result := VerInfo.dwMajorVersion >= 6; end; //------------------------------------------------------------------------------ function IsWin64: boolean; var IsWow64Process: function(Handle: THandle; var Res: boolean): boolean; stdcall; res: boolean; begin res := False; IsWow64Process := GetProcAddress(GetModuleHandle(Kernel32), 'IsWow64Process'); if assigned(IsWow64Process) then IsWow64Process(GetCurrentProcess, res); Result := res; end; //------------------------------------------------------------------------------ function GetFont: string; begin Result := 'tahoma'; try if IsWindowsVista then Result := 'segoe ui'; except end; end; //------------------------------------------------------------------------------ function GetContentFont: string; begin Result := 'verdana'; try if IsWindowsVista then Result := 'calibri'; except end; end; //------------------------------------------------------------------------------ function GetFontSize: integer; begin Result := 8; try if IsWindowsVista then Result := 9; except end; end; //------------------------------------------------------------------------------ function GetContentFontSize: integer; begin Result := 8; try if IsWindowsVista then Result := 10; except end; end; //------------------------------------------------------------------------------ function CreateAFont(Name: string; size: integer): HFont; begin Result := CreateFont(size, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, 0, 0, PROOF_QUALITY, 0, PChar(Name)); end; //------------------------------------------------------------------------------ function cut(itext, ch: string): string; var ipos: integer; begin ipos := pos(AnsiLowerCase(ch), AnsiLowerCase(itext)); if ipos > 0 then Result := copy(itext, 1, ipos - 1) else Result := itext; end; //------------------------------------------------------------------------------ function cutafter(itext, ch: string): string; var ipos: integer; begin ipos := pos(AnsiLowerCase(ch), AnsiLowerCase(itext)); if ipos > 0 then Result := copy(itext, ipos + length(ch), length(itext)) else Result := ''; end; //------------------------------------------------------------------------------ function ReplaceEx(strSrc, strWhat, strWith: string): string; var ipos: integer; begin ipos := pos(AnsiLowerCase(strWhat), AnsiLowerCase(strSrc)); while ipos > 0 do begin strSrc := copy(strSrc, 1, ipos - 1) + strWith + copy(strSrc, ipos + length(strWhat), length(strSrc)); ipos := pos(AnsiLowerCase(strWhat), AnsiLowerCase(strSrc)); end; Result := strSrc; end; //------------------------------------------------------------------------------ function fetch(var itext: string; delim: string; adelete: boolean = False): string; var ipos: integer; begin ipos := pos(AnsiLowerCase(delim), AnsiLowerCase(itext)); if ipos > 0 then begin Result := system.copy(itext, 1, ipos - 1); if adelete then system.Delete(itext, 1, ipos - 1 + length(delim)); end else begin Result := itext; itext := ''; end; end; //------------------------------------------------------------------------------ function FetchValue(itext: string; Value, delim: string): string; var ipos, ipos2: integer; begin ipos := pos(AnsiLowerCase(Value), AnsiLowerCase(itext)); if ipos > 0 then begin ipos2 := posex(delim, itext, ipos + length(Value)); Result := system.copy(itext, ipos + length(Value), ipos2 - ipos - length(Value)); end else Result := ''; end; //------------------------------------------------------------------------------ function PosEx(Value, atext: string; startpos: integer): integer; begin Result := startpos; if Value = '' then exit; while Result <= length(atext) do begin if AnsiLowerCase(atext[Result]) = AnsiLowerCase(Value[1]) then if AnsiLowerCase(copy(atext, Result, length(Value))) = AnsiLowerCase(Value) then exit; Inc(Result); end; end; //------------------------------------------------------------------------------ function cuttolast(itext, ch: string): string; var i, len: integer; begin Result := ''; if itext = '' then exit; i := length(itext); len := length(ch); while i > 0 do begin if AnsiLowerCase(copy(itext, i, len)) = AnsiLowerCase(ch) then begin Result := copy(itext, 1, i - 1); exit; end; Dec(i); end; Result := itext; end; //------------------------------------------------------------------------------ function cutafterlast(itext, ch: string): string; var i, ilen, len: integer; begin Result := ''; if itext = '' then exit; ilen := length(itext); i := ilen; len := length(ch); while i > 0 do begin if AnsiLowerCase(copy(itext, i, len)) = AnsiLowerCase(ch) then begin Result := copy(itext, i + len, ilen); exit; end; Dec(i); end; Result := itext; end; //------------------------------------------------------------------------------ function StringToRect(str: string): Windows.Trect; begin Result := rect(0, 0, 0, 0); try Result.left := StrToInt(trim(fetch(str, ',', True))); except end; try Result.top := StrToInt(trim(fetch(str, ',', True))); except end; try Result.right := StrToInt(trim(fetch(str, ',', True))); except end; try Result.bottom := StrToInt(trim(fetch(str, ')'))); except end; end; //------------------------------------------------------------------------------ function RectToString(r: Windows.Trect): string; begin Result := IntToStr(r.left) + ',' + IntToStr(r.top) + ',' + IntToStr(r.right) + ',' + IntToStr(r.bottom); end; //------------------------------------------------------------------------------ function StringToSize(str: string): Windows.TSize; begin Result.cx := 0; Result.cy := 0; try Result.cx := StrToInt(trim(cut(str, ','))); Result.cy := StrToInt(trim(cutafter(str, ','))); except end; end; //------------------------------------------------------------------------------ function SizeToString(r: Windows.TSize): string; begin Result := IntToStr(r.cx) + ',' + IntToStr(r.cy); end; //------------------------------------------------------------------------------ function StringToPoint(str: string): Windows.Tpoint; begin Result := point(0, 0); try Result.x := StrToInt(trim(cut(str, ','))); Result.y := StrToInt(trim(cutafter(str, ','))); except end; end; //------------------------------------------------------------------------------ function SetRange(value, min, max: integer): integer; begin if value < min then value := min; if value > max then value := max; result := value; end; //------------------------------------------------------------------------------ procedure searchfiles(path, mask: string; list: TStrings); var fhandle: HANDLE; f: TWin32FindData; begin list.Clear; path := IncludeTrailingPathDelimiter(path); fhandle := FindFirstFile(PChar(path + mask), f); if fhandle = INVALID_HANDLE_VALUE then exit; if (f.dwFileAttributes and $18) = 0 then list.addobject(f.cFileName, tobject(0)); while FindNextFile(fhandle, f) do if (f.dwFileAttributes and $18) = 0 then list.addobject(f.cFileName, tobject(0)); if not (fhandle = INVALID_HANDLE_VALUE) then Windows.FindClose(fhandle); end; //------------------------------------------------------------------------------ procedure searchfolders(path: string; list: TStrings); var fhandle: THandle; filename: string; f: TWin32FindData; begin list.Clear; path := IncludeTrailingPathDelimiter(path); fhandle := FindFirstFile(PChar(path + '*.*'), f); if not (fhandle = INVALID_HANDLE_VALUE) then begin filename := strpas(f.cFileName); if ((f.dwFileAttributes and 16) = 16) and (filename <> '.') and (filename <> '..') then list.addobject(filename, tobject(0)); while FindNextFile(fhandle, f) do begin filename := strpas(f.cFileName); if ((f.dwFileAttributes and 16) = 16) and (filename <> '.') and (filename <> '..') then list.addobject(filename, tobject(0)); end; end; if not (fhandle = INVALID_HANDLE_VALUE) then Windows.FindClose(fhandle); end; //------------------------------------------------------------------------------ procedure searchfilesrecurse(path, mask: string; list: TStrings; level: cardinal = 0; maxlevel: cardinal = 255; maxcount: integer = $7fffffff); var fhandle: THandle; filename: string; f: TWin32FindData; begin if level = 0 then list.Clear; path := IncludeTrailingPathDelimiter(path); // folders // fhandle := FindFirstFile(PChar(path + '*.*'), f); if not (fhandle = INVALID_HANDLE_VALUE) then begin filename := strpas(f.cFileName); if ((f.dwFileAttributes and 16) = 16) and (filename <> '.') and (filename <> '..') and (level < maxlevel) then searchfilesrecurse(path + filename, mask, list, level + 1); while FindNextFile(fhandle, f) do begin filename := strpas(f.cFileName); if ((f.dwFileAttributes and 16) = 16) and (filename <> '.') and (filename <> '..') and (level < maxlevel) then searchfilesrecurse(path + filename, mask, list, level + 1, maxlevel); end; end; if not (fhandle = INVALID_HANDLE_VALUE) then Windows.FindClose(fhandle); // files // fhandle := FindFirstFile(PChar(path + mask), f); if not (fhandle = INVALID_HANDLE_VALUE) then begin if ((f.dwFileAttributes and $18) = 0) and (list.Count < maxcount) then list.addobject(path + f.cFileName, tobject(0)); while FindNextFile(fhandle, f) do if ((f.dwFileAttributes and $18) = 0) and (list.Count < maxcount) then list.addobject(path + f.cFileName, tobject(0)); end; if not (fhandle = INVALID_HANDLE_VALUE) then Windows.FindClose(fhandle); end; //------------------------------------------------------------------------------ function ReadIniString(IniFile, IniSection, KeyName, Default: string): string; var buf: array [0..1023] of char; begin GetPrivateProfileString(pchar(IniSection), pchar(KeyName), pchar(Default), pchar(@buf), 1024, pchar(IniFile)); result:= strpas(pchar(@buf)); end; //------------------------------------------------------------------------------ function ReadIniInteger(IniFile, IniSection, KeyName: string; Default: integer): integer; var buf: array [0..15] of char; begin result:= Default; GetPrivateProfileString(pchar(IniSection), pchar(KeyName), pchar(inttostr(Default)), pchar(@buf), 16, pchar(IniFile)); try result:= strtoint(strpas(pchar(@buf))); except end; end; //------------------------------------------------------------------------------ function CheckAutoRun: boolean; var reg: Treginifile; begin reg := Treginifile.Create; reg.RootKey := HKEY_current_user; result := (reg.ReadString('Software\Microsoft\Windows\CurrentVersion\Run', application.title, '') = ParamStr(0)); reg.Free; end; //---------------------------------------------------------------------- procedure SetAutoRun(enable: boolean); var reg: Treginifile; begin reg := Treginifile.Create; reg.RootKey := HKEY_current_user; reg.lazywrite := False; if reg.ReadString('Software\Microsoft\Windows\CurrentVersion\Run', application.title, '') <> '' then reg.DeleteKey('Software\Microsoft\Windows\CurrentVersion\Run', application.title); if enable then reg.WriteString('Software\Microsoft\Windows\CurrentVersion\Run', application.title, ParamStr(0)); reg.Free; end; //---------------------------------------------------------------------- function GetWinVersion: string; var VersionInfo: Windows.TOSVersionInfo; begin VersionInfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo); if Windows.GetVersionEx(VersionInfo) then begin with VersionInfo do begin case dwPlatformId of VER_PLATFORM_WIN32s: Result := 'Win32s'; VER_PLATFORM_WIN32_WINDOWS: Result := 'Windows 95'; VER_PLATFORM_WIN32_NT: Result := 'Windows NT'; end; Result := Result + ' Version ' + IntToStr(dwMajorVersion) + '.' + IntToStr(dwMinorVersion) + ' (Build ' + IntToStr(dwBuildNumber) + ': ' + szCSDVersion + ')'; end; end else Result := ''; end; //---------------------------------------------------------------------- procedure GetFileVersion(filename: string; var maj, min, Release, build: integer); var Info: Pointer; InfoSize: DWORD; FileInfo: PVSFixedFileInfo; FileInfoSize: DWORD; Tmp: DWORD; begin maj := 0; min := 0; Release := 0; build := 0; filename := UnzipPath(filename); InfoSize := GetFileVersionInfoSize(PChar(FileName), Tmp); if InfoSize <> 0 then begin GetMem(Info, InfoSize); try GetFileVersionInfo(PChar(FileName), 0, InfoSize, Info); VerQueryValue(Info, '\', Pointer(FileInfo), FileInfoSize); maj := FileInfo.dwFileVersionMS shr 16; min := FileInfo.dwFileVersionMS and $FFFF; Release := FileInfo.dwFileVersionLS shr 16; build := FileInfo.dwFileVersionLS and $FFFF; finally FreeMem(Info, FileInfoSize); end; end; end; //------------------------------------------------------------------------------ function GetEnvVar(VarName: string): string; var i: integer; begin Result := ''; try i := Windows.GetEnvironmentVariable(PChar(VarName), nil, 0); if i > 0 then begin SetLength(Result, i); Windows.GetEnvironmentVariable(PChar(VarName), PChar(Result), i); end; except end; end; //------------------------------------------------------------------------------ function UnzipPath(path: string): string; var pp: string; begin if trim(path) = '' then exit; Result := path; if length(Result) > 3 then if (Result[2] = ':') and (Result[3] = '\') then if fileexists(Result) or directoryexists(Result) then exit; pp := ExcludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); if fileexists(pp + '\' + Result) then begin Result := pp + '\' + Result; exit; end; // path vars // Result := ReplaceEx(Result, '%pp%', pp); Result := ReplaceEx(Result, '%windir%', GetWinDir); Result := ReplaceEx(Result, '%systemroot%', getwindir); Result := ReplaceEx(Result, '%sysdir%', getsystemdir); Result := ReplaceEx(Result, '%doc%', getsystempath('personal')); Result := ReplaceEx(Result, '%desktop%', getsystempath('desktop')); Result := ReplaceEx(Result, '%startmenu%', getsystempath('start menu')); Result := ReplaceEx(Result, '%commonstartmenu%', getsystempath('common start menu')); Result := ReplaceEx(Result, '%pf%', getwindir[1] + ':\Program Files'); Result := ReplaceEx(Result, '%programfiles%', getwindir[1] + ':\Program Files'); // non-path vars // Result := ReplaceEx(Result, '%date%', formatdatetime('dddddd', now)); Result := ReplaceEx(Result, '%time%', formatdatetime('tt', now)); Result := ReplaceEx(Result, '%win_version%', GetWinVersion); Result := ReplaceEx(Result, '%uptime%', formatdatetime('hh hour nn min ss sec', gettickcount / MSecsPerDay)); Result := ReplaceEx(Result, '%crlf%', #10#13); end; //------------------------------------------------------------------------------ function ZipPath(path: string): string; var windir: string; begin windir := getwindir; path := ReplaceEx(path, IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))), ''); path := ReplaceEx(path, getsystemdir, '%sysdir%'); path := ReplaceEx(path, windir, '%windir%'); path := ReplaceEx(path, getsystempath('personal'), '%doc%'); path := ReplaceEx(path, getsystempath('desktop'), '%desktop%'); path := ReplaceEx(path, getsystempath('start menu'), '%startmenu%'); path := ReplaceEx(path, getsystempath('common start menu'), '%commonstartmenu%'); path := ReplaceEx(path, windir[1] + ':\program files', '%pf%'); Result := path; end; //---------------------------------------------------------------------- function GetSystemDir: string; var SysDir: array [0..MAX_PATH - 1] of char; begin SetString(Result, SysDir, GetSystemDirectory(SysDir, MAX_PATH)); Result := ExcludeTrailingPathDelimiter(Result); end; //---------------------------------------------------------------------- function GetWinDir: string; var WinDir: array [0..MAX_PATH - 1] of char; begin SetString(Result, WinDir, GetWindowsDirectory(WinDir, MAX_PATH)); Result := ExcludeTrailingPathDelimiter(Result); end; //------------------------------------------------------------------------------ function GetSystemPath(path: string): string; var reg: TRegIniFile; begin reg := TRegIniFile.Create; if pos('common', path) > 0 then reg.RootKey := hkey_local_machine else reg.RootKey := hkey_current_user; Result := ExcludeTrailingPathDelimiter(reg.ReadString('Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders', path, '')); reg.Free; end; //-------------------------------------------------------------------------------------------------- function BrowseFolder(hWnd: THandle; title, default: string): string; var lpItemID: PItemIDList; BrowseInfo: Windows.TBrowseInfo; DisplayName: array[0..MAX_PATH] of char; path: array [0..MAX_PATH] of char; begin zeroMemory(@BrowseInfo, sizeof(TBrowseInfo)); BrowseInfo.hwndOwner := hWnd; BrowseInfo.pszDisplayName := @DisplayName; BrowseInfo.lpszTitle := PChar(title); BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS or BIF_NEWDIALOGSTYLE; lpItemID := SHBrowseForFolder(@BrowseInfo); if lpItemId <> nil then begin SHGetPathFromIDList(lpItemID, path); result := strpas(path); result := IncludeTrailingPathDelimiter(Result); GlobalFreePtr(lpItemID); end else Result := default; end; //------------------------------------------------------------------------------ procedure FreeAndNil(var Obj); var p: TObject; begin p := TObject(Obj); TObject(Obj) := nil; p.Free; end; //------------------------------------------------------------------------------ procedure SetClipboard(Text: string); var Data: cardinal; dataPtr: pointer; pch: PChar; begin if not OpenClipboard(application.mainform.handle) then begin ShowMessage('Cannot open clipboard'); exit; end; EmptyClipboard; Data := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, length(Text) + 1); dataPtr := GlobalLock(Data); pch := PChar(Text); move(pch^, dataPtr^, length(Text) + 1); SetClipboardData(CF_TEXT, Data); GlobalUnlock(Data); CloseClipboard; end; //------------------------------------------------------------------------------ function GetClipboard: string; var Data: cardinal; dataptr: pointer; pch: PChar; begin Result := ''; if not OpenClipboard(application.mainform.handle) then begin ShowMessage('Cannot open clipboard'); exit; end; try Data := GetClipboardData(CF_TEXT); if Data > 32 then begin dataptr := GlobalLock(Data); if dataptr <> nil then begin GetMem(pch, GlobalSize(Data)); move(dataPtr^, pch^, GlobalSize(Data)); Result := strpas(pch); FreeMem(pch, GlobalSize(Data)); end; GlobalUnlock(Data); end else Result := ''; except end; CloseClipboard; end; //------------------------------------------------------------------------------ function ColorToString(Color: uint): string; begin FmtStr(Result, '%s%.8x', [HexDisplayPrefix, Color]); end; //------------------------------------------------------------------------------ function StringToColor(const str: string): uint; begin Result := StrToInt(str); end; //------------------------------------------------------------------------------ function confirm(handle: cardinal; Text: string = ''): boolean; begin if Text = '' then Text := 'Confirm action'; Result := messagebox(handle, PChar(Text), 'Confirm', mb_yesno or mb_iconexclamation or mb_defbutton2) = idYes; end; //------------------------------------------------------------------------------ procedure AddLog(LogString: string); var LogFileName: string; faccess: dword; PStr: PChar; LengthLogString: integer; fs: TFileStream; begin try // prepare log string LogString := formatdatetime('yyMMdd-hhnnss', now) + ' ' + LogString + #13#10; LengthLogString := Length(LogString); PStr := StrAlloc(LengthLogString + 1); StrPCopy(PStr, LogString); // open log LogFileName := UnzipPath('%pp%\log.log'); if FileExists(LogFileName) then faccess := fmOpenReadWrite else faccess := fmCreate; fs := TFileStream.Create(LogFileName, faccess); fs.Position := fs.Size; // write string fs.Write(PStr^, LengthLogString); StrDispose(PStr); // truncate file if needed TruncLog(fs); fs.Free; except end; end; //------------------------------------------------------------------------------ procedure TruncLog(fs: TFileStream); const LOG_SIZE_MAX = 1024 * 20; var buf: char; TruncBy: integer; ms: TMemoryStream; begin try // how many bytes to delete from the beginning of the stream TruncBy := fs.Size - LOG_SIZE_MAX; if TruncBy > 0 then begin // skip TruncBy bytes fs.Position := TruncBy; // skip bytes until end-of-line found fs.Read(buf, 1); inc(TruncBy); fs.Position := TruncBy; while (TruncBy < fs.Size) and (buf <> #10) and (buf <> #13) do begin fs.Read(buf, 1); inc(TruncBy); fs.Position := TruncBy; end; inc(TruncBy); fs.Position := TruncBy; TruncBy := fs.Size - TruncBy; // copy data to buffer stream ms := TMemoryStream.Create; ms.Size := TruncBy; ms.Position := 0; ms.CopyFrom(fs, TruncBy); ms.Position := 0; // copy buffer back to file fs.Size := TruncBy; fs.Position := 0; fs.CopyFrom(ms, TruncBy); ms.free; end; except end; end; //------------------------------------------------------------------------------ end.
namespace RemObjects.Elements.System; interface uses Foundation; type NSMutableDictionary<TKey, TValue> = public class(RemObjects.Elements.System.NSDictionary<TKey, TValue>) mapped to Foundation.NSMutableDictionary where TKey is class, TValue is class; public { Class Constructors } class method dictionary: id; mapped to dictionary; class method dictionaryWithContentsOfFile(path: not nullable NSString): id; mapped to dictionaryWithContentsOfFile(path); class method dictionaryWithContentsOfURL(aURL: not nullable NSURL): id; mapped to dictionaryWithContentsOfURL(aURL); class method dictionaryWithDictionary(otherDictionary: not nullable NSDictionary<TKey, TValue>): id; mapped to dictionaryWithDictionary(otherDictionary); class method dictionaryWithObject(anObject: not nullable TValue) forKey(aKey: not nullable TKey): id; mapped to dictionaryWithObject(anObject) forKey(aKey); class method dictionaryWithObjects(objects: not nullable NSArray<TValue>) forKeys(keys: not nullable NSArray<TKey>): id; mapped to dictionaryWithObjects(objects) forKeys(keys); class method dictionaryWithObjects(objects: ^TValue) forKeys(keys: ^TKey) count(count: NSUInteger): id; mapped to dictionaryWithObjects(^id(objects)) forKeys(^id(keys)) count(count); //class method dictionaryWithObjectsAndKeys(firstObject: not nullable id; params param1: array of id): id; mapped to dictionaryWithObjectsAndKeys(firstObject, param1); class method sharedKeySetForKeys(keys: not nullable NSArray<TKey>): id; mapped to sharedKeySetForKeys(keys); (* { Instance Methods } method allKeysForObject(anObject: id): NSArray<TKey>; mapped to allKeysForObject(anObject); method descriptionWithLocale(locale: id): NSString; mapped to descriptionWithLocale(locale); method descriptionWithLocale(locale: id) indent(level: Integer): NSString; mapped to descriptionWithLocale(locale) indent(level); method enumerateKeysAndObjectsUsingBlock(&block: block(key: TKey; obj: TValue; stop: ^Boolean)); mapped to enumerateKeysAndObjectsUsingBlock(NSDictionaryEnumerateBlock(&block)); method enumerateKeysAndObjectsWithOptions(opts: NSEnumerationOptions) usingBlock(&block: block(key: TKey; obj: TValue; stop: ^Boolean)); mapped to enumerateKeysAndObjectsWithOptions(opts) usingBlock(NSDictionaryEnumerateBlock(&block)); //method getObjects(objects: ^id) andKeys(keys: ^id); mapped to getObjects(objects) andKeys(keys); method isEqualToDictionary(otherDictionary: NSDictionary<TKey, TValue>): Boolean; mapped to isEqualToDictionary(otherDictionary); method keysOfEntriesPassingTest(predicate: block(key: TKey; obj: TValue; stop: ^Boolean): Boolean): NSSet; mapped to keysOfEntriesPassingTest(NSDictionaryTestBlock(predicate)); method keysOfEntriesWithOptions(opts: NSEnumerationOptions) passingTest(predicate: block(key: TKey; obj: TValue; stop: ^Boolean): Boolean): NSSet; mapped to keysOfEntriesWithOptions(opts) passingTest(NSDictionaryTestBlock(predicate)); method keysSortedByValueUsingComparator(cmptr: NSComparator): NSArray<TKey>; mapped to keysSortedByValueUsingComparator(cmptr); method keysSortedByValueUsingSelector(comparator: SEL): NSArray<TKey>; mapped to keysSortedByValueUsingSelector(comparator); method keysSortedByValueWithOptions(opts: NSSortOptions) usingComparator(cmptr: NSComparator): NSArray<TKey>; mapped to keysSortedByValueWithOptions(opts) usingComparator(cmptr); method objectForKey(aKey: TKey): TValue; mapped to objectForKey(aKey); method objectForKeyedSubscript(key: TKey): TValue; mapped to objectForKeyedSubscript(key); method objectsForKeys(keys: NSArray<TKey>) notFoundMarker(anObject: id): NSArray<TValue>; mapped to objectsForKeys(keys) notFoundMarker(anObject); method writeToFile(path: String) atomically(flag: Boolean): Boolean; mapped to writeToFile(path) atomically(flag); method writeToURL(aURL: NSURL) atomically(flag: Boolean): Boolean; mapped to writeToURL(aURL) atomically(flag); { Instance Properties } property count: NSUInteger read mapped.count; property allKeys: NSArray<TKey> read mapped.allKeys; property allValues: NSArray<TValue> read mapped.allValues; property descriptionInStringsFileFormat: NSString read mapped.descriptionInStringsFileFormat; property fileCreationDate: NSDate read mapped.fileCreationDate; property fileExtensionHidden: Boolean read mapped.fileExtensionHidden; property fileGroupOwnerAccountID: NSNumber read mapped.fileGroupOwnerAccountID; property fileGroupOwnerAccountName: NSString read mapped.fileGroupOwnerAccountName; property fileHFSCreatorCode: OSType read mapped.fileHFSCreatorCode; property fileHFSTypeCode: OSType read mapped.fileHFSTypeCode; property fileIsAppendOnly: Boolean read mapped.fileIsAppendOnly; property fileIsImmutable: Boolean read mapped.fileIsImmutable; property fileModificationDate: NSDate read mapped.fileModificationDate; property fileOwnerAccountID: NSNumber read mapped.fileOwnerAccountID; property fileOwnerAccountName: NSString read mapped.fileOwnerAccountName; property filePosixPermissions: NSUInteger read mapped.filePosixPermissions; property fileSize: Int64 read mapped.fileSize; property fileSystemFileNumber: NSUInteger read mapped.fileSystemFileNumber; property fileSystemNumber: NSInteger read mapped.fileSystemNumber; property fileType: NSString read mapped.fileType; property keyEnumerator: NSEnumerator read mapped.keyEnumerator; property objectEnumerator: NSEnumerator read mapped.objectEnumerator; *) { NSMutableDictionary } class method dictionaryWithCapacity(numItems: NSUInteger): id; mapped to dictionaryWithCapacity(numItems); class method dictionaryWithSharedKeySet(keyset: id): id; mapped to dictionaryWithSharedKeySet(keyset); method addEntriesFromDictionary(otherDictionary: not nullable NSDictionary<TKey,TValue>); mapped to addEntriesFromDictionary(otherDictionary); method removeAllObjects; mapped to removeAllObjects; method removeObjectForKey(aKey: not nullable TKey); mapped to removeObjectForKey(aKey); method removeObjectsForKeys(keyArray: not nullable NSArray<TKey>); mapped to removeObjectsForKeys(keyArray); method setDictionary(otherDictionary: not nullable NSDictionary<TKey,TValue>); mapped to setDictionary(otherDictionary); method setObject(anObject: TValue) forKey(aKey: not nullable TKey); mapped to setObject(anObject) forKey(aKey); method setObject(anObject: TValue) forKeyedSubscript(aKey: not nullable TKey); mapped to setObject(anObject) forKeyedSubscript(aKey); end; implementation end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX_Colors; {$I FMX_Defines.inc} interface uses Classes, Types, UITypes, FMX_Objects, FMX_Types, FMX_Controls, FMX_Edit, FMX_ListBox; const colorPickSize = 10; type { THueTrackBar } THueTrackBar = class(TBitmapTrackBar) private function IsValueStored: Boolean; protected procedure FillBitmap; override; public constructor Create(AOwner: TComponent); override; published property Value stored IsValueStored; end; { TAlphaTrackBar } TAlphaTrackBar = class(TBitmapTrackBar) private function IsValueStored: Boolean; protected procedure FillBitmap; override; public constructor Create(AOwner: TComponent); override; published property Value stored IsValueStored; end; { TBWTrackBar } TBWTrackBar = class(TBitmapTrackBar) private function IsValueStored: Boolean; protected procedure FillBitmap; override; public constructor Create(AOwner: TComponent); override; published property Value stored IsValueStored; end; { TColorBox } TColorBox = class(TControl) private FColor: TAlphaColor; procedure SetColor(const Value: TAlphaColor); public constructor Create(AOwner: TComponent); override; procedure Paint; override; // property Color: TColor read FColor write SetColor; RAID 283752 published property Color: TAlphaColor read FColor write SetColor; end; { TColorQuad } TColorQuad = class(TControl) private FColorBox: TColorBox; FColorBitmap: TBitmap; FHue: Single; FSat: Single; FLum: Single; FOnChange: TNotifyEvent; FAlpha: Single; FPendingChanges: Boolean; procedure SetHue(const Value: Single); procedure SetLum(const Value: Single); procedure SetSat(const Value: Single); procedure SetAlpha(const Value: Single); procedure SetColorBox(const Value: TColorBox); procedure PreviewColor(const ValHue, ValLum, ValSat, ValAlpha: Single); procedure SetColor(const ValHue, ValLum, ValSat, ValAlpha: Single); function GetIsTracking: Boolean; protected procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; function GetAbsoluteRect: TRectF; override; function PointInObject(X, Y: Single): Boolean; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; published property Hue: Single read FHue write SetHue; property Lum: Single read FLum write SetLum; property Sat: Single read FSat write SetSat; property Alpha: Single read FAlpha write SetAlpha; property ColorBox: TColorBox read FColorBox write SetColorBox; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TColorPicker } TColorPicker = class(TControl) private FHueBitmap: TBitmap; FHue: Single; FColorQuad: TColorQuad; procedure SetHue(const Value: Single); function GetColor: TAlphaColor; procedure SetColor(const Value: TAlphaColor); protected procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; function GetAbsoluteRect: TRectF; override; function PointInObject(X, Y: Single): Boolean; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; property Color: TAlphaColor read GetColor write SetColor; published property Hue: Single read FHue write SetHue; property ColorQuad: TColorQuad read FColorQuad write FColorQuad; end; { TGradientEdit } TGradientEdit = class(TControl) private FBitmap: TBitmap; FGradient: TGradient; FCurrentPoint: Integer; FCurrentPointInvisible: Boolean; FMoving: Boolean; FOnChange: TNotifyEvent; FOnSelectPoint: TNotifyEvent; FColorPicker: TColorPicker; procedure SetGradient(const Value: TGradient); function GetPointRect(const Point: Integer): TRectF; procedure DoChanged(Sender: TObject); procedure SetCurrentPoint(const Value: Integer); procedure SetColorPicker(const Value: TColorPicker); protected procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseMove(Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Paint; override; procedure UpdateGradient; property Gradient: TGradient read FGradient write SetGradient; property CurrentPoint: Integer read FCurrentPoint write SetCurrentPoint; published property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnSelectPoint: TNotifyEvent read FOnSelectPoint write FOnSelectPoint; property ColorPicker: TColorPicker read FColorPicker write SetColorPicker; end; { TColorPanel } TColorPanel = class(TControl) private FOnChange: TNotifyEvent; FColorQuad: TColorQuad; FAlphaTrack: TAlphaTrackBar; FHueTrack: THueTrackBar; FColorBox: TColorBox; FUseAlpha: Boolean; function GetColor: TAlphaColor; procedure SetColor(const Value: TAlphaColor); procedure SetColorBox(const Value: TColorBox); procedure SetUseAlpha(const Value: Boolean); protected procedure DoAlphaChange(Sender: TObject); procedure DoHueChange(Sender: TObject); procedure DoQuadChange(Sender: TObject); procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property OnChange: TNotifyEvent read FOnChange write FOnChange; property Color: TAlphaColor read GetColor write SetColor; property ColorBox: TColorBox read FColorBox write SetColorBox; property UseAlpha: Boolean read FUseAlpha write SetUseAlpha default True; end; { TComboColorBox } TComboColorBox = class(TStyledControl) private FPopup: TPopup; FColorPanel: TColorPanel; FColorBox: TColorBox; FColorText: TEdit; FPlacement: TPlacement; FOnChange: TNotifyEvent; function GetValue: TAlphaColor; procedure SetValue(const Value: TAlphaColor); function GetUseAlpha: Boolean; procedure SetUseAlpha(const Value: Boolean); protected procedure ApplyStyle; override; function GetDefaultStyleLookupName: WideString; override; procedure DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure ChangeParent; override; procedure DoColorChange(Sender: TObject); virtual; procedure DoTextChange(Sender: TObject); virtual; function GetData: Variant; override; procedure SetData(const Value: Variant); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DropDown; published property CanFocus default True; property DisableFocusEffect; property TabOrder; property Color: TAlphaColor read GetValue write SetValue; property UseAlpha: Boolean read GetUseAlpha write SetUseAlpha default True; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TColorButton } TColorButton = class(TCustomButton) private FFill: TShape; FColor: TAlphaColor; FOnChange: TNotifyEvent; FUseStandardDialog: Boolean; procedure SetColor(const Value: TAlphaColor); protected procedure ApplyStyle; override; procedure FreeStyle; override; procedure Click; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property AutoTranslate default False; property CanFocus default True; property DisableFocusEffect; property TabOrder; property Color: TAlphaColor read FColor write SetColor; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; { TColorListBox } TColorListBox = class(TListBox) private procedure SetColor(const Value: TAlphaColor); function GetColor: TAlphaColor; procedure SetItems(const Value: TWideStrings); protected procedure RebuildList; procedure DoApplyStyleLookup(Sender: TObject); function GetDefaultStyleLookupName: WideString; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Color: TAlphaColor read GetColor write SetColor; property Items: TWideStrings read FItems write SetItems stored false; end; { TColorComboBox } TColorComboBox = class(TComboBox) private procedure SetColor(const Value: TAlphaColor); function GetColor: TAlphaColor; protected procedure RebuildList; procedure DoApplyStyleLookup(Sender: TObject); function GetDefaultStyleLookupName: WideString; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Color: TAlphaColor read GetColor write SetColor; end; procedure FillChessBoardBrush(ABrushBitmap: TBrushBitmap; const AChessStep: Single); implementation uses UIConsts, Variants, SysUtils, Math; procedure FillChessBoardBrush(ABrushBitmap: TBrushBitmap; const AChessStep: Single); begin with ABrushBitmap.Bitmap do begin SetSize(Trunc(2 * AChessStep), Trunc(2 * AChessStep)); Clear(TAlphaColorRec.White); ClearRect(RectF(0, 0, AChessStep, AChessStep), TAlphaColorRec.Lightgray); ClearRect(RectF(AChessStep, AChessStep, 2 * AChessStep, 2 * AChessStep), TAlphaColorRec.Lightgray); end; ABrushBitmap.WrapMode := TWrapMode.wmTile; end; { THueTrackBar } constructor THueTrackBar.Create(AOwner: TComponent); begin inherited; Max := 1; Value := 0.5; end; procedure THueTrackBar.FillBitmap; var i, j: Integer; begin for j := 0 to FBitmap.Height - 1 do begin for i := 0 to FBitmap.Width - 1 do begin if Orientation = TOrientation.orHorizontal then FBitmap.Scanline[j][i] := CorrectColor(HSLtoRGB(i / FBitmap.Width, 0.9, 0.5)) else FBitmap.Scanline[j][i] := CorrectColor(HSLtoRGB(j / FBitmap.Height, 0.9, 0.5)); end; end; end; function THueTrackBar.IsValueStored: Boolean; begin Result := Value <> 0.5; end; { TAlphaTrackBar } constructor TAlphaTrackBar.Create(AOwner: TComponent); begin inherited; Max := 1; Value := 1; end; procedure TAlphaTrackBar.FillBitmap; var i, j: Integer; begin for j := 0 to FBitmap.Height - 1 do begin for i := 0 to FBitmap.Width - 1 do begin if odd(i div 3) and not odd(j div 3) then FBitmap.Scanline[j][i] := CorrectColor($FFA0A0A0) else if not odd(i div 3) and odd(j div 3) then FBitmap.Scanline[j][i] := CorrectColor($FFA0A0A0) else FBitmap.Scanline[j][i] := CorrectColor($FFFFFFFF) end; end; if FBitmap.Canvas.BeginScene then try FBitmap.Canvas.Fill.Kind := TBrushKind.bkGradient; FBitmap.Canvas.Fill.Gradient.Points[0].Color := $00FFFFFF; FBitmap.Canvas.Fill.Gradient.Points[1].Color := $FFFFFFFF; FBitmap.Canvas.Fill.Gradient.StopPosition.Point := PointF(1, 0); FBitmap.Canvas.FillRect(RectF(0, 0, FBitmap.Width, FBitmap.Height), 0, 0, [], 1); finally FBitmap.Canvas.EndScene; end; end; function TAlphaTrackBar.IsValueStored: Boolean; begin Result := Value <> 1; end; { TBWTrackBar } constructor TBWTrackBar.Create(AOwner: TComponent); begin inherited; Max := 1; Value := 0.5; end; procedure TBWTrackBar.FillBitmap; var i, j: Integer; a: byte; begin for j := 0 to FBitmap.Height - 1 do begin for i := 0 to FBitmap.Width - 1 do begin if Orientation = TOrientation.orHorizontal then a := round((i / FBitmap.Width) * $FF) else a := round((j / FBitmap.Height) * $FF); FBitmap.Scanline[j][i] := CorrectColor(MakeColor(a, a, a)); end; end; end; function TBWTrackBar.IsValueStored: Boolean; begin Result := Value <> 0.5; end; { TColorBox } constructor TColorBox.Create(AOwner: TComponent); begin inherited; SetAcceptsControls(False); end; procedure TColorBox.Paint; var State: TCanvasSaveState; begin State := Canvas.SaveState; try FillChessBoardBrush(Canvas.Fill.Bitmap, 5); Canvas.Fill.Kind := TBrushKind.bkBitmap; Canvas.FillRect(LocalRect, 0, 0, AllCorners, AbsoluteOpacity); Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := FColor; Canvas.FillRect(LocalRect, 0, 0, AllCorners, AbsoluteOpacity); finally Canvas.RestoreState(State); end; end; procedure TColorBox.SetColor(const Value: TAlphaColor); begin if FColor <> Value then begin FColor := Value; Repaint; end; end; { TColorQuad } constructor TColorQuad.Create(AOwner: TComponent); begin inherited; FAlpha := 1; AutoCapture := True; SetAcceptsControls(False); FPendingChanges := false; end; destructor TColorQuad.Destroy; begin if (FColorBitmap <> nil) then FColorBitmap.Free; inherited; end; function TColorQuad.GetAbsoluteRect: TRectF; begin Result := inherited GetAbsoluteRect; InflateRect(Result, colorPickSize + 1, colorPickSize + 1); end; function TColorQuad.GetIsTracking: Boolean; begin Result := FPressed; end; function TColorQuad.PointInObject(X, Y: Single): Boolean; var P: TPointF; begin Result := False; P := AbsoluteToLocal(PointF(X, Y)); if (P.X > -colorPickSize / 2) and (P.X < Width + colorPickSize / 2) and (P.Y > -colorPickSize / 2) and (P.Y < Height + colorPickSize / 2) then begin Result := True; end; end; procedure TColorQuad.PreviewColor(const ValHue, ValLum, ValSat, ValAlpha: Single); var LChanged : Boolean; begin LChanged := false; if FHue <> ValHue then begin FHue := ValHue; if FHue < 0 then FHue := 0; if FHue > 1 then FHue := 1; LChanged := true; end; if FLum <> ValLum then begin FLum := ValLum; if FLum < 0 then FLum := 0; if FLum > 1 then FLum := 1; LChanged := true; end; if FSat <> ValSat then begin FSat := ValSat; if FSat < 0 then FSat := 0; if FSat > 1 then FSat := 1; LChanged := true; end; if FAlpha <> ValAlpha then begin FAlpha := ValAlpha; if FAlpha < 0 then FAlpha := 0; if FAlpha > 1 then FAlpha := 1; LChanged := true; end; if LChanged then begin if FColorBitmap <> nil then FreeAndNil(FColorBitmap); if FColorBox <> nil then FColorBox.Color := HSLtoRGB(FHue, FSat, FLum) and $FFFFFF or (round(FAlpha * $FF) shl 24); Repaint; end; end; procedure TColorQuad.MouseMove(Shift: TShiftState; X, Y: Single); var LLum, LSat: Single; begin inherited; if FPressed then begin LLum := Lum; LSat := Sat; if Height <> 0 then LLum := 1 - ((Y) / (Height)); if Width <> 0 then LSat := ((X) / (Width)); if GetIsTracking then SetColor(Hue, LLum, LSat, Alpha) else // will not fire OnChange event. MouseUp though will change the value when gets fired PreviewColor(Hue, LLum, LSat, Alpha); end; end; procedure TColorQuad.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var LLum, LSat: Single; begin inherited; LLum := Lum; LSat := Sat; if Height <> 0 then LLum := 1 - ((Y) / (Height)); if Width <> 0 then LSat := ((X) / (Width)); SetColor(Hue, LLum, LSat, Alpha); end; procedure TColorQuad.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FColorBox) then ColorBox := nil; end; procedure TColorQuad.Paint; var i, j: Integer; R: TRectF; H, S, L, A: Single; begin H := Hue; S := Sat; L := Lum; A := Alpha; if FColorBitmap = nil then begin FColorBitmap := TBitmap.Create(Trunc(Width), Trunc(Height)); if FColorBitmap <> nil then begin for i := 0 to FColorBitmap.Width - 1 do begin for j := 0 to FColorBitmap.Height - 1 do begin FColorBitmap.Scanline[j][i] := CorrectColor(HSLtoRGB(H, i / FColorBitmap.Width, (1 - (j / FColorBitmap.Height)))); {$IFDEF FPC_BIG_ENDIAN} ReverseBytes(@FColorBitmap.Scanline[j][i], 4); {$ENDIF} end; end; end; end; if FColorBitmap <> nil then Canvas.DrawBitmap(FColorBitmap, RectF(0, 0, FColorBitmap.Width, FColorBitmap.Height), RectF(0, 0, Width, Height), AbsoluteOpacity); { current } R := RectF(S * (Width), (1 - L) * (Height), S * (Width), (1 - L) * (Height)); InflateRect(R, colorPickSize / 2, colorPickSize / 2); Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.StrokeThickness := 1; Canvas.Stroke.Color := $FF000000; Canvas.DrawEllipse(R, AbsoluteOpacity); InflateRect(R, -1, -1); Canvas.Stroke.Color := $FFFFFFFF; Canvas.DrawEllipse(R, AbsoluteOpacity); InflateRect(R, -1, -1); Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := HSLtoRGB(H, S, L); Canvas.FillEllipse(R, AbsoluteOpacity); end; procedure TColorQuad.SetAlpha(const Value: Single); begin if FAlpha <> Value then begin FAlpha := Value; if FAlpha < 0 then FAlpha := 0; if FAlpha > 1 then FAlpha := 1; if FColorBox <> nil then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); if (not FPressed) and Assigned(FOnChange) then FOnChange(Self); end; end; procedure TColorQuad.SetHue(const Value: Single); begin if FHue <> Value then begin FHue := Value; if FHue < 0 then FHue := 0; if FHue > 1 then FHue := 1; if FColorBitmap <> nil then FreeAndNil(FColorBitmap); if FColorBox <> nil then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); if (not FPressed) and Assigned(FOnChange) then FOnChange(Self); Repaint; end; end; procedure TColorQuad.SetLum(const Value: Single); begin if FLum <> Value then begin FLum := Value; if FLum < 0 then FLum := 0; if FLum > 1 then FLum := 1; if FColorBox <> nil then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); if (not FPressed) and Assigned(FOnChange) then FOnChange(Self); Repaint; end; end; procedure TColorQuad.SetSat(const Value: Single); begin if FSat <> Value then begin FSat := Value; if FSat < 0 then FSat := 0; if FSat > 1 then FSat := 1; if FColorBox <> nil then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); if (not FPressed) and Assigned(FOnChange) then FOnChange(Self); Repaint; end; end; procedure TColorQuad.SetColor(const ValHue, ValLum, ValSat, ValAlpha: Single); begin if FPendingChanges then Exit; FPendingChanges := true; FHue := ValHue; if FHue < 0 then FHue := 0; if FHue > 1 then FHue := 1; FLum := ValLum; if FLum < 0 then FLum := 0; if FLum > 1 then FLum := 1; FSat := ValSat; if FSat < 0 then FSat := 0; if FSat > 1 then FSat := 1; FAlpha := ValAlpha; if FAlpha < 0 then FAlpha := 0; if FAlpha > 1 then FAlpha := 1; if FColorBitmap <> nil then FreeAndNil(FColorBitmap); if FColorBox <> nil then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); if Assigned(FOnChange) then FOnChange(Self); Repaint; FPendingChanges := false; end; procedure TColorQuad.SetColorBox(const Value: TColorBox); begin if FColorBox <> Value then begin FColorBox := Value; if (FColorBox <> nil) and (not FPressed) then FColorBox.Color := HSLtoRGB(Hue, Sat, Lum) and $FFFFFF or (round(Alpha * $FF) shl 24); end; end; { TColorPicker } constructor TColorPicker.Create(AOwner: TComponent); begin inherited; AutoCapture := True; end; destructor TColorPicker.Destroy; begin if (FHueBitmap <> nil) then FreeAndNil(FHueBitmap); inherited; end; procedure TColorPicker.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FColorQuad) then ColorQuad := nil; end; function TColorPicker.GetAbsoluteRect: TRectF; begin Result := inherited GetAbsoluteRect; InflateRect(Result, 0, colorPickSize / 2); end; function TColorPicker.PointInObject(X, Y: Single): Boolean; var P: TPointF; begin Result := False; P := AbsoluteToLocal(PointF(X, Y)); if (P.X > 0) and (P.X < Width) and (P.Y > -colorPickSize / 2) and (P.Y < Height + colorPickSize / 2) then begin Result := True; end; end; procedure TColorPicker.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; if FPressed then begin if Height <> 0 then Hue := ((Y) / (Height)); end; end; procedure TColorPicker.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if FPressed then MouseMove([ssLeft], X, Y); inherited; end; procedure TColorPicker.Paint; var i, j: Integer; R: TRectF; begin if FHueBitmap = nil then begin FHueBitmap := TBitmap.Create(Trunc(Width), Trunc(Height)); if FHueBitmap <> nil then begin for j := 0 to FHueBitmap.Height - 1 do begin for i := 0 to FHueBitmap.Width - 1 do begin FHueBitmap.Scanline[j][i] := CorrectColor(HSLtoRGB(j / FHueBitmap.Height, 0.9, 0.5)); {$IFDEF FPC_BIG_ENDIAN} ReverseBytes(@FHueBitmap.Scanline[j][i], 4); {$ENDIF} end; end; end; end; if FHueBitmap <> nil then Canvas.DrawBitmap(FHueBitmap, RectF(0, 0, FHueBitmap.Width, FHueBitmap.Height), RectF(0, 0, Width, Height), AbsoluteOpacity); { hue pos } R := RectF(Width / 2, FHue * (Height), Width / 2, FHue * (Height)); InflateRect(R, colorPickSize / 2, colorPickSize / 2); // OffsetRect(R, 01, StrokeThickness); Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.StrokeThickness := 1; Canvas.Stroke.Color := $FF000000; Canvas.DrawEllipse(R, AbsoluteOpacity); InflateRect(R, -1, -1); Canvas.Stroke.Color := $FFFFFFFF; Canvas.DrawEllipse(R, AbsoluteOpacity); InflateRect(R, -1, -1); Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := HSLtoRGB(Hue, 0.9, 0.5); Canvas.FillEllipse(R, AbsoluteOpacity); end; function TColorPicker.GetColor: TAlphaColor; begin Result := HSLtoRGB(Hue, 1, 0.5) end; procedure TColorPicker.SetColor(const Value: TAlphaColor); var H, S, L: Single; SaveChange: TNotifyEvent; begin RGBtoHSL(Value, H, S, L); Hue := H; if FColorQuad <> nil then begin FColorQuad.Alpha := TAlphaColorRec(Value).a / $FF; FColorQuad.Hue := H; FColorQuad.Sat := S; FColorQuad.Lum := L; end; end; procedure TColorPicker.SetHue(const Value: Single); begin if FHue <> Value then begin FHue := Value; if FHue < 0 then FHue := 0; if FHue > 1 then FHue := 1; if FColorQuad <> nil then FColorQuad.Hue := FHue; Repaint; end; end; { TGradientEdit } constructor TGradientEdit.Create(AOwner: TComponent); begin inherited; FGradient := TGradient.Create; FGradient.OnChanged := DoChanged; Width := 200; Height := 20; AutoCapture := True; SetAcceptsControls(False); end; destructor TGradientEdit.Destroy; begin if FBitmap <> nil then FreeAndNil(FBitmap); FGradient.Free; inherited; end; function TGradientEdit.GetPointRect(const Point: Integer): TRectF; begin if (Point >= 0) and (Point < FGradient.Points.Count) then with FGradient do begin Result := RectF(0 + colorPickSize + (Points[Point].Offset * (Width - ((0 + colorPickSize) * 2))), Height - 0 - colorPickSize, 0 + colorPickSize + (Points[Point].Offset * (Width - ((0 + colorPickSize) * 2))), Height - 0); InflateRect(Result, colorPickSize / 2, 0); end else Result := RectF(0, 0, 0, 0); end; procedure TGradientEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var NewOffset: Single; NewColor: TAlphaColor; i: Integer; begin inherited; FMoving := False; if Button = TMouseButton.mbLeft then begin { select point } for i := 0 to FGradient.Points.Count - 1 do if PointInRect(PointF(X, Y), GetPointRect(i)) then begin CurrentPoint := i; if Assigned(OnSelectPoint) then OnSelectPoint(Self); FMoving := True; Repaint; Exit; end; { add new point } if (Y > 0) and (Y < Height - 0 - colorPickSize) then begin NewOffset := ((X - 0 - colorPickSize) / (Width - ((0 + colorPickSize) * 2))); if NewOffset < 0 then NewOffset := 0; if NewOffset > 1 then NewOffset := 1; NewColor := FGradient.InterpolateColor(NewOffset); for i := 1 to FGradient.Points.Count - 1 do if NewOffset < FGradient.Points[i].Offset then with TGradientPoint(FGradient.Points.Add) do begin Index := i; CurrentPoint := Index; IntColor := NewColor; Offset := NewOffset; Repaint; DoChanged(Self); Break; end; end; end; end; procedure TGradientEdit.MouseMove(Shift: TShiftState; X, Y: Single); begin inherited; if ssLeft in Shift then begin if FMoving then begin FCurrentPointInvisible := ((Y < -10) or (Y > Height + 10)) and (FGradient.Points.Count > 1) and (CurrentPoint <> 0) and (CurrentPoint <> FGradient.Points.Count - 1); { move } FGradient.Points[CurrentPoint].Offset := ((X - 0 - colorPickSize) / (Width - ((0 + colorPickSize) * 2))); if FGradient.Points[CurrentPoint].Offset < 0 then FGradient.Points[CurrentPoint].Offset := 0; if FGradient.Points[CurrentPoint].Offset > 1 then FGradient.Points[CurrentPoint].Offset := 1; { move right } if CurrentPoint < FGradient.Points.Count - 1 then if FGradient.Points[CurrentPoint].Offset > FGradient.Points [CurrentPoint + 1].Offset then begin FGradient.Points[CurrentPoint].Index := FGradient.Points[CurrentPoint] .Index + 1; CurrentPoint := CurrentPoint + 1; end; { move left } if CurrentPoint > 0 then if FGradient.Points[CurrentPoint].Offset < FGradient.Points [CurrentPoint - 1].Offset then begin FGradient.Points[CurrentPoint].Index := FGradient.Points[CurrentPoint] .Index - 1; CurrentPoint := CurrentPoint - 1; end; Repaint; DoChanged(Self); end; end; end; procedure TGradientEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; FCurrentPointInvisible := False; if FMoving then begin { delete } if (Y > Height + 10) and (FGradient.Points.Count > 2) then begin FGradient.Points.Delete(CurrentPoint); CurrentPoint := CurrentPoint - 1; if CurrentPoint < 0 then CurrentPoint := 0; Repaint; DoChanged(Self); FMoving := False; Exit; end; end; FMoving := False; end; procedure TGradientEdit.Paint; procedure DrawBackground; var GradientRect: TRectF; begin GradientRect := RectF(colorPickSize, 0, Width - colorPickSize, Height - colorPickSize); FillChessBoardBrush(Canvas.Fill.Bitmap, 10); Canvas.Fill.Kind := TBrushKind.bkBitmap; Canvas.FillRect(GradientRect, 0, 0, AllCorners, AbsoluteOpacity); end; procedure RotateGradient(AGradient : TGradient; const ARadian: Single); var CosRadian: Extended; SinRadian: Extended; X: Single; Y: Single; Koef: Single; begin CosRadian := Cos(ARadian); SinRadian := Sin(ARadian); if (CosRadian <> 0) and (Abs(1 / CosRadian) >= 1) and (Abs(1 / CosRadian) <= 1.42) then X := Abs(1 / CosRadian) else X := 1; if (SinRadian <> 0) and (Abs(1 / SinRadian) >= 1) and (Abs(1 / SinRadian) <= 1.42) then Y := Abs(1 / SinRadian) else Y := 1; Koef := Max(X, Y); Koef := Koef * 0.5; AGradient.StartPosition.Point := PointF(0.5 - (CosRadian * Koef), 0.5 + (SinRadian * Koef)); AGradient.StopPosition.Point := PointF(0.5 + (CosRadian * Koef), 0.5 - (SinRadian * Koef)); end; procedure DrawGradient; var GradientRect: TRectF; begin GradientRect := RectF(colorPickSize, 0, Width - colorPickSize, Height - colorPickSize); Canvas.Stroke.Kind := TBrushKind.bkNone; Canvas.Fill.Kind := TBrushKind.bkGradient; Canvas.Fill.Gradient.Assign(FGradient); RotateGradient(Canvas.Fill.Gradient, 0); Canvas.FillRect(GradientRect, 0, 0, AllCorners, AbsoluteOpacity); end; procedure DrawPoints; var I: Integer; PointRect: TRectF; begin Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.StrokeThickness := 1; for I := 0 to FGradient.Points.Count - 1 do begin if FCurrentPointInvisible and (I = CurrentPoint) then Continue; PointRect := GetPointRect(I); InflateRect(PointRect, -1, -1); Canvas.Stroke.Color := $FF757575; Canvas.Fill.Color := FGradient.Points[I].IntColor; Canvas.FillEllipse(PointRect, AbsoluteOpacity); Canvas.DrawEllipse(PointRect, AbsoluteOpacity); if CurrentPoint = I then begin InflateRect(PointRect, 1, 1); Canvas.Stroke.Color := TAlphaColorRec.White; Canvas.DrawEllipse(PointRect, AbsoluteOpacity); end; end; end; begin DrawBackground; DrawGradient; DrawPoints; end; procedure TGradientEdit.SetGradient(const Value: TGradient); begin FGradient.Assign(Value); end; procedure TGradientEdit.DoChanged(Sender: TObject); begin if Assigned(FOnChange) then FOnChange(Self); UpdateGradient; end; procedure TGradientEdit.SetCurrentPoint(const Value: Integer); begin if FCurrentPoint <> Value then begin FCurrentPoint := Value; if Assigned(OnSelectPoint) then OnSelectPoint(Self); if (FColorPicker <> nil) and (CurrentPoint >= 0) then FColorPicker.Color := Gradient.Points[CurrentPoint].IntColor; end; end; procedure TGradientEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FColorPicker) then ColorPicker := nil; end; procedure TGradientEdit.SetColorPicker(const Value: TColorPicker); begin FColorPicker := Value; if (FColorPicker <> nil) and (CurrentPoint >= 0) then FColorPicker.Color := Gradient.Points[CurrentPoint].IntColor; end; procedure TGradientEdit.UpdateGradient; begin if (FColorPicker <> nil) and (CurrentPoint >= 0) then FColorPicker.Color := Gradient.Points[CurrentPoint].IntColor; end; { TColorPanel } constructor TColorPanel.Create(AOwner: TComponent); begin inherited; FUseAlpha := True; Width := 150; Height := 150; FAlphaTrack := TAlphaTrackBar.Create(Self); FAlphaTrack.Parent := Self; FAlphaTrack.Align := TAlignLayout.alBottom; FAlphaTrack.Stored := False; FAlphaTrack.Locked := True; FAlphaTrack.Padding.Rect := RectF(0, 0, 15, 0); FAlphaTrack.Height := 15; FAlphaTrack.DisableFocusEffect := True; FAlphaTrack.OnChange := DoAlphaChange; FHueTrack := THueTrackBar.Create(Self); FHueTrack.Parent := Self; FHueTrack.Align := TAlignLayout.alRight; FHueTrack.Stored := False; FHueTrack.Locked := True; FHueTrack.Padding.Rect := RectF(0, 0, 0, 0); FHueTrack.Orientation := TOrientation.orVertical; FHueTrack.Width := 15; FHueTrack.DisableFocusEffect := True; FHueTrack.OnChange := DoHueChange; FColorQuad := TColorQuad.Create(Self); FColorQuad.Parent := Self; FColorQuad.Align := TAlignLayout.alClient; FColorQuad.Stored := False; FColorQuad.Locked := True; FColorQuad.Padding.Rect := RectF(5, 5, 3, 3); FColorQuad.OnChange := DoQuadChange; Color := TAlphaColors.White; SetAcceptsControls(False); end; destructor TColorPanel.Destroy; begin inherited; end; procedure TColorPanel.DoAlphaChange(Sender: TObject); begin FColorQuad.Alpha := FAlphaTrack.Value; end; procedure TColorPanel.DoHueChange(Sender: TObject); begin FColorQuad.Hue := FHueTrack.Value; end; procedure TColorPanel.DoQuadChange(Sender: TObject); begin if FColorBox <> nil then FColorBox.Color := Color; if Assigned(OnChange) then OnChange(Self); end; function TColorPanel.GetColor: TAlphaColor; begin Result := MakeColor(HSLtoRGB(FColorQuad.Hue, FColorQuad.Sat, FColorQuad.Lum), FColorQuad.Alpha); end; procedure TColorPanel.Loaded; begin inherited; Color := Color; end; procedure TColorPanel.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FColorBox) then ColorBox := nil; end; procedure TColorPanel.SetColor(const Value: TAlphaColor); var H, S, L: Single; C: TAlphaColor; SaveOnChange: TNotifyEvent; SavedOnQuadChange, SavedOnHueChanged, SavedOnAlphaChanged : TNotifyEvent; begin if Value <> Color then begin SaveOnChange := FOnChange; SavedOnQuadChange := FColorQuad.OnChange; SavedOnHueChanged := FHueTrack.OnChange; SavedOnAlphaChanged := FAlphaTrack.OnChange; FOnChange := nil; FColorQuad.OnChange := nil; FHueTrack.OnChange := nil; FAlphaTrack.OnChange := nil; C := Value; RGBtoHSL(C, H, S, L); FColorQuad.Lum := L; FColorQuad.Sat := S; FColorQuad.Hue := H; FHueTrack.Value := H; FAlphaTrack.Value := TAlphaColorRec(C).a / $FF; if not(csLoading in ComponentState) then DoQuadChange(Self); FOnChange := SaveOnChange; FColorQuad.OnChange := SavedOnQuadChange; FHueTrack.OnChange := SavedOnHueChanged; FAlphaTrack.OnChange := SavedOnAlphaChanged; end; end; procedure TColorPanel.SetColorBox(const Value: TColorBox); begin if FColorBox <> Value then begin FColorBox := Value; if FColorBox <> nil then FColorBox.Color := Color; end; end; procedure TColorPanel.SetUseAlpha(const Value: Boolean); begin if FUseAlpha <> Value then begin FUseAlpha := Value; FAlphaTrack.Visible := FUseAlpha; end; end; { TComboColorBox } constructor TComboColorBox.Create(AOwner: TComponent); begin inherited; Width := 60; Height := 22; CanFocus := True; AutoCapture := True; FPopup := TPopup.Create(Self); FPopup.StyleLookup := 'combopopupstyle'; FPopup.PlacementTarget := Self; FPopup.StaysOpen := False; FPopup.Stored := False; FPopup.Parent := Self; FPopup.Locked := True; FPopup.DragWithParent := True; // FPopup.DesignVisible := True; RAID 283593 FPopup.DesignVisible:= False; FPopup.Width := 240; FPopup.Height := 160; FPopup.Margins.Rect := RectF(5, 5, 5, 5); FColorBox := TColorBox.Create(nil); FColorBox.Width := 50; FColorBox.Parent := FPopup; FColorBox.Stored := False; FColorBox.Align := TAlignLayout.alRight; FColorBox.Padding.Rect := RectF(15, 70, 15, 30); FColorText := TEdit.Create(Self); FColorText.Parent := FPopup; FColorText.Stored := False; FColorText.Locked := True; FColorText.FilterChar := '#0123456789abcdefABCDEF'; FColorText.BoundsRect := RectF(160, 20, 160 + 70, 20 + 22); // FColorText.Anchors := [TAnchorKind.akTop, TAnchorKind.akRight]; FColorText.DisableFocusEffect := True; FColorText.OnChange := DoTextChange; FColorPanel := TColorPanel.Create(Self); FColorPanel.Parent := FPopup; FColorPanel.Stored := False; FColorPanel.DisableFocusEffect := True; FColorPanel.Align := TAlignLayout.alClient; FColorPanel.OnChange := DoColorChange; FColorPanel.ColorBox := FColorBox; SetAcceptsControls(False); end; destructor TComboColorBox.Destroy; begin FreeAndNil(FColorBox); inherited; end; procedure TComboColorBox.DoTextChange(Sender: TObject); var C: TAlphaColor; begin try C := Color; Color := StringToAlphaColor(FColorText.Text); except Color := C; end; end; procedure TComboColorBox.DoColorChange(Sender: TObject); begin FColorText.Text := AlphaColorToString(Color); Repaint; if Assigned(FOnChange) then FOnChange(Self); end; procedure TComboColorBox.DropDown; var i: Integer; begin if not FPopup.IsOpen then begin FPopup.Placement := FPlacement; FColorPanel.ApplyStyleLookup; FPopup.IsOpen := True; end else begin FPopup.IsOpen := False; end; end; procedure TComboColorBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; if (Button = TMouseButton.mbLeft) then begin DropDown; end; end; procedure TComboColorBox.ChangeParent; begin inherited; end; function TComboColorBox.GetValue: TAlphaColor; begin Result := FColorPanel.Color end; procedure TComboColorBox.SetValue(const Value: TAlphaColor); begin FColorPanel.Color := Value; end; procedure TComboColorBox.ApplyStyle; var T: TFmxObject; begin inherited; T := FindStyleResource('Content'); if (T <> nil) and (T is TContent) then begin TContent(T).OnPaint := DoContentPaint; end; end; procedure TComboColorBox.DoContentPaint(Sender: TObject; Canvas: TCanvas; const ARect: TRectF); var R: TRectF; State: TCanvasSaveState; i, j: Integer; begin R := ARect; R.Inflate(-0.5 - 2, -0.5 - 2); R.Offset(0.5, 0.5); { draw back } State := Canvas.SaveState; try Canvas.IntersectClipRect(R); Canvas.Stroke.Kind := TBrushKind.bkNone; Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := $FFFFFFFF; Canvas.FillRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.Fill.Color := $FFD3D3D3; for i := 0 to Trunc(RectWidth(R) / 5) + 1 do for j := 0 to Trunc(RectHeight(R) / 5) + 1 do begin if odd(i + j) then begin Canvas.FillRect(RectF(i * 5, j * 5, (i + 1) * 5, (j + 1) * 5), 0, 0, AllCorners, AbsoluteOpacity); end; end; { color } Canvas.Fill.Kind := TBrushKind.bkSolid; Canvas.Fill.Color := Color; Canvas.FillRect(R, 0, 0, AllCorners, AbsoluteOpacity); Canvas.Stroke.Color := TAlphaColors.Black; Canvas.Stroke.Kind := TBrushKind.bkSolid; Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity); finally Canvas.RestoreState(State); end; end; function TComboColorBox.GetUseAlpha: Boolean; begin Result := FColorPanel.UseAlpha; end; procedure TComboColorBox.SetUseAlpha(const Value: Boolean); begin FColorPanel.UseAlpha := Value; end; function TComboColorBox.GetData: Variant; begin Result := Color; end; function TComboColorBox.GetDefaultStyleLookupName: WideString; begin Result := 'comboboxstyle'; end; procedure TComboColorBox.SetData(const Value: Variant); begin if VarIsEvent(Value) then OnChange := VariantToEvent(Value) else if VarIsStr(Value) then Color := StringToAlphaColor(Value); { else if VarIsOrdinal(Value) then Color := Value;} end; { TColorButton } constructor TColorButton.Create(AOwner: TComponent); begin inherited; FAutoTranslate := False; FColor := $FF000000; end; destructor TColorButton.Destroy; begin inherited; end; procedure TColorButton.ApplyStyle; var O: TFmxObject; begin inherited; O := FindStyleResource('fill'); if (O <> nil) and (O is TShape) then begin FFill := TShape(O); FFill.Fill.Color := FColor; end; end; procedure TColorButton.FreeStyle; begin inherited; FFill := nil; end; procedure TColorButton.SetColor(const Value: TAlphaColor); begin FColor := Value; if FFill <> nil then FFill.Fill.Color := FColor; if not(csLoading in ComponentState) then if Assigned(FOnChange) then FOnChange(Self); end; function SwapColor(const C: TAlphaColor): TAlphaColor; begin Result := C; TAlphaColorRec(Result).R := TAlphaColorRec(C).B; TAlphaColorRec(Result).B := TAlphaColorRec(C).R; end; procedure TColorButton.Click; begin inherited; { C := TColorDialog.Create(nil); try C.Color := SwapColor(StrToColor(FColor)) and $FFFFFF; if C.Execute then Color := ColorToStr($FF000000 or SwapColor(C.Color)); finally C.Free; end; } end; type THackListBox = class(TListBox); THackListBoxItem = class(TListBoxItem); const Colors: array [0 .. 147] of TIdentMapEntry = ((Value: Integer($FFF0F8FF); Name: 'Aliceblue'), (Value: Integer($FFFAEBD7); Name: 'Antiquewhite'), (Value: Integer($FF00FFFF); Name: 'Aqua'), (Value: Integer($FF7FFFD4); Name: 'Aquamarine'), (Value: Integer($FFF0FFFF); Name: 'Azure'), (Value: Integer($FFF5F5DC); Name: 'Beige'), (Value: Integer($FFFFE4C4); Name: 'Bisque'), (Value: Integer($FF000000); Name: 'Black';), (Value: Integer($FFFFEBCD); Name: 'Blanchedalmond'), (Value: Integer($FF0000FF); Name: 'Blue'), (Value: Integer($FF8A2BE2); Name: 'Blueviolet'), (Value: Integer($FFA52A2A); Name: 'Brown'), (Value: Integer($FFDEB887); Name: 'Burlywood'), (Value: Integer($FF5F9EA0); Name: 'Cadetblue'), (Value: Integer($FF7FFF00); Name: 'Chartreuse'), (Value: Integer($FFD2691E); Name: 'Chocolate'), (Value: Integer($FFFF7F50); Name: 'Coral'), (Value: Integer($FF6495ED); Name: 'Cornflowerblue'), (Value: Integer($FFFFF8DC); Name: 'Cornsilk'), (Value: Integer($FFDC143C); Name: 'Crimson'), (Value: Integer($FF00FFFF); Name: 'Cyan'), (Value: Integer($FF00008B); Name: 'Darkblue'), (Value: Integer($FF008B8B); Name: 'Darkcyan'), (Value: Integer($FFB8860B); Name: 'Darkgoldenrod'), (Value: Integer($FFA9A9A9); Name: 'Darkgray'), (Value: Integer($FF006400); Name: 'Darkgreen'), (Value: Integer($FFA9A9A9); Name: 'Darkgrey'), (Value: Integer($FFBDB76B); Name: 'Darkkhaki'), (Value: Integer($FF8B008B); Name: 'Darkmagenta'), (Value: Integer($FF556B2F); Name: 'Darkolivegreen'), (Value: Integer($FFFF8C00); Name: 'Darkorange'), (Value: Integer($FF9932CC); Name: 'Darkorchid'), (Value: Integer($FF8B0000); Name: 'Darkred'), (Value: Integer($FFE9967A); Name: 'Darksalmon'), (Value: Integer($FF8FBC8F); Name: 'Darkseagreen'), (Value: Integer($FF483D8B); Name: 'Darkslateblue'), (Value: Integer($FF2F4F4F); Name: 'Darkslategray'), (Value: Integer($FF2F4F4F); Name: 'Darkslategrey'), (Value: Integer($FF00CED1); Name: 'Darkturquoise'), (Value: Integer($FF9400D3); Name: 'Darkviolet'), (Value: Integer($FFFF1493); Name: 'Deeppink'), (Value: Integer($FF00BFFF); Name: 'Deepskyblue'), (Value: Integer($FF696969); Name: 'Dimgray'), (Value: Integer($FF696969); Name: 'Dimgrey'), (Value: Integer($FF1E90FF); Name: 'Dodgerblue'), (Value: Integer($FFB22222); Name: 'Firebrick'), (Value: Integer($FFFFFAF0); Name: 'Floralwhite'), (Value: Integer($FF228B22); Name: 'Forestgreen'), (Value: Integer($FFFF00FF); Name: 'Fuchsia'), (Value: Integer($FFDCDCDC); Name: 'Gainsboro'), (Value: Integer($FFF8F8FF); Name: 'Ghostwhite'), (Value: Integer($FFFFD700); Name: 'Gold'), (Value: Integer($FFDAA520); Name: 'Goldenrod'), (Value: Integer($FF808080); Name: 'Gray'), (Value: Integer($FF008000); Name: 'Green'), (Value: Integer($FFADFF2F); Name: 'Greenyellow'), (Value: Integer($FF808080); Name: 'Grey'), (Value: Integer($FFF0FFF0); Name: 'Honeydew'), (Value: Integer($FFFF69B4); Name: 'Hotpink'), (Value: Integer($FFCD5C5C); Name: 'Indianred'), (Value: Integer($FF4B0082); Name: 'Indigo'), (Value: Integer($FFFFFFF0); Name: 'Ivory'), (Value: Integer($FFF0E68C); Name: 'Khaki'), (Value: Integer($FFE6E6FA); Name: 'Lavender'), (Value: Integer($FFFFF0F5); Name: 'Lavenderblush'), (Value: Integer($FF7CFC00); Name: 'Lawngreen'), (Value: Integer($FFFFFACD); Name: 'Lemonchiffon'), (Value: Integer($FFADD8E6); Name: 'Lightblue'), (Value: Integer($FFF08080); Name: 'Lightcoral'), (Value: Integer($FFE0FFFF); Name: 'Lightcyan'), (Value: Integer($FFFAFAD2); Name: 'Lightgoldenrodyellow'), (Value: Integer($FFD3D3D3); Name: 'Lightgray'), (Value: Integer($FF90EE90); Name: 'Lightgreen'), (Value: Integer($FFD3D3D3); Name: 'Lightgrey'), (Value: Integer($FFFFB6C1); Name: 'Lightpink'), (Value: Integer($FFFFA07A); Name: 'Lightsalmon'), (Value: Integer($FF20B2AA); Name: 'Lightseagreen'), (Value: Integer($FF87CEFA); Name: 'Lightskyblue'), (Value: Integer($FF778899); Name: 'Lightslategray'), (Value: Integer($FF778899); Name: 'Lightslategrey'), (Value: Integer($FFB0C4DE); Name: 'Lightsteelblue'), (Value: Integer($FFFFFFE0); Name: 'Lightyellow'), (Value: Integer($FF00FF00); Name: 'Lime'), (Value: Integer($FF32CD32); Name: 'Limegreen'), (Value: Integer($FFFAF0E6); Name: 'Linen'), (Value: Integer($FFFF00FF); Name: 'Magenta'), (Value: Integer($FF800000); Name: 'Maroon'), (Value: Integer($FF66CDAA); Name: 'Mediumaquamarine'), (Value: Integer($FF0000CD); Name: 'Mediumblue'), (Value: Integer($FFBA55D3); Name: 'Mediumorchid'), (Value: Integer($FF9370DB); Name: 'Mediumpurple'), (Value: Integer($FF3CB371); Name: 'Mediumseagreen'), (Value: Integer($FF7B68EE); Name: 'Mediumslateblue'), (Value: Integer($FF00FA9A); Name: 'Mediumspringgreen'), (Value: Integer($FF48D1CC); Name: 'Mediumturquoise'), (Value: Integer($FFC71585); Name: 'Mediumvioletred'), (Value: Integer($FF191970); Name: 'Midnightblue'), (Value: Integer($FFF5FFFA); Name: 'Mintcream'), (Value: Integer($FFFFE4E1); Name: 'Mistyrose'), (Value: Integer($FFFFE4B5); Name: 'Moccasin'), (Value: Integer($FFFFDEAD); Name: 'Navajowhite'), (Value: Integer($FF000080); Name: 'Navy'), (Value: Integer($FFFDF5E6); Name: 'Oldlace'), (Value: Integer($FF808000); Name: 'Olive'), (Value: Integer($FF6B8E23); Name: 'Olivedrab'), (Value: Integer($FFFFA500); Name: 'Orange'), (Value: Integer($FFFF4500); Name: 'Orangered'), (Value: Integer($FFDA70D6); Name: 'Orchid'), (Value: Integer($FFEEE8AA); Name: 'Palegoldenrod'), (Value: Integer($FF98FB98); Name: 'Palegreen'), (Value: Integer($FFAFEEEE); Name: 'Paleturquoise'), (Value: Integer($FFDB7093); Name: 'Palevioletred'), (Value: Integer($FFFFEFD5); Name: 'Papayawhip'), (Value: Integer($FFFFDAB9); Name: 'Peachpuff'), (Value: Integer($FFCD853F); Name: 'Peru'), (Value: Integer($FFFFC0CB); Name: 'Pink'), (Value: Integer($FFDDA0DD); Name: 'Plum'), (Value: Integer($FFB0E0E6); Name: 'Powderblue'), (Value: Integer($FF800080); Name: 'Purple'), (Value: Integer($FFFF0000); Name: 'Red'), (Value: Integer($FFBC8F8F); Name: 'Rosybrown'), (Value: Integer($FF4169E1); Name: 'Royalblue'), (Value: Integer($FF8B4513); Name: 'Saddlebrown'), (Value: Integer($FFFA8072); Name: 'Salmon'), (Value: Integer($FFF4A460); Name: 'Sandybrown'), (Value: Integer($FF2E8B57); Name: 'Seagreen'), (Value: Integer($FFFFF5EE); Name: 'Seashell'), (Value: Integer($FFA0522D); Name: 'Sienna'), (Value: Integer($FFC0C0C0); Name: 'Silver'), (Value: Integer($FF87CEEB); Name: 'Skyblue'), (Value: Integer($FF6A5ACD); Name: 'Slateblue'), (Value: Integer($FF708090); Name: 'Slategray'), (Value: Integer($FF708090); Name: 'Slategrey'), (Value: Integer($FFFFFAFA); Name: 'Snow'), (Value: Integer($FF00FF7F); Name: 'Springgreen'), (Value: Integer($FF4682B4); Name: 'Steelblue'), (Value: Integer($FFD2B48C); Name: 'Tan'), (Value: Integer($FF008080); Name: 'Teal'), (Value: Integer($FFD8BFD8); Name: 'Thistle'), (Value: Integer($FFFF6347); Name: 'Tomato'), (Value: Integer($FF40E0D0); Name: 'Turquoise'), (Value: Integer($FFEE82EE); Name: 'Violet'), (Value: Integer($FFF5DEB3); Name: 'Wheat'), (Value: Integer($FFFFFFFF); Name: 'White'), (Value: Integer($FFF5F5F5); Name: 'Whitesmoke'), (Value: Integer($FFFFFF00); Name: 'Yellow'), (Value: Integer($FF9ACD32); Name: 'Yellowgreen'), (Value: Integer($0); Name: 'Null')); { TColorListBox } constructor TColorListBox.Create(AOwner: TComponent); begin inherited; RebuildList; SetAcceptsControls(False); end; destructor TColorListBox.Destroy; begin inherited; end; procedure TColorListBox.RebuildList; var i, SaveIndex: Integer; Item: TListBoxItem; begin if FUpdating > 0 then Exit; if csDestroying in ComponentState then Exit; BeginUpdate; SaveIndex := ItemIndex; FItemIndex := -1; Clear; for i := 0 to High(Colors) do begin Item := TListBoxItem.Create(nil); Item.Parent := Self; Item.Stored := False; Item.Locked := True; Item.Text := Colors[i].Name; Item.Tag := i; THackListBoxItem(Item).FStyleLookup := 'colorlistboxitemstyle'; Item.OnApplyStyleLookup := DoApplyStyleLookup; end; EndUpdate; FItemIndex := SaveIndex; end; procedure TColorListBox.SetColor(const Value: TAlphaColor); var i: Integer; begin for i := 0 to High(Colors) do if TAlphaColor(Colors[i].Value) = Value then begin ItemIndex := i; Break; end; end; procedure TColorListBox.SetItems(const Value: TWideStrings); begin RebuildList; end; procedure TColorListBox.DoApplyStyleLookup(Sender: TObject); var ColorObj: TFmxObject; Item: TListboxItem; begin ColorObj := TListBoxItem(Sender).FindStyleResource('color'); if ColorObj is TShape then begin TShape(ColorObj).Fill.Color := Colors[TListBoxItem(Sender).Tag].Value; end; end; function TColorListBox.GetColor: TAlphaColor; begin Result := Colors[ItemIndex].Value; end; function TColorListBox.GetDefaultStyleLookupName: WideString; begin Result := 'listboxstyle'; end; { TColorComboBox } constructor TColorComboBox.Create(AOwner: TComponent); begin inherited; RebuildList; SetAcceptsControls(False); end; destructor TColorComboBox.Destroy; begin inherited; end; procedure TColorComboBox.RebuildList; var i, SaveIndex: Integer; Item: TListBoxItem; begin if FUpdating > 0 then Exit; if csDestroying in ComponentState then Exit; BeginUpdate; SaveIndex := FListbox.ItemIndex; THackListBox(FListbox).FItemIndex := -1; Clear; for i := 0 to High(Colors) do begin Item := TListBoxItem.Create(nil); Item.Parent := Self; Item.Stored := False; Item.Locked := True; Item.Text := Colors[i].Name; Item.Tag := i; THackListBoxItem(Item).FStyleLookup := 'colorlistboxitemstyle'; Item.OnApplyStyleLookup := DoApplyStyleLookup; end; EndUpdate; THackListBox(FListbox).FItemIndex := SaveIndex; end; procedure TColorComboBox.SetColor(const Value: TAlphaColor); var i: Integer; begin for i := 0 to High(Colors) do if TAlphaColor(Colors[i].Value) = Value then begin ItemIndex := i; Break; end; end; procedure TColorComboBox.DoApplyStyleLookup(Sender: TObject); var ColorObj: TFmxObject; Item: TListboxItem; begin ColorObj := TListBoxItem(Sender).FindStyleResource('color'); if ColorObj is TShape then begin TShape(ColorObj).Fill.Color := Colors[TListBoxItem(Sender).Tag].Value; end; end; function TColorComboBox.GetColor: TAlphaColor; begin Result := Colors[ItemIndex].Value; end; function TColorComboBox.GetDefaultStyleLookupName: WideString; begin Result := 'comboboxstyle'; end; initialization RegisterFmxClasses([THueTrackBar, TAlphaTrackBar, TBWTrackBar, TColorQuad, TColorPicker, TGradientEdit, TColorBox, TColorPanel, TComboColorBox, TColorButton, TColorComboBox, TColorListBox]); end.
unit uImpFDB_Ferus; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, DB, nxdb, nxseAllEngines, nxsdServerEngine, nxsrServerEngine, nxllTransport, nxptBasePooledTransport, nxtwWinsockTransport, nxllComponent, Grids, DBGrids, IBDatabase, IBCustomDataSet, IBTable, ExtCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxNavigator, nxreRemoteServerEngine; type TForm16 = class(TForm) nxSe: TnxSession; nxDB: TnxDatabase; tCli: TnxTable; nxTCP: TnxWinsockTransport; IBDB: TIBDatabase; tOdin: TIBTable; IBTransaction1: TIBTransaction; tDeb: TnxTable; tMovEst: TnxTable; nxRSE: TnxRemoteServerEngine; Button3: TButton; OpenDlg: TOpenDialog; Label1: TLabel; Label2: TLabel; tDebData: TDateTimeField; tDebCliente: TLongWordField; tDebValor: TCurrencyField; tDebTipo: TByteField; tDebID: TLongWordField; tCliID: TUnsignedAutoIncField; tCliNome: TStringField; tCliEndereco: TStringField; tCliBairro: TStringField; tCliCidade: TStringField; tCliUF: TStringField; tCliCEP: TStringField; tCliSexo: TStringField; tCliObs: TnxMemoField; tCliCpf: TStringField; tCliRg: TStringField; tCliTelefone: TStringField; tCliEmail: TnxMemoField; tCliMinutos: TFloatField; tCliPassaportes: TFloatField; tCliMinutosUsados: TFloatField; tCliMinutosIniciais: TFloatField; tCliIsento: TBooleanField; tCliUsername: TStringField; tCliPai: TStringField; tCliMae: TStringField; tCliSenha: TStringField; tCliUltVisita: TDateTimeField; tCliDebito: TCurrencyField; tCliEscola: TStringField; tCliEscolaHI: TDateTimeField; tCliEscolaHF: TDateTimeField; tCliNickName: TStringField; tCliDataNasc: TDateTimeField; tCliCelular: TStringField; tCliTemDebito: TBooleanField; tCliLimiteDebito: TCurrencyField; tCliFoto: TGraphicField; tCliIncluidoEm: TDateTimeField; tCliAlteradoEm: TDateTimeField; tCliIncluidoPor: TStringField; tCliAlteradoPor: TStringField; tCliTitEleitor: TStringField; tCliFidPontos: TFloatField; tCliFidTotal: TFloatField; tCliFidResg: TFloatField; tCliAniversario: TStringField; tCliCotaImpEspecial: TBooleanField; tCliCotaImpDia: TLongWordField; tCliCotaImpMes: TLongWordField; tCliSemFidelidade: TBooleanField; tCliTemCredito: TBooleanField; tCliNaoGuardarCredito: TBooleanField; tCliPermiteLoginSemCred: TBooleanField; tCliCHorario: TLongWordField; tCliOpCHorario: TByteField; tCliHP1: TLongWordField; tCliHP2: TLongWordField; tCliHP3: TLongWordField; tCliHP4: TLongWordField; tCliHP5: TLongWordField; tCliHP6: TLongWordField; tCliHP7: TLongWordField; tCliInativo: TBooleanField; tCliTipoAcessoPref: TIntegerField; tCliFornecedor: TBooleanField; tCliValorCred: TCurrencyField; tCliRecVer: TLongWordField; tMovEstID: TUnsignedAutoIncField; tMovEstTran: TLongWordField; tMovEstProduto: TLongWordField; tMovEstQuant: TFloatField; tMovEstUnitario: TCurrencyField; tMovEstTotal: TCurrencyField; tMovEstCustoU: TCurrencyField; tMovEstItem: TByteField; tMovEstDesconto: TCurrencyField; tMovEstPago: TCurrencyField; tMovEstPagoPost: TCurrencyField; tMovEstDescPost: TCurrencyField; tMovEstDataHora: TDateTimeField; tMovEstEntrada: TBooleanField; tMovEstCancelado: TBooleanField; tMovEstEstoqueAnt: TFloatField; tMovEstCliente: TLongWordField; tMovEstCaixa: TIntegerField; tMovEstCategoria: TStringField; tMovEstNaoControlaEstoque: TBooleanField; tMovEstITran: TIntegerField; tMovEstTipoTran: TByteField; tMovEstSessao: TIntegerField; tMovEstplusID: TGuidField; tMovEstComissao: TCurrencyField; tMovEstComissaoPerc: TFloatField; tMovEstComissaoLucro: TBooleanField; tMovEstplusTran: TBooleanField; tMovEstPermSemEstoque: TBooleanField; tMovEstFidResgate: TBooleanField; tMovEstFidPontos: TFloatField; procedure Button3Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form16: TForm16; implementation {$R *.dfm} function CodStr(I: Integer): String; begin Result := IntToStr(I); while length(result)<3 do result := '0'+result; end; function SoDig(S: String): String; var i: integer; begin result := ''; for i := 1 to length(S) do if s[i] in ['0'..'9', '-'] then result := result + s[i]; end; function StrToCurrency(S: String): Currency; var Code : Integer; Res: Real; begin Result := 0; S := SoDig(S); if (Length(S)>=3) then begin S := Copy(S, 1, Length(S)-2) + '.' + Copy(S, Length(S)-1, 2); Val(S, Res, Code); if Code=0 then REsult := Res; end; end; procedure TForm16.Button3Click(Sender: TObject); var I: Integer; begin repeat if not OpenDlg.Execute(Handle) then Exit; until SameText(ExtractFileName(OpenDlg.FileName), 'Férus.FDB'); IBDB.DatabaseName := 'localhost:' + OpenDlg.FileName; tDeb.Open; tMovEst.Open; tCli.Active := True; tCli.DeleteRecords; tOdin.Active := True; I := 0; label2.visible := True; while not tOdin.Eof do begin Inc(I); label2.Caption := 'Aguarde ... '+ IntToStr(I) + ' cadastros importados.'; tCli.Insert; tCliUsername.Value := tOdin.FieldByName('Apelido').AsString; if tOdin.FieldByName('Sexo').Value=1 then tCliSexo.Value := 'F' else tCliSexo.Value := 'M'; tCliNome.Value := tOdin.FieldByName('Nome').AsString; tCliRG.Value := tOdin.FieldByName('Documento').AsString; tCliTelefone.Value := tOdin.FieldByName('Telefone').AsString; tCliCelular.Value := tOdin.FieldByName('Celular').AsString; tCliEndereco.Value := tOdin.FieldByName('Endereco').AsString; tCliBairro.Value := tOdin.FieldByName('Bairro').AsString; tCliUF.Value := tOdin.FieldByName('Estado').AsString; tCliCidade.Value := tOdin.FieldByName('Cidade').AsString; tCliCEP.Value := tOdin.FieldByName('CEP').AsString; tCliEmail.Value := tOdin.FieldByName('Email').AsString; tCliDataNasc.Value := tOdin.FieldByName('Nascimento').AsDateTime; tCliIncluidoEm.Value := tOdin.FieldByName('Cadastro').AsDateTime; tCliUltVisita.Value := tOdin.FieldByName('UltimaVisita').AsDateTime; if tOdin.FieldByName('Saldo').AsFloat > 0.009 then tCliValorCred.Value := tOdin.FieldByName('Saldo').AsFloat else if tOdin.FieldByName('Saldo').AsFloat < -0.009 then begin tCli.Post; tCli.Edit; tMovEst.Insert; tMovEstDataHora.Value := Date; tMovEstTotal.Value := tOdin.FieldByName('Saldo').AsFloat * -1; tMovEstDesconto.Value := 0; tMovEstPago.Value := 0; tMovEstCaixa.Value := -1; tMovEstQuant.Value := 1; tMovEstUnitario.Value := -1 * tOdin.FieldByName('Saldo').AsFloat; tMovEstNaoControlaEstoque.Value := True; tMovEstTipoTran.Value := 4; tMovEstEntrada.Value := False; tMovEstCancelado.Value := False; tMovEstCliente.Value := tCliID.Value; tMovEst.Post; tDeb.Insert; tDebCliente.Value := tCliID.Value; tDebData.Value := Date; tDebValor.Value := -1 * tOdin.FieldByName('Saldo').AsFloat; tDebTipo.Value := 1; tDebID.Value := tMovEstID.Value; tDeb.Post; tCliDebito.Value := -1 * tOdin.FieldByName('Saldo').AsFloat; end; tCliMinutos.Value := tOdin.FieldByName('BancoHora').AsFloat / 60; tCliPai.Value := tOdin.FieldByName('NomePai').AsString; tCliMae.Value := tOdin.FieldByName('NomeMae').AsString; tCliEscola.Value := tOdin.FieldByName('Escola').AsString; tCliIsento.Value := False; tCliInativo.Value := False; tCli.Post; tOdin.Next; Application.ProcessMessages; end; ShowMessage('Fim de Importação '+IntToStr(I)+ ' registros importados'); Close; end; end.
unit DomeProtocol; //****************************************************************************** // UNIT NAME DomeProtocol // USED BY PROJECTS RemoteDome, Remote // AUTHOR Yiftah Lipkin // DESCRIPTION Determines the communication protocol with the Dome Deamon // LAST MODIFIED 2003 Jun 10 //****************************************************************************** interface const msgOK = '.'; //Change to '#'roger roger :char = '#'; msgErr = '+'; /////////////////////////////// //Commands sent TO DomeDeamon// /////////////////////////////// // General Form: [xn1] // x [char] Command to Dome // n1 [integer] (optional) commant parameter //DMInit: sent status every N1[/N2] sec when idle[/busy] (<0.1<N1<1, 0.05<N2<1) DmInit = 'i'; //+2 params (N1, N2) NEW DmSendParam = 'j'; //Send DomeFFAz, ZenParkAz, VentsAz DmSendState = 'k'; //Send: [chch int int] DmState DmShState DmPos*10 DmShPos*10 //OpenClose shutter: Optional. Numerical parameter is [0..10 = 10*DomeShFinalPos]. //Without numerical parameter = go until further notice/fully opened/closed DmShOpen = 'l'; DmShClose = 'm'; DmShStop = 'n'; //Move Dome: Numeric parameter is [0..3600 = 10*DomeFinalAz]. //Mandatory for DmMove. Optional for DmMoveL DmMoveR //DmMoveL DmMoveR without numeric parameter = go until further notice DmMoveL = 'o'; //New DmMoveR = 'p'; //New DmMove = 'q'; //New DmStop = 'r'; //Send Dome to a Special Positions DmFFPark = 's'; DmZenPark = 't'; DmVents = 'u'; /////////////////////////////// //Status sent FROM DomeDeamon// /////////////////////////////// // General Form: [Sxyn1 n2] // 'S' Status message prefix // x [char] Shutter State // y [char] Done State // n1 [integer] Round(Shutter position *10) // n2 [integer] Round(Dome Position* 10) //Shutter States DmShIdle = 'a'; DmShOpening = 'b'; DmShClosing = 'c'; DmShStuck = 'd'; DmShUnKnown = 'v'; //Dome States DmIdle = 'e'; DmMovingL = 'f'; DmMovingR = 'g'; DmStuck = 'h'; DmProblem = 'i'; //ONLY for external use. this is equal to internally turning DMStuckInProgress=TRUE. //Validation Key Generator function keygen(par: integer):integer; implementation uses Windows,math; function keygen(par: integer):integer; const a1 = 0.5534; a2 = 0.6469; a3 = 0.1123; a4 = 0.6735; a5 = 0.1903; var UTNow : _SYSTEMTIME; begin GetSystemTime(UTnow); result := round(1000*(a1*power(par,3)+a2*sqrt(par)+a3*sin(UTNow.wDay+a4*UTNow.wHour))); end; end.
unit ASDInput; {<|Модуль библиотеки ASDEngine|>} {<|Дата создания 31.05.07|>} {<|Автор Adler3D|>} {<|e-mail : Adler3D@Mail.ru|>} {<|Дата последнего изменения 31.05.07|>} interface uses Windows, ASDType, ASDInterface, ASDUtils; type TInput = class(TASDObject, IInput) private FKeySet: set of Byte; FOldKeySet: set of Byte; FOnKeyUp: TKeyEvent; FOnKeyDown: TKeyEvent; FOnKeyPress: TKeyPressEvent; function DownKey(Index: Byte): Boolean; function GetOnKeyDown: TKeyEvent; function GetOnKeyPress: TKeyPressEvent; procedure SetOnKeyDown(const Value: TKeyEvent); procedure SetOnKeyPress(const Value: TKeyPressEvent); procedure SetOnKeyUp(const Value: TKeyEvent); function GetOnKeyUp: TKeyEvent; public constructor CreateEx; override; procedure AddKey(Key: Byte); procedure DelKey(Key: Byte); procedure Clear; procedure UpDate; property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown; property OnKeyPress: TKeyPressEvent read FOnKeyPress write FOnKeyPress; property OnKeyUp: TKeyEvent read FOnKeyUp write FOnKeyUp; property Keys[Index: Byte]: Boolean read DownKey; default; end; TMouse = class(TASDObject, IMouse) private FDown, FOldDown: array[TMouseButton] of Boolean; FPosition: TPoint; FVector: array[TMouseButton] of TPoint; FAbsVector: array[TMouseButton] of TPoint; FLastPosition: TPoint; FEnabled: Boolean; FIsMove: Boolean; FOnMouseUp: TMouseEvent; FOnMouseDown: TMouseEvent; FOnMouseMove: TMouseMoveEvent; //FCapure: Boolean; function GetEnabled: Boolean; procedure SetEnabled(Value: Boolean); procedure SetOnMouseDown(const Value: TMouseEvent); procedure SetOnMouseMove(const Value: TMouseMoveEvent); procedure SetOnMouseUp(const Value: TMouseEvent); function GetOnMouseDown: TMouseEvent; function GetOnMouseMove: TMouseMoveEvent; function GetOnMouseUp: TMouseEvent; public constructor CreateEx; override; procedure MouseDown(AButton: TMouseButton; AX, AY: Integer); procedure MouseMove(AX, AY: Integer); procedure MouseUp(AButton: TMouseButton; AX, AY: Integer); function Position: TPoint; function LastPosition: TPoint; function Vector(Button: TMouseButton): TPoint; function AbsVector(Button: TMouseButton): TPoint; function Down(Button: TMouseButton): Boolean; function IsMove: Boolean; procedure Update; //procedure Capture(Value:Boolean); property Enabled: Boolean read FEnabled write FEnabled; property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown; property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove; end; implementation uses ASDEng, Types; { TInput } procedure TInput.AddKey(Key: Byte); begin Include(FKeySet, Key); end; procedure TInput.Clear; begin FKeySet := []; FOldKeySet := []; end; constructor TInput.CreateEx; begin inherited CreateEx; Clear; end; procedure TInput.DelKey(Key: Byte); begin Exclude(FKeySet, Key); end; function TInput.DownKey(Index: Byte): Boolean; begin Result := Index in FKeySet; end; function TInput.GetOnKeyDown: TKeyEvent; begin Result := FOnKeyDown; end; function TInput.GetOnKeyPress: TKeyPressEvent; begin Result := FOnKeyPress; end; function TInput.GetOnKeyUp: TKeyEvent; begin Result := FOnKeyUp; end; procedure TInput.SetOnKeyDown(const Value: TKeyEvent); begin FOnKeyDown := Value; end; procedure TInput.SetOnKeyPress(const Value: TKeyPressEvent); begin FOnKeyPress := Value; end; procedure TInput.SetOnKeyUp(const Value: TKeyEvent); begin FOnKeyUp := Value; end; procedure TInput.UpDate; var I: Byte; F: Boolean; begin for I := 0 to 255 do begin F := I in FKeySet; if (I in FOldKeySet) xor F then if F then begin if Assigned(FOnKeyDown) then FOnKeyDown(I, []); Include(FOldKeySet, I); end else begin if Assigned(FOnKeyUp) then FOnKeyUp(I, []); Exclude(FOldKeySet, I); end; end; end; { TMouse } function TMouse.AbsVector(Button: TMouseButton): TPoint; begin Result := FAbsVector[Button]; end; {procedure TMouse.Capture(Value: Boolean); begin FCapure:=Value; ShowCursor(FCapure); end;} constructor TMouse.CreateEx; begin inherited CreateEx; FLastPosition := Point(0, 0); FPosition := Point(0, 0); FillChar(FVector, SizeOf(FVector), 0); FillChar(FAbsVector, SizeOf(FAbsVector), 0); FillChar(FDown, SizeOf(FDown), 0); FEnabled := True; end; function TMouse.Down(Button: TMouseButton): Boolean; begin Result := FDown[Button]; end; function TMouse.GetEnabled: Boolean; begin Result := FEnabled; end; function TMouse.GetOnMouseDown: TMouseEvent; begin Result := FOnMouseDown; end; function TMouse.GetOnMouseMove: TMouseMoveEvent; begin Result := FOnMouseMove; end; function TMouse.GetOnMouseUp: TMouseEvent; begin Result := FOnMouseUp; end; function TMouse.IsMove: Boolean; begin Result := FIsMove; end; function TMouse.LastPosition: TPoint; begin Result := FLastPosition; end; procedure TMouse.MouseDown(AButton: TMouseButton; AX, AY: Integer); begin if (FEnabled and not FDown[AButton]) then begin FDown[AButton] := True; FPosition := Point(AX, AY); end; end; procedure TMouse.MouseMove(AX, AY: Integer); procedure DoMove(AButton: TMouseButton); begin with FVector[AButton] do begin X := AX - FPosition.X; Y := AY - FPosition.Y; end; with FAbsVector[AButton] do begin X := X + AX - FLastPosition.X; Y := Y + AY - FLastPosition.Y; end; end; begin if not FEnabled then Exit; if (FDown[mbLeft]) then DoMove(mbLeft); if (FDown[mbRight]) then DoMove(mbRight); if (FDown[mbMiddle]) then DoMove(mbMiddle); FLastPosition := Point(AX, AY); //if FCapure then //SetCursorPos(AX,AY); FIsMove := True; end; procedure TMouse.MouseUp(AButton: TMouseButton; AX, AY: Integer); begin if FDown[AButton] and (Enabled) then begin FDown[AButton] := False; FPosition := Point(AX, AY); FVector[AButton] := Point(0, 0); end; end; function TMouse.Position: TPoint; begin Result := FPosition; end; procedure TMouse.SetEnabled(Value: Boolean); begin FEnabled := Value; end; procedure TMouse.SetOnMouseDown(const Value: TMouseEvent); begin FOnMouseDown := Value; end; procedure TMouse.SetOnMouseMove(const Value: TMouseMoveEvent); begin FOnMouseMove := Value; end; procedure TMouse.SetOnMouseUp(const Value: TMouseEvent); begin FOnMouseUp := Value; end; procedure TMouse.Update; var I: Byte; F: Boolean; B: TMouseButton; begin // SetCursorPos(FLastPosition.X,FLastPosition.Y); for I := 0 to 2 do begin B := TMouseButton(I); F := FDown[B]; if FOldDown[B] xor F then begin if F then begin if Assigned(FOnMouseDown) then FOnMouseDown(B, [], FPosition.X, FPosition.Y); end else begin if Assigned(FOnMouseUp) then FOnMouseUp(B, [], FPosition.X, FPosition.Y); end; FOldDown[B] := F; end; end; if (IsMove) and Assigned(FOnMouseMove) then FOnMouseMove([], FLastPosition.X, FLastPosition.Y); end; function TMouse.Vector(Button: TMouseButton): TPoint; begin Result := FVector[Button]; end; end.
PROGRAM CHESS(INPUT,OUTPUT); LABEL 1, (* INITIALIZE FOR A NEW GAME *) 2, (* EXECUTE MACHINES MOVE *) 9, (* END OF PROGRAM *) { [sam] added jumpin label } 3; CONST AA = 1; ZA = 10; (* CHARACTERS IS A WORD *) {AC = 'A';} ZC = ','; (* CHARACTER LIMITS *) AD = -21; ZD = +21; (* DIRECTION LIMITS *) AJ = 0; ZJ = 73; (* CHARACTERS IN A STRING *) AK = 0; ZK = 16; (* SEARCH DEPTH LIMITS *) AKM2 = -2; (* AK-2 *) ZKP1 = 17; (* ZK+1 *) AL = 0; ZL = 119; (* LARGE B0ARD VECTOR LIMITS *) AZL = -119; ZAL = 119; (* LARGE BOARD DIFFERENCES LIMITS *) AN = 1; ZN = 30; (* HESSAGE LIMITS *) AS = 0; ZS = 63; (* BOARD VECTOR LIMITS *) AT = -1; ZT = 63; (* BOARD VECTOR LIMITS AND ANOTHER VALUE *) AV = -32767; ZV = +32767; (* EVALUATION LIMITS *) AW = 1; ZW = 500; (* MOVE STACK LIMITS *) AX = 0; ZX = 31; (* SUBSETS OF SQUARES *) AY = 0; ZY = 1; (* ARRAY OF SUBSETS TO FORM A SET OF ALL SQUARES ON BOARD *) LPP = 20; (* LINES PER PAGE *) {PZX8 = 16777216; unused[sam]} (* 2^(ZX-7) *) SYNCF = 1; (* FIRST CAPTURE SYNTAX *) SYNCL = 36; (* LAST CAPTURE SYNTAX *) SYNMF = 37; (* FIRST MOVE SYNTAX *) SYNML = 47; (* LAST MOVE SYNTAX *) TYPE (* SIMPLE TYPES *) TA = AA..ZA; (* INDEX TO WORD OF CHAR *) TB = BOOLEAN; (* TRUE OR FALSE *) TC = CHAR; (* SINGLE CHARACTERS *) TD = AD..ZD; (* DIRECTIONS *) TE = (B1,B2,B3,B4,S1,S2,S3,S4,N1,N2,N3,N4,N5,N6,N7,N8); (* NUMBER OF DIRECTIONS *) TF = (F1,F2,F3,F4,F5,F6,F7,F8); (* FILES *) TG = (PQ,PR,PN,PB); (* PROMOTION PIECES *) TH = (H0,H1,H2,H3,H4,H5,H6,H7) ; (* TREE SEARCH MOOES *) TI = INTEGER; (* NUMBERS *) TJ = AJ..ZJ; (* INDEX TO STRINGS *) TK = AK..ZK; (* PLY INDEX *) TL = AL..ZL; (* LARGE [10X12] BOARD *) TM = (LITE,DARK,NONE); (* SIDES *) TN = AN..ZN; (* INDEX TO MESSAGES *) TP = (LP,LR,LN,LB,LQ,LK,DP,DR,DN,DB,DQ,DK,MT); (* PIECES: LIGHT PAWN, LIGHT ROOK, ... , DARK KING, EMPTY SQUARE *) TQ = (LS,LL,DS,DL) ; (* QUADRANTS *) TR = (R1,R2,R3,R4,R5,R6,R7,R8); (* RANKS *) TS = AS..ZS; (* SQUARES *) TT = AT..ZT; (* SQUARES, AND ANOTHER VALUE *) TU = (EP,ER,EN,EB,EQ,EK); (* TYPES: PAWN, ROOK, ... .KING *) TV = AV..ZV; (* EVALUATIONS *) TW = AW..ZW; (* MOVES INDEX *) TX = AX..ZX; (* SOME SQUARES *) TY = AY..ZY; (* NUMBER OF TX'S IN A BOARD *) {TZ = REAL; unused[sam]} (* FLOATING POINT NUMBERS *) (* SETS *) SC = SET OF char {AC..ZC}; (* SET OF CHARACTERS *) SF = SET OF TF; (* SET OF FILES *) SQ = SET OF TQ; (* SET OF CASTLING TYPES *) SR = SET OF TR; (* SET OF RANKS *) SX = SET OF TX; (* SET OF SOME SQUARES *) (* RECOROS *) RC = ARRAY [TS] OF TP; (* BOARD VECTORS *) RB = RECORD (* BOARDS *) RBTM : TM; (* SIDE TO MOVE *) RBTS : TT; (* ENPASSANT SQUARE *) RBTI : TI; (* MOVE NUMBER *) RBSQ : SQ; (* CASTLE FLAGS *) CASE boolean {INTEGER} OF false {0}: ( RBIS : rc); (* INDEXED BY SQUARE *) true {1}: ( RBIRF : ARRAY [TR,TF] OF TP);(* INDEXED BY RANK AND FILE *) END; RA = PACKED ARRAY [TA] OF TC; (* WORDS OF CHARACTERS *) RN = PACKED ARRAY [TN] OF TC; (* MESSAGES *) RJ = PACKED ARRAY [TJ] OF TC; (* STRINGS *) RD = PACKED RECORD (* SYNTAX DESCRIPTOR FOR SINGLE SQUARE *) RDPC : TB; (* PIECE *) RDSL : TB; (* / *) RDKQ : TB; (* K OR Q *) RDNB : TB; (* R, N, OR B *) RDRK : TB; (* RANK *) END; {RK = RECORD unused[sam] (* KLUDGE TO FIND NEXT BIT *) {CASE INTEGER OF} {0: (RKTB: SET OF 0..47);} (* BITS *) {1: (RKTZ: TZ);} (* FLOATING POINT NUMBER *) {END;} RM = PACKED RECORD (* MOVES *) RMFR : TS; (* FROM SQUARE *) RMTO : TS; (* TO SQUARE *) RMCP : TP; (* CAPTURED PIECE *) RMCA : TB; (* CAPTURE *) RMAC : TB; (* AFFECTS CASTLE STATUS *) RMCH : TB; (* CHECK *) RMMT : TB; (* MATE *) RMIL : TB; (* ILLEGAL *) RMSU : TB; (* SEARCHED *) CASE RMPR : TB OF (* PROMOTION *) FALSE: ( CASE RMOO : TB OF (* CASTLE *) FALSE: (RMEP : TB); (* ENPASSANT *) TRUE : (RMQS : TB); (* QUEEN SIDE *) ); TRUE : (RMPP : TG); (* PROMOTION TYPE *) END; RS = RECORD (* BIT BOARDS *) CASE boolean {INTEGER} OF false{0}: (RSSS: ARRAY [TY] OF SX); (* ARRAY OF SETS *) true{1}: (RSTI: ARRAY [TY] OF TI); (* ARRAY OF INTEGERS *) END; RX = ARRAY [TS] OF RS; (* ATTACK MAPS *) RY = PACKED RECORD (* MOVE SYNTAX DESCRIPTOR *) RYLS : RD; (* LEFT SIDE DESCRIPTOR *) RYCH : TC; (* MOVE OR CAPTURE *) RYRS : RD; (* RIGHT SIDE DESCRIPTOR *) END; RE = ARRAY [TW] OF TV; (* ARRAY OF VALUES *) RF = ARRAY [TW] OF RM; (* ARRAY OF MOVES *) { type joins added [sam] } arraytmofrs = array [tm] of rs; arraytkofrs = array [tk] of rs; arraytkoftw = array [tk] of tw; arraytpofte = array [tp] of te; arraytfofrs = ARRAY [TF] OF RS; arraytrofrs = ARRAY [TR] OF RS; arraytqofrs = ARRAY [TQ] OF RS; VAR (* DATA BASE *) BOARD : RB; (* THE BOARD *) MBORD : rc; (* LOOK-AHEAD BOARD *) ATKFR : RX; (* ATTACKS FROM A SQUARE *) ATKTO : RX; (* ATTACKS TO A SQUARE *) ALATK : arraytmofrs; (* ATTACKS BY EACH COLOR *) TPLOC : ARRAY [TP] OF RS; (* LOCATIONS OF PIECE BY TYPE *) TMLOC : arraytmofrs; (* LOCATIONS OF PIECE BY COLOR *) MOVES : rf; (* MOVES *) VALUE : re; (* VALUES *) ALLOC : arraytkofrs; (* ALL PIECES *) BSTMV : arraytkoftw; (* BEST MOVE SO FAR *) BSTVL : ARRAY [AKM2..ZKP1] OF TV; (* VALUE OF BEST MOVE *) CSTAT : arraytkofrs; (* CASTLING SQUARES *) ENPAS : arraytkofrs; (* ENPASSANT SQUARES *) GENPN : arraytkofrs; (* PAWN ORIGINATION SQUARES *) GENTO : arraytkofrs; (* MOVE DESTINATION SQUARES *) GENFR : arraytkofrs; (* MOVE ORIGINATION SQUARES *) MBVAL : ARRAY [TK] OF TV; (* MATERIAL BALANCE VALUES *) MVSEL : ARRAY [TK] OF TI; (* COUNT MOVES SELECTED BY PLY *) INDEX : ARRAY [AK..ZKP1] OF TW; (* CURRENT MOVE FOR PLY *) KILLR : ARRAY [TK] OF RM; (* KILLER MOVES BY PLY *) LINDX : arraytkoftw; (* LAST MOVE FOR PLY *) SRCHM : ARRAY [TK] OF TH; (* SEARCH MOVES *) GOING : TI; (* NUMBER OF MOVES TO EXECUTE *) LSTMV : RM; (* PREVIOUS MOVE *) MAXPS : TV; (* MAXIMUM POSITIONAL SCORE *) MBLTE : TV; (* MATERIAL BALANCE LITE EDGE *) MBPWN : ARRAY [TM] OF TI; (* NUMBER OF PAWNS BY SIDE *) MBTOT : TV; (* TOTAL MATERIAL ON MBOARD *) NODES : TI; (* NUMBER OF MOVES SEARCHEO *) JNTK : TK; (* PLY INDEX *) JMTK : TK; (* ITERATION *) JNTM : TM; (* SIDE TO MOVE *) JNTW : TW; (* MOVES STACK POINTER *) (* LETS *) FKPSHD : TI; (* KING PAWN SHIELD CREDIT *) FKSANQ : TI; (* KING IN SANCTUARY CREDIT *) FMAXMT : TI; (* MAXIMUM MATERIAL SCORE *) FNODEL : TI; (* MOVE LIMIT FOR SEARCH *) FPADCR : ARRAY [TF] OF TI; (* PAWN AOVANCE CREDIT BY FILE *) FPBLOK : TI; (* PAWN BLOCKED PENALTY *) FPCONN : TI; (* PAWN CONNECTED CREDIT *) FPFLNX : TI; (* PAWN PHALANX CREDIT *) FRDUBL : TI; (* DOUBLED ROOK CREDIT *) FRK7TH : TI; (* ROOK ON SEVENTH CREOIT *) FTRADE : TI; (* TRADE-DOWW BONUS FACTOR *) FTRDSL : TI; (* TRADE-DOWN TUNING FACTOR *) FTRPDK : TI; (* PAWN TRADE-DOWN RELAXATION *) FTRPWN : TI; (* PAWN TRADE-DOWN FACTOR *) FWKING : TI; (* KING EVALUATION WEIGHT *) FWMAJM : TI; (* MAJOR PIECE MOBILITY WEIGHT *) FWMINM : TI; (* MINOR PIECE MOBILITY WEIGHT *) FWPAWN : TI; (* PAWN EVALUATION WEIGHT *) FWROOK : TI; (* ROOK EVALUATION WEIGHT *) WINDOW : TI; (* SIZE OF ALPHA-BETA WINDOW *) (* SWITCHES *) SWEC : TB; (* ECHO INPUT *) SWPA : TB; (* PAGING *) SWPS : TB; (* PRINT PRELIMINARY SCORES *) SWRE : TB; (* REPLY WITH MOVE *) SWSU : TB; (* PRINT STATISTICS SUMMARY *) SWTR : TB; (* TRACE TREE SEARCH *) (* COMMAND PROCESSING OATA *) ICARD : RJ; (* INPUT CARD IMAGE *) ILINE : RJ; (* CURRENT COMMAND *) JMTJ : TJ; (* CURRENT INPUT LINE POSITION *) JNTJ : TJ; (* CURRENT COMMAND POSITION *) MOVMS : RN; (* MOVE MESSAGE *) (* TRANSLATION TABLES *) XSPB : ARRAY [TP] OF TB; (* TRUE FOR SWEEP PIECES *) XFPE : arraytpofte; (* FIRST DIRECTION *) XLLD : ARRAY [AZL..ZAL] OF TD; (* DIRECTION FOR LARGE BOARD SQUARE DIFFERENCES *) XLPE : arraytpofte; (* LAST DIRECTION *) XRFS : arraytfofrs; (* BIT BOARD FOR FILES *) XRRS : arraytrofrs; (* BIT BOARD FOR RANKS *) XNFS : arraytfofrs; (* COMP BIT BOARD FOR FILES *) XNRS : arraytrofrs; (* COMP BIT BOARD FOR RANKS *) XRSS : RX; (* BIT BOARD FOR 8X8 INDEX *) XRQM : ARRAY [TQ] OF RM; (* MOVES FOR CASTLE TYPES *) XSQS : arraytqofrs; (* BIT BOARD FOR CASTLE TYPES *) XSSX : ARRAY [TS] OF SX; (* SET ELEMENT FOR 8X8 INDEX *) XTBC : ARRAY [TB] OF TC; (* CHARACTERS FOR BOOLEANS *) XTED : ARRAY [TE] OF TD; (* DIRECTION NUMBER TO 10X12 SQUARE DIFFERENCE *) XTGC : ARRAY [TG] OF TC; (* CHARACTERS FOR PROMOTION *) XTGMP: ARRAY [TG,TM] OF TP; (* PIECE FOR PROMOTION TYPE AND COLOR *) XTLS : ARRAY [TL] OF TT; (* 8X8 INDEX FOR 10X12 INDEX *) XTMA : ARRAY [TM] OF RA; (* WORDS FOR COLORS *) XTMQ : ARRAY [TM] OF TQ; (* CASTLE TYPES FOR SIDE *) XTMV : ARRAY [TM] OF TV; (* SCORE FACTOR FOR SIDE *) XTPC : ARRAY [TP] OF TC; (* CHARACTERS FOR PIECES *) XTPM : ARRAY [TP] OF TM; (* SIDES FOR PIECES *) XTPU : ARRAY [TP] OF TU; (* TYPE FOR PIECE *) XTPV : ARRAY [TP] OF TV; (* VALUES OF PIECES *) XTQA : ARRAY [TQ] OF RA; (* WORDS FOR CASTLES *) XTQS : ARRAY [TQ] OF TS; (* TO SQUARES FOR CASTLE TYPES *) XTRFS: ARRAY [TR,TF] OF TS; (* 8X8 INDEX FOR RANK AND FILE *) XTSF : ARRAY [TS] OF TF; (* FILES FOR SQUARES *) XTSL : ARRAY [TS] OF TL; (* 10X12 INDEX FOR 8X8 INDEX *) XTSR : ARRAY [TS] OF TR; (* RANKS FOR SQUARES *) XTSX : ARRAY [TS] OF TX; (* ELEMENT NUMBER FOR 8X8 INDEX *) XTSY : ARRAY [TS] OF TY; (* ARRAY SUBSCRIPT INTO BIT BOARD FOR 8X8 INDEX *) XTUC : ARRAY [TU] OF TC; (* CHARACTER FOR TYPE *) XTUMP: ARRAY [TU,TM] OF TP; (* PIECE FOR TYPE AND SIDE *) XRQSO: arraytqofrs; (* UNOCCUPIED SQUARES FOR CASTLING *) XRQSA: arraytqofrs; (* UNATTACKED SQUARES FOR CASTLING *) EDGE : ARRAY [TE] OF RS; (* EDGES IN VARIOUS DIRECTIONS *) CORNR: RS; (* KING SANCTUARY *) NULMV: RM; (* NULL MOVE *) OTHER: ARRAY [TM] OF TM; (* OTHER COLOR *) SYNTX: ARRAY [SYNCF..SYNML] OF RY; (* MOVE SYNTAX TABLE *) { [sam] jump into structure flag } jumpin: boolean; FUNCTION MAX(A,B:TI): TI; (* LARGER OF TWO NUMBERS *) BEGIN IF A > B THEN MAX := A ELSE MAX := B; END; (* MAX *) FUNCTION MIN(A,B:TI): TI; (* SMALLER OF TWO NUMBERS *) BEGIN IF A < B THEN MIN := A ELSE MIN := B; END; (* MIN *) FUNCTION SIGN(A,B:TI): TI; (* SIGN OF B APPLIED TO ABSOLUTE VALUE OF A *) BEGIN { Replaced strangeness [sam] } if b < 0 then sign := abs(a)*(-1) else sign := abs(a)*(+1) { SIGN := TRUNC(B/ABS(B)) * ABS(A); } END; (* SIGN *) PROCEDURE SORTIT (* SORT PRELIMINARY SCORES *) (VAR A:RE; (* ARRAY OF SCORES *) VAR B:RF; (* ARRAY OF MOVES *) C:TW); (* NUMBER OF ENTRIES *) VAR INTB : TB; (* LOOP EXIT FLAG *) INTW : TW; (* OUTER LOOP INDEX *) INTI : TI; (* INNER LOOP INDEX *) INTV : TV; (* HOLD SCORE *) INRM : RM; (* HOLD MOVE *) BEGIN FOR INTW := AW+2 TO C DO BEGIN INTI := INTW - 1; INTV := A[INTW]; INRM := B[INTW]; INTB := TRUE; WHILE (INTI > AW) AND INTB DO IF INTV < A[INTI] THEN BEGIN A[INTI+1] := A[INTI]; B[INTI+1] := B[INTI]; INTI := INTI - 1; END ELSE INTB := FALSE; (* EXIT *) A[INTI+1] := INTV; B[INTI+1] := INRM; END; END; (* SORTIT *) PROCEDURE ANDRS (* INTERSECTION OF TWO BIT BOARDS *) (VAR C:RS; (* RESULT *) A, B:RS); (* OPERANDS *) VAR INTY : TY; (* BIT BOARD WORD INDEX *) BEGIN FOR INTY := AY TO ZY DO C.RSSS[INTY] := A.RSSS[INTY] * B.RSSS[INTY]; END; (* ANDRS *) PROCEDURE CLRRS (* REMOVE SQUARE FROM BITBOARD *) (VAR C:RS; (* BIT BOARD *) A:TS); (* SQUARE TO REMOVE *) BEGIN C.RSSS[XTSY[A]] := C.RSSS[XTSY[A]] - XSSX[A]; END; (* CLRRS *) PROCEDURE CPYRS (* COPY OF A BIT BOARD *) (VAR C:RS; (* RESULT *) A:RS); (* OPERAND *) VAR INTY : TY; (* BIT BOARD NORO INDEX *) BEGIN FOR INTY := AY TO ZY DO C.RSSS[INTY] := A.RSSS[INTY]; END; (* CPYRS *) PROCEDURE IORRS (* UNION OF TWO BIT BOARDS *) (VAR C:RS; (* RESULT *) A, B:RS); (* OPERANDS *) VAR INTY : TY; (* BIT BOARD WORD INDEX *) BEGIN FOR INTY := AY TO ZY DO C.RSSS[INTY] := A.RSSS[INTY] + B.RSSS[INTY]; END; (* IORRS *) PROCEDURE NEWRS (* CLEAR BIT BOARD *) (VAR A:RS); (* BIT BOARD TO CLEAR *) VAR INTY : TY; (* BIT BOARD WORD INDEX *) BEGIN FOR INTY := AY TO ZY DO A.RSSS[INTY] := []; END; (* NEWRS *) PROCEDURE NOTRS (* COMPLEMENT OF A BIT BOARD *) (VAR C:RS; (* RESULT *) A:RS); (* OPERAND *) VAR INTY : TY; (* BIT BOARD WORD INDEX *) BEGIN FOR INTY := AY TO ZY DO C.RSSS[INTY] := [AX..ZX]-A.RSSS[INTY]; END; (* NOTRS *) FUNCTION NXTTS (* NEXT ELEMENT IN BIT BOARD *) (VAR A:RS; (* BIT BOARD TO LOCATE FIRST SQUARE, AND THEN REMOVE *) VAR B:TS (* SQUARE NUMBER OF FIRST SQUARE IN BIT BOARD *) ): TB; (* TRUE IFF ANY SQUARES WERE SET INITIALLY *) LABEL 11; (* RETURN *) VAR INTX : TX; (* BIT BOARD BIT INDEX *) INTY : TY; (* BIT BOARD WORD INDEX *) BEGIN FOR INTY := ZY DOWNTO AY DO (* LOOP THRU BIT BOARD WOROS *) IF A.RSTI[INTY] <> 0 THEN BEGIN (*** BEGIN COC 6000 DEPENDANT CODE *) (*** FOLLOWING CODE REQUIRES THE 'EXPO' FUNCTION TO RETURN (*** THE EXPONENT FROM A FLOATING POINT NUMBER. IT ALSO ASSUMES (*** THAT FLOATING POINT MUMBERS HAVE 40 BIT COEFFICIENTS RIGHT- (*** JUSTIFIED IN A WORD. AND THAT SETS ARE RIGHT-JUSTIFIED IN (*** A WORD. *) (* X.RKTZ := A.RSTI[INTY]; (* FLOAT WORD *) (* B := EXPO(X.RKTZ) + INTY * (ZX+1): (* (* CONVERT TO SQUARE NUMBER *) (* X.RKTB := X.RKTB - [47]; (* REMOVE MOST SIGNIFICANT BIT *) (* A.RSTI[INTY] := TRUNC(X.RKTZ); (* INTEGERIZE *) (* NXTTS := TRUE; (* RETURN A 8IT SET *) (* GOTO 11; (* RETURN *) (*** END CDC 6000 DEPENDANT CODE *) (*** BEGIN NACHINE INDEPENDENT CODE *) FOR INTX := ZX DOWNTO AX DO (* LOOP THROUGH BITS IN WORD OF SET *) IF INTX IN A.RSSS[INTY] THEN BEGIN B := INTX+INTY*(ZX+1); (* RETURN SQUARE NUMBER *) A.RSSS[INTY] := A.RSSS[INTY] - [INTX]; (* REMOVE BIT FROM WORD *) NXTTS := TRUE; (* RETURN A BIT SET *) GOTO 11; (* RETURN *) END; (*** END MACHINE XNOEPENDENT CODE *) END; NXTTS := FALSE; (* ELSE RETURN NC BITS SET *) 11: (* RETURN *) END; (* NXTTS *) FUNCTION CNTRS (* COUNT NENBERS OF A BIT BOARD *) (A:RS): TS; (* BIT BOARD TO COUNT *) VAR INTS : TS; (* TEMPORARY *) INRS : RS; (* SCRATCH *) IMTS : TS; (* SCRATCH *) BEGIN INTS := 0; (*** BEGIN MACHINE INDEPENDENT CODE *) CPYRS(INRS,A); WHILE NXTTS(INRS,IMTS) DO INTS := INTS+1; (* COUNT SQUARES *) (*** END MACHINE INDEPENDENT CODE *) (*** BEGIN CDC 6000 DEPENDENT CODE *) (*** FOLLOWING COOE REQUIRES THE 'CARD' FUNCTION TO (*** COUNT THE MEMBERS IN A SET. *) (*FOR INTY := AY TO ZY DO (* INTS := INTS + CARD(A.RSSS[INTY]): (*** END CDC DEPENDENT CODE *) CNTRS := INTS; (* RETURN SUM *) END; (* CNTRS *) PROCEDURE SETRS (* INSERT SQUARE INTO BIT BOARD *) (VAR C:RS; (* BIT BOARD *) A:TS); (* SQUARE TO INSERT *) BEGIN C.RSSS[XTSY[A]] := C.RSSS[XTSY[A]] + XSSX[A]; END; (* SETRS *) PROCEDURE SFTRS (* SHIFT BIT BOARD *) (VAR A:RS; (* RESULT *) B:RS; (* SOURCE *) C:TE); (* DIRECTION *) VAR INTS : TS; (* SCRATCH *) BEGIN (* BEGIN MACHINE INDEPENDENT CODE *) NEWRS(A); (* CLEAR NEW BIT BOARD *) WHILE NXTTS(B,INTS) DO IF XTLS[XTSL[INTS]+XTED[C]] > 0 THEN (* SHIFT EACH BIT *) SETRS(A,XTLS[XTSL[INTS]+XTED[C]]); (*** END MACHINE INDEPENDENT CODE *) (*** BEGIN CDC 6000 DEPENDENT CODE *) (*** FOLLOWING CODE ASSUMES THAT MULTIPLICATION OR DIVISION (*** NY A CONSTANT POWER OF 2 IS DONE WITH A SHIFT INSTRUCTION. *) (*CASE C OF (*SL: BEGIN (* FOR INTY := AY TO ZY DO (* SHIFT ONE PLACE *) (* BEGIN (* B.RSSS[INTY] := B.RSSS[INTV] - EDGE[S1].RSSS[INTY]; (* A.RSTK[INTY] := B.RSTK[INTV] DIV 2; (* END; (* END; (*S2: BEGIN (* FOR INTY := AY TO ZY DO (* SHIFT WORDS *) (* BEGIN (* B.RSSS(INTY) := B.RSSS[INTY] - EDGE(S2).RSSS[INTY]; (* INRS.RSSS[INTY] := B.RSSS[INTY] * [ZX-7..ZX]; (* A.RSSS[INTY] := B.RSSS[INTY] - [ZX-7..ZX]; (* A.RSTI[INTY] := A.RSTI[INTY] * 255 (* END; (* FOR INTY := AY+1 TO ZY DO (* CARRY BETWEEN WOROS *) (* A.PSTI[INTY] := A.RSTI[INTY] + INRS.RSTI[INTY-1] DIV PZX8; (* END; (*S3I BEGIN (* FOR INTY := AY TO ZY DO (* SHIFT ONE PLACE *) (* BEGIN (* A.RSSS[INTY] := B.RSSS[INTY] - EDGE[S3].RSSS[INTY]; (* A.RSTI[INTY] := A.RSTINTY] * 2; (* END; (* END; (S4: BEGIN (* FOR INTY :- AY TO ZY DO (* SHIFT WORDS *) (* BEGIN (* B.RSSS[INTY] := S.RSSS[INTY] - EDGE[S4].RSSS[INTY]; (* INRS.RSSS[INTY] := B.RSSS[INTY] * [AX..AX+7]; (* A.RSTI[INTY] := B.RSTI[INTY] DIV 256: (* END; (* FOR INTY := AY TO ZY-1 DO (* CARRY BETWEEN WORDS *) (* A.RSTI[INTY] := A.RSTI[INTY] + INRS.RSTI[INTY+1] * PZX8; (* END; (*B1: BEGIN (* SFTRS(INRS,B,S1): (* SFTRS(A,INRS,S2); (* END; (*B2: BEGIN (* SFTRS(INRS,B,S2); (* SFTRS(A,INRS,S3); (* END: (*B3: BEGIN (* SFTRS(INRS,B,S3); (* SFTRS(A,IHRS,S4); (* END: (*B4: BEGIN (* SFTRS(INRS,B,S4); (* SFTRS(A,INRS,S1); (* END; (*N1: BEGIN (* SFTRS(INRS,B,B1); (* SFTRS(A,INRS,S2); (* END: (*N2: BEGIN (* SFTRS(INRS,B,B2); (* SFTRS(A,INRS,S2); (* END; (*N3: BEGIN (* SFTRS(INRS,B,B2); (* SFTRS(A,INRS,S3); (* END; (*N4: BEGIN (* SFTRS(INRS,B,B3); (* SFTRS(A,LNRS,S3); (* END; (*N5: BEGIN <* SFTRS(INRS,B,B3); (* SFTRS(A,INRS,S4); (* END; (*N6: BEGIN (* SFTRS(INRS,B,B4); (* SFTRS(A,INRS,S4); (* END: (*N7: BEGIN (* SFTRS(INRS,B,B4); (* SFTRS(A,INRS,S1); (* END; (*N8: BEGIN (* SFTRS(INRS,B,B1); (* SFTRS(A,INRS.S1); (* END; (*END: (*** END CDC 6000 DEPENDENT CODE *) END; (* SFTRS *) FUNCTION INRSTB (* SQUARE IN BIT BOARD BOOLEAN *) (A:RS; (* BIT BOARD *) B:TS): TB; (* SQUARE IN QUESTION *) BEGIN INRSTB := XSSX[B] <= A.RSSS[XTSY[B]]; END; (* INRSTB *) FUNCTION NULRS (* NULL BIT BOARD *) (A:RS) (* BIT BOARD TO CHECK *) : TB; (* TRUE IF BIT BOARD EMPTY *) VAR INTY : TY; (* BIT BOARD WORD INDEX *) INTB : TB; (* TEMPORARY VALUE *) BEGIN INTB := TRUE; FOR INTY := AY TO ZY DO INTB := INTB AND (A.RSTI[INTY] = 0); NULRS := INTB; END; (* NULRS *) FUNCTION NULMVB (* NULL MOVE BOOLEAN *) (A:RM) (* MOVE TO TEST *) : TB; (* TRUE IF NULL MOVE *) BEGIN WITH A DO NULMVB := RMAC AND RMPR AND (NOT RMCA); END; (* NULMVB *) PROCEDURE INICON; (* INITIALIZE GLOBAL CONSTANTS *) VAR INTD : TD; (* DIRECTION INDEX *) INTE : TE; (* DIRECTION *) INTF : TF; (* FILE INDEX *) INTI : TI; (* SCRATCH *) INTI1 : TI; (* SCRATCH eliminates threat error [sam] *) INTL : TL; (* LARGE BOARD INDEX *) INTQ : TQ; (* CASTLE TYPE INDEX *) INTR : TR; (* RANK INDEX *) INTT : TT; (* SQUARE INDEX *) INTX : TX; (* SET ELEMENT INDEX *) INTY : TY; (* BIT BOARD WORD INDEX *) IMTI : TI; (* SCRATCH *) INRS : RS; (* SCRATCH *) PROCEDURE INISYN (* INITIALIZE MOVE SYNTAX TABLE ENTRY *) (A:RA); (* MOVE SYNTAX *) BEGIN WITH SYNTX[INTI] DO BEGIN WITH RYLS DO BEGIN RDPC := TRUE; RDSL := A[AA+0] <> ' '; RDKQ := A[AA+1] <> ' '; RDNB := A[AA+2] <> ' '; RDRK := A[AA+3] <> ' '; END; RYCH := A[AA+4]; WITH RYRS DO BEGIN RDPC := A[AA+5] <> ' '; RDSL := A[AA+6] <> ' '; RDKQ := A[AA+7] <> ' '; RDNB := A[AA+8] <> ' '; RDRK := A[AA+9] <> ' '; END; END; INTI := INTI+1; END; (* INISYN *) PROCEDURE INIXTP (* INITIALIZE PIECE TRANSLATION TABLES *) (A : TP; (* PIECE TO BE TRANSLATED *) B : TC; (* DISPLAV EQUIVALENT *) C : TM; (* COLOR OF PIECE *) D : TU; (* TYPE OF PIECE *) E : TB; (* TRUE IF SWEEP PIECE *) F : TE; (* FIRST DIRECTION OF MOVEMENT *) G : TE; (* LAST DIRECTION OF MOVEMENT *) H : TV); (* VALUE OF PIECE *) BEGIN XTPC[A] := B; XTPM[A] := C; XSPB[A] := E; XFPE[A] := F; XLPE[A] := G; XTPU[A] := D; XTPV[A] := H; IF A <> MT THEN XTUMP[D,C] := A; END; (* INIXTP *) BEGIN (* INICON *) (** INITIALIZE PIECE CHARACTERISTICS *) INIXTP(LP,'A',LITE,EP,FALSE,B1,B2,1*64); INIXTP(LR,'B',LITE,ER,TRUE ,S1,S4,5*64); INIXTP(LN,'C',LITE,EN,FALSE,N1,N8,3*64); INIXTP(LB,'D',LITE,EB,TRUE ,B1,B4,3*64); INIXTP(LQ,'E',LITE,EQ,TRUE ,B1,S4,9*64); INIXTP(LK,'F',LITE,EK,FALSE,B1,S4,0); INIXTP(DP,'1',DARK,EP,FALSE,B3,B4,-1*64); INIXTP(DR,'2',DARK,ER,TRUE ,S1,S4,-5*64); INIXTP(DN,'3',DARK,EN,FALSE,N1,N8,-3*64); INIXTP(DB,'4',DARK,EB,TRUE ,B1,B4,-3*64); INIXTP(DQ,'5',DARK,EQ,TRUE ,B1,S4,-9*64); INIXTP(DK,'6',DARK,EK,FALSE,B1,S4,0); INIXTP(MT,'-',NONE,EP,FALSE,B2,B1,0); XTGMP[PQ,LITE] := LQ; XTGMP[PQ,DARK] := DQ; XTGC[PQ] := 'Q'; XTGMP[PR,LITE] := LR; XTGMP[PR,DARK] := DR; XTGC[PR] := 'R'; XTGMP[PN,LITE] := LN; XTGMP[PN,DARK] := DN; XTGC[PN] := 'N'; XTGMP[PB,LITE] := LB; XTGMP[PB,DARK] := DB; XTGC[PB] := 'B'; XTUC[EK] := 'K'; XTUC[EQ] := 'Q'; XTUC[ER] := 'R'; XTUC[EN] := 'N'; XTUC[EB] := 'B'; XTUC[EP] := 'P'; (** INITIALIZE OTHER CONSTANTS *) XTBC[FALSE] := '-'; XTBC[TRUE ] := '*'; OTHER[LITE] := DARK; XTMV[LITE] := 1; OTHER[DARK] := LITE; XTMV[DARK] := -1; OTHER[NONE] := NONE; XTMA[LITE] := ' WHITE '; XTMA[DARK] := ' BLACK '; XTMA[NONE] := ' NO ONE '; XTQA[LS] := 'WHITE KING'; XTQA[LL] := 'WHITE LONG'; XTQA[DS] := 'BLACK KING'; XTQA[DL] := 'BLACK LONG'; (** INITIALIZE 10X12 TO 8X8 AND 8X8 TO 10X12 TRANSLATION TABLES *) FOR INTL := AL TO ZL DO (* LOOP THROUGH LARGE BOARD *) XTLS[INTL] := -1; (* PRESET ARRAY TO OFF BOARD *) INTL := 21; (* INDEX OF FIRST SQUARE ON LARGE BOARD *) INTT := -1; (* INDEX OF FIRST SQUARE ON SHALL BOARD *) FOR INTR := R1 TO R8 DO (* LOOP THROUGH RANKS *) BEGIN FOR INTF := F1 TO F8 DO (* LOOP THROUGH FILES *) BEGIN INTT := INTT+1; (* ADVANCE SMALL BOARD INDEX *) XTRFS[INTR,INTF] := INTT; (* SET MATRIX TO VECTOR TRANSLATION *) XTLS[INTL] := INTT; (* SET LARGE BOARD TRANSLATION TABLE WITH SMALL BOARD INDEX *) XTSL[INTT] := INTL; (* SET SMALL BOARD TRANSLATION TABLE WITH LARGE BOARD INDEX *) XTSR[INTT] := INTR; (* SET RANK OF SQUARE *) XTSF[INTT] := INTF; (* SET FILE OF SQUARE *) INTL := INTL+1; (* ADVANCE LARGE BOARD INDEX *) END; INTL := INTL+2; (* ADVANCE LARGE BOARD INDEX TO SKIP BORDER *) END; (** INITIALIZE 8X8 TO BIT BOARD TABLES *) INTT := -1; FOR INTY := AY TO ZY DO BEGIN FOR INTX := AX TO ZX DO BEGIN INTT := INTT+1; XTSX[INTT] := INTX; XTSY[INTT] := INTY; XSSX[INTT] := [INTX]; NEWRS(XRSS[INTT]); XRSS[INTT].RSSS[INTY] := [INTX]; END; END; (** INITIALIZE CONSTANT BIT BOARDS *) FOR INTR := R1 TO R8 DO NEWRS(XRRS[INTR]); FOR INTF := F1 TO F8 DO NEWRS(XRFS[INTF]); FOR INTR := R1 TO R8 DO FOR INTF := F1 TO F8 DO BEGIN SETRS(XRRS[INTR],XTRFS[INTR,INTF]); SETRS(XRFS[INTF],XTRFS[INTR,INTF]); END; FOR INTF := F1 TO F8 DO NOTRS(XNFS[INTF],XRFS[INTF]); FOR INTR := R1 TO R8 DO NOTRS(XNRS[INTR],XRRS[INTR]); (** INITIALIZE EDGES *) CPYRS(EDGE[S1],XRFS[F1]); CPYRS(EDGE[S2],XRRS[R8]); CPYRS(EDGE[S3],XRFS[F8]); CPYRS(EDGE[S4],XRRS[R1]); IORRS(EDGE[B1],EDGE[S1],EDGE[S2]); IORRS(EDGE[B2],EDGE[S2],EDGE[S3]); IORRS(EDGE[B3],EDGE[S3],EDGE[S4]); IORRS(EDGE[B4],EDGE[S4],EDGE[S1]); IORRS(EDGE[N1],EDGE[B1],XRRS[R7]); IORRS(EDGE[N2],EDGE[B2],XRRS[R7]); IORRS(EDGE[N3],EDGE[B2],XRFS[F7]); IORRS(EDGE[N4],EDGE[B3],XRFS[F7]); IORRS(EDGE[N5],EDGE[B3],XRRS[R2]); IORRS(EDGE[N6],EDGE[B4],XRRS[R2]); IORRS(EDGE[N7],EDGE[B4],XRFS[F2]); IORRS(EDGE[N8],EDGE[B1],XRFS[F2]); (** INITIALIZE CORNER MASK *) IORRS(INRS,XRRS[R1],XRRS[R2]); IORRS(INRS,INRS,XRRS[R7]); IORRS(INRS,INRS,XRRS[R8]); IORRS(CORNR,XRFS[F1],XRFS[F2]); IORRS(CORNR,CORNR,XRFS[F7]); IORRS(CORNR,CORNR,XRFS[F8]); ANDRS(CORNR,CORNR,INRS); (** INITIALIZE DIRECTION TABLE *) XTED[N1]:= 19; XTED[N2]:= 21; XTED[N8]:= 8;XTED[B1]:= 9;XTED[S2]:= 10;XTED[B2]:= 11;XTED[N3]:= 12; XTED[S1]:= -1; XTED[S3]:= 1; XTED[N7]:=-12;XTED[B4]:=-11;XTED[S4]:=-10;XTED[B3]:= -9;XTED[N4]:= -8; XTED[N6]:=-21; XTED[N5]:=-19; (** INITIALIZE SQUARE DIFFERENCE TO DIRECTION TABLE *) FOR INTI1 := AZL TO ZAL DO XLLD[INTI1] := 0; FOR INTE := B1 TO S4 DO BEGIN INTD := XTED[INTE]; FOR IMTI := 1 TO 7 DO XLLD[IMTI*INTD] := INTD; END; FOR INTE := N1 TO N8 DO XLLD[XTED[INTE]] := XTED[INTE]; (** INITIALIZE CASTLING TRANSLATION TABLES *) IORRS(XSQS[LS],XRSS[XTRFS[R1,F8]],XRSS[XTRFS[R1,F5]]); IORRS(XSQS[LL],XRSS[XTRFS[R1,F1]],XRSS[XTRFS[R1,F5]]); IORRS(XSQS[DS],XRSS[XTRFS[R8,F8]],XRSS[XTRFS[R8,F5]]); IORRS(XSQS[DL],XRSS[XTRFS[R8,F1]],XRSS[XTRFS[R8,F5]]); IORRS(XRQSO[LS],XRSS[XTRFS[R1,F6]],XRSS[XTRFS[R1,F7]]); IORRS(XRQSO[LL],XRSS[XTRFS[R1,F4]],XRSS[XTRFS[R1,F3]]); IORRS(XRQSA[LS],XRSS[XTRFS[R1,F5]],XRQSO[LS]); IORRS(XRQSA[LL],XRSS[XTRFS[R1,F5]],XRQSO[LL]); IORRS(XRQSO[LL],XRSS[XTRFS[R1,F2]],XRQSO[LL]); IORRS(XRQSO[DS],XRSS[XTRFS[R8,F6]],XRSS[XTRFS[R8,F7]]); IORRS(XRQSO[DL],XRSS[XTRFS[R8,F4]],XRSS[XTRFS[R8,F3]]); IORRS(XRQSO[DS],XRSS[XTRFS[R8,F5]],XRQSO[DS]); IORRS(XRQSA[DL],XRSS[XTRFS[R8,F5]],XRQSO[DL]); IORRS(XRQSO[DL],XRSS[XTRFS[R8,F2]],XRQSO[DL]); FOR INTQ := LS TO DL DO WITH XRQM[INTQ] DO BEGIN RMCP := MT; RMCA := FALSE; RMAC := TRUE; RMCH := FALSE; RMMT := FALSE; RMIL := FALSE; RMSU := FALSE; RMPR := FALSE; RMOO := TRUE; END; XRQM[LS].RMFR := XTRFS[R1,F5]; XRQM[LS].RMTO := XTRFS[R1,F7]; XRQM[LL].RMFR := XTRFS[R1,F5]; XRQM[LL].RMTO := XTRFS[R1,F3]; XRQM[DS].RMFR := XTRFS[R8,F5]; XRQM[DS].RMTO := XTRFS[R8,F7]; XRQM[DL].RMFR := XTRFS[R8,F5]; XRQM[DL].RMTO := XTRFS[R8,F3]; XRQM[LS].RMQS := FALSE; XRQM[LL].RMQS := TRUE; XRQM[DS].RMQS := FALSE; XRQM[DL].RMQS := TRUE; XTMQ[LITE] := LS; XTMQ[DARK] := DS; XTQS[LS] := XTRFS[R1,F8]; XTQS[LL] := XTRFS[R1,F1]; XTQS[DS] := XTRFS[R8,F8]; XTQS[DL] := XTRFS[R8,F1]; (** INITIALIZE NULL MOVE *) WITH NULMV DO BEGIN RMFR := AS; RMTO := AS; RMCP := MT; RMCA := FALSE; RMAC := TRUE; RMCH := FALSE; RMMT := FALSE; RMIL := FALSE; RMSU := FALSE; RMPR := TRUE; RMPP := PB; END; (** INITIALIZE COMMMAND PROCESSING VARIABLES *) JMTJ := ZJ; ICARD[ZJ] := ';'; ILINE[ZJ] := ';'; (** INITIALIZE MOVES SYNTAX TABLE *) INTI := SYNCF; INISYN(' *P '); INISYN(' *P/ 1'); INISYN('/ 1*P '); INISYN(' *P/ R '); INISYN('/ R *P '); INISYN(' *P/ R1'); INISYN('/ R1*P '); INISYN(' *P/KR '); INISYN('/KR *P '); INISYN(' *P/KR1'); INISYN('/KR1*P '); INISYN('/ 1*P/ 1'); INISYN('/ R *P/ R '); INISYN('/ 1*P/ R '); INISYN('/ R *P/ 1'); INISYN('/ R1*P/ 1'); INISYN('/ 1*P/ R1'); INISYN('/ R1*P/ R '); INISYN('/ R *P/ R1'); INISYN('/KR *P/ 1'); INISYN('/ 1*P/KR '); INISYN('/KR *P/ R '); INISYN('/ R *P/KR '); INISYN('/ 1*P/KR1'); INISYN('/KR1*P/ 1'); INISYN(' R *P/KR1'); INISYN('/KR1*P/ R '); INISYN('/ R1*P/ R1'); INISYN('/KR *P/ R1'); INISYN('/ R1*P/KR '); INISYN('/KR *P/KR '); INISYN('/KR1*P/ R1'); INISYN('/ R1*P/KR1'); INISYN('/KR1*P/KR '); INISYN('/KR *P/KR1'); INISYN('/KR1*P/KR1'); INISYN(' - R1'); INISYN(' - KR1'); INISYN('/ 1- R1'); INISYN('/ R - R1'); INISYN('/ 1- KR1'); INISYN('/ R - KR1'); INISYN('/ R1- R1'); INISYN('/KR - R1'); INISYN('/ R1- KR1'); INISYN('/KR - KR1'); INISYN('/KR1- KR1'); (** INITIALIZE LETS *) FKPSHD := 10; FKSANQ := 150; FMAXMT := 256; FNODEL := 18; FPADCR[F1] := 0; FPADCR[F2] := 0; FPADCR[F3] := 5; FPADCR[F4] := 10; FPADCR[F5] := 15; FPADCR[F6] := 5; FPADCR[F7] := 0; FPADCR[F8] := 0; FPBLOK := 20; FPCONN := 5; FPFLNX := 12; FRDUBL := 60; FRK7TH := 120; FTRADE := 36; FTRDSL := 5156; FTRPDK := 2; FTRPWN := 8; FWKING := 50; FWMAJM := 1; FWMINM := 200; FWPAWN := 100; FWROOK := 2; WINDOW := 30; (** INITIALIZE SWITCHES *) SWEC := TRUE; SWPA := TRUE; SWPS := FALSE; SWRE := TRUE; SWSU := FALSE; SWTR := FALSE; (** INITIALIZE MAIN LOOP CONTROL VARIABLES *) GOING := 0; END; (* INICON *) PROCEDURE INITAL(VAR A:RB); (* INITIALIZE FOR A NEW GAME *) VAR INTF : TF; (* FILE INDEX *) INTR : TR; (* RANK INDEX *) BEGIN WITH A DO BEGIN RBTM := LITE; (* SIDE TO MOVE *) RBTS := -1; (* NO ENPASSANT SQUARE *) RBTI := 0; (* GAME HAS NOT STARTED *) RBSQ := [LS,LL,DS,DL]; (* ALL CASTLING MOVES LEGAL *) FOR INTF := F1 TO F8 DO (* LOOP THROUGH ALL FILES *) BEGIN RBIRF[R2,INTF] := LP; (* SET LIGHT PAWNS ON BOARD *) FOR INTR := R3 TO R6 DO (* LOOP THRU MIDDLE OF BOARD *) RBIRF[INTR,INTF] := MT; (* SET MIDDLE OF BOARD EMPTY *) RBIRF[R7,INTF] := DP; (* SET DARK PAWNS ON BOARD *) END; RBIRF[R1,F1] := LR; (* SET REMAIMDER OF PIECES ON BOARD *) RBIRF[R1,F2] := LN; RBIRF[R1,F3] := LB; RBIRF[R1,F4] := LQ; RBIRF[R1,F5] := LK; RBIRF[R1,F6] := LB; RBIRF[R1,F7] := LN; RBIRF[R1,F8] := LR; RBIRF[R8,F1] := DR; RBIRF[R8,F2] := DN; RBIRF[R8,F3] := DB; RBIRF[R8,F4] := DQ; RBIRF[R8,F5] := DK; RBIRF[R8,F6] := DB; RBIRF[R8,F7] := DN; RBIRF[R8,F8] := DR; MOVMS := ' ENTER MOVE OR TYPE GO. '; WRITELN(MOVMS); LSTMV := NULMV; (* INITIALIZE PREVIOUS MOVE *) END; END; (* INITAL *) PROCEDURE PAUSER; (* PAUSE FOR CARRIAGE RETURN *) BEGIN IF SWPA THEN BEGIN WRITELN(' PAUSING '); READLN; END; END; (* PAUSER *) PROCEDURE PRIMOV(A:RM); (* PRINT A MOVE *) BEGIN WITH A DO BEGIN WRITE(' FROM ',RMFR:2,' TO ',RMTO:2); IF NULMVB(A) THEN WRITE(', NULL MCVE') ELSE BEGIN IF RMCA THEN WRITE(', CAPTURE ',XTPC[RMCP],',') ELSE WRITE(', SIMPLE,'); IF NOT RMAC THEN WRITE(' NO'); WRITE(' ACS'); IF RMCH THEN WRITE(', CHECK'); IF RMMT THEN WRITE(', MATE'); IF RMIL THEN WRITE(', ILLEGAL'); IF RMSU THEN WRITE(', SEARCHED'); CASE RMPR OF FALSE: (* NOT PROMOTION *) CASE RMOO OF FALSE: (* NOT CASTLE *) IF RMEP THEN WRITE(', ENPASSANT'); TRUE: (* CASTLE *) BEGIN WRITE(', CASTLE '); IF RMQS THEN WRITE('LONG') ELSE WRITE('SHORT'); END; END; TRUE: (* PROMOTION *) BEGIN WRITE(', PROMOTE TO '); CASE RMPP OF PQ: WRITE('QUEEN'); PR: WRITE('ROOK'); PB: WRITE('BISHOP'); PN: WRITE('KNIGHT'); END; END; END; END; END; WRITELN('.'); END; (* PRIMOV *) PROCEDURE PRINTB(A:RC); (* PRINT A BOARD *) VAR INTR : TR; (* RANK INDEX *) INTF : TF; (* FILE INDEX *) BEGIN WRITELN; (* WRITE A BLANK LINE *) FOR INTR := R8 DOWNTO R1 DO (* LOOP DOWN THROUGH RANKS *) BEGIN WRITE(' ',ORD(INTR)+1: 1,' ') ; (* OUTPUT RANK LABEL *) FOR INTF := F1 TO F8 DO (* LOOP ACROSS THROUGH FILES *) WRITE(XTPC[A[XTRFS[INTR,INTF]]]); (* OUTPUT CONTENTS OF SQUARE *) WRITELN; (* WRITE OUT A RANK *) END; WRITELN(' W RNBQKBNR') ; (* WRITE OUT BOTTOM LABEL *) END; (* PRINTB *) {PROCEDURE PRINBB(A:RS); unused [sam]} (* PRINT A BIT BOARD *) {VAR} {INTR : TR;} (* RANK INDEX *) {INTF : TF;} (* FILE INDEX *) {BEGIN} {WRITELN;} (* WRITE OUT A BLANK LINE *) {FOR INTR := R8 DOWNTO R1 DO} (* LOOP DOWN THROUGH RANKS *) {BEGIN} {WRITE(' ',ORD(INTR)+1: 1,' ');} (* OUTPUT RANK LABEL *) {FOR INTF := F1 TO F8 DO} (* LOOP ACROSS THROUGH FILES *) {WRITE(XTBC[INRSTB(A,XTRFS[INTR,INTF])]);} (* OUTPUT CONTENTS OF SQUARE *) {WRITELN;} (* WRITE OUT A RANK *) {END;} {WRITELN(' W RNBQKBNR');} (* WRITE OUT BOTTOM LABEL *) {END;} (* PRINBB *) PROCEDURE PRINAM(A:RX); (* PRINT ATTACK MAP *) VAR INTR, JNTR : TR; (* RANK INDICES *) INTF, JNTF : TF; (* FILE INDICES *) BEGIN WRITELN; FOR INTR := R8 DOWNTO R1 DO BEGIN FOR JNTR := R8 DOWNTO R1 DO BEGIN FOR INTF := F1 TO F8 DO BEGIN WRITE(' '); FOR JNTF := F1 TO F8 DO BEGIN WRITE(XTBC[INRSTB(A[XTRFS[INTR,INTF]],XTRFS[JNTR,JNTF])]); END; WRITE(' '); END; WRITELN; END; WRITELN; IF INTR IN [R1,R3,R5,R7] THEN PAUSER; END; END; (* PRINAM *) PROCEDURE PRISWI(A:RA;B:TB); (* PRINT A SWITCH *) BEGIN WRITE(' ',A[AA],A[AA+1]); IF B THEN WRITELN(' ON') ELSE WRITELN(' OFF'); END; (* PRISWI *) PROCEDURE MBEVAL; (* EVALUATE MATERIAL BALANCE *) VAR INTI : TI; (* COUNT PAWNS OF WINNING SIDE *) BEGIN IF MBLTE <> 0 THEN IF MBLTE > 0 THEN INTI := MBPWN[LITE] ELSE INTI := MBPWN[DARK] ELSE INTI := 0; MBVAL[JNTK] := SIGN(MIN(MIN(FMAXMT,ABS(MBLTE)) +FTRADE*ABS(MBLTE)*(FTRDSL-MBTOT)*(4*INTI+FTRPDK) DIV (4*INTI+FTRPWN) DIV 262144,16320),MBLTE); END; (* MBEVAL *) PROCEDURE MBCAPT (* EVALUATE MATERIAL AFTER CAPTURE *) (A:TP); (* PIECE CAPTURED *) BEGIN MBTOT := MBTOT - ABS(XTPV[A]); (* TOTAL MATERIAL ON BOARD *) IF XTPU[A] = EP THEN MBPWN[XTPM[A]] := MBPWN[XTPM[A]] - 1; (* REMOVE PAWN IF NECESSARY *) MBLTE := MBLTE - XTPV[A]; (* LITE ADVANTAGE *) MBEVAL; (* EVALUATE MATERIAL *) END; (* MBCAPT *) PROCEDURE MBTPAC (* REMOVE CAPTURE FROM MATERIAL BALANCE DATA. THIS IS THE INVERSE OF MBCAPT *) (A:TP); (* PIECE UNCAPTURED *) BEGIN MBTOT := MBTOT + ABS(XTPV[A]); IF XTPU[A] = EP THEN MBPWN[XTPM[A]] := MBPWN[XTPM[A]] + 1; MBLTE := MBLTE + XTPV[A]; END; (* MBTPAC *) PROCEDURE MBPROM (* EVALUATE MATERIAL BALANCE CHANGE DUE TO PAWN PROMOTION *) (A:TP); (* PIECE TO PROMOTE TO *) BEGIN MBTOT := MBTOT + ABS(XTPV[A]-XTPV[XTUMP[EP,XTPM[A]]]); (* TOTAL MATERIAL ON BOARD *) MBPWN[XTPM[A]] := MBPWN[XTPM[A]] - 1;(* COUNT PAWNS *) MBLTE := MBLTE + XTPV[A]-XTPV[XTUMP[EP,XTPM[A]]] ; MBEVAL; (* EVALUATE RESULT *) END; (* MBPROM *) PROCEDURE MBMORP (* REMOVE PAWN PROMOTION FROM MATERIAL BALANCE DATA. THIS IS THE INVERSE OF MBPROM *) (A:TP); (* PIECE PROMOTED TO *) BEGIN MBTOT := MBTOT - ABS(XTPV[A]-XTPV[XTUMP[EP,XTPM[A]]]); MBPWN[XTPM[A]] := MBPWN[XTPM[A]] + 1; MBLTE := MBLTE - (XTPV[A]-XTPV[XTUMP[EP,XTPM[A]]]); END; (* MBMORP *) PROCEDURE ADDATK (* ADD ATTACKS OF PIECE TO DATA BASE *) (A:TS); (* SQUARE OF PIECE TO ADD ATTACK *) VAR INTB : TB; (* LOOP CONTROL BOOLEAN *) INTD : TD; (* CURRENT DIRECTION FFSET *) INTE : TE; (* CURRENT DIRECTION INDEX *) INTM : TM; (* COLOR OF CURRENT PIECE *) INTP : TP; (* CURRENT PIECE *) INTT : TT; (* RUNNING SQUARE *) BEGIN INTP := MBORD[A]; (* PIECE OF INTEREST *) INTM := XTPM[INTP]; (* COLOR *) FOR INTE := XFPE[INTP] TO XLPE[INTP] DO BEGIN INTT := A; (* INITIALIZE RUNNING SQUARE *) INTB := XSPB[INTP]; (* TRUE IF SWEEP PIECE *) INTD := XTED[INTE]; (* OFFSET *) REPEAT INTT := XTLS[XTSL[INTT] + INTD]; (* STEP IN PROPER DIRECTION *) IF INTT >= 0 THEN BEGIN SETRS(ATKFR[A],INTT); SETRS(ATKTO[INTT] ,A); SETRS(ALATK[INTM],INTT); IF MBORD[INTT] <> MT THEN INTB := FALSE; END ELSE INTB := FALSE; UNTIL NOT INTB; END; END; (* ADDATK *) PROCEDURE ADDLOC (* ADD PIECE TO DATA BASE *) (A:TS; (* SQUARE WITH NEW PIECE ON IT *) B:TP); (* NEW PIECE TO ADD *) BEGIN CLRRS(TPLOC[MT],A); (* BIT BOARD OF EMPTY SQUARES *) SETRS(TPLOC[B],A); (* BIT BOARD OF ALL SAME PIECE *) SETRS(TMLOC[XTPM[B]],A); (* SIT BOARD OF ALL SAME COLOR *) SETRS(ALLOC[JNTK],A); (* BIT BOARD OF ALL PIECES *) MBORD[A] := B; (* SET NEW PIECE ON BOARD *) END; (* ADDLOC *) PROCEDURE CLSTAT; (* CLEAR POSITION STATUS *) BEGIN WITH BOARD DO BEGIN RBTM := LITE; (* WHITE TO MOVE *) RBTS := -1; (* NO ENPASSANT *) RBSQ := []; (* NO CASTLING LEGAL *) END; END; (* CLSTAT *) PROCEDURE CUTATK (* CUT ATTACKS THROUGH SQUARE *) (A:TS); (* SQUARE *) VAR INRS : RS; (* ATTACKING PIECES *) INTS : TS; (* ATTACKING PIECE SQUARE *) IMRS : RS; (* SCRATCH *) INTD : TD; (* STEP SIZE *) INTM : TM; (* ATTACKING PIECE SIDE *) INTL : TL; (* NO LONGER ATTACKED SQUARE *) INTT : TT; (* NO LONGER ATTACKED SQUARE *) BEGIN CPYRS(INRS,ATKTO[A]); (* ALL PIECES ATTACKING SQUARE *) WHILE NXTTS(INRS,INTS) DO IF XSPB[MBORD[INTS]] THEN (* IF SWEEP PIECE *) BEGIN INTD := XLLD[XTSL[A]-XTSL[INTS]]; (* STEP SIZE ON 10X12 BOARD *) INTM := XTPM[MBORD[INTS]]; (* SIDE OF ATTACKING PIECE *) INTL := XTSL[A]+INTD; (* FIRST SQUARE BEYOND PIECE *) INTT := XTLS[INTL]; (* FIRST SQUARE BEYOND PIECE ON 8X8 BOARD *) WHILE INTT > AT DO (* WHILE ON BOARD *) BEGIN CLRRS(ATKFR[INTS],INTT); (* CLEAR ATTACK MAP *) CLRRS(ATKTO[INTT],INTS); ANDRS(IMRS,ATKTO[INTT],TMLOC[INTM]); (* OTHER ATTACKS ON SQUARE BY SAME SIDE *) IF NULRS(IMRS) THEN (* IF NO ATTACKS BY THAT SIDE *) CLRRS(ALATK[INTM],INTT); (* CLEAR ATTACKS BY SIDE *) IF MBORD[INTT] = MT THEN BEGIN INTL := INTL+INTD; (* STEP BEYOND SQUARE *) INTT := XTLS[INTL]; END ELSE INTT := AT; (* STOP SCAN *) END; END; END; (* CUTATK *) PROCEDURE DELATK (* DELETE ATTACKS FROM SQUARE *) (A:TS); (* SQUARE TO REMOVE PIECE *) VAR INRS : RS; (* SQUARES ATTACKED BY PIECE ON SQUARE *) IMRS : RS; (* SCRATCH *) INTS : TS; (* SQUARE ATTACKEO BY PIECE ON SQUARE *) INTM : TM; (* SIDE OF PIECE ON SQUARE *) BEGIN CPYRS(INRS,ATKFR[A]); (* SQUARES ATTACKED BY PIECE ON SQUARE *) NEWRS(ATKFR[A]); (* CLEAR ATTACKS FROM SQUARE *) INTM := XTPM[MBORD[A]]; (* SIDE OF PIECE ON SQUARE *) WHILE NXTTS(INRS,INTS) DO (* LOOP THROUGH ALL ATTACKS BY PIECE *) BEGIN CLRRS(ATKTO[INTS],A); (* CLEAR ATTACK TO OTHER SQUARE *) ANDRS(IMRS,ATKTO[INTS],TMLOC[INTM]); (* OTHER ATTACKS BY SAME SIDE *) IF NULRS(IMRS) THEN CLRRS(ALATK[INTM],INTS); (* CLEAR ATTACKS BY SIDE *) CLRRS(TPLOC[MBORD[A]],A); (* CLEAR PIECE *) CLRRS(TMLOC[INTM],A); (* CLEAR PIECE FROM SIDE *) CLRRS(ALLOC[JNTK],A); (* CLEAR PIECE FROM ALL PIECES *) SETRS(TPLOC[MT],A); (* SET EMPTY *) MBORD[A] := MT; END; END; (* DELATK *) PROCEDURE PRPATK (* PROPAGATE ATTACKS THROUGH SQUARE *) (A:TS); (* SQUARE *) VAR INRS : RS; (* ATTACKING PIECES *) INTS : TS; (* ATTACKING PIECE SQUARE *) INTD : TD; (* STEP SIZE *) INTM : TM; (* ATTACKING PIECE SIDE *) INTL : TL; (* NEW ATTACKED SQUARE *) INTT : TT; (* NEW ATTACKEO SQUARE *) BEGIN CPYRS(INRS,ATKTO[A]); (* ALL PIECES ATTACKING SQUARE *) WHILE NXTTS(INRS,INTS) DO IF XSPB[MBORD[INTS]] THEN (* IF SWEEP PIECE *) BEGIN INTD := XLLD[XTSL[A]-XTSL[INTS]]; (* STEP SIZE ON 10X12 BOARD *) INTM := XTPM[MBORD[INTS]]; (* SIDE OF ATTACKING PIECE *) INTL := XTSL[A]+INTD; (* FIRST SQUARE BEYOND PIECE *) INTT := XTLS[INTL]; (* FIRST SQUARE BEYONO PIECE ON 8X8 BOARD *) WHILE INTT >= 0 DO (* WHILE ON BOARD *) BEGIN SETRS(ATKFR[INTS],INTT); (* SET ATTACK MAP *) SETRS(ATKTO[INTT],INTS); SETRS(ALATK[INTM],INTT); (* SET ATTACKS BY SIDE *) IF MBORD[INTT] = MT THEN BEGIN INTL := INTL+INTD; (* STEP BEYOND SQUARE *) INTT := XTLS[INTL]; END ELSE INTT := -1; (* STOP SCAN *) END; END; END; (* PRPATK *) PROCEDURE GAINIT (* UNPROCESS CAPTURE MOVE *) (A:RM); (* CAPTURE MOVE *) BEGIN WITH A DO BEGIN ADDLOC(RMFR,MBORD[RMTO]); (* PUT PIECE ON ORIGINAL SQUARE *) ADDATK(RMFR); CUTATK(RMFR); (* STOP ATTACKS AT THIS SQUARE *) DELATK(RMTO); (* REMOVE THEM FROM DESTINATION SQUARE *) ADDLOC(RMTO,RMCP); (* REPLACE CAPTURED PIECE *) ADDATK(RMTO); MBTPAC(MBORD[RMTO]); (* UPDATE SCORE *) END; END; (* GAINIT *) PROCEDURE LOSEIT (* PROCESS CAPTURE MOVE *) (A:RM); (* CAPTURE MOVE *) BEGIN WITH A DO BEGIN MBCAPT(MBORD[RMTO]); (* UPDATE SCORE *) DELATK(RMTO); (* DELETE ATTACKS OF CAPTURED PIECE *) ADDLOC(RMTO,MBORD[RMFR]); (* ADD PIECE TO DESTINATION SQUARE *) DELATK(RMFR); (* DELETE ATTACKS OF MOVING PIECE *) PRPATK(RMFR); (* PROPAGATE ATTACKS THROUGH FROM SQUARE *) ADDATK(RMTO); (* ADD ATTACKS OF MOVING PIECE *) END; END; (* LOSEIT *) PROCEDURE MOVEIT (* PROCESS ORDINARY MOVE *) (A:RM); (* ORDINARY MOVE *) BEGIN WITH A DO BEGIN ADDLOC(RMTO,MBORD[RMFR]); (* ADD PIECE TO NEW SQUARE *) CUTATK(RMTO); (* CUT ATTACKS THROUGH NEW SQUARE *) DELATK(RMFR); (* DELETE ATTACKS FROM OLD SQUARE *) PRPATK(RMFR); (* PROPAGATE ATTACKS THROUGH OLD SQUARE *) ADDATK(RMTO); (* ADD ATTACKS FROM NEW SQUARE *) END; END; (* MOVEIT *) PROCEDURE RTRKIT (* UNPROCESS ORDIMARY MOVE *) (A:RM); (* THE MOVE TO RETRACT *) BEGIN WITH A DO BEGIN ADDLOC(RMFR,MBORD[RMTO]); (* PUT PIECE ON ORIGINAL SQUARE *) CUTATK(RMFR); (* CUT ATTACKS THROUGH ORIGINAL SQUARE *) DELATK(RMTO); (* DELETE ATTACKS FROM DESTINATION SQUARE *) PRPATK(RMTO); (* PROPAGATE ATTACKS THROUGH DESTINATION SQUARE *) ADDATK(RMFR); (* ADD ATTACKS FROM ORIGINAL SQUARE *) END; END; (* RTRKIT *) PROCEDURE PAWNIT (* UNPROMOTE A PAWN *) (A:RM); (* PROMOTION MOVE *) BEGIN WITH A DO BEGIN MBMORP(MBORD[RMTO]); (* UPDATE SCORE *) MBORD[RMTO] := XTUMP[EP,XTPM[MBORD[RMTO]]]; END; END; (* PAWNIT *) PROCEDURE PROACA (* PROCESS CASTLE STATUS CHANGES *) (A:TS); (* SQUARE *) VAR INRS : RS; (* SCRATCH *) IMRS : RS; (* SCRATCH *) BEGIN CLRRS(CSTAT[JNTK],A); (* CLEAR THIS SQUARE *) ANDRS(INRS,CSTAT[JNTK],XRRS[XTSR[A]]); (* CASTLE BITS FOR THIS SIDE *) IF NOT INRSTB(INRS,XTRFS[XTSR[A],F5]) THEN (* IF KING MOVE *) ANDRS(CSTAT[JNTK],CSTAT[JNTK],XNRS[XTSR[A]]); (* CLEAR ALL CASTLE MOVES FOR SIDE *) ANDRS(IMRS,INRS,XRFS[F8]); (* KING ROOK SQUARE *) ANDRS(INRS, INRS ,XRFS[F1]); (* QUEEN ROOK SQUARE *) IORRS(INRS,INRS,IMRS); (* BOTH ROOK SQUARES *) IF NULRS(INRS) THEN (* IF BOTH ROOKS GONE *) ANDRS(CSTAT[JNTK],CSTAT[JNTK],XNRS[XTSR[A]]); END; (* PROACA *) PROCEDURE PROACS (* PROCESS MOVES AFFECTING CASTLE STATUS *) (A:RM); (* MOVE WITH RMAC *) BEGIN WITH A DO BEGIN IF INRSTB(CSTAT[JNTK],RMFR) THEN (* FROM SQUARE *) PROACA(RMFR); IF INRSTB(CSTAT[JNTK],RMTO) THEN (* TO SQUARE *) PROACA(RMTO); END; END; (* PROACS *) PROCEDURE PROMOT (* PROCESS PROMOTION *) (A: RM); (* PROMOTION MOVE *) BEGIN WITH A DO BEGIN MBPROM(XTGMP[RMPP,JNTM]); (* UPDATE SCORE *) MBORD[RMFR] := XTGMP[RMPP,JNTM]; END; END; (* PROMOT *) PROCEDURE CREATE; (* CREATE GLOBAL DATA BASE *) VAR INRS : RS; (* SCRATCH BIT BOARD *) INTM : TM; (* COLOR INDEX *) INTP : TP; (* PIECE INDEX *) INTQ : TQ; (* CASTLE TYPE INDEX *) INTS : TS; (* SQUARE INDEX *) BEGIN WITH BOARD DO BEGIN JNTW := AW+1; (* INITIALIZE MOVES STACK POINTER *) JNTK := AK; (* PLY INDEX *) JNTM := RBTM; (* SIDE TO MOVE *) NODES := 0; (* INITIALIZE TOTAL NODES *) LINDX[JNTK] := JNTW; (* MOVES ARRAY LIMIT *) SRCHM[JNTK] := H0; (* SEARCH MODE *) FOR INTS := AS TO ZS DO BEGIN NEWRS(ATKFR[INTS]); (* CLEAR ATTACKS FROM *) NEWRS(ATKTO[INTS]); (* CLEAR ATTACKS TO *) MBORD[INTS] := MT; (* CLEAR LOOKAHEAD BOARD *) END; NEWRS(ALLOC[JNTK]); (* CLEAR ALL PIECE LOCATIONS *) FOR INTP := LP TO MT DO NEWRS(TPLOC[INTP]); (* CLEAR PIECE LOCATIONS *) FOR INTM := LITE TO NONE DO BEGIN NEWRS(TMLOC[INTM]); (* CLEAR COLOR LOCATIONS *) NEWRS(ALATK[INTM]); (* CLEAR COLOR ATTACKS *) END; MBTOT := 0; MBPWN[LITE] := 0; MBPWN[DARK] := 0; MBLTE := 0; FOR INTS := AS TO ZS DO IF RBIS[INTS] <> MT THEN BEGIN ADDLOC(INTS,RBIS[INTS]); MBTPAC(RBIS[INTS]); END ELSE SETRS(TPLOC[MT],INTS); MBEVAL; (* EVALUATE MATERIAL *) CPYRS(INRS,ALLOC[JNTK]); (* COPY BIT BOARD OF ALL PIECES *) WHILE NXTTS(INRS,INTS) DO ADDATK(INTS); (* ADD ATTACKS OF ALL PIECES *) NEWRS(CSTAT[JNTK]); (* INITIALIZE CASTLING SQUARES *) FOR INTQ := LS TO DL DO IF INTQ IN RBSQ THEN IORRS(CSTAT[JNTK],CSTAT[JNTK],XSQS[INTQ]); NEWRS(ENPAS[JNTK]); (* INITIALIZE ENPASSANT SQUARE *) IF RBTS >= 0 THEN SETRS(ENPAS[JNTK],RBTS); CPYRS(GENPN[JNTK],TPLOC[XTUMP[EP,JNTM]]); NOTRS(GENTO[JNTK],TMLOC[JNTM]); NOTRS(INRS,GENPN[JNTK]); ANDRS(GENFR[JNTK],TMLOC[JNTM],INRS); END; END; (* CREATE *) PROCEDURE DNDATE (* DOWNOATE DATA BASE TO BACK OUT A MOVE *) (A: RM); (* THE MOVE TO RETRACT *) VAR INTS : TS; (* SCRATCH *) INTR : TR; (* ROOK RANK FOR CASTLING *) INTF : TF; (* ROOK FILE FOR CASTLING *) RKFR : TS; (* ROOK FROM SQUARE *) RKTO : TS; (* ROOK TO SQUARE *) BEGIN WITH A DO BEGIN CASE ORD(RMCA)*4 + ORD(RMAC)*2 + ORD(RMPR) OF 0: (* ORDINARY MOVE *) RTRKIT(A); 1: (* PAWN MOVE AND PROMOTE *) BEGIN PAWNIT(A); RTRKIT(A); END; 2: (* MISCELLANEOUS ACS *) IF RMOO THEN BEGIN (* CASTLE *) IF RMQS THEN INTF := F1 (* ROOK ON QUEEN ROOK FILE *) ELSE INTF := F8; (* ROOK ON KING ROOK FILE *) INTR := XTSR[RMFR]; (* ROOK FILE *) RKFR := XTRFS[INTR,INTF]; (* ROOK FROM SQUARE *) RKTO := (RMFR+RMTO) DIV 2; (* ROOK TO SQUARE *) ADDLOC(RKFR,MBORD[RKTO]); (* REPLACE ROOK *) DELATK(RKTO); PRPATK(RKTO); ADDATK(RKFR); RTRKIT(A); (* RETRACT KING MOVE *) END ELSE (* NOT CASTLE *) RTRKIT(A); 3:; (* NULL MOVE *) 4: (* CAPTURE *) IF RMEP THEN BEGIN (* CAPTURE ENPASSANT *) INTS := XTRFS[XTSR[RMFR],XTSF[RMTO]]; ADDLOC(INTS,RMCP); CUTATK(INTS); ADDATK(INTS); RTRKIT(A); (* RETRACT PAWN MOVE *) MBTPAC(MBORD[INTS]); (* ADD PIECE TO SCORE *) END ELSE (* CAPTURE NOT ENPASSANT *) GAINIT(A); 5: (* CAPTURE AND PROMOTE *) BEGIN PAWNIT(A); (* UNPROMOTE *) GAINIT(A); (* UNCAPTURE *) END; 6: (* CAPTURE ACS *) GAINIT(A); (* UNCAPTURE *) 7: (* CAPTURE ROOK ACS, PROMOTE *) BEGIN PAWNIT(A); GAINIT(A); END; END; JNTW := LINDX[JNTK]; (* RESET MOVE GENERATION POINTER *) JNTK := JNTK-1; (* BACK UP PLY INDEX *) JNTM := OTHER[JNTM]; (* SWITCH SIDE TO MOVE *) END; END; (* DNDATE *) FUNCTION UPDATE (* UPDATE DATA BASE FOR A MOVE *) (VAR A:RM) (* THE MOVE *) :TB; (* RETURNS TRUE IF MOVE IS LEGAL *) VAR INRS : RS; (* SCRATCH *) IMRS : RS; (* SCRATCH *) INTS : TS; (* SCRATCH *) INTF : TF; (* ROOK FILE FOR CASTLING *) INTR : TR; (* ROOK RANK FOR CASTLING *) RKTO : TS; (* ROOK DESTINATION SQUARE *) RKFR : TS; (* ROOK ORIGIN SQUARE *) BEGIN WITH A DO BEGIN JNTK := JNTK+1; (* AOVANCE PLY INDEX *) NEWRS(ENPAS[JNTK]); (* CLEAR ENPASSANT BIT BOARD *) CPYRS(CSTAT[JNTK],CSTAT[JNTK-1]); (* INITIALIZE CASTLE STATUS *) CPYRS(ALLOC[JNTK],ALLOC[JNTK-1]); (* INITIALIZE ALL LOCATIONS *) MBVAL[JNTK] := MBVAL[JNTK-1]; (* INITIALIZE MATERIAL SCORE *) LINDX[JNTK] := JNTW; (* MOVES ARRAY LIMIT *) CASE ORD(RMCA)*4 + ORD(RMAC)*2 + ORD(RMPR) OF 0: (* ORDINARY MOVE *) IF RMEP THEN BEGIN (* PAWN MOVE 2 SPACES *) SFTRS(INRS,XRSS[RMTO],S1); SFTRS(IMRS,XRSS[RMTO],S3); IORRS(INRS,INRS,IMRS); (* SQUARES NEXT TO DESTINATION *) ANDRS(INRS,INRS,TPLOC[XTUMP[EP,OTHER[JNTM]]]); (* INTERSECT WITH ENEMY PAWNS *) IF NOT NULRS(INRS) THEN SETRS(ENPAS[JNTK],(RMTO+RMFR) DIV 2); (* SET ENPASSANT SQUARE *) MOVEIT(A); (* MOVE PAWN *) END ELSE MOVEIT(A); (* MOVE PIECE *) 1: (* MOVE AND PROMOTE *) BEGIN PROMOT(A); (* PROMOTE PAWN *) MOVEIT(A); (* MOVE PROMOTED PIECE *) END; 2: (* MISCELLANEOUS ACS *) BEGIN IF RMOO THEN BEGIN (* CASTLE *) IF RMQS THEN INTF := F1 (* ROOK ON QUEEN ROOK FILE *) ELSE INTF := F8; (* ROOK ON KING ROOK FILE *) INTR := XTSR[RMFR]; (* ROOK ON KINGS RANK *) RKFR := XTRFS[INTR,INTF]; (* ROOK ORIGIN SQUARE *) RKTO := (RMFR+RMTO) DIV 2;(* ROOK DESTINATION SQUARE *) ANDRS(CSTAT[JNTK],CSTAT[JNTK] ,XNRS[INTR]); (* DISALLOW FURTHER CASTLING BY THIS SIDE *) ADDLOC(RKTO,MBORD[RKFR]); (* PUT ROOK ON NEW SQUARE *) ADDATK(RKTO); (* ADD ITS ATTACKS *) DELATK(RKFR); (* DELETE FROM ORIGINAL SQUARE *) MOVEIT(A); (* MOVE KING *) END ELSE (* NOT CASTLE *) BEGIN PROACS(A); (* PROCESS CASTLE STATUS MODS *) MOVEIT(A); (* MOVE TO OR FROM KING OR ROOK SQUARE *) END; END; 3:; (* NULL MOVE *) 4: (* CAPTURE *) IF RMEP THEN BEGIN (* CAPTURE ENPASSANT *) INTS := XTRFS[XTSR[RMFR],XTSF[RMTO]]; (* CAPTURED PAWN SQUARE *) MBCAPT(MBORD[INTS]); (* UPDATE SCORE *) DELATK(INTS); (* DELETE CAPTURED PAWN ATTACKS *) PRPATK(INTS); (* PROPAGATE ATTACKS THROUGH PAWN *) MOVEIT(A); (* MOVE CAPTURING PAWN *) END ELSE (* CAPTURE NOT ENPASSANT *) LOSEIT(A); (* PROCESS CAPTURE *) 5: (* CAPTURE AND PROMOTE *) BEGIN PROMOT(A); (* PROMOTE PAWN *) LOSEIT(A); (* PROCESS CAPTURE WITH PROMOTED PIECE *) END; 6: (* CAPTURE ACS *) BEGIN PROACS(A); (* PROCESS CASTLE STATUS MODS *) LOSEIT(A); (* PROCESS ROOK CAPTURE *) END; 7: (* CAPTURE ROOK ACS, PROMOTE *) BEGIN PROMOT(A); (* PROMOTE PAWN *) PROACS(A); (* CHANGE CASTLE STATUS *) LOSEIT(A); (* PROCESS ROOK CAPTURE *) END; END; (* INITIALIZE MOVE GENERATION *) JNTM := OTHER[JNTM]; (* SWITCH SIDE TO MOVE *) CPYRS(GENPN[JNTK],TPLOC[XTUMP[EP,JNTM]]); NOTRS(GENTO[JNTK],TMLOC[JNTM]); NOTRS(INRS,GENPN[JNTK]); ANDRS(GENFR[JNTK],TMLOC[JNTM],INRS); (* DETERMINE IF MOVE LEAVES KING IN CHECK, OR MOVES KING INTO CHECK *) ANDRS(INRS,TPLOC[XTUMP[EK,JNTM]],ALATK[OTHER[JNTM]]); RMCH := NOT NULRS(INRS); ANDRS(INRS,TPLOC[XTUMP[EK,OTHER[JNTM]]],ALATK[JNTM]); RMIL := NOT NULRS(INRS); UPDATE := NOT RMIL; IF NOT RMIL THEN (* COUNT LEGAL MOVES *) MVSEL[JNTK-1] := MVSEL[JNTK-1] + 1; (* INITIALIZE MOVE SEARCHING *) SRCHM[JNTK] := H1; NODES := NODES+1; (* COUNT NODES SEARCHED *) END; END; (* UPDATE *) PROCEDURE GENONE (* STACK ONE GENERATED MOVE *) (A:TT; (* FROM SQUARE *) B:TS); (* TO SQUARE *) VAR INRS : RS; (* SCRATCH *) BEGIN WITH MOVES[JNTW] DO BEGIN RMFR := A; (* FROM SQUARE *) RMTO := B; (* TO SQUARE *) RMCP := MBORD[B]; (* CAPTURED PIECE *) RMCA := (MBORD[B] <> MT); (* CAPTURE *) IORRS(INRS,XRSS[A],XRSS[B]); ANDRS(INRS,INRS,CSTAT[JNTK]); RMAC := NOT NULRS(INRS); (* AFFECTS CASTLE STATUS *) RMCH := FALSE; (* CHECK *) RMMT := FALSE; (* MATE *) RMIL := FALSE; (* ILLEGAL *) RMSU := FALSE; (* SEARCHED *) RMPR := FALSE; (* PROMOTION *) RMOO := FALSE; (* CASTLE *) RMEP := FALSE; (* ENPASSANT *) END; VALUE[JNTW] := 0; (* CLEAR VALUE *) IF JNTW < ZW THEN JNTW := JNTW+1; (* ADVANCE MOVES STACK POINTER *) END; (* GENONE *) PROCEDURE PWNPRO; (* GENERATE ALL PROMOTION MOVES *) VAR INTG : TG; (* PROMOTION TYPE *) BEGIN MOVES[JNTW-1].RMPR := TRUE; (* SET PROMOTION *) MOVES[JNTW-1].RMPP := PQ; (* PROMOTE TO QUEEN FIRST *) FOR INTG := PR TO PB DO (* GENERATE OTHER PROMOTIONS *) BEGIN MOVES[JNTW] := MOVES[JNTW-1]; (* COPY LAST MOVE *) MOVES[JNTW].RMPP := INTG; (* CHANGE PROMOTE TO PIECE *) JNTW := JNTW+1; (* ADVANCE MOVE INDEX *) END; END; (* PWNPRO *) PROCEDURE GENPWN (* GENERATE PAWN MOVES *) (A:RS; (* PAWNS TO MOVE *) B:RS); (* VALID DESTINATION SQUARES *) VAR INRS, IMRS : RS; (* SCRATCH *) INTS : TS; (* DESTINATION SQUARE *) BEGIN IF JNTM = LITE THEN BEGIN (* WHITE PAMWS *) SFTRS(INRS,A,S2); (* AOVANCE ONE RANK *) ANDRS(INRS,TPLOC[MT],INRS); (* ONLY TO EMPTY SQUARES *) CPYRS(IMRS,INRS); (* SAVE FOR 2 SQUARE MOVES *) ANDRS(INRS,B,INRS); (* ONLY VALID DESTINATION SQUARES *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[S2]],INTS); (* GENERATE SIMPLE PAWN MOVES *) IF INTS >= XTRFS[R8,F1] THEN PWNPRO; (* PROCESS PROMOTION *) END; ANDRS(INRS,IMRS,XRRS[R3]); (* TAKE ONLY PAWNS ON THIRD *) SFTRS(INRS,INRS,S2); (* AOVANCE ONE MORE RANK *) ANDRS(INRS, INRS, TPLOC[MT]); (* ONLY TO EMPTY SQUARES *) ANDRS(INRS,INRS,B); (* ONLY VALID DESTINATION SQUARES *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-2*XTED[S2]],INTS); (* GENERATE DOUBLE PAWN MOVES *) MOVES[JNTW-1].RMEP := TRUE; (* FLAG AS TWO SQUARES *) END; SFTRS(INRS,A,B1); (* TRY CAPTURES TO THE LEFT *) IORRS(IMRS,TMLOC[OTHER[JNTM]],ENPAS[JNTK]); (* OPPONENT PIECES + EP SQUARE *) ANDRS(IMRS,IMRS,B); (* VALID DESTINATION SQUARES *) ANDRS(INRS, INRS, IMRS) ; (* CAPTURE MOVES TO LEFT *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[B1]],INTS); (* GENERATE CAPTURE MOVE *) MOVES[JNTW-1].RMCA := TRUE; (* FLAG CAPTURE *) MOVES[JNTW-1].RMEP := INRSTB(ENPAS[JNTK],INTS); (* FLAG ENPASSANT CAPTURE *) IF MOVES[JNTW-1].RMEP THEN MOVES[JNTW-1].RMCP := DP; (* SET CAPTURED PIECE TYPE *) IF INTS >= XTRFS[R8,F1] THEN PWNPRO; (* PROCESS PROMOTION *) END; SFTRS(INRS,A,B2); (* TRY CAPTURES TO THE RIGHT *) IORRS(IMRS,TMLOC[OTHER[JNTM]],ENPAS[JNTK]); (* OPPONENT PIECES + EP SQUARE *) ANDRS(IMRS,IMRS,B); (* VALID DESTINATION SQUARES *) ANDRS(INRS,INRS,IMRS); (* CAPTURE MOVES TO LEFT *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[B2]],INTS); (* GENERATE CAPTURE MOVE *) MOVES[JNTW-1].RMCA := TRUE; (* FLAG CAPTURE *) MOVES[JNTW-1].RMEP := INRSTB(ENPAS[JNTK],INTS); (* FLAG ENPASSANT CAPTURE *) IF MOVES[JNTW-1].RMEP THEN MOVES[JNTW-1].RMCP := DP; (* SET CAPTURED PIECE TYPE *) IF INTS >= XTRFS[R8,F1] THEN PWNPRO; (* PROCESS PROMOTION *) END; END ELSE BEGIN (* BLACK PAWNS *) SFTRS(INRS,A,S4); (* ADVANCE ONE RANK *) ANDRS(INRS,TPLOC[MT],INRS); (* ONLY TO EMPTY SQUARES *) CPYRS(IMRS,INRS); (* SAVE FOR 2 SQUARE MOVES *) ANDRS(INRS,B,INRS); (* ONLY VALID DESTINATION SQUARES *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[S4]],INTS); (* GENERATE SIMPLE PAWN MOVES *) IF INTS <= XTRFS[R1,F8] THEN PWNPRO; (* PROCESS PROMOTION *) END; ANDRS(INRS,IMRS,XRRS[R6]); (* TAKE ONLY PAWNS ON THIRD *) SFTRS(INRS,INRS,S4); (* ADVANCE ONE MORE RANK *) ANDRS(INRS,INRS,TPLOC[MT]); (* ONLY TO EMPTY SQUARES *) ANDRS(INRS,INRS,B); (* ONLY VALID DESTINATION SQUARES *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-2*XTED[S4]],INTS); (* GENERATE DOUBLE PAWN MOVES *) MOVES[JNTW-1].RMEP := TRUE; (* FLAG AS TWO SQUARES *) END; SFTRS(INRS,A,B3); (* TRY CAPTURES TO THE LEFT *) IORRS(IMRS,TMLOC[OTHER[JNTM]],ENPAS[JNTK]); (* OPPONENT PIECES + EP SQUARE *) ANDRS(IMRS,IMRS,B); (* VALID DESTINATION SQUARES *) ANDRS(INRS,INRS,IMRS); (* CAPTURE MOVES TO LEFT *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[B3]],INTS); (* GENERATE PAWN CAPTURE MOVE *) MOVES[JNTW-1].RMCA := TRUE; (* FLAG CAPTURE *) MOVES[JNTW-1].RMEP := INRSTB(ENPAS[JNTK],INTS); (* FLAG ENPASSANT CAPTURE *) IF MOVES[JNTW-1].RMEP THEN MOVES[JNTW-1].RMCP := LP; (* SET CAPTURED PIECE TYPE *) IF INTS <= XTRFS[R1,F8] THEN PWNPRO; (* PROCESS PROMOTION *) END; SFTRS(INRS,A,B4); (* TRY CAPTURES TO THE RIGHT *) IORRS(IMRS,TMLOC[OTHER[JNTM]],ENPAS[JNTK]); (* OPPONENT PIECES + EP SQUARE *) ANDRS(IMRS,IMRS,B); (* VALID DESTINATION SQUARES *) ANDRS(INRS,INRS,IMRS); (* CAPTURE MOVES TO LEFT *) WHILE NXTTS(INRS,INTS) DO BEGIN GENONE(XTLS[XTSL[INTS]-XTED[B4]],INTS); (* GENERATE PAWN CAPTURE MOVE *) MOVES[JNTW-1].RMCA := TRUE; (* FLAG CAPTURE *) MOVES[JNTW-1].RMEP := INRSTB(ENPAS[JNTK],INTS) ; (* FLAG ENPASSANT CAPTURE *) IF MOVES[JNTW-1].RMEP THEN MOVES[JNTW-1].RMCP := LP; (* SET CAPTURED PIECE TYPE *) IF INTS <= XTRFS[R1,F8] THEN PWNPRO; (* PROCESS PROMOTION *) END; END; END; (* GENPWN *) PROCEDURE GENFSL (* GENERATE ALL MOVES FROM A SET OF SQUARES *) (A:RS); (* ORIGIN SET OF SQUARES *) VAR INRS : RS; (* OUTER LOOP BIT BOARD *) IMRS : RS; (* INNER LOOP BIT BOARD *) IPRS : RS; (* PAWN ORIGIN BIT BOARD *) INTS : TS; (* OUTER LOOP SQUARE NUMBER *) IMTS : TS; (* INNER LOOP SQUARE NUMBER *) BEGIN ANDRS(INRS,A,GENFR[JNTK]); (* ONLY VALID FROM SQUARES *) NOTRS(IMRS,A); ANDRS(GENFR[JNTK],GENFR[JNTK],IMRS); (* REMOVE ORIGIN SQUARES *) ANDRS(IPRS,A,GENPN[JNTK]); (* VALID PAWN FROM SQUARES *) ANDRS(GENPN[JNTK],GENPN[JNTK],IMRS); (* REMOVE PAWNS *) WHILE NXTTS(INRS, INTS) DO (* LOOP THROUGH ORIGINS *) BEGIN ANDRS(IMRS,ATKFR[INTS],GENTO[JNTK]); (* GET UNPROCESSED DESTINATION SQUARES *) WHILE NXTTS(IMRS,IMTS) DO (* LOOP THROUGH DESTINATIONS *) GENONE(INTS,IMTS); (* GENERATE MOVE *) END; GENPWN(IPRS,GENTO[JNTK]); (* GENERATE PAWN MOVES *) END; (* GENFSL *) PROCEDURE GENTSL (* GENERATE ALL MOVES TO A SET OF SQUARES *) (A:RS); (* TARGET SET OF SQUARES *) VAR INRS : RS; (* OUTER LOOP BIT BOARD *) IMRS : RS; (* INNER LOOP BIT BOARD *) IPRS : RS; (* BIT BOARD *) IMTS : TS; (* OUTER LOOP SQUARE NUMBER *) INTS : TS; (* INNER LOOP SQUARE NUMBER *) BEGIN ANDRS(INRS,A,GENTO[JNTK]); (* ONLY VALID TO SQUARES *) NOTRS(IMRS,A); ANDRS(GENTO[JNTK],GENTO[JNTK],IMRS); (* REMOVE DESTINATION SQUARES *) CPYRS(IPRS,INRS); (* SAVE FOR PAWN MOVES *) WHILE NXTTS(INRS,INTS) DO (* LOOP THROUGH DESTINATIONS *) BEGIN ANDRS(IMRS,ATKTO[INTS],GENFR[JNTK]); (* GET PIECES OF SIDE TO MOVE *) WHILE NXTTS(IMRS,IMTS) DO (* LOOP THROUGH ORIGINS *) GENONE(IMTS,INTS); (* GENERATE MOVE *) END; GENPWN(GENPN[JNTK],IPRS); (* GENERATE PAWN MOVES *) END; (* GENTSL *) PROCEDURE GENCAP; (* GENERATE CAPTURE MOVES *) VAR INRS : RS; (* DESTINATION SQUARES *) BEGIN IORRS(INRS,ENPAS[JNTK],TMLOC[OTHER[JNTM]]); GENTSL(INRS); (* GENERATE MOVES TO ENEMY SQUARES *) END; (* GENCAP *) PROCEDURE GENCAS; (* GENERATE CASTLE MOVES *) VAR INTQ : TQ; (* CASTLE TYPE INDEX *) INRS : RS; (* OCCUPIED SQUARES TEST *) IMRS : RS; (* ATTACKED SQUARES TEST *) BEGIN FOR INTQ := XTMQ[JNTM] TO SUCC(XTMQ[JNTM]) DO IF INRSTB(CSTAT[JNTK],XTQS[INTQ]) THEN (* IF CASTLING IS LEGAL *) BEGIN ANDRS(INRS,XRQSO[INTQ],ALLOC[JNTK]); (* CHECK OCCUPIED SQUARES *) ANDRS(IMRS,XRQSA[INTQ],ALATK[OTHER[JNTM]]); (* CHECK ATTACKED SQUARES *) IF NULRS(INRS) AND NULRS(IMRS) THEN (* IF CASTLING IS LEGAL AND POSSIBLE *) BEGIN MOVES[JNTW] := XRQM[INTQ]; (* GENERATE CASTLING MOVE *) VALUE[JNTW] := 0; JNTW := JNTW+1; END; END; END; (* GENCAS *) PROCEDURE GENALL; (* GENERATE ALL LEGAL MOVES *) BEGIN GENFSL(ALLOC[JNTK]); (* GENERATE SIMPLE MOVES *) GENCAS; (* GENERATE CASTLE MOVES *) END; (* GENALL *) PROCEDURE LSTMOV; (* LIST LEGAL PLAYERS MOVES *) VAR INTW : TW; (* MOVES INDEX *) BEGIN CREATE; (* CREATE DATA BASE *) GENALL; (* GENERATE ALL MOVES *) FOR INTW := AW+1 TO JNTW-1 DO BEGIN IF UPDATE(MOVES[INTW]) THEN; (* SET ILLEGAL FLAG *) DNDATE(MOVES[INTW]); END; END; (* LSTMOV *) PROCEDURE THEMOV (* MAKE THE MOVE FOR REAL *) (A:RM); (* THE MOVE TO MAKE *) VAR INTB : TB; (* SCRATCH *) INRS : RS; (* SCRATCH *) INTQ : TQ; (* CASTLE TYPE INDEX *) INTS : TS; (* SCRATCH *) BEGIN LSTMV := A; (* SAVE AS PREVIOUS MOVE *) INTB := UPDATE(A); (* UPDATE THE DATA BASE *) WITH BOARD DO (* AND COPY ALL THE RELEVANT DATA BACK DONN *) BEGIN RBTM := JNTM; (* SIDE TO MOVE *) CPYRS(INRS,ENPAS[JNTK]); IF NXTTS(INRS,INTS) THEN (* FIND ENPASSANT SQUARE *) RBTS := INTS ELSE RBTS := AT; IF JNTM = DARK THEN RBTI := RBTI+1; (* ADVANCE MOVE NUMBER *) FOR INTQ := LS TO DL DO IF INRSTB(CSTAT[JNTK],XTQS[INTQ]) THEN RBSQ := RBSQ+[INTQ] (* CASTLE LEGAL *) ELSE RBSQ := RBSQ-[INTQ]; (* CASTLE NOT LEGAL *) FOR INTS := AS TO ZS DO RBIS[INTS] := MBORD[INTS]; (* COPY POSITION *) END; END; (* THEMOV *) PROCEDURE EVALU8; (* EVALUATE CURRENT POSITION *) VAR INTV : TV; (* SCORE *) FUNCTION EVKING (* EVALUATE KING *) (A:RS; (* KING BIT BOARD *) B:RS): TV; (* FRIENDLY PAWN BIT BOARD *) VAR INTS : TS; (* SCRATCH *) INRS : RS; (* SCRATCH *) INTV : TV; (* SCRATCH *) BEGIN ANDRS(INRS,A,CORNR); IF NULRS(INRS) THEN (* KING NOT IN CORNER *) INTV := 0 ELSE INTV := FKSANQ; (* KING SAFELY IN CORNER *) INRS := A; IF NXTTS(INRS,INTS) THEN BEGIN ANDRS(INRS,ATKFR[INTS],B); (* FIND PAWNS NEXT TO KING *) INTV := INTV + CNTRS(INRS)*FKPSHD; (* CREDIT EACH CLOSE PAWN *) END; EVKING := INTV; (* RETURN KING SCORE *) END; (* EVKING *) FUNCTION EVMOBL (* EVALUATE MOBILITY *) (A,B:TP): TV; (* PIECE TYPES TO EVALUATE *) VAR INRS : RS; (* SCRATCH *) INTS : TS; (* SCRATCH *) INTV : TV; (* SCRATCH *) BEGIN IORRS(INRS,TPLOC[A],TPLOC[B]); (* MERGE PIECE TYPES *) INTV := 0; (* INITIALIZE COUNT *) WHILE NXTTS(INRS,INTS) DO (* COUNT ATTACKS *) INTV := INTV + CNTRS(ATKFR[INTS]); EVMOBL := INTV; (* RETURN TOTAL ATTACKS *) END; (* EVMOBL *) FUNCTION EVPAWN (* EVALUATE PAWNS *) (A:RS; (* LOCATION OF PAWNS *) B:TE; (* PAWN FORWARD DIRECTION *) C:TR): TV; (* PAWN HOME RANK *) VAR INRS : RS; (* SCRATCH *) IMRS : RS; (* SCRATCH *) INTS : TS; (* SCRATCH *) INTV : TV; (* SCRATCH *) BEGIN SFTRS(INRS,A,S1); ANDRS(INRS,INRS,A); (* BIT SET FOR SIDE BY SIDE *) INTV := CNTRS(INRS)*FPFLNX; (* SCORE PHALANX *) SFTRS(INRS,A,B1); ANDRS(INRS, INRS, A); (* SIT SET FOR PAWN DEFENSE *) INTV := INTV + CNTRS(INRS)*FPCONN; (* CREDIT CONNECTED PAWNS *) SFTRS(INRS,A,B2); ANDRS(INRS, INRS, A); INTV := INTV + CNTRS(INRS)*FPCONN; (* AND OTHER CONNECTED PAWNS *) SFTRS(INRS,A,B); (* MOVE FORWARD *) NOTRS(IMRS,TPLOC[MT]); (* OCCUPIED SQUARES *) ANDRS(INRS, INRS ,IMRS); (* BLOCKED PAWNS *) INTV := INTV - CNTRS(INRS)*FPBLOK; (* PENALIZE BLOCKED PAWNS *) CPYRS(INRS,A); WHILE NXTTS(IMRS,INTS) DO (* FOR EACH PAWN *) INTV := INTV +(ABS(ORD(C)-ORD(XTSR[INTS])))*FPADCR[XTSF[INTS]]; (* CREDIT PAWN ADVANCEMENT *) EVPAWN := INTV; (* RETURN PAWN SCORE *) END; (* EVPAWN *) FUNCTION EVROOK (* EVALUATE HOOKS *) (A:RS; (* ROOK LOCATIONS *) B: RS): TV; (* SEVENTH RANK *) VAR INTV : TV; (* SCRATCH *) INTI : TI; (* SCRATCH *) INTS : TS; (* SCRATCH *) INRS : RS; (* SCRATCH *) BEGIN INTV := 0; (* INITIALIZE *) INRS := A; IF NXTTS(INRS,INTS) THEN (* LOCATE FIRST ROOK *) BEGIN ANDRS(INRS,A,ATKFR[INTS]); IF NOT NULRS(INRS) THEN (* ROOK ATTACKS FRIENDLY ROOK *) INTV := INTV + FRDUBL; (* GIVE DOUBLED ROOK CREDIT *) END; ANDRS(INRS,A,B); (* ROOKS ON SEVENTH *) INTI := CNTRS(INRS); EVROOK := INTV + INTI*INTI*FRK7TH; (* CREDIT ROOKS ON SEVENTH *) END; (* EVROOK *) BEGIN IF XTMV[JNTM]+MBVAL[JNTK] + MAXPS <= BSTVL[JNTK-2] THEN (* MOVE WILL PRUNE ANYWAY *) INTV := XTMV[JNTM] + MBVAL[JNTK] ELSE BEGIN INTV := ( FWPAWN*(EVPAWN(TPLOC[LP],S2,R2)-EVPAWN(TPLOC[DP],S4,R7)) + FWMINM*(EVMOBL(LB,LN) -EVMOBL(DB,DN) ) + FWMAJM*(EVMOBL(LR,LQ) -EVMOBL(DR,DQ) ) + FWROOK*(EVROOK(TPLOC[LR],XRRS[R7]) -EVROOK(TPLOC[DR],XRRS[R2]) ) + FWKING*(EVKING(TPLOC[LK],TPLOC[LP]) -EVKING(TPLOC[DK],TPLOC[DP]) ) ) DIV 64; MAXPS := MAX(MAXPS,ABS(INTV)); INTV := XTMV[JNTM] *(MBVAL[JNTK]+INTV); END; IF SWTR THEN BEGIN WRITE(' EVALU8',JNTK,JNTW,INDEX[JNTK],INTV); PRIMOV(MOVES[INDEX[JNTK]]); END; VALUE[INDEX[JNTK]] := INTV; (* RETURN SCORE *) END; (* EVALU8 *) FUNCTION SEARCH (* SEARCH LOOK-AHEAD TREE *) : TW; (* RETURNS THE BEST MOVE *) LABEL 11, (* START NEW PLY *) 12, (* TRY DIFFERENT FIRST MOVE *) 13, (* FLOAT VALUE BACK UP *) 14, (* FIND ANOTHER MOVE *) 15, (* BACK UP A PLY *) 16; (* EXIT SEARCH *) var jumpin: boolean; { added jumpin var [sam] } PROCEDURE NEWBST (* SAVE BEST MOVE INFORMATION *) (A:TK); (* PLY OF BEST MOVE *) VAR INTW : TW; (* MOVES INDEX *) INRM : RM; (* SCRATCH *) BEGIN BSTMV[A] := INDEX[A+1]; (* SAVE BEST MOVE *) IF A = AK THEN (* AT FIRST PLY *) BEGIN INRM := MOVES[BSTMV[A]]; (* SAVE BEST MOVE *) FOR INTW := BSTMV[A]-1 DOWNTO AW+1 DO MOVES[INTW+1] := MOVES[INTW]; (* MOVE OTHER MOVES DOWN *) MOVES[AW+1] := INRM; (* PUT BEST AT BEGINNING *) BSTMV[AK] := AW+1; (* POINTS TO BEST MOVE *) END ELSE IF NOT MOVES[BSTMV[A]].RMCA THEN KILLR[JNTK] := MOVES[BSTMV[A]];(* SAVE KILLER MOVE *) END; (* NEWBST *) FUNCTION MINMAX (* PERFORM MINIMAX OPERATION *) (A:TK) (* PLY TO MINIMAX AT *) : TB; (* TRUE IF REFUTATION *) BEGIN MINMAX := FALSE; (* DEFAULT IS NO PRUNING *) IF SWTR THEN WRITE(' MINMAX',A,-BSTVL[A-1],BSTVL[A],-BSTVL[A+1]); IF -BSTVL[A+1] > BSTVL[A] THEN BEGIN BSTVL[A] := -BSTVL[A+1]; NEWBST(A); (* SAVE BEST MOVE *) MINMAX := BSTVL[A+1] <= BSTVL[A-1]; (* RETURN TRUE IF REFUTATION *) IF SWTR THEN WRITE(' NEW BEST. PRUNE: ',BSTVL[A+1] <= BSTVL[A-1]); END; IF SWTR THEN WRITELN; (* PRINT TRACE LINE *) END; (* MINMAX *) PROCEDURE SCOREM; (* SCORE MATE *) BEGIN MOVES[INDEX[JNTK]].RMMT := TRUE; (* INDICATE MATE *) IF MOVES[INDEX[JNTK]].RMCH THEN (* CHECK MATE *) VALUE[INDEX[JNTK]] := 64*JNTK - ZV ELSE (* STALEMATE *) VALUE[INDEX[JNTK]] := 0; IF SWTR THEN WRITELN(' SCOREM',JNTK,JNTW, INDEX[JNTK],VALUE[INDEX[JNTK]]); END; (* SCOREM *) FUNCTION SELECT (* SELECT NEXT MOVE TO SEARCH *) : TB; (* TRUE IF MOVE RETURNED *) LABEL 21, (* NEW SEARCH MODE *) 22; (* EXIT SELECT *) VAR INTB : TB; (* RETURN VALUE *) INTK : TK; (* SCRATCH *) INTW : TW; (* MOVE INDEX *) IMTW : TW; (* SCRATCH *) INTV : TV; (* SCRATCH *) PROCEDURE SELDON; (* SELECT EXIT - DONE. CALLED WHEN NO FURTHER MOVES ARE TO BE SEARCHED FROM THIS POSITION. THE CURRENT POSITION MUST HAVE BEEN EVALUATED. *) BEGIN INTB := FALSE; (* RETURN NO MOVE SELECTED *) IF SWTR THEN WRITELN(' SELECT', JNTK, ' END.'); GOTO 22; (* EXIT SELECT *) END; (* SELDON *) PROCEDURE SELMOV (* SELECT EXIT - SEARCH. CALLED WHEN A MOVE TO BE SEARCHED HAS BEEN FOUND. *) (A:TW); (* INDEX TO SELECTED MOVE *) BEGIN INTB := TRUE; (* RETURN MOVE SELECTED *) INDEX[JNTK+1] := A; (* POINT TO SELECTED MOVE *) MOVES[A].RMSU := TRUE; (* FLAG MOVE AS SEARCHED *) IF SWTR THEN BEGIN WRITE(' SELECT',JNTK,ORD(SRCHM[JNTK]),A); PRIMOV(MOVES[A]); END; GOTO 22; (* EXIT SELECT *) END; (* SELMOV *) PROCEDURE SELNXT (* SELECT EXIT - NEW MODE. CALLED WHEN A NEW SEARCH MODE IS TO BE SELECTED *) (A:TH); (* NEW SEARCH MODE *) BEGIN INDEX[JNTK+1] := LINDX[JNTK]-1; (* RESET MOVES POINTER *) SRCHM[JNTK] := A; (* CHANGE SEARCH MODE *) GOTO 21; (* EXECUTE NEXT MODE *) END; (* SELNXT *) PROCEDURE SELANY; (* SEARCH ALREADY GENERATED AND NOT ALREADV SEARCHED *) VAR INTW : TW; (* MOVES INDEX *) BEGIN FOR INTW := INDEX[JNTK+1]+1 TO JNTW-1 DO IF NOT MOVES[INTW].RMSU THEN SELMOV(INTW); END; (* SELANY *) BEGIN 21: (* NEW SEARCH MOOE *) CASE SRCHM[JNTK] OF H0: (* INITIALIZE FOR NEW MOVE *) BEGIN MVSEL[JNTK] := 0; (* CLEAR MOVES SEARCHED *) INTV := BSTVL[JNTK-2]; (* SAVE ALPHA *) BSTVL[JNTK-2] := -ZV; (* INHIBIT PRUNING IN EVALU8 *) MAXPS := 0; (* INITIALIZE NAXIMUM POSITIONAL SCORE *) GENALL; (* GENERATE ALL MOVES *) FOR INTW := AW+1 TO JNTW-1 DO BEGIN IF UPDATE(MOVES[INTW]) THEN BEGIN INDEX[JNTK] := INTW; (* POINT TO CURRENT HOVE *) EVALU8; (* SCORE POSITION *) END; DNDATE(MOVES[INTW]); END; BSTVL[JNTK-2] := INTV; (* RESTORE ALPHA *) SORTIT(VALUE,MOVES,JNTW-1); (* SORT PRELIMINARY SCORES *) FOR INTK := AK TO ZK DO KILLR[INTK] := NULMV; (* CLEAR KILLER TABLE *) IF SWTR OR SWPS THEN FOR INTW := AW+1 TO JNTW-1 DO BEGIN WRITE(' PRELIM',INTW,VALUE[INTW]); PRIMOV(MOVES[INTW]); (* PRINT PRELIMINARY SCORES *) IF INTW/LPP = INTW DIV LPP THEN PAUSER; END; SELNXT(H6); (* SEARCH ALL MOVES *) END; H1: (* INITIALIZE AT NEW DEPTH *) BEGIN MVSEL[JNTK] := 0; (* CLEAR MOVES SEARCHED *) IF JNTK > JMTK THEN BEGIN EVALU8; (* EVALUATE CURRENT POSITION *) INDEX[JNTK+1] := AW; BSTVL[JNTK+1] := -VALUE[INDEX[JNTK]]; IF MINMAX(JNTK) OR (JNTK = ZK) THEN SELDON; (* THIS MOVE PRUNES *) SRCHM[JNTK] := H2; (* CAPTURE SEARCH *) END ELSE SRCHM[JNTK] := H3; (* CAPTURES IN FULL SEARCH *) GENCAP; (* GENERATE CAPTURES *) SELNXT(SRCHM[JNTK]); (* CHANGE SEARCH MODE *) END; H2: (* CAPTURE SEARCH *) BEGIN INTW := AW; (* BEST MOVE POINTER *) INTV := AV; (* BEST VALUE *) FOR IMTW := LINDX[JNTK] TO JNTW-1 DO WITH MOVES[IMTW] DO IF NOT RMSU THEN IF ABS(XTPV[RMCP]) > INTV THEN BEGIN INTV := ABS(XTPV[RMCP]); INTW := IMTW; END; IF INTW <> AW THEN (* MOVE FOUND *) SELMOV(INTW) (* SELECT BIGGEST CAPTURE *) ELSE SELDON; (* QUIT *) END; H3: (* FULL WIDTH SEARCH - CAPTURES *) BEGIN INTW := AW; (* BEST MOVE POINTER *) INTV := AV; (* BEST VALUE *) FOR IMTW := LINDX[JNTK] TO JNTW-1 DO WITH MOVES[IMTW] DO IF NOT RMSU THEN IF ABS(XTPV[RMCP]) > INTV THEN BEGIN INTV := ABS(XTPV[RMCP]); INTW := IMTW; END; IF INTW <> AW THEN (* MOVE FOUND *) SELMOV(INTW) (* SELECT BIGGEST CAPTURE *) ELSE IF NOT NULMVB(KILLR[JNTK]) THEN BEGIN IMTW := JNTW; (* SAVE CURRENT MOVES INDEX *) GENFSL(XRSS[KILLR[JNTK].RMFR]); (* GENERATE MOVE BY KILLER *) SRCHM[JNTK] := H4; (* SET NEXT SEARCH MODE *) FOR INTW := IMTW TO JNTW-1 DO (* LOOK AT MOVES BY KILLER *) IF KILLR[JNTK].RMTO = MOVES[INTW].RMTO THEN SELMOV(INTW); (* SELECT KILLER MOVE *) END; SELNXT(H4); (* GO TO NEXT STATE *) END; H4: (* INITIALIZE SCAN OF CASTLE MOVES AND OTHER MOVES BY KILLER PIECE *) BEGIN GENCAS; (* GENERATE CASTLE MOVES *) SELNXT(H5); (* GO TO NEXT STATE *) END; H5: (* FULL WIDTH SEARCH - CASTLES AND OTHER MOVES BY KILLER PIECE *) BEGIN SELANY; (* SELECT ANY MOVE *) GENFSL(ALLOC[JNTK]); (* GENERATE REMAINING MOVES *) SELNXT(H6); (* NEXT SEARCH MODE *) END; H6: (* FULL MIOTH SEARCH - REMAINING MOVES *) BEGIN SELANY; (* SELECT ANYTHING ON LIST *) IF MVSEL[JNTK] = 0 THEN SCOREM; (* SCORE MATE *) SELDON; (* EXIT SELECT *) END; H7: (* RESEARCH FIRST PLY *) BEGIN JNTW := LINDX[AK+1]; (* POINT TO ALREADY GENERATED MOVES *) MVSEL[AK] := 0; (* RESET MOVES SEARCHED *) FOR INTW := AW+1 TO JNTW-1 DO MOVES[INTW].RMSU := FALSE; (* CLEAR SEARCHED BIT *) IF SWTR THEN WRITELN(' REDO ',JNTK,BSTVL[AK-2],BSTVL[AK-1]); SELNXT(H6); (* SEARCH ALL MOVES *) END; END; 22: (* SELECT EXIT *) SELECT := INTB; (* RETURN VALUE *) END; (* SELECT *) BEGIN (* SEARCH *) jumpin := false; { set no jumpin [sam] } BSTMV[AK] := AW; (* INITIALIZE MOVE *) INDEX[JNTK] := AW; (* INITIALIZE TREE *) MOVES[AW] := LSTMV; (* INITIALIZE MOVE *) EVALU8; (* INITIAL GUESS AT SCORE *) BSTVL[AK-2] := VALUE[AW] - WINDOW; (* INITIALIZE ALPHA-BETA WINDON *) BSTVL[AK-1] := -VALUE[AW] - WINDOW; JMTK := AK+1; (* INITIALIZE ITERATION NUMBER *) WHILE (NODES < FNODEL) AND (JNTK < MAX(ZK DIV 2, ZK-8)) DO BEGIN 11: (* START NEW PLY *) BSTVL[JNTK] := BSTVL[JNTK-2]; (* INITIALIZE ALPHA *) 12: (* DIFFERENT FIRST MOVE *) IF NOT SELECT and not jumpin THEN BEGIN BSTVL[JNTK] := VALUE[INDEX[JNTK]]; NEWBST(JNTK); END ELSE BEGIN if jumpin then goto 13; { go jumpin location } IF UPDATE(MOVES[INDEX[JNTK+1]]) THEN GOTO 11 (* START NEW PLY *) ELSE BEGIN DNDATE(MOVES[INDEX[JNTK]]); GOTO 12; (* FIND ANDTHER MOVE *) END; 13: (* FLOAT VALUE BACK *) jumpin := false; { set no jumpin [sam] } IF MINMAX(JNTK) THEN GOTO 15; (* PRUNE *) 14: (* FIND ANOTHER MOVE AT THIS PLY *) IF SELECT THEN IF UPDATE(MOVES[INDEX[JNTK+1]]) THEN GOTO 11 (* START NEW PLY *) ELSE BEGIN DNDATE(MOVES[INDEX[JNTK]]); GOTO 14; (* FIND ANOTHER MOVE *) END; END; 15: (* BACK UP A PLY *) IF JNTK > AK THEN BEGIN (* NOT DONE WITH ITERATION *) DNDATE(MOVES[INDEX[JNTK]]); (* RETRACT MOVE *) jumpin := true; { set jumpin active } GOTO 12 {13}; END; (* DONE WITH ITERATION *) IF (BSTVL[AK] <= BSTVL[AK-2]) OR (BSTVL[AK] >= -BSTVL[AK-1]) THEN BEGIN (* NO MOVE FOUND *) IF MVSEL[AK] = 0 THEN BEGIN (* NO LEGAL MOVES *) GOTO 16; (* GIVE UP *) END; BSTVL[AK-2] := -ZV; (* SET ALPHA-BETA WINDOW LARGE *) BSTVL[AK-1] := -ZV; SRCHM[AK] := H7; JNTW := AK+1; GOTO 11; (* TRY AGAIN *) END; BSTVL[AK-2] := BSTVL[AK] - WINDOW; (* SET ALPHA BETA WINOOW *) BSTVL[AK-1] := -BSTVL[AK] - WINDOW; JMTK := JMTK+1; (* ADVANCE ITERATION NUMBER *) SRCHM[AK] := H7; END; 16: (* EXIT SEARCH *) SEARCH := BSTMV[AK]; (* RETURN BEST MOVE *) END; (* SEARCH *) PROCEDURE READER; (* READ INPUT FROM USER *) LABEL 11; (* COMMAND FINISHED EXIT *) VAR INRA : RA; (* SCRATCH TOKEN *) INTJ : TJ; (* ECHO COMMAND INDEX *) PROCEDURE RDRERR(A:RN); (* PRINT DIAGNOSTIC AND EXIT *) VAR INTJ : TJ; (* STRING INDEX *) INTN : TN; (* HESSAGE INDEX *) BEGIN IF NOT SWEC THEN (* ECHO LINE IF NOT ALREADY DONE *) BEGIN WRITE(' '); FOR INTJ := AJ TO ZJ-1 DO WRITE(ILINE[INTJ]); (* WRITE INPUT LINE *) WRITELN(' '); END; FOR INTJ := AJ TO JNTJ DO WRITE(' '); (* LEADING BLANKS BEFORE ARROW *) WRITELN('^'); (* POINTER TO ERROR *) FOR INTN := AN TO ZN DO WRITE(A[INTN]); (* WRITE DIAGNOSTIC *) WRITELN; GOTO 11; (* COMMAND EXIT *) END; (* RDRERR *) FUNCTION RDRGNT(VAR A:RA):TB; (* GET NEXT TOKEN FROM COMMAND RETURNS TOKEN IN A. RETURNS TRUE IF NON-EMPTY TOKEN. A TOKEN IS ANY CONSECUTIVE COLLECTION OF ALPHANUMERIC CHARACTERS. LEADING SPECIAL CHARACTERS IGNORED. *) VAR INTJ : TJ; (* STRING INDEX *) BEGIN WHILE (JNTJ < ZJ) AND (ORD(ILINE[JNTJ]) >= ORD('+')) DO JNTJ := JNTJ+1; A := ' '; INTJ := AA; WHILE (JNTJ < ZJ) AND (INTJ < ZA) AND (ILINE[JNTJ] IN ['A'..'Z', '0'..'9']) DO BEGIN A[INTJ] := ILINE[JNTJ]; (* COPY CHARACTER TO TOKEN *) INTJ := INTJ+1; (* ADVANCE POINTERS *) JNTJ := JNTJ+1; END; RDRGNT := INTJ <> AA; (* RETURN TRUE IF ANYTHING MOVED *) WHILE (INTJ < ZJ) AND (JNTJ < ZJ) AND (ILINE[JNTJ] IN ['A'..'Z', '0'..'9']) DO JNTJ := JNTJ+1; (* SKIP REST OF TOKEN *) END; (* RDRGNT *) PROCEDURE RDRSFT; (* SKIP FIRST TOKEN IN COMMAND LINE *) VAR INRA : RA; (* SCRATCH *) INTB : TB; (* SCRATCH *) BEGIN JNTJ := AJ; (* INITIALIZE SCAN *) INTB := RDRGNT(INRA); (* THROW AWAY FIRST TOKEN *) END; (* RDRSFT *) PROCEDURE RDRCMD (* TEST FOR AND EXECUTE COMMAND EXITS TO COMMAND EXIT IF COMMAND IS PROCESSED. *) (A:RA; (* POTENTIAL COMMAND KEYWORD *) PROCEDURE XXXCMD); (* PROCEDURE TO EXECUTE COMNAND *) BEGIN IF INRA = A THEN BEGIN XXXCMD; (* EXECUTE COMMAND *) GOTO 11; (* EXIT *) END; END; (* RDRCMD *) PROCEDURE RDLINE; (* GET NEXT INPUT LINE FROM USER *) VAR INTC : TC; (* SCRATCH *) INTJ : TJ; (* STRING INDEX *) BEGIN READLN; (* ADVANCE TO NEXT LINE *) INTJ := AJ; WHILE NOT EOLN AND (INTJ < ZJ) DO BEGIN READ(ICARD[INTJ]); (* COPY INPUT LINE *) INTJ := INTJ+1; END; WHILE NOT EOLN DO READ(INTC); (* SKIP REST OF INPUT LINE *) WHILE INTJ < ZJ DO BEGIN ICARD[INTJ] := ' '; (* BLANK REST OF LINE *) INTJ := INTJ+1; END; ICARD[ZJ] := ';'; (* SET END OF COMMAND *) JMTJ := AJ; (* RESET INPUT LINE POINTER *) END; (* RDLINE *) FUNCTION RDRMOV: TB; (* EXTRACT NEXT COMMAND FROM INPUT LINE. RETURNS TRUE IF NON-EMPTY COMMAND. *) VAR IMTJ : TJ; (* STORING POINTER *) BEGIN WHILE (JMTJ < ZJ) AND (ICARD[JMTJ] = ' ') DO JMTJ := JMTJ+1; (* SKIP LEADING BLANKS *) IMTJ := AJ; WHILE (JMTJ < ZJ) AND (ICARD[JMTJ] <> ';') DO BEGIN ILINE[IMTJ] := ICARD[JMTJ]; IMTJ := IMTJ+1; JMTJ := JMTJ+1; END; IF (ICARD[JMTJ] = ';') AND (JMTJ < ZJ) THEN JMTJ := JMTJ+1; (* SKIP SEMI-COLON *) RDRMOV := IMTJ <> AJ; (* RETURN TRUE IF NON-EMPTY *) WHILE IMTJ < ZJ DO BEGIN ILINE[IMTJ] := ' '; (* BLANK FILL LINE *) IMTJ := IMTJ+1; END; ILINE[ZJ] := ';'; (* STORE COMMAND TERMINATOR *) JNTJ := AJ; (* PRESET COMNAND SCAN *) END; (* RDRMOV *) FUNCTION RDRNUM: TI; (* CRACK NUMBER FROM COMMAND LINE. RETURNS NUMBER IF NO ERROR. EXITS TO COMMAND EXIT IF ERROR. *) VAR INTB : TB; (* SIGN *) INTI : TI; (* VALUE *) BEGIN WHILE (JNTJ < ZJ) AND (ILINE[JNTJ] = ' ') DO JNTJ := JNTJ+1; (* SKIP LEADING BLANKS *) IF ILINE[JNTJ] = '-' THEN BEGIN INTB := TRUE; (* NUMBER IS NEGATIVE *) JNTJ := JNTJ+1; (* ADVANCE CHARACTER POINTER *) END ELSE BEGIN INTB := FALSE; (* NUMBER IS POSITIVE *) IF ILINE[JNTJ] = '+' THEN JNTJ := JNTJ+1; (* SKIP LEADING + *) END; INTI := 0; WHILE ILINE[JNTJ] IN ['0'..'9'] DO BEGIN IF INTI < MAXINT/10 THEN INTI := 10*INTI+ORD(ILINE[JNTJ])-ORD('0') ELSE RDRERR(' NUMBER TOO LARGE '); JNTJ := JNTJ+1; (* ADVANCE *) END; IF ILINE[JNTJ] IN ['A'..'Z'] THEN RDRERR(' DIGIT EXPECTED '); IF INTB THEN INTI := -INTI; (* COMPLEMENT IF NEGATIVE *) RDRNUM := INTI; (* RETURN NUMBER *) END; (* RDRNUM *) PROCEDURE BOACMD; (* COMMAND - SET UP POSITION *) VAR INTM : TM; (* COLOR *) INTS : TS; (* POSITION ON BOARD *) INTS1 : TS; (* POSITION ON BOARD added to avoid threat [sam] *) PROCEDURE BOAADV(A:TI); (* ADVANCE IN FILES *) BEGIN IF INTS+A < ZS THEN INTS := INTS+A ELSE INTS := ZS; END; (* BOAADV *) PROCEDURE BOASTO(A:TP); (* STORE PIECE ON BOARD *) BEGIN BOARD.RBIS[INTS] := A; IF INTS < ZS THEN INTS := INTS+1; END; (* BOASTO *) BEGIN (* BOACMD *) CLSTAT; (* CLEAR STATUS FLAGS *) LSTMV := NULMV; (* CLEAR PREVIOUS MOVE *) FOR INTS1 := AS TO ZS DO BOARD.RBIS[INTS1] := MT; (* CLEAR BOARD *) INTM := LITE; INTS := 0; REPEAT IF ILINE[JNTJ] IN ['P','R','N','B','Q','K','L','D','1'..'8'] THEN CASE ILINE[JNTJ] OF 'P': BOASTO(XTUMP[EP,INTM]); 'R': BOASTO(XTUMP[ER,INTM]); 'N': BOASTO(XTUMP[EN,INTM]); 'B': BOASTO(XTUMP[EB,INTM]); 'Q': BOASTO(XTUMP[EQ,INTM]); 'K': BOASTO(XTUMP[EK,INTM]); 'L': INTM := LITE; 'D': INTM := DARK; '1','2','3','4','5','6','7','8': BOAADV(ORD(ILINE[JNTJ])-ORD('0')); END ELSE IF ILINE[JNTJ] IN ['A'..'Z', '0'..'9'] THEN BEGIN FOR INTS1 := AS TO ZS DO BOARD.RBIS[INTS1] := MT; CLSTAT; (* CLEAR STATUS *) RDRERR(' ILLEGAL BOARD OPTION '); END; JNTJ := JNTJ+1; UNTIL JNTJ = ZJ; END; (* BOACMD *) PROCEDURE ENDCMD; (* COMMAND - END PROGRAM *) BEGIN GOTO 9; (* END PROGRAM *) END; (* ENDCMD *) PROCEDURE GONCMD; (* COMMAMO - GO N MOVES *) BEGIN GOING := RDRNUM; (* CRACK NUMBER *) IF GOING <= 0 THEN GOING := 1; jumpin := true; { [sam] set jumpin flag } GOTO 2; (* EXECUTE MACHINES MOVE *) END; (* GONCMD *) PROCEDURE INICMD; (* COMMAND - INITIALIZE FOR A NEW GAME *) BEGIN GOTO 1; (* INITIALIZE FOR A NEW GAME *) END; (* INICMD *) PROCEDURE LETCMD; (* COMMAND - CHANGE VARIABLE *) LABEL 21; (* LET COMMAND EXIT *) PROCEDURE LETONE (* TEST FOR AND SET ONE VARIABLE *) (A:RA; (* VARIABLE NAME *) VAR B:TI); (* VARIABLE *) BEGIN IF A = INRA THEN BEGIN B := RDRNUM; (* GET VALUE *) GOTO 21; (* EXIT *) END; END; (* LETONE *) BEGIN IF RDRGNT(INRA) THEN BEGIN LETONE('FKPSHD ',FKPSHD); LETONE('FKSANQ ',FKSANQ); LETONE('FMAXMT ',FMAXMT); LETONE('FNODEL ',FNODEL); LETONE('FPADQR ',FPADCR[F1]); LETONE('FPADQN ',FPADCR[F2]); LETONE('FPADQB ',FPADCR[F3]); LETONE('FPADQF ',FPADCR[F4]); LETONE('FPADKF ',FPADCR[F5]); LETONE('FPADKB ',FPADCR[F6]); LETONE('FPADKN ',FPADCR[F7]); LETONE('FPADWR ',FPADCR[F8]); LETONE('FPBLOK ',FPBLOK); LETONE('FPCONN ',FPCONN); LETONE('FPFLNX ',FPFLNX); LETONE('FRDUBL ',FRDUBL); LETONE('FRK7TH ',FRK7TH); LETONE('FTRADE ',FTRADE); LETONE('FTRDSL ',FTRDSL); LETONE('FTRPDK ',FTRPDK); LETONE('FTRPWN ',FTRPWN); LETONE('FWKING ',FWKING); LETONE('FWMAJM ',FWMAJM); LETONE('FWMINM ',FWMINM); LETONE('FWPAWN ',FWPAWN); LETONE('FWROOK ',FWROOK); LETONE('WINDOW ',WINDOW); RDRERR('ILLEGAL LET VARIABLE NAME '); END; 21: (* LET COMMAND EXIT *) END; (* LETCMD *) PROCEDURE PLECMD; (* COMMAND - PRINT VARIABLE *) LABEL 21; (* PRINT LET COMMAND EXIT *) PROCEDURE PRIONE (* TEST FOR AND PRINT VARIABLE *) (A:RA; (* TEST VARIABLE NAME *) B:TI); (* VARIABLE *) BEGIN IF INRA = A THEN BEGIN WRITELN(A,B); GOTO 21; (* EXIT *) END; END; (* PRIONE *) BEGIN (* PLECMD *) 21: (* PRINT LET CCNMAND EXIT *) WHILE RDRGNT(INRA) DO BEGIN PRIONE('FKPSHD ',FKPSHD); PRIONE('FKSANQ ',FKSANQ); PRIONE('FMAXMT ',FMAXMT); PRIONE('FNODEL ',FNODEL); PRIONE('FPADQR ',FPADCR[F1]); PRIONE('FPADQN ',FPADCR[F2]); PRIONE('FPADQB ',FPADCR[F3]); PRIONE('FPADQF ',FPADCR[F4]); PRIONE('FPADKF ',FPADCR[F5]); PRIONE('FPADKB ',FPADCR[F6]); PRIONE('FPADKN ',FPADCR[F7]); PRIONE('FPADKR ',FPADCR[F8]); PRIONE('FPBLOK ',FPBLOK); PRIONE('FPCONN ',FPCONN); PRIONE('FPFLNX ',FPFLNX); PRIONE('FRDUBL ',FRDUBL); PRIONE('FRK7TH ',FRK7TH); PRIONE('FTRADE ',FTRADE); PRIONE('FTRDSL ',FTRDSL); PRIONE('FTRPDK ',FTRPDK); PRIONE('FTRPWN ',FTRPWN); PRIONE('FWKING ',FWKING); PRIONE('FWMAJM ',FWMAJM); PRIONE('FWMINM ',FWMINM); PRIONE('FWPAWN ',FWPAWN); PRIONE('FWROOK ',FWROOK); PRIONE('WINDOW ',WINDOW); RDRERR(' ILLEGAL VARIABLE NAME '); END; END; (* PLECMD *) PROCEDURE PRICMD; (* COMMAND - PRINT BOARD *) BEGIN IF RDRGNT(INRA) THEN PRINTB(MBORD) ELSE PRINTB(BOARD.RBIS); END; (* PRICMD *) PROCEDURE PAMCMD; (* COMMAND - PRINT ATTACK MAP *) BEGIN WHILE RDRGNT(INRA) DO IF INRA[AA] = 'T' THEN PRINAM(ATKTO) ELSE IF INRA[AA] = 'F' THEN PRINAM(ATKFR) ELSE RDRERR(' ATTACK MAP NOT TO OR FROM '); END; (* PAMCMD *) PROCEDURE POPCMD; (* COMMAND - PRINT OTHER STUFF *) VAR INTQ : TQ; (* CASTLE TYPE INDEX *) BEGIN WITH BOARD DO BEGIN WRITELN(XTMA[RBTM],' TO MOVE.'); WRITELN(RBTS,' ENPASSANT.'); WRITELN('MOVE NUMBER ',RBTI); FOR INTQ := LS TO DL DO IF INTQ IN RBSQ THEN WRITELN(XTQA[INTQ],' SIDE CASTLE LEGAL.'); END; END; (* POPCMD *) PROCEDURE PMVCMD; (* COMMAND - PRINT MOVE LIST *) VAR INTW : TW; (* MOVES LIST INDEX *) BEGIN LSTMOV; (* LIST LEGAL MOVES *) FOR INTW := AW TO JNTW-1 DO BEGIN WRITE(INTW:4,' '); PRIMOV(MOVES[INTW]); IF INTW/LPP = INTW DIV LPP THEN PAUSER; END; END; (* PMVCMD *) PROCEDURE SWICMD; (* COMMAND - FLIP SWITCH *) LABEL 21; (* SWITCH OPTION EXIT *) PROCEDURE SWIONE (* PROCESS ONE SWITCH *) (A:RA; (* SWITCH NAME *) VAR B:TB); (* SWITCH *) VAR IMTJ : TJ; (* SAVE COMMAND INDEX *) BEGIN IF INRA = A THEN BEGIN IMTJ := JNTJ; (* SAVE CURRENT POSITION *) IF RDRGNT(INRA) THEN BEGIN IF INRA = 'ON ' THEN B := TRUE (* TURN SWITCH ON *) ELSE IF INRA = 'OFF ' THEN B := FALSE (* TURN SWITCH OFF *) ELSE JNTJ := IMTJ; (* RESTORE CURRENT POSITION *) PRISWI(A,B); (* PRINT SWITCH VALUE *) END ELSE BEGIN PRISWI(A,B); END; GOTO 21; (* SWITCH OPTION EXIT *) END; END; (* SWIONE *) BEGIN (* SWICMD *) 21: (* SWITCH OPTION EXIT *) WHILE RDRGNT(INRA) DO BEGIN SWIONE('EC ',SWEC); SWIONE('PA ',SWPA); SWIONE('PS ',SWPS); SWIONE('RE ',SWRE); SWIONE('SU ',SWSU); SWIONE('TR ',SWTR); RDRERR(' INVALID SWITCH OPTION '); END; END; (* SWICMD *) PROCEDURE STACMD; (* COMMAND - STATUS CHANGES *) LABEL 21; (* STATUS COMMAND OPTION EXIT *) VAR INRA : RA; (* CURRENT TOKEN *) INTM : TM; (* SIDE BEING PROCESSED *) PROCEDURE STAEPF (* PROCESS EP FILE *) (A:RA; (* TEST TOKEN *) B:TF); (* EQUIVALENT FILE *) BEGIN IF A = INRA THEN BEGIN IF INTM = LITE THEN BOARD.RBTS := XTRFS[R6,B] ELSE BOARD.RBTS := XTRFS[R3,B]; GOTO 21; (* EXIT STATUS OPTION *) END; END; (* STAEPF *) PROCEDURE STACAK; (* ALLOW CASTLE KING SIDE *) BEGIN IF INTM = LITE THEN BOARD.RBSQ := BOARD.RBSQ + [LS] ELSE BOARD.RBSQ := BOARD.RBSQ + [DS]; END; (* STACAK *) PROCEDURE STACAQ; (* ALLOW CASTLE QUEEN SIDE *) BEGIN IF INTM = LITE THEN BOARD.RBSQ := BOARD.RBSQ + [LL] ELSE BOARD.RBSQ := BOARD.RBSQ + [DL]; END; (* STACAQ *) PROCEDURE STADRK; (* SET BLACK OPTIONS *) BEGIN INTM := DARK; END; (* STADRK *) PROCEDURE STAENP; (* SET ENPASSANT FILE *) BEGIN IF NOT RDRGNT(INRA) THEN BEGIN CLSTAT; (* CLEAR STATUS *) RDRERR(' ENPASSANT FILE OMITTED '); END; STAEPF('QR ',F1); STAEPF('QN ',F2); STAEPF('QB ',F3); STAEPF('Q ',F4); STAEPF('K ',F5); STAEPF('KB ',F6); STAEPF('KN ',F7); STAEPF('KR ',F8); CLSTAT; (* CLEAR STATUS *) RDRERR(' ILLEGAL ENPASSANT FILE '); END; (* STAENP *) PROCEDURE STAGOS; (* SET SIDE TO MOVE *) BEGIN BOARD.RBTM := INTM; JNTM := INTM; END; (* STAGOS *) PROCEDURE STALIT; (* SET WHITE OPTIONS *) BEGIN INTM := LITE; END; (* STALIT *) PROCEDURE STANUM; (* SET MOVE NUMBER *) BEGIN BOARD.RBTI := RDRNUM; END; (* STANUM *) PROCEDURE STAOPT (* TEST STATUS OPTION *) (A:RA; (* TEST OPTION *) PROCEDURE STAXXX); (* PROCEDURE TO EXECUTE IF EQUAL *) BEGIN IF INRA = A THEN BEGIN STAXXX; (* EXECUTE PROCEDURE *) GOTO 21; (* EXIT STATUS OPTION *) END; END; (* STAOPT *) BEGIN (* STACMD *) CLSTAT; (* CLEAR STATUS *) INTM := LITE; (* DEFAULT SIDE WHITE *) 21: (* STATUS OPTION EXIT *) WHILE RDRGNT(INRA) DO BEGIN STAOPT('D ',STADRK); STAOPT('EP ',STAENP); STAOPT('G ',STAGOS); STAOPT('L ',STALIT); STAOPT('N ',STANUM); STAOPT('OO ',STACAK); STAOPT('OOO ',STACAQ); CLSTAT; RDRERR(' INVALID STATUS OPTION '); END; END; (* STACMD *) PROCEDURE WHACMD; (* COMMAND - WHAT *) BEGIN WRITELN(MOVMS); (* PRINT LAST MESSAGE *) END; (* WHACMD *) BEGIN (* READER *) 11: (* COMMAND EXIT *) WHILE NOT RDRMOV DO RDLINE; IF SWEC THEN BEGIN (* ECHO LINE *) WRITE(' '); FOR INTJ := AJ TO ZJ-1 DO WRITE(ILINE[INTJ]); WRITELN(' '); END; IF ILINE[AJ+1] IN ['A'..'W','Y','Z'] THEN BEGIN INRA := ' '; (* EXTRACT KEYWORD *) INRA[AA] := ILINE[AJ]; INRA[AA+1] := ILINE[AJ+1]; RDRSFT; (* SKIP FIRST TOKEN *) RDRCMD('BO ',BOACMD); RDRCMD('EN ',ENDCMD); RDRCMD('GO ',GONCMD); RDRCMD('IN ',INICMD); RDRCMD('LE ',LETCMD); RDRCMD('PB ',PAMCMD); RDRCMD('PO ',POPCMD); RDRCMD('PL ',PLECMD); RDRCMD('PM ',PMVCMD); RDRCMD('PR ',PRICMD); RDRCMD('ST ',STACMD); RDRCMD('SW ',SWICMD); RDRCMD('WH ',WHACMD); RDRERR('* IMWALID COMMAND '); END; END; (* READER *) PROCEDURE MINENG (* GENERATE MINIMUM ENGLISH NOTATION *) (A:RM; (* MOVE TO NOTATE *) B:RA); (* LEADING COMMENT *) VAR INTN : TN; (* MESSAGE INDEX *) PROCEDURE ADDCHR (* ADD CHARACTER TO MESSAGE *) (A:TC); (* CHARACTER *) BEGIN MOVMS[INTN] := A; (* ADD CHARACTER *) IF INTN < ZN THEN INTN := INTN+1; (* ADVANCE POINTER *) END; (* ADDCHR *) PROCEDURE ADDSQR (* ADD SQUARE TO MESSAGE *) (A:TS; (* SQUARE TO ADD *) B:RD); (* SQUARE SYNTAX *) BEGIN WITH B DO BEGIN IF RDPC THEN ADDCHR(XTUC[XTPU[MBORD[A]]]); IF RDSL THEN ADDCHR('/'); IF RDKQ THEN IF XTSF[A] IN [F1..F4] THEN ADDCHR('Q') ELSE ADDCHR('K'); IF RDNB THEN CASE XTSF[A] OF F1,F8: ADDCHR('R'); F2,F7: ADDCHR('N'); F3,F6: ADDCHR('B'); F4 : ADDCHR('Q'); F5 : ADDCHR('K'); END; IF RDRK THEN IF JNTM = LITE THEN CASE XTSR[A] OF R1: ADDCHR('1'); R2: ADDCHR('2'); R3: ADDCHR('3'); R4: ADDCHR('4'); R5: ADDCHR('5'); R6: ADDCHR('6'); R7: ADDCHR('7'); R8: ADDCHR('8'); END ELSE CASE XTSR[A] OF R1: ADDCHR('8'); R2: ADDCHR('7'); R3: ADDCHR('6'); R4: ADDCHR('5'); R5: ADDCHR('4'); R6: ADDCHR('3'); R7: ADDCHR('2'); R8: ADDCHR('1'); END; END; END; (* ADSQR *) PROCEDURE ADDWRD (* ADD WORD TO MESSAGE *) (A:RA; (* TEXT OF WORD *) B:TA); (* LENGTH OF WORD *) VAR INTA : TA; (* CHARACTER INDEX *) BEGIN FOR INTA := AA TO B DO ADDCHR(A[INTA]); END; (* ADDWRD *) FUNCTION DIFFER (* COMPARE MOVES *) (A,B:RM) (* MOVES TO COMPARE *) : TB; (* TRUE IF MOVES ARE DIFFERENT *) VAR INTB : TB; (* SCRATCH *) BEGIN INTB := (A.RMFR <> B.RMFR) OR (A.RMTO <> B.RMTO) OR (A.RMCP <> B.RMCP); IF A.RMPR = B.RMPR THEN IF A.RMPR THEN DIFFER := INTB OR (A.RMPP <> B.RMPP) ELSE IF A.RMOO = B.RMOO THEN IF A.RMOO THEN DIFFER := INTB OR (A.RMQS <> B.RMQS) ELSE DIFFER := INTB ELSE DIFFER := TRUE ELSE DIFFER := TRUE; END; (* DIFFER *) PROCEDURE SETSQD (* DEFINE SPECIFIC SQUARE DESCRIPTOR *) (A:TS; (* SQUARE TO DESCRIBE *) B:RD; (* SYNTAX TO USE *) VAR C:SR; (* SET OF POSSIBLE RANKS *) VAR O:SF); (* SET OF POSSIBLE FILES *) BEGIN C := [R1..R8]; (* INITIALIZE TO DEFAULTS *) O := [F1..F8]; WITH B DO BEGIN IF RDKQ AND RDNB THEN O := [XTSF[A]]; IF (NOT RDKQ) AND RDNB THEN CASE XTSF[A] OF F1,F8: O := [F1,F8]; F2,F7: O := [F2,F7]; F3,F6: O := [F3,F6]; F4 : O := [F4]; F5 : O := [F5]; END; IF RDRK THEN C := [XTSR[A]]; END; END; (* SETSQD *) PROCEDURE MINGEN (* PRODUCE MINIMUM ENGLISH NOTATION FOR MOVES AND CAPTURES *) (A:RM; (* MOVE OR CAPTURE *) B:TI; (* FIRST SYNTAX TABLE ENTRY *) C:TI); (* LAST SYNTAX TABLE ENTRY *) LABEL 21, (* EXIT AMBIGUOUS MOVE SCAN *) 22; (* EXIT MINGEN *) VAR INTG : TG; (* PROMOTION PIECE *) INTI : TI; (* SYNTAX TABLE INDEX *) INTW : TW; (* MOVES INDEX *) INLR : SR; (* RANKS DEFINED OH LEFT *) INRR : SR; (* RANKS DEFINED ON RIGHT *) INLF : SF; (* FILES DEFINED OH LEFT *) INRF : SF; (* FILES DEFINED ON RIGHT *) BEGIN FOR INTI := B TO C DO (* FOR EACH SYNTAX ENTRY *) WITH SYNTX[INTI] DO BEGIN IF A.RMPR THEN INTG := A.RMPP ELSE INTG := PB; SETSQD(A.RMFR,RYLS,INLR,INLF); (* SET SQUARE SETS *) SETSQD(A.RMTO,RYRS,INRR,INRF); FOR INTW := AW+1 TO JNTW-1 DO IF DIFFER(MOVES[INTW],A) THEN IF (MBORD[A.RMFR] = MBORD[MOVES[INTW].RMFR]) AND (A.RMCP = MOVES[INTW].RMCP) THEN WITH MOVES[INTW] DO IF (XTSR[RMFR] IN INLR) AND (XTSR[RMTO] IN INRR) AND (XTSF[RMFR] IN INLF) AND (XTSF[RMTO] IN INRF) AND ((RMPR AND (INTG = RMPP)) OR (NOT RMPR)) THEN GOTO 21; (* ANOTHER MOVE LOOKS THE SAME *) (* NO OTHER MOVE LOOKS THE SAME *) ADDSQR(A.RMFR,RYLS); (* ADD FROM SQUARE *) ADDCHR(RYCH); (* ADD MOVE OR CAPTURE *) ADDSQR(A.RMTO,RYRS); (* AD TO SQUARE *) GOTO 22; (* EXIT MINGEN *) 21: (* TRY NEXT SYNTAX *) END; 22: (* EXIT MINGEN *) END; (* MINGEN *) BEGIN (* MINENG *) MOVMS := ' '; (* CLEAR MESSAGE *) INTN := AN+1; (* INITIALIZE MESSAGE INDEX *) ADDWRD(B,ZA); (* ADD INITIAL COMMENT *) ADDWRD('- ',2); WITH A DO BEGIN IF RMOO THEN (* CASTLE *) BEGIN ADDWRD('O-O ',3); IF RMQS THEN ADDWRD('-O ',2); END ELSE (* NOT CASTLE *) IF RMCA THEN (* CAPTURE *) MINGEN(A,SYNCF,SYNCL) ELSE (* SIMPLE MOVE *) MINGEN(A,SYNMF,SYNML); IF RMPR THEN (* PROMOTION *) BEGIN ADDCHR('='); ADDCHR(XTGC[RMPP]); END; ADDWRD('. ',3); IF RMCH THEN (* CHECK *) BEGIN ADDWRD('CHECK ',5); IF RMMT THEN (* CHECKMATE *) ADDWRD('MATE ',4); ADDCHR('.'); END ELSE IF RMMT THEN (* STALEMATE *) ADDWRD('STALEMATE.',10); END; END; (* MINENG *) PROCEDURE MYMOVE; (* MAKE MACHINES MOVE *) VAR INRM : RM; (* THE MOVE *) BEGIN CREATE; (* INITIALIZE DATA BASE *) INRM := MOVES[SEARCH]; (* FLND THE BEST MOVE *) IF INRM.RMIL THEN BEGIN (* NO MOVE FOUND *) GOING := 0; IF LSTMV.RMCH THEN (* CHECKMATE *) WRITELN(' CONGRATULATIONS.') ELSE (* STALEMATE *) WRITELN(' DRAWN. '); END ELSE BEGIN MINENG(INRM,' MY MOVE '); (* TRANSLATE MOVE TO ENGLISH *) WRITELN(MOVMS); (* TELL THE PLAYER *) THEMOV(INRM); (* MAKE THE MOVE *) IF SWSU THEN WRITELN(BOARD.RBTI,'.',NODES,' NODES,', BSTVL[AK]); END; END; (* MYMOVE *) PROCEDURE YRMOVE; (* MAKE PLAYERS MOVE *) LABEL 11, 12, 13, 14, 15, (* SYNTAX NODES *) 16, (* SYNTAX ERROR *) 17, (* AMBIGUOUS MOVE *) 18, (* NORMAL EXIT *) { [sam] added one more jump to simulate jumpins } 19; VAR INTB : TB; (* VALID MOVE FOUND *) INTC : TC; (* CURRENT CHARACTER *) INTW : TJ; (* MOVES INDEX *) INTP : TP; (* MOVING PIECE *) INCP : TP; (* CAPTURED PIECE *) IFCA : TB; (* CAPTURE *) IFPR : TB; (* PROMOTION *) IFOO : TB; (* CASTLE *) IFQS : TB; (* QUEEN SIDE CASTLE *) INTG : TG; (* PROMOTION TYPE *) IFMV : TB; (* MOVE FOUND *) IFLD : TB; (* R, N, OR B ON LEFT *) IFLF : TB; (* K OR Q ON LEFT *) IFRD : TB; (* R, N, OR B ON RIGHT *) IFRF : TB; (* K OR Q ON RIGHT *) INLF : SF; (* FILES ON LEFT *) INLR : SR; (* RANKS ON LEFT *) INRF : SF; (* FILES ON RIGHT *) INRR : SR; (* RANKS ON RIGHT *) INRM : RM; (* THE MOVE *) { used to simulate a inside structural jump in } jumpin: boolean; PROCEDURE YRMHIT; (* FOUND A MOVE. EXITS TO AMBIGUOUS MOVE IF THIS IS THE SECOND POSSIBLE MOVE. SAVES THE MOVE IN INRM OTHERWISE. *) BEGIN IF IFMV THEN begin WRITELN(' AMBIGUOUS MOVE.'); GOTO 17; (* SECOND POSSIBLE MOVE *) end; IFMV := TRUE; (* FIRT POSSIBLE MOVE *) INRM := MOVES[INTW]; (* SAVE MOVE *) END; (* YRMHIT *) PROCEDURE YRMCOM; (* COMPARE SQUARES. CALLS YRHMIT IF MOVES[INTW] MOVES THE RIGHT TYPE OF PIECE, CAPTURES THE RIGHT TYPE OF PIECE, AND MOVES TO AND FROM POSSIBLE SQUARES *) BEGIN WITH MOVES[INTW] DO IF (XTSR[RMFR] IN INLR) AND (XTSF[RMFR] IN INLF) AND (XTSR[RMTO] IN INRR) AND (XTSF[RMTO] IN INRF) AND (NOT RMIL) AND (BOARD.RBIS[RMFR] = INTP) THEN IF RMCA = IFCA THEN IF RMCA THEN IF RMCP = INCP THEN YRMHIT ELSE ELSE YRMHIT; END; (* YRMCOM *) PROCEDURE YRMCAP; (* SEMANTICS - CAPTURE *) BEGIN IFCA := TRUE; END; (* YRMCAP *) PROCEDURE YRMCAS; (* SEMANTICS - CASTLE *) BEGIN IFOO := TRUE; END; (* YRMCAS *) PROCEDURE YRMCPC; (* SEMANTICS - CAPTURED PIECE *) BEGIN CASE INTC OF 'P': INCP := XTUMP[EP,OTHER[JNTM]]; 'R': INCP := XTUMP[ER,OTHER[JNTM]]; 'N': INCP := XTUMP[EN,OTHER[JNTM]]; 'B': INCP := XTUMP[EB,OTHER[JNTM]]; 'Q': INCP := XTUMP[EQ,OTHER[JNTM]]; END; END; (* YRMCPC *) PROCEDURE YRMCQS; (* SEMANTICS - CASTLE LONG *) BEGIN IFQS := TRUE; END; (* YRMCQS *) PROCEDURE YRMLKQ; (* SEMANTICS - K OR Q ON LEFT *) BEGIN CASE INTC OF 'K': INLF := [F5..F8] * INLF; (* KING SIDE *) 'Q': INLF := [F1..F4] * INLF; (* QUEEN SIDE *) END; IFLF := TRUE; END; (* YRMLKQ *) PROCEDURE YRMLRB; (* SEMANTICS - R, N, OR B ON LEFT *) BEGIN CASE INTC OF 'R': INLF := [F1,F8] * INLF; (* ROOK FILE *) 'N': INLF := [F2,F7] * INLF; (* KNIGHT FILE *) 'B': INLF := [F3,F6] * INLF; (* BISHOP FILE *) END; IFLD := TRUE; END; (* YRMLRB *) PROCEDURE YRMLRK; (* SEMANTICS - RANK ON LEFT *) BEGIN IF JNTM = LITE THEN CASE INTC OF '1': INLR := [R1]; '2': INLR := [R2]; '3': INLR := [R3]; '4': INLR := [R4]; '5': INLR := [R5]; '6': INLR := [R6]; '7': INLR := [R7]; '8': INLR := [R8]; END ELSE CASE INTC OF '1': INLR := [R8]; '2': INLR := [R7]; '3': INLR := [R6]; '4': INLR := [R5]; '5': INLR := [R4]; '6': INLR := [R3]; '7': INLR := [R2]; '8': INLR := [R1]; END; END; (* YRMLRK *) PROCEDURE YRMNUL; (* SEMANTICS - NULL *) BEGIN END;(* YRMNUL *) PROCEDURE YRMPCM; (* SEMANTICS - PIECE MOVED *) BEGIN CASE INTC OF 'P': INTP := XTUMP[EP,JNTM]; (* PAWN *) 'R': INTP := XTUMP[ER,JNTM]; (* ROOK *) 'N': INTP := XTUMP[EN,JNTM]; (* KNIGNT *) 'B': INTP := XTUMP[EB,JNTM]; (* BISHOP *) 'Q': INTP := XTUMP[EQ,JNTM]; (* QUEEN *) 'K': INTP := XTUMP[EK,JNTM]; (* KING *) END; END; (* YRMPCM *) PROCEDURE YRMPRO; (* SEMANTICS - PROMOTION *) BEGIN CASE INTC OF 'R': INTG := PR; (* ROOK *) 'N': INTG := PN; (* KNIGHT *) 'B': INTG := PB; (* BISHOP *) 'Q': INTG := PQ; (* QUEEN *) END; IFPR := TRUE; END; (* YRMPRO *) PROCEDURE YRMRKQ; (* SEMANTICS - K OR Q ON RIGHT *) BEGIN CASE INTC OF 'K': INRF := [F5..F8] * INRF; (* KING SIDE *) 'Q': INRF := [F1..F4] * INRF; (* QUEEN SIDE *) END; IFRF := TRUE; END; (* YRMRKQ *) PROCEDURE YRMRRB; (* SEMANTICS - R, N, OR 8 ON RIGHT *) BEGIN CASE INTC OF 'R': INRF := [F1,F8] * INRF; (* ROOK FILE *) 'N': INRF := [F2,F7] * INRF; (* KNIGHT FILE *) 'B': INRF := [F3,F6] * INRF; (* BISHOP FILE *) END; IFRD := TRUE; END; (* YRMRRB *) PROCEDURE YRMRRK; (* SEMANTICS - RANK ON RIGHT *) BEGIN IF JNTM = LITE THEN CASE INTC OF '1': INRR := [R1]; '2': INRR := [R2]; '3': INRR := [R3]; '4': INRR := [R4]; '5': INRR := [R5]; '6': INRR := [R6]; '7': INRR := [R7]; '8': INRR := [R8]; END ELSE CASE INTC OF '1': INRR := [R8]; '2': INRR := [R7]; '3': INRR := [R6]; '4': INRR := [R5]; '5': INRR := [R4]; '6': INRR := [R3]; '7': INRR := [R2]; '8': INRR := [R1]; END; END; (* YRMRRK *) FUNCTION NCHIN (* DETERMLNE IF NEXT INPUT CHARACTER IS NOT IN A GIVEN SET *) (A:SC; (* SET OF CHARACTERS TO CHECK *) PROCEDURE YRMXXX) (* SEMANTICS ROUTINE TO CALL IF NEXT CHARACTER IS IN SET *) : TB; (* TRUE IF CHARACTER IS NOT IN SET *) VAR INTB : TB; (* SCRATCH *) BEGIN INTB := NOT (INTC IN A); IF NOT INTB THEN BEGIN (* EXECUTE SEMANTICS ROUTINE *) YRMXXX; JNTJ := JNTJ+1; (* ADVANCE PAST CHARACTER *) WHILE (JNTJ < ZJ) AND ((ILINE[JNTJ]= ' ') OR (ORD(ILINE[JNTJ]) > ORD(ZC))) DO JNTJ := JNTJ+1; (* SKIP BLANKS *) INTC := ILINE[JNTJ]; (* NEXT CHARACTER *) IF (INTC = '.') OR (INTC = ';') THEN begin jumpin := true; { [sam] set execute jumpin } GOTO 19; (* EXIT SCAN *) end END; NCHIN := INTB; (* RETURN TRUE IF CHARACTER IS NOT IN STRING *) END; (* NCHIN *) BEGIN (* YRMOVE *) jumpin := false; { set no jumpin } INTB := FALSE; 19: { perform jumpin } WHILE NOT INTB or jumpin DO BEGIN if jumpin then goto 15; { [sam] perform the jumpin } READER; (* READ NEXT MOVE *) LSTMOV; (* LIST LEGAL MOVES *) IFCA := FALSE; IFPR := FALSE; IFOO := FALSE; IFQS := FALSE; IFLD := FALSE; IFLF := FALSE; IFRD := FALSE; IFRF := FALSE; INTP := MT; INCP := MT; INLF := [F1..F8]; INRF := [F1..F8]; INLR := [R1..R8]; INRR := [R1..R8]; INTC := ILINE[JNTJ]; IF NCHIN(['P','R','N','B','Q','K'],YRMPCM) THEN GOTO 14; IF NCHIN(['/'] ,YRMNUL) THEN GOTO 11; IF NCHIN(['K','Q'] ,YRMLKQ) THEN; IF NCHIN(['R','N','B'] ,YRMLRB) THEN; IF NCHIN(['1'..'8'] ,YRMLRK) THEN; 11: (* LEFT SIDE DONE *) IF NOT NCHIN(['-'] ,YRMNUL) THEN GOTO 12; IF NCHIN(['+','X'] ,YRMCAP) THEN GOTO 16; IF NCHIN(['P','R','N','B','Q'] ,YRMCPC) THEN GOTO 16; IF NCHIN(['/'] ,YRMNUL) THEN GOTO 13; 12: (* RIGHT SIDE SQUARE *) IF NCHIN(['K','Q'] ,YRMRKQ) THEN; IF NCHIN(['R','N','B'] ,YRMRRB) THEN; IF NCHIN(['1'..'8'] ,YRMRRK) THEN; 13: (* PROMOTION *) IF NCHIN(['='] ,YRMNUL) THEN GOTO 15; IF NCHIN(['R','N','B','Q'] ,YRMPRO) THEN GOTO 16; GOTO 15; 14: (* CASTLING *) IF NCHIN(['O','0'] ,YRMNUL) THEN GOTO 16; IF NCHIN(['-'] ,YRMNUL) THEN GOTO 16; IF NCHIN(['O','0'] ,YRMCAS) THEN GOTO 16; IF NCHIN(['-'] ,YRMCQS) THEN GOTO 15; IF NCHIN(['O','0'] ,YRMNUL) THEN GOTO 16; 15: (* SYNTAX CORRECT *) jumpin := false; { [sam] make sure jumpin off } IF IFRF AND NOT IFRD THEN INRF := INRF * [F4,F5]; (* SELECT K OR Q FILE *) IF IFLF AND NOT IFLD THEN INLF := INLF * [F4,F5]; (* SELECT K OR Q FILE *) IFMV := FALSE; (* NO MOVE FOUND YET *) INTW := AW; (* INITIALIZE INDEX *) WHILE INTW < JNTW DO WITH MOVES[INTW] DO BEGIN IF RMPR = IFPR THEN IF RMPR THEN IF RMPP = INTG THEN (* CORRECT PROMOTION TYPE *) YRMCOM (* COMPARE SQUARES AND PIECES *) ELSE ELSE (* NOT PROMOTION *) IF RMOO = IFOO THEN IF RMOO THEN (* CASTLING *) IF RMQS = IFQS THEN (* CASTLING SAME WAY *) YRMHIT ELSE ELSE (* NOT CASTLING *) YRMCOM; (* COMPARE SQUARES AND PIECES *) INTW := INTW+1; (* ADVANCE MOVES INDEX *) END; IF IFMV THEN (* ONE MOVE FOUND *) BEGIN MINENG(INRM,'YOUR MOVE '); (* CONVERT TO OUR STYLE *) WRITELN(MOVMS); (* PRINT MOVE *) THEMOV(INRM); (* MAKE THE MOVE *) INTB := TRUE; (* EXIT YRMOVE *) END ELSE (* NO MOVES FOUND *) WRITELN(' ILLEGAL MOVE.'); GOTO 18; (* EXIT *) 16: (* SYNTAX ERROR *) WRITELN(' SYNTAX ERROR.'); GOTO 18; (* EXIT *) {17:} (* AMBIGUOUS MOVE *) {WRITELN(' AMBIGUOUS MOVE.');} 18: (* EXIT *) END; 17: END; (* YRMOVE *) BEGIN (* THE PROGRAM *) jumpin := false; { [sam] set no jumpin } WRITELN(' HI. THIS IS CHESS .5'); INICON; (* INITIALIZE CONSTANTS *) 1: (* INITIALIZE FOR A NEW GAME *) INITAL(BOARD); (* INITIALIZE FOR A NEW GAME *) 2: REPEAT if jumpin then goto 3; { [sam] execute jumpin } REPEAT YRMOVE; (* EXECUTE PLAYERS MOVE *) UNTIL SWRE; 3: (* EXECUTE MACHINES MOVE *) jumpin := false; { [sam] clear jumpin flag } REPEAT MYMOVE; IF GOING > 0 THEN GOING := GOING-1 UNTIL GOING = 0; UNTIL FALSE; 9: (* END OF PROGRAM *) END.
(*** @abstract(@bold(This unit contains a very simple procedural interface to make http requests and @noAutoLink(process) the returned data.))@br@br To get started, you can just use the function retrieve('...url...') to get the data you need as a string. @br Retrieve also supports file:// urls or other data source; if you want to restrict it to http GET/POST-requests only, you can use the httpRequest function.@br@br The data can then be processed with process which applies an XPath/XQuery expression or a html template to it.@br@br @bold(Example) Get all links on a page: @longCode(# for v in process('http://www.freepascal.org', '//a') do writeln(v.toString, ' => ', v.toNode['href']); #) *) unit simpleinternet; {$mode objfpc}{$H+} interface uses Classes, SysUtils, xquery, internetaccess, simplehtmltreeparser; //Usually this unit uses synapse on linux and wininet on windows, but you can choose a certain wrapper below: //{$DEFINE USE_SYNAPSE_WRAPPER} //{$DEFINE USE_WININET_WRAPPER} //{$DEFINE USE_NO_WRAPPER} //** IXQValue from the xquery unit. Just a wrapper, so that no other unit needs to be included @noAutoLinkHere type IXQValue = xquery.IXQValue; (*** Retrieve data from any url.@br@br It is really simple to use, you pass the desired url as single parameter and get the data of the url.@br@br It supports: @unorderedList( @item(http://...) @item(https://...) @item(file://...) @item(/normal/unix/file/paths) @item(C:\normal\windows\paths) @item(<html>data</html>) ) *) function retrieve(data: string): string; function httpRequest(url: string): string; overload; deprecated 'The httpRequest functions have been moved to the internetaccess unit.'; function httpRequest(url: string; rawpostdata: string): string; overload; deprecated 'The httpRequest functions have been moved to the internetaccess unit.'; function httpRequest(url: string; postdata: TStringList): string; overload; deprecated 'The httpRequest functions have been moved to the internetaccess unit.'; function httpRequest(const method, url, rawdata: string): string; overload; deprecated 'The httpRequest functions have been moved to the internetaccess unit.'; //**Make a http request to an address given in an IXQValue. @br //**node: if a link (a), download @@href. If a resource (img, frame), download @@src. Otherwise download the text@br. //**object: Download obj.url, possibly sending obj.post as postdata. //**else: Download the string value. function httpRequest(const destination: xquery.IXQValue): string; overload; deprecated 'Use destination.retrieve() instead.'; (*** Processes data with a certain query.@br@br data can be an url, or a html/xml file in a string, like in retrieve.@br@br query can be a @link(xquery.TXQueryEngine XPath/XQuery expression), like in @code(process('http://www.google.de', '//title');). @br@br Or query can be a @link(extendedhtmlparser.THtmlTemplateParser html template) like @code(process('http://www.google.de', '<title><t:s>result:=text()</t:s></title>');) The advantage of such templates is that they can return several variables at once and a canonical representation of the same data on different web sites. To get a list of all variables of the last query you can use processedVariables.@br@br This function returns an IXQValue value, which is a variant for XQuery expression. If you want a string value, you can convert it like @code(process(...).toString). Or if you want to access a retrieved node directly, you can use @code(process(..).toNode).@br It can also contain multiple values, which can be access like @code(for x in process(..)), where x is another IXQValue. The global function processedTree returns a tree representation of the last processed data string. *) function process(data: string; query: string): xquery.IXQValue; //**Returns a tree representation of the last processed html/xml data@br //**Might return nil function processedTree: TTreeNode; //**Returns all variable assignments during the last query function processedVariables: TXQVariableChangeLog; //**If you use the functions in this unit from different threads, you have to call freeThreadVars //**before the thread terminates to prevent memory leaks @br //**This also calls freeThreadVars of the xquery and internetaccess units procedure freeThreadVars; function defaultInternet: TInternetAccess; inline; function defaultQueryEngine: TXQueryEngine; inline; procedure needInternetAccess; deprecated 'This procedure no longer does anything'; implementation {$IFNDEF USE_SYNAPSE_WRAPPER} {$IFNDEF USE_WININET_WRAPPER} {$IFNDEF USE_ANDROID_WRAPPER} {$IFNDEF USE_NO_WRAPPER} //use default wrapper {$IFDEF WINDOWS} {$DEFINE USE_WININET_WRAPPER} {$ELSE} {$IFDEF ANDROID} {$DEFINE USE_ANDROID_WRAPPER} {$ELSE} {$DEFINE USE_SYNAPSE_WRAPPER} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} {$ENDIF} uses bbutils, extendedhtmlparser ,xquery_json //enable json as default ,xquery.internals.protectionbreakers {$IFDEF USE_SYNAPSE_WRAPPER} , synapseinternetaccess, internetaccess_inflater_paszlib {$ENDIF} {$IFDEF USE_WININET_WRAPPER} , w32internetaccess, internetaccess_inflater_paszlib {$ENDIF} {$IFDEF USE_ANDROID_WRAPPER} , androidinternetaccess //if the androidinternetaccess unit is not found, you need to add the directory containing this (simpleinternet) unit to the search paths //(it is not included in the lpk, because it depends on the lcl, while all other units depend only on the fcl) {$ENDIF} ; threadvar tree: TTreeParser; templateParser: THtmlTemplateParser; lastQueryWasPXP: boolean; lastRetrievedType: TRetrieveType; function defaultInternet: TInternetAccess; begin result := internetaccess.defaultInternet; end; function defaultQueryEngine: TXQueryEngine; begin result := xquery.defaultQueryEngine; end; procedure needInternetAccess; begin end; function retrieve(data: string): string; var trimmed: string; begin trimmed:=TrimLeft(data); lastRetrievedType:=guessType(data); case lastRetrievedType of rtEmpty: exit(''); rtRemoteURL: exit(internetaccess.httpRequest(trimmed)); rtFile: exit(strLoadFromFileUTF8(trimmed)); else exit(data); end; end; function lastContentType: string; begin if lastRetrievedType = rtRemoteURL then result := defaultInternet.getLastContentType else result := ''; end; function process(data: string; query: string): xquery.IXQValue; var dataFileName: string; datain, contentType: String; tempVars: TXQVariableChangeLog; context: TXQEvaluationContext; format: TInternetToolsFormat; querykind: TExtractionKind; pxpParser: TXQueryEngine; begin result := xqvalue(); if query = '' then exit(); datain := data; data := retrieve(data); case lastRetrievedType of rtRemoteURL: dataFileName := defaultInternet.lastUrl; rtFile: dataFileName := fileNameExpandToURI(datain); else dataFileName := ''; end; contentType := lastContentType; format := guessFormat(data, dataFileName, contentType); query := trim(query); querykind := guessExtractionKind(query); case querykind of ekPatternHTML, ekPatternXML: begin lastQueryWasPXP := false; if templateParser = nil then begin templateParser := THtmlTemplateParser.create; if querykind = ekPatternXML then templateParser.TemplateParser.parsingModel:= pmStrict else templateParser.TemplateParser.parsingModel:= pmHTML; templateParser.TemplateParser.repairMissingStartTags := false; templateParser.HTMLParser.repairMissingStartTags := format = itfHTML; end; templateParser.parseTemplate(query); templateParser.parseHTML(data, dataFileName, contentType); if templateParser.variableChangeLog.count > 0 then begin tempVars := templateParser.VariableChangeLogCondensed.collected; if (tempVars.count = 1) and (tempVars.getName(0) = templateParser.UnnamedVariableName) then begin result := tempVars.get(0); tempVars.free; end else result := tempVars.toStringMap.boxInIXQValue; end; end; else begin lastQueryWasPXP := true; pxpParser := defaultQueryEngine; pxpparser.StaticContext.baseURI:=dataFileName; pxpParser.addAWeirdGlobalVariableH('', 'json'); case querykind of ekDefault, ekXPath2, ekXPath3_0, ekXPath3_1, ekXPath4_0, ekXQuery1, ekXQuery3_0, ekXQuery3_1, ekXQuery4_0: begin case querykind of ekDefault: pxpParser.ParsingOptions.StringEntities := xqseResolveLikeXQueryButIgnoreInvalid; ekXPath2, ekXPath3_0, ekXPath3_1, ekXPath4_0: pxpParser.ParsingOptions.StringEntities := xqseIgnoreLikeXPath; ekXQuery1, ekXQuery3_0, ekXQuery3_1, ekXQuery4_0: pxpParser.ParsingOptions.StringEntities := xqseResolveLikeXQuery; else raise Exception.Create('internal error 21412466'); end; pxpParser.parseQuery(query, xqpmXQuery4_0, pxpParser.StaticContext);//always use xquery, no point in using a less powerful language. end; ekCSS: pxpParser.parseCSS3(query); else raise Exception.Create('internal error 21412466'); end; context := pxpParser.getEvaluationContext(); if format <> itfJSON then begin if tree = nil then begin tree := TTreeParser.Create; tree.parsingModel:=pmHTML; end; tree.repairMissingStartTags := format = itfHTML; tree.parseTree(data, dataFileName); context.SeqValue := xqvalue(tree.getLastTree); context.SeqIndex := 1; context.SeqLength := 1; end else pxpParser.VariableChangelog.add('json', pxpParser.DefaultJSONParser.parse(data)); //TODO: this is bad, it leaks all JSON data, till the engine is reset result := pxpParser.evaluate(context); end; end; end; function processedTree: TTreeNode; begin if lastQueryWasPXP then begin if tree = nil then exit(nil); result := tree.getLastTree; end else if templateParser = nil then exit(nil) else result := templateParser.HTMLTree; end; function processedVariables: TXQVariableChangeLog; begin if templateParser = nil then templateParser := THtmlTemplateParser.create; result := templateParser.variableChangeLog; end; procedure freeThreadVars; begin templateParser.Free; templateParser := nil; tree.Free; tree := nil; xquery.freeThreadVars; end; function httpRequest(url: string): string; begin result:=defaultInternet.get(url); end; function httpRequest(url: string; rawpostdata: string): string; begin result:=defaultInternet.post(url, rawpostdata); end; function httpRequest(url: string; postdata: TStringList): string; begin result := internetaccess.httpRequest(url, TInternetAccess.urlEncodeData(postdata)); end; function httpRequest(const method, url, rawdata: string): string; begin result := defaultInternet.request(method, url, rawdata); end; function httpRequest(const destination: xquery.IXQValue): string; var dest: IXQValue; tempHeaders: String; method: string; url: string; post: string; begin if destination.kind = pvkSequence then dest := destination.get(1) else dest := destination; if dest.kind = pvkSequence then dest := dest.get(1); if dest.kind <> pvkObject then dest := defaultQueryEngine.evaluateXPath('pxp:resolve-html(.)', dest); case dest.kind of pvkUndefined: exit(''); pvkNode: raise EXQEvaluationException.Create('pxp:ASSERT', 'Got '+dest.toXQuery()+', but expected resolved url'); pvkObject: begin tempHeaders := defaultInternet.additionalHeaders.Text; dest.prepareInternetRequest(method, url, post, defaultInternet); result := internetaccess.httpRequest(method, url, post); defaultInternet.additionalHeaders.Text := tempHeaders; end; pvkSequence: raise EXQEvaluationException.Create('pxp:ASSERT', 'Impossible (nested) sequence'); else result := internetaccess.httpRequest(dest.toString); end; end; finalization freeThreadVars; end.
unit osFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ActnList, osUtils, ImgList, osActionList, System.Actions; type TOperacao = (oInserir, oEditar, oExcluir, oVisualizar, oImprimir); TOperacoes = set of TOperacao; TosForm = class(TForm) ActionList: TosActionList; OnCheckActionsAction: TAction; ImageList: TImageList; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); private FOperacoes: TOperacoes; procedure SetOperacoes(const Value: TOperacoes); protected public constructor Create(AOwner: TComponent); override; published property Operacoes: TOperacoes read FOperacoes write SetOperacoes; end; var osForm: TosForm; implementation {$R *.DFM} { TBizForm } constructor TosForm.Create(AOwner: TComponent); begin inherited; //CheckDefaultParams; // Carrega os parâmetros empresa/estabelecimento se necessário end; procedure TosForm.FormShow(Sender: TObject); begin OnCheckActionsAction.Execute; end; procedure TosForm.SetOperacoes(const Value: TOperacoes); begin FOperacoes := Value; end; procedure TosForm.FormCreate(Sender: TObject); begin Operacoes := [oInserir, oEditar, oExcluir, oVisualizar]; // operações Defaults end; end.
object MapLegalAddressSelectDialog: TMapLegalAddressSelectDialog Left = 666 Top = 98 Width = 360 Height = 243 ActiveControl = LegalAddressEdit Caption = 'Choose what street to highlight parcels on.' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [] OldCreateOrder = False Position = poMainFormCenter PixelsPerInch = 96 TextHeight = 16 object Label1: TLabel Left = 16 Top = 23 Width = 78 Height = 16 Caption = 'Road Name:' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False end object OKButton: TBitBtn Left = 80 Top = 168 Width = 86 Height = 33 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 0 OnClick = OKButtonClick Glyph.Data = { DE010000424DDE01000000000000760000002800000024000000120000000100 0400000000006801000000000000000000001000000000000000000000000000 80000080000000808000800000008000800080800000C0C0C000808080000000 FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF00333333333333 3333333333333333333333330000333333333333333333333333F33333333333 00003333344333333333333333388F3333333333000033334224333333333333 338338F3333333330000333422224333333333333833338F3333333300003342 222224333333333383333338F3333333000034222A22224333333338F338F333 8F33333300003222A3A2224333333338F3838F338F33333300003A2A333A2224 33333338F83338F338F33333000033A33333A222433333338333338F338F3333 0000333333333A222433333333333338F338F33300003333333333A222433333 333333338F338F33000033333333333A222433333333333338F338F300003333 33333333A222433333333333338F338F00003333333333333A22433333333333 3338F38F000033333333333333A223333333333333338F830000333333333333 333A333333333333333338330000333333333333333333333333333333333333 0000} NumGlyphs = 2 end object CancelButton: TBitBtn Left = 186 Top = 168 Width = 86 Height = 33 TabOrder = 1 Kind = bkCancel end object LegalAddressEdit: TEdit Left = 126 Top = 19 Width = 206 Height = 24 CharCase = ecUpperCase Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 2 end object NumberGroupBox: TGroupBox Left = 16 Top = 66 Width = 320 Height = 86 Caption = ' Choose a legal address number range: ' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 3 object Label9: TLabel Left = 12 Top = 24 Width = 34 Height = 16 Caption = 'Start:' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False end object Label10: TLabel Left = 12 Top = 53 Width = 28 Height = 16 Caption = 'End:' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False end object StartNumberEdit: TEdit Left = 56 Top = 20 Width = 98 Height = 24 CharCase = ecUpperCase Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 0 end object AllNumbersCheckBox: TCheckBox Left = 170 Top = 24 Width = 103 Height = 17 Caption = ' All Numbers' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 1 OnClick = AllNumbersCheckBoxClick end object ToEndOfNumbersCheckBox: TCheckBox Left = 170 Top = 53 Width = 124 Height = 17 Caption = ' To End of Users' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 2 OnClick = ToEndOfNumbersCheckBoxClick end object EndNumberEdit: TEdit Left = 56 Top = 49 Width = 98 Height = 24 CharCase = ecUpperCase Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -13 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 3 end end end
@{ Layout = null; Response.ContentType = "application/javascript"; Response.Cache.SetExpires(DateTime.Now.AddDays(30)); } $(function() { /// Support for: /// <a href="null">Do nothing</a> $(document.body).on('click', "A[href='null']", function (event) { event.preventDefault(); }); /// Support for: /// <a href="histroy:back">Go Back</a> $(document.body).on('click', "A[href='history:back']", function(event) { history.back(); event.preventDefault(); }); /// Provides an alternative anchor href that can contain form field values. /// The data-href should contain the href where form field id's are written between brackets. /// If all referenced form fields are empty, the regular href is used. /// Tip: to include values from the query string, copy those values in a hidden field and reference /// the field; see the data-init-queryfield extension. /// For instance, the following will perform a search on Google: /// <input id="searchtext" type="text" /> /// <a href="http://www.google.com/" data-href="http://www.google.com/search?q={searchtext}" target="_blank">Google</a> $(document.body).on('click', "A[data-href]", function (event) { var pattern = /{(.*?)}/g; var althref = $(this).data('href'); var useralthref = false; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace var althrefsubst = althref.replace(pattern, function (match, fieldname) { var value = $('#' + fieldname).val(); if (value) useralthref = true; return value; }); if (useralthref) { event.preventDefault(); var target = $(this).attr("target"); if (!target) target = '_self'; window.open(althrefsubst, target); } }); /// Support for forwarding click events. I.e. a click on the div will be translated into /// a click on the link: /// /// <div data-forward-click="#a1">Click me!</div> /// <a id="a1" href="http://www.example.com/">...</a> /// $(document.body).on('click', "*[data-forward-click]", function(event) { $($(this).data('forward-click'))[0].click(); // See: http://goo.gl/lGftqn event.preventDefault(); }); /// Rendering and behavior of 'back-top' control for fast scrolling-up to top of page. /// Usage: simply include the following html in your page('s template), no matter where: /// /// <a id="back-top" href="#top"> /// <i class="glyphicon glyphicon-chevron-up"></i> /// </a> /// /// On top of the page, you can place a '<a name="top"></a>' to support javascript-less browsers, but this is /// not required for javascript supporting browsers. $("#back-top").hide(); $(window).scroll(function () { if ($(this).scrollTop() > 100) { $('#back-top').fadeIn(800); } else { $('#back-top').fadeOut(400); } }); // scroll body to 0px on click $('#back-top').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $(document.body).loaded(); setInterval(function() { $("#clock-text").text(new Date().toLocaleString()); }, 1000); }); jQuery.fn.extend({ loaded: function() { // For any element having a 'data-moveto': moves the content HTML to the given selector. $(this).find("*[data-moveto]").each(function() { $($(this).data("moveto")).html($(this).html()); $($(this).data("moveto")).loaded(); $(this).html(''); }); /// Initializes the input element's value with the named field from the query string. /// I.e: http://.../...?searchquery=What+I+am+searching+for /// <input name="searchquery" data-init-queryfield="searchquery" type="text" /> $(this).find('INPUT[data-init-queryfield]').each(function () { var paramname = $(this).data("init-queryfield"); var match = RegExp('[?&]' + paramname + '=([^&]*)').exec(window.location.search); var value = match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null; $(this).val(value); }); /// For any element having a 'data-utctime' value, render the value as local date/time. /// Either using the .toLocaleString() method, or, if a 'data-format' attribute is present, /// using custom formatting. $(this).find("*[data-utctime]").each(function(index, item) { var d = new Date(parseInt($(item).data("utctime"))).getLocalTime(); var f = $(item).data("format"); if (f === undefined) { $(item).html(d.toLocaleString()); } else { $(item).html(d.format(f)); } }); /// For any element having a 'data-load-url': load the given URL: /// Optionally, a 'data-load-refresh' indicates the time (in seconds) after which to continuously refresh the content. /// The url can contain a "{rnd}" literal that will then be replaced by a random number to force reloading. /// I.e: <div data-load-url="/DebugInfo.aspx?x={rnd}" data-load-refresh="10"></div> $(this).find("*[data-load-url]").each(function () { var url = $(this).data("load-url") + ''; var target = $(this); target.load(url.replace('{rnd}', Math.random()), function() { target.loaded(); }); if ($(this).data("load-refresh")) { window.setInterval(function () { target.load(url.replace('{rnd}', Math.random()), function() { target.loaded(); }); }, $(this).data("load-refresh") * 1000); } }); $(this).find("CANVAS:has(> TABLE)").each(function() { drawGraph($(this)); }); } }); /// Converts an UTC date/time to browser's local date/time. Date.prototype.getLocalTime = function() { return new Date(this.getTime() + 60 * this.getTimezoneOffset()); } /// Formats a Date object based on the given formatstring. Date.prototype.format = function(format) { var s = format; s = s.replace("DD", ("0"+(this.getDate())).substr(-2)); s = s.replace("D", (this.getDate())); s = s.replace("MM", ("0"+(this.getMonth()+1)).substr(-2)); s = s.replace("M", (this.getMonth()+1)); s = s.replace("YYYY", (this.getFullYear())); s = s.replace("YY", ("0"+(this.getYear()%100)).substr(-2)); s = s.replace("hh", ("0"+(this.getHours())).substr(-2)); s = s.replace("mm", ("0"+(this.getMinutes())).substr(-2)); s = s.replace("ss", ("0"+(this.getSeconds())).substr(-2)); s = s.replace("mmm", ("00"+(this.getMilliseconds())).substr(-3)); return s; } // https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial function drawGraph(canvas) { var table = canvas.find('TABLE'); var can = canvas[0]; if (can.getContext) { // Initialize canvas: var ctx = can.getContext('2d'); if (canvas.data("background")) { ctx.fillStyle = canvas.data("background"); ctx.fillRect(0,0,can.width,can.height); } // Find highest graph value: var topv = 20.0; table.find("TD").each(function(index, item) { topv = Math.max(topv, parseFloat($(item).text())) }); // Draw bars: table.find("TR[data-graph-style='bars']").each(function(rowindex, row) { var cellCount = $(row).find("TD").length; var cellWidth = can.width / (cellCount + 1); $(row).find("TD").each(function(cellindex, cell) { if ($(cell).data("fill-style")) ctx.fillStyle = $(cell).data("fill-style"); var value = parseFloat($(cell).text()); ctx.fillRect(cellWidth + cellindex * cellWidth, can.height, cellWidth - 4, -(value / topv * can.height + 2)); }); }); // Draw axes: if (canvas.data("fill-style")) { ctx.fillStyle = canvas.data("fill-style"); } else { ctx.fillStyle = "#000"; } if (canvas.data("font")) { ctx.font = canvas.data("font"); } ctx.fillText('' + (topv), 0.5, 24.5); ctx.fillText('' + (topv / 2), 0.5, 161.5); ctx.fillText('0', 0.5, 299.5); } }
unit TestFizzBuzz; interface uses // DUnitX.TestFramework, DUnitX.DUnitCompatibility, TestFramework, FizzBuzz.GameLogic; type TestTFizzBuzzGame = class(TTestCase) private const TestFizzVal = 3; TestBuzzVal = 5; strict private fGame:TFizzBuzzGame; public procedure SetUp; override; procedure TearDown; override; published procedure CheckFizz; procedure CheckBuzz; procedure CheckFizzBuzz; procedure CheckNonFizzBuzz; procedure CheckFizzText; procedure CheckBuzzText; end; implementation procedure TestTFizzBuzzGame.SetUp; begin fGame := TFizzBuzzGame.Create; fGame.Fizz := TestFizzVal; fGame.Buzz := TestBuzzVal; end; procedure TestTFizzBuzzGame.TearDown; begin fGame.Free; fGame := nil; end; procedure TestTFizzBuzzGame.CheckFizz; begin CheckEqualsString(fGame.FizzText, fGame.CalcFizzBuzz(TestFizzVal)); CheckEqualsString(fGame.FizzText, fGame.CalcFizzBuzz(TestFizzVal * 2)); CheckEqualsString(fGame.FizzText, fGame.CalcFizzBuzz(TestFizzVal * 3)); CheckEqualsString(fGame.FizzText, fGame.CalcFizzBuzz(TestFizzVal * 101)); end; procedure TestTFizzBuzzGame.CheckBuzz; begin CheckEqualsString(fGame.BuzzText, fGame.CalcFizzBuzz(TestBuzzVal)); CheckEqualsString(fGame.BuzzText, fGame.CalcFizzBuzz(TestBuzzVal * 2)); CheckEqualsString(fGame.BuzzText, fGame.CalcFizzBuzz(TestBuzzVal * 4)); CheckEqualsString(fGame.BuzzText, fGame.CalcFizzBuzz(TestBuzzVal * 101)); end; procedure TestTFizzBuzzGame.CheckFizzBuzz; begin CheckEqualsString(fGame.FizzText + fGame.BuzzText, fGame.CalcFizzBuzz(TestFizzVal * TestBuzzVal)); CheckEqualsString(fGame.FizzText + fGame.BuzzText, fGame.CalcFizzBuzz(TestFizzVal * TestBuzzVal * 2)); CheckEqualsString(fGame.FizzText + fGame.BuzzText, fGame.CalcFizzBuzz(TestFizzVal * TestBuzzVal * 3)); CheckEqualsString(fGame.FizzText + fGame.BuzzText, fGame.CalcFizzBuzz(TestFizzVal * TestBuzzVal * 4)); CheckEqualsString(fGame.FizzText + fGame.BuzzText, fGame.CalcFizzBuzz(TestFizzVal * TestBuzzVal * 5)); end; procedure TestTFizzBuzzGame.CheckNonFizzBuzz; begin CheckEqualsString('1', fGame.CalcFizzBuzz(1)); CheckEqualsString('2', fGame.CalcFizzBuzz(2)); CheckEqualsString('4', fGame.CalcFizzBuzz(4)); CheckEqualsString('7', fGame.CalcFizzBuzz(7)); end; procedure TestTFizzBuzzGame.CheckFizzText; begin CheckEqualsString('Fizz', fGame.FizzText); end; procedure TestTFizzBuzzGame.CheckBuzzText; begin CheckEqualsString('Buzz', fGame.BuzzText); end; initialization //TDUnitX.RegisterTestFixture(TestTFizzBuzzGame); RegisterTest(TestTFizzBuzzGame.Suite); end.
namespace RemObjects.Elements.System; interface type &Type = public record assembly fValue: ^IslandTypeInfo; protected public constructor(aValue: ^IslandTypeInfo); property RTTI: ^IslandTypeInfo read fValue; property &Name: String read String.FromPAnsiChars(fValue^.Ext^.Name); property &Flags: IslandTypeFlags read fValue^.Ext^.Flags; method Equals(other: Object): Boolean; override; method GetHashCode: Integer; override; end; IslandExtTypeInfo = public record private public &Flags: IslandTypeFlags; Name: ^AnsiChar; SubType: ^IslandTypeInfo; // If Generic, this will be the "non generic" type end; IslandTypeInfo = public record private public Ext: ^IslandExtTypeInfo; ParentType: ^IslandTypeInfo; InterfaceType: ^IslandInterfaceTable; end; IslandInterfaceTable = public record public HashTableSize: Integer; FirstEntry: ^^IslandTypeInfo; // ends with 0 end; // Keep in sync with compiler. IslandTypeFlags = public flags ( // First 3 bits reserved for type kind TypeKindMask = (1 shl 0) or (1 shl 1) or (1 shl 2) , &Class = 0, &Enum = 1, EnumFlags = 2, &Delegate = 3, Struct = 4, &Interface = 5, &Extension = 6, &Array = 7, MemberInfoPresent = 16, Generic = 1 shl 3) of UInt64; implementation method &Type.Equals(other: Object): Boolean; begin exit (other is &Type) and (&Type(other).fValue = fValue); end; method &Type.GetHashCode: Integer; begin exit Integer({$ifdef cpu64}Int64(fValue) xor (Int64(fValue) shr 32) * 7{$else}fValue{$endif}); end; constructor &Type(aValue: ^IslandTypeInfo); begin fValue := aValue; end; end.
unit Form.EditBook; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Form.BaseEditForm, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinMetropolis, cxClasses, dxSkinsForm, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit, cxTextEdit, cxLabel, Vcl.Buttons, Model.Entities, Aurelius.Bind.Dataset, Aurelius.Engine.ObjectManager, System.ImageList, Vcl.ImgList, Data.DB, cxDBEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TfrmEditBook = class(TfrmBaseEditor) lblCategoryName: TcxLabel; lblParentCategory: TcxLabel; btnAddCategory: TcxButton; lblFileLink: TcxLabel; btnFileLink: TcxButton; adsCategories: TAureliusDataset; adsCategoriesSelf: TAureliusEntityField; adsCategoriesID: TIntegerField; adsCategoriesCategoryName: TStringField; adsCategoriesParent: TAureliusEntityField; adsCategoriesBooks: TDataSetField; dsCategories: TDataSource; adsBooks: TAureliusDataset; adsBooksSelf: TAureliusEntityField; adsBooksID: TIntegerField; adsBooksBookName: TStringField; adsBooksBookLink: TStringField; dsBooks: TDataSource; edtBookName: TcxDBTextEdit; edtFileLink: TcxDBTextEdit; cbbParentCategory: TcxComboBox; adsBooksCategory: TAureliusEntityField; procedure btnOKClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); private procedure SetBook(ABook: TBook; AManager: TObjectManager); procedure LoadCategory; public class function Edit(ABook: TBook; AManager: TObjectManager): Boolean; end; var frmEditBook: TfrmEditBook; implementation uses ConnectionModule, Common.Utils, System.Generics.Collections; {$R *.dfm} { TfrmEditBook } procedure TfrmEditBook.btnCancelClick(Sender: TObject); begin adsBooks.Cancel; inherited; end; procedure TfrmEditBook.btnOKClick(Sender: TObject); begin try if cbbParentCategory.ItemIndex >= 0 then adsBooks.EntityFieldByName('BooksCategory').AsObject := TCategory(cbbParentCategory.ItemObject); adsBooks.Post; except on E: Exception do begin ShowErrorFmt('Не удалось сохранить книгу "%s"'#10#13+'%s', [edtBookName.Text, E.Message]); adsBooks.Cancel; ModalResult := mrCancel; end; end; inherited; end; class function TfrmEditBook.Edit(ABook: TBook; AManager: TObjectManager): Boolean; var Form: TfrmEditBook; BookName: string; begin Form := TfrmEditBook.Create(Application); try BookName := ABook.BookName; if BookName.IsEmpty then Form.Header := 'Новая книга' else Form.Header := Format('Редактирование книги: %s', [BookName]); Form.SetBook(ABook, AManager); Result := Form.ShowModal = mrOk; finally Form.Free; end; end; procedure TfrmEditBook.SetBook(ABook: TBook; AManager: TObjectManager); begin // открытие DS with adsCategories do begin Close; SetSourceCriteria(AManager.Find<TCategory>.OrderBy('CategoryName')); Open; end; with adsBooks do begin Close; SetSourceObject(ABook); Open; Edit; end; LoadCategory; // if Assigned(ABook.BooksCategory) then // cbbParentCategory.ItemIndex := cbbParentCategory.Properties.Items.IndexOf( ABook.BooksCategory.CategoryName ); cbbParentCategory.ItemObject := ABook.BooksCategory; end; procedure TfrmEditBook.LoadCategory; var C: TCategory; begin cbbParentCategory.Properties.Items.Clear; while not adsCategories.Eof do begin C := adsCategories.EntityFieldByName('Self').AsEntity<TCategory>; cbbParentCategory.Properties.Items.AddObject(C.CategoryName, C); adsCategories.Next; end; end; end.
unit mColumnTree; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, VCL.Controls, Forms, Types, Dialogs, ComCtrls, Themes, UxTheme, ORFn; type TColumnTreeNode = class(TTreeNode) private FColumns: TStrings; FVUID: String; FCode: String; FCodeSys: String; FCodeIEN: String; FParentIndex: String; procedure SetColumns(const Value: TStrings); public property Columns: TStrings read FColumns write SetColumns; property VUID: String read FVUID write FVUID; property Code: String read FCode write FCode; property CodeSys: String read FCodeSys write FCodeSys; property CodeIEN: String read FCodeIEN write FCodeIEN; property ParentIndex: String read FParentIndex write FParentIndex; end; TColumnTreeFrame = class(TFrame) hdrColumns: THeaderControl; tvTree: TTreeView; procedure tvTreeCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); procedure tvTreeAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); procedure tvTreeChange(Sender: TObject; Node: TTreeNode); procedure hdrColumnsSectionResize(HeaderControl: THeaderControl; Section: THeaderSection); private { Private declarations } FSelNode: TColumnTreeNode; procedure DrawExpander(ACanvas: TCanvas; ATextRect: TRect; AExpanded: Boolean; AHot: Boolean); // procedure ApplicationShowHint(var HintStr: String; var CanShow: Boolean; // var HintInfo: VCL.Controls.THintInfo); public { Public declarations } procedure SetColumnTreeModel(ResultSet: TStrings); function FindNode(AValue:String): TColumnTreeNode; property SelectedNode: TColumnTreeNode read FSelNode; end; // subclass THintWindow to override font size TTreeViewHintWindowClass = class(THintWindow) public constructor Create(AOwner: TComponent); override; procedure SetFontSize(fontsize: Integer); function GetFontSize: Integer; end; implementation {$R *.dfm} var tvHintWindowClass: TTreeViewHintWindowClass; // tvShowHint: TShowHintEvent; const BUTTON_SIZE = 5; TreeExpanderSpacing = 6; { TTreeViewHintWindowClass } constructor TTreeViewHintWindowClass.Create(AOwner: TComponent); begin inherited Create(AOwner); // use CPRS font size for hint window SetFontSize(Application.MainForm.Font.Size); tvHintWindowClass := Self; end; function TTreeViewHintWindowClass.GetFontSize: Integer; begin Result := Canvas.Font.Size; end; procedure TTreeViewHintWindowClass.SetFontSize(fontsize: Integer); begin Canvas.Font.Size := fontsize; end; { TColumnTreeNode } procedure TColumnTreeNode.SetColumns(const Value: TStrings); begin FColumns := Value; end; { TColumnTreeFrame } function TColumnTreeFrame.FindNode(AValue: String): TColumnTreeNode; var Match: TColumnTreeNode; function Locate(AValue: String): TColumnTreeNode; var Node: TColumnTreeNode; x, Term: String; j: Integer; begin Result := nil; if tvTree.Items.Count = 0 then Exit; Node := tvTree.Items[0] as TColumnTreeNode; while Node <> nil do begin Term := Node.Text; j := Pos(' *', Term); if j > 0 then x := UpperCase(Copy(Term, 1, j-1)) else x := UpperCase(Term); if x = UpperCase(AValue) then begin Result := Node; Result.MakeVisible; Break; end; Node := Node.GetNext as TColumnTreeNode; end; end; begin Match := Locate(AValue); if Match <> nil then begin Match.Selected := True; end; Result := Match; end; procedure TColumnTreeFrame.hdrColumnsSectionResize( HeaderControl: THeaderControl; Section: THeaderSection); begin tvTree.Invalidate end; procedure TColumnTreeFrame.SetColumnTreeModel(ResultSet: TStrings); var i: Integer; Node: TColumnTreeNode; RecStr: String; begin tvTree.Items.Clear; for i := 0 to ResultSet.Count - 1 do begin RecStr := ResultSet[i]; if Piece(RecStr, '^', 8) = '' then Node := (tvTree.Items.Add(nil, Piece(RecStr, '^', 2))) as TColumnTreeNode else Node := (tvTree.Items.AddChild(tvTree.Items[(StrToInt(Piece(RecStr, '^', 8))-1)], Piece(RecStr, '^', 2))) as TColumnTreeNode; with Node do begin VUID := Piece(RecStr, '^', 1); Text := Piece(RecStr, '^', 2); CodeSys := Piece(RecStr, '^', 3); Code := Piece(RecStr, '^', 4); if Piece(RecStr, '^', 8) <> '' then ParentIndex := IntToStr(StrToInt(Piece(RecStr, '^', 8)) - 1); Columns := TStringList.Create; Columns.Add(Piece(RecStr, '^', 2)); Columns.Add(Piece(RecStr, '^', 3)); Columns.Add(Piece(RecStr, '^', 4)); Columns.Add(Piece(RecStr, '^', 6)); end; end; end; procedure TColumnTreeFrame.DrawExpander(ACanvas: TCanvas; ATextRect: TRect; AExpanded: Boolean; AHot: Boolean); var ExpanderRect: TRect; ThemeData: HTHEME; ElementPart: Integer; ElementState: Integer; ExpanderSize: TSize; begin if StyleServices.Enabled then begin if AHot then // ElementPart := TVP_HOTGLYPH ElementPart := TVP_GLYPH else ElementPart := TVP_GLYPH; if AExpanded then ElementState := GLPS_OPENED else ElementState := GLPS_CLOSED; ThemeData := OpenThemeData(tvTree.Handle, 'TREEVIEW'); GetThemePartSize(ThemeData, ACanvas.Handle, ElementPart, ElementState, nil, TS_TRUE, ExpanderSize); ExpanderRect.Left := ATextRect.Left - TreeExpanderSpacing - ExpanderSize.cx; ExpanderRect.Right := ExpanderRect.Left + ExpanderSize.cx; ExpanderRect.Top := ATextRect.Top + (ATextRect.Bottom - ATextRect.Top - ExpanderSize.cy) div 2; ExpanderRect.Bottom := ExpanderRect.Top + ExpanderSize.cy; DrawThemeBackground(ThemeData, ACanvas.Handle, ElementPart, ElementState, ExpanderRect, nil); CloseThemeData(ThemeData); end else begin // Drawing expander without themes... end; end; procedure TColumnTreeFrame.tvTreeAdvancedCustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean); var i: Integer; CTNode: TColumnTreeNode; NodeRect: TRect; NodeTextRect: TRect; Text: string; ThemeData: HTHEME; TreeItemState: Integer; begin DefaultDraw := True; CTNode := Node as TColumnTreeNode; if (CTNode.Columns <> nil) and (CTNode.Columns.Count > 0) then begin if Stage = cdPrePaint then begin NodeRect := Node.DisplayRect(False); NodeTextRect := Node.DisplayRect(True); // Drawing background if (cdsSelected in State) and Sender.Focused then TreeItemState := TREIS_SELECTED else // if (cdsSelected in State) and (cdsHot in State) then // TreeItemState := TREIS_HOTSELECTED // else if cdsSelected in State then TreeItemState := TREIS_SELECTEDNOTFOCUS else if cdsHot in State then TreeItemState := TREIS_HOT else TreeItemState := TREEITEMStateFiller0; if TreeItemState <> TREEITEMStateFiller0 then begin ThemeData := OpenThemeData(Sender.Handle, 'TREEVIEW'); DrawThemeBackground(ThemeData, Sender.Canvas.Handle, TVP_TREEITEM, TreeItemState, NodeRect, nil); CloseThemeData(ThemeData); end; // Drawing expander if Node.HasChildren then DrawExpander(Sender.Canvas, NodeTextRect, Node.Expanded, cdsHot in State); // Set the background mode and selection text color SetBkMode(Sender.Canvas.Handle, TRANSPARENT); if cdsSelected in State then SetTextColor(Sender.Canvas.Handle, clBlue); // Drawing the column text for each node for i := 0 to hdrColumns.Sections.Count - 1 do begin NodeRect := CTNode.DisplayRect(True); if i > 0 then NodeRect.Left := hdrColumns.Sections[i].Left; NodeRect.Right := hdrColumns.Sections[i].Right; Text := CTNode.Columns[i]; Sender.Canvas.TextRect(NodeRect, Text,[tfVerticalCenter, tfSingleLine, tfWordEllipsis, tfLeft]); end; end; PaintImages := False; DefaultDraw := False; end; end; procedure TColumnTreeFrame.tvTreeChange(Sender: TObject; Node: TTreeNode); begin FSelNode := Node as TColumnTreeNode; end; procedure TColumnTreeFrame.tvTreeCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass); begin NodeClass := TColumnTreeNode; end; // override ApplicationShowHint to assign TTreeHintWindow for tvTree {procedure TColumnTreeFrame.ApplicationShowHint(var HintStr: String; var CanShow: Boolean; var HintInfo: VCL.Controls.THintInfo); begin if HintInfo.HintControl = tvTree then begin HintInfo.HintWindowClass := TTreeViewHintWindowClass; if tvHintWindowClass <> nil then if tvHintWindowClass.GetFontSize <> Application.MainForm.Font.Size then tvHintWindowClass.SetFontSize(Application.MainForm.Font.Size); end; end;} end.
PROGRAM DynamischeDiagonalsummen; FUNCTION IndexFor(n, i, j: integer): integer; BEGIN (* IndexFor *) IndexFor := n * i + j; END; (* IndexFor*) PROCEDURE CalculateDiagonalSums(m: ARRAY of integer; n: integer; var d: ARRAY of integer); var i, j: integer; BEGIN (* CalculateDiagonalSums *) FOR i := Low(d) TO High(d) DO BEGIN j := n * i; WHILE (j <= High(m)) DO BEGIN d[i] := d[i] + m[j]; j := j + n + 1; END; (* WHILE *) END; (* FOR *) END; (* CalculateDiagonalSums *) var size: integer; mLength: integer; matrix: ARRAY of integer; d: ARRAY of integer; i: integer; BEGIN (* DynamischeDiagonalsummen *) Write('Geben Sie die groesse der Matrix ein: '); Read(size); mLength := size * size; SetLength(matrix, mLength); SetLength(d, size); FOR i := 0 TO mLength - 1 DO BEGIN Read(matrix[i]); END; (* FOR *) CalculateDiagonalSums(matrix, size, d); Write('Diagonalsummen: '); FOR i := Low(d) TO High(d) DO BEGIN IF (i = High(d)) THEN BEGIN Write(d[i]); END ELSE BEGIN Write(d[i], ', '); END; (* IF *) END; (* FOR *) END. (* DynamischeDiagonalsummen *)
unit UntLanguage_pt_BR; interface const // Tela Login sTituloLogin = 'Login'; lbIdioma = 'Idioma:'; lbUsername = 'Usuário:'; lbSenha = 'Senha:'; btEntrar = 'Entrar'; btCancelar = 'Cancelar'; // ComboBox CBoxLinguagem sItemPt = 'Português (Brasil)'; sItemEn = 'Inglês (EUA)'; sMsgErroLogin = 'Usuário e/ou senha inválido(s)'; // Tela Principal sTituloTelaPrincipal = 'Tela Principal'; menuItemPesquisa = 'Pesquisa'; menuItemFuncionario = 'Funcionário'; menuItemCargo = 'Cargo'; menuItemFornecedor = 'Fornecedor'; menuItemProduto = 'Produto'; menuItemSistema = 'Sistema'; menuItemUsuario = 'Usuário'; menuItemSair = 'Sair'; // Pesquisa de Funcionario sTituloTelaPesqFunci = 'Pesquisa de Funcionário'; sLblTituloTabSheet = 'Funcionários'; sTabShtInc = 'Incluir'; sTabShtEdt = 'Editar'; sMsgCargoObrigatorio = 'O campo Cargo é obrigatório !'; slblIdFunci = 'Id:'; slblNomeFunci = 'Nome:'; slblRGFunci = 'RG:'; slblCPFFunci = 'CPF:'; slblCargoFunci = 'Cargo:'; slblDBGIdFunci = 'Id'; slblDBGNomeFunci = 'Nome'; slblDBGRGFunci = 'RG'; slblDBGCPFFunci = 'CPF'; sbtnPesquFunciSalvar = 'Salvar'; sbtnPesquFunciCancelar = 'Cancelar'; // Consts.pas SMsgDlgConfirm = 'Confirmação'; SMsgDlgWarning = 'Atenção'; SMsgDlgCancel = 'Cancelar'; SDeleteRecordQuestion = 'Deseja realmente deletar o registro ?'; // Pesquisa de Cargo sTituloTelaPesqCargo = 'Pesquisa de Cargo'; sLblTituloTabSheetCargo = 'Cargos'; slblIdCargo = 'Id:'; slblDescricaoCargo = 'Descrição:'; slblSalarioCargo = 'Salário:'; slblDBGIdCargo = 'Id'; slblDBGDescricaoCargo = 'Descrição'; slblDBGSalarioCargo = 'Salário'; sbtnPesquCargoSalvar = 'Salvar'; sbtnPesquCargoCancelar = 'Cancelar'; // Pesquisa de Fornecedor sTituloTelaPesqFornecedor = 'Pesquisa de Fornecedor'; sLblTituloTabSheetFornecedor = 'Fornecedores'; slblCNPJFornecedor = 'CNPJ:'; slblNomeFantasiaFornecedor = 'Nome Fantasia:'; slblDBGCNPJFornecedor = 'CNPJ'; slblDBGNomeFantasiaFornecedor = 'Nome Fantasia'; sbtnPesquFornecedorSalvar = 'Salvar'; sbtnPesquFornecedorCancelar = 'Cancelar'; // Pesquisa de Produto sTituloTelaPesqProduto = 'Pesquisa de Produto'; sLblTituloTabSheetProduto = 'Produtos'; sMsgFornecedorObrigatorio = 'O campo Fornecedor é obrigatório !'; slblIdProduto = 'Id:'; slblDescricaoProduto = 'Descrição:'; slblDetalheProduto = 'Detalhe:'; slblPrecoCompraProduto = 'Preço de Compra:'; slblPrecoVendaProduto = 'Preço de Venda:'; slblFornecedorProduto = 'Fornecedor:'; slblDBGIdProduto = 'Id'; slblDBGDescricaoProduto = 'Descrição'; slblDBGDetalheProduto = 'Detalhe'; slblDBGPrecoCompraProduto = 'Preço de Compra'; slblDBGPrecoVendaProduto = 'Preço de Venda'; sbtnPesquProdutoSalvar = 'Salvar'; sbtnPesquProdutoCancelar = 'Cancelar'; // Pesquisa de Usuario sTituloTelaPesqUsuario = 'Pesquisa de Usuário'; sLblTituloTabSheetUsuario = 'Usuários'; sMsgFuncionarioObrigatorio = 'O campo Funcionário é obrigatório'; slblIdUsuario = 'Id:'; slblUsuarioUsuario = 'Usuário:'; slblSenhaUsuario = 'Senha:'; slblFuncionarioUsuario = 'Funcionário:'; slblDBGIdUsuario = 'Id'; slblDBGUsuarioUsuario = 'Usuário'; slblDBGSenhaUsuario = 'Senha'; sbtnPesquUsuarioSalvar = 'Salvar'; sbtnPesquUsuarioCancelar = 'Cancelar'; implementation end.
{ This unit is part of the Lua4Delphi Source Code Copyright (C) 2009-2012, LaKraven Studios Ltd. Copyright Protection Packet(s): L4D014 www.Lua4Delphi.com www.LaKraven.com -------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------- Unit: L4D.Engine.MainIntf.pas Released: 22nd February 2012 Changelog: 13th March 2012: - Added "IL4D<interface>Internal" as appropriate to separate inner workings from public view - Added access to IL4DEngine interface to all Stack Managers! 12th March 2012: - Refactored a lot related to Stacks, Values and Tables - Removed unnecessary methods related to Methods (such as Offset getter/setter). - Other changes (too many to enumerate) 22nd February 2012: - Created } unit L4D.Engine.MainIntf; interface {$I Lua4Delphi.inc} uses {$IFDEF DELPHIXE2} System.Classes, {$ELSE} Classes, {$ENDIF} L4D.Lua.Intf, L4D.Lua.Common; type { Lua4Delphi-specific Enums } TL4DStackValueType = (svtNone = -1, svtNil = 0, svtBoolean, svtLightUserData, svtNumber, svtString, svtTable, svtFunction, svtUserdata, svtThread); const // Lua4Delphi-specific Type Constants... LUA_TYPES: Array[0..9] of TL4DStackValueType = (svtNone, svtNil, svtBoolean, svtLightUserData, svtNumber, svtString, svtTable, svtFunction, svtUserdata, svtThread); LUA_TYPE_NAMES: Array[TL4DStackValueType] of String = ('None', 'Nil', 'Boolean', 'Light Userdata', 'Number', 'String', 'Table', 'Function', 'Userdata', 'Thread'); type { Forward Declarations } IL4DEngineMember = interface; IL4DMethod = interface; IL4DMethodObject = interface; IL4DStack = interface; IL4DStackIndexed = interface; IL4DStackKeyed = interface; IL4DStackCombo = interface; IL4DStackValue = interface; IL4DTableValue = interface; IL4DTable = interface; IL4DMethodResultStackValue = interface; IL4DMethodResultStack = interface; IL4DMethodStackValue = interface; IL4DMethodStack = interface; IL4DGlobalStackValue = interface; IL4DGlobalStack = interface; IL4DEngineManager = interface; IL4DEngine = interface; { Method Types } TL4DDelphiFunction = procedure(var ALuaStack: IL4DMethodStack); TL4DDelphiObjectFunction = procedure(var ALuaStack: IL4DMethodStack) of object; { Internal-use OnEvent Method Types } TL4DTableChangeEvent = procedure(const ATable: IL4DTable) of object; { IL4DEngineMember } IL4DEngineMember = interface ['{13D03502-588B-4904-872C-3B260E33F94F}'] function GetEngine: IL4DEngine; property Engine: IL4DEngine read GetEngine; end; { IL4DMethod } IL4DMethod = interface ['{E8C80E1B-A5D1-480F-B14E-055898A28C10}'] end; { IL4DMethodObject } IL4DMethodObject = interface ['{9C3B9942-40B4-49F0-95CC-C49F805971E3}'] end; { IL4DStack } IL4DStack = interface ['{B4A38302-6D60-4217-B8A8-792FE4999888}'] function GetCount: Integer; function GetEngine: IL4DEngine; property Count: Integer read GetCount; property Engine: IL4DEngine read GetEngine; end; { IL4DStackIndexed } IL4DStackIndexed = interface(IL4DStack) ['{66CFB82A-D726-48E7-923B-6C0C9BEFDD30}'] function NewTable: IL4DTable; procedure PushAnsiChar(const AValue: AnsiChar); procedure PushAnsiString(const AValue: AnsiString); procedure PushBoolean(const AValue: Boolean); procedure PushChar(const AValue: Char); procedure PushDouble(const AValue: Double); procedure PushExtended(const AValue: Extended); procedure PushFunction(const AValue: TL4DDelphiFunction); overload; // Stack-Managed Delphi Procedure procedure PushFunction(const AValue: TL4DDelphiObjectFunction); overload; // Stack-Managed Delphi Object Procedure procedure PushFunction(const AValue: TLuaDelphiFunction); overload; // Standard Lua "C" Function procedure PushInteger(const AValue: Integer); procedure PushPAnsiChar(const AValue: PAnsiChar); procedure PushPChar(const AValue: PChar); procedure PushPointer(const AValue: Pointer); procedure PushSingle(const AValue: Single); procedure PushString(const AValue: WideString); procedure PushVariant(const AValue: Variant); procedure PushWideString(const AValue: WideString); end; { IL4DStackKeyed } IL4DStackKeyed = interface(IL4DStack) ['{6D889C0C-4611-49D7-841E-1B76C29CE15E}'] function NewTable(const AKey: AnsiString): IL4DTable; procedure PushAnsiChar(const AKey: AnsiString; const AValue: AnsiChar); procedure PushAnsiString(const AKey: AnsiString; const AValue: AnsiString); procedure PushBoolean(const AKey: AnsiString; const AValue: Boolean); procedure PushChar(const AKey: AnsiString; const AValue: Char); procedure PushDouble(const AKey: AnsiString; const AValue: Double); procedure PushExtended(const AKey: AnsiString; const AValue: Extended); procedure PushFunction(const AKey: AnsiString; const AValue: TL4DDelphiFunction); overload; // Stack-Managed Delphi Procedure procedure PushFunction(const AKey: AnsiString; const AValue: TL4DDelphiObjectFunction); overload; // Stack-Managed Delphi Object Procedure procedure PushFunction(const AKey: AnsiString; const AValue: TLuaDelphiFunction); overload; // Standard Lua "C" Function procedure PushInteger(const AKey: AnsiString; const AValue: Integer); procedure PushPAnsiChar(const AKey: AnsiString; const AValue: PAnsiChar); procedure PushPChar(const AKey: AnsiString; const AValue: PChar); procedure PushPointer(const AKey: AnsiString; const AValue: Pointer); procedure PushSingle(const AKey: AnsiString; const AValue: Single); procedure PushString(const AKey: AnsiString; const AValue: WideString); procedure PushVariant(const AKey: AnsiString; const AValue: Variant); procedure PushWideString(const AKey: AnsiString; const AValue: WideString); end; { IL4DStackCombo NOTE: METHODS CONTAINED WITHIN MUST BE A DIRECT CLONE OF "IL4DStackKeyed". This is due to an annoying limitation on Inheritence of Interfaces in Delphi. } IL4DStackCombo = interface(IL4DStackIndexed) ['{3AC69963-8142-44F7-8C10-0CE82C6A5401}'] function NewTable(const AKey: AnsiString): IL4DTable; overload; procedure PushAnsiChar(const AKey: AnsiString; const AValue: AnsiChar); overload; procedure PushAnsiString(const AKey: AnsiString; const AValue: AnsiString); overload; procedure PushBoolean(const AKey: AnsiString; const AValue: Boolean); overload; procedure PushChar(const AKey: AnsiString; const AValue: Char); overload; procedure PushDouble(const AKey: AnsiString; const AValue: Double); overload; procedure PushExtended(const AKey: AnsiString; const AValue: Extended); overload; procedure PushFunction(const AKey: AnsiString; const AValue: TL4DDelphiFunction); overload; // Stack-Managed Delphi Procedure procedure PushFunction(const AKey: AnsiString; const AValue: TL4DDelphiObjectFunction); overload; // Stack-Managed Delphi Object Procedure procedure PushFunction(const AKey: AnsiString; const AValue: TLuaDelphiFunction); overload; // Standard Lua "C" Function procedure PushInteger(const AKey: AnsiString; const AValue: Integer); overload; procedure PushPAnsiChar(const AKey: AnsiString; const AValue: PAnsiChar); overload; procedure PushPChar(const AKey: AnsiString; const AValue: PChar); overload; procedure PushPointer(const AKey: AnsiString; const AValue: Pointer); overload; procedure PushSingle(const AKey: AnsiString; const AValue: Single); overload; procedure PushString(const AKey: AnsiString; const AValue: WideString); overload; procedure PushVariant(const AKey: AnsiString; const AValue: Variant); overload; procedure PushWideString(const AKey: AnsiString; const AValue: WideString); overload; end; { IL4DStackValue } IL4DStackValue = interface ['{42CFEE5D-56E9-4A22-B4F7-AA90E5389CB9}'] // Getters function GetAsAnsiString: AnsiString; function GetAsBoolean: Boolean; function GetAsChar: Char; function GetAsDouble: Double; function GetAsExtended: Extended; function GetAsInteger: Integer; function GetAsPAnsiChar: PAnsiChar; function GetAsPChar: PChar; function GetAsPointer: Pointer; function GetAsSingle: Single; function GetAsString: String; function GetAsTable: IL4DTable; function GetAsVariant: Variant; function GetAsWideString: WideString; function GetCanBeAnsiString: Boolean; function GetCanBeBoolean: Boolean; function GetCanBeChar: Boolean; function GetCanBeDouble: Boolean; function GetCanBeExtended: Boolean; function GetCanBeInteger: Boolean; function GetCanBePAnsiChar: Boolean; function GetCanBePChar: Boolean; function GetCanBePointer: Boolean; function GetCanBeSingle: Boolean; function GetCanBeString: Boolean; function GetCanBeTable: Boolean; function GetCanBeVariant: Boolean; function GetCanBeWideString: Boolean; function GetType: TL4DStackValueType; function GetTypeName: String; // Public & Properties function CallFunction(AParameters: array of const; const AResultCount: Integer = LUA_MULTRET): IL4DMethodResultStack; property AsAnsiString: AnsiString read GetAsAnsiString; property AsBoolean: Boolean read GetAsBoolean; property AsChar: Char read GetAsChar; property AsDouble: Double read GetAsDouble; property AsExtended: Extended read GetAsExtended; property AsInteger: Integer read GetAsInteger; property AsPAnsiChar: PAnsiChar read GetAsPAnsiChar; property AsPChar: PChar read GetAsPChar; property AsPointer: Pointer read GetAsPointer; property AsSingle: Single read GetAsSingle; property AsString: String read GetAsString; property AsTable: IL4DTable read GetAsTable; property AsVariant: Variant read GetAsVariant; property AsWideString: WideString read GetAsWideString; property CanBeAnsiString: Boolean read GetCanBeAnsiString; property CanBeBoolean: Boolean read GetCanBeBoolean; property CanBeChar: Boolean read GetCanBeChar; property CanBeDouble: Boolean read GetCanBeDouble; property CanBeExtended: Boolean read GetCanBeExtended; property CanBeInteger: Boolean read GetCanBeInteger; property CanBePAnsiChar: Boolean read GetCanBePAnsiChar; property CanBePChar: Boolean read GetCanBePChar; property CanBePointer: Boolean read GetCanBePointer; property CanBeSingle: Boolean read GetCanBeSingle; property CanBeString: Boolean read GetCanBeString; property CanBeTable: Boolean read GetCanBeTable; property CanBeVariant: Boolean read GetCanBeVariant; property CanBeWideString: Boolean read GetCanBeWideString; property LuaType: TL4DStackValueType read GetType; property LuaTypeName: String read GetTypeName; end; { IL4DTableValueInternal } IL4DTableValueInternal = interface ['{2F117FB3-92F6-4B05-AD30-AFF8EFCA2715}'] procedure SetIndex(const AIndex: Integer); procedure SetKey(const AKey: AnsiString); end; { IL4DTableValue } IL4DTableValue = interface(IL4DStackValue) ['{6782A114-18C5-4E1F-8FA3-E9E175735961}'] property AsAnsiString: AnsiString read GetAsAnsiString; property AsBoolean: Boolean read GetAsBoolean; property AsChar: Char read GetAsChar; property AsDouble: Double read GetAsDouble; property AsExtended: Extended read GetAsExtended; property AsInteger: Integer read GetAsInteger; property AsPAnsiChar: PAnsiChar read GetAsPAnsiChar; property AsPChar: PChar read GetAsPChar; property AsPointer: Pointer read GetAsPointer; property AsSingle: Single read GetAsSingle; property AsString: String read GetAsString; property AsTable: IL4DTable read GetAsTable; property AsVariant: Variant read GetAsVariant; property AsWideString: WideString read GetAsWideString; property CanBeAnsiString: Boolean read GetCanBeAnsiString; property CanBeBoolean: Boolean read GetCanBeBoolean; property CanBeChar: Boolean read GetCanBeChar; property CanBeDouble: Boolean read GetCanBeDouble; property CanBeExtended: Boolean read GetCanBeExtended; property CanBeInteger: Boolean read GetCanBeInteger; property CanBePAnsiChar: Boolean read GetCanBePAnsiChar; property CanBePChar: Boolean read GetCanBePChar; property CanBePointer: Boolean read GetCanBePointer; property CanBeSingle: Boolean read GetCanBeSingle; property CanBeString: Boolean read GetCanBeString; property CanBeTable: Boolean read GetCanBeTable; property CanBeVariant: Boolean read GetCanBeVariant; property CanBeWideString: Boolean read GetCanBeWideString; property LuaType: TL4DStackValueType read GetType; property LuaTypeName: String read GetTypeName; end; { IL4DTableInternal } IL4DTableInternal = interface ['{2929F799-A7F2-48A8-8DB0-1C6DBFD9141F}'] function GetName: AnsiString; procedure PushTable; procedure SetIndex(const AIndex: Integer); overload; procedure SetName(const AName: AnsiString); overload; procedure SetOnPushTable(const AEvent: TL4DTableChangeEvent); overload; end; { IL4DTable } IL4DTable = interface(IL4DStackCombo) ['{FCFD27AC-D5EC-42A4-81EF-E1288A6A1EB6}'] procedure Close; function GetValueByIndex(const AIndex: Integer): IL4DTableValue; function GetValueByName(const AName: AnsiString): IL4DTableValue; procedure Push; property Value[const AIndex: Integer]: IL4DTableValue read GetValueByIndex; default; property Value[const AName: AnsiString]: IL4DTableValue read GetValueByName; default; end; { IL4DMethodResultStackValue } IL4DMethodResultStackValue = interface(IL4DStackValue) ['{97D4EEDC-D104-42C0-8C5D-DC098ED87B0B}'] property AsAnsiString: AnsiString read GetAsAnsiString; property AsBoolean: Boolean read GetAsBoolean; property AsChar: Char read GetAsChar; property AsDouble: Double read GetAsDouble; property AsExtended: Extended read GetAsExtended; property AsInteger: Integer read GetAsInteger; property AsPAnsiChar: PAnsiChar read GetAsPAnsiChar; property AsPChar: PChar read GetAsPChar; property AsPointer: Pointer read GetAsPointer; property AsSingle: Single read GetAsSingle; property AsString: String read GetAsString; property AsTable: IL4DTable read GetAsTable; property AsVariant: Variant read GetAsVariant; property AsWideString: WideString read GetAsWideString; property CanBeAnsiString: Boolean read GetCanBeAnsiString; property CanBeBoolean: Boolean read GetCanBeBoolean; property CanBeChar: Boolean read GetCanBeChar; property CanBeDouble: Boolean read GetCanBeDouble; property CanBeExtended: Boolean read GetCanBeExtended; property CanBeInteger: Boolean read GetCanBeInteger; property CanBePAnsiChar: Boolean read GetCanBePAnsiChar; property CanBePChar: Boolean read GetCanBePChar; property CanBePointer: Boolean read GetCanBePointer; property CanBeSingle: Boolean read GetCanBeSingle; property CanBeString: Boolean read GetCanBeString; property CanBeTable: Boolean read GetCanBeTable; property CanBeVariant: Boolean read GetCanBeVariant; property CanBeWideString: Boolean read GetCanBeWideString; property LuaType: TL4DStackValueType read GetType; property LuaTypeName: String read GetTypeName; end; { IL4DMethodResultStack } IL4DMethodResultStack = interface(IL4DStack) ['{443213D7-773C-413A-8680-CFEF834CCC15}'] procedure Cleanup; function GetValue(const AIndex: Integer): IL4DMethodResultStackValue; property Count: Integer read GetCount; property Value[const AIndex: Integer]: IL4DMethodResultStackValue read GetValue; default; end; { IL4DMethodStackValue } IL4DMethodStackValue = interface(IL4DStackValue) ['{DF44A959-F488-4970-A74A-3E73E782E388}'] property AsAnsiString: AnsiString read GetAsAnsiString; property AsBoolean: Boolean read GetAsBoolean; property AsChar: Char read GetAsChar; property AsDouble: Double read GetAsDouble; property AsExtended: Extended read GetAsExtended; property AsInteger: Integer read GetAsInteger; property AsPAnsiChar: PAnsiChar read GetAsPAnsiChar; property AsPChar: PChar read GetAsPChar; property AsPointer: Pointer read GetAsPointer; property AsSingle: Single read GetAsSingle; property AsString: String read GetAsString; property AsTable: IL4DTable read GetAsTable; property AsVariant: Variant read GetAsVariant; property AsWideString: WideString read GetAsWideString; property CanBeAnsiString: Boolean read GetCanBeAnsiString; property CanBeBoolean: Boolean read GetCanBeBoolean; property CanBeChar: Boolean read GetCanBeChar; property CanBeDouble: Boolean read GetCanBeDouble; property CanBeExtended: Boolean read GetCanBeExtended; property CanBeInteger: Boolean read GetCanBeInteger; property CanBePAnsiChar: Boolean read GetCanBePAnsiChar; property CanBePChar: Boolean read GetCanBePChar; property CanBePointer: Boolean read GetCanBePointer; property CanBeSingle: Boolean read GetCanBeSingle; property CanBeString: Boolean read GetCanBeString; property CanBeTable: Boolean read GetCanBeTable; property CanBeVariant: Boolean read GetCanBeVariant; property CanBeWideString: Boolean read GetCanBeWideString; property LuaType: TL4DStackValueType read GetType; property LuaTypeName: String read GetTypeName; end; { IL4DMethodInternal } IL4DMethodStackInternal = interface ['{06D1CD69-EBF5-4260-A724-B34AB7363AA3}'] function GetPushCount: Integer; end; { IL4DMethodStack } IL4DMethodStack = interface(IL4DStackIndexed) ['{424F2054-837C-4CAA-AE38-386E247A52CD}'] function GetValue(const AIndex: Integer): IL4DMethodStackValue; property Value[const AIndex: Integer]: IL4DMethodStackValue read GetValue; default; end; { IL4DGlobalStackValue } IL4DGlobalStackValue = interface(IL4DStackValue) ['{849E7A91-C78A-4A1A-B82A-B9B895339198}'] procedure Delete; procedure SetAnsiString(const AValue: AnsiString); procedure SetBoolean(const AValue: Boolean); procedure SetChar(const AValue: Char); procedure SetDouble(const AValue: Double); procedure SetExtended(const AValue: Extended); procedure SetInteger(const AValue: Integer); procedure SetPAnsiChar(const AValue: PAnsiChar); procedure SetPChar(const AValue: PChar); procedure SetPointer(const AValue: Pointer); procedure SetSingle(const AValue: Single); procedure SetString(const AValue: String); procedure SetVariant(const AValue: Variant); procedure SetWideString(const AValue: WideString); property AsAnsiString: AnsiString read GetAsAnsiString write SetAnsiString; property AsBoolean: Boolean read GetAsBoolean write SetBoolean; property AsChar: Char read GetAsChar write SetChar; property AsDouble: Double read GetAsDouble write SetDouble; property AsExtended: Extended read GetAsExtended write SetExtended; property AsInteger: Integer read GetAsInteger write SetInteger; property AsPAnsiChar: PAnsiChar read GetAsPAnsiChar write SetPAnsiChar; property AsPChar: PChar read GetAsPChar write SetPChar; property AsPointer: Pointer read GetAsPointer write SetPointer; property AsSingle: Single read GetAsSingle write SetSingle; property AsString: String read GetAsString write SetString; property AsTable: IL4DTable read GetAsTable; property AsVariant: Variant read GetAsVariant write SetVariant; property AsWideString: WideString read GetAsWideString write SetWideString; property CanBeAnsiString: Boolean read GetCanBeAnsiString; property CanBeBoolean: Boolean read GetCanBeBoolean; property CanBeChar: Boolean read GetCanBeChar; property CanBeDouble: Boolean read GetCanBeDouble; property CanBeExtended: Boolean read GetCanBeExtended; property CanBeInteger: Boolean read GetCanBeInteger; property CanBePAnsiChar: Boolean read GetCanBePAnsiChar; property CanBePChar: Boolean read GetCanBePChar; property CanBePointer: Boolean read GetCanBePointer; property CanBeSingle: Boolean read GetCanBeSingle; property CanBeString: Boolean read GetCanBeString; property CanBeTable: Boolean read GetCanBeTable; property CanBeVariant: Boolean read GetCanBeVariant; property CanBeWideString: Boolean read GetCanBeWideString; property LuaType: TL4DStackValueType read GetType; property LuaTypeName: String read GetTypeName; end; { IL4DGlobalStack } IL4DGlobalStack = interface(IL4DStack) ['{37D5DF87-8737-4512-A8DC-791C26C9D089}'] function GetGlobal(const AKey: AnsiString): IL4DGlobalStackValue; procedure SetGlobal(const AKey: AnsiString); property Value[const AKey: AnsiString]: IL4DGlobalStackValue read GetGlobal; default; end; { IL4DEngineManager } IL4DEngineManager = interface ['{09629B49-C4FB-466B-8513-19BF612EE9D4}'] end; { IL4DEngineInternal } IL4DEngineInternal = interface ['{F3E9410B-C1C6-4533-BCF6-FD04085F8062}'] function CallFunction(AParameters: array of const; const AResultCount: Integer = LUA_MULTRET): IL4DMethodResultStack; function GetAsAnsiString(const AIndex: Integer): AnsiString; function GetAsBoolean(const AIndex: Integer): Boolean; function GetAsChar(const AIndex: Integer): Char; function GetAsDouble(const AIndex: Integer): Double; function GetAsExtended(const AIndex: Integer): Extended; function GetAsInteger(const AIndex: Integer): Integer; function GetAsPAnsiChar(const AIndex: Integer): PAnsiChar; function GetAsPChar(const AIndex: Integer): PChar; function GetAsPointer(const AIndex: Integer): Pointer; function GetAsSingle(const AIndex: Integer): Single; function GetAsString(const AIndex: Integer): WideString; function GetAsTable(const AIndex: Integer): IL4DTable; function GetAsWideString(const AIndex: Integer): WideString; function GetAsVariant(const AIndex: Integer): Variant; function GetLuaType(const AIndex: Integer): TL4DStackValueType; //inline; function GetLuaTypeName(const AIndex: Integer): String; function LoadLuaCode(const ACode, AName: WideString; const AAutoExecute: Boolean = True): Boolean; function LoadLuaFile(const AFileName: WideString; const AAutoExecute: Boolean = True): Boolean; function NewTable: IL4DTable; procedure Pop(const ANumber: Integer); procedure PushAnsiChar(const AValue: AnsiChar); procedure PushAnsiString(const AValue: AnsiString); procedure PushBoolean(const AValue: Boolean); procedure PushChar(const AValue: Char); procedure PushDouble(const AValue: Double); procedure PushExtended(const AValue: Extended); procedure PushFunction(const AValue: TL4DDelphiFunction); overload; // Stack-Managed Delphi Procedure procedure PushFunction(const AValue: TL4DDelphiObjectFunction); overload; // Stack-Managed Delphi Object Procedure procedure PushFunction(const AValue: TLuaDelphiFunction); overload; // Standard Lua "C" Function procedure PushInteger(const AValue: Integer); procedure PushPAnsiChar(const AValue: PAnsiChar); procedure PushPChar(const AValue: PChar); procedure PushPointer(const AValue: Pointer); procedure PushSingle(const AValue: Single); procedure PushString(const AValue: WideString); procedure PushVariant(const AValue: Variant); procedure PushWideString(const AValue: WideString); procedure Remove(const AIndex: Integer); function SafeLuaExecute(const ANumArgs: Integer = 0; const ANumResults: Integer = 0; const AErrorFunc: Integer = 0): Integer; // Handles exceptions when executing Lua code end; { IL4DEngine } IL4DEngine = interface ['{E9C6CD0C-0CE0-4073-AA1B-217520E93929}'] function GetLua: TLuaCommon; property Lua: TLuaCommon read GetLua; end; implementation end.
unit UnitMain; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Types, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, //GLScene GLUtils, GLFilePGM, GLGraphics, GLSCUDAUtility, GLSCUDADataAccess, GLVectorTypes, CPUFFT, GLSCUDAFFTPlan, GLSCUDA, GLSCUDAContext; type TDemoMode = (dmNone, dm1D, dm2D, dmLena); TForm1 = class(TForm) Panel1: TPanel; But1DFFT: TButton; But2DFFT: TButton; BLenna: TButton; Label4: TLabel; CBReorder: TCheckBox; Label5: TLabel; CBInvFFT: TCheckBox; Label3: TLabel; RBModule: TRadioButton; RBPhase: TRadioButton; RBReal: TRadioButton; RBImag: TRadioButton; Panel2: TPanel; Label1: TLabel; LDemoMode: TLabel; Label2: TLabel; Image2: TImage; Image1: TImage; GLSCUDA1: TGLSCUDA; GLSCUDADevice1: TGLSCUDADevice; Signal1D: TCUDAMemData; FFTPlan1D: TCUDAFFTPlan; ESize: TLabeledEdit; DeviceBox: TComboBox; Temp1D: TCUDAMemData; Signal2D: TCUDAMemData; Temp2D: TCUDAMemData; FFTPlan2D: TCUDAFFTPlan; procedure But1DFFTClick(Sender: TObject); procedure But2DFFTClick(Sender: TObject); procedure ExecDemo(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private DemoMode: TDemoMode; FTimer: Cardinal; procedure Load1DBmp(out buf: TByteDynArray); procedure Save1DBmp(buf: TByteDynArray); procedure Load2DBmp(out buf: TByte2DArray); procedure LoadLenna(out buf: TByte2DArray); procedure Save2DBmp(buf: TByte2DArray); procedure DrawBmp(bmp: TBitmap; buf: TByteDynArray); function GetDisplayMode: TProcessMode; end; var Form1: TForm1; implementation {$R *.dfm} // ============================== 1D CASE =========================== procedure TForm1.But1DFFTClick(Sender: TObject); var cArr: TComplexDynArray; j, len: integer; buf: TByteDynArray; c: TComplex; c_: DoubleElement.TVector2; v1, v2: IntElement.TVector3; begin DemoMode := dm1D; // get input signal in buf Load1DBmp(buf); len := length(buf); SetLength(cArr, len); if DeviceBox.ItemIndex = 0 then begin // copy input buf into work array cArr c.Real := 0; c.Imag := 0; for j := len - 1 downto 0 do begin c.Real := buf[j]; cArr[j] := c; end; cutStartTimer( FTimer ); // perform fft on cArr; get result back in cArr ftu(1, len, cArr); // reorder quadrants left<->right if CBReorder.Checked then Reorder(cArr); // perform inverse fft on cArr to restore input signal if CBInvFFT.Checked then ftu(-1, len, cArr); cutStopTimer( FTimer ); end else begin Signal1D.Map([mmfFastWrite]); c_[1] := 0; try for j := len - 1 downto 0 do begin c_[0] := buf[j]; Signal1D.Data<Double>(j).Vector2 := c_; end; finally Signal1D.UnMap; end; cutStartTimer( FTimer ); FFTPlan1D.Execute(Signal1D, Signal1D, fftdForward); if CBReorder.Checked then begin v1[0] := 128; v1[1] := 0; v1[2] := 0; v2[0] := 0; v2[1] := 0; v2[2] := 0; Signal1D.SubCopyTo(Temp1D, v1, v2, v1); Signal1D.SubCopyTo(Signal1D, v2, v1, v1); Temp1D.SubCopyTo(Signal1D, v2, v2, v1); end; if CBInvFFT.Checked then FFTPlan1D.Execute(Signal1D, Signal1D, fftdInverse); // Readback result Signal1D.Map; try // We may move hole data due to types size is equal Move(Signal1D.MappedMemoryAddress^, cArr[0], Signal1D.DataSize); finally Signal1D.UnMap; end; cutStopTimer( FTimer ); end; // normalize result in cArr to [0,255] and copy it to buf Normalize(cArr, buf, GetDisplayMode); // display result Save1DBmp(buf); LDemoMode.Caption := Format('1D FFT Demo, time: %f (ms)', [cutGetTimerValue( FTimer )]); cutResetTimer( FTimer ); end; procedure TForm1.Load1DBmp(out buf: TByteDynArray); var h, i, j, w: integer; bmp: TBitmap; begin // set up bitmap in Image1 bmp := Image1.Picture.Bitmap; bmp.PixelFormat := pf8bit; bmp.Canvas.FillRect(Image1.ClientRect); h := bmp.Height; // =256 // prepare buf to store input data SetLength(buf, h); FillChar(buf[0], h, 0); j := h div 2; w := StrToInt(ESize.Text) div 2; // place a pulse wide 2*w at the center of buf if (w <= 0) or (w > h div 2) then raise Exception.Create('Pulse size is out of range [2,255]'); for i := j - w to j + w do buf[i] := 255; // draw input date into Image1 DrawBmp(bmp, buf); end; procedure TForm1.Save1DBmp(buf: TByteDynArray); var bmp: TBitmap; begin // setup bitmap in Image2 bmp := Image2.Picture.Bitmap; bmp.Canvas.FillRect(Image2.ClientRect); // draw result in Image2 DrawBmp(bmp, buf); end; procedure TForm1.DrawBmp(bmp: TBitmap; buf: TByteDynArray); var h, i: integer; begin h := bmp.Height; bmp.Canvas.MoveTo(0, h - buf[0] - 1); for i := 0 to length(buf) - 1 do bmp.Canvas.LineTo(i, h - buf[i] - 1); end; // ============================== 2D CASE =========================== procedure TForm1.But2DFFTClick(Sender: TObject); var cArr: TComplex2DArray; i, j, len: integer; buf: TByte2DArray; c: TComplex; c_: DoubleElement.TVector2 absolute c; v1, v2, v3, v4: IntElement.TVector3; begin // load input bmp into buf[rows,cols] if Sender = BLenna then LoadLenna(buf) else Load2DBmp(buf); len := length(buf); // the original fft routine uses cArr[1..rows,1..cols] SetLength(cArr, len, len); // cArr[rows,cols] if DeviceBox.ItemIndex = 0 then begin // copy buf[bytes]->cArr[Real,Imag=0] c.Real := 0; c.Imag := 0; for i := 0 to len - 1 do for j := 0 to len - 1 do begin c.Real := buf[i, j]; cArr[i, j] := c; end; cutStartTimer( FTimer ); // apply forward fft ftu(1, len, cArr); // reorder quadrants if CBReorder.Checked then Reorder(cArr); if CBInvFFT.Checked then // apply inverse fft ftu(-1, len, cArr); cutStopTimer( FTimer ); end else begin Signal2D.Map([mmfFastWrite]); c_[1] := 0; try for I := len - 1 downto 0 do for J := len - 1 downto 0 do begin c_[0] := buf[i, j]; Signal2D.Data<Double>(j, i).Vector2 := c_; end; finally Signal2D.UnMap; end; cutStartTimer( FTimer ); FFTPlan2D.Execute(Signal2D, Signal2D, fftdForward); if CBReorder.Checked then begin v1[0] := 128; v1[1] := 128; v1[2] := 128; v2[0] := 0; v2[1] := 0; v2[2] := 0; Signal2D.SubCopyTo(Temp2D, v2, v2, v1); Signal2D.SubCopyTo(Signal2D, v1, v2, v1); Temp2D.SubCopyTo(Signal2D, v2, v1, v1); v3[0] := 128; v3[1] := 0; v3[2] := 0; v4[0] := 0; v4[1] := 128; v4[2] := 0; Signal2D.SubCopyTo(Temp2D, v3, v2, v1); Signal2D.SubCopyTo(Signal2D, v4, v3, v1); Temp2D.SubCopyTo(Signal2D, v2, v4, v1); end; if CBInvFFT.Checked then FFTPlan2D.Execute(Signal2D, Signal2D, fftdInverse); cutStopTimer( FTimer ); // Readback result Signal2D.Map; try // We may move hole data due to types size is equal for I := len - 1 downto 0 do for j := len - 1 downto 0 do begin c_ := Signal2D.Data<Double>(j, i).Vector2; cArr[i, j] := c; end; finally Signal2D.UnMap; end; end; // normalize cArr Normalize(cArr, buf, GetDisplayMode); // stuff bmp with buf Save2DBmp(buf); if Sender = BLenna then LDemoMode.Caption := Format('2D FFT Demo Lenna, time: %f (ms)', [cutGetTimerValue( FTimer )]) else LDemoMode.Caption := Format('2D FFT Demo, time: %f (ms)', [cutGetTimerValue( FTimer )]); cutResetTimer( FTimer ); end; procedure TForm1.Load2DBmp(out buf: TByte2DArray); var bmp: TBitmap; i, j, k, w, h: integer; begin DemoMode := dm2D; h := 256; // setup buf to store input data into SetLength(buf, h, h); // buf[rows,cols] for i := 0 to h - 1 do FillChar(buf[i, 0], h, 0); k := h div 2; w := StrToInt(ESize.Text) div 2; // place pulse size [2*w,2*w] at the center of buf if (w <= 0) or (w > h div 2) then raise Exception.Create('Pulse size is out of range [2,255]'); for i := k - w to k + w do for j := k - w to k + w do buf[i, j] := 255; // prepare Image1 bitmap bmp := Image1.Picture.Bitmap; bmp.PixelFormat := pf8bit; // move input data from buf to Image1 bitmap for i := 0 to h - 1 do Move(buf[i, 0], (bmp.ScanLine[i])^, h); Image1.Refresh; end; procedure TForm1.LoadLenna(out buf: TByte2DArray); var pgm: TGLPGMImage; img: TGLImage; i, j, w, h: integer; begin DemoMode := dmLena; pgm := TGLPGMImage.Create; img := TGLImage.Create; try pgm.LoadFromFile('lena_bw.pgm'); img.Assign(pgm); img.DownSampleByFactor2; img.VerticalReverseOnAssignFromBitmap := True; img.AssignToBitmap(Image1.Picture.Bitmap); h := img.Height; w := img.Width; SetLength(buf, h, w); // buf[rows,cols] for I := 0 to h - 1 do for J := 0 to w - 1 do buf[I, J] := img.ScanLine[i][j].R; finally pgm.Destroy; img.Destroy; end; end; procedure TForm1.Save2DBmp(buf: TByte2DArray); var i, h: integer; bmp: TBitmap; begin bmp := Image2.Picture.Bitmap; h := bmp.Height; for i := 0 to h - 1 do Move(buf[i, 0], (bmp.ScanLine[i])^, h); Image2.Refresh; end; // ============================== COMMON =========================== function TForm1.GetDisplayMode: TProcessMode; begin if RBModule.Checked then Result := module else if RBPhase.Checked then Result := phase else if RBReal.Checked then Result := real else Result := Imag; end; procedure Make8BitPal(pal: PLogPalette); var i, j: integer; k: array [0 .. 3] of byte absolute j; begin pal^.palVersion := $300; pal^.palNumEntries := 256; for i := 0 to 255 do begin j := i; k[1] := i; k[2] := i; pal^.palPalEntry[i] := TPaletteEntry(j); end; end; procedure TForm1.FormCreate(Sender: TObject); var bmp: TBitmap; pPal: PLogPalette; begin SetGLSceneMediaDir(); if not InitCUTIL then begin MessageDlg('Can''t load cutil32.dll', mtError, [mbOk], 0); Application.Terminate; end; cutCreateTimer( FTimer ); DemoMode := dmNone; GetMem(pPal, 1028); // create a gray custom bitmap and assign it to both images bmp := TBitmap.Create; bmp.PixelFormat := pf8bit; Make8BitPal(pPal); bmp.Palette := CreatePalette(pPal^); bmp.Height := 256; bmp.Width := 256; Image1.Picture.Bitmap := bmp; Image2.Picture.Bitmap := bmp; bmp.Free; FreeMem(pPal); Image1.Picture.Bitmap.Canvas.Brush.Color := clBlack; Image1.Picture.Bitmap.Canvas.Pen.Color := clWhite; Image2.Picture.Bitmap.Canvas.Brush.Color := clBlack; Image2.Picture.Bitmap.Canvas.Pen.Color := clWhite; // Force CUFFT initialization FFTPlan1D.Execute(Signal1D, Signal1D); end; procedure TForm1.FormDestroy(Sender: TObject); begin cutDeleteTimer( FTimer ); end; // RadioButton and CheckBox OnClick handler // procedure TForm1.ExecDemo(Sender: TObject); begin case DemoMode of dm1D: But1DFFTClick(But1DFFT); dm2D: But2DFFTClick(But2DFFT); dmLena: But2DFFTClick(BLenna); end; end; end.
unit fGMV_TimeOutManager; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 4/29/09 9:30a $ * Developer: doma.user@domain.ext * Site: Hines OIFO * * Description: Time Out functionality (Just like Roll'n'Scroll) * * Notes: * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/fGMV_TimeOutManager.pas $ * * * ================================================================================ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type TfrmGMV_TimeOutManager = class(TForm) LastChanceTimer: TTimer; Label1: TLabel; lblSecondsLeft: TLabel; lblMessage: TLabel; btnCancelTimeout: TButton; procedure LastChanceTimerTimer(Sender: TObject); private SecondsLeft: Integer; public { Public declarations } end; type TMDShutDownProcedure = procedure; procedure InitTimeOut(ShutDownProcedureName: TMDShutDownProcedure); procedure UpdateTimeOutInterval(Seconds: Cardinal); procedure ShutDownTimeOut; implementation {$IFDEF DLL} uses frmPatientVitals; {$ENDIF} type TMDTimeOut = class(TTimer) private FHooked: Boolean; TimeOutInterval: Cardinal; TimeOutKeyHandle: HHOOK; TimeOutMouseHandle: HHOOK; ShutDownProcedure: TMDShutDownProcedure; protected procedure ResetTimeOut; procedure TimeOutTimer(Sender: TObject); end; var MDTimeOut: TMDTimeOut = nil; function TimeoutKeyHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; forward; function TimeoutMouseHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall; forward; {$R *.DFM} function TimeoutKeyHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; { this is called for every keyboard event that occurs } begin Result := 0; if lParam shr 31 = 1 then MDTimeOut.ResetTimeout; // on KeyUp only try Result := CallNextHookEx(MDTimeOut.TimeoutKeyHandle, Code, wParam, lParam); except end; end; function TimeoutMouseHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; { this is called for every mouse event that occurs } begin Result := 0; if (Code >= 0) and (wParam > WM_MOUSEFIRST) and (wParam <= WM_MOUSELAST) then MDTimeOut.ResetTimeout; // all click events try Result := CallNextHookEx(MDTimeOut.TimeoutMouseHandle, Code, wParam, lParam); except end; end; procedure InitTimeOut(ShutDownProcedureName: TMDShutDownProcedure); begin if (not assigned(MDTimeOut)) then begin MDTimeOut := TMDTimeOut.Create(Application); with MDTimeOut do begin ShutDownProcedure := ShutDownProcedureName; OnTimer := TimeOutTimer; TimeOutInterval := 10000; TimeOutKeyHandle := SetWindowsHookEx(WH_KEYBOARD, TimeOutKeyHook, 0, GetCurrentThreadID); TimeOutMouseHandle := SetWindowsHookEx(WH_MOUSE, TimeOutMouseHook, 0, GetCurrentThreadID); Interval := TimeOutInterval; Enabled := True; FHooked := True; end; end; end; procedure UpdateTimeOutInterval(Seconds: Cardinal); begin if (assigned(MDTimeOut)) then with MDTimeOut do begin Interval := Seconds * 1000; TimeOutInterval := Seconds * 1000; Enabled := True; end; end; procedure ShutDownTimeOut; begin if (assigned(MDTimeOut)) then begin with MDTimeOut do begin Enabled := False; if FHooked then begin UnhookWindowsHookEx(TimeOutKeyHandle); UnhookWindowsHookEx(TimeOutMouseHandle); FHooked := False; end; end; FreeAndNil(MDTimeOut); // AAN 040406 end; end; procedure TMDTimeOut.ResetTimeout; { this restarts the timer whenever there is a keyboard or mouse event } begin Enabled := False; Interval := TimeoutInterval; Enabled := True; end; procedure TMDTimeOut.TimeOutTimer(Sender: TObject); { when the timer expires, the application is closed after warning the user } begin Enabled := False; {$IFNDEF DLL} //zzzzzzandria 050425 { Check for minimized main form and then bring to front } with Application do begin if MainForm <> nil then if MainForm.WindowState = wsMinimized then MainForm.WindowState := wsNormal; BringToFront; ProcessMessages; end; with TfrmGMV_TimeOutManager.Create(Application) do try lblMessage.Caption := 'The application ' + Application.Title + ' is about to ' + 'close due to inactivity. Press the &Cancel button below to ' + 'continue working.'; SecondsLeft := 15; LastChanceTimer.Interval := 1000; LastChanceTimer.Enabled := True; ShowModal; LastChanceTimer.Enabled := False; if ModalResult <> mrCancel then if assigned(ShutDownProcedure) then ShutDownProcedure else Application.Terminate else Self.Enabled := True; finally Free; end; {$ELSE} // if Assigned(frmVitals) then // frmVitals.ModalResult := mrCancel; Application.Terminate; {$ENDIF} end; //////////////////////////////////////////////////////////////////////////////// procedure TfrmGMV_TimeOutManager.LastChanceTimerTimer(Sender: TObject); begin LastChanceTimer.Enabled := False; dec(SecondsLeft); lblSecondsLeft.Caption := IntToStr(SecondsLeft); LastChanceTimer.Enabled := (SecondsLeft > 0); if not LastChanceTimer.Enabled then ModalResult := mrOk; end; initialization initTimeOut(nil); UpdateTimeoutInterval(10000); finalization shutDownTimeOut; end.
unit UnDetalheComandaView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, JvExExtCtrls, JvExtComponent, JvPanel, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls, { Fluente } UnModelo, Componentes, UnAplicacao; type TComandaDetalheView = class(TForm, ITela) pnlDesktop: TPanel; Panel8: TPanel; Panel9: TPanel; lblPagamentos: TLabel; gDetalhe: TDBGrid; pnlCommand: TJvPanel; btnOk: TPanel; procedure btnOkClick(Sender: TObject); private FControlador: IResposta; FModelo: TModelo; public function Controlador(const Controlador: IResposta): ITela; function Descarregar: ITela; function ExibirTela: Integer; function Modelo(const Modelo: TModelo): ITela; function Preparar: ITela; end; var ComandaDetalheView: TComandaDetalheView; implementation {$R *.dfm} procedure TComandaDetalheView.btnOkClick(Sender: TObject); begin Self.ModalResult := mrOk; end; function TComandaDetalheView.Controlador(const Controlador: IResposta): ITela; begin Self.FControlador := Controlador; Result := Self; end; function TComandaDetalheView.Descarregar: ITela; begin Self.gDetalhe.DataSource := nil; Result := Self; end; function TComandaDetalheView.ExibirTela: Integer; begin Result := Self.ShowModal; end; function TComandaDetalheView.Modelo(const Modelo: TModelo): ITela; begin Self.FModelo := Modelo; Result := Self; end; function TComandaDetalheView.Preparar: ITela; begin Self.gDetalhe.DataSource := Self.FModelo.DataSource( Self.FModelo.Parametros.Ler('datasource').ComoTexto); Self.lblPagamentos.Caption := FormatFloat('R$ ###,##0.00', Self.FModelo.Parametros.Ler('total').ComoDecimal); Result := Self; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, uniGUITypes, uniGUIAbstractClasses, uniGUIClasses, uniGUIRegClasses, uniGUIForm, uniTreeView, uniTreeMenu, uniSweetAlert, uniStatusBar, uniScreenMask, uniGUIBaseClasses, uniImageList, Vcl.Menus, uniMainMenu, uniPanel, uniLabel, Vcl.Imaging.pngimage, uniImage, uniScrollBox, uniPageControl, frxClass, frxExportBaseDialog, frxExportPDF, frxGradient, frxDBSet, uniGUIFrame, uniButton, uniBitBtn, uniMenuButton, UniFSMenuButton, DB, UniFSButton, uniEdit, unimImage, Dashboard.Infobox, uniHTMLFrame, uniURLFrame, UniFSCalcEdit, Utils, uFrCadGrupo, uFrCadProdutos, uFrCaixa; type TMainForm = class(TUniForm) frxGradientObject1: TfrxGradientObject; frxPDFExport1: TfrxPDFExport; frxReport1: TfrxReport; UniNativeImageList1: TUniNativeImageList; UniStatusBar1: TUniStatusBar; UniSweetAlert1: TUniSweetAlert; frxDBDataset1: TfrxDBDataset; Popup1: TUniPopupMenu; Usuarios1: TUniMenuItem; Log2: TUniMenuItem; Sair1: TUniMenuItem; paBackGround: TUniContainerPanel; PagePrincipal: TUniPageControl; TabHome: TUniTabSheet; paGeral: TUniContainerPanel; UniPanel1: TUniPanel; UniImage1: TUniImage; Frame: TUniURLFrame; uFramHtml: TUniHTMLFrame; UniTreeMenu1: TUniTreeMenu; PnlTop: TUniPanel; pnLogo: TUniPanel; lbTitulo: TUniLabel; imgIcone: TUniImage; UniFSButton2: TUniFSButton; UniFSMenuButton2: TUniFSMenuButton; UniMenuItems1: TUniMenuItems; E1: TUniMenuItem; mnuGrupos: TUniMenuItem; mnuProdutos: TUniMenuItem; lbOla: TUniLabel; Vendas1: TUniMenuItem; procedure UniFormScreenResize(Sender: TObject; AWidth, AHeight: Integer); procedure Sair1Click(Sender: TObject); procedure Usuarios1Click(Sender: TObject); procedure RegistraLog(Tipo: String; Historico: String); procedure Log2Click(Sender: TObject); procedure DashBoardClick(Sender: TObject);// procedure gravar log procedure AtualizaDados; procedure UniFormShow(Sender: TObject); procedure UniFSButton1Click(Sender: TObject); procedure mnuGruposClick(Sender: TObject); procedure mnuProdutosClick(Sender: TObject); procedure Vendas1Click(Sender: TObject); //atualizar dados html private FInfobox : IInfobox; // Declaração... FValor1, FValor2, FValor3, FValor4 : string; //x----, x----, x---, x---- : string; // para direcionara ao total pelos cards procedure ToogleMenu; // redimenciona lateral public { Public declarations } vADMIN, vUSUARIO : Boolean; // Administrador xUsuario : string; // variavel para chamr o nome do usuario logado vCOD : Integer; end; function MainForm: TMainForm; implementation {$R *.dfm} uses uniGUIVars, MainModule, uniGUIApplication, uFrCadastroUsuario, uDados, uFrLogSys; function MainForm: TMainForm; begin Result := TMainForm(UniMainModule.GetFormInstance(TMainForm)); end; procedure TMainForm.ToogleMenu; // redimenciona lateral begin if UniTreeMenu1.Width > 50 then begin UniTreeMenu1.Micro := true; pnLogo.Width := 50; end else begin pnLogo.ClientEvents.UniEvents.Clear; UniTreeMenu1.Micro := false; pnLogo.ClientEvents.UniEvents.Add('resize=function resize(sender, width, height, oldWidth, oldHeight, eOpts)'+ '{sender.cls="animated zoomIn";}'); pnLogo.Width := 221; pnLogo.Repaint; end; end; procedure TMainForm.AtualizaDados; //atualizar dados html begin FInfobox := TInfobox.Init; // Instância | Instance //procedure para total nos cards // * // * // * // Dados do seu Banco/Consulta | Data from your Database/Query: FValor1 := '1' ; // recebe o valor 1 FValor2 := '2'; // recebe o valor 2 FValor3 := '3'; // recebe o valor 3 FValor4 := '4'; // recebe o valor 4 Frame.HTML.Text := FInfobox .Valor1(FValor1) .Valor2(FValor2) .Valor3(FValor3) .Valor4(FValor4) .HTMLView; end; procedure TMainForm.RegistraLog(Tipo: String; Historico: String); // procedure gravar log var xERRO: String; begin exit; // registra o log ( função Log ) para todos dmDados.QueryAuxiliar.Close; dmDados.QueryAuxiliar.SQL.Clear; dmDados.QueryAuxiliar.SQL.Add('INSERT into LOGSYS values (NULL, :vDIA, :vLOGIN, :vOPERACAO, :vOCORRENCIA )'); // DIA dmDados.QueryAuxiliar.Params[0].DataType := ftDateTime; dmDados.QueryAuxiliar.Params[0].Value := DateTimeToStr(now); // pega a Data do computador // Login dmDados.QueryAuxiliar.Params[1].DataType := ftString; dmDados.QueryAuxiliar.Params[1].Value := MainModule.UniMainModule.xUsuario; // pega o usuario na entrada do sistema ( usuario global ) // operação dmDados.QueryAuxiliar.Params[2].DataType := ftString; dmDados.QueryAuxiliar.Params[2].Value := Tipo; // pega esse valor para a função // Ocorrencia dmDados.QueryAuxiliar.Params[3].DataType := ftString; dmDados.QueryAuxiliar.Params[3].Value := Historico; // pega esse valor para a função dmDados.QueryAuxiliar.ExecSQL(xERRO); dmDados.QueryLogSys.Close; dmDados.QueryLogSys.Open; end; // frame lateral procedure TMainForm.DashBoardClick(Sender: TObject); begin PagePrincipal.ActivePage := TabHome; // ativa pagina Principal end; procedure TMainForm.Log2Click(Sender: TObject); begin if (not MainModule.UniMainModule.vADMIN) then exit; AddTab(PagePrincipal,TFrame(TfrLogSys),'log Sys'); end; procedure TMainForm.mnuGruposClick(Sender: TObject); begin AddTab(PagePrincipal,TFrame(TfrCadGrupo),'Grupos'); end; procedure TMainForm.mnuProdutosClick(Sender: TObject); begin AddTab(PagePrincipal,TFrame(TfrCadProduto),'Produtos'); end; procedure TMainForm.Sair1Click(Sender: TObject); begin Close; end; procedure TMainForm.UniFormScreenResize(Sender: TObject; AWidth, AHeight: Integer); begin // resposividade na tela Self.Left := Round((AWidth / 2) - (Self.Width / 2)); Self.Top := Round((AHeight / 2) - (Self.Height / 2)); end; procedure TMainForm.UniFormShow(Sender: TObject); begin AtualizaDados; //atualizar dados html end; procedure TMainForm.UniFSButton1Click(Sender: TObject); begin ToogleMenu; // UniTreeMenu1.Micro := not UniTreeMenu1.Micro; end; procedure TMainForm.Usuarios1Click(Sender: TObject); begin AddTab(PagePrincipal,TFrame(TfrCadastroUsuario),'Usuário'); end; procedure TMainForm.Vendas1Click(Sender: TObject); begin AddTab(PagePrincipal,TFrame(TfrCaixa),'Vendas'); end; // fim initialization RegisterAppFormClass(TMainForm); end.
unit HKConfig; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IniFiles, FileInfo; type { THKConfig } THKConfig=class private FBaseURL: String; fIni:TIniFile; fFileInfo:TStrings; procedure SetBaseURL(AValue: String); protected procedure LoadConfig;virtual; public constructor Create; destructor Destroy; override; property FileInfo:TStrings read fFileInfo; property BaseURL:String read FBaseURL write SetBaseURL; end; implementation { THKConfig } procedure THKConfig.SetBaseURL(AValue: String); begin if FBaseURL=AValue then Exit; FBaseURL:=AValue; fIni.WriteString('Server','BaseUrl', AValue); end; procedure THKConfig.LoadConfig; begin FBaseURL:=fIni.ReadString('Server', 'BaseUrl', 'http://localhost:11611/'); end; constructor THKConfig.Create; var fInfo:TFileVersionInfo; begin fIni:=TIniFile.Create(ExtractFileDir(ParamStr(1))+PathDelim+'setting.ieu'); fFileInfo:=TStringList.Create; fInfo:=TFileVersionInfo.Create(Nil); try fInfo.ReadFileInfo; fFileInfo.Assign(fInfo.VersionStrings); finally fInfo.Free; end; LoadConfig; end; destructor THKConfig.Destroy; begin fIni.Free; fFileInfo.Free; inherited Destroy; end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OpenGL; type TfrmGL = class(TForm) procedure FormCreate(Sender: TObject); procedure FormPaint(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormResize(Sender: TObject); private DC : HDC; hrc: HGLRC; end; var frmGL: TfrmGL; implementation {$R *.DFM} // Оси координат procedure Axes; var Color : Array [1..4] of GLFloat; begin glPushMatrix; glGetFloatv (GL_CURRENT_COLOR, @Color); glScalef (0.75, 0.75, 0.75); glColor3f (0, 1, 0); glBegin (GL_LINES); glVertex3f (0, 0, 0); glVertex3f (3, 0, 0); glVertex3f (0, 0, 0); glVertex3f (0, 3, 0); glVertex3f (0, 0, 0); glVertex3f (0, 0, 3); glEnd; // буква X glBegin (GL_LINES); glVertex3f (3.1, -0.2, 0.5); glVertex3f (3.1, 0.2, 0.1); glVertex3f (3.1, -0.2, 0.1); glVertex3f (3.1, 0.2, 0.5); glEnd; // буква Y glBegin (GL_LINES); glVertex3f (0.0, 3.1, 0.0); glVertex3f (0.0, 3.1, -0.1); glVertex3f (0.0, 3.1, 0.0); glVertex3f (0.1, 3.1, 0.1); glVertex3f (0.0, 3.1, 0.0); glVertex3f (-0.1, 3.1, 0.1); glEnd; // буква Z glBegin (GL_LINES); glVertex3f (0.1, -0.1, 3.1); glVertex3f (-0.1, -0.1, 3.1); glVertex3f (0.1, 0.1, 3.1); glVertex3f (-0.1, 0.1, 3.1); glVertex3f (-0.1, -0.1, 3.1); glVertex3f (0.1, 0.1, 3.1); glEnd; // Восстанавливаем значение текущего цвета glColor3f (Color [1], Color [2], Color [3]); glPopMatrix; end; {======================================================================= Перерисовка окна} procedure TfrmGL.FormPaint(Sender: TObject); begin // очистка буфера цвета и буфера глубины glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); Axes; // рисование шести сторон куба glBegin(GL_QUADS); glVertex3f(1.0, 1.0, 1.0); glVertex3f(-1.0, 1.0, 1.0); glVertex3f(-1.0, -1.0, 1.0); glVertex3f(1.0, -1.0, 1.0); glEnd; glBegin(GL_QUADS); glVertex3f(1.0, 1.0, -1.0); glVertex3f(1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, 1.0, -1.0); glEnd; glBegin(GL_QUADS); glVertex3f(-1.0, 1.0, 1.0); glVertex3f(-1.0, 1.0, -1.0); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(-1.0, -1.0, 1.0); glEnd; glBegin(GL_QUADS); glVertex3f(1.0, 1.0, 1.0); glVertex3f(1.0, -1.0, 1.0); glVertex3f(1.0, -1.0, -1.0); glVertex3f(1.0, 1.0, -1.0); glEnd; glBegin(GL_QUADS); glVertex3f(-1.0, 1.0, -1.0); glVertex3f(-1.0, 1.0, 1.0); glVertex3f(1.0, 1.0, 1.0); glVertex3f(1.0, 1.0, -1.0); glEnd; glBegin(GL_QUADS); glVertex3f(-1.0, -1.0, -1.0); glVertex3f(1.0, -1.0, -1.0); glVertex3f(1.0, -1.0, 1.0); glVertex3f(-1.0, -1.0, 1.0); glEnd; SwapBuffers(DC); end; {======================================================================= Формат пикселя} procedure SetDCPixelFormat (hdc : HDC); var pfd : TPixelFormatDescriptor; nPixelFormat : Integer; begin FillChar (pfd, SizeOf (pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat (hdc, @pfd); SetPixelFormat (hdc, nPixelFormat, @pfd); end; {======================================================================= Создание формы} procedure TfrmGL.FormCreate(Sender: TObject); begin DC := GetDC (Handle); SetDCPixelFormat(DC); hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона glColor3f (1.0, 0.0, 0.5); // текущий цвет примитивов glEnable (GL_DEPTH_TEST); end; {======================================================================= Конец работы приложения} procedure TfrmGL.FormDestroy(Sender: TObject); begin wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC (Handle, DC); DeleteDC (DC); end; procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; procedure TfrmGL.FormResize(Sender: TObject); begin glViewport(0, 0, ClientWidth, ClientHeight); glLoadIdentity; glFrustum (-1, 1, -1, 1, 3, 10.0); // задаем перспективу glTranslatef (0.0, 0.0, -8.0); // перенос объекта - ось Z glRotatef (30.0, 1.0, 0.0, 0.0); // поворот объекта - ось X glRotatef (60.0, 0.0, 1.0, 0.0); // поворот объекта - ось Y InvalidateRect(Handle, nil, False); end; end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLNewtonRegister<p> Design time registration code for the Newton Manager.<p> <b>History : </b><font size=-1><ul> <li>04/01/11 - FP - Removed Joint <li>15/07/10 - FP - Creation by Franck Papouin </ul></font> } unit GLNewtonRegister; interface uses Classes, GLNGDManager; procedure register; implementation // Register // procedure register; begin RegisterClasses([TGLNGDManager, TGLNGDDynamic, TGLNGDStatic]); RegisterComponents('GLScene', [TGLNGDManager]); end; end.
unit Test_FIToolkit.Logger.Default; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, FIToolkit.Logger.Default; type TestFIToolkitLoggerDefault = class (TGenericTestCase) private const STR_LOG_FILE = 'test_file.log'; published procedure TestInitConsoleLog; procedure TestInitFileLog; procedure TestLog; end; implementation uses System.SysUtils, TestUtils; procedure TestFIToolkitLoggerDefault.TestInitConsoleLog; begin InitConsoleLog(True); InitConsoleLog(False); CheckException( procedure begin Log.Error([]); end, nil, 'CheckException::<nil>' ); end; procedure TestFIToolkitLoggerDefault.TestInitFileLog; var sFileName : TFileName; begin sFileName := TestDataDir + STR_LOG_FILE; DeleteFile(sFileName); Assert(not FileExists(sFileName)); InitFileLog(sFileName); CheckException( procedure begin Log.Error([]); end, nil, 'CheckException::<nil>' ); CheckTrue(FileExists(sFileName), 'CheckTrue::FileExists(sFileName)'); end; procedure TestFIToolkitLoggerDefault.TestLog; begin CheckTrue(Log <> nil, 'Log <> nil'); CheckException( procedure begin Log.Error([]); end, nil, 'CheckException::<nil>' ); end; initialization // Register any test cases with the test runner RegisterTest(TestFIToolkitLoggerDefault.Suite); end.
unit uSayCommandHandler; interface uses uCommandHandler, uTokenizer, dmConnection; type TSayCommandHandler = class(TCommandHandler) function HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; override; end; implementation uses SysUtils; { TSayCommandHandler } function TSayCommandHandler.HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; var Target, Line: string; begin if not ATokenizer.HasMoreTokens then Exit; Target := ATokenizer.NextToken; Line := ATokenizer.NextToken; while ATokenizer.HasMoreTokens do Line := Line + ' ' + ATokenizer.NextToken; AConnection.Say(Target, Line); end; initialization TCommandHandlerFactory.GetInstance.RegisterClass('/say', TSayCommandHandler); TCommandHandlerFactory.GetInstance.RegisterClass('/msg', TSayCommandHandler); end.
unit MainFrm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Platform, FGX.ApplicationEvents, FMX.Layouts, FMX.Memo, FMX.StdCtrls, FMX.MultiView, FMX.Controls.Presentation, FMX.ScrollBox; type TFormMain = class(TForm) fgApplicationEvents: TfgApplicationEvents; mmLog: TMemo; MultiView: TMultiView; cbOnIdle: TCheckBox; GroupBox: TGroupBox; cbOnActionExecute: TCheckBox; cbOnActionUpdate: TCheckBox; cbOnException: TCheckBox; cbOnOrientationChanged: TCheckBox; cbOnStateChanged: TCheckBox; BtnClearLog: TButton; GroupBox1: TGroupBox; cbAllFormsCreated: TCheckBox; cbFormSizeChanged: TCheckBox; cbFormReleased: TCheckBox; Button1: TButton; cbMainFormChanged: TCheckBox; Button2: TButton; Button3: TButton; cbMainFormCaptionChanged: TCheckBox; cbStyleChanged: TCheckBox; Button4: TButton; StyleBookResource: TStyleBook; procedure fgApplicationEventsActionExecute(Action: TBasicAction; var Handled: Boolean); procedure fgApplicationEventsActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure fgApplicationEventsException(Sender: TObject; E: Exception); procedure fgApplicationEventsIdle(Sender: TObject; var Done: Boolean); procedure fgApplicationEventsOrientationChanged(const AOrientation: TScreenOrientation); function fgApplicationEventsStateChange(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; procedure BtnClearLogClick(Sender: TObject); procedure fgApplicationEventsFormsCreated(Sender: TObject); procedure fgApplicationEventsFormSizeChanged(Sender: TObject; const AForm: TCommonCustomForm); procedure fgApplicationEventsFormReleased(Sender: TObject; const AForm: TCommonCustomForm); procedure Button1Click(Sender: TObject); procedure fgApplicationEventsMainFormChanged(Sender: TObject; const ANewForm: TCommonCustomForm); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure fgApplicationEventsMainFormCaptionChanged(Sender: TObject; const ANewForm: TCommonCustomForm; const ANewCaption: string); procedure fgApplicationEventsStyleChanged(Sender: TObject; const AScene: IScene; const AStyleBook: TStyleBook); procedure Button4Click(Sender: TObject); procedure MultiViewPresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass); procedure FormShow(Sender: TObject); private procedure Log(const AFormat: string; Args: array of const); overload; procedure Log(const AFormat: string); overload; public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.fmx} uses ChildFrm, FMX.MultiView.Presentations; procedure TFormMain.BtnClearLogClick(Sender: TObject); begin mmLog.Lines.Clear; end; procedure TFormMain.Button1Click(Sender: TObject); begin if FormChild = nil then FormChild := TFormChild.Create(Self); FormChild.Show; end; procedure TFormMain.Button2Click(Sender: TObject); begin if FormChild = nil then FormChild := TFormChild.Create(Self); if FormChild = Application.MainForm then Application.MainForm := Self else Application.MainForm := FormChild; end; procedure TFormMain.Button3Click(Sender: TObject); begin if Application.MainForm <> nil then Application.MainForm.Caption := Random(100).ToString; end; procedure TFormMain.Button4Click(Sender: TObject); begin if StyleBook = nil then StyleBook := StyleBookResource else StyleBook := nil; end; procedure TFormMain.fgApplicationEventsActionExecute(Action: TBasicAction; var Handled: Boolean); begin if cbOnActionExecute.IsChecked then Log('OnActionExecute'); end; procedure TFormMain.fgApplicationEventsActionUpdate(Action: TBasicAction; var Handled: Boolean); begin if cbOnActionUpdate.IsChecked then Log('OnActionUpdate'); end; procedure TFormMain.fgApplicationEventsException(Sender: TObject; E: Exception); begin if cbOnException.IsChecked then Log('OnException'); end; procedure TFormMain.fgApplicationEventsFormReleased(Sender: TObject; const AForm: TCommonCustomForm); begin if cbFormReleased.IsChecked then Log('OnFormReleased: name="%s"', [AForm.Name]); end; procedure TFormMain.fgApplicationEventsFormsCreated(Sender: TObject); begin if cbAllFormsCreated.IsChecked then Log('OnFormsCreated'); end; procedure TFormMain.fgApplicationEventsFormSizeChanged(Sender: TObject; const AForm: TCommonCustomForm); begin if cbFormSizeChanged.IsChecked then Log('OnFormSizeChanged: name="%s" width=%d height=%d', [AForm.Name, AForm.Width, AForm.Height]); end; procedure TFormMain.fgApplicationEventsIdle(Sender: TObject; var Done: Boolean); begin if cbOnIdle.IsChecked then Log('OnIdle'); end; procedure TFormMain.fgApplicationEventsMainFormCaptionChanged(Sender: TObject; const ANewForm: TCommonCustomForm; const ANewCaption: string); begin if cbMainFormCaptionChanged.IsChecked then if ANewForm <> nil then Log('OnMainFormCaptionChanged: name="%s" caption="%s"', [ANewForm.Name, ANewForm.Caption]) else Log('OnMainFormCaptionChanged: Main form removed', []) end; procedure TFormMain.fgApplicationEventsMainFormChanged(Sender: TObject; const ANewForm: TCommonCustomForm); begin if cbMainFormChanged.IsChecked then if ANewForm <> nil then Log('OnMainFormChanged: NewForm="%s"', [ANewForm.Name]) else Log('OnMainFormChanged: Main form removed', []) end; procedure TFormMain.fgApplicationEventsOrientationChanged(const AOrientation: TScreenOrientation); var OrientationText: string; begin if cbOnOrientationChanged.IsChecked then begin case AOrientation of TScreenOrientation.Portrait: OrientationText := 'Portrait'; TScreenOrientation.Landscape: OrientationText := 'Landscape'; TScreenOrientation.InvertedPortrait: OrientationText := 'InvertedPortrait'; TScreenOrientation.InvertedLandscape: OrientationText := 'InvertedLandscape'; end; Log('OnOrientationChanged=%s', [OrientationText]); end; end; function TFormMain.fgApplicationEventsStateChange(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; var StateText: string; begin if cbOnStateChanged.IsChecked then begin case AAppEvent of TApplicationEvent.FinishedLaunching: StateText := 'FinishedLaunching'; TApplicationEvent.BecameActive: StateText := 'BecameActive'; TApplicationEvent.WillBecomeInactive: StateText := 'WillBecomeInactive'; TApplicationEvent.EnteredBackground: StateText := 'EnteredBackground'; TApplicationEvent.WillBecomeForeground: StateText := 'WillBecomeForeground'; TApplicationEvent.WillTerminate: StateText := 'WillTerminate'; TApplicationEvent.LowMemory: StateText := 'LowMemory'; TApplicationEvent.TimeChange: StateText := 'TimeChange'; TApplicationEvent.OpenURL: StateText := 'OpenURL'; end; Log('OnApplicationEventsStateChanged: state=%s', [StateText]); end; Result := True; end; procedure TFormMain.fgApplicationEventsStyleChanged(Sender: TObject; const AScene: IScene; const AStyleBook: TStyleBook); var FormName: string; StyleBookName: string; begin if cbStyleChanged.IsChecked then begin if (AScene <> nil) and (AScene.GetObject is TCommonCustomForm) then FormName := Format(' name="%s"', [TCommonCustomForm(AScene.GetObject).Name]); if AStyleBook <> nil then StyleBookName:= Format(' resourceName="%s"', [AStyleBook.Name]); Log('Style Book Changed:' + FormName + StyleBookName); end; end; procedure TFormMain.FormShow(Sender: TObject); begin MultiView.Mode := TMultiViewMode.PlatformBehaviour; end; procedure TFormMain.Log(const AFormat: string); begin mmLog.Lines.Add(Format('%s: ' + AFormat, [TimeToStr(Now)])); end; procedure TFormMain.Log(const AFormat: string; Args: array of const); begin mmLog.Lines.Add(TimeToStr(Now) + Format(': ' + AFormat, Args)); end; procedure TFormMain.MultiViewPresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass); begin if PresenterClass = TMultiViewNavigationPanePresentation then PresenterClass := TMultiViewDockedPanelPresentation; end; end.
{********************************************} { TeeChart Pro Charting Library } { For Borland Delphi, C++ Builder & Kylix } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeEngine; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, {$ENDIF} SysUtils, Classes, Messages, {$IFDEF CLX} QGraphics, QControls, QDialogs, Types, {$ELSE} Graphics, Controls, {$ENDIF} {$IFDEF TEETRIAL} TeeAbout, {$ENDIF} {$IFDEF CLR} System.ComponentModel, {$ENDIF} TeeProcs, TeCanvas; Const ChartMarkColor = clInfoBk (* $80FFFF *); { default Series Mark back color } MinAxisIncrement :Double = 0.000000000001; { <-- "double" for BCB } MinAxisRange :Double = 0.0000000001; { <-- "double" for BCB } TeeAllValues = -1; {$IFDEF D6} clTeeColor =TColor(clDefault); {$ELSE} clTeeColor =TColor($20000000); {$ENDIF} ChartSamplesMax = 1000; TeeAutoZOrder = -1; TeeAutoDepth = -1; TeeNoPointClicked = -1; TeeDef3DPercent = 15; TeeColumnSeparator: {$IFDEF CLR}Char{$ELSE}AnsiChar{$ENDIF} = #6; // To separate columns in Legend TeeLineSeparator : {$IFDEF CLR}Char{$ELSE}AnsiChar{$ENDIF} = #13; // To separate lines of text // Index of first custom axis (0 to 5 are pre-created axes: Left,Top, // Right,Bottom,Depth and DepthTop. TeeInitialCustomAxis = 6; var TeeCheckMarkArrowColor : Boolean=False; // when True, the Marks arrow pen // color is changed if the point has // the same color. TeeRandomAtRunTime : Boolean=False; // adds random values at run-time too clTeeGallery1:Integer = 0; // index of ColorPalette[] global variable clTeeGallery2:Integer = 3; // index of ColorPalette[] global variable type TCustomAxisPanel=class; {$IFDEF CLR} [ToolBoxItem(False)] {$ENDIF} TCustomChartElement=class(TComponent) private FActive : Boolean; FBrush : TChartBrush; FParent : TCustomAxisPanel; FPen : TChartPen; protected InternalUse : Boolean; // 7.0 Procedure CanvasChanged(Sender:TObject); virtual; Function CreateChartPen:TChartPen; class Function GetEditorClass:String; virtual; Procedure SetActive(Value:Boolean); virtual; Procedure SetBooleanProperty(Var Variable:Boolean; Value:Boolean); procedure SetBrush(const Value: TChartBrush); Procedure SetColorProperty(Var Variable:TColor; Value:TColor); Procedure SetDoubleProperty(Var Variable:Double; Const Value:Double); Procedure SetIntegerProperty(Var Variable:Integer; Value:Integer); Procedure SetParentChart(Const Value:TCustomAxisPanel); virtual; {$IFNDEF CLR} procedure SetParentComponent(AParent: TComponent); override; {$ENDIF} procedure SetPen(const Value: TChartPen); virtual; Procedure SetStringProperty(Var Variable:String; Const Value:String); public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; procedure Assign(Source:TPersistent); override; Function GetParentComponent: TComponent; override; Function HasParent:Boolean; override; {$IFDEF CLR} procedure SetParentComponent(AParent: TComponent); override; {$ENDIF} Procedure Repaint; property Active:Boolean read FActive write SetActive default True; property Brush:TChartBrush read FBrush write SetBrush; property ParentChart:TCustomAxisPanel read FParent write SetParentChart stored False; property Pen:TChartPen read FPen write SetPen; // Alias for Active property. property Visible:Boolean read FActive write SetActive default True; end; TCustomChartSeries=class; TChartSeries=class; {$IFDEF TEEVALUESINGLE} TChartValue=Single; {$ELSE} {$IFDEF TEEVALUEDOUBLE} TChartValue=Double; {$ELSE} {$IFDEF TEEVALUEEXTENDED} TChartValue=Extended; {$ELSE} TChartValue=Double; { <-- default } {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF TEEARRAY} TChartValues=Array of TChartValue; {$ELSE} PChartValue=^TChartValue; {$ENDIF} TChartListOrder=(loNone,loAscending,loDescending); // CLR: cannot be sealed due to cast tricks TChartValueList=class(TPersistent) private FDateTime : Boolean; {$IFNDEF TEEARRAY} FList : TList; {$ENDIF} FMaxValue : TChartValue; FMinValue : TChartValue; {$IFDEF TEEMULTIPLIER} FMultiplier : Double; { obsolete } {$ENDIF} FName : String; FOrder : TChartListOrder; FOwner : TChartSeries; FTempValue : TChartValue; FTotal : Double; FTotalABS : Double; FValueSource : String; { internal } IDefDateTime : Boolean; {$IFOPT C+} FCount : Integer; function GetCount:Integer; procedure SetCount(const Value:Integer); {$ENDIF} Function CompareValueIndex(a,b:Integer):Integer; Function GetMaxValue:TChartValue; Function GetMinValue:TChartValue; Function GetTotal:Double; Function GetTotalABS:Double; function IsDateStored: Boolean; procedure SetDateTime(Const Value:Boolean); {$IFDEF TEEMULTIPLIER} Function IsMultiStored:Boolean; Procedure SetMultiplier(Const Value:Double); { obsolete } {$ELSE} procedure ReadMultiplier(Reader: TReader); {$ENDIF} Procedure SetValueSource(Const Value:String); protected IData : TObject; Function AddChartValue:Integer; overload; Function AddChartValue(Const AValue:TChartValue):Integer; overload; virtual; Procedure ClearValues; virtual; {$IFNDEF TEEMULTIPLIER} procedure DefineProperties(Filer: TFiler); override; {$ENDIF} Function GetValue(ValueIndex:Integer):TChartValue; Procedure InitDateTime(Value:Boolean); Procedure InsertChartValue(ValueIndex:Integer; Const AValue:TChartValue); virtual; Procedure RecalcStats; overload; procedure RecalcStats(StartIndex:Integer); overload; Procedure SetValue(ValueIndex:Integer; Const AValue:TChartValue); public {$IFDEF TEEARRAY} Value : TChartValues; {$IFOPT C-} // When not using runtime assertions Count : Integer; {$ENDIF} {$ENDIF} Modified : Boolean; Constructor Create(AOwner:TChartSeries; Const AName:String); virtual; Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; {$IFNDEF TEEARRAY} Function Count:Integer; virtual; {$ELSE} {$IFOPT C+} property Count:Integer read GetCount write SetCount; {$ENDIF} {$ENDIF} Procedure Delete(ValueIndex:Integer); overload; virtual; Procedure Delete(Start,Quantity:Integer); overload; {$IFDEF TEEARRAY} Procedure Exchange(Index1,Index2:Integer); {$ENDIF} Procedure FillSequence; Function First:TChartValue; Function Last:TChartValue; Function Locate(Const AValue:TChartValue):Integer; overload; Function Locate(Const AValue:TChartValue; FirstIndex,LastIndex:Integer):Integer; overload; // 7.0 Function Range:TChartValue; Procedure Scroll; dynamic; Procedure Sort; property MaxValue:TChartValue read GetMaxValue; property MinValue:TChartValue read GetMinValue; property Owner:TChartSeries read FOwner; property TempValue:TChartValue read FTempValue write FTempValue; Function ToString(Index:Integer):String; {$IFDEF CLR}reintroduce;{$ENDIF} property Total:Double read GetTotal; property TotalABS:Double read GetTotalABS write FTotalABS; {$IFDEF TEEARRAY} property Items[Index:Integer]:TChartValue read GetValue write SetValue; default; {$ELSE} property Value[Index:Integer]:TChartValue read GetValue write SetValue; default; {$ENDIF} published property DateTime:Boolean read FDateTime write SetDateTime stored IsDateStored; property Name:String read FName write FName; {$IFDEF TEEMULTIPLIER} property Multiplier:Double read FMultiplier write SetMultiplier stored IsMultiStored; { obsolete } {$ENDIF} property Order:TChartListOrder read FOrder write FOrder; property ValueSource:String read FValueSource write SetValueSource; end; TChartAxisTitle=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCustomShape) private FAngle : Integer; FCaption : String; IDefaultAngle : Integer; Function IsAngleStored:Boolean; Procedure SetAngle(const Value:Integer); Procedure SetCaption(Const Value:String); public Procedure Assign(Source:TPersistent); override; published property Angle:Integer read FAngle write SetAngle stored IsAngleStored; property Caption:String read FCaption write SetCaption; property Font; property Visible default True; end; AxisException=class {$IFDEF CLR}sealed{$ENDIF} (Exception); TAxisLabelStyle=(talAuto,talNone,talValue,talMark,talText); TAxisLabelAlign=(alDefault,alOpposite); TAxisCalcPos=function(const Value:TChartValue):Integer of object; TCustomSeriesList=class; TAxisGridPen=class {$IFDEF CLR}sealed{$ENDIF} (TDottedGrayPen) private FZ : Double; IDefaultZ : Double; FCentered: Boolean; function IsZStored:Boolean; procedure SetZ(const Value:Double); procedure SetCentered(const Value: Boolean); public // (pending to move Centered to "published" after removing Axis.GridCentered) property Centered:Boolean read FCentered write SetCentered default False; published property ZPosition:Double read FZ write SetZ stored IsZStored; end; TAxisTicks=Array of Integer; // TAxisTickValues=TChartValues; TChartAxis=class; TAxisItems=class; TAxisItem=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCustomShape) private FValue : Double; FText : String; IAxisItems : TAxisItems; procedure SetText(const Value: String); procedure SetValue(const Value: Double); public procedure Repaint; published property Bevel; property BevelWidth; property Color; property Font; property Gradient; property Shadow; property ShapeStyle; property Text:String read FText write SetText; property Transparency; property Transparent default True; property Value:Double read FValue write SetValue; end; TAxisItems=class {$IFDEF CLR}sealed{$ENDIF} (TList) private FFormat: TTeeShape; IAxis : TChartAxis; function Get(Index:Integer):TAxisItem; public Constructor Create(Axis:TChartAxis); Destructor Destroy; override; Function Add(const Value: Double):TAxisItem; overload; Function Add(const Value: Double; const Text:String):TAxisItem; overload; Procedure CopyFrom(Source:TAxisItems); Procedure Clear; override; property Format:TTeeShape read FFormat; property Item[Index:Integer]:TAxisItem read Get; default; end; TChartAxisPen=class {$IFDEF CLR}sealed{$ENDIF} (TChartPen) private public Constructor Create(OnChangeEvent:TNotifyEvent); published property Width default 2; end; TAxisDrawLabelEvent=procedure(Sender:TChartAxis; var X,Y,Z:Integer; var Text:String; var DrawLabel:Boolean) of object; // internal event, used at TGridBandTool class (only) TAxisDrawGrids=procedure(Sender:TChartAxis) of object; TChartAxis=class(TCollectionItem) private { scales } FAutomatic : Boolean; FAutomaticMaximum : Boolean; FAutomaticMinimum : Boolean; FDesiredIncrement : Double; FMaximumValue : Double; FMinimumValue : Double; FLogarithmic : Boolean; FLogarithmicBase : Double; // 6.0 FMaximumOffset : Integer; FMinimumOffset : Integer; { axis } FAxis : TChartAxisPen; FPosAxis : Integer; FZPosition : Double; { title } FAxisTitle : TChartAxisTitle; FTitleSize : Integer; FPosTitle : Integer; { grid } FGrid : TAxisGridPen; { labels } FLabelsAlign : TAxisLabelAlign; FLabelsAlternate : Boolean; FLabelsAngle : Integer; FItems : TAxisItems; FLabelsOnAxis : Boolean; FLabelsSeparation : Integer; FLabelsSize : Integer; FLabelStyle : TAxisLabelStyle; FLabelsExponent : Boolean; FLabelsMultiLine : Boolean; FPosLabels : Integer; FAxisValuesFormat : String; FDateTimeFormat : String; FExactDateTime : Boolean; FRoundFirstLabel : Boolean; { ticks } FMinorGrid : TChartHiddenPen; FMinorTickCount : Integer; FMinorTickLength : Integer; FMinorTicks : TDarkGrayPen; FTicks : TDarkGrayPen; FTicksInner : TDarkGrayPen; FTickInnerLength : Integer; FTickLength : Integer; FTickOnLabelsOnly : Boolean; { other } FInverted : Boolean; FHorizontal : Boolean; FOtherSide : Boolean; FParentChart : TCustomAxisPanel; FVisible : Boolean; FStartPosition : Double; FEndPosition : Double; FPositionPercent : Double; FPosUnits : TTeeUnits; // Events FOnDrawLabel : TAxisDrawLabelEvent; FMaster : TChartAxis; { internal } IAxisDateTime : Boolean; IAxisLogSizeRange : TChartValue; IAxisSizeRange : TChartValue; ICenterPos : Integer; IDepthAxis : Boolean; ILogMax : Double; ILogMin : Double; IMaximum : Double; IMinimum : Double; IRange : TChartValue; IRangeLog : Double; IRangeZero : Boolean; ISeriesList : TCustomSeriesList; IsVisible : Boolean; IZPos : Integer; Function DepthAxisAlign:Integer; Function DepthAxisPos:Integer; Function RoundLogPower(const Value:Double):Double; Procedure SetAutomatic(Value:Boolean); Procedure SetAutomaticMinimum(Value:Boolean); Procedure SetAutomaticMaximum(Value:Boolean); Procedure SetAutoMinMax(Var Variable:Boolean; Var2,Value:Boolean); Procedure SetAxis(Value:TChartAxisPen); procedure SetAxisTitle(Value:TChartAxisTitle); Procedure SetDateTimeFormat(Const Value:String); Procedure SetDesiredIncrement(Const Value:Double); Procedure SetExactDateTime(Value:Boolean); Procedure SetGrid(Value:TAxisGridPen); procedure SetGridCentered(Value:Boolean); Procedure SetLabels(Value:Boolean); Procedure SetLabelsAlign(Value:TAxisLabelAlign); Procedure SetLabelsAlternate(Value:Boolean); Procedure SetLabelsAngle(const Value:Integer); Procedure SetLabelsFont(Value:TTeeFont); Procedure SetLabelsMultiLine(Value:Boolean); Procedure SetLabelsOnAxis(Value:Boolean); Procedure SetLabelsSeparation(Value:Integer); Procedure SetLabelsSize(Value:Integer); Procedure SetLabelStyle(Value:TAxisLabelStyle); Procedure SetLogarithmic(Value:Boolean); Procedure SetLogarithmicBase(const Value:Double); Procedure SetMaximum(Const Value:Double); Procedure SetMinimum(Const Value:Double); Procedure SetMinorGrid(Value:TChartHiddenPen); Procedure SetMinorTickCount(Value:Integer); Procedure SetMinorTickLength(Value:Integer); Procedure SetMinorTicks(Value:TDarkGrayPen); procedure SetStartPosition(Const Value:Double); procedure SetEndPosition(Const Value:Double); procedure SetPositionPercent(Const Value:Double); procedure SetPosUnits(const Value: TTeeUnits); procedure SetRoundFirstLabel(Value:Boolean); Procedure SetTickLength(Value:Integer); Procedure SetTickInnerLength(Value:Integer); Procedure SetTicks(Value:TDarkGrayPen); Procedure SetTicksInner(Value:TDarkGrayPen); procedure SetTickOnLabelsOnly(Value:Boolean); Procedure SetTitleSize(Value:Integer); Procedure SetValuesFormat(Const Value:String); Procedure SetVisible(Value:Boolean); Function ApplyPosition(APos:Integer; Const R:TRect):Integer; Function CalcDateTimeIncrement(MaxNumLabels:Integer):Double; Function CalcLabelsIncrement(MaxNumLabels:Integer):Double; Procedure CalcRect(Var R:TRect; InflateChartRectangle:Boolean); Function CalcZPos:Integer; Procedure DrawGridLine(tmp:Integer); Procedure DrawTitle(x,y:Integer); Function GetGridCentered:Boolean; Function GetLabels:Boolean; Function GetLabelsFont:TTeeFont; Function GetRectangleEdge(Const R:TRect):Integer; Procedure IncDecDateTime( Increment:Boolean; Var Value:Double; Const AnIncrement:Double; tmpWhichDateTime:TDateTimeStep ); Function LogXPosValue(Const Value:TChartValue):Integer; Function LogYPosValue(Const Value:TChartValue):Integer; Function InternalCalcDepthPosValue(Const Value:TChartValue):Integer; Procedure InternalCalcRange; Procedure InternalCalcPositions; Function InternalCalcSize( tmpFont:TTeeFont; tmpAngle:Integer; Const tmpText:String; tmpSize:Integer):Integer; Function InternalLabelSize(Const Value:Double; IsWidth:Boolean):Integer; function IsAxisValuesFormatStored:Boolean; function IsLogBaseStored: Boolean; Function IsMaxStored:Boolean; Function IsMinStored:Boolean; Function IsPosStored:Boolean; Function IsStartStored:Boolean; Function IsEndStored:Boolean; Function IsCustom:Boolean; function IsZStored: Boolean; Procedure RecalcSizeCenter; procedure SetHorizontal(const Value: Boolean); procedure SetOtherSide(const Value: Boolean); procedure SetLabelsExponent(Value: Boolean); Procedure SetCalcPosValue; procedure SetMaximumOffset(const Value: Integer); procedure SetMinimumOffset(const Value: Integer); procedure SetZPosition(const Value: Double); Function XPosValue(Const Value:TChartValue):Integer; Function YPosValue(Const Value:TChartValue):Integer; Function XPosValueCheck(Const Value:TChartValue):Integer; Function YPosValueCheck(Const Value:TChartValue):Integer; protected IHideBackGrid : Boolean; IHideSideGrid : Boolean; OnDrawGrids : TAxisDrawGrids; Function AxisRect:TRect; Procedure DrawGrids(NumTicks:Integer); Function InternalCalcLabelStyle:TAxisLabelStyle; virtual; Procedure InternalSetInverted(Value:Boolean); Procedure InternalSetMaximum(Const Value:Double); Procedure InternalSetMinimum(Const Value:Double); Procedure SetInverted(Value:Boolean); virtual; Function SizeLabels:Integer; Function SizeTickAxis:Integer; public IStartPos : Integer; IEndPos : Integer; IAxisSize : Integer; CalcXPosValue : TAxisCalcPos; CalcYPosValue : TAxisCalcPos; CalcPosValue : TAxisCalcPos; Tick : TAxisTicks; // 7.0 moved from protected {$IFDEF D5} Constructor Create(Chart:TCustomAxisPanel); reintroduce; overload; {$ENDIF} Constructor Create(Collection:TCollection); {$IFDEF D5}overload;{$ENDIF} override; Destructor Destroy; override; Procedure AdjustMaxMin; Procedure AdjustMaxMinRect(Const Rect:TRect); procedure Assign(Source: TPersistent); override; Function CalcIncrement:Double; Function CalcLabelStyle:TAxisLabelStyle; Procedure CalcMinMax(Var AMin,AMax:Double); Function CalcPosPoint(Value:Integer):Double; Function CalcSizeValue(Const Value:Double):Integer; Function CalcXYIncrement(MaxLabelSize:Integer):Double; Procedure CustomDraw( APosLabels,APosTitle,APosAxis:Integer; GridVisible:Boolean); Procedure CustomDrawMinMax( APosLabels, APosTitle, APosAxis:Integer; GridVisible:Boolean; Const AMinimum,AMaximum,AIncrement:Double); Procedure CustomDrawMinMaxStartEnd( APosLabels, APosTitle, APosAxis:Integer; GridVisible:Boolean; Const AMinimum,AMaximum,AIncrement:Double; AStartPos,AEndPos:Integer); Procedure CustomDrawStartEnd( APosLabels,APosTitle,APosAxis:Integer; GridVisible:Boolean; AStartPos,AEndPos:Integer); Function Clicked(x,y:Integer):Boolean; Procedure Draw(CalcPosAxis:Boolean); procedure DrawAxisLabel(x,y,Angle:Integer; Const St:String; Format:TTeeCustomShape=nil); Function IsDateTime:Boolean; Function LabelWidth(Const Value:Double):Integer; Function LabelHeight(Const Value:Double):Integer; Function LabelValue(Const Value:Double):String; virtual; // 7.0 Function MaxLabelsWidth:Integer; Procedure Scroll(Const Offset:Double; CheckLimits:Boolean=False); Procedure SetMinMax(AMin,AMax:Double); { public } property IsDepthAxis : Boolean read IDepthAxis; property Items : TAxisItems read FItems; property MasterAxis : TChartAxis read FMaster write FMaster; // 7.0 property PosAxis : Integer read FPosAxis; property PosLabels : Integer read FPosLabels; property PosTitle : Integer read FPosTitle; property ParentChart : TCustomAxisPanel read FParentChart; published property Automatic:Boolean read FAutomatic write SetAutomatic default True; property AutomaticMaximum:Boolean read FAutomaticMaximum write SetAutomaticMaximum default True; property AutomaticMinimum:Boolean read FAutomaticMinimum write SetAutomaticMinimum default True; property Axis:TChartAxisPen read FAxis write SetAxis; property AxisValuesFormat:String read FAxisValuesFormat write SetValuesFormat stored IsAxisValuesFormatStored; property DateTimeFormat:String read FDateTimeFormat write SetDateTimeFormat; property ExactDateTime:Boolean read FExactDateTime write SetExactDateTime default True; property Grid:TAxisGridPen read FGrid write SetGrid; property GridCentered:Boolean read GetGridCentered write SetGridCentered default False; property Increment:Double read FDesiredIncrement write SetDesiredIncrement; property Inverted:Boolean read FInverted write SetInverted default False; property Horizontal : Boolean read FHorizontal write SetHorizontal stored IsCustom; property OtherSide : Boolean read FOtherSide write SetOtherSide stored IsCustom; property Labels:Boolean read GetLabels write SetLabels default True; property LabelsAlign:TAxisLabelAlign read FLabelsAlign write SetLabelsAlign default alDefault; property LabelsAlternate:Boolean read FLabelsAlternate write SetLabelsAlternate default False; property LabelsAngle:Integer read FLabelsAngle write SetLabelsAngle default 0; property LabelsExponent:Boolean read FLabelsExponent write SetLabelsExponent default False; property LabelsFont:TTeeFont read GetLabelsFont write SetLabelsFont {stored IsFontStored}; property LabelsMultiLine:Boolean read FLabelsMultiLine write SetLabelsMultiLine default False; property LabelsOnAxis:Boolean read FLabelsOnAxis write SetLabelsOnAxis default True; property LabelsSeparation:Integer read FLabelsSeparation write SetLabelsSeparation default 10; property LabelsSize:Integer read FLabelsSize write SetLabelsSize default 0; property LabelStyle:TAxisLabelStyle read FLabelStyle write SetLabelStyle default talAuto; property Logarithmic:Boolean read FLogarithmic write SetLogarithmic default False; property LogarithmicBase:Double read FLogarithmicBase write SetLogarithmicBase stored IsLogBaseStored; property Maximum:Double read FMaximumValue write SetMaximum stored IsMaxStored; property MaximumOffset:Integer read FMaximumOffset write SetMaximumOffset default 0; property Minimum:Double read FMinimumValue write SetMinimum stored IsMinStored; property MinimumOffset:Integer read FMinimumOffset write SetMinimumOffset default 0; property MinorGrid:TChartHiddenPen read FMinorGrid write SetMinorGrid; property MinorTickCount:Integer read FMinorTickCount write SetMinorTickCount default 3; property MinorTickLength:Integer read FMinorTickLength write SetMinorTickLength default 2; property MinorTicks:TDarkGrayPen read FMinorTicks write SetMinorTicks; property StartPosition:Double read FStartPosition write SetStartPosition stored IsStartStored; property EndPosition:Double read FEndPosition write SetEndPosition stored IsEndStored; property PositionPercent:Double read FPositionPercent write SetPositionPercent stored IsPosStored; property PositionUnits:TTeeUnits read FPosUnits write SetPosUnits default muPercent; property RoundFirstLabel:Boolean read FRoundFirstLabel write SetRoundFirstLabel default True; property TickInnerLength:Integer read FTickInnerLength write SetTickInnerLength default 0; property TickLength:Integer read FTickLength write SetTickLength default 4; property Ticks:TDarkGrayPen read FTicks write SetTicks; property TicksInner:TDarkGrayPen read FTicksInner write SetTicksInner; property TickOnLabelsOnly:Boolean read FTickOnLabelsOnly write SetTickOnLabelsOnly default True; property Title:TChartAxisTitle read FAxisTitle write SetAxisTitle; property TitleSize:Integer read FTitleSize write SetTitleSize default 0; property Visible:Boolean read FVisible write SetVisible default True; property ZPosition:Double read FZPosition write SetZPosition stored IsZStored; // Events property OnDrawLabel:TAxisDrawLabelEvent read FOnDrawLabel write FOnDrawLabel; // 7.0 end; TChartDepthAxis=class(TChartAxis) protected Function InternalCalcLabelStyle:TAxisLabelStyle; override; Procedure SetInverted(Value:Boolean); override; published property Visible default False; end; TAxisOnGetLabel=Procedure( Sender:TChartAxis; Series:TChartSeries; ValueIndex:Integer; Var LabelText:String) of object; TAxisOnGetNextLabel=Procedure( Sender:TChartAxis; LabelIndex:Integer; Var LabelValue:Double; Var Stop:Boolean) of object; TSeriesClick=procedure( Sender:TChartSeries; ValueIndex:Integer; Button:TMouseButton; Shift: TShiftState; X, Y: Integer) of object; TValueEvent=(veClear,veAdd,veDelete,veRefresh,veModify); THorizAxis = (aTopAxis,aBottomAxis,aBothHorizAxis,aCustomHorizAxis); TVertAxis = (aLeftAxis,aRightAxis,aBothVertAxis,aCustomVertAxis); TChartClickedPartStyle=( cpNone, cpLegend, cpAxis, cpSeries, cpTitle, cpFoot, cpChartRect, cpSeriesMarks, cpSubTitle, cpSubFoot ); TChartClickedPart=Packed Record Part : TChartClickedPartStyle; PointIndex : Integer; ASeries : TChartSeries; AAxis : TChartAxis; end; TCustomSeriesList=class(TList) private FOwner : TCustomAxisPanel; procedure Put(Index:Integer; Value:TChartSeries); function Get(Index:Integer):TChartSeries; public procedure ClearValues; procedure FillSampleValues(Num:Integer=0); property Items[Index:Integer]:TChartSeries read Get write Put; default; property Owner:TCustomAxisPanel read FOwner; end; TSeriesGroup=class; TSeriesGroups=class; TChartSeriesList=class {$IFDEF CLR}sealed{$ENDIF} (TCustomSeriesList) private FGroups : TSeriesGroups; function GetAllActive: Boolean; procedure SetAllActive(const Value: Boolean); public Destructor Destroy; override; Function AddGroup(const Name:String):TSeriesGroup; property AllActive:Boolean read GetAllActive write SetAllActive; property Groups:TSeriesGroups read FGroups; end; TSeriesGroupActive=(gaYes, gaNo, gaSome); TSeriesGroup=class {$IFDEF CLR}sealed{$ENDIF} (TCollectionItem) private FName : String; FSeries : TCustomSeriesList; procedure SetActive(const Value:TSeriesGroupActive); function IsSeriesStored: Boolean; procedure SetSeries(const Value: TCustomSeriesList); function GetActive: TSeriesGroupActive; public Constructor Create(Collection:TCollection); {$IFDEF D5}overload;{$ENDIF} override; Destructor Destroy; override; procedure Add(Series:TChartSeries); procedure Hide; procedure Show; published property Active:TSeriesGroupActive read GetActive write SetActive default gaYes; property Name:String read FName write FName; property Series:TCustomSeriesList read FSeries write SetSeries stored IsSeriesStored; end; TSeriesGroups=class {$IFDEF CLR}sealed{$ENDIF} (TOwnedCollection) private Function Get(Index:Integer):TSeriesGroup; Procedure Put(Index:Integer; Const Value:TSeriesGroup); public Function Contains(Series:TChartSeries):Integer; property Items[Index:Integer]:TSeriesGroup read Get write Put; default; end; TChartAxes=class {$IFDEF CLR}sealed{$ENDIF} (TList) private FChart : TCustomAxisPanel; IFastCalc : Boolean; // default False function Get(Index:Integer):TChartAxis; function GetBottomAxis:TChartAxis; function GetDepthAxis:TChartDepthAxis; function GetDepthTopAxis:TChartDepthAxis; function GetLeftAxis:TChartAxis; function GetRightAxis:TChartAxis; function GetTopAxis:TChartAxis; procedure SetFastCalc(const Value: Boolean); function GetBehind: Boolean; function GetVisible: Boolean; procedure SetBehind(const Value: Boolean); procedure SetVisible(const Value: Boolean); public procedure Clear; override; procedure Reset; property Items[Index:Integer]:TChartAxis read Get; default; property Bottom:TChartAxis read GetBottomAxis; property Depth:TChartDepthAxis read GetDepthAxis; property DepthTop:TChartDepthAxis read GetDepthTopAxis; property Left:TChartAxis read GetLeftAxis; property Right:TChartAxis read GetRightAxis; property Top:TChartAxis read GetTopAxis; property Behind:Boolean read GetBehind write SetBehind; property FastCalc:Boolean read IFastCalc write SetFastCalc; property Visible:Boolean read GetVisible write SetVisible; end; TChartCustomAxes=class {$IFDEF CLR}sealed{$ENDIF} (TOwnedCollection) private Function Get(Index:Integer):TChartAxis; Procedure Put(Index:Integer; Const Value:TChartAxis); public procedure ResetScales(Axis:TChartAxis); property Items[Index:Integer]:TChartAxis read Get write Put; default; end; TTeeCustomDesigner=class(TObject) public Procedure Refresh; dynamic; Procedure Repaint; dynamic; end; TChartSeriesEvent=( seAdd, seRemove, seChangeTitle, seChangeColor, seSwap, seChangeActive, seDataChanged); TChartChangePage=class {$IFDEF CLR}sealed{$ENDIF} (TTeeEvent); TChartToolEvent=( cteAfterDraw, cteBeforeDrawSeries, cteBeforeDraw, cteBeforeDrawAxes, // 7.0 cteAfterDrawSeries, // 7.0 cteMouseLeave); // 7.0 TChartMouseEvent=(cmeDown,cmeMove,cmeUp); TTeeCustomTool=class(TCustomChartElement) protected Procedure ChartEvent(AEvent:TChartToolEvent); virtual; Procedure ChartMouseEvent( AEvent: TChartMouseEvent; Button:TMouseButton; Shift: TShiftState; X, Y: Integer); virtual; procedure SetParentChart(const Value: TCustomAxisPanel); override; public class Function Description:String; virtual; end; TTeeCustomToolClass=class of TTeeCustomTool; TChartTools=class {$IFDEF CLR}sealed{$ENDIF} (TList) private Owner : TCustomAxisPanel; Function Get(Index:Integer):TTeeCustomTool; procedure SetActive(Value:Boolean); public Function Add(Tool:TTeeCustomTool):TTeeCustomTool; procedure Clear; override; property Active:Boolean write SetActive; property Items[Index:Integer]:TTeeCustomTool read Get; default; end; // Base object for tools that have a Series property TTeeCustomToolSeries=class(TTeeCustomTool) private FSeries : TChartSeries; protected Function GetHorizAxis:TChartAxis; Function GetVertAxis:TChartAxis; class Function GetEditorClass:String; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetSeries(const Value: TChartSeries); virtual; public property Series:TChartSeries read FSeries write SetSeries; end; // Base object for tools that have an Axis property TTeeCustomToolAxis=class(TTeeCustomTool) private FAxis: TChartAxis; procedure ReadAxis(Reader: TReader); procedure WriteAxis(Writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; class Function GetEditorClass:String; override; procedure SetAxis(const Value: TChartAxis); virtual; public property Axis:TChartAxis read FAxis write SetAxis stored False; end; TTeeEventClass=class of TTeeEvent; TTeeSeriesEvent=class(TTeeEvent) Event : TChartSeriesEvent; Series : TCustomChartSeries; end; TChartSeriesClass=class of TChartSeries; TCustomAxisPanel=class(TCustomTeePanelExtended) private { Private declarations } F3DPercent : Integer; FAxes : TChartAxes; FAxisBehind : Boolean; FAxisVisible : Boolean; FClipPoints : Boolean; FCustomAxes : TChartCustomAxes; FSeriesList : TChartSeriesList; FDepthAxis : TChartDepthAxis; FDepthTopAxis : TChartDepthAxis; FTopAxis : TChartAxis; FBottomAxis : TChartAxis; FLeftAxis : TChartAxis; FRightAxis : TChartAxis; FView3DWalls : Boolean; FOnGetAxisLabel : TAxisOnGetLabel; FOnGetNextAxisLabel:TAxisOnGetNextLabel; FOnPageChange : TNotifyEvent; FOnBeforeDrawChart: TNotifyEvent; FOnBeforeDrawAxes : TNotifyEvent; FOnBeforeDrawSeries:TNotifyEvent; FPage : Integer; FMaxPointsPerPage : Integer; FScaleLastPage : Boolean; FMaxZOrder : Integer; FSeriesWidth3D : Integer; FSeriesHeight3D : Integer; FTools : TChartTools; InvertedRotation : Boolean; Procedure BroadcastTeeEventClass(Event:TTeeEventClass); Procedure BroadcastToolEvent(AEvent:TChartToolEvent); Procedure CalcInvertedRotation; Procedure CheckOtherSeries(Dest,Source:TChartSeries); Function GetAxisSeriesMaxPoints(Axis:TChartAxis):TChartSeries; Function GetSeries(Index:Integer):TChartSeries; Procedure InternalAddSeries(ASeries:TCustomChartSeries); Function InternalMinMax(AAxis:TChartAxis; IsMin,IsX:Boolean):Double; Function NoActiveSeries(AAxis:TChartAxis):Boolean; Procedure Set3DPercent(Value:Integer); Procedure SetAxisBehind(Value:Boolean); Procedure SetAxisVisible(Value:Boolean); Procedure SetBottomAxis(Value:TChartAxis); procedure SetClipPoints(Value:Boolean); Procedure SetCustomAxes(Value:TChartCustomAxes); Procedure SetDepthAxis(Value:TChartDepthAxis); procedure SetDepthTopAxis(const Value: TChartDepthAxis); Procedure SetLeftAxis(Value:TChartAxis); Procedure SetMaxPointsPerPage(Value:Integer); Procedure SetRightAxis(Value:TChartAxis); Procedure SetScaleLastPage(Value:Boolean); Procedure SetTopAxis(Value:TChartAxis); procedure SetView3DWalls(Value:Boolean); function IsCustomAxesStored: Boolean; protected { Protected declarations } LegendColor : TColor; LegendPen : TChartPen; Procedure BroadcastSeriesEvent(ASeries:TCustomChartSeries; Event:TChartSeriesEvent); Function CalcIsAxisVisible(Axis:TChartAxis):Boolean; Procedure CalcWallsRect; virtual; abstract; Function CalcWallSize(Axis:TChartAxis):Integer; virtual; abstract; Function CheckMouseSeries(x,y:Integer):Boolean; procedure ColorPaletteChanged; procedure DoOnAfterDraw; virtual; procedure DoOnBeforeDrawAxes; virtual; procedure DoOnBeforeDrawChart; virtual; procedure DoOnBeforeDrawSeries; virtual; procedure DrawTitlesAndLegend(BeforeSeries:Boolean); virtual; abstract; Function DrawBackWallAfter(Z:Integer):Boolean; virtual; Procedure DrawWalls; virtual; abstract; Procedure InternalDraw(Const UserRectangle: TRect); override; Function IsAxisVisible(Axis:TChartAxis):Boolean; Function MultiLineTextWidth(S:String; Var NumLines:Integer):Integer; procedure RemovedDataSource( ASeries: TChartSeries; AComponent: TComponent ); dynamic; Procedure SetPage(Value:Integer); {$IFNDEF CLR} Procedure GetChildren(Proc:TGetChildProc; Root:TComponent); override; {$ENDIF} {$IFNDEF CLX} procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; {$ELSE} procedure MouseLeave(AControl: TControl); override; {$ENDIF} public { Public declarations } Designer : TTeeCustomDesigner; { used only at Design-Time } ColorPalette : TColorArray; Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; { public methods } procedure Assign(Source:TPersistent); override; Function ActiveSeriesLegend(ItemIndex:Integer):TChartSeries; Function AddSeries(ASeries:TChartSeries):TChartSeries; overload; { 5.01 } Function AddSeries(ASeriesClass:TChartSeriesClass):TChartSeries; overload; Procedure CalcSize3DWalls; Procedure CheckDatasource(ASeries:TChartSeries); virtual; Function CountActiveSeries:Integer; Procedure ExchangeSeries(a,b:Integer); overload; Procedure ExchangeSeries(a,b:TCustomChartSeries); overload; Function FormattedValueLegend(ASeries:TChartSeries; ValueIndex:Integer):String; virtual; Procedure FreeAllSeries( SeriesClass:TChartSeriesClass=nil ); Function GetAxisSeries(Axis:TChartAxis):TChartSeries; {$IFDEF CLR} Procedure GetChildren(Proc:TGetChildProc; Root:TComponent); override; {$ENDIF} Function GetDefaultColor(Index:Integer):TColor; Function GetFreeSeriesColor(CheckBackground:Boolean=True; Series:TChartSeries=nil):TColor; Function GetMaxValuesCount:Integer; Function IsFreeSeriesColor(AColor: TColor; CheckBackground: Boolean; Series:TChartSeries=nil):Boolean; virtual; abstract; Function IsValidDataSource(ASeries: TChartSeries; AComponent: TComponent):Boolean; dynamic; Function MaxXValue(AAxis: TChartAxis):Double; Function MaxYValue(AAxis: TChartAxis):Double; Function MinXValue(AAxis: TChartAxis):Double; Function MinYValue(AAxis: TChartAxis):Double; Function MaxMarkWidth:Integer; Function MaxTextWidth:Integer; Function NumPages:Integer; dynamic; procedure PrintPages(FromPage: Integer=1; ToPage: Integer=0); Procedure RemoveSeries(ASeries: TCustomChartSeries); property Series[Index: Integer]:TChartSeries read GetSeries; default; Function SeriesCount:Integer; Function SeriesLegend(ItemIndex: Integer; OnlyActive: Boolean):TChartSeries; Function SeriesTitleLegend(SeriesIndex: Integer; OnlyActive: Boolean=False):String; { public properties } property Axes:TChartAxes read FAxes; property AxesList:TChartAxes read FAxes; // compatibility v4 property CustomAxes:TChartCustomAxes read FCustomAxes write SetCustomAxes stored IsCustomAxesStored; property MaxZOrder:Integer read FMaxZOrder write FMaxZOrder; property SeriesWidth3D:Integer read FSeriesWidth3D; property SeriesHeight3D:Integer read FSeriesHeight3D; { to be published properties } property AxisBehind:Boolean read FAxisBehind write SetAxisBehind default True; property AxisVisible:Boolean read FAxisVisible write SetAxisVisible default True; property BottomAxis:TChartAxis read FBottomAxis write SetBottomAxis; property Chart3DPercent:Integer read F3DPercent write Set3DPercent default TeeDef3DPercent; // obsolete; property ClipPoints:Boolean read FClipPoints write SetClipPoints default True; property Color; property DepthAxis:TChartDepthAxis read FDepthAxis write SetDepthAxis; property DepthTopAxis:TChartDepthAxis read FDepthTopAxis write SetDepthTopAxis; // 7.0 property LeftAxis:TChartAxis read FLeftAxis write SetLeftAxis; property MaxPointsPerPage:Integer read FMaxPointsPerPage write SetMaxPointsPerPage default 0; property Page:Integer read FPage write SetPage default 1; property RightAxis:TChartAxis read FRightAxis write SetRightAxis; property ScaleLastPage:Boolean read FScaleLastPage write SetScaleLastPage default True; property SeriesList:TChartSeriesList read FSeriesList; property Tools:TChartTools read FTools; property TopAxis:TChartAxis read FTopAxis write SetTopAxis; property View3DWalls:Boolean read FView3DWalls write SetView3DWalls default True; { to be published events } property OnBeforeDrawChart: TNotifyEvent read FOnBeforeDrawChart write FOnBeforeDrawChart; property OnBeforeDrawAxes:TNotifyEvent read FOnBeforeDrawAxes write FOnBeforeDrawAxes; property OnBeforeDrawSeries:TNotifyEvent read FOnBeforeDrawSeries write FOnBeforeDrawSeries; property OnGetAxisLabel:TAxisOnGetLabel read FOnGetAxisLabel write FOnGetAxisLabel; property OnGetNextAxisLabel:TAxisOnGetNextLabel read FOnGetNextAxisLabel write FOnGetNextAxisLabel; property OnPageChange:TNotifyEvent read FOnPageChange write FOnPageChange; end; TSeriesMarkPosition=class public ArrowFrom : TPoint; ArrowFix : Boolean; ArrowTo : TPoint; Custom : Boolean; Height : Integer; LeftTop : TPoint; Width : Integer; Procedure Assign(Source:TSeriesMarkPosition); Function Bounds:TRect; end; TSeriesMarksPositions=class {$IFDEF CLR}sealed{$ENDIF} (TList) private Function Get(Index:Integer):TSeriesMarkPosition; Procedure Put(Index:Integer; APosition:TSeriesMarkPosition); public Procedure Automatic(Index:Integer); procedure Clear; override; Function ExistCustom:Boolean; property Position[Index:Integer]:TSeriesMarkPosition read Get write Put; default; end; TMarksItem=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCustomShape) published property Bevel; property BevelWidth; property Color default ChartMarkColor; property Font; property Gradient; property Shadow; property ShapeStyle; property Transparency; property Transparent; end; TMarksItems=class {$IFDEF CLR}sealed{$ENDIF} (TList) private IMarks : TTeeCustomShape; ILoadingCustom : Boolean; function Get(Index:Integer):TMarksItem; public Procedure Clear; override; property Format[Index:Integer]:TMarksItem read Get; default; end; TSeriesMarksStyle=( smsValue, { 1234 } smsPercent, { 12 % } smsLabel, { Cars } smsLabelPercent, { Cars 12 % } smsLabelValue, { Cars 1234 } smsLegend, { (Legend.Style) } smsPercentTotal, { 12 % of 1234 } smsLabelPercentTotal, { Cars 12 % of 1234 } smsXValue, { 1..2..3.. or 21/6/1996 } smsXY { 123 456 } ); TSeriesMarksGradient=class {$IFDEF CLR}sealed{$ENDIF} (TChartGradient) public Constructor Create(ChangedEvent:TNotifyEvent); override; published property Direction default gdRightLeft; property EndColor default clWhite; property StartColor default clSilver; end; TSeriesPointerStyle=( psRectangle,psCircle,psTriangle,psDownTriangle, psCross,psDiagCross,psStar,psDiamond,psSmallDot, psNothing,psLeftTriangle,psRightTriangle ); TSeriesPointer=class(TTeeCustomShapeBrushPen) private FDark3D : Boolean; FDraw3D : Boolean; FGradient : TTeeGradient; FHorizSize : Integer; FInflate : Boolean; FSeries : TChartSeries; FStyle : TSeriesPointerStyle; FTransparency : TTeeTransparency; // 6.02 FVertSize : Integer; Procedure CheckPointerSize(Value:Integer); function GetColor: TColor; function GetStartZ:Integer; // 6.01 function GetMiddleZ:Integer; // 6.01 function GetEndZ:Integer; // 6.01 procedure SetColor(const Value: TColor); Procedure SetDark3D(Value:Boolean); Procedure SetDraw3D(Value:Boolean); procedure SetGradient(const Value: TTeeGradient); Procedure SetHorizSize(Value:Integer); Procedure SetInflate(Value:Boolean); Procedure SetStyle(Value:TSeriesPointerStyle); procedure SetTransparency(const Value: TTeeTransparency); Procedure SetVertSize(Value:Integer); protected AllowChangeSize : Boolean; FullGradient : Boolean; Procedure CalcHorizMargins(Var LeftMargin,RightMargin:Integer); Procedure CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); Procedure Change3D(Value:Boolean); Procedure ChangeHorizSize(NewSize:Integer); Procedure ChangeStyle(NewStyle:TSeriesPointerStyle); Procedure ChangeVertSize(NewSize:Integer); Procedure Prepare; public Constructor Create(AOwner:TChartSeries); Destructor Destroy; override; Procedure Assign(Source:TPersistent); override; Procedure Draw(P:TPoint); overload; Procedure Draw(X,Y:Integer); overload; Procedure Draw(px,py:Integer; ColorValue:TColor; AStyle:TSeriesPointerStyle); overload; Procedure DrawPointer( ACanvas:TCanvas3D; Is3D:Boolean; px,py,tmpHoriz,tmpVert:Integer; ColorValue:TColor; AStyle:TSeriesPointerStyle); Procedure PrepareCanvas(ACanvas:TCanvas3D; ColorValue:TColor); property Color:TColor read GetColor write SetColor; property ParentSeries:TChartSeries read FSeries; published property Brush; property Dark3D:Boolean read FDark3D write SetDark3D default True; Property Draw3D:Boolean read FDraw3D write SetDraw3D default True; property Gradient:TTeeGradient read FGradient write SetGradient; // 6.0 Property HorizSize:Integer read FHorizSize write SetHorizSize default 4; property InflateMargins:Boolean read FInflate write SetInflate; property Pen; property Style:TSeriesPointerStyle read FStyle write SetStyle; property Transparency:TTeeTransparency read FTransparency write SetTransparency default 0; Property VertSize:Integer read FVertSize write SetVertSize default 4; Property Visible; end; TArrowHeadStyle=(ahNone,ahLine,ahSolid); TChartArrowPen=TWhitePen; TCallout=class(TSeriesPointer) private FArrow : TChartArrowPen; FArrowHead : TArrowHeadStyle; FDistance : Integer; FArrowHeadSize: Integer; procedure SetDistance(const Value: Integer); procedure SetArrow(const Value: TChartArrowPen); procedure SetArrowHead(const Value: TArrowHeadStyle); procedure SetArrowHeadSize(const Value: Integer); protected procedure Draw(AColor:TColor; AFrom,ATo:TPoint; Z:Integer); overload; public Constructor Create(AOwner:TChartSeries); Procedure Assign(Source:TPersistent); override; destructor Destroy; override; published property Arrow:TChartArrowPen read FArrow write SetArrow; property ArrowHead:TArrowHeadStyle read FArrowHead write SetArrowHead default ahNone; property ArrowHeadSize:Integer read FArrowHeadSize write SetArrowHeadSize default 8; property Distance:Integer read FDistance write SetDistance default 0; property Draw3D default False; property InflateMargins default True; property Style default psRectangle; property Visible default True; end; TMarksCallout=class(TCallout) private FLength : Integer; procedure ApplyArrowLength(APosition:TSeriesMarkPosition); Function IsLengthStored:Boolean; procedure SetLength(const Value:Integer); protected DefaultLength : Integer; public Constructor Create(AOwner: TChartSeries); Procedure Assign(Source:TPersistent); override; published property Length:Integer read FLength write SetLength stored IsLengthStored; property Visible default False; end; TSeriesMarksSymbol=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCustomShape) private Function ShouldDraw:Boolean; public Constructor Create(AOwner:TCustomTeePanel); override; published property Bevel; { 5.01 } property BevelWidth; { 5.01 } property Brush; property Frame; property Gradient; property Pen; property Shadow; property ShapeStyle; property Transparency; { 5.01 } property Visible default False; end; // CLR Note: This class cannot be marked as "sealed" // due to required cast access tricks. TSeriesMarks=class(TTeeCustomShape) private FAngle : Integer; FCallout : TMarksCallout; FClip : Boolean; FDrawEvery : Integer; FItems : TMarksItems; FMarkerStyle : TSeriesMarksStyle; FMultiLine : Boolean; FSeries : TChartSeries; FPositions : TSeriesMarksPositions; FSymbol : TSeriesMarksSymbol; FZPosition : Integer; function GetArrowLength: Integer; function GetArrowPen: TChartArrowPen; Function GetBackColor:TColor; Function GetCallout:TMarksCallout; function GetItem(Index:Integer):TMarksItem; Function GetSymbol: TSeriesMarksSymbol; Procedure InternalDraw(Index:Integer; AColor:TColor; Const St:String; APosition:TSeriesMarkPosition); procedure ReadItems(Stream: TStream); Procedure SetAngle(Value:Integer); procedure SetCallout(const Value: TMarksCallout); Procedure SetArrowPen(const Value:TChartArrowPen); Procedure SetArrowLength(Value:Integer); Procedure SetBackColor(Value:TColor); Procedure SetClip(Value:Boolean); Procedure SetDrawEvery(Value:Integer); Procedure SetMultiline(Value:Boolean); Procedure SetStyle(Value:TSeriesMarksStyle); procedure SetSymbol(const Value: TSeriesMarksSymbol); procedure WriteItems(Stream: TStream); protected Procedure AntiOverlap(First, ValueIndex:Integer; APosition:TSeriesMarkPosition); Procedure ConvertTo2D(Point:TPoint; var P:TPoint); procedure DefineProperties(Filer: TFiler); override; Function GetGradientClass:TChartGradientClass; override; Procedure InitShadow(AShadow:TTeeShadow); override; Function MarkItem(ValueIndex:Integer):TTeeCustomShape; procedure SetParent(Value:TCustomTeePanel); override; Function TextWidth(ValueIndex:Integer):Integer; Procedure UsePosition(Index:Integer; Var MarkPosition:TSeriesMarkPosition); public Constructor Create(AOwner:TChartSeries); overload; Destructor Destroy; override; Procedure ApplyArrowLength(APosition:TSeriesMarkPosition); Procedure Assign(Source:TPersistent); override; procedure Clear; Function Clicked(X,Y:Integer):Integer; Procedure DrawText(Const R:TRect; Const St:String); property Item[Index:Integer]:TMarksItem read GetItem; default; property Items:TMarksItems read FItems; property ParentSeries:TChartSeries read FSeries; property Positions:TSeriesMarksPositions read FPositions; procedure ResetPositions; property ZPosition : Integer read FZPosition write FZPosition; published property Angle:Integer read FAngle write SetAngle default 0; property Arrow:TChartArrowPen read GetArrowPen write SetArrowPen; // obsolete property ArrowLength:Integer read GetArrowLength write SetArrowLength stored False; // obsolete property Callout:TMarksCallout read GetCallout write SetCallout; // 6.0 property BackColor:TColor read GetBackColor write SetBackColor default ChartMarkColor; property Bevel; { 5.01 } property BevelWidth; { 5.01 } property Brush; property Clip:Boolean read FClip write SetClip default False; property Color default ChartMarkColor; property DrawEvery:Integer read FDrawEvery write SetDrawEvery default 1; property Font; property Frame; property Gradient; property MultiLine:Boolean read FMultiLine write SetMultiLine default False; property Shadow; property ShapeStyle; property Style:TSeriesMarksStyle read FMarkerStyle write SetStyle default smsLabel; property Symbol:TSeriesMarksSymbol read GetSymbol write SetSymbol; property Transparency; { 5.01 } property Transparent; property Visible; end; TSeriesOnBeforeAdd=Function(Sender:TChartSeries):Boolean of object; TSeriesOnAfterAdd=Procedure(Sender:TChartSeries; ValueIndex:Integer) of object; TSeriesOnClear=Procedure(Sender:TChartSeries) of object; TSeriesOnGetMarkText=Procedure(Sender:TChartSeries; ValueIndex:Integer; Var MarkText:String) of object; TSeriesRecalcOptions=set of (rOnDelete, rOnModify, rOnInsert, rOnClear); TFunctionPeriodStyle=( psNumPoints, psRange ); TFunctionPeriodAlign=( paFirst,paCenter,paLast ); {$IFDEF CLR} [ToolBoxItem(False)] {$ENDIF} TTeeFunction=class(TComponent) private FPeriod : Double; FPeriodStyle : TFunctionPeriodStyle; FPeriodAlign : TFunctionPeriodAlign; FParent : TChartSeries; IUpdating : Boolean; Procedure SetPeriod(Const Value:Double); Procedure SetParentSeries(AParent:TChartSeries); Procedure SetPeriodAlign(Value:TFunctionPeriodalign); Procedure SetPeriodStyle(Value:TFunctionPeriodStyle); protected CanUsePeriod : Boolean; // function uses Period property ? NoSourceRequired : Boolean; // function requires source Series ? SingleSource : Boolean; // function allows more than one source ? HideSourceList : Boolean; // For single-source, allow select value-list ? Procedure AddFunctionXY(YMandatorySource:Boolean; const tmpX,tmpY:Double); Procedure CalculatePeriod( Source:TChartSeries; Const tmpX:Double; FirstIndex,LastIndex:Integer); virtual; Procedure CalculateAllPoints(Source:TChartSeries; NotMandatorySource:TChartValueList); virtual; Procedure CalculateByPeriod(Source:TChartSeries; NotMandatorySource:TChartValueList); virtual; procedure Clear; dynamic; Procedure DoCalculation( Source:TChartSeries; NotMandatorySource:TChartValueList); virtual; class Function GetEditorClass:String; virtual; Procedure InternalSetPeriod(Const APeriod:Double); Function IsValidSource(Value:TChartSeries):Boolean; dynamic; class Procedure PrepareForGallery(Chart:TCustomAxisPanel); virtual; {$IFNDEF CLR} procedure SetParentComponent(Value: TComponent); override; {$ENDIF} Function ValueList(ASeries:TChartSeries):TChartValueList; public Constructor Create(AOwner: TComponent); override; Procedure Assign(Source:TPersistent); override; procedure AddPoints(Source:TChartSeries); dynamic; procedure BeginUpdate; Function Calculate(SourceSeries:TChartSeries; First,Last:Integer):Double; virtual; Function CalculateMany(SourceSeriesList:TList; ValueIndex:Integer):Double; virtual; procedure EndUpdate; function GetParentComponent: TComponent; override; function HasParent: Boolean; override; property ParentSeries:TChartSeries read FParent write SetParentSeries; Procedure ReCalculate; {$IFDEF CLR} procedure SetParentComponent(Value: TComponent); override; {$ENDIF} published property Period:Double read FPeriod write SetPeriod; property PeriodAlign:TFunctionPeriodAlign read FPeriodAlign write SetPeriodAlign default paCenter; property PeriodStyle:TFunctionPeriodStyle read FPeriodStyle write SetPeriodStyle default psNumPoints; end; TTeeMovingFunction=class(TTeeFunction) protected Procedure DoCalculation( Source:TChartSeries; NotMandatorySource:TChartValueList); override; public Constructor Create(AOwner:TComponent); override; published property Period; end; TChartValueLists=class {$IFDEF CLR}sealed{$ENDIF} (TList) private Function Get(Index:Integer):TChartValueList; public Procedure Clear; override; property ValueList[Index:Integer]:TChartValueList read Get; default; end; TChartSeriesStyle=set of ( tssIsTemplate, tssDenyChangeType, tssDenyDelete, tssDenyClone, tssIsPersistent, tssHideDataSource ); TCustomChartSeries=class(TCustomChartElement) private FShowInLegend : Boolean; FTitle : String; FIdentifier : String; { DecisionCube } FStyle : TChartSeriesStyle; { DecisionCube } procedure ReadIdentifier(Reader: TReader); procedure WriteIdentifier(Writer: TWriter); procedure ReadStyle(Reader: TReader); procedure WriteStyle(Writer: TWriter); Procedure RepaintDesigner; Procedure SetShowInLegend(Value:Boolean); Procedure SetTitle(Const Value:String); protected Procedure Added; dynamic; Procedure CalcHorizMargins(Var LeftMargin,RightMargin:Integer); virtual; Procedure CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); virtual; procedure DefineProperties(Filer: TFiler); override; procedure DoBeforeDrawChart; virtual; Procedure GalleryChanged3D(Is3D:Boolean); dynamic; Procedure Removed; dynamic; Procedure SetActive(Value:Boolean); override; public Constructor Create(AOwner: TComponent); override; procedure Assign(Source:TPersistent); override; Function SameClass(tmpSeries:TChartSeries):Boolean; property ShowInLegend:Boolean read FShowInLegend write SetShowInLegend default True; property Title:String read FTitle write SetTitle; { DSS, hidden } property Identifier:String read FIdentifier write FIdentifier; property Style:TChartSeriesStyle read FStyle write FStyle default []; end; TSeriesRandomBounds=packed record tmpX,StepX,tmpY,MinY,DifY:Double; end; TTeeFunctionClass=class of TTeeFunction; {$IFDEF CLR} PString=string; {$ENDIF} TTeeSeriesType=class {$IFDEF CLR}sealed{$ENDIF} (TObject) SeriesClass : TChartSeriesClass; FunctionClass : TTeeFunctionClass; Description : PString; GalleryPage : PString; NumGallerySeries : Integer; end; TChartSubGalleryProc=Function(Const AName:String):TCustomAxisPanel of object; TLegendTextStyle=( ltsPlain,ltsLeftValue,ltsRightValue, ltsLeftPercent,ltsRightPercent,ltsXValue,ltsValue, ltsPercent,ltsXAndValue,ltsXAndPercent); TeeFormatFlags = (tfNoMandatory,tfColor,tfLabel,tfMarkPosition); TeeFormatFlag = set of TeeFormatFlags; TLabelsList=class {$IFDEF CLR}sealed{$ENDIF} (TList) private Series : TChartSeries; Procedure DeleteLabel(ValueIndex:Integer); Function GetLabel(ValueIndex:Integer):String; Procedure SetLabel(ValueIndex:Integer; Const ALabel:String); Procedure InsertLabel(ValueIndex:Integer; Const ALabel:String); public procedure Assign(Source:TLabelsList); procedure Clear; override; Function IndexOfLabel(const ALabel:String; CaseSensitive:Boolean=True):Integer; property Labels[Index:Integer]:String read GetLabel write SetLabel; default; end; TDataSourcesList=class {$IFDEF CLR}sealed{$ENDIF} (TList) // 6.02 private Series : TChartSeries; function InheritedAdd(Value:TComponent):Integer; procedure InheritedClear; {$IFDEF D5} protected {$IFDEF CLR} procedure Notify(Instance:TObject; Action: TListNotification); override; {$ELSE} procedure Notify(Ptr: Pointer; Action: TListNotification); override; {$ENDIF} {$ENDIF} public function Add(Value:TComponent):Integer; procedure Clear; override; end; TChartSeries=class(TCustomChartSeries) private FColor : TColor; FColorEachPoint : Boolean; FColors : TList; FColorSource : String; FCursor : TCursor; FDataSources : TDataSourcesList; FDepth : Integer; FGetHorizAxis : TChartAxis; FGetVertAxis : TChartAxis; FLabelsSource : String; FLinkedSeries : TCustomSeriesList; FMarks : TSeriesMarks; FPercentFormat : String; FTempDataSources : TStringList; FValueFormat : String; FValuesList : TChartValueLists; FX : TChartValueList; FLabels : TLabelsList; FY : TChartValueList; FHorizAxis : THorizAxis; FCustomHorizAxis : TChartAxis; FCustomVertAxis : TChartAxis; FZOrder : Integer; FVertAxis : TVertAxis; FRecalcOptions : TSeriesRecalcOptions; FTeeFunction : TTeeFunction; { Private } IsMouseInside : Boolean; ILabelOrder : TChartListOrder; ISeriesColor : TColor; // Color assigned when creating the Series. { Events } FAfterDrawValues : TNotifyEvent; FBeforeDrawValues : TNotifyEvent; FOnAfterAdd : TSeriesOnAfterAdd; FOnBeforeAdd : TSeriesOnBeforeAdd; FOnClearValues : TSeriesOnClear; FOnClick : TSeriesClick; FOnDblClick : TSeriesClick; FOnGetMarkText : TSeriesOnGetMarkText; FOnMouseEnter : TNotifyEvent; FOnMouseLeave : TNotifyEvent; Function CanAddRandomPoints:Boolean; Procedure ChangeInternalColor(Value:TColor); Function CompareLabelIndex(a,b:Integer):Integer; Function GetDataSource:TComponent; Function GetZOrder:Integer; Procedure GrowColors; Function InternalAddDataSource(Value:TComponent):Integer; Function InternalSetDataSource(Value:TComponent; ClearAll:Boolean):Integer; Procedure InternalRemoveDataSource(Value:TComponent); Function IsColorStored:Boolean; Function IsPercentFormatStored:Boolean; Function IsValueFormatStored:Boolean; Procedure NotifyColorChanged; procedure ReadCustomHorizAxis(Reader: TReader); procedure ReadCustomVertAxis(Reader: TReader); procedure ReadDataSources(Reader: TReader); Procedure RecalcGetAxis; Procedure RemoveAllLinkedSeries; Procedure SetColorSource(Const Value:String); Procedure SetCustomHorizAxis(Value:TChartAxis); Procedure SetCustomVertAxis(Value:TChartAxis); Procedure SetDataSource(Value:TComponent); procedure SetDepth(const Value: Integer); Procedure SetHorizAxis(const Value:THorizAxis); Procedure SetLabelsSource(Const Value:String); procedure SetMarks(Value:TSeriesMarks); Procedure SetPercentFormat(Const Value:String); Procedure SetValueColor(ValueIndex:Integer; AColor:TColor); Procedure SetValueFormat(Const Value:String); Procedure SetVertAxis(const Value:TVertAxis); Procedure SetXValue(Index:Integer; Const Value:Double); Procedure SetYValue(Index:Integer; Const Value:Double); Procedure SetZOrder(Value:Integer); procedure WriteCustomHorizAxis(Writer: TWriter); procedure WriteCustomVertAxis(Writer: TWriter); procedure WriteDataSources(Writer: TWriter); function GetXLabel(Index: Integer): String; procedure SetXLabel(Index: Integer; const Value: String); protected DontSaveData : Boolean; ForceSaveData : Boolean; ManualData : Boolean; FFirstVisibleIndex : Integer; FLastVisibleIndex : Integer; INumSampleValues : Integer; IUpdating : Integer; IUseSeriesColor : Boolean; IUseNotMandatory : Boolean; IZOrder : Integer; ILegend : TTeeCustomShape; IFirstDrawIndex : Integer; Function AddChartValue(Source:TChartSeries; ValueIndex:Integer):Integer; virtual; Procedure Added; override; Procedure AddedValue(Source:TChartSeries; ValueIndex:Integer); virtual; Procedure AddLinkedSeries(ASeries:TChartSeries); Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); dynamic; Procedure AddValues(Source:TChartSeries); virtual; procedure CalcFirstLastPage(var First,Last:Integer); Procedure CalcFirstLastVisibleIndex; virtual; Procedure CalcZOrder; virtual; procedure CalcDepthPositions; virtual; Function CheckMouse(x,y:Integer):Boolean; Procedure ClearLists; virtual; class Procedure CreateSubGallery(AddSubChart:TChartSubGalleryProc); virtual; procedure DefineProperties(Filer: TFiler); override; Procedure DeletedValue(Source:TChartSeries; ValueIndex:Integer); virtual; procedure DoAfterDrawValues; virtual; procedure DoBeforeDrawValues; virtual; procedure DrawAllValues; virtual; Procedure DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); virtual; Procedure DrawMark(ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); virtual; procedure DrawMarks; procedure DrawValue(ValueIndex:Integer); virtual; Function FirstInZOrder:Boolean; Procedure GetChildren(Proc:TGetChildProc; Root:TComponent); override; Function GetMarkText(ValueIndex:Integer):String; Function GetSeriesColor:TColor; Function GetValueColor(ValueIndex:Integer):TColor; virtual; Function GetxValue(ValueIndex:Integer):Double; virtual; { conflicts with c++ wingdi.h } Function GetyValue(ValueIndex:Integer):Double; virtual; { conflicts with c++ wingdi.h } Function InternalColor(ValueIndex:Integer):TColor; Procedure Loaded; override; Function MandatoryAxis:TChartAxis; // 6.02 procedure Notification( AComponent: TComponent; Operation: TOperation); override; Procedure NotifyNewValue(Sender:TChartSeries; ValueIndex:Integer); virtual; Procedure NotifyValue(ValueEvent:TValueEvent; ValueIndex:Integer); virtual; Function MoreSameZOrder:Boolean; virtual; Procedure PrepareForGallery(IsEnabled:Boolean); dynamic; Procedure PrepareLegendCanvas( ValueIndex:Integer; Var BackColor:TColor; Var BrushStyle:TBrushStyle); virtual; class Function RandomValue(const Range:Integer):Integer; procedure ReadData(Stream: TStream); Procedure Removed; override; Procedure RemoveLinkedSeries(ASeries:TChartSeries); Procedure SetChartValueList( AValueList:TChartValueList; Value:TChartValueList); Procedure SetColorEachPoint(Value:Boolean); virtual; Procedure SetHorizontal; Procedure SetParentChart(Const Value:TCustomAxisPanel); override; Procedure SetSeriesColor(AColor:TColor); virtual; class Procedure SetSubGallery(ASeries:TChartSeries; Index:Integer); virtual; Procedure SetXValues(Value:TChartValueList); Procedure SetYValues(Value:TChartValueList); Function ValueListOfAxis(Axis:TChartAxis):TChartValueList; virtual; procedure WriteData(Stream: TStream); dynamic; public CalcVisiblePoints : Boolean; DrawBetweenPoints : Boolean; AllowSinglePoint : Boolean; HasZValues : Boolean; StartZ : Integer; MiddleZ : Integer; EndZ : Integer; MandatoryValueList : TChartValueList; NotMandatoryValueList : TChartValueList; YMandatory : Boolean; Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Function Add(Const AValue:Double; Const ALabel:String=''; AColor:TColor=clTeeColor):Integer; virtual; Function AddArray(Const Values:Array of TChartValue):Integer; overload; Function AddNull(Const Value:Double):Integer; overload; Function AddNull(Const ALabel:String=''):Integer; overload; virtual; Function AddNullXY(Const X,Y:Double; Const ALabel:String=''):Integer; virtual; Function AddX(Const AXValue:Double; Const ALabel:String=''; AColor:TColor=clTeeColor):Integer; Function AddXY(Const AXValue,AYValue:Double; Const ALabel:String=''; AColor:TColor=clTeeColor):Integer; virtual; Function AddY(Const AYValue:Double; Const ALabel:String=''; AColor:TColor=clTeeColor):Integer; procedure Assign(Source:TPersistent); override; procedure AssignFormat(Source:TChartSeries); Function AssociatedToAxis(Axis:TChartAxis):Boolean; virtual; Procedure BeginUpdate; Procedure CheckOrder; dynamic; Procedure Clear; virtual; Function Count:Integer; Function CountLegendItems:Integer; virtual; Procedure Delete(ValueIndex:Integer); overload; virtual; Procedure Delete(Start,Quantity:Integer; RemoveGap:Boolean=False); overload; virtual; Procedure EndUpdate; Procedure FillSampleValues(NumValues:Integer=0); dynamic; Function FirstDisplayedIndex:Integer; Function IsNull(ValueIndex:Integer):Boolean; Function IsValidSourceOf(Value:TChartSeries):Boolean; dynamic; Function IsValidSeriesSource(Value:TChartSeries):Boolean; dynamic; Function LegendToValueIndex(LegendIndex:Integer):Integer; virtual; Function LegendItemColor(LegendIndex:Integer):TColor; virtual; Function LegendString(LegendIndex:Integer; LegendTextStyle:TLegendTextStyle):String; virtual; property LinkedSeries:TCustomSeriesList read FLinkedSeries; Function MaxXValue:Double; virtual; Function MaxYValue:Double; virtual; Function MaxZValue:Double; virtual; Function MinXValue:Double; virtual; Function MinYValue:Double; virtual; Function MinZValue:Double; virtual; Function NumSampleValues:Integer; dynamic; Function RandomBounds(NumValues:Integer):TSeriesRandomBounds; Procedure RemoveDataSource(Value:TComponent); Procedure SetNull(ValueIndex:Integer; Null:Boolean=True); // 6.0 Procedure SortByLabels(Order:TChartListOrder=loAscending); // 6.0 Function VisibleCount:Integer; { <-- Number of VISIBLE points (Last-First+1) } property ValuesList:TChartValueLists read FValuesList; property XValue[Index:Integer]:Double read GetxValue write SetXValue; property YValue[Index:Integer]:Double read GetyValue write SetYValue; property ZOrder:Integer read GetZOrder write SetZOrder default TeeAutoZOrder; Function MaxMarkWidth:Integer; Function CalcXPos(ValueIndex:Integer):Integer; virtual; Function CalcXPosValue(Const Value:Double):Integer; Function CalcXSizeValue(Const Value:Double):Integer; Function CalcYPos(ValueIndex:Integer):Integer; virtual; Function CalcYPosValue(Const Value:Double):Integer; Function CalcYSizeValue(Const Value:Double):Integer; Function CalcPosValue(Const Value:Double):Integer; Function XScreenToValue(ScreenPos:Integer):Double; Function YScreenToValue(ScreenPos:Integer):Double; Function XValueToText(Const AValue:Double):String; Function YValueToText(Const AValue:Double):String; Procedure ColorRange( AValueList:TChartValueList; Const FromValue,ToValue:Double; AColor:TColor); Procedure CheckDataSource; { Public Properties } property Labels:TLabelsList read FLabels; property XLabel[Index:Integer]:String read GetXLabel write SetXLabel; // deprecated (obsolete) property ValueMarkText[Index:Integer]:String read GetMarkText; property ValueColor[Index:Integer]:TColor read GetValueColor write SetValueColor; property XValues:TChartValueList read FX write SetXValues; property YValues:TChartValueList read FY write SetYValues; Function GetYValueList(AListName:String):TChartValueList; virtual; property GetVertAxis:TChartAxis read FGetVertAxis; property GetHorizAxis:TChartAxis read FGetHorizAxis; Function MarkPercent(ValueIndex:Integer; AddTotal:Boolean=False):String; Function Clicked(x,y:Integer):Integer; overload; virtual; Function Clicked(P:TPoint):Integer; overload; Procedure RefreshSeries; property FirstValueIndex:Integer read FFirstVisibleIndex; property LastValueIndex:Integer read FLastVisibleIndex; Function GetOriginValue(ValueIndex:Integer):Double; virtual; Function GetMarkValue(ValueIndex:Integer):Double; virtual; Procedure AssignValues(Source:TChartSeries); Function DrawValuesForward:Boolean; virtual; Function DrawSeriesForward(ValueIndex:Integer):Boolean; virtual; procedure SwapValueIndex(a,b:Integer); dynamic; property RecalcOptions: TSeriesRecalcOptions read FRecalcOptions write FRecalcOptions default [ rOnDelete, rOnModify, rOnInsert, rOnClear]; Function GetCursorValueIndex:Integer; Procedure GetCursorValues(Var XValue,YValue:Double); Procedure DrawLegend(ValueIndex:Integer; Const Rect:TRect); virtual; Function UseAxis:Boolean; virtual; procedure SetFunction(AFunction:TTeeFunction); virtual; property SeriesColor:TColor read GetSeriesColor write SetSeriesColor stored IsColorStored; // deprecated { other } property DataSources:TDataSourcesList read FDataSources; property FunctionType:TTeeFunction read FTeeFunction write SetFunction; Procedure CheckOtherSeries(Source:TChartSeries); Procedure ReplaceList(OldList,NewList:TChartValueList); property CustomHorizAxis:TChartAxis read FCustomHorizAxis write SetCustomHorizAxis; property CustomVertAxis:TChartAxis read FCustomVertAxis write SetCustomVertAxis; { to be published } property Active; property Color:TColor read GetSeriesColor write SetSeriesColor stored IsColorStored; // replaces SeriesColor property ColorEachPoint:Boolean read FColorEachPoint write SetColorEachPoint default False; property ColorSource:String read FColorSource write SetColorSource; property Cursor:TCursor read FCursor write FCursor default crDefault; property Depth:Integer read FDepth write SetDepth default TeeAutoDepth; property HorizAxis:THorizAxis read FHorizAxis write SetHorizAxis default aBottomAxis; property Marks:TSeriesMarks read FMarks write SetMarks; property ParentChart; { datasource below parentchart } property DataSource:TComponent read GetDataSource write SetDataSource; property PercentFormat:String read FPercentFormat write SetPercentFormat stored IsPercentFormatStored; property ShowInLegend; property Title; property ValueFormat:String read FValueFormat write SetValueFormat stored IsValueFormatStored; property VertAxis:TVertAxis read FVertAxis write SetVertAxis default aLeftAxis; property XLabelsSource:String read FLabelsSource write SetLabelsSource; { events } property AfterDrawValues:TNotifyEvent read FAfterDrawValues write FAfterDrawValues; property BeforeDrawValues:TNotifyEvent read FBeforeDrawValues write FBeforeDrawValues; property OnAfterAdd:TSeriesOnAfterAdd read FOnAfterAdd write FOnAfterAdd; property OnBeforeAdd:TSeriesOnBeforeAdd read FOnBeforeAdd write FOnBeforeAdd; property OnClearValues:TSeriesOnClear read FOnClearValues write FOnClearValues; property OnClick:TSeriesClick read FOnClick write FOnClick; property OnDblClick:TSeriesClick read FOnDblClick write FOnDblClick; property OnGetMarkText:TSeriesOnGetMarkText read FOnGetMarkText write FOnGetMarkText; property OnMouseEnter:TNotifyEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave:TNotifyEvent read FOnMouseLeave write FOnMouseLeave; end; ChartException=class(Exception); TTeeSeriesSource=class(TComponent) private FActive : Boolean; FSeries : TChartSeries; procedure SetSeries(const Value: TChartSeries); protected Procedure Loaded; override; procedure Notification( AComponent: TComponent; Operation: TOperation); override; procedure SetActive(const Value: Boolean); virtual; public Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; class Function Available(AChart:TCustomAxisPanel):Boolean; virtual; class Function Description:String; virtual; { bcos BCB, do not make abstract } class Function Editor:TComponentClass; virtual; { bcos BCB, do not make abstract } class Function HasNew:Boolean; virtual; class Function HasSeries(ASeries:TChartSeries):Boolean; virtual; Procedure Close; virtual; Procedure Load; virtual; // abstract; Procedure Open; virtual; Procedure Refresh; property Active:Boolean read FActive write SetActive default False; property Series:TChartSeries read FSeries write SetSeries; end; TTeeSeriesSourceClass=class of TTeeSeriesSource; Var TeeAxisClickGap : Integer=3; { minimum pixels distance to trigger axis click } TeeDefaultCapacity : Integer=1000; { default TList.Capacity to speed-up Lists } Function TeeSources: TList; { List of registered Series Source components } Function SeriesTitleOrName(ASeries:TCustomChartSeries):String; Procedure FillSeriesItems(AItems:TStrings; AList:TCustomSeriesList; UseTitles:Boolean=True); Procedure ShowMessageUser(Const S:String); { Returns if a Series has "X" values } Function HasNoMandatoryValues(ASeries:TChartSeries):Boolean; { Returns True if ASeries has text labels } Function HasLabels(ASeries:TChartSeries):Boolean; { Returns True if ASeries has colors } Function HasColors(ASeries:TChartSeries):Boolean; { Returns set indicating Series contents (colors, labels, etc) } Function SeriesGuessContents(ASeries:TChartSeries):TeeFormatFlag; // Draws the associated series bitmap icon at the specified LeftTop location procedure TeeDrawBitmapEditor(Canvas: TCanvas; Element:TCustomChartElement; Left,Top:Integer); implementation Uses {$IFDEF CLX} QPrinters, {$ELSE} Printers, {$ENDIF} {$IFDEF D6} {$IFNDEF CLX} Types, {$ENDIF} {$ENDIF} {$IFDEF TEEARRAY} {$IFOPT R+} {$IFDEF D6} RtlConsts, {$ELSE} Consts, {$ENDIF} {$ENDIF} {$ENDIF} {$IFNDEF D5} TypInfo, {$ENDIF} Math, TeeConst; { Returns a "good" value, bigger than "OldStep", as 2..5..10..etc } Function TeeNextStep(Const OldStep:Double):Double; Begin if OldStep >= 10 then result := 10*TeeNextStep(0.1*OldStep) else if OldStep < 1 then result := 0.1*TeeNextStep(OldStep*10) else if OldStep < 2 then result:=2 else if OldStep < 5 then result:=5 else result:=10 end; { Determine what a Series point is made of } Function SeriesGuessContents(ASeries:TChartSeries):TeeFormatFlag; begin if HasNoMandatoryValues(ASeries) then result:=[tfNoMandatory] else result:=[]; if HasColors(ASeries) then result:=result+[tfColor]; if HasLabels(ASeries) then result:=result+[tfLabel]; if ASeries.Marks.Positions.ExistCustom then result:=result+[tfMarkPosition]; end; { TChartAxisTitle } Procedure TChartAxisTitle.Assign(Source:TPersistent); Begin if Source is TChartAxisTitle then With TChartAxisTitle(Source) do Begin Self.FAngle :=FAngle; Self.FCaption:=FCaption; end; inherited; end; Function TChartAxisTitle.IsAngleStored:Boolean; begin result:=FAngle<>IDefaultAngle; end; type TTeePanelAccess=class {$IFDEF CLR}sealed{$ENDIF} (TCustomTeePanel); Procedure TChartAxisTitle.SetAngle(const Value:Integer); Begin TTeePanelAccess(ParentChart).SetIntegerProperty(FAngle,Value mod 360); { 5.01 } end; Procedure TChartAxisTitle.SetCaption(Const Value:String); Begin TTeePanelAccess(ParentChart).SetStringProperty(FCaption,Value); end; { TChartAxisPen } Constructor TChartAxisPen.Create(OnChangeEvent:TNotifyEvent); Begin inherited; Width:=2; end; type TOwnedCollectionAccess=class {$IFDEF CLR}sealed{$ENDIF} (TOwnedCollection); { TChartAxis } Constructor TChartAxis.Create(Collection:TCollection); {$IFDEF CLR} var tmp : TCustomAxisPanel; {$ENDIF} Begin {$IFDEF CLR} tmp:=TCustomAxisPanel(Collection.Owner); if tmp.Axes.Count>=6 then inherited Create(Collection) else inherited Create(nil); FParentChart:=tmp; {$ELSE} FParentChart:=TCustomAxisPanel(TOwnedCollectionAccess(Collection).GetOwner); if FParentChart.Axes.Count>=TeeInitialCustomAxis then inherited Create(Collection) else inherited Create(nil); {$ENDIF} SetCalcPosValue; ISeriesList:=TCustomSeriesList.Create; FItems:=TAxisItems.Create(Self); FLogarithmicBase:=10; FAutomatic:=True; FAutomaticMaximum:=True; FAutomaticMinimum:=True; FLabelsSeparation:=10; { % } FAxisValuesFormat:=TeeMsg_DefValueFormat; FLabelsAlign:=alDefault; FLabelStyle:=talAuto; FLabelsOnAxis:=True; FTickOnLabelsOnly:=True; FAxisTitle:=TChartAxisTitle.Create(ParentChart); FAxisTitle.IDefaultAngle:=0; FTicks:=TDarkGrayPen.Create(ParentChart.CanvasChanged); FTickLength:=4; FMinorTicks:=TDarkGrayPen.Create(ParentChart.CanvasChanged); FMinorTickLength :=2; FMinorTickCount :=3; FTicksInner:=TDarkGrayPen.Create(ParentChart.CanvasChanged); FGrid:=TAxisGridPen.Create(ParentChart.CanvasChanged); FMinorGrid:=TChartHiddenPen.Create(ParentChart.CanvasChanged); FAxis:=TChartAxisPen.Create(ParentChart.CanvasChanged); FVisible :=True; FRoundFirstLabel :=True; FExactDateTime :=True; FEndPosition :=100; FParentChart.FAxes.Add(Self); end; Destructor TChartAxis.Destroy; Procedure ResetSeriesAxes; var t : Integer; begin With FParentChart do for t:=0 to SeriesCount-1 do With TChartSeries(Series[t]) do begin if CustomHorizAxis=Self then begin CustomHorizAxis:=nil; HorizAxis:=aBottomAxis; end; if CustomVertAxis=Self then begin CustomVertAxis:=nil; VertAxis:=aLeftAxis; end; end; end; begin FMinorTicks.Free; FTicks.Free; FTicksInner.Free; FGrid.Free; FMinorGrid.Free; FAxis.Free; FAxisTitle.Free; FItems.Free; ResetSeriesAxes; ISeriesList.Free; FParentChart.FAxes.Remove(Self); Tick:=nil; inherited; end; Procedure TChartAxis.IncDecDateTime( Increment:Boolean; Var Value:Double; Const AnIncrement:Double; tmpWhichDateTime:TDateTimeStep); begin TeeDateTimeIncrement( FExactDateTime and IAxisDateTime and (tmpWhichDateTime>=dtHalfMonth), Increment, Value, AnIncrement, tmpWhichDateTime ); end; { An axis is "DateTime" if at least one Active Series with datetime values is associated to it } Function TChartAxis.IsDateTime:Boolean; Var tmpSeries : Integer; tmpList : TChartValueList; Begin With ParentChart do for tmpSeries:=0 to SeriesCount-1 do With Series[tmpSeries] do if Active then begin tmpList:=ValueListOfAxis(Self); if Assigned(tmpList) then begin result:=tmpList.DateTime; exit; end; end; result:=False; end; Procedure TChartAxis.SetTicks(Value:TDarkGrayPen); Begin FTicks.Assign(Value); end; Procedure TChartAxis.SetMinorTicks(Value:TDarkGrayPen); Begin FMinorTicks.Assign(Value); end; Procedure TChartAxis.SetTicksInner(Value:TDarkGrayPen); Begin FTicksInner.Assign(Value); end; Procedure TChartAxis.SetGrid(Value:TAxisGridPen); Begin FGrid.Assign(Value); end; Procedure TChartAxis.SetMinorGrid(Value:TChartHiddenPen); Begin FMinorGrid.Assign(Value); end; Procedure TChartAxis.SetGridCentered(Value:Boolean); Begin Grid.Centered:=Value; end; Procedure TChartAxis.SetAxis(Value:TChartAxisPen); Begin FAxis.Assign(Value); end; Function TChartAxis.IsPosStored:Boolean; begin result:=FPositionPercent<>0; end; Function TChartAxis.IsStartStored:Boolean; begin result:=FStartPosition<>0; end; Function TChartAxis.IsEndStored:Boolean; begin result:=FEndPosition<>100; end; Function TChartAxis.IsCustom:Boolean; begin result:=ParentChart.Axes.IndexOf(Self)>=TeeInitialCustomAxis; end; procedure TChartAxis.SetHorizontal(const Value: Boolean); begin ParentChart.SetBooleanProperty(FHorizontal,Value); SetCalcPosValue; end; procedure TChartAxis.SetOtherSide(const Value: Boolean); begin ParentChart.SetBooleanProperty(FOtherSide,Value); end; Function TChartAxis.CalcPosPoint(Value:Integer):Double; Function InternalCalcPos(Const A,B:Double):Double; begin if (Horizontal and FInverted) or ((not Horizontal) and (not FInverted)) then result:=A else result:=B end; var tmp : Double; Begin if FLogarithmic then Begin if Value=IStartPos then result:=InternalCalcPos(IMaximum,IMinimum) else if Value=IEndPos then result:=InternalCalcPos(IMinimum,IMaximum) else begin tmp:=IRangeLog; if (tmp=0) or (IAxisSize=0) then result:=IMinimum // 5.03 else begin if FInverted then tmp:=((IEndPos-Value)*tmp/IAxisSize) else tmp:=((Value-IStartPos)*tmp/IAxisSize); if Horizontal then result:=Exp(ILogMin+tmp) else result:=Exp(ILogMax-tmp); end; end; end else if IAxisSize>0 then begin if FInverted then tmp:=IEndPos-Value else tmp:=Value-IStartPos; tmp:=tmp*IRange/IAxisSize; if Horizontal then result:=IMinimum+tmp else result:=IMaximum-tmp; end else result:=0; end; Procedure TChartAxis.SetDateTimeFormat(Const Value:String); Begin ParentChart.SetStringProperty(FDateTimeFormat,Value); end; procedure TChartAxis.SetAxisTitle(Value:TChartAxisTitle); begin FAxisTitle.Assign(Value); end; procedure TChartAxis.SetStartPosition(Const Value:Double); begin ParentChart.SetDoubleProperty(FStartPosition,Value); end; procedure TChartAxis.SetEndPosition(Const Value:Double); begin ParentChart.SetDoubleProperty(FEndPosition,Value); end; procedure TChartAxis.SetPositionPercent(Const Value:Double); begin ParentChart.SetDoubleProperty(FPositionPercent,Value); end; procedure TChartAxis.SetRoundFirstLabel(Value:Boolean); begin ParentChart.SetBooleanProperty(FRoundFirstLabel,Value); end; Procedure TChartAxis.SetLabelsMultiLine(Value:Boolean); begin ParentChart.SetBooleanProperty(FLabelsMultiLine,Value); end; Procedure TChartAxis.SetLabelsExponent(Value:Boolean); begin ParentChart.SetBooleanProperty(FLabelsExponent,Value); end; procedure TChartAxis.SetZPosition(const Value: Double); begin ParentChart.SetDoubleProperty(FZPosition,Value); if FZPosition=0 then FZPosition:=0.01; // VCL bug double=0 streaming end; procedure TChartAxis.SetTickOnLabelsOnly(Value:Boolean); begin ParentChart.SetBooleanProperty(FTickOnLabelsOnly,Value); end; function TChartAxis.CalcDateTimeIncrement(MaxNumLabels:Integer):Double; var TempNumLabels : Integer; begin result:=Math.Max(FDesiredIncrement,DateTimeStep[Low(DateTimeStep)]); if (result>0) and (MaxNumLabels>0) then begin if (IRange/Result)>1000000 then Result:=IRange/1000000; Repeat TempNumLabels:=Round(IRange/result); if TempNumLabels>MaxNumLabels then if result<DateTimeStep[dtOneYear] then begin if result<DateTimeStep[dtOneSecond] then result:=TeeNextStep(result) // less than one second else result:=NextDateTimeStep(result) // regular datetime steps end else result:=2.0*result; // years Until (TempNumLabels<=MaxNumLabels){ or (result=DateTimeStep[dtOneYear])}; end; result:=Math.Max(result,DateTimeStep[Low(DateTimeStep)]); end; {$IFNDEF D6} function IsInfinite(const AValue: Double): Boolean; begin Result := ((PInt64(@AValue)^ and $7FF0000000000000) = $7FF0000000000000) and ((PInt64(@AValue)^ and $000FFFFFFFFFFFFF) = $0000000000000000); end; {$ENDIF} Function TChartAxis.RoundLogPower(const Value:Double):Double; begin result:=Power(LogarithmicBase,Round(LogN(LogarithmicBase,Value))); // 7.0 end; Function TChartAxis.CalcLabelsIncrement(MaxNumLabels:Integer):Double; procedure InternalCalcLabelsIncrement; Function AnySeriesHasLessThan(Num:Integer):Boolean; var t : Integer; begin result:=False; for t:=0 to ParentChart.SeriesCount-1 do with ParentChart[t] do if Active then if (YMandatory and Self.Horizontal) or ((not YMandatory) and (not Self.Horizontal)) then if AssociatedToAxis(Self) then begin result:=Count<=Num; if result then break; end; end; var TempNumLabels : Integer; tmp : Double; tmpInf : Boolean; begin TempNumLabels:=MaxNumLabels+1; if FDesiredIncrement<=0 then begin if IRange=0 then result:=1 else begin result:=Abs(IRange)/Succ(MaxNumLabels); if Logarithmic then result:=RoundLogPower(result); // 7.0 if AnySeriesHasLessThan(MaxNumLabels) then result:=Math.Max(1,result); end; end else result:=FDesiredIncrement; tmpInf:=False; if LabelsSeparation>0 then Repeat tmp:=IRange/result; if Abs(tmp)<MaxLongint then begin TempNumLabels:=Round(tmp); if TempNumLabels>MaxNumLabels then if Logarithmic then result:=result*LogarithmicBase else result:=TeeNextStep(result); end else if Logarithmic then result:=result*LogarithmicBase else result:=TeeNextStep(result); tmpInf:=IsInfinite(result); Until (TempNumLabels<=MaxNumLabels) or (result>IRange) or tmpInf; if tmpInf then result:=IRange else result:=Math.Max(result,MinAxisIncrement); end; Begin if MaxNumLabels>0 then Begin if IAxisDateTime then result:=CalcDateTimeIncrement(MaxNumLabels) else InternalCalcLabelsIncrement; end else if IAxisDateTime then result:=DateTimeStep[Low(DateTimeStep)] else result:=MinAxisIncrement; end; Function TChartAxis.LabelWidth(Const Value:Double):Integer; begin result:=InternalLabelSize(Value,True); end; Function TChartAxis.LabelHeight(Const Value:Double):Integer; begin result:=InternalLabelSize(Value,False); end; Function TChartAxis.InternalLabelSize(Const Value:Double; IsWidth:Boolean):Integer; var tmp : Integer; tmpMulti : Boolean; Begin result:=ParentChart.MultiLineTextWidth(LabelValue(Value),tmp); if IsWidth then tmpMulti:=(FLabelsAngle=90) or (FLabelsAngle=270) else tmpMulti:=(FLabelsAngle=0) or (FLabelsAngle=180); if tmpMulti then result:=ParentChart.Canvas.FontHeight*tmp; end; Function TChartAxis.IsMaxStored:Boolean; Begin { dont store max property if automatic } result:=(not FAutomatic) and (not FAutomaticMaximum); end; Function TChartAxis.IsMinStored:Boolean; Begin{ dont store min property if automatic } result:=(not FAutomatic) and (not FAutomaticMinimum); end; Function TChartAxis.CalcXYIncrement(MaxLabelSize:Integer):Double; var tmp : Integer; begin if MaxLabelSize>0 then begin if FLabelsSeparation>0 then Inc(MaxLabelSize,Round(0.01*FLabelsSeparation*MaxLabelSize)); tmp:=Round((1.0*IAxisSize)/MaxLabelSize) end else tmp:=1; result:=CalcLabelsIncrement(tmp) end; Function TChartAxis.CalcIncrement:Double; begin result:=CalcXYIncrement(Math.Max(InternalLabelSize(IMinimum,Horizontal), InternalLabelSize(IMaximum,Horizontal))); if LabelsAlternate then if Logarithmic then result:=result/LogarithmicBase else result:=result*0.5; end; Procedure TChartAxis.AdjustMaxMinRect(Const Rect:TRect); Var tmpMin : Double; tmpMax : Double; Procedure RecalcAdjustedMinMax(Pos1,Pos2:Integer); Var OldStart : Integer; OldEnd : Integer; Begin OldStart :=IStartPos; OldEnd :=IEndPos; Inc(IStartPos,Pos1); Dec(IEndPos,Pos2); IAxisSize:=IEndPos-IStartPos; tmpMin:=CalcPosPoint(OldStart); tmpMax:=CalcPosPoint(OldEnd); end; Begin With ParentChart do begin with Rect do if Horizontal then ReCalcAdjustedMinMax(Left,Right) else ReCalcAdjustedMinMax(Top,Bottom); InternalCalcPositions; IMaximum:=tmpMax; IMinimum:=tmpMin; end; if IMinimum>IMaximum then SwapDouble(IMinimum,IMaximum); InternalCalcRange; end; Procedure TChartAxis.CalcMinMax(Var AMin,AMax:Double); Begin if FAutomatic or FAutomaticMaximum then AMax:=ParentChart.InternalMinMax(Self,False,Horizontal); if FAutomatic or FAutomaticMinimum then AMin:=ParentChart.InternalMinMax(Self,True,Horizontal); end; Procedure TChartAxis.InternalCalcRange; begin IRange:=IMaximum-IMinimum; IRangeZero:=IRange=0; if IRangeZero then IAxisSizeRange:=0 else IAxisSizeRange:=IAxisSize/IRange; if FLogarithmic then begin if IMinimum<=0 then ILogMin:=0 else ILogMin:=ln(IMinimum); if IMaximum<=0 then ILogMax:=0 else ILogMax:=ln(IMaximum); IRangeLog:=ILogMax-ILogMin; if IRangeLog=0 then IAxisLogSizeRange:=0 else IAxisLogSizeRange:=IAxisSize/IRangeLog; end; IZPos:=CalcZPos; end; Procedure TChartAxis.AdjustMaxMin; Begin CalcMinMax(FMinimumValue,FMaximumValue); IMaximum:=FMaximumValue; IMinimum:=FMinimumValue; InternalCalcRange; end; procedure TChartAxis.Assign(Source: TPersistent); Begin if Source is TChartAxis then With TChartAxis(Source) do Begin Self.FAxis.Assign(FAxis); Self.FItems.CopyFrom(FItems); Self.FLabelsAlign :=FLabelsAlign; Self.FLabelsAlternate :=FLabelsAlternate; Self.FLabelsAngle :=FLabelsAngle; Self.FLabelsExponent :=FLabelsExponent; Self.FLabelsMultiLine :=FLabelsMultiLine; Self.FLabelsSeparation :=FLabelsSeparation; Self.FLabelsSize :=FLabelsSize; Self.FLabelStyle :=FLabelStyle; Self.FLabelsOnAxis :=FLabelsOnAxis; Self.Ticks :=FTicks; Self.TicksInner :=FTicksInner; Self.FTitleSize :=FTitleSize; Self.Grid :=FGrid; Self.MinorTicks :=FMinorTicks; Self.MinorGrid :=FMinorGrid; Self.FTickLength :=FTickLength; Self.FMinorTickLength :=FMinorTickLength; Self.FMinorTickCount :=FMinorTickCount; Self.FTickInnerLength :=FTickInnerLength; Self.FAxisValuesFormat :=FAxisValuesFormat; Self.FDesiredIncrement :=FDesiredIncrement; Self.FMaximumValue :=FMaximumValue; Self.FMaximumOffset :=FMaximumOffset; Self.FMinimumValue :=FMinimumValue; Self.FMinimumOffset :=FMinimumOffset; Self.FAutomatic :=FAutomatic; Self.FAutomaticMaximum :=FAutomaticMaximum; Self.FAutomaticMinimum :=FAutomaticMinimum; Self.Title :=FAxisTitle; Self.FDateTimeFormat :=FDateTimeFormat; Self.GridCentered :=GridCentered; Self.FLogarithmic :=FLogarithmic; Self.FLogarithmicBase :=FLogarithmicBase; Self.FInverted :=FInverted; Self.FExactDateTime :=FExactDateTime; Self.FRoundFirstLabel :=FRoundFirstLabel; Self.FTickOnLabelsOnly :=FTickOnLabelsOnly; Self.IDepthAxis :=IDepthAxis; Self.FStartPosition :=FStartPosition; Self.FEndPosition :=FEndPosition; Self.FPositionPercent :=FPositionPercent; Self.FPosUnits :=FPosUnits; Self.FVisible :=FVisible; Self.FHorizontal :=FHorizontal; Self.FOtherSide :=FOtherSide; end else inherited; end; Function TChartAxis.LabelValue(Const Value:Double):String; var tmp : String; Begin if IAxisDateTime then begin if Value>=0 then Begin if FDateTimeFormat='' then tmp:=DateTimeDefaultFormat(IRange) else tmp:=FDateTimeFormat; DateTimeToString(result,tmp,Value); end else result:=''; end else result:=FormatFloat(FAxisValuesFormat,Value); if Assigned(ParentChart.FOnGetAxisLabel) then ParentChart.FOnGetAxisLabel(TChartAxis(Self),nil,-1,Result); if FLabelsMultiLine then result:=ReplaceChar(result,' ',TeeLineSeparator); end; Function TChartAxis.InternalCalcLabelStyle:TAxisLabelStyle; var t : Integer; begin result:=talNone; for t:=0 to ParentChart.SeriesCount-1 do With ParentChart.Series[t] do if Active and AssociatedToAxis(Self) then begin result:=talValue; if not HasZValues then // 7.0 (ie: MapSeries should not use text) if (Horizontal and YMandatory) or ((not Horizontal) and (not YMandatory)) then if (FLabels.Count>0) and (FLabels.First<>nil) then begin result:=talText; break; end; end; end; Function TChartAxis.CalcLabelStyle:TAxisLabelStyle; Begin if FLabelStyle=talAuto then result:=InternalCalcLabelStyle else result:=FLabelStyle; End; Function TChartAxis.MaxLabelsWidth:Integer; Function MaxLabelsValueWidth:Integer; var tmp : Double; tmpA : Double; tmpB : Double; OldGetAxisLabel : TAxisOnGetLabel; tmpNum : Integer; begin if (IsDateTime and FExactDateTime) or RoundFirstLabel then begin tmp:=CalcIncrement; tmpA:=tmp*Int(IMinimum/tmp); tmpB:=tmp*Int(IMaximum/tmp); end else begin tmpA:=IMinimum; tmpB:=IMaximum; end; With ParentChart do begin OldGetAxisLabel:=FOnGetAxisLabel; FOnGetAxisLabel:=nil; With Canvas do result:=TextWidth(' ')+ Math.Max(MultiLineTextWidth(LabelValue(tmpA),tmpNum), MultiLineTextWidth(LabelValue(tmpB),tmpNum)); FOnGetAxisLabel:=OldGetAxisLabel; end; end; var t : Integer; tmp : Integer; begin if Items.Count=0 then Case CalcLabelStyle of talValue : result:=MaxLabelsValueWidth; talMark : result:=ParentChart.MaxMarkWidth; talText : result:=ParentChart.MaxTextWidth; else {talNone : } result:=0; end else begin result:=0; for t:=0 to Items.Count-1 do begin ParentChart.Canvas.AssignFont(Items[t].Font); result:=Max(result,ParentChart.MultiLineTextWidth(Items[t].Text,tmp)); end; end; end; Function TChartAxis.GetLabels:Boolean; begin result:=FItems.Format.Visible; end; Function TChartAxis.GetLabelsFont:TTeeFont; begin result:=FItems.Format.Font; end; Procedure TChartAxis.SetLabels(Value:Boolean); Begin FItems.Format.Visible:=Value; end; Procedure TChartAxis.SetLabelsFont(Value:TTeeFont); begin FItems.Format.Font:=Value; end; Function TChartAxis.DepthAxisAlign:Integer; begin if OtherSide then result:=TA_LEFT else result:=TA_RIGHT; end; Function TChartAxis.DepthAxisPos:Integer; begin if OtherSide then result:=ParentChart.ChartRect.Bottom else result:=ParentChart.ChartRect.Top end; Procedure TChartAxis.SetAutomatic(Value:Boolean); Begin ParentChart.SetBooleanProperty(FAutomatic,Value); if not (csLoading in ParentChart.ComponentState) then begin FAutomaticMinimum:=Value; FAutomaticMaximum:=Value; end; end; Procedure TChartAxis.SetAutoMinMax(Var Variable:Boolean; Var2,Value:Boolean); Begin ParentChart.SetBooleanProperty(Variable,Value); if Value then begin { if both are automatic, then Automatic should be True too } if Var2 then FAutomatic:=True; end else FAutomatic:=False; end; Procedure TChartAxis.SetAutomaticMinimum(Value:Boolean); Begin SetAutoMinMax(FAutomaticMinimum,FAutomaticMaximum,Value); end; Procedure TChartAxis.SetAutomaticMaximum(Value:Boolean); Begin SetAutoMinMax(FAutomaticMaximum,FAutomaticMinimum,Value); end; Function TChartAxis.IsAxisValuesFormatStored:Boolean; begin result:=FAxisValuesFormat<>TeeMsg_DefValueFormat; end; Procedure TChartAxis.SetValuesFormat(Const Value:String); Begin ParentChart.SetStringProperty(FAxisValuesFormat,Value); end; Procedure TChartAxis.SetInverted(Value:Boolean); Begin ParentChart.SetBooleanProperty(FInverted,Value); end; Procedure TChartAxis.InternalSetInverted(Value:Boolean); Begin FInverted:=Value; end; Procedure TChartAxis.SetLogarithmicBase(const Value:Double); begin if (Value=1) or (Value<=0) then raise AxisException.Create(TeeMsg_AxisLogBase); ParentChart.SetDoubleProperty(FLogarithmicBase,Value); end; Procedure TChartAxis.SetLogarithmic(Value:Boolean); Begin if Value and IsDateTime then Raise AxisException.Create(TeeMsg_AxisLogDateTime); if Value then begin AdjustMaxMin; if ((IMinimum<0) or (IMaximum<0)) then Raise AxisException.Create(TeeMsg_AxisLogNotPositive); end; ParentChart.SetBooleanProperty(FLogarithmic,Value); SetCalcPosValue; end; Procedure TChartAxis.SetCalcPosValue; begin if IDepthAxis then begin CalcXPosValue:=InternalCalcDepthPosValue; CalcYPosValue:=InternalCalcDepthPosValue; end else if Logarithmic then begin CalcXPosValue:=LogXPosValue; CalcYPosValue:=LogYPosValue; end else begin if ParentChart.Axes.IFastCalc then begin CalcXPosValue:=XPosValue; CalcYPosValue:=YPosValue; end else begin CalcXPosValue:=XPosValueCheck; CalcYPosValue:=YPosValueCheck; end; end; if Horizontal then CalcPosValue:=CalcXPosValue else CalcPosValue:=CalcYPosValue; end; Procedure TChartAxis.SetLabelsAlign(Value:TAxisLabelAlign); Begin if FLabelsAlign<>Value then begin FLabelsAlign:=Value; ParentChart.Invalidate; end; end; Procedure TChartAxis.SetLabelsAlternate(Value:Boolean); Begin ParentChart.SetBooleanProperty(FLabelsAlternate,Value); end; Procedure TChartAxis.SetLabelsAngle(const Value:Integer); Begin ParentChart.SetIntegerProperty(FLabelsAngle,Value mod 360); end; Procedure TChartAxis.SetLabelsSeparation(Value:Integer); Begin if Value<0 then Raise AxisException.Create(TeeMsg_AxisLabelSep); ParentChart.SetIntegerProperty(FLabelsSeparation,Value); end; Procedure TChartAxis.SetLabelsSize(Value:Integer); Begin ParentChart.SetIntegerProperty(FLabelsSize,Value); end; Procedure TChartAxis.SetTitleSize(Value:Integer); Begin ParentChart.SetIntegerProperty(FTitleSize,Value); end; Procedure TChartAxis.SetLabelsOnAxis(Value:Boolean); Begin ParentChart.SetBooleanProperty(FLabelsOnAxis,Value); end; Procedure TChartAxis.SetExactDateTime(Value:Boolean); begin ParentChart.SetBooleanProperty(FExactDateTime,Value); end; Procedure TChartAxis.SetLabelStyle(Value:TAxisLabelStyle); begin if FLabelStyle<>Value then begin FLabelStyle:=Value; ParentChart.Invalidate; end; end; Procedure TChartAxis.SetVisible(Value:Boolean); Begin ParentChart.SetBooleanProperty(FVisible,Value); end; Procedure TChartAxis.SetDesiredIncrement(Const Value:Double); Begin {$IFNDEF CLR} if Value<0 then Raise AxisException.Create(TeeMsg_AxisIncrementNeg); {$ENDIF} if IsDateTime then DateTimeToStr(Value); ParentChart.SetDoubleProperty(FDesiredIncrement,Value); end; Procedure TChartAxis.SetMinimum(Const Value:Double); Begin if (not (csReading in ParentChart.ComponentState)) and (Value>FMaximumValue) then Raise AxisException.Create(TeeMsg_AxisMinMax); InternalSetMinimum(Value); end; Procedure TChartAxis.InternalSetMinimum(Const Value:Double); Begin ParentChart.SetDoubleProperty(FMinimumValue,Value); end; Procedure TChartAxis.SetMaximum(Const Value:Double); Begin if (not (csReading in ParentChart.ComponentState)) and (Value<FMinimumValue) then Raise AxisException.Create(TeeMsg_AxisMaxMin); InternalSetMaximum(Value); end; Procedure TChartAxis.SetMinMax(AMin,AMax:Double); Begin FAutomatic:=False; FAutomaticMinimum:=False; FAutomaticMaximum:=False; if AMin>AMax then SwapDouble(AMin,AMax); InternalSetMinimum(AMin); InternalSetMaximum(AMax); if (FMaximumValue-FMinimumValue)<MinAxisRange then InternalSetMaximum(FMinimumValue+MinAxisRange); ParentChart.CustomAxes.ResetScales(Self); end; Procedure TChartAxis.InternalSetMaximum(Const Value:Double); Begin ParentChart.SetDoubleProperty(FMaximumValue,Value); end; Procedure TChartAxis.SetTickLength(Value:Integer); Begin ParentChart.SetIntegerProperty(FTickLength,Value); end; Procedure TChartAxis.SetMinorTickLength(Value:Integer); Begin ParentChart.SetIntegerProperty(FMinorTickLength,Value); end; Procedure TChartAxis.SetMinorTickCount(Value:Integer); Begin ParentChart.SetIntegerProperty(FMinorTickCount,Value); End; Procedure TChartAxis.SetTickInnerLength(Value:Integer); Begin ParentChart.SetIntegerProperty(FTickInnerLength,Value); end; Procedure TChartAxis.DrawTitle(x,y:Integer); var Old : Boolean; begin With ParentChart,Canvas do begin AssignFont(FAxisTitle.Font); BackMode:=cbmTransparent; if IsDepthAxis then begin TextAlign:=DepthAxisAlign; TextOut3D(x,y,Width3D div 2,FAxisTitle.FCaption); end else begin Old:=FLabelsExponent; FLabelsExponent:=False; // 5.02 DrawAxisLabel(x,y,FAxisTitle.FAngle,FAxisTitle.FCaption); FLabelsExponent:=Old; end; end; end; // pending: cache into variable (for speed) Function TChartAxis.CalcZPos:Integer; begin if IDepthAxis then result:=ParentChart.ChartHeight else result:=ParentChart.Width3D; result:=Round(result*ZPosition*0.01); // 6.0 end; procedure TChartAxis.DrawAxisLabel(x,y,Angle:Integer; Const St:String; Format:TTeeCustomShape=nil); Const Aligns:Array[Boolean,Boolean] of Integer=( (TA_RIGHT +TA_TOP, TA_LEFT +TA_TOP ), { vertical } (TA_CENTER+TA_TOP, TA_CENTER+TA_BOTTOM ) ); { horizontal } Var tmpSt2 : String; tmpZ : Integer; Procedure DrawExponentLabel; var tmpW : Integer; tmpH : Integer; i : Integer; tmp : String; tmpSub : String; Old : Integer; begin i:=Pos('E',Uppercase(tmpSt2)); With ParentChart.Canvas do if i=0 then TextOut3D(x,y,tmpZ,tmpSt2) else begin tmp:=Copy(tmpSt2,1,i-1); tmpSub:=Copy(tmpSt2,i+1,Length(tmpSt2)-1); tmpH:=FontHeight-1; Old:=Font.Size; if TextAlign=TA_LEFT then begin TextOut3D(x,y,tmpZ,tmp); tmpW:=TextWidth(tmp)+1; Font.Size:=Font.Size-(Font.Size div 4); TextOut3D(x+tmpW,y-(tmpH div 2)+2,tmpZ,tmpSub); end else begin Font.Size:=Font.Size-(Font.Size div 4); TextOut3D(x,y-(tmpH div 2)+2,tmpZ,tmpSub); tmpW:=TextWidth(tmpSub)+1; Font.Size:=Old; TextOut3D(x-tmpW,y,tmpZ,tmp); end; Font.Size:=Old; end; end; { Returns 1 + how many times "TeeLineSeparator #13" is found inside string St parameter } Function TeeNumTextLines(St:String):Integer; var i : Integer; begin result:=0; i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,St); while i>0 do begin Inc(result); Delete(St,1,i); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,St); end; if St<>'' then Inc(result); end; var Delta : Integer; t : Integer; n : Integer; i : Integer; tmp : Double; tmpSt : String; tmpH : Integer; tmpD : Integer; tmpAlign : TCanvasTextAlign; tmpAlign2: TCanvasTextAlign; tmpW : Integer; tmpNum : Integer; tmpSize : Integer; tmpDraw : Boolean; begin tmpH:=ParentChart.Canvas.FontHeight div 2; Case Angle of 0,360: begin if Horizontal or (FLabelsAlign=alDefault) then tmpAlign:=Aligns[Horizontal,OtherSide] else if OtherSide then begin tmpAlign:=TA_RIGHT; Inc(X,SizeLabels); end else begin tmpAlign:=TA_LEFT; Dec(X,SizeLabels); end; if not Horizontal then Dec(Y,tmpH); end; 90: begin if Horizontal then begin tmpAlign:=Aligns[False,OtherSide]; Dec(X,tmpH); end else tmpAlign:=Aligns[True,not OtherSide]; end; 180: begin tmpAlign:=Aligns[Horizontal,not OtherSide]; if not Horizontal then Inc(Y,tmpH); end; 270: begin if Horizontal then begin tmpAlign:=Aligns[False,not OtherSide]; Inc(X,tmpH); end else tmpAlign:=Aligns[True,OtherSide]; end; 45: begin // 5.03 tmpAlign:=TA_LEFT; if Horizontal then begin if OtherSide then begin i:=Round(ParentChart.Canvas.TextWidth('Wj')); Dec(x,i); Dec(y,i); end else begin tmp:=Sin(Angle*TeePiStep); i:=Round(ParentChart.Canvas.TextWidth(St)*tmp); Dec(x,i); Inc(y,i); end; end; end; else begin tmpAlign:=TA_LEFT; { non-supported angles } end; end; tmpZ:=IZPos; // 6.0 n:=TeeNumTextLines(St); Delta:=ParentChart.Canvas.FontHeight; if (Angle=180) or (Angle=270) then Delta:=-Delta; tmpD:=Round(Delta*n); if Horizontal then begin if Angle=0 then if OtherSide then y:=y-tmpD else y:=y-Delta else if Angle=180 then if OtherSide then y:=y-Delta else y:=y-tmpD else if (Angle=90) or (Angle=270) then x:=x-Round(0.5*Delta*(n+1)); end else if (Angle=0) or (Angle=180) then y:=y-Round(0.5*Delta*(n+1)) else if OtherSide then begin if Angle=90 then x:=x-Delta else if Angle=270 then x:=x-tmpD end else if Angle=90 then x:=x-tmpD else if Angle=270 then x:=x-Delta; // 6.0 if not Assigned(Format) then Format:=FItems.Format; with Format do if not Transparent then begin with ShapeBounds do begin tmpSize:=Self.ParentChart.Canvas.TextWidth('W') shr 1; Left:=x; Top:=y+Delta; tmpW:=Self.ParentChart.MultiLineTextWidth(St,tmpNum); tmpH:=ParentChart.Canvas.FontHeight*tmpNum; tmpAlign2:=tmpAlign; if tmpAlign2>=TA_BOTTOM then begin Dec(Top,tmpH); Dec(tmpAlign2,TA_BOTTOM); end; Bottom:=Top+tmpH; Right:=Left+tmpW; if tmpAlign2=TA_RIGHT then begin Right:=Left; Left:=Right-tmpW; end else if tmpAlign2=TA_CENTER then begin tmpW:=(Right-Left) div 2; Dec(Right,tmpW); Dec(Left,tmpW); end; Dec(Left,tmpSize); Inc(Right,tmpSize); end; if tmpZ<>0 then ShapeBounds:=ParentChart.Canvas.CalcRect3D(ShapeBounds,tmpZ); DrawRectRotated(ShapeBounds,FLabelsAngle,tmpZ); with ParentChart.Canvas do begin // trick Brush.Style:=bsSolid; Brush.Style:=bsClear; {$IFDEF CLX} BackMode:=cbmTransparent; {$ENDIF} end; end; ParentChart.Canvas.TextAlign:=tmpAlign; tmpSt:=St; tmpDraw:=True; if Assigned(FOnDrawLabel) then // 7.0 begin FOnDrawLabel(Self,X,Y,tmpZ,tmpSt,tmpDraw); if tmpDraw then n:=TeeNumTextLines(tmpSt); end; if tmpDraw then // 7.0 for t:=1 to n do begin i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,tmpSt); if i>0 then tmpSt2:=Copy(tmpSt,1,i-1) else tmpSt2:=tmpSt; if Angle=0 then begin y:=y+Delta; if FLabelsExponent then DrawExponentLabel else ParentChart.Canvas.TextOut3D(X,Y,tmpZ,tmpSt2); end else begin if Angle=180 then y:=y+Delta else if (Angle=90) or (Angle=270) then x:=x+Delta; ParentChart.Canvas.RotateLabel3D(X,Y,tmpZ,tmpSt2,Angle); end; Delete(tmpSt,1,i); end; ParentChart.Canvas.TextAlign:=TA_LEFT; end; Procedure TChartAxis.Scroll(Const Offset:Double; CheckLimits:Boolean=False); Begin if (not CheckLimits) or ( ((Offset>0) and (FMaximumValue<ParentChart.InternalMinMax(Self,False,Horizontal))) or ((Offset<0) and (FMinimumValue>ParentChart.InternalMinMax(Self,True,Horizontal))) ) then begin FAutomatic:=False; FAutomaticMaximum:=False; FMaximumValue:=FMaximumValue+Offset; FAutomaticMinimum:=False; FMinimumValue:=FMinimumValue+Offset; ParentChart.Invalidate; end; end; Function TChartAxis.InternalCalcDepthPosValue(Const Value:TChartValue):Integer; begin if IRangeZero then result:=ICenterPos else if FInverted then result:=Round(IAxisSizeRange*(IMaximum-Value)) else result:=Round(IAxisSizeRange*(Value-IMinimum)); end; Function TChartAxis.LogXPosValue(Const Value:TChartValue):Integer; begin if IRangeLog=0 then result:=ICenterPos else begin if Value<=0 then if FInverted then result:=IEndPos else result:=IStartPos else begin if FInverted then result:=Round((ILogMax-ln(Value))*IAxisLogSizeRange) else result:=Round((ln(Value)-ILogMin)*IAxisLogSizeRange); result:=IStartPos+result; end; end; end; Function TChartAxis.LogYPosValue(Const Value:TChartValue):Integer; begin if IRangeLog=0 then result:=ICenterPos else begin if Value<=0 then if not FInverted then result:=IEndPos else result:=IStartPos else begin if FInverted then result:=Round((ILogMax-ln(Value))*IAxisLogSizeRange) else result:=Round((ln(Value)-ILogMin)*IAxisLogSizeRange); result:=IEndPos-result; end; end; end; // The following routines perform axis calculations WITH overflow checking // to avoid Windows GDI limits on pixel coordinates. // See below for faster routines. // // To switch between slow and fast, use Chart1.Axes.FastCalc property. var TeeMaxPixelPos:Integer=0; Function TChartAxis.XPosValueCheck(Const Value:TChartValue):Integer; var tmp : Double; begin if IRangeZero then result:=ICenterPos else begin tmp:=(Value-IMinimum)*IAxisSizeRange; if FInverted then tmp:=IEndPos-tmp else tmp:=IStartPos+tmp; if tmp> TeeMaxPixelPos then result:=TeeMaxPixelPos else if tmp<-TeeMaxPixelPos then result:=-TeeMaxPixelPos else result:=Round(tmp); end; end; Function TChartAxis.YPosValueCheck(Const Value:TChartValue):Integer; var tmp : Double; begin if IRangeZero then result:=ICenterPos else begin tmp:=(Value-IMinimum)*IAxisSizeRange; if FInverted then tmp:=IStartPos+tmp else tmp:=IEndPos-tmp; if tmp> TeeMaxPixelPos then result:= TeeMaxPixelPos else if tmp<-TeeMaxPixelPos then result:=-TeeMaxPixelPos else result:=Round(tmp); end; end; // The following routines perform axis calculations WITHOUT overflow checking. // These are 5 to 10% faster than the above ones. // See above for slower (with checking) routines. // // To switch between slow and fast, use Chart1.Axes.FastCalc property. Function TChartAxis.XPosValue(Const Value:TChartValue):Integer; begin if IRangeZero then result:=ICenterPos else begin {$IFNDEF TEENOASM} asm fld Value fsub qword ptr [eax+IMinimum] {$IFDEF TEEVALUESINGLE} fmul dword ptr [eax+IAxisSizeRange] sub esp, 4 fistp dword ptr [esp] pop [result] {$ELSE} fmul qword ptr [eax+IAxisSizeRange] sub esp, 8 fistp qword ptr [esp] pop [result] pop ecx {$ENDIF} end; if Inverted then result:=IEndPos -result else Inc(result,IStartPos); {$ELSE} if FInverted then result:=IEndPos -Round( (Value-IMinimum)*IAxisSizeRange ) else result:=IStartPos+Round( (Value-IMinimum)*IAxisSizeRange ); {$ENDIF} end; end; Function TChartAxis.YPosValue(Const Value:TChartValue):Integer; begin if IRangeZero then result:=ICenterPos else begin {$IFNDEF TEENOASM} asm fld Value fsub qword ptr [eax+IMinimum] {$IFDEF TEEVALUESINGLE} fmul dword ptr [eax+IAxisSizeRange] sub esp, 4 fistp dword ptr [esp] pop [result] {$ELSE} fmul qword ptr [eax+IAxisSizeRange] sub esp, 8 fistp qword ptr [esp] pop [result] pop ecx {$ENDIF} end; if Inverted then Inc(result,IStartPos) else result:=IEndPos -result; {$ELSE} if FInverted then result:=IStartPos+Round( (Value-IMinimum)*IAxisSizeRange ) else result:=IEndPos -Round( (Value-IMinimum)*IAxisSizeRange ) {$ENDIF} end; end; Function TChartAxis.CalcSizeValue(Const Value:Double):Integer; begin result:=0; if Value>0 then if FLogarithmic then Begin if IRangeLog<>0 then result:=Round(ln(Value)*IAxisLogSizeRange); end else if IRange<>0 then result:=Round(Value*IAxisSizeRange); end; Function TChartAxis.AxisRect:TRect; Var tmpPos1 : Integer; Pos1 : Integer; tmpPos2 : Integer; Pos2 : Integer; begin if IStartPos>IEndPos then begin tmpPos1:=IEndPos; tmpPos2:=IStartPos; end else begin tmpPos1:=IStartPos; tmpPos2:=IEndPos; end; if PosAxis>FPosLabels then begin Pos1:=FPosLabels; Pos2:=PosAxis+TeeAxisClickGap; end else begin Pos1:=PosAxis-TeeAxisClickGap; Pos2:=FPosLabels; end; if Horizontal then result:=TeeRect(tmpPos1,Pos1,tmpPos2,Pos2) else result:=TeeRect(Pos1,tmpPos1,Pos2,tmpPos2); end; Function TChartAxis.Clicked(x,y:Integer):Boolean; var tmpR : TRect; tmpZ : Integer; Begin result:=ParentChart.IsAxisVisible(Self); if result then begin if ParentChart.View3D then begin if OtherSide then tmpZ:=ParentChart.Width3D else tmpZ:=0; tmpR:=ParentChart.Canvas.CalcRect3D(AxisRect,tmpZ); end else tmpR:=AxisRect; result:=PointInRect(tmpR,x,y); // pending: DepthAxis and click hit detection with 3D rotation. end; end; Procedure TChartAxis.CustomDrawMinMaxStartEnd( APosLabels, APosTitle, APosAxis:Integer; GridVisible:Boolean; Const AMinimum,AMaximum, AIncrement:Double; AStartPos,AEndPos:Integer); Procedure SetInternals; begin IMaximum :=FMaximumValue; IMinimum :=FMinimumValue; InternalCalcRange; end; var OldMin : Double; OldMax : Double; OldIncrement : Double; OldAutomatic : Boolean; begin OldMin :=FMinimumValue; OldMax :=FMaximumValue; OldIncrement:=FDesiredIncrement; OldAutomatic:=FAutomatic; try FAutomatic :=False; FMinimumValue :=AMinimum; FMaximumValue :=AMaximum; FDesiredIncrement:=AIncrement; SetInternals; CustomDrawStartEnd(APosLabels,APosTitle,APosAxis,GridVisible,AStartPos,AEndPos); finally FMinimumValue :=OldMin; FMaximumValue :=OldMax; FDesiredIncrement:=OldIncrement; FAutomatic :=OldAutomatic; SetInternals; end; end; Procedure TChartAxis.CustomDrawMinMax( APosLabels, APosTitle, APosAxis:Integer; GridVisible:Boolean; Const AMinimum,AMaximum, AIncrement:Double); begin CustomDrawMinMaxStartEnd(APosLabels,APosTitle,APosAxis,GridVisible, AMinimum,AMaximum,AIncrement,IStartPos,IEndPos); end; Procedure TChartAxis.CustomDraw( APosLabels,APosTitle,APosAxis:Integer; GridVisible:Boolean); begin InternalCalcPositions; CustomDrawStartEnd(APosLabels,APosTitle,APosAxis,GridVisible,IStartPos,IEndPos); End; Procedure TChartAxis.CustomDrawStartEnd( APosLabels,APosTitle,APosAxis:Integer; GridVisible:Boolean; AStartPos,AEndPos:Integer); var OldGridVisible : Boolean; OldChange : TNotifyEvent; Begin FPosLabels:=APosLabels; FPosTitle :=APosTitle; FPosAxis :=APosAxis; IStartPos :=AStartPos; IEndPos :=AEndPos; RecalcSizeCenter; OldGridVisible:=FGrid.Visible; OldChange:=FGrid.OnChange; FGrid.OnChange:=nil; FGrid.Visible:=GridVisible; Draw(False); FGrid.Visible:=OldGridVisible; FGrid.OnChange:=OldChange; end; Procedure TChartAxis.RecalcSizeCenter; begin IAxisSize:=IEndPos-IStartPos; ICenterPos:=(IStartPos+IEndPos) div 2; InternalCalcRange; end; Procedure TChartAxis.InternalCalcPositions; Procedure DoCalculation(AStartPos:Integer; ASize:Integer); begin IStartPos:=AStartPos+Round(0.01*ASize*FStartPosition); IEndPos:=AStartPos+Round(0.01*ASize*FEndPosition); end; begin With ParentChart do if IsDepthAxis then DoCalculation(0,Width3D) else if Horizontal then DoCalculation(ChartRect.Left,ChartWidth) else DoCalculation(ChartRect.Top,ChartHeight); RecalcSizeCenter; end; Function TChartAxis.ApplyPosition(APos:Integer; Const R:TRect):Integer; Var tmpSize : Integer; begin result:=APos; if FPositionPercent<>0 then With R do begin if FPosUnits=muPercent then begin if Horizontal then tmpSize:=Bottom-Top else tmpSize:=Right-Left; tmpSize:=Round(0.01*FPositionPercent*tmpSize); end else tmpSize:=Round(FPositionPercent); // pixels if OtherSide then tmpSize:=-tmpSize; if Horizontal then tmpSize:=-tmpSize; result:=APos+tmpSize; end; end; Function TChartAxis.GetRectangleEdge(Const R:TRect):Integer; begin With R do if OtherSide then if Horizontal then result:=Top else result:=Right else if Horizontal then result:=Bottom else result:=Left; end; Procedure TChartAxis.DrawGridLine(tmp:Integer); var tmpZ : Integer; begin if (tmp>IStartPos) and (tmp<IEndPos) then With ParentChart,Canvas,ChartRect do begin if IsDepthAxis then begin VertLine3D(Left,Top,Bottom,tmp); HorizLine3D(Left,Right,Bottom,tmp); end else begin if View3D then begin if AxisBehind then begin if not IHideBackGrid then { 6.0 } if Horizontal then VertLine3D(tmp,Top,Bottom,Width3D) else HorizLine3D(Left,Right,tmp,Width3D); if not IHideSideGrid then begin tmpZ:=Round(Width3D*Grid.ZPosition*0.01); // 6.0 if (tmpZ<>Width3D) then if Horizontal then ZLine3D(tmp,PosAxis,tmpZ,Width3D) else ZLine3D(PosAxis,tmp,tmpZ,Width3D); end; end else if Horizontal then VertLine3D(tmp,Top,Bottom,0) // in-front grid else HorizLine3D(Left,Right,tmp,0); // in-front grid end else if Horizontal then DoVertLine(tmp,Top+1,Bottom) { 5.02 (+1) } else DoHorizLine(Left+1,Right,tmp); { 5.02 (+1) } end; end; end; Procedure TChartAxis.DrawGrids(NumTicks:Integer); var t : Integer; begin if Assigned(OnDrawGrids) then OnDrawGrids(Self); if FGrid.Visible then begin With ParentChart,Canvas do begin BackMode:=cbmTransparent; if FGrid.Color=clTeeColor then AssignVisiblePenColor(FGrid,clGray) else AssignVisiblePen(FGrid); CheckPenWidth(Pen); end; for t:=0 to NumTicks-1 do if Grid.Centered then begin if t>0 then DrawGridLine(Round(0.5*(Tick[t]+Tick[t-1]))) end else DrawGridLine(Tick[t]); end; end; type TTeeMinorTickProc=Procedure(AMinorTickPos:Integer); Procedure TChartAxis.Draw(CalcPosAxis:Boolean); Var tmpValue : Double; tmpNumTicks : Integer; Procedure DrawTicksGrid; Var tmpWallSize : Integer; Procedure InternalDrawTick(tmp,Delta,tmpTickLength:Integer); Begin with ParentChart,Canvas do Begin if IsDepthAxis then if OtherSide then HorizLine3D(PosAxis+Delta,PosAxis+Delta+tmpTickLength,DepthAxisPos,tmp) else HorizLine3D(PosAxis-Delta,PosAxis-Delta-tmpTickLength,DepthAxisPos,tmp) else if OtherSide then Begin if Horizontal then VertLine3D(tmp,PosAxis-Delta,PosAxis-Delta-tmpTickLength,IZPos) else begin Inc(Delta,tmpWallSize); HorizLine3D(PosAxis+Delta,PosAxis+Delta+tmpTickLength,tmp,IZPos) end; end else begin Inc(Delta,tmpWallSize); if Horizontal then if View3D then VertLine3D(tmp,PosAxis+Delta,PosAxis+Delta+tmpTickLength,IZPos) else DoVertLine(tmp,PosAxis+Delta,PosAxis+Delta+tmpTickLength) else if View3D then HorizLine3D(PosAxis-Delta,PosAxis-Delta-tmpTickLength,tmp,IZPos) else DoHorizLine(PosAxis-Delta,PosAxis-Delta-tmpTickLength,tmp); end; end; end; Procedure DrawAxisLine; var tmp : Integer; begin With ParentChart,Canvas do if IsDepthAxis then begin if OtherSide then tmp:=ChartRect.Bottom+CalcWallSize(BottomAxis)-IZPos else tmp:=ChartRect.Top-IZPos; MoveTo3D(PosAxis,tmp,IStartPos); LineTo3D(PosAxis,tmp,IEndPos); end else begin if Horizontal then if OtherSide then // Top axis HorizLine3D(IStartPos,IEndPos,PosAxis,IZPos) else // Bottom axis HorizLine3D(IStartPos-CalcWallSize(LeftAxis), IEndPos+CalcWallSize(RightAxis), PosAxis+tmpWallSize,IZPos) else begin if OtherSide then tmp:=tmpWallSize else tmp:=-tmpWallSize; VertLine3D(PosAxis+tmp,IStartPos,IEndPos+CalcWallSize(BottomAxis),IZPos); end; end; end; Procedure ProcessMinorTicks(IsGrid:Boolean); Procedure AProc(APos:Integer); begin if (APos>IStartPos) and (APos<IEndPos) then if IsGrid then DrawGridLine(APos) else InternalDrawTick(APos,1,FMinorTickLength); end; var tmpInvCount : Double; tmpTicks : TChartValues; procedure DrawLogMinorTicks(tmpValue:Double); var tmpDelta : Double; tt : Integer; tmpLength : Integer; begin tmpLength:=Length(tmpTicks); for tt:=0 to tmpLength-1 do if tmpTicks[tt]=tmpValue then exit; SetLength(tmpTicks,tmpLength+1); tmpTicks[tmpLength]:=tmpValue; tmpDelta:=((tmpValue*FLogarithmicBase)-tmpValue)*tmpInvCount; for tt:=1 to FMinorTickCount do begin tmpValue:=tmpValue+tmpDelta; if (tmpValue<=IMaximum) and (tmpValue>=IMinimum) then AProc(CalcPosValue(tmpValue)); end; end; var t : Integer; tt : Integer; tmpDelta : Double; tmpValue : Double; begin tmpInvCount:=1.0/Succ(FMinorTickCount); if tmpNumTicks>1 then if not FLogarithmic then begin tmpDelta:=1.0*(Tick[1]-Tick[0])*tmpInvCount; for t:=1 to FMinorTickCount do begin AProc(Tick[0]-Round(t*tmpDelta)); AProc(Tick[tmpNumTicks-1]+Round(t*tmpDelta)); end; end; if FLogarithmic then begin tmpTicks:=nil; try if tmpNumTicks>0 then // 7.0 fix first tick begin tmpValue:=CalcPosPoint(Tick[tmpNumTicks-1])/LogarithmicBase; DrawLogMinorTicks(tmpValue); for t:=1 to tmpNumTicks do begin tmpValue:=CalcPosPoint(Tick[t-1]); DrawLogMinorTicks(tmpValue); end; DrawLogMinorTicks(tmpValue*LogarithmicBase); end; finally tmpTicks:=nil; end; end else for t:=1 to tmpNumTicks-1 do begin tmpDelta:=1.0*(Tick[t]-Tick[t-1])*tmpInvCount; for tt:=1 to FMinorTickCount do AProc(Tick[t]-Round(tt*tmpDelta)); end; end; Procedure ProcessTicks(APen:TChartPen; AOffset,ALength:Integer); var t : Integer; begin if APen.Visible then begin ParentChart.Canvas.AssignVisiblePen(APen); for t:=0 to tmpNumTicks-1 do InternalDrawTick(Tick[t],AOffset,ALength); end; end; Procedure ProcessMinor(APen:TChartPen; IsGrid:Boolean); begin if (tmpNumTicks>0) and APen.Visible then begin With ParentChart.Canvas do begin BackMode:=cbmTransparent; { 5.01 } Brush.Style:=bsClear; AssignVisiblePen(APen); end; ProcessMinorTicks(IsGrid); end; end; begin With ParentChart.Canvas do begin Brush.Style:=bsClear; BackMode:=cbmTransparent; end; tmpWallSize:=ParentChart.CalcWallSize(Self); if FAxis.Visible then begin ParentChart.Canvas.AssignVisiblePen(FAxis); DrawAxisLine; end; ProcessTicks(FTicks,1,FTickLength); DrawGrids(tmpNumTicks); ProcessTicks(FTicksInner,-1,-FTickInnerLength); ProcessMinor(FMinorTicks,False); ProcessMinor(FMinorGrid,True); ParentChart.Canvas.BackMode:=cbmOpaque; end; Procedure AddTick(Const APos:Integer); begin SetLength(Tick,Length(Tick)+1); Tick[tmpNumTicks]:=APos; Inc(tmpNumTicks); end; var tmpAlternate : Boolean; Procedure DrawThisLabel(LabelPos:Integer; Const tmpSt:String; Format:TTeeCustomShape=nil); var tmpZ : Integer; tmpPos : Integer; begin if TickOnLabelsOnly then AddTick(LabelPos); With ParentChart,Canvas do begin if Assigned(Format) then AssignFont(Format.Font) else AssignFont(Items.Format.Font); // trick Brush.Style:=bsSolid; Brush.Style:=bsClear; {$IFDEF CLX} BackMode:=cbmTransparent; {$ENDIF} if IsDepthAxis then begin TextAlign:=DepthAxisAlign; if (View3DOptions.Rotation=360) or View3DOptions.Orthogonal then tmpZ:=LabelPos+(FontHeight div 2) else tmpZ:=LabelPos; if OtherSide then tmpPos:=PosLabels else tmpPos:=PosLabels-2-(TextWidth('W') div 2); TextOut3D(tmpPos,DepthAxisPos,tmpZ,tmpSt); end else begin if LabelsAlternate then begin if tmpAlternate then tmpPos:=PosLabels else if Horizontal then if OtherSide then tmpPos:=PosLabels-FontHeight else tmpPos:=PosLabels+FontHeight else if OtherSide then tmpPos:=PosLabels+MaxLabelsWidth else tmpPos:=PosLabels-MaxLabelsWidth; tmpAlternate:=not tmpAlternate; end else tmpPos:=PosLabels; if Horizontal then DrawAxisLabel(LabelPos,tmpPos,FLabelsAngle,tmpSt,Format) else DrawAxisLabel(tmpPos,LabelPos,FLabelsAngle,tmpSt,Format); end; end; end; Var tmpLabelStyle : TAxisLabelStyle; Function GetAxisSeriesLabel(AIndex:Integer; Var AValue:Double; Var ALabel:String):Boolean; var t : Integer; begin result:=False; for t:=0 to ISeriesList.Count-1 do With ISeriesList[t] do if (AIndex>=FFirstVisibleIndex) and (AIndex<=FLastVisibleIndex) then begin { even if the series has no text labels... 5.01 } Case tmpLabelStyle of talMark : ALabel:=ValueMarkText[AIndex]; talText : ALabel:=Labels[AIndex]; end; if Assigned(ParentChart.FOnGetAxisLabel) then ParentChart.FOnGetAxisLabel( TChartAxis(Self),ISeriesList[t], AIndex,ALabel); if ALabel<>'' then // 5.02 begin if Horizontal then AValue:=XValues.Value[AIndex] else AValue:=YValues.Value[AIndex]; result:=True; Break; end; end; end; Procedure AxisLabelsSeries; Procedure CalcFirstLastAllSeries(Var tmpFirst,tmpLast:Integer); var t : Integer; begin tmpFirst:=High(Integer); // 5.02 tmpLast:=-1; for t:=0 to ISeriesList.Count-1 do With ISeriesList[t] do begin CalcFirstLastVisibleIndex; if (FFirstVisibleIndex<tmpFirst) and (FFirstVisibleIndex<>-1) then tmpFirst:=FFirstVisibleIndex; if (FLastVisibleIndex>tmpLast) then tmpLast:=FLastVisibleIndex; end; end; { Select all active Series that have "Labels" } Procedure CalcAllSeries; var t : Integer; begin ISeriesList.Clear; With ParentChart do for t:=0 to SeriesCount-1 do With Series[t] do if Active and AssociatedToAxis(Self) then ISeriesList.Add(Series[t]); end; var t : Integer; tmp : Integer; tmpNum : Integer; tmpFirst : Integer; tmpLast : Integer; tmpSt : String; tmpValue : Double; OldPosLabel : Integer; OldSizeLabel : Integer; tmpLabelSize : Integer; tmpDraw : Boolean; tmpLabelW : Boolean; begin ISeriesList.Clear; CalcAllSeries; CalcFirstLastAllSeries(tmpFirst,tmpLast); if tmpFirst<>High(Integer) then begin OldPosLabel :=-1; OldSizeLabel:= 0; tmpLabelW:=Horizontal; Case FLabelsAngle of 90,270: tmpLabelW:=not tmpLabelW; end; for t:=tmpFirst to tmpLast do if GetAxisSeriesLabel(t,tmpValue,tmpSt) then if (tmpValue>=IMinimum) and (tmpValue<=IMaximum) then begin tmp:=Self.CalcPosValue(tmpValue); if not TickOnLabelsOnly then AddTick(tmp); if FItems.Format.Visible and (tmpSt<>'') then begin With ParentChart.Canvas do begin tmpLabelSize:=ParentChart.MultiLineTextWidth(tmpSt,tmpNum); if not tmpLabelW then tmpLabelSize:=FontHeight*tmpNum; end; if (FLabelsSeparation<>0) and (OldPosLabel<>-1) then begin Inc(tmpLabelSize,Trunc(0.02*tmpLabelSize*FLabelsSeparation)); tmpLabelSize:=tmpLabelSize div 2; if tmp>=OldPosLabel then tmpDraw:=(tmp-tmpLabelSize)>=(OldPosLabel+OldSizeLabel) else tmpDraw:=(tmp+tmpLabelSize)<=(OldPosLabel-OldSizeLabel); if tmpDraw then begin DrawThisLabel(tmp,tmpSt); OldPosLabel:=tmp; OldSizeLabel:=tmpLabelSize; end; end else begin DrawThisLabel(tmp,tmpSt); OldPosLabel:=tmp; OldSizeLabel:=tmpLabelSize div 2; end; end; end; end; ISeriesList.Clear; end; var IIncrement : Double; tmpWhichDateTime : TDateTimeStep; Procedure InternalDrawLabel(var Value:Double; DecValue:Boolean); var tmp : Integer; Begin tmp:=CalcPosValue(Value); if FLabelsOnAxis or ((tmp>IStartPos) and (tmp<IEndPos)) then begin if not TickOnLabelsOnly then AddTick(tmp); if FItems.Format.Visible then DrawThisLabel(tmp,LabelValue(Value)); end; if DecValue then IncDecDateTime(False,Value,IIncrement,tmpWhichDateTime); end; Procedure DoDefaultLogLabels; Function TryDrawLogLabels(Value:Double; Multiply:Boolean; LogDec:Integer; const Base:Double):Integer; // 7.0 var tmp : Double; begin result:=0; tmp:=Power(FLogarithmicBase,LogN(FLogarithmicBase,Value)-LogDec); if Base>1 then While Value<=IMaximum do begin if Value>=IMinimum then begin InternalDrawLabel(Value,False); Inc(result); end; if Multiply then Value:=Value*Base else Value:=Value+tmp; end; end; var tmpValue2 : Double; begin if IMinimum<>IMaximum then begin if IMinimum<=0 then begin if IMinimum=0 then IMinimum:=0.1 else IMinimum:=RoundLogPower(MinAxisRange); tmpValue:=IMinimum; end else tmpValue:=RoundLogPower(IMinimum); // 7.0 if MinorGrid.Visible then // 5.02 begin tmpValue2:=tmpValue; if tmpValue2>=IMinimum then tmpValue2:=Power(FLogarithmicBase,LogN(FLogarithmicBase,IMinimum)-1); if tmpValue2<IMinimum then AddTick(CalcPosValue(tmpValue2)); end; if TryDrawLogLabels(tmpValue,True,0,FLogarithmicBase)=0 then TryDrawLogLabels(tmpValue,False,1,FLogarithmicBase); // For minor grids only... if MinorGrid.Visible and (tmpValue>IMaximum) then // 5.02 AddTick(CalcPosValue(tmpValue)); end; end; Procedure DoDefaultLabels; var tmp : Double; {$IFDEF TEEOCX} tmpInValue : Double; {$ENDIF} Begin tmpValue:=IMaximum/IIncrement; if Abs(IRange/IIncrement)<10000 then { if less than 10000 labels... } Begin { calculate the maximum value... } if IAxisDateTime and FExactDateTime and (tmpWhichDateTime<>dtNone) and (tmpWhichDateTime>=dtOneDay) then tmpValue:=TeeRoundDate(IMaximum,tmpWhichDateTime) else if (FloatToStr(IMinimum)=FloatToStr(IMaximum)) or (not RoundFirstLabel) then tmpValue:=IMaximum else tmpValue:=IIncrement*Trunc(tmpValue); { adjust the maximum value to be inside "IMinimum" and "IMaximum" } While tmpValue>IMaximum do IncDecDateTime(False,tmpValue,IIncrement,tmpWhichDateTime); { Draw the labels... } if IRangeZero then InternalDrawLabel(tmpValue,False) { Maximum is equal to Minimum. Draw one label only } else begin { do the loop and draw labels... } if (Abs(IMaximum-IMinimum)<1e-10) or (FloatToStr(tmpValue)=FloatToStr(tmpValue-IIncrement)) then { fix zooming when axis Max=Min } InternalDrawLabel(tmpValue,False) else begin { draw labels until "tmpVale" is less than minimum } // Commented, negative minimum labels never show if IMinimum>=0 then tmp:=(IMinimum-MinAxisIncrement)/(1.0+MinAxisIncrement) // 7.0 else tmp:=IMinimum; while tmpValue>=tmp do {$IFDEF TEEOCX} begin tmpInValue:=tmpValue; InternalDrawLabel(True); if (Abs((tmpInValue-IIncrement)-tmpValue)>1e-10) and (Abs((tmpInValue-IIncrement)-tmpValue)<1) then Break; end; {$ELSE} InternalDrawLabel(tmpValue,True); {$ENDIF} end; end; end; end; Procedure DoNotCustomLabels; begin if Logarithmic and (FDesiredIncrement=0) then DoDefaultLogLabels else DoDefaultLabels; end; Procedure DoCustomLabels; Const DifFloat = 0.0000001; var LabelIndex : Integer; Stop : Boolean; LabelInside : Boolean; Begin tmpValue:=IMinimum; Stop:=True; LabelIndex:=0; LabelInside:=False; Repeat ParentChart.FOnGetNextAxisLabel(TChartAxis(Self),LabelIndex,tmpValue,Stop); if Stop then Begin if LabelIndex=0 then DoNotCustomLabels; Exit; end else begin { Trick with doubles... } LabelInside:=(tmpValue>=(IMinimum-DifFloat)) and (tmpValue<=(IMaximum+DifFloat)); if LabelInside then InternalDrawLabel(tmpValue,False); Inc(LabelIndex); end; Until (not LabelInside) or (LabelIndex>2000) or Stop; { maximum 2000 labels... } end; Procedure DrawAxisTitle; begin if (FAxisTitle.Visible) and (FAxisTitle.FCaption<>'') then begin if IsDepthAxis then DrawTitle(PosTitle,DepthAxisPos) else if Horizontal then DrawTitle(ICenterPos,PosTitle) else DrawTitle(PosTitle,ICenterPos); end; end; Procedure DepthAxisLabels; Var t : Integer; tmp : Integer; tmpSt : String; begin if ParentChart.CountActiveSeries>0 then for t:=Trunc(IMinimum) to Trunc(IMaximum) do Begin tmp:=Self.CalcYPosValue(IMaximum-t-0.5); if not TickOnLabelsOnly then AddTick(tmp); if FItems.Format.Visible then begin With ParentChart do begin tmpSt:=SeriesTitleLegend(t,True); if Assigned(FOnGetAxisLabel) then FOnGetAxisLabel(TChartAxis(Self),nil,t,tmpSt); end; DrawThisLabel(tmp,tmpSt); end; end; end; Procedure DrawCustomLabels; var t : Integer; tmp : Integer; tmpItem : TAxisItem; tmpSt : String; begin for t:=0 to Items.Count-1 do begin tmpItem:=Items[t]; if (tmpItem.Value>=Minimum) and (tmpItem.Value<=Maximum) then begin tmp:=CalcPosValue(tmpItem.Value); if not TickOnLabelsOnly then AddTick(tmp); if tmpItem.Visible then begin tmpSt:=tmpItem.FText; if tmpSt='' then tmpSt:=LabelValue(tmpItem.Value); DrawThisLabel(tmp,tmpSt,tmpItem); end; end; end; end; Begin tmpAlternate:=Horizontal; With ParentChart,ChartRect do Begin IAxisDateTime:=IsDateTime; if CalcPosAxis then FPosAxis:=ApplyPosition(GetRectangleEdge(ChartRect),ChartRect); DrawAxisTitle; tmpNumTicks:=0; Tick:=nil; if Items.Count=0 then begin tmpLabelStyle:=CalcLabelStyle; if tmpLabelStyle<>talNone then begin // Assign font before CalcIncrement ! Canvas.AssignFont(FItems.Format.Font); IIncrement:=CalcIncrement; if IAxisDateTime and FExactDateTime and (FDesiredIncrement<>0) then begin tmpWhichDateTime:=FindDateTimeStep(FDesiredIncrement); if tmpWhichDateTime<>dtNone then While (IIncrement>DateTimeStep[tmpWhichDateTime]) and (tmpWhichDateTime<>dtOneYear) do tmpWhichDateTime:=Succ(tmpWhichDateTime); end else tmpWhichDateTime:=dtNone; if ((IIncrement>0) or ( (tmpWhichDateTime>=dtHalfMonth) and (tmpWhichDateTime<=dtOneYear)) ) and (IMaximum>=IMinimum) then Begin Case tmpLabelStyle of talValue: if Assigned(FOnGetNextAxisLabel) then DoCustomLabels else DoNotCustomLabels; talMark: AxisLabelsSeries; talText: if IsDepthAxis then DepthAxisLabels else AxisLabelsSeries; end; end; end; end else DrawCustomLabels; DrawTicksGrid; end; end; Function TChartAxis.SizeTickAxis:Integer; begin if FAxis.Visible then result:=FAxis.Width+1 else result:=0; if FTicks.Visible then Inc(result,FTickLength); if FMinorTicks.Visible then result:=Math.Max(result,FMinorTickLength); end; Function TChartAxis.SizeLabels:Integer; begin result:=InternalCalcSize(FItems.Format.Font,FLabelsAngle,'',FLabelsSize); if LabelsAlternate then result:=result*2; end; Function TChartAxis.InternalCalcSize( tmpFont:TTeeFont; tmpAngle:Integer; Const tmpText:String; tmpSize:Integer):Integer; Begin if tmpSize<>0 then result:=tmpSize else With ParentChart,Canvas do Begin AssignFont(tmpFont); if Horizontal then Case tmpAngle of 0, 180: result:=FontHeight; else { optimized for speed } if tmpText='' then result:=MaxLabelsWidth else result:=Canvas.TextWidth(tmpText); end else Case tmpAngle of 90, 270: result:=FontHeight; else { optimized for speed } if tmpText='' then result:=MaxLabelsWidth else result:=Canvas.TextWidth(tmpText); end; end; end; Procedure TChartAxis.CalcRect(Var R:TRect; InflateChartRectangle:Boolean); Procedure InflateAxisRect(Value:Integer); Begin With R do if Horizontal then if OtherSide then Inc(Top,Value) else Dec(Bottom,Value) else if OtherSide then Dec(Right,Value) else Inc(Left,Value); end; Function InflateAxisPos(Value:Integer; Amount:Integer):Integer; Begin result:=Value; if Horizontal then if OtherSide then Dec(result,Amount) else Inc(result,Amount) else if OtherSide then Inc(result,Amount) else Dec(result,Amount); end; Function CalcLabelsRect(tmpSize:Integer):Integer; begin InflateAxisRect(tmpSize); result:=GetRectangleEdge(R); end; var tmp : Integer; Begin IAxisDateTime:=IsDateTime; if InflateChartRectangle then begin if IsDepthAxis then if OtherSide then FPosTitle:=R.Right else FPosTitle:=R.Left else With FAxisTitle do if Visible and (Caption<>'') then FPosTitle:=CalcLabelsRect(InternalCalcSize(Font,FAngle,FCaption,FTitleSize)); if FItems.Format.Visible then FPosLabels:=CalcLabelsRect(SizeLabels); tmp:=SizeTickAxis+ParentChart.CalcWallSize(Self); if tmp>0 then InflateAxisRect(tmp); FPosTitle:=ApplyPosition(FPosTitle,R); FPosLabels:=ApplyPosition(FPosLabels,R); end else begin FPosAxis:=ApplyPosition(GetRectangleEdge(R),R); FPosLabels:=InflateAxisPos(FPosAxis,SizeTickAxis); FPosTitle:=InflateAxisPos(FPosLabels,SizeLabels); end; end; {$IFDEF D5} constructor TChartAxis.Create(Chart: TCustomAxisPanel); begin Create(Chart.CustomAxes); end; {$ENDIF} function TChartAxis.IsZStored: Boolean; begin result:=(not IsDepthAxis) and ( (OtherSide and (FZPosition<>100)) or ((not OtherSide) and (FZPosition>0.011)) // VCL bug double=0 streaming ); end; procedure TChartAxis.SetMaximumOffset(const Value: Integer); begin ParentChart.SetIntegerProperty(FMaximumOffset,Value); end; procedure TChartAxis.SetMinimumOffset(const Value: Integer); begin ParentChart.SetIntegerProperty(FMinimumOffset,Value); end; function TChartAxis.IsLogBaseStored: Boolean; begin result:=LogarithmicBase<>10; end; function TChartAxis.GetGridCentered: Boolean; begin result:=Grid.Centered; end; procedure TChartAxis.SetPosUnits(const Value: TTeeUnits); begin if FPosUnits<>Value then begin FPosUnits:=Value; ParentChart.Invalidate; end; end; { TChartDepthAxis } function TChartDepthAxis.InternalCalcLabelStyle: TAxisLabelStyle; var t : Integer; begin result:=talText; With ParentChart do for t:=0 to SeriesCount-1 do With Series[t] do if Active then if HasZValues or (MinZValue<>MaxZValue) then begin result:=talValue; break; end; end; { TSeriesMarksPosition } Procedure TSeriesMarkPosition.Assign(Source:TSeriesMarkPosition); begin ArrowFrom :=Source.ArrowFrom; ArrowTo :=Source.ArrowTo; LeftTop :=Source.LeftTop; Height :=Source.Height; Width :=Source.Width; end; Function TSeriesMarkPosition.Bounds:TRect; begin result:={$IFDEF CLR}TRect.{$ELSE}{$IFDEF D6}Types.{$ELSE}Classes.{$ENDIF}{$ENDIF}Bounds(LeftTop.X,LeftTop.Y,Width,Height); end; // Set the "other" Depth axis Inverted property to same value procedure TChartDepthAxis.SetInverted(Value: Boolean); begin inherited; if Self=ParentChart.Axes.Depth then ParentChart.Axes.DepthTop.FInverted:=Inverted else ParentChart.Axes.Depth.FInverted:=Inverted end; { TChartValueList } Constructor TChartValueList.Create(AOwner:TChartSeries; Const AName:String); Begin inherited Create; Modified:=True; {$IFDEF TEEMULTIPLIER} FMultiplier:=1; {$ENDIF} FOwner:=AOwner; FOwner.FValuesList.Add(Self); FName:=AName; {$IFNDEF TEEARRAY} FList:=TList.Create; {$ENDIF} ClearValues; end; Destructor TChartValueList.Destroy; Begin {$IFDEF TEEARRAY} ClearValues; {$ELSE} FList.Free; {$ENDIF} inherited; End; Function TChartValueList.First:TChartValue; Begin result:=Value[0] end; {$IFNDEF TEEARRAY} Function TChartValueList.Count:Integer; Begin result:=FList.Count; { <-- virtual } end; {$ENDIF} Function TChartValueList.Last:TChartValue; Begin result:=Value[Count-1] end; Procedure TChartValueList.Delete(ValueIndex:Integer); {$IFDEF CLR} var t : Integer; {$ENDIF} Begin {$IFDEF TEEARRAY} Count:=Count-1; {$IFDEF CLR} for t:=ValueIndex to Count-1 do Value[t]:=Value[t+1]; // System.Array.Copy(Value[t+1],Value[t],Count-ValueIndex-1); {$ELSE} System.Move(Value[ValueIndex+1],Value[ValueIndex], SizeOf(TChartValue)*(Count-ValueIndex)); { 5.03 } {$ENDIF} {$ELSE} Dispose(PChartValue(FList[ValueIndex])); FList.Delete(ValueIndex); {$ENDIF} Modified:=True; end; Procedure TChartValueList.Delete(Start,Quantity:Integer); {$IFNDEF TEEARRAY} var t : Integer; {$ENDIF} begin {$IFDEF TEEARRAY} Count:=Count-Quantity; {$IFNDEF CLR} System.Move(Value[Start+Quantity],Value[Start], SizeOf(TChartValue)*(Count-Start)); {$ENDIF} {$ELSE} for t:=1 to Quantity do Delete(Start); {$ENDIF} Modified:=True; end; Procedure TChartValueList.InsertChartValue(ValueIndex:Integer; Const AValue:TChartValue); {$IFDEF TEEARRAY} Var tmp : Integer; {$IFDEF CLR} t : Integer; {$ENDIF} {$ELSE} Var p : PChartValue; {$ENDIF} Begin {$IFDEF TEEARRAY} tmp:=Length(Value); if Count>=tmp then SetLength(Value,tmp+TeeDefaultCapacity); tmp:=Count-ValueIndex; if tmp>0 then {$IFDEF CLR} for t:=ValueIndex to ValueIndex+tmp do Value[t+1]:=Value[t]; {$ELSE} System.Move(Value[ValueIndex],Value[ValueIndex+1],SizeOf(TChartValue)*tmp); {$ENDIF} Value[ValueIndex]:=AValue; Count:=Count+1; {$ELSE} New(p); p^:=AValue; FList.Insert(ValueIndex,p); { <- virtual } {$ENDIF} Modified:=True; end; Function TChartValueList.AddChartValue(Const AValue:TChartValue):Integer; begin TempValue:=AValue; result:=AddChartValue; end; Function TChartValueList.AddChartValue:Integer; {$IFDEF TEEARRAY} Procedure IncrementArray; var tmp : Integer; begin tmp:=Length(Value); if (Count+1)>tmp then SetLength(Value,tmp+TeeDefaultCapacity); end; {$ENDIF} Var t : Integer; {$IFDEF TEEARRAY} tmp : Integer; {$ELSE} p : PChartValue; {$ENDIF} Begin {$IFNDEF TEEARRAY} New(p); { virtual } p^:=TempValue; {$ENDIF} if FOrder=loNone then begin {$IFDEF TEEARRAY} result:=Count; tmp:=Length(Value); if result>=tmp then SetLength(Value,tmp+TeeDefaultCapacity); Value[result]:=FTempValue; Count:=Count+1; {$ELSE} result:=FList.Add(p) {$ENDIF} end else begin t:={$IFDEF TEEARRAY}Count{$ELSE}FList.Count{$ENDIF}-1; if (t=-1) or ( (FOrder=loAscending) and (FTempValue>={$IFDEF TEEARRAY}Value[t]{$ELSE}PChartValue(FList[t])^{$ENDIF}) ) or ( (FOrder=loDescending) and (FTempValue<={$IFDEF TEEARRAY}Value[t]{$ELSE}PChartValue(FList[t])^{$ENDIF}) ) then begin {$IFDEF TEEARRAY} result:=Count; //IncrementArray; tmp:=Length(Value); if (Count+1)>tmp then SetLength(Value,tmp+TeeDefaultCapacity); Value[result]:=FTempValue; Count:=Count+1; {$ELSE} result:=FList.Add(p) {$ENDIF} end else Begin if FOrder=loAscending then While (t>=0) and ({$IFDEF TEEARRAY}Value[t]{$ELSE}PChartValue(FList[t])^{$ENDIF}>FTempValue) do Dec(t) else While (t>=0) and ({$IFDEF TEEARRAY}Value[t]{$ELSE}PChartValue(FList[t])^{$ENDIF}<FTempValue) do Dec(t); result:=t+1; {$IFDEF TEEARRAY} IncrementArray; for t:=Count downto Succ(result) do Value[t]:=Value[t-1]; Value[result]:=FTempValue; Count:=Count+1; {$ELSE} FList.Insert(result,p); {$ENDIF} end; end; Modified:=True; end; {$IFDEF TEEMULTIPLIER} Procedure TChartValueList.SetMultiplier(Const Value:Double); Begin if Value<>FMultiplier then begin FMultiplier:=Value; Modified:=True; FOwner.NotifyValue(veRefresh,0); FOwner.Repaint; end; end; {$ENDIF} Function TChartValueList.GetValue(ValueIndex:Integer):TChartValue; begin {$IFDEF TEEARRAY} {$IFOPT R+} if (ValueIndex<0) or (ValueIndex>(Count-1)) then Raise ChartException.CreateFmt(SListIndexError,[ValueIndex]); {$ENDIF} result:=Value[ValueIndex]{$IFDEF TEEMULTIPLIER}*FMultiplier{$ENDIF}; {$ELSE} result:=PChartValue(FList[ValueIndex])^{$IFDEF TEEMULTIPLIER}*FMultiplier{$ENDIF}; {$ENDIF} end; Function TChartValueList.Locate(Const AValue:TChartValue; FirstIndex,LastIndex:Integer):Integer; begin for result:=FirstIndex to LastIndex do if Value[result]=AValue then Exit; result:=-1; end; Function TChartValueList.Locate(Const AValue:TChartValue):Integer; Begin result:=Locate(AValue,0,Count-1); end; Procedure TChartValueList.SetValue(ValueIndex:Integer; Const AValue:TChartValue); begin {$IFDEF TEEARRAY} {$IFOPT R+} if (ValueIndex<0) or (ValueIndex>(Count-1)) then Raise ChartException.CreateFmt(SListIndexError,[ValueIndex]); {$ENDIF} Value[ValueIndex]:=AValue; {$ELSE} PChartValue(FList[ValueIndex])^:=AValue; {$ENDIF} Modified:=True; FOwner.NotifyValue(veModify,ValueIndex); end; Function TChartValueList.GetMaxValue:TChartValue; begin if Modified then RecalcStats; result:=FMaxValue; end; Function TChartValueList.GetMinValue:TChartValue; begin if Modified then RecalcStats; result:=FMinValue; end; Function TChartValueList.GetTotal:Double; begin if Modified then RecalcStats; result:=FTotal; end; Function TChartValueList.GetTotalABS:Double; begin if Modified then RecalcStats; result:=FTotalABS; end; procedure TChartValueList.RecalcStats(StartIndex:Integer); var t : Integer; tmpValue : TChartValue; begin {$IFDEF TEEARRAY} if Count>Length(Value) then // 7.0 HV suggestion Count:=Length(Value); {$ENDIF} if Count>0 then begin if StartIndex=0 then begin tmpValue:=Value[0]; FMinValue:=tmpValue; FMaxValue:=tmpValue; FTotal:=tmpValue; FTotalABS:=Abs(tmpValue); end; for t:=StartIndex to Count-1 do Begin tmpValue:=Value[t]; if tmpValue<FMinValue then FMinValue:=tmpValue else if tmpValue>FMaxValue then FMaxValue:=tmpValue; FTotal:=FTotal+tmpValue; FTotalABS:=FTotalABS+Abs(tmpValue); end; end; Modified:=False; end; Procedure TChartValueList.RecalcStats; Begin {$IFDEF TEEARRAY} if Count>Length(Value) then // 7.0 HV suggestion Count:=Length(Value); {$ENDIF} if Count>0 then RecalcStats(0) else begin FMinValue:=0; FMaxValue:=0; FTotal:=0; FTotalABS:=0; end; Modified:=False; end; procedure TChartValueList.SetDateTime(Const Value:Boolean); Begin FOwner.SetBooleanProperty(FDateTime,Value); end; Procedure TChartValueList.ClearValues; {$IFNDEF TEEARRAY} Var t : Integer; {$ENDIF} Begin {$IFDEF TEEARRAY} Count:=0; Value:=nil; {$ELSE} for t:=0 to FList.Count-1 do Dispose(PChartValue(FList[t])); { virtual } FList.Clear; {$ENDIF} Modified:=True; end; Function TChartValueList.Range:TChartValue; begin if Modified then RecalcStats; result:=FMaxValue-FMinValue; end; Procedure TChartValueList.Scroll; var t : Integer; tmpVal : {$IFDEF TEEARRAY}TChartValue{$ELSE}PChartValue{$ENDIF}; Begin {$IFNDEF TEEARRAY} With FList do { virtual } {$ENDIF} if Count>0 then Begin {$IFDEF TEEARRAY} tmpVal:=Value[0]; for t:=1 to Count-1 do Value[t-1]:=Value[t]; Value[Count-1]:=tmpVal; {$ELSE} tmpVal:=Items[0]; for t:=1 to Count-1 do Items[t-1]:=Items[t]; Items[Count-1]:=tmpVal; {$ENDIF} end; end; Procedure TChartValueList.SetValueSource(Const Value:String); Begin if FValueSource<>Value then begin FValueSource:=Value; FOwner.CheckDataSource; end; end; {$IFDEF TEEARRAY} Procedure TChartValueList.Exchange(Index1,Index2:Integer); var tmp : TChartValue; begin {$IFOPT R+} if (Index1<0) or (Index1>(Count-1)) then Raise ChartException.CreateFmt(SListIndexError,[Index1]); if (Index2<0) or (Index2>(Count-1)) then Raise ChartException.CreateFmt(SListIndexError,[Index2]); {$ENDIF} tmp:=Value[Index1]; Value[Index1]:=Value[Index2]; Value[Index2]:=tmp; Modified:=True; FOwner.NotifyValue(veModify,Index1); end; {$ENDIF} Procedure TChartValueList.FillSequence; var t : Integer; begin for t:=0 to Count-1 do Value[t]:=t; {$IFDEF TEEARRAY} Modified:=True; FOwner.NotifyValue(veModify,0); {$ENDIF} end; {$IFOPT C+} function TChartValueList.GetCount:Integer; begin Assert( FCount<=Length(Value), 'ValueList Count ('+IntToStr(FCount)+') greater than array length ('+IntToStr(Length(Value))+').'); result:=FCount; end; procedure TChartValueList.SetCount(const Value:Integer); begin Assert( FCount>=0, 'ValueList Count must be greater than zero.'); FCount:=Value; end; {$ENDIF} Function TChartValueList.CompareValueIndex(a,b:Integer):Integer; var tmpA : TChartValue; tmpB : TChartValue; begin tmpA:=Value[a]; tmpB:=Value[b]; if tmpA<tmpB then result:=-1 else if tmpA>tmpB then result:= 1 else result:= 0; if FOrder=loDescending then result:=-result; end; procedure TChartValueList.Sort; begin if Order<>loNone then TeeSort(0,Count-1,CompareValueIndex,Owner.SwapValueIndex); end; Procedure TChartValueList.Assign(Source:TPersistent); begin if Source is TChartValueList then With TChartValueList(Source) do begin Self.FOrder :=FOrder; Self.FDateTime :=FDateTime; {$IFDEF TEEMULTIPLIER} Self.FMultiplier :=FMultiplier; {$ENDIF} Self.FValueSource:=FValueSource; end; end; {$IFDEF TEEMULTIPLIER} function TChartValueList.IsMultiStored: Boolean; begin result:=FMultiplier<>1; end; {$ELSE} procedure TChartValueList.ReadMultiplier(Reader: TReader); begin if Reader.ReadFloat<>1 then ShowMessageUser('Error: Multiplier property is obsolete.'+#13+ 'Modify TeeDefs.inc (enable Multiplier) and recompile.'); end; procedure TChartValueList.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Multiplier',ReadMultiplier,nil,False); end; {$ENDIF} function TChartValueList.ToString(Index: Integer): String; begin result:=FloatToStr(Value[Index]); end; function TChartValueList.IsDateStored: Boolean; begin result:=FDateTime<>IDefDateTime; end; procedure TChartValueList.InitDateTime(Value: Boolean); begin FDateTime:=Value; IDefDateTime:=Value; end; { TSeriesMarksPositions } Procedure TSeriesMarksPositions.Put(Index:Integer; APosition:TSeriesMarkPosition); begin While Index>=Count do Add(nil); if Items[Index]=nil then Items[Index]:=TSeriesMarkPosition.Create; With Position[Index] do begin Custom:=True; Assign(APosition); end; end; Function TSeriesMarksPositions.Get(Index:Integer):TSeriesMarkPosition; begin if (Index<Count) and Assigned(Items[Index]) then result:=TSeriesMarkPosition(Items[Index]) else result:=nil end; Procedure TSeriesMarksPositions.Automatic(Index:Integer); begin if (Index<Count) and Assigned(Items[Index]) then Position[Index].Custom:=False; end; procedure TSeriesMarksPositions.Clear; var t : Integer; begin for t:=0 to Count-1 do Position[t].Free; inherited; end; Function TSeriesMarksPositions.ExistCustom:Boolean; var t : Integer; begin result:=False; for t:=0 to Count-1 do if Assigned(Position[t]) and Position[t].Custom then begin result:=True; Exit; end; end; { TSeriesMarksGradient } Constructor TSeriesMarksGradient.Create(ChangedEvent: TNotifyEvent); var OldChanged : TNotifyEvent; begin inherited; OldChanged:=IChanged; // 6.02, prevent triggering changes here IChanged:=nil; try Direction:=gdRightLeft; EndColor:=clWhite; StartColor:=clSilver; finally IChanged:=OldChanged; end; end; { TSeriesMarksItems } function TMarksItems.Get(Index:Integer):TMarksItem; var tmp : TMarksItem; begin while Index>(Count-1) do Add(nil); if not Assigned(Items[Index]) then begin tmp:=TMarksItem.Create(IMarks.ParentChart); tmp.Color:=ChartMarkColor; TSeriesMarks(IMarks).InitShadow(tmp.Shadow); Items[Index]:=tmp; end; result:={$IFDEF CLR}TMarksItem{$ENDIF}(Items[Index]); end; procedure TMarksItems.Clear; var t : Integer; begin for t:=0 to Count-1 do TMarksItem(Items[t]).Free; inherited; IMarks.Repaint; end; {$IFNDEF CLR} type TShadowAccess=class(TTeeShadow); {$ENDIF} { TSeriesMarks } Constructor TSeriesMarks.Create(AOwner:TChartSeries); Begin inherited Create(nil); FSeries := AOwner; FMarkerStyle := smsLabel; FDrawEvery := 1; FPositions := TSeriesMarksPositions.Create; FItems := TMarksItems.Create; FItems.IMarks := Self; { inherited } Color := ChartMarkColor; Visible := False; end; Destructor TSeriesMarks.Destroy; begin FSymbol.Free; FCallout.Free; FPositions.Free; FItems.Free; inherited; end; Procedure TSeriesMarks.InitShadow(AShadow:TTeeShadow); Begin with {$IFNDEF CLR}TShadowAccess{$ENDIF}(AShadow) do begin Color:=clGray; DefaultColor:=clGray; Size:=1; DefaultSize:=1; end; end; Procedure TSeriesMarks.Assign(Source:TPersistent); var t : Integer; Begin if Source is TSeriesMarks then With TSeriesMarks(Source) do Begin Self.FAngle :=FAngle; Self.Callout :=FCallout; Self.FClip :=FClip; Self.FDrawEvery :=FDrawEvery; Self.FMarkerStyle:=FMarkerStyle; Self.FMultiLine :=FMultiLine; Self.Symbol :=FSymbol; Self.Items.Clear; for t:=0 to Items.Count-1 do Self.Items[t].Assign(Items[t]); end; inherited; end; Function TSeriesMarks.GetBackColor:TColor; begin result:=Color; end; function TSeriesMarks.GetItem(Index:Integer):TMarksItem; begin result:=FItems[Index]; end; Procedure TSeriesMarks.SetBackColor(Value:TColor); begin Color:=Value; end; Procedure TSeriesMarks.ResetPositions; var t : Integer; begin for t:=0 to Positions.Count-1 do Positions.Position[t].Custom:=False; ParentSeries.Repaint; end; Function TSeriesMarks.GetCallout:TMarksCallout; begin if not Assigned(FCallout) then begin FCallout:=TMarksCallout.Create(FSeries); FCallout.ParentChart:=ParentChart; end; result:=FCallout; end; Procedure TSeriesMarks.SetCallout(const Value:TMarksCallout); begin if Assigned(Value) then Callout.Assign(Value) else FreeAndNil(FCallout); end; Procedure TSeriesMarks.SetArrowLength(Value:Integer); Begin Callout.Length:=Value; end; Procedure TSeriesMarks.SetDrawEvery(Value:Integer); begin ParentSeries.SetIntegerProperty(FDrawEvery,Value); end; Procedure TSeriesMarks.SetAngle(Value:Integer); begin ParentSeries.SetIntegerProperty(FAngle,Value); end; Procedure TSeriesMarks.SetMultiLine(Value:Boolean); Begin ParentSeries.SetBooleanProperty(FMultiLine,Value); end; Function TSeriesMarks.Clicked(X,Y:Integer):Integer; begin if Assigned(ParentChart) then ParentChart.Canvas.Calculate2DPosition(x,y,ZPosition); with FPositions do for result:=0 to Count-1 do if (result mod FDrawEvery=0) and Assigned(Position[result]) and PointInRect(Position[result].Bounds,x,y) then Exit; result:=-1; end; Procedure TSeriesMarks.UsePosition( Index:Integer; Var MarkPosition:TSeriesMarkPosition); var tmp : TSeriesMarkPosition; Old : TPoint; begin with FPositions do begin while Index>=Count do Add(nil); if Items[Index]=nil then begin tmp:=TSeriesMarkPosition.Create; tmp.Custom:=False; Items[Index]:=tmp; end; tmp:=Position[Index]; if tmp.Custom then begin if MarkPosition.ArrowFix then Old:=MarkPosition.ArrowFrom; MarkPosition.Assign(tmp); if MarkPosition.ArrowFix then MarkPosition.ArrowFrom:=Old; end else tmp.Assign(MarkPosition); end; end; Procedure TSeriesMarks.ApplyArrowLength(APosition:TSeriesMarkPosition); begin if Assigned(FCallout) then FCallout.ApplyArrowLength(APosition); end; Procedure TSeriesMarks.SetStyle(Value:TSeriesMarksStyle); Begin if FMarkerStyle<>Value then begin FMarkerStyle:=Value; ParentSeries.Repaint; end; end; Procedure TSeriesMarks.SetClip(Value:Boolean); Begin ParentSeries.SetBooleanProperty(FClip,Value); end; Procedure TSeriesMarks.DrawText(Const R:TRect; Const St:String); Var tmpNumRow : Integer; tmpRowHeight : Integer; Procedure DrawTextLine(Const LineSt:String); var tmpP : TPoint; tmpY : Integer; tmp : Extended; S,C : Extended; tmpCenter: TPoint; begin RectCenter(R,tmpCenter.X,tmpCenter.Y); if Angle<>0 then begin tmp:=Angle*TeePiStep; SinCos(tmp,S,C); tmpY:=tmpNumRow*tmpRowHeight-(R.Bottom-tmpCenter.y); tmpP.X:=tmpCenter.x+Round(tmpY*S); if Angle=90 then Inc(tmpP.X,2); tmpP.Y:=tmpCenter.y+Round(tmpY*C); end else begin tmpP.x:=tmpCenter.x; tmpP.y:=R.Top+tmpNumRow*tmpRowHeight; if Pen.Visible then Inc(tmpP.y,Pen.Width); end; With ParentChart.Canvas do if Supports3DText then if Angle=0 then TextOut3D(tmpP.X,tmpP.Y,ZPosition,LineSt) else RotateLabel3D(tmpP.X,tmpP.Y,ZPosition,LineSt,FAngle) else if Angle=0 then TextOut(tmpP.X,tmpP.Y,LineSt) else RotateLabel(tmpP.X,tmpP.Y,LineSt,FAngle); end; Var i : Integer; tmpSt : String; begin tmpNumRow:=0; tmpRowHeight:=ParentChart.Canvas.FontHeight; i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,St); if i>0 then begin tmpSt:=St; Repeat DrawTextLine(Copy(tmpSt,1,i-1)); tmpSt:=Copy(tmpSt,i+1,255); Inc(tmpNumRow); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,tmpSt); Until i=0; if tmpSt<>'' then DrawTextLine(tmpSt); end else DrawTextLine(St); end; Procedure TSeriesMarks.ConvertTo2D(Point:TPoint; var P:TPoint); var tmpDifX : Integer; tmpDifY : Integer; tmpPos2D : TPoint; begin if ParentChart.View3D and (not ParentChart.Canvas.Supports3DText) then begin tmpDifX:=Point.X-P.X; tmpDifY:=Point.Y-P.Y; tmpPos2D:=ParentChart.Canvas.Calculate3DPosition(Point,ZPosition); P:=TeePoint(tmpPos2D.X-tmpDifX,tmpPos2D.Y-tmpDifY); end; end; type TMarkItemAccess=class {$IFDEF CLR}sealed{$ENDIF} (TTeeCustomShape); Procedure TSeriesMarks.InternalDraw( Index:Integer; AColor:TColor; Const St:String; APosition:TSeriesMarkPosition); var tmpBounds : TRect; tmpH : Integer; tmpMark : TTeeCustomShape; tmpSymbol : Boolean; begin UsePosition(Index,APosition); tmpMark:=MarkItem(Index); with ParentSeries,ParentChart.Canvas do begin if Assigned(FCallout) then if Callout.Visible or Callout.Arrow.Visible then Callout.Draw(AColor,APosition.ArrowFrom,APosition.ArrowTo,ZPosition); if tmpMark.Transparent then begin Brush.Style:=bsClear; BackMode:=cbmTransparent; end else AssignBrush(tmpMark.Brush,tmpMark.Color); AssignVisiblePen(tmpMark.Pen); ConvertTo2D(APosition.ArrowTo,APosition.LeftTop); tmpBounds:=APosition.Bounds; tmpMark.DrawRectRotated(APosition.Bounds,FAngle mod 360,Succ(ZPosition)); tmpSymbol:=Assigned(FSymbol) and FSymbol.ShouldDraw; if tmpSymbol then begin FSymbol.Color:=ParentSeries.ValueColor[Index]; FSymbol.Transparent:=False; tmpH:=FontHeight; FSymbol.ShapeBounds:=TeeRect( APosition.LeftTop.X+4,APosition.LeftTop.Y+3, APosition.LeftTop.X+tmpH-1, APosition.LeftTop.Y+tmpH-2); FSymbol.DrawRectRotated(FSymbol.ShapeBounds,FAngle mod 360,Succ(ZPosition)); end; Brush.Style:=bsClear; BackMode:=cbmTransparent; TextAlign:=TA_CENTER; tmpBounds:=APosition.Bounds; Inc(tmpBounds.Left,2); if tmpSymbol then Inc(tmpBounds.Left,4+FSymbol.Width); DrawText(tmpBounds,St); end; end; function TSeriesMarks.GetGradientClass: TChartGradientClass; begin result:=TSeriesMarksGradient; end; Function TSeriesMarks.MarkItem(ValueIndex:Integer):TTeeCustomShape; begin if FItems.Count>ValueIndex then begin result:=Item[ValueIndex]; if not Assigned(result) then result:=Self; end else result:=Self; end; Procedure TSeriesMarks.AntiOverlap(First, ValueIndex:Integer; APosition:TSeriesMarkPosition); Function TotalBounds(ValueIndex:Integer; APosition:TSeriesMarkPosition):TRect; var P : TPoint; tmp: Integer; begin result:=APosition.Bounds; with MarkItem(ValueIndex) do begin if Pen.Visible then begin Inc(result.Right,Pen.Width); Inc(result.Bottom,Pen.Width); end; with Shadow do begin if HorizSize>0 then Inc(result.Right,HorizSize) else if HorizSize<0 then Dec(result.Left,HorizSize); if VertSize>0 then Inc(result.Bottom,VertSize) else if VertSize<0 then Dec(result.Top,VertSize); end; end; P:=result.TopLeft; ConvertTo2D(APosition.ArrowTo,P); tmp:=result.Left-P.X; Dec(result.Left,tmp); Dec(result.Right,tmp); tmp:=result.Top-P.Y; Dec(result.Top,tmp); Dec(result.Bottom,tmp); end; var tmpBounds : TRect; tmpDest : TRect; t : Integer; tmpR : TRect; tmpH : Integer; begin tmpBounds:=TotalBounds(ValueIndex,APosition); for t:=First to ValueIndex-1 do if Assigned(Positions[t]) then begin tmpR:=TotalBounds(t,Positions[t]); if {$IFNDEF CLR}{$IFNDEF CLX}Windows.{$ENDIF}{$ENDIF}IntersectRect(tmpDest,tmpR,tmpBounds) then begin if tmpBounds.Top<tmpR.Top then tmpH:=tmpBounds.Bottom-tmpR.Top else tmpH:=tmpBounds.Top-tmpR.Bottom; Dec(APosition.LeftTop.Y,tmpH); Dec(APosition.ArrowTo.Y,tmpH); end; end; end; { Returns the length in pixels for the ValueIndex th mark text. It checks if the Mark has multiple lines of text. } function TSeriesMarks.TextWidth(ValueIndex: Integer): Integer; // 5.02 var tmpSt : String; i : Integer; begin result:=0; tmpSt:=ParentSeries.GetMarkText(ValueIndex); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,tmpSt); if i>0 then Repeat result:=Math.Max(result,ParentChart.Canvas.TextWidth(Copy(tmpSt,1,i-1))); tmpSt:=Copy(tmpSt,i+1,255); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,tmpSt); Until i=0; if tmpSt<>'' then result:=Math.Max(result,ParentChart.Canvas.TextWidth(tmpSt)); end; function TSeriesMarks.GetArrowLength: Integer; begin result:=Callout.Length; end; function TSeriesMarks.GetArrowPen: TChartArrowPen; begin result:=Callout.Arrow; end; procedure TSeriesMarks.SetArrowPen(const Value: TChartArrowPen); begin Callout.Arrow:=Value; end; procedure TSeriesMarks.Clear; begin Positions.Clear; if not FItems.ILoadingCustom then FItems.Clear; end; type {$IFDEF CLR} TReaderAccess=class(TReader) protected procedure DoReadProperty(AInstance: TPersistent); end; procedure TReaderAccess.DoReadProperty(AInstance: TPersistent); begin ReadProperty(AInstance); end; {$ELSE} TReaderAccess=class(TReader); {$ENDIF} { internal. Loads series marks items from the DFM stream } procedure TSeriesMarks.ReadItems(Stream: TStream); var tmpCount : Integer; t : Integer; Reader : {$IFDEF CLR}TReaderAccess{$ELSE}TReader{$ENDIF}; tmp : TMarksItem; begin Stream.Read(tmpCount,SizeOf(tmpCount)); FItems.ILoadingCustom:=tmpCount>0; if FItems.ILoadingCustom then begin Reader:={$IFDEF CLR}TReaderAccess{$ELSE}TReader{$ENDIF}.Create(Stream,1024); for t:=0 to tmpCount-1 do begin tmp:=Items[t]; Reader.ReadListBegin; while not Reader.EndOfList do {$IFDEF CLR} Reader.DoReadProperty(tmp); {$ELSE} TReaderAccess(Reader).ReadProperty(tmp); {$ENDIF} Reader.ReadListEnd; end; Reader.Free; end; end; type {$IFDEF CLR} TWriterAccess=class(TWriter) protected procedure DoWriteProperties(Instance: TPersistent); end; {$ELSE} TWriterAccess=class(TWriter); {$ENDIF} {$IFNDEF D5} TPersistentAccess=class(TPersistent); {$ENDIF} {$IFDEF CLR} procedure TWriterAccess.DoWriteProperties(Instance: TPersistent); begin WriteProperties(Instance); end; {$ENDIF} {$IFNDEF D5} procedure WriteProperties( Writer:{$IFDEF CLR}TWriterAccess{$ELSE}TWriter{$ENDIF}; Instance: TPersistent); var I, Count: Integer; PropInfo: PPropInfo; PropList: PPropList; begin with Writer do begin Count := GetTypeData(Instance.ClassInfo)^.PropCount; if Count > 0 then begin GetMem(PropList, Count * SizeOf(Pointer)); try GetPropInfos(Instance.ClassInfo, PropList); for I := 0 to Count - 1 do begin PropInfo := PropList^[I]; if PropInfo = nil then break; if IsStoredProp(Instance, PropInfo) then {$IFDEF CLR} Writer.DoWriteProperty(Instance, PropInfo); {$ELSE} TWriterAccess(Writer).WriteProperty(Instance, PropInfo); {$ENDIF} end; finally FreeMem(PropList, Count * SizeOf(Pointer)); end; end; TPersistentAccess(Instance).DefineProperties(Writer); end; end; {$ENDIF} { internal. stores series marks items into the DFM stream } procedure TSeriesMarks.WriteItems(Stream: TStream); var tmpCount : Integer; t : Integer; Writer : {$IFDEF CLR}TWriterAccess{$ELSE}TWriter{$ENDIF}; begin tmpCount:=Items.Count; Stream.Write(tmpCount,SizeOf(tmpCount)); Writer:={$IFDEF CLR}TWriterAccess{$ELSE}TWriter{$ENDIF}.Create(Stream,1024); for t:=0 to tmpCount-1 do begin Writer.WriteListBegin; if Assigned(Items[t]) then {$IFNDEF D5} WriteProperties(Writer,Items[t]); {$ELSE} {$IFDEF CLR} Writer.DoWriteProperties(Items[t]); {$ELSE} TWriterAccess(Writer).WriteProperties(Items[t]); {$ENDIF} {$ENDIF} Writer.WriteListEnd; end; Writer.Free; end; procedure TSeriesMarks.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineBinaryProperty('Items',ReadItems,WriteItems,Items.Count>0); end; Function TSeriesMarks.GetSymbol:TSeriesMarksSymbol; begin if not Assigned(FSymbol) then FSymbol:=TSeriesMarksSymbol.Create(ParentChart); result:=FSymbol; end; procedure TSeriesMarks.SetSymbol(const Value: TSeriesMarksSymbol); begin if Assigned(Value) then Symbol.Assign(Value) else FreeAndNil(FSymbol); end; procedure TSeriesMarks.SetParent(Value: TCustomTeePanel); begin inherited; if Assigned(FCallout) then FCallout.ParentChart:=Value; if Assigned(FSymbol) then FSymbol.ParentChart:=Value; end; { TTeeFunction } Constructor TTeeFunction.Create(AOwner: TComponent); begin inherited {$IFDEF CLR}Create(AOwner){$ENDIF}; CanUsePeriod:=True; FPeriodAlign:=paCenter; FPeriodStyle:=psNumPoints; end; Procedure TTeeFunction.BeginUpdate; begin IUpdating:=True; end; Procedure TTeeFunction.EndUpdate; begin if IUpdating then begin IUpdating:=False; Recalculate; end; end; Procedure TTeeFunction.Recalculate; begin if (not IUpdating) and Assigned(FParent) then FParent.CheckDataSource; end; Function TTeeFunction.Calculate(SourceSeries:TChartSeries; First,Last:Integer):Double; begin result:=0; { abstract } end; Function TTeeFunction.ValueList(ASeries:TChartSeries):TChartValueList; var tmp : String; begin if Assigned(ParentSeries) then tmp:=ParentSeries.MandatoryValueList.ValueSource else tmp:=''; With ASeries do if tmp='' then result:=MandatoryValueList else result:=GetYValueList(tmp); end; Procedure TTeeFunction.CalculateAllPoints( Source:TChartSeries; NotMandatorySource:TChartValueList); var tmpX : Double; tmpY : Double; begin with ParentSeries do begin tmpY:=Calculate(Source,TeeAllValues,TeeAllValues); if not AllowSinglePoint then begin tmpX:=NotMandatorySource.MinValue; AddFunctionXY(Source.YMandatory,tmpX,tmpY); tmpX:=NotMandatorySource.MaxValue; AddFunctionXY(Source.YMandatory,tmpX,tmpY); end else { centered point } if (not Source.YMandatory) and (ParentSeries.YMandatory) then begin With NotMandatorySource do tmpX:=MinValue+0.5*Range; AddXY(tmpX,tmpY); end else begin With NotMandatorySource do tmpX:=MinValue+0.5*Range; if ParentSeries.YMandatory then AddFunctionXY(Source.YMandatory,tmpX,tmpY) else AddXY(tmpY,tmpX) end; end; end; Procedure TTeeFunction.CalculatePeriod( Source:TChartSeries; Const tmpX:Double; FirstIndex,LastIndex:Integer); begin AddFunctionXY( Source.YMandatory, tmpX, Calculate(Source,FirstIndex,LastIndex) ); end; Procedure TTeeFunction.CalculateByPeriod( Source:TChartSeries; NotMandatorySource:TChartValueList); var tmpX : Double; tmpCount : Integer; tmpFirst : Integer; tmpLast : Integer; tmpBreakPeriod:Double; PosFirst : Double; PosLast : Double; tmpStep : TDateTimeStep; tmpCalc : Boolean; begin With ParentSeries do begin tmpFirst:=0; tmpCount:=Source.Count; tmpBreakPeriod:=NotMandatorySource.Value[tmpFirst]; tmpStep:=FindDateTimeStep(FPeriod); Repeat PosLast:=0; if FPeriodStyle=psNumPoints then begin tmpLast:=tmpFirst+Round(FPeriod)-1; With NotMandatorySource do begin PosFirst:=Value[tmpFirst]; if tmpLast<tmpCount then PosLast:=Value[tmpLast]; end; end else begin tmpLast:=tmpFirst; PosFirst:=tmpBreakPeriod; GetHorizAxis.IncDecDateTime(True,tmpBreakPeriod,FPeriod,tmpStep); PosLast:=tmpBreakPeriod-(FPeriod*0.001); While tmpLast<(tmpCount-1) do if NotMandatorySource.Value[tmpLast+1]<tmpBreakPeriod then Inc(tmpLast) else break; end; tmpCalc:=False; if tmpLast<tmpCount then begin { align periods } if FPeriodAlign=paFirst then tmpX:=PosFirst else if FPeriodAlign=paLast then tmpX:=PosLast else tmpX:=(PosFirst+PosLast)*0.5; if (FPeriodStyle=psRange) and (NotMandatorySource.Value[tmpFirst]<tmpBreakPeriod) then tmpCalc:=True; if (FPeriodStyle=psNumPoints) or tmpCalc then CalculatePeriod(Source,tmpX,tmpFirst,tmpLast) else AddFunctionXY( Source.YMandatory, tmpX, 0 ); end; if (FPeriodStyle=psNumPoints) or tmpCalc then tmpFirst:=tmpLast+1; until tmpFirst>tmpCount-1; end; end; procedure TTeeFunction.Clear; begin // does nothing, see Bollinger function override end; Procedure TTeeFunction.AddFunctionXY(YMandatorySource:Boolean; const tmpX,tmpY:Double); begin if YMandatorySource then ParentSeries.AddXY(tmpX,tmpY) else ParentSeries.AddXY(tmpY,tmpX) end; procedure TTeeFunction.AddPoints(Source:TChartSeries); Procedure CalculateFunctionMany; var t : Integer; tmpX : Double; tmpY : Double; XList : TChartValueList; begin XList:=Source.NotMandatoryValueList; // Find datasource with bigger number of points... 5.02 with ParentSeries do for t:=0 to DataSources.Count-1 do if Assigned(DataSources[t]) and (TChartSeries(DataSources[t]).Count>Source.Count) then begin Source:=TChartSeries(DataSources[t]); XList:=Source.NotMandatoryValueList; end; // use source to calculate points... if Assigned(XList) then for t:=0 to Source.Count-1 do begin tmpX:=XList.Value[t]; tmpY:=CalculateMany(ParentSeries.DataSources,t); if not Source.YMandatory then SwapDouble(tmpX,tmpY); ParentSeries.AddXY( tmpX,tmpY,Source.Labels[t]); end; end; begin if not IUpdating then // 5.02 if Assigned(Source) then With ParentSeries do begin if DataSources.Count>1 then CalculateFunctionMany else if Source.Count>0 then DoCalculation(Source,Source.NotMandatoryValueList); end; end; Procedure TTeeFunction.DoCalculation( Source:TChartSeries; NotMandatorySource:TChartValueList); begin if FPeriod=0 then CalculateAllPoints(Source,NotMandatorySource) else CalculateByPeriod(Source,NotMandatorySource); end; Procedure TTeeFunction.SetParentSeries(AParent:TChartSeries); begin if AParent<>FParent then begin if Assigned(FParent) then FParent.FTeeFunction:=nil; AParent.SetFunction(Self); end; end; Function TTeeFunction.CalculateMany(SourceSeriesList:TList; ValueIndex:Integer):Double; begin result:=0; end; Procedure TTeeFunction.Assign(Source:TPersistent); begin if Source is TTeeFunction then With TTeeFunction(Source) do begin Self.FPeriod :=FPeriod; Self.FPeriodStyle:=FPeriodStyle; Self.FPeriodAlign:=FPeriodAlign; end; end; Procedure TTeeFunction.InternalSetPeriod(Const APeriod:Double); begin FPeriod:=APeriod; end; Procedure TTeeFunction.SetPeriod(Const Value:Double); begin {$IFDEF CLR} // RTL.NET bug loading double properties from dfm. FPeriod:=1; Recalculate; {$ELSE} if Value<0 then Raise ChartException.Create(TeeMsg_FunctionPeriod); if FPeriod<>Value then begin FPeriod:=Value; Recalculate; end; {$ENDIF} end; Procedure TTeeFunction.SetPeriodAlign(Value:TFunctionPeriodalign); begin if Value<>FPeriodAlign then begin FPeriodAlign:=Value; Recalculate; end; end; Procedure TTeeFunction.SetPeriodStyle(Value:TFunctionPeriodStyle); begin if Value<>FPeriodStyle then begin FPeriodStyle:=Value; Recalculate; end; end; function TTeeFunction.GetParentComponent: TComponent; begin result:=FParent; end; procedure TTeeFunction.SetParentComponent(Value: TComponent); begin if Assigned(Value) then ParentSeries:=TChartSeries(Value); end; function TTeeFunction.HasParent: Boolean; begin result:=True; end; Function TTeeFunction.IsValidSource(Value:TChartSeries):Boolean; Begin result:=True; { abstract } end; { TeeMovingFunction } Constructor TTeeMovingFunction.Create(AOwner:TComponent); begin inherited; InternalSetPeriod(1); SingleSource:=True; end; // Calls "Calculate" function for each group of Period points. // ie: When Period=10, calls: // Calculate(0,9) Calculate(1,10) Calculate(2,11)... etc Procedure TTeeMovingFunction.DoCalculation( Source:TChartSeries; NotMandatorySource:TChartValueList); Var t : Integer; P : Integer; begin P:=Round(FPeriod); for t:=P-1 to Source.Count-1 do AddFunctionXY( Source.YMandatory, NotMandatorySource.Value[t], Calculate(Source,t-P+1,t)); end; class function TTeeFunction.GetEditorClass: String; begin result:='TTeeFunctionEditor'; // Default editor // 6.0 end; {$IFNDEF CLR} type TSeriesAccess=class(TChartSeries); {$ENDIF} class Procedure TTeeFunction.PrepareForGallery(Chart:TCustomAxisPanel); var t : Integer; begin for t:=0 to Chart.SeriesCount-1 do {$IFNDEF CLR}TSeriesAccess{$ENDIF}(Chart[t]).PrepareForGallery(True); end; { TCustomChartElement } Constructor TCustomChartElement.Create(AOwner: TComponent); begin inherited {$IFDEF CLR}Create(AOwner){$ENDIF}; FActive:=True; FBrush:=TChartBrush.Create(CanvasChanged); FPen:=CreateChartPen; end; Destructor TCustomChartElement.Destroy; begin FPen.Free; FBrush.Free; {$IFNDEF D5} Destroying; {$ENDIF} ParentChart:=nil; inherited; end; procedure TCustomChartElement.Assign(Source:TPersistent); Begin if Source is TCustomChartElement then With TCustomChartElement(Source) do begin Self.FActive:= FActive; Self.Brush := FBrush; Self.Pen := FPen; Self.Tag := Tag; end else inherited; end; Procedure TCustomChartElement.CanvasChanged(Sender:TObject); Begin Repaint; end; Function TCustomChartElement.CreateChartPen:TChartPen; begin result:=TChartPen.Create(CanvasChanged); end; { Returns the Form class name that allows editing our properties } class Function TCustomChartElement.GetEditorClass:String; Begin result:=''; end; procedure TCustomChartElement.SetBrush(const Value: TChartBrush); begin FBrush.Assign(Value); end; procedure TCustomChartElement.SetPen(const Value: TChartPen); begin FPen.Assign(Value); end; Procedure TCustomChartElement.Repaint; Begin if Assigned(FParent) then FParent.Invalidate; end; Procedure TCustomChartElement.SetActive(Value:Boolean); Begin SetBooleanProperty(FActive,Value); end; { Changes the Parent property } Procedure TCustomChartElement.SetParentChart(Const Value:TCustomAxisPanel); begin FParent:=Value; {$IFDEF TEETRIAL} if Assigned(TeeAboutBoxProc) and not (csDesigning in ComponentState) then TeeAboutBoxProc; {$ENDIF} end; { Changes the Variable parameter with the Value and repaints if different } Procedure TCustomChartElement.SetBooleanProperty(Var Variable:Boolean; Value:Boolean); Begin if Variable<>Value then begin Variable:=Value; Repaint; end; end; { Changes the Variable parameter with the Value and repaints if different } Procedure TCustomChartElement.SetColorProperty(Var Variable:TColor; Value:TColor); Begin if Variable<>Value then begin Variable:=Value; Repaint; end; end; { Changes the Variable parameter with the Value and repaints if different } Procedure TCustomChartElement.SetDoubleProperty(Var Variable:Double; Const Value:Double); begin if Variable<>Value then begin Variable:=Value; Repaint; end; end; { Changes the Variable parameter with the Value and repaints if different } Procedure TCustomChartElement.SetIntegerProperty(Var Variable:Integer; Value:Integer); Begin if Variable<>Value then begin Variable:=Value; Repaint; end; end; { Changes the Variable parameter with the Value and repaints if different } Procedure TCustomChartElement.SetStringProperty(Var Variable:String; Const Value:String); Begin if Variable<>Value then begin Variable:=Value; Repaint; end; end; { Internal. VCL mechanism to define parentship between chart and series. } function TCustomChartElement.GetParentComponent: TComponent; begin result:=FParent; end; { Internal. VCL mechanism to define parentship between chart and series. } procedure TCustomChartElement.SetParentComponent(AParent: TComponent); begin if AParent is TCustomAxisPanel then ParentChart:=TCustomAxisPanel(AParent); end; { Internal. VCL mechanism to define parentship between chart and series. } function TCustomChartElement.HasParent: Boolean; begin result:=True; end; { TCustomChartSeries } Constructor TCustomChartSeries.Create(AOwner: TComponent); begin inherited; FShowInLegend:=True; end; Procedure TCustomChartSeries.Added; { virtual } begin end; { copy basic properties from one series to self } procedure TCustomChartSeries.Assign(Source:TPersistent); Begin if Source is TCustomChartSeries then With TCustomChartSeries(Source) do begin Self.FShowInLegend := FShowInLegend; Self.FTitle := FTitle; Self.FStyle := FStyle; Self.FIdentifier := FIdentifier; end; inherited; end; { Internal. Used in Decision Graph component. } procedure TCustomChartSeries.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('Identifier',ReadIdentifier,WriteIdentifier,Identifier<>''); { <-- don't translate } Filer.DefineProperty('Style',ReadStyle,WriteStyle,Style<>[]); { <-- don't translate } end; { Internal. Used in Decision Graph component. } procedure TCustomChartSeries.ReadIdentifier(Reader: TReader); begin Identifier:=Reader.ReadString; end; { Internal. Used in Decision Graph component. } procedure TCustomChartSeries.WriteIdentifier(Writer: TWriter); begin Writer.WriteString(Identifier); end; { Internal. Used in Decision Graph component. } procedure TCustomChartSeries.ReadStyle(Reader: TReader); var tmp : Integer; begin tmp:=Reader.ReadInteger; FStyle:=[]; if (tmp and 1)=1 then FStyle:=FStyle+[tssIsTemplate]; if (tmp and 2)=2 then FStyle:=FStyle+[tssDenyChangeType]; if (tmp and 4)=4 then FStyle:=FStyle+[tssDenyDelete]; if (tmp and 8)=8 then FStyle:=FStyle+[tssDenyClone]; if (tmp and 16)=16 then FStyle:=FStyle+[tssIsPersistent]; if (tmp and 32)=32 then FStyle:=FStyle+[tssHideDataSource]; end; { Internal. Used in Decision Graph component (Decision Cube components). } procedure TCustomChartSeries.WriteStyle(Writer: TWriter); var tmp : Integer; begin tmp:=0; if tssIsTemplate in FStyle then Inc(tmp); if tssDenyChangeType in FStyle then Inc(tmp,2); if tssDenyDelete in FStyle then Inc(tmp,4); if tssDenyClone in FStyle then Inc(tmp,8); if tssIsPersistent in FStyle then Inc(tmp,16); if tssHideDataSource in FStyle then Inc(tmp,32); Writer.WriteInteger(tmp); end; { Returns the number of pixels for horizontal margins } Procedure TCustomChartSeries.CalcHorizMargins(Var LeftMargin,RightMargin:Integer); begin LeftMargin:=0; RightMargin:=0; { abstract } end; { Returns the number of pixels for vertical margins } Procedure TCustomChartSeries.CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); begin TopMargin:=0; BottomMargin:=0; { abstract } end; procedure TCustomChartSeries.DoBeforeDrawChart; begin end; { Called when the Gallery "3D" option is changed. } Procedure TCustomChartSeries.GalleryChanged3D(Is3D:Boolean); begin ParentChart.View3D:=Is3D; end; Procedure TCustomChartSeries.Removed; begin FParent:=nil; end; { Returns True when the tmpSeries parameter is of the same class } Function TCustomChartSeries.SameClass(tmpSeries:TChartSeries):Boolean; begin result:=( (Self is tmpSeries.ClassType) or (tmpSeries is Self.ClassType)); end; { Tells the design-time Series Designer window to repaint } Procedure TCustomChartSeries.RepaintDesigner; begin if Assigned(ParentChart) and Assigned(ParentChart.Designer) then ParentChart.Designer.Repaint; end; { show / hide Series } Procedure TCustomChartSeries.SetActive(Value:Boolean); Begin inherited; if Assigned(ParentChart) then ParentChart.BroadcastSeriesEvent(Self,seChangeActive); RepaintDesigner; end; Procedure TCustomChartSeries.SetShowInLegend(Value:Boolean); Begin SetBooleanProperty(FShowInLegend,Value); end; { change the Series "Title" (custom text) } Procedure TCustomChartSeries.SetTitle(Const Value:String); Begin SetStringProperty(FTitle,Value); if Assigned(ParentChart) then ParentChart.BroadcastSeriesEvent(Self,seChangeTitle); RepaintDesigner; end; { TChartValueLists } Procedure TChartValueLists.Clear; var t : Integer; begin for t:=0 to Count-1 do ValueList[t].Free; inherited; end; Function TChartValueLists.Get(Index:Integer):TChartValueList; begin result:=TChartValueList({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]); end; { TChartSeries } Constructor TChartSeries.Create(AOwner: TComponent); begin inherited; FZOrder:=TeeAutoZOrder; FDepth:=TeeAutoDepth; FHorizAxis:=aBottomAxis; FVertAxis:=aLeftAxis; FValuesList:=TChartValueLists.Create; FX:=TChartValueList.Create(Self,TeeMsg_ValuesX); FX.FOrder:=loAscending; NotMandatoryValueList:=FX; FY:=TChartValueList.Create(Self,TeeMsg_ValuesY); MandatoryValueList:=FY; YMandatory:=True; FLabels:=TLabelsList.Create; FLabels.Series:=Self; FColor:=clTeeColor; ISeriesColor:=clTeeColor; FCursor:=crDefault; FMarks:=TSeriesMarks.Create(Self); FValueFormat :=TeeMsg_DefValueFormat; FPercentFormat :=TeeMsg_DefPercentFormat; FDataSources:=TDataSourcesList.Create; FDataSources.Series:=Self; FLinkedSeries :=TCustomSeriesList.Create; FRecalcOptions := [rOnDelete,rOnModify,rOnInsert,rOnClear]; FFirstVisibleIndex:=-1; FLastVisibleIndex :=-1; AllowSinglePoint :=True; CalcVisiblePoints :=True; IUseSeriesColor :=True; IUseNotMandatory :=True; end; { Frees all properties } Destructor TChartSeries.Destroy; Var t : Integer; Begin if Assigned(FTeeFunction) {$IFDEF CLX} and (not (csDestroying in FTeeFunction.ComponentState)) {$ENDIF} then FreeAndNil(FTeeFunction); RemoveAllLinkedSeries; if Assigned(DataSource) and (DataSource.Owner=Self) then DataSource.Free; { 5.02 } FreeAndNil(FDataSources); if Assigned(FLinkedSeries) then // 5.02 for t:=0 to FLinkedSeries.Count-1 do FLinkedSeries[t].RemoveDataSource(Self); Clear; FreeAndNil(FLinkedSeries); FValuesList.Free; FColors.Free; FLabels.Free; FreeAndNil(FMarks); // 5.01 inherited; end; { Returns True when in design-mode or when we want random sample points for the series at run-time. } Function TChartSeries.CanAddRandomPoints:Boolean; begin result:=TeeRandomAtRunTime or (csDesigning in ComponentState); end; Procedure TChartSeries.ChangeInternalColor(Value:TColor); begin ISeriesColor:=Value; SeriesColor:=ISeriesColor; end; { Called when the series is added into a Chart series list. } Procedure TChartSeries.Added; begin inherited; if FColor=clTeeColor then begin ChangeInternalColor(FParent.GetFreeSeriesColor); NotifyColorChanged; end; RecalcGetAxis; CheckDataSource; end; { Called when the series is removed from a Chart series list. } Procedure TChartSeries.Removed; begin if Cursor=FParent.Cursor then { restore cursor } FParent.Cursor:=FParent.OriginalCursor; RemoveAllLinkedSeries; inherited; end; procedure TChartSeries.CalcDepthPositions; begin StartZ:=IZOrder*ParentChart.SeriesWidth3D; if Depth=-1 then EndZ:=StartZ+ParentChart.SeriesWidth3D else EndZ:=StartZ+Depth; MiddleZ:=(StartZ+EndZ) div 2; FMarks.ZPosition:=MiddleZ; end; { internal. Called by Chart. Raises OnMouseEnter or OnMouseLeave events, and changes Cursor. Returns True if Clicked and Cursor <> crDefault. } Function TChartSeries.CheckMouse(x,y:Integer):Boolean; begin result:=False; if (Cursor<>crDefault) or Assigned(FOnMouseEnter) or Assigned(FOnMouseLeave) then begin if Clicked(X,Y)<>-1 then { <-- mouse is over a Series value ! } Begin if Cursor<>crDefault then ParentChart.Cursor:=Cursor; if not IsMouseInside then begin IsMouseInside:=True; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); end; result:=True; end else begin if IsMouseInside then begin IsMouseInside:=False; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; end; end; end; { internal. VCL streaming mechanism. Stores the Function, if any. } Procedure TChartSeries.GetChildren(Proc:TGetChildProc; Root:TComponent); begin inherited; if Assigned(FunctionType) then Proc(FunctionType); end; { Sets the chart that will contain and display the series } Procedure TChartSeries.SetParentChart(Const Value:TCustomAxisPanel); Begin if FParent<>Value then Begin if Assigned(FParent) then FParent.RemoveSeries(Self); inherited; if Assigned(FMarks) then FMarks.ParentChart:=FParent; if Assigned(FParent) then FParent.InternalAddSeries(Self); end; end; { Associates the series to a function } procedure TChartSeries.SetFunction(AFunction:TTeeFunction); begin if FTeeFunction<>AFunction then begin FTeeFunction.Free; { set new function } FTeeFunction:=AFunction; if Assigned(FTeeFunction) then begin FTeeFunction.FParent:=Self; ManualData:=False; end; { force recalculation (add points using function or clear) } CheckDataSource; end; end; // When the data source is destroyed, sets it to nil. procedure TChartSeries.Notification( AComponent: TComponent; Operation: TOperation); begin inherited; if Operation=opRemove then if AComponent=FTeeFunction then FTeeFunction:=nil else { if "AComponent" is the same as series datasource, then set datasource to nil } if AComponent=DataSource then InternalRemoveDataSource(AComponent); // 7.0 end; { Hidden properties. Defines them to store / load from the DFM stream } procedure TChartSeries.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('DataSources',ReadDataSources,WriteDataSources,FDataSources.Count > 1); { <-- don't translate } Filer.DefineProperty('CustomHorizAxis', ReadCustomHorizAxis, WriteCustomHorizAxis,Assigned(FCustomHorizAxis)); { <-- don't translate } Filer.DefineProperty('CustomVertAxis', ReadCustomVertAxis, WriteCustomVertAxis,Assigned(FCustomVertAxis)); { <-- don't translate } Filer.DefineBinaryProperty('Data',ReadData,WriteData, ForceSaveData or (ManualData and (not DontSaveData))); end; procedure TChartSeries.ReadData(Stream: TStream); Function ReadColor:TColor; {$IFDEF CLR} var tmp : Integer; {$ENDIF} begin {$IFDEF CLR} Stream.Read(tmp,Sizeof(tmp)); result:=TColor(tmp); {$ELSE} Stream.Read(result,Sizeof(result)); {$ENDIF} end; Function ReadLabel:String; Var L : Byte; {$IFDEF CLR} Bytes : TBytes; {$ENDIF} begin L:=0; { read the label length } Stream.Read(L, SizeOf(L)); { read the label contents } {$IFDEF CLR} SetLength(Bytes,L); Stream.Read(Bytes, L); Result:=String(Bytes); {$ELSE} SetString(Result, nil, L); Stream.Read(Pointer(Result)^, L); {$ENDIF} end; Var tmpFormat : TeeFormatFlag; ValuesListCount : Integer; NotYMandatory : Boolean; Procedure ReadSeriesPoint(Index:Integer); Var tmpFloat : Double; Ax : Double; Ay : Double; AColor : TColor; ALabel : String; tt : Integer; tmp : TSeriesMarkPosition; {$IFDEF CLR} tmpBoolean : Byte; {$ENDIF} begin { read the "X" value if exists } if tfNoMandatory in tmpFormat then Stream.Read(AX,Sizeof(AX)) else AX:=Index; { 5.01 } { read the "Y" value } Stream.Read(AY,Sizeof(AY)); { Swap X <--> Y if necessary... } if NotYMandatory then SwapDouble(AX,AY); { read the Color value if exists } if tfColor in tmpFormat then AColor:=ReadColor else AColor:=clTeeColor; { read the Label value if exists } if tfLabel in tmpFormat then ALabel:=ReadLabel else ALabel:=''; { read the rest of lists values } for tt:=2 to ValuesListCount-1 do begin Stream.Read(tmpFloat,SizeOf(tmpFloat)); ValuesList[tt].TempValue:=tmpFloat; end; { add the new point } AddXY(AX,AY,ALabel,AColor); { 5.01 } if tfMarkPosition in tmpFormat then begin tmp:=TSeriesMarkPosition.Create; With tmp,Stream do begin {$IFDEF CLR} Read(ArrowFrom.X,SizeOf(ArrowFrom.X)); Read(ArrowFrom.Y,SizeOf(ArrowFrom.Y)); Read(tmpBoolean,SizeOf(tmpBoolean)); ArrowFix:=tmpBoolean=1; Read(ArrowTo.X,SizeOf(ArrowTo.X)); Read(ArrowTo.Y,SizeOf(ArrowTo.Y)); Read(tmpBoolean,SizeOf(tmpBoolean)); Custom:=tmpBoolean=1; {$ELSE} Read(ArrowFrom,SizeOf(ArrowFrom)); Read(ArrowFix,SizeOf(ArrowFix)); Read(ArrowTo,SizeOf(ArrowTo)); Read(Custom,SizeOf(Custom)); {$ENDIF} Read(Height,SizeOf(Height)); {$IFDEF CLR} Read(LeftTop.X,SizeOf(LeftTop.X)); Read(LeftTop.Y,SizeOf(LeftTop.Y)); {$ELSE} Read(LeftTop,SizeOf(LeftTop)); {$ENDIF} Read(Width,SizeOf(Width)); end; Marks.Positions.Add(tmp); end; end; Var tmpCount : Integer; t : Integer; {$IFDEF CLR} tmpByte : Byte; {$ENDIF} begin { empty the Series } Clear; { read the point flags } {$IFDEF CLR} Stream.Read(tmpByte,SizeOf(tmpByte)); tmpFormat:=TeeFormatFlag(tmpByte); {$ELSE} Stream.Read(tmpFormat,SizeOf(tmpFormat)); {$ENDIF} { read the number of points } Stream.Read(tmpCount,Sizeof(tmpCount)); { read each point } NotYMandatory:=MandatoryValueList<>YValues; ValuesListCount:=ValuesList.Count; BeginUpdate; // 6.01 try for t:=0 to tmpCount-1 do ReadSeriesPoint(t); finally EndUpdate; end; ManualData:=True; end; { internal. Loads data sources from the DFM stream } procedure TChartSeries.ReadDataSources(Reader: TReader); begin Reader.ReadListBegin; FTempDataSources:=TStringList.Create; With FTempDataSources do begin Clear; while not Reader.EndOfList do Add(Reader.ReadString); end; Reader.ReadListEnd; end; procedure TChartSeries.WriteData(Stream: TStream); Procedure WriteLabel(Const AString:String); Var L : Byte; begin L:=Length(AString); Stream.Write(L,SizeOf(L)); {$IFDEF CLR} Stream.Write(BytesOf(AString), L); {$ELSE} Stream.Write(PChar(AString)^,L); {$ENDIF} end; Var tmpFormat : TeeFormatFlag; tmpNoMandatory : TChartValueList; Procedure WriteSeriesPoint(Index:Integer); Var tmpFloat : Double; tt : Integer; tmpColor : TColor; {$IFDEF CLR} tmpByte : Array[0..0] of Byte; {$ENDIF} begin { write the "X" point value, if exists } if tfNoMandatory in tmpFormat then begin tmpFloat:=tmpNoMandatory.Value[Index]; Stream.Write(tmpFloat,Sizeof(tmpFloat)); end; { write the "Y" point value } tmpFloat:=MandatoryValueList.Value[Index]; Stream.Write(tmpFloat,Sizeof(tmpFloat)); { write the Color point value, if exists } if tfColor in tmpFormat then begin tmpColor:=InternalColor(Index); Stream.Write(tmpColor,Sizeof(tmpColor)); end; { write the Label point value, if exists } if tfLabel in tmpFormat then WriteLabel(Labels[Index]); { write the rest of values (always) } for tt:=2 to ValuesList.Count-1 do begin tmpFloat:=ValuesList[tt].Value[Index]; Stream.Write(tmpFloat,SizeOf(tmpFloat)); end; if tfMarkPosition in tmpFormat then begin With Marks.Positions[Index],Stream do begin {$IFDEF CLR} Write(ArrowFrom.X,SizeOf(ArrowFrom.X)); Write(ArrowFrom.Y,SizeOf(ArrowFrom.Y)); if ArrowFix then tmpByte[0]:=1 else tmpByte[0]:=0; Write(tmpByte,1); Write(ArrowTo.X,SizeOf(ArrowTo.X)); Write(ArrowTo.Y,SizeOf(ArrowTo.Y)); if Custom then tmpByte[0]:=1 else tmpByte[0]:=0; Write(tmpByte,1); {$ELSE} Write(ArrowFrom,SizeOf(ArrowFrom)); Write(ArrowFix,SizeOf(ArrowFix)); Write(ArrowTo,SizeOf(ArrowTo)); Write(Custom,SizeOf(Custom)); {$ENDIF} Write(Height,SizeOf(Height)); {$IFDEF CLR} Write(LeftTop.X,SizeOf(LeftTop.X)); Write(LeftTop.Y,SizeOf(LeftTop.Y)); {$ELSE} Write(LeftTop,SizeOf(LeftTop)); {$ENDIF} Write(Width,SizeOf(Width)); end; end; end; var t : Integer; tmp : Integer; {$IFDEF CLR} tmpByte : Array[0..0] of Byte; {$ENDIF} begin { write the "flag" containing the format of a point } tmpFormat:=SeriesGuessContents(Self); {$IFDEF CLR} tmpByte[0]:=Byte(tmpFormat); Stream.Write(tmpByte,1); {$ELSE} Stream.Write(tmpFormat,SizeOf(tmpFormat)); {$ENDIF} { write all points. pre-calculate tmpNoMandatory } tmpNoMandatory:=NotMandatoryValueList; { write the number of points } tmp:=Count; Stream.Write(tmp,Sizeof(tmp)); for t:=0 to tmp-1 do WriteSeriesPoint(t); end; { internal. stores data sources into the DFM stream } procedure TChartSeries.WriteDataSources(Writer: TWriter); var t : Integer; begin With Writer do begin WriteListBegin; With DataSources do for t:=0 to Count-1 do WriteString(TComponent(Items[t]).Name); WriteListEnd; end; end; { Returns True (the default), when visible points in the series should be drawn in ascending order. } Function TChartSeries.DrawValuesForward:Boolean; begin if YMandatory then begin result:=not GetHorizAxis.Inverted; if ParentChart.InvertedRotation then result:=not result; end else result:=not GetVertAxis.Inverted; end; { Returns True (the default), when several series sharing the same Z order should be drawn in ascending order (the same order the series have inside the SeriesList. } Function TChartSeries.DrawSeriesForward(ValueIndex:Integer):Boolean; begin result:=not ParentChart.InvertedRotation; { abstract } end; { Calls DrawValue for all points that are visible. } procedure TChartSeries.DrawAllValues; Var t : Integer; Begin if DrawValuesForward then { normal "left to right" order } for t:=FFirstVisibleIndex to FLastVisibleIndex do DrawValue(t) else { "right to left" } for t:=FLastVisibleIndex downto FFirstVisibleIndex do DrawValue(t); End; { tell the Chart to refresh series data using Series.DataSource(s) } Procedure TChartSeries.CheckDataSource; begin if (IUpdating=0) and Assigned(FParent) then FParent.CheckDataSource(Self); end; { Change the "source" (ie: Table Field name) associated to series points colors. } Procedure TChartSeries.SetColorSource(Const Value:String); Begin if FColorSource<>Value then Begin FColorSource:=Value; CheckDataSource; end; end; { Change the "source" (ie: Table Field name) associated to series text labels. } Procedure TChartSeries.SetLabelsSource(Const Value:String); Begin if FLabelsSource<>Value then Begin FLabelsSource:=Value; CheckDataSource; end; end; { Returns the point index that is under the XY screen mouse position. } { Returns -1 if no points are found under XY } Function TChartSeries.GetCursorValueIndex:Integer; Begin result:=Clicked(ParentChart.GetCursorPos); end; { Returns the X and Y values that correspond to the mouse screen position. } Procedure TChartSeries.GetCursorValues(Var XValue,YValue:Double); Begin With ParentChart.GetCursorPos do { mouse XY position } begin { convert XY pixel position to axis scales } XValue:=GetHorizAxis.CalcPosPoint(X); YValue:=GetVertAxis.CalcPosPoint(Y); end; end; // Returns the "default" data source component. // It is the first component in the DataSources list. Function TChartSeries.GetDataSource:TComponent; begin if Assigned(FDataSources) and (DataSources.Count>0) then result:={$IFDEF CLR}TComponent{$ENDIF}(DataSources[0]) else result:=nil; end; { add the Value component as datasource. if Value is a Series, add ourselves to Value list of "linked" series } Function TChartSeries.InternalAddDataSource(Value:TComponent):Integer; var Old : Boolean; begin if Assigned(Value) then begin result:=DataSources.InheritedAdd(Value); // 6.02 ManualData:=False; if Value is TChartSeries then TChartSeries(Value).AddLinkedSeries(Self) else begin Value.FreeNotification(Self); { set ourselves as the Series for Value DataSource } if Value is TTeeSeriesSource then with TTeeSeriesSource(Value) do begin if FSeries<>Self then begin Old:=Active; Close; if Value.Owner=FSeries then begin FSeries.RemoveComponent(Value); Self.InsertComponent(Value); end; {$IFDEF D5} if Assigned(FSeries) then FSeries.RemoveFreeNotification(Value); {$ENDIF} FSeries:=Self; FSeries.FreeNotification(Value); if Old then Open; end; end; end; end else result:=-1; end; { When this series is a datasource for other series, this method tells the other series to remove the reference to itself. } Procedure TChartSeries.RemoveAllLinkedSeries; var t : Integer; begin if Assigned(FDataSources) then for t:=0 to DataSources.Count-1 do if Assigned(DataSources[t]) and (TObject(DataSources[t]) is TChartSeries) then // 6.02, changed to TObject TChartSeries(DataSources[t]).RemoveLinkedSeries(Self); end; Function TChartSeries.InternalSetDataSource(Value:TComponent; ClearAll:Boolean):Integer; Function DoSetDataSource:Integer; Begin result:=-1; if DataSources.IndexOf(Value)=-1 then begin if Value is TChartSeries then CheckOtherSeries(TChartSeries(Value)); if ClearAll and (not (csLoading in ComponentState)) then DataSources.Clear; // 6.02 result:=InternalAddDataSource(Value); CheckDataSource; end; end; begin if not Assigned(FParent) then {$IFDEF CLR} if (csLoading in ComponentState) and (csDesigning in ComponentState) then result:=DoSetDataSource else {$ENDIF} raise ChartException.Create(TeeMsg_SeriesSetDataSource) else if FParent.IsValidDataSource(Self,Value) then result:=DoSetDataSource else Raise ChartException.CreateFmt(TeeMsg_SeriesInvDataSource,[Value.Name]); end; Procedure TChartSeries.InternalRemoveDataSource(Value:TComponent); Begin {$IFNDEF TEEOCX} if not (csDestroying in ComponentState) then { 5.02 } {$ENDIF} begin if Assigned(FParent) and Assigned(DataSource) then FParent.RemovedDataSource(Self,Value); if Value=DataSource then DataSources.Clear; CheckDataSource; end; end; { Replaces the DataSource for the series. } Procedure TChartSeries.SetDataSource(Value:TComponent); begin if Assigned(Value) then InternalSetDataSource(Value,True) else InternalRemoveDataSource(Value); end; Function TChartSeries.IsValidSourceOf(Value:TChartSeries):Boolean; Begin result:=Value<>Self; { abstract } end; Function TChartSeries.IsValidSeriesSource(Value:TChartSeries):Boolean; Begin result:=(not Assigned(FTeeFunction)) or FTeeFunction.IsValidSource(Value); { abstract } end; { Returns the value list that has the AListName parameter. } Function TChartSeries.GetYValueList(AListName:String):TChartValueList; Var t : Integer; Begin AListName:={$IFDEF CLR}Uppercase{$ELSE}AnsiUppercase{$ENDIF}(AListName); for t:=2 to FValuesList.Count-1 do if AListName={$IFDEF CLR}Uppercase{$ELSE}AnsiUpperCase{$ENDIF}(FValuesList[t].Name) then Begin result:=FValuesList[t]; exit; end; result:=FY; end; Procedure TChartSeries.CheckOtherSeries(Source:TChartSeries); Begin if Assigned(FParent) then FParent.CheckOtherSeries(Self,Source); end; { Replaces the colors for points in the value list that have values between FromValue and ToValue. } Procedure TChartSeries.ColorRange( AValueList:TChartValueList; Const FromValue,ToValue:Double; AColor:TColor); var t : Integer; tmpValue : Double; begin for t:=0 to AValueList.Count-1 do Begin tmpValue:=AValueList.Value[t]; if (tmpValue>=FromValue) and (tmpValue<=ToValue) and (not IsNull(t)) then ValueColor[t]:=AColor; end; Repaint; end; { Returns the point index that is under the X Y pixel screen position. } Function TChartSeries.Clicked(x,y:Integer):Integer; begin Result:=TeeNoPointClicked; { abstract, no point clicked } end; Function TChartSeries.Clicked(P:TPoint):Integer; begin result:=Clicked(P.X,P.Y); end; { Obtains pointers to the associated axes. This is done to optimize speed (cache) when locating the associated axes. } Procedure TChartSeries.RecalcGetAxis; Begin if Assigned(FParent) then begin { horizontal axis } FGetHorizAxis:=FParent.FBottomAxis; Case FHorizAxis of aTopAxis : FGetHorizAxis:=FParent.FTopAxis; aCustomHorizAxis: if Assigned(FCustomHorizAxis) then FGetHorizAxis:=FCustomHorizAxis; end; { vertical axis } FGetVertAxis:=FParent.LeftAxis; Case FVertAxis of aRightAxis : FGetVertAxis:=FParent.FRightAxis; aCustomVertAxis: if Assigned(FCustomVertAxis) then FGetVertAxis:=FCustomVertAxis; end; end else begin FGetHorizAxis:=nil; FGetVertAxis:=nil; end; end; { internal. read custom horizontal axis from DFM stream } procedure TChartSeries.ReadCustomHorizAxis(Reader: TReader); begin CustomHorizAxis:=FParent.CustomAxes[Reader.ReadInteger]; end; { internal. read custom vertical axis from DFM stream } procedure TChartSeries.ReadCustomVertAxis(Reader: TReader); begin CustomVertAxis:=FParent.CustomAxes[Reader.ReadInteger]; end; { internal. store custom horizontal axis into DFM stream } procedure TChartSeries.WriteCustomHorizAxis(Writer: TWriter); begin Writer.WriteInteger(FCustomHorizAxis.Index); end; { internal. store custom vertical axis into DFM stream } procedure TChartSeries.WriteCustomVertAxis(Writer: TWriter); begin Writer.WriteInteger(FCustomVertAxis.Index); end; { change the series horizontal axis } Procedure TChartSeries.SetHorizAxis(const Value:THorizAxis); Begin if FHorizAxis<>Value then begin FHorizAxis:=Value; if (HorizAxis<>aCustomHorizAxis) and (not (csLoading in ComponentState)) then FCustomHorizAxis:=nil; RecalcGetAxis; Repaint; end; end; { change the series vertical axis } Procedure TChartSeries.SetVertAxis(const Value:TVertAxis); Begin if FVertAxis<>Value then begin FVertAxis:=Value; if (VertAxis<>aCustomVertAxis) and (not (csLoading in ComponentState)) then FCustomVertAxis:=nil; RecalcGetAxis; Repaint; end; end; Procedure TChartSeries.SetChartValueList( AValueList:TChartValueList; Value:TChartValueList); Begin AValueList.Assign(Value); Repaint; end; Procedure TChartSeries.SetXValues(Value:TChartValueList); Begin SetChartValueList(FX,Value); end; Procedure TChartSeries.SetYValues(Value:TChartValueList); Begin SetChartValueList(FY,Value); end; Function TChartSeries.ValueListOfAxis(Axis:TChartAxis):TChartValueList; begin if AssociatedToAxis(Axis) then if Axis.Horizontal then result:=FX else result:=FY else result:=nil; end; { Calculates the range of points that are visible. This depends on the series associated vertical and horizontal axis scales (minimum and maximum). } Procedure TChartSeries.CalcFirstLastVisibleIndex; Function CalcMinMaxValue(A,B,C,D:Integer):Double; begin if YMandatory then With GetHorizAxis do if Inverted then result:=CalcPosPoint(C) else result:=CalcPosPoint(A) else With GetVertAxis do if Inverted then result:=CalcPosPoint(B) else result:=CalcPosPoint(D); end; Var tmpMin : Double; tmpMax : Double; tmpLastIndex : Integer; Begin FFirstVisibleIndex:=-1; FLastVisibleIndex:=-1; if Count>0 then Begin tmpLastIndex:=Count-1; if CalcVisiblePoints and (NotMandatoryValueList.Order<>loNone) then begin { NOTE: The code below does NOT use a "divide by 2" (bubble) algorithm because the tmpMin value might not have any correspondence with a Series point. When the Series point values are "floating" (not integer) the "best" solution is to do a lineal all-traverse search. However, this code can still be optimized. It will be revisited for next coming releases. } With ParentChart.ChartRect do tmpMin:=CalcMinMaxValue(Left,Top,Right,Bottom); FFirstVisibleIndex:=0; While NotMandatoryValueList.Value[FFirstVisibleIndex]<tmpMin do Begin Inc(FFirstVisibleIndex); if FFirstVisibleIndex>tmpLastIndex then begin FFirstVisibleIndex:=-1; break; end; end; if FFirstVisibleIndex>=0 then Begin With ParentChart.ChartRect do tmpMax:=CalcMinMaxValue(Right,Bottom,Left,Top); if NotMandatoryValueList.Last<=tmpMax then FLastVisibleIndex:=tmpLastIndex else Begin FLastVisibleIndex:=FFirstVisibleIndex; While NotMandatoryValueList.Value[FLastVisibleIndex]<tmpMax do begin Inc(FLastVisibleIndex); if FLastVisibleIndex>tmpLastIndex then begin FLastVisibleIndex:=tmpLastIndex; break; end; end; if (not DrawBetweenPoints) and (NotMandatoryValueList.Value[FLastVisibleIndex]>tmpMax) then Dec(FLastVisibleIndex); end; end; end else begin FFirstVisibleIndex:=0; FLastVisibleIndex:=tmpLastIndex; end; end; end; procedure TChartSeries.DrawValue(ValueIndex:Integer); begin { nothing } end; Function TChartSeries.IsValueFormatStored:Boolean; Begin result:=FValueFormat<>TeeMsg_DefValueFormat; end; Function TChartSeries.IsPercentFormatStored:Boolean; Begin result:=FPercentFormat<>TeeMsg_DefPercentFormat; end; Procedure TChartSeries.DeletedValue(Source:TChartSeries; ValueIndex:Integer); Begin Delete(ValueIndex); end; Function TChartSeries.AddChartValue(Source:TChartSeries; ValueIndex:Integer):Integer; var t : Integer; tmp : Integer; tmpX : Double; tmpY : Double; begin With Source do begin tmpX:=FX.Value[ValueIndex]; tmpY:=FY.Value[ValueIndex]; end; { if we are adding values from (for example) an Horizontal Bar series... } if Self.YMandatory<>Source.YMandatory then SwapDouble(tmpX,tmpY); { pending: if ...FY.Order<>loNone then (inverted) } result:=FX.AddChartValue(tmpX); FY.InsertChartValue(result,tmpY); { rest of lists... } tmp:=Source.ValuesList.Count-1; for t:=2 to FValuesList.Count-1 do begin if t<=tmp then tmpY:=Source.FValuesList[t].Value[ValueIndex] else tmpY:=0; FValuesList[t].InsertChartValue(result,tmpY); end; end; { Called when a new value is added to the series. } Procedure TChartSeries.AddedValue(Source:TChartSeries; ValueIndex:Integer); Var tmpIndex : Integer; Begin tmpIndex:=AddChartValue(Source,ValueIndex); if Assigned(Source.FColors) then if Source.FColors.Count>ValueIndex then begin if not Assigned(FColors) then GrowColors; FColors.Insert(tmpIndex,Source.FColors[ValueIndex]); end; if Source.FLabels.Count>ValueIndex then Labels.InsertLabel(tmpIndex,Source.Labels[ValueIndex]); NotifyNewValue(Self,tmpIndex); end; Function TChartSeries.LegendToValueIndex(LegendIndex:Integer):Integer; begin result:=LegendIndex; end; { Returns the formatted string corresponding to the LegendIndex point. The string is used to show at the Legend. Uses the LegendTextStyle property to do the appropiate formatting. } Function TChartSeries.LegendString( LegendIndex:Integer; LegendTextStyle:TLegendTextStyle ):String; var ValueIndex : Integer; Function CalcXValue:String; Var tmpAxis : TChartAxis; begin tmpAxis:=GetHorizAxis; if Assigned(tmpAxis) then result:=tmpAxis.LabelValue(XValues.Value[ValueIndex]) else result:=FormatFloat(ValueFormat,XValues.Value[ValueIndex]) end; Var tmpValue : Double; Function ValueToStr:String; begin if MandatoryValueList.DateTime then DateTimeToString(result,DateTimeDefaultFormat(tmpValue),tmpValue) else result:=FormatFloat(ValueFormat,tmpValue); end; Function CalcPercentSt:String; begin With MandatoryValueList do if TotalAbs=0 then result:=FormatFloat(PercentFormat,100) else result:=FormatFloat(PercentFormat,100.0*tmpValue/TotalAbs); end; begin ValueIndex:=LegendToValueIndex(LegendIndex); result:=Labels[ValueIndex]; if LegendTextStyle<>ltsPlain then begin tmpValue:=GetMarkValue(ValueIndex); Case LegendTextStyle of ltsLeftValue : begin if result<>'' then result:=TeeColumnSeparator+result; result:=ValueToStr+result; end; ltsRightValue : begin if result<>'' then result:=result+TeeColumnSeparator; result:=result+ValueToStr; end; ltsLeftPercent : begin if result<>'' then result:=TeeColumnSeparator+result; result:=CalcPercentSt+result; end; ltsRightPercent: begin if result<>'' then result:=result+TeeColumnSeparator; result:=result+CalcPercentSt; end; ltsXValue : result:=CalcXValue; ltsValue : result:=ValueToStr; ltsPercent : result:=CalcPercentSt; ltsXandValue : result:=CalcXValue+TeeColumnSeparator+ValueToStr; ltsXandPercent : result:=CalcXValue+TeeColumnSeparator+CalcPercentSt; end; end; end; { Clears and adds all points values from Source series. } procedure TChartSeries.AddValues(Source:TChartSeries); var t : Integer; begin BeginUpdate; { before Clear } Clear; if FunctionType=nil then { "Copy Function", copy values... } begin if IsValidSourceOf(Source) then for t:=0 to Source.Count-1 do AddedValue(Source,t) end else begin XValues.DateTime:=Source.XValues.DateTime; YValues.DateTime:=Source.YValues.DateTime; FunctionType.AddPoints(Source); { calculate function } end; EndUpdate; { propagate changes... } end; { Copies (adds) all values from Source series. } Procedure TChartSeries.AssignValues(Source:TChartSeries); begin AddValues(Source); end; { Notifies all series and tools that data (points) has changed. } Procedure TChartSeries.RefreshSeries; Begin NotifyValue(veRefresh,0); if Assigned(ParentChart) then ParentChart.BroadcastSeriesEvent(Self,seDataChanged); End; { Returns True if there are more series that share the same Z order. For example: Stacked Bars. } Function TChartSeries.MoreSameZOrder:Boolean; Var tmpSeries : TChartSeries; t : Integer; Begin if FParent.ApplyZOrder then { fix 4.02 } for t:=0 to FParent.SeriesCount-1 do Begin tmpSeries:=FParent.Series[t]; if tmpSeries<>Self then With tmpSeries do if FActive and (not HasZValues) and (ZOrder=Self.ZOrder) then Begin result:=True; exit; end; end; result:=False; End; { Returns True if the series is the first one with the same Z order. Some series allow sharing the same Z order (example: Stacked Bars). } Function TChartSeries.FirstInZOrder:Boolean; Var tmpSeries : TChartSeries; t : Integer; Begin if FActive then begin result:=True; for t:=0 to FParent.SeriesCount-1 do Begin tmpSeries:=FParent.Series[t]; if tmpSeries=Self then break else With tmpSeries do if FActive and (ZOrder=Self.ZOrder) then Begin result:=False; break; end; end; end else result:=False; end; { Calls the BeforeDrawValues event. } procedure TChartSeries.DoBeforeDrawValues; Begin if Assigned(FBeforeDrawValues) then FBeforeDrawValues(Self); end; { Calls the AfterDrawValues event. } procedure TChartSeries.DoAfterDrawValues; Begin if Assigned(FAfterDrawValues) then FAfterDrawValues(Self); end; { Draws all Marks for all points in the series that are visible. } procedure TChartSeries.DrawMarks; Var t : Integer; St : String; tmpWidth : Integer; tmpW : Integer; tmpH : Integer; APosition : TSeriesMarkPosition; tmpMark : TTeeCustomShape; Begin APosition:=TSeriesMarkPosition.Create; With FParent,FMarks do for t:=FFirstVisibleIndex to FLastVisibleIndex do if (t mod FDrawEvery)=0 then if not IsNull(t) then Begin St:=GetMarkText(t); if St<>'' then Begin tmpMark:=FMarks.MarkItem(t); if tmpMark.Visible then begin Canvas.AssignFont(tmpMark.Font); if View3D and (not Canvas.Supports3DText) and View3DOptions.ZoomText and (View3DOptions.Zoom<>100) then With Canvas.Font do Size:=Math.Max(1,Round(0.01*View3DOptions.Zoom*Size)); tmpW:=MultiLineTextWidth(St,tmpH)+Canvas.TextWidth(TeeCharForHeight); tmpH:=tmpH*Canvas.FontHeight; if Assigned(FSymbol) and FSymbol.ShouldDraw then Inc(tmpW,Canvas.FontHeight-4); Canvas.AssignVisiblePen(tmpMark.Pen); if tmpMark.Pen.Visible then Begin tmpWidth:=2*tmpMark.Pen.Width; Inc(tmpW,tmpWidth); Inc(tmpH,tmpWidth); end else Inc(tmpH); With APosition do begin Width:=tmpW; Height:=tmpH; ArrowTo.X:=CalcXPos(t); ArrowTo.Y:=CalcYPos(t); ArrowFrom:=ArrowTo; LeftTop.X:=ArrowTo.X-(tmpW div 2); LeftTop.Y:=ArrowTo.Y-tmpH+1; end; if Assigned(FSymbol) then with FSymbol.ShapeBounds do begin Top:=APosition.LeftTop.Y+2; Left:=APosition.LeftTop.X+2; Bottom:=Top+Canvas.FontHeight; Right:=Left+Canvas.FontHeight; end; DrawMark(t,St,APosition); end; end; end; APosition.Free; end; { Draws a point Mark using the APosition coordinates. } Procedure TChartSeries.DrawMark( ValueIndex:Integer; Const St:String; APosition:TSeriesMarkPosition); Begin FMarks.InternalDraw(ValueIndex,ValueColor[ValueIndex],St,APosition); end; { Triggers the OnAfterAdd event when a new point is added. } Procedure TChartSeries.NotifyNewValue(Sender:TChartSeries; ValueIndex:Integer); Begin if Assigned(FOnAfterAdd) then FOnAfterAdd(Sender,ValueIndex); NotifyValue(veAdd,ValueIndex); if FActive then Repaint; end; // Returns the index of the first displayed point. // When the chart is rotated, the first point displayed might be // the last "visible" in the series. Function TChartSeries.FirstDisplayedIndex:Integer; begin if DrawValuesForward then result:=FirstValueIndex else result:=LastValueIndex; end; { Returns True is the ValueIndex point in the Series is Null. } Function TChartSeries.IsNull(ValueIndex:Integer):Boolean; begin result:=ValueColor[ValueIndex]=clNone; end; { Adds a new Null (missing) point to the series, with specified Value. } Function TChartSeries.AddNull(Const Value:Double):Integer; begin result:=Add(Value,'',clNone); end; { Adds a new Null (missing) point to the series. The ALabel parameter is optional. } Function TChartSeries.AddNull(Const ALabel:String):Integer; begin result:=Add(0,ALabel,clNone); end; { Adds a new Null (missing) point to the Series with the specified X and Y values. The ALabel parameter is optional. } Function TChartSeries.AddNullXY(Const X,Y:Double; Const ALabel:String):Integer; begin result:=AddXY(X,Y,ALabel,clNone); end; { Adds the Values array parameter into the series. } Function TChartSeries.AddArray(Const Values:Array of TChartValue):Integer; var t : Integer; begin BeginUpdate; try result:=High(Values)-Low(Values)+1; for t:=Low(Values) to High(Values) do Add(Values[t]); finally EndUpdate; end; end; { Adds a new point to the Series. The ALabel and AColor parameters are optional. } Function TChartSeries.Add(Const AValue:Double; Const ALabel:String; AColor:TColor):Integer; Begin if YMandatory then { 5.02 speed opt. } result:=AddXY(FX.Count, AValue, ALabel, AColor ) else result:=AddXY(AValue, FY.Count, ALabel, AColor ); end; Function TChartSeries.AddX(Const AXValue:Double; Const ALabel:String; AColor:TColor):Integer; Begin result:=AddXY(AXValue,FX.Count,ALabel,AColor); end; Function TChartSeries.AddY(Const AYValue:Double; Const ALabel:String; AColor:TColor):Integer; Begin result:=AddXY(FX.Count,AYValue,ALabel,AColor); end; { Adds a new point into the Series. } Function TChartSeries.AddXY( Const AXValue,AYValue:Double; Const ALabel:String; AColor:TColor):Integer; var t : Integer; Begin FX.TempValue:=AXValue; FY.TempValue:=AYValue; if (not Assigned(FOnBeforeAdd)) or FOnBeforeAdd(Self) then Begin result:=FX.AddChartValue; // (FX.TempValue); // 7.0 FY.InsertChartValue(result,FY.TempValue); for t:=2 to ValuesList.Count-1 do With ValuesList[t] do InsertChartValue(result,TempValue); if Assigned(FColors) then FColors.Insert(result,{$IFDEF CLR}TObject{$ELSE}Pointer{$ENDIF}(AColor)) else if AColor<>clTeeColor then begin GrowColors; FColors.Insert(result,{$IFDEF CLR}TObject{$ELSE}Pointer{$ENDIF}(AColor)); end; if (ALabel<>'') or (FLabels.Count>0) then { speed opt. 5.02 } Labels.InsertLabel(result,ALabel); if IUpdating=0 then { 5.02 } NotifyNewValue(Self,result); end else result:=-1; end; Function TChartSeries.Count:Integer; { <-- Total number of points in the series } Begin result:=FX.Count; end; { Virtual. Returns the number of points to show at the Legend. Some series override this function to return other values. } Function TChartSeries.CountLegendItems:Integer; begin result:=Count end; { Returns the number of points that are inside the axis limits. (visible) } Function TChartSeries.VisibleCount:Integer; Begin result:=FLastVisibleIndex-FFirstVisibleIndex+1; end; { Returns the string showing a "percent" value for a given point. For example: "25%" The optional "AddTotal" parameter, when True, returns for example: "25% of 1234". } Function TChartSeries.MarkPercent(ValueIndex:Integer; AddTotal:Boolean=False):String; var tmp : Double; tmpF : String; Begin With MandatoryValueList do Begin if TotalAbs<>0 then tmp:=100.0*Abs(GetMarkValue(ValueIndex))/TotalAbs else tmp:=100; result:=FormatFloat(FPercentFormat,tmp); if AddTotal then begin if Marks.MultiLine then tmpF:=TeeMsg_DefaultPercentOf2 else tmpF:=TeeMsg_DefaultPercentOf; FmtStr(result,tmpF,[result,FormatFloat(FValueFormat,TotalAbs)]); end; end; end; Function TChartSeries.GetOriginValue(ValueIndex:Integer):Double; begin result:=GetMarkValue(ValueIndex); end; Function TChartSeries.GetMarkValue(ValueIndex:Integer):Double; begin result:=MandatoryValueList.Value[ValueIndex]; end; { Returns the string corresponding to the Series Mark text for a given ValueIndex point. The Mark text depends on the Marks.Style property. } Function TChartSeries.GetMarkText(ValueIndex:Integer):String; Function LabelOrValue(ValueIndex:Integer):String; Begin result:=Labels[ValueIndex]; if result='' then result:=FormatFloat(FValueFormat,GetMarkValue(ValueIndex)); End; Function GetAXValue:String; begin if not Assigned(GetHorizAxis) then result:=FormatFloat(FValueFormat,NotMandatoryValueList.Value[ValueIndex]) else result:=GetHorizAxis.LabelValue(NotMandatoryValueList.Value[ValueIndex]); end; Function GetAYValue:String; begin result:=FormatFloat(FValueFormat,GetMarkValue(ValueIndex)); end; var tmp : Char; Begin With FMarks do begin if MultiLine then tmp:=TeeLineSeparator else tmp:=' '; Case FMarkerStyle of smsValue: result:=GetAYValue; smsPercent: result:=MarkPercent(ValueIndex); smsLabel: result:=LabelOrValue(ValueIndex); smsLabelPercent: result:=LabelOrValue(ValueIndex)+tmp+MarkPercent(ValueIndex); smsLabelValue: result:=LabelOrValue(ValueIndex)+tmp+GetAYValue; smsLegend: begin result:=Self.ParentChart.FormattedValueLegend(Self,ValueIndex); if not MultiLine then result:=ReplaceChar(result,TeeColumnSeparator,' '); end; smsPercentTotal: result:=MarkPercent(ValueIndex,True); smsLabelPercentTotal: result:=LabelOrValue(ValueIndex)+tmp+MarkPercent(ValueIndex,True); smsXValue: result:=GetAXValue; smsXY: result:=GetAXValue+tmp+GetAYValue; else result:=''; end; end; if Assigned(FOnGetMarkText) then FOnGetMarkText(Self,ValueIndex,result); end; Procedure TChartSeries.SetValueFormat(Const Value:String); Begin SetStringProperty(FValueFormat,Value); end; Procedure TChartSeries.SetPercentFormat(Const Value:String); Begin SetStringProperty(FPercentFormat,Value); end; { Changes visual properties appropiate to show the series at the gallery. } Procedure TChartSeries.PrepareForGallery(IsEnabled:Boolean); begin inherited; FillSampleValues(4); With Marks do begin Visible:=False; Font.Size:=7; Callout.Length:=4; DrawEvery:=2; end; FColorEachPoint:=False; if IsEnabled then if ParentChart.SeriesList.IndexOf(Self)=0 then SeriesColor:=ParentChart.GetDefaultColor(clTeeGallery1) else SeriesColor:=ParentChart.GetDefaultColor(clTeeGallery2) else SeriesColor:=clSilver; end; Function TChartSeries.NumSampleValues:Integer; Begin result:=25; { default number or random values at design time } end; class Function TChartSeries.RandomValue(const Range:Integer):Integer; begin result:={$IFNDEF CLR}System.{$ENDIF}Random(Range); end; // Calculates appropiate random limits used to add sample // values (FillSampleValues method). Function TChartSeries.RandomBounds(NumValues:Integer):TSeriesRandomBounds; Var MinX : Double; MaxX : Double; MaxY : Double; Begin result.MinY:=0; MaxY:=ChartSamplesMax; if Assigned(FParent) and (FParent.GetMaxValuesCount>0) then begin result.MinY:=FParent.MinYValue(GetVertAxis); MaxY:=FParent.MaxYValue(GetVertAxis); if MaxY=result.MinY then if MaxY=0 then MaxY:=ChartSamplesMax else MaxY:=2.0*result.MinY; MinX:=FParent.MinXValue(GetHorizAxis); MaxX:=FParent.MaxXValue(GetHorizAxis); if MaxX=MinX then if MaxX=0 then MaxX:=NumValues-1 else MaxX:=2.0*MinX; if not YMandatory then begin SwapDouble(MinX,result.MinY); SwapDouble(MaxX,MaxY); end; end else begin if XValues.DateTime then begin MinX:=Date; MaxX:=MinX+NumValues-1; end else begin MinX:=0; MaxX:=NumValues-1; end; end; result.StepX:=MaxX-MinX; if NumValues>1 then result.StepX:=result.StepX/(NumValues-1); result.DifY:=MaxY-result.MinY; if result.DifY>MaxLongint then result.DifY:=MaxLongint else if result.DifY<-MaxLongint then result.DifY:=-MaxLongint; result.tmpY:=result.MinY+RandomValue(Round(result.DifY)); result.tmpX:=MinX; end; Procedure TChartSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); var t : Integer; tmpH : Integer; s : TSeriesRandomBounds; begin s:=RandomBounds(NumValues); with s do begin tmpH:=Round(DifY) div 4; for t:=1 to NumValues do begin tmpY:=Abs(tmpY+RandomValue(tmpH)-(tmpH div 2)); if OnlyMandatory then Add(tmpY) else begin if YMandatory then AddXY(tmpX,tmpY) else AddXY(tmpY,tmpX); tmpX:=tmpX+StepX; end; end; end; end; // Sorts all points in the series using the Labels list. // Warning: non-mandatory values (X) are modified (they are not preserved). Procedure TChartSeries.SortByLabels(Order:TChartListOrder=loAscending); begin if Order<>loNone then begin ILabelOrder:=Order; TeeSort(0,Count-1,CompareLabelIndex,SwapValueIndex); ILabelOrder:=loNone; NotMandatoryValueList.FillSequence; // force set X values (lost them) Repaint; end; end; { Sorts all points in the series if the Order property is used. By default, Series.XValues.Order is set to "ascending". } Procedure TChartSeries.CheckOrder; begin if MandatoryValueList.Order<>loNone then begin MandatoryValueList.Sort; // If NotMand list has a ValueSource, do not call FillSequence if NotMandatoryValueList.ValueSource='' then { 5.02 } NotMandatoryValueList.FillSequence; Repaint; end; end; // Adds random point to the series. Used at design-time to // show sample values. procedure TChartSeries.FillSampleValues(NumValues:Integer=0); begin if NumValues<0 then Raise ChartException.Create(TeeMsg_FillSample) else if NumValues=0 then begin NumValues:=INumSampleValues; if NumValues<=0 then NumValues:=NumSampleValues; end; Clear; BeginUpdate; RandSeed:=Random(7774444); { 5.01 } AddSampleValues(NumValues); CheckOrder; EndUpdate; ManualData:=False; end; procedure TChartSeries.AssignFormat(Source:TChartSeries); var t : Integer; begin With TChartSeries(Source) do begin Self.DataSource:=nil; if Self.YMandatory=YMandatory then { 5.02 } begin Self.FX.Assign(FX); Self.FY.Assign(FY); end else begin Self.FY.Assign(FX); Self.FX.Assign(FY); end; Self.FLabelsSource:=FLabelsSource; Self.FColorSource :=FColorSource; { other lists } for t:=2 to Math.Min(Self.ValuesList.Count-1,ValuesList.Count-1) do Self.ValuesList.ValueList[t].Assign(ValuesList[t]); Self.Marks := FMarks; Self.FColor := FColor; Self.ChangeInternalColor(ISeriesColor); Self.FColorEachPoint := FColorEachPoint; Self.FValueFormat := FValueFormat; Self.FPercentFormat := FPercentFormat; Self.FCustomHorizAxis:= FCustomHorizAxis; // 6.01 Self.FHorizAxis := FHorizAxis; Self.FCustomVertAxis := FCustomVertAxis; // 6.01 Self.FVertAxis := FVertAxis; Self.FRecalcOptions := FRecalcOptions; Self.FCursor := FCursor; Self.FDepth := FDepth; Self.RecalcGetAxis; { 5.01 } end; end; procedure TChartSeries.Assign(Source:TPersistent); Procedure SelfSetDataSources(Value:TList); var t : Integer; begin DataSources.Clear; for t:=0 to Value.Count-1 do InternalAddDataSource(TComponent(Value[t])); end; Procedure AssignColors; var t : Integer; begin With TChartSeries(Source) do if Assigned(FColors) then begin if Assigned(Self.FColors) then Self.FColors.Clear else Self.FColors:=TList.Create; for t:=0 to FColors.Count-1 do Self.FColors.Add(FColors[t]); end else Self.FColors.Free; end; Begin if Source is TChartSeries then begin inherited; AssignFormat(TChartSeries(Source)); With TChartSeries(Source) do begin if Assigned(FunctionType) and (Self.FunctionType=nil) then FunctionType.ParentSeries:=Self; Self.ManualData:=ManualData; // 5.03 if DataSource=nil then begin if ManualData or (not (csDesigning in ComponentState)) then // 6.02 begin AssignColors; Self.Labels.Assign(Labels); Self.AssignValues(TChartSeries(Source)); end; end else SelfSetDataSources(DataSources); { <-- important !!! } Self.CheckDataSource; end; end else inherited; end; Procedure TChartSeries.SetColorEachPoint(Value:Boolean); //var t : Integer; Begin SetBooleanProperty(FColorEachPoint,Value); { if not FColorEachPoint then begin for t:=0 to Count-1 do if IsNull(t) then exit; FreeAndNil(FColors); end;} end; { This method replaces a value list with a new one. } Procedure TChartSeries.ReplaceList(OldList,NewList:TChartValueList); var t : Integer; begin t:=FValuesList.IndexOf(NewList); if t<>-1 then FValuesList.Delete(t); t:=FValuesList.IndexOf(OldList); if t<>-1 then begin NewList.Name:=OldList.Name; if OldList=FX then begin FX:=NewList; NotMandatoryValueList:=NewList; { 5.01 } end else if OldList=FY then begin FY:=NewList; MandatoryValueList:=NewList; { 5.01 } end; FValuesList[t].Free; FValuesList.Items[t]:=NewList; end; end; { Returns an X value. } Function TChartSeries.GetxValue(ValueIndex:Integer):Double; { "x" in lowercase for BCB } Begin result:=FX.Value[ValueIndex] end; { Returns an Y value. } Function TChartSeries.GetyValue(ValueIndex:Integer):Double; { "y" in lowercase for BCB } Begin result:=FY.Value[ValueIndex] end; { Changes an Y value. Tells the chart to repaint. } Procedure TChartSeries.SetYValue(Index:Integer; Const Value:Double); Begin FY.Value[Index]:=Value; {$IFDEF TEEARRAY} FY.Modified:=True; {$ENDIF} Repaint; end; { Changes an X value. Tells the chart to repaint. } Procedure TChartSeries.SetXValue(Index:Integer; Const Value:Double); Begin FX.Value[Index]:=Value; {$IFDEF TEEARRAY} FX.Modified:=True; {$ENDIF} Repaint; end; Function TChartSeries.InternalColor(ValueIndex:Integer):TColor; Begin if Assigned(FColors) and (FColors.Count>ValueIndex) then result:=TColor(FColors{$IFOPT R-}.List{$ENDIF}[ValueIndex]) else result:=clTeeColor; end; { Returns the color for a given "ValueIndex" point. If the "ColorEachPoint" property is used (True) then returns a color from the color palette. } Function TChartSeries.GetValueColor(ValueIndex:Integer):TColor; Begin result:=InternalColor(ValueIndex); if result=clTeeColor then if FColorEachPoint then begin if Assigned(FParent) then result:=FParent.GetDefaultColor(ValueIndex) else result:=GetDefaultColor(ValueIndex) end else result:=SeriesColor; end; { Creates the color list and adds the default color (clTeeColor) for all the points in the series. } Procedure TChartSeries.GrowColors; var t : Integer; begin FColors:=TList.Create; for t:=0 to Count-1 do FColors.Add({$IFDEF CLR}TObject{$ELSE}Pointer{$ENDIF}(clTeeColor)); end; { Sets the AColor parameter into the color list. It is optimized to prevent allocating memory when all the colors are the default (clTeeColor). } Procedure TChartSeries.SetValueColor(ValueIndex:Integer; AColor:TColor); Begin if not Assigned(FColors) then if AColor=clTeeColor then Exit else GrowColors; FColors[ValueIndex]:={$IFDEF CLR}TObject{$ELSE}Pointer{$ENDIF}(AColor); Repaint; end; { Clears (empties) all lists of values, colors and labels. } Procedure TChartSeries.ClearLists; var t : Integer; Begin { Values } for t:=0 to FValuesList.Count-1 do FValuesList[t].ClearValues; { Colors } FreeAndNil(FColors); { Labels } Labels.Clear; { Marks.Positions } if Assigned(FMarks) then FMarks.Clear; end; { Removes all points. Triggers all events and notifications and repaints. } Procedure TChartSeries.Clear; begin FFirstVisibleIndex:=-1; // 7.0 #1281 FLastVisibleIndex:=-1; ClearLists; if Assigned(FOnClearValues) then FOnClearValues(Self); NotifyValue(veClear,0); if Assigned(FunctionType) then FunctionType.Clear; if FActive and Assigned(FParent) and (not (csDestroying in FParent.ComponentState)) then Repaint; end; { Returns True is the series is associated to Axis parameter. Associated means either the horizontal or vertical axis of the Legend includes the Axis parameter. } Function TChartSeries.AssociatedToAxis(Axis:TChartAxis):Boolean; Begin result:=UseAxis and ( (Axis.Horizontal and ((FHorizAxis=aBothHorizAxis) or (GetHorizAxis=Axis))) or ((not Axis.Horizontal) and ((FVertAxis=aBothVertAxis) or (GetVertAxis=Axis))) ); end; { Draws a rectangle at the Legend that corresponds to the ValueIndex point position. If the point color is the same as the Legend background color (color conflict), then an alternative color is used. } Procedure TChartSeries.DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); var OldColor : TColor; begin With FParent,Canvas do begin Rectangle(Rect); { <-- rectangle } if Brush.Color=LegendColor then { <-- color conflict ! } Begin OldColor:=Pen.Color; if Brush.Color=clBlack then Pen.Color:=clWhite; Brush.Style:=bsClear; Rectangle(Rect); { <-- frame rectangle } Pen.Color:=OldColor; end; end; end; { Virtual. Returns the color of the corresponding position in the Legend. By default the color the the same as the point color. Other series (Surface, etc) return a color from the "palette". } Function TChartSeries.LegendItemColor(LegendIndex:Integer):TColor; begin result:=ValueColor[LegendIndex]; end; { For a given ValueIndex point in the series, paints it at the Legend. } Procedure TChartSeries.DrawLegend(ValueIndex:Integer; Const Rect:TRect); Var tmpBack : TColor; OldStyle : TBrushStyle; tmpStyle : TBrushStyle; tmpColor : TColor; OldStyleChanged, Old : Boolean; Begin if (ValueIndex<>-1) or (not ColorEachPoint) then begin Old:=FParent.AutoRepaint; FParent.AutoRepaint:=False; { set brush color } if ValueIndex=-1 then tmpColor:=SeriesColor else tmpColor:=LegendItemColor(ValueIndex); FParent.Canvas.Brush.Color:=tmpColor; { if not empty brush... } if tmpColor<>clNone then begin { set background color and style } tmpBack:=FParent.LegendColor; tmpStyle:=Self.Brush.Style; // By default, set current Series.Pen FParent.Canvas.AssignVisiblePen(Pen); // Give Series opportunity to change pen & brush PrepareLegendCanvas(ValueIndex,tmpBack,tmpStyle); // After calling PrepareLegendCanvas, set custom symbol pen, if any... if Assigned(FParent.LegendPen) then FParent.Canvas.AssignVisiblePen(FParent.LegendPen); { if back color is "default", use Legend back color } if tmpBack=clTeeColor then begin tmpBack:=FParent.LegendColor; if tmpBack=clTeeColor then tmpBack:=FParent.Color; end; OldStyleChanged:=False; OldStyle:=bsSolid; { if brush has no bitmap, set brush style } With Self.Brush do if Style<>tmpStyle then begin if (not Assigned(Bitmap)) or Bitmap.Empty then { 5.01 } begin OldStyle:=Style; OldStyleChanged:=True; Style:=tmpStyle; end; end; { final setting } With FParent do SetBrushCanvas(Canvas.Brush.Color,Self.Brush,tmpBack); { draw shape } DrawLegendShape(ValueIndex,Rect); if OldStyleChanged then Self.Brush.Style:=OldStyle; end; FParent.AutoRepaint:=Old; end; End; Procedure TChartSeries.PrepareLegendCanvas( ValueIndex:Integer; Var BackColor:TColor; Var BrushStyle:TBrushStyle); begin { abstract } end; { Calculates the correct "Z" order for the series } Procedure TChartSeries.CalcZOrder; Begin if FZOrder=TeeAutoZOrder then begin if FParent.View3D then begin Inc(FParent.FMaxZOrder); IZOrder:=FParent.FMaxZOrder; end else IZOrder:=0; end else FParent.FMaxZOrder:=Math.Max(FParent.FMaxZOrder,ZOrder); End; Function TChartSeries.CalcXPosValue(Const Value:Double):Integer; Begin result:=GetHorizAxis.CalcXPosValue(Value); end; { Returns the axis value for a given horizontal ScreenPos pixel position } Function TChartSeries.XScreenToValue(ScreenPos:Integer):Double; Begin result:=GetHorizAxis.CalcPosPoint(ScreenPos); end; Function TChartSeries.CalcXSizeValue(Const Value:Double):Integer; Begin result:=GetHorizAxis.CalcSizeValue(Value); end; Function TChartSeries.CalcYPosValue(Const Value:Double):Integer; Begin result:=GetVertAxis.CalcYPosValue(Value); end; Function TChartSeries.CalcPosValue(Const Value:Double):Integer; Begin if YMandatory then result:=CalcYPosValue(Value) else result:=CalcXPosValue(Value); end; Function TChartSeries.XValueToText(Const AValue:Double):String; Begin result:=GetHorizAxis.LabelValue(AValue); end; Function TChartSeries.YValueToText(Const AValue:Double):String; begin result:=GetVertAxis.LabelValue(AValue); end; { Returns the axis value for a given vertical ScreenPos pixel position } Function TChartSeries.YScreenToValue(ScreenPos:Integer):Double; Begin result:=GetVertAxis.CalcPosPoint(ScreenPos); end; Function TChartSeries.CalcYSizeValue(Const Value:Double):Integer; Begin result:=GetVertAxis.CalcSizeValue(Value); end; Function TChartSeries.CalcXPos(ValueIndex:Integer):Integer; Begin result:=GetHorizAxis.CalcXPosValue(XValues.Value[ValueIndex]); end; Function TChartSeries.CalcYPos(ValueIndex:Integer):Integer; begin result:=GetVertAxis.CalcYPosValue(YValues.Value[ValueIndex]); end; { Removes a point in the series } Procedure TChartSeries.Delete(ValueIndex:Integer); Var t : Integer; Begin if ValueIndex<Count then begin { Values } for t:=0 to FValuesList.Count-1 do FValuesList[t].Delete(ValueIndex); { Color } if Assigned(FColors) and (FColors.Count>ValueIndex) then FColors.Delete(ValueIndex); { Label } if Labels.Count>ValueIndex then Labels.DeleteLabel(ValueIndex); { Marks Position and Item } With FMarks do begin if FPositions.Count>ValueIndex then begin FPositions[ValueIndex].Free; // 7.0 FPositions.Delete(ValueIndex); end; if FItems.Count>ValueIndex then begin FItems[ValueIndex].Free; // 7.0 FItems.Delete(ValueIndex); end; end; { notify deletion } NotifyValue(veDelete,ValueIndex); { Repaint chart } if FActive then Repaint; end else Raise ChartException.CreateFmt(TeeMsg_SeriesDelete,[ValueIndex,Count-1]); end; // Deletes "Quantity" number of points from "Start" index. // Faster than calling Delete repeteadly. // If RemoveGap is True, "X" values are re-calculated to be sequential, // to eliminate gaps created by deletion. Procedure TChartSeries.Delete(Start,Quantity:Integer; RemoveGap:Boolean=False); // 6.01 var t : Integer; begin if Start<Count then begin {$IFDEF TEEARRAY} { Values } for t:=0 to ValuesList.Count-1 do ValuesList[t].Delete(Start,Quantity); { Color } if Assigned(FColors) then begin if FColors.Count>Start then for t:=Start to Start+Quantity-1 do FColors.Delete(Start); if FColors.Count=0 then FreeAndNil(FColors); end; { Label } if FLabels.Count>Start then for t:=Start to Start+Quantity-1 do Labels.DeleteLabel(Start); { Marks.Position } With FMarks.FPositions do if Count>Start then for t:=Start to Start+Quantity-1 do Delete(Start); { notify deletion } NotifyValue(veDelete,-1); { Repaint chart } if Active then Repaint; {$ELSE} for t:=1 to Quantity do Delete(Start); {$ENDIF} if RemoveGap then NotMandatoryValueList.FillSequence(); end; end; { Exchanges one point with another. Also the point color and point label, with safe checking. } procedure TChartSeries.SwapValueIndex(a,b:Integer); var t : Integer; begin for t:=0 to FValuesList.Count-1 do FValuesList[t].{$IFNDEF TEEARRAY}FList.{$ENDIF}Exchange(a,b); if Assigned(FColors) then FColors.Exchange(a,b); if FLabels.Count>0 then FLabels.Exchange(a,b); // 5.01 end; procedure TChartSeries.SetMarks(Value:TSeriesMarks); begin FMarks.Assign(Value); end; Function TChartSeries.GetSeriesColor:TColor; // 6.02 begin if FColor=clTeeColor then result:=ISeriesColor else result:=FColor; end; Procedure TChartSeries.NotifyColorChanged; Begin if Assigned(ParentChart) then ParentChart.BroadcastSeriesEvent(Self,seChangeColor); RepaintDesigner; end; Procedure TChartSeries.SetSeriesColor(AColor:TColor); Begin if (FColor<>clTeeColor) or (AColor<>ISeriesColor) then begin SetColorProperty(FColor,AColor); ISeriesColor:=FColor; NotifyColorChanged; end; end; Function TChartSeries.MaxXValue:Double; Begin result:=FX.MaxValue; end; Function TChartSeries.MaxYValue:Double; Begin result:=FY.MaxValue; end; Function TChartSeries.MinXValue:Double; Begin result:=FX.MinValue; end; Function TChartSeries.MinYValue:Double; Begin result:=FY.MinValue; end; Function TChartSeries.MaxZValue:Double; begin result:=ZOrder; end; Function TChartSeries.MinZValue:Double; begin result:=ZOrder; end; { Returns the length in pixels of the longest visible Mark text } Function TChartSeries.MaxMarkWidth:Integer; var t : Integer; Begin result:=0; for t:=0 to Count-1 do if Marks.MarkItem(t).Visible then result:=Math.Max(result,Marks.TextWidth(t)); end; Procedure TChartSeries.AddLinkedSeries(ASeries:TChartSeries); Begin if FLinkedSeries.IndexOf(ASeries)=-1 then FLinkedSeries.Add(ASeries); end; Procedure TChartSeries.RemoveDataSource(Value:TComponent); begin DataSources.Remove(Value); // CheckDataSource; // 6.02 end; Procedure TChartSeries.SetNull(ValueIndex:Integer; Null:Boolean=True); // 6.0 begin if Null then ValueColor[ValueIndex]:=clNone // set point to null else ValueColor[ValueIndex]:=clTeeColor; // back to default (non-null) color end; Procedure TChartSeries.RemoveLinkedSeries(ASeries:TChartSeries); Begin if Assigned(FLinkedSeries) then FLinkedSeries.Remove(ASeries); end; Procedure TChartSeries.BeginUpdate; begin Inc(IUpdating); end; Procedure TChartSeries.EndUpdate; begin if IUpdating>0 then begin Dec(IUpdating); if IUpdating=0 then RefreshSeries; end; end; { This method is called whenever the series points are added, deleted, modified, etc. } Procedure TChartSeries.NotifyValue(ValueEvent:TValueEvent; ValueIndex:Integer); var t : Integer; Begin if (IUpdating=0) and Assigned(FLinkedSeries) then for t:=0 to FLinkedSeries.Count-1 do With FLinkedSeries[t] do Case ValueEvent of veClear : if rOnClear in FRecalcOptions then Clear; veDelete : if rOnDelete in FRecalcOptions then if FunctionType=nil then DeletedValue(Self,ValueIndex); veAdd : if rOnInsert in FRecalcOptions then if FunctionType=nil then AddedValue(Self,ValueIndex); veModify : if rOnModify in FRecalcOptions then AddValues(Self); veRefresh: AddValues(Self); end; end; Function TChartSeries.UseAxis:Boolean; begin result:=True; end; Procedure TChartSeries.Loaded; var t : Integer; begin inherited; { when the DataSource has multiple Series, load them... } if Assigned(FTempDataSources) then begin if FTempDataSources.Count>0 then begin DataSources.Clear; for t:=0 to FTempDataSources.Count-1 do InternalAddDataSource( Owner.FindComponent(FTempDataSources[t]) ); end; FTempDataSources.Free; end; { finally, gather points from datasource after loading } CheckDatasource; end; Procedure TChartSeries.SetCustomHorizAxis(Value:TChartAxis); begin FCustomHorizAxis:=Value; if Assigned(Value) then FHorizAxis:=aCustomHorizAxis else FHorizAxis:=aBottomAxis; RecalcGetAxis; Repaint; end; Function TChartSeries.GetZOrder:Integer; begin if FZOrder=TeeAutoZOrder then result:=IZOrder else result:=FZOrder; end; Procedure TChartSeries.SetZOrder(Value:Integer); begin SetIntegerProperty(FZOrder,Value); if FZOrder=TeeAutoZOrder then IZOrder:=0 else IZOrder:=FZOrder; end; Procedure TChartSeries.SetCustomVertAxis(Value:TChartAxis); begin FCustomVertAxis:=Value; if Assigned(Value) then FVertAxis:=aCustomVertAxis else FVertAxis:=aLeftAxis; RecalcGetAxis; Repaint; end; class procedure TChartSeries.CreateSubGallery(AddSubChart: TChartSubGalleryProc); begin AddSubChart(TeeMsg_Normal); end; class procedure TChartSeries.SetSubGallery(ASeries: TChartSeries; Index: Integer); begin end; procedure TChartSeries.SetDepth(const Value: Integer); begin SetIntegerProperty(FDepth,Value); end; { Tells the series to swap X and Y values } procedure TChartSeries.SetHorizontal; begin MandatoryValueList:=XValues; NotMandatoryValueList:=YValues; YMandatory:=False; end; // Returns in First and Last parameters the index of points // that start and end the current Chart "Page" procedure TChartSeries.CalcFirstLastPage(var First,Last:Integer); var tmpCount : Integer; tmpMax : Integer; begin tmpCount:=Count; if tmpCount=0 then begin First:=-1; Last:=-1; end else begin tmpMax:=ParentChart.MaxPointsPerPage; if tmpMax>0 then begin First:=(ParentChart.Page-1)*tmpMax; if tmpCount<=First then First:=Math.Max(0,(tmpCount div tmpMax)-1)*tmpMax; Last:=First+tmpMax-1; if tmpCount<=Last then Last:=First+(tmpCount mod tmpMax)-1; end else begin First:=0; Last:=tmpCount-1; end; end; end; function TChartSeries.CompareLabelIndex(a, b: Integer): Integer; var tmpA : String; tmpB : String; begin tmpA:=Labels[a]; tmpB:=Labels[b]; if tmpA<tmpB then result:=-1 else if tmpA>tmpB then result:= 1 else result:= 0; if ILabelOrder=loDescending then result:=-result; end; function TChartSeries.GetXLabel(Index: Integer): String; begin result:=Labels[Index]; end; procedure TChartSeries.SetXLabel(Index: Integer; const Value: String); begin Labels[Index]:=Value; end; function TChartSeries.IsColorStored: Boolean; begin result:=FColor<>clTeeColor; end; function TChartSeries.MandatoryAxis: TChartAxis; begin if YMandatory then result:=GetVertAxis else result:=GetHorizAxis end; { TCustomSeriesList } procedure TCustomSeriesList.Put(Index:Integer; Value:TChartSeries); begin inherited Items[Index]:=Value; end; function TCustomSeriesList.Get(Index:Integer):TChartSeries; begin result:=TChartSeries({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]); end; procedure TCustomSeriesList.ClearValues; // 6.02 var t : Integer; begin for t:=0 to Count-1 do Items[t].Clear; end; procedure TCustomSeriesList.FillSampleValues(Num:Integer=0); var t : Integer; begin for t:=0 to Count-1 do Items[t].FillSampleValues(Num); end; { TChartSeriesList } function TChartSeriesList.AddGroup(const Name: String): TSeriesGroup; begin result:=Groups.Add as TSeriesGroup; result.Name:=Name; end; destructor TChartSeriesList.Destroy; begin FGroups.Free; inherited; end; function TChartSeriesList.GetAllActive: Boolean; var t : Integer; begin result:=True; for t:=0 to Count-1 do if not Items[t].Visible then begin result:=False; exit; end; end; procedure TChartSeriesList.SetAllActive(const Value: Boolean); var t : Integer; begin for t:=0 to Count-1 do Items[t].Visible:=Value; end; { TChartAxes } procedure TChartAxes.Clear; begin While Count>0 do Items[0].Free; inherited; end; function TChartAxes.Get(Index:Integer):TChartAxis; begin result:=TChartAxis({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]); end; function TChartAxes.GetDepthAxis:TChartDepthAxis; begin result:=FChart.DepthAxis; end; function TChartAxes.GetDepthTopAxis:TChartDepthAxis; begin result:=FChart.DepthTopAxis; end; function TChartAxes.GetLeftAxis:TChartAxis; begin result:=FChart.LeftAxis; end; function TChartAxes.GetTopAxis:TChartAxis; begin result:=FChart.TopAxis; end; function TChartAxes.GetRightAxis:TChartAxis; begin result:=FChart.RightAxis; end; function TChartAxes.GetBottomAxis:TChartAxis; begin result:=FChart.BottomAxis; end; procedure TChartAxes.SetFastCalc(const Value: Boolean); var t: Integer; begin IFastCalc:=Value; for t:=0 to Count-1 do Items[t].SetCalcPosValue; end; function TChartAxes.GetBehind: Boolean; begin result:=FChart.AxisBehind; end; function TChartAxes.GetVisible: Boolean; begin result:=FChart.AxisVisible; end; procedure TChartAxes.SetBehind(const Value: Boolean); begin FChart.AxisBehind:=Value; end; procedure TChartAxes.SetVisible(const Value: Boolean); begin FChart.AxisVisible:=Value; end; procedure TChartAxes.Reset; var t : Integer; begin for t:=0 to Count-1 do Items[t].Automatic:=True; end; { TChartCustomAxes } function TChartCustomAxes.Get(Index: Integer):TChartAxis; begin result:=TChartAxis(inherited Items[Index]); end; procedure TChartCustomAxes.Put(Index:Integer; Const Value:TChartAxis); begin Items[Index].Assign(Value); end; // For linked custom axes, change their Min and Max procedure TChartCustomAxes.ResetScales(Axis:TChartAxis); // 7.0 var t: Integer; begin for t:=0 to Count-1 do if Items[t].FMaster=Axis then Items[t].SetMinMax(Axis.Minimum,Axis.Maximum); end; { TTeeCustomDesigner } Procedure TTeeCustomDesigner.Refresh; begin end; Procedure TTeeCustomDesigner.Repaint; begin end; { TTeeCustomTool } procedure TTeeCustomTool.ChartEvent(AEvent: TChartToolEvent); begin end; Procedure TTeeCustomTool.ChartMouseEvent(AEvent: TChartMouseEvent; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin end; class function TTeeCustomTool.Description: String; begin result:=''; end; procedure TTeeCustomTool.SetParentChart(const Value: TCustomAxisPanel); begin if ParentChart<>Value then // 6.02 begin if Assigned(ParentChart) then begin ParentChart.Tools.Remove(Self); if not Assigned(Value) then ParentChart.Repaint; end; inherited; if Assigned(ParentChart) then TList(ParentChart.Tools).Add(Self); end; end; { TChartTools } Function TChartTools.Add(Tool:TTeeCustomTool):TTeeCustomTool; begin Tool.ParentChart:=Owner; result:=Tool; end; procedure TChartTools.Clear; begin While Count>0 do Items[0].Free; inherited; end; function TChartTools.Get(Index: Integer): TTeeCustomTool; begin result:=TTeeCustomTool({$IFOPT R-}List{$ELSE}inherited Items{$ENDIF}[Index]); end; procedure TChartTools.SetActive(Value:Boolean); var t : Integer; begin for t:=0 to Count-1 do Get(t).Active:=Value; end; { TTeeCustomToolSeries } class function TTeeCustomToolSeries.GetEditorClass: String; begin result:='TSeriesToolEditor'; end; Function TTeeCustomToolSeries.GetHorizAxis:TChartAxis; begin if Assigned(FSeries) then result:=FSeries.GetHorizAxis else result:=ParentChart.BottomAxis; end; Function TTeeCustomToolSeries.GetVertAxis:TChartAxis; begin if Assigned(FSeries) then result:=FSeries.GetVertAxis else result:=ParentChart.LeftAxis; end; procedure TTeeCustomToolSeries.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and Assigned(FSeries) and (AComponent=FSeries) then Series:=nil; end; procedure TTeeCustomToolSeries.SetSeries(const Value: TChartSeries); begin if FSeries<>Value then begin {$IFDEF D5} if Assigned(FSeries) then FSeries.RemoveFreeNotification(Self); {$ENDIF} FSeries:=Value; if Assigned(FSeries) then FSeries.FreeNotification(Self); end; end; { TTeeCustomToolAxis } procedure TTeeCustomToolAxis.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('AxisID',ReadAxis,WriteAxis,Assigned(Axis)); end; class function TTeeCustomToolAxis.GetEditorClass: String; begin result:='TAxisToolEditor'; end; procedure TTeeCustomToolAxis.ReadAxis(Reader: TReader); begin Axis:=ParentChart.Axes[Reader.ReadInteger]; end; procedure TTeeCustomToolAxis.SetAxis(const Value: TChartAxis); begin if FAxis<>Value then begin FAxis:=Value; if Assigned(FAxis) then ParentChart:=FAxis.ParentChart else ParentChart:=nil; Repaint; end; end; procedure TTeeCustomToolAxis.WriteAxis(Writer: TWriter); begin Writer.WriteInteger(ParentChart.Axes.IndexOf(Axis)); end; { TCustomAxisPanel } Constructor TCustomAxisPanel.Create(AOwner: TComponent); begin inherited; AutoRepaint :=False; F3DPercent:=TeeDef3DPercent; FTools:=TChartTools.Create; FTools.Owner:=Self; FAxisBehind:=True; FAxisVisible:=True; FSeriesList:=TChartSeriesList.Create; FSeriesList.FOwner:=Self; FSeriesList.FGroups:=TSeriesGroups.Create(Self,TSeriesGroup); FView3DWalls:=True; FClipPoints:=True; { create FIRST the collections... } FAxes:=TChartAxes.Create; FAxes.FChart:=Self; FCustomAxes:=TChartCustomAxes.Create(Self,TChartAxis); { Create axes... } FBottomAxis:=TChartAxis.Create(FCustomAxes); with FBottomAxis do begin FHorizontal:=True; SetCalcPosValue; end; FTopAxis:=TChartAxis.Create(FCustomAxes); With FTopAxis do begin FHorizontal:=True; FOtherSide:=True; FZPosition:=100; { 100% } SetCalcPosValue; FGrid.FZ:=100; FGrid.IDefaultZ:=100; end; FLeftAxis:=TChartAxis.Create(FCustomAxes); With FLeftAxis.FAxisTitle do begin FAngle:=90; IDefaultAngle:=90; end; FRightAxis:=TChartAxis.Create(FCustomAxes); With FRightAxis do begin FAxisTitle.FAngle:=270; FAxisTitle.IDefaultAngle:=270; FOtherSide:=True; FZPosition:=100; { 100% } FGrid.FZ:=100; FGrid.IDefaultZ:=100; end; // Note: Do not add a Create constructor to TChartDepthAxis, // VCL streaming TCollection (CustomAxes property) // does not accept more than one class. FDepthAxis:=TChartDepthAxis.Create(FCustomAxes); FDepthAxis.FVisible:=False; FDepthAxis.IDepthAxis:=True; FDepthAxis.SetCalcPosValue; FDepthAxis.FOtherSide:=True; // 7.0 create DepthTop axis *after* DepthAxis... FDepthTopAxis:=TChartDepthAxis.Create(FCustomAxes); FDepthTopAxis.FVisible:=False; FDepthTopAxis.IDepthAxis:=True; FDepthTopAxis.SetCalcPosValue; { Paging default values } FPage:=1; FScaleLastPage:=True; AutoRepaint :=True; end; Destructor TCustomAxisPanel.Destroy; Begin FreeAllSeries; FAxes.Free; FCustomAxes.Free; FSeriesList.Free; Designer.Free; FTools.Free; inherited; end; procedure TCustomAxisPanel.BroadcastTeeEventClass(Event: TTeeEventClass); begin BroadcastTeeEvent(Event.Create).Free; end; Procedure TCustomAxisPanel.Set3DPercent(Value:Integer); Const Max3DPercent = 100; Min3DPercent = 1; Begin if (Value<Min3DPercent) or (Value>Max3DPercent) then Raise Exception.CreateFmt(TeeMsg_3DPercent,[Min3DPercent,Max3DPercent]) else SetIntegerProperty(F3DPercent,Value); end; // Changes the current page to Value Procedure TCustomAxisPanel.SetPage(Value:Integer); var tmp : Integer; Begin { Allow "Page" to be into: >= 1 , <= NumPages } tmp:=NumPages; if Value>tmp then Value:=tmp; if Value<1 then Value:=1; if FPage<>Value then begin SetIntegerProperty(FPage,Value); BroadcastTeeEventClass(TChartChangePage); { Trigged "changed page" event } if Assigned(FOnPageChange) then FOnPageChange(Self); end; end; Procedure TCustomAxisPanel.SetScaleLastPage(Value:Boolean); Begin SetBooleanProperty(FScaleLastPage,Value); End; { Returns the number of series that are Active (visible). } Function TCustomAxisPanel.CountActiveSeries:Integer; var t : Integer; Begin result:=0; for t:=0 to SeriesCount-1 do if SeriesList[t].Active then Inc(result); end; { Calculates the number of pages. This only applies when the MaxPointsPerPage property is used. If it is not used (is zero), then returns 1 (one page only). } Function TCustomAxisPanel.NumPages:Integer; Function CalcNumPages(AAxis:TChartAxis):Integer; var tmp : Integer; t : Integer; FirstTime : Boolean; Begin { By default, one single page } result:=1; { Calc max number of points for all active series associated to "AAxis" axis } tmp:=0; FirstTime:=True; for t:=0 to SeriesCount-1 do With Series[t] do if FActive and AssociatedToAxis(AAxis) then if FirstTime or (Count>tmp) then begin tmp:=Count; FirstTime:=False; end; { If there are points... divide into pages... } if tmp>0 then Begin result:=tmp div FMaxPointsPerPage; { extra page for remaining points... } if (tmp mod FMaxPointsPerPage)>0 then Inc(result); end; end; Begin if (FMaxPointsPerPage>0) and (SeriesCount>0) then begin if Series[0].YMandatory then result:=Math.Max(CalcNumPages(FTopAxis),CalcNumPages(FBottomAxis)) else result:=Math.Max(CalcNumPages(FLeftAxis),CalcNumPages(FRightAxis)); end else result:=1; End; { Sends pages to the printer. This only applies when the Chart has more than one page (MaxPointsPerPage property). If no parameters are passed, all pages are printed. If only one page exists, then it's printed. } procedure TCustomAxisPanel.PrintPages(FromPage, ToPage: Integer); var tmpOld : Integer; t : Integer; R : TRect; begin if Name<>'' then Printer.Title:=Name; { 5.01 } Printer.BeginDoc; try if ToPage=0 then ToPage:=NumPages; if FromPage=0 then FromPage:=1; tmpOld:=Page; try R:=ChartPrintRect; for t:=FromPage to ToPage do begin Page:=t; PrintPartial(R); if t<ToPage then Printer.NewPage; end; finally Page:=tmpOld; end; Printer.EndDoc; except on Exception do begin Printer.Abort; if Printer.Printing then Printer.EndDoc; Raise; end; end; end; Procedure TCustomAxisPanel.SetMaxPointsPerPage(Value:Integer); var tmp : Integer; Begin if Value<0 then Raise ChartException.Create(TeeMsg_MaxPointsPerPage) else begin SetIntegerProperty(FMaxPointsPerPage,Value); tmp:=NumPages; if FPage>tmp then Page:=tmp; BroadcastTeeEventClass(TChartChangePage); end; end; { Destroys and removes all Series in Chart. The optional parameter defines a series class (for example: TLineSeries) to remove only the series of that class. } Procedure TCustomAxisPanel.FreeAllSeries( SeriesClass:TChartSeriesClass=nil ); var t : Integer; tmp : TCustomChartSeries; begin t:=0; While t<SeriesCount do begin tmp:=Series[t]; if (not Assigned(SeriesClass)) or (tmp is SeriesClass) then begin tmp.ParentChart:=nil; tmp.Free; end else Inc(t); end; end; { Steps to determine if an axis is Visible: 1) The global Chart.AxisVisible property is True... and... 2) The Axis Visible property is True... and... 3) At least there is a Series Active and associated to the axis and the Series has the "UseAxis" property True. } Function TCustomAxisPanel.IsAxisVisible(Axis:TChartAxis):Boolean; begin result:=Axis.IsVisible; end; Function TCustomAxisPanel.CalcIsAxisVisible(Axis:TChartAxis):Boolean; var t : Integer; Begin result:=FAxisVisible and Axis.FVisible; if result then { if still visible... } if Axis.IsDepthAxis then result:=View3D else for t:=0 to SeriesCount-1 do With Series[t] do if FActive then if UseAxis then begin result:=AssociatedToAxis(Axis); if result then exit; end else begin result:=False; exit; end; end; { This function returns the longest width in pixels for a given "S" string. It also considers multi-line strings, returning in the NumLines parameter the count of lines. } Function TCustomAxisPanel.MultiLineTextWidth(S:String; Var NumLines:Integer):Integer; var i : Integer; begin result:=0; NumLines:=0; i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,s); While i>0 do begin result:=Math.Max(result,Canvas.TextWidth(Copy(s,1,i-1))); Inc(NumLines); Delete(s,1,i); i:={$IFDEF CLR}Pos{$ELSE}AnsiPos{$ENDIF}(TeeLineSeparator,s); end; if s<>'' then begin result:=Math.Max(result,Canvas.TextWidth(s)); Inc(NumLines); end; end; { Returns if no series are active (visible) and associated to the Axis parameter } Function TCustomAxisPanel.NoActiveSeries(AAxis:TChartAxis):Boolean; var t : Integer; begin for t:=0 to SeriesCount-1 do With Series[t] do if Active and AssociatedToAxis(AAxis) then begin result:=False; Exit; end; result:=True; end; { Calculates the minimum or maximum for the Axis parameter. This function is used internally. } Function TCustomAxisPanel.InternalMinMax(AAxis:TChartAxis; IsMin,IsX:Boolean):Double; var t : Integer; FirstTime : Boolean; tmpPagingAxis : Boolean; tmp : Double; tmpSeries : TChartSeries; tmpFirstPoint : Integer; tmpLastPoint : Integer; tmpNumPoints : Integer; tt : Integer; tmpList : TChartValueList; Begin if AAxis.IsDepthAxis then begin if AAxis.CalcLabelStyle=talValue then begin result:=0; FirstTime:=True; for tt:=0 to SeriesCount-1 do With Series[tt] do if Active then begin if IsMin then tmp:=MinZValue else tmp:=MaxZValue; if FirstTime or ( IsMin and (tmp<result) ) or ( (Not IsMin) and (tmp>result) ) then begin FirstTime:=False; result:=tmp; end; end; end else if IsMin then result:=-0.5 else result:=MaxZOrder+0.5; end else begin result:=0; tmpSeries:=GetAxisSeries(AAxis); if Assigned(tmpSeries) then begin if tmpSeries.YMandatory then tmpPagingAxis:=IsX else tmpPagingAxis:=not IsX; end else tmpPagingAxis:=IsX; if (FMaxPointsPerPage>0) and tmpPagingAxis then Begin tmpSeries:=GetAxisSeriesMaxPoints(AAxis); if Assigned(tmpSeries) and (tmpSeries.Count>0) then Begin tmpSeries.CalcFirstLastPage(tmpFirstPoint,tmpLastPoint); if IsX then tmpList:=tmpSeries.XValues else tmpList:=tmpSeries.YValues; if IsMin then result:=tmpList.Value[tmpFirstPoint] else Begin result:=tmpList.Value[tmpLastPoint]; if not FScaleLastPage then begin tmpNumPoints:=tmpLastPoint-tmpFirstPoint+1; if tmpNumPoints<FMaxPointsPerPage then begin tmp:=tmpList.Value[tmpFirstPoint]; if tmp=result then result:=tmp+FMaxPointsPerPage/tmpNumPoints // 7.0 else result:=tmp+FMaxPointsPerPage*(result-tmp)/tmpNumPoints; end; end; end; end; end else begin FirstTime:=True; for t:=0 to SeriesCount-1 do With Series[t] do if (FActive or NoActiveSeries(AAxis)) and (Count>0) then Begin if ( IsX and ((HorizAxis=aBothHorizAxis) or (GetHorizAxis=AAxis)) ) or ( (Not IsX) and ((VertAxis=aBothVertAxis) or (GetVertAxis =AAxis)) ) then Begin if IsMin then if IsX then tmp:=MinXValue else tmp:=MinYValue else if IsX then tmp:=MaxXValue else tmp:=MaxYValue; if FirstTime or ( IsMin and (tmp<result) ) or ( (Not IsMin) and (tmp>result) ) then Begin result:=tmp; FirstTime:=False; end; end; end; end; end; end; { Calculate the Maximum value of horizontal (X) Axis } Function TCustomAxisPanel.MaxXValue(AAxis:TChartAxis):Double; Begin result:=InternalMinMax(AAxis,False,True); end; { Calculate the Maximum value of vertical (Y) Axis } Function TCustomAxisPanel.MaxYValue(AAxis:TChartAxis):Double; Begin result:=InternalMinMax(AAxis,False,False); end; { Calculate the Minimum value of horizontal (X) Axis } Function TCustomAxisPanel.MinXValue(AAxis:TChartAxis):Double; Begin result:=InternalMinMax(AAxis,True,True); end; { Calculate the Minimum value of vertical (Y) Axis } Function TCustomAxisPanel.MinYValue(AAxis:TChartAxis):Double; Begin result:=InternalMinMax(AAxis,True,False); end; { When the Legend style is "series", returns the series that corresponds to the Legend "ItemIndex" position. The "OnlyActive" parameter, when False takes into account all series, regardless if they are visible (active) or not. } Function TCustomAxisPanel.SeriesLegend(ItemIndex:Integer; OnlyActive:Boolean):TChartSeries; var t : Integer; tmp : Integer; begin tmp:=0; for t:=0 to SeriesCount-1 do With Series[t] do if ShowInLegend and ((not OnlyActive) or Active) then if tmp=ItemIndex then begin result:=Series[t]; exit; end else Inc(tmp); result:=nil; end; { Returns the Active series (visible) that corresponds to the ItemIndex position in the Legend } Function TCustomAxisPanel.ActiveSeriesLegend(ItemIndex:Integer):TChartSeries; begin result:=SeriesLegend(ItemIndex,True); end; { Returns the string corresponding to the SeriesIndex th series for Legend } Function TCustomAxisPanel.SeriesTitleLegend(SeriesIndex:Integer; OnlyActive:Boolean):String; var tmpSeries : TChartSeries; Begin if OnlyActive then tmpSeries:=ActiveSeriesLegend(SeriesIndex) else tmpSeries:=SeriesLegend(SeriesIndex,False); if Assigned(tmpSeries) then result:=SeriesTitleOrName(tmpSeries) else result:=''; end; { Returns the width in pixels for the longest "Label" of all series, regardless if the series is active (visible) or not. } Function TCustomAxisPanel.MaxTextWidth:Integer; var t : Integer; tt : Integer; tmp: Integer; Begin result:=0; for t:=0 to SeriesCount-1 do With Series[t] do for tt:=0 to Labels.Count-1 do result:=Math.Max(result,MultiLineTextWidth(Labels[tt],tmp)); end; { Returns the longest width in pixels for all the active (visible) series marks. } Function TCustomAxisPanel.MaxMarkWidth:Integer; var t : Integer; Begin result:=0; for t:=0 to SeriesCount-1 do With Series[t] do if Active then result:=Math.Max(result,MaxMarkWidth); end; { Return the Index th series in SeriesList } Function TCustomAxisPanel.GetSeries(Index:Integer):TChartSeries; Begin result:=TChartSeries({$IFOPT R-}FSeriesList.List{$ELSE}FSeriesList{$ENDIF}[Index]); end; type TView3DAccess=class {$IFDEF CLR}sealed{$ENDIF} (TView3DOptions); { Calculates internal parameters for the series Width and Height in 3D mode. } Procedure TCustomAxisPanel.CalcSize3DWalls; var tmpNumSeries : Integer; tmp : Double; Begin if View3D then Begin tmp:=0.001*Chart3DPercent; if not View3DOptions.Orthogonal then tmp:=tmp*2; FSeriesWidth3D :=Round(tmp*ChartWidth); tmp:=TView3DAccess(View3DOptions).CalcOrthoRatio; if tmp>1 then FSeriesWidth3D:=Round(FSeriesWidth3D/tmp); FSeriesHeight3D:=Round(FSeriesWidth3D*tmp); if ApplyZOrder then tmpNumSeries:=Math.Max(1,MaxZOrder+1) else tmpNumSeries:=1; Height3D:=FSeriesHeight3D * tmpNumSeries; Width3D :=FSeriesWidth3D * tmpNumSeries; end else begin FSeriesWidth3D :=0; FSeriesHeight3D:=0; Width3D :=0; Height3D :=0; end; end; { Returns the number of series in the chart } Function TCustomAxisPanel.SeriesCount:Integer; begin result:=FSeriesList.Count; end; { Triggers an event for all "tools" } Procedure TCustomAxisPanel.BroadcastToolEvent(AEvent:TChartToolEvent); var t : Integer; begin for t:=0 to Tools.Count-1 do With Tools[t] do if Active then ChartEvent(AEvent); end; Procedure TCustomAxisPanel.CalcInvertedRotation; begin InvertedRotation:=False; if View3D then if View3DOptions.Orthogonal then begin if View3DOptions.OrthoAngle>90 then InvertedRotation:=True; end else begin if (View3DOptions.Rotation<180) then InvertedRotation:=True; end; end; { Main drawing method. Draws everything. } Procedure TCustomAxisPanel.InternalDraw(Const UserRectangle:TRect); { Draw one single Series } Procedure DrawSeries(TheSeries:TChartSeries); Var ActiveRegion : Boolean; { Create a clipping 3D region (cube) and apply it to Canvas } Procedure ClipRegionCreate; var tmpR : TRect; Begin if CanClip then begin tmpR:=ChartRect; Inc(tmpR.Bottom); Canvas.ClipCube(tmpR,0,Width3D); ActiveRegion:=True; end; end; { Remove the clipping region } Procedure ClipRegionDone; Begin if ActiveRegion then begin Canvas.UnClipRectangle; ActiveRegion:=False; end; end; { Draw one single point (ValueIndex) for all Series } Procedure DrawAllSeriesValue(ValueIndex:Integer); { If the ASeries parameter has the same "Z" order than the current series, draw the point } Procedure TryDrawSeries(ASeries:TChartSeries); begin With ASeries do if FActive and (ZOrder=TheSeries.ZOrder) and (ValueIndex<Count) then DrawValue(ValueIndex) end; var t : Integer; tmp1 : Integer; tmp2 : Integer; Begin tmp1:=SeriesList.IndexOf(TheSeries); tmp2:=SeriesCount-1; if ValueIndex<TheSeries.Count then begin if TheSeries.DrawSeriesForward(ValueIndex) then for t:=tmp1 to tmp2 do TryDrawSeries(Series[t]) else for t:=tmp2 downto tmp1 do TryDrawSeries(Series[t]) end else for t:=tmp1 to tmp2 do TryDrawSeries(Series[t]) end; { Draw the "Marks" of the ASeries } Procedure DrawMarksSeries(ASeries:TChartSeries); begin if ASeries.Count>0 then With ASeries,FMarks do if Visible then Begin if FClip then ClipRegionCreate; DrawMarks; if FClip then ClipRegionDone; end; end; Var t : Integer; tmpFirst : Integer; tmpLast : Integer; Begin ActiveRegion:=False; { <-- VERY IMPORTANT !!!! } With TheSeries do if View3D and MoreSameZOrder then Begin if FirstInZOrder then Begin tmpFirst:=-1; tmpLast :=-1; for t:=SeriesList.IndexOf(TheSeries) to SeriesCount-1 do With Series[t] do if Active and (ZOrder=TheSeries.ZOrder) then Begin CalcFirstLastVisibleIndex; if FFirstVisibleIndex<>-1 then Begin if tmpFirst=-1 then tmpFirst:=FFirstVisibleIndex else tmpFirst:=Math.Max(tmpFirst,FFirstVisibleIndex); if tmpLast=-1 then tmpLast:=FLastVisibleIndex else tmpLast:=Math.Max(tmpLast,FLastVisibleIndex); DoBeforeDrawValues; if ClipPoints and (not ActiveRegion) then ClipRegionCreate; end; end; { values } if tmpFirst<>-1 then if DrawValuesForward then for t:=tmpFirst to tmpLast do DrawAllSeriesValue(t) else for t:=tmpLast downto tmpFirst do DrawAllSeriesValue(t); { Region } ClipRegionDone; { Marks and DoAfterDrawValues } for t:=SeriesList.IndexOf(TheSeries) to SeriesCount-1 do With Series[t] do if Active and (ZOrder=TheSeries.ZOrder) and (FFirstVisibleIndex<>-1) then begin DrawMarksSeries(Series[t]); DoAfterDrawValues; end; end; end else begin CalcFirstLastVisibleIndex; if FFirstVisibleIndex<>-1 then begin DoBeforeDrawValues; if UseAxis and ClipPoints then ClipRegionCreate; DrawAllValues; ClipRegionDone; DrawMarksSeries(TheSeries); DoAfterDrawValues; end; end; end; { Calculate the "Z" order for all Series } Procedure SetSeriesZOrder; Var tmpSeries : Integer; tmpOk : Boolean; begin FMaxZOrder:=0; tmpOk:=ApplyZOrder and View3D; if tmpOk then Begin FMaxZOrder:=-1; for tmpSeries:=0 to SeriesCount-1 do With Series[tmpSeries] do if FActive then CalcZOrder; end; { invert Z Orders } if not DepthAxis.Inverted then // 6.01 for tmpSeries:=0 to SeriesCount-1 do With Series[tmpSeries] do if FActive then if tmpOk then IZOrder:=MaxZOrder-ZOrder else IZOrder:=0; end; { Calculate the Start, End and Middle "Z" coordinates for all Series } Procedure SetSeriesZPositions; var tmp : Integer; begin for tmp:=0 to SeriesCount-1 do with Series[tmp] do if Active then CalcDepthPositions; end; { Draw all Axes (normal and custom) } Procedure DrawAllAxis; var t : Integer; tmpAxis : TChartAxis; Begin if AxisVisible then begin DoOnBeforeDrawAxes; With FAxes do for t:=0 to Count-1 do begin tmpAxis:=FAxes[t]; if IsAxisVisible(tmpAxis) then begin if (tmpAxis<>Axes.Bottom) or (not DrawBackWallAfter(0)) then tmpAxis.Draw(True); end; end; end; end; procedure CalcAxisRect; Procedure RecalcPositions; var tmp : Integer; begin with FAxes do for tmp:=0 to Count-1 do Get(tmp).InternalCalcPositions; end; var tmpR : TRect; OldR : TRect; tmp : Integer; tmpAxis : TChartAxis; begin with FAxes do for tmp:=0 to Count-1 do begin tmpAxis:=Get(tmp); tmpAxis.IsVisible:=CalcIsAxisVisible(tmpAxis); tmpAxis.AdjustMaxMin; end; RecalcPositions; tmpR:=ChartRect; with FAxes do for tmp:=0 to Count-1 do if IsAxisVisible(Get(tmp)) then Begin OldR:=tmpR; Get(tmp).CalcRect(OldR,tmp<5); { <-- inflate only for first 5 axes } {$IFDEF CLX} if IntersectRect(OldR,OldR,tmpR) then {$ELSE} if {$IFNDEF CLR}Windows.{$ENDIF}IntersectRect(OldR,tmpR,OldR) then {$ENDIF} tmpR:=OldR; end; ChartRect:=tmpR; RecalcWidthHeight; RecalcPositions; end; // Calculate all axis offsets Procedure CalcSeriesRect; // Calculate one axis offsets, according to series margins Procedure CalcSeriesAxisRect(Axis:TChartAxis); // Apply offsets in pixels Procedure ApplyOffsets(var a,b:Integer); begin if Axis.Inverted then begin Inc(b,Axis.MinimumOffset); // 6.01 Inc(a,Axis.MaximumOffset); // 6.01 end else begin Inc(a,Axis.MinimumOffset); Inc(b,Axis.MaximumOffset); end; end; Var tmpR : TRect; a : Integer; b : Integer; tmpSeries : Integer; Begin tmpR:=TeeRect(0,0,0,0); // Wish: New axis property to deactivate calculation of "margins". for tmpSeries:=0 to SeriesCount-1 do With Series[tmpSeries] do if Active then if AssociatedToAxis(Axis) then if Axis.Horizontal then begin CalcHorizMargins(a,b); With tmpR do begin if Axis.AutomaticMinimum then Left :=Math.Max(Left,a); if Axis.AutomaticMaximum then Right:=Math.Max(Right,b); end; end else begin CalcVerticalMargins(a,b); With tmpR do begin if Axis.AutomaticMaximum then Top :=Math.Max(Top,a); if Axis.AutomaticMinimum then Bottom:=Math.Max(Bottom,b); end; end; if Axis.Horizontal then ApplyOffsets(tmpR.Left,tmpR.Right) else ApplyOffsets(tmpR.Bottom,tmpR.Top); Axis.AdjustMaxMinRect(tmpR); end; var t : Integer; begin for t:=0 to Axes.Count-1 do CalcSeriesAxisRect(Axes[t]); end; procedure DrawAllSeries; var t : Integer; tmp : Boolean; begin tmp:=DepthAxis.Inverted; // 7.0 if DrawBackWallAfter(Width3D) then tmp:=not tmp; if tmp then // 6.01 begin for t:=SeriesCount-1 downto 0 do if Series[t].Active then DrawSeries(Series[t]) end else for t:=0 to SeriesCount-1 do if Series[t].Active then DrawSeries(Series[t]); end; var tmp, OldRect : TRect; Old : Boolean; t : Integer; Begin Old:=AutoRepaint; AutoRepaint:=False; CalcInvertedRotation; tmp:=UserRectangle; if not InternalCanvas.SupportsFullRotation then PanelPaint(tmp); BroadcastToolEvent(cteBeforeDraw); // 5.02 DoOnBeforeDrawChart; for t:=0 to SeriesCount-1 do With Series[t] do if Active then DoBeforeDrawChart; if not InternalCanvas.SupportsFullRotation then DrawTitlesAndLegend(True); SetSeriesZOrder; CalcWallsRect; tmp:=ChartRect; CalcAxisRect; SetSeriesZPositions; CalcSeriesRect; InternalCanvas.Projection(Width3D,ChartBounds,ChartRect); if InternalCanvas.SupportsFullRotation then begin OldRect:=ChartRect; ChartRect:=tmp; PanelPaint(UserRectangle); // 7.0 DrawTitlesAndLegend(True); ChartRect:=OldRect; end; DrawWalls; if AxisBehind then begin BroadcastToolEvent(cteBeforeDrawAxes); // 7.0 DrawAllAxis; end; BroadcastToolEvent(cteBeforeDrawSeries); DoOnBeforeDrawSeries; DrawAllSeries; BroadcastToolEvent(cteAfterDrawSeries); // 7.0 if not AxisBehind then begin BroadcastToolEvent(cteBeforeDrawAxes); DrawAllAxis; end; DrawTitlesAndLegend(False); if Zoom.Active then DrawZoomRectangle; BroadcastToolEvent(cteAfterDraw); Canvas.ResetState; DoOnAfterDraw; AutoRepaint:=Old; end; procedure TCustomAxisPanel.DoOnBeforeDrawAxes; Begin if Assigned(FOnBeforeDrawAxes) then FOnBeforeDrawAxes(Self); end; procedure TCustomAxisPanel.DoOnBeforeDrawChart; Begin if Assigned(FOnBeforeDrawChart) then FOnBeforeDrawChart(Self); end; procedure TCustomAxisPanel.DoOnBeforeDrawSeries; Begin if Assigned(FOnBeforeDrawSeries) then FOnBeforeDrawSeries(Self); end; procedure TCustomAxisPanel.ColorPaletteChanged; var t : Integer; begin for t:=0 to SeriesCount-1 do with Series[t] do if FColor=clTeeColor then ChangeInternalColor(GetFreeSeriesColor(True,Series[t])); end; procedure TCustomAxisPanel.DoOnAfterDraw; Begin if Assigned(FOnAfterDraw) then FOnAfterDraw(Self); end; procedure TCustomAxisPanel.SetView3DWalls(Value:Boolean); Begin SetBooleanProperty(FView3DWalls,Value); end; { Internal for VCL streaming mechanism. Stores all Series in the DFM. } Procedure TCustomAxisPanel.GetChildren(Proc:TGetChildProc; Root:TComponent); var t : Integer; begin inherited; for t:=0 to SeriesCount-1 do if not Series[t].InternalUse then Proc(Series[t]); end; {$IFNDEF CLX} procedure TCustomAxisPanel.CMMouseLeave(var Message: TMessage); {$ELSE} procedure TCustomAxisPanel.MouseLeave(AControl: TControl); {$ENDIF} begin inherited; BroadcastToolEvent(cteMouseLeave); end; { Abstract virtual } procedure TCustomAxisPanel.RemovedDataSource( ASeries: TChartSeries; AComponent: TComponent ); begin if (AComponent is TTeeSeriesSource) and (AComponent=ASeries.DataSource) then TTeeSeriesSource(AComponent).Series:=nil; end; procedure TCustomAxisPanel.SetClipPoints(Value:Boolean); Begin SetBooleanProperty(FClipPoints,Value); end; Procedure TCustomAxisPanel.SetCustomAxes(Value:TChartCustomAxes); begin FCustomAxes.Assign(Value); end; procedure TCustomAxisPanel.SetLeftAxis(Value:TChartAxis); begin FLeftAxis.Assign(Value); end; procedure TCustomAxisPanel.SetDepthAxis(Value:TChartDepthAxis); begin FDepthAxis.Assign(Value); end; procedure TCustomAxisPanel.SetDepthTopAxis(const Value: TChartDepthAxis); begin FDepthTopAxis.Assign(Value); end; procedure TCustomAxisPanel.SetRightAxis(Value:TChartAxis); begin FRightAxis.Assign(Value); end; procedure TCustomAxisPanel.SetTopAxis(Value:TChartAxis); begin FTopAxis.Assign(Value); end; procedure TCustomAxisPanel.SetBottomAxis(Value:TChartAxis); begin FBottomAxis.Assign(Value); end; { Deletes (not destroys) a given Series. Triggers a "removed series" event and repaints } Procedure TCustomAxisPanel.RemoveSeries(ASeries:TCustomChartSeries); var t : Integer; Begin t:=SeriesList.IndexOf(ASeries); if t<>-1 then begin BroadcastSeriesEvent(ASeries,seRemove); ASeries.Removed; FSeriesList.Delete(t); Invalidate; end; end; { Returns the first series that is Active (visible) and associated to a given Axis. } Function TCustomAxisPanel.GetAxisSeries(Axis:TChartAxis):TChartSeries; Var t : Integer; Begin for t:=0 to SeriesCount-1 do begin result:=Series[t]; With result do if (FActive or NoActiveSeries(Axis) ) and AssociatedToAxis(Axis) then Exit; end; result:=nil; end; // Returns the series that is Active (visible) and // associated to a given Axis, and has maximum number of points. // This function is only used when calculating min and max for axis // when MaxPointsPerPage is > 0. (Paging is activated) Function TCustomAxisPanel.GetAxisSeriesMaxPoints(Axis:TChartAxis):TChartSeries; Var t : Integer; tmp : Integer; tmpSeries : TChartSeries; Begin result:=nil; tmp:=-1; for t:=0 to SeriesCount-1 do begin tmpSeries:=Series[t]; With tmpSeries do if (FActive or NoActiveSeries(Axis) ) and AssociatedToAxis(Axis) then if tmpSeries.Count>tmp then begin tmp:=tmpSeries.Count; result:=tmpSeries; end; end; end; Function TCustomAxisPanel.FormattedValueLegend(ASeries:TChartSeries; ValueIndex:Integer):String; begin { virtual, overrided at TChart } result:=''; end; Function TCustomAxisPanel.GetDefaultColor(Index:Integer):TColor; begin if Assigned(ColorPalette) then result:=ColorPalette[Low(ColorPalette)+(Index mod Succ(High(ColorPalette)-Low(ColorPalette)))] else result:=TeeProcs.GetDefaultColor(Index); end; { Returns a color from the "color palette" global array that is not used by any series. ( SeriesColor ) } Function TCustomAxisPanel.GetFreeSeriesColor(CheckBackground:Boolean=True; Series:TChartSeries=nil):TColor; var t : Integer; l : Integer; Begin t:=0; if Assigned(ColorPalette) then l:=High(ColorPalette) else l:=High(TeeProcs.ColorPalette); Repeat result:=GetDefaultColor(t); Inc(t); Until (t>l) or IsFreeSeriesColor(result,CheckBackground,Series); end; Function TCustomAxisPanel.AddSeries(ASeries:TChartSeries):TChartSeries; begin ASeries.ParentChart:=Self; result:=ASeries; end; function TCustomAxisPanel.AddSeries( ASeriesClass: TChartSeriesClass): TChartSeries; begin result:=AddSeries(ASeriesClass.Create(Owner)); end; { internal. Calls CheckMouse for all visible Series. } Function TCustomAxisPanel.CheckMouseSeries(x,y:Integer):Boolean; var t : Integer; begin result:=False; for t:=SeriesCount-1 downto 0 do with Series[t] do if Active then if CheckMouse(x,y) then result:=True; end; { Triggers an event specific to Series } Procedure TCustomAxisPanel.BroadcastSeriesEvent(ASeries:TCustomChartSeries; Event:TChartSeriesEvent); var tmp : TTeeSeriesEvent; begin tmp:=TTeeSeriesEvent.Create; try tmp.Event:=Event; tmp.Series:=ASeries; BroadcastTeeEvent(tmp); finally tmp.Free; end; end; Procedure TCustomAxisPanel.InternalAddSeries(ASeries:TCustomChartSeries); Begin if SeriesList.IndexOf(ASeries)=-1 then begin with ASeries do begin FParent:=Self; Added; end; FSeriesList.Add(ASeries); BroadcastSeriesEvent(ASeries,seAdd); Invalidate; end; end; { Returns the number of points of the Active (visible) Series that has more points. } Function TCustomAxisPanel.GetMaxValuesCount:Integer; var t : Integer; FirstTime : Boolean; Begin result:=0; FirstTime:=True; for t:=0 to SeriesCount-1 do with Series[t] do if Active and ( FirstTime or (Count>result) ) then begin result:=Count; FirstTime:=False; end; end; Procedure TCustomAxisPanel.SetAxisBehind(Value:Boolean); Begin SetBooleanProperty(FAxisBehind,Value); end; Procedure TCustomAxisPanel.SetAxisVisible(Value:Boolean); Begin SetBooleanProperty(FAxisVisible,Value); end; { Prevents a circular relationship between series and series DataSource. Raises an exception. } Procedure TCustomAxisPanel.CheckOtherSeries(Dest,Source:TChartSeries); var t : Integer; Begin if Assigned(Source) then if Source.DataSource=Dest then Raise ChartException.Create(TeeMsg_CircularSeries) else if Source.DataSource is TChartSeries then for t:=0 to Source.DataSources.Count-1 do CheckOtherSeries(Dest,TChartSeries(Source.DataSources[t])); end; { Returns True when the AComponent is a valid DataSource for the ASeries parameter. } Function TCustomAxisPanel.IsValidDataSource(ASeries:TChartSeries; AComponent:TComponent):Boolean; Begin result:=(ASeries<>AComponent) and (AComponent is TChartSeries) and ASeries.IsValidSeriesSource(TChartSeries(AComponent)); { check virtual "data source" } if not result then if AComponent is TTeeSeriesSource then result:=TTeeSeriesSource(AComponent).Available(Self); end; { When ASeries has a DataSource that is another Series, calls the AddValues method to add (copy) all the points from the DataSource to the ASeries. } Procedure TCustomAxisPanel.CheckDatasource(ASeries:TChartSeries); Begin With ASeries do if not (csLoading in ComponentState) then begin if Assigned(DataSource) then begin if DataSource is TChartSeries then AddValues(TChartSeries(DataSource)) else if DataSource is TTeeSeriesSource then { 5.02 } TTeeSeriesSource(DataSource).Refresh; end else if Assigned(FunctionType) then begin if FunctionType.NoSourceRequired then begin BeginUpdate; { before Clear } Clear; FunctionType.AddPoints(nil); { calculate function } EndUpdate; { propagate changes... } end; end else if not ManualData then if CanAddRandomPoints then FillSampleValues(NumSampleValues) //else //Clear; end; end; function TCustomAxisPanel.DrawBackWallAfter(Z: Integer): Boolean; begin result:=not TeeCull(Canvas.FourPointsFromRect(ChartRect,Z)); end; // Swaps one series with another in the series list. // Triggers a series event (swap event) and repaints. Procedure TCustomAxisPanel.ExchangeSeries(a,b:Integer); var tmpIndex : Integer; tmp : Integer; begin SeriesList.Exchange(a,b); tmpIndex:=Series[a].ComponentIndex; Series[a].ComponentIndex:=Series[b].ComponentIndex; Series[b].ComponentIndex:=tmpIndex; // If both Series are contained in the same series group, // exchange them too. tmp:=SeriesList.Groups.Contains(Series[a]); if (tmp<>-1) and (SeriesList.Groups[tmp].Series.IndexOf(Series[b])<>-1) then with SeriesList.Groups[tmp].Series do Exchange(IndexOf(Series[a]),IndexOf(Series[b])); BroadcastSeriesEvent(nil,seSwap); Invalidate; end; Procedure TCustomAxisPanel.ExchangeSeries(a,b:TCustomChartSeries); begin ExchangeSeries(SeriesList.IndexOf(a),SeriesList.IndexOf(b)); end; { Copies all settings from one chart to self. } Procedure TCustomAxisPanel.Assign(Source:TPersistent); begin if Source is TCustomAxisPanel then With TCustomAxisPanel(Source) do begin Self.F3DPercent := F3DPercent; Self.FAxisBehind := FAxisBehind; Self.FAxisVisible := FAxisVisible; Self.BottomAxis := FBottomAxis; Self.FClipPoints := ClipPoints; Self.ColorPalette := ColorPalette; Self.CustomAxes := FCustomAxes; Self.LeftAxis := FLeftAxis; Self.DepthAxis := FDepthAxis; Self.DepthTopAxis := FDepthTopAxis; Self.FMaxPointsPerPage := FMaxPointsPerPage; Self.FPage := FPage; Self.RightAxis := FRightAxis; Self.FScaleLastPage := FScaleLastPage; Self.TopAxis := FTopAxis; Self.FView3DWalls := FView3DWalls; end; inherited; end; function TCustomAxisPanel.IsCustomAxesStored: Boolean; begin result:=FCustomAxes.Count>0; end; { TTeeSeriesSource } { Base abstract class for Series "datasources" } Constructor TTeeSeriesSource.Create(AOwner: TComponent); begin inherited {$IFDEF CLR}Create(AOwner){$ENDIF}; FActive:=False; end; Destructor TTeeSeriesSource.Destroy; begin Close; inherited; end; procedure TTeeSeriesSource.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation=opRemove) and Assigned(FSeries) and (AComponent=FSeries) then Series:=nil; end; procedure TTeeSeriesSource.SetSeries(const Value: TChartSeries); var Old : TChartSeries; begin if FSeries<>Value then begin {$IFNDEF TEEOCX} Close; if Assigned(FSeries) then begin {$IFDEF D5} FSeries.RemoveFreeNotification(Self); {$ENDIF} end; {$ENDIF} Old:=FSeries; FSeries:=Value; if Assigned(FSeries) then begin FSeries.FreeNotification(Self); FSeries.DataSource:=Self; end else if Assigned(Old) then Old.DataSource:=nil; {$IFDEF TEEOCX} Close; {$ENDIF} end; end; { Load data into Series or Clear Series } procedure TTeeSeriesSource.SetActive(const Value: Boolean); begin if FActive<>Value then begin if Assigned(FSeries) then begin if Value then begin { if True, load points into Series } if not (csLoading in ComponentState) then Load; end else if (not (csDestroying in ComponentState)) and (not (csDestroying in FSeries.ComponentState)) then FSeries.Clear; { remove Series points } end; FActive:=Value; end; end; procedure TTeeSeriesSource.Close; begin { set Active property to False } if (not (csLoading in ComponentState)) and (not (csDestroying in ComponentState)) then Active:=False; end; Procedure TTeeSeriesSource.Load; // virtual; abstract; begin end; procedure TTeeSeriesSource.Open; begin { set Active property to True } Active:=True; end; Procedure TTeeSeriesSource.Refresh; begin { close and re-open the datasource } if Active and (not (csLoading in ComponentState)) then // 6.0 Load; { 5.02 } end; { after loading from DFM, and if Active, load data } Procedure TTeeSeriesSource.Loaded; begin inherited; Refresh; end; { return True when the AChart parameter supports this datasource } class function TTeeSeriesSource.Available(AChart: TCustomAxisPanel): Boolean; begin result:=True; end; class Function TTeeSeriesSource.Description:String; begin result:=''; end; class Function TTeeSeriesSource.Editor:TComponentClass; begin result:=nil; end; { return True when Series DataSource is same class } class function TTeeSeriesSource.HasSeries(ASeries: TChartSeries): Boolean; begin result:=ASeries.DataSource.ClassNameIs(ClassName); end; { returns True if this series source allows "New,Edit,Delete" buttons at Series DataSource editor dialog } class function TTeeSeriesSource.HasNew: Boolean; begin result:=False; end; { Utility functions } { Returns the series Title (or series Name if Title is empty). } Function SeriesTitleOrName(ASeries:TCustomChartSeries):String; begin result:=ASeries.Title; if result='' then begin result:=ASeries.Name; if (result='') and Assigned(ASeries.ParentChart) then result:=TeeMsg_Series+TeeStr(1+ASeries.ParentChart.SeriesList.IndexOf(ASeries)); end end; { Adds all Series to the AItems parameter. } Procedure FillSeriesItems(AItems:TStrings; AList:TCustomSeriesList; UseTitles:Boolean=True); var t : Integer; begin AItems.BeginUpdate; try with AList do for t:=0 to Count-1 do if not Items[t].InternalUse then if UseTitles then AItems.AddObject(SeriesTitleOrName(Items[t]),Items[t]) else AItems.AddObject(Items[t].Name,Items[t]); finally AItems.EndUpdate; end; end; { List of registered Series Source components } var FTeeSources: TList; Function TeeSources: TList; begin if not Assigned(FTeeSources) then FTeeSources:=TList.Create; result:=FTeeSources; end; Procedure ShowMessageUser(Const S:String); {$IFNDEF CLX} var St : Array[0..1023] of Char; {$ENDIF} begin {$IFDEF CLR} MessageBox(0, S,'',MB_OK or MB_ICONSTOP or MB_TASKMODAL); {$ELSE} {$IFDEF CLX} ShowMessage(S); {$ELSE} MessageBox(0, StrPCopy(St,S),'',MB_OK or MB_ICONSTOP or MB_TASKMODAL); {$ENDIF} {$ENDIF} end; { Returns if a Series has "X" values (or Y values for HorizBar series) } Function HasNoMandatoryValues(ASeries:TChartSeries):Boolean; var t : Integer; tmpCount : Integer; tmp : TChartValueList; begin result:=False; With ASeries do if IUseNotMandatory and (Count>0) then begin tmp:=ASeries.NotMandatoryValueList; if (tmp.First=0) and (tmp.Last=Count-1) then begin tmpCount:=Math.Min(10000,Count-1); for t:=0 to tmpCount do if tmp.Value[t]<>t then begin result:=True; Exit; end; end else result:=True; end; end; { Returns if a Series has Colors } Function HasColors(ASeries:TChartSeries):Boolean; var t : Integer; tmpCount : Integer; tmpColor : TColor; tmpSeriesColor:TColor; begin result:=False; With ASeries do begin tmpSeriesColor:=SeriesColor; tmpCount:=Math.Min(10000,Count-1); for t:=0 to tmpCount do begin tmpColor:=InternalColor(t); // tmpColor:=ValueColor[t]; if (tmpColor<>clTeeColor) and (tmpColor<>tmpSeriesColor) then begin result:=True; exit; end; end; end; end; { Returns if a Series has labels } Function HasLabels(ASeries:TChartSeries):Boolean; var t : Integer; tmpCount : Integer; begin result:=False; if ASeries.Labels.Count>0 then // 5.01 begin tmpCount:=Math.Min(100,ASeries.Count-1); for t:=0 to tmpCount do if ASeries.Labels[t]<>'' then begin result:=True; Exit; end; end; end; { TDataSourcesList } // 6.02 {$IFDEF D5} // When calling Series1.DataSources.Remove (or Delete) methods, // Notify is called to make sure the Series does its cleaning. {$IFDEF CLR} procedure TDataSourcesList.Notify(Instance:TObject; Action: TListNotification); {$ELSE} procedure TDataSourcesList.Notify(Ptr: Pointer; Action: TListNotification); {$ENDIF} begin inherited; if Action=lnDeleted then Series.InternalRemoveDataSource({$IFDEF CLR}TComponent(Instance){$ELSE}Ptr{$ENDIF}) end; {$ENDIF} // When adding a source directly using Series1.DataSources.Add( xxx ) // this method calls the Series internal method. function TDataSourcesList.Add(Value:TComponent):Integer; begin result:=Series.InternalSetDataSource(Value,False); end; // Call the TList Add method directly function TDataSourcesList.InheritedAdd(Value:TComponent):Integer; begin result:=inherited Add(Value); end; // Call the TList Clear method directly procedure TDataSourcesList.InheritedClear; begin inherited Clear; end; // When calling Series1.DataSources.Clear, this method // does all the appropiate cleaning. procedure TDataSourcesList.Clear; begin Series.RemoveAllLinkedSeries; InheritedClear; // Remove all points in series, unless data is "manual". if not Series.ManualData then Series.Clear; end; { TLabelsList } { Returns the label string for the corresponding point (ValueIndex). Returns an empty string is no labels exist. } function TLabelsList.GetLabel(ValueIndex: Integer): String; begin // Here there's already a range protection. // No need to access inherited Items with R+ compiler option. if (Count<=ValueIndex) or (List{$IFNDEF CLR}^{$ENDIF}[ValueIndex]=nil) then // 5.01 result:='' else result:={$IFDEF CLR}String(List[ValueIndex]){$ELSE}PString(List^[ValueIndex])^{$ENDIF}; end; { Replaces a Label into the labels list. Allocates the memory for the ALabel string parameter. } function TLabelsList.IndexOfLabel(const ALabel: String; CaseSensitive:Boolean=True): Integer; var t : Integer; tmp : String; begin if CaseSensitive then begin for t:=0 to Count-1 do if Labels[t]=ALabel then begin result:=t; exit; end; end else begin tmp:=UpperCase(ALabel); for t:=0 to Count-1 do if UpperCase(Labels[t])=tmp then begin result:=t; exit; end; end; result:=-1; end; procedure TLabelsList.SetLabel(ValueIndex: Integer; const ALabel: String); var {$IFNDEF CLR} P : PString; {$ENDIF} t : Integer; begin {$IFDEF CLR} if ALabel='' then begin if Count>0 then List[ValueIndex]:=nil { 5.01 } end else begin if Count<=ValueIndex then { 5.01 } for t:=Count to ValueIndex do Add(nil); List[ValueIndex]:=ALabel; end; {$ELSE} if (Count>ValueIndex) and Assigned(List^[ValueIndex]) then // 5.01 Dispose(PString(List^[ValueIndex])); if ALabel='' then begin if (Count>0) and (ValueIndex<Count) then // 7.0 List^[ValueIndex]:=nil // 5.01 end else begin New(P); P^:=ALabel; if Count<=ValueIndex then { 5.01 } for t:=Count to ValueIndex do Add(nil); List^[ValueIndex]:=P; end; {$ENDIF} Series.Repaint; end; { Allocates memory for the ALabel string parameter and inserts it into the labels list. } Procedure TLabelsList.InsertLabel(ValueIndex:Integer; Const ALabel:String); {$IFNDEF CLR} Procedure InternalInsert(P:PString); begin // grow list while Count<ValueIndex do Add(nil); { 5.02 } // insert Insert(ValueIndex,P); end; {$ENDIF} {$IFNDEF CLR} Var P : PString; {$ENDIF} Begin {$IFDEF CLR} if ALabel='' then begin if Count>0 then begin // grow list while Count<ValueIndex do Add(nil); { 5.02 } // insert Insert(ValueIndex,nil); end; end else begin // grow list while Count<ValueIndex do Add(nil); { 5.02 } // insert Insert(ValueIndex,ALabel); end; {$ELSE} if ALabel='' then begin if Count>0 then InternalInsert(nil); { 5.01 } end else begin New(P); P^:=ALabel; InternalInsert(P); end; {$ENDIF} end; procedure TLabelsList.Assign(Source: TLabelsList); var t : Integer; begin Clear; for t:=0 to Source.Count-1 do InsertLabel(t,Source[t]); end; procedure TLabelsList.Clear; {$IFNDEF CLR} var t : Integer; {$ENDIF} begin {$IFNDEF CLR} for t:=0 to Count-1 do if Assigned(List^[t]) then Dispose(PString(List^[t])); {$ENDIF} inherited; end; Procedure TLabelsList.DeleteLabel(ValueIndex:Integer); Begin {$IFNDEF CLR} if (Count>ValueIndex) and Assigned(List^[ValueIndex]) then // 6.02 Dispose(PString(List^[ValueIndex])); { 5.01 } {$ENDIF} Delete(ValueIndex); end; { TSeriesPointer } Constructor TSeriesPointer.Create(AOwner:TChartSeries); Begin {$IFDEF CLR} inherited Create; {$ENDIF} if Assigned(AOwner) then ParentChart:=AOwner.ParentChart; {$IFNDEF CLR} inherited Create; {$ENDIF} AllowChangeSize:=True; FSeries:=AOwner; FInflate:=True; FHorizSize:=4; FVertSize:=4; FDark3D:=True; FDraw3D:=True; FStyle:=psRectangle; FGradient:=TChartGradient.Create(CanvasChanged); end; destructor TSeriesPointer.Destroy; begin FGradient.Free; inherited; end; Procedure TSeriesPointer.ChangeStyle(NewStyle:TSeriesPointerStyle); Begin FStyle:=NewStyle; end; Procedure TSeriesPointer.ChangeHorizSize(NewSize:Integer); Begin FHorizSize:=NewSize; End; Procedure TSeriesPointer.ChangeVertSize(NewSize:Integer); Begin FVertSize:=NewSize; End; Procedure TSeriesPointer.CheckPointerSize(Value:Integer); begin if Value<1 then Raise ChartException.Create(TeeMsg_CheckPointerSize) end; Procedure TSeriesPointer.SetHorizSize(Value:Integer); Begin CheckPointerSize(Value); if HorizSize<>Value then begin FHorizSize:=Value; Repaint; end; end; Procedure TSeriesPointer.SetInflate(Value:Boolean); begin if FInflate<>Value then begin FInflate:=Value; Repaint; end; end; Procedure TSeriesPointer.SetVertSize(Value:Integer); Begin CheckPointerSize(Value); if FVertSize<>Value then begin FVertSize:=Value; Repaint; end; end; Procedure TSeriesPointer.SetDark3D(Value:Boolean); Begin if FDark3D<>Value then begin FDark3D:=Value; Repaint; end; end; Procedure TSeriesPointer.SetDraw3D(Value:Boolean); Begin if FDraw3D<>Value then begin FDraw3D:=Value; Repaint; end; end; Procedure TSeriesPointer.Change3D(Value:Boolean); Begin FDraw3D:=Value; end; Procedure TSeriesPointer.CalcHorizMargins(Var LeftMargin,RightMargin:Integer); begin if Visible and FInflate then begin LeftMargin :=Math.Max(LeftMargin, HorizSize+1); RightMargin:=Math.Max(RightMargin,HorizSize+1); end; end; Procedure TSeriesPointer.CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); begin if Visible and FInflate then begin TopMargin :=Math.Max(TopMargin, VertSize+1); BottomMargin:=Math.Max(BottomMargin,VertSize+1); end; end; Procedure TSeriesPointer.SetStyle(Value:TSeriesPointerStyle); Begin if FStyle<>Value then begin FStyle:=Value; Repaint; end; end; Procedure TSeriesPointer.Prepare; begin PrepareCanvas(ParentChart.Canvas,Color); end; Procedure TSeriesPointer.PrepareCanvas(ACanvas:TCanvas3D; ColorValue:TColor); var tmp : TColor; Begin if Pen.Visible then begin if Pen.Color=clTeeColor then ACanvas.AssignVisiblePenColor(Pen,ColorValue) { use default point color } else ACanvas.AssignVisiblePen(Pen); { use fixed Pen.Color } end else if ACanvas.Pen.Style<>psClear then // 5.02 ACanvas.Pen.Style:=psClear; tmp:=Brush.Color; if tmp=clTeeColor then if Brush.Style=bsSolid then tmp:=ColorValue else tmp:=clBlack; ACanvas.AssignBrushColor(Brush,tmp,ColorValue); end; Procedure TSeriesPointer.DrawPointer( ACanvas:TCanvas3D; Is3D:Boolean; px,py,tmpHoriz,tmpVert:Integer; ColorValue:TColor; AStyle:TSeriesPointerStyle); Var PXMinus : Integer; PXPlus : Integer; PYMinus : Integer; PYPlus : Integer; Procedure DrawDiagonalCross; Begin with ACanvas do begin if Is3D then begin LineWithZ(PXMinus, PYMinus, PXPlus+1,PYPlus+1,GetStartZ); LineWithZ(PXPlus, PYMinus, PXMinus-1,PYPlus+1,GetStartZ); end else begin Line(PXMinus, PYMinus, PXPlus+1,PYPlus+1); Line(PXPlus , PYMinus, PXMinus-1,PYPlus+1); end; end; end; Procedure DrawCross; Begin with ACanvas do begin if Is3D then begin VertLine3D(PX,PYMinus,PYPlus+1,GetStartZ); HorizLine3D(PXMinus,PXPlus+1,PY,GetStartZ); end else begin DoVertLine(PX,PYMinus,PYPlus+1); DoHorizLine(PXMinus,PXPlus+1,PY); end; end; end; var PT : TTrianglePoints; Procedure CalcTriangle3D; begin PT[0]:=ACanvas.Calculate3DPosition(PT[0],GetStartZ); PT[1]:=ACanvas.Calculate3DPosition(PT[1],GetStartZ); PT[2]:=ACanvas.Calculate3DPosition(PT[2],GetStartZ); end; Procedure VertTriangle(DeltaY:Integer); begin if (not Draw3D) or (not Is3D) then begin PT[0]:=TeePoint(PXMinus,PY+DeltaY); PT[1]:=TeePoint(PXPlus,PY+DeltaY); PT[2]:=TeePoint(PX,PY-DeltaY); if Is3D then CalcTriangle3D; end; with ACanvas do if Is3D and Self.Draw3D then Pyramid( True, PXMinus,PY-DeltaY,PXPlus,PY+DeltaY,GetStartZ,GetEndZ,FDark3D) else Polygon(PT); end; var PF : TFourPoints; Procedure DoGradient; var tmpR : TRect; Old, tmpIsTri, tmpIsFour : Boolean; begin tmpR:=TeeRect(PXMinus+Pen.Width,PYMinus+Pen.Width,PXPlus,PYPlus); if not FullGradient then begin Old:=ParentChart.AutoRepaint; ParentChart.AutoRepaint:=False; Gradient.EndColor:=ColorValue; ParentChart.AutoRepaint:=Old; end; if not ParentChart.View3DOptions.Orthogonal then if AStyle=psRectangle then begin Dec(tmpR.Right,Pen.Width); Dec(tmpR.Bottom,Pen.Width); PF:=ACanvas.FourPointsFromRect(tmpR,GetStartZ); Gradient.Draw(ACanvas,PF); exit; end; if Is3D then tmpR:=ACanvas.CalcRect3D(tmpR,GetStartZ); tmpIsFour:=False; tmpIsTri:=False; case AStyle of psRectangle: ACanvas.ClipRectangle(tmpR); psCircle : ACanvas.ClipEllipse(tmpR); psDiamond : tmpIsFour:=True; psLeftTriangle, psRightTriangle: tmpIsTri:=True; psTriangle, psDownTriangle: begin if Draw3D then exit; tmpIsTri:=True; end; else exit; end; if tmpIsFour then Gradient.Draw(ACanvas,PF) else if tmpIsTri then begin ACanvas.ClipPolygon(PT,3); Gradient.Draw(ACanvas,RectFromPolygon(PT,3)); end else Gradient.Draw(ACanvas,tmpR); ACanvas.UnClipRectangle; end; Procedure HorizTriangle(Left,Right:Integer); begin PT[0]:=TeePoint(Left,PY); PT[1]:=TeePoint(Right,PYPlus); PT[2]:=TeePoint(Right,PYMinus); if Is3D then CalcTriangle3D; ACanvas.Polygon(PT); end; var tmpBlend : TTeeBlend; tmpR : TRect; begin PXMinus:=PX-tmpHoriz; PXPlus :=PX+tmpHoriz; PYMinus:=PY-tmpVert; PYPlus :=PY+tmpVert; if Transparency>0 then // 6.02 begin tmpR:=TeeRect(PXMinus,PYMinus,PXPlus+1,PYPlus+1); if (AStyle=psRectangle) and Is3D and Self.Draw3D and ACanvas.View3DOptions.Orthogonal then begin Inc(tmpR.Right,GetEndZ-GetStartZ); Dec(tmpR.Top,GetEndZ-GetStartZ); end; tmpBlend:=ACanvas.BeginBlending(ACanvas.RectFromRectZ(tmpR,GetStartZ),Transparency) end else tmpBlend:=nil; with ACanvas do case AStyle of psRectangle: if Is3D then if Self.FDraw3D then Cube(PXMinus,PXPlus,PYMinus,PYPlus,GetStartZ,GetEndZ,FDark3D) else RectangleWithZ(TeeRect(PXMinus,PYMinus,PXPlus+1,PYPlus+1),GetStartZ) else Rectangle(PXMinus,PYMinus,PXPlus+1,PYPlus+1); psCircle: if Is3D then if Self.FDraw3D and SupportsFullRotation then Sphere(PX,PY,GetMiddleZ,tmpHoriz) else EllipseWithZ(PXMinus,PYMinus,PXPlus,PYPlus,GetStartZ) else Ellipse(PXMinus,PYMinus,PXPlus,PYPlus); psTriangle: VertTriangle( tmpVert); psDownTriangle: VertTriangle(-tmpVert); psLeftTriangle: HorizTriangle(PXMinus,PXPlus); psRightTriangle: HorizTriangle(PXPlus,PXMinus); psCross: DrawCross; psDiagCross: DrawDiagonalCross; psStar: begin DrawCross; DrawDiagonalCross; end; psDiamond: begin PF[0]:=TeePoint(PXMinus,PY); PF[1]:=TeePoint(PX,PYMinus); PF[2]:=TeePoint(PXPlus,PY); PF[3]:=TeePoint(PX,PYPlus); if Is3D then begin PF[0]:=Calculate3DPosition(PF[0],GetStartZ); PF[1]:=Calculate3DPosition(PF[1],GetStartZ); PF[2]:=Calculate3DPosition(PF[2],GetStartZ); PF[3]:=Calculate3DPosition(PF[3],GetStartZ); end; Polygon(PF); end; psSmallDot: if Is3D then Pixels3D[PX,PY,GetMiddleZ]:=Brush.Color else Pixels[PX,PY]:=Brush.Color; end; if Gradient.Visible then DoGradient; if Transparency>0 then ACanvas.EndBlending(tmpBlend); end; Procedure TSeriesPointer.Draw(P:TPoint); begin Draw(P.X,P.Y,Brush.Color,Style) end; Procedure TSeriesPointer.Draw(X,Y:Integer); begin Draw(X,Y,Brush.Color,Style) end; Procedure TSeriesPointer.Draw(px,py:Integer; ColorValue:TColor; AStyle:TSeriesPointerStyle); Begin DrawPointer(ParentChart.Canvas,ParentChart.View3D,px,py,FHorizSize,FVertSize,ColorValue,AStyle); end; Procedure TSeriesPointer.Assign(Source:TPersistent); begin if Source is TSeriesPointer then With TSeriesPointer(Source) do begin Self.FDark3D :=FDark3D; Self.FDraw3D :=FDraw3D; Self.Gradient :=Gradient; Self.FHorizSize :=FHorizSize; Self.FInflate :=FInflate; Self.FStyle :=FStyle; Self.FTransparency:=FTransparency; Self.FVertSize :=FVertSize; end; inherited; end; procedure TSeriesPointer.SetGradient(const Value: TTeeGradient); begin FGradient.Assign(Value); end; function TSeriesPointer.GetColor: TColor; begin result:=Brush.Color; end; function TSeriesPointer.GetStartZ:Integer; // 6.01 begin if Assigned(FSeries) then result:=FSeries.StartZ else result:=0; end; function TSeriesPointer.GetMiddleZ:Integer; // 6.01 begin if Assigned(FSeries) then result:=FSeries.MiddleZ else result:=0; end; function TSeriesPointer.GetEndZ:Integer; // 6.01 begin if Assigned(FSeries) then result:=FSeries.EndZ else result:=0; end; procedure TSeriesPointer.SetColor(const Value: TColor); begin Brush.Color:=Value; end; procedure TSeriesPointer.SetTransparency(const Value: TTeeTransparency); begin if FTransparency<>Value then begin FTransparency:=Value; Repaint; end; end; { TCallout } Constructor TCallout.Create(AOwner:TChartSeries); begin inherited Create(AOwner); FArrow:=TChartArrowPen.Create(CanvasChanged); FInflate:=True; FullGradient:=True; FStyle:=psRectangle; Visible:=True; FDraw3D:=False; FArrowHeadSize:=8; Color:=clBlack; end; Destructor TCallout.Destroy; begin FArrow.Free; inherited; end; Procedure TCallout.Assign(Source:TPersistent); begin if Source is TCallout then with TCallout(Source) do begin Self.FDistance:=Distance; Self.Arrow:=Arrow; Self.FArrowHead:=FArrowHead; Self.FArrowHeadSize:=FArrowHeadSize; end; inherited; end; procedure TCallout.SetDistance(const Value: Integer); begin if FDistance<>Value then begin FDistance:=Value; Repaint; end; end; procedure TCallout.SetArrow(const Value: TChartArrowPen); begin FArrow.Assign(Value); end; procedure TCallout.Draw(AColor:TColor; AFrom,ATo:TPoint; Z:Integer); Const ArrowColors : Array[Boolean] of TColor=(clBlack,clWhite); var tmpFrom : TPoint; tmpCanvas : TCanvas3D; begin tmpCanvas:=ParentChart.Canvas; if Arrow.Visible then begin tmpCanvas.Brush.Style:=bsClear; Prepare; if TeeCheckMarkArrowColor and ( (Arrow.Color=AColor) or (Arrow.Color=ParentChart.Color) ) then tmpCanvas.AssignVisiblePenColor(Arrow,ArrowColors[ParentChart.Color=clBlack]) else tmpCanvas.AssignVisiblePen(Arrow); case ArrowHead of ahLine : tmpCanvas.Arrow(False,ATo,AFrom,ArrowHeadSize,ArrowHeadSize,Z); ahSolid : tmpCanvas.Arrow(True,ATo,AFrom,ArrowHeadSize,ArrowHeadSize,Z); else if ParentChart.View3D then tmpCanvas.LineWithZ(AFrom,ATo,Z) else tmpCanvas.Line(AFrom,ATo); end; end; if (ArrowHead=ahNone) and Visible then begin Prepare; tmpFrom:=AFrom; if ParentChart.View3D then tmpFrom:=tmpCanvas.Calculate3DPosition(tmpFrom,Z); DrawPointer(tmpCanvas, False, // ParentChart.View3D, // 6.01 // 7.0 tmpFrom.X,tmpFrom.Y, HorizSize,VertSize,Color,Style); end; end; procedure TCallout.SetArrowHead(const Value: TArrowHeadStyle); begin if FArrowHead<>Value then begin FArrowHead:=Value; Repaint; end; end; procedure TCallout.SetArrowHeadSize(const Value: Integer); begin if FArrowHeadSize<>Value then begin FArrowHeadSize:=Value; Repaint; end; end; { TMarksCallout } Constructor TMarksCallout.Create(AOwner: TChartSeries); begin inherited Create(AOwner); FLength:=8; DefaultLength:=8; Visible:=False; FArrow.Color:=clWhite; end; procedure TMarksCallout.Assign(Source: TPersistent); begin if Source is TMarksCallout then With TMarksCallout(Source) do begin Self.FLength:=FLength; end; inherited; end; procedure TMarksCallout.SetLength(const Value: Integer); begin ParentSeries.SetIntegerProperty(FLength,Value) end; procedure TMarksCallout.ApplyArrowLength(APosition:TSeriesMarkPosition); var tmp : Integer; begin tmp:=Length+Distance; With APosition do begin Dec(LeftTop.Y,tmp); Dec(ArrowTo.Y,tmp); Dec(ArrowFrom.Y,Distance); end; end; Function TMarksCallout.IsLengthStored:Boolean; begin result:=Length<>DefaultLength; end; { TAxisGridPen } function TAxisGridPen.IsZStored: Boolean; begin result:=FZ<>IDefaultZ; end; procedure TAxisGridPen.SetCentered(const Value: Boolean); begin if FCentered<>Value then begin FCentered:=Value; Changed; end; end; procedure TAxisGridPen.SetZ(const Value: Double); begin if FZ<>Value then begin FZ:=Value; Changed; end; end; { TAxisItem } procedure TAxisItem.SetText(const Value: String); begin if FText<>Value then begin FText:=Value; Repaint; end; end; procedure TAxisItem.Repaint; begin IAxisItems.IAxis.ParentChart.Invalidate; end; procedure TAxisItem.SetValue(const Value: Double); begin if FValue<>Value then begin FValue:=Value; Repaint; end; end; type TTeeShapeAccess=class(TTeeShape); { TAxisItems } constructor TAxisItems.Create(Axis:TChartAxis); begin inherited Create; IAxis:=Axis; FFormat:=TTeeShape.Create(IAxis.ParentChart); TTeeShapeAccess(FFormat).FDefaultTransparent:=True; FFormat.Transparent:=True; end; Destructor TAxisItems.Destroy; begin FFormat.Free; inherited; end; Function TAxisItems.Add(const Value: Double):TAxisItem; begin result:=TAxisItem.Create(IAxis.ParentChart); result.IAxisItems:=Self; TTeeShapeAccess(result).FDefaultTransparent:=True; result.Transparent:=True; result.FValue:=Value; inherited Add(result); end; Function TAxisItems.Add(const Value: Double; const Text: String):TAxisItem; begin result:=Add(Value); result.FText:=Text; end; procedure TAxisItems.CopyFrom(Source: TAxisItems); var t : Integer; begin Format.Assign(Source.Format); Clear; for t:=0 to Source.Count-1 do with Source[t] do Add(Value,Text); end; procedure TAxisItems.Clear; var t : Integer; begin for t:=0 to Count-1 do Item[t].Free; inherited; IAxis.ParentChart.Invalidate; end; function TAxisItems.Get(Index: Integer): TAxisItem; begin result:=TAxisItem(inherited Items[Index]); end; // Draws the associated series bitmap icon at the specified LeftTop location procedure TeeDrawBitmapEditor(Canvas: TCanvas; Element:TCustomChartElement; Left,Top:Integer); var tmpBitmap : TBitmap; begin tmpBitmap:=TBitmap.Create; try TeeGetBitmapEditor(Element,tmpBitmap); {$IFNDEF CLX} // tmpBitmap.Transparent:=True; {$ENDIF} Canvas.Draw(Left,Top,tmpBitmap); finally tmpBitmap.Free; end; end; { TSeriesGroup } constructor TSeriesGroup.Create(Collection: TCollection); begin inherited; FSeries:=TCustomSeriesList.Create; {$IFDEF CLR} FSeries.FOwner:=TCustomAxisPanel(TOwnedCollectionAccess(Collection).Owner); {$ELSE} FSeries.FOwner:=TCustomAxisPanel(TOwnedCollectionAccess(Collection).GetOwner); {$ENDIF} end; destructor TSeriesGroup.Destroy; begin FSeries.Free; inherited; end; procedure TSeriesGroup.Add(Series:TChartSeries); begin FSeries.Add(Series); end; procedure TSeriesGroup.Hide; begin Active:=gaNo; end; procedure TSeriesGroup.Show; begin Active:=gaYes; end; function TSeriesGroup.GetActive: TSeriesGroupActive; var tmpActive : Integer; t : Integer; begin if FSeries.Count=0 then result:=gaYes else begin tmpActive:=0; for t:=0 to FSeries.Count-1 do if FSeries[t].Active then Inc(tmpActive); if tmpActive=FSeries.Count then result:=gaYes else if tmpActive=0 then result:=gaNo else result:=gaSome; end; end; function TSeriesGroup.IsSeriesStored: Boolean; begin result:=FSeries.Count>0; end; procedure TSeriesGroup.SetActive(const Value: TSeriesGroupActive); var t : Integer; begin if (Value<>gaSome) and (Active<>Value) then for t:=0 to FSeries.Count-1 do if Value=gaYes then FSeries[t].Active:=True else if Value=gaNo then FSeries[t].Active:=False; end; procedure TSeriesGroup.SetSeries(const Value: TCustomSeriesList); {$IFNDEF D6} var t : Integer; {$ENDIF} begin {$IFDEF D6} FSeries.Assign(Value); {$ELSE} FSeries.Clear; for t:=0 to Value.Count-1 do FSeries.Add(Value[t]); {$ENDIF} end; { TSeriesGroups } // Returns first group index than contains Series, or -1 if any. function TSeriesGroups.Contains(Series: TChartSeries): Integer; var t : Integer; begin result:=-1; for t:=0 to Count-1 do if Items[t].Series.IndexOf(Series)<>-1 then begin result:=t; break; end; end; function TSeriesGroups.Get(Index: Integer): TSeriesGroup; begin result:=TSeriesGroup(inherited Items[Index]); end; procedure TSeriesGroups.Put(Index: Integer; const Value: TSeriesGroup); begin inherited Items[Index]:=Value; end; { TSeriesMarksSymbol } constructor TSeriesMarksSymbol.Create(AOwner: TCustomTeePanel); begin inherited; Visible:=False; Transparent:=False; Shadow.Size:=1; {$IFNDEF CLR}TShadowAccess{$ENDIF}(Shadow).DefaultSize:=1; end; function TSeriesMarksSymbol.ShouldDraw: Boolean; begin result:=Visible and (not Transparent); end; initialization {$IFDEF D6} {$IFNDEF CLR} StartClassGroup(TControl); ActivateClassGroup(TControl); GroupDescendentsWith(TCustomChartElement, TControl); GroupDescendentsWith(TTeeFunction, TControl); GroupDescendentsWith(TTeeSeriesSource, TControl); {$ENDIF} {$ENDIF} {$IFDEF TEETRIAL} TeeIsTrial:=True; {$ENDIF} // See TChartAxis XPosValueCheck function... if IsWindowsNT then TeeMaxPixelPos:=$3FFFFFF else TeeMaxPixelPos:=$7FFF; // Register basic classes RegisterClasses([ TChartAxisTitle,TChartAxis,TChartDepthAxis,TSeriesMarks ]); finalization FreeAndNil(FTeeSources); // UnRegister basic classes UnRegisterClasses([ TChartAxisTitle,TChartAxis, TChartDepthAxis,TSeriesMarks ]); // 6.01 end.
(****************************************************************************) (* *) (* REV97.PAS - The Relativity Emag (coded in Borland Pascal 7.0) *) (* *) (* "The Relativity Emag" was originally written by En|{rypt, |MuadDib|. *) (* This source may not be copied, distributed or modified in any shape *) (* or form. Some of the code has been derived from various sources and *) (* units to help us produce a better quality electronic magazine to let *) (* the scene know that we are THE BOSS. *) (* *) (* Program Notes : This program presents "The Relativity Emag" *) (* *) (* ASM/BP70 Coder : xxxxx xxxxxxxxx (MuadDib) - xxxxxx@xxxxxxxxxx.xxx *) (* ------------------------------------------------------------------------ *) (* Older Coder : xxxxx xxxxxxxxx (En|{rypt) - xxxxxx@xxxxxxxxxx.xxx :))) *) (* *) (****************************************************************************) {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - The Heading Specifies The Program Name And Parameters. *) (****************************************************************************) Program The_Relativity_Electronic_Magazine_issue_6; {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Compiler Directives - These Directives Are Not Meant To Be Modified. *) (****************************************************************************) {$M 60320,000,603600} {$S 65535} {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Statements To Be Executed When The Program Runs. *) (****************************************************************************) {-plans for the future in the coding- -------------------------------------- * compression * f1 search in memory (bin) * more command lines * vga inroduction cd player is bugged ... no disk recognize and no drive recog /cd for cd player options.. /music for music options rad or mod.. REMOVE ALL HIDECURSOR !!!!!!!!!!!!!!! NO NEED !!!!!11 REMEMBER DISABLED F1 AND F2 IN SMOOTH.. FIX IT REMEMBER RAD MAX FILESIZE POINTER IS 32K AND SO IS VOC !!!!!!!! REMOVED 3RD ENDING PIC {컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴} (****************************************************************************) (* Reserved Words - Each Identifier Names A Unit Used By The Program. *) (****************************************************************************) uses Crt,Dos,revcom,revcol, revconst,revinit,revmenu,revint,revcfgr,revvoc, revhelp,revpoint,revdos,detectso,revwin, revfnt,revrad,revtech,revgfx,revansi,revdisc,revgif, revdat,revsmth,revhard,revmouse,revgame,arkanoid,revfli; var beta:boolean; score:longint; size:word; Begin {Begins The Best Emag In The Scene} {---------------------------} if memavail<350000 then begin writeln(memavail,' Free Mem,'); writeln('Relativity Emag Needs More : ',350000-memavail,', free mem !'); if (paramstr(1)<>'/M') and (paramstr(1)<>'/m') then halt else begin writeln('Ignored Memory Warning.. the emag could get suck.. so dont balme me !!'); delay(1000); end; end; beta:=false; if not beta then checkbreak:=false; vercheck; checkfordat; ReadGlobalIndex; cc:=1; {menu option} ok:=1;{vocals indicator} {-------------------------------------} if InstallMouse then mouse:=true else mouse:=false; {-------------------------------------} if DetSoundBlaster then begin adlib:=true; { voc:=true;} end else begin adlib:=false; voc:=false; voc_start:=false; end; if not adlib then mustype:=2 else mustype:=1; if adlib then InstallRADTimer; {-------------------------------------} Initcommand; g:=true; hard:=true; adlib:=true; { voc:=true; voc_Start:=true;} vga_:=true; bar:=false; intro:=true; smooth:=1; beta:=false; start:=true; cd:=true; if adlib then rand:=true else rand:=false; {-------------------------------------} randomize; initconfigpointer; InitTag; read_config; DeleteDatFilesInDir; initprinter; RevCommand; initpointers; fontloadpointer(config^.font[config^.curfnt],fontp); initavail; InitradVol; Initcd; if not mouse then config^.notavarr[19]:=config^.notavarr[19]+[11]; if vga_ then begin ExtractFileFromDat(config^.closinggif3); DisplayGIF(config^.closinggif3); DeleteDatFile(config^.closinggif3); Reset80x25VideoScreen; textbackground(black); TextColor(7); end; hidecursor; disclaimercheck; smooth:=1; if hard then HardWareInit; if not beta then begin if intro then begin ExtractFileFromDat('REVFLI.FLI'); AAPlay('REVFLI.FLI',true); deletedatfile('REVFLI.FLI'); end; hidecursor; PhazePre; hidecursor; textbackground(black); chbrght; end; extractpointerfromdat(config^.BMMENUFILE,boomm,size); extractpointerfromdat(config^.hpmenufile,helpm,size); extractpointerfromdat(config^.psmenufile,passM,size); extractpointerfromdat(config^.Secmenufile,subm,size); Extractpointerfromdat(config^.DEFMENUFILE,mainm,size); initmouse; { changecol(lightgreen,lightblue);} StartMainMenuPhase; end.
unit uzeichnerSchrittlaenge; {$mode delphi}{$H+} interface uses Classes, SysUtils, uZeichnerBase; type TZeichnerSchrittlaenge = class(TZeichnerBase) private FIdxZuFarbe: array[1..14,0..2] of Real; procedure aktionSchrittMtLinie(list: TStringList); public constructor Create(zeichenPara: TZeichenParameter); override; destructor Destroy; override; end; implementation uses uMatrizen,dglOpenGL; procedure schritt(l:Real;Spur:BOOLEAN); begin if Spur then begin glMatrixMode(GL_ModelView); UebergangsmatrixObjekt_Kamera_Laden; glColor3f(1,1,1); glLineWidth(0.01); glBegin(GL_LINES); glVertex3f(0,0,0);glVertex3f(0,l,0); glEnd; end; ObjInEigenKOSVerschieben(0,l,0) end; procedure TZeichnerSchrittlaenge.aktionSchrittMtLinie(list: TStringList); var m: Cardinal; colorIdx: Cardinal; begin m := StrToInt(list[0]); if (colorIdx > high(FIdxZuFarbe)) then colorIdx := 0; schritt(1/m,true); end; constructor TZeichnerSchrittlaenge.Create(zeichenPara: TZeichenParameter); begin inherited; FName := 'ZeichnerSchrittlaenge'; FVersandTabelle.AddOrSetData('F',aktionSchrittMtLinie); end; destructor TZeichnerSchrittlaenge.Destroy; begin FreeAndNil(FName); inherited; end; end.
unit nkDBGrid; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, StdCtrls, Forms, Controls, Graphics, Dialogs, rxdbgrid, LCLtype; type { TnkDBGrid } TnkDBGrid = class(TRxDBGrid) private FDisplayField: string; FLookupEdit: TCustomEdit; FOnDblClickEx: TNotifyEvent; FOnKeyDownEx: TKeyEvent; protected procedure FOnKeyDwon(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FOnDblClick(Sender:TObject); public procedure Loaded;override; procedure ResetPosition; published property DisplayField:string read FDisplayField write FDisplayField; property LookupEdit:TCustomEdit read FLookupEdit write FLookupEdit; property OnDblClickEx:TNotifyEvent read FOnDblClickEx write FOnDblClickEx; property OnKeyDownEx:TKeyEvent read FOnKeyDownEx write FOnKeyDownEx; end; procedure Register; implementation uses nxLookupEdit; procedure Register; begin RegisterComponents('Additional',[TnkDBGrid]); end; { TnkDBGrid } procedure TnkDBGrid.FOnKeyDwon(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not Assigned(Self.DataSource) then Exit; if not Assigned(Self.DataSource.DataSet) then Exit; if Key=VK_ESCAPE then begin Self.Visible:=False; end; if key=VK_RETURN then begin if Assigned(FLookupEdit) then begin if Trim(FDisplayField)<>'' then begin if not Self.DataSource.DataSet.FieldByName(FDisplayField).IsNull then begin FLookupEdit.Text:=Self.DataSource.DataSet.FieldByName(FDisplayField).Text; FLookupEdit.SetFocus; end; end; end; Self.Visible:=False; end; if Assigned(FOnKeyDownEx) then FOnKeyDownEx(Sender, Key, Shift); if Assigned(FLookupEdit) then begin if FLookupEdit is TnxLookupEdit then begin if Assigned((FLookupEdit as TnxLookupEdit).OnKeyDownEx) then (FLookupEdit as TnxLookupEdit).OnKeyDownEx(nil,Key,Shift); end; end; end; procedure TnkDBGrid.FOnDblClick(Sender: TObject); var mkey:word; begin if Assigned(FLookupEdit) then begin if Trim(FDisplayField)<>'' then begin if not Self.DataSource.DataSet.FieldByName(FDisplayField).IsNull then begin FLookupEdit.Text:=Self.DataSource.DataSet.FieldByName(FDisplayField).Text; FLookupEdit.SetFocus; end; end; end; Self.Visible:=False; if Assigned(FOnDblClickEx) then FOnDblClickEx(Sender); if Assigned(FLookupEdit) then begin if FLookupEdit is TnxLookupEdit then begin if Assigned((FLookupEdit as TnxLookupEdit).OnKeyDownEx) then begin mkey:=VK_RETURN; (FLookupEdit as TnxLookupEdit).OnKeyDownEx(nil,mkey,[]); end; end; end; end; procedure TnkDBGrid.Loaded; begin inherited Loaded; Self.OnKeyDown:=@FOnKeyDwon; Self.OnDblClick:=@FOnDblClick; end; procedure TnkDBGrid.ResetPosition; begin //计算Grid的位置 if Assigned(FLookupEdit) then begin if FLookupEdit is TnxLookupEdit then begin case (FLookupEdit as TnxLookupEdit).GridPosition of alTop,alLeft: begin self.Top:=FLookupEdit.Top+FLookupEdit.Height; if (FLookupEdit as TnxLookupEdit).GridFromRight then self.Left:=FLookupEdit.Left-(Self.Width-FLookupEdit.Width) else self.Left:=FLookupEdit.Left; end; alBottom,alRight: begin self.Top:=FLookupEdit.Top+FLookupEdit.Height; if (FLookupEdit as TnxLookupEdit).GridFromRight then self.Left:=FLookupEdit.Left-(Self.Width-FLookupEdit.Width) else self.Left:=FLookupEdit.Left; end; end; end; end; end; end.
unit uZeichnerBase; {$mode delphi}{$H+} interface uses Classes, SysUtils, fgl; type TPunkt3D = record x,y,z:Real; end; type TZeichenParameter = record winkel: Real; rekursionsTiefe: Cardinal; startPunkt: TPunkt3D; procedure setzeStartPunkt(x,y,z: Real); function copy : TZeichenParameter; end; type TProc = procedure(list: TStringList) of object; type TVersandTabelle = TFPGMap<char, TProc>; type TZeichnerBase = class protected FName: String; FVersandTabelle: TVersandTabelle; FZeichenParameter: TZeichenParameter; private // Bewegungen procedure aktionSchrittMitLinie(list: TStringList); procedure aktionSchrittOhneLinie(list: TStringList); procedure aktionPlus(list: TStringList); procedure aktionMinus(list: TStringList); procedure aktionUnd(list: TStringList); procedure aktionDach(list: TStringList); procedure aktionFSlash(list: TStringList); procedure aktionBSlash(list: TStringList); procedure aktionPush(list: TStringList); procedure aktionPop(list: TStringList); // setter-funktionen procedure setzeWinkel(const phi: Real); procedure setzeRekursionsTiefe(const tiefe: Cardinal); public constructor Create(zeichenPara: TZeichenParameter); virtual; destructor Destroy; override; // properties //// FZeichenParameter property winkel: Real read FZeichenParameter.winkel write setzeWinkel; property rekursionsTiefe: Cardinal read FZeichenParameter.rekursionsTiefe write setzeRekursionsTiefe; property startPunkt: TPunkt3D read FZeichenParameter.startPunkt; property name: String read FName; // setter-Funktionen (public) procedure setzeStartPunkt(x,y,z: Real); // getter-Funktionen (public) function gibZeichenParameter : TZeichenParameter; procedure zeichneBuchstabe(c: char; list: TStringList); virtual; function copy : TZeichnerBase; end; implementation uses uMatrizen,dglOpenGL,uZeichnerInit; ////////////////////////////////////////////////////////// // TZeichenParameter ////////////////////////////////////////////////////////// procedure TZeichenParameter.setzeStartPunkt(x,y,z: Real); begin startPunkt.x := x; startPunkt.y := y; startPunkt.z := z; end; function TZeichenParameter.copy : TZeichenParameter; var zeichenPara: TZeichenParameter; begin zeichenPara.winkel := winkel; zeichenPara.rekursionsTiefe := rekursionsTiefe; zeichenPara.setzeStartPunkt(startPunkt.x, startPunkt.y, startPunkt.z); result := zeichenPara; end; ////////////////////////////////////////////////////////// // TZeichnerBase ////////////////////////////////////////////////////////// procedure TZeichnerBase.setzeWinkel(const phi: Real); begin FZeichenParameter.winkel := phi; end; procedure TZeichnerBase.setzeRekursionsTiefe(const tiefe: Cardinal); begin FZeichenParameter.rekursionsTiefe := tiefe; end; procedure TZeichnerBase.setzeStartPunkt(x,y,z: Real); begin FZeichenParameter.setzeStartPunkt(x,y,z); end; function TZeichnerBase.gibZeichenParameter : TZeichenParameter; begin result := FZeichenParameter; end; procedure TZeichnerBase.zeichneBuchstabe(c: char; list: TStringList); var tmp: TProc; begin if FVersandTabelle.tryGetData(c,tmp) then tmp(list); end; ////////////////////////////////////////////////////////// // Bewegung der Turtle ////////////////////////////////////////////////////////// //// hilfs proceduren procedure schritt(l:Real;Spur:BOOLEAN); begin if Spur then begin glMatrixMode(GL_ModelView); UebergangsmatrixObjekt_Kamera_Laden; glColor3f(1,1,1); glLineWidth(0.01); glBegin(GL_LINES); glVertex3f(0,0,0);glVertex3f(0,l,0); glEnd; end; ObjInEigenKOSVerschieben(0,l,0) end; procedure X_Rot(a:Real); begin ObjUmEigenKOSDrehen(a,0,0,0,1,0,0); end; procedure Y_Rot(a:Real); begin ObjUmEigenKOSDrehen(a,0,0,0,0,1,0) end; procedure Z_Rot(a:Real); begin ObjUmEigenKOSDrehen(a,0,0,0,0,0,1) end; //// feste Aktionen der Versandtabelle procedure TZeichnerBase.aktionSchrittMitLinie(list: TStringList); var m: Cardinal; begin m := 50; schritt(1/m,true); end; procedure TZeichnerBase.aktionSchrittOhneLinie(list: TStringList); var m: Cardinal; begin m := 50; schritt(1/m,false); end; procedure TZeichnerBase.aktionPlus(list: TStringList); begin Z_Rot(FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionMinus(list: TStringList); begin Z_Rot(-FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionUnd(list: TStringList); begin Y_Rot(FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionDach(list: TStringList); begin Y_Rot(-FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionFSlash(list: TStringList); begin X_Rot(FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionBSlash(list: TStringList); begin X_Rot(-FZeichenParameter.winkel); end; procedure TZeichnerBase.aktionPush(list: TStringList); begin glMatrixMode(GL_MODELVIEW_MATRIX); glLoadMatrixf(@OMatrix.o); glPushMatrix; end; procedure TZeichnerBase.aktionPop(list: TStringList); begin glMatrixMode(GL_MODELVIEW_MATRIX); glPopMatrix; glGetFloatv(GL_MODELVIEW_MATRIX,@OMatrix.o); end; function TZeichnerBase.copy : TZeichnerBase; var zeichnerInit: TZeichnerInit; begin zeichnerInit := TZeichnerInit.Create; result := zeichnerinit.initialisiere(FName, FZeichenParameter.copy); end; constructor TZeichnerBase.Create(zeichenPara: TZeichenParameter); begin FName := 'ZeichnerBase'; FZeichenParameter := zeichenPara; FVersandTabelle := TVersandTabelle.Create; FVersandTabelle.add('F',aktionSchrittMitLinie); FVersandTabelle.add('f',aktionSchrittOhneLinie); FVersandTabelle.add('+',aktionPlus); FVersandTabelle.add('-',aktionMinus); FVersandTabelle.add('&',aktionUnd); FVersandTabelle.add('^',aktionDach); FVersandTabelle.add('/',aktionFSlash); FVersandTabelle.add('\',aktionBSlash); FVersandTabelle.add('[',aktionPush); FVersandTabelle.add(']',aktionPop); end; destructor TZeichnerBase.Destroy; begin FreeAndNil(FName); FreeAndNil(FZeichenParameter); FreeAndNil(FVersandTabelle) end; end.
{$mode objfpc}{$H+}{$J-} {$R+} // включена проверка на диапазона - подходящо за дебъг var MyArray: array [0..9] of Integer; I: Integer; begin // инизиализация for I := 0 to 9 do MyArray[I] := I * I; // показване for I := 0 to 9 do WriteLn('Квадрата е ', MyArray[I]); // прави същото като горното for I := Low(MyArray) to High(MyArray) do WriteLn('Квадрата е ', MyArray[I]); // прави същото като горното I := 0; while I < 10 do begin WriteLn('Квадрата е ', MyArray[I]); I := I + 1; // или "I += 1", или "Inc(I)" end; // прави същото като горното I := 0; repeat WriteLn('Квадрата е ', MyArray[I]); Inc(I); until I = 10; // прави същото като горното // забележка: тук се изброяват стойностите на MyArray, а не индексите for I in MyArray do WriteLn('Квадрата е ', I); end.
unit Borer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Buttons, DB, ExtCtrls; type TBorerTypeForm = class(TForm) btn_edit: TBitBtn; btn_ok: TBitBtn; btn_add: TBitBtn; btn_delete: TBitBtn; btn_cancel: TBitBtn; gb1: TGroupBox; lblBorer_name: TLabel; edtBorer_name: TEdit; gb2: TGroupBox; sgBorer: TStringGrid; procedure btn_editClick(Sender: TObject); procedure btn_okClick(Sender: TObject); procedure btn_addClick(Sender: TObject); procedure btn_deleteClick(Sender: TObject); procedure edtBorer_nameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure sgBorerSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_cancelClick(Sender: TObject); private { Private declarations } procedure button_status(int_status:integer;bHaveRecord:boolean); procedure Get_oneRecord(aRow:Integer); function GetInsertSQL:string; function GetUpdateSQL:string; function GetDeleteSQL:string; function Check_Data:boolean; function GetExistedSQL(aBorerName: string):string; public { Public declarations } end; var BorerTypeForm: TBorerTypeForm; m_sgBorerSelectedRow: integer; m_DataSetState: TDataSetState; implementation uses MainDM, public_unit; {$R *.dfm} { TBorerTypeForm } procedure TBorerTypeForm.button_status(int_status: integer; bHaveRecord: boolean); begin case int_status of 1: //浏览状态 begin btn_edit.Enabled :=bHaveRecord; btn_delete.Enabled :=bHaveRecord; btn_edit.Caption :='修改'; btn_ok.Enabled :=false; btn_add.Enabled :=true; Enable_Components(self,false); m_DataSetState := dsBrowse; end; 2: //修改状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsEdit; end; 3: //增加状态 begin btn_edit.Enabled :=true; btn_edit.Caption :='放弃'; btn_ok.Enabled :=true; btn_add.Enabled :=false; btn_delete.Enabled :=false; Enable_Components(self,true); m_DataSetState := dsInsert; end; end; end; function TBorerTypeForm.Check_Data: boolean; begin if trim(edtBorer_name.Text) = '' then begin messagebox(self.Handle,'请输入类别名称!','数据校对',mb_ok); edtBorer_name.SetFocus; result := false; exit; end; result := true; end; procedure TBorerTypeForm.Get_oneRecord(aRow: Integer); begin edtBorer_name.Text := sgBorer.Cells[2,aRow]; end; function TBorerTypeForm.GetDeleteSQL: string; begin result :='DELETE FROM borer WHERE borer_no='+ ''''+sgBorer.Cells[1,sgBorer.row]+''''; end; function TBorerTypeForm.GetExistedSQL(aBorerName: string): string; begin Result:='SELECT borer_no,borer_name FROM borer WHERE borer_name='+ ''''+aBorerName+''''; end; function TBorerTypeForm.GetInsertSQL: string; begin result := 'INSERT INTO Borer (Borer_name) VALUES(' +''''+trim(edtBorer_name.Text)+''''+')'; end; function TBorerTypeForm.GetUpdateSQL: string; var strSQLWhere,strSQLSet:string; begin strSQLWhere:=' WHERE Borer_no='+''''+sgBorer.Cells[1,sgBorer.Row]+''''; strSQLSet:='UPDATE drill_type SET '; strSQLSet := strSQLSet + 'borer_name' +'='+''''+trim(edtBorer_name.Text)+''''; result := strSQLSet + strSQLWhere; end; procedure TBorerTypeForm.btn_editClick(Sender: TObject); begin if btn_edit.Caption ='修改' then begin Button_status(2,true); edtBorer_name.SetFocus; end else begin clear_data(self); Button_status(1,true); self.Get_oneRecord(sgBorer.Row); end; end; procedure TBorerTypeForm.btn_okClick(Sender: TObject); var strSQL: string; begin if not Check_Data then exit; strSQL := self.GetExistedSQL(trim(edtBorer_name.Text)); if isExistedRecord(MainDataModule.qryBorer,strSQL) then exit; if m_DataSetState = dsInsert then begin strSQL := self.GetInsertSQL; if Insert_oneRecord(MainDataModule.qryBorer,strSQL) then begin if (sgBorer.RowCount =2) and (sgBorer.Cells[1,1] ='') then begin m_sgBorerSelectedRow:= sgBorer.RowCount-1; sgBorer.Cells[1,sgBorer.RowCount-1] := '1'; end else begin m_sgBorerSelectedRow := sgBorer.RowCount; sgBorer.RowCount := sgBorer.RowCount+1; sgBorer.Cells[1,sgBorer.RowCount-1] := inttostr(strtoint(sgBorer.Cells[1,sgBorer.RowCount-2])+1); end; sgBorer.Cells[2,sgBorer.RowCount-1] := trim(edtBorer_name.Text); sgBorer.Row := sgBorer.RowCount-1; Button_status(1,true); btn_add.SetFocus; end; end else if m_DataSetState = dsEdit then begin strSQL := self.GetUpdateSQL; if Update_oneRecord(MainDataModule.qryBorer,strSQL) then begin sgBorer.Cells[2,sgBorer.Row] := edtBorer_name.Text ; Button_status(1,true); btn_add.SetFocus; end; end; end; procedure TBorerTypeForm.btn_addClick(Sender: TObject); begin Clear_Data(self); Button_status(3,true); edtBorer_name.SetFocus; end; procedure TBorerTypeForm.btn_deleteClick(Sender: TObject); var strSQL: string; begin if MessageBox(self.Handle, '您确定要删除吗?','警告', MB_YESNO+MB_ICONQUESTION)=IDNO then exit; if edtBorer_name.Text <> '' then begin strSQL := self.GetDeleteSQL; if Delete_oneRecord(MainDataModule.qryBorer,strSQL) then begin Clear_Data(self); DeleteStringGridRow(sgBorer,sgBorer.Row); if sgBorer.Cells[1,sgBorer.row]='' then button_status(1,false) else begin self.Get_oneRecord(sgBorer.Row); button_status(1,true); end end; end; end; procedure TBorerTypeForm.edtBorer_nameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin change_focus(key,self); end; procedure TBorerTypeForm.sgBorerSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if (ARow <>0) and (ARow<>m_sgBorerSelectedRow) then if sgBorer.Cells[1,ARow]<>'' then begin Get_oneRecord(aRow); if sgBorer.Cells[1,ARow]='' then Button_status(1,false) else Button_status(1,true); end else clear_data(self); m_sgBorerSelectedRow:=ARow; end; procedure TBorerTypeForm.FormCreate(Sender: TObject); var i: integer; begin self.Left := trunc((screen.Width -self.Width)/2); self.Top := trunc((Screen.Height - self.Height)/2); sgBorer.RowHeights[0] := 16; sgBorer.Cells[1,0] := '类别代码'; sgBorer.Cells[2,0] := '类别名称'; sgBorer.ColWidths[0]:=10; sgBorer.ColWidths[1]:=80; sgBorer.ColWidths[2]:=125; m_sgBorerSelectedRow:= -1; Clear_Data(self); with MainDataModule.qryBorer do begin close; sql.Clear; sql.Add('Select borer_no,borer_name FROM borer'); open; i:=0; while not Eof do begin i:=i+1; sgBorer.RowCount := i +1; sgBorer.Cells[1,i] := FieldByName('borer_no').AsString; sgBorer.Cells[2,i] := FieldByName('borer_name').AsString; Next ; end; close; end; if i>0 then begin sgBorer.Row :=1; m_sgBorerSelectedRow :=1; Get_oneRecord(1); button_status(1,true); end else button_status(1,false); end; procedure TBorerTypeForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:= caFree; end; procedure TBorerTypeForm.btn_cancelClick(Sender: TObject); begin self.Close; end; end.
{ ****************************************************************************** } { * path Pass struct create 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 zNavigationPass; {$INCLUDE zDefine.inc} interface uses SysUtils, CoreClasses, Math, Geometry2DUnit, zNavigationPoly, MovementEngine; type TPolyPassManager = class; TBasePass = class; TNavBio = class; TNavBioManager = class; TPassState = record Owner: TBasePass; passed: TBasePass; State: ShortInt; function Enabled: Boolean; overload; function Enabled(ignore: TCoreClassListForObj): Boolean; overload; end; PPassState = ^TPassState; TBasePass = class(TCoreClassPersistent) private FDataList: TCoreClassList; FOwner: TPolyPassManager; FPassIndex: Integer; function GetData(index: Integer): PPassState; function GetState(index: Integer): ShortInt; procedure SetState(index: Integer; const Value: ShortInt); public constructor Create(AOwner: TPolyPassManager); destructor Destroy; override; procedure ClearPass; procedure Add(APass: TBasePass); procedure Delete; overload; procedure Delete(idx: Integer); overload; procedure Delete(APass: TBasePass); overload; function Count: Integer; function Exists(APass: TBasePass): Boolean; function IndexOf(APass: TBasePass): Integer; procedure BuildPass(AExpandDist: TGeoFloat); virtual; abstract; function pass(APass: TBasePass): Boolean; virtual; abstract; function GetPosition: TVec2; virtual; abstract; property Position: TVec2 read GetPosition; property State[index: Integer]: ShortInt read GetState write SetState; property Data[index: Integer]: PPassState read GetData; default; property PassIndex: Integer read FPassIndex write FPassIndex; property Owner: TPolyPassManager read FOwner; end; TPointPass = class(TBasePass) private FPoint: TVec2; public constructor Create(AOwner: TPolyPassManager; APoint: TVec2); procedure BuildPass(AExpandDist: TGeoFloat); override; function pass(APass: TBasePass): Boolean; override; function GetPosition: TVec2; override; end; TPolyPass = class(TBasePass) private FPoly: TPolyManagerChildren; FPolyIndex: Integer; FExtandDistance: TGeoFloat; FCachePoint: TVec2; public constructor Create(AOwner: TPolyPassManager; APoly: TPolyManagerChildren; APolyIndex: Integer; AExpandDist: TGeoFloat); procedure BuildPass(AExpandDist: TGeoFloat); override; function pass(APass: TBasePass): Boolean; override; function GetPosition: TVec2; override; end; TNavigationBioPass = class(TBasePass) private FNavBio: TNavBio; FNavBioIndex: Integer; FExtandDistance: TGeoFloat; FFastEdgePass: Boolean; FNeedUpdate: Boolean; public constructor Create(AOwner: TPolyPassManager; ANavBio: TNavBio; ANavBioIndex: Integer; AExpandDist: TGeoFloat; AFastEdgePass: Boolean); destructor Destroy; override; procedure BuildPass(AExpandDist: TGeoFloat); override; function pass(APass: TBasePass): Boolean; override; function GetPosition: TVec2; override; end; TPolyPassManager = class(TCoreClassPersistent) private type TCacheState = (csNoCompute, csYes, csNo); TIntersectCache = array of array of array of array of TCacheState; TPointInCache = array of array of TCacheState; private FPolyManager: TPolyManager; FNavBioManager: TNavBioManager; FPassList: TCoreClassListForObj; FExtandDistance: TGeoFloat; FPassStateIncremental: ShortInt; private FIntersectCache: TIntersectCache; FPointInCache: TPointInCache; protected function GetPass(index: Integer): TBasePass; public constructor Create(APolyManager: TPolyManager; ANavBioManager: TNavBioManager; AExpandDistance: TGeoFloat); destructor Destroy; override; function PointOk(AExpandDist: TGeoFloat; pt: TVec2): Boolean; overload; // include dynamic poly,ignore object function PointOk(AExpandDist: TGeoFloat; pt: TVec2; ignore: TCoreClassListForObj): Boolean; overload; function LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2): Boolean; overload; // include dynamic poly,ignore object function LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2; ignore: TCoreClassListForObj): Boolean; overload; function PointOkCache(AExpandDist: TGeoFloat; poly1: TPolyManagerChildren; idx1: Integer): Boolean; function LineIntersectCache(AExpandDist: TGeoFloat; poly1: TPolyManagerChildren; idx1: Integer; poly2: TPolyManagerChildren; idx2: Integer): Boolean; function ExistsNavBio(NavBio: TNavBio): Boolean; procedure AddNavBio(NavBio: TNavBio); // fast add navBio can auto build Pass for self procedure AddFastNavBio(NavBio: TNavBio); procedure DeleteNavBio(NavBio: TNavBio); procedure BuildNavBioPass; procedure BuildPass; procedure Rebuild; property ExtandDistance: TGeoFloat read FExtandDistance; function NewPassStateIncremental: ShortInt; function Add(AConn: TBasePass; const NowBuildPass: Boolean): Integer; procedure Delete(idx: Integer); overload; procedure Delete(AConn: TBasePass); overload; procedure Clear; function Count: Integer; function IndexOf(b: TBasePass): Integer; property pass[index: Integer]: TBasePass read GetPass; default; function TotalPassNodeCount: Integer; property PolyManager: TPolyManager read FPolyManager; property NavBioManager: TNavBioManager read FNavBioManager; end; TNavState = (nsStop, nsRun, nsPause, nsStatic); TPhysicsPropertys = set of (npNoBounce, npIgnoreCollision, npFlight); TChangeSource = (csBounce, csRun, csGroupRun, csInit, csExternal); TLastState = (lsDetectPoint, lsDirectLerpTo, lsProcessBounce, lsIgnore); TNavBioProcessState = record private FLastState: TLastState; procedure SetLastState(const Value: TLastState); public Owner: TNavBio; LerpTo: TVec2; LerpSpeed: TGeoFloat; Timer: Double; PositionChanged: Boolean; ChangeSource: TChangeSource; LastProcessed: Boolean; LastStateBounceWaitTime: Double; property LastState: TLastState read FLastState write SetLastState; procedure Init(AOwner: TNavBio); procedure ReleaseSelf; end; PNavBioProcessState = ^TNavBioProcessState; INavBioNotifyInterface = interface procedure DoRollAngleStart(Sender: TNavBio); procedure DoMovementStart(Sender: TNavBio; ToPosition: TVec2); procedure DoMovementOver(Sender: TNavBio); procedure DoMovementProcess(deltaTime: Double); end; TNavBio = class(TCoreClassInterfacedObject, IMovementEngineIntf) private FOwner: TNavBioManager; FPassManager: TPolyPassManager; // in Pass manager FEdgePassList: TCoreClassListForObj; FPosition: TVec2; FRollAngle: TGeoFloat; FRadius: TGeoFloat; FMovement: TMovementEngine; FMovementPath: TVec2List; FState: TNavState; FPhysicsPropertys: TPhysicsPropertys; FInternalStates: TNavBioProcessState; FNotifyIntf: INavBioNotifyInterface; protected // MovementEngine interface function GetPosition: TVec2; procedure SetPosition(const Value: TVec2); function GetRollAngle: TGeoFloat; procedure SetRollAngle(const Value: TGeoFloat); procedure DoStartMovement; procedure DoMovementDone; procedure DoRollMovementStart; procedure DoRollMovementOver; procedure DoLoop; procedure DoStop; procedure DoPause; procedure DoContinue; procedure DoMovementStepChange(OldStep, NewStep: TMovementStep); protected // return True so now execute smooth lerpto function SmoothBouncePosition(const OldPos: TVec2; var NewPos, NewLerpPos: TVec2): Boolean; procedure SetDirectPosition(const Value: TVec2); procedure SetState(const Value: TNavState); procedure SetPhysicsPropertys(const Value: TPhysicsPropertys); function GetSlices: Integer; protected FCollisionList: TCoreClassListForObj; procedure LinkCollision(p: TNavBio; const Associated: Boolean); procedure UnLinkCollision(p: TNavBio; const Associated: Boolean); public constructor Create(AOwner: TNavBioManager; APassManager: TPolyPassManager); destructor Destroy; override; procedure DirectionTo(ToPosition: TVec2); function MovementTo(ToPosition: TVec2): Boolean; procedure stop; procedure Hold; function GetBouncePosition(const OldPos: TVec2; var NewPos: TVec2): Boolean; procedure ProcessBounce(p1: TNavBio; deltaTime: Double); procedure Progress(deltaTime: Double); function IsPause: Boolean; function IsStop: Boolean; function IsStatic: Boolean; function IsRun: Boolean; function IsFlight: Boolean; property IsActived: Boolean read FInternalStates.PositionChanged; function CanBounce: Boolean; function CanCollision: Boolean; procedure Collision(Trigger: TNavBio); virtual; procedure UnCollision(Trigger: TNavBio); virtual; property Owner: TNavBioManager read FOwner; property PassManager: TPolyPassManager read FPassManager; property State: TNavState read FState write SetState; property DirectState: TNavState read FState write FState; property PhysicsPropertys: TPhysicsPropertys read FPhysicsPropertys write SetPhysicsPropertys; property Position: TVec2 read GetPosition write SetPosition; property DirectPosition: TVec2 read GetPosition write SetDirectPosition; property RollAngle: TGeoFloat read GetRollAngle write SetRollAngle; property radius: TGeoFloat read FRadius write FRadius; property Slices: Integer read GetSlices; property MovementPath: TVec2List read FMovementPath; property Movement: TMovementEngine read FMovement; property NotifyIntf: INavBioNotifyInterface read FNotifyIntf write FNotifyIntf; property CollisionList: TCoreClassListForObj read FCollisionList; function ExistsCollision(v: TNavBio): Boolean; property PositionChanged: Boolean read FInternalStates.PositionChanged write FInternalStates.PositionChanged; // TNavigationBioPass of list property EdgePassList: TCoreClassListForObj read FEdgePassList; end; TNavBioNotify = procedure(Sender: TNavBio) of object; TNavBioManager = class(TCoreClassPersistent) private FNavBioList: TCoreClassListForObj; FBounceWaitTime: Double; FSlices: Integer; FSmooth: Boolean; FIgnoreAllCollision: Boolean; FOnRebuildNavBioPass: TNavBioNotify; private function GetItems(index: Integer): TNavBio; public constructor Create; destructor Destroy; override; function Add(PassManager: TPolyPassManager; pt: TVec2; angle: TGeoFloat): TNavBio; procedure Clear; function Count: Integer; function ActivtedCount: Integer; property Items[index: Integer]: TNavBio read GetItems; default; function PointOk(AExpandDist: TGeoFloat; pt: TVec2; ignore: TCoreClassListForObj): Boolean; overload; function PointOk(AExpandDist: TGeoFloat; pt: TVec2): Boolean; overload; function LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2; ignore: TCoreClassListForObj): Boolean; overload; function LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2): Boolean; overload; function DetectCollision(p1, p2: TNavBio): Boolean; procedure Progress(deltaTime: Double); property OnRebuildNavBioPass: TNavBioNotify read FOnRebuildNavBioPass write FOnRebuildNavBioPass; property BounceWaitTime: Double read FBounceWaitTime write FBounceWaitTime; property Smooth: Boolean read FSmooth write FSmooth; // slices default are 5 property Slices: Integer read FSlices write FSlices; property IgnoreAllCollision: Boolean read FIgnoreAllCollision write FIgnoreAllCollision; end; implementation uses zNavigationPathFinding, Geometry3DUnit; function TPassState.Enabled: Boolean; begin Result := not Owner.FOwner.FNavBioManager.LineIntersect(Owner.FOwner.ExtandDistance, Owner.Position, passed.Position); end; function TPassState.Enabled(ignore: TCoreClassListForObj): Boolean; begin Result := not Owner.FOwner.FNavBioManager.LineIntersect(Owner.FOwner.ExtandDistance, Owner.Position, passed.Position, ignore); end; function TBasePass.GetData(index: Integer): PPassState; begin Result := FDataList[index]; end; function TBasePass.GetState(index: Integer): ShortInt; begin Result := PPassState(FDataList[index])^.State; end; procedure TBasePass.SetState(index: Integer; const Value: ShortInt); var i: Integer; p1, p2: PPassState; begin p1 := FDataList[index]; p1^.State := Value; for i := 0 to p1^.passed.FDataList.Count - 1 do begin p2 := p1^.passed.FDataList[i]; if p2^.passed = Self then begin p2^.State := Value; Break; end; end; end; constructor TBasePass.Create(AOwner: TPolyPassManager); begin inherited Create; FDataList := TCoreClassList.Create; FOwner := AOwner; FPassIndex := -1; end; destructor TBasePass.Destroy; begin ClearPass; DisposeObject(FDataList); inherited; end; procedure TBasePass.ClearPass; begin while FDataList.Count > 0 do Delete(FDataList.Count - 1); end; procedure TBasePass.Add(APass: TBasePass); var p1, p2: PPassState; begin // add to self list new(p1); p1^.Owner := Self; p1^.passed := APass; p1^.State := 0; FDataList.Add(p1); // add to dest conect list new(p2); p2^.Owner := APass; p2^.passed := Self; p2^.State := 0; APass.FDataList.Add(p2); end; procedure TBasePass.Delete; begin if FOwner <> nil then FOwner.Delete(Self); end; procedure TBasePass.Delete(idx: Integer); var p1, p2: PPassState; i: Integer; begin p1 := FDataList[idx]; i := 0; while i < p1^.passed.FDataList.Count do begin p2 := p1^.passed.FDataList[i]; if p2^.passed = Self then begin p1^.passed.FDataList.Delete(i); Dispose(p2); end else inc(i); end; Dispose(p1); FDataList.Delete(idx); end; procedure TBasePass.Delete(APass: TBasePass); var i: Integer; begin i := 0; while i < FDataList.Count do if PPassState(FDataList[i])^.passed = APass then Delete(i) else inc(i); end; function TBasePass.Count: Integer; begin Result := FDataList.Count; end; function TBasePass.Exists(APass: TBasePass): Boolean; var i: Integer; begin Result := True; for i := Count - 1 downto 0 do if (Data[i]^.passed = APass) then Exit; Result := False; end; function TBasePass.IndexOf(APass: TBasePass): Integer; var i: Integer; begin Result := -1; for i := Count - 1 downto 0 do if (Data[i]^.passed = APass) then begin Result := i; Break; end; end; constructor TPointPass.Create(AOwner: TPolyPassManager; APoint: TVec2); begin inherited Create(AOwner); FPoint := APoint; end; procedure TPointPass.BuildPass(AExpandDist: TGeoFloat); var i: Integer; b: TBasePass; pt: TVec2; begin ClearPass; pt := GetPosition; for i := 0 to FOwner.Count - 1 do begin b := FOwner.pass[i]; if (b <> Self) and (pass(b)) and (not Exists(b)) and (not FOwner.FPolyManager.LineIntersect(AExpandDist, pt, b.GetPosition)) then Add(b); end; end; function TPointPass.pass(APass: TBasePass): Boolean; begin Result := True; end; function TPointPass.GetPosition: TVec2; begin Result := FPoint; end; constructor TPolyPass.Create(AOwner: TPolyPassManager; APoly: TPolyManagerChildren; APolyIndex: Integer; AExpandDist: TGeoFloat); begin inherited Create(AOwner); FPoly := APoly; FPolyIndex := APolyIndex; FExtandDistance := AExpandDist; FCachePoint := FPoly.Expands[FPolyIndex, FExtandDistance]; end; procedure TPolyPass.BuildPass(AExpandDist: TGeoFloat); var pt: TVec2; i: Integer; b: TBasePass; p: TPolyPass; begin ClearPass; pt := GetPosition; for i := 0 to FOwner.Count - 1 do begin b := FOwner.pass[i]; if b is TPolyPass then begin p := TPolyPass(b); if (p <> Self) and (pass(p)) and (not Exists(p)) and (not FOwner.LineIntersectCache(AExpandDist, FPoly, FPolyIndex, p.FPoly, p.FPolyIndex)) then Add(p); end else begin if (b <> Self) and (pass(b)) and (not Exists(b)) and (not FOwner.LineIntersect(AExpandDist, pt, b.GetPosition)) then Add(b); end; end; end; function TPolyPass.pass(APass: TBasePass): Boolean; begin Result := True; end; function TPolyPass.GetPosition: TVec2; begin Result := FCachePoint; end; constructor TNavigationBioPass.Create(AOwner: TPolyPassManager; ANavBio: TNavBio; ANavBioIndex: Integer; AExpandDist: TGeoFloat; AFastEdgePass: Boolean); begin inherited Create(AOwner); FNavBio := ANavBio; FNavBioIndex := ANavBioIndex; FExtandDistance := AExpandDist; FFastEdgePass := AFastEdgePass; FNeedUpdate := True; FNavBio.EdgePassList.Add(Self); end; destructor TNavigationBioPass.Destroy; var i: Integer; begin i := 0; while i < FNavBio.EdgePassList.Count do begin if FNavBio.EdgePassList[i] = Self then FNavBio.EdgePassList.Delete(i) else inc(i); end; inherited Destroy; end; procedure TNavigationBioPass.BuildPass(AExpandDist: TGeoFloat); var pt: TVec2; i: Integer; b: TBasePass; begin ClearPass; if FFastEdgePass then begin pt := GetPosition; for i := 0 to FOwner.Count - 1 do begin b := FOwner.pass[i]; if (b = Self) and (pass(b)) and (not Exists(b)) and (not FOwner.FNavBioManager.LineIntersect(AExpandDist - 1, pt, b.GetPosition)) then Add(b); end; end else begin pt := GetPosition; for i := 0 to FOwner.Count - 1 do begin b := FOwner.pass[i]; if (b <> Self) and (pass(b)) and (not Exists(b)) and (not FOwner.LineIntersect(AExpandDist, pt, b.GetPosition)) and (not FOwner.FNavBioManager.LineIntersect(AExpandDist - 1, pt, b.GetPosition)) then Add(b); end; end; FNeedUpdate := False; end; function TNavigationBioPass.pass(APass: TBasePass): Boolean; begin Result := True; end; function TNavigationBioPass.GetPosition: TVec2; var r: TGeoFloat; begin r := (FNavBio.radius + FExtandDistance) / Sin((180 - 360 / FNavBio.Slices) * 0.5 / 180 * pi); Result := PointRotation(FNavBio.DirectPosition, r, 360 / FNavBio.Slices * FNavBioIndex); end; function TPolyPassManager.GetPass(index: Integer): TBasePass; begin Result := TBasePass(FPassList[index]); end; constructor TPolyPassManager.Create(APolyManager: TPolyManager; ANavBioManager: TNavBioManager; AExpandDistance: TGeoFloat); begin inherited Create; FPolyManager := APolyManager; FNavBioManager := ANavBioManager; FPassList := TCoreClassListForObj.Create; FExtandDistance := AExpandDistance; FPassStateIncremental := 0; end; destructor TPolyPassManager.Destroy; begin Clear; DisposeObject(FPassList); inherited; end; function TPolyPassManager.PointOk(AExpandDist: TGeoFloat; pt: TVec2): Boolean; begin Result := FPolyManager.PointOk(AExpandDist, pt); end; function TPolyPassManager.PointOk(AExpandDist: TGeoFloat; pt: TVec2; ignore: TCoreClassListForObj): Boolean; begin Result := PointOk(AExpandDist, pt); if Result then Result := FNavBioManager.PointOk(AExpandDist, pt, ignore); end; function TPolyPassManager.LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2): Boolean; begin Result := FPolyManager.LineIntersect(AExpandDist, lb, le); end; function TPolyPassManager.LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2; ignore: TCoreClassListForObj): Boolean; begin Result := LineIntersect(AExpandDist, lb, le); if not Result then Result := FNavBioManager.LineIntersect(AExpandDist, lb, le, ignore); end; function TPolyPassManager.PointOkCache(AExpandDist: TGeoFloat; poly1: TPolyManagerChildren; idx1: Integer): Boolean; begin if FPointInCache[poly1.index][idx1] = csNoCompute then begin Result := PointOk(AExpandDist - 1, poly1.Expands[idx1, AExpandDist + 1]); if Result then FPointInCache[poly1.index][idx1] := csYes else FPointInCache[poly1.index][idx1] := csNo; end else begin Result := (FPointInCache[poly1.index][idx1] = csYes); end; end; function TPolyPassManager.LineIntersectCache(AExpandDist: TGeoFloat; poly1: TPolyManagerChildren; idx1: Integer; poly2: TPolyManagerChildren; idx2: Integer): Boolean; begin if FIntersectCache[poly1.index][idx1][poly2.index][idx2] = csNoCompute then begin Result := LineIntersect(AExpandDist, poly1.Expands[idx1, AExpandDist + 1], poly2.Expands[idx2, AExpandDist + 1]); if Result then begin FIntersectCache[poly1.index][idx1][poly2.index][idx2] := csYes; FIntersectCache[poly2.index][idx2][poly1.index][idx1] := csYes; end else begin FIntersectCache[poly1.index][idx1][poly2.index][idx2] := csNo; FIntersectCache[poly2.index][idx2][poly1.index][idx1] := csNo; end; end else begin Result := (FIntersectCache[poly1.index][idx1][poly2.index][idx2] = csYes); end; end; function TPolyPassManager.ExistsNavBio(NavBio: TNavBio): Boolean; var i: Integer; begin Result := True; for i := 0 to Count - 1 do if (pass[i] is TNavigationBioPass) and (TNavigationBioPass(pass[i]).FNavBio = NavBio) then Exit; Result := False; end; procedure TPolyPassManager.AddNavBio(NavBio: TNavBio); var i: Integer; d: TNavigationBioPass; begin if ExistsNavBio(NavBio) then Exit; DeleteNavBio(NavBio); for i := 0 to NavBio.Slices - 1 do begin d := TNavigationBioPass.Create(Self, NavBio, i, FExtandDistance + 1, False); FPassList.Add(d); end; end; procedure TPolyPassManager.AddFastNavBio(NavBio: TNavBio); var i: Integer; d: TNavigationBioPass; List: TCoreClassListForObj; begin DeleteNavBio(NavBio); List := TCoreClassListForObj.Create; for i := 0 to NavBio.Slices - 1 do begin d := TNavigationBioPass.Create(Self, NavBio, i, FExtandDistance + 1, True); FPassList.Add(d); List.Add(d); end; for i := 0 to List.Count - 1 do TNavigationBioPass(List[i]).BuildPass(FExtandDistance - 1); DisposeObject(List); end; procedure TPolyPassManager.DeleteNavBio(NavBio: TNavBio); var i: Integer; begin i := 0; while i < Count do begin if (pass[i] is TNavigationBioPass) and (TNavigationBioPass(pass[i]).FNavBio = NavBio) then pass[i].Delete else inc(i); end; end; procedure TPolyPassManager.BuildNavBioPass; var i: Integer; p: TNavBio; begin for i := 0 to FNavBioManager.Count - 1 do begin p := FNavBioManager[i]; if (p.IsStatic) then AddNavBio(p) else DeleteNavBio(p); end; for i := 0 to Count - 1 do begin if (pass[i] is TNavigationBioPass) and (TNavigationBioPass(pass[i]).FNeedUpdate) then pass[i].BuildPass(FExtandDistance - 1); end; end; procedure TPolyPassManager.BuildPass; function ReBuildCalcCache: Boolean; type TCache = array of array of TCacheState; PCache = ^TCache; procedure Build(const ACache: PCache); var i, j: Integer; begin SetLength(ACache^, FPolyManager.Count + 1); SetLength(ACache^[0], FPolyManager.Scene.Count); for i := 0 to FPolyManager.Scene.Count - 1 do ACache^[0][i] := csNoCompute; for i := 0 to FPolyManager.Count - 1 do begin SetLength(ACache^[1 + i], FPolyManager[i].Count); for j := 0 to FPolyManager[i].Count - 1 do ACache^[1 + i][j] := csNoCompute; end; end; var i, j: Integer; needRebuild: Boolean; begin needRebuild := False; if length(FIntersectCache) <> FPolyManager.Count + 1 then needRebuild := True; if not needRebuild then begin for i := 0 to FPolyManager.Count - 1 do begin if length(FIntersectCache[i + 1]) <> FPolyManager[i].Count then begin needRebuild := True; Break; end; end; end; if not needRebuild then if (length(FIntersectCache[0]) <> FPolyManager.Scene.Count) then needRebuild := True; Result := needRebuild; if not needRebuild then Exit; // rebuild intersect cache SetLength(FIntersectCache, FPolyManager.Count + 1); SetLength(FIntersectCache[0], FPolyManager.Scene.Count); for i := 0 to FPolyManager.Scene.Count - 1 do Build(@FIntersectCache[0][i]); for i := 0 to FPolyManager.Count - 1 do begin SetLength(FIntersectCache[1 + i], FPolyManager[i].Count); for j := 0 to FPolyManager[i].Count - 1 do Build(@FIntersectCache[1 + i][j]); end; // rebuild PointIn cache SetLength(FPointInCache, FPolyManager.Count + 1); SetLength(FPointInCache[0], FPolyManager.Scene.Count); for i := 0 to FPolyManager.Scene.Count - 1 do FPointInCache[0][i] := csNoCompute; for i := 0 to FPolyManager.Count - 1 do begin SetLength(FPointInCache[1 + i], FPolyManager[i].Count); for j := 0 to FPolyManager[i].Count - 1 do FPointInCache[1 + i][j] := csNoCompute; end; end; procedure ProcessPoly(APoly: TPolyManagerChildren); var i: Integer; b: TPolyPass; begin for i := 0 to APoly.Count - 1 do if PointOkCache(FExtandDistance, APoly, i) then begin b := TPolyPass.Create(Self, APoly, i, FExtandDistance + 1); b.BuildPass(FExtandDistance - 1); FPassList.Add(b); end; end; var i: Integer; begin if ReBuildCalcCache() then begin Clear; ProcessPoly(FPolyManager.Scene); for i := 0 to FPolyManager.Count - 1 do ProcessPoly(FPolyManager[i]); end; end; procedure TPolyPassManager.Rebuild; begin SetLength(FIntersectCache, 0); BuildPass; BuildNavBioPass; end; function TPolyPassManager.NewPassStateIncremental: ShortInt; begin inc(FPassStateIncremental); Result := FPassStateIncremental; end; function TPolyPassManager.Add(AConn: TBasePass; const NowBuildPass: Boolean): Integer; begin Assert(AConn.FOwner = Self); if (AConn is TPointPass) then begin if (PointOk(FExtandDistance - 1, AConn.GetPosition)) and (NowBuildPass) then AConn.BuildPass(FExtandDistance - 1); end else if (AConn is TPolyPass) then begin if (PointOkCache(FExtandDistance, TPolyPass(AConn).FPoly, TPolyPass(AConn).FPolyIndex)) and (NowBuildPass) then AConn.BuildPass(FExtandDistance - 1); end; Result := FPassList.Add(AConn); end; procedure TPolyPassManager.Delete(idx: Integer); begin DisposeObject(TBasePass(FPassList[idx])); FPassList.Delete(idx); end; procedure TPolyPassManager.Delete(AConn: TBasePass); var i: Integer; begin for i := 0 to Count - 1 do if FPassList[i] = AConn then begin Delete(i); Break; end; end; procedure TPolyPassManager.Clear; begin while Count > 0 do Delete(Count - 1); end; function TPolyPassManager.Count: Integer; begin Result := FPassList.Count; end; function TPolyPassManager.IndexOf(b: TBasePass): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do if FPassList[i] = b then begin Result := i; Break; end; end; function TPolyPassManager.TotalPassNodeCount: Integer; var i: Integer; begin Result := 0; for i := 0 to Count - 1 do Result := Result + GetPass(i).Count; end; procedure TNavBioProcessState.SetLastState(const Value: TLastState); begin FLastState := Value; LastStateBounceWaitTime := 0; end; procedure TNavBioProcessState.Init(AOwner: TNavBio); begin Owner := AOwner; LastState := lsDetectPoint; LerpTo := NULLPoint; LerpSpeed := 0; Timer := 0; PositionChanged := True; ChangeSource := csInit; LastProcessed := False; LastStateBounceWaitTime := 0; end; procedure TNavBioProcessState.ReleaseSelf; begin end; function TNavBio.GetPosition: TVec2; begin Result := FPosition; end; procedure TNavBio.SetPosition(const Value: TVec2); var oldpt, newpt: TVec2; begin if FMovement.Active then begin DirectPosition := Value; Exit; end; FInternalStates.LastState := lsIgnore; oldpt := FPosition; newpt := Value; if Owner.Smooth then begin if SmoothBouncePosition(oldpt, newpt, FInternalStates.LerpTo) then begin FInternalStates.LastState := lsDirectLerpTo; FInternalStates.LerpSpeed := FMovement.RollMoveRatio * FMovement.MoveSpeed; end else begin end; DirectPosition := newpt; end else begin if GetBouncePosition(oldpt, newpt) then DirectPosition := newpt; end; end; function TNavBio.GetRollAngle: TGeoFloat; begin Result := FRollAngle; end; procedure TNavBio.SetRollAngle(const Value: TGeoFloat); begin if IsNan(Value) then raise Exception.Create('float is nan'); FInternalStates.PositionChanged := True; if not(IsEqual(Value, FRollAngle)) then FRollAngle := Value; end; procedure TNavBio.DoStartMovement; begin State := nsRun; if FNotifyIntf <> nil then FNotifyIntf.DoMovementStart(Self, FMovement.ToPosition); end; procedure TNavBio.DoMovementDone; begin State := nsStop; if FNotifyIntf <> nil then FNotifyIntf.DoMovementOver(Self); FMovementPath.Clear; end; procedure TNavBio.DoRollMovementStart; begin end; procedure TNavBio.DoRollMovementOver; begin end; procedure TNavBio.DoLoop; begin end; procedure TNavBio.DoStop; begin State := nsStop; if (FNotifyIntf <> nil) then FNotifyIntf.DoMovementOver(Self); end; procedure TNavBio.DoPause; begin State := nsPause; if (FNotifyIntf <> nil) then FNotifyIntf.DoMovementOver(Self); end; procedure TNavBio.DoContinue; begin State := nsRun; if FNotifyIntf <> nil then FNotifyIntf.DoMovementStart(Self, FMovement.ToPosition); end; procedure TNavBio.DoMovementStepChange(OldStep, NewStep: TMovementStep); begin end; function TNavBio.SmoothBouncePosition(const OldPos: TVec2; var NewPos, NewLerpPos: TVec2): Boolean; var LineList: TDeflectionPolygonLines; function LineIsLink: Boolean; var i: Integer; L1, l2: PDeflectionPolygonLine; begin Result := True; if LineList.Count = 1 then Exit; L1 := LineList[0]; Result := False; for i := 1 to LineList.Count - 1 do begin l2 := LineList[i]; if l2^.OwnerDeflectionPolygon <> L1^.OwnerDeflectionPolygon then Exit; if not((L1^.OwnerDeflectionPolygonIndex[1] = l2^.OwnerDeflectionPolygonIndex[0]) or (L1^.OwnerDeflectionPolygonIndex[0] = l2^.OwnerDeflectionPolygonIndex[1]) or (L1^.OwnerDeflectionPolygonIndex[1] = l2^.OwnerDeflectionPolygonIndex[1]) or (L1^.OwnerDeflectionPolygonIndex[0] = l2^.OwnerDeflectionPolygonIndex[0])) then Exit; L1 := l2; end; Result := True; end; function ProcessOfLinkMode: Boolean; var dir: TVec2; totaldist, Dist, a1, a2, a3: TGeoFloat; LastPos: TVec2; L: TDeflectionPolygonLine; begin LastPos := NewPos; totaldist := PointDistance(OldPos, LastPos); L := LineList.NearLine(radius + 1, LastPos)^; LastPos := L.ExpandPoly(radius + 1).ClosestPointFromLine(LastPos); Dist := PointDistance(OldPos, LastPos); if Dist > totaldist then begin NewLerpPos := LastPos; NewPos := PointLerpTo(OldPos, LastPos, totaldist); Result := True; end else begin totaldist := totaldist - Dist; dir := PointNormalize(Vec2Sub(LastPos, OldPos)); a1 := PointAngle(L.buff[0], L.buff[1]); a2 := PointAngle(L.buff[1], L.buff[0]); a3 := PointAngle(NULLPoint, dir); if AngleDistance(a1, a3) < AngleDistance(a2, a3) then // dir to index 0..1 LastPos := L.OwnerDeflectionPolygon.LerpToEdge(LastPos, totaldist, radius + 1, L.OwnerDeflectionPolygonIndex[0], L.OwnerDeflectionPolygonIndex[1]) else // dir to index 1..0 LastPos := L.OwnerDeflectionPolygon.LerpToEdge(LastPos, totaldist, radius + 1, L.OwnerDeflectionPolygonIndex[1], L.OwnerDeflectionPolygonIndex[0]); NewLerpPos := LastPos; NewPos := LastPos; Result := False; end; end; begin Result := False; NewLerpPos := NewPos; if (IsFlight) or (IsRun) or (FPassManager.PointOk(radius, NewPos)) then Exit; LineList := TDeflectionPolygonLines.Create; if FPassManager.PolyManager.Collision2Circle(NewPos, radius, LineList) then begin if LineIsLink then Result := ProcessOfLinkMode else begin NewLerpPos := OldPos; NewPos := OldPos; Result := False; end; end else begin NewLerpPos := FPassManager.PolyManager.GetNearLine(radius + 2, NewPos); Result := True; end; DisposeObject(LineList); end; procedure TNavBio.SetDirectPosition(const Value: TVec2); begin if IsNan(Value) then raise Exception.Create('float is nan'); FInternalStates.PositionChanged := True; // if not(IsEqual(Value, FPosition)) then FPosition := Value; end; procedure TNavBio.SetState(const Value: TNavState); var OldState: TNavState; i: Integer; begin if Value <> FState then begin OldState := FState; FState := Value; if OldState = nsStatic then begin if (Assigned(FOwner.OnRebuildNavBioPass)) then FOwner.OnRebuildNavBioPass(Self); end; FInternalStates.PositionChanged := True; for i := 0 to FCollisionList.Count - 1 do TNavBio(FCollisionList[i]).FInternalStates.PositionChanged := True; end; end; procedure TNavBio.SetPhysicsPropertys(const Value: TPhysicsPropertys); var i: Integer; begin if FPhysicsPropertys <> Value then begin FPhysicsPropertys := Value; FInternalStates.PositionChanged := True; for i := 0 to FCollisionList.Count - 1 do TNavBio(FCollisionList[i]).FInternalStates.PositionChanged := True; end; end; function TNavBio.GetSlices: Integer; begin Result := FOwner.FSlices; end; procedure TNavBio.LinkCollision(p: TNavBio; const Associated: Boolean); var i: Integer; begin if p <> Self then begin if Associated then p.LinkCollision(Self, False); for i := FCollisionList.Count - 1 downto 0 do if FCollisionList[i] = p then Exit; FCollisionList.Add(p); if Associated then Collision(p); end; end; procedure TNavBio.UnLinkCollision(p: TNavBio; const Associated: Boolean); var i: Integer; begin if p <> Self then begin i := 0; while i < FCollisionList.Count do begin if FCollisionList[i] = p then begin FCollisionList.Delete(i); if Associated then UnCollision(p); end else inc(i); end; if Associated then p.UnLinkCollision(Self, False); end; end; constructor TNavBio.Create(AOwner: TNavBioManager; APassManager: TPolyPassManager); begin inherited Create; FOwner := AOwner; FPassManager := APassManager; FEdgePassList := TCoreClassListForObj.Create; FMovementPath := TVec2List.Create; FPosition := Make2DPoint(0, 0); FRadius := FPassManager.ExtandDistance; FMovement := TMovementEngine.Create; FMovement.Intf := Self; FNotifyIntf := nil; FState := nsStop; FPhysicsPropertys := []; FInternalStates.Init(Self); FCollisionList := TCoreClassListForObj.Create; FOwner.FNavBioList.Add(Self); end; destructor TNavBio.Destroy; var i: Integer; begin DisposeObject(FMovement); FMovement := nil; DisposeObject(FMovementPath); while FEdgePassList.Count > 0 do TBasePass(FEdgePassList[0]).Delete; for i := 0 to FCollisionList.Count - 1 do TNavBio(FCollisionList[i]).UnLinkCollision(Self, False); i := 0; while i < FOwner.FNavBioList.Count do begin if Self = FOwner.FNavBioList[i] then FOwner.FNavBioList.Delete(i) else inc(i); end; DisposeObject(FCollisionList); DisposeObject(FEdgePassList); FInternalStates.ReleaseSelf; inherited Destroy; end; procedure TNavBio.DirectionTo(ToPosition: TVec2); begin if FMovement.Active then FMovement.stop; FInternalStates.LastState := lsIgnore; FMovementPath.Clear; FMovement.Start(ToPosition); end; function TNavBio.MovementTo(ToPosition: TVec2): Boolean; var nsf: TNavStepFinding; begin if FMovement.Active then FMovement.stop; FInternalStates.LastState := lsIgnore; FMovementPath.Clear; if IsFlight then begin FMovementPath.Add(Position); FMovementPath.Add(ToPosition); FMovement.Start(FMovementPath); Result := True; Exit; end; Result := False; nsf := TNavStepFinding.Create(PassManager); if nsf.PassManager.Count = 0 then nsf.PassManager.Rebuild; if not nsf.PassManager.PointOk(radius, ToPosition) then ToPosition := nsf.PassManager.PolyManager.GetNearLine(radius + 1, ToPosition); if not nsf.PassManager.PointOk(radius, DirectPosition) then DirectPosition := nsf.PassManager.PolyManager.GetNearLine(radius + 1, DirectPosition); if nsf.FindPath(Self, ToPosition) then begin while not nsf.FindingPathOver do nsf.NextStep; if (nsf.Success) then begin nsf.MakeLevel4OptimizationPath(FMovementPath); Result := True; end; end; DisposeObject(nsf); if Result then FMovement.Start(FMovementPath); end; procedure TNavBio.stop; begin FMovement.stop; end; procedure TNavBio.Hold; begin State := nsStatic; end; function TNavBio.GetBouncePosition(const OldPos: TVec2; var NewPos: TVec2): Boolean; var LineList: TDeflectionPolygonLines; function LineIsLink: Boolean; var i: Integer; L1, l2: PDeflectionPolygonLine; begin Result := True; if LineList.Count = 1 then Exit; L1 := LineList[0]; Result := False; for i := 1 to LineList.Count - 1 do begin l2 := LineList[i]; if l2^.OwnerDeflectionPolygon <> L1^.OwnerDeflectionPolygon then Exit; if not((L1^.OwnerDeflectionPolygonIndex[1] = l2^.OwnerDeflectionPolygonIndex[0]) or (L1^.OwnerDeflectionPolygonIndex[0] = l2^.OwnerDeflectionPolygonIndex[1]) or (L1^.OwnerDeflectionPolygonIndex[1] = l2^.OwnerDeflectionPolygonIndex[1]) or (L1^.OwnerDeflectionPolygonIndex[0] = l2^.OwnerDeflectionPolygonIndex[0])) then Exit; L1 := l2; end; Result := True; end; function ProcessOfLinkMode: Boolean; var dir: TVec2; totaldist, Dist, a1, a2, a3: TGeoFloat; LastPos: TVec2; L: TDeflectionPolygonLine; begin LastPos := NewPos; totaldist := PointDistance(OldPos, LastPos); L := LineList.NearLine(radius + 1, LastPos)^; LastPos := L.ExpandPoly(radius + 1).ClosestPointFromLine(LastPos); Dist := PointDistance(OldPos, LastPos); if (Dist <= totaldist) and (Dist > 0) then begin totaldist := totaldist - Dist; dir := PointNormalize(Vec2Sub(LastPos, OldPos)); a1 := PointAngle(L.buff[0], L.buff[1]); a2 := PointAngle(L.buff[1], L.buff[0]); a3 := PointAngle(NULLPoint, dir); if AngleDistance(a1, a3) < AngleDistance(a2, a3) then // dir to index 0..1 LastPos := L.OwnerDeflectionPolygon.LerpToEdge(LastPos, totaldist, radius + 1, L.OwnerDeflectionPolygonIndex[0], L.OwnerDeflectionPolygonIndex[1]) else // dir to index 1..0 LastPos := L.OwnerDeflectionPolygon.LerpToEdge(LastPos, totaldist, radius + 1, L.OwnerDeflectionPolygonIndex[1], L.OwnerDeflectionPolygonIndex[0]); end; NewPos := LastPos; Result := True; end; begin Result := True; if (IsFlight) or (IsRun) or (FPassManager.PointOk(radius, NewPos)) then Exit; LineList := TDeflectionPolygonLines.Create; if FPassManager.PolyManager.Collision2Circle(NewPos, radius, LineList) then begin if LineIsLink then Result := ProcessOfLinkMode else Result := False; end else begin NewPos := FPassManager.PolyManager.GetNearLine(radius + 2, NewPos); Result := True; end; DisposeObject(LineList); end; procedure TNavBio.ProcessBounce(p1: TNavBio; deltaTime: Double); var d: TGeoFloat; pt: TVec2; begin if (not CanBounce) or (not p1.CanBounce) then Exit; if p1.FInternalStates.LastState = lsDirectLerpTo then begin if p1.FInternalStates.LastStateBounceWaitTime + deltaTime > Owner.BounceWaitTime then p1.FInternalStates.LastState := lsDetectPoint else begin p1.FInternalStates.LastStateBounceWaitTime := p1.FInternalStates.LastStateBounceWaitTime + deltaTime; Exit; end; end; if FInternalStates.LastState = lsDirectLerpTo then begin if FInternalStates.LastStateBounceWaitTime + deltaTime > Owner.BounceWaitTime then FInternalStates.LastState := lsDetectPoint else begin FInternalStates.LastStateBounceWaitTime := FInternalStates.LastStateBounceWaitTime + deltaTime; Exit; end; end; if not CircleCollision(DirectPosition, p1.DirectPosition, radius, p1.radius) then Exit; FInternalStates.LastStateBounceWaitTime := 0; if (IsRun) and (p1.IsRun) then begin end else if (not p1.IsRun) and (p1.IsStop) and (p1.FInternalStates.LastState <> lsDirectLerpTo) then begin if IsEqual(p1.DirectPosition, DirectPosition) then begin d := (radius + p1.radius + 1); pt := PointLerpTo(p1.DirectPosition, PointRotation(p1.DirectPosition, 1, -p1.RollAngle), -d); end else begin d := (radius + p1.radius + 1) - PointDistance(p1.DirectPosition, DirectPosition); pt := PointLerpTo(p1.DirectPosition, DirectPosition, -d); end; if p1.GetBouncePosition(p1.DirectPosition, pt) then begin p1.FInternalStates.ChangeSource := csBounce; if (Owner.Smooth) then begin p1.FInternalStates.LastState := lsDirectLerpTo; p1.FInternalStates.LerpTo := pt; p1.FInternalStates.LerpSpeed := p1.FMovement.RollMoveRatio * p1.FMovement.MoveSpeed; if p1.FNotifyIntf <> nil then p1.FNotifyIntf.DoMovementStart(p1, pt); end else begin p1.DirectPosition := pt; p1.FInternalStates.LastState := lsProcessBounce; end; end else begin p1.FInternalStates.LastState := lsDetectPoint; end; end; end; procedure TNavBio.Progress(deltaTime: Double); var i: Integer; p: TNavBio; d: TGeoFloat; begin FMovement.Progress(deltaTime); FInternalStates.ChangeSource := csExternal; if (IsRun) or (FMovement.Active) then begin if (not PassManager.PointOk(radius, DirectPosition)) and (not IsFlight) then begin FInternalStates.ChangeSource := csBounce; DirectPosition := PassManager.PolyManager.GetNearLine(radius + 2, DirectPosition); end; if IsFlight then begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if p.IsFlight then ProcessBounce(p, deltaTime); end; end else begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if not p.IsFlight then ProcessBounce(p, deltaTime); end; end; if FNotifyIntf <> nil then FNotifyIntf.DoMovementProcess(deltaTime); end else begin if IsStatic then begin if (FEdgePassList.Count = 0) and (FCollisionList.Count = 0) then begin if Assigned(FOwner.OnRebuildNavBioPass) then FOwner.OnRebuildNavBioPass(Self); end else begin d := 4; FRadius := FRadius + d; if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin ProcessBounce(CollisionList[i] as TNavBio, deltaTime); end; FRadius := FRadius - d; end; end else if (IsStop) then begin case FInternalStates.LastState of lsDetectPoint: begin if not IsFlight then begin if (FPassManager.PointOk(radius, DirectPosition)) then begin FInternalStates.LastState := lsProcessBounce; end else begin FInternalStates.ChangeSource := csBounce; if Owner.Smooth then begin FInternalStates.LastState := lsDirectLerpTo; FInternalStates.LerpTo := FPassManager.PolyManager.GetNearLine(radius + 1, DirectPosition); FInternalStates.LerpSpeed := FMovement.RollMoveRatio * FMovement.MoveSpeed; end else begin DirectPosition := FPassManager.PolyManager.GetNearLine(radius + 1, DirectPosition); FInternalStates.LastState := lsProcessBounce; end; end; end else begin FInternalStates.LastState := lsProcessBounce; end; end; lsDirectLerpTo: begin FInternalStates.ChangeSource := csBounce; d := PointDistance(DirectPosition, FInternalStates.LerpTo); if FInternalStates.LerpSpeed * deltaTime >= d then begin RollAngle := SmoothAngle(RollAngle, CalcAngle(DirectPosition, FInternalStates.LerpTo), FMovement.RollSpeed * deltaTime); DirectPosition := FInternalStates.LerpTo; FInternalStates.LastState := lsProcessBounce; if FNotifyIntf <> nil then FNotifyIntf.DoMovementOver(Self); end else begin RollAngle := SmoothAngle(RollAngle, CalcAngle(DirectPosition, FInternalStates.LerpTo), FMovement.RollSpeed * deltaTime); DirectPosition := PointLerpTo(DirectPosition, FInternalStates.LerpTo, FInternalStates.LerpSpeed * deltaTime); end; if IsFlight then begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if p.IsFlight then ProcessBounce(p, deltaTime); end; end else begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if (not p.IsFlight) then ProcessBounce(p, deltaTime); end; end; if FNotifyIntf <> nil then FNotifyIntf.DoMovementProcess(deltaTime); end; lsProcessBounce: begin if IsFlight then begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if p.IsFlight then ProcessBounce(p, deltaTime); end; end else begin if (CollisionList.Count > 0) and (CanBounce) then for i := 0 to CollisionList.Count - 1 do begin p := CollisionList[i] as TNavBio; if not p.IsFlight then ProcessBounce(p, deltaTime); end; end; FInternalStates.LastState := lsIgnore; end; lsIgnore: begin if FInternalStates.PositionChanged then begin FInternalStates.Timer := FInternalStates.Timer + deltaTime; if FInternalStates.Timer >= 0.1 then begin FInternalStates.Timer := 0; FInternalStates.LastState := lsDetectPoint; FInternalStates.PositionChanged := False; end; end else FInternalStates.Timer := 0 end; end; end; end; end; function TNavBio.IsPause: Boolean; begin Result := (FState = nsPause); end; function TNavBio.IsStop: Boolean; begin Result := (FState = nsStop); end; function TNavBio.IsStatic: Boolean; begin Result := (FState = nsStatic); end; function TNavBio.IsRun: Boolean; begin Result := (FState = nsRun) or (FState = nsPause); end; function TNavBio.IsFlight: Boolean; begin if IsStatic then Result := False else Result := (npFlight in FPhysicsPropertys); end; function TNavBio.CanBounce: Boolean; begin if IsStatic then Result := True else if (npNoBounce in FPhysicsPropertys) then Result := False else Result := True; end; function TNavBio.CanCollision: Boolean; begin if IsStatic then Result := True else if (npIgnoreCollision in FPhysicsPropertys) then Result := False else Result := True; end; procedure TNavBio.Collision(Trigger: TNavBio); begin end; procedure TNavBio.UnCollision(Trigger: TNavBio); begin end; function TNavBio.ExistsCollision(v: TNavBio): Boolean; var i: Integer; begin Result := True; for i := 0 to FCollisionList.Count - 1 do if FCollisionList[i] = v then Exit; Result := False; end; function TNavBioManager.GetItems(index: Integer): TNavBio; begin Result := FNavBioList[index] as TNavBio; end; constructor TNavBioManager.Create; begin inherited Create; FNavBioList := TCoreClassListForObj.Create; FBounceWaitTime := 5.0; FSlices := 5; FSmooth := True; FIgnoreAllCollision := False; FOnRebuildNavBioPass := nil; end; destructor TNavBioManager.Destroy; begin Clear; DisposeObject(FNavBioList); inherited Destroy; end; function TNavBioManager.Add(PassManager: TPolyPassManager; pt: TVec2; angle: TGeoFloat): TNavBio; begin Result := TNavBio.Create(Self, PassManager); Result.FPosition := pt; Result.FRollAngle := angle; end; procedure TNavBioManager.Clear; begin while FNavBioList.Count > 0 do DisposeObject(TNavBio(FNavBioList[0])); end; function TNavBioManager.Count: Integer; begin Result := FNavBioList.Count; end; function TNavBioManager.ActivtedCount: Integer; var i: Integer; begin Result := 0; for i := 0 to Count - 1 do if Items[i].IsActived then inc(Result); end; function TNavBioManager.PointOk(AExpandDist: TGeoFloat; pt: TVec2; ignore: TCoreClassListForObj): Boolean; function IsIgnore(v: TNavBio): Boolean; begin Result := (ignore <> nil) and (ignore.IndexOf(v) >= 0); end; var i: Integer; begin for i := 0 to Count - 1 do if not IsIgnore(Items[i]) then with Items[i] do if (IsStatic) and (Detect_Circle2Circle(pt, DirectPosition, AExpandDist, radius)) then begin Result := False; Exit; end; Result := True; end; function TNavBioManager.PointOk(AExpandDist: TGeoFloat; pt: TVec2): Boolean; var i: Integer; begin for i := 0 to Count - 1 do with Items[i] do if (IsStatic) and (Detect_Circle2Circle(pt, DirectPosition, AExpandDist, radius)) then begin Result := False; Exit; end; Result := True; end; function TNavBioManager.LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2; ignore: TCoreClassListForObj): Boolean; function IsIgnore(v: TNavBio): Boolean; begin Result := (ignore <> nil) and (ignore.IndexOf(v) >= 0); end; var i: Integer; begin for i := 0 to Count - 1 do if not IsIgnore(Items[i]) then with Items[i] do if (IsStatic) and (Detect_Circle2Line(DirectPosition, radius + AExpandDist, lb, le)) then begin Result := True; Exit; end; Result := False; end; function TNavBioManager.LineIntersect(AExpandDist: TGeoFloat; lb, le: TVec2): Boolean; var i: Integer; begin for i := 0 to Count - 1 do with Items[i] do if (IsStatic) and (Detect_Circle2Line(DirectPosition, radius + AExpandDist, lb, le)) then begin Result := True; Exit; end; Result := False; end; function TNavBioManager.DetectCollision(p1, p2: TNavBio): Boolean; var r1, r2: TGeoFloat; begin if p1.IsStatic then r1 := p1.radius + 4 else r1 := p1.radius; if p2.IsStatic then r2 := p2.radius + 4 else r2 := p2.radius; if (p1.CanCollision) and (p2.CanCollision) then Result := Detect_Circle2Circle(p1.DirectPosition, p2.DirectPosition, r1, r2) else Result := False; end; procedure TNavBioManager.Progress(deltaTime: Double); var j, i: Integer; p1, p2: TNavBio; begin if not FIgnoreAllCollision then for i := 0 to FNavBioList.Count - 1 do begin p1 := FNavBioList[i] as TNavBio; p1.FInternalStates.LastProcessed := False; if p1.CanCollision then for j := i + 1 to FNavBioList.Count - 1 do begin p2 := FNavBioList[j] as TNavBio; if (p1.PositionChanged) or (p2.PositionChanged) then begin if DetectCollision(p1, p2) then p1.LinkCollision(p2, True) else p1.UnLinkCollision(p2, True); end; end; end; for i := 0 to FNavBioList.Count - 1 do begin p1 := FNavBioList[i] as TNavBio; if FIgnoreAllCollision then p1.FInternalStates.LastProcessed := False; p1.Progress(deltaTime); p1.FInternalStates.LastProcessed := True; end; end; end.
program inmultire_matrici; uses SysUtils; const { version information } version = '2.2.0'; autor = 'Micu Matei-Marius'; git = 'https://github.com/micumatei/inmultire-matrici'; gmail = 'micumatei@gmail.com'; licenta = 'The MIT License (MIT)'; type vector_2d=array[1..1000, 1..1000] of longint; matrice = record n, { nr linii } m { nr coloane } :integer; v_2d :vector_2d; end; var mat1, mat2, mat3 :matrice; procedure afis_mat(var mat :matrice); { afisam o matrice } var i, j :integer; begin with mat do begin for i := 1 to n do begin for j := 1 to m do write(v_2d[i, j]:3, ' '); writeln; end; end; writeln; end; procedure init_mat(var mat :matrice); { initializam o matrice } begin with mat do begin n := 0; m := 0; end; end; procedure citire_mat(var mat :matrice; s :string); { citim o matrice dintr-un fisier } var f :text; begin assign(f, s); reset(f); init_mat(mat); with mat do begin while not eof(f) do begin inc(n); { incrementam linia } m := 0; { resetam coloana } while not eoln(f) do begin inc(m); { incrementam coloana } read(f, v_2d[n, m]); { citim elementul } end; readln(f); { trecem la urmatoarea linie in fisier } end; end; close(f); end; function inmultire(var mat1, mat2 :matrice):matrice; var i, j :integer; function lin_pe_col(x, y :integer):longint; { inmultim linia <x> cu coloana <y> } var i2 :integer; begin lin_pe_col := 0; for i2 := 1 to mat1.m do begin lin_pe_col := lin_pe_col + mat1.v_2d[x, i2] * mat2.v_2d[i2, y]; end; end; begin init_mat(inmultire); if mat1.m = mat2.n then { se pot inmulti matricele } begin inmultire.n := mat1.n; { rezultatul va avea numarul de linii a primei coloane } inmultire.m := mat2.m; { si nr de coloane a celei de a doua matrici } for i := 1 to inmultire.n do for j := 1 to inmultire.m do inmultire.v_2d[i, j] := lin_pe_col(i, j); end; end; procedure help; { afisam mesaj ajutator scurt } begin writeln(' Folositi -h, -? sau --help pentru mai multe informatii.'); writeln(' Sau accesati :', git); end; { main program } begin if ParamCount > 0 then { avem macar un parametru } begin if (lowercase(ParamStr(1)) = '-h') OR (lowercase(ParamStr(1)) = '-?') OR (lowercase(ParamStr(1)) = '--help') then { afisam help } begin writeln( ' Program folosit pentru inmultirea matricilor.' ); writeln( ' Primeste ca marametri 2 fisiere care contin doua matrici, va incera ca le inmulteasca' ); writeln( ' Autor : ', autor ); writeln( ' GitHub : ', git ); writeln( ' Gmail : ', gmail ); writeln( ' Version : ', version ); writeln( ' Licenta : ', licenta ); end else { rulam } begin if ParamCount < 2 then { nu avem 2 fisiere } begin writeln(' Nu avem doua fisiere din care sa citim cele doua matrici!'); help; end else begin if FileExists(ParamStr(1)) then begin if FileExists(ParamStr(2)) then begin { citim cele doua matrici } citire_mat(mat1, ParamStr(1)); citire_mat(mat2, ParamStr(2)); mat3 := inmultire(mat1, mat2); if (mat3.n = 0) AND (mat3.m = 0) then { nu am putut imulti } begin writeln(' Nu am putut inmulti cele doua matrici, verificati fisierele'); help; end else { totul a decurs corect } begin writeln(' Rezultatul inmultiri matrici : '); afis_mat(mat1); writeln(' Cu matricia :'); afis_mat(mat2); writeln(' Este :'); afis_mat(mat3); end; end else begin writeln( 'Fisierul : ', ParamStr(2), ' nu exista !' ); help; end; end else { primul fisier nu exista } begin writeln( 'Fisierul : ', ParamStr(1), ' nu exista !' ); help; end; end; end; end else help; end.
unit FileCreator; interface type TFileCreator = class private const // макс длина строки maxstrlen = 1024; // макс число maxnumber = MaxInt; // символы для генерации строки symbols = 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.,?!:;'; private fFileName: string; fFileSize: Int64; // массив для хранения строк, с помощью него создаются одинковые строки arst: array of string; function getSym: char; function getStr(n: integer; accu: boolean): string; function getNum: cardinal; function getNStr(n: integer): string; function getAnyStr: string; procedure addStr(aStr: string); public constructor Create(aFileName: string; aFileSize: Int64); destructor Destroy; override; procedure DoIt; end; implementation uses System.SysUtils; { TFileCreator } // дает случайный символ из строки function TFileCreator.getSym: char; begin result := symbols[Random(Length(symbols)) + 1]; end; // формирует случайную строку // если accu = true, то длина строки = n // если accu = false, то длина строки <=n function TFileCreator.getStr(n: integer; accu: boolean): string; var i, c: integer; begin if accu then c := n else c := Random(n) + 1; SetLength(result, c); for i := 1 to c do result[i] := getSym; end; // возвращает случайное число function TFileCreator.getNum: cardinal; begin result := abs(Random(maxnumber)); if Random > 0.5 then result := result * 2; end; // возвращает строку вида Number. String длиной n function TFileCreator.getNStr(n: integer): string; begin result := Format('%u. %s', [abs(Random(10)), getStr(n - 3, true)]); end; // возвращает любую строку вида Number. String // возможно одну из существующих function TFileCreator.getAnyStr: string; var s: string; begin if Random > 0.5 then s := arst[Random(10)]; if s = '' then s := getStr(maxstrlen, false); // добавляю строку в массив для организации повторения строк addStr(s); result := Format('%u. %s', [getNum, s]); end; // добавить строку в массив в случайную позицию procedure TFileCreator.addStr(aStr: string); begin if Random > 0.5 then arst[Random(10)] := aStr; end; constructor TFileCreator.Create(aFileName: string; aFileSize: Int64); begin fFileName := aFileName; fFileSize := aFileSize; SetLength(arst, 10); end; destructor TFileCreator.Destroy; begin arst := nil; inherited; end; // запись в файл procedure TFileCreator.DoIt; var aFile: text; cs: Int64; s: string; begin cs := 0; AssignFile(aFile, fFileName); FileMode := fmOpenWrite; Rewrite(aFile); // цикл до требуемого размера файла while cs < fFileSize do begin // если осталось меньше байт // по заданию достаточно кодировки ANSI // поэтому упрощаю - один символ = один байт // иначе для юникода нужно было бы SizeOf(Char) if fFileSize - cs < maxstrlen then begin // то генерирую строку длины до оставшегося размера s := getNStr(fFileSize - cs); cs := fFileSize; Write(aFile, s); end else begin // генерирую случайную строку s := getAnyStr; // если остается меньше 4 байт, а такая строка не может быть, // то генерирую строку меньшего размера // чтобы осталось на следующую if abs(cs + Length(s) + 2) < 4 then s := getNStr(maxstrlen div 2); cs := cs + Length(s) + 2; Writeln(aFile, s); end; end; CloseFile(aFile); end; end.
unit ImageBtn; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TImageBtn = class( TCustomControl ) private FBitmapOn : TBitmap; FBitmapOff : TBitmap; FIsOn : boolean; FHRgn : HRGN; FFirstRgn : boolean; procedure SetBitmapOn( Bmp : TBitmap ); procedure SetBitmapOff( Bmp : TBitmap ); procedure WMMouseMove( var Message: TMessage ); message WM_MOUSEMOVE; protected procedure Paint; override; public constructor Create( AOwner : TComponent ); override; destructor Destroy; override; procedure SetRgn( Rgn : HRGN ); procedure SetState( IsOn : boolean ); published property BitmapOn : TBitmap read FBitmapOn write SetBitmapOn; property BitmapOff : TBitmap read FBitmapOff write SetBitmapOff; property OnClick; end; procedure Register; implementation procedure Register; begin RegisterComponents( 'Scrabble' , [TImageBtn] ); end; //============================================================================== // Constructor / destructor //============================================================================== constructor TImageBtn.Create( AOwner : TComponent ); begin inherited; FBitmapOn := TBitmap.Create; FBitmapOff := TBitmap.Create; FIsOn := false; Parent := TWinControl( AOwner ); Width := 105; Height := 105; ControlStyle := ControlStyle + [csOpaque]; FHRgn := CreateRectRgn( 0 , 0 , 0 , 0 ); FFirstRgn := true; SetRgn( CreateRectRgn( 0 , 0 , 37 , 33 ) ); end; destructor TImageBtn.Destroy; begin FBitmapOn.Free; FBitmapOff.Free; inherited; end; //============================================================================== // P R I V A T E //============================================================================== procedure TImageBtn.SetBitmapOn( Bmp : TBitmap ); begin FBitmapOn.Assign( Bmp ); end; procedure TImageBtn.SetBitmapOff( Bmp : TBitmap ); begin FBitmapOff.Assign( Bmp ); Repaint; end; //============================================================================== // P R O T E C T E D //============================================================================== procedure TImageBtn.Paint; begin if (FIsOn) then begin if (FBitmapOn <> nil) then Canvas.Draw( 0 , 0 , FBitmapOn ); end else begin if (FBitmapOff <> nil) then Canvas.Draw( 0 , 0 , FBitmapOff ) else Canvas.FillRect( ClientRect ); end; end; //============================================================================== // P U B L I C //============================================================================== procedure TImageBtn.WMMouseMove( var Message : TMessage ); begin if (FIsOn) then begin if (PtInRegion( FHRgn , Message.LParamLo , Message.LParamHi ) = FALSE) then begin ReleaseCapture; FIsOn := false; Repaint; end; end else begin SetCapture( Handle ); FIsOn := true; Repaint; end; end; procedure TImageBtn.SetRgn( Rgn : HRGN ); begin SetWindowRgn( Handle , Rgn , FALSE ); GetWindowRgn( Handle , FHRgn ); end; procedure TImageBtn.SetState( IsOn : boolean ); begin FIsOn := IsOn; Repaint; end; end.
{ Задача №13 (интерполирование) Программа обеспечивает локальное сглаживание функции, заданной таблицей значений в равноотстоящих точках с помощью многочлена третьей степени, построенного по пяти точкам методом наименьших квадратов. } unit UMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UProcess; type TMForm = class(TForm) Image: TImage; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Ed_x0: TEdit; Ed_xn: TEdit; Ed_a: TEdit; Ed_b: TEdit; Ed_c: TEdit; Ed_d: TEdit; Ed_e: TEdit; Ed_h: TEdit; Btn_build: TButton; Btn_scatter: TButton; Btn_smooth: TButton; Btn_clear: TButton; procedure FormCreate(Sender: TObject); procedure Btn_buildClick(Sender: TObject); procedure Btn_clearClick(Sender: TObject); procedure Btn_scatterClick(Sender: TObject); procedure Btn_smoothClick(Sender: TObject); private X, Y, Z: TVector; NV: Integer; procedure ClearImage(I: TImage); procedure MakeCoords; procedure MakeLine(Color: TColor); public end; var MForm: TMForm; x0, xN: TType; a, b, c, d, e, h: TType; cx0, cy0, cx1, cy1: Integer; implementation uses Math; {$R *.dfm} procedure TMForm.FormCreate(Sender: TObject); begin Ed_x0.Text := '-2'; Ed_xn.Text := '5'; Ed_h.text := '0,3'; Ed_e.Text := '1,3'; Ed_a.Text := '0,2'; Ed_b.Text := '0'; Ed_c.Text := '-3'; Ed_d.Text := '4'; end; procedure TMForm.ClearImage(I: TImage); begin I.Canvas.Brush.Color := clWhite; I.Canvas.Pen.Color := clBlack; I.Canvas.Rectangle(0, 0, I.Width, I.Height); end; procedure Dot(X, Y: TType; Canvas: TCanvas; Color: TColor); var cx, cy, R: Integer; begin R := 2; Canvas.Pen.Color := Color; Canvas.Brush.Color := Color; cx := cx0 + Round(X * cx1); cy := cy0 - Round(Y * cy1); Canvas.Ellipse(cx - R, cy - R, cx + R, cy + R); end; procedure Line(FromX, FromY, ToX, ToY: TType; Canvas: TCanvas; Color: TColor); var cx, cy: Integer; begin Canvas.Pen.Color := Color; cx := cx0 + Round(FromX * cx1); cy := cy0 - Round(FromY * cy1); Canvas.MoveTo(cx, cy); cx := cx0 + Round(ToX * cx1); cy := cy0 - Round(ToY * cy1); Canvas.LineTo(cx, cy); end; procedure DrawCoordinates(MinX, MinY, MaxX, MaxY: TType; W, H: Integer; Canvas: TCanvas); var i, t: Integer; S: String; begin cx1 := Round(W / (MaxX - MinX)); cy1 := Round(H / (MaxY - MinY)); cx0 := (W - Round(Abs(MaxX + MinX)) * cx1) div 2; cy0 := (H + Round(Abs(MaxY + MinY)) * cy1) div 2; // Draw coordinate axis with Canvas do begin Pen.Color := clGray; MoveTo(0, cy0); LineTo(W, cy0); MoveTo(cx0, 0); LineTo(cx0, H); // Draw numbers for i := 1 to Floor(Abs(MaxX)) do begin MoveTo(cx0 + i * cx1, cy0 - 2); LineTo(cx0 + i * cx1, cy0 + 3); S := IntToStr(i); t := Canvas.TextWidth(S) div 2; TextOut(cx0 + i * cx1 - t, cy0 + 5, S); end; for i := 1 to Floor(Abs(MinX)) do begin MoveTo(cx0 - i * cx1, cy0 - 2); LineTo(cx0 - i * cx1, cy0 + 3); S := IntToStr(-i); t := Canvas.TextWidth(S) div 2; TextOut(cx0 - i * cx1 - t, cy0 + 5, S); end; for i := 1 to Floor(Abs(MaxY)) do begin MoveTo(cx0 - 2, cy0 - i * cy1); LineTo(cx0 + 3, cy0 - i * cy1); S := IntToStr(i); t := Canvas.TextHeight(S) div 2; TextOut(cx0 + 5, cy0 - i * cy1 - t, S); end; for i := 1 to Floor(Abs(MinY)) do begin MoveTo(cx0 - 2, cy0 + i * cy1); LineTo(cx0 + 3, cy0 + i * cy1); S := IntToStr(-i); t := Canvas.TextHeight(S) div 2; TextOut(cx0 + 5, cy0 + i * cy1 - t, S); end; end; end; procedure TMForm.Btn_buildClick(Sender: TObject); var i: Integer; begin x0 := StrToFloatDef(Ed_x0.text, 0); xN := StrToFloatDef(Ed_xn.text, 0); h := StrToFloatDef(Ed_h.text, 0); a := StrToFloatDef(Ed_a.Text, 0); b := StrToFloatDef(Ed_b.Text, 0); c := StrToFloatDef(Ed_c.Text, 0); d := StrToFloatDef(Ed_d.Text, 0); e := StrToFloatDef(Ed_e.text, 0); NV := round((xN - x0) / h) + 1; if (xN < x0) then ShowMessage('Неверно заданы концы отрезка!'); if (h <= 0) then ShowMessage('Значение шага должно быть больше 0'); if (StrToFloat(Ed_e.text) <= 0) then ShowMessage('Значение величины разброса занчений должно быть больше 0'); if (NV < 5) then ShowMessage('Для данного метода количество точек должно быть не меньше 5'); // все значения корректны ClearImage(Image); Btn_Scatter.Enabled := true; Btn_clear.Enabled := true; x[1] := x0; y[1] := a*sqr(x0)*x0 + b*sqr(x0) + c*x0 + d; for i := 2 to NV do begin x[i] := x[i-1] + h; y[i] := a*sqr(x[i])*x[i] + b*sqr(x[i]) + c*x[i] + d; end; MakeCoords; MakeLine(clBlack); end; procedure TMForm.MakeCoords; var y_min, y_max: TType; i: Integer; begin // поиск минимального и максимального элементов в Y y_min := y[1]; y_max := y[1]; for i := 2 to NV do if (y[i] > y_max) then y_max := y[i] else if (y[i] < y_min) then y_min := y[i]; DrawCoordinates(x0,y_min,xN,y_max,Image.Width,Image.Height,Image.Canvas); end; procedure TMForm.MakeLine(Color: TColor); var i: Integer; begin Dot(x[1],y[1],Image.Canvas,clBlack); for i := 2 to NV do begin Line(x[i-1],y[i-1],x[i],y[i],Image.Canvas,Color); Dot(x[i],y[i],Image.Canvas,Color); end; end; procedure TMForm.Btn_clearClick(Sender: TObject); begin ClearImage(Image); Btn_build.Enabled:=true; Btn_smooth.Enabled:=false; Btn_scatter.Enabled:=false; end; // выполение разброса procedure TMForm.Btn_scatterClick(Sender: TObject); var i: Integer; k: real; begin Randomize; for i:= 2 to NV-1 do begin k := Random; if Random > 0.5 then k := -k; y[i] := y[i] + k * e; end; MakeLine(clRed); Btn_build.Enabled:=false; Btn_smooth.Enabled:=true; end; procedure TMForm.Btn_smoothClick(Sender: TObject); begin Smooth(nv, y, z, 5); y:=z; MakeLine(clGreen); end; end.
unit v_msgtype_radio; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ExtCtrls; type { TxPLMsgTypeRadio } TxPLMsgTypeRadio = class(TRadioGroup) private FShowAny : boolean; //function GetIsValid: boolean; //function GetMessageType : string; //procedure SetMessageType(const AValue: string); //procedure SetShowAny(const AValue: boolean); public constructor create(aOwner : TComponent); override; //property ItemIndex : tsMsgType read GetMessageType write SetMessageType; //property IsValid : boolean read GetIsValid; published property bShowAny : boolean read FShowAny; // write SetShowAny; end; procedure Register; implementation //uses u_xpl_common; procedure Register; begin RegisterComponents('xPL Components',[TxPLMsgTypeRadio]); end; { TxPLMsgTypeRadio } (*function TxPLMsgTypeRadio.GetMessageType: tsMsgType; begin Result := MsgTypeToString(TxPLMessageType(ItemIndex)); //K_MSG_TYPE_DESCRIPTORS[inherited ItemIndex]; end;*) //function TxPLMsgTypeRadio.GetIsValid: boolean; //begin // result := true; //end; (*procedure TxPLMsgTypeRadio.SetMessageType(const AValue: tsMsgType); begin inherited ItemIndex := Ord(tsMsgType); end;*) //procedure TxPLMsgTypeRadio.SetShowAny(const AValue: boolean); //var mt : TxPLMessageType; //begin // FShowAny := aValue; // Items.Clear ; // for mt:=Low(TxPLMessageType) to High(TxPLMessageType) do // Items.Add(MsgTypeToStr(mt)); // if FShowAny then Items.Add('Any'); // Columns := Items.Count ; //end; constructor TxPLMsgTypeRadio.create(aOwner: TComponent); begin inherited create(aOwner); Height := 37; Width := 256; end; end.
{ GS1 interface library for FPC and Lazarus Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit CrptGlobalUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, CrptGlobalTypes; function CISStatusDecode(AStatus:string):TCISStatus; function CISStatusEncode(AStatus:TCISStatus):string; function DocStatusDecode(AStatus:string):TDocStatus; function DocStatusEncode(AStatus:TDocStatus):string; implementation function CISStatusDecode(AStatus: string): TCISStatus; begin AStatus:=UpperCase(AStatus); if AStatus = 'EMITTED' then Result:=EMITTED else if AStatus = 'APPLIED' then Result:=APPLIED else if AStatus = 'INTRODUCED' then Result:=INTRODUCED else if AStatus = 'WRITTEN_OFF' then Result:=WRITTEN_OFF else if AStatus = 'RETIRED' then Result:=RETIRED else if AStatus = 'RESERVED_NOT_USED' then Result:=RESERVED_NOT_USED else if AStatus = 'INTRODUCED_RETURNED' then Result:=INTRODUCED_RETURNED else if AStatus = 'DISAGGREGATED' then Result:=DISAGGREGATED else if AStatus = 'WAIT_SHIPMENT' then Result:=WAIT_SHIPMENT else if AStatus = 'EXPORTED' then Result:=EXPORTED else if AStatus = 'LOAN_RETIRED' then Result:=LOAN_RETIRED else if AStatus = 'REMARK_RETIRED' then Result:=REMARK_RETIRED else if AStatus = 'APPLIED_NOT_PAID' then Result:=APPLIED_NOT_PAID else if AStatus = 'FTS_RESPOND_NOT_OK' then Result:=FTS_RESPOND_NOT_OK else if AStatus = 'FTS_RESPOND_WAITING' then Result:=FTS_RESPOND_WAITING else if AStatus = 'FTS_CONTROL' then Result:=FTS_CONTROL else Result:=CISStatusError end; function CISStatusEncode(AStatus: TCISStatus): string; begin case AStatus of CISStatusError: Result:='Ошибка'; EMITTED: Result:='Эмитирован'; APPLIED: Result:='Нанесён'; INTRODUCED: Result:='Введен в оборот'; WRITTEN_OFF: Result:='Списан'; RETIRED: Result:='Выведен из оборота Withdrawn'; RESERVED_NOT_USED: Result:='Зарезервировано. Не использовать'; INTRODUCED_RETURNED: Result:='Возвращён в оборот'; DISAGGREGATED: Result:='Дезагрегирован'; WAIT_SHIPMENT: Result:='Ожидает подтверждения приемки'; EXPORTED: Result:='Используется для документов экспорта'; LOAN_RETIRED: Result:='Выведен из оборота по договору рассрочки'; REMARK_RETIRED: Result:='Выведен из оборота при перемаркировке'; APPLIED_NOT_PAID: Result:='Нанесён, не оплачен'; FTS_RESPOND_NOT_OK: Result:='Отрицательное решение ФТС'; FTS_RESPOND_WAITING: Result:='Ожидает подтверждение ФТС'; FTS_CONTROL: Result:='На контроле ФТС'; end; end; function DocStatusDecode(AStatus: string): TDocStatus; var I: TDocStatus; begin Result:=UNDEFINED; AStatus:=UpperCase(AStatus); for I in TDocStatus do if DocStatusStr[I] = AStatus then Exit(I); end; function DocStatusEncode(AStatus: TDocStatus): string; begin case AStatus of UNDEFINED: Result:='Не определён'; IN_PROGRESS: Result:='Проверяется'; CHECKED_OK: Result:='Оформлен'; CHECKED_NOT_OK: Result:='Ошибка при проверке'; PROCESSING_ERROR: Result:='Ошибка при обработке'; CANCELLED: Result:='Документ отменён'; WAIT_ACCEPTANCE: Result:='Ожидание приемку'; WAIT_PARTICIPANT_REGISTRATION: Result:='Ожидает регистрации участника в ГИС МТ'; WAIT_FOR_CONTINUATION: Result:='Ожидает продолжения процессинга документа'; ACCEPTED: Result:='Принят'; end; end; end.
unit FC.StockChart.UnitTask.TradeLine.Snapshot; interface {$I Compiler.inc} uses SysUtils,Classes, BaseUtils, Serialization, Dialogs, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation type TStockUnitTaskExpertLineSnapshot = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskExpertLineSnapshot } function TStockUnitTaskExpertLineSnapshot.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorTradeLine); if result then aOperationName:='Make Snapshot'; end; procedure TStockUnitTaskExpertLineSnapshot.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); var s: string; aExpertLine : ISCIndicatorTradeLine; aShapshot: ISCIndicatorTradeLineSnapshot; aIndicatorInfo : ISCIndicatorInfo; begin aExpertLine:=aIndicator as ISCIndicatorTradeLine; aIndicatorInfo:=IndicatorFactory.GetIndicatorInfo(ISCIndicatorTradeLineSnapshot); s:=aExpertLine.Caption+' - Snapshot['+DateTimeToStr(Now)+']'; if InputQuery('Snapshot for expert line '+aIndicator.Caption, 'Input snapshot name',s) then begin aShapshot:= aStockChart.CreateIndicator(aIndicatorInfo,false) as ISCIndicatorTradeLineSnapshot; aShapshot.Snap(aExpertLine); (aShapshot as ISCWritableName).SetName(s); aExpertLine.Clear; end; end; initialization StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskExpertLineSnapshot.Create); end.
unit FIToolkit.Commons.FiniteStateMachine.Exceptions; interface uses System.SysUtils; type EFiniteStateMachineError = class abstract (Exception); EExecutionInProgress = class (EFiniteStateMachineError); ETransitionNotFound = class (EFiniteStateMachineError); implementation end.
unit Params_1; interface implementation var G1, G2: Int32; procedure P1(A, B: Int32); begin G1 := A; G2 := B; end; procedure Test; begin P1(222, 333); end; initialization Test(); finalization Assert(G1 = 222); Assert(G2 = 333); end.
unit SHA224; {SHA224 - 224 bit Secure Hash Function} interface (************************************************************************* DESCRIPTION : SHA224 - 224 bit Secure Hash Function REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP EXTERNAL DATA : --- MEMORY USAGE : --- DISPLAY MODE : --- REFERENCES : - Latest specification of Secure Hash Standard: http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf - Test vectors and intermediate values: http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf Version Date Author Modification ------- -------- ------- ------------------------------------------ 0.10 02.01.04 W.Ehrhardt Initial version 0.11 05.03.04 we Update fips180-2 URL 0.12 26.02.05 we With {$ifdef StrictLong} 0.13 05.05.05 we $R- for StrictLong, D9: errors if $R+ even if warnings off 0.14 17.12.05 we Force $I- in SHA224File 0.15 15.01.06 we uses Hash unit and THashDesc 0.16 18.01.06 we Descriptor fields HAlgNum, HSig 0.17 22.01.06 we Removed HSelfTest from descriptor 0.18 11.02.06 we Descriptor as typed const 0.19 07.08.06 we $ifdef BIT32: (const fname: shortstring...) 0.20 22.02.07 we values for OID vector 0.21 30.06.07 we Use conditional define FPC_ProcVar 0.22 02.05.08 we Bit-API: SHA224FinalBits/Ex 0.23 05.05.08 we THashDesc constant with HFinalBit field 0.24 12.11.08 we uses BTypes and Str255 0.25 11.03.12 we Updated references 0.26 16.08.15 we Removed $ifdef DLL / stdcall 0.27 15.05.17 we adjust OID to new MaxOIDLen 0.28 29.11.17 we SHA224File - fname: string **************************************************************************) (*------------------------------------------------------------------------- (C) Copyright 2002-2017 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. ----------------------------------------------------------------------------*) {$i STD.INC} uses BTypes,Hash,SHA256; procedure SHA224Init(var Context: THashContext); {-initialize context} procedure SHA224Update(var Context: THashContext; Msg: pointer; Len: word); {-update context with Msg data} procedure SHA224UpdateXL(var Context: THashContext; Msg: pointer; Len: longint); {-update context with Msg data} procedure SHA224Final(var Context: THashContext; var Digest: TSHA224Digest); {-finalize SHA224 calculation, clear context} procedure SHA224FinalEx(var Context: THashContext; var Digest: THashDigest); {-finalize SHA224 calculation, clear context} procedure SHA224FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer); {-finalize SHA224 calculation with bitlen bits from BData (big-endian), clear context} procedure SHA224FinalBits(var Context: THashContext; var Digest: TSHA224Digest; BData: byte; bitlen: integer); {-finalize SHA224 calculation with bitlen bits from BData (big-endian), clear context} function SHA224SelfTest: boolean; {-self test for string from SHA224 document} procedure SHA224Full(var Digest: TSHA224Digest; Msg: pointer; Len: word); {-SHA224 of Msg with init/update/final} procedure SHA224FullXL(var Digest: TSHA224Digest; Msg: pointer; Len: longint); {-SHA224 of Msg with init/update/final} procedure SHA224File({$ifdef CONST} const {$endif} fname: string; var Digest: TSHA224Digest; var buf; bsize: word; var Err: word); {-SHA224 of file, buf: buffer with at least bsize bytes} implementation const SHA224_BlockLen = 64; {2.16.840.1.101.3.4.2.4} {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) hashAlgs(2) sha224(4)} const SHA224_OID : TOID_Vec = (2,16,840,1,101,3,4,2,4,-1,-1); {Len=9} {$ifndef VER5X} const SHA224_Desc: THashDesc = ( HSig : C_HashSig; HDSize : sizeof(THashDesc); HDVersion : C_HashVers; HBlockLen : SHA224_BlockLen; HDigestlen: sizeof(TSHA224Digest); {$ifdef FPC_ProcVar} HInit : @SHA224Init; HFinal : @SHA224FinalEx; HUpdateXL : @SHA224UpdateXL; {$else} HInit : SHA224Init; HFinal : SHA224FinalEx; HUpdateXL : SHA224UpdateXL; {$endif} HAlgNum : longint(_SHA224); HName : 'SHA224'; HPtrOID : @SHA224_OID; HLenOID : 9; HFill : 0; {$ifdef FPC_ProcVar} HFinalBit : @SHA224FinalBitsEx; {$else} HFinalBit : SHA224FinalBitsEx; {$endif} HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) ); {$else} var SHA224_Desc: THashDesc; {$endif} {$ifdef BIT16} {$F-} {$endif} {---------------------------------------------------------------------------} procedure SHA224Init(var Context: THashContext); {-initialize context} {$ifdef StrictLong} {$warnings off} {$R-} {avoid D9 errors!} {$endif} const SIV: array[0..7] of longint = ($c1059ed8, $367cd507, $3070dd17, $f70e5939, $ffc00b31, $68581511, $64f98fa7, $befa4fa4); {$ifdef StrictLong} {$warnings on} {$ifdef RangeChecks_on} {$R+} {$endif} {$endif} begin {Clear context} fillchar(Context,sizeof(Context),0); move(SIV, Context.Hash, sizeof(SIV)); end; {---------------------------------------------------------------------------} procedure SHA224UpdateXL(var Context: THashContext; Msg: pointer; Len: longint); {-update context with Msg data} begin SHA256UpdateXL(Context, Msg, Len); end; {---------------------------------------------------------------------------} procedure SHA224Update(var Context: THashContext; Msg: pointer; Len: word); {-update context with Msg data} begin SHA256UpdateXL(Context, Msg, Len); end; {---------------------------------------------------------------------------} procedure SHA224FinalEx(var Context: THashContext; var Digest: THashDigest); {-finalize SHA224 calculation, clear context} begin SHA256FinalEx(Context, Digest); end; {---------------------------------------------------------------------------} procedure SHA224Final(var Context: THashContext; var Digest: TSHA224Digest); {-finalize SHA224 calculation, clear context} var tmp: THashDigest; begin SHA256FinalEx(Context, tmp); move(tmp, Digest, sizeof(Digest)); end; {---------------------------------------------------------------------------} procedure SHA224FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer); {-finalize SHA224 calculation with bitlen bits from BData (big-endian), clear context} begin SHA256FinalBitsEx(Context, Digest, BData, bitlen); end; {---------------------------------------------------------------------------} procedure SHA224FinalBits(var Context: THashContext; var Digest: TSHA224Digest; BData: byte; bitlen: integer); {-finalize SHA224 calculation with bitlen bits from BData (big-endian), clear context} var tmp: THashDigest; begin SHA256FinalBitsEx(Context, tmp, BData, bitlen); move(tmp, Digest, sizeof(Digest)); end; {---------------------------------------------------------------------------} function SHA224SelfTest: boolean; {-self test for string from SHA224 document} const s1: string[3] = 'abc'; s2: string[56] = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'; D1: TSHA224Digest = ($23, $09, $7d, $22, $34, $05, $d8, $22, $86, $42, $a4, $77, $bd, $a2, $55, $b3, $2a, $ad, $bc, $e4, $bd, $a0, $b3, $f7, $e3, $6c, $9d, $a7); D2: TSHA224Digest = ($75, $38, $8b, $16, $51, $27, $76, $cc, $5d, $ba, $5d, $a1, $fd, $89, $01, $50, $b0, $c6, $45, $5c, $b4, $f5, $8b, $19, $52, $52, $25, $25); D3: TSHA224Digest = ($d3, $fe, $57, $cb, $76, $cd, $d2, $4e, $9e, $b2, $3e, $7e, $15, $68, $4e, $03, $9c, $75, $45, $9b, $ea, $ae, $10, $0f, $89, $71, $2e, $9d); D4: TSHA224Digest = ($b0, $4c, $42, $3c, $90, $91, $ff, $5b, $b3, $2e, $a4, $b0, $06, $3e, $98, $81, $46, $33, $35, $0c, $1b, $c2, $bd, $97, $4f, $77, $6f, $d2); var Context: THashContext; Digest : TSHA224Digest; function SingleTest(s: Str127; TDig: TSHA224Digest): boolean; {-do a single test, const not allowed for VER<7} { Two sub tests: 1. whole string, 2. one update per char} var i: integer; begin SingleTest := false; {1. Hash complete string} SHA224Full(Digest, @s[1],length(s)); {Compare with known value} if not HashSameDigest(@SHA224_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit; {2. one update call for all chars} SHA224Init(Context); for i:=1 to length(s) do SHA224Update(Context,@s[i],1); SHA224Final(Context,Digest); {Compare with known value} if not HashSameDigest(@SHA224_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit; SingleTest := true; end; begin SHA224SelfTest := false; {1 Zero bit from NESSIE test vectors, currently from shatest} SHA224Init(Context); SHA224FinalBits(Context,Digest,0,1); if not HashSameDigest(@SHA224_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit; {4 hightest bits of $50, D4 calculated with program shatest from RFC 4634} SHA224Init(Context); SHA224FinalBits(Context,Digest,$50,4); if not HashSameDigest(@SHA224_Desc, PHashDigest(@Digest), PHashDigest(@D4)) then exit; {strings from SHA224 document} SHA224SelfTest := SingleTest(s1, D1) and SingleTest(s2, D2) end; {---------------------------------------------------------------------------} procedure SHA224FullXL(var Digest: TSHA224Digest; Msg: pointer; Len: longint); {-SHA224 of Msg with init/update/final} var Context: THashContext; begin SHA224Init(Context); SHA224UpdateXL(Context, Msg, Len); SHA224Final(Context, Digest); end; {---------------------------------------------------------------------------} procedure SHA224Full(var Digest: TSHA224Digest; Msg: pointer; Len: word); {-SHA224 of Msg with init/update/final} begin SHA224FullXL(Digest, Msg, Len); end; {---------------------------------------------------------------------------} procedure SHA224File({$ifdef CONST} const {$endif} fname: string; var Digest: TSHA224Digest; var buf; bsize: word; var Err: word); {-SHA224 of file, buf: buffer with at least bsize bytes} var tmp: THashDigest; begin HashFile(fname, @SHA224_Desc, tmp, buf, bsize, Err); move(tmp, Digest, sizeof(Digest)); end; begin {$ifdef VER5X} fillchar(SHA224_Desc, sizeof(SHA224_Desc), 0); with SHA224_Desc do begin HSig := C_HashSig; HDSize := sizeof(THashDesc); HDVersion := C_HashVers; HBlockLen := SHA224_BlockLen; HDigestlen:= sizeof(TSHA224Digest); HInit := SHA224Init; HFinal := SHA224FinalEx; HUpdateXL := SHA224UpdateXL; HAlgNum := longint(_SHA224); HName := 'SHA224'; HPtrOID := @SHA224_OID; HLenOID := 9; HFinalBit := SHA224FinalBitsEx; end; {$endif} RegisterHash(_SHA224, @SHA224_Desc); end.
unit Engine; interface uses Classes, StrUtils; type TEngine = class public Output: TStringList; constructor Create; destructor Destroy; override; procedure AddSourceFile(const FileName: String); procedure Reload(); private FSourceFiles: TStringList; end; implementation uses SourceFile; constructor TEngine.Create; begin FSourceFiles := TStringList.Create; FSourceFiles.Sorted := True; FSourceFiles.Duplicates := dupIgnore; Output := TStringList.Create; end; destructor TEngine.Destroy; begin FSourceFiles.Free; Output.Free; end; procedure TEngine.AddSourceFile(const FileName: String); begin FSourceFiles.Add(FileName); end; procedure TEngine.Reload(); var I: Integer; FileName: String; SourceFile: TSourceFile; begin Output.Clear; // intended to work on a running system, so it only adds and replaces vmt entries and such, it deletes no methods or types and doesn't delete compiled code. //I := 0; // while True do for I := 0 to FSourceFiles.Count-1 do begin FileName := FSourceFiles[I]; Output.Add(FileName); SourceFile := TSourceFile.Create; SourceFile.ReadFromFile(FileName); Output.AddStrings(SourceFile.FErrors); // SourceFile.FOutput.WriteTo(Output); SourceFile.Free; end; end; end.
unit Support.Sandisk; interface uses SysUtils, Support, Device.SMART.List; type TSandiskNSTSupport = class sealed(TNSTSupport) private InterpretingSMARTValueList: TSMARTValueList; function GetFullSupport: TSupportStatus; function GetTotalWrite: TTotalWrite; function IsProductOfSandisk: Boolean; function IsX110: Boolean; public function GetSupportStatus: TSupportStatus; override; function GetSMARTInterpreted(SMARTValueList: TSMARTValueList): TSMARTInterpreted; override; end; implementation { TSandiskNSTSupport } function TSandiskNSTSupport.IsX110: Boolean; begin result := (Pos('SANDISK', Identify.Model) > 0) and (Pos('SD6SB1', Identify.Model) > 0); end; function TSandiskNSTSupport.IsProductOfSandisk: Boolean; begin result := IsX110; end; function TSandiskNSTSupport.GetFullSupport: TSupportStatus; begin result.Supported := Supported; result.FirmwareUpdate := true; result.TotalWriteType := TTotalWriteType.WriteSupportedAsValue; end; function TSandiskNSTSupport.GetSupportStatus: TSupportStatus; begin result.Supported := NotSupported; if IsProductOfSandisk then result := GetFullSupport; end; function TSandiskNSTSupport.GetTotalWrite: TTotalWrite; const GiBToMiB = 1024; IDOfHostWrite = 241; var RAWValue: UInt64; begin result.InValue.TrueHostWriteFalseNANDWrite := true; RAWValue := InterpretingSMARTValueList.GetRAWByID(IDOfHostWrite); result.InValue.ValueInMiB := RAWValue * GiBToMiB; end; function TSandiskNSTSupport.GetSMARTInterpreted( SMARTValueList: TSMARTValueList): TSMARTInterpreted; const IDOfEraseError = 172; IDOfReplacedSector = 5; IDofUsedHour = 9; ReplacedSectorThreshold = 50; EraseErrorThreshold = 10; begin InterpretingSMARTValueList := SMARTValueList; result.TotalWrite := GetTotalWrite; result.UsedHour := InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour); result.ReadEraseError.TrueReadErrorFalseEraseError := false; result.ReadEraseError.Value := InterpretingSMARTValueList.GetRAWByID(IDOfEraseError); result.SMARTAlert.ReadEraseError := result.ReadEraseError.Value >= EraseErrorThreshold; result.ReplacedSectors := InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector); result.SMARTAlert.ReplacedSector := result.ReplacedSectors >= ReplacedSectorThreshold; end; end.
{ TWebChromiumFMX class ES: Clase para la manipulación del contenido de un navegador TChromiumFMX EN: Class for management the contents of a browser TChromiumFMX ========================================================================= History: ver 1.0.1 ES: error: TWebChromiumFMX -> método WebFormFieldValue corregido (GC: issue 6). EN: bug: TWebChromiumFMX -> WebFormFieldValue method (GC: issue 6). ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con el navegador chromium y FireMonkey EN: new: documentation new: now compatible with chromium browser and FireMonkey ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT DEVELOPERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com } {*------------------------------------------------------------------------------ The WebControlFMX unit includes the necessary classes to encapsulate the access to a browser with FMX framework. This browser can be a TChromiumFMX. You can de/activate this browsers into the gmlib.inc file. By default, only the TWebBrowser is active. @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit WebControlFMX incluye las clases necesarias para encapsular el acceso a un navegador mediante el framework de la FMX. Este navegador puede ser un TChromiumFMX. Puedes des/activar estos navegadores desde el archivo gmlib.inc. Por defecto, sólo está activo el TWebBrowser. @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} unit WebControlFMX; {.$DEFINE CHROMIUMFMX} {$I ..\gmlib.inc} interface {$IFDEF CHROMIUMFMX} uses ceffmx, System.SysUtils, WebControl; type {*------------------------------------------------------------------------------ TWebChromiumFMX class is a specialization of TCustomWeb for a TChromiumFMX browser. For that the compiler take into account this class, must be activated in the file gmlib.inc -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La clase TWebChromiumFMX es una especialización de TCustomWeb para el navegador TChromiumFMX. Para que el compilador tenga en cuenta esta clase debes activarla en el fichero gmlib.inc -------------------------------------------------------------------------------} TWebChromiumFMX = class(TCustomWebChromium) protected function WebFormFieldValue(const FormIdx: Integer; const FieldName: string): string; overload; override; public {*------------------------------------------------------------------------------ Constructor of the class @param WebBrowser is the browser to manipulate -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase @param WebBrowser es el navegador a manipular -------------------------------------------------------------------------------} constructor Create(WebBrowser: TChromiumFMX); reintroduce; virtual; procedure WebFormNames; override; procedure WebFormFields(const FormIdx: Integer); overload; override; procedure WebFormSetFieldValue(const FormIdx: Integer; const FieldName, NewValue: string); overload; override; procedure WebFormSubmit(const FormIdx: Integer); overload; override; function WebHTMLCode: string; override; procedure WebPrintWithoutDialog; override; procedure WebPrintWithDialog; override; procedure WebPrintPageSetup; override; procedure WebPreview; override; procedure SaveToJPGFile(FileName: TFileName = ''); override; {*------------------------------------------------------------------------------ Set a browser @param Browser browser to set -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Establece un navegador @param Browser navegador a establecer -------------------------------------------------------------------------------} procedure SetBrowser(Browser: TChromiumFMX); reintroduce; virtual; end; {$ENDIF} implementation {$IFDEF CHROMIUMFMX} uses ceflib, FMX.Types, FMX.Forms; { TWebChromiumFMX } constructor TWebChromiumFMX.Create(WebBrowser: TChromiumFMX); begin inherited Create(WebBrowser); end; procedure TWebChromiumFMX.SaveToJPGFile(FileName: TFileName); var bmp: FMX.Types.TBitmap; begin if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); bmp := FMX.Types.TBitMap.Create(0,0); try ceffmx.CefGetBitmap(TChromiumFMX(FWebBrowser).Browser, PET_VIEW, bmp); bmp.SaveToFile(FileName); finally FreeAndNil(bmp); end; end; procedure TWebChromiumFMX.SetBrowser(Browser: TChromiumFMX); begin FWebBrowser := Browser; end; procedure TWebChromiumFMX.WebFormFields(const FormIdx: Integer); var Finish: Boolean; FormName: string; begin Fields.Clear; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if FForms.Count = 0 then raise Exception.Create('Property Forms not initialized or empty.'); if (FormIdx < 0) or (FormIdx >= FForms.Count) then raise Exception.Create('Index out of bounds.'); FormName := FForms[FormIdx]; Finish := False; TChromiumFMX(FWebBrowser).Browser.MainFrame.VisitDomProc( procedure (const doc: ICefDomDocument) begin FFields.CommaText := GetFieldsName(doc.GetElementById(FormName)); Finish := True; end ); repeat Application.ProcessMessages until (Finish); end; function TWebChromiumFMX.WebFormFieldValue(const FormIdx: Integer; const FieldName: string): string; var Finish: Boolean; FormName: string; Temp: string; begin inherited; Temp := ''; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if FForms.Count = 0 then raise Exception.Create('Property Forms not initialized or empty.'); if (FormIdx < 0) or (FormIdx >= FForms.Count) then raise Exception.Create('Index out of bounds.'); FormName := FForms[FormIdx]; TChromiumFMX(FWebBrowser).Browser.MainFrame.VisitDomProc( procedure (const doc: ICefDomDocument) begin Temp := GetFieldValue(doc.GetElementById(FormName), FieldName); Finish := True; end ); repeat Application.ProcessMessages until (Finish); Result := Temp; if Pos('&nbsp;', Result) > 0 then Result := ReplaceText(Result, '&nbsp;', ' '); end; procedure TWebChromiumFMX.WebFormNames; var Finish: Boolean; begin FForms.Clear; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); Finish := False; TChromiumFMX(FWebBrowser).Browser.MainFrame.VisitDomProc( procedure (const doc: ICefDomDocument) begin FForms.CommaText := GetFormsName(doc.Body); Finish := True; end ); repeat Application.ProcessMessages until (Finish); end; procedure TWebChromiumFMX.WebFormSetFieldValue(const FormIdx: Integer; const FieldName, NewValue: string); var Finish: Boolean; FormName: string; begin inherited; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if FForms.Count = 0 then raise Exception.Create('Property Forms not initialized or empty.'); if (FormIdx < 0) or (FormIdx >= FForms.Count) then raise Exception.Create('Index out of bounds.'); FormName := FForms[FormIdx]; TChromiumFMX(FWebBrowser).Browser.MainFrame.VisitDomProc( procedure (const doc: ICefDomDocument) begin SetFieldValue(doc.GetElementById(FormName), FieldName, NewValue); Finish := True; end ); repeat Application.ProcessMessages until (Finish); end; procedure TWebChromiumFMX.WebFormSubmit(const FormIdx: Integer); var FormName: string; begin inherited; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if FForms.Count = 0 then raise Exception.Create('Property Forms not initialized or empty.'); if (FormIdx < 0) or (FormIdx >= FForms.Count) then raise Exception.Create('Index out of bounds.'); FormName := FForms[FormIdx]; if TChromiumFMX(FWebBrowser).Browser <> nil then TChromiumFMX(FWebBrowser).Browser.MainFrame.ExecuteJavaScript( 'document.forms["' + FormName + '"].submit();', '', 0); end; function TWebChromiumFMX.WebHTMLCode: string; begin Result := ''; if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if TChromiumFMX(FWebBrowser).Browser = nil then Exit; Result := TChromiumFMX(FWebBrowser).Browser.MainFrame.Source; end; procedure TWebChromiumFMX.WebPreview; begin raise Exception.Create('This method is not implemented for this class. Call WebPrintWithDialog in his stead.'); end; procedure TWebChromiumFMX.WebPrintPageSetup; begin raise Exception.Create('This method is not implemented for this class. Call WebPrintWithDialog in his stead.'); end; procedure TWebChromiumFMX.WebPrintWithDialog; begin if not Assigned(FWebBrowser) then raise Exception.Create('WebBrowser not assigned'); if not (FWebBrowser is TChromiumFMX) then raise Exception.Create('The WebBrowser property is not a TChromiumFMX.'); if TChromiumFMX(FWebBrowser).Browser <> nil then TChromiumFMX(FWebBrowser).Browser.MainFrame.Print; end; procedure TWebChromiumFMX.WebPrintWithoutDialog; begin raise Exception.Create('This method is not implemented for this class. Call WebPrintWithDialog in his stead.'); end; {$ENDIF} end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Support } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} unit WebBrokerSOAP; interface uses Classes, HTTPApp, AutoDisp, Masks, WebNode, SoapHTTPDisp; type // webbroker component that dispatches soap requests THTTPSoapDispatcher = class(THTTPSoapDispatchNode, IWebDispatch) private FWebDispatch: TWebDispatch; procedure SetWebDispatch(const Value: TWebDispatch); protected function DispatchEnabled: Boolean; function DispatchMask: TMask; function DispatchMethodType: TMethodType; function DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property WebDispatch: TWebDispatch read FWebDispatch write SetWebDispatch; end; implementation uses SysUtils, InvokeRegistry, SoapConst, Controls; { THTTPSoapDispatcher } constructor THTTPSoapDispatcher.Create(AOwner: TComponent); begin inherited Create(AOwner); FWebDispatch := TWebDispatch.Create(Self); FWebDispatch.PathInfo := 'soap*'; { do not localize } end; destructor THTTPSoapDispatcher.Destroy; begin FWebDispatch.Free; inherited Destroy; end; procedure THTTPSoapDispatcher.SetWebDispatch(const Value: TWebDispatch); begin FWebDispatch.Assign(Value); end; function THTTPSoapDispatcher.DispatchEnabled: Boolean; begin Result := True; end; function THTTPSoapDispatcher.DispatchMask: TMask; begin Result := FWebDispatch.Mask; end; function THTTPSoapDispatcher.DispatchMethodType: TMethodType; begin Result := FWebDispatch.MethodType; end; { DO NOT LOCALIZE } const DefException = SSoapXMLHeader + ' <SOAP-ENV:Envelope' + ' ' + 'xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" >' + '<SOAP-ENV:Body> ' + '<SOAP-ENV:Fault> ' + '<faultcode>SOAP-ENV:Server</faultcode>' + '<faultstring>%s</faultstring>' + '</SOAP-ENV:Fault>' + '</SOAP-ENV:Body>' + '</SOAP-ENV:Envelope>'; function THTTPSoapDispatcher.DispatchRequest(Sender: TObject; Request: TWebRequest; Response: TWebResponse): Boolean; var Path, SoapAction, WResp: WideString; Stream, RStream: TMemoryStream; BytesRead, ChunkSize: Integer; Buffer: array of Byte; Size: Integer; begin try try if not Assigned(FSoapDispatcher) and not ((csDesigning in ComponentState) or (csLoading in ComponentState)) then raise Exception.Create(SNoDispatcher); SoapAction := Request.GetFieldByName(SHTTPSoapAction); Path := Request.PathInfo; Stream := TMemoryStream.Create; try BytesRead := Length(Request.Content); if BytesRead < Request.ContentLength then begin SetLength(Buffer, Request.ContentLength); Stream.Write(Request.Content[1], BytesRead); repeat ChunkSize := Request.ReadClient(Buffer, Request.ContentLength - BytesRead); if ChunkSize > 0 then begin Stream.Write(Buffer, ChunkSize); Inc(BytesRead, ChunkSize); end; until ChunkSize = -1; end else Stream.Write(Request.Content[1], BytesRead); Stream.Position := 0; RStream := TMemoryStream.Create; try FSoapDispatcher.DispatchSoap(Path, SoapAction, Stream, RStream); RStream.Position := 0; Size := RStream.Size; SetLength(WResp, (Size div 2)); RStream.ReadBuffer(WResp[1], Size); Response.Content := UTF8Encode(WResp); Response.ContentType := 'text/xml'; Result := True; finally RStream.Free; end; finally Stream.Free; end; except on E: Exception do begin Response.Content := UTF8Encode(Format(DefException, [E.Message])); Response.ContentType := 'text/xml'; Result := True; end; end; except Result := False; // swallow any unexpected exception, it will bring down some web servers end; end; initialization GroupDescendentsWith(THTTPSoapDispatcher, Controls.TControl); end.
procedure SetRandomColor; begin SetColorRGB(RandomRange(0, 255), RandomRange(0, 255), RandomRange(0, 255)); end;
{******************************************************************************} { } { Delphi JOSE Library } { Copyright (c) 2015 Paolo Rossi } { https://github.com/paolo-rossi/delphi-jose-jwt } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit JWTDemo.Form.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdGlobal, System.Generics.Defaults, System.Generics.Collections, Vcl.ExtCtrls, Vcl.ComCtrls, JOSE.Core.JWT, JOSE.Core.JWS, JOSE.Core.JWK, JOSE.Core.JWA, JOSE.Types.JSON; type TMyClaims = class(TJWTClaims) private function GetAppIssuer: string; procedure SetAppIssuer(const Value: string); public property AppIssuer: string read GetAppIssuer write SetAppIssuer; end; TfrmMain = class(TForm) mmoJSON: TMemo; mmoCompact: TMemo; Label1: TLabel; Label2: TLabel; PageControl1: TPageControl; tsSimple: TTabSheet; tsCustom: TTabSheet; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; edtIssuer: TLabeledEdit; edtIssuedAtTime: TDateTimePicker; edtNotBeforeDate: TDateTimePicker; edtExpiresDate: TDateTimePicker; chkIssuer: TCheckBox; chkIssuedAt: TCheckBox; chkExpires: TCheckBox; chkNotBefore: TCheckBox; btnCustomJWS: TButton; edtIssuedAtDate: TDateTimePicker; edtExpiresTime: TDateTimePicker; edtNotBeforeTime: TDateTimePicker; cbbAlgorithm: TComboBox; btnBuild: TButton; btnTJOSEBuild: TButton; btnTJOSEVerify: TButton; btnTestClaims: TButton; procedure btnTJOSEVerifyClick(Sender: TObject); procedure btnBuildClick(Sender: TObject); procedure btnTestClaimsClick(Sender: TObject); procedure btnTJOSEBuildClick(Sender: TObject); private //FToken: TJWT; public { Public declarations } end; var frmMain: TfrmMain; implementation uses System.Rtti, JOSE.Types.Bytes, JOSE.Core.Builder; {$R *.dfm} procedure TfrmMain.btnTJOSEVerifyClick(Sender: TObject); var LKey: TJWK; LToken: TJWT; begin LKey := TJWK.Create('secret'); // Unpack and verify the token LToken := TJOSE.Verify(LKey, 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJXaVJMIn0.w3BAZ_GwfQYY6dkS8xKUNZ_sOnkDUMELxBN0mKKNhJ4'); if Assigned(LToken) then begin try if LToken.Verified then mmoJSON.Lines.Add('Token signature is verified') else mmoJSON.Lines.Add('Token signature is not verified') finally LToken.Free; end; end; end; procedure TfrmMain.btnBuildClick(Sender: TObject); var LToken: TJWT; LSigner: TJWS; LKey: TJWK; LClaims: TMyClaims; begin LToken := TJWT.Create(TJWTClaims); try LToken.Claims.Issuer := 'WiRL REST Library'; LToken.Claims.IssuedAt := Now; LToken.Claims.Expiration := Now + 1; LSigner := TJWS.Create(LToken); LKey := TJWK.Create('secret'); try LSigner.Sign(LKey, HS256); mmoJSON.Lines.Add('Header: ' + LToken.Header.JSON.ToJSON); mmoJSON.Lines.Add('Claims: ' + LToken.Claims.JSON.ToJSON); mmoCompact.Lines.Add('Header: ' + LSigner.Header); mmoCompact.Lines.Add('Payload: ' + LSigner.Payload); mmoCompact.Lines.Add('Signature: ' + LSigner.Signature); mmoCompact.Lines.Add('Compact Token: ' + LSigner.CompactToken); finally LKey.Free; LSigner.Free; end; finally LToken.Free; end; end; procedure TfrmMain.btnTestClaimsClick(Sender: TObject); var LToken: TJWT; begin // Create a JWT Object LToken := TJWT.Create(TJWTClaims); try LToken.Claims.IssuedAt := Now; mmoJSON.Lines.Add('IssuedAt: ' + DateTimeToStr(LToken.Claims.IssuedAt)); finally LToken.Free; end; end; procedure TfrmMain.btnTJOSEBuildClick(Sender: TObject); var LToken: TJWT; begin // Create a JWT Object LToken := TJWT.Create(TJWTClaims); try // Token claims LToken.Claims.IssuedAt := Now; LToken.Claims.Expiration := Now + 1; LToken.Claims.Issuer := 'WiRL REST Library'; // Signing and Compact format creation mmoCompact.Lines.Add(TJOSE.SHA256CompactToken('secret', LToken)); // Header and Claims JSON representation mmoJSON.Lines.Add(LToken.Header.JSON.ToJSON); mmoJSON.Lines.Add(LToken.Claims.JSON.ToJSON); finally LToken.Free; end; end; function TMyClaims.GetAppIssuer: string; begin Result := TJSONUtils.GetJSONValue('ais', FJSON).AsString; end; procedure TMyClaims.SetAppIssuer(const Value: string); begin TJSONUtils.SetJSONValueFrom<string>('ais', Value, FJSON); end; end.
unit rhlAdler32; interface uses rhlCore; type { TrhlAdler32 } TrhlAdler32 = class(TrhlHash) private m_a, m_b: DWord; protected procedure UpdateBytes(const ABuffer; ASize: LongWord); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlAdler32 } procedure TrhlAdler32.UpdateBytes(const ABuffer; ASize: LongWord); const MOD_ADLER: DWord = 65521; var b: PByte; begin b := @ABuffer; while ASize > 0 do begin m_a := (m_a + b^) mod MOD_ADLER; m_b := (m_b + m_a) mod MOD_ADLER; Inc(b); Dec(ASize); end; end; constructor TrhlAdler32.Create; begin HashSize := 4; BlockSize := 1; end; procedure TrhlAdler32.Init; begin inherited Init; m_a := 1; m_b := 0; end; procedure TrhlAdler32.Final(var ADigest); var x: DWord; begin x := (m_b shl 16) or m_a; Move(x, ADigest, 4); end; end.
unit Controller; interface uses Controller.Interf, Controller.Login, Controller.Cadastros, Model.Interf, Model.Usuario; type TController = class(TInterfacedObject, iController) private FUSUARIO : iUsuario_Model; FLOGIN : iLogin_Controller; FCadastros : iControllerCadastros; public constructor Create; destructor Destroy; override; class function New: iController; function USUARIOS : iUsuario_Model; function LOGIN : iLogin_Controller; function Cadastros: iControllerCadastros; end; implementation uses SysUtils; { TController } function TController.Cadastros: iControllerCadastros; begin if not (Assigned(FCadastros)) then FCadastros := TControllerCadastros.New(Self); Result := FCadastros; end; constructor TController.Create; begin end; destructor TController.Destroy; begin inherited; end; function TController.LOGIN: iLogin_Controller; begin if not Assigned(FLOGIN) then FLOGIN := TLogin_Controller.Create; Result := FLOGIN; end; class function TController.New: iController; begin Result := Self.Create; end; function TController.USUARIOS: iUsuario_Model; begin if not Assigned(FUSUARIO) then FUSUARIO := TUsuario_Model.New; Result := FUSUARIO; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { XML RTL Constants } { } { Copyright (c) 2002 Borland Software Corporation } { } {*******************************************************} unit XMLConst; interface resourcestring { xmldom.pas } SDuplicateRegistration = '"%s" DOMImplementation already registered'; SNoMatchingDOMVendor = 'No matching DOM Vendor: "%s"'; SNoDOMNodeEx = 'Selected DOM Vendor does not support this property or method'; SDOMNotSupported = 'Property or Method "%s" is not supported by DOM Vendor "%s"'; { msxmldom.pas } SNodeExpected = 'Node cannot be null'; SMSDOMNotInstalled = 'Microsoft MSXML is not installed'; { oxmldom.pas } {$IFDEF MSWINDOWS} SErrorDownloadingURL = 'Error downloading URL: %s'; SUrlMonDllMissing = 'Unable to load %s'; {$ENDIF} SNotImplemented = 'This property or method is not implemented in the Open XML Parser'; { xercesxmldom.pas } SINDEX_SIZE_ERR = 'Invalid string offset'; SDOMSTRING_SIZE_ERR = 'Invalid DOMString size'; SHIERARCHY_REQUEST_ERR = 'Cannot insert child node'; SWRONG_DOCUMENT_ERR = 'Node is owned by a different document'; SINVALID_CHARACTER_ERR = 'Invalid character in name'; SNO_DATA_ALLOWED_ERR = 'No data allowed'; // not used SNO_MODIFICATION_ALLOWED_ERR = 'No modification allowed (readonly data)'; SNOT_FOUND_ERR = 'Node not found'; SNOT_SUPPORTED_ERR = 'Not supported'; SINUSE_ATTRIBUTE_ERR = 'Attribute already associated with another element'; SINVALID_STATE_ERR = 'Invalid state'; SSYNTAX_ERR = 'Invalid syntax'; SINVALID_MODIFICATION_ERR = 'Invalid modification'; // not used SNAMESPACE_ERR = 'Invalid namespace request'; SINVALID_ACCESS_ERR = 'Invalid access'; // not used SBadTransformArgs = 'TransformNode most be called using a document node (not a document element) for the source and the stylesheet.'; SErrorWritingFile = 'Error creating file "%s"'; SUnhandledXercesErr = 'Unhandled Xerces DOM error (no message available): %d'; SDOMError = 'DOM Error: '; {$IFDEF LINUX} SErrorLoadingLib = 'Error loading library "%s": "%s"'; {$ENDIF} { XMLDoc.pas } SNotActive = 'No active document'; SNodeNotFound = 'Node "%s" not found'; SMissingNode = 'IDOMNode required'; SNoAttributes = 'Attributes are not supported on this node type'; SInvalidNodeType = 'Invalid node type'; SMismatchedRegItems = 'Mismatched paramaters to RegisterChildNodes'; SNotSingleTextNode = 'Element does not contain a single text node'; SNoDOMParseOptions = 'DOM Implementation does not support IDOMParseOptions'; SNotOnHostedNode = 'Invalid operation on a hosted node'; SMissingItemTag = 'ItemTag property is not initialized'; SNodeReadOnly = 'Node is readonly'; SUnsupportedEncoding = 'Unsupported character encoding "%s", try using LoadFromFile'; SNoRefresh = 'Refresh is only supported if the FileName or XML properties are set'; SMissingFileName = 'FileName cannot be blank'; SLine = 'Line'; SUnknown = 'Unknown'; { XMLSchema.pas } SInvalidSchema = 'Invalid or unsupported XML Schema document'; SNoLocalTypeName = 'Local type declarations cannot have a name. Element: %s'; SUnknownDataType = 'Unknown datatype "%s"'; SInvalidValue = 'Invalid %s value: "%s"'; SInvalidGroupDecl = 'Invalid group declaration in "%s"'; SMissingName = 'Missing Type name'; SInvalidDerivation = 'Invalid complex type derivation: %s'; SNoNameOnRef = 'Name not allowed on a ref item'; SNoGlobalRef = 'Global scheam items may not contain a ref'; SNoRefPropSet = '%s cannot be set on a ref item'; SSetGroupRefProp = 'Set the GroupRef property for the cmGroupRef content model'; SNoContentModel = 'ContentModel not set'; SNoFacetsAllowed = 'Facets and Enumeration not allowed on this kind of datatype "%s"'; SNotBuiltInType = 'Invalid built-in type name "%s"'; SBuiltInType = 'Built-in Type'; { XMLDataToSchema.pas } SXMLDataTransDesc = 'XMLData to XML Schema Translator (.xml -> .xsd)'; { XMLSchema99.pas } S99TransDesc = '1999 XML Schema Translator (.xsd <-> .xsd)'; { DTDSchema.pas } SDTDTransDesc = 'DTD to XML Schema Translator (.dtd <-> .xsd)'; { XDRSchema.pas } SXDRTransDesc = 'XDR to XML Schema Translator (.xdr <-> .xsd)'; implementation end.
unit RecordSplitMergeNumberDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Db, DBTables; type TRecordSplitMergeNumberDialogForm = class(TForm) Label1: TLabel; SplitMergeNumberEdit: TEdit; OKButton: TBitBtn; CancelButton: TBitBtn; procedure OKButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } SplitMergeNumber : String; end; var RecordSplitMergeNumberDialogForm: TRecordSplitMergeNumberDialogForm; implementation {$R *.DFM} uses GlblVars, WinUtils; {===============================================} Procedure TRecordSplitMergeNumberDialogForm.OKButtonClick(Sender: TObject); begin SplitMergeNumber := SplitMergeNumberEdit.Text; If (SplitMergeNumber = '') then begin MessageDlg('Please enter a split\merge number.', mtError, [mbOK], 0); SplitMergeNumberEdit.SetFocus; end else ModalResult := idOK; end; {OKButtonClick} end.
{ ID: nghoang4 PROG: calfflac LANG: PASCAL } const fi = 'calfflac.in'; fo = 'calfflac.out'; maxN = 20001; var a: array[1..maxN] of char; nl: array[1..maxN] of boolean; n, max, l, r, lmax, rmax: integer; procedure Init; begin assign(input,fi); reset(input); n:=0; fillchar(nl,sizeof(nl),false); while not eof do begin while not eoln do begin inc(n); read(a[n]); end; inc(n); a[n]:='.'; nl[n]:=true; readln; end; close(input); end; function min2(a, b: integer): integer; begin if a>b then min2:=b else min2:=a; end; procedure Solve; var count, i: integer; begin max:=0; lmax:=-1; rmax:=-1; for i:=1 to n-1 do begin l:=i-1; r:=i+1; if upcase(a[i]) in ['A'..'Z'] then count:=1 else count:=0; while true do begin while (l > 0) and (not (upcase(a[l]) in ['A'..'Z'])) do dec(l); while (r <= n) and (not (upcase(a[r]) in ['A'..'Z'])) do inc(r); if not ((l > 0) and (r <= n) and (r-l < 2000) and (upcase(a[l]) = upcase(a[r]))) then break; inc(count,2); dec(l); inc(r); end; if count > max then begin max:=count; lmax:=l+1; rmax:=r-1; end; l:=i; r:=i+1; count:=0; while true do begin while (l > 0) and (not (upcase(a[l]) in ['A'..'Z'])) do dec(l); while (r <= n) and (not (upcase(a[r]) in ['A'..'Z'])) do inc(r); if not ((l > 0) and (r <= n) and (r-l+1 < 2001) and (upcase(a[l]) = upcase(a[r]))) then break; inc(count,2); dec(l); inc(r); end; if count > max then begin max:=count; lmax:=l+1; rmax:=r-1; end; end; end; procedure PrintResult; var i: integer; begin assign(output,fo); rewrite(output); writeln(max); while not (upcase(a[lmax]) in ['A'..'Z']) do inc(lmax); while not (upcase(a[rmax]) in ['A'..'Z']) do dec(rmax); for i:=lmax to rmax do begin if nl[i] then writeln else write(a[i]); end; writeln; close(output); end; begin Init; Solve; PrintResult; end.
unit Streams; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls; type TfStreams = class(TForm) btnLoad1: TButton; Label1: TLabel; btnLoad100: TButton; Label2: TLabel; ProgressBar1: TProgressBar; procedure FormCreate(Sender: TObject); procedure btnLoad1Click(Sender: TObject); procedure btnLoad100Click(Sender: TObject); private FPath: string; function LoadStream: TMemoryStream; procedure WriteLabelSize(aSize: Integer; aLabel: TLabel); public end; var fStreams: TfStreams; implementation {$R *.dfm} procedure TfStreams.btnLoad1Click(Sender: TObject); var S: TStream; begin S := LoadStream; try if S <> nil then WriteLabelSize(S.Size, Label1) else WriteLabelSize(0, Label1); finally S.Free; end; end; procedure TfStreams.btnLoad100Click(Sender: TObject); var i, SizeInc: Integer; S: TStream; begin ProgressBar1.Position := 0; ProgressBar1.Max := 100; SizeInc := 0; S := LoadStream; try if S <> nil then begin for i := 0 to 99 do begin SizeInc := SizeInc + S.Size; ProgressBar1.Position := ProgressBar1.Position + 1; Application.ProcessMessages; end; end; finally S.Free; end; WriteLabelSize(SizeInc, Label2); end; procedure TfStreams.FormCreate(Sender: TObject); begin FPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'pdf.pdf'; end; function TfStreams.LoadStream: TMemoryStream; begin if FileExists(FPath) then begin Result := TMemoryStream.Create; Result.LoadFromFile(FPath); end else Result := nil; end; procedure TfStreams.WriteLabelSize(aSize: Integer; aLabel: TLabel); begin aLabel.Caption := 'Size: ' + (aSize div 1024).ToString + ' MB'; end; end.
unit Database; interface uses Classes; type TDayExercise = record Id: Cardinal; Name: String; Param0: String; Comment: String; end; TDayExercises = array of TDayExercise; procedure CreateTables; procedure FetchList(ARet: TStrings; ADate: TDateTime); procedure AddEvent(ADate: TDateTime; AThought, AAction: String; AIfILIkeIt: Boolean); implementation uses Windows, SysUtils, Variants, SQLite3, SQLite3Wrap; resourcestring CreateTable = 'CREATE TABLE IF NOT EXISTS actions (' + 'id INTEGER PRIMARY KEY AUTOINCREMENT, ' + 'evdate DATETIME NOT NULL, ' + 'thought VARCHAR(255) NOT NULL, ' + 'action VARCHAR(255) NOT NULL,' + 'ifILikeIt BOOLEAN NOT NULL' + ')'; SelectList = 'SELECT actions.id AS id, actions.evdate || '': '' || actions.thought || ''/ '' || actions.action AS line ' + 'FROM actions WHERE date(actions.evdate) = date(:date) ORDER BY actions.evdate'; InsertEvent = 'INSERT INTO actions (evdate, thought, action, ifILikeIt) VALUES (:date, :thought, :action, :ifILikeIt)'; var FDB: TSQLite3Database; procedure CreateTables; var sl: TStringList; i: Integer; resourcestring sInitScript = 'init.sql'; begin FDB.Execute(CreateTable); if FileExists(sInitScript) then begin try sl := TStringList.Create; sl.LoadFromFile(sInitScript); for i := 0 to sl.Count - 1 do FDB.Execute(sl[i]); finally if Assigned(sl) then FreeAndNil(sl); end; RenameFile(sInitScript, sInitScript + '.old'); end; end; procedure FetchList(ARet: TStrings; ADate: TDateTime); var stmt: TSQLite3Statement; begin stmt := FDB.Prepare(SelectList); stmt.BindText(':date', FormatDateTime('yyyy-mm-dd hh:nn:ss', ADate)); while stmt.Step = SQLITE_ROW do ARet.AddObject(stmt.ColumnText(1), Pointer(stmt.ColumnInt(0))); end; procedure AddEvent(ADate: TDateTime; AThought, AAction: String; AIfILIkeIt: Boolean); var stmt: TSQLite3Statement; begin stmt := FDB.Prepare(InsertEvent); stmt.BindText(':date', FormatDateTime('yyyy-mm-dd hh:nn:ss', ADate)); stmt.BindText(':thought', AThought); stmt.BindText(':action', AAction); if AIfILIkeIt then stmt.BindInt(':ifILikeIt', 1) else stmt.BindInt(':ifILikeIt', 0); stmt.Step; end; initialization FDB := TSQLite3Database.Create; FDB.Open('timer.db'); finalization if Assigned(FDB) then begin FDB.Close; FreeAndNil(FDB); end; end.
{------------------------------------------------------------------------------- Definition of the constants, types, records and functions used by ECLIB.DLL (c) Bio-Logic company, 1997 - 2008 -------------------------------------------------------------------------------} unit EClib; interface type int8 = Shortint; int16 = SmallInt; int32 = LongInt; uint8 = byte; uint16 = word; uint32 = Longword; puint8 = ^uint8; puint16 = ^uint16; puint32 = ^uint32; pint8 = ^int8; pint16 = ^int16; pint32 = ^int32; psingle = ^single; const LIB_DIRECTORY = '..\..\EC-Lab Development Package\'; {$IFDEF WIN64} ECLIB_DLL = LIB_DIRECTORY + 'EClib64.dll'; {$ELSE} ECLIB_DLL = LIB_DIRECTORY + 'EClib.dll'; {$ENDIF} {Nb of channels} NB_CH = 16; {ERROR CODES} ERR_NOERROR = 0; {function succeeded} {General error codes} ERR_GEN_NOTCONNECTED = -1; {no instrument connected} ERR_GEN_CONNECTIONINPROGRESS = -2; {connection in progress} ERR_GEN_CHANNELNOTPLUGGED = -3; {selected channel(s) not plugged} ERR_GEN_INVALIDPARAMETERS = -4; {invalid function parameters} ERR_GEN_FILENOTEXISTS = -5; {selected file does not exists} ERR_GEN_FUNCTIONFAILED = -6; {function failed} ERR_GEN_NOCHANNELSELECTED = -7; {no channel selected} ERR_GEN_INVALIDCONF = -8; {invalid instrument configuration} ERR_GEN_ECLAB_LOADED = -9; {EC-Lab firmware loaded on the instrument} ERR_GEN_LIBNOTCORRECTLYLOADED = -10; {library not correctly loaded in memory} ERR_GEN_USBLIBRARYERROR = -11; {USB library not correctly loaded in memory} ERR_GEN_FUNCTIONINPROGRESS = -12; {function of the library already in progress} ERR_GEN_CHANNEL_RUNNING = -13; {selected channel(s) already used} ERR_GEN_DEVICE_NOTALLOWED = -14; {Device not allowed} ERR_GEN_UPDATEPARAMETERS = -15; {invalid function update parameters} {Instrument error codes} ERR_INSTR_VMEERROR = -101; {internal instrument communication failed} ERR_INSTR_TOOMANYDATA = -102; {too many data to transfer from the instrument} ERR_INSTR_RESPNOTPOSSIBLE = -103; {channel not plugged or firmware not allowed} ERR_INSTR_RESPERROR = -104; {instrument response error} ERR_INSTR_MSGSIZEERROR = -105; {invalid message size} {Communication error codes} ERR_COMM_COMMFAILED = -200; {communication failed with the instrument} ERR_COMM_CONNECTIONFAILED = -201; {cannot establish connection with the instrument} ERR_COMM_WAITINGACK = -202; {waiting for the instrument response} ERR_COMM_INVALIDIPADDRESS = -203; {invalid IP address} ERR_COMM_ALLOCMEMFAILED = -204; {cannot allocate memory in the instrument} ERR_COMM_LOADFIRMWAREFAILED = -205; {cannot load firmware into selected channel(s)} ERR_COMM_INCOMPATIBLESERVER = -206; {communication firmware not compatible with the library} ERR_COMM_MAXCONNREACHED = -207; {maximum number of allowed connections reached} {Firmware error codes} ERR_FIRM_FIRMFILENOTEXISTS = -300; {cannot find firmware file} ERR_FIRM_FIRMFILEACCESSFAILED = -301; {cannot read firmware file} ERR_FIRM_FIRMINVALIDFILE = -302; {invalid firmware file} ERR_FIRM_FIRMLOADINGFAILED = -303; {cannot load firmware on the selected channel(s)} ERR_FIRM_XILFILENOTEXISTS = -304; {cannot find xilinx file} ERR_FIRM_XILFILEACCESSFAILED = -305; {cannot read xilinx file} ERR_FIRM_XILINVALIDFILE = -306; {invalid xilinx file} ERR_FIRM_XILLOADINGFAILED = -307; {cannot load xilinx file on the selected channel(s)} ERR_FIRM_FIRMWARENOTLOADED = -308; {no firmware loaded on the selected channel(s)} ERR_FIRM_FIRMWAREINCOMPATIBLE = -309; {loaded firmware not compatible with the library} {Technique error codes} ERR_TECH_ECCFILENOTEXISTS = -400; {cannot find the selected ECC file} ERR_TECH_INCOMPATIBLEECC = -401; {ECC file not compatible with the channel firmware} ERR_TECH_ECCFILECORRUPTED = -402; {ECC file corrupted} ERR_TECH_LOADTECHNIQUEFAILED = -403; {cannot load the ECC file} ERR_TECH_DATACORRUPTED = -404; {data returned by the instrument are corrupted} ERR_TECH_MEMFULL = -405; {cannot load techniques : full memory} {Devices constants (used by the function BL_CONNECT)} KBIO_DEV_VMP = 0; KBIO_DEV_VMP2 = 1; KBIO_DEV_MPG = 2; KBIO_DEV_BISTAT = 3; KBIO_DEV_MCS200 = 4; KBIO_DEV_VMP3 = 5; KBIO_DEV_VSP = 6; KBIO_DEV_HCP803 = 7; KBIO_DEV_EPP400 = 8; KBIO_DEV_EPP4000 = 9; KBIO_DEV_BISTAT2 = 10; KBIO_DEV_FCT150S = 11; KBIO_DEV_VMP300 = 12; KBIO_DEV_SP50 = 13; KBIO_DEV_SP150 = 14; KBIO_DEV_FCT50S = 15; KBIO_DEV_SP300 = 16; KBIO_DEV_CLB500 = 17; KBIO_DEV_HCP1005 = 18; KBIO_DEV_CLB2000 = 19; KBIO_DEV_VSP300 = 20; KBIO_DEV_SP200 = 21; KBIO_DEV_MPG2 = 22; KBIO_DEV_SP100 = 23; KBIO_DEV_MOSLED = 24; KBIO_DEV_SP240 = 27; KBIO_DEV_UNKNOWN = 255; {Firmware code constants (used by the structure TCHANNELINFOS)} KBIO_FIRM_NONE = 0; KBIO_FIRM_INTERPR = 1; KBIO_FIRM_UNKNOWN = 4; KBIO_FIRM_KERNEL = 5; KBIO_FIRM_INVALID = 8; KBIO_FIRM_ECAL = 10; {Amplifier code constants (used by the structure TCHANNELINFOS)} KBIO_AMPL_NONE = 0; KBIO_AMPL_2A = 1; KBIO_AMPL_1A = 2; KBIO_AMPL_5A = 3; KBIO_AMPL_10A = 4; KBIO_AMPL_20A = 5; KBIO_AMPL_HEUS = 6; KBIO_AMPL_LC = 7; KBIO_AMPL_80A = 8; KBIO_AMPL_4AI = 9; KBIO_AMPL_PAC = 10; KBIO_AMPL_4AI_VSP = 11; KBIO_AMPL_LC_VSP = 12; KBIO_AMPL_UNDEF = 13; KBIO_AMPL_MUIC = 14; KBIO_AMPL_NONE_GIL = 15; KBIO_AMPL_8AI = 16; KBIO_AMPL_LB500 = 17; KBIO_AMPL_100A5V = 18; KBIO_AMPL_LB2000 = 19; KBIO_AMPL_1A48V = 20; KBIO_AMPL_4A10V = 21; {Option error codes} KBIO_OPT_NOERR = 0; {Option no error} KBIO_OPT_CHANGE = 1; {Option change} KBIO_OPT_4A10V_ERR = 100; {Amplifier 4A10V error} KBIO_OPT_4A10V_OVRTEMP = 101; {Amplifier 4A10V overload temperature} KBIO_OPT_4A10V_BADPOW = 102; {Amplifier 4A10V invalid power} KBIO_OPT_4A10V_POWFAIL = 103; {Amplifier 4A10V power fail} KBIO_OPT_1A48V_ERR = 200; {Amplifier 1A48V error} KBIO_OPT_1A48V_OVRTEMP = 201; {Amplifier 1A48V overload temperature} KBIO_OPT_1A48V_BADPOW = 202; {Amplifier 1A48V invalid power} KBIO_OPT_1A48V_POWFAIL = 203; {Amplifier 1A48V power fail} {I Range constants (used by the structures TDATAINFOS and TECCPARAMGEN)} KBIO_IRANGE_100pA = 0; KBIO_IRANGE_1nA = 1; KBIO_IRANGE_10nA = 2; KBIO_IRANGE_100nA = 3; KBIO_IRANGE_1uA = 4; KBIO_IRANGE_10uA = 5; KBIO_IRANGE_100uA = 6; KBIO_IRANGE_1mA = 7; KBIO_IRANGE_10mA = 8; KBIO_IRANGE_100mA = 9; KBIO_IRANGE_1A = 10; KBIO_IRANGE_BOOSTER = 11; KBIO_IRANGE_AUTO = 12; KBIO_IRANGE_10pA = 13; {IRANGE_100pA + Igain x10} KBIO_IRANGE_1pA = 14; {IRANGE_100pA + Igain x100} {E Range constants (used by the structures TDATAINFOS and TECCPARAMGEN)} KBIO_ERANGE_2_5 = 0; {±2.5V} KBIO_ERANGE_5 = 1; {±5V} KBIO_ERANGE_10 = 2; {±10V} KBIO_ERANGE_AUTO = 3; {auto} {Bandwidth constants (used by the structures TDATAINFOS and TECCPARAMGEN)} KBIO_BW_1 = 1; KBIO_BW_2 = 2; KBIO_BW_3 = 3; KBIO_BW_4 = 4; KBIO_BW_5 = 5; KBIO_BW_6 = 6; KBIO_BW_7 = 7; KBIO_BW_8 = 8; KBIO_BW_9 = 9; {E/I gain constants} KBIO_GAIN_1 = 0; KBIO_GAIN_10 = 1; KBIO_GAIN_100 = 2; KBIO_GAIN_1000 = 3; {E/I filter constants} KBIO_FILTER_NONE = 0; KBIO_FILTER_50KHZ = 1; KBIO_FILTER_1KHZ = 2; KBIO_FILTER_5HZ = 3; {Coulometry constants} KBIO_COUL_SOFT = 0; KBIO_COUL_HARD = 1; {Electrode connection constants} KBIO_CONN_STD = 0; KBIO_CONN_CETOGRND = 1; KBIO_CONN_WETOGRND = 2; KBIO_CONN_HV = 3; {Controled potential mode constants} KBIO_REF21 = 0; KBIO_REF31 = 1; KBIO_REF32 = 2; KBIO_REF32DIFF = 3; {Channel mode constants} KBIO_MODE_GROUNDED = 0; KBIO_MODE_FLOATING = 1; {LC measurement constants} KBIO_BOOST_NOISE = 0; KBIO_BOOST_SPEED = 1; {Technique ID constants (used by the structure TDATAINFOS)} KBIO_TECHID_NONE = 0; KBIO_TECHID_OCV = 100; KBIO_TECHID_CA = 101; KBIO_TECHID_CP = 102; KBIO_TECHID_CV = 103; KBIO_TECHID_PEIS = 104; KBIO_TECHID_POTPULSE = 105; KBIO_TECHID_GALPULSE = 106; KBIO_TECHID_GEIS = 107; KBIO_TECHID_STACKPEIS_SLAVE = 108; KBIO_TECHID_STACKPEIS = 109; KBIO_TECHID_CPOWER = 110; KBIO_TECHID_CLOAD = 111; KBIO_TECHID_FCT = 112; KBIO_TECHID_SPEIS = 113; KBIO_TECHID_SGEIS = 114; KBIO_TECHID_STACKPDYN = 115; KBIO_TECHID_STACKPDYN_SLAVE = 116; KBIO_TECHID_STACKGDYN = 117; KBIO_TECHID_STACKGEIS_SLAVE = 118; KBIO_TECHID_STACKGEIS = 119; KBIO_TECHID_STACKGDYN_SLAVE = 120; KBIO_TECHID_CPO = 121; KBIO_TECHID_CGA = 122; KBIO_TECHID_COKINE = 123; KBIO_TECHID_PDYN = 124; KBIO_TECHID_GDYN = 125; KBIO_TECHID_CVA = 126; KBIO_TECHID_DPV = 127; KBIO_TECHID_SWV = 128; KBIO_TECHID_NPV = 129; KBIO_TECHID_RNPV = 130; KBIO_TECHID_DNPV = 131; KBIO_TECHID_DPA = 132; KBIO_TECHID_EVT = 133; KBIO_TECHID_LP = 134; KBIO_TECHID_GC = 135; KBIO_TECHID_CPP = 136; KBIO_TECHID_PDP = 137; KBIO_TECHID_PSP = 138; KBIO_TECHID_ZRA = 139; KBIO_TECHID_MIR = 140; KBIO_TECHID_PZIR = 141; KBIO_TECHID_GZIR = 142; KBIO_TECHID_LOOP = 150; KBIO_TECHID_TO = 151; KBIO_TECHID_TI = 152; KBIO_TECHID_TOS = 153; KBIO_TECHID_MUX = 154; KBIO_TECHID_CPLIMIT = 155; KBIO_TECHID_GDYNLIMIT = 156; KBIO_TECHID_CALIMIT = 157; KBIO_TECHID_PDYNLIMIT = 158; KBIO_TECHID_LASV = 159; KBIO_TECHID_MUXLOOP = 160; KBIO_TECHID_ABS = 1000; KBIO_TECHID_FLUO = 1001; KBIO_TECHID_RABS = 1002; KBIO_TECHID_RFLUO = 1003; KBIO_TECHID_RDABS = 1004; KBIO_TECHID_DABS = 1005; KBIO_TECHID_ABSFLUO = 1006; KBIO_TECHID_RAFABS = 1007; KBIO_TECHID_RAFFLUO = 1008; EXP_GRP_EXPRESS_GAL = [KBIO_TECHID_CP, KBIO_TECHID_GEIS, KBIO_TECHID_SGEIS, KBIO_TECHID_STACKGDYN, KBIO_TECHID_GDYN, KBIO_TECHID_GZIR, KBIO_TECHID_CPLIMIT, KBIO_TECHID_GDYNLIMIT]; {Galvano techniques} {Channel state constants (used by the structures TDATAINFOS and TECCPARAMGEN)} KBIO_STATE_STOP = 0; KBIO_STATE_RUN = 1; KBIO_STATE_PAUSE = 2; {Parameter type constants (used by the structure TECCPARAM and TEccParam_LV)} PARAM_INT32 = 0; PARAM_BOOLEAN = 1; PARAM_SINGLE = 2; {Separator for EccParams} SEPARATOR = ';'; type PPAnsiChar = array of array of ansichar; TArrayDouble = array of Double; {Device informations. WARNING : record aligned on 32 bits} TDeviceInfos = record DeviceCode : int32; {Device} RAMsize : int32; {RAM size (MBytes)} CPU : int32; {Computer board cpu (68040, 68060)} NumberOfChannels : int32; {number of channels} NumberOfSlots : int32; {number of slots} FirmwareVersion : int32; {Communication firmware version} FirmwareDate_yyyy : int32; {Communication firmware date YYYY} FirmwareDate_mm : int32; {Communication firmware date MM} FirmwareDate_dd : int32; {Communication firmware date DD} HTdisplayOn : int32; {Allow hyperterminal prints (true/false)} NbOfConnectedPC : int32; {Number of connected PC} end; PDeviceInfos = ^TDeviceInfos; {Channel informations. WARNING : record aligned on 32 bits} TChannelInfos = record Channel : int32; {Channel (0-based)} BoardVersion : int32; {Board version} BoardSerialNumber : int32; {Board serial number} FirmwareCode : int32; {Firmware code} FirmwareVersion : int32; {Firmware version} XilinxVersion : int32; {Xilinx version} AmpCode : int32; {Amplifier code} NbAmp : int32; {Nb Amplifiers 4A} LCboard : int32; {Low Current board} Zboard : int32; {EIS board} MUXboard : int32; {MUX board} GPRAboard : int32; {Generateur Programmable Rampe Analogique board} MemSize : int32; {Memory size (in bytes)} MemFilled : int32; {Memory filled (in bytes)} State : int32; {Channel state (run/stop/pause)} MaxIRange : int32; {Max I range allowed} MinIRange : int32; {Min I range allowed} MaxBandwidth : int32; {Max bandwidth allowed} NbOfTechniques : int32; {Number of techniques loaded} end; PChannelInfos = ^TChannelInfos; {Current values. WARNING : record aligned on 32 bits} TCurrentValues = record State : int32; {Channel state (run/stop/pause)} MemFilled : int32; {Memory filled (bytes)} TimeBase : single; {Timebase (s)} Ewe : single; {Ewe (V)} EweRangeMin : single; {Ewe min range (V)} EweRangeMax : single; {Ewe max range (V)} Ece : single; {Ece (V)} EceRangeMin : single; {Ece min range (V)} EceRangeMax : single; {Ece max range (V)} Eoverflow : int32; {E overflow} I : single; {I (A)} IRange : int32; {I range} Ioverflow : int32; {I overflow} ElapsedTime : single; {Elapsed time (s)} Freq : single; {Frequency (Hz)} Rcomp : single; {R compensation (Ohm)} Saturation : int32; {E or/and I saturation} OptErr : int32; {Option error code} OptPos : int32; {Option position} end; PCurrentValues = ^TCurrentValues; {Current values for BioKine. WARNING : record aligned on 32 bits} TCurrentValuesBk = record State : int32; {Channel state (run/stop/pause)} MemFilled : int32; {Memory filled (bytes)} TimeBase : single; {Timebase (s)} ElapsedTime : single; {Elapsed time (s)} PHout : single; {PHout (V)} PMout : single; {PMout (V)} HVMON : single; {Hv Monitor (V)} ledbCode : int32; {LedA code} ledaCode : int32; {LedB code} phCode : int32; {PH code} pmCode : int32; {PM code} HVMAX : single; {Hv Max (V)} PhSat : int32; {PH or/and PM saturation} PmSat : int32; {PH or/and PM saturation} Saturation : int32; {PH or/and PM saturation} RefPh : single; {Valeur de la reference de la ph (V)} RefPm : single; {Valeur de la reference du pm (V)} RefokPh : int32; RefokPm : int32; HT0RefPm : single; Int0RefPh : single; Int0RefPm : single; AUXIN : single; end; PCurrentValuesBk = ^TCurrentValuesBk; {Data informations. WARNING : record aligned on 32 bits} TDataInfos = record IRQskipped : int32; {Number of IRQ skipped} NbRaws : int32; {Number of raws into the data buffer} NbCols : int32; {Number of columns into the data buffer} TechniqueIndex : int32; {Technique index (0-based)} TechniqueID : int32; {Technique ID} ProcessIndex : int32; {Process index (0-based)} loop : int32; {Loop number} StartTime : double; {Start time (s)} MuxPad : int32; {Multiplexeur pad} end; PDataInfos = ^TDataInfos; {Data buffer. WARNING : record aligned on 32 bits} TDataBuffer = array[1..1000] of uint32; PDataBuffer = ^TDataBuffer; {Elementary technique parameter. WARNING : record aligned on 32 bits} TEccParam = record ParamStr : array[1..64] of ansichar; {string who defines the parameter} ParamType : int32; {Parameter type (0=int32, 1=boolean, 2=single)} ParamVal : int32; {Parameter value (WARNING : numerical value)} ParamIndex : int32; {Parameter index (0-based)} end; PEccParam = ^TEccParam; TDynArrayofEccParam = array of TEccParam; {Technique parameters. WARNING : record aligned on 32 bits} TEccParams = record len : int32; {Length of the array pParams^[]} pParams : PEccParam; {Pointer on the first record who defines the parameters} end; {Elementary technique parameter (define for LabVIEW compatibility)} TArrayOfChar_LV = record {Array of ansichar} dimSize : int32; {length of the array} FirstChar : ansichar; {first element in the array of ansichar} end; PArrayOfChar_LV = ^TArrayOfChar_LV; PPArrayOfChar_LV = ^PArrayOfChar_LV; TEccParam_LV = record ppParamStr_LV : PPArrayOfChar_LV; {string who defines the parameter} ParamType : int32; {Parameter type (0=int32, 1=boolean, 2=single)} ParamVal : int32; {Parameter value} ParamIndex : int32; {parameter index} end; PEccParam_LV = ^TEccParam_LV; {Array of elementary parameters TEccParam_LV (define for LabVIEW compatibility)} TEccParams_LV = record dimSize : int32; {length of the array} FirstEccParam_LV : TEccParam_LV; {first element in the array} end; PEccParams_LV = ^TEccParams_LV; PPEccParams_LV = ^PEccParams_LV; {Experiment informations. WARNING : record aligned on 32 bits} TExperimentInfos = record Group : int32; PCidentifier : int32; TimeHMS : int32; TimeYMD : int32; FileName : array[1..256] of ansichar; end; PExperimentInfos = ^TExperimentInfos; {Hardware configuration WARNING : record aligned on 32 bits} THardwareConf = record Conn : int32; {Electrode connection} Ground : int32; {Instrument ground} end; PHardwareConf = ^THardwareConf; {General functions} function BL_GetLibVersion( pVersion : pansichar; {(out) version of the library (C-string)} psize : puint32 {(in/out) size of the string} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetVolumeSerialNumber: uint32; stdcall; external ECLIB_DLL; function BL_GetErrorMsg( errorcode : int32; {(in) error code} pmsg : pansichar; {(out) message (C-string)} psize : puint32 {(in/out) size of the message} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Communication functions} function BL_Connect( pstr : PAnsiChar; {(in) IP address or USB port (C-string)} TimeOut : uint8; {(in) communication timeout (sec)} pID : pint32; {(out) device identifier (1-based)} pInfos : PDeviceInfos {(out) device informations} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_Disconnect( ID: int32 {(in) device identifier} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_TestConnection( ID: int32 {(in) device identifier} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_TestCommSpeed( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} spd_rcvt : pint32; {(out) device communication speed (ms)} spd_kernel : pint32 {(out) channel communication speed (ms)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetUSBdeviceinfos( USBindex : uint32; {(in) USB device index} pcompany : pansichar; {(out) company name} pcompanysize : puint32; {(in/out) size of company name} pdevice : pansichar; {(out) device name} pdevicesize : puint32; {(in/out) size of device name} pSN : pansichar; {(out) serial number} pSNsize : puint32 {(in/out) size of serial number} ): boolean; stdcall; external ECLIB_DLL; {Firmware functions} function BL_LoadFirmware( ID : int32; {(in) device identifier} pChannels : puint8; {(in) selected channels} pResults : pint32; {(out) results for each channels} length : uint8; {(in) length of the arrays pChannels^[] and pResults^[]} ShowGauge : boolean; {(in) show the gauge during transfer} ForceLoad : boolean; {(in) force load the firmware} BinFile : PAnsiChar; {(in) bin file (nil for default file)} XlxFile : PAnsiChar {(in) xilinx file (nil for default file)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Channel informations functions} function BL_GetChannelsPlugged( ID : int32; {(in) device identifier} pChPlugged : puint8; {(out) array of channels plugged} Size : uint8 {(in) size of the array} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_IsChannelPlugged( ID : int32; {(in) device identifier} ch : uint8 {(in) selected channel (0->15)} ): boolean; stdcall; {(out) true/false} external ECLIB_DLL; function BL_GetChannelInfos( ID : int32; {(in) device identifier} ch : uint8; {(in) selected channel (0->15)} pInfos : PChannelInfos {(out) channel infos} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetMessage( ID : int32; {(in) device identifier} ch : uint8; {(in) selected channel (0->15)} pMsg : pansichar; {(out) message (C-string)} psize : puint32 {(in/out) size of the message} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Technique functions} function BL_LoadTechnique( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pFName : pansichar; {(in) file name of the ecc file (C-string)} Params : TEccParams; {(in) Technique parameters} FirstTechnique : boolean; {(in) TRUE if first technique loaded} LastTechnique : boolean; {(in) TRUE if last technique loaded} DisplayParams : boolean {(in) Display parameters sent (for debugging purpose)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_LoadTechnique_LV( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pFName : pansichar; {(in) file name of the ecc file (C-string)} HdlParams : PPEccParams_LV; {(in) Technique parameters} FirstTechnique : boolean; {(in) TRUE if first technique loaded} LastTechnique : boolean; {(in) TRUE if last technique loaded} DisplayParams : boolean {(in) Display parameters (for debugging purpose)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_LoadTechnique_VEE (ID : int32; {(in) device identifier} channel : uint8; {(in) channel selected (0->15)} pFName : PAnsiChar; {(in) file name of the ecc file (C-string)} appParams : PPAnsiChar; {(in) Vee Pro array handle, i.e. pointer to pointer of char, FirstTechnique : boolean; {(in) if TRUE the index used to load the technique are freed before} LastTechnique : boolean; {(in) if TRUE the technique(s) loaded is(are) built} DisplayParams : boolean {(in) Display parameters (for debugging purpose)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_DefineBoolParameter( lbl : pansichar; {(in) Label (C-string)} value : boolean; {(in) Value} index : int32; {(in) Index} pParam : PEccParam {(out) Parameter record} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_DefineSglParameter( lbl : pansichar; {(in) Label (C-string)} value : single; {(in) Value} index : int32; {(in) Index} pParam : PEccParam {(out) Parameter record} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_DefineIntParameter( lbl : pansichar; {(in) Label (C-string)} value : int32; {(in) Value} index : int32; {(in) Index} pParam : PEccParam {(out) Parameter record} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_UpdateParameters( ID : int32; {(in) device identifier} channel : uint8; {(in) channel selected (0->15)} TechIndx : int32; {Index of technique to read} Params : TEccParams; {(in) Technique parameters} EccFileName : PansiChar {(in) Ecc file name} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_UpdateParameters_VEE(ID : int32; {(in) device identifier} channel : uint8; {(in) channel selected (0->15)} TechIndx : int32; {Index of technique to update} appParams : PPAnsiChar; {(in) Technique parameters} EccFileName : pansichar {(in) Ecc file name} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Start/stop functions} function BL_StartChannels( ID : int32; {(in) device identifier} pChannels : puint8; {(in) selected channels } pResults : pint32; {(out) results for each channels} length : uint8 {(in) length of the arrays pChannels^[] and pResults^[]} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_StartChannel( ID : int32; {(in) device identifier} channel : uint8 {(in) selected channel (0->15)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_StopChannels( ID : int32; {(in) device identifier} pChannels : puint8; {(in) selected channels } pResults : pint32; {(out) results for each channels} length : uint8 {(in) length of the arrays pChannels^[] and pResults^[]} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_StopChannel( ID : int32; {(in) device identifier} channel : uint8 {(in) selected channel (0->15)} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Data functions} function BL_GetCurrentValues( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pValues : PCurrentValues {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetData( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pBuf : PDataBuffer; {(out) data buffer} pInfos : PDataInfos; {(out) data informations} pValues : PCurrentValues {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetFCTData( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pBuf : PDataBuffer; {(out) data buffer} pInfos : PDataInfos; {(out) data informations} pValues : PCurrentValues {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetData_VEE( ID : int32; {(in) device identifier} channel : uint8; {(in) channel selected (0->15)} pBuf : PDataBuffer; {(out) data buffer} pInfos : TArrayDouble; {(out) data informations} pValues : TArrayDouble {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_ConvertNumericIntoSingle( num : uint32; {(in) numeric value (32bits)} psgl : psingle {(out) single} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetCurrentValuesBk( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pValues : PCurrentValuesBk {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetDataBk( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pBuf : PDataBuffer; {(out) data buffer} pInfos : PDataInfos; {(out) data informations} pValues : PCurrentValuesBk {(out) current values} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Hardware functions} function BL_SetHardConf( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} hardConf : THardwareConf {(in) hardware configuration} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetHardConf( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pHardConf : PHardwareConf {(out) hardware configuration} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetOptErr( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pOptErr : pint32; {(out) Option error code} pOptPos : pint32 {(out) Option position} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; {Miscellaneous functions} function BL_SetExperimentInfos( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} ExpInfos : TExperimentInfos {(in) Experiment informations} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_GetExperimentInfos( ID : int32; {(in) device identifier} channel : uint8; {(in) selected channel (0->15)} pExpInfos : PExperimentInfos {(out) Experiment informations} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; function BL_LoadFlash( ID : int32; {(in) device identifier} pfname : pansichar; {(in) flash file name (C-string)} ShowGauge : boolean {(in) show a gauge during transfer} ): int32; stdcall; {(out) cf. error codes} external ECLIB_DLL; implementation end.
{ "Connection Provider wrapper" - Copyright (c) Danijel Tkalcec @html(<br>) This unit defines the connection provider component wrappers, which define the methods and properties every connection provider has to implement. RTC Component suite uses Connection Providers to implement connection functionality using low-level system code, while the Connection components themselves do not have any system-dependant code and therefor are 100% portable between all systems. @html(<br><br>) Connections create and use connection providers internaly and completely transparent from the connection component user. This lose coupling between the connection component and the connection provider makes it relatively easy to port the RTC connection components to any system. And even more important, port user's code to other systems, without major code modifications. @exclude } unit rtcConnProv; {$INCLUDE rtcDefs.inc} interface uses rtcTrashcan, SysUtils, Windows, rtcSyncObjs, rtcPlugins, rtcThrPool; type // Supported connection states TRtcConnectionState = ( // Connection inactive conInactive, // Listener (waiting for connections) conListening, // Trying to connect conActivating, // Connection active conActive, // Connection was active, now closing conClosing ); { Exception raised when the limit for client connections (specified in rtcConn) was reached and therefor a new connection could not be opened. } EClientLimitReached = class(Exception); // Standard connection provider event (no parameters) TRtcEvent = procedure of object; // Connection provider event with a boolean parameter TRtcBoolEvent = procedure(Value:boolean) of object; // Exception handling event for the connection provider TRtcExceptEvent = procedure(E:Exception) of object; // Error handling event for the connection provider TRtcErrEvent = procedure(Err:string) of object; // Event for creating a new connection provider TRtcProviderEvent = procedure(var Provider:TObject) of object; { @name is a basic wrapper for any connection provider component. It which defines abstract methods and some properties every connection provider has to implement. RTC Component suite uses Connection Providers to implement connection functionality using low-level system code, while the Connection components themselves do not have any system-dependant code and therefor are 100% portable between all systems. Connections create and use connection providers internaly and completely transparent from the connection component user. This lose coupling between the connection component and the connection provider makes it relatively easy to port the RTC connection components to any system. And even more important, port user's code to other systems, without major code modifications. } TRtcConnectionProvider = class private FInSync:boolean; FMultiThreaded:boolean; FAddr:string; FPort:string; FLost, FClosing, FSilent:boolean; // Used for triggering events (provider declares those as virtual abstract) FError:TRtcErrEvent; FOnReadyToRelease:TRtcEvent; FOnBeforeCreate:TrtcEvent; FOnAfterDestroy:TrtcEvent; FOnConnecting:TrtcEvent; FOnConnect:TrtcEvent; FOnDisconnect:TrtcEvent; FOnDisconnecting:TrtcEvent; FOnDataSent:TrtcEvent; FOnDataOut:TrtcEvent; FOnDataIn:TrtcEvent; FOnLastWrite:TrtcEvent; FOnDataReceived:TrtcEvent; FOnDataLost:TrtcEvent; FOnException:TrtcExceptEvent; procedure SetLost(a:boolean); function GetLost:boolean; procedure SetClosing(a:boolean); function GetClosing:boolean; procedure SetSilent(a:boolean); function GetSilent:boolean; protected { Conncetion provider has to set FDataOut to the number of byte sent out, before it calls the TriggerDataOut method. } FDataOut:int64; { Conncetion provider has to set FDataIn to the number of byte read in, before it calls the TriggerDataIn method. } FDataIn:int64; procedure Enter; virtual; abstract; procedure Leave; virtual; abstract; { Properties ready for usage by the connection provider (not used directly by the connection) } property Lost:boolean read GetLost write SetLost; property Closing:boolean read GetClosing write SetClosing; property Silent:boolean read GetSilent write SetSilent; { Triggers to be used by the ConncetionProvider. Connection sets those triggers using SetTrigger_ methods (below). Connection provider should use those methods to trigger all or most of those events, when they happen. } procedure Error(const text:string); virtual; procedure TriggerReadyToRelease; virtual; procedure TriggerBeforeCreate; virtual; procedure TriggerAfterDestroy; virtual; procedure TriggerConnecting; virtual; procedure TriggerConnect; virtual; procedure TriggerDisconnecting; virtual; procedure TriggerDisconnect; virtual; procedure TriggerDataSent; virtual; procedure TriggerDataOut; virtual; procedure TriggerDataIn; virtual; procedure TriggerLastWrite; virtual; procedure TriggerDataReceived; virtual; procedure TriggerDataLost; virtual; procedure TriggerException(E:Exception); virtual; public constructor Create; virtual; destructor Destroy; override; { ********************************************* } function GetThread:TRtcThread; virtual; abstract; { Methods which have to be implemented by the Connection Provider } procedure Release; virtual; abstract; // Called when user calls Disconnect (wanted disconnect) procedure Disconnect; virtual; abstract; // Called when timeout happens or connection gets lost (unwanted disconnect) procedure InternalDisconnect; virtual; abstract; procedure Check; virtual; abstract; function GetParent:TRtcConnectionProvider; virtual; abstract; function GetState:TRtcConnectionState; virtual; abstract; { Support for multithreaded processing -> } function PostJob(Job:TObject; HighPriority:boolean):boolean; virtual; abstract; function inMainThread:boolean; virtual; abstract; function inThread:boolean; virtual; abstract; function SyncEvent(Event:TRtcEvent):boolean; virtual; abstract; procedure Processing; virtual; abstract; function Pause:boolean; virtual; abstract; function Resume:boolean; virtual; abstract; { <- multithreading } procedure Write(const s:string; SendNow:boolean=True); virtual; abstract; function Read:string; virtual; abstract; function GetPeerAddr:string; virtual; abstract; function GetPeerPort:string; virtual; abstract; function GetLocalAddr:string; virtual; abstract; function GetLocalPort:string; virtual; abstract; { ********************************************* } { Methods to be used by the Connection Provider ... Component which uses this connection provider has to use Set_ methods (below) before calling Connect or Listen, to set this properties. } function GetAddr:string; function GetPort:string; function GetMultiThreaded:boolean; { Methods used by the Connection component, to set connection properties, before calling Connect or Listen. } procedure SetAddr(val:string); procedure SetPort(val:string); procedure SetMultiThreaded(val:boolean); { Methods that set Triggers before using the connection provider. Those methods are used by the Conncetion component. } procedure SetError(Event:TRtcErrEvent); procedure SetTriggerReadyToRelease(Event:TrtcEvent); procedure SetTriggerBeforeCreate(Event:TrtcEvent); procedure SetTriggerAfterDestroy(Event:TrtcEvent); procedure SetTriggerConnecting(Event:TrtcEvent); procedure SetTriggerConnect(Event:TrtcEvent); procedure SetTriggerDisconnect(Event:TrtcEvent); procedure SetTriggerDisconnecting(Event:TrtcEvent); procedure SetTriggerDataSent(Event:TrtcEvent); procedure SetTriggerDataOut(Event:TrtcEvent); procedure SetTriggerDataIn(Event:TrtcEvent); procedure SetTriggerLastWrite(Event:TrtcEvent); procedure SetTriggerDataReceived(Event:TrtcEvent); procedure SetTriggerDataLost(Event:TrtcEvent); procedure SetTriggerException(Event:TrtcExceptEvent); { This property is used to check the number of bytes just sent out. It is used by the TriggerDataOut method. } property DataOut:int64 read FDataOut; { This property is used to check the number of bytes just read in. It is used by the TriggerDataIn method. } property DataIn:int64 read FDataIn; end; { @name is a wrapper for the Server-side connection provider. It declares abstract methods which all server-side connection providers have to implement, so they can be used by the Server-side connecion components. } TRtcServerProvider = class(TRtcConnectionProvider) private // Used for counting connections in use FOnConnectionAccepted:TRtcEvent; // we have acepted a new connection FOnConnectionAccepting:TRtcEvent; // check if we can accept a new connection FOnConnectionLost:TRtcEvent; // we have lost the connection // Used for triggering events (provider declares those as virtual abstract) FOnNewProvider:TRtcProviderEvent; FOnListenStart:TrtcEvent; FOnListenStop:TrtcEvent; FOnListenLost:TrtcEvent; FOnListenError:TrtcExceptEvent; public { Triggers to be used by the ConncetionProvider. Connection component, which uses the provider, will set those triggers using SetTrigger_ methods (below). } procedure TriggerNewProvider(var Provider:TObject); virtual; procedure TriggerConnectionAccepting; virtual; procedure TriggerConnectionAccepted; virtual; procedure TriggerConnectionLost; virtual; procedure TriggerListenStart; virtual; procedure TriggerListenStop; virtual; procedure TriggerListenError(E:Exception); virtual; procedure TriggerListenLost; virtual; public { *** Methods which have to be implemented by the Connection Provider *** } procedure Listen; virtual; abstract; { *** Methods used by the connection to set Triggers before using the connection provider. *** } procedure SetTriggerConnectionAccepting(Event:TrtcEvent); // check if we can acept a new connection procedure SetTriggerConnectionAccepted(Event:TrtcEvent); // we have acepted a new connection procedure SetTriggerConnectionLost(Event:TrtcEvent); // we have lost the connection procedure SetTriggerNewProvider(Event:TrtcProviderEvent); procedure SetTriggerListenStart(Event:TrtcEvent); procedure SetTriggerListenStop(Event:TrtcEvent); procedure SetTriggerListenError(Event:TrtcExceptEvent); procedure SetTriggerListenLost(Event:TrtcEvent); end; { @name is a wrapper for the Client-side connection provider. It declares abstract methods which all server-side connection providers have to implement, so they can be used by the Server-side connecion components. } TRtcClientProvider = class(TRtcConnectionProvider) // provides basic connection functionality private // Used for counting connections in use FOnConnectionOpening:TrtcBoolEvent; // we are opening a new connection FOnConnectionClosing:TrtcEvent; // we are closing the connection // Used for triggering events (provider declares those as virtual abstract) FOnConnectFail:TrtcEvent; FOnConnectLost:TrtcEvent; FOnConnectError:TrtcExceptEvent; protected { Triggers to be used by the ConncetionProvider. Connection component, which uses the provider, will set those triggers using SetTrigger_ methods (below). } procedure TriggerConnectionOpening(Force:boolean); virtual; procedure TriggerConnectionClosing; virtual; procedure TriggerConnectError(E:Exception); virtual; procedure TriggerConnectFail; virtual; procedure TriggerConnectLost; virtual; public { *** Methods which have to be implemented by the Connection Provider *** } procedure Connect(Force:boolean=False); virtual; abstract; { *** Methods used by the Connection to set Triggers before using the connection provider. *** } procedure SetTriggerConnectionOpening(Event:TrtcBoolEvent); // we are opening a new connection procedure SetTriggerConnectionClosing(Event:TrtcEvent); // we are closing the connection procedure SetTriggerConnectFail(Event:TrtcEvent); procedure SetTriggerConnectLost(Event:TrtcEvent); procedure SetTriggerConnectError(Event:TrtcExceptEvent); end; TRtcBasicClientProvider = class(TRtcClientProvider) protected FState:TRtcConnectionState; FPeerAddr, FPeerPort, FLocalAddr, FLocalPort:string; procedure SetLocalAddr(const Value: string); procedure SetLocalPort(const Value: string); procedure SetPeerAddr(const Value: string); procedure SetPeerPort(const Value: string); procedure SetState(value:TRtcConnectionState); property State:TRtcConnectionState read GetState write SetState; property PeerAddr:string read GetPeerAddr write SetPeerAddr; property PeerPort:string read GetPeerPort write SetPeerPort; property LocalAddr:string read GetLocalAddr write SetLocalAddr; property LocalPort:string read GetLocalPort write SetLocalPort; public constructor Create; override; procedure Release; override; function GetParent:TRtcConnectionProvider; override; function GetState:TRtcConnectionState; override; function GetPeerAddr:string; override; function GetPeerPort:string; override; function GetLocalAddr:string; override; function GetLocalPort:string; override; procedure Check; override; end; TRtcBasicServerProvider = class(TRtcServerProvider) protected FState:TRtcConnectionState; FPeerAddr, FPeerPort, FLocalAddr, FLocalPort:string; procedure SetLocalAddr(const Value: string); procedure SetLocalPort(const Value: string); procedure SetPeerAddr(const Value: string); procedure SetPeerPort(const Value: string); procedure SetState(value:TRtcConnectionState); property State:TRtcConnectionState read GetState write SetState; property PeerAddr:string read GetPeerAddr write SetPeerAddr; property PeerPort:string read GetPeerPort write SetPeerPort; property LocalAddr:string read GetLocalAddr write SetLocalAddr; property LocalPort:string read GetLocalPort write SetLocalPort; public constructor Create; override; procedure Release; override; function GetState:TRtcConnectionState; override; function GetPeerAddr:string; override; function GetPeerPort:string; override; function GetLocalAddr:string; override; function GetLocalPort:string; override; procedure Check; override; end; function GetNextConnID:TRtcConnID; implementation { TRtcConnectionProvider } constructor TRtcConnectionProvider.Create; begin inherited; FInSync:=False; FClosing:=False; FSilent:=False; FLost:=True; // if connection is closing and we didnt call disconnect, we lost it. FDataOut:=0; FDataIn:=0; TriggerBeforeCreate; end; destructor TRtcConnectionProvider.Destroy; begin TriggerAfterDestroy; inherited; end; function TRtcConnectionProvider.GetClosing: boolean; begin Enter; try Result:=FClosing; finally Leave; end; end; function TRtcConnectionProvider.GetLost: boolean; begin Enter; try Result:=FLost; finally Leave; end; end; function TRtcConnectionProvider.GetSilent: boolean; begin Enter; try Result:=FSilent; finally Leave; end; end; procedure TRtcConnectionProvider.SetClosing(a: boolean); begin Enter; try FClosing:=a; finally Leave; end; end; procedure TRtcConnectionProvider.SetLost(a: boolean); begin Enter; try FLost:=a; finally Leave; end; end; procedure TRtcConnectionProvider.SetSilent(a: boolean); begin Enter; try FSilent:=a; finally Leave; end; end; procedure TRtcConnectionProvider.Error(const text: string); begin if assigned(FError) then FError(text); end; function TRtcConnectionProvider.GetAddr: string; begin Result:=FAddr; end; function TRtcConnectionProvider.GetPort: string; begin Result:=FPort; end; procedure TRtcConnectionProvider.SetAddr(val: string); begin FAddr:=val; end; procedure TRtcConnectionProvider.SetError(Event: TRtcErrEvent); begin FError:=Event; end; procedure TRtcConnectionProvider.SetPort(val: string); begin FPort:=val; end; procedure TRtcConnectionProvider.SetTriggerAfterDestroy(Event: TrtcEvent); begin FOnAfterDestroy:=Event; end; procedure TRtcConnectionProvider.SetTriggerBeforeCreate(Event: TrtcEvent); begin FOnBeforeCreate:=Event; end; procedure TRtcConnectionProvider.SetTriggerConnect(Event: TrtcEvent); begin FOnConnect:=Event; end; procedure TRtcConnectionProvider.SetTriggerConnecting(Event: TrtcEvent); begin FOnConnecting:=Event; end; procedure TRtcConnectionProvider.SetTriggerDisconnecting(Event: TrtcEvent); begin FOnDisconnecting:=Event; end; procedure TRtcConnectionProvider.SetTriggerDataReceived(Event: TrtcEvent); begin FOnDataReceived:=Event; end; procedure TRtcConnectionProvider.SetTriggerDataLost(Event: TrtcEvent); begin FOnDataLost:=Event; end; procedure TRtcConnectionProvider.SetTriggerDataSent(Event: TrtcEvent); begin FOnDataSent:=Event; end; procedure TRtcConnectionProvider.SetTriggerDataOut(Event: TrtcEvent); begin FOnDataOut:=Event; end; procedure TRtcConnectionProvider.SetTriggerDataIn(Event: TrtcEvent); begin FOnDataIn:=Event; end; procedure TRtcConnectionProvider.SetTriggerLastWrite(Event: TrtcEvent); begin FOnLastWrite:=Event; end; procedure TRtcConnectionProvider.SetTriggerDisconnect(Event: TrtcEvent); begin FOnDisconnect:=Event; end; procedure TRtcConnectionProvider.SetTriggerException(Event: TrtcExceptEvent); begin FOnException:=Event; end; procedure TRtcConnectionProvider.SetTriggerReadyToRelease(Event: TrtcEvent); begin FOnReadyToRelease:=Event; end; procedure TRtcConnectionProvider.TriggerAfterDestroy; begin if assigned(FOnAfterDestroy) then FOnAfterDestroy; end; procedure TRtcConnectionProvider.TriggerBeforeCreate; begin if assigned(FOnBeforeCreate) then FOnBeforeCreate; end; procedure TRtcConnectionProvider.TriggerConnect; begin if assigned(FOnConnect) then FOnConnect; end; procedure TRtcConnectionProvider.TriggerConnecting; begin if assigned(FOnConnecting) then FOnConnecting; end; procedure TRtcConnectionProvider.TriggerDisconnecting; begin if assigned(FOnDisconnecting) then FOnDisconnecting; end; procedure TRtcConnectionProvider.TriggerDataReceived; begin if assigned(FOnDataReceived) then FOnDataReceived; end; procedure TRtcConnectionProvider.TriggerDataLost; begin if assigned(FOnDataLost) then FOnDataLost; end; procedure TRtcConnectionProvider.TriggerDataSent; begin if assigned(FOnDataSent) then FOnDataSent; end; procedure TRtcConnectionProvider.TriggerDataOut; begin if assigned(FOnDataOut) then FOnDataOut; end; procedure TRtcConnectionProvider.TriggerDataIn; begin if assigned(FOnDataIn) then FOnDataIn; end; procedure TRtcConnectionProvider.TriggerLastWrite; begin if assigned(FOnLastWrite) then FOnLastWrite; end; procedure TRtcConnectionProvider.TriggerDisconnect; begin if assigned(FOnDisconnect) then FOnDisconnect; end; procedure TRtcConnectionProvider.TriggerException(E: Exception); begin if assigned(FOnException) then FOnException(E); end; procedure TRtcConnectionProvider.TriggerReadyToRelease; begin if assigned(FOnReadyToRelease) then FOnReadyToRelease; end; function TRtcConnectionProvider.GetMultiThreaded: boolean; begin Result:=FMultiThreaded; end; procedure TRtcConnectionProvider.SetMultiThreaded(val: boolean); begin FMultiThreaded:=val; end; { TRtcServerProvider } procedure TRtcServerProvider.SetTriggerConnectionAccepting(Event: TrtcEvent); begin FOnConnectionAccepting:=Event; end; procedure TRtcServerProvider.SetTriggerConnectionAccepted(Event: TrtcEvent); begin FOnConnectionAccepted:=Event; end; procedure TRtcServerProvider.SetTriggerListenStart(Event: TrtcEvent); begin FOnListenStart:=Event; end; procedure TRtcServerProvider.SetTriggerListenStop(Event: TrtcEvent); begin FOnListenStop:=Event; end; procedure TRtcServerProvider.SetTriggerListenLost(Event: TrtcEvent); begin FOnListenLost:=Event; end; procedure TRtcServerProvider.SetTriggerNewProvider(Event: TrtcProviderEvent); begin FOnNewProvider:=Event; end; procedure TRtcServerProvider.TriggerConnectionAccepting; begin if assigned(FOnConnectionAccepting) then FOnConnectionAccepting; end; procedure TRtcServerProvider.TriggerConnectionAccepted; begin if assigned(FOnConnectionAccepted) then FOnConnectionAccepted; end; procedure TRtcServerProvider.TriggerListenStart; begin if assigned(FOnListenStart) then FOnListenStart; end; procedure TRtcServerProvider.TriggerListenStop; begin if assigned(FOnListenStop) then FOnListenStop; end; procedure TRtcServerProvider.TriggerListenLost; begin if assigned(FOnListenLost) then FOnListenLost; end; procedure TRtcServerProvider.SetTriggerConnectionLost(Event: TrtcEvent); begin FOnConnectionLost:=Event; end; procedure TRtcServerProvider.TriggerConnectionLost; begin if assigned(FOnConnectionLost) then FOnConnectionLost; end; procedure TRtcServerProvider.TriggerListenError(E: Exception); begin if assigned(FOnListenError) then FOnListenError(E); end; procedure TRtcServerProvider.SetTriggerListenError(Event: TrtcExceptEvent); begin FOnListenError:=Event; end; procedure TRtcServerProvider.TriggerNewProvider(var Provider: TObject); begin if assigned(FOnNewProvider) then FOnNewProvider(Provider); end; { TRtcClientProvider } procedure TRtcClientProvider.SetTriggerConnectError(Event: TrtcExceptEvent); begin FOnConnectError:=Event; end; procedure TRtcClientProvider.SetTriggerConnectFail(Event: TrtcEvent); begin FOnConnectFail:=Event; end; procedure TRtcClientProvider.SetTriggerConnectLost(Event: TrtcEvent); begin FOnConnectLost:=Event; end; procedure TRtcClientProvider.SetTriggerConnectionOpening(Event: TrtcBoolEvent); begin FOnConnectionOpening:=Event; end; procedure TRtcClientProvider.SetTriggerConnectionClosing(Event: TrtcEvent); begin FOnConnectionClosing:=Event; end; procedure TRtcClientProvider.TriggerConnectionClosing; begin if assigned(FOnConnectionClosing) then FOnConnectionClosing; end; procedure TRtcClientProvider.TriggerConnectError(E: Exception); begin if assigned(FOnConnectError) then FOnConnectError(E); end; procedure TRtcClientProvider.TriggerConnectFail; begin if assigned(FOnConnectFail) then FOnConnectFail; end; procedure TRtcClientProvider.TriggerConnectLost; begin if assigned(FOnConnectLost) then FOnConnectLost; end; procedure TRtcClientProvider.TriggerConnectionOpening(Force: boolean); begin if assigned(FOnConnectionOpening) then FOnConnectionOpening(Force); end; { TRtcBasicClientProvider } constructor TRtcBasicClientProvider.Create; begin inherited; FState:=conInactive; FLocalAddr:='0.0.0.0'; FLocalPort:=''; FPeerAddr:='0.0.0.0'; FPeerPort:=''; end; procedure TRtcBasicClientProvider.Release; begin Destroy; end; procedure TRtcBasicClientProvider.Check; begin // do nothing end; function TRtcBasicClientProvider.GetParent: TRtcConnectionProvider; begin Result:=nil; end; function TRtcBasicClientProvider.GetLocalAddr: string; begin Result:=FLocalAddr; end; function TRtcBasicClientProvider.GetLocalPort: string; begin Result:=FLocalPort; end; function TRtcBasicClientProvider.GetPeerAddr: string; begin Result:=FPeerAddr; end; function TRtcBasicClientProvider.GetPeerPort: string; begin Result:=FPeerPort; end; function TRtcBasicClientProvider.GetState: TRtcConnectionState; begin Enter; try Result:=FState; finally Leave; end; end; procedure TRtcBasicClientProvider.SetLocalAddr(const Value: string); begin FLocalAddr:=Value; end; procedure TRtcBasicClientProvider.SetLocalPort(const Value: string); begin FLocalPort:=Value; end; procedure TRtcBasicClientProvider.SetPeerAddr(const Value: string); begin FPeerAddr:=Value; end; procedure TRtcBasicClientProvider.SetPeerPort(const Value: string); begin FPeerPort:=Value; end; procedure TRtcBasicClientProvider.SetState(value: TRtcConnectionState); begin Enter; try FState:=Value; finally Leave; end; end; { TRtcBasicServerProvider } constructor TRtcBasicServerProvider.Create; begin inherited; FState:=conInactive; FLocalAddr:='0.0.0.0'; FLocalPort:=''; FPeerAddr:='0.0.0.0'; FPeerPort:=''; end; procedure TRtcBasicServerProvider.Release; begin Destroy; end; procedure TRtcBasicServerProvider.Check; begin // do nothing end; function TRtcBasicServerProvider.GetLocalAddr: string; begin Result:=FLocalAddr; end; function TRtcBasicServerProvider.GetLocalPort: string; begin Result:=FLocalPort; end; function TRtcBasicServerProvider.GetPeerAddr: string; begin Result:=FPeerAddr; end; function TRtcBasicServerProvider.GetPeerPort: string; begin Result:=FPeerPort; end; function TRtcBasicServerProvider.GetState: TRtcConnectionState; begin Result:=FState; end; procedure TRtcBasicServerProvider.SetLocalAddr(const Value: string); begin FLocalAddr:=Value; end; procedure TRtcBasicServerProvider.SetLocalPort(const Value: string); begin FLocalPort:=Value; end; procedure TRtcBasicServerProvider.SetPeerAddr(const Value: string); begin FPeerAddr:=Value; end; procedure TRtcBasicServerProvider.SetPeerPort(const Value: string); begin FPeerPort:=Value; end; procedure TRtcBasicServerProvider.SetState(value: TRtcConnectionState); begin FState:=Value; end; const MaxConnID:longint=2000000000; var GlobalConnID:longint=1; CS:TRtcCritSec; function GetNextConnID:TRtcConnID; begin CS.Enter; try if GlobalConnID>=MaxConnID then GlobalConnID:=1 else Inc(GlobalConnID); Result:=GlobalConnID; finally CS.Leave; end; end; initialization CS:=TRtcCritSec.Create; finalization Garbage(CS); end.
unit uFrameDateView; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UI.Standard, UI.Base, UI.Frame, UI.Calendar, FMX.Controls.Presentation, FMX.Gestures; type TFrameDateView = class(TFrame) LinearLayout1: TLinearLayout; btnBack: TTextView; tvTitle: TTextView; CalendarView1: TCalendarView; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CalendarLanguage_CN1: TCalendarLanguage_CN; GestureManager1: TGestureManager; txtHint: TTextView; procedure btnBackClick(Sender: TObject); procedure CheckBox1Change(Sender: TObject); procedure CheckBox2Change(Sender: TObject); procedure CalendarView1ClickView(Sender: TObject; const ID: Integer); private { Private declarations } public { Public declarations } end; implementation {$R *.fmx} procedure TFrameDateView.btnBackClick(Sender: TObject); begin Finish; end; procedure TFrameDateView.CalendarView1ClickView(Sender: TObject; const ID: Integer); begin case ID of InvaludeDate: txtHint.Text := 'InvaludeDate'; BID_Up: txtHint.Text := 'Up clicked'; BID_Next: txtHint.Text := 'Next clicked'; BID_Today: txtHint.Text := 'Today clicked'; BID_Navigation: txtHint.Text := 'Navigation clicked'; BID_Clear: txtHint.Text := 'Clear clicked'; else txtHint.Text := FormatDateTime('yyyy-mm-dd', ID); end; end; procedure TFrameDateView.CheckBox1Change(Sender: TObject); begin if CheckBox1.IsChecked then CalendarView1.Language := CalendarLanguage_CN1 else CalendarView1.Language := nil; end; procedure TFrameDateView.CheckBox2Change(Sender: TObject); begin if CheckBox2.IsChecked then CalendarView1.Options := CalendarView1.Options + [coShowLunar] else CalendarView1.Options := CalendarView1.Options - [coShowLunar] end; end.
unit MainForm; {$MODE Delphi} interface uses LCLIntf, LCLType, LMessages, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, Buttons, Contnrs, ExtDlgs, StdCtrls, Menus, ImageKnifeDocument, RectGrid, Grids; type { TForm1 } TForm1 = class(TForm) StatusBar1: TStatusBar; Panel1: TPanel; OpenPictureDialog1: TOpenPictureDialog; btnExport: TSpeedButton; SaveDialog1: TSaveDialog; btnAutoName: TButton; tbCompression: TTrackBar; MainMenu1: TMainMenu; mnuFile: TMenuItem; mnuFileNew: TMenuItem; mnuFileOpen: TMenuItem; mnuFileSave: TMenuItem; mnuFileSaveAs: TMenuItem; N1: TMenuItem; mnuFileExport: TMenuItem; N2: TMenuItem; mnuFileExit: TMenuItem; mnuFileClose: TMenuItem; SpeedButton3: TSpeedButton; SpeedButton4: TSpeedButton; SpeedButton5: TSpeedButton; saveKnife: TSaveDialog; openKnife: TOpenDialog; popSlice: TPopupMenu; Deleteslice1: TMenuItem; mnuView: TMenuItem; mnuViewRefresh: TMenuItem; Panel2: TPanel; TreeView1: TTreeView; Memo1: TMemo; ScrollBox1: TScrollBox; Splitter1: TSplitter; PaintBox1: TPaintBox; N3: TMenuItem; mnuViewZoomIn: TMenuItem; mnuViewZoomOut: TMenuItem; mnuViewZoomNormal: TMenuItem; Splitter2: TSplitter; Panel3: TPanel; chkSingleColor: TCheckBox; Label1: TLabel; lblSingleColor: TLabel; btnPickSingleColor: TSpeedButton; btnScan1: TButton; Panel4: TPanel; btnSelector: TSpeedButton; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; chkAcross: TCheckBox; btnSelectParents: TSpeedButton; btnGroup: TSpeedButton; chkBackground: TCheckBox; Label3: TLabel; cmbVAlign: TComboBox; btnRefreshWidth: TBitBtn; StringGrid1: TStringGrid; procedure FormCreate(Sender: TObject); procedure mnuFileExitClick(Sender: TObject); procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: String); procedure TreeView1Change(Sender: TObject; Node: TTreeNode); procedure btnAutoNameClick(Sender: TObject); procedure mnuFileNewClick(Sender: TObject); procedure mnuFileSaveClick(Sender: TObject); procedure mnuFileSaveAsClick(Sender: TObject); procedure mnuFileOpenClick(Sender: TObject); procedure mnuViewRefreshClick(Sender: TObject); procedure mnuFileExportClick(Sender: TObject); procedure mnuViewZoomNormalClick(Sender: TObject); procedure mnuViewZoomInClick(Sender: TObject); procedure mnuViewZoomOutClick(Sender: TObject); procedure chkSingleColorClick(Sender: TObject); procedure btnScan1Click(Sender: TObject); procedure btnSelectorClick(Sender: TObject); procedure btnSelectParentsClick(Sender: TObject); procedure btnGroupClick(Sender: TObject); procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure chkBackgroundClick(Sender: TObject); procedure cmbVAlignChange(Sender: TObject); procedure btnRefreshWidthClick(Sender: TObject); procedure StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); private document: TImageKnifeDocument; rgSelection: TObjectList; OldMarker: TPoint; MarkerMode: (mmSelect, mmSelectParents, mmHorizontal, mmVertical, mmCross); zoomLevel: Double; procedure DrawCross(const ptPhysical: TPoint); procedure DrawHorizontal(const ptPhysical: TPoint); procedure DrawVertical(const ptPhysical: TPoint); procedure DrawMarker(const ptLogical: TPoint); procedure SaveRect(const Filename: String; const rt: TRect); procedure BuildTree; procedure BuildHTML; procedure BuildTreeOneLevel(const node: TTreeNode; const rg: TRectGrid); procedure ResizePaintBox; procedure DocumentChanged; procedure SelectionChanged; function PhysicalPoint(const ptLogical: TPoint): TPoint; function LogicalPoint(const ptPhysical: TPoint): TPoint; function PhysicalRect(const rtLogical: TRect): TRect; function LogicalRect(const rtPhysical: TRect): TRect; procedure InitializePropertyGrid; function GetGridProperty(const Index: String): String; procedure SetGridProperty(const Index: String; const Value: String); public property GridProperty[const Index: String]: String read GetGridProperty write SetGridProperty; end; var Form1: TForm1; implementation {$R *.lfm} procedure TForm1.DrawCross(const ptPhysical: TPoint); begin with PaintBox1.Canvas do begin MoveTo(0, ptPhysical.Y); LineTo(ptPhysical.X, ptPhysical.Y); LineTo(ptPhysical.X, 0); MoveTo(PaintBox1.Width, ptPhysical.Y); LineTo(ptPhysical.X, ptPhysical.Y); LineTo(ptPhysical.X, PaintBox1.Height); end; end; procedure TForm1.DrawHorizontal(const ptPhysical: TPoint); begin with PaintBox1.Canvas do begin MoveTo(0, ptPhysical.Y); LineTo(PaintBox1.Width, ptPhysical.Y); end; end; procedure TForm1.DrawVertical(const ptPhysical: TPoint); begin with PaintBox1.Canvas do begin MoveTo(ptPhysical.X, 0); LineTo(ptPhysical.X, PaintBox1.Height); end; end; function TForm1.PhysicalPoint(const ptLogical: TPoint): TPoint; begin Result.X := Round(ptLogical.X * zoomLevel); Result.Y := Round(ptLogical.Y * zoomLevel); end; function TForm1.LogicalPoint(const ptPhysical: TPoint): TPoint; begin Result.X := Round(ptPhysical.X / zoomLevel); Result.Y := Round(ptPhysical.Y / zoomLevel); end; function TForm1.PhysicalRect(const rtLogical: TRect): TRect; begin Result.Left := Round(rtLogical.Left * zoomLevel); Result.Top := Round(rtLogical.Top * zoomLevel); Result.Right := Round(rtLogical.Right * zoomLevel); Result.Bottom := Round(rtLogical.Bottom * zoomLevel); end; function TForm1.LogicalRect(const rtPhysical: TRect): TRect; begin Result.Left := Round(rtPhysical.Left / zoomLevel); Result.Top := Round(rtPhysical.Top / zoomLevel); Result.Right := Round(rtPhysical.Right / zoomLevel); Result.Bottom := Round(rtPhysical.Bottom / zoomLevel); end; procedure TForm1.DrawMarker(const ptLogical: TPoint); var ptPhysical: TPoint; begin if document.Empty then Exit; if (0 = ptLogical.X) and (0 = ptLogical.Y) then exit; ptPhysical := PhysicalPoint(ptLogical); PaintBox1.Canvas.Pen.Mode := pmNot; case MarkerMode of mmHorizontal: DrawHorizontal(ptPhysical); mmVertical: DrawVertical(ptPhysical); mmCross: DrawCross(ptPhysical); end; PaintBox1.Canvas.Pen.Mode := pmCopy; end; procedure TForm1.FormCreate(Sender: TObject); begin rgSelection := TObjectList.Create(False); document := TImageKnifeDocument.Create; zoomLevel := 1; OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmSelect; BuildTree; InitializePropertyGrid; end; procedure TForm1.mnuFileExitClick(Sender: TObject); begin Close; end; procedure TForm1.SaveRect(const Filename: String; const rt: TRect); var bmp: TBitmap; //png: TPNGObject; begin bmp := TBitmap.Create; bmp.Width := rt.Right - rt.Left; bmp.Height := rt.Bottom - rt.Top; bmp.Canvas.CopyRect(Rect(0, 0, bmp.Width, bmp.Height), document.NormalImage.Bitmap.Canvas, rt); //png := TPNGObject.Create; //png.Assign(bmp); bmp.Free; //png.CompressionLevel := tbCompression.Position; //png.SaveToFile(Filename); //png.Free; end; procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var pt: TPoint; begin DrawMarker(OldMarker); pt := LogicalPoint(Point(X, Y)); DrawMarker(pt); OldMarker := pt; StatusBar1.SimpleText := IntToStr(OldMarker.X) + '-' + IntToStr(OldMarker.Y); end; procedure TForm1.SpeedButton1Click(Sender: TObject); begin DrawMarker(OldMarker); OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmHorizontal; end; procedure TForm1.SpeedButton2Click(Sender: TObject); begin DrawMarker(OldMarker); OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmVertical; end; procedure TForm1.SpeedButton3Click(Sender: TObject); begin DrawMarker(OldMarker); OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmCross; end; procedure TForm1.FormDestroy(Sender: TObject); begin document.Free; rgSelection.Free; end; procedure TForm1.PaintBox1Paint(Sender: TObject); const stColor: array [TSliceType] of TColor = (clGray, clRed, clBlue); var k: TObjectList; rg: TRectGrid; x, y: Integer; i: Integer; physRect: TRect; begin if document.Empty then Exit; k := TObjectList.Create(False); k.Add(document.Grid); PaintBox1.Canvas.StretchDraw(PaintBox1.ClientRect, document.NormalImage.Bitmap); //PaintBox1.Canvas.CopyRect(PaintBox1.ClientRect, document.NormalImage.Bitmap.Canvas, PaintBox1.ClientRect); PaintBox1.Canvas.Brush.Color := clBlue; PaintBox1.Canvas.Brush.Style := bsSolid; while k.Count > 0 do begin rg := k[0] as TRectGrid; physRect := PhysicalRect(rg.Rect); k.Delete(0); if rg.Sliced then begin for i := 0 to rg.Kids.Count - 1 do k.Add(rg.Kids[i]); end else begin PaintBox1.Canvas.FrameRect(physRect); end; end; for i := 0 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; physRect := PhysicalRect(rg.Rect); for y := physRect.Top to physRect.Bottom - 1 do for x := physRect.Left to physRect.Right - 1 do if ((x mod 3) = 0) and ((y mod 3) = 0) then PaintBox1.Canvas.Pixels[x, y] := stColor[rg.SliceType]; end; k.Free; end; procedure TForm1.BuildTree; begin TreeView1.Items.Clear; if not document.Empty then begin BuildTreeOneLevel(nil, document.Grid); TreeView1.Items[0].Expand(True); end; BuildHTML; end; procedure TForm1.BuildTreeOneLevel(const node: TTreeNode; const rg: TRectGrid); var nn: TTreeNode; i: Integer; begin nn := TreeView1.Items.AddChild(node, rg.Name); nn.Data := rg; if (rg.Sliced) then for i := 0 to rg.Kids.Count - 1 do BuildTreeOneLevel(nn, rg.Kids[i]); end; procedure TForm1.TreeView1Edited(Sender: TObject; Node: TTreeNode; var S: String); var rg: TRectGrid; begin rg := TRectGrid(Node.Data); rg.Name := S; end; procedure TForm1.TreeView1Change(Sender: TObject; Node: TTreeNode); var rg: TRectGrid; begin DrawMarker(OldMarker); rg := TRectGrid(Node.Data); rgSelection.Clear; rgSelection.Add(rg); SelectionChanged; PaintBox1.Refresh; DrawMarker(OldMarker); end; procedure TForm1.btnAutoNameClick(Sender: TObject); procedure RenameKids(rg: TRectGrid); var i: Integer; s: String; begin if not rg.Sliced then Exit; if rg.SliceType = stHorizontal then s := 'r' else s := 'c'; for i := 0 to rg.Kids.Count - 1 do begin rg.Kids[i].Name := rg.Name + '-' + s + IntToStr(i + 1); RenameKids(rg.Kids[i]); end; end; begin if document.Empty then Exit; document.Grid.Name := 'cell'; RenameKids(document.Grid); BuildTree; end; function HTMLColor(col: DWORD): String; begin Result := '#' + IntToHex(GetRValue(col), 2) + IntToHex(GetGValue(col), 2) + IntToHex(GetBValue(col), 2); end; procedure TForm1.BuildHTML; procedure AddText(const template, Value: String); begin if Value <> '' then Memo1.Text := Memo1.Text + StringReplace(template, '?', Value, []); end; procedure OpenTD(const rg: TRectGrid); begin Memo1.Lines.Append('<td'); AddText(' valign="?"', rg.Attributes['valign']); if rg.IsSingleColor then AddText(' bgcolor="?"', HTMLColor(rg.SingleColor)); if rg.IsBackground then begin Memo1.Text := Memo1.Text + ' style="'; AddText('background-repeat: ?;', rg.Attributes['background-repeat']); AddText('background-position: ?;', rg.Attributes['background-position']); AddText('background-image:url(''?'')', rg.Name + '.png'); Memo1.Text := Memo1.Text + '"'; end; AddText(' width="?"', rg.Attributes['width']); Memo1.Text := Memo1.Text + '>'; end; procedure WriteSimpleCell(const rg: TRectGrid); begin OpenTD(rg); AddText('<a href="?">', rg.Attributes['href']); if rg.IsSingleColor or rg.IsBackground then Memo1.Text := Memo1.Text + rg.Attributes['text'] else Memo1.Text := Memo1.Text + '<img alt="" border="0" src="' + rg.Name + '.png">'; AddText('</a>', rg.Attributes['href']); Memo1.Text := Memo1.Text + '</td>'; end; procedure WriteHTMLTable(const rg: TRectGrid); var i, j: Integer; begin for i := 0 to rg.Kids.Count - 1 do begin Memo1.Lines.Append('<tr>'); for j := 0 to rg.Kids[i].Kids.Count - 1 do WriteSimpleCell(rg.Kids[i].Kids[j]); Memo1.Lines.Append('</tr>'); end; end; procedure WriteInvertedHTMLTable(const rg: TRectGrid); var i, j: Integer; begin for j := 0 to rg.Kids[0].Kids.Count - 1 do begin Memo1.Lines.Append('<tr>'); for i := 0 to rg.Kids.Count - 1 do WriteSimpleCell(rg.Kids[i].Kids[j]); Memo1.Lines.Append('</tr>'); end; end; function IsHTMLTable(const rg: TRectGrid): Boolean; var i, j: Integer; oldcount: Integer; oldwidth: Integer; begin Result := False; if (rg.SliceType = stHorizontal) then begin for i := 0 to rg.Kids.Count - 1 do if rg.Kids[i].SliceType <> stVertical then Exit; oldcount := rg.Kids[0].Kids.Count; for i := 1 to rg.Kids.Count - 1 do if oldcount <> rg.Kids[i].Kids.Count then Exit; for i := 0 to rg.Kids.Count - 1 do for j := 0 to rg.Kids[i].Kids.Count - 1 do if rg.Kids[i].Kids[j].Sliced then Exit; for j := 0 to oldcount - 1 do begin oldwidth := rg.Kids[0].Kids[j].Rect.Right - rg.Kids[0].Kids[j].Rect.Left; for i := 1 to rg.Kids.Count - 1 do if oldwidth <> (rg.Kids[i].Kids[j].Rect.Right - rg.Kids[i].Kids[j].Rect.Left) then Exit; end; end; Result := True; end; function IsInvertedHTMLTable(const rg: TRectGrid): Boolean; var i, j: Integer; oldcount: Integer; oldheight: Integer; begin Result := False; if (rg.SliceType = stVertical) then begin for i := 0 to rg.Kids.Count - 1 do if rg.Kids[i].SliceType <> stHorizontal then Exit; oldcount := rg.Kids[0].Kids.Count; for i := 1 to rg.Kids.Count - 1 do if oldcount <> rg.Kids[i].Kids.Count then Exit; for i := 0 to rg.Kids.Count - 1 do for j := 0 to rg.Kids[i].Kids.Count - 1 do if rg.Kids[i].Kids[j].Sliced then Exit; for j := 0 to oldcount - 1 do begin oldheight := rg.Kids[0].Kids[j].Rect.Bottom - rg.Kids[0].Kids[j].Rect.Top; for i := 1 to rg.Kids.Count - 1 do if oldheight <> (rg.Kids[i].Kids[j].Rect.Bottom - rg.Kids[i].Kids[j].Rect.Top) then Exit; end; end; Result := True; end; procedure BuildHTMLOneLevel(const rg: TRectGrid); var i: Integer; begin if rg.SliceType = stNone then Memo1.Text := Memo1.Text + '<img src="' + rg.Name + '.png">' else begin Memo1.Lines.Append('<table'); AddText(' width="?"', rg.Attributes['width']); Memo1.Text := Memo1.Text + ' border="0" cellpadding="0" cellspacing="0">'; if rg.SliceType = stHorizontal then begin if (IsHTMLTable(rg)) then WriteHTMLTable(rg) else for i := 0 to rg.Kids.Count - 1 do begin if (rg.Kids[i].Sliced) then begin Memo1.Lines.Append('<tr>'); OpenTD(rg.Kids[i]); BuildHTMLOneLevel(rg.Kids[i]); Memo1.Text := Memo1.Text + '</td>'; Memo1.Lines.Append('</tr>'); end else begin Memo1.Lines.Append('<tr>'); WriteSimpleCell(rg.Kids[i]); Memo1.Lines.Append('</tr>'); end; end; end else begin { stVertical } if (IsInvertedHTMLTable(rg)) then WriteInvertedHTMLTable(rg) else begin Memo1.Lines.Append('<tr>'); for i := 0 to rg.Kids.Count - 1 do begin if (rg.Kids[i].Sliced) then begin OpenTD(rg.Kids[i]); BuildHTMLOneLevel(rg.Kids[i]); Memo1.Text := Memo1.Text + '</td>'; end else begin WriteSimpleCell(rg.Kids[i]); end; end; Memo1.Lines.Append('</tr>'); end; end; Memo1.Lines.Append('</table>'); end; end; begin Memo1.Text := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"'; Memo1.Lines.Append('"http://www.w3.org/TR/html4/loose.dtd">'); Memo1.Lines.Append('<html>'); Memo1.Lines.Append('<head>'); Memo1.Lines.Append('<title>QuickWeb</title>'); Memo1.Lines.Append('<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >'); Memo1.Lines.Append('</head>'); Memo1.Lines.Append('<body>'); if not document.Empty then BuildHTMLOneLevel(document.Grid); Memo1.Lines.Append('</body></html>'); end; procedure TForm1.mnuFileNewClick(Sender: TObject); //var //tmp: TImageKnifeDocument; begin //tmp := TImageKnifeDocument.Create; rgSelection.Clear; try OpenPictureDialog1.Title := 'Select normal image'; if OpenPictureDialog1.Execute then begin document.NormalImageFilename := OpenPictureDialog1.Filename; OpenPictureDialog1.Title := 'Select rollover image'; if OpenPictureDialog1.Execute then begin document.OverImageFilename := OpenPictureDialog1.Filename; end; //document.Free; //document := tmp; //tmp := nil; DocumentChanged; end; finally //if tmp <> nil then tmp.Free; end; end; procedure TForm1.mnuFileSaveClick(Sender: TObject); begin if document.Filename = '' then mnuFileSaveAsClick(Sender) else document.SaveToFile(document.Filename); end; procedure TForm1.mnuFileSaveAsClick(Sender: TObject); begin if saveKnife.Execute then begin document.SaveToFile(saveKnife.Filename); document.Filename := saveKnife.Filename; end; end; procedure TForm1.mnuFileOpenClick(Sender: TObject); //var //tmp: TImageKnifeDocument; begin //tmp := TImageKnifeDocument.Create; rgSelection.Clear; try if openKnife.Execute then begin document.LoadFromFile(openKnife.Filename); document.Filename := openKnife.Filename; //document.Free; //document := tmp; //tmp := nil; DocumentChanged; end; finally //if tmp <> nil then tmp.Free; end; end; procedure TForm1.mnuViewRefreshClick(Sender: TObject); begin PaintBox1.Refresh; DrawMarker(OldMarker); end; procedure TForm1.mnuFileExportClick(Sender: TObject); var strPath: String; k: TObjectList; rg: TRectGrid; i: Integer; begin if document.Empty then Exit; with SaveDialog1 do if Execute then begin strPath := ExtractFilePath(Filename); k := TObjectList.Create(False); k.Add(document.Grid); while k.Count > 0 do begin rg := k[0] as TRectGrid; k.Delete(0); if rg.Sliced then begin for i := 0 to rg.Kids.Count - 1 do k.Add(rg.Kids[i]); end else begin if not rg.IsSingleColor then SaveRect(strPath + rg.Name + '.png', rg.Rect); end; end; k.Free; Memo1.Lines.SaveToFile(FileName); end; end; procedure TForm1.ResizePaintBox; begin PaintBox1.SetBounds(PaintBox1.Left, PaintBox1.Top, Round(zoomLevel * document.Width), Round(zoomLevel * document.Height)); end; procedure TForm1.DocumentChanged; begin ResizePaintBox; //PaintBox1.Repaint; BuildTree; end; procedure TForm1.mnuViewZoomNormalClick(Sender: TObject); begin zoomLevel := 1; ResizePaintBox; end; procedure TForm1.mnuViewZoomInClick(Sender: TObject); begin zoomLevel := zoomLevel * 2; ResizePaintBox; end; procedure TForm1.mnuViewZoomOutClick(Sender: TObject); begin zoomLevel := zoomLevel / 2; ResizePaintBox; end; procedure TForm1.chkSingleColorClick(Sender: TObject); var rg: TRectGrid; begin if rgSelection.Count = 1 then begin rg := rgSelection[0] as TRectGrid; rg.IsSingleColor := chkSingleColor.Checked; if rg.IsSingleColor then begin rg.SingleColor := document.NormalImage.Bitmap.Canvas.Pixels[rg.Rect.Left, rg.Rect.Top]; lblSingleColor.Color := rg.SingleColor; end; end; end; procedure TForm1.btnScan1Click(Sender: TObject); var k: TObjectList; rg: TRectGrid; i: Integer; x, y: Integer; lastColor: TColor; rt: TRect; found: Boolean; begin if document.Empty then Exit; k := TObjectList.Create(False); k.Add(document.Grid); while k.Count > 0 do begin rg := k[0] as TRectGrid; k.Delete(0); if rg.Sliced then begin for i := 0 to rg.Kids.Count - 1 do k.Add(rg.Kids[i]); end else begin rt := rg.Rect; found := False; lastColor := document.NormalImage.Bitmap.Canvas.Pixels[rt.Left, rt.Top]; for y := rt.Top to rt.Bottom - 1 do for x := rt.Left to rt.Right - 1 do if lastColor <> document.NormalImage.Bitmap.Canvas.Pixels[x, y] then begin found := True; Break; end; if not found then begin rg.IsSingleColor := True; rg.SingleColor := lastColor; end; end; end; k.Free; end; procedure TForm1.btnSelectorClick(Sender: TObject); begin rgSelection.Clear; PaintBox1.Repaint; DrawMarker(OldMarker); OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmSelect; end; procedure TForm1.btnSelectParentsClick(Sender: TObject); begin rgSelection.Clear; PaintBox1.Repaint; DrawMarker(OldMarker); OldMarker.X := 0; OldMarker.Y := 0; MarkerMode := mmSelectParents; end; procedure TForm1.btnGroupClick(Sender: TObject); var iMin, iMax: Integer; i, iCur: Integer; rg, oldParent: TRectGrid; begin if rgSelection.Count <= 1 then Exit; rg := rgSelection[0] as TRectGrid; oldParent := rg.Parent; iMin := oldParent.Kids.IndexOf(rg); iMax := iMin; for i := 1 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; if rg.Parent <> oldParent then raise Exception.Create('All selected rects must belong to the same parent'); iCur := oldParent.Kids.IndexOf(rg); if iCur < iMin then iMin := iCur; if iCur > iMax then iMax := iCur; end; if (iMax - iMin + 1 > rgSelection.Count) then raise Exception.Create('Selection must be contiguous'); rgSelection.Clear; oldParent.GroupKids(iMin, iMax); PaintBox1.Repaint; BuildTree; end; procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var k: TObjectList; rg: TRectGrid; i: Integer; begin if document.Empty then Exit; DrawMarker(OldMarker); k := TObjectList.Create(False); if (chkAcross.Checked) and (MarkerMode in [mmHorizontal, mmVertical]) then begin if MarkerMode = mmHorizontal then document.Grid.RectsFromY(OldMarker.Y, k) else if MarkerMode = mmVertical then document.Grid.RectsFromX(OldMarker.X, k); end else k.Add(document.Grid.RectFromPos(Point(OldMarker.X, OldMarker.Y))); if MarkerMode = mmSelect then begin if ssCtrl in Shift then begin for i := 0 to k.Count - 1 do begin rg := k[i] as TRectGrid; if (rgSelection.IndexOf(rg) < 0) then rgSelection.Add(rg) else rgSelection.Remove(rg); end; end else begin rgSelection.Clear; for i := 0 to k.Count - 1 do begin rg := k[i] as TRectGrid; rgSelection.Add(rg); end; end; end else if MarkerMode = mmSelectParents then begin if ssCtrl in Shift then begin for i := 0 to k.Count - 1 do begin rg := (k[i] as TRectGrid).Parent; if (rgSelection.IndexOf(rg) < 0) then rgSelection.Add(rg) else rgSelection.Remove(rg); end; end else begin rgSelection.Clear; for i := 0 to k.Count - 1 do begin rg := (k[i] as TRectGrid).Parent; rgSelection.Add(rg); end; end; end else begin for i := 0 to k.Count - 1 do begin rg := k[i] as TRectGrid; case MarkerMode of mmHorizontal: rg.SliceHorizontal(OldMarker.Y); mmVertical: rg.SliceVertical(OldMarker.X); end; end; end; PaintBox1.Refresh; DrawMarker(OldMarker); k.Free; if MarkerMode in [mmHorizontal, mmVertical] then BuildTree else if MarkerMode in [mmSelect, mmSelectParents] then SelectionChanged; end; procedure TForm1.InitializePropertyGrid; begin StringGrid1.RowCount := 5; StringGrid1.ColCount := 2; StringGrid1.Cells[0, 0] := 'text'; StringGrid1.Cells[0, 1] := 'href'; StringGrid1.Cells[0, 2] := 'width'; StringGrid1.Cells[0, 3] := 'background-repeat'; StringGrid1.Cells[0, 4] := 'background-position'; end; function TForm1.GetGridProperty(const Index: String): String; var i: Integer; begin Result := ''; for i := 0 to StringGrid1.RowCount - 1 do if StringGrid1.Cells[0, i] = Index then begin Result := StringGrid1.Cells[1, i]; Break; end; end; procedure TForm1.SetGridProperty(const Index: String; const Value: String); var i: Integer; begin for i := 0 to StringGrid1.RowCount - 1 do if StringGrid1.Cells[0, i] = Index then begin StringGrid1.Cells[1, i] := Value; Break; end; end; procedure TForm1.SelectionChanged; var rg: TRectGrid; i: Integer; begin if rgSelection.Count = 1 then begin rg := rgSelection[0] as TRectGrid; chkSingleColor.Checked := rg.IsSingleColor; if rg.IsSingleColor then begin lblSingleColor.Color := rg.SingleColor; //lblSingleColor.Visible := True; //btnPickSingleColor.Visible := True; end else begin //lblSingleColor.Enabled := False; //btnPickSingleColor.Enabled := False; end; chkBackground.Checked := rg.IsBackground; cmbVAlign.ItemIndex := cmbVAlign.Items.IndexOf(rg.Attributes['valign']); for i := 0 to StringGrid1.RowCount - 1 do StringGrid1.Cells[1, i] := rg.Attributes[StringGrid1.Cells[0, i]]; end; end; procedure TForm1.chkBackgroundClick(Sender: TObject); var rg: TRectGrid; i: Integer; begin for i := 0 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; rg.IsBackground := chkBackground.Checked; end; end; procedure TForm1.cmbVAlignChange(Sender: TObject); var rg: TRectGrid; i: Integer; begin for i := 0 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; rg.Attributes['valign'] := cmbVAlign.Text; end; end; procedure TForm1.btnRefreshWidthClick(Sender: TObject); var rg: TRectGrid; i: Integer; begin for i := 0 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; rg.Attributes['width'] := IntToStr(rg.Rect.Right - rg.Rect.Left); GridProperty['width'] := rg.Attributes['width']; { stupid code } end; end; procedure TForm1.StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); var rg: TRectGrid; i: Integer; strName: String; begin strName := StringGrid1.Cells[0, ARow]; for i := 0 to rgSelection.Count - 1 do begin rg := rgSelection[i] as TRectGrid; rg.Attributes[strName] := Value; end; end; end.