text stringlengths 14 6.51M |
|---|
unit uSetupDatabaseActions;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
Windows,
uActions,
SysUtils,
uAssociations,
uInstallScope,
uConstants,
uUserUtils;
const
InstallPoints_StartProgram = 1024 * 1024;
InstallPoints_SetUpDatabaseProgram = 1024 * 1024;
type
TSetupDatabaseActions = class(TInstallAction)
public
function CalculateTotalPoints : Int64; override;
procedure Execute(Callback : TActionCallback); override;
end;
implementation
{ TSetupDatabaseActions }
function TSetupDatabaseActions.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_StartProgram + InstallPoints_SetUpDatabaseProgram;
end;
procedure TSetupDatabaseActions.Execute(Callback: TActionCallback);
var
PhotoDBExeFile: string;
Terminate: Boolean;
begin
inherited;
PhotoDBExeFile := IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName;
RunAsUser(PhotoDBExeFile, '/install /NoLogo', CurrentInstall.DestinationPath, True);
Callback(Self, InstallPoints_StartProgram + InstallPoints_SetUpDatabaseProgram, CalculateTotalPoints, Terminate);
end;
end.
|
(* WPSPELL.PAS - Copyright (c) 1995-1996, Eminent Domain Software *)
unit WPSpell;
{-WordPerfect style spell dialog for EDSSpell component}
{$D-}
{$L-}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, Menus,
{$IFDEF Win32}
{$IFDEF Ver100}
LexDCTD3,
{$ELSE}
LexDCT32,
{$ENDIF}
{$ELSE}
LexDCT,
{$ENDIF}
ExtCtrls, EDSUtil, AbsSpell, SpellGbl;
{$I SpellDef.PAS}
type
TWPLabels = (tlblFound, tlblNotFound, tlblReplace, tlblSuggestions,
tbtnReplace, tbtnAdd, tbtnSkip, tbtnSkipAll,
tbtnSuggest, tbtnClose);
TLabelArray = array[TWPLabels] of string[20];
const
cLabels : array[TLanguages] of TLabelArray = (
{$IFDEF SupportEnglish}
{English} ('Found', 'Not Found', 'Replace &With', 'Sugg&estions',
'&Replace', '&Add', 'Skip &Once', 'Skip &Always',
'&Suggest', 'Close')
{$ENDIF}
{$IFDEF SupportSpanish}
{Spanish} ,('Encontrado', 'No Encontrado', 'Reemplazar Con', 'Sugerencias',
'Reemplazar', 'Añadir', 'Saltar', 'Ignorar',
'Sugerir', 'Cerrar')
{$ENDIF}
{$IFDEF SupportBritish}
{British} ,('Found', 'Not Found', 'Replace &With', 'Sugg&estions',
'&Replace', '&Add', 'Skip &Once', 'Skip &Always',
'&Suggest', 'Close')
{$ENDIF}
{$IFDEF SupportItalian}
{Italian} ,('Trovato', 'Non trovato', 'Modifica', 'Suggerimenti',
'Sostituisci', 'Aggiungi', 'Salta', 'Salta Tutti',
'Suggerisci', 'Cancella')
{$ENDIF}
{$IFDEF SupportFrench}
{French} ,('Dans le dictionaire', 'Pas dans le dictionarie', 'Remplacer par', 'Sugg&estions',
'&Remplacer', '&Ahouter', '&Ignorer', 'Ignorer toujours',
'Suggérer', 'Annuler')
{$ENDIF}
{$IFDEF SupportGerman}
{German} ,('Gefunden', 'Nicht Gefunden', 'Ersetze &Mit', '&Vorschläge',
'&Ersetze', 'E&infügen', 'Ü&berspringe', 'Überspringe &Immer',
'&Schlage vor', 'Schließen')
{$ENDIF}
{$IFDEF SupportDutch}
{Dutch} ,('Gevonden', 'Niet gevonden', 'Vervangen door', 'Suggesties',
'Vervang', 'Toevoegen', 'Negeer', 'Totaal negeren',
'Suggesties', 'Annuleren')
{$ENDIF}
);
type
TWPSpellDlg = class(TAbsSpellDialog)
lblFound: TLabel;
lblNotFound: TLabel;
lblReplace: TLabel;
edtWord: TEnterEdit;
lblSuggestions: TLabel;
lstSuggest: TNewListBox;
btnReplace: TBitBtn;
btnSkip: TBitBtn;
btnSkipAll: TBitBtn;
btnSuggest: TBitBtn;
btnAdd: TBitBtn;
btnClose: TBitBtn;
pnlIcons: TPanel;
btnA: TSpeedButton;
btnE: TSpeedButton;
btnI: TSpeedButton;
btnO: TSpeedButton;
btnU: TSpeedButton;
btnN: TSpeedButton;
btnN2: TSpeedButton;
procedure edtWordExit(Sender: TObject);
procedure lstSuggestChange(Sender: TObject);
procedure lstSuggestDblClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure AccentClick(Sender: TObject);
procedure btnSuggestClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnSkipClick(Sender: TObject);
procedure btnSkipAllClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure lstSuggestClick(Sender: TObject);
procedure lstSuggestEnter(Sender: TObject);
procedure QuickSuggest(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
constructor Create (AOwner: TComponent); override;
{--- Extensions of TAbsSpellDialog ---}
{--- Labels and Prompts ----}
procedure SetNotFoundPrompt (ToString: String); override;
{-sets the not found prompt}
procedure SetNotFoundCaption (ToString: String); override;
{-sets the not found caption}
procedure SetEditWord (ToWord: String); override;
{-sets the edit word string}
function GetEditWord: String; override;
{-gets the edit word}
procedure SetEditAsActive; override;
{-sets activecontrol the edit control}
procedure SetLabelLanguage; override;
{-sets labels and buttons to a the language}
{--- Buttons ---}
procedure EnableSkipButtons; override;
{-enables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
procedure DisableSkipButtons; override;
{-disables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
{--- Accented Buttons ---}
procedure SetAccentSet (Accents: TAccentSet); override;
{-sets the accented buttons to be displayed}
{--- Suggest List ----}
procedure ClearSuggestList; override;
{-clears the suggest list}
procedure MakeSuggestions; override;
{-sets the suggest list}
end;
implementation
{$R *.DFM}
constructor TWPSpellDlg.Create (AOwner: TComponent);
begin
inherited Create (AOwner);
end; { TWPSpellDlg.Create }
procedure TWPSpellDlg.edtWordExit(Sender: TObject);
var
ChkWord: String;
begin
lblNotFound.Caption := edtWord.Text;
if ActiveControl is TBitBtn then
exit;
ChkWord := edtWord.Text;
if DCT.InDictionary (ChkWord) then
begin
lblFound.Caption := cLabels[Language][tlblFound];
ActiveControl := btnReplace;
end {:} else
begin
lblFound.Caption := cLabels[Language][tlblNotFound];
ActiveControl := btnSuggest;
end; { else }
end;
procedure TWPSpellDlg.lstSuggestChange(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
end;
procedure TWPSpellDlg.lstSuggestDblClick(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
btnReplaceClick (Sender);
end;
procedure TWPSpellDlg.lstSuggestClick(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
end;
procedure TWPSpellDlg.lstSuggestEnter(Sender: TObject);
begin
if lstSuggest.ItemIndex<>-1 then
edtWord.Text := lstSuggest.Items[lstSuggest.ItemIndex];
end;
procedure TWPSpellDlg.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
ClearKey: Boolean;
begin
ClearKey := TRUE;
case Key of
Ord ('e'): if ssAlt in Shift then ActiveControl := lstSuggest;
Ord ('w'): if ssAlt in Shift then ActiveControl := edtWord;
else ClearKey := FALSE;
end; { case }
if ClearKey then Key := 0;
end;
procedure TWPSpellDlg.AccentClick(Sender: TObject);
begin
if Sender is TSpeedButton then
edtWord.SelText := TSpeedButton (Sender).Caption[1];
end; { TSpellWin.AccentClick }
{--- Extensions of TAbsSpellDialog ---}
{--- Labels and Prompts ----}
procedure TWPSpellDlg.SetNotFoundPrompt (ToString: String);
{-sets the not found prompt}
begin
lblFound.Caption := ToString;
end; { TWPSpellDlg.SetNotFoundPrompt }
procedure TWPSpellDlg.SetNotFoundCaption (ToString: String);
{-sets the not found caption}
begin
lblNotFound.Caption := ToString;
end; { TSpellDlg.SetNotFoundCaption }
procedure TWPSpellDlg.SetEditWord (ToWord: String);
{-sets the edit word string}
begin
edtWord.Text := ToWord;
end; { TWPSpellDlg.SetEditWord }
function TWPSpellDlg.GetEditWord: String;
{-gets the edit word}
begin
Result := edtWord.Text;
end; { TWPSpellDlg.GetEditWord }
procedure TWPSpellDlg.SetEditAsActive;
{-sets activecontrol the edit control}
begin
ActiveControl := btnReplace;
ActiveControl := edtWord;
end; { TWPSpellDlg.SetEditAsActive }
procedure TWpSpellDlg.SetLabelLanguage;
{-sets labels and buttons to a the language}
begin
inherited SetLabelLanguage;
lblFound.Caption := cLabels[Language][tlblFound];
lblReplace.Caption := cLabels[Language][tlblReplace];
lblSuggestions.Caption := cLabels[Language][tlblSuggestions];
btnReplace.Caption := cLabels[Language][tbtnReplace];
btnAdd.Caption := cLabels[Language][tbtnAdd];
btnSkip.Caption := cLabels[Language][tbtnSkip];
btnSkipAll.Caption := cLabels[Language][tbtnSkipAll];
btnSuggest.Caption := cLabels[Language][tbtnSuggest];
btnClose.Caption := cLabels[Language][tbtnClose];
end; { TWpSpellDlg.SetLabelLanguage }
{--- Buttons ---}
procedure TWPSpellDlg.EnableSkipButtons;
{-enables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
begin
btnSkip.Enabled := TRUE;
btnSkipAll.Enabled := TRUE;
end; { TSPSpellDlg.EnableSjipButtons }
procedure TWPSpellDlg.DisableSkipButtons;
{-disables the Skip and Skip All buttons}
{-or Ignore and Ignore All}
begin
btnSkip.Enabled := FALSE;
btnSkipAll.Enabled := FALSE;
end; { TWPSpellDlg.DisableSkipButtons }
{--- Accented Buttons ---}
procedure TWPSpellDlg.SetAccentSet (Accents: TAccentSet);
{-sets the accented buttons to be displayed}
begin
lstSuggest.Top := pnlIcons.Top + 1;
lstSuggest.Height := 161;
pnlIcons.Visible := FALSE;
if acSpanish in Accents then
begin
pnlIcons.Visible := TRUE;
lstSuggest.Top := lstSuggest.Top + pnlIcons.Height;
lblSuggestions.Top := lblSuggestions.Top + pnlIcons.Height;
lstSuggest.Height := lstSuggest.Height - pnlIcons.Height;
end; { if... }
end; { TWPSpellDlg.SetAccentSet }
{--- Suggest List ----}
procedure TWPSpellDlg.ClearSuggestList;
{-clears the suggest list}
begin
lstSuggest.Clear;
end; { TWPSpellDlg.ClearSuggestList }
procedure TWPSpellDlg.MakeSuggestions;
{-sets the suggest list}
var
TempList: TStringList;
SaveCursor: TCursor;
begin
SaveCursor := Screen.Cursor;
Screen.Cursor := crHourglass;
Application.ProcessMessages;
TempList := DCT.SuggestWords (edtWord.Text, Suggestions);
lstSuggest.Items.Assign (TempList);
TempList.Free;
if lstSuggest.Items.Count > 0 then
SetEditWord (lstSuggest.Items[0]);
ActiveControl := btnReplace;
Screen.Cursor := SaveCursor;
end; { TWPSpellDlg.MakeSuggestions }
procedure TWPSpellDlg.btnSuggestClick(Sender: TObject);
begin
MakeSuggestions;
end;
procedure TWPSpellDlg.btnReplaceClick(Sender: TObject);
begin
SpellDlgResult := mrReplace;
end;
procedure TWPSpellDlg.btnAddClick(Sender: TObject);
begin
SpellDlgResult := mrAdd;
end;
procedure TWPSpellDlg.btnSkipClick(Sender: TObject);
begin
SpellDlgResult := mrSkipOnce;
end;
procedure TWPSpellDlg.btnSkipAllClick(Sender: TObject);
begin
SpellDlgResult := mrSkipAll;
end;
procedure TWPSpellDlg.btnCloseClick(Sender: TObject);
begin
SpellDlgResult := mrCancel;
end;
procedure TWPSpellDlg.QuickSuggest(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
TempList: TStringList;
begin
if (Shift = []) and (Char (Key) in ValidChars) then
begin
if edtWord.Text <> '' then
begin
TempList := DCT.QuickSuggest (edtWord.Text, Suggestions);
lstSuggest.Items.Assign (TempList);
TempList.Free;
end {:} else
lstSuggest.Clear;
end; { if... }
end;
end. { WPSpell }
|
unit sfBasic;
{Basic common code for special functions (extended/double precision)}
interface
{$i std.inc}
{$ifdef BIT16}
{$N+}
{$endif}
{$ifdef NOBASM}
{$undef BASM}
{$endif}
uses AMath;
(*************************************************************************
DESCRIPTION : Basic common code for special functions (extended/double precision)
Definitions, constants, etc.
REQUIREMENTS : TP5.5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REMARK : The unit can be compiled with TP5 but some functions generate
invalid operations due to TP5's brain-damaged usage of the FPU
REFERENCES : Index in amath_info.txt/references
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 29.12.09 W.Ehrhardt Initial version: gamma
0.11 30.12.09 we lngamma, signgamma
0.12 31.12.09 we lngamma2, fix lngamma
0.13 01.01.10 we agm, agm2
0.14 01.01.10 we complementary elliptic integrals
0.15 01.01.10 we elliptic integrals
0.16 01.01.10 we cel, cel1, cel2
0.17 02.01.10 we ell_rc
0.18 03.01.10 we el1, el2
0.19 03.01.10 we ell_rf
0.20 04.01.10 we ell_rd
0.21 04.01.10 we ell_rj, el3
0.22 04.01.10 we Range EllipticF extended to |z|<=1 |k*z|<1
0.23 04.01.10 we EllipticE, EllipticEC, for |k|=1
0.24 04.01.10 we el1,el2 for kc=0
0.25 05.01.10 we Jacobi elliptic functions sn,cn,dn
0.26 06.01.10 we erf, erfc
0.27 06.01.10 we normstd_pdf, normstd_cdf, normstd_inv
0.28 08.01.10 we psi(digamma)
0.29 09.01.10 we beta, lnbeta
0.30 10.01.10 we rgamma
0.31 13.01.10 we unit SFCommon
0.32 17.01.10 we removed lngamma2
0.33 21.01.10 we adjusted eps for ell_rf (^6 scaling is not optimal)
0.34 22.01.10 we use absolute values of arguments in agm/2
0.35 22.01.10 we Asymptotic values for small/large args in Maple style
complete elliptic integrals of 1st and 2nd kind
0.36 23.01.10 we sfc_signgamma returns extended
0.37 23.01.10 we removed TP5 code
0.38 24.01.10 we sncndn: use sincos, handle case x=0
0.39 24.01.10 we Inf handling in sfc_normstd_cdf
0.40 27.01.10 we sfc_gamma
0.41 10.02.10 we removed Carlson debug code
0.42 10.02.10 we sfc_zeta, sfc_zeta1p
0.43 14.02.10 we sfc_e1
0.44 15.02.10 we sfc_ei, sfc_li
0.45 16.02.10 we improved sfc_li(x) for x>exp(6) via sfc_eiex
0.46 17.02.10 we sfc_en
0.47 18.02.10 we en_cfrac from [7]
0.48 22.02.10 we sfc_gamma: Pi/MaxExtended instead of Pi/MaxDouble
0.49 01.03.10 we e1(x) = -ei(-x) for x < 0
0.50 02.03.10 we sfc_shi
0.51 03.03.10 we sfc_ci, sfc_si, sfc_ssi
0.52 04.03.10 we sfc_chi
0.53 06.03.10 we sfc_dawson
0.54 11.03.10 we sfc_erf_inv, sfc_erfc_inv
0.55 11.03.10 we CSInitX
0.56 16.03.10 we sfc_dilog
0.57 16.03.10 we Pi^2/6 as hex for VER5X
0.58 01.04.10 we sfc_j0, sfc_y0
0.59 02.04.10 we sfc_j1, sfc_y1
0.60 03.04.10 we sfc_jn, cfrac_jn
0.61 04.04.10 we sfc_yn
0.62 04.04.10 we sfc_i0, sfc_i0e
0.63 04.04.10 we sfc_i1, sfc_i1e
0.64 05.04.10 we sfc_k0, sfc_k0e
0.65 05.04.10 we sfc_k1, sfc_k1e
0.66 07.04.10 we sfc_cin, sfc_cinh
0.67 08.04.10 we fix auxfg for x>sqrt(MaxExtended)
0.68 10.04.10 we sfc_fac
0.69 10.04.10 we sfc_in, sfc_kn
0.70 12.04.10 we sfc_ti2
0.71 17.04.10 we improved sfc_lngamma
0.72 17.04.10 we sfc_gamma1pm1
0.73 22.04.10 we sfc_cl2
0.74 03.05.10 we sincosPix2
0.75 04.05.10 we sfc_fresnel
0.76 18.05.10 we sfc_LambertW, sfc_LambertW1
0.77 19.05.10 we Fix sfc_LambertW1 for x denormal
0.78 19.05.10 we Typed const RTE_NoConvergence
0.79 19.05.10 we Fix for non-BASM in sfc_LambertW1
0.80 20.05.10 we Better decomposition em1h/em1l in sfc_LambertW
0.81 21.05.10 we Improved accuracy in sfc_normstd_cdf
0.82 10.07.10 we Typed const RTE_ArgumentRange
0.83 10.07.10 we sfc_ibeta
0.84 10.07.10 we sfc_beta_pdf
0.85 10.07.10 we sfc_beta_inv, sfc_beta_cdf
0.86 13.07.10 we sfc_t_pdf, sfc_t_cdf, sfc_t_inv
0.87 16.07.10 we sfc_f_pdf, sfc_f_cdf, sfc_f_inv
0.88 18.07.10 we Argument check $ifopt R+
0.89 17.08.10 we SFCommon split into several units
1.00.00 17.08.10 we Common version number after split
1.00.01 17.08.10 we sfGamma: Temme's gstar function
1.00.02 23.08.10 we sfGamma: Incomplete Gamma functions
1.00.03 25.08.10 we sfc_incgamma: cases when a is integer or half integer
1.00.04 29.08.10 we sfc_incgamma: dax calculated via Lanczos sum
1.00.05 01.09.10 we sfc_incgamma_ex, sfc_igprefix
1.00.06 04.09.10 we sfc_incgamma_inv
1.00.07 05.09.10 we sfc_incgamma_inv: use eps_d for p+q=1 check
1.00.08 05.09.10 we sfc_incgamma_inv: return Inf if p=1 and q=0
1.00.09 05.09.10 we sfSDist: sfc_chi2_pdf/cdf/inv
1.00.10 07.09.10 we sfSDist: sfc_gamma_pdf/cdf/inv
1.00.11 07.09.10 we avoid infinite loop if x is NAN in sfc_ei/sfc_e1
1.00.12 08.09.10 we Improved arg checking and NAN/INF handling
1.00.13 09.09.10 we sfc_fresnel handles NANs
1.00.14 10.09.10 we sfc_trigamma
1.00.15 11.09.10 we ibeta_series with iteration limit and convergence check
1.00.16 11.09.10 we sfBessel: Improved arg checking and NAN/INF handling
1.00.17 12.09.10 we Extended over/underflow check in sfc_jn
1.00.18 14.09.10 we sfc_eta, sfc_etam1
1.00.19 15.09.10 we sfc_zetam1
1.01.00 06.10.10 we sfGamma: sfc_dfac
1.01.01 06.10.10 we sfPoly: legendre_pq
1.01.02 06.10.10 we sfPoly: sfc_legendre_p, sfc_legendre_q
1.01.03 07.10.10 we sfPoly: legendre_plmf, sfc_legendre_plm
1.01.04 10.10.10 we sfPoly: sfc_chebyshev_t, sfc_chebyshev_u
1.01.05 10.10.10 we fix sign in sfc_chebyshev_t if x<0, n>=NTR
1.01.06 11.10.10 we sfPoly: sfc_gegenbauer_c
1.01.07 15.10.10 we sfPoly: sfc_jacobi_p
1.01.08 16.10.10 we sfMisc: Fix sfc_LambertW1 for WIN16
1.01.09 16.10.10 we sfPoly: sfc_hermite_h
1.01.10 17.10.10 we sfPoly: sfc_laguerre
1.01.11 18.10.10 we sfGamma: Lanczos sum with and without expg scale
1.01.12 19.10.10 we gamma_delta_ratio, gamma_ratio, pochhammer
1.01.13 20.10.10 we sfPoly: sfc_laguerre_ass, sfc_laguerre_l
1.01.14 20.10.10 we sfPoly: sfc_spherical_harmonic
1.01.15 22.10.10 we sfPoly: sfc_zernike_r
1.01.16 22.10.10 we sfPoly: legendre_plmf with sfc_gamma_ratio
1.01.17 23.10.10 we sfGamma: sfc_zetah
1.02.00 31.10.10 we sfBessel: sfc_yn: improved pre-checks
1.02.01 01.11.10 we sfBessel: sfc_jv, sfc_yv, sfc_bess_jyv
1.02.02 03.11.10 we sfBessel: sfc_iv, sfc_kv, sfc_bess_ikv
1.02.03 04.11.10 we sfBessel: NAN/INF handling for real order functions
1.02.04 05.11.10 we sfMisc : Tolerance 1.0078125*eps_x in LambertW/1
1.02.05 05.11.10 we sfBessel: Airy functions Ai, Ai', Bi, Bi'
1.02.06 06.11.10 we sfBessel: sfc_sph_jn, sfc_sph_yn
1.02.07 06.11.10 we sfBessel: increased MAXIT in CF1_j
1.02.08 11.11.10 we sfGamma : sfc_beta uses sfc_pochhammer for integer x+y=0
1.02.09 11.11.10 we sfGamma : Fixed missing check in sfc_lnbeta
1.02.10 14.11.10 we sfBessel: Fixed sfc_i0e for small x
1.02.11 15.11.10 we sfBessel: sfc_ive, sfc_kve
1.03.00 01.12.10 we sfBasic : sfc_bernoulli and small B(2n) as interfaced typed const
1.03.01 03.12.10 we sfMisc : sfc_polylog
1.03.02 05.12.10 we sfBasic : sfc_zetaint
1.03.03 07.12.10 we sfMisc : sfc_debye
1.03.04 07.12.10 we sfGamma : Fixed sfc_psi(+INF) = +INF
1.03.05 13.12.10 we sfGamma : sfc_trigamma with Hurwitz zeta
1.03.06 14.12.10 we sfGamma : sfc_tetragamma, sfc_pentagamma
1.03.07 15.12.10 we sfGamma : sfc_polygamma
1.03.08 19.12.10 we sfGamma : sfc_(ln)gamma return NAN/RTE if x is a non-positive integer
1.03.09 29.12.10 we sfGamma : improved sfc_dfac for a few small values to return integer
1.03.10 30.12.10 we sfGamma : sfc_binomial
1.04.00 10.02.11 we sfBessel: Improved J0,J1 for |x| >= 500; Y0,Y1 for x >= 1600
1.04.01 12.02.11 we sfErf : Goodwin-Staton integral sfc_gsi
1.04.02 13.02.11 we sfErf : sfc_expint3
1.04.03 14.02.11 we sfErf : imaginary error function erfi
1.04.04 17.02.11 we sfMisc : sfc_ri
1.05.00 31.03.11 we Fix for some units: uses sfBasic for RTE_ArgumentRange ifopt R+
1.05.01 10.04.11 we sfBessel: Zero order Kelvin functions ber,bei,ker,kei
1.05.02 10.04.11 we sfc_kei(0) = -Pi/4
1.05.03 13.04.11 we sfSDist : sfc_cauchy_pdf/cdf/inv
1.05.04 14.04.11 we sfSDist : sfc_normal_pdf/cdf/inv
1.05.05 14.04.11 we sfSDist : sfc_exp_pdf/cdf/inv
1.05.06 15.04.11 we sfSDist : sfc_lognormal_pdf/cdf/inv
1.05.07 16.04.11 we sfSDist : sfc_logistic_pdf/cdf/inv
1.05.08 16.04.11 we sfSDist : sfc_weibull_pdf/cdf/inv
1.05.09 17.04.11 we sfSDist : sfc_laplace_pdf/cdf/inv
1.05.10 17.04.11 we sfSDist : changed sh,sc to a,b in sfc_gamma_pdf/cdf/inv
1.05.11 19.04.11 we sfSDist : sfc_pareto_pdf/cdf/inv
1.05.12 20.04.11 we sfSDist : sfc_uniform_pdf/cdf/inv
1.06.00 05.05.11 we sfBessel: sfc_struve_h0
1.06.01 05.05.11 we sfBessel: sfc_struve_h1
1.06.02 06.05.11 we sfBessel: sfc_struve_l1
1.06.03 07.05.11 we sfBessel: sfc_struve_l0
1.06.04 12.05.11 we sfc_sncndn moved from sfMisc to sfEllInt
1.06.05 13.05.11 we sfEllInt: sfc_theta2/3/4
1.06.06 14.05.11 we sfEllInt: sfc_theta1p
1.06.07 16.05.11 we sfEllInt: sfc_jtheta
1.06.08 17.05.11 we sfEllInt: hack: fix overflow for theta_ts for q near 1
1.06.09 19.05.11 we sfEllInt: sfc_ellmod
1.06.10 19.05.11 we replaced misleading kc by k in EllipticCK and EllipticCE
1.06.11 20.05.11 we sfEllInt: sfc_nome
1.06.12 22.05.11 we sfEllInt: improved sfc_nome with Chebyshev for k <= 1/8
1.06.13 26.05.11 we sfBessel: fix for very large x in kelvin_large
1.06.14 26.05.11 we sfEllInt: improved NAN handling for theta functions
1.07.00 01.06.11 we sfExpInt: sfc_ein
1.07.01 02.06.11 we sfEllInt: reordered argument check in sfc_ell_rc
1.07.02 02.06.11 we sfEllInt: sfc_ellint_1/2
1.07.03 03.06.11 we sfEllInt: sfc_ellint_2: case k=1
1.07.04 03.06.11 we sfEllInt: sfc_EllipticPiC/CPi with sfc_cel
1.07.05 04.06.11 we sfEllInt: inline agm in sfc_EllipticK
1.07.06 04.06.11 we sfEllInt: sfc_ellint_2: fix phi close to n*Pi_2
1.07.07 05.06.11 we comp_ellint_1/2/3(x)
1.07.08 06.06.11 we sfEllInt: sfc_jam
1.07.09 07.06.11 we sfEllInt: sfc_jzeta
1.07.10 08.06.11 we sfEllInt: sfc_ellint_3
1.07.11 10.06.11 we sfEllInt: fix D2/D3 issue in sfc_ellint_3
1.07.12 10.06.11 we sfErf: sfc_erfce
1.07.13 15.06.11 we sfEllInt: parameter check in sfc_EllipticK
1.07.14 16.06.11 we sfEllInt: sfc_jam for |k| > 1
1.07.15 17.06.11 we sfEllInt: sfc_ellint_1 for |k| > 1
1.07.16 17.06.11 we sfEllInt: sfc_jacobi_arcsn/cn/dn
1.07.17 18.06.11 we sfEllInt: sfc_jacobi_sn/cn/dn
1.07.18 19.06.11 we sfEllInt: sfc_ellint_2/3 for |k| > 1
1.07.19 19.06.11 we SpecFun: Fix result for Nan argument in LambertW/1
1.07.20 19.06.11 we sfMisc: Move IsNanOrInf test to top in LambertW1
1.07.21 23.06.11 we sfEllInt: sfc_hlambda
1.07.22 26.06.11 we sfMisc: simplified range check in sfc_LambertW/1
1.08.00 03.07.11 we sfGamma: Asymptotic expansion for x>1024 in stirf
1.08.01 12.07.11 we sfGamma: polygam_negx: polygamma for x<0 and 1<=n<=10
1.08.02 17.07.11 we sfExpInt: range sfc_li(x) now x>=0, x<>1
1.08.03 26.07.11 we sfEllInt: improved sfc_EllipticEC
1.08.04 26.07.11 we sfEllInt: nu<>1 in sfc_EllipticCPi,sfc_EllipticPiC
1.08.05 27.07.11 we sfEllInt: Reciprocal-Modulus Transformation in sfc_EllipticE
1.08.06 02.08.11 we sfEllInt: sfc_el1 uses arcsinh for kc=0
1.08.07 03.08.11 we sfGamma: invgamma renamed to rgamma
1.08.08 04.08.11 we sfGamma: small simplification in sfc_gstar
1.08.09 06.08.11 we sfGamma: sfc_dfac for odd negative n, fac/dfac return INF if undefined
1.08.10 08.08.11 we sfGamma: const ETAEPS, improved etam1pos
1.08.11 09.08.11 we sfGamma: improved sfc_zetah
1.08.12 13.08.11 we sfBessel: cases |v|=0,1 in sfc_kve
1.08.13 13.08.11 we sfBessel: v=-1 in sfc_iv/e
1.08.14 15.08.11 we sfSDist: Fix sfc_t_cdf for t>0 and large nu
1.08.15 15.08.11 we sfErf: Range check sfc_erf(c)_inv
1.08.16 15.08.11 we sfSDist: sfc_normstd_inv uses sfc_erfc_inv
1.09.00 14.09.11 we sfGamma: improved lngamma_small
1.09.01 14.09.11 we sfGamma: sfc_lngamma1p
1.09.02 17.09.11 we sfGamma: lanczos interfaced
1.09.03 17.09.11 we sfGamma: sfc_ibetaprefix
1.09.04 18.09.11 we sfGamma: improved sfc_ibeta
1.09.05 06.10.11 we sfGamma: sfc_zetah for 0 <= s < 1
1.10.00 24.11.11 we sfGamma: sfc_lnfac
1.10.01 10.12.11 we sfSDist: sfc_triangular_pdf/cdf/inv
1.10.02 13.12.11 we sfSDist: sfc_beta_pdf uses sfc_ibetaprefix
1.10.03 14.12.11 we sfSDist: sfc_binomial_cdf/pmf
1.10.04 15.12.11 we sfGamma: sfc_igprefix for TP5 without Lanczos
1.10.05 15.12.11 we sfSDist: sfc_poisson_cdf/pmf
1.10.06 16.12.11 we sfMisc: sfc_debye with DE integration for x>4 and n>6
1.10.07 18.12.11 we sfSDist: sfc_negbinom_cdf/pmf
1.10.08 21.12.11 we sfGamma: TP5 for sfc_zetah/sfc_zetam1
1.10.09 21.12.11 we sfMisc: sfc_pz
1.10.10 22.12.11 we sfGamma: etam1pos with exp7
1.10.11 22.12.11 we sfMisc: sfc_pz with Cohen's speed-up $ifdef BASM
1.10.12 26.12.11 we sfSDist: sfc_hypergeo_cdf/pmf
1.10.13 27.12.11 we sfSDist: Fix sfc_hypergeo_pmf(0,0,0,k)
1.10.14 28.12.11 we sfBessel: sfc_sph_in, sfc_sph_ine
1.10.15 29.12.11 we sfBessel: sfc_sph_kn, sfc_sph_kne
1.10.16 29.12.11 we sfBessel: Fix bug for small negative x in sfc_sph_ine
1.10.17 02.01.12 we sfMisc: improved sfc_polylog for n<-9 and -4 < x < -11.5
1.11.00 03.02.12 we sfZeta: New unit with zeta functions and polylogarithms
1.11.01 04.02.12 we sfZeta: sfc_lerch
1.11.02 05.02.12 we sfZeta: sfc_lerch for z=-1: use lphi_aj instead of zetah
1.11.03 06.02.12 we sfZeta: sfc_dbeta
1.11.04 06.02.12 we sfZeta: sfc_dlambda
1.11.05 07.02.12 we sfZeta: sfc_lchi
1.11.06 08.02.12 we sfZeta: sfc_polylogr
1.11.07 15.02.12 we SpecFun: use Ext2Dbl with el3, gamma, beta, e1
1.12.00 25.02.12 we sfMisc: Avoid over/underflow for large x in debye_dei
1.12.01 13.03.12 we sfZeta: sfc_lchi(1,x) = arctanh(x)
1.12.02 20.03.12 we sfBasic: BoFHex array: Bernoulli(2k+2)/(2k+2)!
1.12.03 20.03.12 we sfZeta: sfc_zetah with BoFHex
1.12.04 21.03.12 we sfGamma: sfc_gamma_delta_ratio for negative arguments
1.12.05 21.03.12 we sfGamma: improved sfc_pochhammer
1.12.06 22.03.12 we sfGamma: sfc_poch1
1.12.07 04.04.12 we sfPoly: sfc_legendre_p, sfc_legendre_plm for |x| > 1
1.12.08 09.04.12 we sfGamma: fix special case if prefix is zero in sfc_incgamma_ex
1.12.09 11.04.12 we sfGamma: sfc_igamma (non-normalised upper incomplete gamma)
1.12.10 17.04.12 we sfPoly: sfc_legendre_q for |x| > 1
1.12.11 18.04.12 we sfGamma: sfc_lngammas
1.12.12 22.04.12 we sfGamma: sfc_gamma for x < -MAXGAMX
1.12.13 22.04.12 we sfGamma: sfc_igammal (non-normalised lower incomplete gamma)
1.12.14 27.04.12 we sfPoly: sfc_legendre_qlm
1.12.15 16.05.12 we sfPoly: sfc_thq (toroidal harmonics)
1.12.16 20.05.12 we sfPoly: sfc_thp (toroidal harmonics)
1.12.17 24.05.12 we sfPoly: sfc_thq for m < 0
1.12.18 29.05.12 we sfBasic: fix missing bit in B2nHex[0]
1.13.00 07.06.12 we sfGamma: fix sfc_igprefix for a<1 and underflow of exp(-x)
1.13.01 08.06.12 we sfGamma: improved sfc_rgamma
1.13.02 09.06.12 we sfGamma: sfc_taylor
1.13.03 09.06.12 we sfZeta: sfc_polylog uses sfc_taylor
1.13.04 09.06.12 we sfZeta: sfc_fermi_dirac
1.13.05 10.06.12 we sfZeta: fix n>x in fd_asymp_exp_int
1.13.06 11.06.12 we sfZeta: sfc_zeta uses sfc_zetaint
1.13.07 12.06.12 we sfZeta: sfc_etaint
1.13.08 12.06.12 we sfBasic: sfc_diagctr
1.13.09 13.06.12 we sfZeta: sfc_fdm05, sfc_fdp05
1.13.10 15.06.12 we sfErf: sfc_gendaw (generalized Dawson integral)
1.13.11 16.06.12 we sfErf: sfc_inerfc (repeated integrals of erfc)
1.13.12 20.06.12 we sfExpInt: corrected bound in sfc_en (11140.0 -> 11390.2)
1.13.13 22.06.12 we sfExpInt: uniform asymptotic expansion ep_largep for n>=10000
1.13.14 23.06.12 we sfExpInt: generalized exponential integral sfc_gei
1.13.15 26.06.12 we sfErf: sfc_erfg (generalized error function)
1.13.16 29.06.12 we sfBasic: sfc_write_debug_str
1.13.17 30.06.12 we sfGamma: sfc_git (Tricomi's incomplete gamma)
1.13.18 01.07.12 we sfGamma: check loss of accuracy in sfc_igammal
1.14.00 20.07.12 we sfGamma: removed special treatment for a=0 in sfc_poch
1.14.01 23.07.12 we sfExpInt: more compact sfc_eiex
1.14.02 31.01.13 we sfBasic: sfc_write_debug_str: fix and D17 adjustment
1.15.00 15.02.13 we sfGamma: improved sfc_git
1.15.01 15.02.13 we sfErf: fix sfc_expint3 for 0.4e-6 .. 6e-6
1.15.02 16.02.13 we sfGamma: fix sfc_trigamma/tetragamma/pentagamma for very large arguments
1.15.03 16.02.13 we sfZeta: improved sfc_zetah
1.15.04 19.02.13 we sfBessel: improved quick check in sfc_jn
1.15.05 20.02.13 we sfBessel: Yv_series
1.15.06 20.02.13 we sfBessel: handle some near overflows in bessel_jy
1.15.07 20.02.13 we sfBessel: improved check in sfc_yn
1.16.00 14.03.13 we sfEllInt: Remaining Jacobi elliptic functions
1.16.01 15.03.13 we sfEllInt: Improved sfc_jacobi_arcsn/cn/dn
1.16.02 20.03.13 we sfZeta: fix sfc_zetah for j>NBoF
1.16.03 22.03.13 we sfEllInt: sfc_jacobi_arcsc, sfc_jacobi_arccs
1.16.04 23.03.13 we sfEllInt: sfc_jacobi_arcnc, sfc_jacobi_arcns
1.16.05 23.03.13 we sfEllInt: sfc_jacobi_arcnd
1.16.06 24.03.13 we sfEllInt: sfc_jacobi_arccd, sfc_jacobi_arcdc
1.16.07 24.03.13 we sfEllInt: sfc_jacobi_arcsd
1.16.08 25.03.13 we sfEllInt: sfc_jacobi_arcds
1.16.09 27.03.13 we sfZeta: sfc_zetah for s<0
1.16.10 28.03.13 we sfZeta: sfc_trilog
1.16.11 29.03.13 we sfZeta: TP5 fix for sfc_zeta
1.16.12 29.03.13 we sfZeta: sfc_zetah for a near 1 and s<0
1.16.13 30.03.13 we sfGamma: improved sfc_binomial
1.17.00 07.04.13 we sfSDist: Improved sfc_chi2_pdf for very small x
1.17.01 10.04.13 we sfZeta: sfc_fdp15
1.17.02 13.04.13 we sfSDist: k changed to longint in sfc_poisson_pmf
1.17.03 14.04.13 we sfSDist: sfc_rayleigh_pdf/cdf/inv
1.17.04 15.04.13 we sfGamma: improved sfc_beta
1.17.05 16.04.13 we sfGamma: ibeta_series with parameter normalised
1.17.06 17.04.13 we sfGamma: sfc_nnbeta
1.17.07 19.04.13 we sfSDist: sfc_maxwell_pdf/cdf/inv
1.17.08 20.04.13 we sfSDist: sfc_evt1_pdf/cdf/inv
1.17.09 20.04.13 we sfSDist: sfc_maxwell_cdf/inv with lower igamma functions
1.17.10 21.04.13 we sfGamma: lanczos_gm05 = lanczos_g - 0.5 in implementation
1.17.11 27.04.13 we sfGamma: polygam_negx for n=11,12
1.17.12 01.05.13 we FresnelC/FresnelS
1.18.00 09.05.13 we sfBessel: Airy/Scorer functions Gi/Hi
1.18.01 09.05.13 we sfBessel: Prevent some wrong compiler optimizations for div by 3
1.18.02 11.05.13 we sfGamma: improved sfc_polygamma for large order: e.g. (3000,200)
1.18.03 14.05.13 we sfHyperG: 2F1: major rewrite (additional linear transformations)
1.18.04 14.05.13 we sfHyperG: 2F1: fix y=0 in h2f1_sum
1.18.05 16.05.13 we sfHyperG: 2F1: removed recurrence on c (to make c-a-b > 0)
1.18.06 17.05.13 we sfHyperG: 2F1: h2f1poly with parameter err
1.18.07 18.05.13 we sfHyperG: 2F1: no Luke for TP5
1.18.08 19.05.13 we (some) Prevent some wrong compiler optimizations for div by 3
1.18.09 21.05.13 we sfHyperG: 2F1: regularized function sfc_2f1r
1.18.10 21.05.13 we sfHyperG: 1F1: h1f1_sum_laguerre
1.18.11 23.05.13 we sfHyperG: 1F1: h1f1_tricomi only if 2bx > 4ax
1.18.12 23.05.13 we sfHyperG: 1F1: fix h1f1_acf if x >= Ln_MaxExt
1.18.13 24.05.13 we sfHyperG: 1F1: regularized function sfc_1f1r
1.18.14 26.05.13 we sfGamma: sfc_nnbeta for a<=0 or b<=0
1.18.15 27.05.13 we sfHyperG: CHU: handle a or b negative integer
1.18.16 28.05.13 we sfHyperG: CHU: special cases a=-1, x=0, a=b
1.18.17 29.05.13 we sfHyperG: CHU: case b=2a, allow a or a+1-b negative integer in luke
1.18.18 30.05.13 we sfHyperG: CHU: handle b=a+n+1
1.18.19 31.05.13 we sfHyperG: CHU: fix some double/overflow cases in dchu
1.19.00 06.06.13 we sfBessel: Fix typo in h1v_large
1.19.01 08.06.13 we sfBessel: sfc_bess_kv2
1.19.02 09.06.13 we sfHyperG: CHU: fix sign in special case a=-1
1.19.03 12.06.13 we sfHyperG: CHU: implementation of Temme's chu and uabx
1.19.04 14.06.13 we sfHyperG: CHU: use dchu with Kummer if b<0.0 and t>T_MAXA
1.19.05 16.06.13 we sfHyperG: Whittaker functions sfc_whitm/sfc_whitw
1.19.06 27.06.13 we sfBessel: Check overflow / return INF in bessel_jy
1.19.07 27.06.13 we sfHyperG: sfc_0f1
1.19.08 28.06.13 we sfHyperG: gen_0f1, sfc_0f1r
1.20.00 27.07.13 we sfHyperG: MAXIT=64 in h1f1_tricomi
1.20.01 27.07.13 we sfGamma: sfc_git for x<0
1.20.02 14.08.13 we sfSDist: Removed code fragment for y>1 in sfc_beta_inv
1.20.03 14.08.13 we sfSDist: Check a,b > 0 in sfc_beta_cdf
1.20.04 15.08.13 we sfSDist: sfc_kumaraswamy_pdf/cdf/inv
1.20.05 16.08.13 we sfZeta: sfc_zeta for small s
1.20.06 16.08.13 we sfZeta: sfc_polylog with sfc_zetaint
1.20.07 17.08.13 we sfSDist: Improved sfc_lognormal_pdf with expmx2h
1.20.08 18.08.13 we sfErf: sfc_erf_p, sfc_erf_q, sfc_erf_z
1.20.09 18.08.13 we sfSDist: normal/normstd_pdf/cdf with erf_z and erf_p
1.21.00 07.09.13 we sfZeta: Improved sfc_zetah/hurwitz_formula
1.21.01 11.09.13 we sfZeta: Bernoulli polynomials sfc_bernpoly
1.21.02 14.09.13 we sfPoly: sfc_chebyshev_v
1.21.03 15.09.13 we sfPoly: sfc_chebyshev_w
1.21.04 24.09.13 we sfMisc: sfc_cosint, sfc_sinint
1.21.05 25.09.13 we sfGamma: sfc_batemang
1.21.06 26.09.13 we sfMisc: Fixed quasi-periodic code for sfc_cos/sinint
1.21.07 27.09.13 we sfEllInt: Fixed quasi-periodic code for sfc_ellint_1/2/3
1.21.08 28.09.13 we sfEllInt: special_reduce_modpi, used in sfc_ellint_1/2/3 and sfc_hlambda
1.22.00 19.10.13 we sfSDist: sfc_moyal_pdf/cdf/inv
1.22.01 22.10.13 we sfEllInt: sfc_EllipticKim
1.22.02 23.10.13 we sfEllInt: sfc_EllipticECim
1.22.03 04.11.13 we sfSDist: improved sfc_t_pdf for small x^2/nu
1.23.00 26.12.13 we sfZeta: sfc_fdp25
1.23.01 26.12.13 we sfBasic: complete references in amath_info.txt
1.24.00 11.03.14 we sfExpInt: Adjust arrays sizes in sfc_ci, si_medium
1.24.01 24.03.14 we sfHyperG: chu_luke only with $ifdef in dchu
1.24.02 26.03.14 we sfBessel: sfc_yn with LnPi from AMath
1.25.00 16.04.14 we sfGamma: Improved polygam_negx (larger n for x<0}
1.25.01 01.05.14 we sfZeta: sfc_harmonic
1.25.02 03.05.14 we sfZeta: sfc_harmonic2
1.25.03 04.05.14 we sfSDist: sfc_zipf_pmf/cdf
1.26.00 24.05.14 we sfMisc: sfc_ali (functional inverse of sfc_li)
1.26.01 27.05.14 we sfZeta: Removed redundancy in sfc_harmonic2
1.26.02 28.05.14 we sfZeta: sfc_harmonic with nch = 22
1.26.03 29.05.14 we sfZeta: polylogneg with array of single
1.26.04 30.05.14 we SpecFun: Fix zipf_pmf/cdf function type
1.26.05 30.05.14 we sfZeta: Lobachevski sfc_llci, sfc_llsi
1.26.06 31.05.14 we sfZeta: improved harm2core
1.26.07 01.06.14 we sfMisc: Fibonacci polynomials sfc_fpoly
1.26.08 02.06.14 we sfMisc: Lucas polynomials sfc_lpoly
1.26.09 05.06.14 we sfSDist: sfc_levy_pdf/cdf/inv
1.27.00 15.06.14 we Inverse/incomplete Gamma/Beta moved to unit sfGamma2
1.27.01 15.06.14 we sfGamma: const lanczos_gm05: extended
1.27.02 15.06.14 we sfGamma2: sfc_ibeta_inv (code from sfSDist)
1.27.03 15.06.14 we sfZeta: Fermi/Dirac, Lobachewsky, harmonic functions moved to sfZeta2
1.27.04 22.06.14 we sfGamma2: sfc_ilng (inverse of lngamma)
1.27.05 25.06.14 we sfGamma2: sfc_ipsi (inverse of psi/digamma)
1.27.06 02.07.14 we SpecFun/X ibeta_inv/x
1.27.07 11.07.14 we sfHyperG: sfc_pcfd
1.27.08 11.07.14 we sfHyperG: sfc_pcfu
1.27.09 12.07.14 we sfHyperG: sfc_pcfhh
1.28.00 29.07.14 we sfBasic: moebius[1..95]
1.28.01 29.07.14 we sfZeta: Improved and expanded primezeta sfc_pz
1.28.02 05.08.14 we sfZeta: sfc_zeta for s < -MaxGAMX
1.28.03 05.08.14 we sfGamma: First check IsNaN(x) in sfc_lngamma
1.28.04 05.08.14 we sfGamma: improved sfc_gdr_pos for small x
1.28.05 08.08.14 we sfBessel: Iv := PosInf_x if Kv,Kv1=0 in bessel_ik or if x >= IvMaxXH in sfc_iv
1.28.06 10.08.14 we sfGamma: fix sfc_lnbeta for VER50
1.28.07 11.08.14 we sfGamma: special case x=x+y in sfc_beta
1.28.08 17.08.14 we sfMisc: Catalan function sfc_catf
1.28.09 19.08.14 we sfHyperG: sfc_pcfv
1.28.10 20.08.14 we sfGamma: sfc_gamma_delta_ratio returns 1 if x=x+d
1.29.00 01.09.14 we sfHyperG: sfc_chu for x<0
1.29.01 04.09.14 we sfHyperG: fix h1f1_tricomi (division by t=0)
1.29.02 07.09.14 we sfSDist: sfc_logistic_inv uses logit function
1.29.03 06.10.14 we sfSDist: sfc_logistic_cdf uses logistic function
1.30.00 26.10.14 we sfHyperG: No Kummer transformation in 1F1 if b=0,-1,-2,...
1.30.01 28.10.14 we sfHyperG: 1F1 = 1 + a/b*(exp(x)-1) for very small a,b
1.30.02 06.11.14 we sfBasic: Small Bernoulli numbers B2nHex moved to AMath
1.31.00 14.12.14 we sfGamma: small changes in sfc_batemang
1.31.01 16.12.14 we sfGamma2: Check IsNanOrInf in sfc_ilng
1.31.02 23.12.14 we sfSDist: sfc_invgamma_pdf/cdf/inv
1.31.03 26.12.14 we sfSDist: logarithmic (series) distribution
1.31.04 31.12.14 we sfSDist: sfc_wald_cdf/pdf
1.31.05 01.01.15 we sfSDist: sfc_wald_inv
1.31.06 02.01.15 we sfSDist: Improved sfc_wald_inv (restart with mode)
1.31.07 05.01.15 we sfHyperG: Special case b=1 in gen_0f1
1.31.08 05.01.15 we sfSDist: Error if k<1 in sfc_ls_cdf/pmf
1.32.00 25.01.15 we sfExpint: sfc_ali from sfMisc
1.32.01 25.01.15 we sfExpint: sfc_ei_inv
1.32.02 26.03.15 we sfEllInt: sfc_cel_d
1.32.03 27.03.15 we sfEllInt: sfc_ellint_d
1.32.04 01.05.15 we sfExpint: fix sfc_ei_inv for x Nan
1.33.00 17.05.15 we sfZeta: sfc_lerch for s >= -1
1.33.01 18.05.15 we sfZeta: sfc_polylogr for s >= -1
1.33.02 18.05.15 we sfZeta: Improved sfc_etam1 (adjusted Borwein constants)
1.33.03 24.05.15 we sfZeta: sfc_lerch(1,s,a) for s<>1 and special case z=0
1.33.04 04.06.15 we sfMisc: sfc_kepler
1.33.05 04.06.15 we sfBasic: remove CSInitX
1.33.06 07.06.15 we sfBessel: new IJ_series replaces Jv_series
1.33.07 07.06.15 we sfBessel: rewrite of sfc_in: use IJ_series and CF1_I
1.33.08 08.06.15 we sfBessel: improved bess_m0p0/bess_m1p1 with rem_2pi_sym and Kahan summation
1.33.09 09.06.15 we sfBessel: sfc_struve_l
1.33.10 10.06.15 we sfBessel: sfc_struve_h
1.33.11 10.06.15 we sfBessel: sfc_struve_l0/1 use sfc_struve_l
1.33.12 14.06.15 we sfBessel: sfc_struve_h/l with real nu >= 0
1.33.13 19.06.15 we sfBessel: scaled Airy functions sfc_airy_ais, sfc_airy_bis
1.33.14 21.06.15 we sfEllInt: avoid overflow in sfc_ell_rf, better arg checks in Carlson functions
1.33.15 22.06.15 we sfEllInt: Carlson sfc_ell_rg
1.34.00 05.07.15 we sfBessel: special cases Yv(+- 1/2, x)
1.34.01 06.07.15 we sfBessel: sfc_struve_h for v < 0
1.34.02 07.07.15 we sfBessel: sfc_struve_l for v < 0
1.34.03 09.07.15 we sfBessel: fix sfc_struve_h/l(v,0) for v<=-1
1.34.04 18.07.15 we sfZeta: eta near s=1
1.34.05 19.07.15 we sfEllint: sfc_el1(x, kc) = arctan(x) for kc^2=1
1.34.06 01.08.15 we sfHyperG: Avoid some overflows in h2f1_sum, improved h2f1_trans
1.35.00 25.08.15 we (some): Use THREE & SIXX to avoid 'optimization'
1.35.01 25.08.15 we sfZeta: sfc_bernpoly: avoid integer overflow and FPC optimization error
1.35.02 26.08.15 we sfBessel: Sqrt2 in kelvin functions (anti-'optimizing')
1.36.00 26.09.15 we sfEllInt: lemniscate functions sin_lemnx, cos_lemnx
1.36.01 29.09.15 we sfHyperG: sfc_pcfv(a,x) for a<0
1.36.02 11.10.15 we sfGamma: polygamma for x<0 uses Euler series for Pi*cot(Pi*x)
***************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2015 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
(*-------------------------------------------------------------------------
This Pascal code uses material and ideas from open source and public
domain libraries, see the file '3rdparty.ama' for the licenses.
---------------------------------------------------------------------------*)
const
SF_BaseVersion = '1.36.02';
const
RTE_NoConvergence: integer = 234; {RTE for no convergence, set negative}
{to continue (with inaccurate result)}
RTE_ArgumentRange: integer = 235; {RTE for argument(s) out of range, set}
{negative to continue with NAN result.}
{Tested if $R+ option is enabled}
procedure sincosPix2(x: extended; var s,c: extended);
{-Return s=sin(Pi/2*x^2), c=cos(Pi/2*x^2); (s,c)=(0,1) for abs(x) >= 2^64}
function sfc_bernoulli(n: integer): extended;
{-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3}
{#Z+}
{---------------------------------------------------------------------------}
{Moebius function æ(n) for small arguments}
const
n_moeb = 95;
moebius: array[1..n_moeb] of shortint = (
1, -1, -1, 0, -1, 1, -1, 0, 0, 1,
-1, 0, -1, 1, 1, 0, -1, 0, -1, 0,
1, 1, -1, 0, 0, 1, 0, 0, -1, -1,
-1, 0, 1, 1, 1, 0, -1, 1, 1, 0,
-1, -1, -1, 0, 0, 1, -1, 0, 0, 0,
1, 0, -1, 0, 1, 0, 1, 1, -1, 0,
-1, 1, 0, 0, 1, -1, -1, 0, 1, -1,
-1, 0, -1, 1, 0, 0, 1, -1, -1, 0,
0, 1, -1, 0, 1, 1, 1, 0, -1, 0,
1, 0, 1, 1, 1);
{---------------------------------------------------------------------------}
{Bernoulli numbers. The B(2n), n = 0..MaxB2nSmall are in AMath}
const
MaxBernoulli = 2312;
const
NBoF = 20;
BoFHex: array[0..NBoF] of THexExtW = ( {Bernoulli(2k+2)/(2k+2)! }
($AAAB,$AAAA,$AAAA,$AAAA,$3FFB), {+8.3333333333333333336E-2}
($B60B,$0B60,$60B6,$B60B,$BFF5), {-1.3888888888888888888E-3}
($355E,$08AB,$55E0,$8AB3,$3FF0), {+3.3068783068783068783E-5}
($5563,$A778,$BC99,$DDEB,$BFEA), {-8.2671957671957671957E-7}
($ED15,$B875,$795F,$B354,$3FE5), {+2.0876756987868098980E-8}
($F7BA,$2133,$2EB2,$9140,$BFE0), {-5.2841901386874931847E-10}
($0FDC,$048B,$9627,$EB6D,$3FDA), {+1.3382536530684678833E-11}
($E260,$CCAA,$70FB,$BED2,$BFD5), {-3.3896802963225828668E-13}
($ECEE,$2974,$38EB,$9AAC,$3FD0), {+8.5860620562778445639E-15}
($8664,$5567,$CB46,$FABE,$BFCA), {-2.1748686985580618731E-16}
($77D8,$E1BB,$0F84,$CB3F,$3FC5), {+5.5090028283602295151E-18}
($E371,$D15A,$C819,$A4BE,$BFC0), {-1.3954464685812523341E-19}
($3204,$3568,$96BE,$8589,$3FBB), {+3.5347070396294674718E-21}
($B3E6,$F8E0,$96AC,$D87B,$BFB5), {-8.9535174270375468504E-23}
($6AD7,$6513,$6D26,$AF79,$3FB0), {+2.2679524523376830603E-24}
($57E2,$6F1C,$EFCB,$8E3B,$BFAB), {-5.7447906688722024451E-26}
($0D7F,$90DB,$CEF2,$E694,$3FA5), {+1.4551724756148649018E-27}
($3676,$2BA5,$F32B,$BAE6,$BFA0), {-3.6859949406653101781E-29}
($F634,$DA56,$46D9,$977F,$3F9B), {+9.3367342570950446721E-31}
($F768,$3B0F,$1482,$F599,$BF95), {-2.3650224157006299346E-32}
($2185,$9423,$FFC9,$C712,$3F90)); {+5.9906717624821343044E-34}
{#Z-}
{$ifdef debug}
type
sfc_debug_str = string[255];
const
NDCTR = 8;
var
sfc_diagctr: array[0..NDCTR-1] of longint; {General counters for diagnostics}
sfc_debug_output: boolean; {Really doing the outputs if true}
procedure sfc_dump_diagctr;
{-writeln diagnostic counters}
procedure sfc_write_debug_str({$ifdef CONST}const{$endif}msg: sfc_debug_str);
{-Writeln or Outputdebugstr of msg}
{$endif}
implementation
{$ifdef Debug}
{$ifdef WIN32or64}
{$ifndef VirtualPascal}
{$define USE_OutputDebugString}
{$endif}
{$endif}
{$ifdef USE_OutputDebugString}
{$ifdef UNIT_SCOPE}
uses winapi.windows;
{$else}
uses windows;
{$endif}
{$endif}
{$endif}
{---------------------------------------------------------------------------}
procedure sincosPix2(x: extended; var s,c: extended);
{-Return s=sin(Pi/2*x^2), c=cos(Pi/2*x^2); (s,c)=(0,1) for abs(x) >= 2^64}
var
n,f,g: extended;
begin
{Note that this routine is very sensible to argument changes!}
{Example: for x = 10000.1 the s value is 1.57073173006607621E-2, and the}
{result for the same extended x in MPArith gives 1.57073173006607619E-2,}
{the difference is 2.181E-19. If x is represented with MPArith's default}
{240 bit precision the value is 1.57073173118206758E-2 with a difference}
{of 1.115991E-11. The differences of the MPArith arguments were absolute}
{10000.1 - x(extended) = 3.553E-16, relative 3.553E-20}
if TExtRec(x).xp and $7FFF >= $403F then begin
{abs(x) >= 2^64}
s := 0.0;
c := 1.0;
end
else begin
{c, s depend on frac(x) and int(x) mod 4. This code is based on }
{W. Van Snyder: Remark on algorithm 723: Fresnel integrals, 1993.}
{http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.101.7180}
{Fortran source from http://netlib.org/toms/723}
f := abs(x);
n := int(f);
f := f - n;
g := 2.0*frac(f*int(0.5*n));
if frac(0.5*n)=0.0 then sincosPi(0.5*f*f + g, s, c)
else begin
sincosPi((0.5*f*f + f) + g, c, s);
c := -c;
end;
end;
end;
{---------------------------------------------------------------------------}
function sfc_bernoulli(n: integer): extended;
{-Return the nth Bernoulli number, 0 if n<0 or odd n >= 3}
var
bn,p4: extended;
m: integer;
const
bx32: array[0..68] of THexExtw = ( {Bernoulli(32*n+128)}
($52FD,$BE3D,$B49C,$DA4E,$C178), {-5.2500923086774133900E+113}
($FF69,$87B9,$BE6D,$ABE4,$C209), {-1.8437723552033869727E+157}
($4263,$EB29,$A09A,$A2CC,$C2A3), {-3.9876744968232207445E+203}
($F6AA,$C1D8,$F6B1,$FC3C,$C344), {-1.8059559586909309014E+252}
($B09F,$C9C2,$93E6,$9464,$C3ED), {-7.9502125045885252855E+302}
($9CD8,$18C3,$6CDC,$9557,$C49B), {-1.9158673530031573512E+355}
($4195,$04C1,$073E,$A49C,$C54E), {-1.6181135520838065925E+409}
($739D,$571F,$11CD,$8B25,$C606), {-3.3538244754399336890E+464}
($6270,$777F,$2738,$86CE,$C6C2), {-1.2747336393845383643E+521}
($7FAB,$7570,$F9E6,$EADB,$C781), {-6.9702671752326436791E+578}
($4BFF,$0F88,$1349,$95D1,$C845), {-4.4656129117005935721E+637}
($77B2,$1772,$C601,$EAC7,$C90B), {-2.8113943110814931668E+697}
($215A,$6E86,$91AA,$C206,$C9D5), {-1.4934073418970347178E+758}
($5C7F,$D540,$F299,$9400,$CAA2), {-5.8578844571843963827E+819}
($9A59,$4576,$14FE,$B949,$CB71), {-1.5084075750891085972E+882}
($F479,$B007,$0BB5,$AB72,$CC43), {-2.2966905497257900647E+945}
($C675,$9DA9,$A628,$D590,$CD17), {-1.8830664597658071289E+1009}
($0CCE,$2F96,$B80B,$A49C,$CDEE), {-7.6426951845750635249E+1073}
($3EA8,$63C6,$E69D,$9180,$CEC7), {-1.4228762140674037692E+1139}
($4F15,$2C2F,$CD6C,$899F,$CFA2), {-1.1338551314597730180E+1205}
($3CE2,$FDE0,$5490,$82C2,$D07F), {-3.6304766452190330209E+1271}
($3E25,$B6E8,$D002,$EB8A,$D15D), {-4.4077763139644032336E+1338}
($C753,$F062,$8250,$BEAA,$D23E), {-1.9238585974016076227E+1406}
($0C77,$16EC,$4BAC,$840D,$D321), {-2.8737803110109338078E+1474}
($4BEB,$3C03,$6AAB,$9587,$D405), {-1.4036962824375857856E+1543}
($55C7,$0248,$8353,$84AE,$D4EB), {-2.1491058465822269708E+1612}
($E368,$D032,$65E9,$B163,$D5D2), {-9.9151825072869898178E+1681}
($BDEF,$D7FE,$04EF,$AC37,$D6BB), {-1.3287264083350159101E+1752}
($7A90,$3C2E,$9735,$EA9B,$D7A5), {-4.9971936871087436659E+1822}
($9FC1,$AC12,$A7FA,$D91F,$D891), {-5.1070475539922579356E+1893}
($C234,$DE06,$003E,$8470,$D97F), {-1.3759818684504019193E+1965}
($D312,$510C,$861B,$CEFB,$DA6D), {-9.4989226808690414704E+2036}
($B32D,$A0BE,$8870,$C9B7,$DB5D), {-1.6356184195123832511E+2109}
($F8D5,$2E47,$4E40,$EF06,$DC4E), {-6.8487492292184253538E+2181}
($4706,$AFF3,$6F23,$A81A,$DD41), {-6.8082216303292659152E+2254}
($269B,$331E,$4461,$892E,$DE35), {-1.5706145196821570477E+2328}
($B8F7,$3321,$712A,$FE3E,$DF29), {-8.2289799425426414984E+2401}
($D598,$89BA,$1E5D,$830E,$E020), {-9.5930887251893861974E+2475}
($5173,$0867,$AB5F,$9368,$E117), {-2.4402644753692194590E+2550}
($E63F,$76FF,$2870,$B191,$E20F), {-1.3295801865055646274E+2625}
($F314,$7CE5,$BF4B,$E10C,$E308), {-1.5244028786126305655E+2700}
($C94F,$DECD,$6EC9,$9389,$E403), {-3.6161842428643845094E+2775}
($5940,$BF69,$792C,$C4E9,$E4FE), {-1.7464299021830195980E+2851}
($A1C0,$F220,$16A1,$83B6,$E5FB), {-1.6907945786261035527E+2927}
($92B8,$8BC5,$F001,$AE03,$E6F8), {-3.2332881196060927594E+3003}
($DBF1,$FA98,$71AD,$DFDC,$E7F6), {-1.2040771662431166519E+3080}
($BEF9,$BB8F,$DE3B,$8A4F,$E8F6), {-8.6141885195778356538E+3156}
($D7D6,$F08B,$2222,$A20A,$E9F6), {-1.1685695524501785594E+3234}
($E709,$C538,$6958,$B1BD,$EAF7), {-2.9684329116433388662E+3311}
($9EFA,$77E4,$442C,$B459,$EBF9), {-1.3950642936150073193E+3389}
($9693,$9589,$9A1E,$A753,$ECFC), {-1.1989884572796487307E+3467}
($1F33,$FD26,$C024,$8C5F,$EE00), {-1.8635271302518619006E+3545}
($BFDB,$D0DD,$0E46,$D2AF,$EF04), {-5.1817804064721174490E+3623}
($36A4,$A1D6,$BAE4,$8BF7,$F00A), {-2.5511413022051873656E+3702}
($04E7,$CCC3,$B596,$A2FF,$F110), {-2.2016594557163485556E+3781}
($0B04,$CD7E,$45F3,$A4C4,$F217), {-3.2985559030415466710E+3860}
($E49A,$0504,$EDB4,$8F39,$F31F), {-8.4995513646331021388E+3939}
($9F07,$D98B,$CC09,$D433,$F427), {-3.7328650389340701819E+4019}
($1417,$52A2,$A454,$84CC,$F531), {-2.7699188001914063216E+4099}
($3D97,$75F1,$0EF2,$8B3C,$F63B), {-3.4434756013646314132E+4179}
($198B,$2EA0,$521E,$F293,$F745), {-7.1133726432191288073E+4259}
($A708,$C185,$31CE,$AE2D,$F851), {-2.4224631302940113182E+4340}
($955A,$427F,$7027,$CC98,$F95D), {-1.3495915388686739922E+4421}
($E7A1,$2BA2,$3BF4,$C31E,$FA6A), {-1.2208793515089649122E+4502}
($B45B,$AA6B,$972C,$95FC,$FB78), {-1.7804374121649736373E+4583}
($CB82,$33DD,$DA5B,$B88F,$FC86), {-4.1563772250412736023E+4664}
($90AA,$6E95,$658B,$B48A,$FD95), {-1.5426825919798643530E+4746}
($C03F,$1D53,$D309,$8B77,$FEA5), {-9.0434733129342411538E+4827}
($3D11,$CC1D,$E67F,$A912,$FFB5)); {-8.3194707606651575345E+4909}
begin
if odd(n) or (n<0) then begin
if n=1 then sfc_bernoulli := -0.5
else sfc_bernoulli := 0.0;
end
else begin
m := n div 2;
if m<=MaxB2nSmall then sfc_bernoulli := extended(B2nHex[m])
else if n>MaxBernoulli then sfc_bernoulli := PosInf_x
else begin
{When n is even, B(2n) = -2*(-1)^n*m!/(2Pi)^m*zeta(m) with m=2n. For }
{large m (e.g. m>63) zeta(m) is very close to 1 and we can derive the}
{asymptotic recursion formula B(m+1) = -m*(m+1)/(2Pi)^2 * B(m). The }
{avg. iteration count is <4, the max. rel. error=4.5*eps_x for n=878.}
m := (n - 112) div 32;
bn := extended(bx32[m]);
m := 32*m + 128;
p4 := 4.0*PiSqr;
if n>m then begin
while n>m do begin
inc(m,2);
bn := bn/p4*m*(1-m);
end;
end
else begin
while m>n do begin
bn := bn/m/(1-m)*p4;
dec(m,2);
end;
end;
sfc_bernoulli := bn;
end;
end;
end;
{$ifdef debug}
{$ifdef USE_OutputDebugString}
{---------------------------------------------------------------------------}
procedure sfc_write_debug_str(const msg: sfc_debug_str);
{-Writeln or Outputdebugstr of msg}
var
ax: ansistring;
begin
if sfc_debug_output then begin
if IsConsole then writeln(msg)
else begin
ax := msg;
OutputDebugString(pchar({$ifdef D12Plus}string{$endif}(ax)));
end;
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure sfc_write_debug_str({$ifdef CONST}const{$endif}msg: sfc_debug_str);
{-Writeln or Outputdebugstr of msg}
begin
if sfc_debug_output then writeln(msg);
end;
{$endif}
{---------------------------------------------------------------------------}
procedure sfc_dump_diagctr;
{-writeln diagnostic counters}
var
k: integer;
begin
write('Diag ctr:');
for k:=0 to NDCTR-1 do write(k:3,':',sfc_diagctr[k]);
writeln;
end;
begin
sfc_debug_output := false;
fillchar(sfc_diagctr, sizeof(sfc_diagctr),0);
{$endif}
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.PackageDetailsFrame;
interface
{$I ..\DPMIDE.inc}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
System.Diagnostics,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.Themes,
Vcl.StdCtrls, Vcl.ExtCtrls,
ToolsApi,
Spring.Container,
Spring.Collections,
VSoft.Awaitable,
DPM.Core.Types,
DPM.Core.Configuration.Interfaces,
DPM.Core.Package.Interfaces,
DPM.Core.Package.Installer.Interfaces,
DPM.Core.Repository.Interfaces,
DPM.Core.Logging,
DPM.IDE.Logger,
DPM.Core.Cache.Interfaces,
DPM.Core.Options.Search,
DPM.Core.Options.Install,
DPM.Core.Options.UnInstall,
DPM.IDE.Details.Interfaces,
DPM.IDE.PackageDetailsPanel,
DPM.IDE.IconCache,
DPM.IDE.Types,
Vcl.ImgList,
{$IFDEF USEIMAGECOLLECTION}
Vcl.VirtualImageList,
{$ENDIF}
DPM.Controls.VersionGrid, Vcl.Buttons, Vcl.Imaging.pngimage;
type
TPackageDetailsFrame = class(TFrame)
sbPackageDetails: TScrollBox;
pnlPackageId: TPanel;
lblPackageId: TLabel;
imgPackageLogo: TImage;
pnlVersion: TPanel;
lblVersionTitle: TLabel;
cboVersions: TComboBox;
pnlGridHost: TPanel;
DetailsSplitter: TSplitter;
btnInstallAll: TSpeedButton;
btnUpgradeAll: TSpeedButton;
btnUninstallAll: TSpeedButton;
DebounceTimer: TTimer;
procedure cboVersionsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure cboVersionsChange(Sender: TObject);
procedure cboVersionsCloseUp(Sender: TObject);
procedure cboVersionsDropDown(Sender: TObject);
procedure btnInstallAllClick(Sender: TObject);
procedure btnUpgradeAllClick(Sender: TObject);
procedure btnUninstallAllClick(Sender: TObject);
procedure DebounceTimerTimer(Sender: TObject);
private
//controls
FProjectsGrid : TVersionGrid;
FDetailsPanel : TPackageDetailsPanel;
//controls
{$IFDEF USEIMAGECOLLECTION }
FImageList : TVirtualImageList;
{$ELSE}
FImageList : TImageList;
FUpgradeBmp : TBitmap;
FDowngradeBmp : TBitmap;
{$ENDIF}
FConfiguration : IConfiguration;
FPackageCache : IPackageCache;
FIconCache : TDPMIconCache;
FHost : IDetailsHost;
FLogger : IDPMIDELogger;
FPackageInstaller : IPackageInstaller;
FInstallerContext :IPackageInstallerContext;
FRespositoryManager : IPackageRepositoryManager;
FProjectGroup : IOTAProjectGroup;
FIDEStyleServices : TCustomStyleServices;
FPackageMetaData : IPackageSearchResultItem;
FInstalledVersion : TPackageVersion;
FSelectedVersion : TPackageVersion;
FCancellationTokenSource : ICancellationTokenSource;
FRequestInFlight : boolean;
FVersionsDelayTimer : TTimer;
FClosing : boolean;
FIncludePreRelease : boolean;
FCurrentPlatform : TDPMPlatform;
FDropdownOpen : boolean;
FFetchVersions : boolean;
FVersionsCache : IDictionary<string, IList<TPackageVersion>>;
FMetaDataCache : IDictionary<string, IPackageSearchResultItem>;
FVersionsCacheUdate : TStopWatch;
protected
procedure AssignImages;
procedure ProjectSelectionChanged(Sender : TObject);
procedure UpdateButtonState;
procedure SetPackageLogo(const id : string);
function GetReferenceVersion : TPackageVersion;
procedure VersionsDelayTimerEvent(Sender : TObject);
procedure OnDetailsUriClick(Sender : TObject; const uri : string; const element : TDetailElement);
procedure DoGetPackageMetaDataAsync(const id: string; const version: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform);
procedure UpdateProjectPackageVersions(const packageId : string);
procedure DoPackageUninstall(options : TUnInstallOptions);
procedure DoPackageInstall(options : TInstallOptions; const isUpdate : boolean);
function GetPackageMetaDataAsync(const id: string; const version: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IAwaitable<IPackageSearchResultItem>;
procedure ChangeScale(M: Integer; D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND}); override;
procedure VersionGridOnInstallEvent(const project : string);
procedure VersionGridOnUnInstallEvent(const project : string);
procedure VersionGridOnUpgradeEvent(const project : string);
procedure VersionGridOnDowngradeEvent(const project : string);
procedure DoUpdateVersions(const sReferenceVersion : string; const versions : IList<TPackageVersion>);
//versions cache
function TryGetCachedVersions(const Id : string; const includePrerelease : boolean; out versions : IList<TPackageVersion>) : boolean;
procedure UpdateVersionsCache(const id : string; const includePrerelease : boolean; const versions : IList<TPackageVersion>);
procedure SetImageList(const value : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF});
public
constructor Create(AOwner : TComponent);override;
destructor Destroy;override;
procedure Init(const container : TContainer; const iconCache : TDPMIconCache; const config : IConfiguration; const host : IDetailsHost; const projectGroup : IOTAProjectGroup);
procedure SetPackage(const package : IPackageSearchResultItem; const preRelease : boolean; const fetchVersions : boolean = true);
procedure SetPlatform(const platform : TDPMPlatform);
procedure ViewClosing;
procedure ThemeChanged(const StyleServices : TCustomStyleServices {$IFDEF THEMESERVICES}; const ideThemeSvc : IOTAIDEThemingServices{$ENDIF});
procedure ProjectReloaded;
property ImageList : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF} read FImageList write SetImageList;
end;
implementation
{$R *.dfm}
uses
WinApi.ShellApi,
WinApi.ActiveX,
WinApi.CommCtrl,
DPM.IDE.Constants,
DPM.Core.Utils.Strings,
DPM.Core.Utils.System,
DPM.Core.Package.Metadata,
DPM.Core.Package.SearchResults,
DPM.Core.Dependency.Interfaces;
{ TGroupPackageDetailsFrame }
procedure TPackageDetailsFrame.btnInstallAllClick(Sender: TObject);
var
options : TInstallOptions;
begin
options := TInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FSelectedVersion;
//only install in projects it's not installed in already
options.Projects := FProjectsGrid.GetNotInstalledProjects;
options.Platforms := [FPackageMetaData.Platform];
options.Prerelease := FIncludePreRelease;
options.CompilerVersion := IDECompilerVersion;
DoPackageInstall(options, false);
end;
procedure TPackageDetailsFrame.btnUninstallAllClick(Sender: TObject);
var
options : TUnInstallOptions;
begin
options := TUnInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FPackageMetaData.Version;
//only attempt to uninstall from projects it's actually installed in.
options.Projects := FProjectsGrid.GetInstalledProjects;
options.Platforms := [FPackageMetaData.Platform];
options.CompilerVersion := IDECompilerVersion;
DoPackageUninstall(options);
end;
procedure TPackageDetailsFrame.btnUpgradeAllClick(Sender: TObject);
var
options : TInstallOptions;
begin
options := TInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FSelectedVersion;
//only upgrade/downgrade in projects it's actually ibstalled in.
options.Projects := FProjectsGrid.GetInstalledProjects;
options.Platforms := [FPackageMetaData.Platform];
options.Prerelease := FIncludePreRelease;
options.CompilerVersion := IDECompilerVersion;
options.IsUpgrade := true;
DoPackageInstall(options, true);
end;
procedure TPackageDetailsFrame.DebounceTimerTimer(Sender: TObject);
var
package : IPackageSearchResultItem;
begin
DebounceTimer.Enabled := false;
package := FPackageMetaData; //take a local reference to stop rug being pulled
if package = nil then
exit;
UpdateProjectPackageVersions(package.Id);
FProjectsGrid.Enabled := true;
if FFetchVersions then
FVersionsDelayTimer.Enabled := true;
if FSelectedVersion <> package.Version then
DoGetPackageMetaDataAsync(package.Id, FSelectedVersion.ToStringNoMeta, package.CompilerVersion, package.Platform)
else
FDetailsPanel.SetDetails(FPackageMetaData);
end;
destructor TPackageDetailsFrame.Destroy;
begin
{$IFNDEF USEIMAGECOLLECTION}
FUpgradeBmp.Free;
FDowngradeBmp.Free;
{$ENDIF}
inherited;
end;
procedure TPackageDetailsFrame.DoGetPackageMetaDataAsync(const id: string; const version: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform);
var
metaData : IPackageMetadata;
packageId : IPackageId;
packageVersion : TPackageVersion;
item : IPackageSearchResultItem ;
key : string;
begin
key := LowerCase(id) + '-' + LowerCase(version);
//try and get it from the cache first rather than going to the repo.
if not FMetaDataCache.TryGetValue(key, item) then
begin
packageVersion := TPackageVersion.Parse(version);
packageId := TPackageId.Create(id, packageVersion, compilerVersion, platform);
metaData := FPackageCache.GetPackageMetadata(packageId);
if metaData <> nil then
begin
item := TDPMPackageSearchResultItem.FromMetaData('cache',metaData);
FMetaDataCache[key] := item;
end;
end;
if item <> nil then
begin
FDetailsPanel.SetDetails(item);
FSelectedVersion := item.Version;
UpdateButtonState;
exit;
end;
//didn't find it in the cache so fire off a task to get it from the repo.
GetPackageMetaDataAsync(id, version, compilerVersion, platform)
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('Cancelled searching for packages.');
end)
.Await(
procedure(const theResult : IPackageSearchResultItem)
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
key := LowerCase(theResult.id) + '-' + LowerCase(theResult.version.ToStringNoMeta);
FMetaDataCache[key] := theResult;
FDetailsPanel.SetDetails(theResult);
FSelectedVersion := theResult.Version;
UpdateButtonState;
end);
end;
procedure TPackageDetailsFrame.DoPackageInstall(options: TInstallOptions; const isUpdate : boolean);
var
installResult : boolean;
sPlatform : string;
packageMetadata : IPackageSearchResultItem;
projectCount : integer;
begin
installResult := false;
try
if FRequestInFlight then
FCancellationTokenSource.Cancel;
while FRequestInFlight do
Application.ProcessMessages;
FCancellationTokenSource.Reset;
FLogger.Clear;
FLogger.StartInstall(FCancellationTokenSource);
projectCount := Length(options.Projects);
if projectCount = 0 then
projectCount := 1;
FHost.BeginInstall(projectCount);
installResult := FPackageInstaller.Install(FCancellationTokenSource.Token, options, FInstallerContext);
if installResult then
begin
packageMetadata := FPackageMetaData;
packageMetadata.Installed := true;
packageMetadata.IsTransitive := false;
FHost.PackageInstalled;
UpdateProjectPackageVersions(packageMetaData.Id);
SetPackage(packageMetadata, FIncludePreRelease, true);
FInstalledVersion := options.Version;
FPackageMetaData := packageMetadata;
sPlatform := DPMPlatformToString(FPackageMetaData.Platform);
FLogger.Information('Package ' + FPackageMetaData.Id + ' - ' + FInstalledVersion.ToStringNoMeta + ' [' + sPlatform + '] installed.');
end
else
FLogger.Error('Package ' + FPackageMetaData.Id + ' - ' + FInstalledVersion.ToStringNoMeta + ' [' + sPlatform + '] did not install.');
finally
FLogger.EndInstall(installResult);
FHost.EndInstall;
end;
end;
procedure TPackageDetailsFrame.DoPackageUninstall(options: TUnInstallOptions);
var
uninstallResult : boolean;
sPlatform : string;
packageMetaData : IPackageSearchResultItem;
projectCount : integer;
begin
uninstallResult := false;
try
if FRequestInFlight then
FCancellationTokenSource.Cancel;
while FRequestInFlight do
Application.ProcessMessages;
FCancellationTokenSource.Reset;
FLogger.Clear;
FLogger.StartUnInstall(FCancellationTokenSource);
projectCount := Length(options.Projects);
if projectCount = 0 then
projectCount := 1;
FHost.BeginInstall(projectCount);
sPlatform := DPMPlatformToString(FPackageMetaData.Platform);
FLogger.Information('UnInstalling package ' + FPackageMetaData.Id + ' - ' + FPackageMetaData.Version.ToStringNoMeta + ' [' + sPlatform + ']');
uninstallResult := FPackageInstaller.UnInstall(FCancellationTokenSource.Token, options, FInstallerContext);
if uninstallResult then
begin
packageMetaData := FPackageMetaData;
FLogger.Information('Package ' + packageMetaData.Id + ' - ' + packageMetaData.Version.ToStringNoMeta + ' [' + sPlatform + '] uninstalled.');
FHost.PackageInstalled;
UpdateProjectPackageVersions(packageMetaData.Id);
if FProjectsGrid.HasAnyInstalled then
begin
FInstalledVersion := options.Version;
packageMetaData.Installed := true;
SetPackage(packageMetaData, FIncludePreRelease, false);
end
else
begin
FInstalledVersion := options.Version;
SetPackage(nil, FIncludePreRelease);
end;
end
else
FLogger.Error('Package ' + FPackageMetaData.Id + ' - ' + FPackageMetaData.Version.ToStringNoMeta + ' [' + sPlatform + '] did not uninstall.');
finally
FLogger.EndUnInstall(uninstallResult);
FHost.EndInstall;
end;
end;
procedure TPackageDetailsFrame.cboVersionsChange(Sender: TObject);
var
sVersion : string;
packageVer : TPackageVersion;
begin
sVersion := cboVersions.Items[cboVersions.ItemIndex];
packageVer := TPackageVersion.Parse(sVersion);
FProjectsGrid.PackageVersion := packageVer;
DoGetPackageMetaDataAsync(FPackageMetaData.Id, sVersion, FPackageMetaData.CompilerVersion, FPackageMetaData.Platform);
end;
procedure TPackageDetailsFrame.cboVersionsCloseUp(Sender: TObject);
begin
FDropdownOpen := false;
end;
procedure TPackageDetailsFrame.cboVersionsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
sInstalledVersion : string;
begin
cboVersions.Canvas.FillRect(Rect);
if (cboVersions.Items.Count = 0) or (index < 0) then
exit;
cboVersions.Canvas.Font.Style := [];
sInstalledVersion := FInstalledVersion.ToStringNoMeta;
if odComboBoxEdit in State then
cboVersions.Canvas.TextOut(Rect.Left + 1, Rect.Top + 1, cboVersions.Items[Index]) //Visual state of the text in the edit control
else
begin
if FDropdownOpen {and (Index > 0)} then
begin
if SameText(sInstalledVersion, cboVersions.Items[index]) then
cboVersions.Canvas.Font.Style := [TFontStyle.fsBold];
end;
cboVersions.Canvas.TextOut(Rect.Left + 2, Rect.Top, cboVersions.Items[Index]); //Visual state of the text(items) in the deployed list
end;
end;
procedure TPackageDetailsFrame.cboVersionsDropDown(Sender: TObject);
begin
FDropdownOpen := true;
end;
procedure TPackageDetailsFrame.ChangeScale(M, D: Integer{$IF CompilerVersion > 33}; isDpiChange: Boolean{$IFEND});
begin
inherited;
//scaling seems to be working ok without manual intervention here
end;
constructor TPackageDetailsFrame.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
//not published in older versions, so gets removed when we edit in older versions.
{$IFDEF STYLEELEMENTS}
StyleElements := [seFont];
{$ENDIF}
//trying to inject the grid and the splitter inside the design time controls.
FProjectsGrid := TVersionGrid.Create(AOwner);
FProjectsGrid.Margins.Left := 5;
FProjectsGrid.Margins.Right := 5;
FProjectsGrid.AlignWithMargins := true;
FProjectsGrid.Align := alClient;
FProjectsGrid.Top := 0;
FProjectsGrid.Height := 300;
FProjectsGrid.ParentColor := false;
FProjectsGrid.ParentBackground := false;
FProjectsGrid.ParentFont := true;
FProjectsGrid.DoubleBuffered := true;
FProjectsGrid.OnSelectionChanged := Self.ProjectSelectionChanged;
FProjectsGrid.OnInstallEvent := Self.VersionGridOnInstallEvent;
FProjectsGrid.OnUnInstallEvent := Self.VersionGridOnUnInstallEvent;
FProjectsGrid.OnUpgradeEvent := Self.VersionGridOnUpgradeEvent;
FProjectsGrid.OnDowngradeEvent := Self.VersionGridOnDowngradeEvent;
FProjectsGrid.Enabled := false;
FProjectsGrid.Parent := pnlGridHost;
FDetailsPanel := TPackageDetailsPanel.Create(AOwner);
FDetailsPanel.ParentColor := false;
FDetailsPanel.ParentBackground := false;
FDetailsPanel.DoubleBuffered := true;
FDetailsPanel.Align := alClient;
FDetailsPanel.Height := 200;
FDetailsPanel.Top := DetailsSplitter.Top + DetailsSplitter.Height;
FDetailsPanel.OnUriClick := Self.OnDetailsUriClick;
FDetailsPanel.Parent := sbPackageDetails;
FCurrentPlatform := TDPMPlatform.UnknownPlatform;
FVersionsDelayTimer := TTimer.Create(AOwner);
FVersionsDelayTimer.Interval := 100;
FVersionsDelayTimer.Enabled := false;
FVersionsDelayTimer.OnTimer := VersionsDelayTimerEvent;
FCancellationTokenSource := TCancellationTokenSourceFactory.Create;
{$IFNDEF USEIMAGECOLLECTION } //10.4 or later
FUpgradeBmp := TBitmap.Create;
FDowngradeBmp := TBitmap.Create;
{$ENDIF}
// moved to editorviewframe
// LoadImages;
// AssignImages;
// FProjectsGrid.ImageList := FImageList;
btnInstallAll.Caption := '';
btnUpgradeAll.Caption := '';
btnUninstallAll.Caption := '';
FVersionsCache := TCollections.CreateDictionary<string, IList<TPackageVersion>>;
FVersionsCacheUdate := TStopWatch.Create;
FMetaDataCache := TCollections.CreateDictionary<string, IPackageSearchResultItem>;
SetPackage(nil,false);
// ThemeChanged;
end;
procedure TPackageDetailsFrame.Init(const container: TContainer; const iconCache: TDPMIconCache; const config: IConfiguration; const host: IDetailsHost; const projectGroup : IOTAProjectGroup);
begin
FIconCache := iconCache;
FConfiguration := config;
FLogger := container.Resolve<IDPMIDELogger>;
FPackageInstaller := container.Resolve<IPackageInstaller>;
FInstallerContext := container.Resolve<IPackageInstallerContext>;
FRespositoryManager := container.Resolve<IPackageRepositoryManager>;
FPackageCache := container.Resolve<IPackageCache>;
FHost := host;
SetPackage(nil, FIncludePreRelease);
FProjectGroup := projectGroup;
ProjectReloaded; //loads the project Grid;
end;
procedure TPackageDetailsFrame.AssignImages;
{$IFNDEF USEIMAGECOLLECTION}
var
bmp : TBitmap;
{$ENDIF}
begin
{$IFNDEF USEIMAGECOLLECTION}
bmp := TBitmap.Create;
try
bmp.SetSize(16,16);
FImageList.GetBitmap(0, bmp); //Add
btnInstallAll.Glyph.Assign(bmp);
bmp.SetSize(0,0);
bmp.SetSize(16,16);
FImageList.GetBitmap(1, bmp); //remove
btnUninstallAll.Glyph.Assign(bmp);
FUpgradeBmp.SetSize(16,16);
FImageList.GetBitmap(2, FUpgradeBmp); //upgrade
btnUpgradeAll.Glyph.Assign(FUpgradeBmp);
FDowngradeBmp.SetSize(16,16);
FImageList.GetBitmap(3, FDowngradeBmp); //upgrade
finally
bmp.Free;
end;
{$ELSE}
btnInstallAll.Images := FImageList;
btnInstallAll.ImageIndex := 0;
btnUpgradeAll.Images := FImageList;
btnUpgradeAll.ImageIndex := 2;
btnUninstallAll.Images := FImageList;
btnUninstallAll.ImageIndex := 1;
{$ENDIF}
end;
procedure TPackageDetailsFrame.OnDetailsUriClick(Sender: TObject; const uri: string; const element: TDetailElement);
begin
case element of
deNone : ;
deLicense,
deProjectUrl,
deReportUrl : ShellExecute(Application.Handle, 'open', PChar(uri), nil, nil, SW_SHOWNORMAL);
deTags : ;
end;
end;
procedure TPackageDetailsFrame.ProjectReloaded;
var
i : integer;
begin
FProjectsGrid.BeginUpdate;
FProjectsGrid.Clear;
for i := 0 to FProjectGroup.ProjectCount -1 do
FProjectsGrid.AddProject(FProjectGroup.Projects[i].FileName, '');
FProjectsGrid.EndUpdate;
end;
procedure TPackageDetailsFrame.ProjectSelectionChanged(Sender: TObject);
begin
UpdateButtonState;
end;
procedure TPackageDetailsFrame.UpdateProjectPackageVersions(const packageId : string);
var
i: Integer;
packageRefs : IPackageReference;
projectRefs : IPackageReference;
projectRef : IPackageReference;
begin
packageRefs := FHost.GetPackageReferences;
FProjectsGrid.BeginUpdate;
try
FProjectsGrid.PackageVersion := FSelectedVersion;
for i := 0 to FProjectsGrid.RowCount -1 do
begin
if packageRefs <> nil then
begin
projectRef := nil;
projectRefs := packageRefs.FindDependency(LowerCase(FProjectGroup.Projects[i].FileName));
if projectRefs <> nil then
projectRef := projectRefs.FindDependency(LowerCase(packageId));
end;
if projectRef <> nil then
FProjectsGrid.ProjectVersion[i] := projectRef.Version
else
FProjectsGrid.ProjectVersion[i] := TPackageVersion.Empty;
end;
finally
FProjectsGrid.EndUpdate;
end;
end;
function TPackageDetailsFrame.GetPackageMetaDataAsync(const id: string; const version: string; const compilerVersion: TCompilerVersion; const platform: TDPMPlatform): IAwaitable<IPackageSearchResultItem>;
var
repoManager : IPackageRepositoryManager;
begin
//TODO: can we get from the package cache here???
//local for capture
repoManager := FRespositoryManager;
repoManager.Initialize(FConfiguration);
result := TAsync.Configure <IPackageSearchResultItem> (
function(const cancelToken : ICancellationToken) : IPackageSearchResultItem
begin
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
try
result := repoManager.GetPackageMetaData(cancelToken, id, version, compilerVersion, platform);
finally
CoUninitialize;
end;
//simulating long running.
end, FCancellationTokenSource.Token);
end;
function TPackageDetailsFrame.GetReferenceVersion: TPackageVersion;
var
latestVersion : TPackageVersion;
begin
if FPackageMetaData = nil then
exit(TPackageVersion.Empty);
if FIncludePreRelease then
latestVersion := FPackageMetaData.LatestVersion
else
latestVersion := FPackageMetaData.LatestStableVersion;
if latestVersion > FPackageMetaData.Version then
result := latestVersion
else
result := FPackageMetaData.Version;
end;
procedure TPackageDetailsFrame.SetImageList(const value : {$IFDEF USEIMAGECOLLECTION} TVirtualImageList {$ELSE} TImageList {$ENDIF});
begin
FImageList := value;
FProjectsGrid.ImageList := FImageList;
if FImageList <> nil then
AssignImages;
end;
procedure TPackageDetailsFrame.SetPackage(const package: IPackageSearchResultItem; const preRelease : boolean; const fetchVersions : boolean = true);
var
i: Integer;
wasNil : boolean;
begin
FIncludePreRelease := preRelease;
DebounceTimer.Enabled := false;
FVersionsDelayTimer.Enabled := false;
if FRequestInFlight then
FCancellationTokenSource.Cancel;
//todo - should we wait here?
FMetaDataCache.Clear;
wasNil := FPackageMetaData = nil;
FPackageMetaData := package;
FFetchVersions := fetchVersions;
if package <> nil then
begin
if package.Installed then
FInstalledVersion := package.Version
else
FInstalledVersion := TPackageVersion.Empty;
FSelectedVersion := GetReferenceVersion;
lblPackageId.Caption := package.Id;
SetPackageLogo(package.Id);
cboVersions.Enabled := true;
imgPackageLogo.Visible := true;
lblPackageId.Visible := true;
lblVersionTitle.Visible := true;
cboVersions.Enabled := true;
cboVersions.Visible := true;
FProjectsGrid.Visible := true;
sbPackageDetails.Visible := true;
Application.ProcessMessages;
//if we had no package before then update immediately
if wasNil then
DebounceTimerTimer(DebounceTimer)
else //otherwise debounce as we may be scrolling.
DebounceTimer.Enabled := true;
end
else
begin
FInstalledVersion := TPackageVersion.Empty;
FSelectedVersion := TPackageVersion.Empty;
FProjectsGrid.BeginUpdate;
try
FProjectsGrid.Enabled := false;
for i := 0 to FProjectsGrid.RowCount -1 do
FProjectsGrid.ProjectVersion[i] := TPackageVersion.Empty;
FProjectsGrid.PackageVersion := TPackageVersion.Empty;
finally
FProjectsGrid.EndUpdate;
end;
FDetailsPanel.SetDetails(nil);
// SetPackageLogo('');
cboVersions.Clear;
lblPackageId.Caption := '';
imgPackageLogo.Visible := false;
lblPackageId.Visible := false;
cboVersions.Enabled := false;
lblVersionTitle.Visible := false;
cboVersions.Visible := false;
FProjectsGrid.Visible := false;
sbPackageDetails.Visible := false;
end;
UpdateButtonState;
end;
procedure TPackageDetailsFrame.SetPackageLogo(const id: string);
var
logo : IPackageIconImage;
graphic : TGraphic;
begin
if FIconCache = nil then
exit;
logo := FIconCache.Request(id);
if logo = nil then
logo := FIconCache.Request('missing_icon');
if logo <> nil then
begin
graphic := logo.ToGraphic;
try
imgPackageLogo.Picture.Assign(graphic);
imgPackageLogo.Visible := true;
finally
graphic.Free;
end;
end
else
imgPackageLogo.Visible := false;
end;
procedure TPackageDetailsFrame.SetPlatform(const platform: TDPMPlatform);
begin
FCurrentPlatform := platform;
end;
procedure TPackageDetailsFrame.ThemeChanged(const StyleServices : TCustomStyleServices {$IFDEF THEMESERVICES}; const ideThemeSvc : IOTAIDEThemingServices{$ENDIF});
begin
{$IFDEF THEMESERVICES}
FIDEStyleServices := StyleServices;
ideThemeSvc.ApplyTheme(Self);
{$ELSE}
FIDEStyleServices := Vcl.Themes.StyleServices;
{$ENDIF}
Self.Color := FIDEStyleServices.GetSystemColor(clWindow);
{$IF CompilerVersion >= 32.0}
sbPackageDetails.ParentColor := false;
sbPackageDetails.ParentBackground := false;
sbPackageDetails.StyleElements := [seFont];
sbPackageDetails.Color := FIDEStyleServices.GetSystemColor(clWindow);
pnlPackageId.StyleElements := [seFont];
pnlPackageId.Color := sbPackageDetails.Color;
pnlVersion.StyleElements := [seFont];
pnlVersion.Color := sbPackageDetails.Color;
FDetailsPanel.StyleElements := [seFont];
FDetailsPanel.Color := sbPackageDetails.Color;
FDetailsPanel.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FProjectsGrid.Color := sbPackageDetails.Color;
FProjectsGrid.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
{$ELSE}
sbPackageDetails.Color := FIDEStyleServices.GetSystemColor(clWindow);
FDetailsPanel.Color := FIDEStyleServices.GetSystemColor(clWindow);
FDetailsPanel.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
FProjectsGrid.Color := FIDEStyleServices.GetSystemColor(clWindow);
FProjectsGrid.Font.Color := FIDEStyleServices.GetSystemColor(clWindowText);
{$IFEND}
FProjectsGrid.StyleServices := FIDEStyleServices;
end;
function TPackageDetailsFrame.TryGetCachedVersions(const Id: string; const includePrerelease : boolean; out versions: IList<TPackageVersion>): boolean;
begin
result := false;
if FVersionsCacheUdate.IsRunning and (FVersionsCacheUdate.Elapsed.Seconds > 60) then
begin
FVersionsCache.Clear;
FVersionsCacheUdate.Reset;
FVersionsCacheUdate.Start;
exit;
end
else
begin
result := FVersionsCache.TryGetValue(LowerCase(id + '-' + BoolToStr(includePrerelease,true)), versions);
FVersionsCacheUdate.Start;
end;
end;
procedure TPackageDetailsFrame.UpdateButtonState;
var
referenceVersion : TPackageVersion;
begin
if FPackageMetaData = nil then
begin
btnInstallAll.Enabled := false;
btnUpgradeAll.Enabled := false;
btnUninstallAll.Enabled := false;
btnInstallAll.Visible := false;
btnUpgradeAll.Visible := false;
btnUninstallAll.Visible := false;
exit;
end
else
begin
btnUninstallAll.Visible := true;
btnUpgradeAll.Visible := true;
btnInstallAll.Visible := true;
end;
referenceVersion := GetReferenceVersion;
btnInstallAll.Enabled := FPackageMetaData <> nil;
btnUpgradeAll.Enabled := (FPackageMetaData <> nil) and (FInstalledVersion <> TPackageVersion.Empty) and (FSelectedVersion <> FInstalledVersion);
btnUninstallAll.Enabled := (FPackageMetaData <> nil) and (FInstalledVersion <> TPackageVersion.Empty);
{$IFNDEF USEIMAGECOLLECTION}
if FSelectedVersion = FInstalledVersion then
begin
btnUpgradeAll.Glyph.Assign(nil);
end
else if FSelectedVersion > FInstalledVersion then
begin
btnUpgradeAll.Glyph.Assign(FUpgradeBmp);
btnUpgradeAll.Hint := 'Upgrade package in all projects';
end
else
begin
btnUpgradeAll.Glyph.Assign(FDowngradeBmp);
btnUpgradeAll.Hint := 'Downgrade package in all projects';
end;
{$ELSE}
if FSelectedVersion = FInstalledVersion then
begin
btnUpgradeAll.ImageIndex := -1;
end
else if FSelectedVersion > FInstalledVersion then
begin
btnUpgradeAll.ImageIndex := 2;
btnUpgradeAll.Hint := 'Upgrade package in all projects';
end
else
begin
btnUpgradeAll.ImageIndex := 3;
btnUpgradeAll.Hint := 'Downgrade package in all projects';
end;
{$ENDIF}
end;
procedure TPackageDetailsFrame.UpdateVersionsCache(const id: string; const includePrerelease : boolean; const versions: IList<TPackageVersion>);
begin
FVersionsCacheUdate.Stop;
if FVersionsCacheUdate.Elapsed.Seconds > 120 then
begin
FVersionsCache.Clear;
FVersionsCacheUdate.Reset;
end;
FVersionsCache[LowerCase(id + '-' + BoolToStr(includePrerelease,true))] := versions;
FVersionsCacheUdate.Start;
end;
procedure TPackageDetailsFrame.VersionGridOnDowngradeEvent(const project: string);
var
options : TInstallOptions;
begin
options := TInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FSelectedVersion;
options.ProjectPath := project;
options.Platforms := [FPackageMetaData.Platform];
options.Prerelease := FIncludePreRelease;
options.CompilerVersion := IDECompilerVersion;
options.Force := true;
DoPackageInstall(options, true);
end;
procedure TPackageDetailsFrame.VersionGridOnInstallEvent(const project: string);
var
options : TInstallOptions;
begin
options := TInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FSelectedVersion;
options.ProjectPath := project;
options.Platforms := [FPackageMetaData.Platform];
options.Prerelease := FIncludePreRelease;
options.CompilerVersion := IDECompilerVersion;
DoPackageInstall(options, false);
//call common function
end;
procedure TPackageDetailsFrame.VersionGridOnUnInstallEvent(const project: string);
var
options : TUnInstallOptions;
begin
options := TUnInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FPackageMetaData.Version;
options.ProjectPath := project;
options.Platforms := [FPackageMetaData.Platform];
options.CompilerVersion := IDECompilerVersion;
DoPackageUninstall(options);
end;
procedure TPackageDetailsFrame.VersionGridOnUpgradeEvent(const project: string);
var
options : TInstallOptions;
begin
options := TInstallOptions.Create;
options.ConfigFile := FConfiguration.FileName;
options.PackageId := FPackageMetaData.Id;
options.Version := FSelectedVersion;
options.ProjectPath := project;
options.Platforms := [FPackageMetaData.Platform];
options.Prerelease := FIncludePreRelease;
options.CompilerVersion := IDECompilerVersion;
options.IsUpgrade := true; //changing the installed version
DoPackageInstall(options, true);
//call common function
end;
procedure TPackageDetailsFrame.DoUpdateVersions(const sReferenceVersion : string; const versions : IList<TPackageVersion>);
var
version : TPackageVersion;
begin
cboVersions.Items.BeginUpdate;
try
cboVersions.Clear;
if versions.Any then
begin
for version in versions do
begin
if FPackageMetaData.IsTransitive then
begin
if FPackageMetaData.VersionRange.IsSatisfiedBy(version) then
cboVersions.Items.Add(version.ToStringNoMeta);
end
else
cboVersions.Items.Add(version.ToStringNoMeta);
end;
cboVersions.ItemIndex := cboVersions.Items.IndexOf(sReferenceVersion);
end
else
begin
//no versions returned
//this can happen if there is only 1 version and its prerelease and
//prerlease not checked.
//in this case we will just add the reference version
if sReferenceVersion <> '' then
begin
cboVersions.Items.Add(sReferenceVersion);
cboVersions.ItemIndex := 0;
end;
//btnInstall.Enabled := false;
end;
finally
cboVersions.Items.EndUpdate;
end;
end;
procedure TPackageDetailsFrame.VersionsDelayTimerEvent(Sender: TObject);
var
repoManager : IPackageRepositoryManager;
sReferenceVersion : string;
includePreRelease : boolean;
cachedVersions : IList<TPackageVersion>;
begin
FVersionsDelayTimer.Enabled := false;
if FRequestInFlight then
FCancellationTokenSource.Cancel;
while FRequestInFlight do
Application.ProcessMessages;
FCancellationTokenSource.Reset;
cboVersions.Clear;
sReferenceVersion := GetReferenceVersion.ToStringNoMeta;
includePreRelease := FIncludePreRelease or (not FPackageMetaData.Version.IsStable);
//avoid going to the repo for the info all the time, new versions are not published
//that often so we can afford to cache the info.
if TryGetCachedVersions(FPackageMetaData.Id, includePreRelease, cachedVersions ) then
begin
DoUpdateVersions(sReferenceVersion, cachedVersions);
exit;
end;
repoManager := FRespositoryManager; //local for capture
repoManager.Initialize(FConfiguration);
TAsync.Configure<IList<TPackageVersion>> (
function(const cancelToken : ICancellationToken) : IList<TPackageVersion>
begin
//need this for the http api/
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
try
result := repoManager.GetPackageVersions(cancelToken, IDECompilerVersion, FCurrentPlatform, FPackageMetaData.Id, includePreRelease);
finally
CoUninitialize;
end;
end, FCancellationTokenSource.Token)
.OnException(
procedure(const e : Exception)
begin
FRequestInFlight := false;
if FClosing then
exit;
FLogger.Error(e.Message);
end)
.OnCancellation(
procedure
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('Cancelled getting package versions.');
end)
.Await(
procedure(const versions : IList<TPackageVersion>)
begin
FRequestInFlight := false;
//if the view is closing do not do anything else.
if FClosing then
exit;
FLogger.Debug('Got package versions .');
UpdateVersionsCache(FPackageMetaData.Id, includePreRelease, versions);
DoUpdateVersions(sReferenceVersion, versions);
end);
end;
procedure TPackageDetailsFrame.ViewClosing;
begin
FClosing := true;
FHost := nil;
FCancellationTokenSource.Cancel;
end;
end.
|
unit UnitDBDeclare;
interface
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
System.DateUtils,
Vcl.Graphics,
Vcl.Forms,
Vcl.Imaging.JPEG,
Data.DB,
EasyListview,
GraphicCrypt,
Dmitry.CRC32,
Dmitry.Utils.Files,
Dmitry.PathProviders,
uMemory,
uDBBaseTypes,
uDBGraphicTypes,
uRuntime,
uDBAdapter,
uCDMappingTypes;
const
BufferSize = 100 * 3 * 4 * 4096;
const
LINE_INFO_UNDEFINED = 0;
LINE_INFO_OK = 1;
LINE_INFO_ERROR = 2;
LINE_INFO_WARNING = 3;
LINE_INFO_PLUS = 4;
LINE_INFO_PROGRESS = 5;
LINE_INFO_DB = 6;
LINE_INFO_GREETING = 7;
LINE_INFO_INFO = -1;
type
PBuffer = ^TBuffer;
TBuffer = array [1..BufferSize] of Byte;
type
TPasswordRecord = class
public
CRC: Cardinal;
FileName: string;
ID: Integer;
end;
TWriteLineProcedure = procedure(Sender: TObject; Line: string; aType: Integer) of object;
TGetFilesWithoutPassProc = function(Sender: TObject): TList of object;
TAddCryptFileToListProc = procedure(Sender: TObject; Rec: TPasswordRecord) of object;
TGetAvaliableCryptFileList = function(Sender: TObject): TArInteger of object;
type
TEventField = (EventID_Param_Name, EventID_Param_ID, EventID_Param_Rotate,
EventID_Param_Rating, EventID_Param_Access, EventID_Param_Comment,
EventID_Param_KeyWords, EventID_Param_Attr,
EventID_Param_Image, EventID_Param_Refresh, EventID_Param_Critical,
EventID_Param_Delete, EventID_Param_Date,
EventID_Param_Person,
EventID_Param_Time, EventID_Param_IsDate , EventID_Param_IsTime,
EventID_Param_Groups, EventID_Param_Crypt, EventID_Param_Include,
EventID_Param_GroupsChanged,
EventID_Param_Add_Crypt_WithoutPass, SetNewIDFileData, EventID_CancelAddingImage,
EventID_Param_Links, EventID_Param_DB_Changed, EventID_Param_Refresh_Window,
EventID_FileProcessed, EventID_Repaint_ImageList, EventID_No_EXIF,
EventID_PersonAdded, EventID_PersonChanged, EventID_PersonRemoved,
EventID_GroupAdded, EventID_GroupChanged, EventID_GroupRemoved,
EventID_ShelfChanged, EventID_ShelfItemRemoved, EventID_ShelfItemAdded,
EventID_CollectionInfoChanged, EventID_CollectionFoldersChanged,
EventID_CollectionFolderWatchSupress, EventID_CollectionFolderWatchResume);
TEventFields = set of TEventField;
TEventValues = record
ID: Integer;
FileName: string;
NewName: string;
Rotation: Integer;
Rating: Integer;
Comment: string;
KeyWords: string;
Access: Integer;
Attr: Integer;
Date: TDateTime;
Time: TDateTime;
IsDate: Boolean;
IsTime: Boolean;
Groups: string;
Links: string;
JPEGImage: TJpegImage;
IsEncrypted: Boolean;
Include: Boolean;
Data: TObject;
end;
TClonableObject = class(TObject)
public
function Clone: TClonableObject; virtual; abstract;
end;
TSearchDataExtension = class(TClonableObject)
public
Bitmap: TBitmap;
Icon: TIcon;
CompareResult: TImageCompareResult;
function Clone: TClonableObject; override;
constructor Create;
destructor Destroy; override;
end;
TLVDataObject = class(TObject)
private
public
Include: Boolean;
IsImage: Boolean;
Data: TObject;
constructor Create;
destructor Destroy; override;
end;
TCryptImageThreadOptions = record
Files: TArStrings;
IDs: TArInteger;
Selected: TArBoolean;
Password: string;
EncryptOptions: Integer;
Action: Integer;
end;
// Структура с информацией об изменении в файловой системе (передается в callback процедуру)
PInfoCallback = ^TInfoCallback;
TInfoCallback = record
Action: Integer; // тип изменения (константы FILE_ACTION_XXX)
OldFileName: string; // имя файла до переименования
NewFileName: string; // имя файла после переименования
end;
TInfoCallBackDirectoryChangedArray = array of TInfoCallback;
TDirectoryWatchType = (dwtBoth, dwtDirectories, dwtFiles);
// callback процедура, вызываемая при изменении в файловой системе
TWatchFileSystemCallback = procedure(WatchType: TDirectoryWatchType; PInfo: TInfoCallBackDirectoryChangedArray) of object;
TNotifyDirectoryChangeW = procedure(Sender: TObject; SID: string; pInfo: TInfoCallBackDirectoryChangedArray) of object;
TImportPlace = class(TObject)
public
Path: string;
end;
TGeoLocation = class
Latitude: Double;
Longitude: Double;
function Copy: TGeoLocation;
procedure Assign(Item: TGeoLocation);
end;
TEncryptImageOptions = record
Password: string;
CryptFileName: Boolean;
end;
TDataObject = class
public
function Clone: TDataObject; virtual; abstract;
procedure Assign(Source: TDataObject); virtual; abstract;
end;
TDatabaseInfo = class(TDataObject)
private
FOldTitle: string;
FTitle: string;
procedure SetTitle(const Value: string);
public
Path: string;
Icon: string;
Description: string;
Order: Integer;
constructor Create; overload;
constructor Create(Title, Path, Icon, Description: string; Order: Integer = 0); overload;
function Clone: TDataObject; override;
procedure Assign(Source: TDataObject); override;
property Title: string read FTitle write SetTitle;
property OldTitle: string read FOldTitle;
end;
type
TRemoteCloseFormProc = procedure(Form: TForm; ID: string) of object;
TFileFoundedEvent = procedure(Owner: TObject; FileName: string; Size: Int64) of object;
type
TCallBackBigSizeProc = procedure(Sender: TObject; SizeX, SizeY: Integer) of object;
TWatermarkMode = (WModeImage, WModeText);
TWatermarkOptions = record
DrawMode: TWatermarkMode;
ImageFile: string;
KeepProportions: Boolean;
ImageTransparency: Byte;
StartPoint, EndPoint: TPoint;
Text: string;
BlockCountX: Integer;
BlockCountY: Integer;
Transparenty: Byte;
Color: TColor;
FontName: string;
IsBold: Boolean;
IsItalic: Boolean;
end;
TPreviewOptions = record
GeneratePreview: Boolean;
PreviewWidth: Integer;
PreviewHeight: Integer;
end;
TProcessingParams = record
Rotation: Integer;
ResizeToSize: Boolean;
Width: Integer;
Height: Integer;
Resize: Boolean;
Rotate: Boolean;
PercentResize: Integer;
Convert: Boolean;
GraphicClass: TGraphicClass;
SaveAspectRation: Boolean;
Preffix: string;
WorkDirectory: string;
AddWatermark: Boolean;
WatermarkOptions: TWatermarkOptions;
PreviewOptions: TPreviewOptions;
end;
implementation
{ TSearchDataExtension }
function TSearchDataExtension.Clone: TClonableObject;
begin
Result := TSearchDataExtension.Create;
TSearchDataExtension(Result).CompareResult := CompareResult;
if Bitmap <> nil then
begin
TSearchDataExtension(Result).Bitmap := TBitmap.Create;
TSearchDataExtension(Result).Bitmap.Assign(Bitmap);
end;
end;
constructor TSearchDataExtension.Create;
begin
Bitmap := nil;
Icon := nil;
end;
destructor TSearchDataExtension.Destroy;
begin
F(Bitmap);
F(Icon);
inherited;
end;
{ TLVDataObject }
constructor TLVDataObject.Create;
begin
Data := nil;
end;
destructor TLVDataObject.Destroy;
begin
F(Data);
inherited;
end;
{ TGeoLocation }
procedure TGeoLocation.Assign(Item: TGeoLocation);
begin
Self.Latitude := Item.Latitude;
Self.Longitude := Item.Longitude;
end;
function TGeoLocation.Copy: TGeoLocation;
begin
Result := TGeoLocation.Create;
Result.Assign(Self);
end;
{ TDatabaseInfo }
procedure TDatabaseInfo.Assign(Source: TDataObject);
var
DI: TDatabaseInfo;
begin
DI := Source as TDatabaseInfo;
if DI <> nil then
begin
Title := DI.Title;
Path := DI.Path;
Icon := DI.Icon;
Description := DI.Description;
Order := DI.Order;
end;
end;
function TDatabaseInfo.Clone: TDataObject;
begin
Result := TDatabaseInfo.Create(Title, Path, Icon, Description, Order);
end;
constructor TDatabaseInfo.Create;
begin
end;
constructor TDatabaseInfo.Create(Title, Path, Icon, Description: string; Order: Integer = 0);
begin
Self.Title := Title;
Self.Path := Path;
Self.Icon := Icon;
Self.Description := Description;
Self.Order := Order;
FOldTitle := Title;
end;
procedure TDatabaseInfo.SetTitle(const Value: string);
begin
FTitle := Value;
end;
end.
|
unit UDLogOnServerAdd;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TCrpeLogOnServerAddDlg = class(TForm)
pnlLogOnServerAdd: TPanel;
lblServerName: TLabel;
lblDatabaseName: TLabel;
lblUserID: TLabel;
lblPassword: TLabel;
lblDLLName: TLabel;
editServerName: TEdit;
editDatabaseName: TEdit;
editUserID: TEdit;
editPassword: TEdit;
editDLLName: TEdit;
btnOk: TButton;
btnCancel: TButton;
procedure btnOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CrpeLogOnServerAddDlg: TCrpeLogOnServerAddDlg;
implementation
{$R *.DFM}
uses UCrpeUtl;
procedure TCrpeLogOnServerAddDlg.btnOkClick(Sender: TObject);
begin
{Check to see if ServerName edit field is blank}
if IsStrEmpty(editServerName.Text) then
begin
MessageDlg('Please fill in ServerName before Adding.', mtWarning, [mbOk], 0);
ModalResult := mrNone;
end;
end;
end.
|
(* Stack ADS 19.04.2017 *)
(* ---------- *)
(* implementing the stack as abstract data structure *)
(* ================================================== *)
UNIT StackADS;
INTERFACE
PROCEDURE Init;
PROCEDURE Push(e: INTEGER);
PROCEDURE Pop(VAR e: INTEGER);
FUNCTION Empty: BOOLEAN;
IMPLEMENTATION
CONST
max = 100;
VAR
data: Array[1..max] OF INTEGER;
top: INTEGER;
PROCEDURE Init;
BEGIN
top := 0;
END;
PROCEDURE Push(e: INTEGER);
BEGIN
IF top = max THEN BEGIN
WriteLn('Stack overflow');
END
ELSE BEGIN
top := top + 1;
data[top] := e;
END;
END;
PROCEDURE Pop(VAR e: INTEGER);
BEGIN
IF top = 0 THEN BEGIN
WriteLn('Stack underflow');
END
ELSE BEGIN
e := data[top];
top := top - 1;
END;
END;
FUNCTION Empty: BOOLEAN;
BEGIN
Empty := top = 0;
END;
BEGIN
Init;
END. (* StackADS *)
|
object FindInFilesDialog: TFindInFilesDialog
Left = 412
Top = 114
HelpContext = 810
BorderStyle = bsDialog
Caption = 'Find in Files Search'
ClientHeight = 288
ClientWidth = 361
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
KeyPreview = True
OldCreateOrder = True
Position = poScreenCenter
Scaled = False
DesignSize = (
361
288)
PixelsPerInch = 96
TextHeight = 13
object lblFind: TLabel
Left = 21
Top = 12
Width = 53
Height = 13
Alignment = taRightJustify
Caption = '&Text to find'
FocusControl = cbText
end
object cbText: TComboBox
Left = 80
Top = 8
Width = 275
Height = 21
Anchors = [akLeft, akTop, akRight]
DropDownCount = 15
ItemHeight = 13
TabOrder = 0
end
object gbxOptions: TGroupBox
Left = 8
Top = 40
Width = 161
Height = 106
Caption = 'Options'
TabOrder = 1
object cbNoCase: TCheckBox
Left = 8
Top = 16
Width = 148
Height = 17
Caption = '&Case sensitive'
TabOrder = 0
end
object cbNoComments: TCheckBox
Left = 8
Top = 79
Width = 148
Height = 17
Caption = '&Ignore comments'
TabOrder = 3
end
object cbWholeWord: TCheckBox
Left = 8
Top = 36
Width = 148
Height = 17
Caption = '&Whole word'
TabOrder = 1
end
object cbRegEx: TCheckBox
Left = 8
Top = 58
Width = 148
Height = 17
Caption = 'Regular e&xpression'
TabOrder = 2
end
end
object gbxWhere: TGroupBox
Left = 176
Top = 40
Width = 178
Height = 106
Anchors = [akLeft, akTop, akRight]
Caption = 'Where'
TabOrder = 2
object rbOpenFiles: TRadioButton
Left = 8
Top = 36
Width = 168
Height = 17
Caption = '&Open files'
TabOrder = 1
OnClick = rbDirectoriesClick
end
object rbDirectories: TRadioButton
Left = 8
Top = 57
Width = 168
Height = 17
Caption = 'Search in &directories'
TabOrder = 2
OnClick = rbDirectoriesClick
end
object rbCurrentOnly: TRadioButton
Left = 8
Top = 16
Width = 168
Height = 17
Caption = 'Current &file only'
TabOrder = 0
OnClick = rbDirectoriesClick
end
end
object gbxDirectories: TGroupBox
Left = 8
Top = 152
Width = 347
Height = 97
Anchors = [akLeft, akTop, akRight]
Caption = 'Directory Search'
TabOrder = 3
DesignSize = (
347
97)
object lblMasks: TLabel
Left = 15
Top = 52
Width = 49
Height = 13
Alignment = taRightJustify
Caption = 'File mas&ks'
FocusControl = cbMasks
end
object lblDirectory: TLabel
Left = 14
Top = 26
Width = 50
Height = 13
Alignment = taRightJustify
Caption = 'Di&rectories'
FocusControl = cbDirectory
end
object cbMasks: TComboBox
Left = 70
Top = 48
Width = 264
Height = 21
Anchors = [akLeft, akTop, akRight]
DropDownCount = 15
ItemHeight = 13
TabOrder = 2
end
object cbInclude: TCheckBox
Left = 70
Top = 72
Width = 266
Height = 17
Anchors = [akLeft, akTop, akRight]
Caption = 'Include su&bdirectories'
TabOrder = 3
end
object cbDirectory: TComboBox
Left = 70
Top = 22
Width = 242
Height = 21
Anchors = [akLeft, akTop, akRight]
DropDownCount = 15
ItemHeight = 13
TabOrder = 0
OnDropDown = cbDirectoryDropDown
end
object btnBrowse: TButton
Left = 313
Top = 22
Width = 20
Height = 20
Hint = 'Select Directory'
Anchors = [akTop, akRight]
Caption = '...'
ParentShowHint = False
ShowHint = True
TabOrder = 1
TabStop = False
OnClick = btnBrowseClick
end
end
object btnOK: TButton
Left = 120
Top = 256
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
TabOrder = 4
OnClick = btnOKClick
end
object btnCancel: TButton
Left = 200
Top = 256
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 5
end
object btnHelp: TButton
Left = 280
Top = 256
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = '&Help'
TabOrder = 6
OnClick = btnHelpClick
end
end
|
unit ClothDemo.Cloth;
{$ifdef FPC}
{$mode Delphi}
{$endif FPC}
interface
uses
UITypes, Types, Contnrs, Controls, Graphics;
type
TMouseState = record
Cut: integer;
Influence: integer;
IsDown: Boolean;
Button: TMouseButton;
Pos: TPoint;
PrevPos: TPoint;
end;
TConstraint = class;
TWorld = class
Buffer: TBitmap;
Mouse: TMouseState;
Accuracy: integer;
Gravity: double;
Spacing: double;
TearDist: double;
Friction: double;
Bounce: double;
constructor Create;
constructor CreateWithDefaults(aWidth,aHeight:Integer);
constructor CreateWithZeroG(aWidth,aHeight:Integer);
procedure InitWithDefaults;
public
destructor Destroy; override;
procedure ClearCanvas;
end;
TClothPoint = class
type
{ TPointFHelper }
TPointFHelper = record helper for TPointF
function SquareDistance(const P2: TPointF): Double; {$ifdef FPC}overload;{$endif}
{$ifdef FPC}
function SquareDistance(const P2: TPoint): Double; overload;
class function Zero: TPointF; static;
class function Create(x, y: Single): TPointF; static;
{$endif}
end;
var
World: TWorld;
Pos:TPointF;
PrevPos:TPointF;
Force:TPointF;
PinPos:TPointF;
isPinned:Boolean;
Constraints: TObjectList;
constructor Create(aPoint: TPointF; aWorld: TWorld);
procedure Update(const aRect: TRect; aDelta: double);
procedure Draw(aColor:TColor);
procedure Resolve;
procedure Attach(aPoint: TClothPoint);
procedure Free(aConstraint: TConstraint);
procedure AddForce(const aForce:TPointF);
procedure Pin;
private
procedure CalcBounce(const aRect: TRect);
public
destructor Destroy; override;
end;
TConstraint = class
P1: TClothPoint;
P2: TClothPoint;
Length: double;
World: TWorld;
constructor Create(aP1, aP2: TClothPoint; aWorld: TWorld);
procedure Resolve;
procedure Draw(aCanvas: TCanvas; aCol:TColor);
end;
TCloth = class
World: TWorld;
Points: TObjectList;
Color:TColor;
procedure Offset(p:TPointF);
constructor Create(aFree: Boolean; aWorld: TWorld; aXCount, aYCount: integer);
procedure Update(aDelta: double);
destructor Destroy; override;
end;
{$ifdef FPC}
function PointF(x, y: Single): TPointF; overload;
function PointF(const P: TPoint): TPointF; overload;
{$endif FPC}
implementation
uses
Math;
{$ifdef FPC}
type
TRectFHelper = record helper for TRectF
function Truncate: TRect;
end;
function PointF(x, y: Single): TPointF; overload;
begin
Result.x := x;
Result.y := y;
end;
function PointF(const P: TPoint): TPointF; overload;
begin
Result := PointF(P.x, P.y);
end;
function RectF(Left, Top, Right, Bottom: Single): TRectF;
begin
Result.Left := Left;
Result.Top := Top;
Result.Right := Right;
Result.Bottom := Bottom;
end;
{ TRectFHelper }
function TRectFHelper.Truncate: TRect;
begin
Result.Left := Trunc(Left);
Result.Top := Trunc(Top);
Result.Right := Trunc(Right);
Result.Bottom := Trunc(Bottom);
end;
{$endif FPC}
constructor TClothPoint.Create(aPoint: TPointF; aWorld: TWorld);
begin
World := aWorld;
Pos := aPoint;
PrevPos := Pos;
Force.x := 0;
Force.y := 0;
PinPos.x := 0;
PinPos.y := 0;
Constraints := TObjectList.Create;
end;
destructor TClothPoint.Destroy;
begin
Constraints.Free;
inherited;
end;
procedure TClothPoint.Draw(aColor:TColor);
var
i: integer;
begin
World.Buffer.Canvas.Brush.Color := clBlue;
if IsPinned then
World.Buffer.Canvas.FillRect(Rectf(Pos.X-2,Pos.Y-2,Pos.X+2,Pos.Y+2).Truncate);
for i := Constraints.Count-1 downto 0 do
TConstraint(Constraints[i]).Draw(World.Buffer.Canvas, aColor);
end;
procedure TClothPoint.Update(const aRect: TRect; aDelta: double);
var
sqdist:Double;
n:TPointF;
begin
if isPinned then
Exit;
if World.Mouse.IsDown then
begin
sqdist := Pos.SquareDistance(World.Mouse.Pos);
if (World.Mouse.Button = TMouseButton.mbLeft) and (sqdist < sqr(World.Mouse.Influence)) then
PrevPos := Pos - (PointF(World.Mouse.Pos) - PointF(World.Mouse.PrevPos))
else if sqdist < sqr(World.Mouse.Cut) then
Constraints.Clear;
end;
AddForce(PointF(0, World.Gravity));
n := Pos + (Pos - PrevPos) * World.Friction + Force * aDelta;
PrevPos := Pos;
Pos := n;
Force := TPointF.Zero;
CalcBounce(aRect);
end;
procedure TClothPoint.Resolve;
var
i: integer;
begin
if isPinned then
Exit;
for i := Constraints.Count-1 downto 0 do
TConstraint(Constraints[i]).Resolve;
end;
procedure TClothPoint.Attach(aPoint: TClothPoint);
begin
Constraints.Add( TConstraint.Create(self, aPoint, World) );
end;
procedure TClothPoint.Free(aConstraint: TConstraint);
begin
Constraints.Remove(aConstraint);
end;
procedure TClothPoint.AddForce(const aForce:TPointF);
begin
Force := Force + aForce;
end;
procedure TClothPoint.Pin;
begin
isPinned := True;
PinPos := Pos;
end;
procedure TClothPoint.CalcBounce(const aRect: TRect);
begin
if Pos.X >= aRect.Width then begin PrevPos.X := aRect.Width + (aRect.Width - PrevPos.X) * World.Bounce; Pos.X := aRect.Width; end else
if Pos.X <= 0 then begin PrevPos.X := PrevPos.X * (-1 * World.Bounce); Pos.X := 0; end;
if Pos.Y >= aRect.height then begin PrevPos.Y := aRect.height + (aRect.height - PrevPos.Y) * World.Bounce; Pos.Y := aRect.height; end else
if Pos.Y <= 0 then begin PrevPos.Y := PrevPos.Y * (-1 * World.Bounce); Pos.Y := 0; end;
end;
{ TConstraint }
constructor TConstraint.Create(aP1, aP2: TClothPoint; aWorld: TWorld);
begin
World := aWorld;
// note that we get p1 and p2 passed in, and we just keep the reference
// don't free these when destroying the constraint
P1 := aP1;
P2 := aP2;
Length := World.Spacing;
end;
procedure TConstraint.Resolve;
var
d,p:TPointF;
dist, diff, mul: double;
begin
dist := P1.Pos.Distance(P2.Pos);
if dist < Length then
Exit;
d := P1.Pos - P2.Pos;
diff := (Length - dist) / dist;
if dist > World.TearDist then
begin
P1.Free(self);
Exit;
end;
mul := diff * 0.5 * (1 - Length / dist);
p := d * mul;
if not P1.isPinned then
P1.Pos := P1.Pos + p;
if not P2.isPinned then
P2.Pos := P2.Pos - p;
end;
procedure TConstraint.Draw(aCanvas: TCanvas; aCol:TColor);
begin
aCanvas.Pen.Color := aCol;
aCanvas.moveTo(Round(P1.Pos.x), Round(P1.Pos.y));
aCanvas.lineTo(Round(P2.Pos.x), Round(P2.Pos.y));
end;
{ TCloth }
procedure TCloth.Offset(p: TPointF);
var i:integer;
begin
for I := 0 to Points.Count - 1 do
begin
TClothPoint(Points[I]).Pos.Offset(p);
TClothPoint(Points[I]).PrevPos.Offset(p);
TClothPoint(Points[I]).Force.Offset(p);
TClothPoint(Points[I]).PinPos.Offset(p);
end;
end;
constructor TCloth.Create(aFree: Boolean; aWorld: TWorld; aXCount, aYCount: integer);
var
startX: double;
startY: double;
y, x : integer;
point : TClothPoint;
begin
World := aWorld;
Points := TObjectList.Create;
startX := World.Buffer.Width / 2 - aXCount * World.Spacing / 2;
startY := 20;
for y := 0 to aYCount do
begin
for x := 0 to aXCount do
begin
point := TClothPoint.Create(
Tpointf.Create(
startX + x * World.Spacing ,
startY + y * World.Spacing
), World);
if (not aFree) and (y = 0) and (x mod 5 = 0) then
point.Pin;
if x <> 0 then
point.Attach(TClothPoint(Points.Last));
if y <> 0 then
point.Attach(TClothPoint(Points[x + (y - 1) * (aXCount + 1)]));
Points.Add(point);
end;
end;
end;
procedure TCloth.Update(aDelta: double);
var
a,p: integer;
begin
for a := 0 to World.Accuracy-1 do
for p := Points.Count-1 downto 0 do
TClothPoint(Points[p]).Resolve;
for p := 0 to Points.Count-1 do
begin
TClothPoint(Points[p]).Update(Rect(0, 0, World.Buffer.Width, World.Buffer.Height), aDelta * aDelta);
TClothPoint(Points[p]).Draw(Color);
end;
end;
destructor TCloth.Destroy;
begin
Points.Free;
inherited;
end;
constructor TWorld.CreateWithDefaults(aWidth,aHeight:Integer);
begin
Create;
InitWithDefaults;
self.Buffer.SetSize(aWidth,aHeight);
end;
{ TWorld }
procedure TWorld.ClearCanvas;
begin
Buffer.Canvas.Brush.Color := $888888;
Buffer.Canvas.FillRect(Rect(0, 0, Buffer.Width, Buffer.Height));
end;
constructor TWorld.Create;
begin
inherited;
Buffer := TBitmap.Create;
end;
constructor TWorld.CreateWithZeroG(aWidth,aHeight:Integer);
begin
CreateWithDefaults(aWidth,aHeight);
Gravity := 0;
end;
destructor TWorld.Destroy;
begin
Buffer.Free;
inherited;
end;
procedure TWorld.InitWithDefaults;
begin
Accuracy := 5;
Gravity := 400;
Spacing := 8;
TearDist := 60;
Friction := 0.99;
Bounce := 0.5;
Mouse.Cut := 4;
Mouse.Influence := 36;
Mouse.IsDown := false;
Mouse.Button := TMouseButton.mbLeft;
Mouse.Pos := TPoint.Zero;
Mouse.PrevPos:= TPoint.Zero;
end;
{ TClothPoint.TPointFHelper }
function TClothPoint.TPointFHelper.SquareDistance(const P2: TPointF): Double;
begin
Result := Sqr(Self.X - P2.X) + Sqr(Self.Y - P2.Y);
end;
function TClothPoint.TPointFHelper.SquareDistance(const P2: TPoint): Double;
begin
Result := SquareDistance(PointF(P2.x, P2.y));
end;
{$ifdef FPC}
class function TClothPoint.TPointFHelper.Zero: TPointF;
begin
Result.x := 0;
Result.y := 0;
end;
class function TClothPoint.TPointFHelper.Create(x, y: Single): TPointF;
begin
Result.x := x;
Result.y := y;
end;
{$endif FPC}
end.
|
unit FornecedorOperacaoDuplicar.Controller;
interface
uses Fornecedor.Controller.Interf, Fornecedor.Model.Interf, TPAGFORNECEDOR.Entidade.Model;
type
TFornecedorOperacaoDuplicarController = class(TInterfacedObject,
IFornecedorOperacaoDuplicarController)
private
FFornecedorModel: IFornecedorModel;
FNomeFantasia: string;
FCNPJ: string;
FIE: string;
FTelefone: string;
FEmail: string;
public
constructor Create;
destructor Destroy; override;
class function New: IFornecedorOperacaoDuplicarController;
function fornecedorModel(AValue: IFornecedorModel)
: IFornecedorOperacaoDuplicarController;
function nomeFantasia(AValue: string): IFornecedorOperacaoDuplicarController;
function cnpj(AValue: string): IFornecedorOperacaoDuplicarController;
function ie(AValue: string): IFornecedorOperacaoDuplicarController;
function telefone(AValue: string): IFornecedorOperacaoDuplicarController;
function email(AValue: string): IFornecedorOperacaoDuplicarController;
procedure finalizar;
end;
implementation
{ TFornecedorOperacaoDuplicarController }
function TFornecedorOperacaoDuplicarController.cnpj(
AValue: string): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FCNPJ := AValue;
end;
constructor TFornecedorOperacaoDuplicarController.Create;
begin
end;
destructor TFornecedorOperacaoDuplicarController.Destroy;
begin
inherited;
end;
function TFornecedorOperacaoDuplicarController.email(
AValue: string): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FEmail := AValue;
end;
procedure TFornecedorOperacaoDuplicarController.finalizar;
begin
FFornecedorModel.Entidade(TTPAGFORNECEDOR.Create);
FFornecedorModel.Entidade.NOMEFANTASIA := FNomeFantasia;
FFornecedorModel.Entidade.CNPJ := FCNPJ;
FFornecedorModel.Entidade.IE := FIE;
FFornecedorModel.Entidade.TELEFONE := FTelefone;
FFornecedorModel.Entidade.EMAIL := FEmail;
FFornecedorModel.DAO.Insert(FFornecedorModel.Entidade);
end;
function TFornecedorOperacaoDuplicarController.fornecedorModel
(AValue: IFornecedorModel): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FFornecedorModel := AValue;
end;
function TFornecedorOperacaoDuplicarController.ie(
AValue: string): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FIE := AValue;
end;
class function TFornecedorOperacaoDuplicarController.New
: IFornecedorOperacaoDuplicarController;
begin
Result := Self.Create;
end;
function TFornecedorOperacaoDuplicarController.nomeFantasia(
AValue: string): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FNomeFantasia := AValue;
end;
function TFornecedorOperacaoDuplicarController.telefone(
AValue: string): IFornecedorOperacaoDuplicarController;
begin
Result := Self;
FTelefone := AValue;
end;
end.
|
program dynamicArrFill1;
type
MyArrType = array[1..20] of integer;
var
arr1:array of integer;
arr2:MyArrType;
{----------------------------------------}
procedure fillArrValue(arr:array of integer);
var
i:integer;
begin
for i:=low(arr) to high(arr) do
begin
arr[i] := i;
end;
end;
{----------------------------------------}
procedure fillArr(var arr:array of integer);
var
i:integer;
begin
for i:=low(arr) to high(arr) do
begin
arr[i] := i;
end;
end;
{----------------------------------------}
procedure showArr(var arr:array of integer);
var
i:integer;
begin
writeln('length(arr):', length(arr), '; low(arr):', low(arr), '; high(arr):', high(arr));
for i:=0 to length(arr) - 1 do
begin
write(arr[i], ' ');
end;
writeln;
end;
{----------------------------------------}
procedure showStaticArr(var arr:MyArrType);
var
i:integer;
begin
writeln('length(arr):', length(arr), '; low(arr):', low(arr), '; high(arr):', high(arr));
for i:=low(arr) to high(arr) do
begin
write(arr[i], ' ');
end;
writeln;
end;
{----------------------------------------}
begin
setLength(arr1, 17);
showArr(arr1);
writeln('-------------------');
writeln('fillArrValue:');
fillArrValue(arr1);
showArr(arr1);
writeln('-------------------');
fillArr(arr1);
showArr(arr1);
writeln('-------------------');
setLength(arr1, 20);
showArr(arr1);
writeln('-------------------');
setLength(arr1, 10);
showArr(arr1);
writeln('-------------------');
writeln('length(arr2):', length(arr2), '; low(arr2):', low(arr2), '; high(arr2):', high(arr2));
fillArr(arr2);
showArr(arr2);
writeln('-------------------');
showStaticArr(arr2);
writeln('-------------------');
end.
|
unit uInternetProxy;
interface
uses
Winapi.Windows,
System.SysUtils,
System.SyncObjs,
Generics.Collections,
idHTTP,
uMemory,
uSettings;
type
HINTERNET = Pointer;
INTERNET_PORT = Word;
PWinHTTPProxyInfo = ^TWinHTTPProxyInfo;
WINHTTP_PROXY_INFO = record
dwAccessType: DWORD;
lpszProxy: LPWSTR;
lpszProxyBypass: LPWSTR;
end;
TWinHTTPProxyInfo = WINHTTP_PROXY_INFO;
LPWINHTTP_PROXY_INFO = PWinHTTPProxyInfo;
PWinHTTPAutoProxyOptions = ^TWinHTTPAutoProxyOptions;
WINHTTP_AUTOPROXY_OPTIONS = record
dwFlags: DWORD;
dwAutoDetectFlags: DWORD;
lpszAutoConfigUrl: LPCWSTR;
lpvReserved: Pointer;
dwReserved: DWORD;
fAutoLogonIfChallenged: BOOL;
end;
TWinHTTPAutoProxyOptions = WINHTTP_AUTOPROXY_OPTIONS;
LPWINHTTP_AUTOPROXY_OPTIONS = PWinHTTPAutoProxyOptions;
PWinHTTPCurrentUserIEProxyConfig = ^TWinHTTPCurrentUserIEProxyConfig;
WINHTTP_CURRENT_USER_IE_PROXY_CONFIG = record
fAutoDetect: BOOL;
lpszAutoConfigUrl: LPWSTR;
lpszProxy: LPWSTR;
lpszProxyBypass: LPWSTR;
end;
TWinHTTPCurrentUserIEProxyConfig = WINHTTP_CURRENT_USER_IE_PROXY_CONFIG;
LPWINHTTP_CURRENT_USER_IE_PROXY_CONFIG = PWinHTTPCurrentUserIEProxyConfig;
function WinHttpOpen(pwszUserAgent: LPCWSTR; dwAccessType: DWORD;
pwszProxyName, pwszProxyBypass: LPCWSTR; dwFlags: DWORD): HINTERNET; stdcall;
external 'winhttp.dll' name 'WinHttpOpen' delayed;
function WinHttpConnect(hSession: HINTERNET; pswzServerName: LPCWSTR;
nServerPort: INTERNET_PORT; dwReserved: DWORD): HINTERNET; stdcall;
external 'winhttp.dll' name 'WinHttpConnect' delayed;
function WinHttpOpenRequest(hConnect: HINTERNET; pwszVerb: LPCWSTR;
pwszObjectName: LPCWSTR; pwszVersion: LPCWSTR; pwszReferer: LPCWSTR;
ppwszAcceptTypes: PLPWSTR; dwFlags: DWORD): HINTERNET; stdcall;
external 'winhttp.dll' name 'WinHttpOpenRequest' delayed;
function WinHttpQueryOption(hInet: HINTERNET; dwOption: DWORD;
lpBuffer: Pointer; var lpdwBufferLength: DWORD): BOOL; stdcall;
external 'winhttp.dll' name 'WinHttpQueryOption' delayed;
function WinHttpGetProxyForUrl(hSession: HINTERNET; lpcwszUrl: LPCWSTR;
pAutoProxyOptions: LPWINHTTP_AUTOPROXY_OPTIONS;
var pProxyInfo: WINHTTP_PROXY_INFO): BOOL; stdcall;
external 'winhttp.dll' name 'WinHttpGetProxyForUrl' delayed;
function WinHttpGetIEProxyConfigForCurrentUser(
var pProxyInfo: WINHTTP_CURRENT_USER_IE_PROXY_CONFIG): BOOL; stdcall;
external 'winhttp.dll' name 'WinHttpGetIEProxyConfigForCurrentUser' delayed;
function WinHttpCloseHandle(hInternet: HINTERNET): BOOL; stdcall;
external 'winhttp.dll' name 'WinHttpCloseHandle' delayed;
type
TProxyInfo = record
ProxyURL: WideString;
ProxyBypass: WideString;
ProxyAutoDetected: Boolean;
end;
const
WINHTTP_NO_REFERER = nil;
{$EXTERNALSYM WINHTTP_NO_REFERER}
WINHTTP_NO_PROXY_NAME = nil;
{$EXTERNALSYM WINHTTP_NO_PROXY_NAME}
WINHTTP_NO_PROXY_BYPASS = nil;
{$EXTERNALSYM WINHTTP_NO_PROXY_BYPASS}
WINHTTP_DEFAULT_ACCEPT_TYPES = nil;
{$EXTERNALSYM WINHTTP_DEFAULT_ACCEPT_TYPES}
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0;
{$EXTERNALSYM WINHTTP_ACCESS_TYPE_DEFAULT_PROXY}
WINHTTP_ACCESS_TYPE_NO_PROXY = 1;
{$EXTERNALSYM WINHTTP_ACCESS_TYPE_NO_PROXY}
WINHTTP_OPTION_PROXY = 38;
{$EXTERNALSYM WINHTTP_OPTION_PROXY}
WINHTTP_OPTION_PROXY_USERNAME = $1002;
{$EXTERNALSYM WINHTTP_OPTION_PROXY_USERNAME}
WINHTTP_OPTION_PROXY_PASSWORD = $1003;
{$EXTERNALSYM WINHTTP_OPTION_PROXY_PASSWORD}
WINHTTP_AUTOPROXY_AUTO_DETECT = $00000001;
{$EXTERNALSYM WINHTTP_AUTOPROXY_AUTO_DETECT}
WINHTTP_AUTOPROXY_CONFIG_URL = $00000002;
{$EXTERNALSYM WINHTTP_AUTOPROXY_CONFIG_URL}
WINHTTP_AUTO_DETECT_TYPE_DHCP = $00000001;
{$EXTERNALSYM WINHTTP_AUTO_DETECT_TYPE_DHCP}
WINHTTP_AUTO_DETECT_TYPE_DNS_A = $00000002;
{$EXTERNALSYM WINHTTP_AUTO_DETECT_TYPE_DNS_A}
WINHTTP_FLAG_BYPASS_PROXY_CACHE = $00000100;
{$EXTERNALSYM WINHTTP_FLAG_BYPASS_PROXY_CACHE}
WINHTTP_FLAG_REFRESH = WINHTTP_FLAG_BYPASS_PROXY_CACHE;
{$EXTERNALSYM WINHTTP_FLAG_REFRESH}
procedure ConfigureIdHttpProxy(HTTP: TIdHTTP; RequestUrl: string);
function IsProxyServerUsed(RequestUrl: string): Boolean;
procedure ClearProxyCache;
implementation
var
FSync: TCriticalSection = nil;
FProxyList: TDictionary<string, TProxyInfo> = nil;
procedure InitProxyCache;
begin
if FSync = nil then
FSync := TCriticalSection.Create;
if FProxyList = nil then
FProxyList := TDictionary<string, TProxyInfo>.Create;
end;
procedure ClearProxyCache;
begin
InitProxyCache;
FProxyList.Clear;
end;
function GetProxyInfo(const AURL: WideString; var AProxyInfo: TProxyInfo): DWORD;
var
Session: HINTERNET;
AutoDetectProxy: Boolean;
WinHttpProxyInfo: TWinHTTPProxyInfo;
AutoProxyOptions: TWinHTTPAutoProxyOptions;
IEProxyConfig: TWinHTTPCurrentUserIEProxyConfig;
begin
// initialize the result
Result := 0;
if not AppSettings.ReadBool('Options', 'UseProxyServer', False) then
Exit;
// initialize auto-detection to off
AutoDetectProxy := False;
// initialize the result structure
AProxyInfo.ProxyURL := '';
AProxyInfo.ProxyBypass := '';
AProxyInfo.ProxyAutoDetected := False;
// initialize the auto-proxy options
FillChar(AutoProxyOptions, SizeOf(AutoProxyOptions), 0);
// check if the Internet Explorer's proxy configuration is
// available and if so, check its settings for auto-detect
// proxy settings and auto-config script URL options
if WinHttpGetIEProxyConfigForCurrentUser(IEProxyConfig) then
begin
// if the Internet Explorer is configured to auto-detect
// proxy settings then we try to detect them later on
if IEProxyConfig.fAutoDetect then
begin
AutoProxyOptions.dwFlags := WINHTTP_AUTOPROXY_AUTO_DETECT;
AutoProxyOptions.dwAutoDetectFlags := WINHTTP_AUTO_DETECT_TYPE_DHCP or
WINHTTP_AUTO_DETECT_TYPE_DNS_A;
AutoDetectProxy := True;
end;
// if the Internet Explorer is configured to use the proxy
// auto-config script then we try to use it
if IEProxyConfig.lpszAutoConfigURL <> '' then
begin
AutoProxyOptions.dwFlags := AutoProxyOptions.dwFlags or
WINHTTP_AUTOPROXY_CONFIG_URL;
AutoProxyOptions.lpszAutoConfigUrl := IEProxyConfig.lpszAutoConfigUrl;
AutoDetectProxy := True;
end;
// if IE don't have auto-detect or auto-config set, we are
// done here and we can fill the AProxyInfo with the IE settings
if not AutoDetectProxy then
begin
AProxyInfo.ProxyURL := IEProxyConfig.lpszProxy;
AProxyInfo.ProxyBypass := IEProxyConfig.lpszProxyBypass;
AProxyInfo.ProxyAutoDetected := False;
end;
end else
begin
// if the Internet Explorer's proxy configuration is not
// available, then try to auto-detect it
AutoProxyOptions.dwFlags := WINHTTP_AUTOPROXY_AUTO_DETECT;
AutoProxyOptions.dwAutoDetectFlags := WINHTTP_AUTO_DETECT_TYPE_DHCP or
WINHTTP_AUTO_DETECT_TYPE_DNS_A;
AutoDetectProxy := True;
end;
// if the IE proxy settings are not available or IE has
// configured auto-config script or auto-detect proxy settings
if AutoDetectProxy then
begin
// create a temporary WinHttp session to allow the WinHTTP
// auto-detect proxy settings if possible
Session := WinHttpOpen(nil, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
// if the WinHttp session has been created then try to
// get the proxy data for the specified URL else we assign
// the last error code to the function result
if Assigned(Session) then
try
// get the proxy data for the specified URL with the
// auto-proxy options specified, if succeed then we can
// fill the AProxyInfo with the retrieved settings else
// we assign the last error code to the function result
if WinHttpGetProxyForUrl(Session, LPCWSTR(AURL),
@AutoProxyOptions, WinHttpProxyInfo) then
begin
AProxyInfo.ProxyURL := WinHttpProxyInfo.lpszProxy;
AProxyInfo.ProxyBypass := WinHttpProxyInfo.lpszProxyBypass;
AProxyInfo.ProxyAutoDetected := True;
end
else
Result := GetLastError;
finally
WinHttpCloseHandle(Session);
end
else
Result := GetLastError;
end;
end;
function GetHostName(url: string): string;
var
P: Integer;
begin
P := LastDelimiter(':', url);
if P <= 1 then
Exit(url);
Result := Copy(url, 1, P - 1);
end;
function GetHostPort(url: string): Integer;
var
P: Integer;
Port: string;
begin
P := LastDelimiter(':', url);
if (P <= 1) and (P < Length(url)) then
Exit(80);
Port := Copy(url, P + 1, Length(url) - P);
Result := StrToIntDef(Port, 80);
end;
function IsProxyServerUsed(RequestUrl: string): Boolean;
var
Res: DWORD;
ProxyInfo: TProxyInfo;
begin
Result := False;
FSync.Enter;
try
if FProxyList.ContainsKey(RequestUrl) then
begin
ProxyInfo := FProxyList[RequestUrl];
if ProxyInfo.ProxyURL <> '' then
Result := GetHostName(ProxyInfo.ProxyURL) <> '';
Exit;
end;
Res := GetProxyInfo(RequestUrl, ProxyInfo);
case Res of
0:
Result := GetHostName(ProxyInfo.ProxyURL) <> '';
end;
FProxyList.Add(RequestUrl, ProxyInfo);
finally
FSync.Leave;
end;
end;
procedure ConfigureIdHttpProxy(HTTP: TIdHTTP; RequestUrl: string);
var
Result: DWORD;
ProxyInfo: TProxyInfo;
begin
InitProxyCache;
FSync.Enter;
try
if FProxyList.ContainsKey(RequestUrl) then
begin
ProxyInfo := FProxyList[RequestUrl];
if ProxyInfo.ProxyURL <> '' then
begin
HTTP.ProxyParams.ProxyServer := GetHostName(ProxyInfo.ProxyURL);
HTTP.ProxyParams.ProxyPort := GetHostPort(ProxyInfo.ProxyURL);
HTTP.ProxyParams.ProxyUsername := AppSettings.ReadString('Options', 'ProxyUser');
HTTP.ProxyParams.ProxyPassword := AppSettings.ReadString('Options', 'ProxyPassword');
end;
Exit;
end;
Result := GetProxyInfo(RequestUrl, ProxyInfo);
case Result of
0:
begin
HTTP.ProxyParams.ProxyServer := GetHostName(ProxyInfo.ProxyURL);
HTTP.ProxyParams.ProxyPort := GetHostPort(ProxyInfo.ProxyURL);
HTTP.ProxyParams.ProxyUsername := AppSettings.ReadString('Options', 'ProxyUser');
HTTP.ProxyParams.ProxyPassword := AppSettings.ReadString('Options', 'ProxyPassword');
end;
//12166, //ShowMessage('Error in proxy auto-config script code');
//12167, //ShowMessage('Unable to download proxy auto-config script');
//12180: //ShowMessage('WPAD detection failed');
else
end;
FProxyList.Add(RequestUrl, ProxyInfo);
finally
FSync.Leave;
end;
end;
initialization
finalization
F(FSync);
F(FProxyList);
end.
|
unit uAddPlace;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, {uCharControl, uFControl, uLabeledFControl, uSpravControl,}
StdCtrls, Buttons,{ uFormControl,} uAdr_DataModule,{ uAddModifForm,}
cxLookAndFeelPainters, FIBQuery, pFIBQuery, pFIBStoredProc, DB,
FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ActnList, cxButtons,
cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, AdrSp_MainForm, AdrSp_Types,
IBase, cxMaskEdit, cxButtonEdit, cxCheckBox, Address_ZMessages;
type
TAdd_Place_Form = class(TAdrEditForm)
NameTE: TcxTextEdit;
NameLbl: TcxLabel;
AcceptBtn: TcxButton;
CancelBtn: TcxButton;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
TypeBE: TcxButtonEdit;
RegionBE: TcxButtonEdit;
EqualCB: TcxCheckBox;
Zip1: TcxMaskEdit;
Zip2: TcxMaskEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
ActionList: TActionList;
AcceptAction: TAction;
CancelAction: TAction;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
StProc: TpFIBStoredProc;
cxLabel5: TcxLabel;
DistrictBE: TcxButtonEdit;
procedure TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RegionBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelActionExecute(Sender: TObject);
procedure AcceptActionExecute(Sender: TObject);
procedure EqualCBPropertiesChange(Sender: TObject);
procedure Zip1PropertiesEditValueChanged(Sender: TObject);
procedure Zip2PropertiesEditValueChanged(Sender: TObject);
procedure DistrictBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RegionBEPropertiesChange(Sender: TObject);
private
pIdPlace:Integer;
procedure UpdateZip2;
function CheckData:Boolean;
public
// DBHandle: integer;
// Mode:TFormMode;
pIdRegion:Integer;
pIdDistrict:Integer;
pIdType:Integer;
constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdPlace:Integer=-1);reintroduce;
end;
implementation
{$R *.dfm}
uses RxMemDS;
constructor TAdd_Place_Form.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdPlace:Integer=-1);
begin
inherited Create(AOwner);
//******************************************************************************
DB.Handle:=ADB_HANDLE;
StartId:=AIdPlace;
end;
procedure TAdd_Place_Form.TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник типів населених пунктів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='ini_type_place';
Params.Fields:='Name_full,id_type_place';
Params.FieldsName:='Назва';
Params.KeyField:='id_type_place';
Params.ReturnFields:='Name_full,id_type_place';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdType:=output['id_type_place'];
TypeBE.Text:=VarToStr(output['Name_full']);
end;
end;
procedure TAdd_Place_Form.RegionBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник регіонів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='adr_region_SELECT_SP(NULL)';
Params.Fields:='Name_region,NAME_TYPE,NAME_COUNTRY,ZIP,id_region';
Params.FieldsName:='Назва, Тип регіона, Країна, Індекси';
Params.KeyField:='id_region';
Params.ReturnFields:='Name_region,id_region';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdRegion:=output['id_region'];
RegionBE.Text:=VarToStr(output['Name_region']);
end;
end;
procedure TAdd_Place_Form.FormShow(Sender: TObject);
begin
ReadTransaction.Active:=True;
pIdPlace:=StartId;
pIdDistrict:=-1;
if pIdPlace>-1 then
begin
// изменение
Caption:='Змінити населенний пункт';
if DSet.Active then DSet.Close;
DSet.SQLs.SelectSQL.Text:='SELECT * FROM ADR_PLACE_S('+IntToStr(pIdPlace)+')';
DSet.Open;
NameTE.Text:=DSet['NAME_PLACE'];
pIdRegion:=DSet['ID_REGION'];
pIdType:=DSet['ID_PLACE_TYPE'];
if not(VarIsNull(DSet['ID_DISTRICT'])) then
pIdDistrict:=DSet['ID_DISTRICT'];
RegionBE.Text:=DSet['NAME_REGION'];
TypeBE.Text:=DSet['TYPE_NAME'];
DistrictBE.Text:=VarToStr(DSet['NAME_DISTRICT']);
Zip1.Text:=VarToStr(DSet['ZIP_BEG']);
Zip2.Text:=VarToStr(DSet['ZIP_END']);
end
else
begin
Caption:='Додати населенний пункт';
if (VarIsArray(Additional)) and (not (VarIsNull(Additional))) then
begin
pIdRegion:=Additional[0];
RegionBE.Text:=VarToStr(Additional[1]);
if not VarIsNull(Additional[2]) then
pIdDistrict:=Additional[2];
DistrictBE.Text:=VarToStr(Additional[3]);
end;
end;
end;
procedure TAdd_Place_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ReadTransaction.Active:=False;
end;
procedure TAdd_Place_Form.CancelActionExecute(Sender: TObject);
begin
// Ничего не меняли, а, следовательно, обновлять ничего не надо
ResultId:=-1;
ModalResult:=mrCancel;
end;
function TAdd_Place_Form.CheckData:Boolean;
begin
Result:=True;
if NameTE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть назву населенного пункта',mtError,[mbOK]);
NameTE.SetFocus;
Result:=False;
Exit;
end;
if TypeBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть тип населенного пункта',mtError,[mbOK]);
TypeBE.SetFocus;
Result:=False;
Exit;
end;
if RegionBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть регіон',mtError,[mbOK]);
RegionBE.SetFocus;
Result:=False;
Exit;
end;
if ((Zip1.Text='') or (Zip2.Text='')) and
not((Zip1.Text='') and (Zip2.Text='')) then
begin
ZShowMessage('Помилка!','Вкажіть діапазон повністю',mtError,[mbOK]);
if (Zip1.Text='') then
Zip1.SetFocus
else
Zip2.SetFocus;
Result:=False;
Exit;
end;
if not((Zip1.Text='') and (Zip2.Text='')) and
(Zip1.EditValue>Zip2.EditValue) then
begin
ZShowMessage('Помилка!','Кінець діапазону має бути більшим за початок',mtError,[mbOK]);
Result:=False;
Zip1.SetFocus;
Exit;
end;
end;
procedure TAdd_Place_Form.AcceptActionExecute(Sender: TObject);
begin
if not(CheckData) then Exit;
try
StProc.StoredProcName:='ADR_PLACE_IU';
WriteTransaction.StartTransaction;
StProc.Prepare;
if pIdPlace>-1 then
StProc.ParamByName('ID_P').AsInteger:=pIdPlace;
StProc.ParamByName('NAME_PLACE').AsString:=NameTE.Text;
StProc.ParamByName('ID_REGION').AsInteger:=pIdRegion;
StProc.ParamByName('ID_PLACE_TYPE').AsInteger:=pIdType;
if DistrictBE.Text<>'' then
StProc.ParamByName('ID_DISTRICT').AsInteger:=pIdDistrict;
StProc.ExecProc;
pIdPlace:=StProc.FN('ID_PLACE').AsInteger;
// WriteTransaction.Commit;
if not((Zip1.Text='')) and not((Zip2.Text='')) then
begin
StProc.StoredProcName:='ADR_ZIP_PLACE_IU';
// WriteTransaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('ID_PLACE').AsInteger:=pIdPlace;
StProc.ParamByName('ZIP_BEG').AsInteger:=Zip1.EditValue;
StProc.ParamByName('ZIP_END').AsInteger:=Zip2.EditValue;
StProc.ExecProc;
end;
WriteTransaction.Commit;
ResultId:=pIdPlace;
ModalResult:=mrOk;
except
on E:Exception do
begin
WriteTransaction.Rollback;
ZShowMessage('Помилка',E.Message,mtError,[mbOk]);
end;
end;
end;
procedure TAdd_Place_Form.UpdateZip2;
//var c:Variant;
begin
if EqualCB.Checked then
Zip2.EditValue:=Zip1.EditValue
{ else
if (Zip1.EditValue>Zip2.EditValue) and not((Zip2.Text='')) then
begin
c:=Zip1.EditValue;
Zip1.EditValue:=Zip2.EditValue;
Zip2.EditValue:=c;
end;}
end;
procedure TAdd_Place_Form.EqualCBPropertiesChange(Sender: TObject);
begin
Zip2.Enabled:=not(EqualCB.Checked);
UpdateZip2;
end;
procedure TAdd_Place_Form.Zip1PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
procedure TAdd_Place_Form.Zip2PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
procedure TAdd_Place_Form.DistrictBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut : TRxMemoryData;
begin
if RegionBE.Text='' then
begin
ZShowMessage('Помилка','Спочатку оберіть регіон!',mtError,[mbOK]);
Exit;
end;
Params.FormCaption:='Довідник районів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_District_Form';
Params.ModifFormClass:='TAdd_District_Form';
Params.TableName:='adr_district_select_SP('+IntToStr(pIdRegion)+');';
Params.Fields:='Name_district,NAME_TYPE,NAME_REGION,NAME_COUNTRY,ZIP,id_district';
Params.FieldsName:='Район, Тип района, Регіон, Країна, Індекси';
Params.KeyField:='id_district';
Params.ReturnFields:='Name_district,id_district';
Params.DeleteSQL:='execute procedure adr_district_d(:id_district);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut)
then
begin
if not VarIsNull(output['id_district']) then
pIdDistrict:=output['id_district'];
DistrictBE.Text:=VarToStr(output['Name_district']);
end;
end;
procedure TAdd_Place_Form.RegionBEPropertiesChange(Sender: TObject);
begin
DistrictBE.EditValue:=Null;
end;
initialization
RegisterClass(TAdd_Place_Form);
end.
|
unit Grijjy.Http2;
{ Provides a generic HTTP2 client class based upon the ngHttp2 library }
interface
{$I Grijjy.inc}
uses
Classes,
SysUtils,
StrUtils,
SyncObjs,
IOUtils,
DateUtils,
Grijjy.Uri,
Grijjy.SocketPool.Win,
Nghttp2,
Grijjy.BinaryCoding;
const
{ Timeout for operations }
TIMEOUT_CONNECT = 5000;
TIMEOUT_SEND = 5000;
DEFAULT_TIMEOUT_RECV = 5000;
{ Ports }
DEFAULT_HTTP_PORT = 80;
DEFAULT_HTTPS_PORT = 443;
type
{ HTTP events }
TOnRedirect = procedure(Sender: TObject; var ALocation: UnicodeString; const AFollow: Boolean) of object;
TOnPassword = procedure(Sender: TObject; var AAgain: Boolean) of object;
{ Socket activity state }
TSocketState = (None, Sending, Receiving, Success, Failure);
type
{ Http header }
THTTPHeader = record
Name: AnsiString;
Value: AnsiString;
end;
{ Http headers class }
THTTPHeaders = class(TObject)
private
FHeaders: TArray<THTTPHeader>;
public
constructor Create;
destructor Destroy; override;
public
{ Add a header and value to a list of headers }
procedure Add(const AName, AValue: UnicodeString);
{ Gets the value associated with the header }
function Value(const AName: UnicodeString): UnicodeString;
{ Writes out the headers as ngHttp2 compatible headers }
procedure ToNgHttp2Headers(var AHeaders: TArray<nghttp2_nv>);
public
property Headers: TArray<THTTPHeader> read FHeaders write FHeaders;
end;
type
{ HTTP client }
TgoHTTP2Client = class(TObject)
private
FConnection: TgoSocketConnection;
FConnectionLock: TCriticalSection;
FCertificate: TBytes;
FPrivateKey: TBytes;
{ Recv }
FRecvBuffer: TBytes;
FRecvIndex: Integer;
FLastRecv: TDateTime;
{ Send }
FSendBuffer: TBytes;
FSendIndex: Integer;
FLastSent: TDateTime;
{ Http request }
FURL: UnicodeString;
FMethod: UnicodeString;
FURI: TgoURI;
FLastURI: TgoURI;
FFollowRedirects: Boolean;
FAuthorization: UnicodeString;
FUserName: UnicodeString;
FPassword: UnicodeString;
FConnected: TEvent;
FInternalHeaders: THTTPHeaders;
FRequestHeaders: THTTPHeaders;
FRequestBody: UnicodeString;
FRequestData: TBytes;
FRequestSent: TSocketState;
{ Http response }
FResponseHeaders: THTTPHeaders;
FResponseData: TBytes;
FResponseStatusCode: Integer;
FResponseRecv: TSocketState;
{ ngHttp2 }
FCallbacks_http2: nghttp2_session_callbacks;
FSession_http2: nghttp2_session;
protected
FOnPassword: TOnPassword;
FOnRedirect: TOnRedirect;
private
{ ngHttp2 callbacks }
function nghttp2_data_source_read_callback(session: nghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
function nghttp2_on_data_chunk_recv_callback(session: nghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_frame_recv_callback(session: nghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
function nghttp2_on_header_callback(session: nghttp2_session;
const frame: pnghttp2_frame; const name: puint8; namelen: size_t;
const value: puint8; valuelen: size_t; flags: uint8;
user_data: Pointer): Integer; cdecl;
function nghttp2_on_stream_close_callback(session: nghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
private
procedure Reset;
function _Send: Boolean;
function _Recv: Boolean;
procedure CreateRequest;
function Connect: Boolean;
procedure SendRequest;
function WaitForSendSuccess: Boolean;
function WaitForRecvSuccess(const ARecvTimeout: Integer): Boolean;
function DoResponse(var AAgain: Boolean): UnicodeString;
function DoRequest(const AMethod, AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
protected
{ Socket routines }
procedure OnSocketConnected;
procedure OnSocketDisconnected;
procedure OnSocketSent(const ABuffer: Pointer; const ASize: Integer);
procedure OnSocketRecv(const ABuffer: Pointer; const ASize: Integer);
public
constructor Create;
destructor Destroy; override;
public
{ Get method }
function Get(const AURL: UnicodeString;
const ARecvTimeout: Integer = DEFAULT_TIMEOUT_RECV): UnicodeString;
{ Post method }
function Post(const AURL: UnicodeString;
const ARecvTimeout: Integer = DEFAULT_TIMEOUT_RECV): UnicodeString;
{ Put method }
function Put(const AURL: UnicodeString;
const ARecvTimeout: Integer = DEFAULT_TIMEOUT_RECV): UnicodeString;
{ Delete method }
function Delete(const AURL: UnicodeString;
const ARecvTimeout: Integer = DEFAULT_TIMEOUT_RECV): UnicodeString;
{ Options method }
function Options(const AURL: UnicodeString;
const ARecvTimeout: Integer = DEFAULT_TIMEOUT_RECV): UnicodeString;
{ Optional body for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestBody: UnicodeString read FRequestBody write FRequestBody;
{ Optional binary body data for a request.
You can either use RequestBody or RequestData. If both are specified then
only RequestBody is used. }
property RequestData: TBytes read FRequestData write FRequestData;
{ Request headers }
property RequestHeaders: THTTPHeaders read FRequestHeaders;
{ Response headers from the server }
property ResponseHeaders: THTTPHeaders read FResponseHeaders;
{ Response status code }
property ResponseStatusCode: Integer read FResponseStatusCode;
{ Allow 301 and other redirects }
property FollowRedirects: Boolean read FFollowRedirects write FFollowRedirects;
{ Called when a redirect is requested }
property OnRedirect: TOnRedirect read FOnRedirect write FOnRedirect;
{ Called when a password is needed }
property OnPassword: TOnPassword read FOnPassword write FOnPassword;
{ Username and password for Basic Authentication }
property UserName: UnicodeString read FUserName write FUserName;
property Password: UnicodeString read FPassword write FPassword;
{ Certificate in PEM format }
property Certificate: TBytes read FCertificate write FCertificate;
{ Private key in PEM format }
property PrivateKey: TBytes read FPrivateKey write FPrivateKey;
{ Authorization }
property Authorization: UnicodeString read FAuthorization write FAuthorization;
end;
implementation
uses
Grijjy.SysUtils;
var
_HTTPClientSocketManager: TgoClientSocketManager;
{ Helpers }
function AsString(const AString: Pointer; const ALength: Integer): String;
var
S: AnsiString;
begin
SetLength(S, ALength);
Move(AString^, S[1], ALength);
Result := String(S);
end;
{ ngHttp2 callback cdecl }
function data_source_read_callback(session: nghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t; cdecl;
var
Http: TgoHTTP2Client;
begin
Assert(Assigned(user_data));
Http := TgoHTTP2Client(user_data);
Result := Http.nghttp2_data_source_read_callback(session, stream_id, buf, len, data_flags, source, user_data);
end;
function on_header_callback(session: nghttp2_session; const frame: pnghttp2_frame;
const name: puint8; namelen: size_t; const value: puint8; valuelen: size_t;
flags: uint8; user_data: Pointer): Integer; cdecl;
var
Http: TgoHTTP2Client;
begin
Assert(Assigned(user_data));
Http := TgoHTTP2Client(user_data);
Result := Http.nghttp2_on_header_callback(session, frame, name, namelen, value, valuelen, flags, user_data);
end;
function on_frame_recv_callback(session: nghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer; cdecl;
var
Http: TgoHTTP2Client;
begin
Assert(Assigned(user_data));
Http := TgoHTTP2Client(user_data);
Result := Http.nghttp2_on_frame_recv_callback(session, frame, user_data);
end;
function on_data_chunk_recv_callback(session: nghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer; cdecl;
var
Http: TgoHTTP2Client;
begin
Assert(Assigned(user_data));
Http := TgoHTTP2Client(user_data);
Result := Http.nghttp2_on_data_chunk_recv_callback(session, flags, stream_id, data, len, user_data);
end;
function on_stream_close_callback(session: nghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer; cdecl;
var
Http: TgoHTTP2Client;
begin
Assert(Assigned(user_data));
Http := TgoHTTP2Client(user_data);
Result := Http.nghttp2_on_stream_close_callback(session, stream_id, error_code, user_data);
end;
{ THTTPHeaders }
constructor THTTPHeaders.Create;
begin
end;
destructor THTTPHeaders.Destroy;
begin
FHeaders := nil;
inherited;
end;
procedure THTTPHeaders.Add(const AName, AValue: UnicodeString);
var
Header: THTTPHeader;
begin
Header.Name := AnsiString(AName);
Header.Value := AnsiString(AValue);
FHeaders := FHeaders + [Header];
end;
function THTTPHeaders.Value(const AName: UnicodeString): UnicodeString;
var
Header: THTTPHeader;
begin
Result := '';
for Header in FHeaders do
if Header.Name = AnsiString(AName) then
begin
Result := String(Header.Value);
Break;
end;
end;
procedure THTTPHeaders.ToNgHttp2Headers(var AHeaders: TArray<nghttp2_nv>);
var
Header: THTTPHeader;
NgHttp2Header: nghttp2_nv;
begin
for Header in FHeaders do
begin
NgHttp2Header.name := PAnsiChar(Header.Name);
NgHttp2Header.value := PAnsiChar(Header.Value);
NgHttp2Header.namelen := Length(Header.Name);
NgHttp2Header.valuelen := Length(Header.Value);
NgHttp2Header.flags := NGHTTP2_NV_FLAG_NONE;
AHeaders := AHeaders + [NgHttp2Header];
end;
end;
{ TgoHTTP2Client }
constructor TgoHTTP2Client.Create;
var
Settings: nghttp2_settings_entry;
Error: Integer;
begin
inherited Create;
{ initialize nghttp2 library }
if nghttp2_session_callbacks_new(FCallbacks_http2) = 0 then
begin
nghttp2_session_callbacks_set_on_header_callback(FCallbacks_http2, on_header_callback);
nghttp2_session_callbacks_set_on_frame_recv_callback(FCallbacks_http2, on_frame_recv_callback);
nghttp2_session_callbacks_set_on_data_chunk_recv_callback(FCallbacks_http2, on_data_chunk_recv_callback);
nghttp2_session_callbacks_set_on_stream_close_callback(FCallbacks_http2, on_stream_close_callback);
if (nghttp2_session_client_new(FSession_http2, FCallbacks_http2, Self) = 0) then
begin
Settings.settings_id := NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS;
Settings.value := 100;
Error := nghttp2_submit_settings(FSession_http2, NGHTTP2_FLAG_NONE, Settings, 1);
if (Error <> 0) then
raise Exception.Create('Unable to submit ngHttp2 settings');
end
else
raise Exception.Create('Unable to setup ngHttp2 session.');
end
else
raise Exception.Create('Unable to setup ngHttp2 callbacks.');
FAuthorization := '';
FConnection := nil;
FConnectionLock := TCriticalSection.Create;
FConnected := TEvent.Create(nil, False, False, '');
FFollowRedirects := True;
FInternalHeaders := THTTPHeaders.Create;
FRequestHeaders := THTTPHeaders.Create;
FResponseHeaders := THTTPHeaders.Create;
end;
destructor TgoHTTP2Client.Destroy;
var
Connection: TgoSocketConnection;
begin
nghttp2_session_callbacks_del(FCallbacks_http2);
nghttp2_session_terminate_session(FSession_http2, NGHTTP2_NO_ERROR);
FConnectionLock.Enter;
try
Connection := FConnection;
FConnection := nil;
finally
FConnectionLock.Leave;
end;
if Connection <> nil then
_HTTPClientSocketManager.Release(Connection);
FInternalHeaders.Free;
FRequestHeaders.Free;
FResponseHeaders.Free;
FConnected.Free;
FConnectionLock.Free;
inherited Destroy;
end;
procedure TgoHTTP2Client.Reset;
begin
FRecvIndex := 0;
FSendIndex := 0;
FRequestSent := TSocketState.None;
FResponseRecv := TSocketState.None;
FResponseStatusCode := 0;
FInternalHeaders.Headers := nil;
FResponseHeaders.Headers := nil;
end;
function TgoHTTP2Client.WaitForSendSuccess: Boolean;
begin
FLastSent := Now;
while (MillisecondsBetween(Now, FLastSent) < TIMEOUT_SEND) and
(FRequestSent = TSocketState.Sending) do
Sleep(5);
Result := FRequestSent = TSocketState.Success;
end;
function TgoHTTP2Client.WaitForRecvSuccess(const ARecvTimeout: Integer): Boolean;
begin
FLastRecv := Now;
while (MillisecondsBetween(Now, FLastRecv) < ARecvTimeout) and
(FResponseRecv = TSocketState.Receiving) do
Sleep(5);
Result := FResponseRecv = TSocketState.Success;
end;
function TgoHTTP2Client.DoResponse(var AAgain: Boolean): UnicodeString;
var
Location: UnicodeString;
begin
Result := TEncoding.Default.GetString(FResponseData);
case FResponseStatusCode of
301,
302,
303,
307,
308,
808: { redirect? }
begin
if FFollowRedirects then
begin
Location := FResponseHeaders.Value('Location');
if not Assigned(FOnRedirect) then
begin
FURL := Location;
AAgain := True;
end
else
begin
AAgain := True;
FOnRedirect(Self, Location, AAgain);
if AAgain then
FURL := Location;
end;
if (FResponseStatusCode = 303) then
FMethod := 'GET';
end;
end;
401: { password required? }
begin
if Assigned(FOnPassword) then
FOnPassword(Self, AAgain);
end;
end;
end;
function TgoHTTP2Client.DoRequest(const AMethod: UnicodeString;
const AURL: UnicodeString; const ARecvTimeout: Integer): UnicodeString;
var
Again: Boolean;
begin
Result := '';
FURL := AURL;
FMethod := AMethod;
repeat
Again := False;
Reset;
CreateRequest;
if Connect then
begin
SendRequest;
if (WaitForSendSuccess) and (WaitForRecvSuccess(ARecvTimeout)) then
Result := DoResponse(Again);
FLastURI := FURI;
end;
until not Again;
end;
procedure TgoHTTP2Client.OnSocketConnected;
begin
FRequestSent := TSocketState.Sending;
FConnected.SetEvent;
end;
procedure TgoHTTP2Client.OnSocketDisconnected;
begin
FRequestSent := TSocketState.None;
FResponseRecv := TSocketState.None;
end;
procedure TgoHTTP2Client.OnSocketSent(const ABuffer: Pointer;
const ASize: Integer);
begin
FLastSent := Now;
end;
procedure TgoHTTP2Client.OnSocketRecv(const ABuffer: Pointer; const ASize: Integer);
begin
FLastRecv := Now;
{ expand the buffer }
SetLength(FRecvBuffer, Length(FRecvBuffer) + ASize);
Move(ABuffer^, FRecvBuffer[Length(FRecvBuffer) - ASize], ASize);
{ send to nghttp2 }
_Recv;
end;
function TgoHTTP2Client.Get(const AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
begin
Result := DoRequest('GET', AURL, ARecvTimeout);
end;
function TgoHTTP2Client.Post(const AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
begin
Result := DoRequest('POST', AURL, ARecvTimeout);
end;
function TgoHTTP2Client.Put(const AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
begin
Result := DoRequest('PUT', AURL, ARecvTimeout);
end;
function TgoHTTP2Client.Delete(const AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
begin
Result := DoRequest('DELETE', AURL, ARecvTimeout);
end;
function TgoHTTP2Client.Options(const AURL: UnicodeString;
const ARecvTimeout: Integer): UnicodeString;
begin
Result := DoRequest('OPTIONS', AURL, ARecvTimeout);
end;
function TgoHTTP2Client._Send: Boolean;
var
DataPtr: Pointer;
DataLen: Integer;
Data: TBytes;
begin
Result := False;
while nghttp2_session_want_write(FSession_http2) > 0 do
begin
DataLen := nghttp2_session_mem_send(FSession_http2, DataPtr);
if DataLen > 0 then
begin
SetLength(Data, DataLen);
Move(DataPtr^, Data[0], DataLen);
Result := FConnection.Send(Data);
end;
end;
end;
function TgoHTTP2Client._Recv: Boolean;
var
ReadLen: Integer;
begin
Result := False;
if FRecvIndex < Length(FRecvBuffer) then
begin
ReadLen := nghttp2_session_mem_recv(FSession_http2, @FRecvBuffer[FRecvIndex], Length(FRecvBuffer) - FRecvIndex);
if ReadLen > 0 then
FRecvIndex := FRecvIndex + ReadLen;
end;
end;
procedure TgoHTTP2Client.CreateRequest;
var
_Username: UnicodeString;
_Password: UnicodeString;
begin
{ parse the URL into a URI }
FURI := TgoURI.Create(FURL);
{ http or https }
if (FURI.Port = 0) then
begin
if FURI.Scheme.ToLower = 'https' then
FURI.Port := DEFAULT_HTTPS_PORT
else
FURI.Port := DEFAULT_HTTP_PORT;
end;
{ add method }
FInternalHeaders.Add(':method', FMethod.ToUpper);
{ add scheme }
FInternalHeaders.Add(':scheme', FURI.Scheme.ToLower);
{ add path }
FInternalHeaders.Add(':path', FURI.Path);
{ add host }
FInternalHeaders.Add('host', FURI.Host);
{ use credentials in URI, if provided }
_Username := FURI.Username;
_Password := FURI.Password;
if (_Username = '') then
begin
{ credentials provided? }
_Username := FUserName;
_Password := FPassword;
end;
if (_Username <> '') then
begin
{ add basic authentication }
FInternalHeaders.Add('authorization', 'Basic ' +
TEncoding.Utf8.GetString(goBase64Encode(TEncoding.Utf8.GetBytes(_Username + ':' + _Password))));
end
else
{ add authorization }
if (FAuthorization <> '') then
FInternalHeaders.Add('authorization', FAuthorization);
end;
function TgoHTTP2Client.Connect: Boolean;
begin
FConnectionLock.Enter;
try
if (FConnection <> nil) and
((FURI.Scheme.ToLower <> FLastURI.Scheme) or
(FURI.Host <> FLastURI.Host ) or
(FURI.Port <> FLastURI.Port)) then
begin
_HTTPClientSocketManager.Release(FConnection);
FConnection := nil;
end;
if FConnection = nil then
begin
FConnection := _HTTPClientSocketManager.Request(FURI.Host, FURI.Port);
FConnection.OnConnected := OnSocketConnected;
FConnection.OnDisconnected := OnSocketDisconnected;
FConnection.OnRecv := OnSocketRecv;
if FURI.Scheme.ToLower = 'https' then
begin
FConnection.SSL := True;
FConnection.ALPN := True;
if FCertificate <> nil then
FConnection.Certificate := FCertificate;
if FPrivateKey <> nil then
FConnection.PrivateKey := FPrivateKey;
end
else
FConnection.SSL := False;
end;
Result := FConnection.State = TgoConnectionState.Connected;
if not Result then
if FConnection.Connect(False) then { disable nagle }
Result := FConnected.WaitFor(TIMEOUT_CONNECT) <> wrTimeout;
finally
FConnectionLock.Leave;
end;
end;
procedure TgoHTTP2Client.SendRequest;
var
Stream_id: Integer;
DataProvider: nghttp2_data_provider;
Headers: TArray<nghttp2_nv>;
begin
FConnectionLock.Enter;
try
if (FConnection <> nil) then
begin
{ setup data callback }
DataProvider.source.ptr := nil;
DataProvider.read_callback := data_source_read_callback;
{ create nghttp2 compatible headers }
FInternalHeaders.ToNgHttp2Headers(Headers);
FRequestHeaders.ToNgHttp2Headers(Headers);
{ setup send buffer }
if (FRequestBody <> '') then
FSendBuffer := TEncoding.Utf8.GetBytes(FRequestBody)
else
FSendBuffer := FRequestData;
{ submit request }
Stream_id := nghttp2_submit_request(FSession_http2, Nil, Headers[0], Length(Headers), @DataProvider, Self);
if Stream_id >= 0 then
begin
if _Send then
begin
FResponseRecv := TSocketState.Receiving;
FRequestSent := TSocketState.Success;
end
else
FRequestSent := TSocketState.Failure;
end
else
FRequestSent := TSocketState.Failure;
end;
finally
FConnectionLock.Leave;
end;
end;
function TgoHTTP2Client.nghttp2_data_source_read_callback(session: nghttp2_session;
stream_id: int32; buf: puint8; len: size_t; data_flags: puint32;
source: pnghttp2_data_source; user_data: Pointer): ssize_t;
begin
// Note: if you want request specific data you can use the API nghttp2_session_get_stream_user_data(session, stream_id);
{$WARNINGS OFF}
if (Length(FSendBuffer) - FSendIndex) <= len then
{$WARNINGS ON}
begin
Result := Length(FSendBuffer) - FSendIndex;
Move(FSendBuffer[FSendIndex], Buf^, Result);
data_flags^ := data_flags^ or NGHTTP2_DATA_FLAG_EOF;
end
else
begin
Result := len;
Move(FSendBuffer[FSendIndex], Buf^, Result);
FSendIndex := FSendIndex + Result;
end;
end;
function TgoHTTP2Client.nghttp2_on_header_callback(session: nghttp2_session; const frame: pnghttp2_frame;
const name: puint8; namelen: size_t; const value: puint8; valuelen: size_t;
flags: uint8; user_data: Pointer): Integer;
var
AName, AValue: String;
begin
if frame.hd.&type = _NGHTTP2_HEADERS then
if (frame.headers.cat = NGHTTP2_HCAT_RESPONSE) then
begin
{ single response header }
AName := AsString(name, namelen);
AValue := AsString(value, valuelen);
FResponseHeaders.Add(AName, AValue);
{ response status code }
if AName = ':status' then
FResponseStatusCode := StrToInt64Def(AValue, -1)
end;
Result := 0;
end;
function TgoHTTP2Client.nghttp2_on_frame_recv_callback(session: nghttp2_session;
const frame: pnghttp2_frame; user_data: Pointer): Integer;
begin
if frame.hd.&type = _NGHTTP2_HEADERS then
if (frame.headers.cat = NGHTTP2_HCAT_RESPONSE) then
begin
// all headers received
end;
Result := 0;
end;
function TgoHTTP2Client.nghttp2_on_data_chunk_recv_callback(session: nghttp2_session;
flags: uint8; stream_id: int32; const data: puint8; len: size_t;
user_data: Pointer): Integer;
begin
// response chunk
{$WARNINGS OFF}
SetLength(FResponseData, Length(FResponseData) + len);
Move(data^, FResponseData[Length(FResponseData) - len], len);
{$WARNINGS ON}
Result := 0;
end;
function TgoHTTP2Client.nghttp2_on_stream_close_callback(session: nghttp2_session;
stream_id: int32; error_code: uint32; user_data: Pointer): Integer;
begin
if FResponseStatusCode <> 0 then
FResponseRecv := TSocketState.Success
else
FResponseRecv := TSocketState.Failure;
Result := 0;
{ Note : connection is still open at this point unless you call
nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR) }
end;
initialization
_HTTPClientSocketManager := TgoClientSocketManager.Create;
finalization
_HTTPClientSocketManager.Free;
end.
|
unit uMakeSpcPrice;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Mask, DB, DBTables, DBCtrls, Grids, DBGrids,
ADODB, siComp, siLangRT, PaideForms;
type
TFrmMakeSpcPrice = class(TFrmParentForms)
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
Panel6: TPanel;
Label1: TLabel;
Label3: TLabel;
quSpecialPrice: TADOQuery;
dsSpecialPrice: TDataSource;
quSpecialPriceIDSpecialPrice: TIntegerField;
quSpecialPriceSpecialPrice: TStringField;
ListPrice: TListBox;
btOK: TButton;
btCancel: TButton;
procedure btOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
//Translation
sManagerAuto,
sSelectSP,
sNone : String;
MyIDPreSale, MySpecialPriceID : Integer;
public
{ Public declarations }
function Start(IDPreSale, SpecialPriceID : Integer) : Boolean;
end;
implementation
uses uDM, uPassword, uAskManager, uInvoice, uDMGlobal, uMsgBox, uMsgConstant,
uSystemConst;
{$R *.DFM}
function TFrmMakeSpcPrice.Start(IDPreSale, SpecialPriceID : Integer ) : Boolean;
begin
MyIDPreSale := IDPreSale;
MySpecialPriceID := SpecialPriceID;
Result := True;
// Testa se tem senha de Manager
if (not Password.HasFuncRight(12)) then
begin
with TFrmAskManager.Create(Self) do
Result := Start(sManagerAuto);
end;
if Result then
Result := (ShowModal = mrOK);
end;
procedure TFrmMakeSpcPrice.btOKClick(Sender: TObject);
var
frmInvoiceAux : TfrmInvoice;
bTaxExempt : Boolean;
begin
if ListPrice.ItemIndex < 0 then
raise exception.create(sSelectSP);
// Acha o item selecionado
bTaxExempt := DM.fSystem.SrvParam[PARAM_TAX_EXEMPT_ON_SALE];
if ListPrice.ItemIndex > 0 then
begin
quSpecialPrice.Locate('SpecialPrice', ListPrice.Items[ListPrice.ItemIndex],
[locaseInsensitive]);
DM.fPOS.AddSpecialPrice(MyIDPreSale, quSpecialPriceIDSpecialPrice.AsInteger, Now, bTaxExempt);
SpecialPrice := ListPrice.ItemIndex;
end
else
DM.fPOS.DeleteSpecialPrice(MyIDPreSale, Now, bTaxExempt);
ModalResult := mrOK;
end;
procedure TFrmMakeSpcPrice.FormShow(Sender: TObject);
begin
inherited;
quSpecialPrice.Open;
// carrega o list box
ListPrice.Items.Clear;
with quSpecialPrice do
begin
First;
ListPrice.Items.Add(sNone);
ListPrice.ItemIndex := 0;
while not eof do
begin
ListPrice.Items.Add(quSpecialPriceSpecialPrice.AsString);
if quSpecialPriceIDSpecialPrice.AsInteger = MySpecialPriceID then
ListPrice.ItemIndex := ListPrice.Items.Count-1;
Next;
end;
end;
btOk.SetFocus;
end;
procedure TFrmMakeSpcPrice.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFrmMakeSpcPrice.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
quSpecialPrice.Close;
Action := caFree;
Screen.Cursor := crDefault;
end;
procedure TFrmMakeSpcPrice.FormCreate(Sender: TObject);
begin
inherited;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sManagerAuto := 'To Make Special Prices you should have the Manager Authorization.';
sSelectSP := 'Select a special price.';
sNone := '<none>';
end;
LANG_PORTUGUESE :
begin
sManagerAuto := 'Para aplicar um Desconto Especial você precisa da autorização do Gerente.';
sSelectSP := 'Selecione um Preço Especial.';
sNone := '<nada>';
end;
LANG_SPANISH :
begin
sManagerAuto := 'Para aplicar un Descuento Especial usted necesita de la autorización del Gerente.';
sSelectSP := 'Seleccione un Precio Especial.';
sNone := '<ninguno>';
end;
end;
end;
end.
|
unit OTFEFreeOTFE_U;
// Description: Delphi FreeOTFE Component
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
{
TOTFEFreeOTFE is a wrapper round the driver and also does all drive operations,
enc data, create new vols, etc
is a singleton class, only ever one instance - this is enforced by assertion in
base class ctor
set up instance by calling OTFEFreeOTFEBase_U.SetFreeOTFEType then get instance
by calling OTFEFreeOTFEBase_U.GetFreeOTFE or TOTFEFreeOTFE.GetFreeOTFE
}
interface
uses
Classes, Controls, dialogs,
Forms,
Graphics, Messages, OTFE_U,
OTFEConsts_U,
DriverAPI,
FreeOTFEDriverConsts,
OTFEFreeOTFE_DriverCypherAPI,
OTFEFreeOTFE_DriverHashAPI,
OTFEFreeOTFE_LUKSAPI,
PKCS11Lib,
VolumeFileAPI,
OTFEFreeOTFEBase_U,
pkcs11_library,
pkcs11_object,
pkcs11_session,
SDUGeneral, SysUtils, Windows;
type
TOTFEFreeOTFE = class (TOTFEFreeOTFEBase)
protected
DriverHandle: THandle;
fDefaultDriveLetter: DriveLetterChar;
fDefaultMountAs: TFreeOTFEMountAs;
// Connect/disconnect to the main FreeOTFE device driver
function Connect(): Boolean; override;
function Disconnect(): Boolean; override;
// ---------
// FreeOTFE *disk* *device* management functions
// These talk directly to the disk devices to carrry out operations
// deviceType - Set to FILE_DEVICE_DISK, etc
function CreateDiskDevice(deviceType: DWORD = FILE_DEVICE_DISK): String;
function DestroyDiskDevice(deviceName: Ansistring): Boolean;
function MountDiskDevice(
deviceName: String;
// PC kernel drivers: disk device to mount. PC DLL: "Drive letter"
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
volumeIV: TSDUBytes;
ReadOnly: Boolean;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
metaData: TOTFEFreeOTFEVolumeMetaData;
offset: Int64 = 0;
size: Int64 = 0;
storageMediaType: TFreeOTFEStorageMediaType =
mtFixedMedia // PC kernel drivers *only* - ignored otherwise
): Boolean; override;
function CreateMountDiskDevice(
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
volumeIV: TSDUBytes;
ReadOnly: Boolean;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
DriveLetter: Char;
// PC kernel drivers: disk device to mount. PC DLL: "Drive letter"
offset: Int64 = 0;
size: Int64 = 0;
MetaData_LinuxVolume: Boolean = False; // Linux volume
MetaData_PKCS11SlotID: Integer = PKCS11_NO_SLOT_ID; // PKCS11 SlotID
MountMountAs: TFreeOTFEMountAs = fomaRemovableDisk;
// PC kernel drivers *only* - ignored otherwise
mountForAllUsers: Boolean =
True // PC kernel drivers *only* - ignored otherwise
): Boolean; override;
function DismountDiskDevice(
deviceName: String;
// PC kernel drivers: disk device to mount. PC DLL: "Drive letter"
emergency: Boolean
): Boolean; override;
function LDREUDriver(
driveLetter: Char;
deviceName: Ansistring;
emergency: Boolean
): Boolean;
function LDREUUserApp(
driveLetter: Char;
deviceName: Ansistring;
emergency: Boolean;
var unableToOpenDrive: Boolean
): Boolean;
// ---------
// Status functions
// Get the number of disk devices the driver currently has (including both
// mounted and unmounted disks)
function GetDiskDeviceCount(): Cardinal;
// Get the kernel mode device name of all disk devices
function GetDiskDeviceList(deviceNames: TStringList): Boolean;
// Get a list of all FreeOTFE devices which are currently mounted
// Note: Unmounted devices will have '' in the "driveLetters" item
// corresponding to the unmounted device listed in the same item
// position in "deviceNames"
function GetMountedDevices(driveLetters: TStringList; deviceNames: TStringList): Boolean;
// Given the specified drive letter, return the FreeOTFE device for that
// mounted drive
function GetDriveDeviceName(driveLetter: Char): String;
// Given the specified device name, return the drive mounted on that device
function GetDriveDeviceLetter(deviceName: String): Char;
// ---------
// Raw volume access functions
// Note: These all transfer RAW data to/from the volume - no
// encryption/decryption takes place
// This executes a sipmle call to the driver to read dataLength bytes from
// offsetWithinFile
// Note: Will probably not work when reading directly from partitions;
// they typically need read/writes carried out in sector sized blocks
// - see ReadRawVolumeDataBounded for this.
function ReadRawVolumeDataSimple(
filename: String;
offsetWithinFile: Int64;
dataLength: DWORD; // In bytes
var Data: Ansistring
): Boolean; override;
function WriteRawVolumeDataSimple(
filename: String;
offsetWithinFile: Int64;
data: Ansistring
): Boolean; override;
function ReadWritePlaintextToVolume(
readNotWrite: Boolean;
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
mountMountAs: TFreeOTFEMountAs;
dataOffset: Int64;
// Offset from within mounted volume from where to read/write data
dataLength: Integer; // Length of data to read/write. In bytes
var data: TSDUBytes; // Data to read/write
offset: Int64 = 0;
size: Int64 = 0;
storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia
): Boolean; override;
// ---------
// Misc functions
// Call QueryDosDevice, and return it's output
function DoQueryDosDevice(deviceName: Ansistring; queryResults: TStringList): Boolean;
// Given an MSDOS device name, return the device name of that device
// (Uses DoQueryDosDevice)
function GetDeviceName(MSDOSKernelModeDeviceName: String): Ansistring;
// Create/delete DosDevices symlink; effectivly wraps DefineDosDevice(...) with
// additional support required for Vista changes
function DosDeviceSymlink(
CreateNotDelete: Boolean;
DeviceName: Ansistring;
DriveLetter: DriveLetterChar;
Global: Boolean
): Boolean;
// Delete both local and global DosDevices symlinks, as possible
function DeleteDosDeviceSymlink(DeviceName: String; DriveLetter: Char): Boolean;
// Connect to the specified user mode named device
function ConnectDevice(devicename: String): THandle;
// Disconnect to the specified device
function DisconnectDevice(deviceHandle: THandle): Boolean;
// Convert kernel mode device name to user mode device name
function GetHashDeviceUserModeDeviceName(hashKernelModeDeviceName: String): String;
// Convert kernel mode device name to user mode device name
function GetCypherDeviceUserModeDeviceName(cypherKernelModeDeviceName: String): String;
function GetNextDriveLetter(userDriveLetter, requiredDriveLetter: Char): Char; override;
function DriverType(): String; override;
// ---------
// Convert critical data area to/from a string representation
// Convert a user-space volume filename to a format the kernel mode driver
// can understand
function GetKernelModeVolumeFilename(userModeFilename: String): String;
// Convert a kernel mode driver volume filename to format user-space
// filename
function GetUserModeVolumeFilename(kernelModeFilename: Ansistring): Ansistring;
// Return TRUE/FALSE, depending on whether the specified KERNEL MODE volume
// filename refers to a partition/file
function IsPartition_KernelModeName(kernelModeFilename: String): Boolean;
// expectedLength - Set to the amount of metadata to retrieve
function GetVolumeMetaData(driveLetter: Char; expectedLength: Integer;
var metaData: Ansistring): Boolean;
// v1 / v3 Cypher API functions
// Note: This shouldn't be called directly - only via wrapper functions!
function _GetCypherDriverCyphers_v1(cypherDriver: Ansistring;
var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; override;
function _GetCypherDriverCyphers_v3(cypherDriver: Ansistring;
var cypherDriverDetails: TFreeOTFECypherDriver): Boolean; override;
public
// -----------------------------------------------------------------------
// TOTFE standard API
constructor Create(); override;
destructor Destroy(); override;
function Dismount(driveLetter: DriveLetterChar; emergency: Boolean = False): Boolean;
overload; override;
function Version(): Cardinal; overload; override;
function DrivesMounted(): String; overload; override;
// -----------------------------------------------------------------------
// TOTFEFreeOTFEBase standard API
function GetVolumeInfo(driveLetter: Char; var volumeInfo: TOTFEFreeOTFEVolumeInfo): Boolean;
override;
function GetHashDrivers(var hashDrivers: TFreeOTFEHashDriverArray): Boolean; override;
function GetHashDriverHashes(hashDriver: Ansistring;
var hashDriverDetails: TFreeOTFEHashDriver): Boolean; override;
function GetCypherDrivers(var cypherDrivers: TFreeOTFECypherDriverArray): Boolean; override;
function _EncryptDecryptData(
encryptFlag: Boolean;
cypherDriver: Ansistring;
cypherGUID: TGUID;
var key: TSDUBytes;
var IV: Ansistring;
var inData: Ansistring;
var outData: Ansistring
): Boolean; override;
function EncryptDecryptSectorData(
encryptFlag: Boolean;
cypherDriver: Ansistring;
cypherGUID: TGUID;
SectorID: LARGE_INTEGER;
SectorSize: Integer;
var key: TSDUBytes;
var IV: Ansistring;
var inData: Ansistring;
var outData: Ansistring
): Boolean; override;
function HashData(
hashDriver: Ansistring;
hashGUID: TGUID;
const data: TSDUBytes;
out hashOut: TSDUBytes
): Boolean; override;
function MACData(
macAlgorithm: TFreeOTFEMACAlgorithm;
HashDriver: Ansistring;
HashGUID: TGUID;
CypherDriver: Ansistring;
CypherGUID: TGUID;
var key: PasswordString;
var data: Ansistring;
var MACOut: Ansistring;
tBits: Integer = -1
): Boolean; override;
function DeriveKey(
kdfAlgorithm: TFreeOTFEKDFAlgorithm;
HashDriver: Ansistring;
HashGUID: TGUID;
CypherDriver: Ansistring;
CypherGUID: TGUID;
Password: TSDUBytes;
Salt: array of Byte;
Iterations: Integer;
dkLenBits: Integer; // In *bits*
out DK: TSDUBytes
): Boolean; override;
// -----------------------------------------------------------------------
// Extended FreeOTFE specific functions
// ---------
// FreeOTFE Driver handling...
// Display control for controlling underlying drivers
procedure ShowDriverControlDlg();
// Install and start FreeOTFE drivers in portable mode
function PortableStart(driverFilenames: TStringList; showProgress: Boolean): Boolean;
// Stop and uninstall any FreeOTFE drivers started in portable mode
function PortableStop(): Boolean;
// Identify how many drivers are currently running in portable mode
function DriversInPortableMode(): Integer;
function CanUserManageDrivers(): Boolean;
// ---------
// See function comment in body of function
{$IFDEF LINUX_DETECT}
function DetectLinux(
volumeFilename: string;
userKey: string;
keyProcSeed: string;
keyProcIterations: integer;
fileOptOffset: int64;
fileOptSize: int64;
mountDriveLetter: char;
mountMountAs: TFreeOTFEMountAs;
testFilename: string
): string;
{$ENDIF}
published
property DefaultDriveLetter: DriveLetterChar Read fDefaultDriveLetter
Write fDefaultDriveLetter default #0;
property DefaultMountAs: TFreeOTFEMountAs Read fDefaultMountAs
Write fDefaultMountAs default fomaRemovableDisk;
end;
{returns an instance of the only object. call SetFreeOTFEType first}
function GetFreeOTFE: TOTFEFreeOTFE;
implementation
uses
SDUi18n,
{$IFDEF LINUX_DETECT}
DbugIntf, // GExperts
{$ENDIF}
{$IFDEF FREEOTFE_DEBUG}
DbugIntf, // GExperts
{$ENDIF}
SDUProgressDlg,
SDUDialogs,
SDUEndianIntegers,
frmSelectVolumeType,
frmKeyEntryFreeOTFE,
frmKeyEntryLinux,
frmKeyEntryLUKS,
frmHashInfo,
frmCypherInfo,
// frmWizardCreateVolume,
frmSelectHashCypher,
DriverControl,
frmDriverControl,
frmSelectPartition,
frmPKCS11Session,
frmPKCS11Management,
Math, // Required for min
ActiveX, // Required for IsEqualGUID
ComObj, // Required for GUIDToString
WinSvc; // Required for SERVICE_ACTIVE
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
type
EFreeOTFEReadCDBFailure = EFreeOTFEError; // Internal error - should never
// be propagated beyond this unit
EFreeOTFEWriteCDBFailure = EFreeOTFEError; // Internal error - should never
// be propagated beyond this unit
PHashIdentify = ^THashIdentify;
THashIdentify = record
KernelModeDriverName: String;
GUID: String;
Details: TFreeOTFEHash;
end;
PCypherIdentify = ^TCypherIdentify;
TCypherIdentify = record
KernelModeDriverName: String;
GUID: String;
Details: TFreeOTFECypher_v3;
end;
const
VERSION_ID_NOT_CACHED = VERSION_ID_FAILURE;
// These are artifical maximums; they must be enough to store the results of
// the DIOC calls when the amount of data output is variable
MAX_DERIVED_KEY_LENGTH = 1024 * 1024; // In *bits*
MAX_MAC_LENGTH = 1024 * 1024; // In *bits*
// Version ID for arbitary metadata passed to, and returned from, driver
METADATA_VERSION = 1;
// ----------------------------------------------------------------------------
//procedure Register;
//begin
// RegisterComponents('OTFE', [TOTFEFreeOTFE]);
//end;
// ----------------------------------------------------------------------------
constructor TOTFEFreeOTFE.Create();
begin
inherited;
end;
// ----------------------------------------------------------------------------
destructor TOTFEFreeOTFE.Destroy();
begin
inherited;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.Connect(): Boolean;
begin
Result := False;
DriverHandle := ConnectDevice(DEVICE_SYMLINK_MAIN_NAME);
if (DriverHandle <> 0) then begin
Result := True;
end else begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.Disconnect(): Boolean;
begin
DisconnectDevice(DriverHandle);
Result := True;
end;
// ----------------------------------------------------------------------------
{$IFDEF LINUX_DETECT}
// This function was included to allow the detection of Linux encrypted
// volume's settings
// This function is *not* normally built, and it's inclusion is only for
// development/diagnostic purposes; not for general use
// It operates by being given the volume's password, and the filename of a file
// stored on the encrypted volume.
// This function cycles through all possible combinations of Linux settings for
// that password, attempting to mount the volume using the given password.
// It does not terminate on a successful mount, as there may be more than one
// set of settings which mount correctly
// IMPORTANT: The encrypted volume *must* be formatted with a filesystem
// MS Windows understands (e.g. FAT)
// WARNING: This procedure can take some time to complete(!)
// WARNING: Some parts of this function may be commented out in order to
// increase it's speed, but at a cost of not checking all combinations
// NOTE: Makes use of GExpert's (3rd party) debugging tool to pump out details
// of successful mounts before this function returns
function TOTFEFreeOTFE.DetectLinux(
volumeFilename: string;
userKey: string;
keyProcSeed: string;
keyProcIterations: integer;
fileOptOffset: int64;
fileOptSize: int64;
mountDriveLetter: char;
mountMountAs: TFreeOTFEMountAs;
testFilename: string
): string;
var
deviceName: string;
i: integer;
volumeKey: string;
keyProcHashDriver: string;
keyProcHashGUID: TGUID;
keyProcHashWithAs: boolean;
keyProcCypherDriver: string;
keyProcCypherGUID: TGUID;
mainCypherDriver: string;
mainCypherGUID: TGUID;
mainIVHashDriver: string;
mainIVHashGUID: TGUID;
mainIVCypherDriver: string;
mainIVCypherGUID: TGUID;
currDriveLetter: Ansichar;
startOfVolFile: boolean;
startOfEndData: boolean;
VolumeFlags: DWORD;
mr: integer;
mainCypherDetails: TFreeOTFECypher;
hashDrivers: array of TFreeOTFEHashDriver;
cypherDrivers: array of TFreeOTFECypherDriver;
kph_i, kph_j: integer;
kpc_i, kpc_j: integer;
mc_i, mc_j: integer;
hashWithAsInt: integer;
ivh_i, ivh_j: integer;
ivc_i, ivc_j: integer;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
ivStartSectorInt: integer;
kph_currDriver: TFreeOTFEHashDriver;
kph_currImpl: TFreeOTFEHash;
kpc_currDriver: TFreeOTFECypherDriver;
kpc_currImpl: TFreeOTFECypher;
mc_currDriver: TFreeOTFECypherDriver;
mc_currImpl: TFreeOTFECypher;
ivh_currDriver: TFreeOTFEHashDriver;
ivh_currImpl: TFreeOTFEHash;
ivc_currDriver: TFreeOTFECypherDriver;
ivc_currImpl: TFreeOTFECypher;
begin
LastErrorCode := OTFE_ERR_SUCCESS;
Result := '';
CheckActive();
// Sanity checking
// Is the user attempting to mount Linux LUKS volumes?
// Mount as LUKS if they are...
if (IsLUKSVolume(volumeFilename)) then
begin
Result := Result + 'LUKS container; no need to do exhaustive search';
exit;
end;
if (Result = '') then
begin
// Obtain details of all hashes...
SetLength(hashDrivers, 0);
if not(GetHashDrivers(TFreeOTFEHashDriverArray(hashDrivers))) then
begin
Result := Result + 'Unable to get list of hash drivers.';
end;
end;
if (Result = '') then
begin
// Obtain details of all cyphers...
SetLength(cypherDrivers, 0);
if not(GetCypherDrivers(TFreeOTFECypherDriverArray(cypherDrivers))) then
begin
Result := Result + 'Unable to get list of cypher drivers.';
end;
end;
if (Result = '') then
begin
currDriveLetter := GetNextDriveLetter(mountDriveLetter, #0);
if (currDriveLetter = #0) then
begin
// No more drive letters following the user's specified drive
// letter - don't mount further drives
Result := Result + 'Out of drive letters.';
end;
end;
if (Result = '') then
begin
// KEY PROCESSING
// FOR ALL HASH DRIVERS...
SendDateTime('START', now);
for kph_i:=low(hashDrivers) to high(hashDrivers) do
begin
SendDebug('-kph_i: '+inttostr(kph_i)+'/'+inttostr(high(hashDrivers) - low(hashDrivers)));
kph_currDriver := hashDrivers[kph_i];
// FOR ALL HASHES SUPPORTED BY THE CURRENT DRIVER...
for kph_j:=low(kph_currDriver.Hashes) to high(kph_currDriver.Hashes) do
begin
SendDebug('--kph_j: '+inttostr(kph_j)+'/'+inttostr(high(kph_currDriver.Hashes) - low(kph_currDriver.Hashes)));
kph_currImpl := kph_currDriver.Hashes[kph_j];
keyProcHashDriver := kph_currDriver.DeviceKernelModeName;
keyProcHashGUID := kph_currImpl.HashGUID;
// KEY PROCESSING
// FOR ALL CYPHER DRIVERS...
for kpc_i:=low(cypherDrivers) to high(cypherDrivers) do
begin
SendDebug('---kpc_i: '+inttostr(kpc_i)+'/'+inttostr(high(cypherDrivers) - low(cypherDrivers)));
kpc_currDriver := cypherDrivers[kpc_i];
// FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER...
for kpc_j:=low(kpc_currDriver.Cyphers) to high(kpc_currDriver.Cyphers) do
begin
SendDebug('----kpc_j: '+inttostr(kpc_j)+'/'+inttostr(high(kpc_currDriver.Cyphers) - low(kpc_currDriver.Cyphers)));
kpc_currImpl := kpc_currDriver.Cyphers[kpc_j];
keyProcCypherDriver := kpc_currDriver.DeviceKernelModeName;
keyProcCypherGUID := kpc_currImpl.CypherGUID;
// // MAIN CYPHER
// // FOR ALL CYPHER DRIVERS...
// for mc_i:=low(cypherDrivers) to high(cypherDrivers) do
// begin
// mc_currDriver := cypherDrivers[mc_i];
// // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER...
// for mc_j:=low(mc_currDriver.Cyphers) to high(mc_currDriver.Cyphers) do
// begin
// mc_currImpl := kpc_currDriver.Cyphers[mc_j];
// xxx
// xxx
mc_currDriver := kpc_currDriver;
mc_currImpl := kpc_currImpl;
mainCypherDriver := mc_currDriver.DeviceKernelModeName;
mainCypherGUID := mc_currImpl.CypherGUID;
mainCypherDetails := mc_currImpl;
for hashWithAsInt:=0 to 1 do
begin
SendDebug('-----hashWithAsInt: '+inttostr(hashWithAsInt)+'/(0-1)');
// Generate volume key for encryption/decryption
if not(GenerateLinuxVolumeKey(
keyProcHashDriver,
keyProcHashGUID,
userKey,
keyProcSeed,
(hashWithAsInt = 1),
mainCypherDetails.KeySize,
volumeKey
)) then
begin
Result := Result + 'HASH FAILURE: '+keyProcHashDriver+':'+GUIDToString(keyProcHashGUID);
continue;
end;
// IV GENERATION
// FOR ALL HASH DRIVERS...
for ivh_i:=low(hashDrivers) to high(hashDrivers) do
begin
SendDebug('------ivh_i: '+inttostr(ivh_i)+'/'+inttostr(high(hashDrivers) - low(hashDrivers)));
ivh_currDriver := hashDrivers[ivh_i];
// FOR ALL HASHES SUPPORTED BY THE CURRENT DRIVER...
for ivh_j:=low(ivh_currDriver.Hashes) to high(ivh_currDriver.Hashes) do
begin
SendDebug('-------ivh_j: '+inttostr(ivh_j)+'/'+inttostr(high(ivh_currDriver.Hashes) - low(ivh_currDriver.Hashes)));
ivh_currImpl := ivh_currDriver.Hashes[ivh_j];
mainIVHashDriver := ivh_currDriver.DeviceKernelModeName;
mainIVHashGUID := ivh_currImpl.HashGUID;
// // IV GENERATION
// // FOR ALL CYPHER DRIVERS...
// for ivc_i:=low(cypherDrivers) to high(cypherDrivers) do
// begin
// ivc_currDriver := cypherDrivers[ivc_i];
// // FOR ALL CYPHERS SUPPORTED BY THE CURRENT DRIVER...
// for ivc_j:=low(ivc_currDriver.Cyphers) to high(ivc_currDriver.Cyphers) do
// begin
// ivc_currImpl := ivc_currDriver.Cyphers[ivc_j];
// xxx
ivc_currDriver := kpc_currDriver;
ivc_currImpl := kpc_currImpl;
mainIVCypherDriver := ivc_currDriver.DeviceKernelModeName;
mainIVCypherGUID := ivc_currImpl.CypherGUID;
// IV GENERATION
// for sectorIVGenMethod := low(sectorIVGenMethod) to high(sectorIVGenMethod) do
sectorIVGenMethod := foivg32BitSectorID;
begin
// SendDebug('--------sectorIVGenMethod: '+inttostr(ord(sectorIVGenMethod))+'/'+inttostr(ord(high(sectorIVGenMethod)) - loword((sectorIVGenMethod))));
// for ivStartSectorInt:=0 to 1 do
begin
ivStartSectorInt := 1;
// SendDebug('---------ivStartSectorInt: '+inttostr(ivStartSectorInt)+'/(0-1)');
startOfVolFile := (ivStartSectorInt = 0);
startOfEndData := (ivStartSectorInt = 1);
// Encode IV generation method to flags...
VolumeFlags := 0;
if (startOfVolFile) then
begin
VolumeFlags := VolumeFlags OR VOL_FLAGS_SECTOR_ID_ZERO_VOLSTART;
end;
// Attempt to create a new device to be used
deviceName := CreateDiskDevice(FreeOTFEMountAsDeviceType[mountMountAs]);
if (deviceName <> '') then
begin
// Attempt to mount the device
if MountDiskDevice(
deviceName,
volumeFilename,
volumeKey,
sectorIVGenMethod,
'', // Linux volumes don't have per-volume IVs
TRUE,
mainIVHashDriver,
mainIVHashGUID,
mainIVCypherDriver,
mainIVCypherGUID,
mainCypherDriver,
mainCypherGUID,
VolumeFlags,
'',
fileOptOffset,
fileOptSize,
FreeOTFEMountAsStorageMediaType[mountMountAs]
) then
begin
if DosDeviceSymlink(
TRUE,
deviceName,
currDriveLetter,
TRUE
) then
begin
// Test if mounted OK
if FileExists(currDriveLetter+':'+testFilename) then
begin
Result := Result + '---------------------------------------------------------------';
Result := Result + 'OK!';
Result := Result + 'mountedAs: '+currDriveLetter;
Result := Result + 'kph: '+keyProcHashDriver +':'+GUIDToString(keyProcHashGUID );
Result := Result + 'kpc: '+keyProcCypherDriver +':'+GUIDToString(keyProcCypherGUID );
Result := Result + 'mc: '+mainCypherDriver +':'+GUIDToString(mainCypherGUID);
Result := Result + 'hashWithAsInt: '+inttostr(hashWithAsInt);
Result := Result + 'ivh: '+mainIVHashDriver +':'+GUIDToString(mainIVHashGUID );
Result := Result + 'ivc: '+mainIVCypherDriver +':'+GUIDToString(mainIVCypherGUID );
Result := Result + 'sectorIVGenMethod: '+inttostr(ord(sectorIVGenMethod));
Result := Result + 'ivStartSectorInt: '+inttostr(ivStartSectorInt);
Result := Result + '---------------------------------------------------------------';
SendDateTime('HIT', now);
SendDebug('Result: '+Result);
end;
Dismount(currDriveLetter);
end
else
begin
// Cleardown
DismountDiskDevice(deviceName, TRUE);
DestroyDiskDevice(deviceName);
end; // ELSE PART - if DefineDosDevice(
end
else
begin
// Cleardown
DestroyDiskDevice(deviceName);
end; // ELSE PART - if MountDiskDevice(
end; // ELSE PART - if (deviceName <> '') then
end; // for ivStartSectorInt:=0 to 1 do
end; // for sectorIVGenMethod := low(sectorIVGenMethod) to high(sectorIVGenMethod) do
// end; // for ivc_j:=low(ivc_currDriver.Cyphers) to high(ivc_currDriver.Cyphers) do
// end; // for ivc_i:=low(cypherDrivers) to high(cypherDrivers) do
end; // for ivh_j:=low(ivh_currDriver.Hashes) to high(ivh_currDriver.Hashes) do
end; // for ivh_i:=low(hashDrivers) to high(hashDrivers) do
end; // for hashWithAsInt:=0 to 1 do
// end; // for mc_j:=low(mc_currDriver.Cyphers) to high(mc_currDriver.Cyphers) do
// end; // for mc_i:=low(cypherDrivers) to high(cypherDrivers) do
end; // for kpc_j:=low(kpc_currDriver.Cyphers) to high(kpc_currDriver.Cyphers) do
end; // for kpc_i:=low(cypherDrivers) to high(cypherDrivers) do
end; // for kph_j:=low(kph_currDriver.Hashes) to high(kph_currDriver.Hashes) do
end; // for kph_i:=low(hashDrivers) to high(hashDrivers) do
end; // if (Result = '') then
SendDateTime('FINISHED', now);
end;
{$ENDIF}
// ----------------------------------------------------------------------------
// Attempt to create a new device to be used
function TOTFEFreeOTFE.CreateDiskDevice(deviceType: DWORD): String;
var
DIOCBufferIn: TDIOC_DISK_DEVICE_CREATE;
DIOCBufferOut: TDIOC_DEVICE_NAME;
bytesReturned: DWORD;
begin
Result := '';
CheckActive();
// !!! WARNING !!!
// We use FILE_DEVICE_DISK as FILE_DEVICE_VIRTUAL_DISK can
// make NTFS-only Windows XP systems unstable?
// See MS Knowledgebase article: Q257405 for further details
// http://support.microsoft.com/default.aspx?scid=kb;en-us;257405
DIOCBufferIn.DeviceType := deviceType;
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_CREATE, @DIOCBufferIn,
sizeof(DIOCBufferIn), @DIOCBufferOut,
sizeof(DIOCBufferOut), bytesReturned,
nil)) then begin
Result := copy(DIOCBufferOut.DeviceName, 1, StrLen(DIOCBufferOut.DeviceName));
DebugMsg('Disk device created: '+Result);
end;
end;
// ----------------------------------------------------------------------------
// Attempt to mount on an existing device
function TOTFEFreeOTFE.MountDiskDevice(
deviceName: String;
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
volumeIV: TSDUBytes;
ReadOnly: Boolean;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
metaData: TOTFEFreeOTFEVolumeMetaData;
offset: Int64 = 0;
size: Int64 = 0;
storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia
): Boolean;
var
ptrDIOCBuffer: PDIOC_MOUNT_PC_DRIVER;
bytesReturned: DWORD;
bufferSize: Integer;
mainCypherDetails: TFreeOTFECypher_v3;
kmFilename: String;
useVolumeFlags: Integer;
strMetaData: Ansistring;
volumeKeyStr: Ansistring;
begin
Result := False;
DebugMsg('In MountDiskDevice');
VolumeMetadataToString(metaData, strMetaData);
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('MountDiskDevice called with: ');
DebugMsg(' deviceName: '+deviceName);
DebugMsg(' filename: '+volFilename);
DebugMsg(' volumeKey: ');
DebugMsg(volumeKey);
DebugMsg(' IVHashDriver: '+IVHashDriver);
DebugMsg(' IVHashGUID: '+GUIDToString(IVHashGUID));
DebugMsg(' IVCypherDriver: '+IVCypherDriver);
DebugMsg(' IVCypherGUID: '+GUIDToString(IVCypherGUID));
DebugMsg(' mainCypherDriver: '+mainCypherDriver);
DebugMsg(' mainCypherGUID: '+GUIDToString(mainCypherGUID));
DebugMsg(' sectorIVGenMethod: '+FreeOTFESectorIVGenMethodTitle[sectorIVGenMethod]);
DebugMsg(' VolumeFlags: '+inttostr(VolumeFlags));
DebugMsg(' metaData: <not shown>');
DebugMsg(' strMetaData:');
DebugMsgBinary(strMetaData);
DebugMsg(' offset: '+inttostr(offset));
DebugMsg(' size: '+inttostr(size));
{$ENDIF}
CheckActive();
if not (GetSpecificCypherDetails(mainCypherDriver, mainCypherGUID, mainCypherDetails)) then begin
//
exit;
end;
// Ensure the volumeKey's length matches that of the cypher's keysize, if
// the cypher's keysize is >= 0
if (mainCypherDetails.KeySizeRequired >= 0) then begin
// THIS IS CORRECT; caters for both volumeKey>keysize and
// volumeKey<keysize
// Copy as much of the hash value as possible to match the key length
volumeKeyStr := SDUBytesToString(volumeKey);
volumeKeyStr := Copy(volumeKeyStr, 1, min((mainCypherDetails.KeySizeRequired div 8),
length(volumeKeyStr)));
// If the hash wasn't big enough, pad out with zeros
volumeKeyStr := volumeKeyStr + StringOfChar(AnsiChar(#0),
((mainCypherDetails.KeySizeRequired div 8) - Length(volumeKeyStr)));
SafeSetLength(volumeKey, mainCypherDetails.KeySizeRequired div 8);
assert(volumeKeyStr = SDUBytesToString(volumeKey));// passed
end;
// If the sector IV doesn't use hashing, don't pass a hash algorithm in
if not (SCTRIVGEN_USES_HASH[sectorIVGenMethod]) then begin
IVHashDriver := '';
IVHashGUID := StringToGUID(NULL_GUID);
end;
// If the sector IV doesn't use hashing, don't pass a hash algorithm in
if not (SCTRIVGEN_USES_CYPHER[sectorIVGenMethod]) then begin
IVCypherDriver := '';
IVCypherGUID := StringToGUID(NULL_GUID);
end;
// Subtract sizeof(char) - once for the volume key, once for the volumeIV
bufferSize := sizeof(ptrDIOCBuffer^) - sizeof(Ansichar) +
(sizeof(Ansichar) * Length(volumeKey)) - sizeof(Ansichar) +
(sizeof(Ansichar) * Length(volumeIV)) - sizeof(Ansichar) +
(sizeof(Ansichar) * Length(strMetaData));
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrDIOCBuffer := allocmem(bufferSize);
try
StrPCopy(ptrDIOCBuffer.DiskDeviceName, deviceName);
// Determine the filename as the kernel sees it
kmFilename := GetKernelModeVolumeFilename(volFilename);
StrPCopy(ptrDIOCBuffer.Filename, kmFilename);
ptrDIOCBuffer.DataStart := offset;
ptrDIOCBuffer.DataEnd := 0;
if (size > 0) then begin
ptrDIOCBuffer.DataEnd := offset + size;
end;
StrPCopy(ptrDIOCBuffer.IVHashDeviceName, IVHashDriver);
ptrDIOCBuffer.IVHashGUID := IVHashGUID;
StrPCopy(ptrDIOCBuffer.IVCypherDeviceName, IVCypherDriver);
ptrDIOCBuffer.IVCypherGUID := IVCypherGUID;
StrPCopy(ptrDIOCBuffer.MainCypherDeviceName, mainCypherDriver);
ptrDIOCBuffer.MainCypherGUID := mainCypherGUID;
ptrDIOCBuffer.ReadOnly := ReadOnly;
ptrDIOCBuffer.MountSource := FreeOTFEMountSourceID[fomsFile];
if IsPartition_KernelModeName(kmFilename) then begin
ptrDIOCBuffer.MountSource := FreeOTFEMountSourceID[fomsPartition];
end;
ptrDIOCBuffer.StorageMediaType := FreeOTFEStorageMediaTypeID[storageMediaType];
useVolumeFlags := VolumeFlags;
// Yes, this timestamp reverting is the right way around; if the bit
// *isn't* set, the timestamps get reverted
if frevertVolTimestamps then
// Strip off bit VOL_FLAGS_NORMAL_TIMESTAMPS
useVolumeFlags := useVolumeFlags and not (VOL_FLAGS_NORMAL_TIMESTAMPS)
else
// Set bit VOL_FLAGS_NORMAL_TIMESTAMPS
useVolumeFlags := useVolumeFlags or VOL_FLAGS_NORMAL_TIMESTAMPS;
ptrDIOCBuffer.VolumeFlags := useVolumeFlags;
ptrDIOCBuffer.SectorIVGenMethod := FreeOTFESectorIVGenMethodID[sectorIVGenMethod];
ptrDIOCBuffer.MasterKeyLength := Length(volumeKey) * 8;
ptrDIOCBuffer.VolumeIVLength := Length(volumeIV) * 8;
ptrDIOCBuffer.MetaDataLength := Length(strMetaData);
// This may seem a little weird, but we do this because the VolumeIV and metaData are
// immediatly after the master key
StrMove(@ptrDIOCBuffer.MasterKey, PAnsiChar(volumeKey), Length(volumeKey));
StrMove(((PAnsiChar(@ptrDIOCBuffer.MasterKey)) + length(volumeKey)),
PAnsiChar(volumeIV), Length(volumeIV));
StrMove(((PAnsiChar(@ptrDIOCBuffer.MasterKey)) + length(volumeKey) + length(volumeIV)),
PAnsiChar(strMetaData), Length(strMetaData));
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('+++ ABOUT TO DIOC MOUNT WITH STRUCT:');
DebugMsg('+++ struct size: '+inttostr(bufferSize));
DebugMsg('+++ ---begin struct---');
DebugMsgBinaryPtr(PAnsiChar(ptrDIOCBuffer), bufferSize);
DebugMsg('+++ ---end struct---');
{$ENDIF}
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_MOUNT, ptrDIOCBuffer,
bufferSize, nil, 0,
bytesReturned, nil)) then
begin
DebugMsg('Mounted OK!');
Result := True;
end;
DebugMsg('+++ DIOC STRUCT COMPLETE');
finally
FreeMem(ptrDIOCBuffer);
end;
DebugMsg('Exiting MountDiskDevice');
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.CreateMountDiskDevice(
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
volumeIV: TSDUBytes;
ReadOnly: Boolean;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
DriveLetter: Char;
// PC kernel drivers: disk device to mount. PC DLL: "Drive letter"
offset: Int64 = 0;
size: Int64 = 0;
MetaData_LinuxVolume: Boolean = False; // Linux volume
MetaData_PKCS11SlotID: Integer = PKCS11_NO_SLOT_ID; // PKCS11 SlotID
MountMountAs: TFreeOTFEMountAs = fomaRemovableDisk;
// PC kernel drivers *only* - ignored otherwise
mountForAllUsers: Boolean =
True // PC kernel drivers *only* - ignored otherwise
): Boolean;
var
deviceName: String;
mountMetadata: TOTFEFreeOTFEVolumeMetaData;
begin
Result := False;
// Attempt to create a new device to be used
deviceName := CreateDiskDevice(FreeOTFEMountAsDeviceType[MountMountAs]);
if (deviceName <> '') then begin
PopulateVolumeMetadataStruct(
MetaData_LinuxVolume,
MetaData_PKCS11SlotID,
mountMetadata
);
// Attempt to mount the device
if MountDiskDevice(deviceName, volFilename,
volumeKey, sectorIVGenMethod,
volumeIV, ReadOnly,
IVHashDriver, IVHashGUID,
IVCypherDriver, IVCypherGUID,
mainCypherDriver, mainCypherGUID,
VolumeFlags, mountMetadata,
offset, size,
FreeOTFEMountAsStorageMediaType[MountMountAs]) then
begin
if DosDeviceSymlink(True, deviceName,
DriveLetter, mountForAllUsers
) then begin
Result := True;
end else begin
// Cleardown
DismountDiskDevice(deviceName, True);
DestroyDiskDevice(deviceName);
end;
end else begin
// Cleardown
DestroyDiskDevice(deviceName);
end;
end;
//
end;
// ----------------------------------------------------------------------------
// Attempt to dismount a device
function TOTFEFreeOTFE.DismountDiskDevice(deviceName: String; emergency: Boolean): Boolean;
var
DIOCBuffer: TDIOC_DISMOUNT;
bytesReturned: DWORD;
begin
Result := False;
CheckActive();
StrPCopy(DIOCBuffer.DiskDeviceName, deviceName);
DIOCBuffer.Emergency := emergency;
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_DISMOUNT, @DIOCBuffer,
sizeof(DIOCBuffer), nil,
0, bytesReturned,
nil)) then begin
Result := True;
end;
end;
// ----------------------------------------------------------------------------
// This dismount routine is based on the MS "media eject" routine for NT/2k/XP
// at:
// http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q165/7/21.asp&NoWebContent=1
function TOTFEFreeOTFE.LDREUUserApp(
driveLetter: Char;
deviceName: Ansistring;
emergency: Boolean;
var unableToOpenDrive: Boolean
): Boolean;
var
driveDevice: THandle;
BytesReturned: DWORD;
driveLetterColon: String;
driveFile: WideString;
pmr: TPREVENT_MEDIA_REMOVAL;
volumeInfo: TOTFEFreeOTFEVolumeInfo;
begin
CheckActive();
driveLetterColon := upcase(driveLetter) + ':';
driveFile := '\\.\' + driveLetterColon;
Result := True;
if Result then begin
DebugMsg('getVolumeInfo');
Result := GetVolumeInfo(driveLetter, volumeInfo);
// If we couldn't get the drive info, then we can't even do an
// emergency dismount; we don't know which FreeOTFE device to dismount
if (not Result) then begin
DebugMsg('getVolumeInfo NOT Result');
emergency := False;
end;
end;
// We attempt to open the drive, and then carry out various operations to
// shut the drive down.
// If were operating in an emergency, then we don't care if some of these
// operations fail - it's an EMERGENCY! JUST GET RID OF THE %$!# DRIVE!
// Initialize to flag that we haven't opened it
driveDevice := INVALID_HANDLE_VALUE;
if Result then begin
DebugMsg('createfile: '+driveFile);
driveDevice := CreateFile(PChar(driveFile),
//GENERIC_READ or GENERIC_WRITE,
GENERIC_READ, FILE_SHARE_READ or
FILE_SHARE_WRITE, nil, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0);
Result := (driveDevice <> INVALID_HANDLE_VALUE);
DebugMsg('driveDevice: '+inttostr(driveDevice)+' (INVALID_HANDLE_VALUE = '+inttostr(INVALID_HANDLE_VALUE));
end;
unableToOpenDrive := (driveDevice = INVALID_HANDLE_VALUE);
if (Result or (emergency and (driveDevice <> INVALID_HANDLE_VALUE))) then begin
DebugMsg('lockvolume');
Result := DeviceIoControl(driveDevice,
FSCTL_LOCK_VOLUME, nil,
0, nil,
0, bytesReturned,
nil);
end;
if (Result or (emergency and (driveDevice <> INVALID_HANDLE_VALUE))) then begin
DebugMsg('dismountvolume');
Result := DeviceIoControl(driveDevice,
FSCTL_DISMOUNT_VOLUME, nil,
0, nil,
0, bytesReturned,
nil);
end;
if (Result or (emergency and (driveDevice <> INVALID_HANDLE_VALUE))) then begin
pmr.PreventMediaRemoval := False;
DebugMsg('mediaremoval');
Result := DeviceIoControl(driveDevice,
IOCTL_STORAGE_MEDIA_REMOVAL, @pmr,
sizeof(pmr), nil,
0, bytesReturned,
nil);
end;
if (Result or (emergency and (driveDevice <> INVALID_HANDLE_VALUE))) then begin
pmr.PreventMediaRemoval := False;
DebugMsg('ejectmedia');
Result := DeviceIoControl(driveDevice,
IOCTL_STORAGE_EJECT_MEDIA, nil,
0, nil,
0, bytesReturned,
nil);
end;
// An explicit call to IOCTL_FREEOTFE_DISMOUNT should be redundant; the
// IOCTL_STORAGE_EJECT_MEDIA should have already done this
if (Result or emergency) then begin
DebugMsg('dismountdevice');
Result := DismountDiskDevice(volumeInfo.deviceName, emergency);
end;
if (Result or (emergency and (driveDevice <> INVALID_HANDLE_VALUE))) then begin
DebugMsg('unlock');
Result := DeviceIoControl(driveDevice,
FSCTL_UNLOCK_VOLUME, nil,
0, nil,
0, bytesReturned,
nil);
end;
if (driveDevice <> INVALID_HANDLE_VALUE) then begin
DebugMsg('closehandle');
// Note that we can't do:
// Result := Result and CloseHandle(driveDevice);"
// here because lazy evaluation will prevent CloseHandle(...) from being
// called if Result is FALSE - and we *want* CloseHandle(...) called
// regardless, otherwise we end up with FreeOTFE never closing this file
// handle, and "leaking" this handle
if not (CloseHandle(driveDevice)) then begin
Result := False;
end;
end;
end;
// Send LDREU to get the driver to lock, dismount, remove eject and unlock
// driveFile - Must be of the format "\??\Z:"
// deviceName - Must be of the formst \Device\FreeOTFE\Disks\Disk1
function TOTFEFreeOTFE.LDREUDriver(
driveLetter: Char;
deviceName: Ansistring;
emergency: Boolean
): Boolean;
var
DIOCBuffer: TDIOC_LDREU;
bytesReturned: DWORD;
kernelDriveFile: Ansistring;
begin
Result := False;
CheckActive();
// This functionality only present in v2.00 o f the FreeOTFE driver; previous
// versions could only carry this out within the userspace app
if CheckVersionAtLeast(FREEOTFE_ID_v02_00_0000) then begin
kernelDriveFile := '\??\' + uppercase(AnsiChar(driveLetter)) + ':';
StrPCopy(DIOCBuffer.DriveFile, kernelDriveFile);
StrPCopy(DIOCBuffer.DiskDeviceName, deviceName);
DIOCBuffer.Emergency := emergency;
DebugMsg('LDREUDriver: "'+ DIOCBuffer.DriveFile+ '" : "'+ DIOCBuffer.DiskDeviceName+'" '+Booltostr(emergency) );
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_LDREU, @DIOCBuffer,
sizeof(DIOCBuffer), nil,
0, bytesReturned,
nil)) then begin
Result := True;
end;
end;
end;
// ----------------------------------------------------------------------------
// Attempt to destroy a device
function TOTFEFreeOTFE.DestroyDiskDevice(deviceName: Ansistring): Boolean;
var
DIOCBuffer: TDIOC_DEVICE_NAME;
bytesReturned: DWORD;
begin
Result := False;
CheckActive();
StrPCopy(DIOCBuffer.DeviceName, deviceName);
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_DESTROY, @DIOCBuffer,
sizeof(DIOCBuffer), nil,
0, bytesReturned,
nil)) then begin
Result := True;
end;
end;
// ----------------------------------------------------------------------------
// This dismount routine is based on the MS "media eject" routine for NT/2k/XP
// at:
// http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q165/7/21.asp&NoWebContent=1
function TOTFEFreeOTFE.Dismount(driveLetter: DriveLetterChar; emergency: Boolean = False): Boolean;
var
volumeInfo: TOTFEFreeOTFEVolumeInfo;
unableToOpenDrive: Boolean;
begin
CheckActive();
Result := True;
if Result then begin
DebugMsg('getVolumeInfo');
Result := GetVolumeInfo(driveLetter, volumeInfo);
// If we couldn't get the drive info, then we can't even do an
// emergency dismount; we don't know which FreeOTFE device to dismount
if (not Result) then begin
DebugMsg('getVolumeInfo NOT Result');
emergency := False;
end;
end;
// We attempt to open the drive, and then carry out various operations to
// shut the drive down.
// If were operating in an emergency, then we don't care if some of these
// operations fail - it's an EMERGENCY! JUST GET RID OF THE %$!# DRIVE!
if Result then begin
unableToOpenDrive := False;
DebugMsg('LDREUUserApp: "'+ driveLetter+ '" : "'+ volumeInfo.deviceName+'" '+Booltostr(emergency)+ Booltostr(unableToOpenDrive));
Result := LDREUUserApp(driveLetter,
volumeInfo.deviceName, emergency,
unableToOpenDrive);
end;
// If we were unable to open the drive to carry out the dismount, we're
// probably on Vista, without having escalated UAC before trying to dismount.
// Fallback to getting the driver handle the privileged part of the
// dismount (i.e. opening the volume) and carry out the LDREU
if (not Result and unableToOpenDrive) then begin
DebugMsg(Format('LDREUDriver "%s" "%s" %s',[driveLetter,volumeInfo.deviceName,Booltostr(emergency)]));
Result := LDREUDriver(driveLetter, volumeInfo.deviceName, emergency);
end;
if (Result or emergency) then begin
DebugMsg('remove definition');
Result := DeleteDosDeviceSymlink(volumeInfo.deviceName, driveLetter);
end;
// And finally... Destroy the device
if (Result or emergency) then begin
DebugMsg('destroy device');
Result := DestroyDiskDevice(volumeInfo.deviceName);
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.Version(): Cardinal;
var
BytesReturned: DWORD;
DIOCBuffer: TDIOC_VERSION;
begin
Result := VERSION_ID_FAILURE;
CheckActive();
// If we have the version ID cached, use the cached information
if (fCachedVersionID <> VERSION_ID_NOT_CACHED) then begin
Result := fCachedVersionID;
end else begin
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_VERSION, nil,
0, @DIOCBuffer,
sizeof(DIOCBuffer), BytesReturned,
nil)) then begin
if BytesReturned = sizeof(DIOCBuffer) then begin
Result := DIOCBuffer.VersionID;
fCachedVersionID := Result;
end;
end;
end;
end;
// ----------------------------------------------------------------------------
// Get the number of disk devices the driver currently has
// Returns $FFFFFFFF on error
function TOTFEFreeOTFE.GetDiskDeviceCount(): Cardinal;
var
BytesReturned: DWORD;
DIOCBuffer: TDIOC_DISK_DEVICE_COUNT;
begin
Result := $FFFFFFFF;
CheckActive();
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GET_DISK_DEVICE_COUNT, nil,
0, @DIOCBuffer, sizeof(DIOCBuffer),
BytesReturned, nil)) then begin
if BytesReturned = sizeof(DIOCBuffer) then begin
Result := DIOCBuffer.Count;
end;
end;
end;
// ----------------------------------------------------------------------------
// Get the kernel mode device name of all disk devices
// WARNING: If devices are mounted while this function is called, this function
// may fail if the number of devices goes up between the call to
// GetDiskDevicesCount(), and the DIOC call (the buffer won't be big
// enough to store all device names)
function TOTFEFreeOTFE.GetDiskDeviceList(deviceNames: TStringList): Boolean;
var
BytesReturned: DWORD;
ptrBuffer: Pointer;
ptrBufferOffset: Pointer;
bufferSize: Cardinal;
i: Integer;
devName: Ansistring;
deviceCount: Integer;
ptrDIOCDeviceNameList: PDIOC_DEVICE_NAME_LIST;
begin
Result := False;
CheckActive();
deviceCount := GetDiskDeviceCount();
bufferSize := sizeof(ptrDIOCDeviceNameList^) - FREEOTFE_MAX_FILENAME_LENGTH +
(FREEOTFE_MAX_FILENAME_LENGTH * deviceCount);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrBuffer := allocmem(bufferSize);
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GET_DISK_DEVICE_LIST, nil,
0, ptrBuffer, bufferSize,
BytesReturned, nil)) then begin
if BytesReturned <= bufferSize then begin
// In case devices were unmounted between the call to
// GetDiskDeviceCount() and the DIOC call...
ptrDIOCDeviceNameList := ptrBuffer;
deviceCount := ptrDIOCDeviceNameList.DeviceCount;
ptrBufferOffset := Pointer(PAnsiChar(ptrBuffer) +
sizeof(ptrDIOCDeviceNameList^) -
FREEOTFE_MAX_FILENAME_LENGTH);
for i := 1 to deviceCount do begin
devName := Copy(PAnsiChar(ptrBufferOffset), 1, StrLen(PAnsiChar(ptrBufferOffset)));
deviceNames.Add(devName);
// Setup for the next one...
ptrBufferOffset := Pointer(PAnsiChar(ptrBufferOffset) + FREEOTFE_MAX_FILENAME_LENGTH);
end;
Result := True;
end;
end else begin
DebugMsg('devicelist DIOC 2 FAIL');
end;
FreeMem(ptrBuffer);
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.DrivesMounted(): String;
var
i: Integer;
driveLetters: TStringList;
deviceNames: TStringList;
begin
Result := '';
CheckActive();
driveLetters := TStringList.Create();
try
deviceNames := TStringList.Create();
try
if GetMountedDevices(driveLetters, deviceNames) then begin
for i := 0 to (driveLetters.Count - 1) do begin
if (driveLetters[i] <> '') then begin
Result := Result + driveLetters[i];
end;
end;
Result := SortString(Result);
end;
finally
deviceNames.Free();
end;
finally
driveLetters.Free();
end;
end;
// ----------------------------------------------------------------------------
// Get a list of all FreeOTFE devices which are currently mounted
// Drive letters will be added to "driveLetters", and the corresponding device
// in "deviceNames".
// If the FreeOTFE driver reports that a device is mounted, but there is no
// corresponding drive letter, then the relevant entry in "driveLetter" will
// be an empty string, instead of a drive letter.
// NOTE: THIS FUNCTION *CANNOT* CALL "GetVolumeInfo(...)"!!
// Returns TRUE/FALSE on success/failure
function TOTFEFreeOTFE.GetMountedDevices(driveLetters: TStringList;
deviceNames: TStringList): Boolean;
const
// 5 is the arbitary number of times we'll try this until we just give up on
// it...
MAX_ATTEMPTS = 5;
var
i: Integer;
driveLetter: ansichar;
driveColon: String;
foundDriveLetter: Boolean;
attempt: Integer;
flagTryAgain: Boolean;
currDeviceName: String;
queryResults: TStringList;
begin
Result := False;
CheckActive();
// flagTryAgain indicates whether the devices have changed during this
// operation; if they have, it tries it again
flagTryAgain := True;
// attempt counts the number of times the this loop was attempted
attempt := 1;
while ((flagTryAgain) and (attempt <= MAX_ATTEMPTS)) do begin
flagTryAgain := False;
driveLetters.Clear();
deviceNames.Clear();
if not (GetDiskDeviceList(deviceNames)) then begin
Inc(attempt);
flagTryAgain := True;
end;
end; // while
if (attempt <= MAX_ATTEMPTS) then begin
for i := 0 to (deviceNames.Count - 1) do begin
currDeviceName := deviceNames[i];
foundDriveLetter := False;
for driveLetter := 'A' to 'Z' do begin
driveColon := driveLetter + ':';
queryResults := TStringList.Create();
try
if (DoQueryDosDevice(driveColon, queryResults)) then begin
if (queryResults.Count >= 1) then begin
if (queryResults[0] = currDeviceName) then begin
foundDriveLetter := True;
driveLetters.Add(driveLetter);
break;
end;
end;
end;
finally
queryResults.Free();
end;
end;
if (not (foundDriveLetter)) then begin
driveLetters.Add('');
end;
end;
Result := True;
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.GetVolumeInfo(driveLetter: Char;
var volumeInfo: TOTFEFreeOTFEVolumeInfo): Boolean;
var
deviceName: String;
BytesReturned: DWORD;
inBuffer: TDIOC_DEVICE_NAME;
outBuffer: TDIOC_DISK_DEVICE_STATUS_PC_DRIVER;
tmpSectorIVGenMethod: TFreeOTFESectorIVGenMethod;
begin
Result := False;
CheckActive();
driveLetter := upcase(driveLetter);
deviceName := GetDriveDeviceName(driveLetter);
DebugMsg('deviceName: '+deviceName);
if (deviceName <> '') then begin
StrPCopy(inBuffer.DeviceName, deviceName);
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GET_DISK_DEVICE_STATUS,
@inBuffer, sizeof(inBuffer),
@outBuffer, sizeof(outBuffer),
BytesReturned, nil)) then
begin
if (BytesReturned <= sizeof(outBuffer)) then begin
volumeInfo.Filename := Copy(outBuffer.Filename, 1, StrLen(outBuffer.Filename));
volumeInfo.DeviceName :=
Copy(outBuffer.DiskDeviceName, 1, StrLen(outBuffer.DiskDeviceName));
volumeInfo.IVHashDevice :=
Copy(outBuffer.IVHashDeviceName, 1, StrLen(outBuffer.IVHashDeviceName));
volumeInfo.IVHashGUID := outBuffer.IVHashGUID;
volumeInfo.IVCypherDevice :=
Copy(outBuffer.IVCypherDeviceName, 1, StrLen(outBuffer.IVCypherDeviceName));
volumeInfo.IVCypherGUID := outBuffer.IVCypherGUID;
volumeInfo.MainCypherDevice :=
Copy(outBuffer.MainCypherDeviceName, 1, StrLen(outBuffer.MainCypherDeviceName));
volumeInfo.MainCypherGUID := outBuffer.MainCypherGUID;
volumeInfo.Mounted := outBuffer.Mounted;
volumeInfo.ReadOnly := outBuffer.ReadOnly;
volumeInfo.VolumeFlags := outBuffer.VolumeFlags;
volumeInfo.SectorIVGenMethod := foivgUnknown;
for tmpSectorIVGenMethod :=
low(TFreeOTFESectorIVGenMethod) to high(TFreeOTFESectorIVGenMethod) do begin
if (FreeOTFESectorIVGenMethodID[tmpSectorIVGenMethod] = outBuffer.SectorIVGenMethod) then
begin
volumeInfo.SectorIVGenMethod := tmpSectorIVGenMethod;
end;
end;
volumeInfo.DriveLetter := AnsiChar(driveLetter);
volumeInfo.Filename := GetUserModeVolumeFilename(volumeInfo.Filename);
Result := GetVolumeMetaData(driveLetter, outBuffer.MetaDataLength, volumeInfo.MetaData);
volumeInfo.MetaDataStructValid :=
ParseVolumeMetadata(
volumeInfo.MetaData,
volumeInfo.MetaDataStruct);
end;
end;
end;
end;
// ----------------------------------------------------------------------------
// expectedLength - Set to the amount of metadata to retrieve
function TOTFEFreeOTFE.GetVolumeMetaData(driveLetter: Char; expectedLength: Integer;
var metaData: Ansistring): Boolean;
var
deviceName: Ansistring;
bufferSize: DWORD;
BytesReturned: DWORD;
inBuffer: TDIOC_DEVICE_NAME;
ptrDIOCBuffer: PDIOC_DISK_DEVICE_METADATA;
begin
Result := False;
CheckActive();
driveLetter := upcase(driveLetter);
DebugMsg('expectedLength: '+inttostr(expectedLength));
deviceName := GetDriveDeviceName(driveLetter);
if (deviceName <> '') then begin
StrPCopy(inBuffer.DeviceName, deviceName);
bufferSize := sizeof(ptrDIOCBuffer^) - sizeof(Ansichar) +
(sizeof(Ansichar) * expectedLength);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrDIOCBuffer := allocmem(bufferSize);
try
StrPCopy(inBuffer.DeviceName, deviceName);
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GET_DISK_DEVICE_METADATA,
@inBuffer, sizeof(inBuffer),
ptrDIOCBuffer, bufferSize,
BytesReturned, nil))
then begin
if (BytesReturned <= bufferSize) then begin
// Set metaData so that it has enough characters which can be
// overwritten with StrMove
metaData := StringOfChar(Ansichar(#0), ptrDIOCBuffer.MetaDataLength);
StrMove(PAnsiChar(metaData), @ptrDIOCBuffer.MetaData, ptrDIOCBuffer.MetaDataLength);
DebugMsg('Metadata length: '+inttostr(ptrDIOCBuffer.MetaDataLength));
DebugMsgBinary(metaData);
Result := True;
end;
end;
finally
FreeMem(ptrDIOCBuffer);
end;
end;
end;
// ----------------------------------------------------------------------------
// Determine the FreeOTFE device for the specified drive letter, this may then
// be passed back to the driver
// NOTE: THIS FUNCTION *CANNOT* CALL "GetVolumeInfo(...)"!!
// Returns '' on failure
function TOTFEFreeOTFE.GetDriveDeviceName(driveLetter: Char): String;
var
mountedDriveLetters: TStringList;
deviceNames: TStringList;
i: Integer;
begin
Result := '';
CheckActive();
mountedDriveLetters := TStringList.Create();
try
deviceNames := TStringList.Create();
try
if GetMountedDevices(mountedDriveLetters, deviceNames) then begin
for i := 0 to (mountedDriveLetters.Count - 1) do begin
if (mountedDriveLetters[i] = driveLetter) then begin
Result := deviceNames[i];
break;
end;
end;
end;
finally
deviceNames.Free();
end;
finally
mountedDriveLetters.Free();
end;
end;
// ----------------------------------------------------------------------------
// Given the specified device name, return the drive mounted on that device
// NOTE: THIS FUNCTION *CANNOT* CALL "GetVolumeInfo(...)"!!
// Returns #0 on failure
function TOTFEFreeOTFE.GetDriveDeviceLetter(deviceName: String): Char;
var
mountedDriveLetters: TStringList;
deviceNames: TStringList;
i: Integer;
begin
Result := #0;
CheckActive();
mountedDriveLetters := TStringList.Create();
try
deviceNames := TStringList.Create();
try
if GetMountedDevices(mountedDriveLetters, deviceNames) then begin
for i := 0 to (mountedDriveLetters.Count - 1) do begin
if (deviceNames[i] = deviceName) then begin
Result := mountedDriveLetters[i][1];
break;
end;
end;
end;
finally
deviceNames.Free();
end;
finally
mountedDriveLetters.Free();
end;
end;
// ----------------------------------------------------------------------------
// Connects to the named device, returns a device handle, or 0 on error
function TOTFEFreeOTFE.ConnectDevice(devicename: String): THandle;
var
deviceHandle: THandle;
begin
deviceHandle := CreateFile(PChar(devicename),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING,
0);
if (deviceHandle = INVALID_HANDLE_VALUE) then begin
deviceHandle := 0;
end;
Result := deviceHandle;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.DisconnectDevice(deviceHandle: THandle): Boolean;
begin
CloseHandle(deviceHandle);
Result := True;
end;
// ----------------------------------------------------------------------------
// Create/delete DosDevices symlink; effectivly wraps DefineDosDevice(...) with
// additional support required for Vista changes
// createNotDelete - Set to TRUE to create, FALSE to delete
function TOTFEFreeOTFE.DosDeviceSymlink(
CreateNotDelete: Boolean;
DeviceName: Ansistring;
DriveLetter: DriveLetterChar;
Global: Boolean
): Boolean;
var
DIOCBuffer: TDIOC_DOS_MOUNTPOINT;
bytesReturned: DWORD;
mountpoint: Ansistring;
DIOCCode: DWORD;
driveLetterColon: WideString;
begin
Result := False;
CheckActive();
DriveLetter := upcase(DriveLetter);
// v2.00 of the FreeOTFE driver use DIOC call to create global/local version
if not (CheckVersionAtLeast(FREEOTFE_ID_v02_00_0000)) then begin
driveLetterColon := DriveLetter + ':';
if CreateNotDelete then begin
Result := DefineDosDevice(DDD_RAW_TARGET_PATH,
PWideChar(driveLetterColon),
PWideChar(deviceName));
end else begin
Result := DefineDosDevice(DDD_REMOVE_DEFINITION,
PWideChar(driveLetterColon),
nil);
end;
end else begin
mountpoint := DriveLetter + ':';
StrPCopy(DIOCBuffer.DiskDeviceName, DeviceName);
DIOCBuffer.Global := Global;
StrPCopy(DIOCBuffer.Mountpoint, mountpoint);
if CreateNotDelete then begin
DIOCCode := IOCTL_FREEOTFE_CREATE_DOS_MOUNTPOINT;
end else begin
DIOCCode := IOCTL_FREEOTFE_DELETE_DOS_MOUNTPOINT;
end;
if (DeviceIoControl(DriverHandle, DIOCCode,
@DIOCBuffer, sizeof(DIOCBuffer),
nil, 0, bytesReturned,
nil)) then begin
Result := True;
BroadcastDriveChangeMessage(CreateNotDelete, DriveLetter);
end;
end;
end;
// ----------------------------------------------------------------------------
// Delete both local and global DosDevices symlinks, as possible
function TOTFEFreeOTFE.DeleteDosDeviceSymlink(DeviceName: String; DriveLetter: Char): Boolean;
begin
Result := False;
// Note: We do ***NOT*** use
// Result := (
// DosDeviceSymlink(..., TRUE) or
// DosDeviceSymlink(..., FALSE)
// );
// here, as lazy evaluation will prevent one or the other from being
// evaluated - we want *both* to always be executed!
if DosDeviceSymlink(False, DeviceName,
DriveLetter, True) then begin
Result := True;
end;
if DosDeviceSymlink(False, DeviceName,
DriveLetter, False) then begin
Result := True;
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.DoQueryDosDevice(deviceName: Ansistring;
queryResults: TStringList): Boolean;
const
buffSizeIncrement: Integer = 1024;
var
ptrBuffer: Pointer;
ptrBufferOffset: Pointer;
dev: String;
offset: Integer;
z: Integer;
pcharDeviceName: PAnsiChar;
bufferSize: Integer;
bufferUsed: Integer;
finished: Boolean;
begin
Result := False;
bufferUsed := 0;
pcharDeviceName := PAnsiChar(deviceName);
if (deviceName = '') then begin
pcharDeviceName := nil;
end;
finished := False;
bufferSize := buffSizeIncrement;
ptrBuffer := AllocMem(bufferSize);
FillChar(ptrBuffer^, bufferSize, 'Z');
try
while (not (finished)) do begin
// Cleardown any previous error
SetLastError($FFFFFFFF);
// Here, we dereference ptrBuffer to zero the buffer's contents
bufferUsed := QueryDosDeviceA(pcharDeviceName, ptrBuffer, bufferSize);
// We need this "if" statement because Windows 2000 *will* return a partial
// buffer (set bufferUsed > 0) if the buffer is large enough to store some,
// but not all, of the information
// Windows XP will only return bufferUsed > 0 if *all* information could
// be returned (it seems)
if (GetLastError() = ERROR_INSUFFICIENT_BUFFER) then begin
FreeMem(ptrBuffer);
bufferSize := bufferSize + 1024; // Increment buffer size by 10K
ptrBuffer := AllocMem(bufferSize);
continue;
end else begin
finished := True;
end;
end;
if (bufferUsed > 0) then begin
queryResults.Clear();
offset := 0;
while (offset <= bufferUsed) do begin
ptrBufferOffset := PAnsiChar(ptrBuffer) + offset;
z := StrLen(PAnsiChar(ptrBufferOffset));
// From the help file on QueryDosDevice:
// "The final null-terminated string is followed by an additional NULL."
// i.e. if z=0, then we've done the last one; quit the loop
if (z = 0) then begin
break;
end;
dev := Copy(PAnsiChar(ptrBufferOffset), 1, z);
queryResults.add(dev);
offset := offset + length(dev) + 1;
end;
Result := True;
end;
finally
FreeMem(ptrBuffer);
end;
end;
// ----------------------------------------------------------------------------
// Given an MSDOS device name, return the device name of that device
// Returns '' on error
function TOTFEFreeOTFE.GetDeviceName(MSDOSKernelModeDeviceName: String): Ansistring;
var
deviceNames: TStringList;
deviceNameMapping: TStringList;
i, j: Integer;
begin
Result := '';
deviceNames := TStringList.Create();
try
if DoQueryDosDevice('', deviceNames) then begin
for i := 0 to (deviceNames.Count - 1) do begin
deviceNameMapping := TStringList.Create();
try
if DoQueryDosDevice(deviceNames[i], deviceNameMapping) then begin
for j := 0 to (deviceNameMapping.Count - 1) do begin
if (deviceNameMapping[j] = MSDOSKernelModeDeviceName) then begin
Result := deviceNames[i];
break;
end;
end;
// If we've found the name, exit the outer loop as well
if (Result <> '') then begin
break;
end;
end;
finally
deviceNameMapping.Free();
end;
end;
end;
finally
deviceNames.Free();
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.GetCypherDrivers(var cypherDrivers: TFreeOTFECypherDriverArray): Boolean;
var
deviceNames: TStringList;
deviceNameMapping: TStringList;
i, j: Integer;
begin
Result := True;
SetLength(cypherDrivers, 0);
deviceNames := TStringList.Create();
try
if DoQueryDosDevice('', deviceNames) then begin
for i := 0 to (deviceNames.Count - 1) do begin
deviceNameMapping := TStringList.Create();
try
if DoQueryDosDevice(deviceNames[i], deviceNameMapping) then begin
for j := 0 to (deviceNameMapping.Count - 1) do begin
if pos(DEVICE_CYPHER_DIR_NAME, deviceNameMapping[j]) > 0 then begin
// Get the details for the device
SetLength(cypherDrivers, (Length(cypherDrivers) + 1));
Result := GetCypherDriverCyphers(deviceNameMapping[j],
cypherDrivers[high(cypherDrivers)]);
// If we got the details, bang on to the next device
// Note: If we couldn't get the details, this will have the
// effect of allowing the loop to go round again, but
// this time Result will still be FALSE; if the loop
// eventually exits, then Result will *still* be false,
// signalling an error
// Note: This "break" condition differs between the DLL and kernel
// driver versions
if Result then begin
break;
end;
end;
end; // for j:=1 to (deviceNameMapping.count-1) do
end;
finally
deviceNameMapping.Free();
end;
// Propogate breakout, if Result is FALSE
if (not (Result)) then begin
break;
end;
end; // for i:=1 to (deviceNames.count-1) do
end;
finally
deviceNames.Free();
end;
end;
// ----------------------------------------------------------------------------
// Get cypher details - using FreeOTFE v3 and later API
// Don't call this function directly! Call GetCypherDriverCyphers(...) instead!
function TOTFEFreeOTFE._GetCypherDriverCyphers_v1(cypherDriver: Ansistring;
var cypherDriverDetails: TFreeOTFECypherDriver): Boolean;
var
cypherHandle: THandle;
BytesReturned: DWORD;
DIOCBuffer: TDIOC_CYPHER_IDENTIFYDRIVER;
ptrBuffer: Pointer;
ptrBufferOffset: Pointer;
DIOCBufferCyphers: PDIOC_CYPHER_IDENTIFYSUPPORTED_v1; // for debugging only
bufferSize: Cardinal;
cypherDetails: PCYPHER_v1;
i: Integer;
currCypherMode: TFreeOTFECypherMode;
arrIdx: Integer;
deviceUserModeName: Ansistring;
begin
Result := False;
if CachesGetCypherDriver(cypherDriver, cypherDriverDetails) then begin
Result := True;
end else begin
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetCypherDeviceUserModeDeviceName(cypherDriver);
DebugMsg('Connecting to: '+deviceUserModeName);
cypherHandle := ConnectDevice(deviceUserModeName);
if (cypherHandle = 0) then begin
DebugMsg('Couldn''t connect to: '+deviceUserModeName);
end else begin
if (DeviceIoControl(cypherHandle,
IOCTL_FREEOTFECYPHER_IDENTIFYDRIVER, nil,
0, @DIOCBuffer,
sizeof(DIOCBuffer), BytesReturned,
nil)) then begin
DebugMsg('_1_ supplied: '+inttostr(sizeof(DIOCBuffer))+' used: '+inttostr(BytesReturned));
if BytesReturned = sizeof(DIOCBuffer) then begin
cypherDriverDetails.DriverGUID := DIOCBuffer.DriverGUID;
cypherDriverDetails.DeviceName := GetDeviceName(cypherDriver);
cypherDriverDetails.LibFNOrDevKnlMdeName := cypherDriver;
cypherDriverDetails.DeviceUserModeName := DeviceUserModeName;
cypherDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title));
cypherDriverDetails.VersionID := DIOCBuffer.VersionID;
cypherDriverDetails.CypherCount := DIOCBuffer.CypherCount;
bufferSize := sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v1) -
sizeof(cypherDetails^) +
(sizeof(cypherDetails^) * cypherDriverDetails.CypherCount);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrBuffer := allocmem(bufferSize);
SetLength(cypherDriverDetails.Cyphers, cypherDriverDetails.CypherCount);
if (DeviceIoControl(cypherHandle,
IOCTL_FREEOTFECYPHER_IDENTIFYSUPPORTED_v1,
nil, 0, ptrBuffer,
bufferSize, BytesReturned,
nil)) then begin
DebugMsg('_2_ supplied: '+inttostr(bufferSize)+' used: '+inttostr(BytesReturned));
if BytesReturned <= bufferSize then begin
DIOCBufferCyphers := (PDIOC_CYPHER_IDENTIFYSUPPORTED_v1(ptrBuffer));
DebugMsg('cypher details count: '+inttostr(DIOCBufferCyphers.BufCount));
ptrBufferOffset :=
Pointer(PAnsiChar(ptrBuffer) +
sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v1) -
sizeof(
cypherDetails^));
arrIdx := low(cypherDriverDetails.Cyphers);
for i := 1 to cypherDriverDetails.CypherCount do begin
cypherDetails := (PCYPHER_v1(ptrBufferOffset));
cypherDriverDetails.Cyphers[arrIdx].CypherGUID := cypherDetails.CypherGUID;
cypherDriverDetails.Cyphers[arrIdx].Title :=
Copy(cypherDetails.Title, 1, StrLen(cypherDetails.Title));
// Failsafe to "unknown"
cypherDriverDetails.Cyphers[arrIdx].Mode := focmUnknown;
for currCypherMode := low(FreeOTFECypherModeID) to high(FreeOTFECypherModeID) do
begin
if (cypherDetails.Mode = FreeOTFECypherModeID[currCypherMode]) then begin
cypherDriverDetails.Cyphers[arrIdx].Mode := currCypherMode;
end;
end;
cypherDriverDetails.Cyphers[arrIdx].KeySizeUnderlying :=
cypherDetails.KeySizeUnderlying;
cypherDriverDetails.Cyphers[arrIdx].BlockSize := cypherDetails.BlockSize;
cypherDriverDetails.Cyphers[arrIdx].VersionID := cypherDetails.VersionID;
cypherDriverDetails.Cyphers[arrIdx].KeySizeRequired :=
cypherDetails.KeySizeUnderlying;
// Setup for the next one...
ptrBufferOffset :=
Pointer(PAnsiChar(ptrBufferOffset) +
sizeof(
cypherDetails^));
Inc(arrIdx);
end;
// Cache the information retrieved
CachesAddCypherDriver(cypherDriver, cypherDriverDetails);
Result := True;
end;
end else begin
DebugMsg('getcypherdrivers DIOC 2 FAIL');
end;
FreeMem(ptrBuffer);
end;
end;
DisconnectDevice(cypherHandle);
end;
end; // if CachesGetCypherDriver(cypherKernelModeDeviceName, cypherDriverDetails) then
DebugMsg('Exiting function...');
end;
// ----------------------------------------------------------------------------
// Get cypher details - using FreeOTFE v3 and later API
// Don't call this function directly! Call GetCypherDriverCyphers(...) instead!
function TOTFEFreeOTFE._GetCypherDriverCyphers_v3(cypherDriver: Ansistring;
var cypherDriverDetails: TFreeOTFECypherDriver): Boolean;
var
cypherHandle: THandle;
BytesReturned: DWORD;
DIOCBuffer: TDIOC_CYPHER_IDENTIFYDRIVER;
ptrBuffer: Pointer;
ptrBufferOffset: Pointer;
DIOCBufferCyphers: PDIOC_CYPHER_IDENTIFYSUPPORTED_v3;// for debugging only
bufferSize: Cardinal;
cypherDetails: PCYPHER_v3;
i: Integer;
currCypherMode: TFreeOTFECypherMode;
arrIdx: Integer;
deviceUserModeName: Ansistring;
begin
Result := False;
if CachesGetCypherDriver(cypherDriver, cypherDriverDetails) then begin
Result := True;
end else begin
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetCypherDeviceUserModeDeviceName(cypherDriver);
DebugMsg('Connecting to: '+deviceUserModeName);
cypherHandle := ConnectDevice(deviceUserModeName);
if (cypherHandle = 0) then begin
DebugMsg('Couldn''t connect to: '+deviceUserModeName);
end else begin
if (DeviceIoControl(cypherHandle,
IOCTL_FREEOTFECYPHER_IDENTIFYDRIVER, nil,
0, @DIOCBuffer,
sizeof(DIOCBuffer), BytesReturned,
nil)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_1_ supplied: '+inttostr(sizeof(DIOCBuffer))+' used: '+inttostr(BytesReturned));
{$ENDIF}
if BytesReturned = sizeof(DIOCBuffer) then begin
cypherDriverDetails.DriverGUID := DIOCBuffer.DriverGUID;
cypherDriverDetails.DeviceName := GetDeviceName(cypherDriver);
cypherDriverDetails.LibFNOrDevKnlMdeName := cypherDriver;
cypherDriverDetails.DeviceUserModeName := DeviceUserModeName;
cypherDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title));
cypherDriverDetails.VersionID := DIOCBuffer.VersionID;
cypherDriverDetails.CypherCount := DIOCBuffer.CypherCount;
bufferSize := sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v3) -
sizeof(cypherDetails^) +
(sizeof(cypherDetails^) * cypherDriverDetails.CypherCount);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrBuffer := allocmem(bufferSize);
SetLength(cypherDriverDetails.Cyphers, cypherDriverDetails.CypherCount);
if (DeviceIoControl(cypherHandle,
IOCTL_FREEOTFECYPHER_IDENTIFYSUPPORTED_v3,
nil, 0, ptrBuffer,
bufferSize, BytesReturned,
nil)) then begin
DebugMsg('_2_ supplied: '+inttostr(bufferSize)+' used: '+inttostr(BytesReturned));
if BytesReturned <= bufferSize then begin
DIOCBufferCyphers := (PDIOC_CYPHER_IDENTIFYSUPPORTED_v3(ptrBuffer));
DebugMsg('cypher details count: '+inttostr(DIOCBufferCyphers.BufCount));
ptrBufferOffset :=
Pointer(PAnsiChar(ptrBuffer) +
sizeof(TDIOC_CYPHER_IDENTIFYSUPPORTED_v3) -
sizeof(
cypherDetails^));
arrIdx := low(cypherDriverDetails.Cyphers);
for i := 1 to cypherDriverDetails.CypherCount do begin
cypherDetails := (PCYPHER_v3(ptrBufferOffset));
cypherDriverDetails.Cyphers[arrIdx].CypherGUID := cypherDetails.CypherGUID;
cypherDriverDetails.Cyphers[arrIdx].Title :=
Copy(cypherDetails.Title, 1, StrLen(cypherDetails.Title));
// Failsafe to "unknown"
cypherDriverDetails.Cyphers[arrIdx].Mode := focmUnknown;
for currCypherMode := low(FreeOTFECypherModeID) to high(FreeOTFECypherModeID) do
begin
if (cypherDetails.Mode = FreeOTFECypherModeID[currCypherMode]) then begin
cypherDriverDetails.Cyphers[arrIdx].Mode := currCypherMode;
end;
end;
cypherDriverDetails.Cyphers[arrIdx].KeySizeRequired :=
cypherDetails.KeySizeRequired;
cypherDriverDetails.Cyphers[arrIdx].KeySizeUnderlying :=
cypherDetails.KeySizeUnderlying;
cypherDriverDetails.Cyphers[arrIdx].BlockSize := cypherDetails.BlockSize;
cypherDriverDetails.Cyphers[arrIdx].VersionID := cypherDetails.VersionID;
// Setup for the next one...
ptrBufferOffset :=
Pointer(PAnsiChar(ptrBufferOffset) +
sizeof(
cypherDetails^));
Inc(arrIdx);
end;
// Cache the information retrieved
CachesAddCypherDriver(cypherDriver, cypherDriverDetails);
Result := True;
end;
end else begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('getcypherdrivers DIOC 2 FAIL');
{$ENDIF}
end;
FreeMem(ptrBuffer);
end;
end;
DisconnectDevice(cypherHandle);
end;
end; // if CachesGetCypherDriver(cypherKernelModeDeviceName, cypherDriverDetails) then
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Exiting function...');
{$ENDIF}
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.GetHashDrivers(var hashDrivers: TFreeOTFEHashDriverArray): Boolean;
var
deviceNames: TStringList;
deviceNameMapping: TStringList;
i, j: Integer;
begin
Result := True;
SetLength(hashDrivers, 0);
deviceNames := TStringList.Create();
try
if DoQueryDosDevice('', deviceNames) then begin
for i := 0 to (deviceNames.Count - 1) do begin
deviceNameMapping := TStringList.Create();
try
if DoQueryDosDevice(deviceNames[i], deviceNameMapping) then begin
for j := 0 to (deviceNameMapping.Count - 1) do begin
if pos(DEVICE_HASH_DIR_NAME, deviceNameMapping[j]) > 0 then begin
// Get the details for the device
SetLength(hashDrivers, (Length(hashDrivers) + 1));
Result := GetHashDriverHashes(deviceNameMapping[j],
hashDrivers[high(hashDrivers)]);
// If we got the details, bang on to the next device
// Note: If we couldn't get the details, this will have the
// effect of allowing the loop to go round again, but
// this time Result will still be FALSE; if the loop
// eventually exits, then Result will *still* be false,
// signalling an error
// Note: This "break" condition differs between the DLL and kernel
// driver versions
if Result then begin
break;
end;
end;
end; // for j:=1 to (deviceNameMapping.count-1) do
end;
finally
deviceNameMapping.Free();
end;
// Propogate breakout, if Result is FALSE
if (not (Result)) then begin
break;
end;
end; // for i:=1 to (deviceNames.count-1) do
end;
finally
deviceNames.Free();
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.GetHashDriverHashes(hashDriver: Ansistring;
var hashDriverDetails: TFreeOTFEHashDriver): Boolean;
var
hashHandle: THandle;
BytesReturned: DWORD;
DIOCBuffer: TDIOC_HASH_IDENTIFYDRIVER;
ptrBuffer: Pointer;
ptrBufferOffset: Pointer;
{$IFDEF FREEOTFE_DEBUG}
DIOCBufferHashes: PDIOC_HASH_IDENTIFYSUPPORTED;
{$ENDIF}
bufferSize: Cardinal;
hashDetails: PHASH;
i: Integer;
arrIdx: Integer;
deviceUserModeName: Ansistring;
begin
Result := False;
if CachesGetHashDriver(hashDriver, hashDriverDetails) then begin
Result := True;
end else begin
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetHashDeviceUserModeDeviceName(hashDriver);
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Connecting to: '+deviceUserModeName);
{$ENDIF}
hashHandle := ConnectDevice(deviceUserModeName);
if (hashHandle = 0) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Couldn''t connect to: '+deviceUserModeName);
{$ENDIF}
end else begin
if (DeviceIoControl(hashHandle,
IOCTL_FREEOTFEHASH_IDENTIFYDRIVER, nil,
0, @DIOCBuffer,
sizeof(DIOCBuffer), BytesReturned,
nil)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_3_ supplied: '+inttostr(sizeof(DIOCBuffer))+' used: '+inttostr(BytesReturned));
{$ENDIF}
if BytesReturned = sizeof(DIOCBuffer) then begin
hashDriverDetails.DriverGUID := DIOCBuffer.DriverGUID;
hashDriverDetails.DeviceName := GetDeviceName(hashDriver);
hashDriverDetails.LibFNOrDevKnlMdeName := hashDriver;
hashDriverDetails.DeviceUserModeName := DeviceUserModeName;
hashDriverDetails.Title := Copy(DIOCBuffer.Title, 1, StrLen(DIOCBuffer.Title));
hashDriverDetails.VersionID := DIOCBuffer.VersionID;
hashDriverDetails.HashCount := DIOCBuffer.HashCount;
bufferSize := sizeof(TDIOC_HASH_IDENTIFYSUPPORTED) -
sizeof(hashDetails^) + (sizeof(hashDetails^) *
hashDriverDetails.HashCount);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrBuffer := allocmem(bufferSize);
SetLength(hashDriverDetails.Hashes, hashDriverDetails.HashCount);
if (DeviceIoControl(hashHandle,
IOCTL_FREEOTFEHASH_IDENTIFYSUPPORTED,
nil, 0,
ptrBuffer, bufferSize,
BytesReturned, nil
)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_4_ supplied: '+inttostr(bufferSize)+' used: '+inttostr(BytesReturned));
{$ENDIF}
if (BytesReturned <= bufferSize) then begin
{$IFDEF FREEOTFE_DEBUG}
DIOCBufferHashes := (PDIOC_HASH_IDENTIFYSUPPORTED(ptrBuffer));
DebugMsg('hash details count: '+inttostr(DIOCBufferHashes.BufCount));
{$ENDIF}
ptrBufferOffset := Pointer(PAnsiChar(ptrBuffer) +
sizeof(TDIOC_HASH_IDENTIFYSUPPORTED) -
sizeof(hashDetails^));
arrIdx := low(hashDriverDetails.Hashes);
for i := 1 to hashDriverDetails.HashCount do begin
hashDetails := (PHASH(ptrBufferOffset));
hashDriverDetails.Hashes[arrIdx].HashGUID := hashDetails.HashGUID;
hashDriverDetails.Hashes[arrIdx].Title :=
Copy(hashDetails.Title, 1, StrLen(hashDetails.Title));
hashDriverDetails.Hashes[arrIdx].VersionID := hashDetails.VersionID;
hashDriverDetails.Hashes[arrIdx].Length := hashDetails.Length;
hashDriverDetails.Hashes[arrIdx].BlockSize := hashDetails.BlockSize;
// Setup for the next one...
ptrBufferOffset := Pointer(PAnsiChar(ptrBufferOffset) + sizeof(hashDetails^));
Inc(arrIdx);
end;
// Cache the information retrieved
CachesAddHashDriver(hashDriver, hashDriverDetails);
Result := True;
end;
end else begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('gethashdrivers DIOC 2 FAIL');
{$ENDIF}
end;
FreeMem(ptrBuffer);
end;
end;
DisconnectDevice(hashHandle);
end;
end; // if CachesGetHashDriver(driver, hashDriverDetails) then
end;
// ----------------------------------------------------------------------------
// Convert kernel mode device name to user mode device name
function TOTFEFreeOTFE.GetHashDeviceUserModeDeviceName(hashKernelModeDeviceName: String): String;
var
deviceUserModeName: String;
begin
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := hashKernelModeDeviceName;
// Lose the prefix
Delete(deviceUserModeName, 1, length(DEVICE_HASH_DIR_NAME));
// Trim off the leading "\"
Delete(deviceUserModeName, 1, 1);
// Tack on the dosdevice root
deviceUserModeName := DEVICE_HASH_SYMLINK_PREFIX + deviceUserModeName;
Result := deviceUserModeName;
end;
// ----------------------------------------------------------------------------
// Convert kernel mode device name to user mode device name
function TOTFEFreeOTFE.GetCypherDeviceUserModeDeviceName(cypherKernelModeDeviceName:
String): String;
var
deviceUserModeName: String;
begin
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := cypherKernelModeDeviceName;
// Lose the prefix
Delete(deviceUserModeName, 1, length(DEVICE_CYPHER_DIR_NAME));
// Trim off the leading "\"
Delete(deviceUserModeName, 1, 1);
// Tack on the dosdevice root
deviceUserModeName := DEVICE_CYPHER_SYMLINK_PREFIX + deviceUserModeName;
Result := deviceUserModeName;
end;
// ----------------------------------------------------------------------------
// Hash the specified data with the supplied hash device/hash GUID
function TOTFEFreeOTFE.HashData(
hashDriver: Ansistring;
hashGUID: TGUID;
const data: TSDUBytes;
out hashOut: TSDUBytes
): Boolean;
var
hashHandle: THandle;
BytesReturned: DWORD;
ptrDIOCBufferIn: PDIOC_HASH_DATA_IN;
bufferSizeIn: DWORD;
ptrDIOCBufferOut: PDIOC_HASH_DATA_OUT;
bufferSizeOut: DWORD;
hashDetails: TFreeOTFEHash;
deviceUserModeName: String;
hashByteCount: Integer;
expectedHashSizeBits: Integer; // In *bits*
begin
LastErrorCode := OTFE_ERR_SUCCESS;
Result := False;
CheckActive();
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetHashDeviceUserModeDeviceName(hashDriver);
if GetSpecificHashDetails(hashDriver, hashGUID, hashDetails) then begin
hashHandle := ConnectDevice(deviceUserModeName);
if (hashHandle = 0) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('couldn''t connect to: '+deviceUserModeName);
{$ENDIF}
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
end else begin
bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(Byte) + Length(Data);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY));
ptrDIOCBufferIn := allocmem(bufferSizeIn);
try
// Just make sure its big enough
expectedHashSizeBits := hashDetails.Length;
if (hashDetails.Length = -1) then begin
expectedHashSizeBits := (Length(Data) * 8);
end;
bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(Byte) + (expectedHashSizeBits div 8);
ptrDIOCBufferOut := allocmem(bufferSizeOut);
try
ptrDIOCBufferIn.HashGUID := hashGUID;
ptrDIOCBufferIn.DataLength := Length(Data) * 8;
StrMove(@ptrDIOCBufferIn.Data, PAnsiChar(Data), Length(Data));
if (DeviceIoControl(hashHandle,
IOCTL_FREEOTFEHASH_HASHDATA,
ptrDIOCBufferIn, bufferSizeIn,
ptrDIOCBufferOut, bufferSizeOut,
BytesReturned, nil
)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_5_ supplied: '+inttostr(bufferSizeOut)+' used: '+inttostr(BytesReturned));
{$ENDIF}
if (BytesReturned <= bufferSizeOut) then begin
hashByteCount := (ptrDIOCBufferOut.HashLength div 8);
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('hashByteCount: '+inttostr(hashByteCount));
{$ENDIF}
// Set hashOut so that it has enough characters which can be
// overwritten with StrMove
SDUInitAndZeroBuffer(hashByteCount, hashOut);
// hashOut := StringOfChar(#0, hashByteCount);
StrMove(PAnsiChar(hashOut), @ptrDIOCBufferOut.Hash, hashByteCount);
Result := True;
end else begin
LastErrorCode := OTFE_ERR_HASH_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('incorrect bytecount returned');
{$ENDIF}
end;
end else begin
LastErrorCode := OTFE_ERR_HASH_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('hash DIOC 2 FAIL');
{$ENDIF}
end;
finally
FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0);
FreeMem(ptrDIOCBufferOut);
end;
finally
FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0);
FreeMem(ptrDIOCBufferIn);
end;
DisconnectDevice(hashHandle);
end;
end else begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Unable to GetSpecificHashDetails');
{$ENDIF}
end; // ELSE PART - if GetSpecificHashDetails(hashKernelModeDeviceName, hashGUID, hashDetails) then
end;
// ----------------------------------------------------------------------------
// Generate MAC of data using hash driver/encryption driver identified
// Note: "tBits" is in *bits* not *bytes*
// tBits - Set the the number of bits to return; set to -ve value for no
// truncation/padding
// If tBits is larger than the number of bits the MAC would normally
// be, then the MAC will be right-padded with NULLs
// If tBits is set to a -ve number, then this function will return
// an MAC of variable length
function TOTFEFreeOTFE.MACData(
macAlgorithm: TFreeOTFEMACAlgorithm;
HashDriver: Ansistring;
HashGUID: TGUID;
CypherDriver: Ansistring;
CypherGUID: TGUID;
var key: PasswordString;
var data: Ansistring;
var MACOut: Ansistring;
tBits: Integer = -1
): Boolean;
var
BytesReturned: DWORD;
ptrDIOCBufferIn: PDIOC_GENERATE_MAC_IN_PC_DRIVER;
bufferSizeIn: DWORD;
ptrDIOCBufferOut: PDIOC_GENERATE_MAC_OUT;
bufferSizeOut: DWORD;
outputByteCount: Integer;
tmpSizeBytes: Integer;
minBufferSizeOut: Integer;
begin
LastErrorCode := OTFE_ERR_SUCCESS;
Result := False;
CheckActive();
bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Key) +
Length(key) - sizeof(ptrDIOCBufferIn^.Data) +
Length(data);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY));
ptrDIOCBufferIn := allocmem(bufferSizeIn);
try
// We use the maximum buffer possible, as the full DK length depends on
// the algorithm, hash, etc
tmpSizeBytes := (max(MAX_MAC_LENGTH, tBits) div 8); // Convert to bytes
minBufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.MAC);
bufferSizeOut := minBufferSizeOut + tmpSizeBytes;
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeOut := bufferSizeOut + (DIOC_BOUNDRY - (bufferSizeOut mod DIOC_BOUNDRY));
ptrDIOCBufferOut := allocmem(bufferSizeOut);
try
ptrDIOCBufferIn.MACAlgorithm := FreeOTFEMACID[macAlgorithm];
StrPCopy(ptrDIOCBufferIn.HashDeviceName, HashDriver);
ptrDIOCBufferIn.HashGUID := HashGUID;
StrPCopy(ptrDIOCBufferIn.CypherDeviceName, CypherDriver);
ptrDIOCBufferIn.CypherGUID := CypherGUID;
ptrDIOCBufferIn.LengthWanted := tBits;
ptrDIOCBufferIn.KeyLength := Length(key) * 8;
ptrDIOCBufferIn.DataLength := Length(data) * 8;
// This may seem a little weird, but we do this because the data is
// immediatly after the key
StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key), Length(key));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key)) + length(key)), PAnsiChar(data), Length(data));
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GENERATE_MAC, ptrDIOCBufferIn,
bufferSizeIn, ptrDIOCBufferOut,
bufferSizeOut, BytesReturned,
nil)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('MAC out buffer supplied: '+inttostr(bufferSizeOut)+'; DIOC call used: '+inttostr(BytesReturned)+'; min: '+inttostr(minBufferSizeOut));
{$ENDIF}
if ((BytesReturned >= DWORD(minBufferSizeOut)) and
(BytesReturned <= DWORD(bufferSizeOut))) then begin
outputByteCount := (ptrDIOCBufferOut.MACLength div 8);
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('outputByteCount: '+inttostr(outputByteCount));
{$ENDIF}
// Set MACOut so that it has enough characters which can be
// overwritten with StrMove
MACOut := StringOfChar(#0, outputByteCount);
StrMove(PAnsiChar(MACOut), @ptrDIOCBufferOut.MAC, outputByteCount);
Result := True;
end else begin
LastErrorCode := OTFE_ERR_MAC_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('incorrect bytecount returned');
{$ENDIF}
end;
end else begin
LastErrorCode := OTFE_ERR_MAC_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('MAC DIOC 2 FAIL');
{$ENDIF}
end;
finally
FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0);
FreeMem(ptrDIOCBufferOut);
end;
finally
FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0);
FreeMem(ptrDIOCBufferIn);
end;
end;
// ----------------------------------------------------------------------------
// dkLenBits - This must *always* be >= 0
function TOTFEFreeOTFE.DeriveKey(
kdfAlgorithm: TFreeOTFEKDFAlgorithm;
HashDriver: Ansistring;
HashGUID: TGUID;
CypherDriver: Ansistring;
CypherGUID: TGUID;
Password: TSDUBytes;
Salt: array of Byte;
Iterations: Integer;
dkLenBits: Integer; // In *bits*
out DK: TSDUBytes
): Boolean;
var
BytesReturned: DWORD;
ptrDIOCBufferIn: PDIOC_DERIVE_KEY_IN_PC_DRIVER;
bufferSizeIn: DWORD;
ptrDIOCBufferOut: PDIOC_DERIVE_KEY_OUT;
bufferSizeOut: DWORD;
outputByteCount: Integer;
tmpSizeBytes: Integer;
minBufferSizeOut: Integer;
begin
DebugMsg('DeriveKey:');
DebugMsg(IntToStr(ord(kdfAlgorithm)));
DebugMsg(HashDriver);
DebugMsg(HashGUID);
DebugMsg(CypherDriver);
DebugMsg(CypherGUID);
DebugMsg(Password);
DebugMsg(Salt);
DebugMsg(Iterations);
DebugMsg(dkLenBits);
LastErrorCode := OTFE_ERR_SUCCESS;
Result := False;
CheckActive();
bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(ptrDIOCBufferIn^.Password) +
Length(Password) - sizeof(ptrDIOCBufferIn^.Salt) +
Length(Salt);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY));
ptrDIOCBufferIn := allocmem(bufferSizeIn);
try
// We use the maximum buffer possible, as the full MAC length depends on
// the MAC, hash, etc
tmpSizeBytes := (max(MAX_DERIVED_KEY_LENGTH, dkLenBits) div 8); // Convert to bytes
minBufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.DerivedKey);
bufferSizeOut := minBufferSizeOut + tmpSizeBytes;
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeOut := bufferSizeOut + (DIOC_BOUNDRY - (bufferSizeOut mod DIOC_BOUNDRY));
ptrDIOCBufferOut := allocmem(bufferSizeOut);
try
ptrDIOCBufferIn.KDFAlgorithm := FreeOTFEKDFID[kdfAlgorithm];
StrPCopy(ptrDIOCBufferIn.HashDeviceName, HashDriver);
ptrDIOCBufferIn.HashGUID := HashGUID;
StrPCopy(ptrDIOCBufferIn.CypherDeviceName, CypherDriver);
ptrDIOCBufferIn.CypherGUID := CypherGUID;
ptrDIOCBufferIn.Iterations := Iterations;
ptrDIOCBufferIn.LengthWanted := dkLenBits;
ptrDIOCBufferIn.PasswordLength := (Length(Password) * 8);
ptrDIOCBufferIn.SaltLength := (Length(Salt) * 8);
// This may seem a little weird, but we do this because the salt is
// immediatly after the password
StrMove(@ptrDIOCBufferIn.Password, PAnsiChar(Password), Length(Password));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Password)) + length(Password)),
PAnsiChar(@Salt[0]), Length(Salt));
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_DERIVE_KEY, ptrDIOCBufferIn,
bufferSizeIn, ptrDIOCBufferOut,
bufferSizeOut, BytesReturned,
nil)) then begin
DebugMsg('MAC out buffer supplied: '+inttostr(bufferSizeOut)+'; DIOC call used: '+inttostr(BytesReturned)+'; min: '+inttostr(minBufferSizeOut));
if ((BytesReturned >= DWORD(minBufferSizeOut)) and
(BytesReturned <= DWORD(bufferSizeOut))) then begin
outputByteCount := (ptrDIOCBufferOut.DerivedKeyLength div 8);
DebugMsg('outputByteCount: '+inttostr(outputByteCount));
// Set DK so that it has enough characters which can be
// overwritten with StrMove
SDUInitAndZeroBuffer(outputByteCount, DK);
// DK := StringOfChar(#0, outputByteCount);
StrMove(PAnsiChar(DK), @ptrDIOCBufferOut.DerivedKey, outputByteCount);
Result := True;
end else begin
LastErrorCode := OTFE_ERR_KDF_FAILURE;
DebugMsg('incorrect bytecount returned');
end;
end else begin
LastErrorCode := OTFE_ERR_KDF_FAILURE;
DebugMsg('MAC DIOC 2 FAIL');
end;
finally
FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0);
FreeMem(ptrDIOCBufferOut);
end;
finally
FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0);
FreeMem(ptrDIOCBufferIn);
end;
DebugMsg(DK);
end;
// ----------------------------------------------------------------------------
// encryptFlag - set to TRUE to encrypt, FALSE to decrypt
function TOTFEFreeOTFE._EncryptDecryptData(
encryptFlag: Boolean;
cypherDriver: Ansistring;
cypherGUID: TGUID;
var key: TSDUBytes;
var IV: Ansistring;
var inData: Ansistring;
var outData: Ansistring
): Boolean;
var
cypherHandle: THandle;
BytesReturned: DWORD;
ptrDIOCBufferIn: PDIOC_CYPHER_DATA_IN;
bufferSizeIn: DWORD;
ptrDIOCBufferOut: PDIOC_CYPHER_DATA_OUT;
bufferSizeOut: DWORD;
cypherDetails: TFreeOTFECypher_v3;
deviceUserModeName: String;
dwIoControlCode: DWORD;
begin
LastErrorCode := OTFE_ERR_SUCCESS;
Result := False;
CheckActive();
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetCypherDeviceUserModeDeviceName(cypherDriver);
if GetSpecificCypherDetails(cypherDriver, cypherGUID, cypherDetails) then begin
cypherHandle := ConnectDevice(deviceUserModeName);
if (cypherHandle = 0) then begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('couldn''t connect to: '+deviceUserModeName);
{$ENDIF}
end else begin
dwIoControlCode := IOCTL_FREEOTFECYPHER_DECRYPT;
if encryptFlag then begin
dwIoControlCode := IOCTL_FREEOTFECYPHER_ENCRYPT;
end;
bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(
ptrDIOCBufferIn^.Key) + Length(key) -
sizeof(ptrDIOCBufferIn^.IV) + Length(IV) -
sizeof(ptrDIOCBufferIn^.Data) + Length(inData);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY));
ptrDIOCBufferIn := allocmem(bufferSizeIn);
try
// Just make sure its big enough
bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.Data) +
Length(inData);
ptrDIOCBufferOut := allocmem(bufferSizeOut);
try
ptrDIOCBufferIn.CypherGUID := cypherGUID;
ptrDIOCBufferIn.KeyLength := (Length(key) * 8); // In *bits*
ptrDIOCBufferIn.IVLength := (Length(IV) * 8); // In *bits*
ptrDIOCBufferIn.DataLength := Length(inData); // In *bytes*
// This may seem a little weird, but we do this because the data is
// immediatly after the IV, which is immediatly after the key
StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key),
Length(key));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key)) + length(key)),
PAnsiChar(IV), Length(IV));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key)) + length(key) + length(IV)),
PAnsiChar(inData), Length(inData));
if (DeviceIoControl(cypherHandle,
dwIoControlCode, ptrDIOCBufferIn,
bufferSizeIn, ptrDIOCBufferOut,
bufferSizeOut, BytesReturned,
nil)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_6_ supplied: '+inttostr(bufferSizeOut)+' used: '+inttostr(BytesReturned));
{$ENDIF}
if (BytesReturned <= bufferSizeOut) then begin
// Set outData so that it has enough characters which can be
// overwritten with StrMove
outData := StringOfChar(#0, BytesReturned);
StrMove(PAnsiChar(outData), @ptrDIOCBufferOut.Data, BytesReturned);
Result := True;
end else begin
LastErrorCode := OTFE_ERR_CYPHER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('incorrect bytecount returned');
{$ENDIF}
end;
end else begin
LastErrorCode := OTFE_ERR_CYPHER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('cypher DIOC 2 FAIL');
{$ENDIF}
end;
finally
FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0);
FreeMem(ptrDIOCBufferOut);
end;
finally
FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0);
FreeMem(ptrDIOCBufferIn);
end;
DisconnectDevice(cypherHandle);
end;
end else begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Unable to EncryptDecryptData');
{$ENDIF}
end;
end;
// ----------------------------------------------------------------------------
// encryptFlag - set to TRUE to encrypt, FALSE to decrypt
function TOTFEFreeOTFE.EncryptDecryptSectorData(
encryptFlag: Boolean;
cypherDriver: Ansistring;
cypherGUID: TGUID;
SectorID: LARGE_INTEGER;
SectorSize: Integer;
var key: TSDUBytes;
var IV: Ansistring;
var inData: Ansistring;
var outData: Ansistring
): Boolean;
var
cypherHandle: THandle;
BytesReturned: DWORD;
ptrDIOCBufferIn: PDIOC_CYPHER_SECTOR_DATA_IN;
bufferSizeIn: DWORD;
ptrDIOCBufferOut: PDIOC_CYPHER_DATA_OUT;
bufferSizeOut: DWORD;
cypherDetails: TFreeOTFECypher_v3;
deviceUserModeName: String;
dwIoControlCode: DWORD;
begin
LastErrorCode := OTFE_ERR_SUCCESS;
Result := False;
CheckActive();
// Determine the user mode MSDOS device name from the kernel mode device name
deviceUserModeName := GetCypherDeviceUserModeDeviceName(cypherDriver);
if GetSpecificCypherDetails(cypherDriver, cypherGUID, cypherDetails) then begin
cypherHandle := ConnectDevice(deviceUserModeName);
if (cypherHandle = 0) then begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('couldn''t connect to: '+deviceUserModeName);
{$ENDIF}
end else begin
dwIoControlCode := IOCTL_FREEOTFECYPHER_DECRYPTSECTOR;
if encryptFlag then begin
dwIoControlCode := IOCTL_FREEOTFECYPHER_ENCRYPTSECTOR;
end;
bufferSizeIn := sizeof(ptrDIOCBufferIn^) - sizeof(
ptrDIOCBufferIn^.Key) + Length(key) -
sizeof(ptrDIOCBufferIn^.IV) + Length(IV) -
sizeof(ptrDIOCBufferIn^.Data) + Length(inData);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSizeIn := bufferSizeIn + (DIOC_BOUNDRY - (bufferSizeIn mod DIOC_BOUNDRY));
ptrDIOCBufferIn := allocmem(bufferSizeIn);
try
// Just make sure its big enough
bufferSizeOut := sizeof(ptrDIOCBufferOut^) - sizeof(ptrDIOCBufferOut^.Data) +
Length(inData);
ptrDIOCBufferOut := allocmem(bufferSizeOut);
try
ptrDIOCBufferIn.CypherGUID := cypherGUID;
ptrDIOCBufferIn.SectorID := SectorID;
ptrDIOCBufferIn.SectorSize := SectorSize;
ptrDIOCBufferIn.KeyLength := (Length(key) * 8); // In *bits*
ptrDIOCBufferIn.IVLength := (Length(IV) * 8); // In *bits*
ptrDIOCBufferIn.DataLength := Length(inData); // In *bytes*
// This may seem a little weird, but we do this because the data is
// immediatly after the IV, which is immediately after the key
StrMove(@ptrDIOCBufferIn.Key, PAnsiChar(key),
Length(key));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key)) + length(key)),
PAnsiChar(IV), Length(IV));
StrMove(((PAnsiChar(@ptrDIOCBufferIn.Key)) + length(key) + length(IV)),
PAnsiChar(inData), Length(inData));
if (DeviceIoControl(cypherHandle,
dwIoControlCode, ptrDIOCBufferIn,
bufferSizeIn, ptrDIOCBufferOut,
bufferSizeOut, BytesReturned,
nil)) then begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('_6_ supplied: '+inttostr(bufferSizeOut)+' used: '+inttostr(BytesReturned));
{$ENDIF}
if (BytesReturned <= bufferSizeOut) then begin
// Set outData so that it has enough characters which can be
// overwritten with StrMove
outData := StringOfChar(#0, BytesReturned);
StrMove(PAnsiChar(outData), @ptrDIOCBufferOut.Data, BytesReturned);
Result := True;
end else begin
LastErrorCode := OTFE_ERR_CYPHER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('incorrect bytecount returned');
{$ENDIF}
end;
end else begin
LastErrorCode := OTFE_ERR_CYPHER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('cypher DIOC 2 FAIL');
{$ENDIF}
end;
finally
FillChar(ptrDIOCBufferOut^, bufferSizeOut, 0);
FreeMem(ptrDIOCBufferOut);
end;
finally
FillChar(ptrDIOCBufferIn^, bufferSizeIn, 0);
FreeMem(ptrDIOCBufferIn);
end;
DisconnectDevice(cypherHandle);
end;
// If there was a problem, fallback to using v1 cypher API
if not (Result) then begin
Result := _EncryptDecryptData(encryptFlag,
cypherDriver, cypherGUID,
key, IV,
inData, outData
);
end;
end else begin
LastErrorCode := OTFE_ERR_DRIVER_FAILURE;
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Unable to EncryptDecryptData');
{$ENDIF}
end;
end;
// ----------------------------------------------------------------------------
// Identify the next drive letter to mount a volume as
// i.e. If userDriveLetter is not set to #0, then return either that letter, or
// the next free drive letter.
// If userDriveLetter is set to #0, then use requiredDriveLetter instead
// of userDriveLetter
// userDriveLetter - The drive letter the user has specifically requested
// requiredDriveLetter - The drive letter the system would normally use
// Returns: Drive letter to mount as, or #0 on error
function TOTFEFreeOTFE.GetNextDriveLetter(userDriveLetter, requiredDriveLetter: Char): Char;
var
freeDriveLetters: String;
searchDriveLetter: Char;
begin
Result := #0;
searchDriveLetter := userDriveLetter;
if (searchDriveLetter = #0) then begin
searchDriveLetter := requiredDriveLetter;
end;
// If still #0, just get the next one after C:
if (searchDriveLetter = #0) then begin
searchDriveLetter := 'C';
end;
freeDriveLetters := uppercase(SDUGetUnusedDriveLetters());
searchDriveLetter := upcase(searchDriveLetter);
// Delete drive letters from the free drive letters, until we hit one which
// appears after the one we've been requested - or we run out of free drive
// letters
while (freeDriveLetters <> '') and (freeDriveLetters[1] < searchDriveLetter) do begin
Delete(freeDriveLetters, 1, 1);
end;
if (freeDriveLetters <> '') then begin
Result := freeDriveLetters[1];
end;
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.DriverType(): String;
begin
Result := _('Kernel driver');
end;
// ----------------------------------------------------------------------------
// Display control for controlling underlying drivers
// You *shouldn't* call this while the component is active, as the user may
// try to do something dumn like uninstall the main FreeOTFE driver while we're
// connected to it!
procedure TOTFEFreeOTFE.ShowDriverControlDlg();
var
dlg: TfrmDriverControl;
begin
// TfrmDriverControl.Create(nil) will raise an exception if the user doesn't
// have the required privs to access driver control
dlg := TfrmDriverControl.Create(nil);
try
dlg.ShowModal();
finally
dlg.Free();
end;
// In case drivers were added/removed...
CachesFlush();
end;
// ----------------------------------------------------------------------------
//PortableDriverFilenames
function TOTFEFreeOTFE.PortableStart(driverFilenames: TStringList;
showProgress: Boolean): Boolean;
var
DriverControlObj: TDriverControl;
begin
DriverControlObj := TDriverControl.Create();
try
Result := DriverControlObj.InstallMultipleDrivers(
driverFilenames,
True,
showProgress,
True
);
finally
DriverControlObj.Free();
end;
// In case drivers were added/removed...
CachesFlush();
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.PortableStop(): Boolean;
var
DriverControlObj: TDriverControl;
begin
DriverControlObj := TDriverControl.Create();
try
Result := DriverControlObj.UninstallAllDrivers(True)
finally
DriverControlObj.Free();
end;
// In case drivers were added/removed...
CachesFlush();
end;
// -----------------------------------------------------------------------------
// Identify how many drivers are currently running in portable mode
// Returns -1 on failure
function TOTFEFreeOTFE.DriversInPortableMode(): Integer;
var
DriverControlObj: TDriverControl;
allDrivers: TStringList;
wasInstalledPortable: Boolean;
i: Integer;
begin
Result := -1;
try
DriverControlObj := TDriverControl.Create();
try
allDrivers := TStringList.Create();
try
if DriverControlObj.GetFreeOTFEDrivers(allDrivers) then begin
Result := 0;
for i := 0 to (allDrivers.Count - 1) do begin
// If the driver was installed in portable mode, stop and uninstall it
if DriverControlObj.IsDriverInstalledPortable(allDrivers[i], wasInstalledPortable) then
begin
if wasInstalledPortable then begin
Inc(Result);
end;
end;
// if DriverControlObj.IsDriverInstalledPortable(allDrivers[i], wasInstalledPortable) then
end; // for i:=0 to (allDrivers.count-1) do
end; // if DriverControlObj.GetFreeOTFEDrivers(allDrivers) then
finally
allDrivers.Free();
end;
finally
DriverControlObj.Free();
end;
except
on EFreeOTFENeedAdminPrivs do begin
// Do nothing - Result already set to -1
end;
end;
end;
// ----------------------------------------------------------------------------
// Convert a kernel mode volume filename to a user mode volume filename
function TOTFEFreeOTFE.GetUserModeVolumeFilename(kernelModeFilename: Ansistring): Ansistring;
begin
Result := kernelModeFilename;
// Kernel mode drivers take volume filenames of the format:
// \??\UNC<unc path>
// \??\<filename>
// <devicename>
// e.g.:
// \??\UNC\myOtherComputer\shareName\dirname\file.dat
// \??\C:\file.dat
// \Device\Harddisk0\Partition1\path\filedisk.img
// \Device\Harddisk0\Partition1
// Strip out the filename prefix
if Pos('\??\UNC\', Result) = 1 then begin
// \\server\share\path\filedisk.img
Delete(Result, 1, length('\??\UNC\'));
Result := '\\' + Result;
end else
if Pos('\??\', Result) = 1 then begin
// C:\path\filedisk.img
Delete(Result, 1, length('\??\'));
end else begin
// \Device\Harddisk0\Partition1\path\filedisk.img
// Do nothing.
end;
end;
// ----------------------------------------------------------------------------
// Convert a user mode volume filename to a kernel mode volume filename
function TOTFEFreeOTFE.GetKernelModeVolumeFilename(userModeFilename: String): String;
begin
Result := '';
// Kernel mode drivers take volume filenames of the format:
// \??\UNC<unc path>
// \??\<filename>
// <devicename>
// e.g.:
// \??\UNC\myOtherComputer\shareName\dirname\file.dat
// \??\C:\file.dat
// \Device\Harddisk0\Partition1\path\filedisk.img
// \Device\Harddisk0\Partition1
if (Pos('\\', userModeFilename) = 1) then begin
// \\server\share\path\filedisk.img
// Remove first "\"
Delete(userModeFilename, 1, 1);
Result := '\??\UNC' + userModeFilename;
end else
if ((Pos(':\', userModeFilename) = 2) or
(Pos(':/', userModeFilename) = 2)) then begin
// C:\path\filedisk.img
Result := '\??\' + userModeFilename;
end else begin
// \Device\Harddisk0\Partition1\path\filedisk.img
Result := userModeFilename;
end;
end;
// ----------------------------------------------------------------------------
// Return TRUE/FALSE, depending on whether the specified KERNEL MODE volume
// filename refers to a partition/file
function TOTFEFreeOTFE.IsPartition_KernelModeName(kernelModeFilename: String): Boolean;
begin
// In kernel mode, partitions start with just "\", not "\??\"
Result := (Pos('\??\', kernelModeFilename) <> 1);
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.ReadRawVolumeDataSimple(
filename: String;
offsetWithinFile: Int64;
dataLength: DWORD; // In bytes
var Data: Ansistring
): Boolean;
var
BytesReturned: DWORD;
kmFilename: String;
DIOCBufferIn: TDIOC_GET_RAW_DATA_IN;
ptrDIOCBufferOut: PDIOC_GET_RAW_DATA_OUT;
begin
Result := False;
CheckActive();
// +1 because StrPCopy(...) copies a terminating NULL
ptrDIOCBufferOut := allocmem(dataLength + 1);
try
// Determine the filename as the kernel sees it
kmFilename := GetKernelModeVolumeFilename(filename);
StrPCopy(DIOCBufferIn.Filename, kmFilename);
DIOCBufferIn.Offset := offsetWithinFile;
DIOCBufferIn.DataLength := dataLength;
DebugMsg('Read raw data from: '+filename);
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_GET_RAW, @DIOCBufferIn,
sizeof(DIOCBufferIn), ptrDIOCBufferOut,
dataLength, BytesReturned,
nil)) then begin
DebugMsg('DIOC OK (bytes: '+inttostr(BytesReturned)+')');
if (BytesReturned = dataLength) then begin
DebugMsg('Bytes OK');
// Set data so that it has enough characters which can be
// overwritten with StrMove
data := StringOfChar(AnsiChar(#0), dataLength);
StrMove(PAnsiChar(data), @ptrDIOCBufferOut.Data, dataLength);
Result := True;
end;
end;
finally
FillChar(ptrDIOCBufferOut^, dataLength, 0); // Overwrite buffer before
// freeing off
FreeMem(ptrDIOCBufferOut);
end;
end;
// ----------------------------------------------------------------------------
// Get the FreeOTFE driver to write a critical data block from the named file
// starting from the specified offset
// criticalData - This should be set to the string representation of a raw
// (encrypted) critical data block
function TOTFEFreeOTFE.WriteRawVolumeDataSimple(
filename: String;
offsetWithinFile: Int64;
data: Ansistring
): Boolean;
var
BytesReturned: DWORD;
kmFilename: String;
ptrDIOCBuffer: PDIOC_SET_RAW_DATA;
bufferSize: Integer;
begin
Result := False;
CheckActive();
// Determine the volume filename as the kernel sees it
kmFilename := GetKernelModeVolumeFilename(filename);
// Subtract sizeof(char) - once for the volume key, once for the volumeIV
bufferSize := sizeof(ptrDIOCBuffer^) - sizeof(ptrDIOCBuffer^.Data) + Length(data);
// Round up to next "DIOC boundry". Although this always results in an
// oversized buffer, it's guaranteed to be big enough.
bufferSize := bufferSize + (DIOC_BOUNDRY - (bufferSize mod DIOC_BOUNDRY));
ptrDIOCBuffer := allocmem(bufferSize);
try
StrPCopy(ptrDIOCBuffer.Filename, kmFilename);
ptrDIOCBuffer.Offset := offsetWithinFile;
ptrDIOCBuffer.DataLength := Length(data);
StrMove(@ptrDIOCBuffer.Data, PAnsiChar(data), Length(data));
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Write raw data from: '+filename);
{$ENDIF}
if (DeviceIoControl(DriverHandle,
IOCTL_FREEOTFE_SET_RAW, ptrDIOCBuffer,
bufferSize, nil, 0,
BytesReturned, nil)) then
begin
{$IFDEF FREEOTFE_DEBUG}
DebugMsg('Written OK');
{$ENDIF}
Result := True;
end;
finally
FillChar(ptrDIOCBuffer^, bufferSize, 0);
FreeMem(ptrDIOCBuffer);
end;
end;
// ----------------------------------------------------------------------------
// Use the FreeOTFE device driver to mount the specified volume, and either:
// *) Read in and decrypt specified data, returning the decrypted version
// *) Encrypt specified data, and write to volume
// readNotWrite - Set to TRUE to read, FALSE to write
function TOTFEFreeOTFE.ReadWritePlaintextToVolume(
readNotWrite: Boolean;
volFilename: String;
volumeKey: TSDUBytes;
sectorIVGenMethod: TFreeOTFESectorIVGenMethod;
IVHashDriver: Ansistring;
IVHashGUID: TGUID;
IVCypherDriver: Ansistring;
IVCypherGUID: TGUID;
mainCypherDriver: Ansistring;
mainCypherGUID: TGUID;
VolumeFlags: Integer;
mountMountAs: TFreeOTFEMountAs;
dataOffset: Int64; // Offset from within mounted volume from where to read/write data
dataLength: Integer; // Length of data to read/write. In bytes
var data: TSDUBytes; // Data to read/write
offset: Int64 = 0; // Offset within volume where encrypted data starts
size: Int64 = 0; // Size of volume
storageMediaType: TFreeOTFEStorageMediaType = mtFixedMedia): Boolean;
var
deviceName: String;
dummyMetadata: TOTFEFreeOTFEVolumeMetaData;
// emptyIV:TSDUBytes;
strData: Ansistring; { TODO 1 -otdk -crefactor : store data in arrays not strings }
begin
LastErrorCode := OTFE_ERR_SUCCESS;
CheckActive();
DebugMsg('BEGIN ReadWritePlaintextToVolume');
DebugMsg(readNotWrite);
DebugMsg(volFilename);
DebugMsg(volumeKey);
DebugMsg(Ord(sectorIVGenMethod));
DebugMsg(IVHashDriver);
DebugMsg(IVHashGUID );
DebugMsg(IVCypherDriver );
DebugMsg(IVCypherGUID );
DebugMsg(mainCypherDriver );
DebugMsg(mainCypherGUID );
DebugMsg(VolumeFlags );
DebugMsg(Ord(mountMountAs ));
DebugMsg(dataOffset );
DebugMsg(dataLength );
DebugMsg(offset );
DebugMsg(size );
DebugMsg(Ord(storageMediaType) );
DebugMsg('END ReadWritePlaintextToVolume');
// Attempt to create a new device to be used
deviceName := CreateDiskDevice(FreeOTFEMountAsDeviceType[mountMountAs]);
Result := (deviceName <> '');
if (Result) then begin
try
PopulateVolumeMetadataStruct(
False, // Linux volume
PKCS11_NO_SLOT_ID, // PKCS11 SlotID
dummyMetadata
);
// SDUInitAndZeroBuffer(0,emptyIV);
// Attempt to mount the device
Result := MountDiskDevice(deviceName,
volFilename, volumeKey,
sectorIVGenMethod, nil,
False, IVHashDriver,
IVHashGUID, IVCypherDriver, // IV cypher
IVCypherGUID, // IV cypher
mainCypherDriver, // Main cypher
mainCypherGUID, // Main cypher
VolumeFlags, dummyMetadata,
offset, size,
FreeOTFEMountAsStorageMediaType[mountMountAs]);
if (Result) then begin
try
// Read decrypted data from mounted device
if (readNotWrite) then begin
Result := ReadRawVolumeData(deviceName,
dataOffset, dataLength,
strData);
data := SDUStringToSDUBytes(strData);
end else begin
Result := WriteRawVolumeData(deviceName,
dataOffset,
SDUBytesToString(data));
end;
finally
// Unmount
DismountDiskDevice(deviceName, True);
end;
end; // if (Result) then
finally
// Destroy device
DestroyDiskDevice(deviceName);
end;
end; // if (Result) then
end;
// ----------------------------------------------------------------------------
function TOTFEFreeOTFE.CanUserManageDrivers(): Boolean;
var
testControlObj: TDriverControl;
begin
Result := False;
try
// If we can't create a drive control object (i.e. we don't have admin
// access to open the SCManager), we'll get an exception here.
testControlObj := TDriverControl.Create();
testControlObj.Free();
Result := True;
except
on EFreeOTFENeedAdminPrivs do begin
// Do nothing - just swallow the exception
end;
end;
end;
{returns an instance of the only object. call SetFreeOTFEType first}
function GetFreeOTFE: TOTFEFreeOTFE;
begin
assert(GetFreeOTFEBase is TOTFEFreeOTFE, 'call SetFreeOTFEType with correct type');
Result := GetFreeOTFEBase as TOTFEFreeOTFE;
end;
end.
|
unit frmWorkerPrize;
{******************************************************************************}
{ }
{ 软件名称 WMS }
{ 版权所有 (C) 2004-2005 ESQUEL GROUP GET/IT }
{ 单元名称 frmYSDictionary.pas }
{ 创建日期 2004-8-12 11:03:49 }
{ 创建人员 cuijf }
{ 修改人员 }
{ 修改日期 }
{ 修改原因 }
{ 对应用例 }
{ 字段描述 }
{ 相关数据库表 STSYSTEMDICTIONARY; STLOCATIONLIST }
{ 调用重要函数/SQL对象说明 }
{ 功能描述 维护纱仓的通用字典及架位列表 }
{ }
{******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frmBase, ComCtrls, ExtCtrls, DB, DBClient, Buttons, cxSplitter,
StdCtrls, DBCtrls, Mask, cxGridLevel, cxClasses, cxControls,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, cxDBData;
type
TWorkerPrizeForm = class(TBaseForm)
pgcPrize: TPageControl;
pnlTool: TPanel;
tsCommon: TTabSheet;
tsLocation: TTabSheet;
grpWorkerPrize: TGroupBox;
grpWorkerPrizeEdit: TGroupBox;
lblMonitor: TLabel;
lblReason: TLabel;
lblWorkerID: TLabel;
pnlTools: TPanel;
cxspl1: TcxSplitter;
btnAdd: TSpeedButton;
btnModify: TSpeedButton;
btnDelete: TSpeedButton;
btnUndo: TSpeedButton;
btnExport: TSpeedButton;
btnSave: TSpeedButton;
btnExit: TSpeedButton;
btnRefresh: TSpeedButton;
cdsWorkerPrize: TClientDataSet;
grpWorkerError: TGroupBox;
grpWorkerErrorEdit: TGroupBox;
dsWorkerPrize: TDataSource;
cxgridtvWorkerPrize: TcxGridDBTableView;
cxGridlWorkerPrize: TcxGridLevel;
cxgridWorkerPrize: TcxGrid;
cdsWorkerError: TClientDataSet;
cxgridWorkerError: TcxGrid;
cxgridtvWorkerError: TcxGridDBTableView;
cxGridlWorkerError: TcxGridLevel;
dsWorkerError: TDataSource;
dtpQueryDate: TDateTimePicker;
lblQueryDate: TLabel;
dblkcbbWorkerID: TDBLookupComboBox;
dblkcbbMonitor: TDBLookupComboBox;
dbedtPrize: TDBEdit;
lblPrize: TLabel;
dbmmoPrizeReson: TDBMemo;
lbl1: TLabel;
dblkcbbWorker_ID: TDBLookupComboBox;
lbl2: TLabel;
dblkcbbFinder: TDBLookupComboBox;
lbl3: TLabel;
dbedtErrorField: TDBEdit;
lbl4: TLabel;
dbmmoErrorReason: TDBMemo;
cxspl2: TcxSplitter;
dsWorkerList: TDataSource;
dsMonitorList: TDataSource;
cdsMonitorList: TClientDataSet;
//取通用字典
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure btnExitClick(Sender: TObject);
procedure btnModifyClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnUndoClick(Sender: TObject);
procedure btnRefreshClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnExportClick(Sender: TObject);
procedure grpWorkerPrizeEditExit(Sender: TObject);
procedure grpWorkerErrorEditExit(Sender: TObject);
procedure pnlToolsMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
{ Private declarations }
//初始化
procedure Initialize;
//查询数据
procedure GetWorkerPrizeOrErrorInfo;
procedure GetData;
//新增数据
procedure AddNew;
//设置输入框状态
procedure SetPanelStatus(Enable:Boolean);
//设置button状态
procedure SetButtonStatus;
//进入修改状态
procedure Modify;
//保存数据
procedure SaveData;
//删除记录
procedure DeleteData;
//导出记录
procedure ExportData;
public
{ Public declarations }
end;
var
WorkerPrizeForm: TWorkerPrizeForm;
implementation
uses ServerDllPub, UShowMessage,uLogin,
UAppOption, UGridDecorator,uGlobal,uDictionary;
{$R *.dfm}
procedure TWorkerPrizeForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TWorkerPrizeForm.FormDestroy(Sender: TObject);
begin
WorkerPrizeForm:=nil;
end;
procedure TWorkerPrizeForm.btnExitClick(Sender: TObject);
begin
Close;
end;
procedure TWorkerPrizeForm.btnModifyClick(Sender: TObject);
begin
Modify;
end;
procedure TWorkerPrizeForm.btnSaveClick(Sender: TObject);
begin
SaveData;
end;
procedure TWorkerPrizeForm.Initialize;
begin
GetData();
end;
procedure TWorkerPrizeForm.FormCreate(Sender: TObject);
begin
inherited;
dtpQueryDate.Date := Date;
Initialize;
end;
procedure TWorkerPrizeForm.GetWorkerPrizeOrErrorInfo;
var vData: OleVariant;
sQuery_Date,sErrorMsg: WideString;
iType: Integer;
begin
try
TStatusBarMessage.ShowMessageOnMainStatsusBar('正在获取数据稍等!', crHourGlass);
sQuery_Date := DateToStr(dtpQueryDate.Date);
iType := pgcPrize.ActivePageIndex;
FNMServerObj.GetWorkerPrizeOrErrorInfo(vData,sQuery_Date,Login.CurrentDepartment,iType, sErrorMsg);
if sErrorMsg <> '' then
begin
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError);
Exit;
end;
if pgcPrize.ActivePageIndex =0 then
begin
cdsWorkerPrize.Data := vData;
GridDecorator.BindCxViewWithDataSource(cxgridtvWorkerPrize,dsWorkerPrize);
end else
begin
cdsWorkerError.Data := vData;
GridDecorator.BindCxViewWithDataSource(cxgridtvWorkerError,dsWorkerError);
end;
finally
TStatusBarMessage.ShowMessageOnMainStatsusBar('', crDefault);
end;
end;
procedure TWorkerPrizeForm.GetData;
var FilterStr: string;
begin
//Monitor List
FilterStr:='';
TGlobal.FilterData(Dictionary.cds_WorkerList,FilterStr);
cdsMonitorList.Data := Dictionary.cds_WorkerList.Data;
//WorkerList
FilterStr:='';
TGlobal.FilterData(Dictionary.cds_WorkerList,FilterStr);
dsWorkerList.DataSet := Dictionary.cds_WorkerList;
//设置BUTTON的状态
GetWorkerPrizeOrErrorInfo;
SetButtonStatus;
SetPanelstatus(false);
end;
procedure TWorkerPrizeForm.AddNew;
begin
case pgcPrize.ActivePageIndex of
0:
begin
with cdsWorkerPrize do
begin
if not Active then exit;
try
DisableControls;
Append;
FieldByName('Prize_Date').AsString := DateToStr(dtpQueryDate.Date);
FieldByName('Current_Department').AsString := Login.CurrentDepartment;
FieldByName('Operator').AsString := Login.LoginName;
FieldByName('Operate_Time').AsDateTime := Now;
finally
EnableControls;
end;
end;
end;
1:
begin
with cdsWorkerError do
begin
if not Active then exit;
try
DisableControls;
Append;
FieldByName('Error_Date').AsString := DateToStr(dtpQueryDate.Date);
FieldByName('Current_Department').AsString := Login.CurrentDepartment;
FieldByName('Operator').AsString := Login.LoginName;
FieldByName('Operate_Time').AsDateTime := Now;
finally
EnableControls;
end
end;;
end;
end;
SetPanelStatus(True);
SetButtonStatus;
end;
procedure TWorkerPrizeForm.btnAddClick(Sender: TObject);
begin
inherited;
AddNew;
end;
procedure TWorkerPrizeForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
case pgcPrize.ActivePageIndex of
0: ;
1: ;
end;
end;
procedure TWorkerPrizeForm.btnUndoClick(Sender: TObject);
begin
inherited;
if pgcPrize.ActivePageIndex=0 then
cdsWorkerPrize.CancelUpdates
else if pgcPrize.ActivePageIndex=1 then
cdsWorkerError.CancelUpdates;
//恢fu为只读状态
SetButtonStatus;
SetPanelStatus(False);
end;
procedure TWorkerPrizeForm.SetPanelStatus(enable:Boolean);
var i:integer;
begin
case pgcPrize.ActivePageIndex of
0:
begin
for i:=0 to grpWorkerPrizeEdit.ControlCount-1 do
grpWorkerPrizeEdit.Controls[i].Enabled:=Enable;
end;
1:
begin
for i:=0 to grpWorkerErrorEdit.ControlCount-1 do
grpWorkerErrorEdit.Controls[i].Enabled:=Enable;
end;
end;
end;
procedure TWorkerPrizeForm.Modify;
begin
case pgcPrize.ActivePageIndex of
0:
begin
if not cdsWorkerPrize.Active then exit;
if cdsWorkerPrize.IsEmpty then exit;
cdsWorkerPrize.Edit;
end;
1:
begin
if not cdsWorkerError.Active then exit;
if cdsWorkerError.IsEmpty then exit;
cdsWorkerError.Edit;
end;
end;
SetPanelStatus(true);
end;
procedure TWorkerPrizeForm.btnRefreshClick(Sender: TObject);
begin
inherited;
GetData();
end;
procedure TWorkerPrizeForm.SaveData;
var
vData:OleVariant;
sErrorMsg:WideString;
begin
try
ShowMsg('正在保存数据!请稍候...',crHourGlass) ;
case pgcPrize.ActivePageIndex of
0:
begin
if cdsWorkerPrize.ChangeCount =0 then exit;
vData:=cdsWorkerPrize.Delta;
FNMServerObj.SaveBaseTableInfo(vData,'dbo.fnWorkerPrize','Iden',sErrorMsg);
cdsWorkerPrize.MergeChangeLog;
end;
1:
begin
if cdsWorkerError.ChangeCount =0 then exit;
vData:=cdsWorkerError.Delta;
FNMServerObj.SaveBaseTableInfo(vData,'dbo.fnWorkerError','Iden',sErrorMsg);
cdsWorkerError.MergeChangeLog;
end;
end;
if sErrorMsg<>'' then
TMsgDialog.ShowMsgDialog(sErrorMsg,mtError)
else
begin
TMsgDialog.ShowMsgDialog('数据保存成功!',mtInformation);
GetData();
SetPanelStatus(False);
end;
finally
SetButtonStatus;
ShowMsg('') ;
end;
end;
procedure TWorkerPrizeForm.btnDeleteClick(Sender: TObject);
begin
inherited;
DeleteData;
end;
procedure TWorkerPrizeForm.DeleteData;
begin
case pgcPrize.ActivePageIndex of
0:
begin
if (not cdsWorkerPrize.Active) or (cdsWorkerPrize.IsEmpty) then exit;
if TMsgDialog.ShowMsgDialog('你确认要删除该记录吗?',mtConfirmation,[mebYes,mebNo],mebYes)=mrYes then
cdsWorkerPrize.Delete;
end;
1:
begin
if (not cdsWorkerError.Active) or (cdsWorkerError.IsEmpty) then exit;
if TMsgDialog.ShowMsgDialog('你确认要删除该记录吗?',mtConfirmation,[mebYes,mebNo],mebYes)=mrYes then
cdsWorkerError.Delete;
end;
end;
SetButtonStatus;
end;
procedure TWorkerPrizeForm.SetButtonStatus;
var acds:TClientDataSet;
begin
if pgcPrize.ActivePageIndex = 0 then
acds:=cdsWorkerPrize
else
acds:=cdsWorkerError;
btnAdd.Enabled:=acds.Active;
btnModify.Enabled:=acds.Active;
btnDelete.Enabled:=acds.Active;
btnUnDo.Enabled:= not TGlobal.DeltaIsNull(acds);
btnExport.Enabled:=acds.Active;
btnSave.Enabled:= not TGlobal.DeltaIsNull(acds);
end;
procedure TWorkerPrizeForm.btnExportClick(Sender: TObject);
begin
inherited;
ExportData;
end;
procedure TWorkerPrizeForm.ExportData;
begin
case pgcPrize.ActivePageIndex of
0: TGlobal.SaveDataToFile(cdsWorkerPrize, sftXLS);
1: TGlobal.SaveDataToFile(cdsWorkerError, sftXLS);
end;
end;
procedure TWorkerPrizeForm.grpWorkerPrizeEditExit(Sender: TObject);
begin
inherited;
SetButtonStatus;
end;
procedure TWorkerPrizeForm.grpWorkerErrorEditExit(Sender: TObject);
begin
inherited;
SetButtonStatus;
end;
procedure TWorkerPrizeForm.pnlToolsMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
inherited;
SetButtonStatus;
end;
end.
|
unit DPM.Core.Sources.ServiceIndex;
interface
uses
Spring.Collections,
JsonDataObjects,
DPM.Core.Sources.Interfaces;
type
TServiceIndex = class(TInterfacedObject, IServiceIndex)
private
FItems : IList<IServiceIndexItem>;
protected
function FindItem(const resourceType : string) : IServiceIndexItem;
function FindItems(const resourceType: string): IEnumerable<IServiceIndexItem>;
function GetItems: Spring.Collections.IList<IServiceIndexItem>;
procedure LoadFromJsonObject(const jsonObject : TJsonObject);
public
constructor Create;
class function LoadFromJson(const jsonObject : TJsonObject) : IServiceIndex;
class function LoadFromString(const jsonString : string) : IServiceIndex;
end;
TServiceIndexItem = class(TInterfacedObject, IServiceIndexItem)
private
FResourceType: string;
FResourceUrl: string;
protected
function GetResourceType: string;
function GetResourceUrl: string;
public
constructor Create(const resourceType : string; const resourceUrl : string);
end;
implementation
uses
System.SysUtils;
{ TServiceIndexItem }
constructor TServiceIndexItem.Create(const resourceType, resourceUrl: string);
begin
FResourceType := resourceType;
FResourceUrl := resourceUrl;
end;
function TServiceIndexItem.GetResourceType: string;
begin
result := FResourceType;
end;
function TServiceIndexItem.GetResourceUrl: string;
begin
result := FResourceUrl;
end;
{ TServiceIndex }
constructor TServiceIndex.Create;
begin
FItems := TCollections.CreateList<IServiceIndexItem>;
end;
function TServiceIndex.FindItem(const resourceType: string): IServiceIndexItem;
begin
result := FindItems(resourceType).FirstOrDefault;
end;
function TServiceIndex.FindItems(const resourceType: string): IEnumerable<IServiceIndexItem>;
begin
result := FItems.Where(
function(const item : IServiceIndexItem) : boolean
begin
result := SameText(item.ResourceType, resourceType);
end);
end;
function TServiceIndex.GetItems: Spring.Collections.IList<IServiceIndexItem>;
begin
result := FItems;
end;
class function TServiceIndex.LoadFromJson(const jsonObject: TJsonObject): IServiceIndex;
begin
result := TServiceIndex.Create;
(result as TServiceIndex).LoadFromJsonObject(jsonObject);
end;
procedure TServiceIndex.LoadFromJsonObject(const jsonObject: TJsonObject);
var
resourcesArray : TJsonArray;
resourceObj : TJsonObject;
i: integer;
resourceType : string;
resourceUrl : string;
item : IServiceIndexItem;
begin
resourcesArray := jsonObject.A['resources'];
if resourcesArray.Count = 0 then
exit;
for i := 0 to resourcesArray.Count -1 do
begin
resourceObj := resourcesArray.O[i];
resourceType := resourceObj.S['@type'];
resourceUrl := resourceObj.S['@id'];
item := TServiceIndexItem.Create(resourceType, resourceUrl);
FItems.Add(item);
end;
end;
class function TServiceIndex.LoadFromString(const jsonString: string): IServiceIndex;
var
jsonObj : TJsonObject;
begin
jsonObj := TJsonObject.Parse(jsonString) as TJsonObject;
try
result := LoadFromJson(jsonObj);
finally
jsonObj.Free;
end;
end;
end.
|
unit gateway_protocol.Client;
// This unit was initially generated by: DelphiGrpc "ProtoBufGenerator.exe"
(* -----------------------------------------------------------
PMM 18.05.2020 The following changes where found necessary:
Int64 -> UInt64 (so far used)
function Topology: Has no parameter (was empty record)
----------------------------------------------------------*)
interface
uses Ultraware.Grpc.Client, gateway_protocol.Proto;
type
TActivateJobsCallback = TProtoCallback<TActivatedJobArray>;
IGateway_Client = interface
procedure ActivateJobs(const aActivateJobsRequest: TActivateJobsRequest; const aActivateJobsCallback: TActivateJobsCallback);
procedure CancelWorkflowInstance(const aworkflowInstanceKey: UInt64);
procedure CompleteJob(const aCompleteJobRequest: TCompleteJobRequest);
function CreateWorkflowInstance(const aCreateWorkflowInstanceRequest: TCreateWorkflowInstanceRequest): TCreateWorkflowInstanceResponse; overload;
function CreateWorkflowInstanceWithResult(const aCreateWorkflowInstanceWithResultRequest: TCreateWorkflowInstanceWithResultRequest): TCreateWorkflowInstanceWithResultResponse;
function DeployWorkflow(const aworkflows: TWorkflowRequestObjectArray): TDeployWorkflowResponse;
procedure FailJob(const aFailJobRequest: TFailJobRequest);
procedure PublishMessage(const aPublishMessageRequest: TPublishMessageRequest);
procedure ResolveIncident(const aincidentKey: Int64);
procedure SetVariables(const aSetVariablesRequest: TSetVariablesRequest);
function Topology(): TTopologyResponse;
procedure UpdateJobRetries(const aUpdateJobRetriesRequest: TUpdateJobRetriesRequest);
end;
TGateway_Client = class(TBaseGrpcClient,IGateway_Client)
procedure ActivateJobs(const aActivateJobsRequest: TActivateJobsRequest; const aActivateJobsCallback: TActivateJobsCallback);
procedure CancelWorkflowInstance(const aworkflowInstanceKey: UInt64);
procedure CompleteJob(const aCompleteJobRequest: TCompleteJobRequest);
function CreateWorkflowInstance(const aCreateWorkflowInstanceRequest: TCreateWorkflowInstanceRequest): TCreateWorkflowInstanceResponse; overload;
function CreateWorkflowInstanceWithResult(const aCreateWorkflowInstanceWithResultRequest: TCreateWorkflowInstanceWithResultRequest): TCreateWorkflowInstanceWithResultResponse;
function DeployWorkflow(const aworkflows: TWorkflowRequestObjectArray): TDeployWorkflowResponse;
procedure FailJob(const aFailJobRequest: TFailJobRequest);
procedure PublishMessage(const aPublishMessageRequest: TPublishMessageRequest);
procedure ResolveIncident(const aincidentKey: Int64);
procedure SetVariables(const aSetVariablesRequest: TSetVariablesRequest);
function Topology(): TTopologyResponse;
procedure UpdateJobRetries(const aUpdateJobRetriesRequest: TUpdateJobRetriesRequest);
function BasePath: string; override;
end;
implementation
{ TGateway_Client }
function TGateway_Client.BasePath: string;
begin
Result := '/gateway_protocol.Gateway/';
end;
procedure TGateway_Client.ActivateJobs(const aActivateJobsRequest: TActivateJobsRequest; const aActivateJobsCallback: TActivateJobsCallback);
var SubCallback: TProtoCallback<TActivateJobsResponse>;
begin
SubCallback := procedure(const aInput: TActivateJobsResponse; const aHasData, aClosed: Boolean)
begin
aActivateJobsCallback(aInput.jobs, aHasData, aClosed);
end;
DoOuputStreamRequest<TActivateJobsRequest,TActivateJobsResponse>(aActivateJobsRequest, 'ActivateJobs', SubCallback);
end;
procedure TGateway_Client.CancelWorkflowInstance(const aworkflowInstanceKey: UInt64);
var CancelWorkflowInstanceRequest_In: TCancelWorkflowInstanceRequest;
begin
CancelWorkflowInstanceRequest_In.workflowInstanceKey := aworkflowInstanceKey;
DoRequest<TCancelWorkflowInstanceRequest,TCancelWorkflowInstanceResponse>(CancelWorkflowInstanceRequest_In, 'CancelWorkflowInstance');
end;
procedure TGateway_Client.CompleteJob(const aCompleteJobRequest: TCompleteJobRequest);
begin
DoRequest<TCompleteJobRequest,TCompleteJobResponse>(aCompleteJobRequest, 'CompleteJob');
end;
function TGateway_Client.CreateWorkflowInstance(const aCreateWorkflowInstanceRequest: TCreateWorkflowInstanceRequest): TCreateWorkflowInstanceResponse;
begin
Result := DoRequest<TCreateWorkflowInstanceRequest,TCreateWorkflowInstanceResponse>(aCreateWorkflowInstanceRequest, 'CreateWorkflowInstance');
end;
function TGateway_Client.CreateWorkflowInstanceWithResult(const aCreateWorkflowInstanceWithResultRequest: TCreateWorkflowInstanceWithResultRequest): TCreateWorkflowInstanceWithResultResponse;
begin
Result := DoRequest<TCreateWorkflowInstanceWithResultRequest,TCreateWorkflowInstanceWithResultResponse>(aCreateWorkflowInstanceWithResultRequest, 'CreateWorkflowInstanceWithResult');
end;
function TGateway_Client.DeployWorkflow(const aworkflows: TWorkflowRequestObjectArray): TDeployWorkflowResponse;
var DeployWorkflowRequest_In: TDeployWorkflowRequest;
begin
DeployWorkflowRequest_In.workflows := aworkflows;
Result := DoRequest<TDeployWorkflowRequest,TDeployWorkflowResponse>(DeployWorkflowRequest_In, 'DeployWorkflow');
end;
procedure TGateway_Client.FailJob(const aFailJobRequest: TFailJobRequest);
begin
DoRequest<TFailJobRequest,TFailJobResponse>(aFailJobRequest, 'FailJob');
end;
procedure TGateway_Client.PublishMessage(const aPublishMessageRequest: TPublishMessageRequest);
begin
DoRequest<TPublishMessageRequest,TPublishMessageResponse>(aPublishMessageRequest, 'PublishMessage');
end;
procedure TGateway_Client.ResolveIncident(const aincidentKey: Int64);
var ResolveIncidentRequest_In: TResolveIncidentRequest;
begin
ResolveIncidentRequest_In.incidentKey := aincidentKey;
DoRequest<TResolveIncidentRequest,TResolveIncidentResponse>(ResolveIncidentRequest_In, 'ResolveIncident');
end;
procedure TGateway_Client.SetVariables(const aSetVariablesRequest: TSetVariablesRequest);
begin
DoRequest<TSetVariablesRequest,TSetVariablesResponse>(aSetVariablesRequest, 'SetVariables');
end;
function TGateway_Client.Topology({const aTopologyRequest: TTopologyRequest}): TTopologyResponse;
begin
Result := DoRequestNoInput<TTopologyResponse>('Topology');
end;
procedure TGateway_Client.UpdateJobRetries(const aUpdateJobRetriesRequest: TUpdateJobRetriesRequest);
begin
DoRequest<TUpdateJobRetriesRequest,TUpdateJobRetriesResponse>(aUpdateJobRetriesRequest, 'UpdateJobRetries');
end;
end.
|
unit Render3;
interface
uses
SysUtils, Types, Graphics,
Style, Layout;
type
TRenderer = class
private
Boxes: TBoxList;
Canvas: TCanvas;
Pen: TPoint;
Width: Integer;
protected
function GetContextRect(inBox: TBox): TRect;
procedure RenderBox(inBox: TBox); virtual;
procedure RenderBoxes;
public
constructor Create;
destructor Destroy; override;
procedure Render(inBoxes: TBoxList; inCanvas: TCanvas; inRect: TRect);
end;
procedure TestBoxRenderer(inCanvas: TCanvas; inRect: TRect);
implementation
uses
Nodes;
function BuildBox(inClass: TNodeClass; inW, inH, inX, inY: Integer): TBox;
function rc: Integer;
begin
Result := Random(192) + 64;
end;
begin
Result := TBox.Create;
Result.Width := inW;
Result.Height := inH;
Result.Offset := Point(inX, inY);
Result.Node := inClass.Create;
Result.Node.Style.BackgroundColor := (rc shl 16) + (rc shl 8) + rc;
Result.Node.Text := 'Box ' + IntToStr(Random(255));
end;
function BuildBoxes(inClass: TNodeClass;
inCount, inW, inH, inX, inY: Integer): TBoxList;
var
i: Integer;
begin
Result := TBoxList.Create;
for i := 1 to inCount do
Result.Add(BuildBox(inClass, inW, inH, inX, inY));
end;
function BuildTestBoxes: TBoxList;
begin
RandSeed := 234535;
Result := TBoxList.Create;
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
Result[2].Boxes := BuildBoxes(TCustomNode, 2, 150, 40, 150, 0);
Result[2].Boxes[0].Boxes := BuildBoxes(TCustomNode, 1, 130, 40, 0, 30);
Result[2].Boxes[0].Boxes[0].Boxes := BuildBoxes(TCustomNode, 3, 40, 15, 40, 0);
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
Result[3].Boxes := BuildBoxes(TCustomNode, 3, 50, 20, 50, 0);
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
// Result[4].Boxes := BuildBoxes(TBoxContextNode, 5, 500, 20);
Result.Add(BuildBox(TCustomNode, 500, 100, 0, 100));
end;
procedure TestBoxRenderer(inCanvas: TCanvas; inRect: TRect);
var
r: TRenderer;
b: TBoxList;
begin
r := TRenderer.Create;
try
b := BuildTestBoxes;
try
r.Render(b, inCanvas, inRect);
finally
b.Free;
end;
finally
r.Free;
end;
end;
{ TRenderer }
constructor TRenderer.Create;
begin
end;
destructor TRenderer.Destroy;
begin
inherited;
end;
function TRenderer.GetContextRect(inBox: TBox): TRect;
begin
with inBox do
Result := Rect(Left, Top, Left + Width, Top + Height);
OffsetRect(Result, Pen.X, Pen.Y);
end;
procedure TRenderer.RenderBox(inBox: TBox);
begin
TCustomNode(inBox.Node).Render(inBox, Canvas, GetContextRect(inBox));
Inc(Pen.X, inBox.Offset.X);
Inc(Pen.Y, inBox.Offset.Y);
end;
procedure TRenderer.RenderBoxes;
var
i: Integer;
begin
for i := 0 to Boxes.Max do
RenderBox(Boxes[i]);
end;
procedure TRenderer.Render(inBoxes: TBoxList; inCanvas: TCanvas;
inRect: TRect);
begin
Boxes := inBoxes;
Canvas := inCanvas;
Width := inRect.Right - inRect.Left;
Pen := Point(inRect.Left, inRect.Top);
RenderBoxes;
end;
end.
|
unit Dmitry.Controls.Angle;
interface
uses
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Winapi.Messages,
Vcl.Controls,
Vcl.Graphics,
Vcl.Themes,
Dmitry.Memory,
Dmitry.Controls.Base;
type
TAngle = class(TBaseWinControl)
private
{ Private declarations }
FCanvas: TCanvas;
FBuffer: TBitmap;
FAngle: Extended;
FMouseDown: Boolean;
FOnChange: TNotifyEvent;
FLoading: Boolean;
procedure SetAngle(const Value: Extended);
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetLoading(const Value: Boolean);
procedure UpdateAngle(var Mes: TWMMouse);
protected
{ Protected declarations }
procedure Paint(var Msg: TMessage); message WM_PAINT;
procedure OnChangeSize(var Msg: Tmessage); message WM_SIZE;
procedure OnMouseDownMSG(var Mes: TWMMouse); message WM_LBUTTONDOWN;
procedure OnMouseMOVEMSG(var Mes: TWMMouse); message WM_MOUSEMOVE;
procedure OnMouseUpMSG(var Mes: TWMMouse); message WM_LBUTTONUP;
procedure Erased(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure RecteateImage;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Align;
property Anchors;
property Angle: Extended read FAngle write SetAngle;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Loading: Boolean read FLoading write SetLoading default True;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Dm', [TAngle]);
end;
{ TAngle }
constructor TAngle.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLoading := True;
FBuffer := TBitmap.Create;
FBuffer.PixelFormat := pf24bit;
FAngle := 0;
FOnChange := nil;
FMouseDown := False;
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FLoading := False;
RecteateImage;
end;
destructor TAngle.Destroy;
begin
F(FCanvas);
F(FBuffer);
inherited;
end;
procedure TAngle.Erased(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
procedure TAngle.OnChangeSize(var Msg: Tmessage);
begin
if FLoading then
Exit;
if FBuffer = nil then
Exit;
FBuffer.Height := Height;
FBuffer.Width := Width;
RecteateImage;
end;
procedure TAngle.UpdateAngle(var Mes: TWMMouse);
var
X, Y, W, H: Integer;
begin
X := Mes.XPos;
Y := Mes.YPos;
H := Height div 2;
W := Width div 2;
if (Y - H) <> 0 then
begin
if (Y - H) > 0 then
Angle := 180 - Round(180 * Arctan((X - W) / (Y - H)) / Pi)
else
Angle := -Round(180 * Arctan((X - W) / (Y - H)) / Pi);
end else
begin
if (X - W) > 0 then
Angle := 90
else
Angle := 270;
end;
end;
procedure TAngle.OnMouseDownMSG(var Mes: TWMMouse);
begin
FMouseDown := True;
UpdateAngle(Mes);
end;
procedure TAngle.OnMouseMOVEMSG(var Mes: TWMMouse);
begin
if not FMouseDown then
Exit;
UpdateAngle(Mes);
end;
procedure TAngle.OnMouseUpMSG(var Mes: TWMMouse);
begin
FMouseDown := False;
end;
procedure TAngle.Paint(var Msg: TMessage);
var
DC: HDC;
PS: TPaintStruct;
begin
DC := BeginPaint(Handle, PS);
BitBlt(DC, 0, 0, ClientRect.Right, ClientRect.Bottom, FBuffer.Canvas.Handle, 0, 0, SRCCOPY);
EndPaint(Handle, PS);
end;
procedure TAngle.RecteateImage;
var
X, Y, H, W, X1, Y1: Integer;
DAngle: Extended;
C, CW: TColor;
begin
if StyleServices.Enabled then
begin
CW := StyleServices.GetStyleFontColor(sfPanelTextNormal);
C := StyleServices.GetStyleColor(scWindow);
end else
begin
CW := clWindowText;
C := clWindow;
end;
DrawBackground(FBuffer.Canvas);
FBuffer.Canvas.Pen.Color := CW;
FBuffer.Canvas.Brush.Color := C;
FBuffer.Canvas.Ellipse(0, 0, Width, Height);
FBuffer.Canvas.MoveTo(Width div 2, Height div 2);
DAngle := Angle * Pi / 180;
H := Height div 2;
W := Width div 2;
X := Round(W + W * Sin(DAngle));
Y := Round(H - H * Cos(DAngle));
FBuffer.Canvas.LineTo(X, Y);
FBuffer.Canvas.MoveTo(X, Y);
X1 := Round(W + 0.8 * W * Sin(DAngle + Pi / 20));
Y1 := Round(H - 0.8 * H * Cos(DAngle + Pi / 20));
FBuffer.Canvas.LineTo(X1, Y1);
FBuffer.Canvas.MoveTo(X, Y);
X1 := Round(W + 0.8 * W * Sin(DAngle - Pi / 20));
Y1 := Round(H - 0.8 * H * Cos(DAngle - Pi / 20));
FBuffer.Canvas.LineTo(X1, Y1);
if Parent <> nil then
begin
Invalidate;
PostMessage(Handle, WM_PAINT, 0, 0);
end;
end;
procedure TAngle.SetAngle(const Value: Extended);
begin
FAngle := Value;
if Assigned(FOnChange) then
FOnChange(Self);
RecteateImage;
end;
procedure TAngle.SetLoading(const Value: boolean);
begin
FLoading := Value;
end;
procedure TAngle.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
end;
end.
|
unit StringProcessing;
interface
Uses
System.SysUtils, Unit1;
const
ENGLISH_ALPHABET_SIZE = 26;
RUSSIAN_ALPHABET_SIZE = 33;
ENGLISH_ALPHABET_SHIFT = 65;
RUSSIAN_ALPHABET_SHIFT = 128;
var
alphabetSize : integer;
function chrExt(const num : integer) : char;
function GetAlphabetSize : integer;
function DecipherText(const fileName : string) : string;
function ordExt(const symb : char) : integer;
procedure EncipherText(sourceText : string; const outputFileName : string);
procedure ConvertStringToUpperCase(var sourceText : string);
procedure RemoveUnexpectedSymbols(var sourceText : string);
implementation
Uses
Enchipher, KeyCheck, FileUnit;
procedure ConvertSymbolToUpperCase(var symbol : char); forward;
procedure SaveEncipheredText(fileName, encipheredText : string); forward;
function UnexpectedSymbol(const symbol : char) : boolean; forward;
//function OpenSourceText(fileName : string) : string; forward;
function GetAlphabetSize : integer;
begin
if LanguageForm.GetLanguage = english then Result := ENGLISH_ALPHABET_SIZE
else Result := RUSSIAN_ALPHABET_SIZE;
end;
function GetAlphabet : TAlphabet;
var
alphabet : TAlphabet;
i : integer;
begin
if LanguageForm.GetLanguage = english then
begin
SetLength(alphabet, 26);
for i := 0 to 25 do
alphabet[i] := ENGLISH_ALPHABET[i];
end else
begin
SetLength(alphabet, 33);
for i := 0 to 32 do
alphabet[i] := RUSSIAN_ALPHABET[i];
end;
Result := alphabet;
end;
{procedure OpenSourceTextFile;
var
textFile : Text;
sourceText : string;
begin
try
AssignFile(textFile, SOURCE_TEXT_FILE_NAME);
Reset(textFile);
while (not EOF(textFile)) do
Read(textFile, sourceText);
CloseFile(textFile);
except
//добавить исключение
end;
end; }
procedure EncipherText(sourceText : string; const outputFileName : string);
var
alphabet : TAlphabet;
encipheredText : string;
begin
ConvertStringToUpperCase(sourceText);
RemoveUnexpectedSymbols(sourceText);
alphabet := GetAlphaBet;
FileUnit.saveTextToFile('enciphered.txt', GetEnchipheredText(alphabet, sourceText, KeyCheck.KeyCheckForm.GetKey, true));
encipheredText := FileUnit.loadTextFromFile('enciphered.txt');
Enchipher.Analize(encipheredText);
end;
function ordExt(const symb : char) : integer;
begin
if symb <= 'Z' then Result := ord(symb)
else case (symb) of
'А' : Result := 128;
'Б' : Result := 129;
'В' : Result := 130;
'Г' : Result := 131;
'Д' : Result := 132;
'Е' : Result := 133;
'Ё' : Result := 134;
'Ж' : Result := 135;
'З' : Result := 136;
'И' : Result := 137;
'Й' : Result := 138;
'К' : Result := 139;
'Л' : Result := 140;
'М' : Result := 141;
'Н' : Result := 142;
'О' : Result := 143;
'П' : Result := 144;
'Р' : Result := 145;
'С' : Result := 146;
'Т' : Result := 147;
'У' : Result := 148;
'Ф' : Result := 149;
'Х' : Result := 150;
'Ц' : Result := 151;
'Ч' : Result := 152;
'Ш' : Result := 153;
'Щ' : Result := 154;
'Ъ' : Result := 155;
'Ы' : Result := 156;
'Ь' : Result := 157;
'Э' : Result := 158;
'Ю' : Result := 159;
'Я' : Result := 160;
else Result := 0;
end
end;
function chrExt(const num : integer) : char;
begin
if num <= ENGLISH_ALPHABET_SIZE + ENGLISH_ALPHABET_SHIFT then Result := chr(num)
else case (num) of
128 : Result := 'А';
129 : Result := 'Б';
130 : Result := 'В';
131 : Result := 'Г';
132 : Result := 'Д';
133 : Result := 'Е';
134 : Result := 'Ё';
135 : Result := 'Ж';
136 : Result := 'З';
137 : Result := 'И';
138 : Result := 'Й';
139 : Result := 'К';
140 : Result := 'Л';
141 : Result := 'М';
142 : Result := 'Н';
143 : Result := 'О';
144 : Result := 'П';
145 : Result := 'Р';
146 : Result := 'С';
147 : Result := 'Т';
148 : Result := 'У';
149 : Result := 'Ф';
150 : Result := 'Х';
151 : Result := 'Ц';
152 : Result := 'Ч';
153 : Result := 'Ш';
154 : Result := 'Щ';
155 : Result := 'Ъ';
156 : Result := 'Ы';
157 : Result := 'Ь';
158 : Result := 'Э';
159 : Result := 'Ю';
160 : Result := 'Я';
end;
end;
function getNextSymbol(const symb : char; const step : integer) : char;
begin
if languageForm.GetLanguage = english then
result := chr(ord(symb) + step)
else
result := chrExt(ordExt(symb) + 1);
end;
function DecipherText(const fileName : string) : string;
var
alphabet : TAlphabet;
enciphedText : string;
begin
enciphedText := FileUnit.loadTextFromFile('enciphered.txt');
alphabet := GetAlphabet;
SaveEncipheredText('decipheredText.txt', GetEnchipheredText(alphabet, enciphedText, KeyCheck.KeyCheckForm.GetKey, DECIPHER));
Result := FileUnit.loadTextFromFile('decipheredText.txt');
end;
//процедура преобразования строки из нижнего регистра в верхний
procedure ConvertStringToUpperCase(var sourceText : string);
var
i : integer;
begin
//ветка для латинских букв
if LanguageForm.GetLanguage = english then
for i := 1 to Length(sourceText) do
begin
if (ord(sourceText[i]) >= 97) then ConvertSymbolToUpperCase(sourceText[i])
end
//ветка для кириллицы
else
for i := 1 to Length(sourceText) do
if (sourceText[i] >= 'а') and (sourceText[i] <= 'я') and (sourceText[i] <> 'ё')
then ConvertSymbolToUpperCase(sourceText[i])
else if (sourceText[i] = 'ё') then sourceText[i] := 'Ё';
end;
//процедура преобразования символа нижнего регистра в верхний
procedure ConvertSymbolToUpperCase(var symbol : char);
begin
symbol := chr(ord(symbol) - 32);
end;
//процедура удаления ненужных(игнорируемых) символов из строки
procedure RemoveUnexpectedSymbols(var sourceText : string);
var
i, shiftCount, len : integer;
begin
shiftCount := 0;
len := Length(sourceText);
i := 1;
while i <= len do
begin
while UnexpectedSymbol(sourceText[i + shiftCount]) and (i <= len) do
begin
inc(shiftCount);
dec(len);
end;
sourceText[i] := sourceText[i + shiftCount];
inc(i);
end;
SetLength(sourceText, len);
end;
//функция, определяющая несоответствие символа алфавиту
//не соответствует - true, соответствует - false
function UnexpectedSymbol(const symbol : char) : boolean;
begin
//для латиницы
if LanguageForm.GetLanguage = english then
Result := not ((ord(symbol) >= 65) and (ord(symbol) <= 90))
//для кириллицы
else
Result := not (((symbol >= 'А') and (symbol <= 'Я') or (symbol = 'Ё'))
or ((symbol >= 'а') and (symbol <= 'я') or (symbol = 'ё')));
end;
procedure SaveEncipheredText(fileName, encipheredText : string);
var
T : Text;
begin
AssignFile(T, fileName);
Rewrite(T);
Writeln(T, encipheredText);
CloseFile(T);
end;
function OpenSourceText(fileName : string) : string;
var
T : Text;
sourceText : string;
i : integer;
begin
AssignFile(T, fileName);
Reset(T);
SetLength(sourceText, 0);
Readln(T, sourceText);
CloseFile(T);
Result := sourceText;
end;
end.
|
unit E_UtilsFiles;
//------------------------------------------------------------------------------
// Модуль подпрограмм манипуляций с файловыми именами
//------------------------------------------------------------------------------
// Содержит утилиты по выделению отдельных частей ФС
// Работает только с путями Windows
// Есть калька стандартых из SysUtils, но эти должны работать быстрее (по идее)
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils,
C_FileNames;
//------------------------------------------------------------------------------
//! получить имя файла (*** и путь, если есть) без расширения и точки
//! -> ищет последнюю точку и возвращает строку до неё
//! возвращает неизменную строку, если точка не найдена
//------------------------------------------------------------------------------
function QExcludeFileExt(
const AFullName: string
): string;
//------------------------------------------------------------------------------
//! получить расширение файла без точки
//! -> ищет последнюю точку и возвращает строку после неё
//! возвращает неизменную строку, если точка не найдена
//------------------------------------------------------------------------------
function QExtractFileExt(
const AFullName: string
): string;
//------------------------------------------------------------------------------
//! получить имя файла с расширением из полного пути файла
//! -> ищет последнюю наклонную и возвращает строку после неё
//! возвращает неизменную строку, если наклонная не найдена
//------------------------------------------------------------------------------
function QExcludeFilePath(
const AFullPath: string
): string;
//------------------------------------------------------------------------------
//! получить путь к папке из полного пути файла
//! -> ищет последнюю наклонную и возвращает строку по неё (*** включая наклонную)
//! возвращает неизменную строку, если наклонная не найдена
//------------------------------------------------------------------------------
function QExtractFilePath(
const AFullPath: string
): string;
//------------------------------------------------------------------------------
implementation
function QExcludeFileExt(
const AFullName: string
): string;
var
//!
I: Integer;
//------------------------------------------------------------------------------
begin
for I := Length( AFullName ) downto 1 do
begin
if ( AFullName[I] = CExtDelim ) then Exit( Copy( AFullName, 1, I - 1 ) );
end;
Result := AFullName;
end;
function QExtractFileExt(
const AFullName: string
): string;
var
//!
I: Integer;
//------------------------------------------------------------------------------
begin
for I := Length( AFullName ) downto 1 do
begin
if ( AFullName[I] = CExtDelim ) then Exit( Copy( AFullName, I + 1, MaxInt ) );
end;
Result := AFullName;
end;
function QExcludeFilePath(
const AFullPath: string
): string;
var
//!
I: Integer;
//------------------------------------------------------------------------------
begin
for I := Length( AFullPath ) downto 1 do
begin
if ( AFullPath[I] = CPathDelim ) then Exit( Copy( AFullPath, I + 1, MaxInt ) );
end;
Result := AFullPath;
end;
function QExtractFilePath(
const AFullPath: string
): string;
var
//!
I: Integer;
//------------------------------------------------------------------------------
begin
for I := Length( AFullPath ) downto 1 do
begin
if ( AFullPath[I] = CPathDelim ) then Exit( Copy( AFullPath, 1, I ) );
end;
Result := AFullPath;
end;
end.
|
unit AbstractDataSet;
interface
type
TAbstractDataSet = class
private
FData : array of pointer;
protected
// Gets
function GetData(_pos: integer): pointer; virtual;
function GetDataLength: integer; virtual;
function GetLength: integer; virtual;
function GetLast: integer; virtual;
// Sets
procedure SetData(_pos: integer; _data: pointer); virtual;
procedure SetLength(_size: integer); virtual;
public
// constructors and destructors
constructor Create; overload;
constructor Create(const _Source: TAbstractDataSet); overload;
destructor Destroy; override;
// copies
procedure Assign(const _Source: TAbstractDataSet); virtual;
// properties
property Length: integer read GetLength write SetLength;
property Last: integer read GetLast;
end;
implementation
// Constructors and Destructors
constructor TAbstractDataSet.Create;
begin
Length := 0;
end;
constructor TAbstractDataSet.Create(const _Source: TAbstractDataSet);
begin
Assign(_Source);
end;
destructor TAbstractDataSet.Destroy;
begin
Length := 0;
inherited Destroy;
end;
// Gets
function TAbstractDataSet.GetData(_pos: integer): pointer;
begin
Result := FData[_pos];
end;
function TAbstractDataSet.GetLength: integer;
begin
Result := GetDataLength;
end;
function TAbstractDataSet.GetDataLength: integer;
begin
Result := High(FData) + 1;
end;
function TAbstractDataSet.GetLast: integer;
begin
Result := High(FData);
end;
// Sets
procedure TAbstractDataSet.SetData(_pos: integer; _data: pointer);
begin
FData[_pos] := _data;
end;
procedure TAbstractDataSet.SetLength(_size: Integer);
begin
System.SetLength(FData,_size);
end;
// copies
procedure TAbstractDataSet.Assign(const _Source: TAbstractDataSet);
var
maxData,i: integer;
begin
Length := _Source.Length;
maxData := GetDataLength() - 1;
for i := 0 to maxData do
begin
SetData(i,_Source.GetData(i));
end;
end;
end.
|
unit uSprItemDlg;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, DB, UtilsBase, TypInfo;
type
TSprItemDlg = class;
TItemDlgClass = class of TSprItemDlg;
TItemDlgState = (idsBrowse, idsEdit);
TCtrlMapItem = class(TCollectionItem)
private
FControl: TControl;
FField: TField;
public
property Control: TControl read FControl write FControl;
property Field: TField read FField write FField;
end;
TCtrlMap = class(TOwnedCollection)
private
FDataSet: TDataSet;
public
constructor Create(ADataSet: TDataSet; AOwner: TPersistent;
AClass: TCollectionItemClass);
function Find(const AName: string): TCtrlMapItem;
function IndexOf(const AName: string): Integer;
property DataSet: TDataSet read FDataSet;
end;
TSprItemDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
procedure Initialize;
protected
FMap: TCtrlMap;
FDataSet: TDataSet;
FState: TItemDlgState;
procedure OwnInitialize; virtual;
procedure UpdControls; virtual;
procedure SetCtrlsEnabled(Value: Boolean); virtual;
public
{ Public declarations }
class function Execute(ADataSet: TDataSet; AClass: TItemDlgClass; AState: TItemDlgState): Boolean;
procedure LoadData;
procedure AddMap(FieldName: string; Control: TControl);
property DataSet: TDataSet read FDataSet;
end;
var
SprItemDlg: TSprItemDlg;
implementation
{$R *.dfm}
constructor TCtrlMap.Create(ADataSet: TDataSet; AOwner: TPersistent;
AClass: TCollectionItemClass);
begin
inherited Create(AOwner, AClass);
FDataSet := ADataSet;
end;
function TCtrlMap.IndexOf(const AName: string): Integer;
begin
for Result := 0 to Count - 1 do
if AnsiCompareText(TCtrlMapItem(Items[Result]).Field.FieldName, AName) = 0 then Exit;
Result := -1;
end;
function TCtrlMap.Find(const AName: string): TCtrlMapItem;
var
I: Integer;
begin
I := IndexOf(AName);
if I < 0 then Result := nil else Result := TCtrlMapItem(Items[I]);
end;
class function TSprItemDlg.Execute(ADataSet: TDataSet; AClass: TItemDlgClass; AState: TItemDlgState): Boolean;
begin
with AClass.Create(nil) do
try
FDataSet := ADataSet;
FState := AState;
try
Initialize;
LoadData;
UpdControls;
Result := ShowModal = mrOk;
except
on E: Exception do
begin
ShowError(E.Message);
Result := false;
end;
end;
finally
Free;
end;
end;
procedure TSprItemDlg.Initialize;
begin
FMap := TCtrlMap.Create(FDataSet, Self, TCtrlMapItem);
OKBtn.Enabled := false;
if FState = idsBrowse then
Self.Caption := Self.Caption + ' ÏÐÎÑÌÎÒÐ'
else
if FState = idsEdit then
Self.Caption := Self.Caption + ' ÐÅÄÀÊÒÈÐÎÂÀÍÈÅ';
OwnInitialize;
end;
procedure TSprItemDlg.OwnInitialize;
begin
// Empty
end;
procedure TSprItemDlg.UpdControls;
begin
SetCtrlsEnabled(FState = idsEdit);
end;
procedure TSprItemDlg.SetCtrlsEnabled(Value: Boolean);
var
I: Integer;
vItem: TCtrlMapItem;
begin
for I := 0 to FMap.Count - 1 do
begin
vItem := TCtrlMapItem(FMap.Items[I]);
if IsPublishedProp(vItem.Control, 'ReadOnly') then
SetPropValue(vItem.Control, 'ReadOnly', not Value or vItem.Field.ReadOnly)
else
vItem.Control.Enabled := Value and not vItem.Field.ReadOnly;
if Value then
begin
if IsPublishedProp(vItem.Control, 'Color') then
begin
if vItem.Field.ReadOnly then
SetOrdProp(vItem.Control, 'Color', clBtnFace)
else
SetOrdProp(vItem.Control, 'Color', clWindow);
end;
end;
end;
end;
procedure TSprItemDlg.FormDestroy(Sender: TObject);
begin
if Assigned(FMap) then
FreeAndNil(FMap);
end;
procedure TSprItemDlg.LoadData;
var
I: Integer;
vItem: TCtrlMapItem;
begin
for I := 0 to FMap.Count - 1 do
begin
vItem := TCtrlMapItem(FMap.Items[I]);
if vItem.Control is TEdit then
TEdit(vItem.Control).Text := vItem.Field.AsString
else
if vItem.Control is TMemo then
TMemo(vItem.Control).Text := vItem.Field.AsString;
end;
end;
procedure TSprItemDlg.AddMap(FieldName: string; Control: TControl);
var
vItem: TCtrlMapItem;
vField: TField;
begin
if not Assigned(DataSet) then
raise Exception.Create('DataSet íå îïðåäåëåí');
vField := DataSet.FindField(FieldName);
if not Assigned(vField) then
raise Exception.Create('Ïîëå ' + FieldName + ' íå íàéäåíî');
vItem := TCtrlMapItem(FMap.Add);
vItem.Field := vField;
vItem.Control := Control;
end;
end.
|
unit Pospolite.View.Drawing.NativeDrawer;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
...
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Pospolite.View.Basics, Pospolite.View.Drawing.Basics,
Pospolite.View.Drawing.Drawer, math;
type
{ TPLNativeDrawer }
TPLNativeDrawer = class(TPLAbstractDrawer)
public
constructor Create(ACanvas: TCanvas); override;
destructor Destroy; override;
procedure DrawObjectBackground(const AObject: TPLHTMLObject); override;
procedure DrawObjectBorder(const AObject: TPLHTMLObject); override;
procedure DrawObjectOutline(const AObject: TPLHTMLObject); override;
procedure DrawObjectOutlineText(const AObject: TPLHTMLObject); override;
procedure DrawObjectText(const AObject: TPLHTMLObject); override;
procedure DrawObjectDebug(const AObject: TPLHTMLObject); override;
procedure DrawObjectShadow(const AObject: TPLHTMLObject); override;
procedure DrawObjectTextShadow(const AObject: TPLHTMLObject); override;
procedure DrawObjectPseudoBefore(const AObject: TPLHTMLObject); override;
procedure DrawObjectPseudoAfter(const AObject: TPLHTMLObject); override;
procedure DrawFrame(const ABorders: TPLDrawingBorders; const ARect: TPLRectF); override;
end;
function NewDrawingMatrixNative: IPLDrawingMatrix;
function NewDrawingPenNative(ABrush: IPLDrawingBrush; AWidth: TPLFloat = 1): IPLDrawingPen;
overload;
function NewDrawingPenNative(AColor: TPLColor; AWidth: TPLFloat = 1): IPLDrawingPen;
overload;
function NewDrawingSolidBrushNative(AColor: TPLColor): IPLDrawingBrushSolid;
function NewDrawingBitmapBrushNative(ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap;
function NewDrawingLinearGradientBrushNative(
const A, B: TPLPointF): IPLDrawingBrushGradientLinear;
function NewDrawingRadialGradientBrushNative(
const ARect: TPLRectF): IPLDrawingBrushGradientRadial;
function NewDrawingFontNative(AFontData: TPLDrawingFontData): IPLDrawingFont;
function NewDrawingSurfaceNative(ACanvas: TCanvas): IPLDrawingSurface;
function NewDrawingBitmapNative(AWidth, AHeight: TPLInt): IPLDrawingBitmap;
implementation
{ TPLNativeDrawer }
constructor TPLNativeDrawer.Create(ACanvas: TCanvas);
begin
inherited Create(ACanvas);
end;
destructor TPLNativeDrawer.Destroy;
begin
inherited Destroy;
end;
procedure TPLNativeDrawer.DrawObjectBackground(const AObject: TPLHTMLObject);
begin
inherited DrawObjectBackground(AObject);
end;
procedure TPLNativeDrawer.DrawObjectBorder(const AObject: TPLHTMLObject);
begin
inherited DrawObjectBorder(AObject);
end;
procedure TPLNativeDrawer.DrawObjectOutline(const AObject: TPLHTMLObject);
begin
inherited DrawObjectOutline(AObject);
end;
procedure TPLNativeDrawer.DrawObjectOutlineText(const AObject: TPLHTMLObject);
begin
inherited DrawObjectOutlineText(AObject);
end;
procedure TPLNativeDrawer.DrawObjectText(const AObject: TPLHTMLObject);
begin
inherited DrawObjectText(AObject);
end;
procedure TPLNativeDrawer.DrawObjectDebug(const AObject: TPLHTMLObject);
begin
inherited DrawObjectDebug(AObject);
end;
procedure TPLNativeDrawer.DrawObjectShadow(const AObject: TPLHTMLObject);
begin
inherited DrawObjectShadow(AObject);
end;
procedure TPLNativeDrawer.DrawObjectTextShadow(const AObject: TPLHTMLObject);
begin
inherited DrawObjectTextShadow(AObject);
end;
procedure TPLNativeDrawer.DrawObjectPseudoBefore(const AObject: TPLHTMLObject);
begin
inherited DrawObjectPseudoBefore(AObject);
end;
procedure TPLNativeDrawer.DrawObjectPseudoAfter(const AObject: TPLHTMLObject);
begin
inherited DrawObjectPseudoAfter(AObject);
end;
procedure TPLNativeDrawer.DrawFrame(const ABorders: TPLDrawingBorders;
const ARect: TPLRectF);
begin
//inherited DrawFrame(ABorders);
end;
function NewDrawingMatrixNative: IPLDrawingMatrix;
begin
end;
function NewDrawingPenNative(ABrush: IPLDrawingBrush; AWidth: TPLFloat
): IPLDrawingPen;
begin
end;
function NewDrawingPenNative(AColor: TPLColor; AWidth: TPLFloat): IPLDrawingPen;
begin
end;
function NewDrawingSolidBrushNative(AColor: TPLColor): IPLDrawingBrushSolid;
begin
end;
function NewDrawingBitmapBrushNative(ABitmap: IPLDrawingBitmap
): IPLDrawingBrushBitmap;
begin
end;
function NewDrawingLinearGradientBrushNative(const A, B: TPLPointF
): IPLDrawingBrushGradientLinear;
begin
end;
function NewDrawingRadialGradientBrushNative(const ARect: TPLRectF
): IPLDrawingBrushGradientRadial;
begin
end;
function NewDrawingFontNative(AFontData: TPLDrawingFontData): IPLDrawingFont;
begin
end;
function NewDrawingSurfaceNative(ACanvas: TCanvas): IPLDrawingSurface;
begin
end;
function NewDrawingBitmapNative(AWidth, AHeight: TPLInt): IPLDrawingBitmap;
begin
end;
end.
|
program simd;
//Example of how to insert C code into FPC project
// in this example, the C code uses SIMD intrinsics to generate SSE or Neon code
//you must compile scale2uint8.cpp first!
// fpc -O3 simd.pas; ./simd
{$mode objfpc}{$H+}
//{$mode delphi}{$H+}
uses Math, SysUtils,DateUtils;
{$L scale2uint8.o}
{$IFDEF Darwin}
function f32_i8sse(in32: pointer; out8: pointer; n: int64; slope, intercept: single): Integer; external name '__Z9f32_i8ssePfPaxff';
{$ELSE}
function f32_i8sse(in32: pointer; out8: pointer; n: int64; slope, intercept: single): Integer; external name '_Z9f32_i8ssePfPalff';
{$ENDIF}
procedure testF32(reps: integer = 3);
const
//number of voxels for test, based on HCP resting state https://protocols.humanconnectome.org/HCP/3T/imaging-protocols.html
n = 104*90*72*400; //= 104*90*72*400;
slope = 1;
intercept = 0.5;
var
i, r: Integer;
f: single;
in32: array of single;
out8fpc, out8c: array of byte;
startTime : TDateTime;
ms, cSum, fpcSum, cMin, fpcMin: Int64;
begin
//initialize
Writeln('values ', n, ' repetitions ', reps);
setlength(in32, n);
setlength(out8c, n);
setlength(out8fpc, n);
cSum := 0;
fpcSum := 0;
cMin := MaxInt;
fpcMin := MaxInt;
for i := 0 to (n-1) do
in32[i] := (random(2048) - 100) * 0.1;
for r := 1 to (reps) do begin
//c Code
startTime := Now;
f32_i8sse(@in32[0], @out8c[0], n, slope, intercept);
ms := MilliSecondsBetween(Now,startTime);
cMin := min(cMin, ms);
cSum += ms;
//fpc code:
startTime := Now;
for i := 0 to (n-1) do begin
f := max(min((in32[i] * slope) + intercept, 255), 0);
out8fpc[i] := round(f);
end;
ms := MilliSecondsBetween(Now,startTime);
fpcMin := min(fpcMin, ms);
fpcSum += ms;
end;
//validate results:
for i := 0 to (n-1) do begin
if (out8c[i] <> out8fpc[i]) then
Writeln(in32[i], ' c->', out8c[i], ' fpc-> ', out8fpc[i]);
end;
Writeln('f32 elapsed C (msec) min ', cMin, ' total ', cSum);
Writeln('f32 elapsed FPC (msec) min ', fpcMin, ' total ', fpcSum);
end; //testF32()
begin
testF32(3);
end.
|
unit APIWindow;
interface
uses
Windows,
Messages,
UtilFunc,
UtilClass;
type
TCreateParamsEx = record
dwExStyle: DWORD;
lpClassName: PChar;
lpWindowName: PChar;
dwStyle: DWORD;
X, Y, nWidth, nHeight: Integer;
hWndParent: HWND;
hMenu: HMENU;
hInstance: HINST;
lpParam: Pointer;
end;
//-------------- TAPIWindow -----------------------------------
TOnClassParams = procedure (var WC:TWndClass);
TOnWindowParams = procedure (var CP:TCreateParamsEx; dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW);
TAPIWindow = class(TObject)
private
FHandle: HWND;
FParent: HWND;
FClassName: string;
FColor: COLORREF;
FOnClassParams: TOnClassParams;
FOnWindowparams: TOnWindowParams;
FOnCreate: TNotifyMessage;
FOnDestroy: TNotifyMessage;
FOnCommand: TNotifyMessage;
procedure SetColor(value:COLORREF);
protected
procedure APIClassParams(var WC:TWndClass); virtual;
procedure APICreateParams(var CP: TCreateParamsEx; dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW); virtual;
public
constructor Create(hParent:HWND;ClassName:string);virtual;
destructor Destroy; override;
procedure DefaultHandler(var Message);override;
procedure DoCreate(dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW); virtual;
property Handle: HWND read FHandle;
property Parent: HWND read FParent;
property Color: COLORREF read FColor write SetColor;
property OnClassParams: TOnClassParams read FOnClassParams
write FOnClassParams;
property OnWindowParams: TOnWindowParams read FOnWindowParams
write FOnWindowparams;
property OnCreate: TNotifyMessage read FOnCreate write FOnCreate;
property OnDestroy: TNotifyMessage read FOnDestroy write FOnDestroy;
property OnCommand: TNotifyMessage read FOnCommand write FOnCommand;
end;
//-------------- TAPIWindow2 ----------------------------------
TAPIWindow2 = class(TAPIWindow)
private
FTrapMessage: TIntegerList;
FTrapHandler: TIntegerList;
FNumHandler: integer;
public
constructor Create(hParent:HWND;ClassName:string);override;
destructor Destroy; override;
procedure DefaultHandler(var Message); override;
procedure Trap(Msg: UINT; Hndlr: TNotifyMessage);
property NumHandler: integer read FNumHandler;
end;
//-------------- TAPIWindow3 ----------------------------------
TAPIWindow3 = class(TAPIWindow2)
private
FCursor: HCURSOR;
function GetWidth: integer;
procedure SetWidth(value: integer);
function GetHeight: integer;
procedure SetHeight(value: integer);
function GetVisible: Boolean;
procedure SetVisible(value: Boolean);
function GetEnable: Boolean;
procedure SetEnable(value:Boolean);
public
procedure DefaultHandler(var Message);override;
property Width: integer read GetWidth write SetWidth;
property Height: integer read GetHeight write SetHeight;
property Visible: Boolean read GetVisible write SetVisible;
property Enable: Boolean read GetEnable write SetEnable;
property Cursor: HCURSOR read FCursor write FCursor;
end;
//-------------- TSDIMainWindow ----------------------------------
TMaxMinRestore = (Max,Min,Restore);
TSDIMainWindow = class(TAPIWindow3)
private
function GetXPos: integer;
procedure SetXPos(value: integer);
function GetYPos: integer;
procedure SetYPos(value: integer);
function GetTitle: string;
procedure SetTitle(s: string);
function GetIcon: HICON;
procedure SetIcon(value: HICON);
function GetClientWidth: integer;
procedure SetClientWidth(value: integer);
function GetClientHeight: integer;
procedure SetClientHeight(value: integer);
function GetState: TMaxMinRestore;
procedure SetState(value: TMaxMinRestore);
public
constructor Create(hParent:HWND;ClassName:string);override;
procedure Center;
procedure Close;
property XPos: integer read GetXPos write SetXPos;
property YPos: integer read GetYPos write SetYPos;
property Title: string read GetTitle write SetTitle;
property Icon: HICON read GetIcon write SetIcon;
property ClientWidth: integer read GetClientWidth write SetClientWidth;
property ClientHeight: integer read GetClientHeight write SetClientHeight;
property State: TMaxMinRestore read GetState write SetState;
end;
//---------- TAPIPanel ----------------------------------------------
TEdgeStyle = (esNone,esRaised,esSunken);
TAPIPanel = class(TAPIWindow3)
private
FOuterEdge: TEdgeStyle;
FInnerEdge: TEdgeStyle;
FEdgeWidth: integer;
function GetDimension: TRect;
procedure SetDimension(value: TRect);
function GetXPos: integer;
procedure SetXPos(value: integer);
function GetYPos: integer;
procedure SetYPos(value: integer);
procedure SetOuterEdge(value: TEdgeStyle);
procedure SetInnerEdge(value: TEdgeStyle);
procedure SetEdgeWidth(value: integer);
protected
procedure APIClassParams(var WC:TWndClass); override;
procedure APICreateParams(var CP:TCreateParamsEx; dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW); override;
public
procedure DefaultHandler(var Message); override;
property Dimension : TRect read GetDimension write SetDimension;
property XPos: integer read GetXPos write SetXPos;
property YPos: integer read GetYPos write SetYPos;
property OuterEdge: TEdgeStyle read FOuterEdge write SetOuterEdge;
property InnerEdge: TEdgeStyle read FInnerEdge write SetInnerEdge;
property EdgeWidth: integer read FEdgeWidth write SetEdgeWidth;
end;
function CreatePanel(hParent:HWND;x,y,cx,cy:integer):TAPIPanel;
implementation
{---------------------------------------------------------------------
Custom Window Procedure
----------------------------------------------------------------------}
function CustomWndProc(hWindow: HWND; Msg: UINT; WParam: WPARAM;
LParam: LPARAM): LRESULT; stdcall;
var
WPMsg: TMessage;
Wnd: TAPIWindow;
pCS: PCreateStruct;
begin
Result := 0;
if Msg = WM_NCCREATE then begin
pCS := Pointer(LParam);
SetProp(hWindow,'OBJECT',integer(pCS^.lpCreateParams));
TAPIWindow(pCS^.lpCreateParams).FHandle := hWindow;
end;
WPMsg.Msg := Msg;
WPMsg.WParam := WParam;
WPMsg.LParam := LParam;
WPMsg.Result := 0;
Wnd := TAPIWindow(GetProp(hWindow,'OBJECT'));
case Msg of
{------------------ WM_DESTROY --------------------------------}
WM_DESTROY: begin
if Assigned(Wnd) then begin
Wnd.Dispatch(WPMsg);
Wnd.Free;
end;
end;
{--------- 他のメッセージをオブジェクトに Dispatch する ----}
else begin
if Assigned(Wnd) then Wnd.Dispatch(WPMsg);
if WPMsg.Result = 0 then
Result := DefWindowProc( hWindow, Msg, wParam, lParam )
else Result := WPMsg.Result;
end;
end; // case
end;
//-------------------- TAPIWindow ---------------------------
constructor TAPIWindow.Create(hParent:HWND;ClassName:string);
begin
FParent := hParent;
FClassName := ClassName;
FColor := clrBtnFace;
end;
destructor TAPIWindow.Destroy;
begin
RemoveProp(FHandle,'OBJECT');
inherited Destroy;
end;
procedure TAPIWindow.APIClassParams(var WC:TWndClass);
begin
WC.lpszClassName := PChar(FClassName);
WC.lpfnWndProc := @CustomWndProc;
WC.style := CS_VREDRAW or CS_HREDRAW or CS_NOCLOSE; //CS_NOCLOSE block close window
WC.hInstance := hInstance;
WC.hIcon := LoadIcon(0,IDI_APPLICATION);
WC.hCursor := LoadCursor(0,IDC_ARROW);
WC.hbrBackground := ( COLOR_WINDOW+1 );
WC.lpszMenuName := nil;
WC.cbClsExtra := 0;
WC.cbWndExtra := 0;
If Assigned(FOnClassParams) then FOnClassParams(WC);
end;
procedure TAPIWindow.APICreateParams(var CP: TCreateParamsEx; dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW);
begin
CP.dwExStyle := 0;
CP.lpClassName := PChar(FClassName);
CP.lpWindowName := PChar(FClassName);
CP.dwStyle := dwStyle;
CP.X := 200;
CP.Y := 100;
CP.nWidth := 300;
CP.nHeight := 200;
CP.hWndParent := FParent;
CP.hMenu := 0;
CP.hInstance := hInstance;
CP.lpParam := self;
If Assigned(FOnWindowParams) then FOnWindowParams(CP);
end;
procedure TAPIWindow.DefaultHandler(var Message);
var
AMsg:TMessage;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_CREATE: if Assigned(FOnCreate) then OnCreate(AMsg);
WM_DESTROY: if Assigned(FOnDestroy) then OnDestroy(AMsg);
WM_COMMAND: if Assigned(FOnCommand) then OnCommand(AMsg);
WM_ERASEBKGND: AMsg.result := EraseBkGnd(FHandle,FColor,AMsg.WParam);
end; // case
TMessage(Message).result := AMsg.result;
end;
procedure TAPIWindow.DoCreate(dwStyle: cardinal);
var
WC: TWndClass;
CP: TCreateParamsEx;
begin
APIClassParams(WC);
RegisterClass(WC);
APICreateParams(CP, dwStyle);
CreateWindowEx(CP.dwExStyle,
CP.lpClassName,
CP.lpWindowName,
CP.dwStyle,
CP.X,
CP.Y,
CP.nWidth,
CP.nHeight,
CP.hWndParent,
CP.hMenu,
CP.hInstance,
CP.lpParam);
ShowWindow( FHandle, CmdShow );
UpDateWindow(FHandle);
end;
procedure TAPIWindow.SetColor(value: COLORREF);
begin
if FColor = value then Exit;
FColor := value;
InvalidateRect(FHandle,nil,true);
end;
//-------------- TAPIWindow2 ----------------------------------
constructor TAPIWindow2.Create(hParent:HWND;ClassName:string);
begin
inherited Create(hParent,ClassName);
FTrapMessage := TIntegerList.Create($10,$10);
FTrapHandler := TIntegerList.Create($10,$10);
end;
destructor TAPIWindow2.Destroy;
begin
FTrapMessage.Free;
FTrapHandler.Free;
inherited Destroy;
end;
procedure TAPIWindow2.DefaultHandler(var Message);
var
AMsg:TMessage;
i: integer;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_CREATE:if Assigned(FOnCreate) then OnCreate(AMsg);
WM_COMMAND:if Assigned(FOnCreate) then OnCommand(AMsg);
WM_DESTROY:if Assigned(FOnDestroy) then OnDestroy(AMsg);
WM_ERASEBKGND:AMsg.result := EraseBkGnd(FHandle,FColor,AMsg.WParam);
else if FNumHandler > 0 then begin
i := FTrapMessage.Search(integer(AMsg.Msg));
if i <> -1 then TNotifyMessage(FTrapHandler[i])(AMsg);
end;
end; // case
TMessage(Message).result := AMsg.result;
end;
procedure TAPIWindow2.Trap(Msg: UINT; Hndlr: TNotifyMessage);
begin
Inc(FNumHandler);
FTrapMessage[FNumHandler-1] := integer(Msg);
FTrapHandler[FNumHandler-1] := integer(@Hndlr);
end;
//-------------- TAPIWindow3 ----------------------------------
procedure TAPIWindow3.DefaultHandler(var Message);
var
AMsg:TMessage;
i: integer;
begin
AMsg := TMessage(Message);
case AMsg.Msg of
WM_CREATE: if Assigned(FOnCreate) then OnCreate(AMsg);
WM_DESTROY: if Assigned(FOnDestroy) then OnDestroy(AMsg);
WM_COMMAND: if Assigned(FOnCommand) then OnCommand(AMsg);
WM_ERASEBKGND: AMsg.result := EraseBkGnd(FHandle,FColor,AMsg.WParam);
WM_SETCURSOR : if AMsg.LParamLo = HTCLIENT then begin
SetCursor(FCursor);
AMsg.Result := 1;
end;
else if FNumHandler > 0 then begin
i := FTrapMessage.Search(integer(AMsg.Msg));
if i <> -1 then TNotifyMessage(FTrapHandler[i])(AMsg);
end;
end; // case
TMessage(Message).result := AMsg.result;
end;
function TAPIWindow3.GetWidth: integer;
var
r: TRect;
begin
GetWindowRect(FHandle,r);
result := r.Right-r.Left+1;
end;
procedure TAPIWindow3.SetWidth(value: integer);
var
r: TRect;
begin
GetWindowRect(FHandle,r);
ChangeWindowSize(FHandle,value,(r.Bottom-r.Top+1));
end;
function TAPIWindow3.GetHeight: integer;
var
r: TRect;
begin
GetWindowRect(FHandle,r);
result := r.Bottom-r.Top+1;
end;
procedure TAPIWindow3.SetHeight(value: integer);
var
r: TRect;
begin
GetWindowRect(FHandle,r);
ChangeWindowSize(FHandle,(r.Right-r.Left+1),value);
end;
function TAPIWindow3.GetVisible: Boolean;
begin
result := IsWindowVisible(FHandle);
end;
procedure TAPIWindow3.SetVisible(value: Boolean);
begin
if value then
ShowWindow(FHandle,SW_SHOW)
else
ShowWindow(FHandle,SW_HIDE);
end;
function TAPIWindow3.GetEnable: Boolean;
begin
result := Boolean(IsWindowEnabled(FHandle));
end;
procedure TAPIWindow3.SetEnable(value: Boolean);
begin
EnableWindow(FHandle,value);
end;
//-------------- TSDIMainWindow ----------------------------------
constructor TSDIMainWindow.Create(hParent:HWND;ClassName:string);
begin
inherited Create(hParent,ClassName);
FCursor := LoadCursor(0,IDC_ARROW);
end;
procedure TSDIMainWindow.Center;
begin
CenterWindow(FHandle);
end;
procedure TSDIMainWindow.Close;
begin
DestroyWindow(FHandle);
end;
function TSDIMainWindow.GetXPos: integer;
var
r: TRect;
begin
GetWindowRect(FHandle,r);
result := r.Left;
end;
procedure TSDIMainWindow.SetXPos(value: integer);
begin
ChangeWindowPos(FHandle,value,YPos);
end;
function TSDIMainWindow.GetYPos: integer;
var
r: TRect;
begin
GetWindowRect(FHandle,r);
result := r.Top;
end;
procedure TSDIMainWindow.SetYPos(value: integer);
begin
ChangeWindowPos(FHandle,XPos,value);
end;
function TSDIMainWindow.GetTitle: string;
var
s: string;
len: integer;
begin
SetLength(s,100);
len := GetWindowText(FHandle,PChar(s),100);
SetLength(s,len);
result := s;
end;
procedure TSDIMainWindow.SetTitle(s: string);
begin
SetWindowText(FHandle, PChar(s));
end;
function TSDIMainWindow.GetIcon: HICON;
begin
result := GetClassLong(FHandle,GCL_HICON);
end;
procedure TSDIMainWindow.SetIcon(value: HICON);
begin
SetClassLong(FHandle,GCL_HICON,value);
end;
function TSDIMainWindow.GetClientWidth: integer;
var
r: TRect;
begin
GetClientRect(FHandle,r);
result := r.Right+1;
end;
procedure TSDIMainWindow.SetClientWidth(value: integer);
begin
ChangeWindowSize(FHandle,(value+Width-ClientWidth-1),Height);
end;
function TSDIMainWindow.GetClientHeight: integer;
var
r: TRect;
begin
GetClientRect(FHandle,r);
result := r.Bottom+1;
end;
procedure TSDIMainWindow.SetClientHeight(value: integer);
begin
ChangeWindowSize(FHandle,Width,(value+Height-ClientHeight));
end;
procedure TSDIMainWindow.SetState(value: TMaxMinRestore);
begin
case value of
Max: ShowWindow(FHandle,SW_SHOWMAXIMIZED);
Min: ShowWindow(FHandle,SW_SHOWMINIMIZED);
Restore: ShowWindow(FHandle,SW_RESTORE);
end;
end;
function TSDIMainWindow.GetState: TMaxMinRestore;
begin
if IsZoomed(FHandle) then
result := Max
else
if IsIconic(FHandle) then
result := Min
else
result := Restore;
end;
//--------------- TAPIPanel ----------------------------------------------
function PanelWndProc(hWindow: HWND; Msg: UINT; WParam: WPARAM;
LParam: LPARAM): LRESULT; stdcall;
var
WPMsg: TMessage;
Wnd: TAPIPanel;
pCS: PCreateStruct;
begin
Result := 0;
if Msg = WM_CREATE then begin
pCS := Pointer(LParam);
SetProp(hWindow,'OBJECT',integer(pCS^.lpCreateParams));
TAPIPanel(pCS^.lpCreateParams).FHandle := hWindow;
end;
Wnd := TAPIPanel(GetProp(hWindow,'OBJECT'));
case Msg of
{------------------ WM_PAINT,WMERASEBKGND ---------------------}
WM_PAINT,WM_ERASEBKGND: begin
WPMsg.Msg := Msg;
WPMsg.WParam := WParam;
WPMsg.LParam := LParam;
WPMsg.Result := Result;
if Assigned(Wnd) then begin
Wnd.Dispatch(WPMsg);
if WPMsg.result <> 0 then Result := WPMsg.result;
end;
end;
{------------------ WM_DESTROY --------------------------------}
WM_DESTROY: begin
if Assigned(Wnd) then begin
Wnd.Free;
end;
end;
else Result := DefWindowProc( hWindow, Msg, wParam, lParam );
end; //case
end;
procedure TAPIPanel.APIClassParams(var WC:TWndClass);
begin
WC.lpszClassName := 'APIPanel';
WC.lpfnWndProc := @PanelWndProc;
WC.style := CS_VREDRAW or CS_HREDRAW or CS_NOCLOSE; //CS_NOCLOSE block close window
WC.hInstance := hInstance;
WC.hIcon := 0;
WC.hCursor := LoadCursor(0,IDC_ARROW);
WC.hbrBackground := ( COLOR_BTNFACE+1 );
WC.lpszMenuName := nil;
WC.cbClsExtra := 0;
WC.cbWndExtra := 0;
FOuterEdge := esRaised;
FInnerEdge := esNone;
FEdgeWidth := 2;
If Assigned(FOnClassParams) then FOnClassParams(WC);
end;
procedure TAPIPanel.APICreateParams(var CP: TCreateParamsEx; dwStyle: cardinal = WS_VISIBLE or WS_OVERLAPPEDWINDOW);
begin
dwStyle := WS_CHILD or WS_VISIBLE or WS_CLIPSIBLINGS;
CP.dwExStyle := WS_EX_CONTROLPARENT;
CP.lpClassName := 'APIPanel';
CP.lpWindowName := 'APIPanel';
CP.dwStyle := dwStyle;
CP.X := 0;
CP.Y := 0;
CP.nWidth := 0;
CP.nHeight := 0;
CP.hWndParent := FParent;
CP.hMenu := 0;
CP.hInstance := hInstance;
CP.lpParam := self;
If Assigned(FOnWindowParams) then FOnWindowParams(CP);
end;
procedure TAPIPanel.DefaultHandler(var Message);
var
AMsg:TMessage;
r: TRect;
DC: HDC;
ps: TPaintStruct;
begin
AMsg := TMessage(message);
case AMsg.Msg of
WM_PAINT:begin
DC := BeginPaint(FHandle,ps);
GetClientRect(FHandle,r);
case FOuterEdge of
esRaised:DrawEdge(DC,r,BDR_RAISEDOUTER or BDR_RAISEDINNER,
BF_RECT);
esSunken:DrawEdge(DC,r,BDR_SUNKENOUTER or BDR_SUNKENINNER,
BF_RECT);
end;
InflateRect(r,-FEdgeWidth,-FEdgeWidth);
case FInnerEdge of
esRaised:DrawEdge(DC,r,BDR_RAISEDOUTER or BDR_RAISEDINNER,
BF_RECT);
esSunken:DrawEdge(DC,r,BDR_SUNKENOUTER or BDR_SUNKENINNER,
BF_RECT);
end;
EndPaint(FHandle,ps);
end;
WM_ERASEBKGND:TMessage(message).Result := EraseBkgnd(FHandle,
FColor,AMsg.WParam);
end; // case
end;
function TAPIPanel.GetDimension: TRect;
begin
result := SetDim(XPos,YPos,Width,Height);
end;
procedure TAPIPanel.SetDimension(value: TRect);
begin
MoveWindow(FHandle,value.left, value.top,
value.right, value.bottom, true);
end;
function TAPIPanel.GetXPos: integer;
var
r: TRect;
p: TPoint;
begin
GetWindowRect(FHandle,r);
p.x := r.Left; p.y := r.Top;
ScreenToClient(FParent,p);
result := p.x;
end;
procedure TAPIPanel.SetXPos(value: integer);
begin
ChangeWindowPos(FHandle,value,YPos);
end;
function TAPIPanel.GetYPos: integer;
var
r: TRect;
p: TPoint;
begin
GetWindowRect(FHandle,r);
p.x := r.Left; p.y := r.Top;
ScreenToClient(FParent,p);
result := p.y;
end;
procedure TAPIPanel.SetYPos(value: integer);
begin
ChangeWindowPos(FHandle,XPos,value);
end;
procedure TAPIPanel.SetOuterEdge(value: TEdgeStyle);
begin
FOuterEdge := value;
InvalidateRect(FHandle,nil,true);
end;
procedure TAPIPanel.SetInnerEdge(value: TEdgeStyle);
begin
FInnerEdge := value;
InvalidateRect(FHandle,nil,true);
end;
procedure TAPIPanel.SetEdgeWidth(value: integer);
begin
FEdgeWidth := value;
InvalidateRect(FHandle,nil,true);
end;
function CreatePanel(hParent:HWND;x,y,cx,cy:integer):TAPIPanel;
begin
result := TAPIPanel.Create(hParent,'');
result.DoCreate;
result.Dimension := SetDim(x,y,cx,cy);
end;
end. |
{*****************************************
* *
* Step by step from tightly coupled code *
* to dependency injection *
* *
******************************************}
unit ProcessOrder;
interface
type
TOrder = class
end;
TOrderEntry = class
public
function EnterOrderIntoDatabase(aOrder: TOrder): Boolean;
end;
TOrderValidator = class
public
function ValidateOrder(aOrder: TOrder): Boolean;
end;
TOrderProcessor = class
private
fOrdervalidator: TOrderValidator;
fOrderEntry: TOrderEntry;
public
constructor Create(aOrdervalidator: TOrderValidator; aOrderEntry: TorderEntry);
destructor Destroy; override;
function ProcessOrder(aOrder: TOrder): Boolean;
end;
procedure DoOrderProcessing;
implementation
procedure DoOrderProcessing;
var
Order: TOrder;
OrderProcessor: TOrderProcessor;
OrderValidator: TOrderValidator;
OrderEntry: TOrderEntry;
begin
Order := TOrder.Create;
try
OrderValidator := TOrderValidator.Create;
OrderEntry := TOrderEntry.Create;
OrderProcessor := TOrderProcessor.Create(OrderValidator, OrderEntry);
try
if OrderProcessor.ProcessOrder(Order) then
Writeln('Order successfully processed...');
finally
OrderProcessor.Free;
end;
finally
Order.Free;
end;
end;
constructor TOrderProcessor.Create(aOrdervalidator: TOrderValidator; aOrderEntry: TorderEntry);
begin
FOrderValidator := aOrdervalidator;
FOrderEntry := aOrderEntry;
end;
destructor TOrderProcessor.Destroy;
begin
FOrderValidator.free;
FOrderEntry.free;
inherited;
end;
function TOrderProcessor.ProcessOrder(aOrder: TOrder): Boolean;
begin
Result := FOrderValidator.ValidateOrder(aOrder) and FOrderEntry.EnterOrderIntoDatabase(aOrder);
WriteLn('Order has been processed...');
end;
{ TOrderValidator }
function TOrderValidator.ValidateOrder(aOrder: TOrder): Boolean;
begin
Result := True;
end;
{ TOrderEntry }
function TOrderEntry.EnterOrderIntoDatabase(aOrder: TOrder): Boolean;
begin
Result := True;
end;
end.
|
//------------------------------------------------------------------------------
//HeliosOptions UNIT
//------------------------------------------------------------------------------
// What it does-
// This unit is used to gain access to configuration variables loaded from
// Helios.ini.
//
// Changes -
// January 7th, 2007 - RaX - Broken out from ServerOptions.
//
//------------------------------------------------------------------------------
unit HeliosOptions;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IniFiles;
type
//------------------------------------------------------------------------------
//THeliosOptions CLASS
//------------------------------------------------------------------------------
THeliosOptions = class(TMemIniFile)
private
//private variables
fMapDirectory : String;
fDatabaseDirectory : String;
fConfigDirectory : String;
fScriptDirectory : String;
fLoginEnabled : Boolean;
fCharaEnabled : Boolean;
fInterEnabled : Boolean;
fZoneEnabled : Boolean;
fReconnectDelay : LongWord;
public
property MapDirectory : String read fMapDirectory;
property DatabaseDirectory : String read fDatabaseDirectory;
property ConfigDirectory : String read fConfigDirectory;
property ScriptDirectory : String read fScriptDirectory;
property LoginEnabled : Boolean read fLoginEnabled;
property CharaEnabled : Boolean read fCharaEnabled;
property InterEnabled : Boolean read fInterEnabled;
property ZoneEnabled : Boolean read fZoneEnabled;
property ReconnectDelay : LongWord read fReconnectDelay;
//Public methods
procedure Load;
procedure Save;
end;
//------------------------------------------------------------------------------
implementation
uses
Classes,
SysUtils,
WinLinux;
//------------------------------------------------------------------------------
//Load() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine is called to load the ini file values from file itself.
// This routine contains multiple subroutines. Each one loads a different
// portion of the ini. All changes to said routines should be documented in
// THIS changes block.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure THeliosOptions.Load;
var
Section : TStringList;
//--------------------------------------------------------------------------
//LoadFolderStructure SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadFolderStructure;
begin
ReadSectionValues('Folder Structure', Section);
if NOT IsValidFolderName(Section.Values['Maps']) then
begin
Section.Values['Maps'] := './Maps';
end;
if NOT IsValidFolderName(Section.Values['Database']) then
begin
Section.Values['Database'] := './Database';
end;
if NOT IsValidFolderName(Section.Values['Configuration']) then
begin
Section.Values['Configuration'] := './Configuration';
end;
if NOT IsValidFolderName(Section.Values['Script']) then
begin
Section.Values['Script'] := './Scripts';
end;
fMapDirectory := Section.Values['Maps'];
fDatabaseDirectory := Section.Values['Database'];
fConfigDirectory := Section.Values['Configuration'];
fScriptDirectory := Section.Values['Script'];
end;{Subroutine LoadZone}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadLogin SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadLogin;
begin
ReadSectionValues('Login', Section);
fLoginEnabled := StrToBoolDef(Section.Values['Enabled'] ,true);
end;{Subroutine LoadLogin}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadChara SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadChara;
begin
ReadSectionValues('Character', Section);
fCharaEnabled := StrToBoolDef(Section.Values['Enabled'] ,true);
end;{Subroutine LoadChara}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadInter SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadInter;
begin
ReadSectionValues('Inter', Section);
fInterEnabled := StrToBoolDef(Section.Values['Enabled'] ,true);
end;{Subroutine LoadInter}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadZone SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadZone;
begin
ReadSectionValues('Zone', Section);
fZoneEnabled := StrToBoolDef(Section.Values['Enabled'] ,true);
end;{Subroutine LoadZone}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadGeneral SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadGeneral;
begin
ReadSectionValues('General', Section);
fReconnectDelay := StrToIntDef(Section.Values['Reconnect Delay'] , 3000);
end;{Subroutine LoadZone}
//--------------------------------------------------------------------------
begin
Section := TStringList.Create;
Section.QuoteChar := '"';
Section.Delimiter := ',';
LoadFolderStructure;
LoadLogin;
LoadChara;
LoadInter;
LoadZone;
LoadGeneral;
Section.Free;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine saves all configuration values defined here to the .ini
// file.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure THeliosOptions.Save;
begin
//Folder Structure
WriteString('Folder Structure','Maps',MapDirectory);
WriteString('Folder Structure','Database',DatabaseDirectory);
WriteString('Folder Structure','Configuration',ConfigDirectory);
WriteString('Folder Structure','Script',ScriptDirectory);
//Login
WriteString('Login','Enabled',BoolToStr(LoginEnabled));
//Chara
WriteString('Character','Enabled',BoolToStr(CharaEnabled));
//Inter
WriteString('Inter','Enabled',BoolToStr(InterEnabled));
//Zone
WriteString('Zone','Enabled',BoolToStr(ZoneEnabled));
//General
WriteString('General', 'Reconnect Delay', IntToStr(ReconnectDelay));
UpdateFile;
end;{Save}
//------------------------------------------------------------------------------
end{ServerOptions}.
|
unit ThDbData;
interface
uses
Classes, DB, DBCtrls;
type
TThDbData = class(TFieldDataLink)
protected
function GetFieldText: string;
public
procedure Notification(AComponent: TComponent; Operation: TOperation);
public
property FieldText: string read GetFieldText;
end;
implementation
{ TThDbData }
function TThDbData.GetFieldText: string;
begin
if Field <> nil then
begin
if Field.DataType = ftMemo then
Result := Field.AsString
else
Result := Field.DisplayText;
end else
Result := '';
end;
procedure TThDbData.Notification(AComponent: TComponent;
Operation: TOperation);
begin
//if (Operation = opRemove) and (AComponent = DataSource) then
// DataSource := nil;
end;
end.
|
unit uIImageViewer;
interface
uses
Generics.Collections,
System.Classes,
Vcl.Controls,
Vcl.Graphics,
Vcl.ComCtrls,
Dmitry.Controls.LoadingSign,
Dmitry.Controls.WebLink,
uMemory,
uInterfaces,
uDBEntities,
uFaceDetection,
uExifInfo,
uThreadForm;
type
TImageViewerButton = (ivbPrevious, ivbNext, ivbRotateCW, ivbRotateCCW, ivbInfo, ivbRating, ivbZoomIn, ivbZoomOut);
TImageViewerButtonState = (ivbsVisible, ivbsEnabled, ivbsDown);
TImageViewerButtonStates = set of TImageViewerButtonState;
TButtonState = class
private
FButton: TImageViewerButton;
FStates: TImageViewerButtonStates;
public
constructor Create(Button: TImageViewerButton; States: TImageViewerButtonStates = []);
function AddState(State: TImageViewerButtonState): TButtonState;
function HasState(State: TImageViewerButtonState): Boolean;
property Button: TImageViewerButton read FButton;
property States: TImageViewerButtonStates read FStates;
end;
TButtonStates = class
private
FButtons: TList<TButtonState>;
function GetButtonByType(Index: TImageViewerButton): TButtonState;
public
constructor Create;
destructor Destroy; override;
property Buttons[Index: TImageViewerButton]: TButtonState read GetButtonByType; default;
end;
TPersonsFoundOnImageEvent = procedure(Sender: TObject; FileName: string; Items: TFaceDetectionResult) of object;
TBeginLoadingImageEvent = procedure(Sender: TObject; NewImage: Boolean) of object;
TUpdateButtonsStateEvent = procedure(Sender: TObject; Buttons: TButtonStates) of object;
type
IImageViewer = interface(IFaceResultForm)
procedure AttachTo(OwnerForm: TThreadForm; Control: TWinControl; X, Y: Integer);
procedure LoadFiles(FileList: TMediaItemCollection);
procedure LoadPreviousFile;
procedure LoadNextFile;
procedure ResizeTo(Width, Height: Integer);
procedure SetStaticImage(Image: TBitmap; RealWidth, RealHeight: Integer; Rotation: Integer; ImageScale: Double; Exif: IExifInfo);
procedure SetAnimatedImage(Image: TGraphic; RealWidth, RealHeight: Integer; Rotation: Integer; ImageScale: Double; Exif: IExifInfo);
procedure FailedToLoadImage(ErrorMessage: string);
procedure ZoomOut;
procedure ZoomIn;
procedure RotateCW;
procedure RotateCCW;
procedure SetFaceDetectionControls(AWlFaceCount: TWebLink; ALsDetectingFaces: TLoadingSign; ATbrActions: TToolBar);
procedure FinishDetectionFaces;
procedure SelectPerson(PersonID: Integer);
procedure ResetPersonSelection;
procedure StartPersonSelection;
procedure StopPersonSelection;
procedure CheckFaceIndicatorVisibility;
procedure UpdateAvatar(PersonID: Integer);
function GetWidth: Integer;
function GetHeight: Integer;
function GetTop: Integer;
function GetLeft: Integer;
function GetActiveThreadId: TGUID;
function GetItem: TMediaItem;
function GetDisplayBitmap: TBitmap;
function GetCurentFile: string;
function GetIsAnimatedImage: Boolean;
property Width: Integer read GetWidth;
property Height: Integer read GetHeight;
property Top: Integer read GetTop;
property Left: Integer read GetLeft;
property ActiveThreadId: TGUID read GetActiveThreadId;
property Item: TMediaItem read GetItem;
property DisplayBitmap: TBitmap read GetDisplayBitmap;
property CurentFile: string read GetCurentFile;
property IsAnimatedImage: Boolean read GetIsAnimatedImage;
function GetText: string;
procedure SetText(Text: string);
function GetShowInfo: Boolean;
procedure SetShowInfo(Value: Boolean);
procedure SetOnBeginLoadingImage(Event: TBeginLoadingImageEvent);
function GetOnBeginLoadingImage: TBeginLoadingImageEvent;
procedure SetOnRequestNextImage(Event: TNotifyEvent);
function GetOnRequestNextImage: TNotifyEvent;
procedure SetOnRequestPreviousImage(Event: TNotifyEvent);
function GetOnRequestPreviousImage: TNotifyEvent;
procedure SetOnDblClick(Event: TNotifyEvent);
function GetOnDblClick: TNotifyEvent;
procedure SetOnPersonsFoundOnImage(Event: TPersonsFoundOnImageEvent);
function GetOnPersonsFoundOnImage: TPersonsFoundOnImageEvent;
procedure SetOnStopPersonSelection(Event: TNotifyEvent);
function GetOnStopPersonSelection: TNotifyEvent;
procedure SetOnUpdateButtonsState(Event: TUpdateButtonsStateEvent);
function GetOnUpdateButtonsState: TUpdateButtonsStateEvent;
property Text: string read GetText write SetText;
property ShowInfo: Boolean read GetShowInfo write SetShowInfo;
property OnBeginLoadingImage: TBeginLoadingImageEvent read GetOnBeginLoadingImage write SetOnBeginLoadingImage;
property OnRequestNextImage: TNotifyEvent read GetOnRequestNextImage write SetOnRequestNextImage;
property OnRequestPreviousImage: TNotifyEvent read GetOnRequestPreviousImage write SetOnRequestPreviousImage;
property OnDblClick: TNotifyEvent read GetOnDblClick write SetOnDblClick;
property OnPersonsFoundOnImage: TPersonsFoundOnImageEvent read GetOnPersonsFoundOnImage write SetOnPersonsFoundOnImage;
property OnStopPersonSelection: TNotifyEvent read GetOnStopPersonSelection write SetOnStopPersonSelection;
property OnUpdateButtonsState: TUpdateButtonsStateEvent read GetOnUpdateButtonsState write SetOnUpdateButtonsState;
end;
implementation
{ TButtonState }
function TButtonState.AddState(State: TImageViewerButtonState): TButtonState;
begin
FStates := FStates + [State];
Result := Self;
end;
constructor TButtonState.Create(Button: TImageViewerButton;
States: TImageViewerButtonStates = []);
begin
FButton := Button;
FStates := States;
end;
function TButtonState.HasState(State: TImageViewerButtonState): Boolean;
begin
Result := [State] * FStates <> [];
end;
{ TButtonStates }
constructor TButtonStates.Create;
begin
FButtons := TList<TButtonState>.Create;
end;
destructor TButtonStates.Destroy;
begin
FreeList(FButtons);
inherited;
end;
function TButtonStates.GetButtonByType(Index: TImageViewerButton): TButtonState;
var
I: Integer;
begin
for I := 0 to FButtons.Count - 1 do
begin
if FButtons[I].Button = Index then
Exit(FButtons[I]);
end;
Result := TButtonState.Create(Index);
FButtons.Add(Result);
end;
end.
|
namespace com.example.android.lunarlander;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
android.content,
android.content.res,
android.graphics,
android.graphics.drawable,
android.os,
android.util,
android.view,
android.widget;
/// <summary>
/// View that draws, takes keystrokes, etc. for a simple LunarLander game.
///
/// Has a mode which RUNNING, PAUSED, etc. Has a x, y, dx, dy, ... capturing the
/// current ship physics. All x/y etc. are measured with (0,0) at the lower left.
/// updatePhysics() advances the physics based on realtime. draw() renders the
/// ship, and does an invalidate() to prompt another draw() as soon as possible
/// by the system.
/// </summary>
type
Direction = (Top, Right, Bottom, Left);
LunarView = public class(SurfaceView, SurfaceHolder.Callback)
private
// Pointer to the text view to display "Paused.." etc.
var mStatusText: TextView;
// The thread that actually draws the animation
var thread: LunarThread;
var mContext: Context;
var mHandler: Handler;
// If this is set, then we have a thread active to resume
var mGameIsRunning: Boolean := false;
method whichTriangularQuadrant(x, y: Single): Direction;
public
constructor(ctx: Context; attrs: AttributeSet);
method getThread: LunarThread;
method onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean; override;
method onKeyUp(keyCode: Integer; msg: KeyEvent): Boolean; override;
method onTouchEvent(evt: MotionEvent): Boolean; override;
method onWindowFocusChanged(hasWindowFocus: Boolean); override;
method setTextView(textView: TextView);
method surfaceChanged(holder: SurfaceHolder; format, width, height: Integer);
method surfaceCreated(holder: SurfaceHolder);
method surfaceDestroyed(holder: SurfaceHolder);
end;
implementation
constructor LunarView(ctx: Context; attrs: AttributeSet);
begin
inherited;
Log.w(&Class.Name, 'LunarView constructor');
mContext := ctx;
// register our interest in hearing about changes to our surface
var surfHolder := Holder;
surfHolder.addCallback(self);
mHandler := new Handler(new interface Handler.Callback(
handleMessage :=
method(m: Message);
begin
mStatusText.Visibility := m.Data.Int['viz'];
mStatusText.Text := m.Data.String['text']
end));
// create thread only; it's started in surfaceCreated()
Log.w(&Class.Name, 'Creating gameplay thread');
thread := new LunarThread(surfHolder, mContext, mHandler);
Focusable := true;
end;
/// <summary>
/// Fetches the animation thread corresponding to this LunarView.
/// </summary>
/// <returns>the animation thread</returns>
method LunarView.getThread: LunarThread;
begin
exit thread
end;
/// <summary>
/// Standard override to get key-press events.
/// </summary>
/// <param name="keyCode"></param>
/// <param name="msg"></param>
/// <returns></returns>
method LunarView.onKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
begin
exit thread.doKeyDown(keyCode, msg)
end;
/// <summary>
/// Standard override for key-up. We actually care about these, so we can
/// turn off the engine or stop rotating.
/// </summary>
/// <param name="keyCode"></param>
/// <param name="msg"></param>
/// <returns></returns>
method LunarView.onKeyUp(keyCode: Integer; msg: KeyEvent): Boolean;
begin
exit thread.doKeyUp(keyCode, msg)
end;
method LunarView.onTouchEvent(evt: MotionEvent): Boolean;
begin
//Get coords by index to cater for multiple pointers (multi-touch)
var pointerIndex := evt.ActionIndex;
var x := evt.X[pointerIndex];
var y := evt.Y[pointerIndex];
//var pointerId := evt.PointerId[pointerIndex];
var action := evt.ActionMasked;
//var pointCnt := motionEvent.PointerCount;
if action in [MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN,
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP] then
begin
var key: Integer := case whichTriangularQuadrant(x, y) of
Direction.Left: KeyEvent.KEYCODE_Q; //same as DPad left
Direction.Right: KeyEvent.KEYCODE_W; //same as DPad right
Direction.Top: KeyEvent.KEYCODE_DPAD_UP; //start game or pause
else {Direction.Bottom:} KeyEvent.KEYCODE_SPACE; //fire thrusters - same as DPad centre
end;
if action in [MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN] then
onKeyDown(key, new KeyEvent(KeyEvent.ACTION_DOWN, key))
else //MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP
onKeyUp(key, new KeyEvent(KeyEvent.ACTION_UP, key))
end;
exit true
end;
/// <summary>
/// Standard window-focus override. Notice focus lost so we can pause on
/// focus lost. e.g. user switches to take a call.
/// </summary>
/// <param name="hasWindowFocus"></param>
method LunarView.onWindowFocusChanged(hasWindowFocus: Boolean);
begin
if not hasWindowFocus then
thread.pause
end;
/// <summary>
/// Installs a pointer to the text view used for messages.
/// </summary>
/// <param name="textView"></param>
method LunarView.setTextView(textView: TextView);
begin
mStatusText := textView
end;
/// <summary>
/// Callback invoked when the Surface has been created and is ready to be
/// used
/// </summary>
/// <param name="holder"></param>
method LunarView.surfaceCreated(holder: SurfaceHolder);
begin
Log.w(&Class.Name, 'surfaceCreated');
// start the thread here
if not mGameIsRunning then
begin
Log.w(&Class.Name, 'starting thread');
thread.start;
mGameIsRunning := true
end
else
begin
Log.w(&Class.Name, 'unpausing thread');
thread.unpause;
end
end;
/// <summary>
/// Callback invoked when the surface dimensions change.
/// </summary>
/// <param name="holder"></param>
/// <param name="format"></param>
/// <param name="width"></param>
/// <param name="height"></param>
method LunarView.surfaceChanged(holder: SurfaceHolder; format, width, height: Integer);
begin
thread.setSurfaceSize(width, height)
end;
/// <summary>
/// Callback invoked when the Surface has been destroyed and must no longer
/// be touched. WARNING: after this method returns, the Surface/Canvas must
/// never be touched again!
/// </summary>
/// <param name="holder"></param>
method LunarView.surfaceDestroyed(holder: SurfaceHolder);
begin
Log.w(&Class.Name, 'surfaceDestroyed');
end;
method LunarView.whichTriangularQuadrant(x, y: Single): Direction;
begin
var slope: Single := Single(Width) / Height;
var leftOrBottom: Boolean := x < y * slope;
var leftOrTop: Boolean := x < (Height - y) * slope;
if leftOrTop and leftOrBottom then
exit Direction.Left;
if leftOrTop and not leftOrBottom then
exit Direction.Top;
if not leftOrTop and leftOrBottom then
exit Direction.Bottom;
//Only option now
//if not leftOrTop and not leftOrBottom then
exit Direction.Right;
end;
end. |
unit FormMainMenu;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMainMenuForm = class(TForm)
btnNewGame: TButton;
btnLoadGame: TButton;
btnResult: TButton;
btnExit: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnExitClick(Sender: TObject);
procedure btnResultClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnNewGameClick(Sender: TObject);
procedure btnLoadGameClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
newGame: Boolean;
end;
var
MainMenuForm: TMainMenuForm;
implementation
uses TitleForm, ResultsForm, FormGame;
{$R *.dfm}
procedure TMainMenuForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FormLoad.Close;
end;
procedure TMainMenuForm.btnExitClick(Sender: TObject);
begin
MainMenuForm.Close;
end;
procedure TMainMenuForm.btnResultClick(Sender: TObject);
begin
FormResults.Visible := true;
end;
procedure TMainMenuForm.FormCreate(Sender: TObject);
begin
if (not Assigned(FormResults)) then
begin
FormResults:=TFormResults.Create(Self);
end;
end;
procedure TMainMenuForm.btnNewGameClick(Sender: TObject);
begin
MainMenuForm.Visible := false;
MainMenuForm.newGame := true;
if (not Assigned(GameForm)) then
begin
GameForm:=TGameForm.Create(Self);
GameForm.Show;
end;
end;
procedure TMainMenuForm.btnLoadGameClick(Sender: TObject);
begin
MainMenuForm.Visible := false;
MainMenuForm.newGame := false;
if (not Assigned(GameForm)) then
begin
GameForm:=TGameForm.Create(Self);
GameForm.Show;
end;
end;
end.
|
unit unCustomPanelButton;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Graphics,
Vcl.StdCtrls, Vcl.ImgList;
type
TRedimensionar = (trManual, trAutomatico);
TCustomPanelButton = class(TPanel)
private
FQImage: TPicture;
panelIMG:Tpanel;
panelLabel:Tpanel;
Image1: TImage;
lbCaption: TLabel;
FQImageRedimensiar: TRedimensionar;
FQTexCaption: String;
FQImageIndex: Integer;
FQImageList: TCustomImageList;
FQImageWidth: Integer;
FQTextFont: TFont;
procedure setQImage(const Value: TPicture);
procedure setFQTexCaption(const Value: String);
procedure ArredondarImagem(Panel: TPanel);
procedure setQImageIndex(const Value: Integer);
procedure setQImageWidth(const Value: Integer);
procedure setQImageList(const Value: TCustomImageList);
procedure setQTextFont(const Value: TFont);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent); override;
procedure Resize(Sender:TObject);
published
{ Published declarations }
property QTexTCaption:String read FQTexCaption write setFQTexCaption;
property QTextFont:TFont read FQTextFont write setQTextFont;
property QImageIndex:Integer read FQImageIndex write setQImageIndex default -1;
property QImageList: TCustomImageList read FQImageList write setQImageList;
property QImageWidth: Integer read FQImageWidth write setQImageWidth;
property QImageRedimensiar:TRedimensionar read FQImageRedimensiar write FQImageRedimensiar;
end;
procedure Register;
implementation
uses
Winapi.Windows;
procedure Register;
begin
RegisterComponents('Suites Quinhone', [TCustomPanelButton]);
end;
{ TCustomPanelButton }
constructor TCustomPanelButton.Create(AOwner: TComponent);
begin
inherited;
FQImageIndex := -1;
FQImageRedimensiar := trAutomatico;
Self.Padding.Left := 3;
Self.Padding.Right := 3;
Self.Padding.Top := 3;
Self.Padding.Bottom := 3;
panelIMG := TPanel.Create(Self);
panelIMG.Parent := Self;
panelIMG.Width := Trunc(Self.Width/3);
panelIMG.Align := TAlign.alLeft;
panelIMG.BevelInner := TBevelCut.bvNone;
panelIMG.BevelKind := TBevelKind.bkNone;
panelIMG.BevelOuter := TBevelCut.bvNone;
panelIMG.OnResize := Resize;
panelLabel := TPanel.Create(Self);
panelLabel.Caption := '';
panelLabel.Parent := Self;
panelLabel.Width := Trunc(Self.Width/3);
panelLabel.Align := TAlign.alClient;
panelLabel.BevelInner := TBevelCut.bvNone;
panelLabel.BevelKind := TBevelKind.bkNone;
panelLabel.BevelOuter := TBevelCut.bvNone;
lbCaption := TLabel.Create(panelLabel);
lbCaption.Alignment := TAlignment.taCenter;
lbCaption.Layout := TTextLayout.tlCenter;
lbCaption.Caption := Self.Caption;
lbCaption.Parent := panelLabel;
lbCaption.Align := TAlign.alClient;
lbCaption.WordWrap := true;
Image1 := TImage.Create(Self);
Image1.Parent := panelIMG;
Image1.Align := TAlign.alClient;
Image1.Stretch := true;
Image1.Visible := true;
FQTextFont := TFont.Create;
FQTextFont.Color := clRed;
FQTextFont.Name := 'Segoe UI';
FQTextFont.Size := 10;
FQTextFont.Style := [];
lbCaption.Font := FQTextFont;
//if (FQImageIndex >= 0) and Assigned(FQImageList) then
// QImageList.GetBitmap(FQImageIndex, Image1.Picture.Bitmap);
Self.Caption := ' ';
end;
procedure TCustomPanelButton.ArredondarImagem(Panel : TPanel);
var
rgn: HRGN;
dc: HDC;
begin
rgn := CreateRoundRectRgn(0, 0, Panel.Width, Panel.Height, 350, 350);
dc := GetDC(Panel.Handle);
SetWindowRgn(Panel.Handle, rgn, true);
ReleaseDC(Panel.Handle, dc);
DeleteObject(rgn);
end;
procedure TCustomPanelButton.Resize(Sender:TObject);
begin
case QImageRedimensiar of
trManual:panelIMG.Width := FQImageWidth;
trAutomatico:panelIMG.Width := Trunc(Self.Width/3);
end;
end;
procedure TCustomPanelButton.setFQTexCaption(const Value: String);
begin
FQTexCaption := Value;
lbCaption.Caption := FQTexCaption;
end;
procedure TCustomPanelButton.setQImage(const Value: TPicture);
begin
FQImage.Assign(Value);
end;
procedure TCustomPanelButton.setQImageIndex(const Value: Integer);
begin
FQImageIndex := Value;
if (FQImageIndex >= 0) and Assigned(FQImageList) then
QImageList.GetBitmap(FQImageIndex, Image1.Picture.Bitmap);
end;
procedure TCustomPanelButton.setQImageList(const Value: TCustomImageList);
begin
if Assigned(Value) then
FQImageList := Value;
if (FQImageIndex >= 0) and Assigned(FQImageList) then
begin
QImageList.GetBitmap(FQImageIndex, Image1.Picture.Bitmap);
end;
end;
procedure TCustomPanelButton.setQImageWidth(const Value: Integer);
begin
FQImageWidth := Value;
if QImageRedimensiar = trManual then
begin
panelIMG.Width := FQImageWidth;
end;
end;
procedure TCustomPanelButton.setQTextFont(const Value: TFont);
begin
FQTextFont.Assign(Value);
if Assigned(FQTextFont) then
lbCaption.Font.Assign(FQTextFont);
end;
end.
|
unit LrControls;
interface
uses
Windows, Messages, Classes, Controls;
type
//:$ Enhanced TGraphicControl.
//:: TLrGraphicControl adds auto-sizing and text handling machinery.
TLrGraphicControl = class(TGraphicControl)
protected
FAutoSize: Boolean;
//:$ Property setter for AutoSize.
//:: TurboHtml defines a custom AutoSize property so that it will be
//:: available for both VCL and CLX classes.
procedure SetCustomAutoSize(const Value: Boolean); virtual;
//:$ Specifies whether the control should size itself based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize.
property AutoSize: Boolean read FAutoSize write SetCustomAutoSize;
protected
Resizing: Boolean;
{$ifdef __LrClx__}
FCaption: string;
function GetText: TCaption; override;
procedure SetText(const inText: TCaption); override;
//:$ Hook for the control to take action if it's text is changed (CLX).
//:: TextChanged calls AdjustSize and Invalidate. Descendant classes can
//:: override TextChanged for different behavior.
procedure TextChanged; override;
{$else}
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
//:$ Hook for the control to take action if it's text is changed (VCL).
//:: TextChanged calls AdjustSize and Invalidate. Descendant classes can
//:: override TextChanged for different behavior.
procedure TextChanged; virtual;
{$endif}
function ShouldAutoSize: Boolean; virtual;
procedure Resize; override;
procedure AdjustSize; override;
//:$ Adjusts the controls size based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize in order to implement auto sizing.
procedure PerformAutoSize; virtual;
end;
//
//:$ Enhanced TCusomControl.
//:: TLrCustomControl adds machinery for auto-sizing, text handling, and
//:: transparency.
TLrCustomControl = class(TCustomControl)
private
{$ifdef __LrClx__}
FCaption: string;
{$endif}
FResizing: Boolean;
FTransparent: Boolean;
FOpaque: Boolean;
protected
// Protected not private so subclasses can set a default value
FAutoSize: Boolean;
//:$ Property setter for AutoSize.
//:: TurboHtml defines a custom AutoSize property so that it will be
//:: available for both VCL and CLX classes.
procedure SetCustomAutoSize(const Value: Boolean); virtual;
procedure SetOpaque(const Value: Boolean);
{$ifdef __LrClx__}
function GetText: TCaption; override;
procedure SetText(const inText: TCaption); override;
{$endif}
procedure SetParent(inParent: TWinControl); override;
procedure SetTransparent(const Value: Boolean);
protected
function ShouldAutoSize: Boolean; virtual;
procedure AdjustSize; override;
procedure Paint; override;
//:$ Adjusts the controls size based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize in order to implement AutoSizing.
procedure PerformAutoSize; virtual;
procedure Resize; override;
{$ifdef __LrClx__}
procedure TextChanged; override;
{$else}
procedure CMInvalidate(var Message: TMessage); message CM_INVALIDATE;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CreateParams(var Params: TCreateParams); override;
//:$ Hook for the control to take action if it's text is changed (VCL).
//:: TextChanged calls AdjustSize and Invalidate. Descendant classes can
//:: override TextChanged for different behavior.
procedure TextChanged; virtual;
{$endif}
procedure WMEraseBkGnd(var Msg: TWMEraseBkGnd); message WM_ERASEBKGND;
procedure WMMove(var Message: TWMMove); message WM_MOVE;
protected
//:$ Specifies whether the control should size itself based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize.
property AutoSize: Boolean read FAutoSize write SetCustomAutoSize;
property Opaque: Boolean read FOpaque write SetOpaque;
property Transparent: Boolean read FTransparent write SetTransparent;
public
procedure Invalidate; override;
end;
implementation
{ TLrGraphicControl }
{$ifdef __LrClx__}
function TLrGraphicControl.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TLrGraphicControl.SetText(const inText: TCaption);
begin
if (FCaption <> inText) then
begin
FCaption := inText;
TextChanged;
end;
end;
{$else}
procedure TLrGraphicControl.CMTextChanged(var Message: TMessage);
begin
inherited;
TextChanged;
end;
{$endif}
procedure TLrGraphicControl.SetCustomAutoSize(const Value: Boolean);
begin
FAutoSize := Value;
if FAutoSize then
AdjustSize
else if (Parent <> nil) then
Parent.Realign;
end;
procedure TLrGraphicControl.Resize;
begin
inherited;
if not Resizing then
try
Resizing := true;
AdjustSize;
finally
Resizing := false;
end;
end;
procedure TLrGraphicControl.TextChanged;
begin
AdjustSize;
Invalidate;
end;
function TLrGraphicControl.ShouldAutoSize: Boolean;
begin
Result := AutoSize;
end;
procedure TLrGraphicControl.AdjustSize;
begin
if not ShouldAutoSize or ([csLoading, csDestroying] * ComponentState <> []) then
inherited
else if Parent <> nil then
PerformAutoSize
end;
procedure TLrGraphicControl.PerformAutoSize;
begin
//
end;
{ TLrCustomControl }
procedure TLrCustomControl.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
{
if Transparent then
begin
Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT;
ControlStyle := ControlStyle - [csOpaque];
end
else begin
Params.ExStyle := Params.ExStyle and not WS_EX_TRANSPARENT;
ControlStyle := ControlStyle + [csOpaque];
end;
}
end;
procedure TLrCustomControl.SetTransparent(const Value: Boolean);
begin
FTransparent := Value;
{
if not (csCreating in ControlState) then
begin
RecreateWnd;
Invalidate;
end;
}
end;
procedure TLrCustomControl.SetOpaque(const Value: Boolean);
begin
FOpaque := Value;
Invalidate;
end;
procedure TLrCustomControl.Paint;
//var
// cache: HDC;
begin
{
if Transparent then
begin
if Tag <> 99 then
try
Tag := 99;
Parent.PaintTo(Canvas, -Left, -Top);
finally
Tag := 0;
end;
end;
}
{
if Transparent then
begin
cache := SaveDC(Canvas.Handle);
try
MoveWindowOrg(Canvas.Handle, -Left, -Top);
Parent.Perform(WM_PAINT, Canvas.Handle, 0);
finally
RestoreDC(Canvas.Handle, cache);
end;
end;
}
end;
procedure TLrCustomControl.WMEraseBkGnd(var Msg : TWMEraseBkGnd);
begin
if Transparent or Opaque then
Msg.Result := 0
else
inherited;
end;
procedure TLrCustomControl.WMMove(Var Message:TWMMove);
begin
if Transparent then
Invalidate
// else
// inherited;
end;
procedure TLrCustomControl.CMInvalidate(var Message: TMessage);
var
i: Integer;
begin
inherited;
if HandleAllocated then
begin
if Parent <> nil then
Parent.Perform(CM_INVALIDATE, 1, 0);
if Message.WParam = 0 then
begin
//InvalidateRect(Handle, nil, not (csOpaque in ControlStyle));
for i := 0 to ControlCount - 1 do
if Controls[i] is TLrCustomControl then
Controls[i].Invalidate;
end;
end;
end;
procedure TLrCustomControl.SetParent(inParent: TWinControl);
begin
inherited;
{
The trick needed to make it all work!
I don't know if changing the parent's style is a good idea, but it only
removes the WS_CLIPCHILDREN style which shouldn't cause
any problems.
}
{
if Parent <> nil then
SetWindowLong(Parent.Handle, GWL_STYLE,
GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_ClipChildren);
}
end;
procedure TLrCustomControl.Invalidate;
//var
// Rect :TRect;
begin
{
Rect:= BoundsRect;
if (Parent <> nil) and Parent.HandleAllocated then
InvalidateRect(Parent.Handle, @Rect, True)
else
}
inherited;
end;
{$ifdef __LrClx__}
function TLrCustomControl.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TLrCustomControl.SetText(const inText: TCaption);
begin
if (FCaption <> inText) then
begin
FCaption := inText;
TextChanged;
end;
end;
{$else}
procedure TLrCustomControl.CMTextChanged(var Message: TMessage);
begin
inherited;
TextChanged;
end;
{$endif}
procedure TLrCustomControl.SetCustomAutoSize(const Value: Boolean);
begin
FAutoSize := Value;
if FAutoSize then
AdjustSize
else if (Parent <> nil) then
Parent.Realign;
end;
procedure TLrCustomControl.Resize;
begin
inherited;
if not FResizing then
try
FResizing := true;
AdjustSize;
finally
FResizing := false;
end;
end;
procedure TLrCustomControl.TextChanged;
begin
AdjustSize;
Invalidate;
end;
function TLrCustomControl.ShouldAutoSize: Boolean;
begin
Result := AutoSize;
end;
procedure TLrCustomControl.AdjustSize;
begin
if ShouldAutoSize and ([csLoading, csDestroying] * ComponentState = []) then
PerformAutoSize
else
inherited;
end;
procedure TLrCustomControl.PerformAutoSize;
begin
//
end;
end.
|
unit uDM_RepositorySQLServer;
interface
uses
Forms, Dialogs, uiRepositories, uiRepoSystem,
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MSSQL,
FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait, FireDAC.Phys.ODBCBase, Data.DB,
FireDAC.Comp.Client;
type
TDM_RepositorySQLServer = class(TDataModule, IRepositories)
FDConnSQLServer: TFDConnection;
FDPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
function Repository: IRepoSystem;
{ Public declarations }
end;
var
DM_RepositorySQLServer: TDM_RepositorySQLServer;
procedure initialize;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
uRepositorySystemSQLServer;
var
mRepository : IRepoSystem;
procedure initialize;
begin
If Assigned( DM_RepositorySQLServer ) then
exit;
Application.CreateForm(TDM_RepositorySQLServer, DM_RepositorySQLServer);
end;
procedure TDM_RepositorySQLServer.DataModuleCreate(Sender: TObject);
begin
Try
FDConnSQLServer.Connected := False;
FDConnSQLServer.Connected := True;
Except
On E : Exception do
ShowMessage('Error Connect SQL Server : ' + E.Message)
End;
end;
function TDM_RepositorySQLServer.Repository: IRepoSystem;
begin
if not assigned(mRepository) then
mRepository := TDM_RepositorySystemSQLServer.Create(Self);
Result := mRepository;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, System.ImageList, Vcl.ImgList,
Vcl.ComCtrls, Vcl.ToolWin, Vcl.ActnList, Vcl.StdActns, System.Actions;
type
TForm1 = class(TForm)
ImageList1: TImageList;
PopupMenu1: TPopupMenu;
Open2: TMenuItem;
Save2: TMenuItem;
N2: TMenuItem;
Close2: TMenuItem;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ActionList1: TActionList;
FileOpen1: TFileOpen;
FileSaveAs1: TFileSaveAs;
FileExit1: TFileExit;
Action1: TAction;
Action2: TAction;
MainMenu1: TMainMenu;
File1: TMenuItem;
Open1: TMenuItem;
SaveAs1: TMenuItem;
Edit1: TMenuItem;
Red1: TMenuItem;
Yellow1: TMenuItem;
procedure Open1Click(Sender: TObject);
procedure Red1Click(Sender: TObject);
procedure Close1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Close1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.Open1Click(Sender: TObject);
begin
ShowMessage('File Open');
end;
procedure TForm1.Red1Click(Sender: TObject);
begin
Red1.Checked := true;
Color := clRed;
end;
end.
|
unit Sort.StringCompare;
interface
uses
Windows, SysUtils, Classes, ComCtrls;
function NaturalOrderCompareString( const A1, A2: string; ACaseSensitive: Boolean ): Integer;
function StrCmpLogicalW(psz1, psz2: PWideChar): Integer; stdcall; external 'shlwapi.dll';
type
TStringListSortCompare = record
class function DoNatural(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoCompareStr(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoWinAPI(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoStrCmpLogicalW(List: TStringList; Index1, Index2: Integer): Integer; static;
end;
TStringListSortCompareDesc = record
class function DoNatural(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoCompareStr(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoWinAPI(List: TStringList; Index1, Index2: Integer): Integer; static;
class function DoStrCmpLogicalW(List: TStringList; Index1, Index2: Integer): Integer; static;
end;
PGroupSortData = ^TGroupSortData;
TGroupSortData = record
ListView: TListview;
ColumnIndex: Integer;
Ascend: Boolean;
end;
implementation
function NaturalOrderCompareString( const A1, A2: string; ACaseSensitive: Boolean ): Integer;
var
Str1, Str2: PChar;
Pos1, Pos2: Integer;
EndPos1, EndPos2: Integer;
begin
Str1 := PChar(A1);
Str2 := PChar(A2);
Pos1 := -1;
Pos2 := -1;
while True do
begin
Inc( Pos1 );
Inc( Pos2 );
if (Str1[Pos1] = #0) and (Str2[Pos2] = #0) then
begin
Result := 0;
Exit;
end
else if Str1[Pos1] = #0 then
begin
Result := -1;
Exit;
end
else if Str2[Pos2] = #0 then
begin
Result := 1;
Exit;
end;
if (Str1[Pos1] >= '0') and (Str1[Pos1] <= '9') and
(Str2[Pos2] >= '0') and (Str2[Pos2] <= '9') then
begin
EndPos1 := Pos1;
repeat
Inc(EndPos1);
until not ((Str1[EndPos1] >= '0') and (Str1[EndPos1] <= '9'));
EndPos2 := Pos2;
repeat
Inc(EndPos2);
until not ((Str2[EndPos2] >= '0') and (Str2[EndPos2] <= '9'));
while True do
begin
if EndPos1 - Pos1 = EndPos2 - Pos2 then
begin
// 이부분이 숫자비교임. StrToInt 한 다음에 빼도 될 것임
Result := CompareStr( Copy(Str1, Pos1+1, EndPos1 - Pos1), Copy(Str2, Pos2+1, EndPos1 - Pos1) ) ;
if Result = 0 then
begin
Pos1 := EndPos1 - 1;
Pos2 := EndPos2 - 1;
Break;
end
else
begin
Exit;
end;
end
else if EndPos1 - Pos1 > EndPos2 - Pos2 then
begin
if Str1[Pos1] = '0' then
Inc(Pos1)
else
begin
Result := 1;
Exit;
end;
end
else
begin
if Str2[Pos2] = '0' then
Inc( Pos2 )
else
begin
Result := -1;
Exit;
end;
end;
end;
end
else
begin
if ACaseSensitive then
Result := CompareStr( Copy(Str1, Pos1, 1), Copy(Str2, Pos2, 1) )
else
Result := CompareText( Copy(Str1, Pos1, 1), Copy(Str2, Pos2, 1) );
if Result <> 0 then
Exit;
end;
end;
end;
{ TStringListSortCompare }
class function TStringListSortCompare.DoCompareStr(List: TStringList; Index1,
Index2: Integer): Integer;
begin
Result := CompareStr( List.Strings[Index1], List.Strings[Index2] );
end;
class function TStringListSortCompare.DoNatural(List: TStringList; Index1,
Index2: Integer): Integer;
begin
Result := NaturalOrderCompareString( List.Strings[Index1], List.Strings[Index2], True );
end;
class function TStringListSortCompare.DoStrCmpLogicalW(List: TStringList; Index1,
Index2: Integer): Integer;
begin
Result := StrCmpLogicalW( PWideChar(List.Strings[Index1]), PWideChar(List.Strings[Index2]) );
end;
class function TStringListSortCompare.DoWinAPI(List: TStringList; Index1,
Index2: Integer): Integer;
var
CompareResult: Integer;
begin
Result := 0;
CompareResult := CompareString( LOCALE_USER_DEFAULT, 0, PWideChar(List.Strings[Index1]), Length(List.Strings[Index1]), PWideChar(List.Strings[Index2]), Length(List.Strings[Index2]) );
case CompareResult of
CSTR_LESS_THAN: Result := -1;
CSTR_GREATER_THAN: Result := 1;
CSTR_EQUAL: Result := 0;
end;
end;
{ TStringListSortCompareDesc }
class function TStringListSortCompareDesc.DoCompareStr(List: TStringList;
Index1, Index2: Integer): Integer;
begin
Result := -TStringListSortCompare.DoCompareStr( List, Index1, Index2 );
end;
class function TStringListSortCompareDesc.DoNatural(List: TStringList; Index1,
Index2: Integer): Integer;
begin
Result := -TStringListSortCompare.DoNatural( List, Index1, Index2 );
end;
class function TStringListSortCompareDesc.DoStrCmpLogicalW(List: TStringList;
Index1, Index2: Integer): Integer;
begin
Result := -TStringListSortCompare.DoStrCmpLogicalW( List, Index1, Index2 );
end;
class function TStringListSortCompareDesc.DoWinAPI(List: TStringList; Index1,
Index2: Integer): Integer;
begin
Result := -TStringListSortCompare.DoWinAPI( List, Index1, Index2 );
end;
end.
|
unit URepositorioFamiliaProduto;
interface
USES
UFamiliaProduto,
UEntidade,
URepositorioDB,
SqlExpr;
type
TRepositorioFAMILIAPRODUTO = class (TRepositorioDB<TFamiliaProduto>)
public
constructor create;
procedure AtribuiDBParaEntidade(const coFamiliaProduto : TFamiliaProduto); override;
procedure AtribuiEntidadeParaDB(const coFamiliaProduto : TFamiliaProduto;
const coSQLQuery : TSQLQuery); override;
end;
implementation
uses
UDM
;
procedure TRepositorioFamiliaProduto.AtribuiDBParaEntidade(const coFamiliaProduto: TFamiliaProduto);
begin
inherited;
with FSQLSelect do
begin
coFamiliaProduto.NOMEFAMILIA := FieldByName(FLD_FAMILIAPRODUTO_NOMEFAMILIA).AsString;
end;
end;
procedure TRepositorioFamiliaProduto.AtribuiEntidadeParaDB(const coFamiliaProduto: TFamiliaProduto;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_FAMILIAPRODUTO_NOMEFAMILIA).AsString := coFamiliaProduto.NOMEFAMILIA;
end;
end;
constructor TRepositorioFamiliaProduto.Create;
begin
inherited Create(TFamiliaProduto, TBL_FamiliaProduto, FLD_ENTIDADE_ID, STR_FamiliaProduto);
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit uHTMLTidy;
interface
{$I ConTEXT.inc}
{$IFDEF SUPPORTS_HTML_TIDY}
uses
Classes, SysUtils, uCommon, Dialogs,
TidyLib, TidyGlobal, TidyEnums, TidyOpaqueTypes, TidyConfigurationOptions,
JclFileUtils;
type
THTMLTidy = class;
TTidyProfile = class
private
fTidy: THTMLTidy;
fConfiguration: TTidyConfiguration;
fFileName: string;
function GetConfiguration: TTidyConfiguration;
public
constructor Create(Tidy: THTMLTidy);
destructor Destroy; override;
property Configuration: TTidyConfiguration read GetConfiguration;
property FileName: string read fFileName;
end;
THTMLTidy = class
private
fInitSuccessful: boolean;
fTidy: TLibTidy;
fEnabled: boolean;
function IsTidyLibAvailable: boolean;
function Init: boolean;
function GetProfile: TTidyConfiguration;
public
constructor Create;
destructor Destroy; override;
function LoadFromFile(FileName: string): boolean;
function SaveToFile(FileName: string): boolean;
procedure SetDefaults;
function ProfileFileList: TStringList;
function ProfileList: TStringList;
property Enabled: boolean read fEnabled;
property Profile: TTidyConfiguration read GetProfile;
end;
var
HTMLTidy: THTMLTidy;
const
STR_TIDY_ENCODING_ID: array[Low(TidyEncodingID)..High(TidyEncodingID)] of string =
('Raw', 'ASCII', 'Latin1', 'UTF8', 'ISO2022', 'MacRoman', 'Win1252', 'UTF16le',
'UTF16be', 'UTF16', 'Big5', 'ShiftJIS');
STR_TIDY_DUP_ATTR_MODES: array[Low(TidyDupAttrModes)..High(TidyDupAttrModes)] of string =
('Keep first', 'Keep last');
STR_TIDY_TRISTATE: array[Low(TTidyTriState)..High(TTidyTriState)] of string =
('No', 'Yes', 'Auto');
function MakeProfileFilename(Name: string): string;
{$ENDIF}
implementation
{$IFDEF SUPPORTS_HTML_TIDY}
const
TIDY_LIB_FILENAME = 'libtidy.dll';
TIDY_DIRECTORY = 'Tidy\';
PROFILE_EXT = '.tidy';
////////////////////////////////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function MakeProfileFilename(Name: string): string;
begin
result:=Format('%s%s%s%s', [ApplicationDir, TIDY_DIRECTORY, Name, PROFILE_EXT]);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// TTidyProfile
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TTidyProfile.Create(Tidy: THTMLTidy);
begin
fTidy:=Tidy;
end;
//------------------------------------------------------------------------------------------
destructor TTidyProfile.Destroy;
begin
if Assigned(fConfiguration) then
FreeAndNil(fConfiguration);
inherited;
end;
//------------------------------------------------------------------------------------------
function TTidyProfile.GetConfiguration: TTidyConfiguration;
begin
if not Assigned(fConfiguration) then begin
fConfiguration:=TTidyConfiguration.Create;
fTidy.Init;
end;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function THTMLTidy.GetProfile: TTidyConfiguration;
begin
if Init then
result:=fTidy.Configuration
else
result:=nil;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function THTMLTidy.Init: boolean;
begin
if (_GlobalTidyLibHandle=0) then
fInitSuccessful:=TidyGlobal.LoadTidyLibrary('libtidy.dll');
if not Assigned(fTidy) then begin
fTidy:=TLibTidy.Create(nil);
with fTidy do begin
end;
end;
result:=fInitSuccessful;
end;
//------------------------------------------------------------------------------------------
function THTMLTidy.IsTidyLibAvailable: boolean;
begin
result:=FileExists(ApplicationDir+TIDY_LIB_FILENAME);
end;
//------------------------------------------------------------------------------------------
function THTMLTidy.LoadFromFile(FileName: string): boolean;
begin
result:=Init and FileExists(FileName) and fTidy.LoadConfigFile(FileName);
end;
//------------------------------------------------------------------------------------------
function THTMLTidy.SaveToFile(FileName: string): boolean;
begin
ForceDirectories(ApplicationDir+TIDY_DIRECTORY);
result:=Init and fTidy.SaveConfigFile(FileName);
end;
//------------------------------------------------------------------------------------------
procedure THTMLTidy.SetDefaults;
begin
if Init then
fTidy.ResetConfig;
end;
//------------------------------------------------------------------------------------------
function THTMLTidy.ProfileFileList: TStringList;
begin
result:=TStringList.Create;
AdvBuildFileList(ApplicationDir+TIDY_DIRECTORY+'*'+PROFILE_EXT, faAnyFile, result, amAny, [flFullNames]);
end;
//------------------------------------------------------------------------------------------
function THTMLTidy.ProfileList: TStringList;
var
i: integer;
begin
result:=ProfileFileList;
for i:=0 to result.Count-1 do
result[i]:=PathExtractFileNameNoExt(result[i]);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Constructor, destructor
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor THTMLTidy.Create;
begin
fEnabled:=IsTidyLibAvailable;
end;
//------------------------------------------------------------------------------------------
destructor THTMLTidy.Destroy;
begin
if Assigned(fTidy) then
FreeAndNil(fTidy);
inherited;
end;
//------------------------------------------------------------------------------------------
initialization
finalization
if Assigned(HTMLTidy) then
FreeAndNil(HTMLTidy);
{$ENDIF}
end.
|
{
publish with BSD Licence.
Copyright (c) Terry Lao
}
unit iCBConstructs;
{$MODE Delphi}
interface
uses iLBC_define,gainquants,getCBvecs,C2Delphi_header;
{----------------------------------------------------------------*
* Convert the codebook indexes to make the search easier
*---------------------------------------------------------------}
procedure index_conv_enc(
index:painteger { (i/o) Codebook indexes }
);
procedure index_conv_dec(
index:painteger { (i/o) Codebook indexes }
);
procedure iCBConstruct(
decvector:pareal; { (o) Decoded vector }
index:painteger; { (i) Codebook indices }
gain_index:painteger;{ (i) Gain quantization indices }
mem:pareal; { (i) Buffer for codevector construction }
lMem:integer; { (i) Length of buffer }
veclen:integer; { (i) Length of vector }
nStages:integer { (i) Number of codebook stages }
);
implementation
procedure index_conv_enc(
index:painteger { (i/o) Codebook indexes }
);
var
k:integer;
begin
for k:=1 to CB_NSTAGES-1 do
begin
if ((index[k]>=108) and (index[k]<172)) then
begin
index[k]:=index[k]-64
end
else
if (index[k]>=236) then
begin
index[k]:=index[k]-128;
end
else
begin
{ ERROR }
end;
end;
end;
procedure index_conv_dec(
index:painteger { (i/o) Codebook indexes }
);
var
k:integer;
begin
for k:=1 to CB_NSTAGES-1 do
begin
if ((index[k]>=44) and (index[k]<108)) then
begin
index[k]:=index[k]+64;
end
else
if ((index[k]>=108) and (index[k]<128)) then
begin
index[k]:=index[k]+128;
end
else
begin
{ ERROR }
end;
end;
end;
{----------------------------------------------------------------*
* Construct decoded vector from codebook and gains.
*---------------------------------------------------------------}
procedure iCBConstruct(
decvector:pareal; { (o) Decoded vector }
index:painteger; { (i) Codebook indices }
gain_index:painteger;{ (i) Gain quantization indices }
mem:pareal; { (i) Buffer for codevector construction }
lMem:integer; { (i) Length of buffer }
veclen:integer; { (i) Length of vector }
nStages:integer { (i) Number of codebook stages }
);
var
j,k:integer;
gain:array [0..CB_NSTAGES-1] of real;
cbvec:array [0..SUBL] of real;
begin
{ gain de-quantization }
gain[0] := gaindequant(gain_index[0], 1.0, 32);
if (nStages > 1) then
begin
gain[1] := gaindequant(gain_index[1],abs(gain[0]), 16);
end;
if (nStages > 2) then
begin
gain[2] := gaindequant(gain_index[2],abs(gain[1]), 8);
end;
{ codebook vector construction and construction of
total vector }
getCBvec(@cbvec, mem, index[0], lMem, veclen);
for j:=0 to veclen-1 do
begin
decvector[j] := gain[0]*cbvec[j];
end;
if (nStages > 1) then
begin
for k:=1 to nStages-1 do
begin
getCBvec(@cbvec, mem, index[k], lMem, veclen);
for j:=0 to veclen-1 do
begin
decvector[j] :=decvector[j] + gain[k]*cbvec[j];
end;
end;
end;
end;
end.
|
{: FileDXF<p>
DXF file loader<p>
<b>History :</b><font size=-1><ul>
<li>26/01/03 - DA - SaveToStream is now correct
<li>21/01/03 - DA - Supported DXF entities are now stored in an array
<li>07/01/03 - DA - Update the progress bar with a logarithmic scale when reading entities
<li>06/12/02 - SJ - Added block reading
<li>30/11/02 - DA - Added header and tables support,
Moved TDXFEntitiesList to the TypesDXF unit
<li>27/11/02 - DA - Support for Vertices and Text
<li>23/11/02 - DA - Moved base DXF IO functions to the TDXFIOObject
<li>16/11/02 - DA - Entities are now created
<li>20/10/02 - SJ - Uses TDXFEntity of TypesDXF unit
<li>13/10/02 - DA - Entity reading base and progress information
<li>05/10/02 - DA - Unit creation
</ul></font>
}
unit FileDXF;
interface
uses
Classes,
Contnrs, // TObjectList
TypesDXF,
CodesValuesDXF,
ObjectsDXF
;
type
// TDXFProgressFunc
//
{: Function to call when loading or saving from/to DXF }
TDXFProgressFunc = procedure(const Msg: String; ActualPosition,
PositionMax: Longint) of object;
// TFileDXF
//
{: TFileDXF is the main class and supplies the user with all available data
from a specific DXF file. }
TFileDXF = class(TDXFIOObject)
private
FHeader: TDXFHeader;
FEntities: TDXFEntitiesList;
FLayers: TDXFLayersList;
FBlocks: TDXFBlocksList;
FOnProgress: TDXFProgressFunc;
//: go to the specified section
function GoToSection(const ASectionName: String): boolean;
//: call the load/save progress function
procedure DoProgress(const AMsg: string; APos, AMax: LongInt);
protected
//: Read the header section
procedure ReadHeader;
//: Read the tables section
procedure ReadTables;
//: Read the blocks section
procedure ReadBlocks;
//: Read the entities section
procedure ReadEntities;
//: Write the header section
procedure WriteHeader;
//: Write the tables section
procedure WriteTables;
//: Write the blocks section
procedure WriteBlocks;
//: Write the entities section
procedure WriteEntities;
public
constructor Create; virtual;
destructor Destroy; override;
//: load from a stream
procedure LoadFromStream(AStream: TStream); override;
//: save to a stream
procedure SaveToStream(AStream: TStream); override;
//: DXF header
property Header: TDXFHeader read FHeader;
//: list of entities in the DXF file
property Entities: TDXFEntitiesList read FEntities;
//: list of layers in the DXF file
property Layers: TDXFLayersList read FLayers;
//: list of blocks in the DXF file
property Blocks: TDXFBlocksList read FBlocks;
//: function called on load/save progress
property OnProgress: TDXFProgressFunc read FOnProgress write FOnProgress;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
uses
SysUtils,
WinProcs, // OutputDebugString()
Math
;
{ TFileDXF }
// Create
//
constructor TFileDXF.Create;
begin
inherited;
FEntities := TDXFEntitiesList.Create;
FLayers := TDXFLayersList.Create;
FBlocks := TDXFBlocksList.Create;
FHeader := TDXFHeader.Create;
end;
// Destroy
//
destructor TFileDXF.Destroy;
begin
FEntities.Free;
FLayers.Free;
FBlocks.Free;
FHeader.Free;
inherited;
end;
// DoProgress
//
{: @param AMsg Message to show
@param APos Actual load/save position
@param AMax Maximum position }
procedure TFileDXF.DoProgress(const AMsg: string; APos, AMax: Integer);
begin
if Assigned(FOnProgress) then FOnProgress(AMsg, APos, AMax);
end;
// GoToSection
//
{: @param ASectionName Name of the section where to go
@return True if success, False otherwise }
function TFileDXF.GoToSection(const ASectionName: String): boolean;
var
Code: integer;
Value: string;
begin
// return to the beginning
DXFStream.Position := 0;
try
repeat
// search a section
repeat
ReadCodes(Code, Value);
until (Code = DXF_START) and (Value = DXFV_SECTION);
// check if this section is the one we are searching
ReadCodes(Code, Value);
Result := (Code = DXF_NAME) and (Value = ASectionName);
until Result;
except
Result := False;
end;
end;
// LoadFromStream
//
procedure TFileDXF.LoadFromStream(AStream: TStream);
begin
try
inherited;
except
end;
// read the header section
DoProgress('Lecture de l''entête...', 1, 100);
if GoToSection(DXFV_HEADER) then begin
ReadHeader;
end;
// read the tables section
DoProgress('Lecture des tables...', 10, 100);
if GoToSection(DXFV_TABLES) then begin
ReadTables;
end;
// read the blocks section
DoProgress('Lecture des blocs...', 20, 100);
if GoToSection(DXFV_BLOCKS) then begin
ReadBlocks;
end;
// read the entities section
DoProgress('Lecture des entitées...', 30, 100);
if GoToSection(DXFV_ENTITIES) then begin
ReadEntities;
end;
DoProgress('Terminé', 100, 100);
Sleep(25);
end;
// ReadBlocks
//
procedure TFileDXF.ReadBlocks;
var
Code: integer;
Value: string;
EndSec: boolean;
Block: TDXFBlock;
begin
repeat
Block := nil;
ReadCodes(Code, Value);
// end of section ?
EndSec := (Code = DXF_START) and (Value = DXFV_ENDSEC);
// create entities
if (not EndSec) and (Code = DXF_START) then begin
if Value = DXFV_BLOCK then Block := TDXFBlock.Create(FLayers, FBlocks) else
;
end;
// if a new entity was read then ...
if Assigned(Block) then begin
// the entity read itself
Block.LoadFromStream(DXFStream);
// add it to the layers list
FBlocks.AddBlock(Block);
end;
until EndSec;
end;
// ReadEntities
//
procedure TFileDXF.ReadEntities;
var
Code: integer;
Value: string;
EndSec : boolean;
Entity : TDXFEntity;
SuppEntIdx: Integer; // supported entity index
EntityClass: TDXFEntityClass; // class of the entity
begin
repeat
Entity := nil;
ReadCodes(Code, Value);
// end of section ?
EndSec := (Code = DXF_START) and (Value = DXFV_ENDSEC);
// create entities
if (not EndSec) and (Code = DXF_START) then begin
with SupportedDXFEntities do begin
// search a DXF entity with this name in the supported DXF entities list
if Find(Value, SuppEntIdx) then begin
// get the entity class
EntityClass := TDXFEntityClass(Objects[SuppEntIdx]);
// check the entity classes
if EntityClass.InheritsFrom(TDXFInsert) then begin
// inserts need the block list too
Entity := TDXFInsertClass(EntityClass).Create(FLayers, FBlocks);
end else begin
Entity := EntityClass.Create(FLayers); // create the entity
end;
end
else OutputDebugString(PWideChar('Unsuported entity type ' + Value));
end;
end;
// if a new entity was read then ...
if Assigned(Entity) then begin
// the entity read itself
Entity.LoadFromStream(DXFStream);
// add it to the entities list
FEntities.AddEntity(Entity);
// update the progress bar with a logarithmic scale
DoProgress('Ajout de l''entitée ' + IntToStr(FEntities.Count) + '...', 30 + Trunc(Ln(FEntities.Count)*7), 100);
end;
until EndSec;
end;
// ReadHeader
//
procedure TFileDXF.ReadHeader;
begin
FHeader.LoadFromStream(DXFStream);
end;
// ReadTables
//
procedure TFileDXF.ReadTables;
var
Code: integer;
Value: string;
EndSec: boolean;
Layer: TDXFLayer;
begin
repeat
Layer := nil;
ReadCodes(Code, Value);
// end of section ?
EndSec := (Code = DXF_START) and (Value = DXFV_ENDSEC);
// create entities
if (not EndSec) and (Code = DXF_START) then begin
if Value = DXFV_LAYER then Layer := TDXFLayer.Create else
;
end;
// if a new entity was read then ...
if Assigned(Layer) then begin
// the entity read itself
Layer.LoadFromStream(DXFStream);
// add it to the layers list
FLayers.AddLayer(Layer);
end;
until EndSec;
end;
// SaveToStream
//
procedure TFileDXF.SaveToStream(AStream: TStream);
begin
inherited;
// write the header section
DoProgress('Ecriture de l''entête...', 1, 100);
WriteHeader;
// write the tables section
DoProgress('Ecriture des tables...', 10, 100);
WriteTables;
// write the blocks section
DoProgress('Ecriture des blocs...', 20, 100);
WriteBlocks;
// write the entities section
DoProgress('Ecriture des entitées...', 30, 100);
WriteEntities;
DoProgress('Terminé', 100, 100);
Sleep(25);
end;
// WriteBlocks
//
procedure TFileDXF.WriteBlocks;
var
i: Integer;
begin
WriteCodes(DXF_START, DXFV_SECTION); // open section
WriteCodes(DXF_NAME, DXFV_BLOCKS); // write section name
// write blocks
for i := 0 to FBlocks.Count - 1 do
FBlocks.Block[i].SaveToStream(DXFStream);
WriteCodes(DXF_START, DXFV_ENDSEC); // close section
end;
// WriteEntities
//
procedure TFileDXF.WriteEntities;
var
i: Integer;
begin
WriteCodes(DXF_START, DXFV_SECTION); // open section
WriteCodes(DXF_NAME, DXFV_ENTITIES); // write section name
// write entities
for i := 0 to FEntities.Count - 1 do
FEntities.Entity[i].SaveToStream(DXFStream);
WriteCodes(DXF_START, DXFV_ENDSEC); // close section
end;
// WriteHeader
//
procedure TFileDXF.WriteHeader;
begin
FHeader.SaveToStream(DXFStream);
end;
// WriteTables
//
procedure TFileDXF.WriteTables;
var
i: Integer;
begin
WriteCodes(DXF_START, DXFV_SECTION); // open section
WriteCodes(DXF_NAME, DXFV_TABLES); // write section name
WriteCodes(DXF_START, DXFV_TABLE); // open the layer tables
// write layers
for i := 0 to FLayers.Count - 1 do
FLayers.Layer[i].SaveToStream(DXFStream);
WriteCodes(DXF_START, DXFV_ENDTAB); // close the layer tables
WriteCodes(DXF_START, DXFV_ENDSEC); // close section
end;
end.
|
unit Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TTest1DLL = procedure(aStrValue: string; aInt: Integer); StdCall;
TTestIntDLL = procedure(aZahl: Integer); StdCall;
TTestFormDLL = procedure(aCaption:String); StdCall;
TAddierenDLL = function (aZahl1, aZahl2: Integer): Integer; StdCall;
type
Tfrm_Main = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
fDLLPath: string;
fTest1DLLHandle: THandle;
fTest1DLL: TTest1DLL;
fTestIntDLL: TTestIntDLL;
fTestFormDLL: TTestFormDLL;
public
end;
var
frm_Main: Tfrm_Main;
implementation
{$R *.dfm}
procedure Tfrm_Main.Button2Click(Sender: TObject);
var
dllHandle: THandle;
fTestAddieren: TAddierenDLL;
Ergebnis: Integer;
begin
dllHandle := LoadLibrary(PChar(fDLLPath + 'TestDLL2.dll'));
fTestAddieren := GetProcAddress(dllHandle, 'addieren');
Ergebnis := fTestAddieren(1,2);
Caption := IntToStr(Ergebnis);
FreeLibrary(dllHandle);
end;
procedure Tfrm_Main.FormCreate(Sender: TObject);
begin //
fDLLPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
end;
procedure Tfrm_Main.Button1Click(Sender: TObject);
var
i: Integer;
begin
fTest1DLLHandle := LoadLibrary(PChar(fDLLPath + 'TestDLL.dll'));
fTestFormDLL := GetProcAddress(fTest1DLLHandle, 'ShowForm');
fTestIntDLL := GetProcAddress(fTest1DLLHandle, 'TestInt');
//fTest1DLL := GetProcAddress(fTest1DLLHandle, 'Test1');
//fTest1Dll('Hurra es funktioniert', 10);
i := 101;
fTestIntDLL(i);
fTestFormDLL('Test');
FreeLibrary(fTest1DLLHandle);
end;
end.
|
{*******************************************************************************
* uBoolFControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Компонент для ввода булевского значения (TqFBoolControl) *
* Copyright © 2005-2007, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uBoolControl;
interface
uses
SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, Registry;
type
TStoreBool = (StoreAs01, StoreAsTF);
TqFBoolControl = class(TqFControl)
private
FOldOnEnterEvent: TNotifyEvent;
FCheckBox: TCheckBox;
FStoreAs: TStoreBool;
FUseBlock: Boolean;
protected
procedure SetValue(Val: Variant); override;
function GetValue: Variant; override;
procedure Loaded; override;
procedure Prepare;
procedure SetDisplayName(Name: string); override;
procedure SetLabelColor(Color: TColor); override;
procedure SetSemicolon(Val: Boolean); override;
procedure SetAsterisk(Val: Boolean); override;
procedure SetRequired(Val: Boolean); override;
procedure Resize; override;
procedure BlockCheck(Sender: TObject);
function GetKeyDown: TKeyEvent;
procedure SetKeyDown(e: TKeyEvent);
function GetKeyUp: TKeyEvent;
procedure SetKeyUp(e: TKeyEvent);
public
constructor Create(AOwner: TComponent); override;
procedure Block(Flag: Boolean); override;
procedure Highlight(HighlightOn: Boolean); override;
procedure ShowFocus; override;
function ToString: string; override;
procedure LoadFromRegistry(reg: TRegistry); override; // vallkor
procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor
published
property StoreAs: TStoreBool read FStoreAs write FStoreAs;
property OnKeyDown: TKeyEvent read GetKeyDown write SetKeyDown;
property OnKeyUp: TKeyEvent read GetKeyUp write SetKeyUp;
end;
procedure Register;
{$R *.res}
implementation
uses qFTools, qFStrings, Variants;
function TqFBoolControl.GetKeyDown: TKeyEvent;
begin
Result := FCheckBox.OnKeyDown;
end;
procedure TqFBoolControl.SetKeyDown(e: TKeyEvent);
begin
FCheckBox.OnKeyDown := e;
end;
function TqFBoolControl.GetKeyUp: TKeyEvent;
begin
Result := FCheckBox.OnKeyUp;
end;
procedure TqFBoolControl.SetKeyUp(e: TKeyEvent);
begin
FCheckBox.OnKeyUp := e;
end;
function TqFBoolControl.ToString: string;
begin
if (FStoreAs = StoreAs01) and FCheckBox.Checked then
Result := '1'
else
if (FStoreAs = StoreAs01) and not FCheckBox.Checked then
Result := '0'
else
if (FStoreAs = StoreAsTF) and FCheckBox.Checked then
Result := '''T'''
else
if (FStoreAs = StoreAsTF) and not FCheckBox.Checked then
Result := '''F''';
end;
procedure TqFBoolControl.ShowFocus;
begin
inherited ShowFocus;
qFSafeFocusControl(FCheckBox);
end;
procedure TqFBoolControl.Highlight(HighlightOn: Boolean);
begin
inherited Highlight(HighlightOn);
if HighlightOn then
begin
FOldColor := FCheckBox.Color;
FCheckBox.Color := qFHighlightColor;
end
else
if FOldColor <> 0 then
FCheckBox.Color := FOldColor;
Repaint;
end;
procedure TqFBoolControl.BlockCheck(Sender: TObject);
var
ctrl: TControl;
begin
// qFErrorDialog(qFControlBlocked);
if (Sender is TControl) then
begin
ctrl := Sender as TControl;
if (ctrl.Parent <> nil) then
qFSafeFocusControl(ctrl.Parent);
end;
end;
procedure TqFBoolControl.Block(Flag: Boolean);
begin
inherited Block(Flag);
if Flag then
begin
if not FUseBlock then
begin
FOldOnEnterEvent := FCheckBox.OnEnter;
FUseBlock := True;
end;
FCheckBox.OnEnter := BlockCheck;
end
else
FCheckBox.OnEnter := FOldOnEnterEvent;
end;
procedure TqFBoolControl.Loaded;
begin
FCheckBox.OnClick := FOnChange;
inherited Loaded;
end;
procedure TqFBoolControl.SetValue(Val: Variant);
begin
inherited SetValue(Val);
if VarIsNull(Val) then
FCheckBox.Checked := False
else
if (VarType(Val) = varString) and (FStoreAs = StoreAsTF) then
begin
if Val = 'T' then
FCheckBox.Checked := True;
if Val = 'F' then
FCheckBox.Checked := False;
end
else
if (VarType(Val) = varInteger) and (FStoreAs = StoreAs01) then
begin
if Val = 1 then
FCheckBox.Checked := True;
if Val = 0 then
FCheckBox.Checked := False;
end
else
FCheckBox.Checked := Val;
end;
function TqFBoolControl.GetValue: Variant;
begin
Result := FCheckBox.Checked;
end;
constructor TqFBoolControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCheckBox := TCheckBox.Create(Self);
FCheckBox.Parent := Self;
Asterisk := False;
Semicolon := False;
Prepare;
end;
procedure TqFBoolControl.Resize;
begin
inherited Resize;
Prepare;
end;
procedure TqFBoolControl.Prepare;
begin
FCheckBox.Font := Font;
FCheckBox.Font.Color := LabelColor;
FCheckBox.Top := (Height - FCheckBox.Height) div 2;
FCheckBox.Width := Width;
FCheckBox.Caption := DisplayName;
if Semicolon then
FCheckBox.Caption := FCheckBox.Caption + ':';
if Asterisk then
if Required then
FCheckBox.Caption := '* ' + FCheckBox.Caption
else
FCheckBox.Caption := ' ' + FCheckBox.Caption;
end;
procedure TqFBoolControl.SetDisplayName(Name: string);
begin
inherited SetDisplayName(Name);
Prepare;
end;
procedure TqFBoolControl.SetRequired(Val: Boolean);
begin
inherited SetRequired(Val);
Prepare;
end;
procedure TqFBoolControl.SetSemicolon(Val: Boolean);
begin
inherited SetSemicolon(Val);
Prepare;
end;
procedure TqFBoolControl.SetAsterisk(Val: Boolean);
begin
inherited SetAsterisk(Val);
Prepare;
end;
procedure TqFBoolControl.SetLabelColor(Color: TColor);
begin
inherited SetLabelColor(Color);
Prepare;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFBoolControl]);
end;
procedure TqFBoolControl.LoadFromRegistry(reg: TRegistry); // vallkor
begin
inherited LoadFromRegistry(reg);
Value := (Reg.ReadString('Value') = 'T');
end;
procedure TqFBoolControl.SaveIntoRegistry(reg: TRegistry); // vallkor
var
C: Char;
begin
inherited SaveIntoRegistry(reg);
if Value then
c := 'T'
else
c := 'F';
Reg.WriteString('Value', C);
end;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_HugeCardinalUtils;
interface
uses uTPLb_HugeCardinal, uTPLb_MemoryStreamPool;
type
TPrimalityTestNoticeProc = procedure( CountPrimalityTests: integer) of object;
function gcd( a, b: THugeCardinal): THugeCardinal;
// Computes the Greatest Common Divisor of a and b.
// A and b may be trashed as a result.
// The result is a new object.
function lcm( a, b: THugeCardinal): THugeCardinal;
// Computes the Least Common Multiple of a and b.
// A and b may be trashed as a result.
// The result is a new object.
function isCoPrime( a, b: THugeCardinal): boolean;
// Returns True if and only if a and b are co-prime.
// A and b may be trashed as a result.
function isProbablyPrime( p: THugeCardinal; OnProgress: TProgress; var wasAborted: boolean): boolean;
// True means that p is almost certainly prime.
// False means that p is composite.
// The Fermat Primality test is used with only 1 pass.
// p is preserved.
function hasSmallFactor( p: THugeCardinal): boolean;
// True means that p does not have a small factor.
// It is a good candidate for testing for primality.
// False means that p is composite, and indeed, at least one of its
// factors is a small number.
function GeneratePrime( NumBits: integer;
OnProgress: TProgress;
OnPrimalityTest: TPrimalityTestNoticeProc;
PassCount: integer;
const Pool1: IMemoryStreamPool;
var Prime: THugeCardinal;
var NumbersTested: integer): boolean;
// Returns True if Prime was succesfully generated.
// Returns False if user aborted.
// On input, Prime is nil.
// Upon output, if user did not abort, Prime is a prime number
// of NumBits bits. PassCount passes of the Fermat Primality test
// are used to test primality of random candidates.
function Inverse( Prime, Modulus: THugeCardinal; var TestPassed: boolean): THugeCardinal;
// Computes multiplicative inverse of Prime over modulus.
// Assumes:
// Modulus >= 3
// 2 <= Prime < Modulus
// 'Prime' is a prime number.
const
StandardExponent = 65537;
procedure Compute_RSA_Fundamentals_2Factors(
RequiredBitLengthOfN: integer;
Fixed_e: uint64; // Put as -1 to generate a random number.
// A value of StandardExponent is recommended.
var N, e, d, Totient: THugeCardinal;
var p, q, dp, dq, qinv: THugeCardinal; // For use with CRT.
OnProgress: TProgress;
OnPrimalityTest: TPrimalityTestNoticeProc;
GeneratePrimePassCount: integer; // 1 .. 20;
const Pool1: IMemoryStreamPool;
var NumbersTested: integer;
var wasAborted: boolean);
function Validate_RSA_Fundamentals(
var N, e, d, Totient: THugeCardinal): boolean;
var
GreatestPassCount: integer = 0; // Investigative tool used for tweeking the algorithm.
RSA_FailCount: integer = 0;
implementation
uses SysUtils, Classes, uTPLb_PointerArithmetic, uTPLb_IntegerUtils,
uTPLb_I18n, Math;
const
SmallPrimeSetCardinality = 200;
EratosthenesSieveSize = 2000; // Must choose value such that:
// SmallPrimeSetCardinality'th prime number < EratosthenesSieveSize
var
SmallPrimes: array[ 0.. SmallPrimeSetCardinality-1] of integer;
procedure PreComputeSmallPrimes; forward;
// The above computes the set of small prime numbers.
procedure InitUnit_HugeCardinalUtils;
begin
FillChar( SmallPrimes, SizeOf( SmallPrimes), 0);
PreComputeSmallPrimes
end;
procedure DoneUnit_HugeCardinalUtils;
begin
end;
procedure PreComputeSmallPrimes;
// Uses the sieve of Eratosthenes algorithm.
var
p, j, k: integer;
Numbers: TBits;
begin
p := 2;
Numbers := TBits.Create;
try
Numbers.Size := EratosthenesSieveSize;
// Numbers[j] = False means that j is possibly prime.
// Numbers[j] = True means that j is composite.
for j := 0 to SmallPrimeSetCardinality-1 do
begin
// p is a prime.
k := 2 * p;
while k < EratosthenesSieveSize do
begin
Numbers[k] := True;
Inc( k, p)
end;
SmallPrimes[j] := p;
repeat
Inc( p)
until (p >= EratosthenesSieveSize) or (not Numbers[p]);
if p >= EratosthenesSieveSize then
raise Exception.CreateFmt(
ES_EratosthenesSievSizeTooSmall,
[EratosthenesSieveSize, SmallPrimeSetCardinality])
end;
finally
Numbers.Free
end end;
function gcd( a, b: THugeCardinal): THugeCardinal;
// Uses Stein's algorithm.
// TO DO: Implement an alternate implementation using Euclid and
// measure the performance difference.
var
ResultBitShifts: integer;
isA_Odd, isB_Odd: boolean;
begin
ResultBitShifts := 0;
result := nil;
repeat
if a.isZero then
result := b
else if b.isZero then
result := a
else
begin
isA_Odd := a.isOdd;
isB_Odd := b.isOdd;
if (not isA_Odd) and (not isB_Odd) then
begin
Inc( ResultBitShifts);
a.MulPower2( -1); // a := a / 2;
b.MulPower2( -1); // b := b / 2;
end
else if isA_Odd and (not isB_odd) then
b.MulPower2( -1)
else if (not isA_Odd) and isB_odd then
a.MulPower2( -1)
else
case a.Compare( b) of
rGreaterThan:
begin
a.Subtract( b);
a.MulPower2( -1)
end;
rEqualTo:
result := a;
rLessThan:
begin
b.Subtract( a);
b.MulPower2( -1)
end;
end;
end;
until Assigned( result);
result := result.CloneSized( result.BitLength + ResultBitShifts);
result.MulPower2( ResultBitShifts)
end;
function lcm( a, b: THugeCardinal): THugeCardinal;
var
gcd1, Temp, Quotient, Remainder: THugeCardinal;
begin
Quotient := nil;
Remainder := nil;
result := a.Multiply( b);
gcd1 := gcd( a, b);
try
if (not gcd1.isSmall) or (gcd1.ExtractSmall <> 1) then
begin
result.Divide( gcd1, Quotient, Remainder);
Assert( Remainder.isZero, AS_LCM_Fail);
Temp := result;
result := Quotient;
Quotient := Temp
end
finally
gcd1.Free;
Quotient.Free;
Remainder.Free
end end;
function isCoPrime( a, b: THugeCardinal): boolean;
var
gcd1: THugeCardinal;
begin
gcd1 := gcd( a, b);
result := gcd1.isSmall and (gcd1.ExtractSmall = 1);
gcd1.Free
end;
function isProbablyPrime( p: THugeCardinal; OnProgress: TProgress; var wasAborted: boolean): boolean;
var
Witness: THugeCardinal;
pMinusOne: THugeCardinal;
begin
pMinusOne := nil;
wasAborted := False;
if p.isSmall and (p.ExtractSmall <= 3) then
begin
result := True;
exit
end;
Witness := nil;
try
repeat
FreeAndNil( Witness);
Witness := THugeCardinal.CreateZero( p.BitLength, p.FPool);
Witness.Random( p);
until (not Witness.isSmall) or (Witness.ExtractSmall > 1);
// 2 <= Witness < p
pMinusOne := p.Clone;
try
pMinusOne.Increment( -1);
wasAborted := not Witness.PowerMod( pMinusOne, p, OnProgress);
// isPrime := (Witness ** (p-1) mod p) = 1
result := Witness.isSmall and (Witness.ExtractSmall = 1)
finally
Witness.Free
end
finally
pMinusOne.Free
end
end;
function hasSmallFactor( p: THugeCardinal): boolean;
var
j, q: integer;
Modulus, TestValue, TestValue2: THugeCardinal;
doSmallTest: boolean;
pValue: uint64;
begin
result := not p.isOdd;
if result then exit;
doSmallTest := p.isSmall;
if doSmallTest then
pValue := p.ExtractSmall
else
pValue := 0;
Modulus := THugeCardinal.CreateZero( 0, p.FPool);
TestValue := THugeCardinal.CreateZero( p.MaxBits, p.FPool);
try
for j := 1 to SmallPrimeSetCardinality-1 do
begin
q := SmallPrimes[j]; // q is a small prime number.
if doSmallTest and (q >= pValue) then break;
Modulus.AssignSmall( q);
TestValue.Assign( p);
TestValue2 := TestValue.Modulo( Modulus);
result := TestValue2.isZero;
TestValue2.Free;
if result then break
end
finally
Modulus.Free;
TestValue.Free
end
end;
function GeneratePrime( NumBits: integer;
OnProgress: TProgress;
OnPrimalityTest: TPrimalityTestNoticeProc;
PassCount: integer;
const Pool1: IMemoryStreamPool;
var Prime: THugeCardinal;
var NumbersTested: integer): boolean;
// Returns True if Prime was succesfully generated.
// Returns False if user aborted.
const
PrimeDeltas: array[ 0..7 ] of integer = (6, 4, 2, 4, 2, 2, 6, 2);
var
Thirty, Temp, Temp2: THugeCardinal;
Delta: int64;
Idx, j: integer;
FoundPrime: boolean;
wasAborted: boolean;
begin
if PassCount <= 0 then
PassCount := 1;
if PassCount > 20 then
PassCount := 20;
// generate p1
Prime := THugeCardinal.CreateRandom( NumBits, NumBits + 2, True, Pool1);
Thirty := THugeCardinal.CreateSmall( 30, 0, Pool1);
Temp := nil; Temp2 := nil;
try
Temp := Prime.Clone;
Temp2 := Temp.Modulo( Thirty);
Delta := 31 - Temp2.ExtractSmall;
finally
Thirty.Free;
Temp.Free; Temp2.Free
end;
// p := p1 - (p1 mod 30) + 1;
Prime.Increment( Delta);
// So now, p mod 30 = 1
// i := 0;
Idx := 0;
result := True;
wasAborted := False;
repeat
FoundPrime := not hasSmallFactor( Prime);
if FoundPrime then
for j := 1 to PassCount do
begin
FoundPrime := isProbablyPrime( Prime, OnProgress, wasAborted);
result := not wasAborted;
if result and (not FoundPrime) and (j > GreatestPassCount) then
GreatestPassCount := j;
if (not FoundPrime) or (not result) then break;
end;
Inc( NumbersTested);
if (not wasAborted) and assigned( OnPrimalityTest) then
OnPrimalityTest( NumbersTested);
if FoundPrime or (not result) then break;
// This candidate failed, so try the next likely one.
// p += (6,4,2,4,2,2,6,2)[i];
Delta := PrimeDeltas[ Idx];
Prime.Increment( Delta);
if Idx >= 7 then
Idx := 0
else
Inc( Idx)
until FoundPrime or (not result);
if not result then
FreeAndNil( Prime)
end;
function extended_gcd( a, b: THugeCardinal;
var x, y: THugeCardinal;
var xPve, yPve: boolean;
var gcd : THugeCardinal): boolean;
// Solve:
// a*x + b*y = gcd(a,b)
// Using Extended Euclidean algorithm.
var
NextX, NextY, a1, b1, SwapTemp: THugeCardinal;
Quotient, Remainder: THugeCardinal;
NextXpve, NextYpve, SwapPve: boolean;
QxNextXY: THugeCardinal;
Cmp: TCompareResult;
gcd_factor1, gcd_factor2: THugeCardinal;
gcdPve: boolean;
// s: string;
begin
NextX := THugeCardinal.CreateSimple(0); NextXpve := True;
x := THugeCardinal.CreateSimple(1); xPve := True;
NextY := THugeCardinal.CreateSimple(1); NextYpve := True;
y := THugeCardinal.CreateSimple(0); yPve := True;
a1 := a.Clone;
b1 := b.Clone;
SwapTemp := THugeCardinal.CreateSimple( 0);
while not b1.isZero do
begin
a1.Divide( b1, Quotient, Remainder);
SafeAssign( a1, b1);
b1.Free;
b1 := Remainder;
Remainder := nil;
SafeAssign( SwapTemp, NextX); SwapPve := NextXpve;
QxNextXY := Quotient.Multiply( NextX);
Cmp := x.Compare( QxNextXY);
if Xpve = NextXpve then
begin
if Cmp in [rGreaterThan, rEqualTo] then
begin
SafeAssign( NextX, x);
NextX.Subtract( QxNextXY);
NextXpve := xPve
end
else
begin
SafeAssign( NextX, QxNextXY);
NextX.Subtract( x);
NextXpve := not xPve
end
end
else
begin
SafeAdd( NextX, x, QxNextXY);
NextXpve := xPve
end;
SafeAssign( x, SwapTemp);
xPve := SwapPve;
QxNextXY.Free;
SafeAssign( SwapTemp, NextY); SwapPve := NextYpve;
QxNextXY := Quotient.Multiply( NextY);
Cmp := y.Compare( QxNextXY);
if Ypve = NextYpve then
begin
if Cmp in [rGreaterThan, rEqualTo] then
begin
SafeAssign( NextY, y);
NextY.Subtract( QxNextXY);
NextYpve := yPve
end
else
begin
SafeAssign( NextY, QxNextXY);
NextY.Subtract( y);
NextYpve := not yPve
end
end
else
begin
SafeAdd( NextY, y, QxNextXY);
NextYpve := yPve
end;
SafeAssign( y, SwapTemp);
yPve := SwapPve;
QxNextXY.Free;
Quotient.Free;
end;
gcd_factor1 := a.Multiply( x);
gcd_factor2 := b.Multiply( y);
if xPve = yPve then
begin
gcd := THugeCardinal.CreateSimple( 0);
SafeAdd( gcd, gcd_factor1, gcd_factor2);
gcdPve := xPve
end
else if gcd_factor1.Compare( gcd_factor2) in [rGreaterThan, rEqualTo] then
begin
gcd := gcd_factor1.Clone;
gcd.Subtract( gcd_factor2);
gcdPve := xPve
end
else
begin
gcd := gcd_factor2.Clone;
gcd.Subtract( gcd_factor1);
gcdPve := yPve
end;
result := (gcd.CompareSmall( 1) = rEqualTo) and gcdPve;
NextX.Free;
NextY.Free;
a1.Free;
b1.Free;
SwapTemp.Free;
Quotient.Free;
// gcd_factor1.Free;
gcd_factor2.Free
end;
function Inverse( Prime, Modulus: THugeCardinal; var TestPassed: boolean): THugeCardinal;
// Computes multiplicative inverse of Prime over modulus.
// Assumes:
// Modulus >= 3
// 2 <= Prime < Modulus
// 'Prime' is a prime number.
var
xPrev: THugeCardinal;
xPrevPve: boolean;
x: THugeCardinal;
xPve: boolean;
r: THugeCardinal;
rPrev: THugeCardinal;
div1: THugeCardinal;
rem1: THugeCardinal;
Delta: THugeCardinal;
xNext: THugeCardinal;
xNextPve: boolean;
Bits: integer;
Pool: IMemoryStreamPool;
Cmp: TCompareResult;
//Tmp: THugeCardinal;
//Ok: boolean;
//s: string;
Dummy1, Dummy2: THugeCardinal;
resultPve, DummyBool2: boolean;
function IsInverse( Candidate: THugeCardinal): boolean;
var
Tmp2: THugeCardinal;
begin
// result * Prime mod Modulus == 1
Tmp2 := Candidate.Clone;
Tmp2.MultiplyMod( Prime, Modulus);
result := Tmp2.CompareSmall( 1) = rEqualTo;
Tmp2.Free
end;
procedure Negate( ModValue: THugeCardinal);
var
Tmp2: THugeCardinal;
begin
Tmp2 := Modulus.Clone;
Tmp2.Subtract( ModValue);
SafeAssign( ModValue, Tmp2);
Tmp2.Free
end;
begin
Bits := Modulus.BitLength;
Pool := Modulus.FPool;
xPrev := THugeCardinal.CreateZero( Bits, Pool);
xPrevPve := True;
x := THugeCardinal.CreateSmall( 1, Bits, Pool);
xPve := True;
r := Prime.CloneSized( Bits);
rPrev := Modulus.Clone;
div1 := nil;
rem1 := nil;
Delta := nil;
xNext := nil;
try
while (not r.isSmall) or (r.ExtractSmall > 1) do
begin
FreeAndNil( div1); FreeAndNil( rem1);
rPrev.Divide( r, div1, rem1);
rPrev.Assign( r);
r.Assign( rem1);
FreeAndNil( Delta);
Delta := x.Multiply( div1);
FreeAndNil( xNext);
xNext := xPrev.Clone;
if xPve = xPrevPve then
begin
Cmp := xPrev.Compare( Delta);
if Cmp in [rGreaterThan, rEqualTo] then
begin
xNext.Subtract( Delta);
xNextPve := xPve
end
else
begin
xNext.Assign( Delta);
xNext.Subtract( xPrev);
xNextPve := not xPve
end;
end
else
begin
xNext.Add( Delta);
xNextPve := xPrevPve
end;
xPrev.Assign( x);
xPrevPve := xPve;
x.Assign( xNext);
xPve := xNextPve
end
finally
result := x;
xPrev.Free;
r.Free;
rPrev.Free;
div1.Free;
rem1.Free;
Delta.Free;
xNext.Free;
end;
TestPassed := IsInverse( result);
if not TestPassed then
begin
Negate( result);
TestPassed := IsInverse( result);
end;
if not TestPassed then
begin
result.Free;
TestPassed := extended_gcd(
Prime, Modulus, result, Dummy1, resultPve, DummyBool2, Dummy2);
// a b x y x+ve y+ve gcd
if not resultPve then
Negate( result);
TestPassed := TestPassed and IsInverse( result);
Dummy1.Free; Dummy2.Free;
end;
end;
function isAllSmallFactors( Number: THugeCardinal): boolean;
var
Rem: THugeCardinal;
j, SmallPrime: integer;
Divisor, Quotient, Remainder: THugeCardinal;
begin
Rem := Number.Clone;
while (not Rem.isZero) and (not Rem.isOdd) do
Rem.MulPower2( -1);
Divisor := THugeCardinal.CreateZero( 0, Number.FPool);
Quotient := nil;
Remainder := nil;
try
for j := Low( SmallPrimes) + 1 to High( SmallPrimes) do
begin
SmallPrime := SmallPrimes[j];
if (SmallPrime = 0) or
(Rem.CompareSmall( SmallPrime) in [rEqualTo, rLessThan]) then break;
Divisor.AssignSmall( SmallPrime);
repeat
FreeAndNil( Quotient);
FreeAndNil( Remainder);
Rem.Divide( Divisor, Quotient, Remainder);
if Remainder.isZero then
Rem.Assign( Quotient);
until (not Remainder.isZero) or (Rem.Compare( Divisor) in [rEqualTo, rLessThan])
end;
result := Rem.BitLength <= 16;
finally
Rem.Free;
Divisor.Free;
Quotient.Free;
Remainder.Free
end end;
function Validate_CRT_Numbers(
n, e, d, p, q, dp, dq, qinv: THugeCardinal): boolean;
var
c, c1, c2: THugeCardinal;
pMinus1, qMinus1: THugeCardinal;
Temp, Totient: THugeCardinal;
InverseIsGood, Ok: boolean;
begin
// dp = d mod (p - 1)
pMinus1 := p.Clone;
pMinus1.Increment( -1);
Temp := d.Modulo( pMinus1);
result := dp.Compare( Temp) = rEqualTo;
Temp.Free;
// dq = d mod (q - 1)
qMinus1 := q.Clone;
qMinus1.Increment( -1);
Temp := d.Modulo( qMinus1);
Ok := dq.Compare( Temp) = rEqualTo;
result := result and Ok;
Temp.Free;
// qinv = q ** -1 mod p
Temp := Inverse( q, p, InverseIsGood);
Ok := (qinv.Compare( Temp) = rEqualTo) and InverseIsGood;
result := result and Ok;
Temp.Free;
// ((qinv * q) mod p) = 1
Temp := qinv.CloneSized( qinv.BitLength + q.BitLength + 1);
Temp.MultiplyMod( q, p); // but this is p-1
Ok := Temp.CompareSmall( 1) = rEqualTo;
result := result and Ok;
Temp.Free;
// n = p * q
Temp := p.Multiply( q);
Ok := Temp.Compare( n) = rEqualTo;
result := result and Ok;
Temp.Free;
// (d * e) mod (lcm(p-1, q-1))) = 1
Totient := LCM( pMinus1, qMinus1);
pMinus1.Free;
qMinus1.Free;
Temp := d.Clone;
Temp.MultiplyMod( e, Totient);
Ok := Temp.CompareSmall( 1) = rEqualTo;
result := result and Ok;
Totient.Free;
Temp.Free;
if not result then exit;
c := THugeCardinal.CreateRandom( n.BitLength, n.BitLength, False, nil);
c1 := c.Modulo( n);
c2 := c1.Clone;
c.Free;
c1.PowerMod( d, n, nil);
c2.PowerMod_WithChineseRemainderAlgorithm( d, n, p, q, dp, dq, qinv, nil);
result := c1.Compare( c2) = rEqualTo;
c1.Free;
c2.Free;
end;
procedure Compute_RSA_Fundamentals_2Factors(
RequiredBitLengthOfN: integer;
Fixed_e: uint64; // Put as -1 to generate a random number.
// A value of StandardExponent is recommended.
var N, e, d, Totient: THugeCardinal;
var p, q, dp, dq, qinv: THugeCardinal; // For use with CRT.
OnProgress: TProgress;
OnPrimalityTest: TPrimalityTestNoticeProc;
GeneratePrimePassCount: integer; // 1 .. 20; 20 is good.
const Pool1: IMemoryStreamPool;
var NumbersTested: integer;
var wasAborted: boolean);
// Refer: http://en.wikipedia.org/wiki/Rsa#Key_generation_2
// This could easily be adapted to multiple factors, but for the
// time being, two will do.
// At the moment CRT exponents and co-efficients are not returned.
// In future, speed improvements could be made to Signature and Descryption
// operations by leveraging the Chinese Remainder Theroum (CRT).
procedure CopyHugeCard( var Dest: THugeCardinal; Source: THugeCardinal);
begin
if assigned( Dest) and (Dest.MaxBits >= Source.BitLength) then
Dest.Assign( Source)
else
begin
FreeAndNil( Dest);
Dest := Source.Clone
end
end;
var
p_bits, q_bits: integer;
pMinus1, qMinus1: THugeCardinal;
Dummy: integer;
e_TrashCopy, Totient_TrashCopy: THugeCardinal;
Ok, InverseIsGood: boolean;
begin
// Algorithm to generate RSA fundamental numbers:
// 1. Compute p bits p.bits := n.bits div 2 + 2;
// 2. Compute q bits q.bits := n.bits div 2 - 2;
// 3. Compute p & p-1 p := Random Prime with exactly p.bits bits.
// 4. Test for Pollard attack on p Check (p-1) is not ONLY small factors.
// 5. Compute q & q-1 q := Random Prime with exactly q.bits bits.
// 6. Test for Pollard attack on q Check (q-1) is not ONLY small factors.
// 7. Compute Totient (Carmichael function) := lcm( p-1, q-1)
// 8. Compute n := p * q;
// 9. Test N.Bits not too small n.bits should not be 16 or more, smaller than the target.
// 10. Compute e e := 65537
// 10.5 Test that e and Totient are co-prime.
// 11. Compute d d := Inverse( e, Totient);
// 12. Test Wiener attack on d Checks d.bits >= ((n.bits div 4) + 4)
// If any test fails, loop back to step 3 and retry.
// If user abort at any point, then break loop.
dp := nil;
dq := nil;
qinv:= nil;
Assert( RequiredBitLengthOfN >= 32, AS_HugeCardinal_N_tooSmall);
Assert( RequiredBitLengthOfN <= 32768, AS_HugeCardinal_N_tooBig);
if Fixed_e <> -1 then
Assert( (RequiredBitLengthOfN - BitCount_64( Fixed_e)) >= 16,
AS_HugeCardinal_N_tooSmall_for_n);
p := nil;
q := nil;
dp := nil;
dq := nil;
qinv := nil;
pMinus1 := nil;
qMinus1 := nil;
wasAborted := False;
N := nil;
e := nil;
d := nil;
Totient := nil;
Dummy := 0;
e_TrashCopy := nil;
Totient_TrashCopy := nil;
// Steps 1 & 2;
q_bits := (RequiredBitLengthOfN div 2) - 2;
p_bits := RequiredBitLengthOfN - q_bits;
try try
repeat
// Step 3
FreeAndNil( p);
wasAborted := not GeneratePrime(
p_bits, OnProgress, OnPrimalityTest, GeneratePrimePassCount, Pool1,
p, NumbersTested);
if wasAborted then break;
CopyHugeCard( pMinus1, p);
pMinus1.Increment( -1);
// Step 4 test: Test for Pollard attack on p
if isAllSmallFactors( pMinus1) then
continue;
// Step 5
FreeAndNil( q);
wasAborted := not GeneratePrime(
q_bits, OnProgress, OnPrimalityTest, GeneratePrimePassCount, Pool1,
q, NumbersTested);
if wasAborted then break;
CopyHugeCard( qMinus1, q);
qMinus1.Increment( -1);
// Step 6 test: Test for Pollard attack on q
if isAllSmallFactors( qMinus1) then
continue;
// Step 7.
FreeAndNil( Totient);
Totient := lcm( pMinus1, qMinus1);
// Step 8.
FreeAndNil( n);
n := p.Multiply( q);
// Step 9
if (RequiredBitLengthOfN - n.BitLength) >= 16 then
continue;
// Step 10
if not assigned( e) then
begin
if Fixed_e = -1 then
// We require e and Totient to be co-prime.
// e does not have to be prime, however, its just easier
// to generate a small prime number.
GeneratePrime( 18, nil, nil, 10, Pool1, e, Dummy)
else
e := THugeCardinal.CreateSmall( Fixed_e, 0, Pool1);
// The popular choice for Fixed_e is 2**16+1
end;
// Step 10.5
// For a specified choice of e, check that e is co-prime to the Totient.
if Fixed_e <> -1 then
begin
e_TrashCopy := e.Clone;
Totient_TrashCopy := Totient.Clone;
try
Ok := isCoPrime( e_TrashCopy, Totient_TrashCopy);
finally
FreeAndNil( e_TrashCopy);
FreeAndNil( Totient_TrashCopy)
end;
if not Ok then
continue // Totient not compatible with e. Try another totient!
end;
// Step 11.
FreeAndNil( d);
d := Inverse( e, Totient, InverseIsGood);
// 12. Test Wiener attack on d Checks d.bits >= ((n.bits div 4) + 4)
if d.BitLength < ((n.BitLength div 4) + 4) then
continue;
// The Sanity Clause.
// Two more tests...
// Test: e * d (mod Totient) == 1
// Test: m**e**d = m where m is a random number. 1 trial.
// TO DO: Boost the number of inversion trials (2nd test).
if not Validate_RSA_Fundamentals( n, e, d, Totient) then
begin
// This can happen if we get bad luck with False Primality Witnesses.
// Some-what counter-intuitively, this event seems to be more frequent
// with lower key sizes.
Inc( RSA_FailCount);
continue
end;
// Prior to CRT implementation, we compute just:
// e := 65537 -- set at higher level.
// n := p * q -- step 8.
// d := e ** -1 mod Phi(n) -- step 11.
// But now with CRT, we need additionally:
// dp := d mod p-1
// dq := d mod q-1
// qinv := q ** -1 mod p
FreeAndNil( dp);
CopyHugeCard( pMinus1, p);
pMinus1.Increment( -1);
dp := d.Modulo( pMinus1);
FreeAndNil( dq);
CopyHugeCard( qMinus1, q);
qMinus1.Increment( -1);
dq := d.Modulo( qMinus1);
FreeAndNil( qinv);
qinv := Inverse( q, p, InverseIsGood);
if Validate_CRT_Numbers( n, e, d, p, q, dp, dq, qinv) then
break
until wasAborted
finally
FreeAndNil( pMinus1); FreeAndNil( qMinus1)
end;
except
begin
FreeAndNil( N);
FreeAndNil( e);
FreeAndNil( d);
FreeAndNil( p); FreeAndNil( q);
FreeAndNil( dp); FreeAndNil( dq); FreeAndNil( qinv);
FreeAndNil( Totient);
raise
end
end
end;
function Validate_RSA_Fundamentals(
var N, e, d, Totient: THugeCardinal): boolean;
var
TestVector, Reconstruction: THugeCardinal;
eCopy: THugeCardinal;
begin
if assigned( Totient) then
begin
// Test: e * d (mod Totient) == 1
ecopy := e.CloneSized( N.BitLength);
ecopy.MultiplyMod( d, Totient);
result := ecopy.isSmall and (ecopy.ExtractSmall = 1);
FreeAndNil( ecopy)
end
else
result := True;
if not result then exit;
// Test for: m**e**d = m
try
TestVector := THugeCardinal.CreateZero( N.BitLength, N.FPool);
try
TestVector.Random( N);
Reconstruction := TestVector.Clone;
try
Reconstruction.PowerMod( e, N, nil);
Reconstruction.PowerMod( d, N, nil);
result := TestVector.Compare( Reconstruction) = rEqualTo
finally
Reconstruction.Free
end
finally
TestVector.Free
end
except
result := False
end
end;
initialization
InitUnit_HugeCardinalUtils;
finalization
DoneUnit_HugeCardinalUtils;
end.
|
unit GLDPyramidParamsFrame;
interface
uses
Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDSystem,
GLDPyramid, GLDNameAndColorFrame, GLDUpDown;
type
TGLDPyramidParamsFrame = class(TFrame)
NameAndColor: TGLDNameAndColorFrame;
GB_Params: TGroupBox;
L_Width: TLabel;
L_Depth: TLabel;
L_Height: TLabel;
L_WidthSegs: TLabel;
L_DepthSegs: TLabel;
L_HeightSegs: TLabel;
E_Width: TEdit;
E_Depth: TEdit;
E_Height: TEdit;
E_WidthSegs: TEdit;
E_DepthSegs: TEdit;
E_HeightSegs: TEdit;
UD_Width: TGLDUpDown;
UD_Depth: TGLDUpDown;
UD_Height: TGLDUpDown;
UD_WidthSegs: TUpDown;
UD_DepthSegs: TUpDown;
UD_HeightSegs: TUpDown;
procedure SizeChangeUD(Sender: TObject);
procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function HavePyramid: GLboolean;
function GetParams: TGLDPyramidParams;
procedure SetParams(const Name: string; const Color: TGLDColor3ub;
const Width, Depth, Height: GLfloat; const WidthSegs, DepthSegs, HeightSegs: GLushort);
procedure SetParamsFrom(Pyramid: TGLDPyramid);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
procedure Register;
implementation
{$R *.dfm}
uses
SysUtils, GLDX, GLDConst;
constructor TGLDPyramidParamsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
end;
destructor TGLDPyramidParamsFrame.Destroy;
begin
if Assigned(FDrawer) then
if FDrawer.IOFrame = Self then
FDrawer.IOFrame := nil;
inherited Destroy;
end;
function TGLDPyramidParamsFrame.HavePyramid: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedObject) and
(FDrawer.EditedObject is TGLDPyramid) then
Result := True;
end;
function TGLDPyramidParamsFrame.GetParams: TGLDPyramidParams;
begin
if HavePyramid then
with TGLDPyramid(FDrawer.EditedObject) do
begin
Result.Position := Position.Vector3f;
Result.Rotation := Rotation.Params;
end else
begin
Result.Position := GLD_VECTOR3F_ZERO;
Result.Rotation := GLD_ROTATION3D_ZERO;
end;
Result.Color := NameAndColor.ColorParam;
Result.Width := UD_Width.Position;
Result.Depth := UD_Depth.Position;
Result.Height := UD_Height.Position;
Result.WidthSegs := UD_WidthSegs.Position;
Result.DepthSegs := UD_DepthSegs.Position;
Result.HeightSegs := UD_HeightSegs.Position;
end;
procedure TGLDPyramidParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub;
const Width, Depth, Height: GLfloat; const WidthSegs, DepthSegs, HeightSegs: GLushort);
begin
NameAndColor.NameParam := Name;
NameAndColor.ColorParam := Color;
UD_Width.Position := Width;
UD_Depth.Position := Depth;
UD_Height.Position := Height;
UD_WidthSegs.Position := WidthSegs;
UD_DepthSegs.Position := DepthSegs;
UD_HeightSegs.Position := HeightSegs;
end;
procedure TGLDPyramidParamsFrame.SetParamsFrom(Pyramid: TGLDPyramid);
begin
if not Assigned(Pyramid) then Exit;
with Pyramid do
SetParams(Name, Color.Color3ub, Width, Depth, Height,
WidthSegs, DepthSegs, HeightSegs);
end;
procedure TGLDPyramidParamsFrame.ApplyParams;
begin
if HavePyramid then
TGLDPyramid(FDrawer.EditedObject).Params := GetParams;
end;
procedure TGLDPyramidParamsFrame.SizeChangeUD(Sender: TObject);
begin
if HavePyramid then
with TGLDPyramid(FDrawer.EditedObject) do
if Sender = UD_Width then
Width := UD_Width.Position else
if Sender = UD_Depth then
Depth := UD_Depth.Position else
if Sender = UD_Height then
Height := UD_Height.Position;
end;
procedure TGLDPyramidParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType);
begin
if HavePyramid then
with TGLDPyramid(FDrawer.EditedObject) do
if Sender = UD_WidthSegs then
WidthSegs := UD_WidthSegs.Position else
if Sender = UD_DepthSegs then
DepthSegs := UD_DepthSegs.Position else
if Sender = UD_HeightSegs then
HeightSegs := UD_HeightSegs.Position;
end;
procedure TGLDPyramidParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDPyramidParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDPyramidParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
NameAndColor.Drawer := FDrawer;
end;
procedure Register;
begin
//RegisterComponents('GLDraw', [TGLDPyramidParamsFrame]);
end;
end.
|
unit LanguageStringMapUnit;
interface
uses
gutil,
ghashmap;
type
{ TStringHash }
TStringHash = class
public
class function hash(const s: string; const n: SizeUInt): SizeUInt;
end;
TStringMap = specialize THashmap<string, string, TStringHash>;
implementation
{ TStringHash }
class function TStringHash.hash(const s: string; const n: SizeUInt): SizeUInt;
var
p: PChar;
begin
result := 0;
p := PChar(s);
while
p^ <> #0
do
begin
Inc(result, Byte(p^));
Inc(p);
end;
result := result mod n;
end;
end.
|
unit VH_Voxel;
interface
Uses OpenGl15,SysUtils,Voxel,VH_Global,VH_Types,Math3d,HVA,palette,Windows;
procedure ClearVoxelBoxes(var _VoxelBoxGroup: TVoxelBoxs; var _Num: integer);
procedure UpdateVoxelList;
procedure UpdateVoxelList2(const Vxl : TVoxel; Var VoxelBoxes : TVoxelBoxs; Var VoxelBox_No : Integer; Const HVAOpen : Boolean; HVA : THVA; Frames : Integer);
Procedure GETMinMaxBounds(Const Vxl : TVoxel; i : Integer; Var _Scale,_Offset : TVector3f);
Procedure GetOffsetAndSize(Const Vxl : TVoxel; i : Integer; Var Size,Offset : TVector3f);
function GetSectionStartPosition(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift, _TurretOffset: TVector3f; const _Rotation: single; const _VoxelBoxSize: single): TVector3f;
function GetSectionCenterPosition(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift, _TurretOffset: TVector3f; const _Rotation: single; const _VoxelBoxSize: single): TVector3f;
Function GetVXLColorWithSelection(const Vxl : TVoxel; Color,Normal,Section : integer) : TVector4f;
Procedure LoadVoxel(const Filename : String);
Procedure SetSpectrum(Colours : Boolean);
Procedure ChangeOffset(const Vxl : TVoxel; Section : integer; X,Y,Z : single);
procedure ChangeRemappable (var Palette:TPalette; Colour : TVector3f);
implementation
function checkface(const Vxl : TVoxelSection; x,y,z : integer) : boolean;
var
v: TVoxelUnpacked;
begin
Result := true;
if (X < 0) or (X > Vxl.Tailer.XSize-1) then
Exit;
if (Y < 0) or (Y > Vxl.Tailer.YSize-1) then
Exit;
if (Z < 0) or (Z > Vxl.Tailer.ZSize-1) then
Exit;
Vxl.GetVoxel(x,y,z,v);
if v.Used then
Result := false;
end;
procedure ClearVoxelBoxes(var _VoxelBoxGroup: TVoxelBoxs; var _Num: integer);
var
sec : integer;
begin
if _Num > 0 then
begin
for sec := Low(_VoxelBoxGroup.Sections) to High(_VoxelBoxGroup.Sections) do
begin
If _VoxelBoxGroup.Sections[sec].List > 0 then
begin
glDeleteLists(_VoxelBoxGroup.Sections[sec].List, 1);
_VoxelBoxGroup.Sections[sec].List := 0;
end;
SetLength(_VoxelBoxGroup.Sections[sec].Boxs,0);
_VoxelBoxGroup.Sections[sec].NumBoxs := 0;
end;
SetLength(_VoxelBoxGroup.Sections,0);
end;
_VoxelBoxGroup.NumSections := 0;
_Num := 0;
end;
procedure UpdateVoxelList;
begin
ClearVoxelBoxes(VoxelBoxes,VoxelBox_No);
ClearVoxelBoxes(VoxelBoxesT,VoxelBox_NoT);
ClearVoxelBoxes(VoxelBoxesB,VoxelBox_NoB);
LowestZ := 1000;
If VoxelOpen then
UpdateVoxelList2(VoxelFile,VoxelBoxes,VoxelBox_No,HVAOpen,HVAFile,HVAFrame);
If VoxelOpenT then
UpdateVoxelList2(VoxelTurret,VoxelBoxesT,VoxelBox_NoT,HVAOpenT,HVATurret,HVAFrameT);
If VoxelOpenB then
UpdateVoxelList2(VoxelBarrel,VoxelBoxesB,VoxelBox_NoB,HVAOpenB,HVABarrel,HVAFrameB);
end;
procedure UpdateVoxelList2(const Vxl : TVoxel; Var VoxelBoxes : TVoxelBoxs; Var VoxelBox_No : Integer; Const HVAOpen : Boolean; HVA : THVA; Frames : Integer);
var
x,y,z,i: Byte;
v: TVoxelUnpacked;
num : integer;
CD : TVector3f;
begin
VoxelBoxes.NumSections := VXL.Header.NumSections;
SetLength(VoxelBoxes.Sections,VXL.Header.NumSections);
for i := 0 to VXL.Header.NumSections-1 do
begin
VoxelBoxes.Sections[i].NumBoxs := 0;
num:=0;
SetLength(VoxelBoxes.Sections[i].Boxs,VoxelBoxes.Sections[i].NumBoxs);
for z:=0 to (Vxl.Section[i].Tailer.zSize-1) do
begin
for y:=0 to (Vxl.Section[i].Tailer.YSize-1) do
begin
for x:=0 to (Vxl.Section[i].Tailer.xSize-1) do
begin
Vxl.Section[i].GetVoxel(x,y,z,v);
if v.Used=true then
begin
inc(VoxelBox_No);
inc(VoxelBoxes.Sections[i].NumBoxs);
SetLength(VoxelBoxes.Sections[i].Boxs,VoxelBoxes.Sections[i].NumBoxs);
VoxelBoxes.Sections[i].Boxs[num].Section := i;
VoxelBoxes.Sections[i].Boxs[num].MinBounds.x := (Vxl.Section[i].Tailer.MaxBounds[1]-Vxl.Section[i].Tailer.MinBounds[1])/Vxl.Section[i].Tailer.xSize;
VoxelBoxes.Sections[i].Boxs[num].MinBounds.y := (Vxl.Section[i].Tailer.MaxBounds[2]-Vxl.Section[i].Tailer.MinBounds[2])/Vxl.Section[i].Tailer.ySize;
VoxelBoxes.Sections[i].Boxs[num].MinBounds.z := (Vxl.Section[i].Tailer.MaxBounds[3]-Vxl.Section[i].Tailer.MinBounds[3])/Vxl.Section[i].Tailer.zSize;
CD.x := Vxl.Section[i].Tailer.MaxBounds[1] + (-(Vxl.Section[i].Tailer.MaxBounds[1]-Vxl.Section[i].Tailer.MinBounds[1])/2);
CD.y := Vxl.Section[i].Tailer.MaxBounds[2] + (-(Vxl.Section[i].Tailer.MaxBounds[2]-Vxl.Section[i].Tailer.MinBounds[2])/2);
CD.z := Vxl.Section[i].Tailer.MaxBounds[3] + (-(Vxl.Section[i].Tailer.MaxBounds[3]-Vxl.Section[i].Tailer.MinBounds[3])/2);
VoxelBoxes.Sections[i].Boxs[num].MinBounds2.x := CD.x + (-(Vxl.Section[i].Tailer.MaxBounds[1]-Vxl.Section[i].Tailer.MinBounds[1])/2);
VoxelBoxes.Sections[i].Boxs[num].MinBounds2.y := CD.y + (-(Vxl.Section[i].Tailer.MaxBounds[2]-Vxl.Section[i].Tailer.MinBounds[2])/2);
VoxelBoxes.Sections[i].Boxs[num].MinBounds2.z := CD.z + (-(Vxl.Section[i].Tailer.MaxBounds[3]-Vxl.Section[i].Tailer.MinBounds[3])/2);
if HVAOpen then
begin
VoxelBoxes.Sections[i].Boxs[num].Faces[1] := True;
VoxelBoxes.Sections[i].Boxs[num].Faces[2] := True;
VoxelBoxes.Sections[i].Boxs[num].Faces[3] := True;
VoxelBoxes.Sections[i].Boxs[num].Faces[4] := True;
VoxelBoxes.Sections[i].Boxs[num].Faces[5] := True;
VoxelBoxes.Sections[i].Boxs[num].Faces[6] := True;
VoxelBoxes.Sections[i].Boxs[num].Position.X := {Vxl.Section[i].Tailer.Transform[1][4]+}X;//X {* Vxl.Section[i].Tailer.MinBounds[1]}-((Vxl.Section[i].Tailer.xSize-1) / 2){+ 80* Vxl.Section[i].Tailer.Det};
VoxelBoxes.Sections[i].Boxs[num].Position.Y := {Vxl.Section[i].Tailer.Transform[2][4]+}Y;//Y {* Vxl.Section[i].Tailer.MinBounds[2]}-((Vxl.Section[i].Tailer.ySize-1) / 2){+ 80* Vxl.Section[i].Tailer.Det};
VoxelBoxes.Sections[i].Boxs[num].Position.Z := {Vxl.Section[i].Tailer.Transform[3][4]+}Z;//Z {* Vxl.Section[i].Tailer.MinBounds[3]} {- ((Vxl.Section[i].Tailer.zSize-1) / 2) + 80* Vxl.Section[i].Tailer.Det};
{
if ApplyMatrix2(HVA,Vxl,AddVector(ScaleVector3f(VoxelBoxes.Sections[i].Boxs[num].Position,VoxelBoxes.Sections[i].Boxs[num].MinBounds),VoxelBoxes.Sections[i].Boxs[num].MinBounds2),i,Frames).Z < LowestZ then
LowestZ := ApplyMatrix2(HVA,Vxl,AddVector(ScaleVector3f(VoxelBoxes.Sections[i].Boxs[num].Position,VoxelBoxes.Sections[i].Boxs[num].MinBounds),VoxelBoxes.Sections[i].Boxs[num].MinBounds2),i,Frames).Z;
}
end
else
begin
VoxelBoxes.Sections[i].Boxs[num].Faces[1] := CheckFace(Vxl.Section[i],x,y+1,z);
VoxelBoxes.Sections[i].Boxs[num].Faces[2] := CheckFace(Vxl.Section[i],x,y-1,z);
VoxelBoxes.Sections[i].Boxs[num].Faces[3] := CheckFace(Vxl.Section[i],x,y,z+1);
VoxelBoxes.Sections[i].Boxs[num].Faces[4] := CheckFace(Vxl.Section[i],x,y,z-1);
VoxelBoxes.Sections[i].Boxs[num].Faces[5] := CheckFace(Vxl.Section[i],x-1,y,z);
VoxelBoxes.Sections[i].Boxs[num].Faces[6] := CheckFace(Vxl.Section[i],x+1,y,z);
VoxelBoxes.Sections[i].Boxs[num].Position.X := Vxl.Section[i].Tailer.Transform[1][4]+X;// - ((Vxl.Section[i].Tailer.xSize-1) / 2);
VoxelBoxes.Sections[i].Boxs[num].Position.Y := Vxl.Section[i].Tailer.Transform[2][4]+Y;// - ((Vxl.Section[i].Tailer.ySize-1) / 2);
VoxelBoxes.Sections[i].Boxs[num].Position.Z := {HighestZ+}Vxl.Section[i].Tailer.Transform[3][4]+Z;// - ((Vxl.Section[i].Tailer.zSize-1) / 2);
{
if AddVector(ScaleVector3f(VoxelBoxes.Sections[i].Boxs[num].Position,VoxelBoxes.Sections[i].Boxs[num].MinBounds),VoxelBoxes.Sections[i].Boxs[num].MinBounds2).Z < LowestZ then
LowestZ := AddVector(ScaleVector3f(VoxelBoxes.Sections[i].Boxs[num].Position,VoxelBoxes.Sections[i].Boxs[num].MinBounds),VoxelBoxes.Sections[i].Boxs[num].MinBounds2).Z;
}
end;
VoxelBoxes.Sections[i].Boxs[num].Color := v.Colour;
VoxelBoxes.Sections[i].Boxs[num].Normal := v.Normal;
Inc(num);
end;
end;
end;
end;
end;
end;
Procedure GETMinMaxBounds(Const Vxl : TVoxel; i : Integer; Var _Scale,_Offset : TVector3f);
begin
// As far as I could understand, this is the scale.
_Scale.x := (Vxl.Section[i].Tailer.MaxBounds[1]-Vxl.Section[i].Tailer.MinBounds[1])/Vxl.Section[i].Tailer.xSize;
_Scale.y := (Vxl.Section[i].Tailer.MaxBounds[2]-Vxl.Section[i].Tailer.MinBounds[2])/Vxl.Section[i].Tailer.ySize;
_Scale.z := (Vxl.Section[i].Tailer.MaxBounds[3]-Vxl.Section[i].Tailer.MinBounds[3])/Vxl.Section[i].Tailer.zSize;
// That's the offset.
_Offset.x := Vxl.Section[i].Tailer.MinBounds[1];
_Offset.y := Vxl.Section[i].Tailer.MinBounds[2];
_Offset.z := Vxl.Section[i].Tailer.MinBounds[3];
end;
Procedure GetOffsetAndSize(Const Vxl : TVoxel; i : Integer; Var Size,Offset : TVector3f);
begin
Size.x := (Vxl.Section[i].Tailer.MaxBounds[1] - Vxl.Section[i].Tailer.MinBounds[1])/Vxl.Section[i].Tailer.xSize;
Size.y := (Vxl.Section[i].Tailer.MaxBounds[2] - Vxl.Section[i].Tailer.MinBounds[2])/Vxl.Section[i].Tailer.ySize;
Size.z := (Vxl.Section[i].Tailer.MaxBounds[3] - Vxl.Section[i].Tailer.MinBounds[3])/Vxl.Section[i].Tailer.zSize;
Offset.x := (Vxl.Section[i].Tailer.MaxBounds[1] - Vxl.Section[i].Tailer.MinBounds[1])/2;
Offset.y := (Vxl.Section[i].Tailer.MaxBounds[2] - Vxl.Section[i].Tailer.MinBounds[2])/2;
Offset.z := (Vxl.Section[i].Tailer.MaxBounds[3] - Vxl.Section[i].Tailer.MinBounds[3])/2;
ScaleVector3f(Offset,Size);
end;
Function CleanV3fCol(Color : TVector3f) : TVector3f;
Var
T : TVector3f;
begin
T.X := Color.X;
T.Y := Color.Y;
T.Z := Color.Z;
If T.X > 255 then
T.X := 255;
If T.X < 0 then
T.X := 0;
If T.Y > 255 then
T.Y := 255;
If T.Y < 0 then
T.Y := 0;
If T.Z > 255 then
T.Z := 255;
If T.Z < 0 then
T.Z := 0;
T.X := T.X / 255;
T.Y := T.Y / 255;
T.Z := T.Z / 255;
Result := T;
end;
Function CleanV4fCol(Color : TVector4f) : TVector4f;
Var
T : TVector3f;
begin
T.X := Color.X;
T.Y := Color.Y;
T.Z := Color.Z;
T := CleanV3fCol(T);
Result.X := T.X;
Result.Y := T.Y;
Result.Z := T.Z;
If Color.W > 255 then
Result.W := 255
else If Color.W < 0 then
Result.W := 0
else
Result.W := Color.W;
Result.W := Result.W / 255;
end;
// Importing and adapting change remappable from OS SHP Builder.
procedure ChangeRemappable (var Palette:TPalette; Colour : TVector3f);
var
base,x,rsub,gsub,bsub:byte;
rmult,gmult,bmult: single;
begin
base := 64;
rmult := (Colour.X * 255) / 128;
gmult := (Colour.Y * 255) / 128;
bmult := (Colour.Z * 255) / 128;
// Generate Remmapable colours
if rmult <> 0 then
rsub := 1
else
rsub := 0;
if gmult <> 0 then
gsub := 1
else
gsub := 0;
if bmult <> 0 then
bsub := 1
else
bsub := 0;
for x := 16 to 31 do
begin
Palette[x]:= RGB(Round(((base*2)*rmult)-rsub),Round(((base*2)*gmult)-gsub),Round(((base*2)*bmult)-bsub));
if (((x+1) div 3) <> 0) then
base := base - 4
else
base := base - 3;
end;
end;
function GetCorrectColour(Color : integer) : TVector3f;
begin
result := TColorToTVector3f(VXLPalette[Color]);
end;
Function GetVXLColor(Color,Normal : integer) : TVector3f;
begin
if SpectrumMode = ModeColours then
Result := GetCorrectColour(color)
else
Result := CleanV3fCol(SetVector(127,127,127));
end;
Function GetVXLColorWithSelection(const Vxl : TVoxel; Color,Normal,Section : integer) : TVector4f;
var
Color3f: TVector3f;
begin
Color3f := GetVXLColor(Color,Normal);
Result.X := Color3f.X;
Result.Y := Color3f.Y;
Result.Z := Color3f.Z;
Result.W := 1;
if ((Vxl <> CurrentVoxel^) or (Section <> CurrentVoxelSection)) and (Highlight) then
begin
Result.W := 0.05;
end;
end;
Procedure LoadVoxel2(const Filename,Ext : String; Var Voxel : TVoxel; Var VoxelOpen : Boolean);
Var
FName : String;
begin
FName := ExtractFileDir(Filename) + '\' + copy(ExtractFilename(Filename),1,Length(ExtractFilename(Filename))-Length('.vxl')) + Ext;
if VoxelOpen then
try
Voxel.Free;
Voxel := nil;
finally
VoxelOpen := false;
end;
If FileExists(FName) then
begin
Try
Voxel := TVoxel.Create;
Voxel.LoadFromFile(FName);
VoxelOpen := True;
Except
VoxelOpen := False;
End;
end
else
begin
VoxelOpen := False;
end;
end;
Procedure LoadVoxel(const Filename : String);
begin
VXLChanged := False;
HVAFrame := 0;
HVAFrameT := 0;
HVAFrameB := 0;
CurrentVoxelSection := 0;
LoadVoxel2(Filename,'.vxl',VoxelFile,VoxelOpen);
LoadVoxel2(Filename,'tur.vxl',VoxelTurret,VoxelOpenT);
LoadVoxel2(Filename,'barl.vxl',VoxelBarrel,VoxelOpenB);
If VoxelOpen then
begin
VXLFilename := Copy(ExtractFilename(Filename),1,Length(ExtractFilename(Filename))-Length(ExtractFileExt(Filename)));
CurrentVoxel := @VoxelFile;
CurrentSectionVoxel := @VoxelFile;
end
else
begin
VXLFilename := '';
CurrentVoxel := nil;
CurrentSectionVoxel := nil;
end;
LoadHVA(Filename);
UpdateVoxelList;
end;
Procedure SetSpectrum(Colours : Boolean);
begin
If Colours then
SpectrumMode := ModeColours
else
SpectrumMode := ModeNormals;
end;
Procedure ChangeOffset(const Vxl : TVoxel; Section : integer; X,Y,Z : single);
var
CD : TVector3f;
begin
CD.x := CurrentVoxel^.Section[Section].Tailer.MaxBounds[1] + (-(CurrentVoxel^.Section[Section].Tailer.MaxBounds[1]-CurrentVoxel^.Section[Section].Tailer.MinBounds[1])/2);
CD.y := CurrentVoxel^.Section[Section].Tailer.MaxBounds[2] + (-(CurrentVoxel^.Section[Section].Tailer.MaxBounds[2]-CurrentVoxel^.Section[Section].Tailer.MinBounds[2])/2);
CD.z := CurrentVoxel^.Section[Section].Tailer.MaxBounds[3] + (-(CurrentVoxel^.Section[Section].Tailer.MaxBounds[3]-CurrentVoxel^.Section[Section].Tailer.MinBounds[3])/2);
Vxl.Section[Section].Tailer.MinBounds[1] := Vxl.Section[Section].Tailer.MinBounds[1] + X;
Vxl.Section[Section].Tailer.MinBounds[2] := Vxl.Section[Section].Tailer.MinBounds[2] + Y;
Vxl.Section[Section].Tailer.MinBounds[3] := Vxl.Section[Section].Tailer.MinBounds[3] + Z;
Vxl.Section[Section].Tailer.MaxBounds[1] := Vxl.Section[Section].Tailer.MaxBounds[1] + X;
Vxl.Section[Section].Tailer.MaxBounds[2] := Vxl.Section[Section].Tailer.MaxBounds[2] + Y;
Vxl.Section[Section].Tailer.MaxBounds[3] := Vxl.Section[Section].Tailer.MaxBounds[3] + Z;
end;
function GetSectionStartPosition(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift, _TurretOffset: TVector3f; const _Rotation: single; const _VoxelBoxSize: single): TVector3f;
var
Scale, Offset: TVector3f;
UnitRotation, TurretRotation: single;
begin
GETMinMaxBounds(_Voxel^,_Section,Scale,Offset);
Result.X := (Offset.X * _VoxelBoxSize * 2) - _VoxelBoxSize;
Result.Y := (Offset.Y * _VoxelBoxSize * 2) - _VoxelBoxSize;
Result.Z := (Offset.Z * _VoxelBoxSize * 2) - _VoxelBoxSize;
if (_Voxel^ = VoxelTurret) or (_Voxel^ = VoxelBarrel) then
begin
Result.X := Result.X + _TurretOffset.X * _VoxelBoxSize * 2 * LeptonSize;
end;
Scale := ScaleVector(Scale, _VoxelBoxSize * 2);
Result := ApplyMatrixToVector(_HVA^, _Voxel^, Result, Scale, _Section, _Frame);
if (_Voxel = Addr(VoxelTurret)) or (_Voxel = Addr(VoxelBarrel)) then
begin
TurretRotation := DEG2RAD(VXLTurretRotation.X);
Result.X := (Result.X * cos(TurretRotation)) - (Result.Y * sin(TurretRotation));
Result.Y := (Result.X * sin(TurretRotation)) + (Result.Y * cos(TurretRotation));
end;
UnitRotation := DEG2RAD(_Rotation);
Result.X := (Result.X * cos(UnitRotation)) - (Result.Y * sin(UnitRotation));
Result.Y := (Result.X * sin(UnitRotation)) + (Result.Y * cos(UnitRotation));
Result := AddVector(Result, _UnitShift);
end;
function GetSectionCenterPosition(const _Voxel: PVoxel; const _HVA: PHVA; const _Section, _Frame: integer; const _UnitShift, _TurretOffset: TVector3f; const _Rotation: single; const _VoxelBoxSize: single): TVector3f;
var
Scale, Offset: TVector3f;
UnitRotation, TurretRotation: single;
begin
GETMinMaxBounds(_Voxel^,_Section,Scale,Offset);
Result.X := (_Voxel^.Section[_Section].Tailer.XSize * _VoxelBoxSize * Scale.X) + (Offset.X * _VoxelBoxSize * 2) - _VoxelBoxSize;
Result.Y := (_Voxel^.Section[_Section].Tailer.YSize * _VoxelBoxSize * Scale.Y) + (Offset.Y * _VoxelBoxSize * 2) - _VoxelBoxSize;
Result.Z := (_Voxel^.Section[_Section].Tailer.ZSize * _VoxelBoxSize * Scale.Z) + (Offset.Z * _VoxelBoxSize * 2) - _VoxelBoxSize;
if (_Voxel^ = VoxelTurret) or (_Voxel^ = VoxelBarrel) then
begin
Result.X := Result.X + _TurretOffset.X * _VoxelBoxSize * 2 * LeptonSize;
end;
Scale := ScaleVector(Scale, _VoxelBoxSize * 2);
Result := ApplyMatrixToVector(_HVA^, _Voxel^, Result, Scale, _Section, _Frame);
if (_Voxel = Addr(VoxelTurret)) or (_Voxel = Addr(VoxelBarrel)) then
begin
TurretRotation := DEG2RAD(VXLTurretRotation.X);
Result.X := (Result.X * cos(TurretRotation)) - (Result.Y * sin(TurretRotation));
Result.Y := (Result.X * sin(TurretRotation)) + (Result.Y * cos(TurretRotation));
end;
UnitRotation := DEG2RAD(_Rotation);
Result.X := (Result.X * cos(UnitRotation)) - (Result.Y * sin(UnitRotation));
Result.Y := (Result.X * sin(UnitRotation)) + (Result.Y * cos(UnitRotation));
Result := AddVector(Result, _UnitShift);
end;
begin
VoxelBox_No := 0;
VoxelBoxes.NumSections := 0;
SetLength(VoxelBoxes.Sections,VoxelBox_No);
VoxelBox_NoT := 0;
VoxelBoxesT.NumSections := 0;
SetLength(VoxelBoxesB.Sections,VoxelBox_NoT);
VoxelBox_NoB := 0;
VoxelBoxesB.NumSections := 0;
SetLength(VoxelBoxesB.Sections,VoxelBox_NoB);
end.
|
unit uLoginCS;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxControls, cxContainer, cxEdit, cxLabel,
cxLookAndFeelPainters, StdCtrls, cxButtons, ActnList;
type
TFormLoginCS = class(TForm)
cxLabelLogin: TcxLabel;
cxLabelPassword: TcxLabel;
cxTextEditLogin: TcxTextEdit;
cxTextEditPassword: TcxTextEdit;
ActionListKlassSpravEdit: TActionList;
ActionOK: TAction;
ActionCansel: TAction;
cxButtonOK: TcxButton;
cxButtonCansel: TcxButton;
procedure FormCreate(Sender: TObject);
procedure ActionOKExecute(Sender: TObject);
procedure ActionCanselExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
Id_LangLog :integer;
procedure inicCaption;
public
{ Public declarations }
end;
var
FormLoginCS: TFormLoginCS;
implementation
uses
uCS_Constants,uCS_Resources,registry;
{$R *.dfm}
{ TFormLogin }
procedure TFormLoginCS.FormCreate(Sender: TObject);
var
reg :TRegistry;
begin
Id_LangLog:=SelectLanguage;
inicCaption;
cxTextEditLogin.Text :='';
cxTextEditPassword.Text :='';
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\CS\Data\',false) then
begin
cxTextEditLogin.Text :=reg.ReadString('Login');
end;
finally
reg.Free;
end;
end;
procedure TFormLoginCS.inicCaption;
begin
TFormLoginCS(self).Caption := nFormLogin_Caption[Id_LangLog];
cxLabelLogin.Caption := nLabelLogin[Id_LangLog];
cxLabelPassword.Caption := nLabelPassword[Id_LangLog];
ActionOK.Caption :=nActiont_OK[Id_LangLog];
ActionCansel.Caption :=nActiont_Cansel[Id_LangLog];
ActionOK.Hint :=nHintActiont_OK[Id_LangLog];
ActionCansel.Hint :=nHintActiont_Cansel[Id_LangLog];
end;
procedure TFormLoginCS.ActionOKExecute(Sender: TObject);
var
reg :TRegistry;
begin
reg:=TRegistry.Create;
try
reg.RootKey :=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\CS\Data\',true) then
begin
reg.WriteString('Login', cxTextEditLogin.Text);
end;
finally
reg.Free;
end;
ModalResult:=mrOk;
end;
procedure TFormLoginCS.ActionCanselExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormLoginCS.FormShow(Sender: TObject);
begin
if Trim(cxTextEditLogin.Text)<>''
then cxTextEditPassword.SetFocus;
end;
end.
|
unit Allgemein.RegIni;
interface
uses
IniFiles, SysUtils, Types, Registry, Variants, Windows, Classes;
type
TevRootKey = (HKEY_CLASSES_ROOT_, HKEY_CURRENT_USER_, HKEY_LOCAL_MACHINE_,
HKEY_USERS_, HKEY_PERFORMANCE_DATA_, HKEY_CURRENT_CONFIG_,
HKEY_DYN_DATA_);
function ReadIni(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): WideString;
function ReadIniToInt(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): Integer;
function ReadIniToDir(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): WideString;
procedure ReadIniSection(const aFullFileName: string; aSectionList: TStrings);
procedure DeleteIniSection(const aFullFileName: string; aSection: string);
procedure WriteIni(const aFullFileName, aSection, aKey: WideString; aValue: WideString);
function RootKeyToDWord(const aevRootKey: TevRootKey): DWord;
procedure WriteRegistry(const aRootKey: TevRootKey; const aRegPfad, aSchluessel: String;
const aValue: Variant; const aCanCreate: Boolean = true);
function ReadRegistry(const aRootKey: TevRootKey; const aRegPfad, aSchluessel: String;
aDefault: Variant; const aCanCreate: Boolean = false): Variant;
implementation
function ReadIni(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): WideString;
var
INI: TIniFile;
begin
INI := TIniFile.Create(aFullFileName);
try
Result := INI.ReadString(aSection, aKey, aDefault);
finally
FreeAndNil(INI);
end;
end;
// Lesen aus einer INI-Datei und Rückgabe als Integer-Wert
function ReadIniToInt(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): Integer;
var
INI: TIniFile;
s : string;
begin
INI := TIniFile.Create(aFullFileName);
try
s := INI.ReadString(aSection, aKey, aDefault);
if not TryStrToInt(s, Result) then
Result := StrToInt(aDefault);
finally
FreeAndNil(INI);
end;
end;
// Lesen aus einer INI-Datei mit Rückgabe als Direction inclusive letzten Backslash
function ReadIniToDir(const aFullFileName, aSection, aKey: WideString; aDefault: WideString): WideString;
var
INI: TIniFile;
begin
INI := TIniFile.Create(aFullFileName);
try
Result := INI.ReadString(aSection, aKey, aDefault);
if Result = '' then
exit;
Result := IncludeTrailingPathDelimiter(Result);
finally
FreeAndNil(INI);
end;
end;
// Schreibe in eine INI-Datei
procedure WriteIni(const aFullFileName, aSection, aKey: WideString; aValue: WideString);
var
INI: TIniFile;
begin
INI := TIniFile.Create(aFullFileName);
try
INI.WriteString(aSection, aKey, aValue);
finally
FreeAndNil(INI);
end;
end;
// Den Rootkey holen
function RootKeyToDWord(const aevRootKey: TevRootKey): DWord;
begin
Result := 0;
if aevRootKey = HKEY_CLASSES_ROOT_ then
Result := Windows.HKEY_CLASSES_ROOT;
if aevRootKey = HKEY_CURRENT_USER_ then
Result := Windows.HKEY_CURRENT_USER;
if aevRootKey = HKEY_LOCAL_MACHINE_ then
Result := Windows.HKEY_LOCAL_MACHINE;
if aevRootKey = HKEY_USERS_ then
Result := Windows.HKEY_USERS;
if aevRootKey = HKEY_PERFORMANCE_DATA_ then
Result := Windows.HKEY_PERFORMANCE_DATA;
if aevRootKey = HKEY_CURRENT_CONFIG_ then
Result := Windows.HKEY_CURRENT_CONFIG;
if aevRootKey = HKEY_DYN_DATA_ then
Result := Windows.HKEY_DYN_DATA;
end;
// Schreiben in die Registry
procedure WriteRegistry(const aRootKey: TevRootKey; const aRegPfad, aSchluessel: String;
const aValue: Variant; const aCanCreate: Boolean = true);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
Try
Reg.RootKey := RootKeyToDWord(aRootKey);
if not Reg.OpenKey(aRegPfad, aCanCreate) then
exit;
Reg.WriteString(aSchluessel, aValue);
{
Case VarType(aValue) of
varOleStr,
varString: Reg.WriteString(aSchluessel, aValue);
varInteger: Reg.WriteInteger(aSchluessel, aValue);
varDate: Reg.WriteDate(aSchluessel, aValue);
varBoolean: Reg.WriteBool(aSchluessel, aValue);
varCurrency,
varDouble: Reg.WriteFloat(aSchluessel, aValue);
end;
}
Reg.CloseKey;
finally
FreeAndNil(Reg);
end;
end;
// Lesen der Registry
function ReadRegistry(const aRootKey: TevRootKey; const aRegPfad, aSchluessel: String;
aDefault: Variant; const aCanCreate: Boolean = false): Variant;
var
Reg: TRegistry;
Result_OpenKey: Boolean;
begin
Reg := TRegistry.Create(KEY_READ);
Try
Reg.RootKey := RootKeyToDWord(aRootKey);
if aCanCreate then
Result_OpenKey := Reg.OpenKey(aRegPfad, aCanCreate)
else
Result_OpenKey := Reg.OpenKeyReadOnly(aRegPfad);
if not Result_OpenKey then
begin
Result := aDefault;
exit;
end;
Result := Reg.ReadString(aSchluessel);
{
Case VarType(aDefault) of
varOleStr,
varString:
begin
try
Result := Reg.ReadString(aSchluessel);
except
Result := aDefault;
end;
if Result = '' then
Result := aDefault;
end;
varInteger:
begin
try
Result := Reg.ReadInteger(aSchluessel);
except
Result := aDefault;
end;
end;
varDate:
begin
try
Result := Reg.ReadDate(aSchluessel);
except
Result := aDefault;
end;
end;
varBoolean:
begin
try
Result := Reg.ReadBool(aSchluessel);
except
Result := aDefault;
end;
end;
varCurrency,
varDouble:
begin
try
Result := Reg.ReadFloat(aSchluessel);
except
Result := aDefault;
end;
end;
end;
}
Reg.CloseKey;
finally
FreeAndNil(Reg);
end;
end;
procedure ReadIniSection(const aFullFileName: string; aSectionList: TStrings);
var
INI: TIniFile;
begin
aSectionList.Clear;
INI := TIniFile.Create(aFullFileName);
try
Ini.ReadSections(aSectionList);
finally
FreeAndNil(INI);
end;
end;
procedure DeleteIniSection(const aFullFileName: string; aSection: string);
var
INI: TIniFile;
begin
INI := TIniFile.Create(aFullFileName);
try
Ini.EraseSection(aSection);
finally
FreeAndNil(INI);
end;
end;
end.
|
unit ClassesMOD;
interface
uses
Activex,
Windows,
StreamUnit;
type
ISequentialStream = interface(IUnknown)
['{0c733a30-2a1c-11ce-ade5-00aa0044773d}']
function Read(pv: Pointer; cb: Longint; pcbRead: PLongint): HResult;
stdcall;
function Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult;
stdcall;
end;
TStreamOwnership = (soReference, soOwned);
TStreamAdapter = class(TInterfacedObject, IStream)
private
FStream: TStream;
FOwnership: TStreamOwnership;
public
constructor Create(Stream: TStream; Ownership: TStreamOwnership = soReference);
destructor Destroy; override;
function Read(pv: Pointer; cb: Longint;
pcbRead: PLongint): HResult; virtual; stdcall;
function Write(pv: Pointer; cb: Longint;
pcbWritten: PLongint): HResult; virtual; stdcall;
function Seek(dlibMove: Largeint; dwOrigin: Longint;
out libNewPosition: Largeint): HResult; virtual; stdcall;
function SetSize(libNewSize: Largeint): HResult; virtual; stdcall;
function CopyTo(stm: IStream; cb: Largeint; out cbRead: Largeint;
out cbWritten: Largeint): HResult; virtual; stdcall;
function Commit(grfCommitFlags: Longint): HResult; virtual; stdcall;
function Revert: HResult; virtual; stdcall;
function LockRegion(libOffset: Largeint; cb: Largeint;
dwLockType: Longint): HResult; virtual; stdcall;
function UnlockRegion(libOffset: Largeint; cb: Largeint;
dwLockType: Longint): HResult; virtual; stdcall;
function Stat(out statstg: TStatStg;
grfStatFlag: Longint): HResult; virtual; stdcall;
function Clone(out stm: IStream): HResult; virtual; stdcall;
property Stream: TStream read FStream;
property StreamOwnership: TStreamOwnership read FOwnership write FOwnership;
end;
implementation
constructor TStreamAdapter.Create(Stream: TStream;
Ownership: TStreamOwnership);
begin
inherited Create;
FStream := Stream;
FOwnership := Ownership;
end;
destructor TStreamAdapter.Destroy;
begin
if FOwnership = soOwned then
begin
FStream.Free;
FStream := nil;
end;
inherited Destroy;
end;
function TStreamAdapter.Read(pv: Pointer; cb: Longint; pcbRead: PLongint): HResult;
var
NumRead: Longint;
begin
try
if pv = Nil then
begin
Result := STG_E_INVALIDPOINTER;
Exit;
end;
NumRead := FStream.Read(pv^, cb);
if pcbRead <> Nil then pcbRead^ := NumRead;
Result := S_OK;
except
Result := S_FALSE;
end;
end;
function TStreamAdapter.Write(pv: Pointer; cb: Longint; pcbWritten: PLongint): HResult;
var
NumWritten: Longint;
begin
try
if pv = Nil then
begin
Result := STG_E_INVALIDPOINTER;
Exit;
end;
NumWritten := FStream.Write(pv^, cb);
if pcbWritten <> Nil then pcbWritten^ := NumWritten;
Result := S_OK;
except
Result := STG_E_CANTSAVE;
end;
end;
function TStreamAdapter.Seek(dlibMove: Largeint; dwOrigin: Longint;
out libNewPosition: Largeint): HResult;
var
NewPos: LargeInt;
begin
try
if (dwOrigin < STREAM_SEEK_SET) or (dwOrigin > STREAM_SEEK_END) then
begin
Result := STG_E_INVALIDFUNCTION;
Exit;
end;
NewPos := FStream.Seek(dlibMove, dwOrigin);
if @libNewPosition <> nil then libNewPosition := NewPos;
Result := S_OK;
except
Result := STG_E_INVALIDPOINTER;
end;
end;
function TStreamAdapter.SetSize(libNewSize: Largeint): HResult;
begin
try
FStream.Size := libNewSize;
if libNewSize <> FStream.Size then
Result := E_FAIL
else
Result := S_OK;
except
Result := E_UNEXPECTED;
end;
end;
function TStreamAdapter.CopyTo(stm: IStream; cb: Largeint; out cbRead: Largeint;
out cbWritten: Largeint): HResult;
const
MaxBufSize = 1024 * 1024; // 1mb
var
Buffer: Pointer;
BufSize, N, I, R: Integer;
BytesRead, BytesWritten, W: LargeInt;
begin
Result := S_OK;
BytesRead := 0;
BytesWritten := 0;
try
if cb > MaxBufSize then
BufSize := MaxBufSize
else
BufSize := Integer(cb);
GetMem(Buffer, BufSize);
try
while cb > 0 do
begin
if cb > MaxInt then
I := MaxInt
else
I := cb;
while I > 0 do
begin
if I > BufSize then N := BufSize else N := I;
R := FStream.Read(Buffer^, N);
if R = 0 then Exit; // The end of the stream was hit.
Inc(BytesRead, R);
W := 0;
Result := stm.Write(Buffer, R, @W);
Inc(BytesWritten, W);
if (Result = S_OK) and (Integer(W) <> R) then Result := E_FAIL;
if Result <> S_OK then Exit;
Dec(I, R);
Dec(cb, R);
end;
end;
finally
FreeMem(Buffer);
if (@cbWritten <> nil) then cbWritten := BytesWritten;
if (@cbRead <> nil) then cbRead := BytesRead;
end;
except
Result := E_UNEXPECTED;
end;
end;
function TStreamAdapter.Commit(grfCommitFlags: Longint): HResult;
begin
Result := S_OK;
end;
function TStreamAdapter.Revert: HResult;
begin
Result := STG_E_REVERTED;
end;
function TStreamAdapter.LockRegion(libOffset: Largeint; cb: Largeint;
dwLockType: Longint): HResult;
begin
Result := STG_E_INVALIDFUNCTION;
end;
function TStreamAdapter.UnlockRegion(libOffset: Largeint; cb: Largeint;
dwLockType: Longint): HResult;
begin
Result := STG_E_INVALIDFUNCTION;
end;
function TStreamAdapter.Stat(out statstg: TStatStg; grfStatFlag: Longint): HResult;
begin
Result := S_OK;
try
if (@statstg <> nil) then
with statstg do
begin
dwType := STGTY_STREAM;
cbSize := FStream.Size;
mTime.dwLowDateTime := 0;
mTime.dwHighDateTime := 0;
cTime.dwLowDateTime := 0;
cTime.dwHighDateTime := 0;
aTime.dwLowDateTime := 0;
aTime.dwHighDateTime := 0;
grfLocksSupported := LOCK_WRITE;
end;
except
Result := E_UNEXPECTED;
end;
end;
function TStreamAdapter.Clone(out stm: IStream): HResult;
begin
Result := E_NOTIMPL;
end;
end.
|
unit Form.Request;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Lib.HTTPContent,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Lib.HTTPConsts,
Lib.HTTPUtils,
Lib.HeaderValues;
type
TRequestForm = class(TForm)
RequestButton: TButton;
CancelButton: TButton;
MethodLabel: TLabel;
MethodComboBox: TComboBox;
HeadersLabel: TLabel;
AddButton: TButton;
RequestLabel: TLabel;
RequestEdit: TEdit;
ProtocolLabel: TLabel;
BottomBevel: TBevel;
HeaderNameComboBox: TComboBox;
HeaderValueComboBox: TComboBox;
ContentMemo: TMemo;
ContentLabel: TLabel;
ContentTypeComboBox: TComboBox;
ContentTypeLabel: TLabel;
OpenFileButton: TButton;
OpenDialog1: TOpenDialog;
RemoveFileButton: TButton;
HeadersMemo: TMemo;
ProtocolComboBox: TComboBox;
procedure AddButtonClick(Sender: TObject);
procedure HeaderNameComboBoxChange(Sender: TObject);
procedure OpenFileButtonClick(Sender: TObject);
procedure RemoveFileButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FRequest: TRequest;
FContentFileName: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean;
procedure SetURL(const Value: string);
property Request: TRequest read FRequest;
end;
implementation
{$R *.dfm}
constructor TRequestForm.Create(AOwner: TComponent);
begin
inherited;
FContentFileName:='';
FRequest:=TRequest.Create;
HTTPGetContentTypes(ContentTypeComboBox.Items);
end;
destructor TRequestForm.Destroy;
begin
FRequest.Free;
inherited;
end;
procedure TRequestForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=TCloseAction.caFree;
end;
procedure TRequestForm.SetURL(const Value: string);
begin
Request.Reset;
Request.DecomposeURL(Value);
Request.Protocol:=PROTOCOL_HTTP11;
Request.Method:=METHOD_GET;
Request.Headers.SetValue('Host',Request.Host);
RequestEdit.Text:=Value;
end;
function TRequestForm.Execute: Boolean;
begin
ProtocolComboBox.Text:=FRequest.Protocol;
ContentMemo.Clear;
MethodComboBox.ItemIndex:=MethodComboBox.Items.IndexOf(FRequest.Method.ToUpper);
HeaderNameComboBox.OnChange(nil);
ContentTypeComboBox.ItemIndex:=0;
HeadersMemo.Lines.Text:=FRequest.Headers.Text;
HeaderNameComboBox.Text:='';
HeaderValueComboBox.Text:='';
Result:=ShowModal=mrOk;
if Result then
begin
FRequest.DecomposeURL(RequestEdit.Text);
FRequest.Protocol:=ProtocolComboBox.Text;
FRequest.Method:=MethodComboBox.Text;
FRequest.Headers.Text:=HeadersMemo.Lines.Text;
if FContentFileName<>'' then
FRequest.AddContentFile(FContentFileName,ContentTypeComboBox.Text)
else
if ContentMemo.Text<>'' then
FRequest.AddContentText(ContentMemo.Text,ContentTypeComboBox.Text);
end;
end;
procedure TRequestForm.AddButtonClick(Sender: TObject);
begin
if string(HeaderNameComboBox.Text).Trim<>'' then
if string(HeaderValueComboBox.Text).Trim<>'' then
begin
HeadersMemo.Lines.Add(HeaderNameComboBox.Text+': '+HeaderValueComboBox.Text);
HeaderNameComboBox.Text:='';
HeaderValueComboBox.Text:='';
end;
end;
procedure TRequestForm.HeaderNameComboBoxChange(Sender: TObject);
begin
GetHeaderRequestValues(RequestEdit.Text,HeaderNameComboBox.Text,
HeaderValueComboBox.Items);
HeaderValueComboBox.Text:='';
HeaderValueComboBox.ItemIndex:=-1;
HeaderValueComboBox.ItemIndex:=0;
end;
procedure TRequestForm.OpenFileButtonClick(Sender: TObject);
begin
if OpenDialog1.Execute(Handle) then
begin
FContentFileName:=OpenDialog1.FileName;
ContentMemo.Text:=FContentFileName;
ContentMemo.ReadOnly:=True;
ContentMemo.ParentColor:=True;
ContentTypeComboBox.Text:=HTTPGetMIMEType(ExtractFileExt(FContentFileName));
end;
end;
procedure TRequestForm.RemoveFileButtonClick(Sender: TObject);
begin
FContentFileName:='';
ContentTypeComboBox.ItemIndex:=-1;
ContentTypeComboBox.ItemIndex:=0;
ContentMemo.Clear;
ContentMemo.ReadOnly:=False;
ContentMemo.Color:=HeadersMemo.Color;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclBase.pas. }
{ }
{ The Initial Developer of the Original Code is Marcel van Brakel. }
{ Portions created by Marcel van Brakel are Copyright Marcel van Brakel. All rights reserved. }
{ }
{ Contributors: }
{ Marcel van Brakel, }
{ Peter Friese, }
{ Robert Marquardt (marquardt) }
{ Robert Rossmair (rrossmair) }
{ Petr Vones (pvones) }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ This unit contains generic JCL base classes and routines to support earlier }
{ versions of Delphi as well as FPC. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2009-06-22 21:15:21 +0200 (lun. 22 juin 2009) $ }
{ Revision: $Rev:: 2826 $ }
{ Author: $Author:: outchy $ }
{ }
{**************************************************************************************************}
unit JclBase;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF CLR}
Classes, System.Reflection,
{$ELSE ~CLR}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF MSWINDOWS}
{$ENDIF ~CLR}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
{$ENDIF SUPPORTS_GENERICS}
SysUtils;
// Version
const
JclVersionMajor = 1; // 0=pre-release|beta/1, 2, ...=final
JclVersionMinor = 105; // Fifth minor release since JCL 1.90
JclVersionRelease = 1; // 0: pre-release|beta/ 1: release
JclVersionBuild = 3400; // build number, days since march 1, 2000
JclVersion = (JclVersionMajor shl 24) or (JclVersionMinor shl 16) or
(JclVersionRelease shl 15) or (JclVersionBuild shl 0);
// EJclError
type
EJclError = class(Exception);
{$IFDEF CLR}
DWORD = LongWord;
TIntegerSet = set of 0..SizeOf(Integer) * 8 - 1;
{$ENDIF CLR}
// EJclWin32Error
{$IFDEF MSWINDOWS}
type
EJclWin32Error = class(EJclError)
private
FLastError: DWORD;
FLastErrorMsg: string;
public
constructor Create(const Msg: string);
constructor CreateFmt(const Msg: string; const Args: array of const);
{$IFNDEF CLR}
constructor CreateRes(Ident: Integer); overload;
constructor CreateRes(ResStringRec: PResStringRec); overload;
{$ENDIF ~CLR}
property LastError: DWORD read FLastError;
property LastErrorMsg: string read FLastErrorMsg;
end;
{$ENDIF MSWINDOWS}
// EJclInternalError
type
EJclInternalError = class(EJclError);
// Types
type
{$IFDEF MATH_EXTENDED_PRECISION}
Float = Extended;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
Float = Double;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
Float = Single;
{$ENDIF MATH_SINGLE_PRECISION}
PFloat = ^Float;
type
{$IFDEF FPC}
Largeint = Int64;
{$ELSE ~FPC}
PPointer = ^Pointer;
{$IFDEF RTL140_UP}
{$IFDEF CLR}
PJclByteArray = TBytes;
{$ELSE ~CLR}
PByte = System.PByte;
Int8 = ShortInt;
Int16 = Smallint;
Int32 = Integer;
UInt8 = Byte;
UInt16 = Word;
UInt32 = LongWord;
{$ENDIF ~CLR}
{$ELSE ~RTL140_UP}
PBoolean = ^Boolean;
PByte = Windows.PByte;
{$ENDIF ~RTL140_UP}
{$ENDIF ~FPC}
PCardinal = ^Cardinal;
{$IFNDEF COMPILER7_UP}
UInt64 = Int64;
{$ENDIF ~COMPILER7_UP}
{$IFNDEF CLR}
PWideChar = System.PWideChar;
PPWideChar = ^JclBase.PWideChar;
PInt64 = type System.PInt64;
PPInt64 = ^JclBase.PInt64;
{$ENDIF ~CLR}
// Interface compatibility
{$IFDEF SUPPORTS_INTERFACE}
{$IFNDEF FPC}
{$IFNDEF RTL140_UP}
type
IInterface = IUnknown;
{$ENDIF ~RTL140_UP}
{$ENDIF ~FPC}
{$ENDIF SUPPORTS_INTERFACE}
// Int64 support
procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal);
procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal);
// Redefinition of TLargeInteger to relieve dependency on Windows.pas
type
PLargeInteger = ^TLargeInteger;
TLargeInteger = Int64;
{$IFNDEF COMPILER11_UP}
TBytes = array of Byte;
{$ENDIF ~COMPILER11_UP}
{$IFDEF CLR}
type
TJclBytes = TBytes;
{$ELSE ~CLR}
// Redefinition of PByteArray to avoid range check exceptions.
type
TJclByteArray = array [0..MaxInt div SizeOf(Byte) - 1] of Byte;
PJclByteArray = ^TJclByteArray;
TJclBytes = Pointer; // under .NET System.pas: TBytes = array of Byte;
// Redefinition of TULargeInteger to relieve dependency on Windows.pas
type
PULargeInteger = ^TULargeInteger;
TULargeInteger = record
case Integer of
0:
(LowPart: LongWord;
HighPart: LongWord);
1:
(QuadPart: Int64);
end;
{$ENDIF ~CLR}
// Dynamic Array support
type
TDynByteArray = array of Byte;
TDynShortIntArray = array of Shortint;
TDynWordArray = array of Word;
TDynSmallIntArray = array of Smallint;
TDynLongIntArray = array of Longint;
TDynInt64Array = array of Int64;
TDynCardinalArray = array of Cardinal;
TDynIntegerArray = array of Integer;
TDynExtendedArray = array of Extended;
TDynDoubleArray = array of Double;
TDynSingleArray = array of Single;
TDynFloatArray = array of Float;
{$IFNDEF CLR}
TDynPointerArray = array of Pointer;
{$ENDIF ~CLR}
TDynStringArray = array of string;
TDynAnsiStringArray = array of AnsiString;
TDynWideStringArray = array of WideString;
{$IFDEF SUPPORTS_UNICODE_STRING}
TDynUnicodeStringArray = array of UnicodeString;
{$ENDIF SUPPORTS_UNICODE_STRING}
TDynIInterfaceArray = array of IInterface;
TDynObjectArray = array of TObject;
TDynCharArray = array of Char;
TDynAnsiCharArray = array of AnsiChar;
TDynWideCharArray = array of WideChar;
// Cross-Platform Compatibility
const
// line delimiters for a version of Delphi/C++Builder
NativeLineFeed = Char(#10);
NativeCarriageReturn = Char(#13);
NativeCrLf = string(#13#10);
// default line break for a version of Delphi on a platform
{$IFDEF MSWINDOWS}
NativeLineBreak = NativeCrLf;
{$ENDIF MSWINDOWS}
{$IFDEF UNIX}
NativeLineBreak = NativeLineFeed;
{$ENDIF UNIX}
HexPrefixPascal = string('$');
HexPrefixC = string('0x');
{$IFDEF BCB}
HexPrefix = HexPrefixC;
{$ELSE ~BCB}
HexPrefix = HexPrefixPascal;
{$ENDIF ~BCB}
const
BOM_UTF16_LSB: array [0..1] of Byte = ($FF,$FE);
BOM_UTF16_MSB: array [0..1] of Byte = ($FE,$FF);
BOM_UTF8: array [0..2] of Byte = ($EF,$BB,$BF);
BOM_UTF32_LSB: array [0..3] of Byte = ($FF,$FE,$00,$00);
BOM_UTF32_MSB: array [0..3] of Byte = ($00,$00,$FE,$FF);
// BOM_UTF7_1: array [0..3] of Byte = ($2B,$2F,$76,$38);
// BOM_UTF7_2: array [0..3] of Byte = ($2B,$2F,$76,$39);
// BOM_UTF7_3: array [0..3] of Byte = ($2B,$2F,$76,$2B);
// BOM_UTF7_4: array [0..3] of Byte = ($2B,$2F,$76,$2F);
// BOM_UTF7_5: array [0..3] of Byte = ($2B,$2F,$76,$38,$2D);
type
// Unicode transformation formats (UTF) data types
PUTF7 = ^UTF7;
UTF7 = AnsiChar;
PUTF8 = ^UTF8;
UTF8 = AnsiChar;
PUTF16 = ^UTF16;
UTF16 = WideChar;
PUTF32 = ^UTF32;
UTF32 = Cardinal;
// UTF conversion schemes (UCS) data types
PUCS4 = ^UCS4;
UCS4 = Cardinal;
PUCS2 = PWideChar;
UCS2 = WideChar;
TUCS2Array = array of UCS2;
TUCS4Array = array of UCS4;
// string types
TUTF8String = AnsiString;
TUTF16String = WideString;
TUCS2String = WideString;
var
AnsiReplacementCharacter: AnsiChar;
const
UCS4ReplacementCharacter: UCS4 = $0000FFFD;
MaximumUCS2: UCS4 = $0000FFFF;
MaximumUTF16: UCS4 = $0010FFFF;
MaximumUCS4: UCS4 = $7FFFFFFF;
SurrogateHighStart = UCS4($D800);
SurrogateHighEnd = UCS4($DBFF);
SurrogateLowStart = UCS4($DC00);
SurrogateLowEnd = UCS4($DFFF);
// basic set types
type
TSetOfAnsiChar = set of AnsiChar;
{$IFNDEF XPLATFORM_RTL}
procedure RaiseLastOSError;
{$ENDIF ~XPLATFORM_RTL}
procedure MoveArray(var List: TDynIInterfaceArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFNDEF CLR}
procedure MoveArray(var List: TDynStringArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynFloatArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynPointerArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF SUPPORTS_UNICODE_STRING}
procedure MoveArray(var List: TDynUnicodeStringArray; FromIndex, ToIndex, Count: Integer); overload;
{$ENDIF SUPPORTS_UNICODE_STRING}
{$ENDIF ~CLR}
{$IFNDEF FPC}
procedure MoveArray(var List: TDynAnsiStringArray; FromIndex, ToIndex, Count: Integer); overload;
{$ENDIF}
procedure MoveArray(var List: TDynWideStringArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynObjectArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynSingleArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynDoubleArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFNDEF FPC}
procedure MoveArray(var List: TDynExtendedArray; FromIndex, ToIndex, Count: Integer); overload;
{$ENDIF}
procedure MoveArray(var List: TDynIntegerArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynCardinalArray; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveArray(var List: TDynInt64Array; FromIndex, ToIndex, Count: Integer); overload;
procedure MoveChar(const Source: string; FromIndex: Integer;
var Dest: string; ToIndex, Count: Integer); overload; // Index: 0..n-1
{$IFDEF CLR}
function GetBytesEx(const Value): TBytes;
procedure SetBytesEx(var Value; Bytes: TBytes);
procedure SetIntegerSet(var DestSet: TIntegerSet; Value: UInt32); inline;
function AnsiByteArrayStringLen(Data: TBytes): Integer;
function StringToAnsiByteArray(const S: string): TBytes;
function AnsiByteArrayToString(const Data: TBytes; Count: Integer): string;
type
TStringAnsiBufferStreamHelper = class helper for TStream
public
function WriteStringAnsiBuffer(const Buffer: string): Integer; overload;
function WriteStringAnsiBuffer(const Buffer: string; StrLen: Integer): Integer; overload;
function ReadStringAnsiBuffer(var Buffer: string; AnsiLen: Integer): Integer; overload;
function WriteStringAnsiBuffer(const Buffer: AnsiString): Integer; overload;
function WriteStringAnsiBuffer(const Buffer: AnsiString; StrLen: Integer): Integer; overload;
function ReadStringAnsiBuffer(var Buffer: AnsiString; AnsiLen: Integer): Integer; overload;
end;
{$ENDIF CLR}
{$IFNDEF CLR}
function BytesOf(const Value: AnsiString): TBytes; overload;
{$IFDEF COMPILER6_UP}
function BytesOf(const Value: WideString): TBytes; overload;
function BytesOf(const Value: WideChar): TBytes; overload;
{$ENDIF COMPILER6_UP}
function BytesOf(const Value: AnsiChar): TBytes; overload;
function StringOf(const Bytes: array of Byte): AnsiString; overload;
function StringOf(const Bytes: Pointer; Size: Cardinal): AnsiString; overload;
{$ENDIF CLR}
{$IFNDEF COMPILER11_UP}
type // Definitions for 32 Bit Compilers
// From BaseTsd.h
INT_PTR = Integer;
{$EXTERNALSYM INT_PTR}
LONG_PTR = Longint;
{$EXTERNALSYM LONG_PTR}
UINT_PTR = Cardinal;
{$EXTERNALSYM UINT_PTR}
ULONG_PTR = LongWord;
{$EXTERNALSYM ULONG_PTR}
DWORD_PTR = ULONG_PTR;
{$EXTERNALSYM DWORD_PTR}
{$ENDIF COMPILER11_UP}
type
TJclAddr64 = Int64;
TJclAddr32 = Cardinal;
{$IFDEF 64BIT}
TJclAddr = TJclAddr64;
{$ELSE ~64BIT}
TJclAddr = TJclAddr32;
{$ENDIF}
EJclAddr64Exception = class(EJclError);
function Addr64ToAddr32(const Value: TJclAddr64): TJclAddr32;
function Addr32ToAddr64(const Value: TJclAddr32): TJclAddr64;
{$IFDEF SUPPORTS_GENERICS}
type
TCompare<T> = function(const Obj1, Obj2: T): Integer;
TEqualityCompare<T> = function(const Obj1, Obj2: T): Boolean;
THashConvert<T> = function(const AItem: T): Integer;
{$IFNDEF CLR}
IEqualityComparer<T> = interface
function Equals(A, B: T): Boolean;
function GetHashCode(Obj: T): Integer;
end;
{$ENDIF CLR}
TEquatable<T: class> = class(TInterfacedObject, IEquatable<T>, IEqualityComparer<T>)
public
{ IEquatable<T> }
function TestEquals(Other: T): Boolean; overload;
function IEquatable<T>.Equals = TestEquals;
{ IEqualityComparer<T> }
function TestEquals(A, B: T): Boolean; overload;
function IEqualityComparer<T>.Equals = TestEquals;
function GetHashCode2(Obj: T): Integer;
function IEqualityComparer<T>.GetHashCode = GetHashCode2;
end;
{$ENDIF SUPPORTS_GENERICS}
const
{$IFDEF SUPPORTS_UNICODE}
AWSuffix = 'W';
{$ELSE ~SUPPORTS_UNICODE}
AWSuffix = 'A';
{$ENDIF ~SUPPORTS_UNICODE}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.105-Build3400/jcl/source/common/JclBase.pas $';
Revision: '$Revision: 2826 $';
Date: '$Date: 2009-06-22 21:15:21 +0200 (lun. 22 juin 2009) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
JclResources;
procedure MoveArray(var List: TDynIInterfaceArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := nil
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := nil;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := nil
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := nil;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Keep reference counting working }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
{$IFNDEF CLR}
procedure MoveArray(var List: TDynStringArray; FromIndex, ToIndex, Count: Integer); overload;
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Keep reference counting working }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
procedure MoveArray(var List: TDynFloatArray; FromIndex, ToIndex, Count: Integer); overload;
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
procedure MoveArray(var List: TDynPointerArray; FromIndex, ToIndex, Count: Integer); overload;
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$IFDEF SUPPORTS_UNICODE_STRING}
procedure MoveArray(var List: TDynUnicodeStringArray; FromIndex, ToIndex, Count: Integer); overload;
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Keep reference counting working }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF SUPPORTS_UNICODE_STRING}
{$ENDIF ~CLR}
{$IFNDEF FPC}
procedure MoveArray(var List: TDynAnsiStringArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := ''
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := '';
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := ''
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := '';
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Keep reference counting working }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
{$ENDIF ~FPC}
procedure MoveArray(var List: TDynWideStringArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := ''
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := '';
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := ''
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := '';
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Keep reference counting working }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveArray(var List: TDynObjectArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := nil
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := nil;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := nil
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := nil;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveArray(var List: TDynSingleArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveArray(var List: TDynDoubleArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
{$IFNDEF FPC}
procedure MoveArray(var List: TDynExtendedArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0.0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0.0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
{$ENDIF ~FPC}
procedure MoveArray(var List: TDynIntegerArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveArray(var List: TDynCardinalArray; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveArray(var List: TDynInt64Array; FromIndex, ToIndex, Count: Integer); overload;
{$IFDEF CLR}
var
I: Integer;
begin
if FromIndex < ToIndex then
begin
for I := Count - 1 downto 0 do
List[ToIndex + I] := List[FromIndex + I];
if (ToIndex - FromIndex) < Count then
// overlapped source and target
for I := 0 to ToIndex - FromIndex - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end
else
if FromIndex > ToIndex then
begin
for I := 0 to Count - 1 do
List[ToIndex + I] := List[FromIndex + I];
if (FromIndex - ToIndex) < Count then
// overlapped source and target
for I := Count - FromIndex + ToIndex to Count - 1 do
List[FromIndex + I] := 0
else
// independant
for I := 0 to Count - 1 do
List[FromIndex + I] := 0;
end;
end;
{$ELSE ~CLR}
begin
if Count > 0 then
begin
Move(List[FromIndex], List[ToIndex], Count * SizeOf(List[0]));
{ Clean array }
if FromIndex < ToIndex then
begin
if (ToIndex - FromIndex) < Count then
FillChar(List[FromIndex], (ToIndex - FromIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end
else
if FromIndex > ToIndex then
begin
if (FromIndex - ToIndex) < Count then
FillChar(List[ToIndex + Count], (FromIndex - ToIndex) * SizeOf(List[0]), 0)
else
FillChar(List[FromIndex], Count * SizeOf(List[0]), 0);
end;
end;
end;
{$ENDIF ~CLR}
procedure MoveChar(const Source: string; FromIndex: Integer;
var Dest: string; ToIndex, Count: Integer);
{$IFDEF CLR}
var
I: Integer;
Buf: array of Char;
begin
Buf := Dest.ToCharArray;
if FromIndex <= ToIndex then
for I := 0 to Count - 1 do
Buf[ToIndex + I] := Source[FromIndex + I]
else
for I := Count - 1 downto 0 do
Buf[ToIndex + I] := Source[FromIndex + I];
Dest := System.String.Create(Buf);
end;
{$ELSE ~CLR}
begin
Move(Source[FromIndex + 1], Dest[ToIndex + 1], Count * SizeOf(Char));
end;
{$ENDIF ~CLR}
{$IFDEF CLR}
function GetBytesEx(const Value): TBytes;
begin
if TObject(Value) is TBytes then
Result := Copy(TBytes(Value))
else
if TObject(Value) is TDynByteArray then
Result := Copy(TDynByteArray(Value))
else
if TObject(Value) is System.Enum then // e.g. TIntegerSet
BitConverter.GetBytes(UInt32(Value))
{ TODO : Add further types }
else
raise EJclError.CreateFmt(RsEGetBytesExFmt, [TObject(Value).GetType.FullName]);
end;
procedure SetBytesEx(var Value; Bytes: TBytes);
begin
if TObject(Value) is TBytes then
Value := Copy(Bytes)
else
if TObject(Value) is TDynByteArray then
Value := Copy(Bytes)
else
if TObject(Value) is System.Enum then // e.g. TIntegerSet
Value := BitConverter.ToUInt32(Bytes, 0)
{ TODO : Add further types }
else
raise EJclError.CreateFmt(RsESetBytesExFmt, [TObject(Value).GetType.FullName]);
end;
procedure SetIntegerSet(var DestSet: TIntegerSet; Value: UInt32);
begin
DestSet := TIntegerSet(Value);
end;
function AnsiByteArrayStringLen(Data: TBytes): Integer;
var
I: Integer;
begin
for I := 0 to High(Data) do
if Data[I] = 0 then
begin
Result := I + 1;
Exit;
end;
Result := Length(Data);
end;
function StringToAnsiByteArray(const S: string): TBytes;
var
I: Integer;
AnsiS: AnsiString;
begin
AnsiS := S; // convert to AnsiString
SetLength(Result, Length(AnsiS));
for I := 0 to High(Result) do
Result[I] := Byte(AnsiS[I + 1]);
end;
function AnsiByteArrayToString(const Data: TBytes; Count: Integer): string;
var
I: Integer;
AnsiS: AnsiString;
begin
if Length(Data) < Count then
Count := Length(Data);
SetLength(AnsiS, Count);
for I := 0 to Length(AnsiS) - 1 do
AnsiS[I + 1] := AnsiChar(Data[I]);
Result := AnsiS; // convert to System.String
end;
// == { TStringAnsiBufferStreamHelper } ======================================
function TStringAnsiBufferStreamHelper.WriteStringAnsiBuffer(const Buffer: string; StrLen: Integer): Integer;
begin
Result := WriteStringAnsiBuffer(Copy(Buffer, StrLen));
end;
function TStringAnsiBufferStreamHelper.WriteStringAnsiBuffer(const Buffer: string): Integer;
var
Bytes: TBytes;
begin
Bytes := StringToAnsiByteArray(Buffer);
Result := Write(Bytes, Length(Bytes));
end;
function TStringAnsiBufferStreamHelper.ReadStringAnsiBuffer(var Buffer: string; AnsiLen: Integer): Integer;
var
Bytes: TBytes;
begin
if AnsiLen > 0 then
begin
SetLength(Bytes, AnsiLen);
Result := Read(Bytes, AnsiLen);
Buffer := AnsiByteArrayToString(Bytes, Result);
end
else
begin
Buffer := '';
Result := 0;
end;
end;
function TStringAnsiBufferStreamHelper.WriteStringAnsiBuffer(const Buffer: AnsiString; StrLen: Integer): Integer;
begin
Result := WriteStringAnsiBuffer(Copy(Buffer, StrLen));
end;
function TStringAnsiBufferStreamHelper.WriteStringAnsiBuffer(const Buffer: AnsiString): Integer;
var
Bytes: TBytes;
begin
Bytes := BytesOf(Buffer);
Result := Write(Bytes, Length(Bytes));
end;
function TStringAnsiBufferStreamHelper.ReadStringAnsiBuffer(var Buffer: AnsiString; AnsiLen: Integer): Integer;
var
Bytes: TBytes;
begin
if AnsiLen > 0 then
begin
SetLength(Bytes, AnsiLen);
Result := Read(Bytes, AnsiLen);
SetLength(Bytes, Result);
Buffer := StringOf(Bytes);
end
else
begin
Buffer := '';
Result := 0;
end;
end;
{$ELSE ~CLR}
function BytesOf(const Value: AnsiString): TBytes;
begin
SetLength(Result, Length(Value));
if Value <> '' then
Move(Pointer(Value)^, Result[0], Length(Value));
end;
{$IFDEF COMPILER6_UP}
function BytesOf(const Value: WideString): TBytes;
begin
if Value <> '' then
Result := JclBase.BytesOf(AnsiString(Value))
else
SetLength(Result, 0);
end;
function BytesOf(const Value: WideChar): TBytes;
begin
Result := JclBase.BytesOf(WideString(Value));
end;
{$ENDIF COMPILER6_UP}
function BytesOf(const Value: AnsiChar): TBytes;
begin
SetLength(Result, 1);
Result[0] := Byte(Value);
end;
function StringOf(const Bytes: array of Byte): AnsiString;
begin
if Length(Bytes) > 0 then
begin
SetLength(Result, Length(Bytes));
Move(Bytes[0], Pointer(Result)^, Length(Bytes));
end
else
Result := '';
end;
function StringOf(const Bytes: Pointer; Size: Cardinal): AnsiString;
begin
if (Bytes <> nil) and (Size > 0) then
begin
SetLength(Result, Size);
Move(Bytes^, Pointer(Result)^, Size);
end
else
Result := '';
end;
{$ENDIF ~CLR}
//== { EJclWin32Error } ======================================================
{$IFDEF MSWINDOWS}
constructor EJclWin32Error.Create(const Msg: string);
begin
{$IFDEF CLR}
inherited Create(''); // this works because the GC cleans the memory
{$ENDIF CLR}
FLastError := GetLastError;
FLastErrorMsg := SysErrorMessage(FLastError);
inherited CreateFmt(Msg + NativeLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]);
end;
constructor EJclWin32Error.CreateFmt(const Msg: string; const Args: array of const);
begin
{$IFDEF CLR}
inherited Create(''); // this works because the GC cleans the memory
{$ENDIF CLR}
FLastError := GetLastError;
FLastErrorMsg := SysErrorMessage(FLastError);
inherited CreateFmt(Msg + NativeLineBreak + Format(RsWin32Prefix, [FLastErrorMsg, FLastError]), Args);
end;
{$IFNDEF CLR}
constructor EJclWin32Error.CreateRes(Ident: Integer);
begin
FLastError := GetLastError;
FLastErrorMsg := SysErrorMessage(FLastError);
inherited CreateFmt(LoadStr(Ident) + NativeLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]);
end;
constructor EJclWin32Error.CreateRes(ResStringRec: PResStringRec);
begin
FLastError := GetLastError;
FLastErrorMsg := SysErrorMessage(FLastError);
{$IFDEF FPC}
inherited CreateFmt(ResStringRec^ + AnsiLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]);
{$ELSE ~FPC}
inherited CreateFmt(LoadResString(ResStringRec) + NativeLineBreak + RsWin32Prefix, [FLastErrorMsg, FLastError]);
{$ENDIF ~FPC}
end;
{$ENDIF ~CLR}
{$ENDIF MSWINDOWS}
// Int64 support
procedure I64ToCardinals(I: Int64; var LowPart, HighPart: Cardinal);
begin
{$IFDEF CLR}
LowPart := Cardinal(I and $00000000FFFFFFFF);
HighPart := Cardinal(I shr 32);
{$ELSE ~CLR}
LowPart := TULargeInteger(I).LowPart;
HighPart := TULargeInteger(I).HighPart;
{$ENDIF ~CLR}
end;
procedure CardinalsToI64(var I: Int64; const LowPart, HighPart: Cardinal);
begin
{$IFDEF CLR}
I := Int64(HighPart) shl 16 or LowPart;
{$ELSE ~CLR}
TULargeInteger(I).LowPart := LowPart;
TULargeInteger(I).HighPart := HighPart;
{$ENDIF ~CLR}
end;
// Cross Platform Compatibility
{$IFNDEF XPLATFORM_RTL}
procedure RaiseLastOSError;
begin
RaiseLastWin32Error;
end;
{$ENDIF ~XPLATFORM_RTL}
{$OVERFLOWCHECKS OFF}
function Addr64ToAddr32(const Value: TJclAddr64): TJclAddr32;
begin
if (Value shr 32) = 0 then
Result := Value
else
{$IFDEF CLR}
raise EJclAddr64Exception.CreateFmt(RsCantConvertAddr64, [HexPrefix, Value]);
{$ELSE ~CLR}
raise EJclAddr64Exception.CreateResFmt(@RsCantConvertAddr64, [HexPrefix, Value]);
{$ENDIF ~CLR}
end;
function Addr32ToAddr64(const Value: TJclAddr32): TJclAddr64;
begin
Result := Value;
end;
{$IFDEF OVERFLOWCHECKS_ON}
{$OVERFLOWCHECKS ON}
{$ENDIF OVERFLOWCHECKS_ON}
{$IFDEF SUPPORTS_GENERICS}
//=== { TEquatable<T> } ======================================================
function TEquatable<T>.TestEquals(Other: T): Boolean;
begin
if Other = nil then
Result := False
else
Result := GetHashCode = Other.GetHashCode;
end;
function TEquatable<T>.TestEquals(A, B: T): Boolean;
begin
if A = nil then
Result := B = nil
else
if B = nil then
Result := False
else
Result := A.GetHashCode = B.GetHashCode;
end;
function TEquatable<T>.GetHashCode2(Obj: T): Integer;
begin
if Obj = nil then
Result := 0
else
Result := Obj.GetHashCode;
end;
{$ENDIF SUPPORTS_GENERICS}
procedure LoadAnsiReplacementCharacter;
{$IFDEF MSWINDOWS}
{$IFDEF CLR}
begin
AnsiReplacementCharacter := '?';
end;
{$ELSE ~CLR}
var
CpInfo: TCpInfo;
begin
if GetCPInfo(CP_ACP, CpInfo) then
AnsiReplacementCharacter := AnsiChar(Chr(CpInfo.DefaultChar[0]))
else
raise EJclInternalError.CreateRes(@RsEReplacementChar);
end;
{$ENDIF ~CLR}
{$ELSE ~MSWINDOWS}
begin
AnsiReplacementCharacter := '?';
end;
{$ENDIF ~MSWINDOWS}
initialization
LoadAnsiReplacementCharacter;
{$IFDEF UNITVERSIONING}
RegisterUnitVersion(HInstance, UnitVersioning);
{$ENDIF UNITVERSIONING}
finalization
{$IFDEF UNITVERSIONING}
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit ULogin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TfrmLogin = class(TForm)
panelPlayerX: TPanel;
panelPlayerO: TPanel;
labelX: TLabel;
labelO: TLabel;
btnPlayerX: TSpeedButton;
btnIIX: TSpeedButton;
panelStart: TPanel;
btnPlayerO: TSpeedButton;
btnIIO: TSpeedButton;
btnStartGame: TButton;
editXName: TEdit;
editOName: TEdit;
procedure FormCreate(Sender: TObject);
procedure btnIIXClick(Sender: TObject);
procedure btnIIOClick(Sender: TObject);
procedure editXNameEnter(Sender: TObject);
procedure editXNameExit(Sender: TObject);
procedure editONameEnter(Sender: TObject);
procedure editONameExit(Sender: TObject);
procedure btnStartGameClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmLogin: TfrmLogin;
implementation
uses Math, UMain;
{$R *.dfm}
const
sENTER_X_NAME = 'Введите имя крестиков';
sENTER_O_NAME = 'Введите имя ноликов';
procedure TfrmLogin.FormCreate(Sender: TObject);
begin
Caption := Application.Title;
editXName.Text := sENTER_X_NAME;
editOName.Text := sENTER_O_NAME;
btnPlayerX.Down := true;
btnIIO.Down := true;
end;
{ Нельзя выбрать двух компьютеров }
procedure TfrmLogin.btnIIXClick(Sender: TObject);
begin
btnPlayerO.Down := true;
end;
procedure TfrmLogin.btnIIOClick(Sender: TObject);
begin
btnPlayerX.Down := true;
end;
{ При нажатии на поле, убирает подсказку }
procedure TfrmLogin.editXNameEnter(Sender: TObject);
begin
if editXName.Text = sENTER_X_NAME then
editXName.Text := '';
end;
{ При выходе из поля, возвращает подсказку }
procedure TfrmLogin.editXNameExit(Sender: TObject);
begin
if editXName.Text = '' then
editXName.Text := sENTER_X_NAME;
end;
{ При нажатии на поле, убирает подсказку }
procedure TfrmLogin.editONameEnter(Sender: TObject);
begin
if editOName.Text = sENTER_O_NAME then
editOName.Text := '';
end;
{ При выходе из поля, возвращает подсказку }
procedure TfrmLogin.editONameExit(Sender: TObject);
begin
if editOName.Text = '' then
editOName.Text := sENTER_O_NAME;
end;
{ Запускает главную форму }
procedure TfrmLogin.btnStartGameClick(Sender: TObject);
begin
if (editOName.Text = sENTER_O_NAME) or (editXName.Text = sENTER_X_NAME) then
begin
ShowMessage('Введите имена игроков');
end
else
begin
if Assigned(frmMain) then
frmMain.Close;
frmMain := TfrmMain.Create(Self);
frmMain.FIsPlayer1II := btnIIX.Down; // Если эта кнопка нажата, то за 1 игрока играет компьютер
frmMain.FIsPlayer2II := btnIIO.Down;
frmMain.FPlayer1Name := editXName.Text;
frmMain.FPlayer2Name := editOName.Text;
Self.Hide;
frmMain.Show;
end;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLODECustomColliders<p>
Custom ODE collider implementations.<p>
<b>Credits : </b><font size=-1><ul>
<li>Heightfield collider code originally adapted from Mattias Fagerlund's
DelphiODE terrain collision demo.
Website: http://www.cambrianlabs.com/Mattias/DelphiODE
</ul>
<b>History : </b><font size=-1><ul>
<li>08/11/09 - DaStr - Improved FPC compatibility
(thanks Predator) (BugtrackerID = 2893580)
<li>12/04/08 - DaStr - Cleaned up uses section
(thanks Sandor Domokos) (BugtrackerID = 1808373)
<li>06/02/08 - Mrqzzz - Upgrade to ODE 0.9 (by Paul Robello)
Fixed reference to odeimport
<li>25/12/07 - DaStr - Fixed memory leak in TGLODECustomCollider.Destroy()
(thanks Sandor Domokos) (BugtrackerID = 1808373)
<li>10/10/07 - Mrqzzz - Fixed reference ODEGL.ODERToGLSceneMatrix
<li>07/10/07 - Mrqzzz - Added reference to ODEGL
<li>11/09/07 - Mrqzzz - Added reference to ODEImport
<li>07/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211)
Added $I GLScene.inc
<li>08/12/04 - SG - Added contact point rendering to TGLODECustomCollider.
<li>07/12/04 - SG - Added new TGLODECustomCollider class,
Geom collide code now uses Resolution to determine the
number of contact points to generate.
<li>19/11/04 - SG - Changed TGLODETerrainCollider to TGLODEHeightField
which now inherits from TGLODEBehaviour and works for
both TGLTerrainRenderer and TGLHeightField objects.
Added Capsule, Cylinder and Cone collider code for
the heightfield collider.
<li>23/04/04 - SG - Removed freeform static collider
<li>29/10/03 - SG - Fix for GLODETerrainCollider (Matheus Degiovani)
<li>30/07/03 - SG - Creation.
</ul>
}
unit GLODECustomColliders;
interface
{$I GLScene.inc}
uses
// VCL
Classes, SysUtils,
// GLscene
GLODEManager, dynode, odegl,dynodegl, ODEImport, GLVectorGeometry,
GLVectorLists, GLScene, GLTerrainRenderer, GLGraph, XCollection,
OpenGL1x, GLTexture, GLColor, GLRenderContextInfo;
type
TContactPoint = class
public
Position,
Normal : TAffineVector;
Depth : Single;
end;
// TGLODECustomCollider
//
{: The custom collider is designed for generic contact handling. There is a
contact point generator for sphere, box, capped cylinder, cylinder and
cone geoms.<p>
Once the contact points for a collision are generated the abstract Collide
function is called to generate the depth and the contact position and
normal. These points are then sorted and the deepest are applied to ODE. }
TGLODECustomCollider = class (TGLODEBehaviour)
private
{ Private Declarations }
FGeom : PdxGeom;
FContactList,
FContactCache : TList;
FTransform : TMatrix;
FContactResolution : Single;
FRenderContacts : Boolean;
FContactRenderPoints : TAffineVectorList;
FPointSize : Single;
FContactColor : TGLColor;
protected
{ Protected Declarations }
procedure Initialize; override;
procedure Finalize; override;
procedure WriteToFiler(writer : TWriter); override;
procedure ReadFromFiler(reader : TReader); override;
//: Test a position for a collision and fill out the contact information.
function Collide(aPos : TAffineVector; var Depth : Single;
var cPos, cNorm : TAffineVector) : Boolean; virtual; abstract;
//: Clears the contact list so it's ready for another collision.
procedure ClearContacts;
//: Add a contact point to the list for ApplyContacts to processes.
procedure AddContact(x,y,z : TdReal); overload;
procedure AddContact(pos : TAffineVector); overload;
//: Sort the current contact list and apply the deepest to ODE.
function ApplyContacts(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer;
{: Set the transform used that transforms contact points generated with
AddContact. }
procedure SetTransform(ATransform : TMatrix);
procedure SetContactResolution(const Value : Single);
procedure SetRenderContacts(const Value : Boolean);
procedure SetPointSize(const Value : Single);
procedure SetContactColor(const Value : TGLColor);
public
{ Public Declarations }
constructor Create(AOwner : TXCollection); override;
destructor Destroy; override;
procedure Render(var rci : TRenderContextInfo); override;
property Geom : PdxGeom read FGeom;
published
{: Defines the resolution of the contact points created for the colliding
Geom. The number of contact points generated change base don the size
of the object and the ContactResolution. Lower values generate higher
resolution contact boundaries, and thus smoother but slower collisions. }
property ContactResolution : Single read FContactResolution write SetContactResolution;
{: Toggle contact point rendering on and off. (Rendered through the assigned
Manager.RenderPoint. }
property RenderContacts : Boolean read FRenderContacts write SetRenderContacts;
//: Contact point rendering size (in pixels).
property PointSize : Single read FPointSize write SetPointSize;
//: Contact point rendering color.
property ContactColor : TGLColor read FContactColor write SetContactColor;
end;
// TGLODEHeightField
//
{: Add this behaviour to a TGLHeightField or TGLTerrainRenderer to enable
height based collisions for spheres, boxes, capped cylinders, cylinders
and cones. }
TGLODEHeightField = class (TGLODECustomCollider)
protected
{ Protected Declarations }
procedure WriteToFiler(writer : TWriter); override;
procedure ReadFromFiler(reader : TReader); override;
function Collide(aPos : TAffineVector; var Depth : Single;
var cPos, cNorm : TAffineVector) : Boolean; override;
public
{ Public Declarations }
constructor Create(AOwner : TXCollection); override;
class function FriendlyName : String; override;
class function FriendlyDescription : String; override;
class function UniqueItem : Boolean; override;
class function CanAddTo(collection : TXCollection) : Boolean; override;
end;
function GetODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField;
function GetOrCreateODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField;
implementation
var
vCustomColliderClass : TdGeomClass;
vCustomColliderClassNum : Integer;
// GetODEHeightField
//
function GetODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField;
begin
result:= TGLODEHeightField(obj.Behaviours.GetByClass(TGLODEHeightField));
end;
// GetOrCreateODEHeightField
//
function GetOrCreateODEHeightField(obj: TGLBaseSceneObject): TGLODEHeightField;
begin
result:= TGLODEHeightField(obj.GetOrCreateBehaviour(TGLODEHeightField));
end;
// GetColliderFromGeom
//
function GetColliderFromGeom(aGeom : PdxGeom) : TGLODECustomCollider;
var
temp : TObject;
begin
Result:=nil;
temp:=dGeomGetData(aGeom);
if Assigned(temp) then
if temp is TGLODECustomCollider then
Result:=TGLODECustomCollider(temp);
end;
// ContactSort
//
function ContactSort(Item1, Item2: Pointer): Integer;
var
c1, c2 : TContactPoint;
begin
c1 := TContactPoint(Item1);
c2 := TContactPoint(Item2);
if c1.Depth>c2.Depth then
result := -1
else if c1.Depth=c2.Depth then
result := 0
else
result := 1;
end;
// CollideSphere
//
function CollideSphere(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer; cdecl;
var
Collider : TGLODECustomCollider;
i, j, res : Integer;
pos : PdVector3;
R : PdMatrix3;
rmat, mat : TMatrix;
rad, dx, dy, dz : TdReal;
begin
Result:=0;
Collider:=GetColliderFromGeom(o1);
if not Assigned(Collider) then exit;
pos:=dGeomGetPosition(o2);
R:=dGeomGetRotation(o2);
ODEGL.ODERToGLSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
rad:=dGeomSphereGetRadius(o2);
res:=Round(10*rad/Collider.ContactResolution);
if res<8 then res:=8;
Collider.AddContact(0, 0, -rad);
Collider.AddContact(0, 0, rad);
rmat:=CreateRotationMatrixZ(2*Pi/res);
for i:=0 to res-1 do begin
mat:=MatrixMultiply(rmat, mat);
Collider.SetTransform(mat);
for j:=-(res div 2)+1 to (res div 2)-1 do begin
dx:=rad*cos(j*Pi/res);
dy:=0;
dz:=rad*sin(j*Pi/res);
Collider.AddContact(dx, dy, dz);
end;
end;
Result:=Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
// CollideBox
//
function CollideBox(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer; cdecl;
var
Collider : TGLODECustomCollider;
i, j, res : Integer;
rcpres, len1, len2 : Single;
s : TdVector3;
pos : PdVector3;
R : PdMatrix3;
mat : TMatrix;
begin
Result:=0;
Collider:=GetColliderFromGeom(o1);
if not Assigned(Collider) then exit;
pos:=dGeomGetPosition(o2);
R:=dGeomGetRotation(o2);
ODEGL.ODERToGLSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomBoxGetLengths(o2, s);
res:=Round(Sqrt(MaxFloat([s[0], s[1], s[2]]))/Collider.ContactResolution);
if res<1 then res:=1;
rcpres:=1/res;
s[0]:=0.5*s[0];
s[1]:=0.5*s[1];
s[2]:=0.5*s[2];
with Collider do begin
// Corners
AddContact( s[0], s[1], s[2]);
AddContact( s[0], s[1],-s[2]);
AddContact( s[0],-s[1], s[2]);
AddContact( s[0],-s[1],-s[2]);
AddContact(-s[0], s[1], s[2]);
AddContact(-s[0], s[1],-s[2]);
AddContact(-s[0],-s[1], s[2]);
AddContact(-s[0],-s[1],-s[2]);
// Edges
for i:=-(res-1) to (res-1) do begin
len1:=i*rcpres*s[0];
AddContact(len1, s[1], s[2]);
AddContact(len1, s[1],-s[2]);
AddContact(len1,-s[1], s[2]);
AddContact(len1,-s[1],-s[2]);
len1:=i*rcpres*s[1];
AddContact( s[0],len1, s[2]);
AddContact( s[0],len1,-s[2]);
AddContact(-s[0],len1, s[2]);
AddContact(-s[0],len1,-s[2]);
len1:=i*rcpres*s[2];
AddContact( s[0], s[1],len1);
AddContact( s[0],-s[1],len1);
AddContact(-s[0], s[1],len1);
AddContact(-s[0],-s[1],len1);
end;
// Faces
for i:=-(res-1) to (res-1) do
for j:=-(res-1) to (res-1) do begin
len1:=i*rcpres*s[0];
len2:=j*rcpres*s[1];
AddContact(len1,len2, s[2]);
AddContact(len1,len2,-s[2]);
len2:=j*rcpres*s[2];
AddContact(len1, s[1],len2);
AddContact(len1,-s[1],len2);
len1:=i*rcpres*s[1];
AddContact( s[0],len1,len2);
AddContact(-s[0],len1,len2);
end;
end;
Result:=Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
// CollideCCylinder
//
function CollideCCylinder(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer; cdecl;
var
Collider : TGLODECustomCollider;
i, j, res : Integer;
pos : PdVector3;
R : PdMatrix3;
mat, rmat : TMatrix;
rad, len, dx, dy, dz : Single;
begin
Result:=0;
Collider:=GetColliderFromGeom(o1);
if not Assigned(Collider) then exit;
pos:=dGeomGetPosition(o2);
R:=dGeomGetRotation(o2);
ODEGL.ODERToGLSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomCCylinderGetParams(o2, rad, len);
res:=Round(5*MaxFloat(4*rad, len)/Collider.ContactResolution);
if res<8 then res:=8;
rmat:=CreateRotationMatrixZ(2*Pi/res);
with Collider do begin
AddContact(0, 0, -rad-0.5*len);
AddContact(0, 0, rad+0.5*len);
for i:=0 to res-1 do begin
mat:=MatrixMultiply(rmat, mat);
SetTransform(mat);
for j:=0 to res do
AddContact(rad, 0, len*(j/res-0.5));
for j:=1 to (res div 2)-1 do begin
dx:=rad*cos(j*Pi/res);
dy:=0;
dz:=rad*sin(j*Pi/res);
Collider.AddContact(dx, dy, -dz-0.5*len);
Collider.AddContact(dx, dy, dz+0.5*len);
end;
end;
end;
Result:=Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
// CollideCylinder
//
function CollideCylinder(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer; cdecl;
var
Collider : TGLODECustomCollider;
i, j, res : Integer;
pos : PdVector3;
R : PdMatrix3;
mat : TMatrix;
rad, len, dx, dy : Single;
begin
Result:=0;
Collider:=GetColliderFromGeom(o1);
if not Assigned(Collider) then exit;
pos:=dGeomGetPosition(o2);
R:=dGeomGetRotation(o2);
ODEGL.ODERToGLSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomCylinderGetParams(o2, rad, len);
res:=Round(5*MaxFloat(4*rad, len)/Collider.ContactResolution);
if res<8 then res:=8;
with Collider do begin
AddContact(0, -0.5*len, 0);
AddContact(0, 0.5*len, 0);
for i:=0 to res-1 do begin
SinCos(2*Pi*i/res, rad, dy, dx);
AddContact(dx, -0.5*len, dy);
AddContact(dx, 0, dy);
AddContact(dx, 0.5*len, dy);
for j:=0 to res do
AddContact(dx, len*(j/res-0.5), dy);
for j:=1 to (res div 2)-1 do begin
SinCos(2*Pi*i/res, rad*j/(res div 2), dy, dx);
AddContact(dx, -0.5*len, dy);
AddContact(dx, 0.5*len, dy);
end;
end;
end;
Result:=Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;
// CollideCone
//
{function CollideCone(o1, o2 : PdxGeom; flags : Integer;
contact : PdContactGeom; skip : Integer) : Integer; cdecl;
var
Collider : TGLODECustomCollider;
i, j, res : Integer;
pos : PdVector3;
R : PdMatrix3;
mat : TMatrix;
rad, len, dx, dy : Single;
begin
Result:=0;
Collider:=GetColliderFromGeom(o1);
if not Assigned(Collider) then exit;
pos:=dGeomGetPosition(o2);
R:=dGeomGetRotation(o2);
ODEGL.ODERToGLSceneMatrix(mat, R^, pos^);
Collider.SetTransform(mat);
dGeomConeGetParams(o2, rad, len);
res:=Round(5*MaxFloat(4*rad, len)/Collider.ContactResolution);
if res<8 then res:=8;
with Collider do begin
AddContact(0, 0, 0);
AddContact(0, 0, len);
for i:=0 to res-1 do begin
SinCos(2*Pi*i/res, rad, dy, dx);
AddContact(dx, dy, 0);
for j:=1 to (res div 2)-1 do begin
SinCos(2*Pi*i/res, rad*j/(res div 2), dy, dx);
AddContact(dx, dy, len*(1-j/(res div 2)));
if (j and 1) = 0 then
AddContact(dx, dy, 0);
end;
end;
end;
Result:=Collider.ApplyContacts(o1, o2, flags, contact, skip);
Collider.SetTransform(IdentityHMGMatrix);
end;}
// GetCustomColliderFn
//
function GetCustomColliderFn(num : Integer):TdColliderFn; cdecl;
begin
if num = dSphereClass then
Result:=CollideSphere
else if num = dBoxClass then
Result:=CollideBox
else if num = dCCylinderClass then
Result:=CollideCCylinder
else if num = dCylinderClass then
Result:=CollideCylinder
{ else if num = dConeClass then
Result:=CollideCone}
else
Result:=nil;
end;
// ---------------
// --------------- TGLODECustomCollider --------------
// ---------------
// Create
//
constructor TGLODECustomCollider.Create(AOwner: TXCollection);
begin
inherited;
FContactList:=TList.Create;
FContactCache:=TList.Create;
FContactResolution:=1;
FRenderContacts:=False;
FContactRenderPoints:=TAffineVectorList.Create;
FContactColor:=TGLColor.CreateInitialized(Self, clrRed, NotifyChange);
FPointSize:=3;
end;
// Destroy
//
destructor TGLODECustomCollider.Destroy;
var
i : integer;
begin
FContactList.Free;
for i:=0 to FContactCache.Count-1 do
TContactPoint(FContactCache[i]).Free;
FContactCache.Free;
FContactRenderPoints.Free;
FContactColor.Free;
inherited;
end;
// Initialize
//
procedure TGLODECustomCollider.Initialize;
begin
if not Assigned(Manager) then exit;
if not Assigned(Manager.Space) then exit;
if vCustomColliderClassNum = 0 then begin
with vCustomColliderClass do begin
bytes:=0;
collider:=GetCustomColliderFn;
aabb:=dInfiniteAABB;
aabb_test:=nil;
dtor:=nil;
end;
vCustomColliderClassNum:=dCreateGeomClass(vCustomColliderClass);
end;
FGeom:=dCreateGeom(vCustomColliderClassNum);
dGeomSetData(FGeom, Self);
dSpaceAdd(Manager.Space, FGeom);
inherited;
end;
// Finalize
//
procedure TGLODECustomCollider.Finalize;
begin
if not Initialized then exit;
if Assigned(FGeom) then begin
dGeomDestroy(FGeom);
FGeom:=nil;
end;
inherited;
end;
// WriteToFiler
//
procedure TGLODECustomCollider.WriteToFiler(writer : TWriter);
begin
inherited;
with writer do begin
WriteInteger(0); // Archive version
WriteFloat(FContactResolution);
WriteBoolean(FRenderContacts);
WriteFloat(FPointSize);
Write(PByte(FContactColor.AsAddress)^, 4);
end;
end;
// ReadFromFiler
//
procedure TGLODECustomCollider.ReadFromFiler(reader : TReader);
var
archiveVersion : Integer;
begin
inherited;
with reader do begin
archiveVersion:=ReadInteger;
Assert(archiveVersion = 0); // Archive version
FContactResolution:=ReadFloat;
FRenderContacts:=ReadBoolean;
FPointSize:=ReadFloat;
Read(PByte(FContactColor.AsAddress)^, 4);
end;
end;
// ClearContacts
//
procedure TGLODECustomCollider.ClearContacts;
begin
FContactList.Clear;
end;
// AddContact (x,y,z)
//
procedure TGLODECustomCollider.AddContact(x,y,z : TdReal);
begin
AddContact(AffineVectorMake(x,y,z));
end;
// AddContact (pos)
//
procedure TGLODECustomCollider.AddContact(pos : TAffineVector);
var
absPos, colPos, colNorm : TAffineVector;
depth : Single;
ContactPoint : TContactPoint;
begin
absPos:=AffineVectorMake(VectorTransform(PointMake(pos), FTransform));
if Collide(absPos, depth, colPos, colNorm) then begin
if FContactList.Count<FContactCache.Count then
ContactPoint:=FContactCache[FContactList.Count]
else begin
ContactPoint:=TContactPoint.Create;
FContactCache.Add(ContactPoint);
end;
ContactPoint.Position:=colPos;
ContactPoint.Normal:=colNorm;
ContactPoint.Depth:=depth;
FContactList.Add(ContactPoint);
end;
if FRenderContacts and Manager.Visible and Manager.VisibleAtRunTime then
FContactRenderPoints.Add(absPos);
end;
// ApplyContacts
//
function TGLODECustomCollider.ApplyContacts(o1, o2 : PdxGeom;
flags : Integer; contact : PdContactGeom; skip : Integer) : Integer;
var
i, maxContacts : integer;
begin
FContactList.Sort(ContactSort);
Result:=0;
maxContacts:=flags and $FFFF;
try
for i := 0 to FContactList.Count-1 do begin
if Result>=maxContacts then Exit;
with TContactPoint(FContactList[i]) do begin
contact.depth:=Depth;
contact.pos[0]:=Position[0];
contact.pos[1]:=Position[1];
contact.pos[2]:=Position[2];
contact.pos[3]:=1;
contact.normal[0]:=-Normal[0];
contact.normal[1]:=-Normal[1];
contact.normal[2]:=-Normal[2];
contact.normal[3]:=0;
end;
contact.g1:=o1;
contact.g2:=o2;
contact:=PdContactGeom(Integer(contact)+skip);
Inc(Result);
end;
finally
ClearContacts;
end;
end;
// SetTransform
//
procedure TGLODECustomCollider.SetTransform(ATransform: TMatrix);
begin
FTransform:=ATransform;
end;
// SetContactResolution
//
procedure TGLODECustomCollider.SetContactResolution(const Value : Single);
begin
FContactResolution:=Value;
if FContactResolution<=0 then
FContactResolution:=0.01;
end;
// Render
//
procedure TGLODECustomCollider.Render(var rci: TRenderContextInfo);
var
i : Integer;
begin
if FRenderContacts and (FContactRenderPoints.Count>0) then begin
glPushAttrib(GL_CURRENT_BIT);
glColor3fv(FContactColor.AsAddress);
glPointSize(FPointSize);
glBegin(GL_POINTS);
for i:=0 to FContactRenderPoints.Count-1 do
glVertex3fv(@FContactRenderPoints.List[i]);
glEnd;
glPopAttrib;
end;
FContactRenderPoints.Clear;
end;
// SetRenderContacts
//
procedure TGLODECustomCollider.SetRenderContacts(const Value: Boolean);
begin
if Value<>FRenderContacts then begin
FRenderContacts:=Value;
NotifyChange(Self);
end;
end;
// SetContactColor
//
procedure TGLODECustomCollider.SetContactColor(const Value: TGLColor);
begin
FContactColor.Assign(Value);
end;
// SetPointSize
//
procedure TGLODECustomCollider.SetPointSize(const Value: Single);
begin
if Value<>FPointSize then begin
FPointSize:=Value;
NotifyChange(Self);
end;
end;
// ---------------
// --------------- TGLODEHeightField --------------
// ---------------
// Create
//
constructor TGLODEHeightField.Create(AOwner: TXCollection);
var
Allow : Boolean;
begin
Allow:=False;
if Assigned(AOwner) then begin
if Assigned(AOwner.Owner) then begin
if ((AOwner.Owner) is TGLTerrainRenderer)
or ((AOwner.Owner) is TGLHeightField) then
Allow:=True;
end;
end;
if not Allow then
raise Exception.Create('This element must be a behaviour of a TGLTerrainRenderer or TGLHeightField');
inherited Create(AOwner);
end;
// WriteToFiler
//
procedure TGLODEHeightField.WriteToFiler(writer : TWriter);
begin
inherited;
with writer do begin
WriteInteger(0); // Archive version
end;
end;
// ReadFromFiler
//
procedure TGLODEHeightField.ReadFromFiler(reader : TReader);
var
archiveVersion : Integer;
begin
inherited;
with reader do begin
archiveVersion:=ReadInteger;
Assert(archiveVersion = 0); // Archive version
end;
end;
// FriendlyName
//
class function TGLODEHeightField.FriendlyName : String;
begin
Result:='ODE HeightField Collider';
end;
// FriendlyDescription
//
class function TGLODEHeightField.FriendlyDescription : String;
begin
Result:='A custom ODE collider powered by it''s parent TGLTerrainRenderer or TGLHeightField';
end;
// UniqueItem
//
class function TGLODEHeightField.UniqueItem : Boolean;
begin
Result:=True;
end;
// CanAddTo
//
class function TGLODEHeightField.CanAddTo(collection: TXCollection) : Boolean;
begin
Result:=False;
if collection is TGLBehaviours then
if Assigned(TGLBehaviours(collection).Owner) then
if (TGLBehaviours(collection).Owner is TGLHeightField)
or (TGLBehaviours(collection).Owner is TGLTerrainRenderer) then
Result:=True;
end;
// Collide
//
function TGLODEHeightField.Collide(aPos : TAffineVector;
var Depth : Single; var cPos, cNorm : TAffineVector) : Boolean;
function AbsoluteToLocal(vec : TVector) : TVector;
var
mat : TMatrix;
begin
if Owner.Owner is TGLHeightField then
Result:=TGLHeightField(Owner.Owner).AbsoluteToLocal(vec)
else if Owner.Owner is TGLTerrainRenderer then begin
mat:=TGLTerrainRenderer(Owner.Owner).AbsoluteMatrix;
NormalizeMatrix(mat);
InvertMatrix(mat);
Result:=VectorTransform(vec, mat);
end else
Assert(False);
end;
function LocalToAbsolute(vec : TVector) : TVector;
var
mat : TMatrix;
begin
if Owner.Owner is TGLHeightField then
Result:=TGLHeightField(Owner.Owner).LocalToAbsolute(vec)
else if Owner.Owner is TGLTerrainRenderer then begin
mat:=TGLTerrainRenderer(Owner.Owner).AbsoluteMatrix;
NormalizeMatrix(mat);
Result:=VectorTransform(vec, mat);
end else
Assert(False);
end;
function GetHeight(pos : TVector; var height : Single) : Boolean;
var
dummy1 : TVector;
dummy2 : TTexPoint;
begin
Result:=False;
if Owner.Owner is TGLTerrainRenderer then begin
height:=TGLTerrainRenderer(Owner.Owner).InterpolatedHeight(LocalToAbsolute(pos));
Result:=True;
end else if Owner.Owner is TGLHeightField then begin
if Assigned(TGLHeightField(Owner.Owner).OnGetHeight) then begin
TGLHeightField(Owner.Owner).OnGetHeight(pos[0], pos[1], height, dummy1, dummy2);
Result:=True;
end;
end;
end;
const
cDelta = 0.1;
var
localPos : TVector;
height : Single;
temp1, temp2 : TAffineVector;
begin
localPos:=AbsoluteToLocal(PointMake(aPos));
if GetHeight(localPos, height) then begin
Depth:=height-localPos[2];
Result:=(Depth>0);
if Result then begin
localPos[2]:=height;
cPos:=AffineVectorMake(LocalToAbsolute(localPos));
temp1[0]:=localPos[0]+cDelta;
temp1[1]:=localPos[1];
temp1[2]:=localPos[2];
GetHeight(PointMake(temp1), temp1[2]);
temp2[0]:=localPos[0];
temp2[1]:=localPos[1]+cDelta;
temp2[2]:=localPos[2];
GetHeight(PointMake(temp2), temp2[2]);
cNorm:=CalcPlaneNormal(AffineVectorMake(localPos), temp1, temp2);
cNorm:=AffineVectorMake(LocalToAbsolute(VectorMake(cNorm)));
end;
end else
Result:=False;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterXCollectionItemClass(TGLODEHeightField);
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
finalization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
UnregisterXCollectionItemClass(TGLODEHeightField);
end.
|
unit CRC;
interface
uses SysUtils,StrUtils;
type vetBytes = array[1..4] of byte;
vetDoisBytes = array[1..2] of byte;
vetDados = array[0..511] of byte;
TCRC=class
private
function byteParaBinario(num: Byte):String;
function dividePolinomio(dividendo:String;divisor:String):String;
function wordParaBinario(num: word):String;//devolve um binário de 8 bits
function pot(base : Byte; exp: Byte):word;
function binarioParaCRC(numbin : String): Word;
function crcParaBinario(crc: Word):String;
public
function calculaCRC(versao: Byte; hLen: Word; totalLen : Word; identificacao:Word; Source: vetBytes; Destination: vetBytes; infoAdicionais : Byte ; vetDados: array of Byte):Word;//retorna BCC
function crcCorreto(versao: Byte; hLen: Word; totalLen : Word; identificacao:Word; Source: vetBytes; Destination: vetBytes; infoAdicionais : Byte ; vetDados: array of Byte; crc : Word):Boolean;
end;
implementation
function TCRC.byteParaBinario(num: Byte):String;//devolve um binário de 8 bits
var numBin:String;
resto,quociente,i:Byte;
begin
numBin:='';
while(num>=2) do
begin
resto:=num mod 2;
quociente:= num div 2;
numBin:=numBin+IntToStr(resto);
num:=quociente;
end;
numBin:=numBin+IntToStr(num);
for i:=0 to (8-length(numBin)) do
numBin:=numBin+'0';
byteParaBinario:=reverseString(numBin) ;
end;
function TCRC.crcParaBinario(crc: Word):String;
var numBin:String;
resto,quociente:Word;
begin
numBin:='';
while(crc>=2) do
begin
resto:=crc mod 2;
quociente:= crc div 2;
numBin:=numBin+IntToStr(resto);
crc:=quociente;
end;
numBin:=numBin+IntToStr(crc);
crcParaBinario:=reverseString(numBin) ;
end;
function TCRC.wordParaBinario(num: word):String;//devolve um binário de 16 bits
var numBin:String;
resto,quociente,i:word;
begin
numBin:='';
while(num>=2) do
begin
resto:=num mod 2;
quociente:= num div 2;
numBin:=numBin+IntToStr(resto);
num:=quociente;
end;
numBin:=numBin+IntToStr(num);
for i:=0 to (16-length(numBin)) do
numBin:=numBin+'0';
wordParaBinario:=reverseString(numBin) ;
end;
//esta funcao devolve-me apenas o resto da divisão de D´(x) po G(x)!!!
function TCRC.calculaCRC(versao: Byte; hLen: Word; totalLen : Word; identificacao : Word; Source: vetBytes; Destination: vetBytes;infoAdicionais:Byte;vetDados: array of Byte):word;//retorna BCC
var Dx,Gx,resto: String;
i: integer;
begin
Dx:='';
Gx:='11000000000000101';
//agrupar os bytes em uma longa cadeia de binarios
Dx:=Dx+byteParaBinario(versao);
Dx:=Dx+wordParaBinario(hlen);
Dx:=Dx+wordParaBinario(totalLen);
Dx:=Dx+wordParaBinario(identificacao);
for i:=1 to 4 do
Dx:=Dx+byteParaBinario(Source[i]);
for i:=1 to 4 do
Dx:=Dx+byteParaBinario(Destination[i]);
Dx:=Dx+byteParaBinario(infoAdicionais);
for i:=0 to Length(vetDados)-1 do
Dx:=Dx+byteParaBinario(vetDados[i]);
//ao adicionar 16 caracteres 0 ao final da cadeia de dados, automaticamente estou multiplicando o polinômio por xE16.
Dx:=Dx+'0000000000000000';//suponhamos que aqui seja D´(x)..e é!
//pego o resto
resto:=dividePolinomio(Dx,Gx);
//tranformo meu resto em um inteiro
calculaCRC:= binarioParaCrc(resto); //valor do bcc
end;
function TCRC.crcCorreto(versao: Byte; hLen: Word; totalLen : Word; identificacao : Word; Source: vetBytes; Destination: vetBytes;infoAdicionais:Byte; vetDados: array of Byte; CRC:word):boolean;
var Dx,resto,teste:String;
resultado:boolean;
i:integer;
begin
Dx:='';
//recalculo outra vez o D(x)
Dx:=Dx+byteParaBinario(versao);
Dx:=Dx+wordParaBinario(hlen);
Dx:=Dx+wordParaBinario(totalLen);
Dx:=Dx+wordParaBinario(identificacao);
for i:=1 to 4 do
Dx:=Dx+byteParaBinario(Source[i]);
for i:=1 to 4 do
Dx:=Dx+byteParaBinario(Destination[i]);
Dx:=Dx+byteParaBinario(infoAdicionais);
for i:=0 to Length(vetDados)-1 do
Dx:=Dx+byteParaBinario(vetDados[i]);
//agora uno o meu Dx com o crc
teste:=crcParaBinario(crc);
Dx:=Dx+crcParaBinario(crc);
resto:=dividePolinomio(Dx,'11000000000000101');
resultado:=true;
for i:=1 to Length(resto) do
if(resto[i]='1')then
resultado:=false;
crcCorreto:=resultado;
end;
function TCRC.dividePolinomio(dividendo:String;divisor:String):String;
var i,maiorGrauDivisor,maiorGrauDividendo,tempGrau:integer;
tempString,resto:String;
begin
dividendo:=reverseString(dividendo);
divisor:=reverseString(divisor);
tempString:='';
resto:='';
maiorGrauDividendo:=length(Dividendo)-1;
maiorGrauDivisor:=length(Divisor)-1;
for i:=1 to length(dividendo) do
tempString:=tempString + '0';
//for i:=1 to length(divisor) do
//resto:=resto + '0';
while(maiorGrauDividendo>=maiorGrauDivisor) do
begin
tempGrau:=maiorGrauDividendo-maiorGrauDivisor;
for i:=1 to length(divisor) do
if(divisor[i]='1') then
tempString[tempGrau+i]:='1';
for i:=1 to length(dividendo) do
begin
if((tempString[i]='1') and (dividendo[i]='1')) then
begin
tempString[i]:='0';
dividendo[i]:='0';
end;
if((tempString[i]='1') and (dividendo[i]='0')) then
begin
tempString[i]:='0';
dividendo[i]:='1';
end;
end;
maiorGrauDividendo:=0;
for i:=1 to length(dividendo) do
if(dividendo[i]='1') then
if(i-1>maiorGrauDividendo) then
maiorGrauDividendo:=i-1;
end;//while
for i:=maiorGrauDivisor downto 1 do
resto:=resto+dividendo[i];
dividePolinomio:=resto;
end;
function TCRC.binarioParaCRC(numBin : String): Word;
var i,numCRC:Word;
begin
numBin:=reverseString(numBin);
numCRC:=0;
for i:=1 to length(numBin) do
if(numBin[i]='1')then
numCRC:=numCRC+pot(2,i-1);
binarioParaCRC:=numCRC;
end;
function TCRC.pot(base : Byte; exp: Byte):Word;
var i,resposta: word;
begin
resposta:=1;
if(exp<>0)then
for i:=1 to exp do
resposta:=resposta*base;
pot:=resposta;
end;
end.
|
unit timez;
interface
type
times = record
bSecond: byte;
bMinute: byte;
bHour: byte;
bDay: byte;
bMonth: byte;
bYear: byte;
end;
function ToTimes(daT: TDateTime): times;
function DeltaTimes2Str(tiT: times; tiS: times): string;
function PopTimes: times;
function Times2Str(tiT: times): string;
function Times2StrHour(tiT: times): string;
function Times2StrDay(tiT: times): string;
function Times2StrMon(tiT: times): string;
function PopTimes2Str: string;
function Str2Times(s: string): times;
procedure AddInfoTime(ti: times);
implementation
uses SysUtils, output, support;
function ToTimes(daT: TDateTime): times;
var
Year,Month,Day,Hour,Min,Sec,MSec: word;
begin
try
with Result do begin
bSecond := 0;
bMinute := 0;
bHour := 0;
bDay := 0;
bMonth := 0;
bYear := 0;
end;
DecodeTime(daT, Hour,Min,Sec,MSec);
DecodeDate(daT, Year,Month,Day);
with Result do begin
bSecond := Sec;
bMinute := Min;
bHour := Hour;
bDay := Day;
bMonth := Month;
bYear := Year-2000;
end;
except
end;
end;
function DaysInWords(dwDays: longword): string;
begin
if (dwDays mod 100 = 0) then
Result := 'дней'
else case (dwDays mod 20) of
1: Result := 'день';
2..4: Result := 'дня';
else Result := 'дней';
end;
Result := IntToStr(dwDays) + ' ' + Result + ' ';
end;
function DeltaTimes2Str(tiT: times; tiS: times): string;
var
daA,daB: TDateTime;
Hour,Min,Sec,MSec: word;
begin
Result := 'ошибка';
try
Result := '';
daA := EncodeDate(2000+tiT.bYear,tiT.bMonth,tiT.bDay) +
EncodeTime(tiT.bHour,tiT.bMinute,tiT.bSecond,0);
daB := EncodeDate(2000+tiS.bYear,tiS.bMonth,tiS.bDay) +
EncodeTime(tiS.bHour,tiS.bMinute,tiS.bSecond,0);
if daA > daB then begin
daA := daA - daB;
Result := Result + ' + ';
end
else begin
daA := daB - daA;
Result := Result + ' - ';
end;
DecodeTime(daA, Hour,Min,Sec,MSec);
if (daA > 1) then Result := Result + DaysInWords(Trunc(daA));
if (Hour > 0) then Result := Result + IntToStr(Hour) + ' часов ';
if (Min > 0) then Result := Result + IntToStr(Min) + ' минут ';
Result := Result + IntToStr(Sec) + ' секунд(а) ';
except
end;
end;
function PopTimes: times;
begin
with Result do begin
bSecond := PopByte;
bMinute := PopByte;
bHour := PopByte;
bDay := PopByte;
bMonth := PopByte;
bYear := PopByte;
end;
end;
function Times2Str(tiT: times): string;
begin
with tiT do
Result := Int2Str(bHour) +
':' + Int2Str(bMinute) +
':' + Int2Str(bSecond) +
' ' + Int2Str(bDay) +
'.' + Int2Str(bMonth) +
'.' + Int2Str(bYear);
end;
function Times2StrHour(tiT: times): string;
begin
with tiT do
Result := Int2Str(bHour) +
':' + Int2Str(bMinute) +
':' + Int2Str(bSecond);
end;
function Times2StrDay(tiT: times): string;
begin
with tiT do
Result := Int2Str(bDay) +
'.' + Int2Str(bMonth) +
'.' + Int2Str(bYear);
end;
function Times2StrMon(tiT: times): string;
begin
with tiT do
Result := Int2Str(bMonth) +
'.' + Int2Str(bYear);
end;
function PopTimes2Str: string;
begin
Result := Times2Str(PopTimes);
end;
function Str2Times(s: string): times;
begin
try
with Result do begin
bSecond := StrToInt(Copy(s, 7, 2));
bMinute := StrToInt(Copy(s, 4, 2));
bHour := StrToInt(Copy(s, 1, 2));
bDay := StrToInt(Copy(s, 10, 2));
bMonth := StrToInt(Copy(s, 13, 2));
bYear := StrToInt(Copy(s, 16, 2));
end;
except
ErrBox('Время/дата заданы неправильно !');
Abort;
end;
end;
procedure AddInfoTime(ti: times);
const
COLUMN_WIDTH = 28;
begin
AddInfo(PackStrR('Время сумматора', COLUMN_WIDTH) + Times2Str(ti));
AddInfo(PackStrR('Время компьютера', COLUMN_WIDTH) + Times2Str(ToTimes(Now)));
AddInfo(PackStrR('Разница', COLUMN_WIDTH) + DeltaTimes2Str(ti, ToTimes(Now)));
end;
end.
|
unit uFrmBaseEtypeInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmBaseInput, Menus, cxLookAndFeelPainters, ActnList, cxLabel,
cxControls, cxContainer, cxEdit, cxCheckBox, StdCtrls, cxButtons,
ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics,
cxDropDownEdit, uParamObject, ComCtrls, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, uDBComConfig, cxCalendar, uBaseInfoDef, uModelFunIntf;
type
TfrmBaseEtypeInput = class(TfrmBaseInput)
edtFullname: TcxButtonEdit;
lbl1: TLabel;
lbl2: TLabel;
edtUsercode: TcxButtonEdit;
edtPYM: TcxButtonEdit;
lbl3: TLabel;
chkStop: TcxCheckBox;
edtDType: TcxButtonEdit;
lbl4: TLabel;
lbl5: TLabel;
lbl6: TLabel;
edtTel: TcxButtonEdit;
edtAddress: TcxButtonEdit;
lbl7: TLabel;
lbl8: TLabel;
lbl9: TLabel;
edtJob: TcxButtonEdit;
edtTopTotal: TcxButtonEdit;
edtEMail: TcxButtonEdit;
lbl10: TLabel;
edtLowLimitDiscount: TcxButtonEdit;
lbl11: TLabel;
deBirthday: TcxDateEdit;
protected
{ Private declarations }
procedure SetFrmData(ASender: TObject; AList: TParamObject); override;
procedure GetFrmData(ASender: TObject; AList: TParamObject); override;
procedure ClearFrmData; override;
procedure DoSelectBasic(Sender: TObject; ABasicType: TBasicType;
ASelectBasicParam: TSelectBasicParam;
ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas;
var AReturnCount: Integer); override;
public
{ Public declarations }
procedure BeforeFormShow; override;
class function GetMdlDisName: string; override; //得到模块显示名称
end;
var
frmBaseEtypeInput: TfrmBaseEtypeInput;
implementation
{$R *.dfm}
uses uSysSvc, uBaseFormPlugin, uModelBaseTypeIntf, uModelControlIntf, uOtherIntf, uDefCom;
{ TfrmBasePtypeInput }
procedure TfrmBaseEtypeInput.BeforeFormShow;
begin
SetTitle('职员信息');
FModelBaseType := IModelBaseTypePtype((SysService as IModelControl).GetModelIntf(IModelBaseTypeEtype));
FModelBaseType.SetParamList(ParamList);
FModelBaseType.SetBasicType(btEtype);
DBComItem.AddItem(edtFullname, 'Fullname', 'EFullname');
DBComItem.AddItem(edtUsercode, 'Usercode', 'EUsercode');
DBComItem.AddItem(edtPYM, 'Namepy', 'Enamepy');
DBComItem.AddItem(chkStop, 'IsStop', 'IsStop');
DBComItem.AddItem(edtDType, 'DTypeId', 'DTypeId', 'DFullname', btDtype);
DBComItem.AddItem(edtTel, 'Tel', 'Tel');
DBComItem.AddItem(deBirthday, 'Birthday', 'Birthday');
DBComItem.AddItem(edtEMail, 'EMail', 'EMail');
DBComItem.AddItem(edtJob, 'Job', 'Job');
DBComItem.AddItem(edtTopTotal, 'TopTotal', 'TopTotal', cfFloat);
DBComItem.AddItem(edtLowLimitDiscount, 'LowLimitDiscount', 'LowLimitDiscount', cfFloat);
DBComItem.AddItem(edtAddress, 'Address', 'Address');
inherited;
end;
procedure TfrmBaseEtypeInput.ClearFrmData;
begin
inherited;
edtTopTotal.Text := '0';
edtLowLimitDiscount.Text := '0';
end;
procedure TfrmBaseEtypeInput.DoSelectBasic(Sender: TObject;
ABasicType: TBasicType; ASelectBasicParam: TSelectBasicParam;
ASelectOptions: TSelectBasicOptions; var ABasicDatas: TSelectBasicDatas;
var AReturnCount: Integer);
begin
if Sender = edtDType then
begin
// ASelectOptions := ASelectOptions + [opMultiSelect]
end;
inherited;
// if Sender = edtDType then
// begin
// if AReturnCount >= 1 then
// begin
// DBComItem.SetBasicItemValue(edtDType, ABasicDatas[0]);
// end;
// end;
end;
procedure TfrmBaseEtypeInput.GetFrmData(ASender: TObject;
AList: TParamObject);
begin
inherited;
AList.Add('@Parid', ParamList.AsString('ParId'));
DBComItem.SetDataToParam(AList);
AList.Add('@Comment', '');
if FModelBaseType.DataChangeType in [dctModif] then
begin
AList.Add('@typeId', ParamList.AsString('CurTypeid'));
end;
end;
class function TfrmBaseEtypeInput.GetMdlDisName: string;
begin
Result := '职员信息';
end;
procedure TfrmBaseEtypeInput.SetFrmData(ASender: TObject;
AList: TParamObject);
begin
inherited;
DBComItem.GetDataFormParam(AList);
end;
end.
|
unit ULang;
(*====================================================================
All language dependent strings, except for the strings in the forms
======================================================================*)
interface
const
{$ifdef CZECH}
{QB_CONV4}
lsInconsistencyOfDataInDBase = 'Nekonzistence dat v databázi';
{QDBASE}
lsDBaseCannotBeOpened = 'Databázi nelze otevřít';
lsError = 'Chyba';
lsName = 'Jméno';
lsDateAndTime = 'Datum a čas';
lsSize = 'Velikost';
lsFolder = '(složka)';
lsDisk3 = '(disk)';
lsDescription = 'Popiska';
lsFolder1 = '(složka) ';
lsSeriousProblemWritingToDBase =
'Vyskytl se závažný problém při zápisu do databáze.'#13#10'Doporučuji vám program ihned ukončit.';
lsErrorInDBaseFound = 'Byla nalezena chyba ve struktuře databáze. '#13#10'Doporučuji vám databázi uzavřít a opravit.';
lsDrive = 'Jednotka ';
lsIsNotAccesible = ' není dostupná.';
lsLabelDifferent_Change = 'Zadané jméno je odlišné od skutečného jména disku. Zmìnit též pojmenování disku?';
lsDifferentNames = 'Rozdílná jména';
lsOnDisk = 'Na disku ';
lsLimitedLength = ' může mít pojmenování délku pouze 12 znakù.';
lsTotalFolders = ' ';
lsTotalFiles = ' složek, ';
lsTotalSize = ' souborù, ';
lsVolumeLabel = 'Pojmenování disku ';
lsCannotBeChanged = ' nelze změnit.';
lsOverwriteExistingRecord = 'Přepsat existující disk ';
lsWarning = 'Varování';
lsRecordCannotBeDeleted = 'Nelze smazat disk ';
lsProblem = 'Problém';
lsImportConversion =
'Při importu je prováděna konverze kódování znaků. Chcete provést '+
'konverzi z kódu Kamenických? (Odpověď "Ne" znamená konverzi z kódování Latin2.)';
lsImportFrom4 = 'Import databáze z formátu QuickDir verze 4.1';
lsRecordsSelected = 'Vybráno diskù: ';
lsDeleteAll = '. Smazat všechny?';
lsConfirmation = 'Potvrzení';
lsDeleteRecord = 'Smazat disk "';
lsNewNameForUndeletedDisk = 'Nové jméno pro obnovený disk';
lsDiskWithName = 'Disk se jménem "';
lsAlreadyExists = '" již existuje.';
lsDiskNameChange = 'Změna jména disku';
lsNameMustBeUnique = 'Jméno musí být unikátní';
lsNoSelectedDisk = 'Je požadováno hledání ve vybraných discích, ale žádný není vybrán.';
lsAllDisksSelected = 'Je požadováno hledání v nevybraných discích, ale všechny jsou vybrány.';
lsTooManyFilesSelected = 'Je vybráno příliž mnoho souborù. Budou vyhledány jen některé.';
lsNotification = 'Upozornění';
lsDescriptionCannotBeByParentDir = 'Odkaz na nadøazenou složku nemůže mít popisku.';
lsListOfFreeSpace = ': Výpis volného místa';
lsDescriptionCannotBeSaved = 'Popisku nelze uložit.';
lsSelectionOfDisks = 'Výběr diskù';
lsEnterMaskForSelectionOfDisks = 'Zadejte masku pro výběr disků:';
lsSelectionOfFiles = 'Výběr souborů';
lsEnterMaskForSelectionOfFiles = 'Zadejte masku pro výběr souborů:';
lsSelectionTooLargeForClipboard = 'Výběr je příliž velký, nelze okopírovat do schránky.';
lsCannotCopy = 'Nelze kopírovat';
lsDisk1 = 'Disk: ';
lsFolder2 = 'Složka: ';
lsPage = 'Strana ';
lsQDir = 'DiskBase ';
lsPreparingToPrint = 'Připravuje se tisk...';
lsQuickDir = 'DiskBase';
lsPrintingPage = 'Tiskne se strana ';
lsSkippingPage = 'Přeskakuje se strana ';
lsDatabase = 'Databáze: ';
lsVolumesDifferent1 =
'Jméno disku v databázi (%s) a jméno disku, jehož obsah bude čten (%s), se liší. ';
lsVolumesDifferent2 =
'To může znamenat, že se chystáte sejmout obsah jiného disku, než je ten, jehož ';
lsVolumesDifferent3 =
'obraz má být v databázi aktualizován. Mám přesto pokračovat?';
lsFileCannotBeOpen = #13#10#13#10'Soubor není možné otevřít. Možné příčiny:'#13#10;
lsFolderCannotBeOpen = #13#10#13#10'Složku není možné otevřít. Možné příčiny:'#13#10;
lsDiskNotAccessible = ' - disk není dostupný'#13#10;
lsDifferentDisk = ' - v mechanice je jiný disk'#13#10;
lsFileInArchive = ' - soubor se nachází v archivu (ZIP, ARJ, atd.)'#13#10;
lsFolderInArchive = ' - složka se nachází v archivu (ZIP, ARJ, atd.)'#13#10;
lsDiskIsNetworkDrive = ' - disk je síťový a není právě dostupný'#13#10;
lsVolumeLabelDiffers = ' - liší se jména disků: jde pravděpodobně o jiný disk'#13#10;
lsFileProbablyDeleted = ' - soubor byl smazán, přejmenován nebo přemístěn'#13#10;
lsFolderProbablyDeleted = ' - složka byla smazána, přejmenována nebo přemístěna'#13#10;
lsFileNotFound = 'Soubor nenalezen';
lsFolderNotFound = 'Složka nenalezena';
{QDBINFO}
lsYes = 'ano';
lsNo = 'ne';
{QDESC}
lsDescrTextModified = 'Text popisky byl modifikován. Uložit?';
{QDPRINTS}
lsPrintSelection = 'Výběr tisku';
lsPrintWhat = 'Tisknout:';
lsExportSelection = 'Výběr položek k exportu';
lsExportWhat = 'Exportovat:';
{QDEXPORT}
lsDefaultFilter = 'Všechny soubory (*.*)|*.*';
lsNotValidFormatFile = 'Tento soubor neobsahuje platný formát pro export z DiskBase.';
lsPreparingToExport = 'Příprava na export...';
lsProcessed = 'Zpracováno ';
lsFiles_Written = ' souborů, zapsáno ';
lsExportFolder = 'Export';
{QDPRINT}
lsCalculatingPrintExtent = 'Zjišťuje se rozsah tisku...';
lsDisk = 'Disk: ';
lsDateTime = 'Datum a čas';
lsExpectedNoOfPages = 'Předpokládaný počet stran je ';
lsReallyPrintThem = '. Chcete skutečně všechny vytisknout?';
lsPreparingPrint = 'Připravuje se tisk...';
{QE_Archi}
lsExploringContent = 'Zjišťuji obsah ';
lsCentralDirCPBNotFound = ' Centrální adresář CP-Backup nenalezen ';
{QE_Main}
lsError1000 = '(chyba 1000)';
lsError1001 = '(chyba 1001)';
lsError1002 = '(chyba 1002)';
lsError1003 = '(chyba 1003)';
lsError1004 = '(chyba 1004)';
lsError1005 = '(chyba 1005)';
lsInconsitencyOfDataInDBase = 'Nekonzistence dat v databázi ';
lsNotEnoughSpaceOnDisk = 'Není dostatek místa na disku s databází.';
lsLoadingLibrary = 'Zavádím knihovnu ';
lsExtracting = 'Dekomprimuji ';
lsFrom = ' z ';
lsLibrary = 'Knihovna ';
lsDoesNotContainProperFunctions = ' neobsahuje všechny potřebné funkce.';
lsLibrary1 = 'Knihovnu ';
lsCannotBeOpened = ' nelze otevřít.';
lsReleasingLibrary = 'Uvolňuji knihovnu ';
lsNotAQDirDBase = 'Tento soubor není databáze DiskBase.';
lsRequiresNewerVersion = 'Tato databáze vyžaduje novější verzi programu.';
lsCorruptedHeader = 'Databáze má poškozené záhlaví.';
lsTrialPeriodExpired =
'Lhůta pro použití databáze neregistrovanou verzí vypršela. Prosím registrujte se.';
lsTrialOpenCountExpired =
'Počet použití databáze neregistrovanou verzí je vyčerpán. Prosím registrujte se.';
lsErrorReading = 'Chyba při čtení: ';
lsErrorWriting = 'Chyba při zápisu: ';
lsDBaseIsFull = 'Databáze je plná. Proveďte komprimaci.';
lsDiskInfo = 'DiskInfo.txt';
lsDiskInfoName = 'DiskInfo';
lsDiskInfoExt = '.txt';
lsDiskInfoUpperCase = 'DISKINFO.TXT';
lsDirInfo = 'DirInfo';
lsDefaultMasks = '*.txt|500||*.doc|1000|Uni|*.wri|500|Uni|*.htm|500|HTML|*.html|500|HTML|*.602|500|T602|*.rtf|500|RTF|*.mp3|1000|MP3Tag|';
{QExcept}
lsCriticalError = 'Kritická chyba';
lsCriticalError1 = 'Kritická chyba.';
lsDBaseStructError = 'Nalezena chyba ve struktuře databáze. Zavřete databázi a vyvolejte Opravu (v menu Soubor). ';
{QFindE}
lsNoDiskFound = 'Nebyl nalezen žádný disk.';
lsInformation = 'Informace';
{QFindF}
lsNoFileFound = 'Nebyl nalezen žádný soubor.';
{QFindFD}
lsNoMaskEntered = 'Nebyl zadán žádný text k vyhledání.';
lsCannotSearch = 'Nelze vyhledávat';
{QFoundE, QFoundF}
lsSorting = 'Řazení';
lsDisk2 = 'Disk';
lsFreeSpace = 'Volno';
lsFreeSpacePerCent = 'Volno %';
lsFreeSpacePerCent1 = ' Volno % ';
lsSelectionTooLarge = 'Výběr je příliš velký, nelze okopírovat do schránky.';
lsFolder3 = 'Složka';
lsFile = 'Soubor';
{QI_Face}
lsErrorDBaseIsNil = 'Interní chyba 500: DBaseIsNil';
lsErrorTreeStructIsNil = 'Interní chyba 501: TreeStructIsNil';
lsErrorCurDirColIsNil = 'Interní chyba 502: CurDirColIsNil';
lsErrorFileSearchColIsNil = 'Interní chyba 503: FileSearchColIsNil';
lsErrorKeyFieldIsNil = 'Interní chyba 503: KeyFieldIsIsNil';
lsErrorCurFileColIsNil = 'Interní chyba 504: CurFileColIsNil';
lsErrorRootDirColIsNil = 'Interní chyba 505: RootDirColIsNil';
lsErrorDirColHandleIsNil = 'Interní chyba 506: DirColHandleIsNil';
lsErrorFileColHandleIsNil = 'Interní chyba 507: FileColHandleIsNil';
{QLocOpt}
lsMask = 'Maska';
lskB = 'Bajtů';
lsDLL = 'Filtr';
{QMain}
lsFatalInternalError = ' (Fatální interní chyba ';
lsDbaseWithThisNameIsOpen = 'Databáze s tímto jménem je otevřena - soubor nelze přepsat.';
lsCannotCreate = 'Nelze založit';
lsDBaseCannotBeCreated = 'Databázi nelze vytvořit';
lsFileDoesNotExist = 'Soubor neexistuje: ';
lsErrorOnCommandLine = 'Chyba na příkazovém řádku';
lsErrorInProgramSettings = 'Chyba v nastavení programu';
lsInvalidParameter = 'Neplatný parametr: ';
lsOptionsCannotBeMixed = 'Volby /f a /s nelze na příkazovém řádku uvést zároveň.';
lsInvalidOption = 'Neplatná volba: ';
lsDBaseIsOpenCannotCompress =
'Databáze s tímto jménem je otevřena - pro kompresi je nutno ji uzavřít.';
lsCannotCompress = 'Nelze komprimovat';
lsCannotCompressAsItIsProtected =
'Databázi s tímto jménem nelze komprimovat, neboť se jedná o chráněnou verzi.';
lsDbaseIsOpenCannotOverwrite = 'Databáze s tímto jménem je otevřena - nelze ji přepsat.';
lsCannotExport = 'Nelze exportovat';
lsDBaseIsOpenMustBeClosedFirst =
'Databáze s tímto jménem je otevřena. Aby bylo možné ji importovat, je nutno jí zavřít.';
lsCannotImport = 'Nelze importovat';
lsCannotImportAsItIsProtected =
'Databázi s tímto jménem nelze importovat, neboť se jedná o chráněnou verzi.';
lsCannotImportProbablyCorrupted =
'Tuto databázi nelze importovat. Buď je poškozena, nebo vyžaduje novější verzi programu.';
lsAttentionMakeReindexFirst =
'Upozornění: Před importem je potřeba provést reindexaci databáze, kterou chcete importovat.';
lsCannotContinue = 'Nelze pokračovat';
lsDBaseIsOpenCannotRepair =
'Databáze s tímto jménem je otevřena - pro opravu je nutno ji uzavřít.';
lsCannotRepairCorruptedHeader =
'Tento soubor buď není databází DiskBase nebo má neopravitelně poškozenou hlavičku.';
lsCannotRepairByOldVersion =
'Tato databáze byla vytvořena novější verzí programu DiskBase; touto verzí programu ji nelze opravovat.';
lsCannotRepairRuntimeDatabase =
'Tuto databázi nelze opravovat, neboť se jedná o chráněnou verzi.';
lsDatabaseRepair = 'Oprava databáze';
lsRepairingIndex = 'Probíhá reindexace tabulky...';
lsScannningDatabase = 'Zjišťuji obsah databáze, prosím vyčkejte...';
lsEject = 'Vysunout disk z ';
{QReindex}
lsCompressingDatabase = 'Probíhá komprese databáze';
lsExportingToRunTime = 'Probíhá export jen pro čtení';
lsExporting = 'Probíhá export';
lsImporting = 'Probíhá import';
lsCompressNotSuccessful = 'Komprese neúspěšná';
lsExportNotSuccessful = 'Export neúspěšný';
lsImportNotSuccessful = 'Import neúspěšný';
lsSourceDBase = 'Zdrojovou databázi ';
lsTargetDBase = 'Cílovou databázi ';
lsCannotBeCreated = ' nelze založit.';
lsProcessNotSuccessful = 'Proces nebyl úspěšný';
lsDBase = 'Databázi ';
lsCannotBeRenamedTo = ' nelze přejmenovat na ';
lsOriginalDBase = 'Původní databázi ';
lsCannotBeDeleted = ' nelze smazat.';
{QScanDrv}
lsIsItLastCPBDisk = 'Jedná se o disk s posledním CPB archivem?';
lsCPBFound = 'Nalezen soubor typu CPB';
lsScanArchive = 'Zjistit obsah archivu ';
lsScanningTree = 'Zjišťuje se stromová struktura:';
lsScanningFoldersAndFiles = 'Zjišťuje se obsah složek a archivů:';
{QSetting}
lsBold = ', tučné';
lsItalics = ', kurzíva';
lsArial = 'Arial CE';
lsMSSansSerif = 'MS Sans Serif';
lsScript = 'CentralEurope';
lsCompressionNecessary =
'POZOR: Pokud změníte toto nastavení, je potřeba provést kompresi všech databází. Viz Nápověda.';
{QStream}
lsFileAccessError = 'Chyba pøi přístupu k souboru.';
lsFileCreationError = 'Chyba při vytvoření nebo otevření souboru.';
lsFileReadingError = 'Chyba při čtení souboru.';
lsFileWritingError = 'Chyba při zápisu do souboru.';
lsFileSeekingError = 'Chyba při vyhledávání v souboru.';
lsFileError = 'Chyba souboru: ';
{QRegNote}
lsOk = 'OK';
lsEndProgram = 'Konec';
lsRegisterNow = 'Registrovat';
lsNonameFile = 'Bezjmena.qdr';
lsExportFile = 'Export.qdr';
{QScanDir}
lsInvalidFolder = 'Neplatná složka. Zadejte úplnou cestu, včetně disku.';
lsScanFolderAsDisk = 'Přečíst složku jako disk';
lsScanFolder = 'Přečíst složku:';
lsAndSaveItAsDisk = 'a uložit do databáze jako disk:';
lsRescanDisk = 'Aktualizovat disk';
lsRescanFolder = 'Znovu přečíst obsah disku (složky):';
lsAndSaveItAsUpdateOfDisk = 'a uložit do databáze jako aktualizaci disku:';
lsRescanWarning =
'Specifikace disku/složky je odlišná od původní. To může způsobit ztrátu popisek. Pokračovat?';
{QCollect}
lsCollectionOverflow = 'Příliž velký seznam nebo nedostatek paměti';
lsInvalidIndex = 'Interní problém při indexaci seznamu';
lsAbstractMethodUsed = 'Interní problém (abstraktní metoda)';
{QFAskLab}
lsGenerated = 'Vytvořené jméno: ';
{QFExport}
lsExportOnlySelected = 'Exportovat pouze vybrané položky?'#13#10'Ne = exportovat všechny.';
lsMultipleItemsSelected = 'Je vybrána skupina položek.';
lsFilterDatabase = 'Export formát pro databázi (*.defd)|*.defd|Všechny soubory (*.*)|*.*';
lsFilterFileList = 'Export formát pro soubory (*.deff)|*.deff|Všechny soubory (*.*)|*.*';
lsFilterEmptyList = 'Export formát pro volná místa (*.defs)|*.defs|Všechny soubory (*.*)|*.*';
{$endif}
{====================================================================}
{$ifdef ENGLISH}
{QB_CONV4}
lsInconsistencyOfDataInDBase = 'Inconsistency of data in the database.';
{QDBASE}
lsDBaseCannotBeOpened = 'The database cannot be open';
lsError = 'Error';
lsName = 'Name';
lsDateAndTime = 'Date and time';
lsSize = 'Size';
lsFolder = '(folder)';
lsDisk3 = '(disk)';
lsDescription = 'Description';
lsFolder1 = '(folder) ';
lsSeriousProblemWritingToDBase =
'Serious problem occurred when writing to database.'#13#10'Immediate program shutdown is recommended.';
lsErrorInDBaseFound = 'Database inconsistency was found.'#13#10'Close the database and repair it.';
lsDrive = 'Drive ';
lsIsNotAccesible = ' is not accessible.';
lsLabelDifferent_Change = 'Entered name is different from the current Volume Label. Change the Volume Label?';
lsDifferentNames = 'Different names';
lsOnDisk = 'The Volume Label can have max. 12 characters on disk ';
lsLimitedLength = '';
lsTotalFolders = ' ';
lsTotalFiles = ' folders, ';
lsTotalSize = ' files, ';
lsVolumeLabel = 'Volume Label ';
lsCannotBeChanged = ' cannot be changed.';
lsOverwriteExistingRecord = 'Overwrite existing disk ';
lsWarning = 'Warning';
lsRecordCannotBeDeleted = 'The disk cannot be deleted.';
lsProblem = 'Problem';
lsRecordsSelected = 'Disks selected: ';
lsDeleteAll = '. Delete them all?';
lsConfirmation = 'Confirmation';
lsDeleteRecord = 'Delete disk "';
lsNewNameForUndeletedDisk = 'New name for undeleted disk';
lsDiskWithName = 'Disk with name "';
lsAlreadyExists = '" already exists.';
lsDiskNameChange = 'Disk name change';
lsNameMustBeUnique = 'The name must be unique';
lsNoSelectedDisk = 'Search in selected disks is required, but no disk is selected.';
lsAllDisksSelected = 'Search in not selected disks is required, but all disks are selected.';
lsTooManyFilesSelected = 'Too many files selected. Not all of them will be searched.';
lsNotification = 'Notification';
lsDescriptionCannotBeByParentDir = 'Reference to the parent folder cannot have a description.';
lsListOfFreeSpace = ': List of free space';
lsDescriptionCannotBeSaved = 'The description cannot be saved.';
lsSelectionOfDisks = 'Selection of disks';
lsEnterMaskForSelectionOfDisks = 'Mask for selection of disks:';
lsSelectionOfFiles = 'Selection of files';
lsEnterMaskForSelectionOfFiles = 'Mask for selection of files:';
lsSelectionTooLargeForClipboard = 'Selection too large; cannot copy to Clipboard.';
lsCannotCopy = 'Cannot copy';
lsDisk1 = 'Disk: ';
lsFolder2 = 'Folder: ';
lsPage = 'Page ';
lsQDir = 'DiskBase ';
lsPreparingToPrint = 'Preparing to print...';
lsQuickDir = 'DiskBase';
lsPrintingPage = 'Printing page ';
lsSkippingPage = 'Skipping page ';
lsDatabase = 'Database: ';
lsVolumesDifferent1 =
'The original volume label (%s) and actual volume label (%s) are different. ';
lsVolumesDifferent2 =
'This may indicate, that you are not scanning the same disk, that is recorded in the database. ';
lsVolumesDifferent3 =
'Are you still sure you want to rescan the disk?';
lsFileCannotBeOpen = #13#10#13#10'File cannot be open. Possible causes:'#13#10;
lsFolderCannotBeOpen = #13#10#13#10'Folder cannot be open. Possible causes:'#13#10;
lsDiskNotAccessible = ' - disk is not accessible'#13#10;
lsDifferentDisk = ' - another disk in the drive'#13#10;
lsFileInArchive = ' - file is in compressed archive'#13#10;
lsFolderInArchive = ' - folder is in compressed archive'#13#10;
lsDiskIsNetworkDrive = ' - disk is a network drive, not accessible now'#13#10;
lsVolumeLabelDiffers = ' - volume labels differ: probably different disk'#13#10;
lsFileProbablyDeleted = ' - file was deleted, moved or renamed'#13#10;
lsFolderProbablyDeleted = ' - folder was deleted, moved or renamed'#13#10;
lsFileNotFound = 'File Not Found';
lsFolderNotFound = 'Folder Not Found';
{QDBINFO}
lsYes = 'yes';
lsNo = 'no';
{QDESC}
lsDescrTextModified = 'Description text was modified. Save?';
{QDPRINTS}
lsPrintSelection = 'Print Selection';
lsPrintWhat = 'Print:';
lsExportSelection = 'Items To Be Exported';
lsExportWhat = 'Export:';
{QDEXPORT}
lsDefaultFilter = 'All files (*.*)|*.*';
lsNotValidFormatFile = 'This file does not contain valid data for DiskBase export.';
lsPreparingToExport = 'Preparing to export...';
lsProcessed = 'Processed ';
lsFiles_Written = ' files, written ';
lsExportFolder = 'Export';
lsExportDBaseFormatsFolder = lsExportFolder + '\Formats for database export';
lsExportFoundFormatsFolder = lsExportFolder + '\Formats for list export';
{QDPRINT}
lsCalculatingPrintExtent = 'Calculating print extent...';
lsDisk = 'Disk: ';
lsDateTime = 'Date and time';
lsExpectedNoOfPages = 'Expected number of pages is ';
lsReallyPrintThem = '. Are you sure you want to print them all?';
lsPreparingPrint = lsPreparingToPrint;
{QE_Archi}
lsExploringContent = 'Scanning contents of ';
lsCentralDirCPBNotFound = ' Central dir of PC-Backup not found ';
{QE_Main}
lsError1000 = '(error 1000)';
lsError1001 = '(error 1001)';
lsError1002 = '(error 1002)';
lsError1003 = '(error 1003)';
lsError1004 = '(error 1004)';
lsError1005 = '(error 1005)';
lsInconsitencyOfDataInDBase = 'Inconsisteny of data in database ';
lsNotEnoughSpaceOnDisk = 'Insufficient free space on disk with database ';
lsLoadingLibrary = 'Loading library ';
lsExtracting = 'Extracting ';
lsFrom = ' from ';
lsLibrary = 'Library ';
lsDoesNotContainProperFunctions = ' does not contain all needed functions.';
lsLibrary1 = 'The library ';
lsCannotBeOpened = ' cannot be open.';
lsReleasingLibrary = 'Releasing library ';
lsNotAQDirDBase = 'This file is not a DiskBase database.';
lsRequiresNewerVersion = 'This database requires newer version of the program.';
lsCorruptedHeader = 'The database has corrupted header.';
lsErrorReading = 'Error reading: ';
lsErrorWriting = 'Error writing: ';
lsDBaseIsFull = 'Database is full. Make compression.';
lsDiskInfo = 'DiskInfo.txt';
lsDiskInfoName = 'DiskInfo';
lsDiskInfoExt = '.txt';
lsDiskInfoUpperCase = 'DISKINFO.TXT';
lsDirInfo = 'DirInfo';
lsDefaultMasks = '*.txt|500||*.doc|1000|Uni|*.wri|500|Uni|*.htm|500|HTML|*.html|500|HTML|*.rtf|500|RTF|*.mp3|1000|MP3Tag|';
{QExcept}
lsCriticalError = 'Critical error';
lsCriticalError1 = 'Critical error.';
lsDBaseStructError = 'Error in database structure found. Close the database and call Repair from the File menu. ';
{QFindE}
lsNoDiskFound = 'No disk found.';
lsInformation = 'Information';
{QFindF}
lsNoFileFound = 'No file found.';
{QFindFD}
lsNoMaskEntered = 'You did not enter the text to be searched.';
lsCannotSearch = 'Cannot search';
{QFoundE, QFoundF}
lsSorting = 'Sorting';
lsDisk2 = 'Disk';
lsFreeSpace = 'Free';
lsFreeSpacePerCent = 'Free %';
lsFreeSpacePerCent1 = ' Free % ';
lsSelectionTooLarge = 'Selection too large, cannot copy to Clipboard.';
lsFolder3 = 'Folder';
lsFile = 'File';
{QI_Face}
lsErrorDBaseIsNil = 'Internal error 500: DBaseIsNil';
lsErrorTreeStructIsNil = 'Internal error 501: TreeStructIsNil';
lsErrorCurDirColIsNil = 'Internal error 502: CurDirColIsNil';
lsErrorFileSearchColIsNil = 'Internal error 503: FileSearchColIsNil';
lsErrorKeyFieldIsNil = 'Internal error 503: KeyFieldIsIsNil';
lsErrorCurFileColIsNil = 'Internal error 504: CurFileColIsNil';
lsErrorRootDirColIsNil = 'Internal error 505: RootDirColIsNil';
lsErrorDirColHandleIsNil = 'Internal error 506: DirColHandleIsNil';
lsErrorFileColHandleIsNil = 'Internal error 507: FileColHandleIsNil';
{QLocOpt}
lsMask = 'Mask';
lskB = 'Bytes';
lsDLL = 'Filter';
{QMain}
lsFatalInternalError = ' (Fatal internal error ';
lsDbaseWithThisNameIsOpen = 'Database with this name is open - file cannot be overwritten.';
lsCannotCreate = 'Cannot create';
lsDBaseCannotBeCreated = 'Database cannot be created';
lsFileDoesNotExist = 'File does not exist: ';
lsErrorOnCommandLine = 'Error on command line';
lsErrorInProgramSettings = 'Error in program settings';
lsInvalidParameter = 'Invalid parameter: ';
lsOptionsCannotBeMixed = 'Options /f and /s cannot be mixed on command line.';
lsInvalidOption = 'Invalid option: ';
lsDBaseIsOpenCannotCompress =
'Database with this name is open - it must be closed for compression.';
lsCannotCompress = 'Cannot compress';
lsCannotCompressAsItIsProtected =
'This database cannot be compressed, because it is a read-only database.';
lsDbaseIsOpenCannotOverwrite = 'Database with this name is open - cannot be overwritten.';
lsCannotExport = 'Cannot export';
lsDBaseIsOpenMustBeClosedFirst =
'Database with this name is open. Only closed databases can be imported.';
lsCannotImport = 'Cannot import';
lsCannotImportAsItIsProtected =
'The database cannot be imported, because it is a read-only (protected) database.';
lsCannotImportProbablyCorrupted =
'This database cannot be imported. It is either corrupted or requires newer version of this program.';
lsCannotContinue = 'Cannot continue';
lsDBaseIsOpenCannotRepair =
'Database with this name is open. Only closed databases can be repaired.';
lsCannotRepairCorruptedHeader =
'This file is either not a DiskBase database, or it has unrepairable header.';
lsCannotRepairByOldVersion =
'The database was created by a newer version of the program. You cannot repair it by this version of the program.';
lsCannotRepairRuntimeDatabase =
'This database cannot be repaired, as it is read-only database.';
lsDatabaseRepair = 'Database Repair';
lsRepairingIndex = 'Repairing index table...';
lsScannningDatabase = 'Scanning the database, please wait...';
lsEject = 'Eject disk from ';
{QReindex}
lsCompressingDatabase = 'Compressing database';
lsExportingToRunTime = 'Exporting to read-only form';
lsExporting = 'Exporting';
lsImporting = 'Importing';
lsCompressNotSuccessful = 'Compression was not successful';
lsExportNotSuccessful = 'Export was not successful';
lsImportNotSuccessful = 'Import was not successful';
lsSourceDBase = 'The source database ';
lsTargetDBase = 'The target database ';
lsCannotBeCreated = ' cannot be created.';
lsProcessNotSuccessful = 'Process was not successful.';
lsDBase = 'The database ';
lsCannotBeRenamedTo = ' cannot be renamed to ';
lsOriginalDBase = 'The original database ';
lsCannotBeDeleted = ' cannot be deleted.';
{QScanDrv}
lsScanArchive = 'Scan archive file ';
lsScanningTree = 'Scanning tree structure:';
lsScanningFoldersAndFiles = 'Scanning contents of folders and archives:';
{QSetting}
lsBold = ', bold';
lsItalics = ', italics';
lsArial = 'Arial';
lsMSSansSerif = 'MS Sans Serif';
lsScript = 'Default';
lsCompressionNecessary =
'WARNING: If you change this setting, you must close and compress all DiskBase databases. See Help for details.';
{QStream}
lsFileAccessError = 'File access error.';
lsFileCreationError = 'File creation or open error.';
lsFileReadingError = 'File reading error.';
lsFileWritingError = 'File writing error.';
lsFileSeekingError = 'File seeking error.';
lsFileError = 'File error: ';
{QRegNote}
lsOk = 'OK';
lsEndProgram = 'Exit';
lsRegisterNow = 'Register now';
lsNonameFile = 'NoName.qdr';
lsExportFile = 'Export.qdr';
{QScanDir}
lsInvalidFolder = 'Invalid folder. Enter full path, including the disk letter.';
lsScanFolderAsDisk = 'Scan Folder As Disk';
lsScanFolder = 'Scan folder:';
lsAndSaveItAsDisk = 'and save it to database as disk:';
lsRescanDisk = 'Rescan Disk';
lsRescanFolder = 'Rescan disk (folder):';
lsAndSaveItAsUpdateOfDisk = 'and save it to database as update of disk:';
lsRescanWarning =
'The disk or folder is different from the original one. This may cause a loss of manually created descriptions. Continue?';
{QCollect}
lsCollectionOverflow = 'Too large list or not enough memory.';
lsInvalidIndex = 'Internal problem in list indexing.';
lsAbstractMethodUsed = 'Internal error: Abstract method used.';
{QFAskLab}
lsGenerated = 'Generated name: ';
{QFExport}
lsExportOnlySelected = 'Export only selected items?'#13#10'No = export all.';
lsMultipleItemsSelected = 'Group of items is selected.';
lsFilterDatabase = 'Export Format for Database (*.defd)|*.defd|All files (*.*)|*.*';
lsFilterFileList = 'Export Format for Found files (*.deff)|*.deff|All files (*.*)|*.*';
lsFilterEmptyList = 'Export Format for free Space (*.defs)|*.defs|All files (*.*)|*.*';
{$endif}
implementation
end.
|
// Simple Pascal FizzBuzz implementation
// Author: @veotani
program FizzBuzz;
var i: integer;
begin
for i:=1 to 100 do
if i mod 15 = 0 then
writeln ('FizzBuzz')
else if i mod 3 = 0 then
writeln('Fizz')
else if i mod 5 = 0 then
writeln('Buzz')
else
writeln(i)
end. |
unit Cons_checker;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Level, Level_Utils, misc_utils, GlobalVars, Buttons;
type
TConsistency = class(TForm)
Errors: TListBox;
Panel: TPanel;
BNClose: TButton;
BNGoto: TButton;
BNCheck: TButton;
BNOptions: TButton;
SBHelp: TSpeedButton;
procedure ErrorsDblClick(Sender: TObject);
procedure BNCloseClick(Sender: TObject);
procedure BNCheckClick(Sender: TObject);
procedure BNGotoClick(Sender: TObject);
procedure ErrorsClick(Sender: TObject);
procedure BNOptionsClick(Sender: TObject);
procedure SBHelpClick(Sender: TObject);
private
{ Private declarations }
Procedure ClearErrors;
Function L:TLevel;
public
MapWindow:TForm;
Procedure Check;
{ Public declarations }
end;
implementation
Uses Mapper, U_Options;
Const
et_none=0;
et_sector=1;
et_wall=2;
et_object=3;
Type
TConsistencyError=class
etype:Integer;
ID:Longint;
ScID:Longint;
end;
{$R *.DFM}
Function TConsistency.L:TLevel;
begin
Result:=TMapWindow(MapWindow).Level;
end;
procedure TConsistency.ErrorsDblClick(Sender: TObject);
begin
BNGoto.Click;
end;
procedure TConsistency.BNCloseClick(Sender: TObject);
begin
Close;
end;
Procedure TConsistency.ClearErrors;
var i:Integer;
begin
for i:=0 to Errors.Items.Count-1 do Errors.Items.Objects[i].Free;
Errors.Items.Clear;
end;
{Assumes the sector has 2 walls at each vertex, all vertex references valid}
Function ArrangeVertices(L:TLevel;sc:integer):boolean;
var i,j:integer;
TheSector:TSector;
TheWall:TWall;
nwall,cvx:integer;
wln,vxn,vxs,wls:TList;
revwls:TList;
cyclebase:integer;
Procedure vx_add(n:Integer);
begin
vxn.Add(Pointer(n));
vxs.Add(TheSector.Vertices[n]);
end;
Procedure wl_add(n:Integer);
begin
wln.Add(Pointer(n));
wls.Add(TheSector.Walls[n]);
end;
Procedure AdjustWLRef(var aSC,aWl:integer);
var w:integer;
begin
if aSc<>sc then exit;
w:=wln.IndexOf(Pointer(aWL));
if w<>-1 then aWl:=w else begin aSC:=-1; aWL:=-1; end;
end;
Procedure AdjustVXRef(var aVX:Integer);
var v:integer;
begin
V:=vxn.IndexOf(Pointer(aVX));
if V=-1 then V:=0;
aVX:=V;
end;
begin {Arrangevertices}
Result:=false;
TheSector:=L.Sectors[sc];
With TheSector do
begin
for i:=0 to vertices.count-1 do Vertices[i].Mark:=0;
for i:=0 to walls.count-1 do
with Walls[i] do
begin
Mark:=0;
if Vertices[V1].Mark=1 then exit;
Vertices[V1].Mark:=1;
end;
vxs:=TList.Create;vxn:=TList.Create;
wls:=TList.Create;wln:=TList.Create;
Result:=true;
Repeat
nwall:=-1;
for i:=0 to Walls.count-1 do if Walls[i].Mark=0 then begin nwall:=i; break; end;
if nwall=-1 then break;
TheWall:=Walls[nwall];
TheWall.Mark:=1;
cyclebase:=TheWall.V1;
wl_add(nwall);
vx_add(TheWall.V1);
vx_add(TheWall.V2);
cvx:=TheWall.V2;
Repeat
nwall:=-1;
for i:=0 to walls.count-1 do
With Walls[i] do
if (Mark=0) and (V1=cvx) then
begin
nwall:=i;
Mark:=1;
wl_add(nwall);
cvx:=V2;
if cvx=cyclebase then nwall:=-1 else vx_add(V2);
break;
end;
until nwall=-1;
until false;
{Change wall references}
for i:=0 to L.Sectors.Count-1 do
With L.Sectors[i] do
begin
AdjustWLRef(FloorSlope.Sector,FloorSlope.Wall);
AdjustWLRef(CeilingSlope.Sector,CeilingSlope.Wall);
for j:=0 to Walls.Count-1 do
With Walls[j] do
begin
AdjustWLRef(Adjoin,Mirror);
AdjustWLRef(DAdjoin,DMirror);
end;
end;
{Rearrange walls}
for i:=0 to wls.Count-1 do Walls[i]:=TWall(wls[i]);
{Change vertex references}
for i:=0 to Walls.Count-1 do
With Walls[i] do
begin
AdjustVXRef(V1);
AdjustVXRef(V2);
end;
{Rearrange vertices}
for i:=0 to vxs.Count-1 do Vertices[i]:=TVertex(vxs[i]);
wls.free;wln.free;
vxs.free;vxn.free;
end;
end;
Procedure TConsistency.Check;
var i,s,w,v,o:Integer;
Lev:TLevel;
TheSector,Sec:TSector;
TheWall,cWall:TWall;
NotClosed:Boolean;
tmp:Integer;
Players,
startpos,
flagstars,
ballstars:Integer;
PF,
SPF,
FSF,
BSF:Longint;
oname:String;
BadVX:Boolean;
BadVXOrder:Boolean;
TwoWLPerVX:Boolean;
fixOrder:boolean;
Cyclebase,CycleCount:Integer;
Const
AdjoinedFlags=WALLFLAG1_MIDTEX or WALLFLAG1_NOPASS or
WALLFLAG1_FORCEPASS or WALLFLAG1_FENCE or WALLFLAG1_SHATTER or
WALLFLAG1_PROJECTILE_OK;
Procedure AddError(Const Text:String;etype:Integer;ID:longint);
var ce:TConsistencyError;
begin
ce:=TConsistencyError.Create;
ce.etype:=etype;
Case eType of
et_Sector,et_Object: ce.ID:=ID;
et_Wall: begin ce.ID:=ID; ce.scID:=Sec.HexID; end;
et_none: begin ce.free; ce:=nil; end;
end;
if etype=et_none then Errors.Items.AddObject(Text,ce)
else Errors.Items.AddObject(Format('%s ID: %x',[Text,ID]),ce);
end;
Function FixError(const Text:String;etype:Integer;ID:longint):Boolean;
begin
Case cc_FixErrors of
cc_Fix:Result:=true;
cc_NeverFix: Result:=false;
cc_Ask: Result:=MsgBox(Text+' Fix?','Fix confirmation',MB_YesNo)=IDYes;
end;
if Result then AddError(Text+'(Fixed)',etype,ID)
else AddError(Text,etype,ID);
end;
Function SCInvalid(SC:Integer):Boolean;
begin
Result:=(SC<-1) or (SC>=Lev.Sectors.Count);
end;
Function WLInvalid(SC,WL:Integer):Boolean;
begin
Result:=True;
If SCInvalid(SC) then exit;
if (SC<>-1) and (WL=-1) then exit;
if SC=-1 then begin Result:=false; exit; end;
Result:=(WL<-1) or (WL>=Lev.Sectors[SC].Walls.Count);
end;
Procedure CheckTX(var tx:String;const text:String;etype:integer;ID:Longint);
begin
if tx='' then
if FixError(text,etype,ID) then tx:='DEFAULT.PCX';
end;
Procedure CheckFlags(var f:longint; corFlag,ID:longint);
begin
If (f<>corFlag) then
if FixError('Incorrect flags on player start',et_object,ID) then f:=corFlag;
end;
begin
if Not Visible then Show;
ClearErrors;
Lev:=l;
if Length(TMapWindow(MapWindow).LevelName)>8 then AddError('Level name is more than 8 characters long',et_none,0);
if Trim(Lev.Music)='' then
begin
if FixError('No MUSIC in the level header',et_none,0) then L.Music:='NULL';
end;
With L do
begin
for s:=Sectors.Count-1 downto 0 do
With Sectors[s] do
begin
Sec:=Sectors[s];
{Sector checks}
for i:=1 to length(Name) do
if Name[i] in ['a'..'z'] then
begin
if FixError('Sector name in lowercase',et_sector,HexID) then
Name:=UpperCase(Name);
break;
end;
If Floor_Y>Ceiling_Y Then AddError('Floor is higher than ceiling',et_sector,HexID);
if SCInvalid(VADJOIN) then AddError('VADJOIN out of range',et_sector,HexID);
if (Friction<0) or (Friction>1) then AddError('Friction invalid',et_sector,HexID);
if (Elasticity<0) or (Elasticity>4) then AddError('Elasticity invalid',et_sector,HexID);
With FloorSlope do If WLInvalid(Sector,Wall) then AddError('Invalid floor slope',et_sector,HexID);
With CeilingSlope do If WLInvalid(Sector,Wall) then AddError('Invalid ceiling slope',et_sector,HexID);
CheckTX(Floor_Texture.Name,'Empty floor texture',et_sector,HexID);
CheckTX(Ceiling_Texture.Name,'Empty ceiling texture',et_sector,HexID);
if (Vertices.Count=0) or (Walls.Count=0) then
if FixError('Empty sector',et_sector,HexID) then begin DeleteSector(Lev,s); continue; end;
if Walls.Count<3 then
if FixError('Less than 3 walls in sector',et_sector,HexID) then begin DeleteSector(Lev,s); continue; end;
if Walls.Count<>Vertices.Count then AddError('Warning: Number of Walls<>Number of vertices',et_sector,HexID);
{Clear vertex marks}
for v:=0 to Vertices.Count-1 do Vertices[v].Mark:=0;
{Checking walls}
For w:=Walls.Count-1 downto 0 do
With Walls[w] do
begin
cWall:=Walls[w];
CheckTX(MID.Name,'Empty MID texture',et_wall,cWall.HexID);
CheckTX(BOT.Name,'Empty BOT texture',et_wall,cWall.HexID);
CheckTX(TOP.Name,'Empty TOP texture',et_wall,cWall.HexID);
{Check wall flags}
if (Adjoin=-1) and (DAdjoin=-1) and (Flags and AdjoinedFlags<>0) then
if FixError('Unadjoined wall has adjoined flags set',et_wall,cWall.HexID) then
Flags:=Flags and (not AdjoinedFlags);
{Check if Adjoin=-1 and Dadjoin<>-1}
if (Adjoin=-1) and (DAdjoin<>-1) then
if FixError('Second adjoin exists while first doesn''t',et_wall,cWall.HexID) then
begin
Adjoin:=Dadjoin;
Mirror:=Dmirror;
DAdjoin:=-1;
DMirror:=-1;
end;
{Check if Adjoin=DAdjoin}
if (Adjoin<>-1) and (DADJOIN<>-1) and (Adjoin=DAdjoin) and (Mirror=DMirror) then
if FixError('Second adjoin is the same as first',et_wall,cWall.HexID) then
begin DAdjoin:=-1; DMirror:=-1; end;
if (V1<0) or (V1>=Vertices.Count) then
begin
AddError('Invalid Wall vertex',et_wall,cWall.HexID);
BadVX:=true;
end
else Inc(Vertices[V1].Mark);
if (V2<0) or (V2>=Vertices.Count) then
begin
AddError('Invalid Wall vertex',et_wall,Walls[w].HexID);
BadVX:=true;
end
else Inc(Vertices[V2].Mark);
if BadVX then continue;
{Check adjoin}
if WLInvalid(ADJOIN,MIRROR) then AddError('Invalid adjoin',et_wall,cWall.HexID)
else if WLInvalid(DADJOIN,DMIRROR) then AddError('Invalid Dadjoin',et_wall,cWall.HexID)
else
begin
if not ReverseAdjoinValid(Lev,s,w) then AddError('Invalid reverse adjoin',et_wall,cWall.HexID);
{Check double adjoin}
if (Adjoin<>-1) and (DAdjoin<>-1) then
if Sectors[DAdjoin].Floor_Y>Sectors[Adjoin].Floor_Y then
if FixError('Adjoin and DAdjoin are in incorrect order',et_Wall,cWall.HexID) then
begin
Tmp:=Adjoin; Adjoin:=DAdjoin; DAdjoin:=tmp;
tmp:=Mirror; Mirror:=DMirror; DMirror:=tmp;
end;
if V1=V2 then
AddError('Wall starts and ends at the same vertex!',et_wall,Walls[w].HexID);
if GetWLLen(Lev,s,w)=0 then
if FixError('Zero length wall',et_wall,Walls[w].HexID) then DeleteWall(Lev,s,w);
end;
end; {For w:=o to walls.count-1}
{Check Vertex Order}
Cyclebase:=0; Cyclecount:=0; BadVXOrder:=false;
For w:=0 to Walls.Count-1 do
With Walls[w] do
begin
if V1<>w then begin BadVXOrder:=true; break; end;
if V2=w+1 then inc(CycleCount)
else if V2=CycleBase then
begin
Inc(CycleCount);
CycleBase:=w+1;
if CycleCount<3 then AddError('Cycle of less than 3 vertices in sector',et_sector,Sec.HexID);
cycleCount:=0;
end
else begin BadVXOrder:=true; break; end;
end;
{Check vertex references}
NotClosed:=false;
TwoWLPerVX:=true;
For v:=Vertices.Count-1 downto 0 do
With Vertices[v] do
case Mark of
0: if FixError('Orphan vertex',et_sector,HexID) then DeleteVertex(Lev,s,v) else TwoWLPerVX:=false;
1: begin NotClosed:=true; TwoWLPerVX:=false; end;
2: ;
else
begin
TwoWLPerVX:=false;
if Mark And 1<>0 then AddError('Uneven number of walls meet at one vertex',et_sector,HexID);
end;
end;
{Fix bad vertex order, if possible}
if BadVXOrder then
if not TwoWLPerVX then AddError('Bad vertex order - can''t fix',et_sector,HexID)
else
begin
FixOrder:=true;
if DoConfirm(c_VXOrderFix) then FixOrder:=
MsgBox(Pchar(Format('Bad Vertex Order SC %x. Fix?',[HexID])),'Confirm',mb_YesNo)=idYes;
if FixOrder then
begin
ArrangeVertices(L,s);
AddError('Bad Vertex Order(fixed)',et_sector,HexID);
end
else AddError('Bad Vertex Order',et_sector,HexID);
end;
if NotClosed then AddError('Sector not closed',et_sector,HexID);
end; {End for s:=0 to Sectors.count-1}
Players:=0;
startpos:=0;
flagstars:=0;
ballstars:=0;
PF:=0;
SPF:=0;
FSF:=0;
BSF:=0;
for o:=Objects.Count-1 downto 0 do
With Objects[o] do
begin
if Name='' then AddError('Empty object name',et_object,HexID);
if Sector=-1 then
AddError('Object not in sector',et_object,HexID);
oname:=UpperCase(Name);
if oname='PLAYER' then begin inc(players); PF:=PF or Flags2; end
else if oName='STARTPOS' then begin inc(startpos); CheckFlags(Flags2,$F0000000,HexID); end
else if oName='FLAGSTAR' then begin inc(flagstars); CheckFlags(Flags2,$F0800000,HexID); end
else if oName='BALLSTAR' then begin inc(ballstars); CheckFlags(Flags2,$F2000000,HexID); end;
end;
if PF and $B0000000<>$B0000000 then AddError('PLAYER object doesn''t exist on all difficulties!',et_none,0);
if Startpos<7 then AddError('Less than 7 STARTPOS objects',et_none,0);
if flagstars<8 then AddError('Less than 8 FLAGSTAR objects',et_none,0);
if ballstars<8 then AddError('Less than 8 BALLSTAR objects',et_none,0);
end; {End with L do}
if Errors.ItemIndex<=0 then Errors.ItemIndex:=0 else Errors.OnClick(nil);
end;
procedure TConsistency.BNCheckClick(Sender: TObject);
begin
Check;
end;
procedure TConsistency.BNGotoClick(Sender: TObject);
var Index:Integer;
ce:TConsistencyError;
sc,wl,ob:Integer;
begin
Index:=Errors.ItemIndex;
if Index<0 then exit;
ce:=TConsistencyError(Errors.Items.Objects[Index]);
if ce=nil then exit;
Case ce.Etype of
et_sector: begin
sc:=L.GetSectorByID(ce.ID);
if sc=-1 then
begin MsgBox('No sector with this ID','Error',mb_OK); exit; end;
TMapWindow(MapWindow).Goto_Sector(SC);
end;
et_wall: begin
sc:=L.GetSectorByID(ce.ScID);
if sc=-1 then
begin MsgBox('No sector with this ID','Error',mb_OK); exit; end;
wl:=L.Sectors[SC].GetWallByID(ce.ID);
if wl=-1 then MsgBox('No wall with this ID','Error',mb_OK);
TMapWindow(MapWindow).Goto_Wall(Sc,Wl);
end;
et_Object: begin
OB:=L.GetObjectByID(ce.ID);
if ob=-1 then
begin MsgBox('No Object with this ID','Error',mb_OK); exit; end;
TMapWindow(MapWindow).Goto_Object(OB);
end;
end;
end;
procedure TConsistency.ErrorsClick(Sender: TObject);
var Index:Integer;
ce:TConsistencyError;
begin
Index:=Errors.ItemIndex;
if Index=-1 then begin BNGoto.Enabled:=false; exit; end;
ce:=TConsistencyError(Errors.Items.Objects[Index]);
if ce=nil then BNGoto.Enabled:=false
else BNGoto.Enabled:=true;
end;
procedure TConsistency.BNOptionsClick(Sender: TObject);
begin
Options.SetOptions(Options.Misc);
end;
procedure TConsistency.SBHelpClick(Sender: TObject);
begin
Application.HelpJump('Hlp_Consistency_Checker');
end;
end.
|
unit uPctPetSaleFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentModalForm, XiButton, ExtCtrls, cxControls, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox, mrSuperCombo, DB, DBClient,
cxCalendar, cxDBEdit, mrDBDateEdit, StdCtrls, cxCurrencyEdit,
mrDBCurrencyEdit, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGridLevel, cxClasses, cxGridCustomView, cxGrid;
type
TPctPetSaleFrm = class(TParentModalForm)
cdsPetSale: TClientDataSet;
cdsPetSaleStoreID: TIntegerField;
cdsPetSaleModelID: TIntegerField;
cdsPetSaleIDPessoa: TIntegerField;
cdsPetSaleIDUser: TIntegerField;
cdsPetSaleCostPrice: TCurrencyField;
cdsPetSaleSalePrice: TCurrencyField;
cdsPetSaleDiscount: TCurrencyField;
cdsPetSaleIDWarrantyCustomer: TIntegerField;
cdsPetSaleIDPet: TIntegerField;
scPet: TmrDBSuperCombo;
dsPetSale: TDataSource;
scSystemUser: TmrDBSuperCombo;
cdsPetSaleSaleDate: TDateTimeField;
edtRecordDate: TmrDBDateEdit;
edtSale: TmrDBCurrencyEdit;
Label1: TLabel;
Bevel1: TBevel;
scCustomerPurchase: TmrDBSuperCombo;
Bevel2: TBevel;
Label2: TLabel;
scCustomerWarranty: TmrDBSuperCombo;
scPetSatus: TmrDBSuperCombo;
cdsPetSaleIDStatus: TIntegerField;
cdsMicrochipSale: TClientDataSet;
cdsRegistrySale: TClientDataSet;
cdsMicrochipSaleIDMicrochip: TIntegerField;
cdsMicrochipSaleMicrochip: TStringField;
cdsMicrochipSaleMicrochipNum: TStringField;
cdsRegistrySaleIDRegistry: TIntegerField;
cdsRegistrySaleMarked: TBooleanField;
cdsRegistrySaleRegistry: TStringField;
cdsRegistrySaleRegistrationNum: TStringField;
lbMAddress: TLabel;
lbWAddress: TLabel;
cdsMicrochipSaleIDPet: TIntegerField;
pnlMicrochips: TPanel;
dsMicrochipSale: TDataSource;
grdMicrochip: TcxGrid;
grdMicrochipDBTableView: TcxGridDBTableView;
grdMicrochipLevel: TcxGridLevel;
cdsMicrochipSaleAmount: TBCDField;
grdMicrochipDBTableViewMicrochip: TcxGridDBColumn;
grdMicrochipDBTableViewMicrochipNum: TcxGridDBColumn;
grdMicrochipDBTableViewAmount: TcxGridDBColumn;
grdMicrochipDBTableViewMarked: TcxGridDBColumn;
cdsMicrochipSaleMarked: TBooleanField;
cdsMicrochipSaleIDModel: TIntegerField;
lbEmail: TLabel;
cdsPetSaleInvoiceTotal: TCurrencyField;
edtInvoiceTotal: TmrDBCurrencyEdit;
procedure FormCreate(Sender: TObject);
procedure scPetPropertiesEditValueChanged(Sender: TObject);
procedure cdsPetSaleNewRecord(DataSet: TDataSet);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure scCustomerPurchasePropertiesEditValueChanged(
Sender: TObject);
procedure scCustomerWarrantyPropertiesEditValueChanged(
Sender: TObject);
procedure cdsMicrochipSaleBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
private
FIDSpecies : Integer;
FIDPet : Integer;
FIDSalePet : Integer;
procedure OpenPetSale;
procedure ClosePetSale;
procedure OpenMicrochipSale;
procedure CloseMicrochipSale;
procedure OpenRegistrySale;
procedure CloseRegistrySale;
procedure PrintWarranty;
function ValidateField : Boolean;
protected
procedure ConfirmFrm; override;
procedure CancelFrm; override;
public
{ Public declarations }
end;
implementation
uses uDMPet, uDMGlobalNTier, uDMPetCenter, mrMsgBox, uMRSQLParam,
uPctWarrantyPrintForm, uDMMaintenance, uClasseFunctions;
{$R *.dfm}
{ TPctPetSaleFrm }
procedure TPctPetSaleFrm.CancelFrm;
begin
inherited;
end;
procedure TPctPetSaleFrm.ClosePetSale;
begin
with cdsPetSale do
if Active then
Close;
end;
procedure TPctPetSaleFrm.OpenPetSale;
begin
with cdsPetSale do
if not Active then
CreateDataSet;
end;
procedure TPctPetSaleFrm.ConfirmFrm;
var
sMsgError : String;
begin
inherited;
if ValidateField then
begin
if DMPet.PetCenterConn.AppServer.PetCreateSale(cdsPetSale.Data, cdsMicrochipSale.Data, cdsRegistrySale.Data, sMsgError, FIDSalePet) then
PrintWarranty
else
MsgBox('Error. Sale not recorded!-> Check report configuration!', vbCritical + vbOKOnly, sMsgError);
end
else
ModalResult := mrNone;
end;
procedure TPctPetSaleFrm.FormCreate(Sender: TObject);
begin
inherited;
scSystemUser.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, '');
scPet.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, 'MenuDisplay=Puppy;');
scPetSatus.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, '');
scCustomerWarranty.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, 'MenuDisplay=Customer;EntityType='+IntToStr(PT_CUSTOMER)+';');
scCustomerPurchase.CreateListSource(DMPet.TraceControl, DMPet.DataSetControl, DMPet.UpdateControl, nil, DMPet.SystemUser, 'MenuDisplay=Customer;EntityType='+IntToStr(PT_CUSTOMER)+';');
OpenPetSale;
OpenMicrochipSale;
OpenRegistrySale;
end;
procedure TPctPetSaleFrm.scPetPropertiesEditValueChanged(Sender: TObject);
var
cSalePrice,
cDiscount,
cPromoPrice : Variant;
begin
inherited;
if (cdsPetSale.State <> dsInactive) and (scPet.EditValue <> Null) then
begin
cPromoPrice := scPet.GetFieldValue('PromoPrice');
cSalePrice := scPet.GetFieldValue('SalePrice');
cDiscount := 0;
if cPromoPrice <> 0 then
cSalePrice := cPromoPrice;
FIDPet := scPet.EditValue;
FIDSpecies := scPet.GetFieldValue('IDSpecies');
cdsPetSale.FieldByName('IDStatus').Value := scPet.GetFieldValue('IDStatus');
cdsPetSale.FieldByName('CostPrice').Value := scPet.GetFieldValue('VendorCost');
cdsPetSale.FieldByName('ModelID').Value := scPet.GetFieldValue('IDModel');
cdsPetSale.FieldByName('SalePrice').Value := cSalePrice;
cdsPetSale.FieldByName('Discount').Value := cDiscount;
cdsMicrochipSale.Close;
cdsMicrochipSale.Open;
end;
end;
procedure TPctPetSaleFrm.cdsPetSaleNewRecord(DataSet: TDataSet);
begin
inherited;
cdsPetSale.FieldByName('SaleDate').AsDateTime := Now;
cdsPetSale.FieldByName('StoreID').AsInteger := DMPet.GetPropertyDomain('PctDefaultStore');
cdsPetSale.FieldByName('IDUser').Value := DMPet.SystemUser.ID;
end;
function TPctPetSaleFrm.ValidateField: Boolean;
begin
Result := False;
if (scSystemUser.EditValue = Null) or (scSystemUser.EditValue = 0) then
begin
MsgBox('User cannot be empty', vbInformation + vbOKOnly);
scSystemUser.SetFocus;
Exit;
end;
if (scPet.EditValue = Null) or (scPet.EditValue = 0) then
begin
MsgBox('SKU cannot be empty', vbInformation + vbOKOnly);
scPet.SetFocus;
Exit;
end;
if (edtRecordDate.EditValue = Null) then
begin
MsgBox('Date cannot be empty', vbInformation + vbOKOnly);
edtRecordDate.SetFocus;
Exit;
end;
if (edtSale.EditValue = Null) or (edtSale.EditValue = 0) then
begin
MsgBox('Sale Price cannot be 0', vbInformation + vbOKOnly);
edtSale.SetFocus;
Exit;
end;
if (scCustomerWarranty.EditValue = Null) or (scCustomerWarranty.EditValue = 0) then
begin
MsgBox('Customer warranty cannot be empty', vbInformation + vbOKOnly);
scCustomerWarranty.SetFocus;
Exit;
end;
Result := True;
end;
procedure TPctPetSaleFrm.CloseMicrochipSale;
begin
with cdsMicrochipSale do
if not Active then
CreateDataSet;
end;
procedure TPctPetSaleFrm.CloseRegistrySale;
begin
with cdsMicrochipSale do
if Active then
Close;
end;
procedure TPctPetSaleFrm.OpenMicrochipSale;
begin
with cdsRegistrySale do
if not Active then
CreateDataSet;
end;
procedure TPctPetSaleFrm.OpenRegistrySale;
begin
with cdsRegistrySale do
if Active then
Close;
end;
procedure TPctPetSaleFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
ClosePetSale;
CloseMicrochipSale;
CloseRegistrySale;
end;
procedure TPctPetSaleFrm.PrintWarranty;
var
Form : TForm;
WPD: TWarrantyPrintData;
MS : TMemoryStream;
begin
Form := CreateForm(Self, 'TPctWarrantyPrintForm');
try
try
WPD := TWarrantyPrintData.Create;
try
WPD.IDPet := FIDPet;
WPD.IDSpecies := FIDSpecies;
WPD.IDPetSale := FIDSalePet;
MS := DMPetCenter.GetWarrantyReport('IDSpecies', WPD.IDSpecies);
try
TPctWarrantyPrintForm(Form).MSReport := MS;
TPctWarrantyPrintForm(Form).PrintReport(WPD);
finally
FreeAndNil(MS);
end;
finally
WPD.Free;
end;
except
MsgBox('Report error._Check report configuration', vbCritical + vbOKOnly);
end;
finally
FreeAndNil(Form);
end;
end;
procedure TPctPetSaleFrm.scCustomerPurchasePropertiesEditValueChanged(
Sender: TObject);
begin
inherited;
if (cdsPetSale.State <> dsInactive) and (scCustomerPurchase.EditValue <> Null) then
begin
cdsPetSale.FieldByName('IDWarrantyCustomer').AsInteger := scCustomerPurchase.EditValue;
lbMAddress.Caption := DMPetCenter.FormatAddress(scCustomerPurchase.GetFieldValue('Endereco'),
scCustomerPurchase.GetFieldValue('Cidade'),
scCustomerPurchase.GetFieldValue('IDEstado'),
scCustomerPurchase.GetFieldValue('CEP'));
scCustomerPurchase.Hint := lbMAddress.Caption;
lbEmail.Caption := VarToStr(scCustomerPurchase.GetFieldValue('Email'));
end;
end;
procedure TPctPetSaleFrm.scCustomerWarrantyPropertiesEditValueChanged(
Sender: TObject);
begin
inherited;
if (cdsPetSale.State <> dsInactive) then
lbWAddress.Caption := DMPetCenter.FormatAddress(scCustomerWarranty.GetFieldValue('Endereco'),
scCustomerWarranty.GetFieldValue('Cidade'),
scCustomerWarranty.GetFieldValue('IDEstado'),
scCustomerWarranty.GetFieldValue('CEP'));
scCustomerWarranty.Hint := lbWAddress.Caption;
end;
procedure TPctPetSaleFrm.cdsMicrochipSaleBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
inherited;
with TMRSQLParam.Create do
try
if (FIDPet <> 0) then
begin
AddKey('PM.IDPet').AsInteger := FIDPet;
KeyByName('PM.IDPet').Condition := tcEquals;
end;
OwnerData := ParamString;
finally
Free;
end;
end;
initialization
RegisterClass(TPctPetSaleFrm);
end.
|
unit clsInfoCashSale;
interface
type
InfoCashSale = class
private
subTotal: Currency;
itemDiscounts: Currency;
saleDiscount: Currency;
otherCosts: Currency;
tax: Currency;
totalDue: Currency;
totalSaved: Currency;
newTotalDue: Currency;
newTotalSaved: Currency;
ftotalToStoreAccount: Currency;
public
function getNewTotalDue: Currency;
procedure setNewTotalDue(pValue: Currency);
function getNewTotalSaved: Currency;
procedure setNewTotalSaved(pValue: Currency);
function getSubtotal: Currency;
procedure setSubtotal(pValue: Currency);
function getItemDiscounts: Currency;
procedure setItemDiscounts(pValue: Currency);
function getSaleDiscount: Currency;
procedure setSaleDiscount(pValue: Currency);
function getOtherCosts: Currency;
procedure setOtherCosts(pValue: Currency);
function getTax: Currency;
procedure setTax(pValue: Currency);
function getTotalDue: Currency;
procedure setTotalDue(pValue: Currency);
function getTotalSaved: Currency;
procedure setTotalSaved(pValue: Currency);
function getTotalStoreAccount(): Currency;
procedure setTotalStoreAccount(arg_total: Currency);
end;
implementation
{ InfoSale }
function InfoCashSale.getItemDiscounts: Currency;
begin
result := self.itemDiscounts;
end;
function InfoCashSale.getNewTotalDue: Currency;
begin
result := self.newTotalDue;
end;
function InfoCashSale.getNewTotalSaved: Currency;
begin
result := self.newTotalSaved;
end;
function InfoCashSale.getOtherCosts: Currency;
begin
result := self.otherCosts;
end;
function InfoCashSale.getSaleDiscount: Currency;
begin
result := self.saleDiscount;
end;
function InfoCashSale.getSubtotal: Currency;
begin
result := self.subTotal;
end;
function InfoCashSale.getTax: Currency;
begin
result := self.tax;
end;
function InfoCashSale.getTotalDue: Currency;
begin
result := self.totalDue;
end;
function InfoCashSale.getTotalSaved: Currency;
begin
result := self.totalSaved;
end;
function InfoCashSale.getTotalStoreAccount: Currency;
begin
result := ftotalToStoreAccount;
end;
procedure InfoCashSale.setItemDiscounts(pValue: Currency);
begin
self.itemDiscounts := pValue;
end;
procedure InfoCashSale.setNewTotalDue(pValue: Currency);
begin
self.newTotalDue := pValue;
end;
procedure InfoCashSale.setNewTotalSaved(pValue: Currency);
begin
self.newTotalSaved := pValue;
end;
procedure InfoCashSale.setOtherCosts(pValue: Currency);
begin
self.otherCosts := pValue;
end;
procedure InfoCashSale.setSaleDiscount(pValue: Currency);
begin
self.saleDiscount := pValue;
end;
procedure InfoCashSale.setSubtotal(pValue: Currency);
begin
self.subTotal := pValue;
end;
procedure InfoCashSale.setTax(pValue: Currency);
begin
self.tax := pValue;
end;
procedure InfoCashSale.setTotalDue(pValue: Currency);
begin
self.totalDue := pValue;
end;
procedure InfoCashSale.setTotalSaved(pValue: Currency);
begin
self.totalSaved := pValue;
end;
procedure InfoCashSale.setTotalStoreAccount(arg_total: Currency);
begin
ftotalToStoreAccount := arg_total
end;
end.
|
unit ProjectView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, VirtualTrees, Project, ImgList, ActiveX, Menus;
type
TProjectForm = class(TForm)
Tree: TVirtualStringTree;
ImageList1: TImageList;
PopupMenu: TPopupMenu;
NewFolderItem: TMenuItem;
RemoveItem: TMenuItem;
AddExistingPageItem: TMenuItem;
NewPageItem: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure TreeInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure TreeInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeDragOver(Sender: TBaseVirtualTree; Source: TObject;
Shift: TShiftState; State: TDragState; Pt: TPoint; Mode: TDropMode;
var Effect: Integer; var Accept: Boolean);
procedure TreeDragDrop(Sender: TBaseVirtualTree; Source: TObject;
DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState;
Pt: TPoint; var Effect: Integer; Mode: TDropMode);
procedure TreeDragAllowed(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var Allowed: Boolean);
procedure PopupMenuPopup(Sender: TObject);
procedure NewFolderItemClick(Sender: TObject);
procedure TreeEditing(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; var Allowed: Boolean);
procedure AddExistingPageItemClick(Sender: TObject);
procedure RemoveItemClick(Sender: TObject);
procedure TreeNewText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; NewText: WideString);
procedure TreeDblClick(Sender: TObject);
procedure NewPageItemClick(Sender: TObject);
procedure TreeCompareNodes(Sender: TBaseVirtualTree; Node1,
Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
private
{ Private declarations }
FProject: TProject;
FOnOpen: TNotifyEvent;
protected
function GetFocusedFolder: TProjectItem;
function GetFocusedItem: TProjectItem;
function GetFolderItem(inNode: PVirtualNode): TProjectItem;
function GetNodeItem(inNode: PVirtualNode): TProjectItem;
function GetNodeItems(inNode: PVirtualNode): TProjectItems;
procedure SetProject(const Value: TProject);
public
{ Public declarations }
procedure BuildTree;
procedure MoveNode(inNode, inTarget: PVirtualNode);
property FocusedItem: TProjectItem read GetFocusedItem;
property OnOpen: TNotifyEvent read FOnOpen write FOnOpen;
property Project: TProject read FProject write SetProject;
end;
implementation
uses
Main;
{$R *.dfm}
{ TProjectItems }
procedure TProjectForm.FormCreate(Sender: TObject);
begin
//
end;
procedure TProjectForm.SetProject(const Value: TProject);
begin
FProject := Value;
BuildTree;
end;
procedure TProjectForm.BuildTree;
begin
Tree.BeginUpdate;
try
Tree.Clear;
if Project = nil then
Tree.RootNodeCount := 0
else
Tree.RootNodeCount := Project.Items.Count;
Tree.FullExpand;
finally
Tree.EndUpdate;
end;
//Tree.SortTree(0, sdAscending);
end;
function TProjectForm.GetNodeItems(inNode: PVirtualNode): TProjectItems;
begin
if (inNode = nil) or (inNode = Tree.RootNode) then
Result := Project.Items
else
Result := TProjectItems(Tree.GetNodeData(inNode)^);
end;
function TProjectForm.GetNodeItem(inNode: PVirtualNode): TProjectItem;
begin
with GetNodeItems(inNode.Parent) do
Result := TProjectItem(Items[inNode.Index])
end;
function TProjectForm.GetFocusedItem: TProjectItem;
begin
Result := GetNodeItem(Tree.FocusedNode);
end;
function TProjectForm.GetFolderItem(inNode: PVirtualNode): TProjectItem;
begin
Result := GetNodeItem(inNode);
if not Result.IsFolder then
Result := GetNodeItem(inNode.Parent);
end;
function TProjectForm.GetFocusedFolder: TProjectItem;
begin
Result := GetFolderItem(Tree.FocusedNode);
end;
procedure TProjectForm.TreeInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
items: TProjectItems;
begin
items := GetNodeItems(ParentNode);
with TProjectItem(items.Items[Node.Index]) do
if IsFolder then
begin
Move(Items, Sender.GetNodeData(Node)^, 4);
Include(InitialStates, ivsHasChildren);
end;
end;
procedure TProjectForm.TreeInitChildren(Sender: TBaseVirtualTree;
Node: PVirtualNode; var ChildCount: Cardinal);
begin
with GetNodeItem(Node) do
ChildCount := Items.Count;
end;
procedure TProjectForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
begin
if (Node.Parent = Sender.RootNode) then
case Column of
0: CellText := ExtractFileName(Project.Filename);
1: CellText := '';
end
else
with GetNodeItem(Node) do
case Column of
0: CellText := ExtractFileName(Filename);
1: if IsFolder then
CellText := ''
else
CellText := ExtractFilePath(Project.ProjectPath(Filename));
end;
end;
procedure TProjectForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
begin
if Column = 0 then
case Kind of
ikNormal, ikSelected:
with GetNodeItem(Node) do
if IsFolder then
ImageIndex := 0
else
ImageIndex := 1;
end;
end;
procedure TProjectForm.TreeCompareNodes(Sender: TBaseVirtualTree; Node1,
Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
begin
Result := CompareText(GetNodeItem(Node1).Filename,
GetNodeItem(Node2).Filename);
end;
procedure TProjectForm.TreeDragOver(Sender: TBaseVirtualTree;
Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint;
Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
begin
Accept := (Tree.DropTargetNode <> nil)
and GetNodeItem(Tree.DropTargetNode).IsFolder
and (Mode = dmOnNode);
end;
procedure TProjectForm.MoveNode(inNode, inTarget: PVirtualNode);
begin
Project.MoveItem(GetNodeItem(inNode), GetNodeItem(inTarget));
end;
procedure TProjectForm.TreeDragDrop(Sender: TBaseVirtualTree;
Source: TObject; DataObject: IDataObject; Formats: TFormatArray;
Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
begin
Effect := DROPEFFECT_NONE;
if Source = Sender then
begin
MoveNode(Tree.FocusedNode, Tree.DropTargetNode);
//BuildTree;
end;
end;
procedure TProjectForm.TreeDragAllowed(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
begin
Allowed := Node.Parent <> Tree.RootNode;
end;
procedure TProjectForm.TreeEditing(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
begin
Allowed := GetNodeItem(Node).IsFolder;
end;
procedure TProjectForm.PopupMenuPopup(Sender: TObject);
begin
if Tree.FocusedNode = nil then
Tree.FocusedNode := Tree.GetFirst;
RemoveItem.Enabled := GetFocusedItem <> Project.Items.Items[0];
end;
procedure TProjectForm.NewFolderItemClick(Sender: TObject);
begin
Project.NewFolder(GetFocusedFolder);
// BuildTree;
end;
procedure TProjectForm.AddExistingPageItemClick(Sender: TObject);
begin
Project.AddExistingPage(GetFocusedFolder);
// BuildTree;
end;
procedure TProjectForm.NewPageItemClick(Sender: TObject);
begin
// Project.AddPage(GetFocusedFolder);
// BuildTree;
end;
procedure TProjectForm.RemoveItemClick(Sender: TObject);
begin
Project.RemoveItem(GetFocusedItem);
// BuildTree;
end;
procedure TProjectForm.TreeNewText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; NewText: WideString);
begin
Project.Rename(GetNodeItem(Node), NewText);
end;
procedure TProjectForm.TreeDblClick(Sender: TObject);
begin
if (Tree.FocusedNode <> nil) and Assigned(OnOpen) then
OnOpen(Self);
end;
end.
|
unit usqlitedao;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, sqlite3conn;
type
{ TSQLiteDAO }
TSQLiteDAO = class
private
FConn: TSQLite3Connection;
FTran: TSQLTransaction;
procedure Exec(ASQL: String);
public
constructor Create(ADatabaseName: String);
destructor Destroy; override;
procedure Write(AFilename, ASheetName, AXML: String);
function ReadXML(AFilename, ASheetName: String): String;
function Count(AFilename: String): Integer;
end;
implementation
uses
db;
{ TSQLiteDAO }
const
CreateSQL = 'CREATE TABLE data (' +
'filename text NOT NULL,' +
'sheetname text NOT NULL,' +
'xml text NOT NULL,' +
'PRIMARY KEY (filename, sheetname));';
WriteSQL = 'REPLACE INTO data (filename, sheetname, xml)' +
'VALUES (''%s'',''%s'',''%s'');';
ReadSQL = 'SELECT xml FROM data WHERE filename = ''%s'' AND sheetname = ''%s'';';
CountSQL = 'SELECT count(*) AS cnt FROM data WHERE filename = ''%s'';';
function DoubleQuotedString(s: String): String;
begin
Result := StringReplace(s, '''', '''''', [rfReplaceAll]);
end;
procedure TSQLiteDAO.Exec(ASQL: String);
begin
FConn.Open;
FTran.Active := True;
FConn.ExecuteDirect(ASQL);
FTran.Commit;
end;
constructor TSQLiteDAO.Create(ADatabaseName: String);
begin
FConn := TSQLite3Connection.Create(Nil);
FConn.DatabaseName := ADatabaseName;
FTran := TSQLTransaction.Create(Nil);
FTran.DataBase := FConn;
if not FileExists(ADatabaseName) then
Exec(CreateSQL)
else
FConn.Open;
end;
destructor TSQLiteDAO.Destroy;
begin
FTran.CloseDataSets;
FTran.Free;
FConn.Close(False);
FConn.Free;
inherited Destroy;
end;
procedure TSQLiteDAO.Write(AFilename, ASheetName, AXML: String);
begin
AFilename := DoubleQuotedString(AFilename);
ASheetName := DoubleQuotedString(ASheetName);
Exec(Format(WriteSQL, [AFilename, ASheetName, AXML]));
end;
function TSQLiteDAO.ReadXML(AFilename, ASheetName: String): String;
var
q: TSQLQuery;
begin
Result := '';
AFilename := DoubleQuotedString(AFilename);
ASheetName := DoubleQuotedString(ASheetName);
q := TSQLQuery.Create(Nil);
try
q.DataBase := FConn;
q.SQL.Text := Format(ReadSQL, [AFilename, ASheetName]);
FTran.Active := True;
q.Open;
if not q.Eof then
Result := q.FieldByName('xml').AsString;
FTran.Commit;
finally
q.Close;
q.Free;
end;
end;
function TSQLiteDAO.Count(AFilename: String): Integer;
var
q: TSQLQuery;
begin
Result := 0;
AFilename := DoubleQuotedString(AFilename);
q := TSQLQuery.Create(Nil);
try
q.DataBase := FConn;
q.SQL.Text := Format(CountSQL, [AFilename]);
FTran.Active := True;
q.Open;
if not q.Eof then
Result := q.FieldByName('cnt').AsInteger;
FTran.Commit;
finally
q.Close;
q.Free;
end;
end;
end.
|
unit Demo.Trendlines.Sample;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Trendlines_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Trendlines_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_SCATTER_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Diameter'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Age')
]);
Chart.Data.AddRow([8, 37]);
Chart.Data.AddRow([4, 19.5]);
Chart.Data.AddRow([11, 52]);
Chart.Data.AddRow([4, 22]);
Chart.Data.AddRow([3, 16.5]);
Chart.Data.AddRow([6.5, 32.8]);
Chart.Data.AddRow([14, 72]);
// Options
Chart.Options.Title('Age of sugar maples vs. trunk diameter, in inches');
Chart.Options.HAxis('title', 'Diameter');
Chart.Options.VAxis('title', 'Age');
Chart.Options.Legend('position', 'none');
Chart.Options.TrendLines(['0: {}']); // Draw a trendline for data series 0.
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="chart_div" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('chart_div', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Trendlines_Sample);
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0067.PAS
Description: Totally Erased files
Author: DAVID DRZYZGA
Date: 11-26-94 05:03
*)
Program Zap;
Procedure ZapIt(FileName : String; Pattern : Char; LastPass : Boolean);
Var
NumRead,
NumWritten : Word;
Buffer : Array[1..4096] Of Char;
BufferSize : Word;
ZapFile : File;
ZapFilePos : LongInt;
Begin
BufferSize := SizeOf(Buffer);
Assign(ZapFile, FileName);
{$I-} Reset(ZapFile, 1); {$I+}
If IOResult <> 0 Then Begin
WriteLn('File not found');
Halt;
end;
Repeat
ZapFilePos := FilePos(ZapFile);
BlockRead(ZapFile, Buffer, BufferSize, NumRead);
FillChar(Buffer, BufferSize, Pattern);
Seek(ZapFile, ZapFilePos);
BlockWrite(ZapFile, Buffer, NumRead, NumWritten);
Until (NumRead = 0) Or (NumWritten <> NumRead);
Close(ZapFile);
if LastPass Then Erase(ZapFile);
End;
begin
ZapIt(ParamStr(1), #005, False); {0101}
ZapIt(ParamStr(1), #010, False); {1010}
ZapIt(ParamStr(1), #000, False); {0000}
ZapIt(ParamStr(1), #255, True ); {1111}
end.
{
Here's the comments for the above procedure:
Get the buffer size for later use
Get the file name from the first command line parameter
Try to open the file
If there was an error opening file, show the user and exit
otherwise repeat this code
Save the current file position
Read a block of data from the file into a buffer
Fill buffer with specified bit pattern
Reset file position to where we read this block from and
write the block back to the file
until we're done or there was a conflict in the read/write size
close the file
delete the file from disk if it's the last pass
}
|
unit SDUSpin64Units;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SDUFrames, StdCtrls, Spin64,
SDUGeneral;
type
TSDUSpin64Unit = class(TSDUFrame)
se64Value: TSpinEdit64;
cbUnits: TComboBox;
procedure se64ValueChange(Sender: TObject);
procedure cbUnitsChange(Sender: TObject);
private
FOnChange: TNotifyEvent;
FMultiplier: integer;
FReadOnly: boolean;
protected
procedure DoShow(); override;
procedure DoChange();
function GetPrettyValue(): string;
function GetValue(): int64;
procedure SetValue(val: int64);
function GetUnits(): TStrings;
procedure SetUnits(units: TStrings);
function GetMaxLength(): integer;
procedure SetMaxLength(val: integer);
function GetMaxValue(): int64;
procedure SetMaxValue(val: int64);
function GetMinValue(): int64;
procedure SetMinValue(val: int64);
function GetSelectedUnits: string;
procedure SetSelectedUnits(selUnits: string);
function GetMultiplier(): integer;
procedure SetMultiplier(mult: integer);
procedure SetReadOnly(ro: boolean);
public
constructor Create(AOwner: TComponent); override;
published
property Units: TStrings read GetUnits write SetUnits;
property Multiplier: integer read GetMultiplier write SetMultiplier default 1000;
property SelectedUnits: string read GetSelectedUnits write SetSelectedUnits;
property MaxLength: integer read GetMaxLength write SetMaxLength;
property MaxValue: int64 read GetMaxValue write SetMaxValue;
property MinValue: int64 read GetMinValue write SetMinValue;
property Value: int64 read GetValue write SetValue;
property PrettyValue: string read GetPrettyValue;
property ReadOnly: boolean read FReadOnly write SetReadOnly;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TSDUSpin64Unit_Storage = class(TSDUSpin64Unit)
public
constructor Create(AOwner: TComponent); override;
published
property Multiplier: integer read GetMultiplier write SetMultiplier default 1024;
end;
procedure Register;
implementation
{$R *.dfm}
procedure Register;
begin
RegisterComponents('SDeanUtils', [TSDUSpin64Unit]);
RegisterComponents('SDeanUtils', [TSDUSpin64Unit_Storage]);
end;
constructor TSDUSpin64Unit.Create(AOwner: TComponent);
begin
inherited;
Multiplier := 1000;
ReadOnly := FALSE;
end;
function TSDUSpin64Unit.GetUnits(): TStrings;
begin
Result := cbUnits.Items;
end;
procedure TSDUSpin64Unit.SetUnits(units: TStrings);
begin
cbUnits.Items.Assign(units);
// Select first unit
if (units.count = 0) then
begin
cbUnits.ItemIndex := -1;
end
else
begin
cbUnits.ItemIndex := 0;
end;
end;
procedure TSDUSpin64Unit.cbUnitsChange(Sender: TObject);
begin
inherited;
DoChange();
end;
procedure TSDUSpin64Unit.DoShow();
begin
se64Value.left := 0;
se64Value.top := 0;
cbUnits.top := 0;
self.height := se64Value.height;
inherited;
end;
procedure TSDUSpin64Unit.se64ValueChange(Sender: TObject);
begin
inherited;
DoChange();
end;
procedure TSDUSpin64Unit.DoChange();
begin
if Assigned(FOnChange) then
FOnChange(self);
end;
function TSDUSpin64Unit.GetValue(): int64;
var
i: integer;
i64Multiplier: int64;
begin
Result := se64Value.Value;
// Use int64 to store multiplier, so Delphi doesn't cast int64s as integer
i64Multiplier:= FMultiplier;
// Start from 1 - we don't divide by 1000 on the single units
for i:=1 to cbUnits.ItemIndex do
Result := Result * i64Multiplier;
end;
procedure TSDUSpin64Unit.SetValue(val: int64);
var
i: integer;
i64Zero: int64;
i64Multiplier: int64;
unitsIdx: integer;
useValue: int64;
begin
// Use int64 to store multiplier, so Delphi doesn't cast int64s as integer
i64Multiplier:= FMultiplier;
// Use int64 to store 0, so Delphi doesn't cast int64s as integer
i64Zero := 0;
unitsIdx := 0;
useValue := val;
if (val <> i64Zero) then begin
// Start from 1 - we don't divide by 1000 on the last one
for i:=1 to (cbUnits.Items.Count - 1) do begin
if ((useValue mod i64Multiplier) <> i64Zero) then begin
break
end;
unitsIdx := i;
useValue := (useValue div i64Multiplier);
end;
end;
se64Value.Value := useValue;
cbUnits.ItemIndex := unitsIdx;
end;
function TSDUSpin64Unit.GetMaxLength(): integer;
begin
Result := se64Value.MaxLength;
end;
procedure TSDUSpin64Unit.SetMaxLength(val: integer);
begin
se64Value.MaxLength := val
end;
function TSDUSpin64Unit.GetMinValue(): int64;
begin
Result := se64Value.MinValue;
end;
procedure TSDUSpin64Unit.SetMinValue(val: int64);
begin
se64Value.MinValue := val
end;
function TSDUSpin64Unit.GetMaxValue(): int64;
begin
Result := se64Value.MaxValue;
end;
procedure TSDUSpin64Unit.SetMaxValue(val: int64);
begin
se64Value.MaxValue := val
end;
function TSDUSpin64Unit.GetSelectedUnits: string;
begin
Result := cbUnits.Items[cbUnits.ItemIndex];
end;
procedure TSDUSpin64Unit.SetSelectedUnits(selUnits: string);
begin
cbUnits.ItemIndex := cbUnits.items.IndexOf(selUnits);
end;
function TSDUSpin64Unit.GetMultiplier(): integer;
begin
Result := FMultiplier;
end;
procedure TSDUSpin64Unit.SetMultiplier(mult: integer);
begin
FMultiplier := mult;
end;
function TSDUSpin64Unit.GetPrettyValue(): string;
begin
Result := inttostr(se64Value.Value) + ' ' + SelectedUnits;
end;
procedure TSDUSpin64Unit.SetReadOnly(ro: boolean);
begin
inherited;
FReadOnly:= ro;
SDUReadonlyControl(se64Value, FReadOnly);
SDUReadonlyControl(cbUnits, FReadOnly);
end;
constructor TSDUSpin64Unit_Storage.Create(AOwner: TComponent);
var
stlTmp: TStringList;
i: TUnits_Storage;
begin
inherited;
Multiplier := UNITS_BYTES_MULTIPLIER;
stlTmp:= TStringList.Create();
try
for i:=low(i) to high(i) do
begin
stlTmp.Add(SDUUnitsStorageToText(i));
end;
Units := stlTmp;
finally
stlTmp.Free();
end;
end;
// ============================================================================
// ============================================================================
// ============================================================================
END.
|
{..............................................................................}
{ Summary Deleting Schematic Objects and Updating the Undo System }
{ Use of the RobotManager interface to send schematic messages }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure DeleteSchObjects;
Var
OldPort : ISch_Port;
Port : ISch_Port;
CurrentSheet : ISch_Document;
Iterator : ISch_Iterator;
Begin
// Obtain the schematic server interface.
If SchServer = Nil Then Exit;
// Then obtain the current schematic sheet interface.
CurrentSheet := SchServer.GetCurrentSchDocument;
If CurrentSheet = Nil Then Exit;
// Initialize the robots in Schematic editor.
SchServer.ProcessControl.PreProcess(CurrentSheet, '');
// Set up iterator to look for Port objects only
Iterator := CurrentSheet.SchIterator_Create;
If Iterator = Nil Then Exit;
Iterator.AddFilter_ObjectSet(MkSet(ePort));
Try
Port := Iterator.FirstSchObject;
While Port <> Nil Do
Begin
OldPort := Port;
Port := Iterator.NextSchObject;
CurrentSheet.RemoveSchObject(OldPort);
SchServer.RobotManager.SendMessage(CurrentSheet.I_ObjectAddress,c_BroadCast,
SCHM_PrimitiveRegistration,OldPort.I_ObjectAddress);
End;
Finally
CurrentSheet.SchIterator_Destroy(Iterator);
End;
// Clean up robots in Schematic editor.
SchServer.ProcessControl.PostProcess(CurrentSheet, '');
// Refresh the screen
CurrentSheet.GraphicallyInvalidate;
End;
{..............................................................................}
{..............................................................................}
|
PROGRAM bintree;
TYPE
Node = ^NodeRec;
NodeRec = RECORD
value: INTEGER;
left, right: Node;
END;
Tree = Node;
PROCEDURE InitTree (VAR t: Tree);
BEGIN
t:= NIL;
END;
FUNCTION NewNode (value: INTEGER): Node;
VAR
n: Node;
BEGIN
New(n);
n^.value := value;
n^.left := NIL;
n^.right := NIL;
NewNode := n;
END;
PROCEDURE InsertNode( VAR t: tree; n: Node);
VAR
subtree, parent: Node;
BEGIN
IF t = NIL THEN BEGIN
t := n;
END
ELSE BEGIN
parent := NIL;
subtree := t;
WHILE subtree <> NIL DO BEGIN
parent := subtree;
IF n^.value < subtree^.value THEN BEGIN
subtree := subtree^.left;
END
ELSE (*n^.value >= subtree^.value*)
subtree := subtree^.right;
END;
IF n^.value < parent^.value THEN
parent^.left := n
ELSE
parent^.right := n;
END;
END;
PROCEDURE InsertRec (VAR t: Tree; n: Node);
BEGIN
IF t= NIL THEN BEGIN
t := n;
END
ELSE BEGIN
IF n^.value < t^.value THEN
InsertRec(t^.left, n)
ELSE
InsertRec(t^.right, n)
END;
END;
PROCEDURE WriteTreeInOrder (t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
WriteTreeInOrder(t^.left);
WriteLn(t^.value);
WriteTreeInOrder(t^.right);
END;
END;
PROCEDURE WriteTreePreOrder (t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
WriteLn(t^.value);
WriteTreePreOrder(t^.left);
WriteTreePreOrder(t^.right);
END;
END;
PROCEDURE WriteTreePostOrder (t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
WriteTreePostOrder(t^.left);
WriteTreePostOrder(t^.right);
WriteLn(t^.value);
END;
END;
FUNCTION Height(t: Tree) : INTEGER;
VAR
hl, hr: INTEGER;
BEGIN
IF t = NIL THEN
Height := 0
ELSE BEGIN
hl := Height (t^.left);
hr := Height (t^.right);
IF hl > hr THEN
Height := 1 + hl
ELSE
Height := 1 + hr;
END;
END;
PROCEDURE Remove (VAR t: Tree; value: INTEGER);
VAR
n, nPar: Node;
st: Node; (*subtree*)
succ, succPar: Node;
BEGIN
nPar := NIL;
n := t;
WHILE (n <> NIL) AND (n^.value <> value) DO BEGIN
nPar := n;
IF value < n^.value THEN
n := n^.left
ELSE
n := n^.right;
END;
IF n <> NIL THEN BEGIN (*kein Rechter Teilbaum*)
IF n^.right = NIL THEN BEGIN
st := n^.left;
END
ELSE BEGIN
IF n^.right^.left = NIL THEN BEGIN (*rechter Teilbaum, aber kein linker Nachfolger davon*)
st := n^.right;
st^.left := n^.left;
END
ELSE BEGIN
(*common case*)
succPar := NIL;
succ := n^.right;
WHILE succ^.left <> NIL DO BEGIN
succPar := succ;
succ := succ^.left;
END;
succPar^.left := succ^.right;
st := succ;
st^.left := n^.left;
st^.right := n^.right;
END;
END;
(*insert the new sub-tree*)
IF nPar = NIL THEN
t := st
ELSE IF n^.value < nPar^.value THEN
nPar^.left := st
ELSE
nPar^.right := st;
Dispose(n);
END; (*n<> NIL*)
END;
PROCEDURE FindValuePreOrder (t: Tree; val : INTEGER);
BEGIN
IF t <> NIL THEN BEGIN
IF val = t^.value THEN
WriteLn('Found');
FindValuePreOrder(t^.left, val);
FindValuePreOrder(t^.right, val);
END;
END;
PROCEDURE RemoveValuePreOrder (t,t_temp: Tree; val : INTEGER);
BEGIN
IF t <> NIL THEN BEGIN
IF (t^.value = val) THEN
BEGIN
WriteLn('t: ',t^.value);
WriteLn('ttemp: ',t_temp^.value, ' ', t_temp^.left^.value, ' ',t_temp^.right^.value);
IF val >= t_temp^.value THEN
BEGIN
IF t^.right <> NIL THEN
t_temp^.right := t^.right
ELSE IF t^.left <> NIL THEN
t_temp^.right := t^.left
ELSE
t_temp^.right := NIL;
END
ELSE
BEGIN
IF t^.right <> NIL THEN
t_temp^.left := t^.right
ELSE IF t^.left <> NIL THEN
t_temp^.left := t^.left
ELSE
t_temp^.right := NIL;
END;
t^.left := NIL;
t^.right := NIL;
Dispose(t);
END;
t_temp := t;
IF val < t^.value THEN
RemoveValuePreOrder(t^.left, t_temp, val)
ELSE
RemoveValuePreOrder(t^.right, t_temp, val);
END;
END;
(* amount of value in tree *)
FUNCTION AmountOf(t : Tree; val : INTEGER) : INTEGER;
VAR
amount : INTEGER;
BEGIN
amount := 0;
IF t = NIL THEN BEGIN
AmountOf := amount;
END
ELSE IF t^.value = val THEN BEGIN
amount := AmountOf(t^.right, val) + 1;
END
ELSE IF t^.value > val THEN BEGIN
amount := AmountOf(t^.left, val);
END
ELSE IF t^.value < val THEN BEGIN
amount := AmountOf(t^.right, val);
END;
AmountOf := amount;
END;
FUNCTION ContainsVal(t : Tree; val : INTEGER) : BOOLEAN;
BEGIN
IF t = NIL THEN BEGIN
ContainsVal := false;
END
ELSE IF t^.value = val THEN BEGIN
ContainsVal := true;
END
ELSE IF val < t^.value THEN BEGIN
ContainsVal := ContainsVal(t^.left, val);
END
ELSE BEGIN
ContainsVal := ContainsVal(t^.right, val);
END;
END;
FUNCTION IsSorted(t : Tree) : BOOLEAN;
VAR b : BOOLEAN;
BEGIN
b := true;
IF t <> NIL THEN BEGIN
b := IsSorted(t^.left) AND IsSorted(t^.right);
IF t^.left <> NIL THEN BEGIN
b := b AND (t^.left^.value < t^.value);
END;
IF t^.right <> NIL THEN BEGIN
b := b AND (t^.right^.value >= t^.value);
END;
END;
ISSorted := b;
END;
PROCEDURE DisposeTree(VAR t: Tree);
BEGIN
IF t <> NIL THEN BEGIN
DisposeTree(t^.left);
DisposeTree(t^.right);
Dispose(t);
t := NIL;
END;
END;
VAR
t,t_temp: Tree;
BEGIN
InitTree(t);
InitTree(t_temp);
InsertNode(t,NewNode(14));
InsertNode(t,NewNode(5));
InsertNode(t,NewNode(5));
InsertNode(t,NewNode(20));
InsertRec(t, NewNode(12));
InsertRec(t, NewNode(11));
InsertRec(t, NewNode(3));
InsertRec(t, NewNode(25));
InsertNode(t,NewNode(5));
// WriteLn('-InOrder-');
// WriteTreeInOrder(t);
// Remove(t, 11);
// WriteLn('Removed 11 ---------');
// WriteLn('-PreOrder-');
// WriteTreePreOrder(t);
// WriteLn('-PostOrder-');
// WriteTreePostOrder(t);
// WriteLn('-----------------------');
// WriteLn('Height= ', Height(t));
// DisposeTree(t);
// WriteLn('-----------------------');
// WriteTreePostOrder(t);
//Wurzelknoten removen geht nicht
//RemoveValuePreOrder(t,t_temp,5);
WriteLn('Found: ', AmountOf(t, 5));
//WriteTreeInOrder(t);
DisposeTree(t);
END. |
unit uDMClient;
interface
uses
System.SysUtils, System.Classes, IPPeerClient, Datasnap.DSClientRest, uClientClasses,
System.ImageList, Vcl.ImgList, Vcl.Controls, uDBUtils, Data.DB,
Datasnap.DBClient, cxStyles, cxClasses;
type
TDMClient = class(TDataModule)
cxStyle: TcxStyleRepository;
cxStyleBold: TcxStyle;
cxStyleGridEven: TcxStyle;
cxStyleGridHeader: TcxStyle;
cxStyleInfoBK: TcxStyle;
cxStyleMaroon: TcxStyle;
cxStyleMoneyGreen: TcxStyle;
cxStyleSkyBlue: TcxStyle;
cxStyleTabGrid: TcxStyle;
cxStyleTabGridBg: TcxStyle;
ilImage24: TImageList;
imgListButton: TImageList;
imgListIcon: TImageList;
RestConn: TDSRestConnection;
procedure DataModuleCreate(Sender: TObject);
private
FCrudAdjFakClient: TCrudAdjFakturClient;
FCrudBankCashOutClient: TCrudBankCashOutClient;
FCrudDOTraderClient: TCRUDDOTraderClient;
FCRUDPOSClient: TCRUDPosClient;
FCrudBarangHargaJualClient: TCrudBarangHargaJualClient;
FCrudClaimFakturClient: TCRUDClaimFakturClient;
FCrudBarangClient: TCrudBarangClient;
FCrudBankCashInClient: TCrudBankCashInClient;
FCrudClient: TCrudClient;
FCrudCNClient: TCrudCNRecvClient;
FCrudContrabonSalesClient: TCrudContrabonSalesClient;
FCrudCustomerInvoiceClient: TCrudCustomerInvoiceClient;
FCrudDNClient: TCrudDNRecvClient;
FCrudDOClient: TCrudDOClient;
FCrudKuponBotolClient: TCrudKuponBotolClient;
FCrudPOClient: TCrudPOClient;
FCrudSettingAppClient: TCrudSettingAppClient;
FCrudSupplierClient: TCrudSupplierClient;
FCRUDJurnalClient: TCRUDJurnalClient;
FPOSClient: TPOSClient;
FCrudUpdatePOSClient: TCrudUpdatePOSClient;
FDSProviderClient: TDSProviderClient;
FInstanceOwner: Boolean;
FCrudCrazyPriceClient: TCrudCrazyPriceClient;
FCRUDTransferBarangClient: TCRUDTransferBarangClient;
FCrudPOTraderClient: TCrudPOTraderClient;
FCRUDBarcodeRequest: TCRUDBarcodeRequestClient;
FCRUDBarcodeUsageClient: TCRUDBarcodeUsageClient;
FCrudReturTraderClient: TCRUDReturTraderClient;
function GetCrudAdjFakClient: TCrudAdjFakturClient;
function GetCrudBankCashOutClient: TCrudBankCashOutClient;
function GetCrudDOTraderClient: TCRUDDOTraderClient;
function GetCRUDPOSClient: TCRUDPosClient;
function GetCrudBarangHargaJualClient: TCrudBarangHargaJualClient;
function GetCrudClaimFakturClient: TCRUDClaimFakturClient;
function GetCrudBarangClient: TCrudBarangClient;
function GetCrudBankCashInClient: TCrudBankCashInClient;
function GetCrudClient: TCrudClient;
function GetCrudCNClient: TCrudCNRecvClient;
function GetCrudContrabonSalesClient: TCrudContrabonSalesClient;
function GetCrudCustomerInvoiceClient: TCrudCustomerInvoiceClient;
function GetCrudDNClient: TCrudDNRecvClient;
function GetCrudDOClient: TCrudDOClient;
function GetCrudKuponBotolClient: TCrudKuponBotolClient;
function GetCrudPOClient: TCrudPOClient;
function GetCrudSettingAppClient: TCrudSettingAppClient;
function GetCrudSupplierClient: TCrudSupplierClient;
function GetCRUDJurnalClient: TCRUDJurnalClient;
function GetPOSClient: TPOSClient;
function GetCrudUpdatePOSClient: TCrudUpdatePOSClient;
function GetDSProviderClient: TDSProviderClient;
function GetInstanceOwner: Boolean;
function GetCrudCrazyPriceClient: TCrudCrazyPriceClient;
function GetCRUDTransferBarangClient: TCRUDTransferBarangClient;
function GetCrudPOTraderClient: TCrudPOTraderClient;
function GetCRUDBarcodeRequest: TCRUDBarcodeRequestClient;
function GetCRUDBarcodeUsageClient: TCRUDBarcodeUsageClient;
function GetCrudReturTraderClient: TCRUDReturTraderClient;
property InstanceOwner: Boolean read GetInstanceOwner write FInstanceOwner;
public
property CrudAdjFakClient: TCrudAdjFakturClient read GetCrudAdjFakClient write
FCrudAdjFakClient;
property CrudBankCashOutClient: TCrudBankCashOutClient read
GetCrudBankCashOutClient write FCrudBankCashOutClient;
property CrudDOTraderClient: TCRUDDOTraderClient read GetCrudDOTraderClient
write FCrudDOTraderClient;
property CRUDPOSClient: TCRUDPosClient read GetCRUDPOSClient write
FCRUDPOSClient;
property CrudBarangHargaJualClient: TCrudBarangHargaJualClient read
GetCrudBarangHargaJualClient write FCrudBarangHargaJualClient;
property CrudClaimFakturClient: TCRUDClaimFakturClient read
GetCrudClaimFakturClient write FCrudClaimFakturClient;
property CrudBarangClient: TCrudBarangClient read GetCrudBarangClient write
FCrudBarangClient;
property CrudBankCashInClient: TCrudBankCashInClient read
GetCrudBankCashInClient write FCrudBankCashInClient;
property CrudClient: TCrudClient read GetCrudClient write FCrudClient;
property CrudCNClient: TCrudCNRecvClient read GetCrudCNClient write
FCrudCNClient;
property CrudContrabonSalesClient: TCrudContrabonSalesClient read
GetCrudContrabonSalesClient write FCrudContrabonSalesClient;
property CrudCustomerInvoiceClient: TCrudCustomerInvoiceClient read
GetCrudCustomerInvoiceClient write FCrudCustomerInvoiceClient;
property CrudDNClient: TCrudDNRecvClient read GetCrudDNClient write
FCrudDNClient;
property CrudDOClient: TCrudDOClient read GetCrudDOClient write FCrudDOClient;
property CrudKuponBotolClient: TCrudKuponBotolClient read
GetCrudKuponBotolClient write FCrudKuponBotolClient;
property CrudPOClient: TCrudPOClient read GetCrudPOClient write FCrudPOClient;
property CrudSettingAppClient: TCrudSettingAppClient read
GetCrudSettingAppClient write FCrudSettingAppClient;
property CrudSupplierClient: TCrudSupplierClient read GetCrudSupplierClient
write FCrudSupplierClient;
property CRUDJurnalClient: TCRUDJurnalClient read GetCRUDJurnalClient write
FCRUDJurnalClient;
property POSClient: TPOSClient read GetPOSClient write FPOSClient;
property CrudUpdatePOSClient: TCrudUpdatePOSClient read GetCrudUpdatePOSClient
write FCrudUpdatePOSClient;
property DSProviderClient: TDSProviderClient read GetDSProviderClient write
FDSProviderClient;
property CrudCrazyPriceClient: TCrudCrazyPriceClient read
GetCrudCrazyPriceClient write FCrudCrazyPriceClient;
property CRUDTransferBarangClient: TCRUDTransferBarangClient read
GetCRUDTransferBarangClient write FCRUDTransferBarangClient;
property CrudPOTraderClient: TCrudPOTraderClient read GetCrudPOTraderClient
write FCrudPOTraderClient;
property CRUDBarcodeRequest: TCRUDBarcodeRequestClient read
GetCRUDBarcodeRequest write FCRUDBarcodeRequest;
property CRUDBarcodeUsageClient: TCRUDBarcodeUsageClient read
GetCRUDBarcodeUsageClient write FCRUDBarcodeUsageClient;
property CrudReturTraderClient: TCRUDReturTraderClient read
GetCrudReturTraderClient write FCrudReturTraderClient;
end;
ERestClientError = class(Exception)
private
FSrcExceptClass: String;
public
constructor Create(E: Exception);
property SrcExceptClass: String read FSrcExceptClass write FSrcExceptClass;
end;
procedure RestClientError(E: Exception);
function ToCDS(aDataSet: TDataSet; AOwner: TComponent = nil): TClientDataSet;
var
DMClient: TDMClient;
implementation
uses
Datasnap.DSHTTPClient, Dialogs,uAppUtils;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure RestClientError(E: Exception);
begin
Raise ERestClientError.Create(E);
end;
function ToCDS(aDataSet: TDataSet; AOwner: TComponent = nil): TClientDataSet;
begin
Result := TDBUtils.DSToCDS(ADataSet, AOwner);
end;
constructor ERestClientError.Create(E: Exception);
var
Msg: string;
begin
Msg := E.Message;
if E is EHTTPProtocolException then
Msg := Msg + #13 + EHTTPProtocolException(E).ErrorMessage;
SrcExceptClass := E.ClassName;
inherited Create(Msg);
end;
procedure TDMClient.DataModuleCreate(Sender: TObject);
var
lPort: Integer;
begin
//set true akan menyebabkan ada expired time di client
//kecuali butuh _cache
lPort := 8080;
TryStrToInt(TAppUtils.BacaRegistry('port'), lPort);
RestConn.Host := TAppUtils.BacaRegistry('server');
RestConn.Port := lPort;
RestConn.UserName := TAppUtils.BacaRegistry('user');
RestConn.Password := TAppUtils.BacaRegistry('password');
RestConn.PreserveSessionID := False;
end;
function TDMClient.GetCrudAdjFakClient: TCrudAdjFakturClient;
begin
if FCrudAdjFakClient <> nil then
FreeAndNil(FCrudAdjFakClient);
FCrudAdjFakClient := TCrudAdjFakturClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudAdjFakClient;
end;
function TDMClient.GetCrudBankCashOutClient: TCrudBankCashOutClient;
begin
if FCrudBankCashOutClient <> nil then
FreeAndNil(FCrudBankCashOutClient);
FCrudBankCashOutClient := TCrudBankCashOutClient.Create(RestConn, InstanceOwner);
Result := FCrudBankCashOutClient;
end;
function TDMClient.GetCrudDOTraderClient: TCRUDDOTraderClient;
begin
if FCrudDOTraderClient <> nil then
FreeAndNil(FCrudDOTraderClient);
FCrudDOTraderClient := TCRUDDOTraderClient.Create(RestConn, InstanceOwner);
Result := FCrudDOTraderClient;
end;
function TDMClient.GetCRUDPOSClient: TCRUDPosClient;
begin
if FCRUDPOSClient <> nil then
FreeAndNil(FCRUDPOSClient);
FCRUDPOSClient := TCRUDPosClient.Create(RestConn, InstanceOwner);
Result := FCRUDPOSClient;
end;
function TDMClient.GetCrudBarangHargaJualClient: TCrudBarangHargaJualClient;
begin
if FCrudBarangHargaJualClient <> nil then
FreeAndNil(FCrudBarangHargaJualClient);
FCrudBarangHargaJualClient := TCrudBarangHargaJualClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudBarangHargaJualClient;
end;
function TDMClient.GetCrudClaimFakturClient: TCRUDClaimFakturClient;
begin
if FCrudClaimFakturClient <> nil then
FreeAndNil(FCrudClaimFakturClient);
FCrudClaimFakturClient := TCRUDClaimFakturClient.Create(DMClient.RestConn,InstanceOwner);
Result := FCrudClaimFakturClient;
end;
function TDMClient.GetCrudBarangClient: TCrudBarangClient;
begin
if FCrudBarangClient <> nil then
FreeAndNil(FCrudBarangClient);
FCrudBarangClient := TCrudBarangClient.Create(DMClient.RestConn,InstanceOwner);
Result := FCrudBarangClient;
end;
function TDMClient.GetCrudBankCashInClient: TCrudBankCashInClient;
begin
if FCrudBankCashInClient <> nil then
FreeAndNil(FCrudBankCashInClient);
FCrudBankCashInClient := TCrudBankCashInClient.Create(DMClient.RestConn,InstanceOwner);
Result := FCrudBankCashInClient;
end;
function TDMClient.GetCrudClient: TCrudClient;
begin
if FCrudClient <> nil then
FreeAndNil(FCrudClient);
FCrudClient := TCrudClient.Create(RestConn, InstanceOwner);
Result := FCrudClient;
end;
function TDMClient.GetCrudCNClient: TCrudCNRecvClient;
begin
if FCrudCNClient <> nil then
FreeAndNil(FCrudCNClient);
FCrudCNClient := TCrudCNRecvClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudCNClient;
end;
function TDMClient.GetCrudContrabonSalesClient: TCrudContrabonSalesClient;
begin
if FCrudContrabonSalesClient <> nil then
FreeAndNil(FCrudContrabonSalesClient);
FCrudContrabonSalesClient := TCrudContrabonSalesClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudContrabonSalesClient;
end;
function TDMClient.GetCrudCustomerInvoiceClient: TCrudCustomerInvoiceClient;
begin
if FCrudCustomerInvoiceClient = nil then
FreeAndNil(FCrudCustomerInvoiceClient);
FCrudCustomerInvoiceClient := TCrudCustomerInvoiceClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudCustomerInvoiceClient;
end;
function TDMClient.GetCrudDNClient: TCrudDNRecvClient;
begin
if FCrudDNClient <> nil then
FreeAndNil(FCrudDNClient);
FCrudDNClient := TCrudDNRecvClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudDNClient;
end;
function TDMClient.GetCrudDOClient: TCrudDOClient;
begin
if FCrudDOClient <> nil then
FreeAndNil(FCrudDOClient);
FCrudDOClient := TCrudDOClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudDOClient;
end;
function TDMClient.GetCrudKuponBotolClient: TCrudKuponBotolClient;
begin
if FCrudKuponBotolClient <> nil then
FreeAndNil(FCrudKuponBotolClient);
FCrudKuponBotolClient := TCrudKuponBotolClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudKuponBotolClient;
end;
function TDMClient.GetCrudPOClient: TCrudPOClient;
begin
if FCrudPOClient <> nil then
FreeAndNil(FCrudPOClient);
FCrudPOClient := TCrudPOClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudPOClient;
end;
function TDMClient.GetCrudSettingAppClient: TCrudSettingAppClient;
begin
if FCrudSettingAppClient <> nil then
FreeAndNil(FCrudSettingAppClient);
FCrudSettingAppClient := TCrudSettingAppClient.Create(RestConn, InstanceOwner);
Result := FCrudSettingAppClient;
end;
function TDMClient.GetCrudSupplierClient: TCrudSupplierClient;
begin
if FCrudSupplierClient <> nil then
FreeAndNil(FCrudSupplierClient);
FCrudSupplierClient := TCrudSupplierClient.Create(RestConn, InstanceOwner);
Result := FCrudSupplierClient;
end;
function TDMClient.GetCRUDJurnalClient: TCRUDJurnalClient;
begin
if FCRUDJurnalClient <> nil then
FreeAndNil(FCRUDJurnalClient);
FCRUDJurnalClient := TCRUDJurnalClient.Create(RestConn, InstanceOwner);
Result := FCRUDJurnalClient;
end;
function TDMClient.GetPOSClient: TPOSClient;
begin
if FPOSClient <> nil then
FreeAndNil(FPOSClient);
FPOSClient := TPOSCLient.Create(RestConn, InstanceOwner);
Result := FPOSClient;
end;
function TDMClient.GetCrudUpdatePOSClient: TCrudUpdatePOSClient;
begin
if FCrudUpdatePOSClient <> nil then
FreeAndNil(FCrudUpdatePOSClient);
FCrudUpdatePOSClient := TCrudUpdatePOSClient.Create(DMClient.RestConn, InstanceOwner);
Result := FCrudUpdatePOSClient;
end;
function TDMClient.GetDSProviderClient: TDSProviderClient;
begin
if FDSProviderClient <> nil then
FreeAndNil(FDSProviderClient);
FDSProviderClient := TDSProviderClient.Create(RestConn, InstanceOwner);
Result := FDSProviderClient;
end;
function TDMClient.GetInstanceOwner: Boolean;
begin
FInstanceOwner := False;
Result := FInstanceOwner;
end;
function TDMClient.GetCrudCrazyPriceClient: TCrudCrazyPriceClient;
begin
if FCrudCrazyPriceClient <> nil then
FreeAndNil(FCrudCrazyPriceClient);
FCrudCrazyPriceClient := TCrudCrazyPriceClient.Create(RestConn, InstanceOwner);
Result := FCrudCrazyPriceClient;
end;
function TDMClient.GetCRUDTransferBarangClient: TCRUDTransferBarangClient;
begin
if FCRUDTransferBarangClient <> nil then
FreeAndNil(FCRUDTransferBarangClient);
FCRUDTransferBarangClient := TCRUDTransferBarangClient.Create(RestConn, InstanceOwner);
Result := FCRUDTransferBarangClient;
end;
function TDMClient.GetCrudPOTraderClient: TCrudPOTraderClient;
begin
if FCrudPOTraderClient <> nil then
FreeAndNil(FCrudPOTraderClient);
FCrudPOTraderClient := TCrudPOTraderClient.Create(RestConn, InstanceOwner);
Result := FCrudPOTraderClient;
end;
function TDMClient.GetCRUDBarcodeRequest: TCRUDBarcodeRequestClient;
begin
if FCRUDBarcodeRequest <> nil then
FreeAndNil(FCRUDBarcodeRequest);
FCRUDBarcodeRequest := TCRUDBarcodeRequestClient.Create(RestConn, InstanceOwner);
Result := FCRUDBarcodeRequest;
end;
function TDMClient.GetCRUDBarcodeUsageClient: TCRUDBarcodeUsageClient;
begin
if FCRUDBarcodeUsageClient <> nil then
FreeAndNil(FCRUDBarcodeUsageClient);
FCRUDBarcodeUsageClient := TCRUDBarcodeUsageClient.Create(RestConn, InstanceOwner);
Result := FCRUDBarcodeUsageClient;
end;
function TDMClient.GetCrudReturTraderClient: TCRUDReturTraderClient;
begin
if FCrudReturTraderClient <> nil then
FreeAndNil(FCrudReturTraderClient);
FCrudReturTraderClient := TCRUDReturTraderClient.Create(RestConn, InstanceOwner);
Result := FCrudReturTraderClient;
end;
end.
|
unit SIDConvTypes;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
Classes, Generics.Collections, SysUtils, SyncObjs;
type
TSIDConvCompFmt = (scfFormat0, scfFormat1, scfDetermine, scfDumpOnly);
TSIDConvCompType = (sctNone, sctDeflate, sctLZMA);
TSIDPlayEndType = (speLoop, speOverlap, speFadeOut);
TSIDPlayLenType = (splUnknown, splDefault, splEstimated, splClosestSeconds,
splAccurate);
PSIDPlayDetailRec = ^TSIDPlayDetailRec;
TSIDPlayDetailRec = record
time: TTime;
endType: TSIDPlayEndType;
lenType: TSIDPlayLenType;
end;
TSIDPlayMD5 = array[0..15] of Byte;
TSIDPlayDetails = TList<PSIDPlayDetailRec>;
TSIDPlayLengths = TDictionary<TSIDPlayMD5, TSIDPlayDetails>;
TSIDPlayHeaderRec = packed record
tag: array[0..3] of AnsiChar;
version: Word;
dataOffset: Word;
loadAddress,
initAddress,
playAddress: Word;
songs: Word;
startSong: Word;
speedFlags: Cardinal;
name: array[0..31] of AnsiChar;
author: array[0..31] of AnsiChar;
released: array[0..31] of AnsiChar;
flags: Word;
end;
TSIDPlaySubSong = 0..63;
TSIDPlaySubSongs = set of TSIDPlaySubSong;
PNodeData = ^TNodeData;
TNodeData = record
fileIndex: Integer;
caption: string;
header: TSIDPlayHeaderRec;
updateRate: Byte;
sidType: Byte;
md5: TSIDPlayMD5;
details: TSIDPlayDetails;
lengths: array of TTime;
selected: TSIDPlaySubSongs;
sidParams,
metaData: array of string;
end;
PSIDConvConfig = ^TSIDConvConfig;
TSIDConvConfig = record
songLengths,
viceVSID,
outputPath: string;
startDelay: TTime;
procedure LoadFromIniFile(const AFile: string);
procedure SaveToIniFile(const AFile: string);
end;
TSIDConvCompCntrl = class;
TSIDConvCompress = class(TThread)
protected
FCntrl: TSIDConvCompCntrl;
FFormat: TSIDConvCompFmt;
FStream: TMemoryStream;
FDone: TSimpleEvent;
procedure Execute; override;
procedure DoWriteHeader;
procedure DoWriteSIDDesc;
procedure DoConvertTracks;
procedure DoWriteMetaData;
public
constructor Create(const AController: TSIDConvCompCntrl;
const AFormat: TSIDConvCompFmt; const AStream: TMemoryStream;
const ADone: TSimpleEvent);
end;
TSIDConvCompCntrl = class(TThread)
protected
FNode: PNodeData;
FSong: Integer;
FFormat: TSIDConvCompFmt;
FCompType: TSIDConvCompType;
FDumpFile: string;
FStream0,
FStream1: TMemoryStream;
FDone0,
FDone1: TSimpleEvent;
procedure Execute; override;
public
constructor Create(const ANode: PNodeData; const ASong: Integer;
const AFormat: TSIDConvCompFmt; const ACompType: TSIDConvCompType;
const ADumpFile: string);
end;
function SIDPlayComputeStreamMD5(AStream: TStream; const AHeader: TSIDPlayHeaderRec;
var AMD5: TSIDPlayMD5): Boolean;
function SIDPlayMD5ToString(const AMD5: TSIDPlayMD5): AnsiString;
function SIDPlayStringToMD5(const AString: AnsiString): TSIDPlayMD5;
procedure LoadSongLengths(const AFileName: string);
procedure ClearSongLengths;
var
ConvCountLock: TMultiReadExclusiveWriteSynchronizer;
ConvCount: Integer;
ConvPending: Integer;
SongLengths: TSIDPlayLengths;
implementation
uses
IniFiles, ULZBinTree, URangeEncoder, ULZMAEncoder,
{$IFDEF DCC}
AnsiStrings, Zip, ZLib;
{$ELSE}
ZStream;
{$ENDIF}
type
TXSIDHeaderRec = packed record
tag: array[0..3] of AnsiChar;
size: Byte;
version: Byte;
format: Byte;
sidCnt: Byte;
system: Byte;
updateRate: Byte;
end;
TXSIDSIDDescRec = packed record
tag: array[0..3] of AnsiChar;
size: Cardinal;
sid: Byte;
sidType: Byte;
end;
TXSIDTrackRec = packed record
tag: array[0..3] of AnsiChar;
size: Cardinal;
compType: Byte;
end;
TXSIDMetaDataRec = packed record
tag: array[0..3] of AnsiChar;
size: Cardinal;
end;
TSIDPlayMD5Context = record
private
FTotal: array[0..1] of Cardinal;
FState: array[0..3] of Cardinal;
FBuffer: array[0..63] of Byte;
procedure Process(ABuf: PByte);
public
procedure Start;
procedure Update(ABuf: PByte; ACount: Cardinal);
procedure Finish(var AMD5: TSIDPlayMD5);
end;
{ TSIDPlayMD5Context }
const
ARR_VAL_RSIDMD5_PADDING: array[0..63] of Byte = (
$80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
function READ_LE_UINT32(ptr: Pointer): Cardinal; inline;
begin
Result:= PCardinal(ptr)^;
end;
procedure WRITE_LE_UINT32(ptr: Pointer; value: Cardinal); inline;
begin
PCardinal(ptr)^:= value;
end;
procedure GET_UINT32(var val: Cardinal; base: PByte; offs: Integer); inline;
begin
val:= READ_LE_UINT32(base + offs);
end;
procedure PUT_UINT32(val: Cardinal; base: PByte; offs: Integer); inline;
begin
WRITE_LE_UINT32(base + offs, val);
end;
//Should make it a function and return false if value can not fit in AResult
procedure CardToVarLen(const AValue: Cardinal; var ALen: Byte;
var AResult: array of Byte; const AMaxLen: Byte = 4);
var
i: Byte;
data: Cardinal;
buffer: Integer;
begin
// These must be true
Assert(AMaxLen > 0);
Assert(Length(AResult) >= AMaxLen);
Assert(AValue < ($01 shl (AMaxLen * 7)));
ALen:= 0;
buffer:= AValue and $7F;
data:= AValue shr 7;
while (ALen < AMaxLen) and (data > 0) do
begin
// Data bytes
buffer:= buffer shl 8;
buffer:= buffer or Byte((data and $7F) or $80);
data:= data shr 7;
Inc(ALen);
end;
// First/Last byte
Inc(ALen);
// Byte swap for big endian!
for i:= 0 to ALen - 1 do
begin
AResult[i]:= buffer and $FF;
// Shouldn't need this if test for break since the length is known
if (buffer and $80) > 0 then
buffer:= buffer shr 8
else
// ???
Break;
end;
end;
procedure TSIDPlayMD5Context.Finish(var AMD5: TSIDPlayMD5);
var
last,
padn: Cardinal;
high,
low: Cardinal;
msglen: array[0..7] of Byte;
begin
high:= (FTotal[0] shr 29) or (FTotal[1] shl 3);
low:= FTotal[0] shl 3;
PUT_UINT32(low, @msglen[0], 0);
PUT_UINT32(high, @msglen[0], 4);
last:= FTotal[0] and $3F;
if last < 56 then
padn:= 56 - last
else
padn:= 120 - last;
Update(@ARR_VAL_RSIDMD5_PADDING[0], padn);
Update(@msglen[0], 8);
PUT_UINT32(FState[0], @AMD5[0], 0);
PUT_UINT32(FState[1], @AMD5[0], 4);
PUT_UINT32(FState[2], @AMD5[0], 8);
PUT_UINT32(FState[3], @AMD5[0], 12);
end;
//This is pretty nasty. I hope there are no artefacts from the conversion and
// that I haven't otherwise broken the logic. For some reason the F
// routines don't match my pascal reference. I guess someone has
// determined that these versions are likely to be better??
procedure TSIDPlayMD5Context.Process(ABuf: PByte);
//define S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
function S(AX: Cardinal; AN: Byte): Cardinal; inline;
begin
Result:= ((AX shl AN) or ((AX and $FFFFFFFF) shr (32 - AN)));
end;
//define P(a, b, c, d, k, s, t)
// {
// a += F(b,c,d) + X[k] + t; a = S(a,s) + b;
// }
//define F(x, y, z) (z ^ (x & (y ^ z)))
procedure P1(var AA: Cardinal; AB, AC, AD: Cardinal; AX: Cardinal; AN: Byte;
AT: Cardinal); inline;
begin
Inc(AA, (AD xor (AB and (AC xor AD))) + AX + AT);
AA:= S(AA, AN) + AB;
end;
//define F(x, y, z) (y ^ (z & (x ^ y)))
procedure P2(var AA: Cardinal; AB, AC, AD: Cardinal; AX: Cardinal; AN: Byte;
AT: Cardinal); inline;
begin
Inc(AA, (AC xor (AD and (AB xor AC))) + AX + AT);
AA:= S(AA, AN) + AB;
end;
//define F(x, y, z) (x ^ y ^ z)
procedure P3(var AA: Cardinal; AB, AC, AD: Cardinal; AX: Cardinal; AN: Byte;
AT: Cardinal); inline;
begin
Inc(AA, (AB xor AC xor AD) + AX + AT);
AA:= S(AA, AN) + AB;
end;
//define F(x, y, z) (y ^ (x | ~z))
procedure P4(var AA: Cardinal; AB, AC, AD: Cardinal; AX: Cardinal; AN: Byte;
AT: Cardinal); inline;
begin
Inc(AA, (AC xor (AB or (not AD))) + AX + AT);
AA:= S(AA, AN) + AB;
end;
var
X: array[0..15] of Cardinal;
A,
B,
C,
D: Cardinal;
begin
GET_UINT32(X[0], ABuf, 0);
GET_UINT32(X[1], ABuf, 4);
GET_UINT32(X[2], ABuf, 8);
GET_UINT32(X[3], ABuf, 12);
GET_UINT32(X[4], ABuf, 16);
GET_UINT32(X[5], ABuf, 20);
GET_UINT32(X[6], ABuf, 24);
GET_UINT32(X[7], ABuf, 28);
GET_UINT32(X[8], ABuf, 32);
GET_UINT32(X[9], ABuf, 36);
GET_UINT32(X[10], ABuf, 40);
GET_UINT32(X[11], ABuf, 44);
GET_UINT32(X[12], ABuf, 48);
GET_UINT32(X[13], ABuf, 52);
GET_UINT32(X[14], ABuf, 56);
GET_UINT32(X[15], ABuf, 60);
A:= FState[0];
B:= FState[1];
C:= FState[2];
D:= FState[3];
P1(A, B, C, D, X[ 0], 7, $D76AA478);
P1(D, A, B, C, X[ 1], 12, $E8C7B756);
P1(C, D, A, B, X[ 2], 17, $242070DB);
P1(B, C, D, A, X[ 3], 22, $C1BDCEEE);
P1(A, B, C, D, X[ 4], 7, $F57C0FAF);
P1(D, A, B, C, X[ 5], 12, $4787C62A);
P1(C, D, A, B, X[ 6], 17, $A8304613);
P1(B, C, D, A, X[ 7], 22, $FD469501);
P1(A, B, C, D, X[ 8], 7, $698098D8);
P1(D, A, B, C, X[ 9], 12, $8B44F7AF);
P1(C, D, A, B, X[ 10], 17, $FFFF5BB1);
P1(B, C, D, A, X[ 11], 22, $895CD7BE);
P1(A, B, C, D, X[ 12], 7, $6B901122);
P1(D, A, B, C, X[ 13], 12, $FD987193);
P1(C, D, A, B, X[ 14], 17, $A679438E);
P1(B, C, D, A, X[ 15], 22, $49B40821);
P2(A, B, C, D, X[ 1], 5, $F61E2562);
P2(D, A, B, C, X[ 6], 9, $C040B340);
P2(C, D, A, B, X[ 11], 14, $265E5A51);
P2(B, C, D, A, X[ 0], 20, $E9B6C7AA);
P2(A, B, C, D, X[ 5], 5, $D62F105D);
P2(D, A, B, C, X[ 10], 9, $02441453);
P2(C, D, A, B, X[ 15], 14, $D8A1E681);
P2(B, C, D, A, X[ 4], 20, $E7D3FBC8);
P2(A, B, C, D, X[ 9], 5, $21E1CDE6);
P2(D, A, B, C, X[ 14], 9, $C33707D6);
P2(C, D, A, B, X[ 3], 14, $F4D50D87);
P2(B, C, D, A, X[ 8], 20, $455A14ED);
P2(A, B, C, D, X[ 13], 5, $A9E3E905);
P2(D, A, B, C, X[ 2], 9, $FCEFA3F8);
P2(C, D, A, B, X[ 7], 14, $676F02D9);
P2(B, C, D, A, X[ 12], 20, $8D2A4C8A);
P3(A, B, C, D, X[ 5], 4, $FFFA3942);
P3(D, A, B, C, X[ 8], 11, $8771F681);
P3(C, D, A, B, X[ 11], 16, $6D9D6122);
P3(B, C, D, A, X[ 14], 23, $FDE5380C);
P3(A, B, C, D, X[ 1], 4, $A4BEEA44);
P3(D, A, B, C, X[ 4], 11, $4BDECFA9);
P3(C, D, A, B, X[ 7], 16, $F6BB4B60);
P3(B, C, D, A, X[ 10], 23, $BEBFBC70);
P3(A, B, C, D, X[ 13], 4, $289B7EC6);
P3(D, A, B, C, X[ 0], 11, $EAA127FA);
P3(C, D, A, B, X[ 3], 16, $D4EF3085);
P3(B, C, D, A, X[ 6], 23, $04881D05);
P3(A, B, C, D, X[ 9], 4, $D9D4D039);
P3(D, A, B, C, X[ 12], 11, $E6DB99E5);
P3(C, D, A, B, X[ 15], 16, $1FA27CF8);
P3(B, C, D, A, X[ 2], 23, $C4AC5665);
P4(A, B, C, D, X[ 0], 6, $F4292244);
P4(D, A, B, C, X[ 7], 10, $432AFF97);
P4(C, D, A, B, X[ 14], 15, $AB9423A7);
P4(B, C, D, A, X[ 5], 21, $FC93A039);
P4(A, B, C, D, X[ 12], 6, $655B59C3);
P4(D, A, B, C, X[ 3], 10, $8F0CCC92);
P4(C, D, A, B, X[ 10], 15, $FFEFF47D);
P4(B, C, D, A, X[ 1], 21, $85845DD1);
P4(A, B, C, D, X[ 8], 6, $6FA87E4F);
P4(D, A, B, C, X[ 15], 10, $FE2CE6E0);
P4(C, D, A, B, X[ 6], 15, $A3014314);
P4(B, C, D, A, X[ 13], 21, $4E0811A1);
P4(A, B, C, D, X[ 4], 6, $F7537E82);
P4(D, A, B, C, X[ 11], 10, $BD3AF235);
P4(C, D, A, B, X[ 2], 15, $2AD7D2BB);
P4(B, C, D, A, X[ 9], 21, $EB86D391);
Inc(FState[0], A);
Inc(FState[1], B);
Inc(FState[2], C);
Inc(FState[3], D);
end;
procedure TSIDPlayMD5Context.Start;
begin
FTotal[0]:= 0;
FTotal[1]:= 0;
FState[0]:= $67452301;
FState[1]:= $EFCDAB89;
FState[2]:= $98BADCFE;
FState[3]:= $10325476;
end;
procedure TSIDPlayMD5Context.Update(ABuf: PByte; ACount: Cardinal);
var
left,
fill: Cardinal;
len: Cardinal;
input: PByte;
begin
len:= ACount;
input:= ABuf;
if len = 0 then
Exit;
left:= FTotal[0] and $3F;
fill:= 64 - left;
Inc(FTotal[0], len);
FTotal[0]:= FTotal[0] and $FFFFFFFF;
if FTotal[0] < len then
Inc(FTotal[1]);
if (left <> 0) and (len >= fill) then
begin
// memcpy((void *)(ctx->buffer + left), (const void *)input, fill);
Move(input^, FBuffer[left], fill);
Process(@FBuffer[0]);
Dec(len, fill);
Inc(input, fill);
left:= 0;
end;
while len >= 64 do
begin
Process(input);
Dec(len, 64);
Inc(input, 64);
end;
if len > 0 then
// memcpy((void *)(ctx->buffer + left), (const void *)input, length);
Move(input^, FBuffer[left], len);
end;
function SIDPlayComputeStreamMD5(AStream: TStream; const AHeader: TSIDPlayHeaderRec;
var AMD5: TSIDPlayMD5): Boolean;
var
ctx: TSIDPlayMD5Context;
i: Integer;
buf: array[0..999] of Byte;
// restricted: Boolean;
// readlen: Cardinal;
// len: Cardinal;
function Min(AValue1, AValue2: Integer): Integer; inline;
begin
if AValue1 < AValue2 then
Result:= AValue1
else
Result:= AValue2;
end;
begin
// len:= AMaxLen;
FillChar(AMD5, SizeOf(AMD5), 0);
// restricted:= (len <> 0);
// if (not restricted) or (SizeOf(buf) <= len) then
// readlen:= SizeOf(buf)
// else
// readlen:= len;
ctx.Start;
// i:= AStream.Read(buf, readlen);
i:= AStream.Read(buf, SizeOf(buf));
while i > 0 do
begin
ctx.Update(@buf[0], i);
// if restricted then
// begin
// Dec(len, i);
// if len = 0 then
// Break;
//
// if SizeOf(buf) > len then
// readlen:= len;
// end;
// i:= AStream.Read(buf, readlen);
i:= AStream.Read(buf, SizeOf(buf));
end;
buf[1]:= (AHeader.initAddress and $FF00) shr 8;
buf[0]:= (AHeader.initAddress and $00FF);
ctx.Update(@buf[0], 2);
buf[1]:= (AHeader.playAddress and $FF00) shr 8;
buf[0]:= (AHeader.playAddress and $00FF);
ctx.Update(@buf[0], 2);
buf[1]:= (AHeader.songs and $FF00) shr 8;
buf[0]:= (AHeader.songs and $00FF);
ctx.Update(@buf[0], 2);
buf[0]:= Byte(#60);
buf[1]:= Byte(#0);
for i:= 0 to AHeader.songs - 1 do
begin
if CompareText(AHeader.tag, AnsiString('RSID')) = 0 then
ctx.update(@buf[0], 1)
else if (AHeader.speedFlags and (1 shl Min(i, 31))) <> 0 then
ctx.update(@buf[0], 1)
else
ctx.update(@buf[1], 1);
end;
if AHeader.version >= 2 then
if (AHeader.flags and $0C) = $08 then
begin
buf[0]:= Byte(#2);
ctx.update(@buf[0], 1);
end;
ctx.Finish(AMD5);
Result:= True;
end;
function SIDPlayMD5ToString(const AMD5: TSIDPlayMD5): AnsiString;
var
i: Integer;
begin
Result:= '';
for i:= 0 to 15 do
{$IFDEF FPC}
Result:= Result + Format('%2.2x', [AMD5[i]]);
{$ELSE}
Result:= Result + AnsiStrings.Format('%2.2x', [AMD5[i]]);
{$ENDIF}
end;
function SIDPlayStringToMD5(const AString: AnsiString): TSIDPlayMD5;
const
SET_VAL_ANSI_DIGIT = [#$30..#$39];
SET_VAL_ANSI_UPPER = [#$41..#$46];
SET_VAL_ANSI_LOWER = [#$61..#$66];
var
i: Integer;
c: AnsiChar;
h, l: Byte;
begin
Assert(Length(AString) >= 32, 'MD5 string length must be 32');
h:= $00;
for i:= 1 to 32 do
begin
c:= AString[i];
if c in SET_VAL_ANSI_LOWER then
c:= AnsiChar(Byte(c) - $20);
Assert((c in SET_VAL_ANSI_DIGIT) or (c in SET_VAL_ANSI_UPPER),
'MD5 string must contain only characters 0..9 and A..F');
if c in SET_VAL_ANSI_DIGIT then
l:= Byte(c) - $30
else
l:= Byte(c) - $37;
if (i mod 2) = 0 then
Result[i shr 1 - 1]:= h + l
else
h:= l shl 4;
end;
end;
procedure ClearSongLengths;
begin
SongLengths.Clear;
end;
procedure LoadSongLengths(const AFileName: string);
var
i: Integer;
f: TextFile;
sl: TStringList;
dl: TStringList;
md5: TSIDPlayMD5;
det: TSIDPlayDetails;
s: AnsiString;
procedure ParseDetailValues(AList: TStringList; out ADetails: TSIDPlayDetails);
var
i,
p: Integer;
s: string;
t: Char;
d: PSIDPlayDetailRec;
dt: TDateTime;
begin
ADetails:= TSIDPlayDetails.Create;
for i:= 0 to AList.Count - 1 do
begin
New(d);
p:= Pos('-', AList[i]);
if p > 0 then
begin
d^.time:= EncodeTime(0, 3, 0, 0);
d^.endType:= speLoop;
d^.lenType:= splDefault;
end
else
begin
p:= Pos('(', AList[i]);
if p > 0 then
begin
s:= '0:' + Copy(AList[i], 1, p - 1);
t:= AList[i][p + 1];
end
else
begin
s:= '0:' + AList[i];
t:= 'L';
end;
if not TryStrToTime(s, dt) then
begin
d^.time:= EncodeTime(0, 3, 0, 0);
d^.lenType:= splDefault;
end
else
begin
d^.time:= dt;
d^.lenType:= splClosestSeconds;
end;
case t of
'G':
begin
d^.endType:= speOverlap;
d^.lenType:= splEstimated;
end;
'B':
begin
d^.endType:= speLoop;
d^.lenType:= splEstimated;
end;
'M':
begin
d^.endType:= speFadeOut;
d^.lenType:= splClosestSeconds;
end;
'Z':
begin
d^.endType:= speFadeOut;
d^.lenType:= splEstimated;
end;
else
d^.endType:= speLoop;
end;
end;
ADetails.Add(d);
end;
end;
begin
SongLengths.Clear;
sl:= TStringList.Create;
dl:= TStringList.Create;
try
dl.Delimiter:= ' ';
FileMode:= fmOpenRead;
AssignFile(f, AFileName);
try
Reset(f);
while not Eof(f) do
begin
Readln(f, s);
if Length(s) > 0 then
if not (s[1] in [';', '[']) then
sl.Add(string(s));
end;
finally
CloseFile(f);
end;
for i:= 0 to sl.Count - 1 do
begin
md5:= SIDPlayStringToMD5(AnsiString(sl.Names[i]));
dl.DelimitedText:= sl.ValueFromIndex[i];
ParseDetailValues(dl, det);
SongLengths.Add(md5, det);
end;
finally
sl.Free;
dl.Free;
end;
end;
{ TSIDConvConfig }
procedure TSIDConvConfig.LoadFromIniFile(const AFile: string);
var
ini: TIniFile;
s: string;
begin
ini:= TIniFile.Create(AFile);
try
songLengths:= ini.ReadString('Paths', 'SongLengths', '');
viceVSID:= ini.ReadString('Paths', 'VICEVSID', '');
outputPath:= ini.ReadString('Paths', 'OutputPath', '');
s:= ini.ReadString('Settings', 'StartDelay', '00:00:00');
startDelay:= StrToDateTime(s);
finally
ini.Free;
end;
end;
procedure TSIDConvConfig.SaveToIniFile(const AFile: string);
var
ini: TIniFile;
s: string;
begin
ini:= TIniFile.Create(AFile);
try
ini.WriteString('Paths', 'SongLengths', songLengths);
ini.WriteString('Paths', 'VICEVSID', viceVSID);
ini.WriteString('Paths', 'OutputPath', outputPath);
s:= FormatDateTime('hh:nn:ss', startDelay);
ini.WriteString('Settings', 'StartDelay', s);
finally
ini.Free;
end;
end;
{ TSIDConvCompress }
constructor TSIDConvCompress.Create(const AController: TSIDConvCompCntrl;
const AFormat: TSIDConvCompFmt; const AStream: TMemoryStream;
const ADone: TSimpleEvent);
begin
Assert(AFormat in [scfFormat0, scfFormat1]);
FCntrl:= AController;
FFormat:= AFormat;
FStream:= AStream;
FDone:= ADone;
FDone.ResetEvent;
FreeOnTerminate:= True;
inherited Create(False);
end;
procedure TSIDConvCompress.DoConvertTracks;
var
h: TXSIDTrackRec;
mtk: Boolean;
enb: array[0..3] of Boolean;
os: Integer;
mos: array[0..3] of TMemoryStream;
mts: TMemoryStream;
cd: TCompressionStream;
cl: TLZMAEncoder;
ofs: array[0..3] of Cardinal;
fis: TFileStream;
o: Cardinal;
r,
v: Byte;
ov: array[0..3] of Byte;
vl: Byte;
w: Boolean;
i: Integer;
procedure ReadOffset;
var
b: AnsiChar;
s: AnsiString;
begin
s:= '';
fis.Read(b, 1);
while b <> #32 do
begin
s:= s + b;
fis.Read(b, 1);
end;
o:= StrToInt64(string(s));
end;
procedure ReadRegister;
var
b: AnsiChar;
s: AnsiString;
n: Byte;
begin
s:= '';
fis.Read(b, 1);
while b <> #32 do
begin
s:= s + b;
fis.Read(b, 1);
end;
n:= StrToInt(string(s));
if n > 24 then
Exception.Create('Invalid register number');
r:= Byte(n);
end;
procedure ReadValue;
var
b: AnsiChar;
s: AnsiString;
begin
s:= '';
fis.Read(b, 1);
while not (b in [#32, #13, #10]) do
begin
s:= s + b;
fis.Read(b, 1);
end;
v:= StrToInt(string(s));
while (fis.Position < fis.Size) and (b in [#32, #13, #10]) do
fis.Read(b, 1);
if fis.Position < fis.Size then
fis.Seek(-1, soCurrent);
end;
begin
mtk:= FFormat = scfFormat1;
enb[0]:= True;
enb[1]:= True;
enb[2]:= True;
enb[3]:= True;
ofs[0]:= 0;
ofs[1]:= 0;
ofs[2]:= 0;
ofs[3]:= 0;
mos[0]:= TMemoryStream.Create;
mos[1]:= TMemoryStream.Create;
mos[2]:= TMemoryStream.Create;
mos[3]:= TMemoryStream.Create;
try
fis:= TFileStream.Create(FCntrl.FDumpFile, fmOpenRead or fmShareDenyWrite);
try
fis.Seek(0, soFromBeginning);
while fis.Position < fis.Size do
try
ReadOffset;
ReadRegister;
ReadValue;
w:= ((r in [0..6]) and enb[0]) or
((r in [7..13]) and enb[1]) or
((r in [14..20]) and enb[2]) or
((r in [21..24]) and enb[3]);
if w then
if (not mtk)
or (r in [0..6]) then
os:= 0
else if r in [7..13] then
os:= 1
else if r in [14..20] then
os:= 2
else
os:= 3
else
os:= -1;
for i:= 0 to 3 do
Inc(ofs[i], o);
if w then
begin
CardToVarLen(ofs[os], vl, ov);
mos[os].Write(ov[0], vl);
mos[os].Write(r, 1);
mos[os].Write(v, 1);
ofs[os]:= 0;
end;
except
Break;
end;
finally
fis.Free;
end;
for i:= 0 to 3 do
begin
mos[i].Position:= 0;
if mos[i].Size > 0 then
begin
h.tag:= 'XSTK';
if FCntrl.FCompType = sctDeflate then
begin
h.compType:= 1;
mts:= TMemoryStream.Create;
cd:= TCompressionStream.Create(clMax, mts);
try
cd.CopyFrom(mos[i], mos[i].Size);
finally
cd.Free;
end;
mts.Position:= 0;
end
else if FCntrl.FCompType = sctLZMA then
begin
h.compType:= 2;
mts:= TMemoryStream.Create;
ULZBinTree.InitCRC;
// URangeEncoder.RangeEncoder:= TRangeEncoder.Create;
URangeEncoder.RangeEncoderCreate;
cl:= TLZMAEncoder.Create;
try
cl.SetAlgorithm(2);
cl.SetDictionarySize(1 shl 23);
cl.SeNumFastBytes(128);
cl.SetMatchFinder(1);
cl.SetLcLpPb(3, 0, 2);
cl.SetEndMarkerMode(True);
// cl.WriteCoderProperties(mts);
cl.Code(mos[i], mts, -1, -1);
finally
cl.Free;
// URangeEncoder.RangeEncoder.Free;
URangeEncoder.RangeEncoderFree;
end;
mts.Position:= 0;
end
else
begin
h.compType:= 0;
mts:= mos[i];
end;
h.size:= 1 + mts.Size;
FStream.Write(h, SizeOf(TXSIDTrackRec));
FStream.CopyFrom(mts, mts.Size);
if FCntrl.FCompType <> sctNone then
mts.Free;
end;
end;
finally
mos[3].Free;
mos[2].Free;
mos[1].Free;
mos[0].Free;
end;
end;
procedure TSIDConvCompress.DoWriteHeader;
var
h: TXSIDHeaderRec;
v: Integer;
begin
h.tag:= 'XSHD';
h.size:= 5;
h.version:= 1;
h.format:= Ord(FFormat);
h.sidCnt:= 1;
v:= (FCntrl.FNode^.header.flags and $0C) shr 2;
h.system:= v;
h.updateRate:= FCntrl.FNode^.updateRate;
FStream.Write(h, SizeOf(TXSIDHeaderRec));
end;
procedure TSIDConvCompress.DoWriteMetaData;
var
h: TXSIDMetaDataRec;
d: AnsiString;
begin
h.tag:= 'XSMD';
//FIXME Should actually convert it to UTF8.
d:= AnsiString(FCntrl.FNode^.metaData[FCntrl.FSong]);
h.size:= Length(d);
FStream.Write(h, SizeOf(TXSIDMetaDataRec));
if Length(d) > 0 then
FStream.Write(d[1], Length(d));
end;
procedure TSIDConvCompress.DoWriteSIDDesc;
var
h: TXSIDSIDDescRec;
d: AnsiString;
// v: Integer;
begin
h.tag:= 'XSSD';
h.sid:= 1;
// v:= (FCntrl.FNode^.header.flags and $30) shr 4;
// if v = 3 then
// v:= 0;
// h.sidType:= v;
h.sidType:= FCntrl.FNode^.sidType;
//FIXME Should actually convert it to UTF8.
d:= AnsiString(FCntrl.FNode^.sidParams[FCntrl.FSong]);
h.size:= 2 + Length(d);
FStream.Write(h, SizeOf(TXSIDSIDDescRec));
if Length(d) > 0 then
FStream.Write(d[1], Length(d));
end;
procedure TSIDConvCompress.Execute;
begin
ConvCountLock.BeginWrite;
try
Inc(ConvCount);
finally
ConvCountLock.EndWrite;
end;
DoWriteHeader;
DoWriteSIDDesc;
DoConvertTracks;
DoWriteMetaData;
FDone.SetEvent;
ConvCountLock.BeginWrite;
try
Dec(ConvCount);
finally
ConvCountLock.EndWrite;
end;
end;
{ TSIDConvCompCntrl }
constructor TSIDConvCompCntrl.Create(const ANode: PNodeData; const ASong: Integer;
const AFormat: TSIDConvCompFmt; const ACompType: TSIDConvCompType;
const ADumpFile: string);
begin
Assert(AFormat <> scfDumpOnly);
FNode:= ANode;
FSong:= ASong;
FFormat:= AFormat;
FCompType:= ACompType;
FDumpFile:= ADumpFile;
FreeOnTerminate:= True;
inherited Create(False);
end;
procedure TSIDConvCompCntrl.Execute;
var
f: TFileStream;
s: string;
m: TMemoryStream;
begin
if not ConvCountLock.BeginWrite then
raise Exception.Create('Error Message');
try
Inc(ConvPending);
finally
ConvCountLock.EndWrite;
end;
try
FStream0:= TMemoryStream.Create;
FStream1:= TMemoryStream.Create;
FDone0:= TSimpleEvent.Create;
FDone1:= TSimpleEvent.Create;
try
if FFormat in [scfFormat0, scfDetermine] then
TSIDConvCompress.Create(Self, scfFormat0, FStream0, FDone0)
else
FDone0.SetEvent;
if FFormat in [scfFormat1, scfDetermine] then
TSIDConvCompress.Create(Self, scfFormat1, FStream1, FDone1)
else
FDone1.SetEvent;
FDone0.WaitFor(INFINITE);
FDone1.WaitFor(INFINITE);
if FFormat = scfDetermine then
if FStream0.Size < FStream1.Size then
m:= FStream0
else
m:= FStream1
else if FFormat = scfFormat0 then
m:= FStream0
else
m:= FStream1;
s:= ChangeFileExt(FDumpFile, '.xsid');
f:= TFileStream.Create(s, fmCreate);
try
m.Position:= 0;
f.CopyFrom(m, m.Size);
finally
f.Free;
end;
finally
FDone1.Free;
FDone0.Free;
FStream1.Free;
FStream0.Free;
end;
finally
if not ConvCountLock.BeginWrite then
raise Exception.Create('Error Message');
try
Dec(ConvPending);
finally
ConvCountLock.EndWrite;
end;
end;
end;
initialization
ConvCount:= 0;
ConvCountLock:= TMultiReadExclusiveWriteSynchronizer.Create;
SongLengths:= TSIDPlayLengths.Create;
finalization
ConvCountLock.Free;
ClearSongLengths;
SongLengths.Free;
end.
|
// ##################################
// ###### IT PAT 2018 #######
// ###### GrowCery #######
// ###### Tiaan van der Riel #######
// ##################################
unit frmAdminHomeScreen_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, pngimage, ExtCtrls, StdCtrls, clsDisplayUserInfo_u;
type
TfrmAdminHomeScreen = class(TForm)
btnVeiwAnalytics: TButton;
btnVeiwStock: TButton;
btnCreateNewAccount: TButton;
btnDeleteAnAccount: TButton;
btnLogOut: TButton;
imgBackground: TImage;
imgWelcomeHeading: TImage;
lblLoggedOnUser: TLabel;
lblAdminInfo: TLabel;
imgDarkLogo: TImage;
btnVeiwTransactions: TButton;
btnHelp: TButton;
procedure FormActivate(Sender: TObject);
procedure btnLogOutClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnVeiwAnalyticsClick(Sender: TObject);
procedure btnVeiwStockClick(Sender: TObject);
procedure btnCreateNewAccountClick(Sender: TObject);
procedure btnDeleteAnAccountClick(Sender: TObject);
procedure btnVeiwTransactionsClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
private
{ Private declarations }
objDisplayUserInfo: TDisplayUserInfo;
public
{ Public declarations }
sLoggedOnUser: string;
end;
var
frmAdminHomeScreen: TfrmAdminHomeScreen;
implementation
uses
frmLogIn_u, frmAnalytics_u, frmStock_u, frmCreateNewAccount_u,
frmDeleteAnAccount_u, frmTransactions_u;
{$R *.dfm}
/// ======================== Form Activate ====================================
procedure TfrmAdminHomeScreen.FormActivate(Sender: TObject);
begin
{ The function of this piece of code is to create the object objDisplayUserInfo,
this object will make use of the class clsDisplayUserInfo, as the variable
sLoggedOnUser, to find and return all of the relevant information regarding the
currently logged in user, and display that information in the top left
* also used by frmTellerHomeScreeen }
sLoggedOnUser := frmLogIn.sLoggedOnUser;
objDisplayUserInfo := TDisplayUserInfo.Create(sLoggedOnUser);
lblAdminInfo.Caption := objDisplayUserInfo.ToString;
objDisplayUserInfo.Free;
end;
/// =================== Create A New Account Button ===========================
procedure TfrmAdminHomeScreen.btnCreateNewAccountClick(Sender: TObject);
begin
frmAdminHomeScreen.Hide;
frmCreateNewAccount.ShowModal;
end;
procedure TfrmAdminHomeScreen.btnDeleteAnAccountClick(Sender: TObject);
begin
frmAdminHomeScreen.Hide;
frmDeleteAnAccount.ShowModal;
end;
/// ======================== Veiw Analytics Button ============================
procedure TfrmAdminHomeScreen.btnVeiwAnalyticsClick(Sender: TObject);
begin
frmAdminHomeScreen.Hide;
frmAnalytics.ShowModal;
end;
/// ======================== Veiw Stock Button ================================
procedure TfrmAdminHomeScreen.btnVeiwStockClick(Sender: TObject);
begin
frmAdminHomeScreen.Hide;
frmStock.ShowModal;
end;
/// ===================== Veiw Transactions Button ============================
procedure TfrmAdminHomeScreen.btnVeiwTransactionsClick(Sender: TObject);
begin
frmAdminHomeScreen.Hide;
frmTransactions.ShowModal;
end;
/// ======================== Form Close =======================================
procedure TfrmAdminHomeScreen.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
/// Log the user out
ShowMessage('You have been logged out of your account.');
end;
/// ============================ Help Button ==================================
procedure TfrmAdminHomeScreen.btnHelpClick(Sender: TObject);
var
tHelp: TextFile;
sLine: string;
sMessage: string;
begin
sMessage := '========================================';
AssignFile(tHelp, 'Help_AdminHomeScreen.txt');
try { Code that checks to see if the file about the sponsors can be opened
- displays error if not }
reset(tHelp);
Except
ShowMessage('ERROR: The help file could not be opened.');
Exit;
end;
while NOT EOF(tHelp) do
begin
Readln(tHelp, sLine);
sMessage := sMessage + #13 + sLine;
end;
sMessage := sMessage + #13 + '========================================';
CloseFile(tHelp);
ShowMessage(sMessage);
end;
/// ======================== Log Out Button ====================================
procedure TfrmAdminHomeScreen.btnLogOutClick(Sender: TObject);
begin
if MessageDlg(' Are you sure you want to log out of your account ?',
mtConfirmation, [mbYes, mbCancel], 0) = mrYes then
begin
frmAdminHomeScreen.Close;
end
else
Exit
end;
end.
|
unit WarodaiXrefs;
{
Матчит различные XRef-ссылки в Вародае.
Общая идея:
Матчим последовательности вида
"см. <a href>ССЫЛКА 1</a> и ССЫЛКА 2"
Затем разбираем на отдельные ссылки. Каждая ссылка либо отмечена <a href>,
либо определённого формата (см. ниже).
}
interface
uses JWBStrings, Warodai, FastArray, EdictWriter, PerlRegEx;
{$INCLUDE 'Warodai.inc'}
procedure EatXrefs(var ln: string; sn: PEdictSenseEntry);
function HasHrefParts(const ln: UTF8String): boolean;
procedure AssertNoHrefsLeft(const ln: UTF8String);
{
Можно посчитать, какие виды предисловий ко ссылкам встречаются в файле.
Передавайте в MatchHrefs все строки с HTML-разметкой, а в конце проверьте AllHrefTypes;
}
var
AllHrefTypes: TArray<string>;
xrefStats: record
HrefExpr: integer;
SimpleHref: integer;
end;
procedure MatchHrefs(const ln: string);
implementation
uses SysUtils, UniStrUtils, WarodaiHeader, RegexUtils;
{
Форма ссылки:
あわ【泡】 (в едикте через точку)
そとわ【外輪】(の足)
あいおい【相老】(~する)
あいおい【相老】(~する) 1
あいおい【相老2】
Страшные вещи ловим:
きだおれ(京の)着倒れ
}
const
pRomanDigit='IVX'; //используются для ссылок на подзначения
pSomeCJKPunctuation='\x{3000}-\x{3009}\x{3012}-\x{303F}'; //без 【】
pCJKRefChar = pCJKUnifiedIdeographs + pCJKUnifiedIdeographsExtA
+ pCJKUnifiedIdeographsExtB + pCJKUnifiedIdeographsExtC
+ pHiragana + pKatakana + pSomeCJKPunctuation
+ '\/…';
pCJKRefStr='['+pCJKRefChar+']+(?:['+pRomanDigit+']+)?'; //слово и, опционально, латинский номер его вариации (см. DropVariantIndicator)
pRefBase=pCJKRefStr;
pRefWri1='【[^】]*】'; //расшифровка в формате あわ【泡】 -- матчим побольше, что внутри только CJK - проверим потом
pRefNo='\s*\d{1,3}'; //опционально 1-2о цифры с пробелом или без -- ссылка на подзначение
//Хвост ссылки
pRefRoundBrackets = '\s?\(.*?\)'; //любое число символов - русских или японских - в скобках -- продолжение или пояснение
pRefFreeTail = '\s?['+pCJKRefChar+']+?'; //некоторое число японских символов без скобок
//полный хвост ссылки - поставляется во множестве разновидностей
pRefTail =
'(?:' //в любом порядке (RefNo может идти после скобок):
+'(?:'+pRefNo+')?'
+'('+pRefRoundBrackets+'|)' //#+1
+'('+pRefFreeTail+'|)' //#+2
+'|'
+'('+pRefRoundBrackets+'|)' //#+3
+'(?:'+pRefNo+')?'
+'('+pRefFreeTail+'|)' //#+4
+'|'
+'('+pRefRoundBrackets+'|)' //#+5
+'('+pRefFreeTail+'|)' //#+6
+'(?:'+pRefNo+')?'
+')';
gcRefTail=6; //group count
//одна голая ссылка в нужном формате -> base, writing, [tail groups]
pSingleTextRef=
'('+pRefBase+')'
+'('+pRefWri1+'|)' //любое из пояснений, или ничего -- чтобы число скобок не менялось
+ pRefTail;
gcSingleTextRef=8;
//теги
pHrefOpen='<a href=[^>]*>';
pHrefClose='</a>';
//одна href-ссылка в нужном формате -> base, writing, [tail groups]
pSingleHref=
pHrefOpen
+ pSingleTextRef
+ pHrefClose
+ pRefTail; //хвост может быть как внутри SingleTextRef, так и снаружи. Хвост может быть пустым, так что беды это принести не должно
//одна ссылка либо в <a href>, либо голая -> a_href_base, a_href_writing, [a_href_tail], text_base, text_writing, [text_tail]
pSingleRef=
'(?:'
+pSingleHref
+'|'
+pSingleTextRef
+')'
//когда матчим отдельные ссылки, строго проверяем, чтобы после них шёл разрыв слова -
//иначе матчится даже палочка в </a>
+'(?=$|[\p{Z}\p{P}])';
{
Группы:
1, 2 - href\base
(3, 4), (5, 6), (7, 8) - href\tail\versions
(9, 10), (11, 12), (13, 14) - href\tail\version
15, 16 - text\base
(17, 18), (19, 20), (21, 22) - text\tail\version
}
//одна ссылка в a href с любым содержимым
//в содержимом не должно быть теговых знаков <> - это запрещено HTML (если нарушено - останутся ошмётки <a>, и позже матчнутся в проверке)
pHyperRef=
pHrefOpen
+ '([^<>]*)'
+ pHrefClose
+ pRefTail;
//либо голая ссылка в нужном формате, либо <a href> с ЛЮБЫМ содержимым (мы так хотим: дальше будут проверки)
pTextOrHyperRef = '(?:'+pSingleTextRef+'|'+pHyperRef+')';
pRefNames= //case-insensitive, см. pXref
'уст\.|'
+'см\. тж\.|см\.|'
+'ср\. тж\.|ср\.|ср\. напр\.|'
+'тж\. уст\.|тж\. редко|тж\.|'
+'ант\.|'
+'неправ\. вм\.|ошибочно вм\.|вм\.|'
+'редко |'
+'сокр\. см\.|сокр\. от|от сокр\.|сокр\.|'
+'в отличие от|кн\. опред\. форма от|производное от|от'
;
{
Одноразовые (фиксите):
тж. редко,
Нельзя парсить:
связ., связ.:, чаще, напр., как
}
//название ссылки + некоторое число рефов ("см <a href>СТАТЬЯ1</a> и СТАТЬЯ2")
pXref=
'\s*'
+'(?i)('+pRefNames+')(?-i)\s' //case insensitive
+'('+pTextOrHyperRef+'(?:\s*[\,\;и]\s+'+pTextOrHyperRef+')*)' //любое число ссылок больше одной, через запятую
+'\s*';
//К сожалению, регэкспы не могут матчить повторяющиеся группы (будет заматчена последняя),
//так что элементы внутри наборы ссылок надо матчить отдельно
var
preXref: TPerlRegEx;
preSingleRef: TPerlRegEx;
//после сложного матча всех ссылок матчим по-простому, чтобы проверить, что мы нигде не ошиблись
preHrefOpen: TPerlRegEx;
preHrefClose: TPerlRegEx;
{ Находит в строке все элементы ссылочного типа и регистрирует их в записи Sense }
procedure EatXrefs(var ln: string; sn: PEdictSenseEntry);
var xr0, xr1, xr2, xr3: UnicodeString;
tmp: UnicodeString;
xr_off: integer;
begin
preXref.Subject := UTF8String(ln);
if not preXref.Match then exit;
preXref.Replacement := '';
preSingleRef.Replacement := '';
repeat
xr0 := UnicodeString(preXref.Groups[1]); //тип ссылки
//Может быть несколько: "см. ОДНО, ДРУГОЕ"
//Матчим все
preSingleRef.Subject := preXref.Groups[2];
Assert(preSingleRef.Match); //не может быть чтоб не матчилось
repeat
//Вычисляем отступ номера группы матчей
if preSingleRef.Groups[0][1]='<' then
//Первая группа -- с <a href>
xr_off := 0
else
//Вторая группа -- просто ссылка
xr_off := gcSingleTextRef + gcRefTail;
//Читаем базу и расшифровку
xr1 := DropVariantIndicator(UnicodeString(preSingleRef.Groups[xr_off+1]));
xr2 := UnicodeString(preSingleRef.Groups[xr_off+2]); //индикатор удалим после снятия скобок
//Оба поля сразу не должны быть пустыми - если пустые, скорее всего,
//мы промазали с номерами групп (кто-то менял регэкс)
if (xr1='') and (xr2='') then
raise EUnsupportedXref.Create('Both reading and writing fields of xref are empty -- WTF');
//Удаляем скобки из записи
if xr2<>'' then begin
Assert(xr2[1]='【');
xr2 := copy(xr2,2,Length(xr2)-2);
end;
xr2 := DropVariantIndicator(xr2); //после удаления скобкок
//Проверяем, что внутри 【】 осталось только CJK
if (xr2<>'') and (EvalChars(xr2) and (EV_CYR or EV_LATIN) <> 0) then
raise EUnsupportedXref.Create('Illegal symbols in Xref kanji block');
//Бесскобочные хвосты отлавливаются, но не поддерживаются. Почти не встречаются.
//Хвостов у нас из-за комбинаций три набора групп
if (preSingleRef.Groups[xr_off+4]<>'') or (preSingleRef.Groups[xr_off+6]<>'')
or (preSingleRef.Groups[xr_off+8]<>'') then
raise EUnsupportedXref.Create('Invalid Xref tail -- non-bracketed tail');
if xr_off=0 then //доп. хвост для href-версии
if (preSingleRef.Groups[xr_off+10]<>'') or (preSingleRef.Groups[xr_off+12]<>'')
or (preSingleRef.Groups[xr_off+14]<>'') then
raise EUnsupportedXref.Create('Invalid Xref tail -- non-bracketed tail');
//Проверяем на скобочные продолжения -- そとわ【外輪】(の足)
xr3 := UnicodeString(preSingleRef.Groups[xr_off+3]);
if xr3='' then xr3 := UnicodeString(preSingleRef.Groups[xr_off+5]);
if xr3='' then xr3 := UnicodeString(preSingleRef.Groups[xr_off+7]);
if xr_off=0 then begin //доп. хвост для href-версии
if xr3='' then xr3 := UnicodeString(preSingleRef.Groups[xr_off+9]);
if xr3='' then xr3 := UnicodeString(preSingleRef.Groups[xr_off+11]);
if xr3='' then xr3 := UnicodeString(preSingleRef.Groups[xr_off+13]);
end;
if xr3<>'' then begin
xr3 := Trim(xr3);
//Почему-то поймали в скобочное выражение бесскобочный хвост.
//Раньше проверка была нужна, теперь оставил только на всякий случай
if (Length(xr3)<2) or (xr3[1]<>'(') or (xr3[Length(xr3)]<>')') then
raise EUnsupportedXref.Create('Invalid Xref tail -- non-bracketed bracket WTF');
xr3 := copy(xr3,2,Length(xr3)-2);
if EvalChars(xr3) and (EV_CYR or EV_LATIN) <> 0 then
//たていれ【達入れ】(татэирэ)
raise EUnsupportedXref.Create('Cyrillic/latin reading in (round brackets) -- format error');
if xr3[1]='~' then
//こ【粉】(~にする) -- просто удаляем тильду (у нас для каждого такого шаблона своя статья)
delete(xr3,1,1);
//Если у ссылки есть скобочная часть - это продолжение, напр. あな【穴】(を明ける)
//Продолжение может уже включать в себя написание:
if (xr2<>'') and (pos(xr2,xr3)>0) then begin
//くも【雲】(雲の上)
end else
//или чтение
if (pos(xr1,xr3)>0) then begin
end else begin
//в остальных случаях считаем, что это чистое продолжение
//встречались ошибки вроде ぎんこう(眼の銀行), но у нас нет никаких способов их поймать -- и их мало (пара штук)
if xr2<>'' then
xr3 := xr2+xr3
else
xr3 := xr1+xr3;
end;
//Теперь у нас
//xr1: база (кана/кандзи?)
//xr2: кандзи?
//xr3: полное выражение с базой
//Пробуем сделать и кану
if xr2<>'' then begin
tmp := repl(xr3, xr2, xr1);
if EvalChars(tmp) and EV_KANJI = 0 then begin
//Ура, получилось!
xr2 := xr3; //написание
xr1 := tmp; //чтение
end else begin
xr2 := ''; //не получилось чтения
xr1 := xr3; //написание
end;
end else begin
//Ничего не остаётся, как превратить ссылку в одиночную на выражение целиком, без расшифровки
xr2 := '';
xr1 := xr3;
end;
end;
xr1 := FixEllipsis(xr1);
xr2 := FixEllipsis(xr2);
//Пока что баним записи с точечками (несколько вариантов написания) - вообще их надо разделять
//Обратите внимание, что есть ДВЕ разные похожие точки - другая разделяет слова, и является просто буквой
if (pos('・', xr1)>0) or (pos('・', xr2)>0) then
raise EUnsupportedXref.Create('dot in xref value');
//Объединяем
if xr2<>'' then xr1 := xr1+'・'+xr2;
//Всё это ненормально
if pos('[', xr1)>0 then
raise EUnsupportedXref.Create('[ in xref value');
if pos('(', xr1)>0 then
raise EUnsupportedXref.Create('( in xref value');
if pos('/', xr1)>0 then //этих очень мало -- 3 штуки
raise EUnsupportedXref.Create('/ in xref value');
if (xr0='см. тж.') or (xr0='ср. тж.') or (xr0='см.') or (xr0='ср.')
or (xr0='тж.') then
//эти xref-ы не требуют пояснений
xr0 := ''
else
if (xr0='тж. уст.') then
xr0 := 'уст.'
else
if (xr0='тж. редко') then
xr0 := 'редко'
else
if (xr0='неправ. вм.') or (xr0='ошибочно вм.') then
xr0 := 'вм.'
else
if (xr0='сокр. см.') or (xr0='сокр. от') or (xr0='от сокр.') then
xr0 := 'сокр.'
else
if (xr0='кн. опред. форма от') or (xr0='производное от') then
xr0 := 'от';
if xr0='ант.' then
sn.AddAnt(xr1)
else
sn.AddXref(xr0, xr1);
preSingleRef.Replace;
until not preSingleRef.MatchAgain;
//Проверяем, что ошмёток ссылок не осталось
AssertNoHrefsLeft(preSingleRef.Subject);
preXref.Replace;
until not preXref.MatchAgain;
{
//Проверяем, что ошмёток ссылок не осталось
//Здесь это не очень правильно! В строке могли остаться легальные <a href=>
AssertNoHrefsLeft(preXref.Subject);
}
ln := UnicodeString(preXref.Subject); //after replacements
end;
{ True, если в строке есть ошмётки <a href> }
function HasHrefParts(const ln: UTF8String): boolean;
begin
preHrefOpen.Subject := ln;
preHrefClose.Subject := ln;
Result := preHrefOpen.Match or preHrefClose.Match;
end;
{ Бросает исключение, если в строке остались ошмётки <a href>
Полезно вызывать для контроля после разбора какого-то Xref-блока на его остатки.
Учтите, что в строках могут легально встречаться невынутые href-ссылки:
не все ссылки должны превращаться в <see also>. }
procedure AssertNoHrefsLeft(const ln: UTF8String);
begin
if HasHrefParts(ln) then
raise EUnsupportedXref.Create('Remains of <a href> are left in string -- prob. unsupported href structure');
end;
{
Другой вариант:
Все ссылки в формате <a href="#1-107-1-37">.*</a>, без разбору.
Встречаются такие формы:
<i>см.</i> <a href="#1-107-1-37">ごぎょう【五行】</a>
Этот вариант мы используем только для того, чтобы составить список всех
существующих вариантов предисловия к оформленной ссылке.
}
const
pAttributeValue='"[^"]*"|[^\s>]*'; //-> 1 group
pLink = '<a href=('+pAttributeValue+')[^>]*>([^<]*?)</a>';
pHrefExpr = '(?<=^|\s)([^\s]+?)(?:\s+)'+pLink;
pSimpleHref = '<a href=';
var
preHrefExpr: TPerlRegEx;
preSimpleHref: TPerlRegEx;
procedure MatchHrefs(const ln: string);
begin
preHrefExpr.Subject := UTF8String(ln);
if preHrefExpr.Match then
repeat
Inc(xrefStats.HrefExpr);
AllHrefTypes.AddUnique(UnicodeString(preHrefExpr.Groups[1]));
until not preHrefExpr.MatchAgain;
preSimpleHref.Subject := UTF8String(ln);
if preSimpleHref.Match then
repeat
Inc(xrefStats.SimpleHref);
until not preSimpleHref.MatchAgain;
end;
initialization
preXref := Regex(pXref);
preSingleRef := Regex(pSingleRef);
preHrefOpen := Regex(pHrefOpen);
preHrefClose := Regex(pHrefClose);
preHrefExpr := Regex(pHrefExpr);
preSimpleHref := Regex(pSimpleHref);
AllHrefTypes.Clear;
AllHrefTypes.Comparison := UniCompareStr;
FillChar(xrefStats, SizeOf(xrefStats), 0);
finalization
FreeAndNil(preSimpleHref);
FreeAndNil(preHrefExpr);
FreeAndNil(preHrefClose);
FreeAndNil(preHrefOpen);
FreeAndNil(preSingleRef);
FreeAndNil(preXref);
end.
|
unit UAvaliador;
interface
uses Generics.Collections, ULeilao, ULance, UUsuario;
type
TAvaliador = class
private
FMaiorValorLance: double;
FUsuarioMaiorLance: TUsuario;
function getMaiorValorLance: double;
procedure setMaiorValorLance(const Value: double);
public
procedure AvaliaLance(aLeilao: TLeilao);
property UsuarioMaiorLance: TUsuario read FUsuarioMaiorLance;
property MaiorValorLance: double read getMaiorValorLance
write setMaiorValorLance;
end;
implementation
{ TAvaliador }
procedure TAvaliador.AvaliaLance(aLeilao: TLeilao);
var
I: Integer;
begin
setMaiorValorLance(0);
for I := 0 to Pred(aLeilao.ListaLances.Count) do
if aLeilao.ListaLances.Items[I].ValorLance > getMaiorValorLance then
begin
setMaiorValorLance(aLeilao.ListaLances.Items[I].ValorLance);
FUsuarioMaiorLance := aLeilao.ListaLances.Items[I].Usuario;
end;
end;
function TAvaliador.getMaiorValorLance: double;
begin
result := FMaiorValorLance;
end;
procedure TAvaliador.setMaiorValorLance(const Value: double);
begin
FMaiorValorLance := Value;
end;
end.
|
PROGRAM Recursion;
FUNCTION GGT(p: INTEGER; q: INTEGER): INTEGER;
BEGIN
IF (p MOD q) = 0 THEN
GGT := q
ELSE
GGT := GGT(q, p MOD q);
END;
FUNCTION GGTIter(p: INTEGER; q: INTEGER): INTEGER;
VAR
x: INTEGER;
BEGIN
WHILE NOT ((p MOD q) = 0) DO BEGIN
x := p;
p := q;
q := x MOD q;
END;
GGTIter := q;
END;
FUNCTION Fact(n: LONGINT): LONGINT;
BEGIN
IF n <= 0 THEN
Fact := 1
ELSE
Fact := Fact(n-1) * n
END;
FUNCTION FactIterative(n: LONGINT): LONGINT;
VAR
res: LONGINT;
BEGIN
res := 1;
WHILE n > 0 DO BEGIN
res := res * n;
n := n - 1;
END;
Fact := res;
END;
FUNCTION Fib(n: LONGINT): LONGINT;
BEGIN
IF n <= 0 THEN
Fib := 0
ELSE IF n = 1 THEN
Fib := 1
ELSE
Fib := Fib(n-1) + Fib(n-2);
END;
TYPE
Node = ^NodeRec;
NodeRec = RECORD
value: LONGINT;
next: Node;
END;
List = Node;
FUNCTION Contains(l: List; value: INTEGER): BOOLEAN;
BEGIN
IF l = NIL THEN
Contains := FALSE
ELSE
Contains := (l^.value = value) OR Contains(l^.next, value);
END;
FUNCTION ContainsIter(l: List; value: INTEGER): BOOLEAN;
BEGIN
WHILE NOT (l = NIL) DO BEGIN
l := l^.next;
value := value;
END;
IF l = NIL THEN
ContainsIter := FALSE
ELSE
ContainsIter := (l^.value = value) OR Contains(l^.next, value);
END;
PROCEDURE Display(l: List);
BEGIN
IF l = NIL THEN
WriteLn
ELSE BEGIN
Write(l^.value, ' ');
Display(l^.next);
END;
END;
PROCEDURE DisplayIterative(l: List);
BEGIN
WHILE l <> NIL DO BEGIN
Write(l^.value, ' ');
l := l^.next;
END;
WriteLn;
END;
// not end-recursive --> stays as it is... :(
// Rückwertsausgabe der Liste
PROCEDURE DisplayInverted(l: List);
VAR
s: STRING;
BEGIN
IF l = NIL THEN
WriteLn
ELSE BEGIN
DisplayInverted(l^.next);
Write(l^.value, ' ');
END;
END;
VAR
l: List;
n: Node;
i: LONGINT;
BEGIN
l := NIL;
FOR i := 1 TO 10000 DO BEGIN
New(n);
n^.value := i;
n^.next := l;
l := n;
END;
// Display(l);
DisplayInverted(l);
END. |
object BigImagesSizeForm: TBigImagesSizeForm
Left = 192
Top = 114
BorderStyle = bsToolWindow
Caption = 'BigImagesSizeForm'
ClientHeight = 176
ClientWidth = 158
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
FormStyle = fsStayOnTop
KeyPreview = True
OldCreateOrder = False
OnCreate = FormCreate
OnDeactivate = FormDeactivate
OnKeyDown = FormKeyDown
OnShow = FormShow
PixelsPerInch = 96
TextHeight = 13
object TrbImageSize: TTrackBar
Left = 0
Top = 0
Width = 45
Height = 176
Align = alLeft
Max = 50
Min = 1
Orientation = trVertical
Position = 1
TabOrder = 0
OnChange = TrbImageSizeChange
end
object Panel1: TPanel
Left = 45
Top = 0
Width = 113
Height = 176
Align = alClient
TabOrder = 1
object RgPictureSize: TRadioGroup
Left = 1
Top = 1
Width = 111
Height = 144
Align = alTop
Caption = 'Big Images Size:'
ItemIndex = 1
Items.Strings = (
'Other (215x215)'
'300x300'
'250x250'
'200x200'
'150x150'
'100x100'
'85x85')
TabOrder = 0
OnClick = RgPictureSizeClick
end
object LnkClose: TWebLink
Left = 48
Top = 151
Width = 47
Height = 16
Cursor = crHandPoint
Text = 'Close'
OnClick = LnkCloseClick
ImageIndex = 0
UseEnterColor = False
EnterColor = clBlack
EnterBould = False
TopIconIncrement = 0
UseSpecIconSize = True
HightliteImage = False
StretchImage = True
CanClick = True
end
end
object TimerActivate: TTimer
Interval = 200
OnTimer = TimerActivateTimer
Left = 32
Top = 24
end
end
|
unit ideSHNavigator;
interface
uses
Windows, SysUtils, Classes, Controls, Graphics, Types, Forms, ComCtrls, Menus,
Contnrs, StdCtrls, Buttons, ExtCtrls, ActnList,
SHDesignIntf, SHOptionsIntf, ideSHDesignIntf;
type
TideSHNavigator = class;
TideSHNavBranchController = class
private
FOwner: TideSHNavigator;
FBranchList: TObjectList;
FButton: TToolButton;
FMenu: TPopupMenu;
FItemIndex: Integer;
procedure SetButton(Value: TToolButton);
procedure SetItemIndex(Value: Integer);
function GetStartIndex: Integer;
procedure SetStartIndex(Value: Integer);
function GetCurrentBranch: TSHComponent;
procedure ButtonClick(Sender: TObject);
procedure MenuPopup(Sender: TObject);
procedure MenuClick(Sender: TObject);
protected
procedure AddBranch(ABranch: TSHComponent);
property Button: TToolButton read FButton write SetButton;
public
constructor Create(AOwner: TideSHNavigator);
destructor Destroy; override;
procedure SetBranchMenuItems(AMenuItem: TMenuItem);
procedure SetBranchByIID(const ABranchIID: TGUID);
property BranchList: TObjectList read FBranchList;
property ItemIndex: Integer read FItemIndex write SetItemIndex;
property StartIndex: Integer read GetStartIndex write SetStartIndex;
property CurrentBranch: TSHComponent read GetCurrentBranch;
end;
TideSHNavGUIController = class
private
FOwner: TideSHNavigator;
FButton: TToolButton;
FLPanel: TPanel;
FLSplitter: TSplitter;
FRPanel: TPanel;
FRSplitter: TSplitter;
FLeftSide: Boolean;
FTopSide: Boolean;
procedure SetButton(Value: TToolButton);
procedure SetLPanel(Value: TPanel);
procedure SetLSplitter(Value: TSplitter);
procedure SetRPanel(Value: TPanel);
procedure SetRSplitter(Value: TSplitter);
function GetLWidth: Integer;
procedure SetLWidth(Value: Integer);
function GetRWidth: Integer;
procedure SetRWidth(Value: Integer);
procedure SetLeftSide(Value: Boolean);
procedure SetTopSide(Value: Boolean);
function GetVisible: Boolean;
procedure SetVisible(Value: Boolean);
public
constructor Create(AOwner: TideSHNavigator);
destructor Destroy; override;
procedure SetNavigatorPosition(Sender: TObject);
procedure SetToolboxPosition(Sender: TObject);
property Button: TToolButton read FButton write SetButton;
property LPanel: TPanel read FLPanel write SetLPanel;
property LSplitter: TSplitter read FLSplitter write SetLSplitter;
property RPanel: TPanel read FRPanel write SetRPanel;
property RSplitter: TSplitter read FRSplitter write SetRSplitter;
property LWidth: Integer read GetLWidth write SetLWidth;
property RWidth: Integer read GetRWidth write SetRWidth;
property LeftSide: Boolean read FLeftSide write SetLeftSide;
property TopSide: Boolean read FTopSide write SetTopSide;
property Visible: Boolean read GetVisible write SetVisible;
end;
TideSHNavPageController = class
private
FOwner: TideSHNavigator;
FBranchFormList: TObjectList;
protected
procedure AddBranchPage(ABranch: TSHComponent);
procedure ReloadComponents;
procedure ShowNecessaryForm;
function GetNecessaryForm(ABranch: TSHComponent; Index: Integer): TForm;
function GetNecessaryConnection(ABranch: TSHComponent): IideSHConnection;
function GetCurrentConnection: IideSHConnection;
public
constructor Create(AOwner: TideSHNavigator);
destructor Destroy; override;
property BranchFormList: TObjectList read FBranchFormList;
end;
TideSHNavigator = class(TComponent, IideSHNavigator)
private
FBranchController: TideSHNavBranchController;
FGUIController: TideSHNavGUIController;
FPageController: TideSHNavPageController;
function GetCurrentBranch: TSHComponent;
function GetCurrentServer: TSHComponent;
function GetCurrentDatabase: TSHComponent;
function GetCurrentServerInUse: Boolean;
function GetCurrentDatabaseInUse: Boolean;
function GetServerCount: Integer;
function GetDatabaseCount: Integer;
function GetCanConnect: Boolean;
function GetCanReconnect: Boolean;
function GetCanDisconnect: Boolean;
function GetCanDisconnectAll: Boolean;
function GetCanRefresh: Boolean;
function GetCanMoveUp: Boolean;
function GetCanMoveDown: Boolean;
function GetCanShowScheme: Boolean;
function GetCanShowPalette: Boolean;
function GetLoadingFromFile: Boolean;
function GetToolbox: IideSHToolbox;
function GetOptions: ISHSystemOptions;
function GetConnectionBranch(AConnection: TSHComponent): TSHComponent;
procedure SetBranchMenuItems(AMenuItem: TMenuItem);
procedure SetRegistrationMenuItems(AMenuItem: TMenuItem);
procedure SetConnectionMenuItems(AMenuItem: TMenuItem);
protected
property Options: ISHSystemOptions read GetOptions;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ IideSHNavigator }
function RegisterConnection(AConnection: TSHComponent): Boolean; // регистрация соединения
function UnregisterConnection(AConnection: TSHComponent): Boolean; // отрегистрация соединения
function DestroyConnection(AConnection: TSHComponent): Boolean; // разрушение соединения
function DisconnectAllConnections: Boolean; // отключить все коннекты
function ConnectTo(AConnection: TSHComponent): Boolean;
function ReconnectTo(AConnection: TSHComponent): Boolean;
function DisconnectFrom(AConnection: TSHComponent): Boolean;
procedure RefreshConnection(AConnection: TSHComponent);
procedure ActivateConnection(AConnection: TSHComponent);
function SynchronizeConnection(AConnection: TSHComponent; const AClassIID: TGUID;
const ACaption: string; Operation: TOperation): Boolean;
procedure Connect;
procedure Reconnect;
procedure Disconnect;
function DisconnectAll: Boolean;
procedure Refresh;
procedure SaveRegisteredInfoToFile; // сохранение регинфы в файл
procedure LoadRegisteredInfoFromFile; // вычитка регинфы из файла
procedure RecreatePalette;
procedure RefreshPalette;
procedure ShowScheme;
procedure ShowPalette;
property GUIController: TideSHNavGUIController read FGUIController;
property BranchController: TideSHNavBranchController read FBranchController;
property PageController: TideSHNavPageController read FPageController;
property CurrentBranch: TSHComponent read GetCurrentBranch;
property CurrentServer: TSHComponent read GetCurrentServer;
property CurrentDatabase: TSHComponent read GetCurrentDatabase;
property CurrentServerInUse: Boolean read GetCurrentServerInUse;
property CurrentDatabaseInUse: Boolean read GetCurrentDatabaseInUse;
property ServerCount: Integer read GetServerCount;
property DatabaseCount: Integer read GetDatabaseCount;
property CanConnect: Boolean read GetCanConnect;
property CanReconnect: Boolean read GetCanReconnect;
property CanDisconnect: Boolean read GetCanDisconnect;
property CanDisconnectAll: Boolean read GetCanDisconnectAll;
property CanRefresh: Boolean read GetCanRefresh;
property CanMoveUp: Boolean read GetCanMoveUp;
property CanMoveDown: Boolean read GetCanMoveDown;
property LoadingFromFile: Boolean read GetLoadingFromFile;
end;
implementation
uses
ideSHConsts, ideSHSystem, ideSHSysUtils,
ideSHBaseDialogFrm,
ideSHToolboxFrm,
ideSHComponentPageFrm,
ideSHConnectionPageFrm,
ideSHConnectionObjectsPageFrm;
{ TideSHNavBranchController }
constructor TideSHNavBranchController.Create(AOwner: TideSHNavigator);
begin
FOwner := AOwner;
inherited Create;
FBranchList := TObjectList.Create(False);
FMenu := TPopupMenu.Create(nil);
FMenu.AutoHotkeys := maManual;
FMenu.Images := DesignerIntf.ImageList;
FMenu.OnPopup := MenuPopup;
FItemIndex := -1;
end;
destructor TideSHNavBranchController.Destroy;
begin
FBranchList.Free;
while FMenu.Items.Count > 0 do FMenu.Items.Delete(0);
FMenu.Free;
inherited Destroy;
end;
procedure TideSHNavBranchController.SetBranchMenuItems(AMenuItem: TMenuItem);
var
I: Integer;
Branch: TSHComponent;
NewItem: TMenuItem;
begin
AMenuItem.Insert(0, NewLine);
for I := 0 to Pred(BranchList.Count) do
begin
Branch := TSHComponent(BranchList[I]);
NewItem := TMenuItem.Create(nil);
NewItem.Caption := Branch.CaptionExt;
NewItem.ImageIndex := DesignerIntf.GetImageIndex(Branch.ClassIID);
NewItem.Default := ItemIndex = I;
NewItem.Tag := I;
NewItem.OnClick := MenuClick;
AMenuItem.Add(NewItem);
end;
end;
procedure TideSHNavBranchController.SetBranchByIID(const ABranchIID: TGUID);
var
I, J: Integer;
begin
J := -1;
for I := 0 to Pred(BranchList.Count) do
if IsEqualGUID(TSHComponent(BranchList[I]).BranchIID, ABranchIID) then
begin
J := I;
Break;
end;
if I <> -1 then
begin
ItemIndex := J;
StartIndex := ItemIndex;
end;
end;
procedure TideSHNavBranchController.SetButton(Value: TToolButton);
begin
if FButton <> Value then
begin
FButton := Value;
FButton.DropdownMenu := FMenu;
FButton.Style := tbsDropDown;
FButton.ImageIndex := 0;
FButton.ShowHint := True;
FButton.OnClick := ButtonClick;
end;
end;
procedure TideSHNavBranchController.SetItemIndex(Value: Integer);
begin
if (Value >= 0) and (Value <= Pred(BranchList.Count)) then
if FItemIndex <> Value then
begin
FItemIndex := Value;
if FItemIndex = -1 then
begin
Button.Enabled := False;
Button.ImageIndex := 0;
Button.Hint := Format('%s: %s', ['Current Branch', SNothingSelected]);
end else
begin
Button.Enabled := True;
Button.ImageIndex := DesignerIntf.GetImageIndex(TSHComponent(BranchList[ItemIndex]).ClassIID);
Button.Hint := Format('%s: %s', ['Current Branch', TSHComponent(BranchList[ItemIndex]).CaptionExt]);
end;
FOwner.PageController.ShowNecessaryForm;
Button.Invalidate;
end;
end;
function TideSHNavBranchController.GetStartIndex: Integer;
begin
Result := FOwner.Options.StartBranch;
end;
procedure TideSHNavBranchController.SetStartIndex(Value: Integer);
begin
FOwner.Options.StartBranch := Value;
end;
function TideSHNavBranchController.GetCurrentBranch: TSHComponent;
begin
Result := nil;
if (ItemIndex >= 0) and (ItemIndex <= Pred(BranchList.Count)) then
Result := TSHComponent(BranchList[ItemIndex]);
end;
procedure TideSHNavBranchController.ButtonClick(Sender: TObject);
begin
if (Sender is TToolButton) then TToolButton(Sender).CheckMenuDropdown;
end;
procedure TideSHNavBranchController.MenuPopup(Sender: TObject);
var
I: Integer;
Branch: TSHComponent;
NewItem: TMenuItem;
begin
while FMenu.Items.Count > 0 do FMenu.Items.Delete(0);
for I := 0 to Pred(BranchList.Count) do
begin
Branch := TSHComponent(BranchList[I]);
NewItem := TMenuItem.Create(nil);
NewItem.Caption := Branch.CaptionExt;
NewItem.ImageIndex := DesignerIntf.GetImageIndex(Branch.ClassIID);
NewItem.Default := ItemIndex = I;
NewItem.Tag := I;
NewItem.OnClick := MenuClick;
FMenu.Items.Add(NewItem);
end;
end;
procedure TideSHNavBranchController.MenuClick(Sender: TObject);
begin
if (Sender is TMenuItem) and (ItemIndex <> TMenuItem(Sender).Tag) then
begin
ItemIndex := TMenuItem(Sender).Tag;
StartIndex := ItemIndex;
end;
end;
procedure TideSHNavBranchController.AddBranch(ABranch: TSHComponent);
begin
if BranchList.IndexOf(ABranch) = -1 then
begin
ItemIndex := BranchList.Add(ABranch);
FOwner.PageController.AddBranchPage(ABranch);
end;
end;
{ TideSHNavGUIController }
constructor TideSHNavGUIController.Create(AOwner: TideSHNavigator);
begin
FOwner := AOwner;
inherited Create;
end;
destructor TideSHNavGUIController.Destroy;
begin
inherited Destroy;
end;
procedure TideSHNavGUIController.SetButton(Value: TToolButton);
begin
FButton := Value;
FOwner.BranchController.Button := FButton;
end;
procedure TideSHNavGUIController.SetLPanel(Value: TPanel);
begin
FLPanel := Value;
if Assigned(FLPanel) then FLPanel.Caption := EmptyStr;
end;
procedure TideSHNavGUIController.SetLSplitter(Value: TSplitter);
begin
FLSplitter := Value;
end;
procedure TideSHNavGUIController.SetRPanel(Value: TPanel);
begin
FRPanel := Value;
if Assigned(FRPanel) then FRPanel.Caption := EmptyStr;
end;
procedure TideSHNavGUIController.SetRSplitter(Value: TSplitter);
begin
FRSplitter := Value;
end;
function TideSHNavGUIController.GetLWidth: Integer;
begin
Result := LPanel.Width;
end;
procedure TideSHNavGUIController.SetLWidth(Value: Integer);
begin
LPanel.Width := Value;
end;
function TideSHNavGUIController.GetRWidth: Integer;
begin
Result := RPanel.Width;
end;
procedure TideSHNavGUIController.SetRWidth(Value: Integer);
begin
RPanel.Width := Value;
end;
procedure TideSHNavGUIController.SetLeftSide(Value: Boolean);
var
I: Integer;
begin
FLeftSide := Value;
for I := 0 to Pred(FOwner.PageController.BranchFormList.Count) do
begin
if FLeftSide then
begin
case TSHComponentForm(FOwner.PageController.BranchFormList[I]).Tag of
0: TSHComponentForm(FOwner.PageController.BranchFormList[I]).Parent := LPanel;
1: TSHComponentForm(FOwner.PageController.BranchFormList[I]).Parent := RPanel;
end;
end else
begin
case TSHComponentForm(FOwner.PageController.BranchFormList[I]).Tag of
0: TSHComponentForm(FOwner.PageController.BranchFormList[I]).Parent := RPanel;
1: TSHComponentForm(FOwner.PageController.BranchFormList[I]).Parent := LPanel;
end;
end;
end;
{
if Value then
begin
LPanel.Align := alLeft;
LSplitter.Align := alLeft;
end else
begin
LPanel.Align := alRight;
LSplitter.Align := alRight;
end;
}
if Assigned(SystemOptionsIntf) then SystemOptionsIntf.NavigatorLeft := Value;
end;
procedure TideSHNavGUIController.SetTopSide(Value: Boolean);
var
I: Integer;
begin
FTopSide := Value;
for I := 0 to Pred(FOwner.PageController.BranchFormList.Count) do
case TSHComponentForm(FOwner.PageController.BranchFormList[I]).Tag of
1: TToolboxForm(FOwner.PageController.BranchFormList[I]).SetToolboxPosition(FTopSide);
end;
if Assigned(SystemOptionsIntf) then SystemOptionsIntf.ToolboxTop := Value;
end;
function TideSHNavGUIController.GetVisible: Boolean;
begin
Result := LPanel.Visible;
end;
procedure TideSHNavGUIController.SetVisible(Value: Boolean);
begin
if Value then
begin
LSplitter.Visible := not Value;
LPanel.Visible := not Value;
RPanel.Visible := not Value;
RSplitter.Visible := not Value;
end else
begin
LPanel.Visible := not Value;
LSplitter.Visible := not Value;
RPanel.Visible := not Value;
RSplitter.Visible := not Value;
RPanel.Left := RSplitter.Left + 100;
end;
end;
procedure TideSHNavGUIController.SetNavigatorPosition(Sender: TObject);
begin
LeftSide := not LeftSide;
end;
procedure TideSHNavGUIController.SetToolboxPosition(Sender: TObject);
begin
TopSide := not TopSide;
end;
{ TideSHNavPageController }
constructor TideSHNavPageController.Create(AOwner: TideSHNavigator);
begin
FOwner := AOwner;
inherited Create;
FBranchFormList := TObjectList.Create;
end;
destructor TideSHNavPageController.Destroy;
begin
FBranchFormList.Free;
inherited Destroy;
end;
procedure TideSHNavPageController.AddBranchPage(ABranch: TSHComponent);
begin
// регистратор + навигатор
BranchFormList.Add(
TConnectionPageForm.Create(FOwner.GUIController.LPanel,
FOwner.GUIController.LPanel,
ABranch,
EmptyStr));
TForm(BranchFormList.Last).Tag := 0;
// палитра
BranchFormList.Add(
TToolboxForm.Create(FOwner.GUIController.RPanel,
FOwner.GUIController.RPanel,
ABranch,
EmptyStr));
TForm(BranchFormList.Last).Tag := 1;
ShowNecessaryForm;
end;
procedure TideSHNavPageController.ReloadComponents;
var
I: Integer;
begin
for I := 0 to Pred(BranchFormList.Count) do
if BranchFormList[I] is TToolboxForm then
TToolboxForm(BranchFormList[I]).ReloadComponents;
end;
procedure TideSHNavPageController.ShowNecessaryForm;
var
I: Integer;
begin
for I := 0 to Pred(BranchFormList.Count) do
if (TSHComponentForm(BranchFormList[I]).Component = FOwner.BranchController.CurrentBranch) {and
(TSHComponentForm(BranchFormList[I]).Tag = FOwner.GUIController.PageControl.ActivePageIndex)} then
begin
TSHComponentForm(BranchFormList[I]).Show;
TSHComponentForm(BranchFormList[I]).BringToTop;
end;
end;
function TideSHNavPageController.GetNecessaryForm(ABranch: TSHComponent; Index: Integer): TForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to Pred(BranchFormList.Count) do
if (TSHComponentForm(BranchFormList[I]).Component = ABranch) and
(TSHComponentForm(BranchFormList[I]).Tag = Index) then
begin
Result := TForm(BranchFormList[I]);
Exit
end
end;
function TideSHNavPageController.GetNecessaryConnection(ABranch: TSHComponent): IideSHConnection;
var
I: Integer;
begin
for I := 0 to Pred(BranchFormList.Count) do
if (TSHComponentForm(BranchFormList[I]).Component = ABranch) and
(TSHComponentForm(BranchFormList[I]).Tag = 0) then
begin
Supports(BranchFormList[I], IideSHConnection, Result);
if Assigned(Result) then
Exit;
end
end;
function TideSHNavPageController.GetCurrentConnection: IideSHConnection;
var
I: Integer;
begin
for I := 0 to Pred(BranchFormList.Count) do
if (TSHComponentForm(BranchFormList[I]).Component = FOwner.BranchController.CurrentBranch) and
(TSHComponentForm(BranchFormList[I]).Tag = 0) then
Supports(BranchFormList[I], IideSHConnection, Result);
end;
{ TideSHNavigator }
constructor TideSHNavigator.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBranchController := TideSHNavBranchController.Create(Self);
FGUIController := TideSHNavGUIController.Create(Self);
FPageController := TideSHNavPageController.Create(Self);
Supports(Self, IideSHNavigator, NavigatorIntf);
end;
destructor TideSHNavigator.Destroy;
begin
NavigatorIntf := nil;
FBranchController.Free;
FGUIController.Free;
FPageController.Free;
inherited Destroy;
end;
function TideSHNavigator.GetCurrentBranch: TSHComponent;
begin
Result := BranchController.CurrentBranch;
end;
function TideSHNavigator.GetCurrentServer: TSHComponent;
begin
Result := nil;
if Assigned(BranchController.CurrentBranch) then
Result := PageController.GetCurrentConnection.CurrentServer;
end;
function TideSHNavigator.GetCurrentDatabase: TSHComponent;
begin
Result := nil;
if Assigned(BranchController.CurrentBranch) then
Result := PageController.GetCurrentConnection.CurrentDatabase;
end;
function TideSHNavigator.GetCurrentServerInUse: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CurrentServerInUse;
end;
function TideSHNavigator.GetCurrentDatabaseInUse: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CurrentDatabaseInUse;
end;
function TideSHNavigator.GetServerCount: Integer;
begin
Result := 0;
if Assigned(BranchController.CurrentBranch) then
Result := PageController.GetCurrentConnection.ServerCount;
end;
function TideSHNavigator.GetDatabaseCount: Integer;
begin
Result := 0;
if Assigned(BranchController.CurrentBranch) then
Result := PageController.GetCurrentConnection.DatabaseCount;
end;
function TideSHNavigator.GetCanConnect: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanConnect;
end;
function TideSHNavigator.GetCanReconnect: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanReconnect;
end;
function TideSHNavigator.GetCanDisconnect: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanDisconnect;
end;
function TideSHNavigator.GetCanDisconnectAll: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanDisconnectAll;
end;
function TideSHNavigator.GetCanRefresh: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanRefresh;
end;
function TideSHNavigator.GetCanMoveUp: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanMoveUp;
end;
function TideSHNavigator.GetCanMoveDown: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.CanMoveDown;
end;
function TideSHNavigator.GetCanShowScheme: Boolean;
begin
Result := Assigned(CurrentDatabase) and (CurrentDatabase as ISHRegistration).Connected;
end;
function TideSHNavigator.GetCanShowPalette: Boolean;
begin
Result := Assigned(CurrentServer);
end;
function TideSHNavigator.GetLoadingFromFile: Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetCurrentConnection.LoadingFromFile;
end;
function TideSHNavigator.GetToolbox: IideSHToolbox;
begin
Supports(PageController.GetNecessaryForm(BranchController.CurrentBranch, 1), IideSHToolbox, Result);
end;
function TideSHNavigator.GetOptions: ISHSystemOptions;
begin
Result := SystemOptionsIntf;
end;
function TideSHNavigator.GetConnectionBranch(AConnection: TSHComponent): TSHComponent;
begin
Result := nil;
if Assigned(AConnection) then
Result := DesignerIntf.FindComponent(IUnknown, AConnection.BranchIID);
end;
procedure TideSHNavigator.SetBranchMenuItems(AMenuItem: TMenuItem);
begin
BranchController.SetBranchMenuItems(AMenuItem);
end;
procedure TideSHNavigator.SetRegistrationMenuItems(AMenuItem: TMenuItem);
begin
if Assigned(BranchController.CurrentBranch) and
Assigned(PageController.GetNecessaryConnection(BranchController.CurrentBranch)) then
PageController.GetNecessaryConnection(BranchController.CurrentBranch).SetRegistrationMenuItems(AMenuItem);
end;
procedure TideSHNavigator.SetConnectionMenuItems(AMenuItem: TMenuItem);
begin
if Assigned(BranchController.CurrentBranch) and
Assigned(PageController.GetNecessaryConnection(BranchController.CurrentBranch)) then
PageController.GetNecessaryConnection(BranchController.CurrentBranch).SetConnectionMenuItems(AMenuItem);
end;
function TideSHNavigator.RegisterConnection(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).RegisterConnection(AConnection);
end;
function TideSHNavigator.UnregisterConnection(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).UnregisterConnection(AConnection);
end;
function TideSHNavigator.DestroyConnection(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).DestroyConnection(AConnection);
end;
function TideSHNavigator.DisconnectAllConnections: Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to Pred(BranchController.BranchList.Count) do
begin
Result := PageController.GetNecessaryConnection(TSHComponent(BranchController.BranchList[I])).DisconnectAll;
Application.ProcessMessages;
if not Result then Break;
end;
end;
function TideSHNavigator.ConnectTo(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).ConnectTo(AConnection);
end;
function TideSHNavigator.ReconnectTo(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).ReconnectTo(AConnection);
end;
function TideSHNavigator.DisconnectFrom(AConnection: TSHComponent): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).DisconnectFrom(AConnection);
end;
procedure TideSHNavigator.RefreshConnection(AConnection: TSHComponent);
begin
if Assigned(BranchController.CurrentBranch) then
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).RefreshConnection(AConnection);
end;
procedure TideSHNavigator.ActivateConnection(AConnection: TSHComponent);
begin
if Assigned(BranchController.CurrentBranch) then
begin
BranchController.SetBranchByIID(AConnection.BranchIID);
if (AConnection as ISHRegistration).Connected then
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).ActivateConnection(AConnection);
end;
end;
function TideSHNavigator.SynchronizeConnection(AConnection: TSHComponent; const AClassIID: TGUID;
const ACaption: string; Operation: TOperation): Boolean;
begin
Result := Assigned(BranchController.CurrentBranch) and
PageController.GetNecessaryConnection(GetConnectionBranch(AConnection)).SynchronizeConnection(AConnection, AClassIID, ACaption, Operation);
if Result and (Operation = opRemove) then
ObjectEditorIntf.JumpRemove(AConnection.InstanceIID, AClassIID, ACaption);
end;
procedure TideSHNavigator.Connect;
begin
PageController.GetCurrentConnection.Connect;
end;
procedure TideSHNavigator.Reconnect;
begin
PageController.GetCurrentConnection.Reconnect;
end;
procedure TideSHNavigator.Disconnect;
begin
PageController.GetCurrentConnection.Disconnect;
end;
function TideSHNavigator.DisconnectAll: Boolean;
begin
Result := PageController.GetCurrentConnection.DisconnectAll;
end;
procedure TideSHNavigator.Refresh;
begin
PageController.GetCurrentConnection.Refresh;
end;
procedure TideSHNavigator.SaveRegisteredInfoToFile;
var
I: Integer;
begin
for I := 0 to Pred(BranchController.BranchList.Count) do
PageController.GetNecessaryConnection(TSHComponent(BranchController.BranchList[I])).SaveToFile;
end;
procedure TideSHNavigator.LoadRegisteredInfoFromFile;
var
I: Integer;
begin
for I := 0 to Pred(BranchController.BranchList.Count) do
PageController.GetNecessaryConnection(TSHComponent(BranchController.BranchList[I])).LoadFromFile;
end;
procedure TideSHNavigator.RecreatePalette;
var
I: Integer;
begin
for I := 0 to Pred(RegistryIntf.GetRegBranchList.Count) do
BranchController.AddBranch(TSHComponent(RegistryIntf.GetRegBranchList[I]));
PageController.ReloadComponents;
BranchController.ItemIndex := Options.StartBranch;
end;
procedure TideSHNavigator.RefreshPalette;
var
I: Integer;
begin
for I := 0 to Pred(PageController.BranchFormList.Count) do
if PageController.BranchFormList[I] is TToolboxForm then
TToolboxForm(PageController.BranchFormList[I]).InvalidateComponents;
end;
procedure TideSHNavigator.ShowScheme;
var
DialogForm: TBaseDialogForm;
begin
DialogForm := TBaseDialogForm.Create(Application);
try
DialogForm.ComponentForm := TConnectionObjectsPageForm.Create(DialogForm, DialogForm.pnlClient, CurrentDatabase, '%s\Scheme Objects');
DialogForm.ShowModal;
if Assigned(DialogForm.OnAfterModalClose) then
DialogForm.OnAfterModalClose(DialogForm, DialogForm.ModalResult);
finally
FreeAndNil(DialogForm);
end;
end;
procedure TideSHNavigator.ShowPalette;
var
DialogForm: TBaseDialogForm;
begin
DialogForm := TBaseDialogForm.Create(Application);
try
DialogForm.ComponentForm := TComponentPageForm.Create(DialogForm, DialogForm.pnlClient, CurrentBranch, '%s\Component List ');
(DialogForm.ComponentForm as TComponentPageForm).ReloadComponents;
DialogForm.ShowModal;
if Assigned(DialogForm.OnAfterModalClose) then
DialogForm.OnAfterModalClose(DialogForm, DialogForm.ModalResult);
finally
FreeAndNil(DialogForm);
end;
end;
end.
|
unit Gar_MarkaTopl_Edit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxLookAndFeelPainters, cxMaskEdit,
cxDropDownEdit, cxDBEdit, DB, FIBDataSet, pFIBDataSet, StdCtrls,
cxButtons, cxControls, cxContainer, cxEdit, cxTextEdit, gar_Types, zTypes,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, ActnList, gr_uMessage, gr_uCommonConsts,
gr_uCommonProc, cxGroupBox, gar_MarkaTopl_DM;
type
TFEditMarkaTopl = class(TForm)
Panel1: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
Actions: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
ActionAdd: TAction;
ActionDel: TAction;
ActionClean: TAction;
ActionList1: TActionList;
Action1: TAction;
GroupBoxProp: TcxGroupBox;
cxMaskEdit1: TcxMaskEdit;
Action2: TAction;
procedure Action1Execute(Sender: TObject);
procedure Action2Execute(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
private
PLanguageIndex:integer;
ParamLoc:TgarParamMarkaTopl;
public
constructor Create(Param:TgarParamMarkaTopl);reintroduce;
function Delete(Param:TgarParamMarkaTopl):variant;
function PrepareData(Param:TgarParamMarkaTopl):variant;
end;
function View_FEdit(Param:TgarParamMarkaTopl):variant;
var
FEditMarkaTopl: TFEditMarkaTopl;
implementation
{$R *.dfm}
constructor TFEditMarkaTopl.Create(Param:TgarParamMarkaTopl);
begin
inherited Create(Param.owner);
PLanguageIndex:=IndexLanguage;
ParamLoc:=Param;
end;
function TFEditMarkaTopl.Delete(Param:TgarParamMarkaTopl):variant;
begin
DM.pFIBStoredProc1.StoredProcName:='GAR_SP_MARKA_TOPL_D';
DM.pFIBStoredProc1.Transaction.StartTransaction;
DM.pFIBStoredProc1.Prepare;
DM.pFIBStoredProc1.ParamByName('ID_MARKA_TOPL').AsInteger:= Param.ID_MARKA_TOPL;
DM.pFIBStoredProc1.ExecProc;
DM.pFIBStoredProc1.Transaction.Commit;
end;
function View_FEdit(Param:TgarParamMarkaTopl):variant;
begin
FEditMarkaTopl:=TFEditMarkaTopl.Create(Param);
if Param.fs=garfsDelete then FEditMarkaTopl.delete(Param)
else FEditMarkaTopl.PrepareData(Param);
if Param.fs<>garfsDelete then
FEditMarkaTopl.ShowModal;
FEditMarkaTopl.Free;
Result:=Param.ID_MARKA_TOPL;
end;
function TFEditMarkaTopl.PrepareData(Param:TgarParamMarkaTopl):variant;
begin
case Param.fs of
//zcfsInsert:
//cxTextEdit1.EditValue:=Param.MARKA_TOPL;
garfsUpdate:
begin
cxMaskEdit1.EditValue:=Param.MARKA_TOPL;
end;
end;
end;
procedure TFEditMarkaTopl.Action1Execute(Sender: TObject);
begin
if (cxMaskEdit1.Text='') then
begin
showmessage('Поле марки не заполнено!');
exit;
end;
with DM do
try
pFIBStoredProc1.Transaction.StartTransaction;
case ParamLoc.fs of
garfsInsert: pFIBStoredProc1.StoredProcName:='GAR_SP_MARKA_TOPL_I';
garfsUpdate: pFIBStoredProc1.StoredProcName:='GAR_SP_MARKA_TOPL_U';
end;
pFIBStoredProc1.Prepare;
pFIBStoredProc1.ParamByName('MARKA_TOPL').AsVariant := cxMaskEdit1.EditValue;
case ParamLoc.fs of
garfsUpdate:
pFIBStoredProc1.ParamByName('ID_MARKA_TOPL').AsInt64 := ParamLoc.ID_MARKA_TOPL;
end;
pFIBStoredProc1.ExecProc;
if ParamLoc.fs=garfsInsert then ParamLoc.ID_MARKA_TOPL:=pFIBStoredProc1.ParamByName('ID_MARKA_TOPL').AsInt64;
pFIBStoredProc1.Transaction.Commit;
except
on e:Exception do
begin
grShowMessage(ECaption[PLanguageIndex],e.message,mtError,[mbOk]);
pFIBStoredProc1.Transaction.RollBack;
end;
end;
ModalResult:=mrYes;
end;
procedure TFEditMarkaTopl.Action2Execute(Sender: TObject);
begin
if cxButton1.Focused Then Action1Execute(Sender);
if cxButton2.Focused Then cxButton2Click(Sender);
SendKeyDown(Self.ActiveControl,VK_TAB,[]);
end;
procedure TFEditMarkaTopl.cxButton2Click(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
unit Amazon.Storage.Service.Types;
interface
type
{$SCOPEDENUMS ON}
TAmazonProtocol = (http, https);
{$SCOPEDENUMS OFF}
TAmazonProtocollHelper = record helper for TAmazonProtocol
function GetValue: string;
end;
implementation
uses TypInfo;
function TAmazonProtocollHelper.GetValue: string;
begin
Result := GetEnumName(TypeInfo(TAmazonProtocol), Integer(Self));
end;
end.
|
program HowToMoveCameraToDifferentPoints;
uses
SwinGame, sgTypes;
procedure Main();
begin
OpenGraphicsWindow('Move Camera To Different Points', 800, 600);
LoadDefaultColors();
repeat // The game loop...
ProcessEvents();
//Move the camera by KeyBoard
if KeyDown(UPKey) then MoveCameraBy(0, -1);
if KeyDown(DOWNKey) then MoveCameraBy(0, +1);
if KeyDown(LEFTKey) then MoveCameraBy(-1, 0);
if KeyDown(RIGHTKey) then MoveCameraBy(+1, 0);
// Move Camera to a certain point
if KeyTyped(AKey) then MoveCameraTo(400, 450);
if KeyTyped(BKey) then MoveCameraTo(1400, 1300);
if KeyTyped(CKey) then MoveCameraTo(-500, -300);
ClearScreen(ColorWhite);
//Camera current coordinate
DrawTextOnScreen(PointToString(CameraPos()), ColorBlack, 690, 2);
DrawRectangle(ColorGreen, CameraScreenRect()); // Draw rectangle that encompases the area of the game world that is curretnly on the screen
FillCircle(ColorBlue, 400, 450, 4);
DrawText('Point A', ColorBlue, 'Arial', 24, 407, 444);
FillCircle(ColorBlue, 1400, 1300, 4);
DrawText('Point B', ColorBlue, 'Arial', 24, 1407, 1294);
FillCircle(ColorBlue, -500, -300, 4);
DrawText('Point C', ColorBlue, 'Arial', 24, -493, -294);
RefreshScreen(60);
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSLDiffuseSpecularShader<p>
This is a collection of GLSL diffuse-specular shaders.<p>
<b>History : </b><font size=-1><ul>
<li>07/01/10 - DaStr - Bugfixed all DoInitialize() calls
(thanks YarUnderoaker)
<li>25/07/09 - DaStr - Fixed a bug with "dot(reflect_vec, LightVector)" clamping
which occured on all GeForce 8x and later graphic cards
<li>24/07/09 - DaStr - Added Fog support for single-light shaders and fixed
a bug with material Alpha (thanks Controller)
<li>02/09/07 - LC - Fixed texture bug in TGLSLMLDiffuseSpecularShader.
(Bugtracker ID = 1786286)
<li>03/04/07 - LC - Shader didn't respect the texture matrix. Changed
vertex shader to fix this. (Bugtracker ID = 1693389)
<li>20/03/07 - DaStr - Made changes related to the new parameter passing model
<li>06/03/07 - DaStr - Again replaced DecimalSeparator stuff with
a single Str procedure (thanks Uwe Raabe)
<li>03/03/07 - DaStr - Made compatible with Delphi6
Added more stuff to RegisterClasses()
<li>21/02/07 - DaStr - Initial version (contributed to GLScene)
This is a collection of GLSL Diffuse Specular shaders, comes in these variaties
(to know what these suffixes and prefixes mean see GLCustomShader.pas):
- TGLSLDiffuseSpecularShader
- TGLSLDiffuseSpecularShaderMT
- TGLSLDiffuseSpecularShaderAM
- TGLSLMLDiffuseSpecularShader
- TGLSLMLDiffuseSpecularShaderMT
Notes:
1) Alpha is a synthetic property, in real life your should set each
color's Alpha individualy
2) TGLSLDiffuseSpecularShader takes all Light parameters directly
from OpenGL (that includes TGLLightSource's)
Previous version history:
v1.0 01 November '2006 Creation
v1.1 19 December '2006 TGLBaseCustomGLSLDiffuseSpecular[MT] abstracted
5 different versions of this shader added
v1.1.2 06 February '2007 IGLMaterialLibrarySupported renamed to
IGLMaterialLibrarySupported
v1.2 16 February '2007 Updated to the latest CVS version of GLScene
}
unit GLSLDiffuseSpecularShader;
interface
{$I GLScene.inc}
uses
// VCL
Classes, SysUtils,
// GLScene
GLTexture, GLScene, GLVectorGeometry, OpenGL1x, GLStrings, GLCustomShader,
GLSLShader, GLColor, GLRenderContextInfo, GLMaterial;
type
EGLSLDiffuseSpecularShaderException = class(EGLSLShaderException);
//: Abstract class.
TGLBaseCustomGLSLDiffuseSpecular = class(TGLCustomGLSLShader)
private
FSpecularPower: Single;
FLightPower: Single;
FRealisticSpecular: Boolean;
FFogSupport: TGLShaderFogSupport;
procedure SetRealisticSpecular(const Value: Boolean);
procedure SetFogSupport(const Value: TGLShaderFogSupport);
protected
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
public
constructor Create(AOwner : TComponent); override;
property SpecularPower: Single read FSpecularPower write FSpecularPower;
property LightPower: Single read FLightPower write FLightPower;
property RealisticSpecular: Boolean read FRealisticSpecular write SetRealisticSpecular;
//: User can disable fog support and save some FPS if he doesn't need it.
property FogSupport: TGLShaderFogSupport read FFogSupport write SetFogSupport default sfsAuto;
end;
//: Abstract class.
TGLBaseGLSLDiffuseSpecularShaderMT = class(TGLBaseCustomGLSLDiffuseSpecular, IGLMaterialLibrarySupported)
private
FMaterialLibrary: TGLMaterialLibrary;
FMainTexture: TGLTexture;
FMainTextureName: TGLLibMaterialName;
function GetMainTextureName: TGLLibMaterialName;
procedure SetMainTextureName(const Value: TGLLibMaterialName);
//: Implementing IGLMaterialLibrarySupported.
function GetMaterialLibrary: TGLMaterialLibrary;
protected
procedure SetMaterialLibrary(const Value: TGLMaterialLibrary); virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
public
property MainTexture: TGLTexture read FMainTexture write FMainTexture;
property MainTextureName: TGLLibMaterialName read GetMainTextureName write SetMainTextureName;
property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write SetMaterialLibrary;
end;
{******** Single Light ************}
TGLCustomGLSLDiffuseSpecularShaderAM = class(TGLBaseGLSLDiffuseSpecularShaderMT)
private
FAmbientColor: TGLColor;
FDiffuseColor: TGLColor;
FSpecularColor: TGLColor;
function GetAlpha: Single;
procedure SetAlpha(const Value: Single);
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
property AmbientColor: TGLColor read FAmbientColor;
property DiffuseColor: TGLColor read FDiffuseColor;
property SpecularColor: TGLColor read FSpecularColor;
property Alpha: Single read GetAlpha write SetAlpha;
end;
TGLCustomGLSLDiffuseSpecularShader = class(TGLBaseCustomGLSLDiffuseSpecular)
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
end;
TGLCustomGLSLDiffuseSpecularShaderMT = class(TGLBaseGLSLDiffuseSpecularShaderMT)
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
end;
{******** Multi Light ************}
{: Note: probably LightCount should be replaced by LightSources, like in
GLSLBumpShader.pas }
TGLCustomGLSLMLDiffuseSpecularShader = class(TGLBaseCustomGLSLDiffuseSpecular)
private
FLightCount: Integer;
FLightCompensation: Single;
procedure SetLightCount(const Value: Integer);
procedure SetLightCompensation(const Value: Single);
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
public
constructor Create(AOwner : TComponent); override;
property LightCount: Integer read FLightCount write SetLightCount default 1;
{: Setting LightCompensation to a value less than 1 decreeses individual
light intensity when using multiple lights }
property LightCompensation: Single read FLightCompensation write SetLightCompensation;
end;
TGLCustomGLSLMLDiffuseSpecularShaderMT = class(TGLBaseGLSLDiffuseSpecularShaderMT)
private
FLightCount: Integer;
FLightCompensation: Single;
procedure SetLightCount(const Value: Integer);
procedure SetLightCompensation(const Value: Single);
protected
procedure DoInitialize(var rci: TRenderContextInfo; Sender: TObject); override;
public
constructor Create(AOwner : TComponent); override;
property LightCount: Integer read FLightCount write SetLightCount default 1;
{: Setting LightCompensation to a value less than 1 decreeses individual
light intensity when using multiple lights }
property LightCompensation: Single read FLightCompensation write SetLightCompensation;
end;
{******** Published Stuff ************}
TGLSLDiffuseSpecularShaderAM = class(TGLCustomGLSLDiffuseSpecularShaderAM)
published
property AmbientColor;
property DiffuseColor;
property SpecularColor;
property Alpha stored False;
property MainTexture;
property SpecularPower;
property LightPower;
property FogSupport;
end;
TGLSLDiffuseSpecularShaderMT = class(TGLCustomGLSLDiffuseSpecularShaderMT)
published
property MainTextureName;
property SpecularPower;
property LightPower;
property FogSupport;
end;
TGLSLDiffuseSpecularShader = class(TGLCustomGLSLDiffuseSpecularShader)
published
property SpecularPower;
property LightPower;
property FogSupport;
end;
TGLSLMLDiffuseSpecularShaderMT = class(TGLCustomGLSLMLDiffuseSpecularShaderMT)
published
property MainTextureName;
property SpecularPower;
property LightPower;
property LightCount;
property LightCompensation;
property FogSupport;
end;
TGLSLMLDiffuseSpecularShader = class(TGLCustomGLSLMLDiffuseSpecularShader)
published
property SpecularPower;
property LightPower;
property LightCount;
property LightCompensation;
property FogSupport;
end;
implementation
procedure GetVertexProgramCode(const Code: TStrings;
const AFogSupport: Boolean; var rci: TRenderContextInfo);
begin
with Code do
begin
Clear;
Add('varying vec3 Normal; ');
Add('varying vec3 LightVector; ');
Add('varying vec3 CameraVector; ');
if AFogSupport then
begin
Add('varying float fogFactor; ');
end;
Add(' ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' gl_Position = ftransform(); ');
Add(' gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; ');
Add(' Normal = normalize(gl_NormalMatrix * gl_Normal); ');
Add(' vec3 p = (gl_ModelViewMatrix * gl_Vertex).xyz; ');
Add(' LightVector = normalize(gl_LightSource[0].position.xyz - p); ');
Add(' CameraVector = normalize(p); ');
if AFogSupport then
begin
Add(' const float LOG2 = 1.442695; ');
Add(' gl_FogFragCoord = length(p); ');
case TGLSceneBuffer(rci.buffer).FogEnvironment.FogMode of
fmLinear:
Add(' fogFactor = (gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale; ');
fmExp, // Yep, I don't know about this type, so I use fmExp2.
fmExp2:
begin
Add(' fogFactor = exp2( -gl_Fog.density * ');
Add(' gl_Fog.density * ');
Add(' gl_FogFragCoord * ');
Add(' gl_FogFragCoord * ');
Add(' LOG2 ); ');
end;
else
Assert(False, glsUnknownType);
end;
Add(' fogFactor = clamp(fogFactor, 0.0, 1.0); ');
end;
Add('} ');
end;
end;
procedure GetFragmentProgramCode(const Code: TStrings; const ARealisticSpecular: Boolean;
const AFogSupport: Boolean);
begin
with Code do
begin
Clear;
Add('uniform float LightIntensity; ');
Add('uniform float SpecPower; ');
Add('uniform sampler2D MainTexture; ');
Add(' ');
Add('varying vec3 Normal; ');
Add('varying vec3 LightVector; ');
Add('varying vec3 CameraVector; ');
if AFogSupport then
begin
Add('varying float fogFactor; ');
end;
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].xy); ');
Add(' vec4 DiffuseContrib = clamp(gl_LightSource[0].diffuse * dot(LightVector, Normal), 0.0, 1.0); ');
Add(' ');
Add(' vec3 reflect_vec = reflect(CameraVector, -Normal); ');
Add(' float Temp = max(dot(reflect_vec, LightVector), 0.0); ');
Add(' vec4 SpecContrib = gl_LightSource[0].specular * clamp(pow(Temp, SpecPower), 0.0, 0.95); ');
Add(' ');
if AFogSupport then
begin
if ARealisticSpecular then
Add(' gl_FragColor = mix(gl_Fog.color, LightIntensity * (TextureContrib * (gl_LightSource[0].ambient + DiffuseContrib) + SpecContrib), fogFactor ); ')
else
Add(' gl_FragColor = mix(gl_Fog.color, TextureContrib * LightIntensity * (gl_LightSource[0].ambient + DiffuseContrib + SpecContrib), fogFactor ); ');
end
else
begin
if ARealisticSpecular then
Add(' gl_FragColor = LightIntensity * (TextureContrib * (gl_LightSource[0].ambient + DiffuseContrib) + SpecContrib); ')
else
Add(' gl_FragColor = TextureContrib * LightIntensity * (gl_LightSource[0].ambient + DiffuseContrib + SpecContrib); ');
end;
Add(' gl_FragColor.a = TextureContrib.a; ');
Add('} ');
end;
end;
procedure GetFragmentProgramCodeAM(const Code: TStrings; const ARealisticSpecular: Boolean;
const AFogSupport: Boolean);
begin
with Code do
begin
Clear;
Add('uniform vec4 AmbientColor; ');
Add('uniform vec4 DiffuseColor; ');
Add('uniform vec4 SpecularColor; ');
Add(' ');
Add('uniform float LightIntensity; ');
Add('uniform float SpecPower; ');
Add('uniform sampler2D MainTexture; ');
Add(' ');
Add('varying vec3 Normal; ');
Add('varying vec3 LightVector; ');
Add('varying vec3 CameraVector; ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].xy); ');
Add(' vec4 DiffuseContrib = clamp(DiffuseColor * dot(LightVector, Normal), 0.0, 1.0); ');
Add(' ');
Add(' vec3 reflect_vec = reflect(CameraVector, -Normal); ');
Add(' float Temp = max(dot(reflect_vec, LightVector), 0.0); ');
Add(' vec4 SpecContrib = SpecularColor * clamp(pow(Temp, SpecPower), 0.0, 0.95); ');
Add(' ');
if AFogSupport then
begin
if ARealisticSpecular then
Add(' gl_FragColor = mix(gl_Fog.color, LightIntensity * (TextureContrib * (AmbientColor + DiffuseContrib) + SpecContrib); ')
else
Add(' gl_FragColor = mix(gl_Fog.color, TextureContrib * LightIntensity * (AmbientColor + DiffuseContrib + SpecContrib), fogFactor ); ');
end
else
begin
if ARealisticSpecular then
Add(' gl_FragColor = LightIntensity * (TextureContrib * (AmbientColor + DiffuseContrib) + SpecContrib); ')
else
Add(' gl_FragColor = TextureContrib * LightIntensity * (AmbientColor + DiffuseContrib + SpecContrib); ');
end;
Add(' gl_FragColor.a = TextureContrib.a; ');
Add('} ');
end;
end;
procedure GetMLVertexProgramCode(const Code: TStrings);
begin
with Code do
begin
Clear;
Add('varying vec3 Normal; ');
Add('varying vec3 LightVector; ');
Add('varying vec3 ViewDirection; ');
Add(' ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' gl_Position = ftransform(); ');
Add(' gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; ');
Add(' Normal = normalize(gl_NormalMatrix * gl_Normal); ');
Add(' ViewDirection = (gl_ModelViewMatrix * gl_Vertex).xyz; ');
Add('} ');
end;
end;
procedure GetMLFragmentProgramCodeBeg(const Code: TStrings);
begin
with Code do
begin
Clear;
Add('uniform float LightIntensity; ');
Add('uniform float SpecPower; ');
Add('uniform sampler2D MainTexture; ');
Add(' ');
Add('varying vec3 Normal; ');
Add('varying vec3 ViewDirection; ');
Add(' ');
Add('void main(void) ');
Add('{ ');
Add(' vec3 LightVector; ');
Add(' vec3 reflect_vec; ');
Add(' float Temp; ');
Add(' vec4 TextureContrib = texture2D(MainTexture, gl_TexCoord[0].st); ');
Add(' vec3 CameraVector = normalize(ViewDirection); ');
Add(' ');
Add(' vec4 DiffuseContrib = vec4(0, 0, 0, 0); ');
Add(' vec4 SpecContrib = vec4(0, 0, 0, 0); ');
Add(' vec4 AmbientContrib = vec4(0, 0, 0, 0); ');
end;
end;
procedure GetMLFragmentProgramCodeMid(const Code: TStrings; const CurrentLight: Integer);
begin
with Code do
begin
Add(' LightVector = normalize(gl_LightSource[' + IntToStr(CurrentLight) + '].position.xyz - ViewDirection); ');
Add(' AmbientContrib = AmbientContrib + gl_LightSource[' + IntToStr(CurrentLight) + '].ambient; ');
Add(' DiffuseContrib = min(DiffuseContrib + clamp(gl_LightSource[' + IntToStr(CurrentLight) + '].diffuse * dot(LightVector, Normal), 0.0, 1.0), 1.0); ');
Add(' reflect_vec = reflect(CameraVector, -Normal); ');
Add(' Temp = max(dot(reflect_vec, LightVector), 0.0); ');
Add(' SpecContrib = min(SpecContrib + gl_LightSource[' + IntToStr(CurrentLight) + '].specular * clamp(pow(Temp, SpecPower), 0.0, 0.95), 1.0); ');
end;
end;
procedure GetMLFragmentProgramCodeEnd(const Code: TStrings; const FLightCount: Integer; const FLightCompensation: Single; const FRealisticSpecular: Boolean);
var
Temp: string;
begin
with Code do
begin
if (FLightCount = 1) or (FLightCompensation = 1) then
begin
if FRealisticSpecular then
Add(' gl_FragColor = LightIntensity * (TextureContrib * (AmbientContrib + DiffuseContrib) + SpecContrib); ')
else
Add(' gl_FragColor = LightIntensity * TextureContrib * (AmbientContrib + DiffuseContrib + SpecContrib); ');
end
else
begin
Str((1 + (FLightCount - 1) * FLightCompensation) / FLightCount: 1: 1, Temp);
if FRealisticSpecular then
Add(' gl_FragColor = (LightIntensity * TextureContrib * (AmbientContrib + DiffuseContrib) + SpecContrib) * ' + Temp + '; ')
else
Add(' gl_FragColor = LightIntensity * TextureContrib * (AmbientContrib + DiffuseContrib + SpecContrib) * ' + Temp + '; ');
end;
Add(' gl_FragColor.a = TextureContrib.a; ');
Add('} ');
end;
end;
{ TGLBaseCustomGLSLDiffuseSpecular }
constructor TGLBaseCustomGLSLDiffuseSpecular.Create(
AOwner: TComponent);
begin
inherited;
FSpecularPower := 8;
FLightPower := 1;
FFogSupport := sfsAuto;
TStringList(VertexProgram.Code).OnChange := nil;
TStringList(FragmentProgram.Code).OnChange := nil;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
GetGLSLProg.UseProgramObject;
Param['SpecPower'].AsVector1f := FSpecularPower;
Param['LightIntensity'].AsVector1f := FLightPower;
end;
function TGLBaseCustomGLSLDiffuseSpecular.DoUnApply(
var rci: TRenderContextInfo): Boolean;
begin
Result := False;
GetGLSLProg.EndUseProgramObject;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.SetFogSupport(
const Value: TGLShaderFogSupport);
begin
if FFogSupport <> Value then
begin
FFogSupport := Value;
Self.FinalizeShader;
end;
end;
procedure TGLBaseCustomGLSLDiffuseSpecular.SetRealisticSpecular(
const Value: Boolean);
begin
if FRealisticSpecular <> Value then
begin
FRealisticSpecular := Value;
Self.FinalizeShader;
end;
end;
{ TGLBaseGLSLDiffuseSpecularShaderMT }
procedure TGLBaseGLSLDiffuseSpecularShaderMT.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
Param['MainTexture'].AsTexture2D[0] := FMainTexture;
end;
function TGLBaseGLSLDiffuseSpecularShaderMT.GetMainTextureName: TGLLibMaterialName;
begin
Result := FMaterialLibrary.GetNameOfTexture(FMainTexture);
end;
function TGLBaseGLSLDiffuseSpecularShaderMT.GetMaterialLibrary: TGLMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.Notification(
AComponent: TComponent; Operation: TOperation);
var
Index: Integer;
begin
inherited;
if Operation = opRemove then
if AComponent = FMaterialLibrary then
if FMaterialLibrary <> nil then
begin
//need to nil the textures that were ownned by it
if FMainTexture <> nil then
begin
Index := FMaterialLibrary.Materials.GetTextureIndex(FMainTexture);
if Index <> -1 then
FMainTexture := nil;
end;
FMaterialLibrary := nil;
end;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.SetMainTextureName(
const Value: TGLLibMaterialName);
begin
if FMaterialLibrary = nil then
begin
FMainTextureName := Value;
if not (csLoading in ComponentState) then
raise EGLSLDiffuseSpecularShaderException.Create(glsErrorEx + glsMatLibNotDefined);
end
else
begin
FMainTexture := FMaterialLibrary.TextureByName(Value);
FMainTextureName := '';
end;
end;
procedure TGLBaseGLSLDiffuseSpecularShaderMT.SetMaterialLibrary(
const Value: TGLMaterialLibrary);
begin
if FMaterialLibrary <> nil then
FMaterialLibrary.RemoveFreeNotification(Self);
FMaterialLibrary := Value;
if FMaterialLibrary <> nil then
begin
FMaterialLibrary.FreeNotification(Self);
if FMainTextureName <> '' then
SetMainTextureName(FMainTextureName);
end
else
FMainTextureName := '';
end;
{ TGLCustomGLSLDiffuseSpecularShaderAM }
constructor TGLCustomGLSLDiffuseSpecularShaderAM.Create(AOwner: TComponent);
begin
inherited;
FAmbientColor := TGLColor.Create(Self);
FDiffuseColor := TGLColor.Create(Self);
FSpecularColor := TGLColor.Create(Self);
//setup initial parameters
FAmbientColor.SetColor(0.15, 0.15, 0.15, 1);
FDiffuseColor.SetColor(1, 1, 1, 1);
FSpecularColor.SetColor(1, 1, 1, 1);
end;
destructor TGLCustomGLSLDiffuseSpecularShaderAM.Destroy;
begin
FAmbientColor.Destroy;
FDiffuseColor.Destroy;
FSpecularColor.Destroy;
inherited;
end;
procedure TGLCustomGLSLDiffuseSpecularShaderAM.DoApply(var rci: TRenderContextInfo;
Sender: TObject);
begin
inherited;
Param['AmbientColor'].AsVector4f := FAmbientColor.Color;
Param['DiffuseColor'].AsVector4f := FDiffuseColor.Color;
Param['SpecularColor'].AsVector4f := FSpecularColor.Color;
end;
procedure TGLCustomGLSLDiffuseSpecularShaderAM.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
GetFragmentProgramCodeAM(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci));
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
function TGLCustomGLSLDiffuseSpecularShaderAM.GetAlpha: Single;
begin
Result := (FAmbientColor.Alpha + FDiffuseColor.Alpha + FSpecularColor.Alpha) / 3;
end;
procedure TGLCustomGLSLDiffuseSpecularShaderAM.SetAlpha(const Value: Single);
begin
FAmbientColor.Alpha := Value;
FDiffuseColor.Alpha := Value;
FSpecularColor.Alpha := Value;
end;
{ TGLCustomGLSLDiffuseSpecularShaderMT }
procedure TGLCustomGLSLDiffuseSpecularShaderMT.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci));
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
{ TGLCustomGLSLDiffuseSpecularShader }
procedure TGLCustomGLSLDiffuseSpecularShader.DoApply(
var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
Param['MainTexture'].AsVector1i := 0; // Use the current texture.
end;
procedure TGLCustomGLSLDiffuseSpecularShader.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
begin
GetVertexProgramCode(VertexProgram.Code, IsFogEnabled(FFogSupport, rci), rci);
GetFragmentProgramCode(FragmentProgram.Code, FRealisticSpecular, IsFogEnabled(FFogSupport, rci));
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
{ TGLCustomGLSLMLDiffuseSpecularShader }
constructor TGLCustomGLSLMLDiffuseSpecularShader.Create(
AOwner: TComponent);
begin
inherited;
FLightCount := 1;
FLightCompensation := 1;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.DoApply(var rci: TRenderContextInfo; Sender: TObject);
begin
inherited;
Param['MainTexture'].AsVector1i := 0; // Use the current texture.
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
begin
GetMLVertexProgramCode(VertexProgram.Code);
with FragmentProgram.Code do
begin
GetMLFragmentProgramCodeBeg(FragmentProgram.Code);
// Repeat for all lights.
for I := 0 to FLightCount - 1 do
GetMLFragmentProgramCodeMid(FragmentProgram.Code, I);
GetMLFragmentProgramCodeEnd(FragmentProgram.Code, FLightCount, FLightCompensation, FRealisticSpecular);
end;
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.SetLightCompensation(
const Value: Single);
begin
FLightCompensation := Value;
FinalizeShader;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShader.SetLightCount(
const Value: Integer);
begin
Assert(FLightCount > 0, glsErrorEx + glsShaderNeedsAtLeastOneLightSource);
FLightCount := Value;
FinalizeShader;
end;
{ TGLCustomGLSLMLDiffuseSpecularShaderMT }
constructor TGLCustomGLSLMLDiffuseSpecularShaderMT.Create(
AOwner: TComponent);
begin
inherited;
FLightCount := 1;
FLightCompensation := 1;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShaderMT.DoInitialize(var rci: TRenderContextInfo; Sender: TObject);
var
I: Integer;
begin
GetMLVertexProgramCode(VertexProgram.Code);
with FragmentProgram.Code do
begin
GetMLFragmentProgramCodeBeg(FragmentProgram.Code);
// Repeat for all lights.
for I := 0 to FLightCount - 1 do
GetMLFragmentProgramCodeMid(FragmentProgram.Code, I);
GetMLFragmentProgramCodeEnd(FragmentProgram.Code, FLightCount, FLightCompensation, FRealisticSpecular);
end;
VertexProgram.Enabled := True;
FragmentProgram.Enabled := True;
inherited;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShaderMT.SetLightCompensation(
const Value: Single);
begin
FLightCompensation := Value;
FinalizeShader;
end;
procedure TGLCustomGLSLMLDiffuseSpecularShaderMT.SetLightCount(
const Value: Integer);
begin
Assert(FLightCount > 0, glsErrorEx + glsShaderNeedsAtLeastOneLightSource);
FLightCount := Value;
FinalizeShader;
end;
initialization
RegisterClasses([
TGLCustomGLSLDiffuseSpecularShader,
TGLCustomGLSLDiffuseSpecularShaderAM,
TGLCustomGLSLDiffuseSpecularShaderMT,
TGLCustomGLSLMLDiffuseSpecularShader,
TGLCustomGLSLMLDiffuseSpecularShaderMT,
TGLSLDiffuseSpecularShader,
TGLSLDiffuseSpecularShaderAM,
TGLSLDiffuseSpecularShaderMT,
TGLSLMLDiffuseSpecularShader,
TGLSLMLDiffuseSpecularShaderMT
]);
end.
|
//------------------------------------------------------------------------------
//CharacterServer UNIT
//------------------------------------------------------------------------------
// What it does-
// The Character Server Class.
// An object type that contains all information about a character server
// This unit is to help for future design of multi server communication IF
// the user were to want to do so. Else, it would act as an all-in-one.
// Only one type in this unit for the time being.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// June 28th, 2008 - Tsusai - Updated GetPacketLength to PacketDB.GetLength
// in various calls
//
//------------------------------------------------------------------------------
unit CharacterServer;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Character,
IdContext,
CommClient,
List32,
SysUtils,
PacketTypes,
CharaOptions,
Server;
type
//------------------------------------------------------------------------------
//TCharacterServer CLASS
//------------------------------------------------------------------------------
TCharacterServer = class(TServer)
protected
fZoneServerList : TIntList32;
fAccountList : TIntList32;
CharaToLoginClient : TInterClient;
Procedure OnConnect(AConnection: TIdContext);override;
Procedure OnExecute(AConnection: TIdContext);override;
Procedure OnDisconnect(AConnection: TIdContext);override;
Procedure OnException(AConnection: TIdContext;
AException: Exception);override;
procedure LoginClientOnConnect(Sender : TObject);
procedure LoginClientKickAccount(
AClient : TInterClient;
var InBuffer : TBuffer
);
procedure LoginClientRead(AClient : TInterClient);
procedure VerifyZoneServer(
AClient : TIdContext;
InBuffer : TBuffer
);
procedure UpdateToAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
procedure RemoveFromAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
function WriteCharacterDataToBuffer(
ACharacter : TCharacter;
var ReplyBuffer : TBuffer;
const Offset : Integer
) : Byte;
procedure SendCharas(AClient : TIdContext; var ABuffer : TBuffer);
procedure SendCharaToMap(AClient : TIdContext; var ABuffer : TBuffer);
procedure CreateChara(AClient : TIdContext; var ABuffer : TBuffer);
procedure DeleteChara(AClient : TIdContext; var ABuffer : Tbuffer);
procedure RenameChara(AClient : TIdContext; var ABuffer : Tbuffer);
procedure RenameCharaResult(AClient : TIdContext;const Flag:Word);
procedure DoRenameChara(AClient : TIdContext; var ABuffer : Tbuffer);
Procedure LoadOptions;
public
ServerName : String;
Options : TCharaOptions;
Constructor Create();
Destructor Destroy();Override;
Procedure Start();override;
Procedure Stop();override;
Procedure ConnectToLogin();
function GetOnlineUserCount : Word;
procedure UpdateOnlineCountToZone;
end;
//------------------------------------------------------------------------------
implementation
uses
Math,
//Helios
BeingList,
CharAccountInfo,
CharaLoginCommunication,
ZoneCharaCommunication,
BufferIO,
Account,
GameConstants,
Globals,
TCPServerRoutines,
ZoneServerInfo,
ItemTypes,
//3rd
Types,
StrUtils,
Main;
const
INVALIDNAME = 0;
INVALIDMISC = 2;
DELETEBADCHAR = 1;
DELETEBADEMAIL = 0;
//------------------------------------------------------------------------------
//Create () CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Initializes our character server
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
// January 14th, 2007 - Tsusai - Updated CharaClient create, and initialized
// the fZoneServerList
//
//------------------------------------------------------------------------------
Constructor TCharacterServer.Create;
begin
inherited;
CharaToLoginClient := TInterClient.Create('Character','Login', true, MainProc.Options.ReconnectDelay);
CharaToLoginClient.OnConnected := LoginClientOnConnect;
CharaToLoginClient.OnReceive := LoginClientRead;
fZoneServerList := TIntList32.Create;
fAccountList := TIntList32.Create;
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy() DESTRUCTOR
//------------------------------------------------------------------------------
// What it does-
// Destroys our character server
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
// January 14th, 2007 - Tsusai - Frees fZoneServerList
//
//------------------------------------------------------------------------------
Destructor TCharacterServer.Destroy;
begin
CharaToLoginClient.Free;
fZoneServerList.Free;
fAccountList.Free;
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnException EVENT
//------------------------------------------------------------------------------
// What it does-
// Handles Socket exceptions gracefully by outputting the exception message
// and then disconnecting the client.
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.OnException(AConnection: TIdContext;
AException: Exception);
begin
if AnsiContainsStr(AException.Message, '10053') or
AnsiContainsStr(AException.Message, '10054')
then begin
AConnection.Connection.Disconnect;
end;
end;{OnException}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Start() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Enables the character server to accept incoming connections
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TCharacterServer.Start();
begin
if NOT Started then
begin
LoadOptions;
ServerName := Options.ServerName;
Port := Options.Port;
ActivateServer('Character',TCPServer, Options.IndySchedulerType, Options.IndyThreadPoolSize);
WANIP := Options.WANIP;
LANIP := Options.LANIP;
inherited;
end else
begin
Console.Message('Cannot Start():: Character Server is already running!', 'Character Server', MS_ALERT);
end;
end;{Start}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Stop() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Stops the character server from accepting incoming connections
//
// Changes -
// September 19th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TCharacterServer.Stop();
var
Index : Integer;
begin
if Started then
begin
inherited;
DeActivateServer('Character',TCPServer);
DeActivateClient(CharaToLoginClient);
//Free up our existing server info objects
for Index := fZoneServerList.Count - 1 downto 0 do
begin
TZoneServerInfo(fZoneServerList[Index]).Free;
fZoneServerList.Delete(Index);
end;
Options.Save;
Options.Free;
end else
begin
Console.Message('Cannot Stop():: Character Server is not running', 'Character Server', MS_ALERT);
end;
end;{Start}
//------------------------------------------------------------------------------
//Tsusai
//Write information about the character into the buffer
//Takes into account the ini flag to use clients from Dec 2006 and newer
function TCharacterServer.WriteCharacterDataToBuffer(
ACharacter : TCharacter;
var ReplyBuffer : TBuffer;
const Offset : Integer
) : Byte;
begin
Result := 112;
FillChar(ReplyBuffer[Offset],Offset + Result,0);
with ACharacter do begin
WriteBufferLongWord(Offset + 0, ID,ReplyBuffer);
WriteBufferLongWord(Offset + 4, BaseEXP,ReplyBuffer);
WriteBufferLongWord(Offset + 8, Zeny,ReplyBuffer);
WriteBufferLongWord(Offset + 12, JobEXP,ReplyBuffer);
WriteBufferLongWord(Offset + 16, JobLV,ReplyBuffer);
WriteBufferLongWord(Offset + 20, 0,ReplyBuffer);
WriteBufferLongWord(Offset + 24, 0,ReplyBuffer);
WriteBufferLongWord(Offset + 28, Option,ReplyBuffer);
WriteBufferLongWord(Offset + 32, Karma,ReplyBuffer);
WriteBufferLongWord(Offset + 36, Manner,ReplyBuffer);
WriteBufferWord(Offset + 40, EnsureRange(StatusPts, 0, High(SmallInt)),ReplyBuffer);
WriteBufferLongWord(Offset + 42, EnsureRange(HP, 0, High(SmallInt)),ReplyBuffer);
WriteBufferLongWord(Offset + 46, EnsureRange(MAXHP, 0, High(SmallInt)),ReplyBuffer);
WriteBufferWord(Offset + 50, EnsureRange(SP, 0, High(SmallInt)),ReplyBuffer);
WriteBufferWord(Offset + 52, EnsureRange(MAXSP, 0, High(SmallInt)),ReplyBuffer);
WriteBufferWord(Offset + 54, Speed,ReplyBuffer);
WriteBufferWord(Offset + 56, JID,ReplyBuffer);
WriteBufferWord(Offset + 58, Hair,ReplyBuffer);
WriteBufferWord(Offset + 60, Equipment.SpriteID[RIGHTHAND],ReplyBuffer);
WriteBufferWord(Offset + 62, BaseLV,ReplyBuffer);
WriteBufferWord(Offset + 64, EnsureRange(SkillPts, 0, High(Word)),ReplyBuffer);
WriteBufferWord(Offset + 66, Equipment.SpriteID[HEADLOWER],ReplyBuffer);
WriteBufferWord(Offset + 68, Equipment.SpriteID[LEFTHAND],ReplyBuffer);
WriteBufferWord(Offset + 70, Equipment.SpriteID[HEADUPPER],ReplyBuffer);
WriteBufferWord(Offset + 72, Equipment.SpriteID[HEADMID],ReplyBuffer);
WriteBufferWord(Offset + 74, HairColor,ReplyBuffer);
WriteBufferWord(Offset + 76, ClothesColor,ReplyBuffer);
WriteBufferString(Offset + 78, Name, 24,ReplyBuffer);
WriteBufferByte(Offset + 102, EnsureRange(ParamBase[STR], 0, High(Byte)),ReplyBuffer);
WriteBufferByte(Offset + 103, EnsureRange(ParamBase[AGI], 0, High(Byte)),ReplyBuffer);
WriteBufferByte(Offset + 104, EnsureRange(ParamBase[VIT], 0, High(Byte)),ReplyBuffer);
WriteBufferByte(Offset + 105, EnsureRange(ParamBase[INT], 0, High(Byte)),ReplyBuffer);
WriteBufferByte(Offset + 106, EnsureRange(ParamBase[DEX], 0, High(Byte)),ReplyBuffer);
WriteBufferByte(Offset + 107, EnsureRange(ParamBase[LUK], 0, High(Byte)),ReplyBuffer);
WriteBufferWord(Offset + 108, CharaNum,ReplyBuffer);
WriteBufferWord(Offset + 110, 1,ReplyBuffer); //Rename Flag
end;
end;
//------------------------------------------------------------------------------
//LoginClientOnConnect() EVENT
//------------------------------------------------------------------------------
// What it does-
// Executed on connection to the login server.
//
// Changes -
// January 4th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.LoginClientOnConnect(Sender : TObject);
begin
ValidateWithLoginServer(CharaToLoginClient,Self);
end;{LoginClientOnConnect}
//------------------------------------------------------------------------------
procedure TCharacterServer.LoginClientKickAccount(
AClient : TInterClient;
var InBuffer : TBuffer
);
var
AccountID : LongWord;
Idx : Integer;
ZoneIdx : Integer;
AccountInfo : TCharAccountInfo;
OutBuffer : TBuffer;
begin
AccountID := BufferReadLongWord(2, InBuffer);
Idx := fAccountList.IndexOf(AccountID);
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[Idx] as TCharAccountInfo;
if AccountInfo.InGame then
begin
//If we can't find the zone, just forget about it
//Most cause will be connection between zone and char server is dropped.
ZoneIdx := fZoneServerList.IndexOf(AccountInfo.ZoneServerID);
if ZoneIdx > -1 then
begin
SendKickAccountToZone(TZoneServerInfo(fZoneServerList.Objects[idx]).Connection, AccountInfo.CharacterID);
end;
end else begin
//Show "Someone has already logged in with this ID" ?
if Options.ShowFriendlyMessageOnDupLogin then
begin
FillChar(OutBuffer, PacketDB.GetLength($0081), 0);
WriteBufferWord(0, $0081, OutBuffer);
WriteBufferByte(2, 2, OutBuffer);
SendBuffer(AccountInfo.ClientInfo, OutBuffer, PacketDB.GetLength($0081));
end;
AccountInfo.ClientInfo.Connection.Disconnect;
end;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnConnect EVENT
//------------------------------------------------------------------------------
// What it does-
// Nothing
//
// Changes -
//
//------------------------------------------------------------------------------
procedure TCharacterServer.OnConnect(AConnection: TIdContext);
begin
end;{OnConnect}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoginClientRead() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Reads information sent from the login server.
//
// Changes -
// January 3rd, 2007 - Tsusai - Added console messages.
// January 4th, 2007 - RaX - Created Header.
// January 14th, 2007 - Tsusai - Updated procedure calls.
// April 10th, 2007 - Aeomin - Updated to support Server ID.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.LoginClientRead(AClient : TInterClient);
var
ABuffer : TBuffer;
PacketID : Word;
Response : Byte;
begin
RecvBuffer(AClient,ABuffer,2);
PacketID := BufferReadWord(0,ABuffer);
case PacketID of
$2001:
begin
RecvBuffer(AClient,ABuffer[2],PacketDB.GetLength($2001)-2);
Response := BufferReadByte(2,ABuffer);
if Response = 0 then
begin
Console.Message('Verified with Login Server, '+
'sending details.', 'Character Server', MS_NOTICE);
SendCharaWANIPToLogin(CharaToLoginClient,Self);
SendCharaLANIPToLogin(CharaToLoginClient,Self);
SendCharaOnlineUsersToLogin(CharaToLoginClient,Self);
end else
begin
case Response of
1 : Console.Message('Failed to verify with Login Server. ID already in use.', 'Character Server', MS_WARNING);
2 : Console.Message('Failed to verify with Login Server. Invalid security key.', 'Character Server', MS_WARNING);
end;
Console.Message('Stopping...', 'Zone Server', MS_NOTICE);
Stop;
end;
end;
$2007:
begin
RecvBuffer(AClient,ABuffer[2],PacketDB.GetLength($2007)-2);
LoginClientKickAccount(AClient, ABuffer);
end;
end;
end;{LoginClientRead}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SendCharas PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Verifies the new connection by checking the account ID which is received
// and the two random keys generated during login. Upon validation, check
// database for any/all created characters. If found any, send to client.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// July 6th, 2006 - Tsusai - Started work on changing dummy procedure to real
// procedure.
// January 3rd, 2007 - Tsusai - Added console messages.
// January 20th, 2007 - Tsusai - Wrapped the console messages, now using
// IdContext.Binding shortcut
// March 12th, 2007 - Aeomin - Modified Header.
// April 12th, 2007 - Aeomin - Append check to disallow 0 of LoginKey
//
//------------------------------------------------------------------------------
procedure TCharacterServer.SendCharas(AClient : TIdContext; var ABuffer : TBuffer);
const
Ver : Byte = 24;
CharacterDataSize : Byte = 112;
var
AccountID : LongWord;
AnAccount : TAccount;
ReplyBuffer : TBuffer;
ACharacter : TCharacter;
Index : integer;
Count : Byte;
PacketSize : Word;
ACharaList : TBeingList;
BaseIndex : Integer;
Idx : Integer;
AccountInfo : TCharAccountInfo;
begin
Count := 0;
AccountID := BufferReadLongWord(2, ABuffer);
AnAccount := TAccount.Create(AClient);
AnAccount.ID := AccountID;
TThreadLink(AClient.Data).DatabaseLink.Account.Load(AnAccount);
if (AnAccount.LoginKey[1] = BufferReadLongWord(6, ABuffer)) and (AnAccount.LoginKey[1] > 0) and
(AnAccount.LoginKey[2] = BufferReadLongWord(10, ABuffer)) and (AnAccount.LoginKey[2] > 0) then
begin
//LINK the account to the client connection for the other procedures
TClientLink(AClient.Data).AccountLink := AnAccount;
SendPadding(AClient, AccountID);
ACharaList := TBeingList.Create(TRUE);
TThreadLink(AClient.Data).DatabaseLink.Character.LoadByAccount(ACharaList, AnAccount);
Idx := fAccountList.IndexOf(AnAccount.ID);
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[idx] as TCharAccountInfo;
//Make sure no dup login via skip server.
if (not AccountInfo.Transfering)or(AccountInfo.InGame) then
begin //Reject!
WriteBufferWord(0, $006a, ReplyBuffer);
WriteBufferByte(2, 03, ReplyBuffer);
SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($006a));
end else
begin
AccountInfo.ClientInfo := AClient;
TClientLink(AClient.Data).AccountInfo := AccountInfo;
end;
end else
begin
AccountInfo := TCharAccountInfo.Create(AnAccount.ID);
AccountInfo.ClientInfo := AClient;
TClientLink(AClient.Data).AccountInfo := AccountInfo;
AccountInfo.Transfering := True;
fAccountList.AddObject(AnAccount.ID, AccountInfo);
SendAccountLogon(CharaToLoginClient, AccountInfo, Self);
end;
//Ah..lets make sure again
if (AccountInfo.Transfering)or(not AccountInfo.InGame) then
begin
for Index := ACharaList.Count-1 downto 0 do
begin
ACharacter := ACharaList.Items[Index] as TCharacter;
AnAccount.CharaID[ACharacter.CharaNum] := ACharacter.ID;
with ACharacter do
begin
BaseIndex := Ver+(Count*CharacterDataSize);
TThreadLink(AClient.Data).DatabaseLink.Items.GetSpriteIDs(
ACharacter.Equipment
);
WriteCharacterDataToBuffer(ACharacter,ReplyBuffer,BaseIndex);
Inc(Count);
end;
ACharaList.Delete(Index);
end;
//size is (24 + (character count * Character data size))
PacketSize := (Ver + (Count * CharacterDataSize));
WriteBufferWord(0,$006b,ReplyBuffer); //header
WriteBufferWord(2,PacketSize,ReplyBuffer);
SendBuffer(AClient,ReplyBuffer,PacketSize);
end;
ACharaList.Free;
AccountInfo.Transfering := False;
end else
begin
WriteBufferWord(0, $0081, ReplyBuffer);
WriteBufferByte(2, 01, ReplyBuffer);
SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($0081));
Console.Message(
'Connecting RO client from '+
AClient.Binding.PeerIP +
' did not pass key validation.', 'Character Server', MS_WARNING
);
AClient.Connection.Disconnect;
end;
end; {SendCharas}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SendCharaToMap PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Refers a character to whatever map server is handling the map that the
// character is on.
//
// Changes -
// December 17th, 2006 - RaX - Created Header. - Stubbed for later use.
// January 20th, 2007 - Tsusai - Now using IdContext.Binding shortcut,
// Removed extra comma inthe ZserverAddress procedure (Kylix caught this)
// March 30th, 2007 - Aeomin - Changed server down Error Code from 3 to 1
//------------------------------------------------------------------------------
procedure TCharacterServer.SendCharaToMap(
AClient : TIdContext;
var ABuffer : TBuffer
);
var
AnAccount : TAccount;
CharaIdx : Byte;
ACharacter : TCharacter;
OutBuffer : TBuffer;
ZServerInfo : TZoneServerInfo;
ZoneID : Integer;
idx : integer;
begin
AnAccount := TClientLink(AClient.Data).AccountLink;
//Tsusai: Possible Check for online characters here...but
//they should be terminated when logging in.
CharaIdx := BufferReadByte(2, ABuffer);
if (CharaIdx < 9) AND (AnAccount.CharaID[CharaIdx] > 0) then
begin
ACharacter := TCharacter.Create(AClient);
ACharacter.ID := AnAccount.CharaID[CharaIdx];
TThreadLink(AClient.Data).DatabaseLink.Character.Load(ACharacter);
//ACharacter.ClientVersion := -1; //Need to either save, or make sure its cleared
//later on
if TThreadLink(AClient.Data).DatabaseLink.Map.CantSave(ACharacter.Map) then
begin
ACharacter.Map := ACharacter.SaveMap;
ACharacter.Position := ACharacter.SavePoint;
end;
//get zone ID for the map.
ZoneID := TThreadLink(AClient.Data).DatabaseLink.Map.GetZoneID(ACharacter.Map);
//get the zone info from that
idx := fZoneServerList.IndexOf(ZoneID);
if idx > -1 then
begin
TThreadLink(AClient.Data).DatabaseLink.Character.Save(ACharacter);
TClientLink(AClient.Data).AccountInfo.CharacterID := ACharacter.ID;
TClientLink(AClient.Data).Transfering := True;
ZServerInfo := TZoneServerInfo(fZoneServerList.Objects[idx]);
WriteBufferWord(0, $0071, OutBuffer);
WriteBufferLongWord(2, ACharacter.ID, OutBuffer);
WriteBufferString(6, ACharacter.Map + '.rsw', 16, OutBuffer);
WriteBufferLongWord(22,
ZServerInfo.Address(AClient.Binding.PeerIP
),
OutBuffer
);
WriteBufferWord(26, ZServerInfo.Port, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($0071));
end else
begin
//Server offline error goes here
WriteBufferWord(0, $0081, Outbuffer);
WriteBufferByte(2, 01, OutBuffer);
SendBuffer(AClient, OutBuffer, PacketDB.GetLength($0081));
end;
ACharacter.Free;
end;
end;{SendCharaToMap}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//CreateChara PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Is called after creating a character in the client.
// Creates and saves the character object
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// July 6th, 2006 - Tsusai - Started work on changing dummy procedure to
// real procedure.
// January 12th, 2007 - Tsusai - Fixed Stat point display.
// September 29th 2008 - Tsusai - Corrected InventoryID spelling error.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.CreateChara(
AClient : TIdContext;
var ABuffer : TBuffer
);
var
CharaName : string;
StatPoints : array [0..5] of byte;
HairStyle : byte;
HairColor : byte;
SlotNum : byte;
ACharacter : TCharacter;
Account : TAccount;
ReplyBuffer: TBuffer;
idx : byte;
TotalStatPt: byte;
Validated : Boolean;
Size : integer;
procedure CreateCharaError(const Error : byte);
var
ReplyBuf : TBuffer;
begin
WriteBufferWord(0, $006e, ReplyBuf);
WriteBufferByte(2, Error, ReplyBuf);
SendBuffer(AClient,ReplyBuf,PacketDB.GetLength($006e));
end;
begin
Validated := TRUE; //Assume passes all checks.
Account := TClientLink(AClient.Data).AccountLink;
CharaName := BufferReadString(2,24,ABuffer);
SlotNum := BufferReadByte(32,ABuffer);
HairColor := BufferReadByte(33,ABuffer);
HairStyle := BufferReadByte(35,ABuffer);
TotalStatPt := 0;
//Name Check.
ACharacter := TCharacter.Create(AClient);
try
ACharacter.Name := CharaName;
if NOT TThreadLink(AClient.Data).DatabaseLink.Character.Exists(ACharacter) then
begin
//Stat Point check.
for idx := 0 to 5 do begin
StatPoints[idx] := BufferReadByte(idx+26,ABuffer);
if (StatPoints[idx] < 1) or (StatPoints[idx] > 9) then
begin
CreateCharaError(INVALIDMISC);
Validated := FALSE;
end else
begin
Inc(TotalStatPt,StatPoints[idx]);
end;
end;
//Stat Point check.
if TotalStatPt <> 30 then begin
CreateCharaError(INVALIDMISC);
Validated := FALSE;
end;
//Slot Check.
ACharacter.CharaNum := SlotNum;
if TThreadLink(AClient.Data).DatabaseLink.Character.Exists(ACharacter) then
begin
CreateCharaError(INVALIDMISC);
Validated := FALSE;
end;
//Did we pass all the checks?
if Validated then
begin
//Validated...Procede with creation
//Set a record in Database for our new character
ACharacter.AccountID := Account.ID;
ACharacter.Inventory.InventoryID := TThreadLink(AClient.Data).DatabaseLink.Character.CreateInventory;
TThreadLink(AClient.Data).DatabaseLink.Character.New(ACharacter);
TThreadLink(AClient.Data).DatabaseLink.Character.Load(ACharacter);
//All other info is already saved
ACharacter.BaseLV := 1;
ACharacter.JobLV := 1;
ACharacter.JID := 0;
ACharacter.Zeny := Options.DefaultZeny;
ACharacter.ParamBase[STR] := StatPoints[0];
ACharacter.ParamBase[AGI] := StatPoints[1];
ACharacter.ParamBase[VIT] := StatPoints[2];
ACharacter.ParamBase[INT] := StatPoints[3];
ACharacter.ParamBase[DEX] := StatPoints[4];
ACharacter.ParamBase[LUK] := StatPoints[5];
ACharacter.CalcMaxHP;
ACharacter.CalcMaxSP;
ACharacter.CalcSpeed;
ACharacter.CalcMaxWeight;
ACharacter.CalcASpeed;
ACharacter.HP := ACharacter.MaxHP;
ACharacter.SP := ACharacter.MaxSP;
ACharacter.StatusPts := 0;
ACharacter.SkillPts := 0;
ACharacter.Option := 0;
ACharacter.Karma := 0;
ACharacter.Manner := 0;
ACharacter.PartyID := 0;
ACharacter.GuildID := 0;
ACharacter.PetID := 0;
ACharacter.Hair := EnsureRange(HairStyle,0,Options.MaxHairStyle);
ACharacter.HairColor := EnsureRange(HairColor,0,Options.MaxHairColor);
ACharacter.ClothesColor := 0;
if Options.DefaultHeadTop > 0 then
ACharacter.Inventory.Add(Options.DefaultHeadTop,1,True);
if Options.DefaultHeadMid > 0 then
ACharacter.Inventory.Add(Options.DefaultHeadMid,1,True);
if Options.DefaultHeadLow > 0 then
ACharacter.Inventory.Add(Options.DefaultHeadLow,1,True);
if Options.DefaultRightHand >0 then
ACharacter.Inventory.Add(Options.DefaultRightHand,1,True);
if Options.DefaultLeftHand > 0 then
ACharacter.Inventory.Add(Options.DefaultLeftHand,1,True);
if Options.DefaultArmor > 0 then
ACharacter.Inventory.Add(Options.DefaultArmor,1,True);
if Options.DefaultShoes > 0 then
ACharacter.Inventory.Add(Options.DefaultShoes,1,True);
if Options.DefaultGarment > 0 then
ACharacter.Inventory.Add(Options.DefaultGarment,1,True);
if Options.DefaultAccessory1 > 0 then
ACharacter.Inventory.Add(Options.DefaultAccessory1,1,True);
if Options.DefaultAccessory2 > 0 then
ACharacter.Inventory.Add(Options.DefaultAccessory2,1,True);
// ACharacter.Equipment.EquipmentID[RIGHTHAND] := Options.DefaultRightHand;
// ACharacter.Equipment.EquipmentID[LEFTHAND] := Options.DefaultLeftHand;
// ACharacter.Equipment.EquipmentID[BODY] := Options.DefaultArmor;
// ACharacter.Equipment.EquipmentID[CAPE] := Options.DefaultGarment;
// ACharacter.Equipment.EquipmentID[FEET] := Options.DefaultShoes;
// ACharacter.Equipment.EquipmentID[ACCESSORY1] := Options.DefaultAccessory1;
// ACharacter.Equipment.EquipmentID[ACCESSORY2] := Options.DefaultAccessory2;
// ACharacter.Equipment.EquipmentID[HEADUPPER] := Options.DefaultHeadTop;
// ACharacter.Equipment.EquipmentID[HEADMID] := Options.DefaultHeadMid;
// ACharacter.Equipment.EquipmentID[HEADLOWER] := Options.DefaultHeadLow;
ACharacter.Map := Options.DefaultMap;
ACharacter.Position := Point(Options.DefaultPoint.X,Options.DefaultPoint.Y);
ACharacter.SaveMap := Options.DefaultMap;
ACharacter.SavePoint := Point(Options.DefaultPoint.X,Options.DefaultPoint.Y);
ACharacter.PartnerID := 0;
ACharacter.ParentID1 := 0;
ACharacter.ParentID2 := 0;
ACharacter.BabyID := 0;
ACharacter.Online := 0;
ACharacter.HomunID := 0;
//INSERT ANY OTHER CREATION CHANGES HERE!
TThreadLink(AClient.Data).DatabaseLink.Character.Save(ACharacter);
Account.CharaID[ACharacter.CharaNum] := ACharacter.ID;
WriteBufferWord(0, $006d,ReplyBuffer);
Size := WriteCharacterDataToBuffer(ACharacter,ReplyBuffer,2);
SendBuffer(AClient,ReplyBuffer,Size+2);
end;
end else
begin
CreateCharaError(INVALIDNAME);
end;
finally
ACharacter.Free;
end;
end;{CreateChara}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//DeleteChara PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Delete's a character after client request and criteria are met
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.DeleteChara(
AClient : TIdContext;
var ABuffer : Tbuffer
);
var
CharacterID : LongWord;
AnEmail : string;
AnAccount : TAccount;
ACharacter : TCharacter;
ReplyBuffer : TBuffer;
procedure DeleteCharaError(const Error : byte);
begin
WriteBufferWord(0, $0070, ReplyBuffer);
WriteBufferByte(2, Error, ReplyBuffer);
SendBuffer(AClient,ReplyBuffer,PacketDB.GetLength($0070));
end;
begin
CharacterID := BufferReadLongWord(2,ABuffer);
AnEmail := BufferReadString(6,40,ABuffer);
AnAccount := TClientLink(AClient.Data).AccountLink;
ACharacter := TCharacter.Create(AClient);
try
ACharacter.ID := CharacterID;
TThreadLink(AClient.Data).DatabaseLink.Character.Load(ACharacter);
if (AnAccount.EMail <> AnEmail) then
begin
DeleteCharaError(DELETEBADEMAIL);
end else
if (ACharacter.AccountID <> AnAccount.ID) then
begin
DeleteCharaError(DELETEBADCHAR);
end else
begin
TThreadLink(AClient.Data).DatabaseLink.Character.Delete(ACharacter);
WriteBufferWord(0, $006f, ReplyBuffer);
SendBuffer(AClient,ReplyBuffer, PacketDB.GetLength($006f));
end;
finally
ACharacter.Free;
end;
end;{DeleteChara}
//------------------------------------------------------------------------------
procedure TCharacterServer.RenameChara(AClient : TIdContext; var ABuffer : Tbuffer);
var
AccountID : LongWord;
{CharacterID : LongWord;}
NewName : String;
ReplyBuffer : TBuffer;
begin
AccountID := BufferReadLongWord(2,ABuffer);
{CharacterID := BufferReadLongWord(6,ABuffer);}
NewName := BufferReadString(10,24,ABuffer);
if (TClientLink(AClient.Data).AccountLink.ID = AccountID) then
begin
TClientLink(AClient.Data).NewCharName := NewName;
WriteBufferWord(0, $028e, ReplyBuffer);
WriteBufferWord(2, 1, ReplyBuffer); //Confirm
SendBuffer(AClient,ReplyBuffer, 4);
end else
begin
RenameCharaResult(
AClient,
2 //Failed
);
end;
end;
procedure TCharacterServer.RenameCharaResult(AClient : TIdContext;const Flag:Word);
var
ReplyBuffer : TBuffer;
begin
WriteBufferWord(0, $0290, ReplyBuffer);
WriteBufferWord(2, Flag, ReplyBuffer);
SendBuffer(AClient,ReplyBuffer, 4);
end;
procedure TCharacterServer.DoRenameChara(AClient : TIdContext; var ABuffer : Tbuffer);
var
CharacterID : LongWord;
AChara:TCharacter;
TargetChar :TCharacter;
begin
CharacterID := BufferReadLongWord(2,ABuffer);
if TClientLink(AClient.Data).NewCharName <> '' then
begin
AChara:=TCharacter.Create(nil);
TargetChar:=TCharacter.Create(nil);
try
AChara.Name := TClientLink(AClient.Data).NewCharName;
if TClientLink(AClient.Data).DatabaseLink.Character.Exists(AChara) then
begin
RenameCharaResult(
AClient,
4 //Name used
);
end else
begin
TargetChar.ID := CharacterID;
TClientLink(AClient.Data).DatabaseLink.Character.Load(TargetChar);
if TClientLink(AClient.Data).AccountLink.ID = TargetChar.AccountID then
begin
TClientLink(AClient.Data).DatabaseLink.Character.Rename(
TClientLink(AClient.Data).AccountLink.ID,
CharacterID,
TClientLink(AClient.Data).NewCharName
);
RenameCharaResult(
AClient,
0
);
end else
begin
RenameCharaResult(
AClient,
2
);
end;
end;
finally
AChara.Free;
TargetChar.Free;
end;
end else
begin
RenameCharaResult(
AClient,
2 //Failed
);
end;
end;
//------------------------------------------------------------------------------
//VerifyZoneServer PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Verify request connection from zone server
//
// Changes -
// January 14th, 2007 - Tsusai - Added
// January 20th, 2007 - Tsusai - Wrapped the console messages, now using
// IdContext.Binding shortcut
// March 12th, 2007 - Aeomin - Fix the header.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.VerifyZoneServer(
AClient : TIdContext;
InBuffer : TBuffer
);
var
Password : string;
Validated : byte;
ZServerInfo : TZoneServerInfo;
ID : LongWord;
begin
Validated := 0; //Assume true
Console.Message(
'Reading Zone Server connection from ' +
AClient.Binding.PeerIP, 'Character Server', MS_NOTICE
);
ID := BufferReadLongWord(2,InBuffer);
Password := BufferReadMD5(8,InBuffer);
if (fZoneServerList.IndexOf(ID) > -1) then
begin
Console.Message('Zone Server failed verification. ID already in use.', 'Character Server', MS_WARNING);
Validated := 1;
end;
if (Password <> GetMD5(Options.Key)) then
begin
Console.Message('Zone Server failed verification. Invalid Security Key.', 'Character Server', MS_WARNING);
Validated := 2;
end;
if Validated = 0 then
begin
Console.Message('Zone Server connection validated.','Character Server', MS_INFO);
ZServerInfo := TZoneServerInfo.Create;
ZServerInfo.ZoneID := ID;
ZServerInfo.Port := BufferReadWord(6,InBuffer);
ZServerInfo.Connection := AClient;
AClient.Data := TZoneServerLink.Create(AClient);
TZoneServerLink(AClient.Data).DatabaseLink := Database;
TZoneServerLink(AClient.Data).Info := ZServerInfo;
fZoneServerList.AddObject(ZServerInfo.ZoneID,ZServerInfo);
end;
SendValidateFlagToZone(AClient,Validated);
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//UpdateToAccountList PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Update the account data in list (ex, switching zone)
//
// Changes -
// April 12th, 2007 - Aeomin - Created Header
//
//------------------------------------------------------------------------------
procedure TCharacterServer.UpdateToAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
var
AccountID: LongWord;
Idx : Integer;
AccountInfo : TCharAccountInfo;
begin
AccountID := BufferReadLongWord(2, InBuffer);
Idx := fAccountList.IndexOf(AccountID);
//If already exist, just update it.
//Should be exist, since data is create upon connect to Char Server
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[Idx] as TCharAccountInfo;
AccountInfo.ZoneServerID := BufferReadWord(6, InBuffer);
AccountInfo.InGame := True;
AccountInfo.Transfering := False;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//RemoveFromAccountList PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Remove/Reset the account data in list (ex, Exit game/Return to character select)
//
// Changes -
// April 12th, 2007 - Aeomin - Created Header
//
//------------------------------------------------------------------------------
procedure TCharacterServer.RemoveFromAccountList(
AClient : TIdContext;
InBuffer : TBuffer
);
var
AccountID: LongWord;
Idx : Integer;
AccountInfo : TCharAccountInfo;
Action : Byte;
begin
AccountID := BufferReadLongWord(2, InBuffer);
Idx := fAccountList.IndexOf(AccountID);
//Should be exist, since data is create upon connect to Char Server
if Idx > -1 then
begin
AccountInfo := fAccountList.Objects[Idx] as TCharAccountInfo;
Action := BufferReadByte(6, InBuffer);
// 0 = Delete it and forward to Account Server..
// 1 = Keep data (Returning to Character Server..)
if Action = 0 then
begin
if AccountInfo.InGame then
begin
fAccountList.Delete(Idx);
SendAccountLogOut(CharaToLoginClient, AccountInfo, Self);
end;
end else
begin
AccountInfo.Transfering := True;
AccountInfo.InGame := False;
end;
end;
end;
//------------------------------------------------------------------------------
//OnExecute PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Root procedure to handling client connections to the Character Server.
// Incoming connections do not have a valid TThreadLink.AccountLink, so
// we check for that, and then assign as needed. Keeps the various checks to
// a minimum.
//
// Changes -
// December 17th, 2006 - RaX - Created Header.
// January 14th, 2007 - Tsusai - Added Zone server packet parsing.
// March 30th, 2007 - Tsusai - Added packets 0x2105 & 0x2106
// March 30th, 2007 - Aeomin - Change from TThreadLink to TClientLink
//
//------------------------------------------------------------------------------
procedure TCharacterServer.OnExecute(AConnection : TIdContext);
var
ABuffer : TBuffer;
PacketID : Word;
Size : Word;
begin
RecvBuffer(AConnection,ABuffer,2);
PacketID := BufferReadWord(0, ABuffer);
//Check to see if it is an already connected Client
if (AConnection.Data is TClientLink) then
begin
case PacketID of
$0066: // Character Selected -- Refer Client to Map Server
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($0066)-2);
SendCharaToMap(AConnection,ABuffer);
end;
$0067: // Create New Character
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($0067)-2);
CreateChara(AConnection,ABuffer);
end;
$01bf,
$0068: // Request to Delete Character
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($0068)-2);
DeleteChara(AConnection,ABuffer);
end;
$0187: //Client keep alive
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($0187)-2);
end;
$028d: //Enter Character Rename mode
begin
{RecvBuffer(AConnection,ABuffer[2],32);
RenameChara(AConnection,ABuffer);}
end;
$028f: // ??
begin
//<Char ID>
{RecvBuffer(AConnection,ABuffer[2],4);
DoRenameChara(AConnection,ABuffer);}
end
else
begin
Size := PacketDB.GetLength(PacketID);
Console.Message('Unknown Character Server Packet : ' + IntToHex(PacketID,4), 'Character Server', MS_WARNING);
if (Size-2 > 0) then
begin
Console.Message(IntToStr(Size-2) + ' additional bytes were truncated','Character Server', MS_WARNING);
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength(PacketID)-2);
end;
end;
end;
end else
begin
case PacketID of
$0065: // RO Client request to connect and get characters
begin
//Thread Data should have a TThreadLink object...if not, make one
AConnection.Data := TClientlink.Create(AConnection);
TClientLink(AConnection.Data).DatabaseLink := Database;
//Verify login and send characters
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($0065)-2);
SendCharas(AConnection,ABuffer);
end;
$2100: // Zone Server Connection request
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2100)-2);
VerifyZoneServer(AConnection,ABuffer);
end;
$2102: // Zone Server sending new WAN location details
begin
if AConnection.Data is TZoneServerLink then
begin
RecvBuffer(AConnection,ABuffer[2],2);
Size := BufferReadWord(2,ABuffer);
RecvBuffer(AConnection,ABuffer[4],Size-4);
TZoneServerLink(AConnection.Data).Info.WAN := BufferReadString(4,Size-4,ABuffer);
Console.Message('Received updated Zone Server WANIP.', 'Character Server', MS_NOTICE);
end;
end;
$2103: // Zone Server sending new LAN location details
begin
if AConnection.Data is TZoneServerLink then
begin
RecvBuffer(AConnection,ABuffer[2],2);
Size := BufferReadWord(2,ABuffer);
RecvBuffer(AConnection,ABuffer[4],Size-4);
TZoneServerLink(AConnection.Data).Info.LAN := BufferReadString(4,Size-4,ABuffer);
Console.Message('Received updated Zone Server LANIP.', 'Character Server', MS_NOTICE);
end;
end;
$2104: // Zone Server sending new Online User count (relink while running)
begin
if AConnection.Data is TZoneServerLink then
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2104)-2);
TZoneServerLink(AConnection.Data).Info.OnlineUsers := BufferReadWord(2,ABuffer);
if CharaToLoginClient.Connected then
begin
SendCharaOnlineUsersToLogin(CharaToLoginClient,Self);
end;
UpdateOnlineCountToZone;
Console.Message('Received updated Zone Server Online Users.', 'Character Server', MS_DEBUG);
end;
end;
$2105: // Zone Server sending decrease of online users by 1
begin
if AConnection.Data is TZoneServerLink then
begin
TZoneServerLink(AConnection.Data).Info.OnlineUsers :=
Min(TZoneServerLink(AConnection.Data).Info.OnlineUsers +1, High(Word));
SendCharaOnlineUsersToLogin(CharaToLoginClient,Self);
UpdateOnlineCountToZone;
Console.Message('Received updated Zone Server Online Users (+1).', 'Character Server', MS_DEBUG);
end;
end;
$2106: // Zone Server sending decrease of online users by 1
begin
if AConnection.Data is TZoneServerLink then
begin
TZoneServerLink(AConnection.Data).Info.OnlineUsers :=
Max(TZoneServerLink(AConnection.Data).Info.OnlineUsers -1, 0);
SendCharaOnlineUsersToLogin(CharaToLoginClient,Self);
UpdateOnlineCountToZone;
Console.Message('Received updated Zone Server Online Users (-1).', 'Character Server', MS_DEBUG);
end;
end;
$2108: //Zone send update an account in fAccountList
begin
if AConnection.Data is TZoneServerLink then
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2108)-2);
UpdateToAccountList(AConnection,ABuffer);
end;
end;
$2109: //Zone send remove an account in fAccountList
begin
if AConnection.Data is TZoneServerLink then
begin
RecvBuffer(AConnection,ABuffer[2],PacketDB.GetLength($2109)-2);
RemoveFromAccountList(AConnection,ABuffer);
end;
end;
else
begin
Console.Message('Unknown Character Server Packet : ' + IntToHex(PacketID,4), 'Character Server', MS_WARNING);
end;
end;
end;
end; {ParseCharaServ}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//ConnectToLogin PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Connects to the login server.
//
// Changes -
// January 25th, 2007 - RaX - Moved from Start().
//
//------------------------------------------------------------------------------
Procedure TCharacterServer.ConnectToLogin;
begin
CharaToLoginClient.Host := Options.LoginIP;
CharaToLoginClient.Port := Options.LoginPort;
ActivateClient(CharaToLoginClient);
end;//ConnectToLogin
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//LoadOptions PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Creates and Loads the inifile.
//
// Changes -
// January 4th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TCharacterServer.LoadOptions;
begin
Options := TCharaOptions.Create(MainProc.Options.ConfigDirectory+'/Character.ini');
Options.Load;
Options.Save;
end;{LoadOptions}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//OnDisconnect() EVENT
//------------------------------------------------------------------------------
// What it does-
// Executes when a client disconnects from the character server.
// Removes disconnected zone servers from the list.
//
// Changes -
// January 10th, 2007 - Tsusai - Created Header.
// March 12th, 2007 - Aeomin - Fix header (should be character
// server not login server)
// April 10th, 2007 - Aeomin - Added
//
//------------------------------------------------------------------------------
Procedure TCharacterServer.OnDisconnect(AConnection: TIdContext);
var
idx : integer;
AZoneServInfo : TZoneServerInfo;
AccountInfo : TCharAccountInfo;
begin
if AConnection.Data is TZoneServerLink then
begin
AZoneServInfo := TZoneServerLink(AConnection.Data).Info;
idx := fZoneServerList.IndexOfObject(AZoneServInfo);
if not (idx = -1) then
begin
fZoneServerList.Delete(idx);
end;
end else
if AConnection.Data is TClientLink then
begin
Idx := fAccountList.IndexOf(TClientLink(AConnection.Data).AccountLink.ID);
if (Idx > -1) and (not TClientLink(AConnection.Data).Transfering) then
begin
AccountInfo := fAccountList.Objects[Idx] as TCharAccountInfo;
SendAccountLogOut(CharaToLoginClient, AccountInfo, Self);
fAccountList.Delete(Idx);
end;
end;
if Assigned(AConnection.Data) then
begin
AConnection.Data.Free;
AConnection.Data:=nil;
end;
end;{OnDisconnect}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetOnlineUserCount() Procedure
//------------------------------------------------------------------------------
// What it does-
// Count total online players
//
// Changes -
// March 31th, 2007 - Aeomin - Added header.
//
//------------------------------------------------------------------------------
function TCharacterServer.GetOnlineUserCount : Word;
var
Index : integer;
begin
Result := 0;
for Index := fZoneServerList.Count - 1 downto 0 do
begin
Inc(Result,TZoneServerInfo(fZoneServerList.Objects[Index]).OnlineUsers);
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//UpdateOnlineCountToZone() Procedure
//------------------------------------------------------------------------------
// What it does-
// Send new online count to every zone server
//
// Changes -
// April 5th, 2007 - Aeomin - Added header.
//
//------------------------------------------------------------------------------
procedure TCharacterServer.UpdateOnlineCountToZone;
var
Count : Word;
Index : Integer;
begin
Count := GetOnlineUserCount;
for Index := fZoneServerList.Count - 1 downto 0 do
begin
SendOnlineCountToZone(TZoneServerInfo(fZoneServerList.Objects[Index]).Connection, Count);
end;
end;
//------------------------------------------------------------------------------
end.
|
unit FormMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ShellCtrls,
ComCtrls, ExtCtrls, Menus, process, LazUTF8, FormProgRun, config,
LockedQueue;
const
ICON_NORMAL = 0;
ICON_CHANGED = 1;
ICON_CONFLICT = 2;
MILLISEC = 1 / (24 * 60 * 60 * 1000);
type
TUpdaterQueue = specialize TLockedQueue<TShellTreeNode>;
{ TUpdateThread }
TUpdateThread = class(TThread)
procedure Execute; override;
end;
{ TFMain }
TFMain = class(TForm)
ImageList: TImageList;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
MenuItemStashPop: TMenuItem;
MenuItemStash: TMenuItem;
MenuItemGitGui: TMenuItem;
MenuItemGitk: TMenuItem;
MenuItemConsole: TMenuItem;
MenuItemMeld: TMenuItem;
MenuItemPull: TMenuItem;
NodeMenu: TPopupMenu;
TreeView: TShellTreeView;
UpdateTimer: TTimer;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure MenuItemConsoleClick(Sender: TObject);
procedure MenuItemGitGuiClick(Sender: TObject);
procedure MenuItemGitkClick(Sender: TObject);
procedure MenuItemMeldClick(Sender: TObject);
procedure MenuItemPullClick(Sender: TObject);
procedure MenuItemPushClick(Sender: TObject);
procedure MenuItemStashClick(Sender: TObject);
procedure MenuItemStashPopClick(Sender: TObject);
procedure NodeMenuPopup(Sender: TObject);
procedure TreeViewExpanded(Sender: TObject; Node: TTreeNode);
procedure TreeViewGetImageIndex(Sender: TObject; Node: TTreeNode);
procedure TreeViewGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure UpdateTimerTimer(Sender: TObject);
procedure QueueForUpdate(Node: TShellTreeNode);
procedure QueueForImmediateUpdate(Node: TShellTreeNode);
private
FUpdaterInbox: TUpdaterQueue;
FUpdateThread: TUpdateThread;
procedure QueryStatus(N: TShellTreeNode; RemoteUpdate: Boolean);
procedure AsyncQueryStatus(P: PtrInt);
procedure UpdateAllNodes(Root: TTreeNode);
function NodeHasTag(TagName: String): Boolean;
function NodeIsDirty: Boolean;
function NodeIsConflict: Boolean;
function NodeIsGit: Boolean;
function SelNode: TShellTreeNode;
procedure EnableTimer;
procedure DisableTimer;
end;
var
FMain: TFMain;
AppTerminating: Boolean;
implementation
{$ifdef windows}
uses
Windows;
{$endif}
procedure Print(Txt: String);
begin
{$ifdef windows}
OutputDebugString(PChar(Txt));
{$else}
Writeln(Txt);
{$endif}
end;
function GetExe(Name: String): String;
{$ifdef windows}
function TryProgPaths(Path: String): String;
begin
Result := GetEnvironmentVariableUTF8('ProgramW6432') + Path;
if FileExists(Result) then exit;
Result := GetEnvironmentVariableUTF8('programfiles') + Path;
if FileExists(Result) then exit;
Result := GetEnvironmentVariableUTF8('programfilesx86') + Path;
if FileExists(Result) then exit;
end;
{$endif}
begin
{$ifdef windows}
if Name = 'git' then
Result := TryProgPaths('\Git\bin\git.exe');
if Name = 'gitk' then
Result := TryProgPaths('\Git\bin\gitk');
if Name = 'meld' then
Result := TryProgPaths('\Meld\Meld.exe');
{$else}
Result := Name;
{$endif}
end;
procedure AddToolsToPath;
{$ifdef windows}
var
GitPath, MeldPath, PathVariable: String;
{$endif}
begin
{$ifdef windows}
GitPath := ExtractFileDir(GetExe('git'));
MeldPath := ExtractFileDir(GetExe('meld'));
PathVariable := GetEnvironmentVariableUTF8('PATH');
PathVariable := GitPath + ';' + MeldPath + ';' + PathVariable;
SetEnvironmentVariable('PATH', PChar(PathVariable));
{$endif}
end;
procedure StartWaitExe(Path: String; Cmd: String; Args: array of string; Wait: Boolean; Console: Boolean);
var
P: TProcess;
begin
P := TProcess2.Create(nil, Path, Cmd, Args);
if Wait then
P.Options := P.Options + [poWaitOnExit];
if not Console then
P.Options := P.Options + [poNoConsole];
P.Execute;
P.Free;
end;
function RunTool(Path: String; cmd: String; Args: array of string; out ConsoleOutput: String): Boolean;
var
P: TProcess;
begin
P := TProcess2.Create(nil, Path, Cmd, Args);
P.Options := P.Options + [poUsePipes, poNoConsole];
P.Execute;
ConsoleOutput := '';
repeat
Sleep(1);
if ThreadID = MainThreadID then
Application.ProcessMessages;
if AppTerminating then
P.Terminate(1);
until not P.Running;
while P.Output.NumBytesAvailable > 0 do
ConsoleOutput += Chr(P.Output.ReadByte);
while P.Stderr.NumBytesAvailable > 0 do
ConsoleOutput += Chr(P.Stderr.ReadByte);
Result := (P.ExitCode = 0);
P.Free;
end;
function RunGit(Node: TShellTreeNode; Args: array of String; out CmdOut: String): Boolean;
var
Path: String;
begin
Path := Node.FullFilename;
Result := RunTool(Path, 'git', Args, CmdOut);
end;
{$R *.lfm}
{ TUpdateThread }
procedure TUpdateThread.Execute;
var
Node: TShellTreeNode;
O: String;
begin
repeat
if FMain.FUpdaterInbox.Get(Node, 100) then begin
Print('update queue processing, halting update timer');
Synchronize(@FMain.DisableTimer);
repeat
Print('updating: ' + Node.ShortFilename);
if RunTool(Node.FullFilename, 'git', ['remote', 'update'], O) then begin
Application.QueueAsyncCall(@FMain.AsyncQueryStatus, PtrInt(Node));
end;
until not FMain.FUpdaterInbox.Get(Node, 100);
Print('queue empty, resuming update timer');
Synchronize(@FMain.EnableTimer);
end;
until AppTerminating;
end;
{ TFMain }
procedure TFMain.UpdateTimerTimer(Sender: TObject);
var
N: TShellTreeNode;
begin
N := TShellTreeNode(TreeView.TopItem);
while Assigned(N) do begin
QueryStatus(N, True);
N := TShellTreeNode(N.GetNext);
end;
end;
procedure TFMain.QueueForUpdate(Node: TShellTreeNode);
begin
FUpdaterInbox.Put(Node);
end;
procedure TFMain.QueueForImmediateUpdate(Node: TShellTreeNode);
begin
FUpdaterInbox.PutFront(Node);
end;
procedure TFMain.QueryStatus(N: TShellTreeNode; RemoteUpdate: Boolean);
var
Path: String;
O: String;
Behind: Boolean = False;
Ahead: Boolean = False;
Dirty: Boolean = False;
Conflict: Boolean = False;
Diverged: Boolean = False;
procedure ApplyTag(Name: String);
begin
N.Text := '[' + Name + '] ' + N.Text;
end;
function HasWord(w: String): Boolean;
begin
Result := Pos(W, O) > 0;
end;
procedure ApplyIcon(IconIdex: Integer);
begin
N.Data := {%H-}Pointer(IconIdex + 1);
end;
begin
Path := N.FullFilename;
if DirectoryExists(Path + DirectorySeparator + '.git') then begin
TreeView.BeginUpdate;
if RunGit(N, ['status'], O) then begin
N.Text := N.ShortFilename;
Conflict := HasWord('Unmerged');
Behind := HasWord('behind');
Ahead := HasWord('ahead');
Diverged := HasWord('diverged');
Dirty := HasWord('Changes');
if Behind then ApplyTag('BEHIND');
if Ahead then ApplyTag('AHEAD');
if Diverged then ApplyTag('DIVERGED');
if Dirty then ApplyTag('DIRTY');
if Conflict then ApplyTag('CONFLICT');
end;
if Conflict then
ApplyIcon(ICON_CONFLICT)
else if Dirty or Behind or Ahead or Diverged then
ApplyIcon(ICON_CHANGED)
else
ApplyIcon(ICON_NORMAL);
if RemoteUpdate then
QueueForUpdate(N);
TreeView.EndUpdate;
TreeView.Refresh;
end;
end;
procedure TFMain.AsyncQueryStatus(P: PtrInt);
begin
QueryStatus(TShellTreeNode(P), False);
end;
procedure TFMain.UpdateAllNodes(Root: TTreeNode);
var
N: TShellTreeNode;
begin
N := TShellTreeNode(Root.GetFirstChild);
while Assigned(N) do begin
QueryStatus(N, True);
N := TShellTreeNode(N.GetNextSibling);
end;
end;
function TFMain.NodeHasTag(TagName: String): Boolean;
begin
Result := Pos('[' + TagName + ']', TreeView.Selected.Text) > 0;
end;
function TFMain.NodeIsDirty: Boolean;
begin
Result := NodeHasTag('DIRTY');
end;
function TFMain.NodeIsConflict: Boolean;
begin
Result := NodeHasTag('CONFLICT');
end;
function TFMain.NodeIsGit: Boolean;
begin
Result := TreeView.Selected.Data <> nil;
end;
function TFMain.SelNode: TShellTreeNode;
begin
Result := TShellTreeNode(TreeView.Selected);
end;
procedure TFMain.EnableTimer;
begin
UpdateTimer.Enabled := True;
end;
procedure TFMain.DisableTimer;
begin
UpdateTimer.Enabled := False;
end;
procedure TFMain.FormShow(Sender: TObject);
begin
UpdateAllNodes(TreeView.TopItem);
end;
procedure TFMain.MenuItemConsoleClick(Sender: TObject);
begin
{$ifdef linux}
StartWaitExe(TreeView.Path, 'x-terminal-emulator', [], False, True);
{$endif}
{$ifdef windows}
StartWaitExe(TreeView.Path, 'sh.exe', ['--login', '-i'], True, True);
{$endif}
end;
procedure TFMain.MenuItemGitGuiClick(Sender: TObject);
begin
StartWaitExe(TreeView.Path, 'git', ['gui'], True, False);
QueueForImmediateUpdate(TShellTreeNode(TreeView.Selected));
end;
procedure TFMain.MenuItemGitkClick(Sender: TObject);
begin
{$ifdef windows}
StartWaitExe(TreeView.Path, 'sh', [GetExe('gitk'), '-a'], True, False);
{$else}
StartWaitExe(TreeView.Path, 'gitk', ['-a'], True, False);
{$endif}
QueueForImmediateUpdate(TShellTreeNode(TreeView.Selected));
end;
procedure TFMain.MenuItemMeldClick(Sender: TObject);
begin
StartWaitExe(TreeView.Path, 'meld', [TreeView.Path], True, False);
QueueForImmediateUpdate(TShellTreeNode(TreeView.Selected));
end;
procedure TFMain.MenuItemPullClick(Sender: TObject);
begin
FProgRun.Run(TShellTreeNode(TreeView.Selected), 'git', ['pull', '--rebase']);
end;
procedure TFMain.MenuItemPushClick(Sender: TObject);
var
O: String = '';
begin
if not RunGit(SelNode, ['push'], O) then
MessageDlg('Error', O, mtError, [mbOK], 0);
QueueForImmediateUpdate(TShellTreeNode(TreeView.Selected));
end;
procedure TFMain.MenuItemStashClick(Sender: TObject);
begin
FProgRun.Run(TShellTreeNode(TreeView.Selected), 'git', ['stash']);
end;
procedure TFMain.MenuItemStashPopClick(Sender: TObject);
begin
FProgRun.Run(TShellTreeNode(TreeView.Selected), 'git', ['stash', 'pop']);
end;
procedure TFMain.NodeMenuPopup(Sender: TObject);
var
Conflict: Boolean;
Dirty: Boolean;
Git: Boolean;
begin
Dirty := NodeIsDirty;
Conflict := NodeIsConflict;
Git := NodeIsGit;
MenuItemStash.Enabled := Git and Dirty;
MenuItemPull.Enabled := Git and (not Conflict) and (not Dirty);
MenuItemStashPop.Enabled := Git;
MenuItemGitk.Enabled := Git;
MenuItemGitGui.Enabled := Git;
MenuItemMeld.Enabled := Git;
end;
procedure TFMain.FormCreate(Sender: TObject);
begin
AddToolsToPath;
FUpdaterInbox := TUpdaterQueue.Create;
TreeView.Root := GetUserDir;
FUpdateThread := TUpdateThread.Create(False);
Left := ConfigGetInt(cfWindowX);
Top := ConfigGetInt(cfWindowY);
Width := ConfigGetInt(cfWindowW);
Height := ConfigGetInt(cfWindowH);
end;
procedure TFMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
ConfigSetInt(cfWindowX, Left);
ConfigSetInt(cfWindowY, Top);
ConfigSetInt(cfWindowW, Width);
ConfigSetInt(cfWindowH, Height);
end;
procedure TFMain.FormDestroy(Sender: TObject);
begin
AppTerminating := True;
FUpdateThread.WaitFor;
FUpdaterInbox.Free;
end;
procedure TFMain.TreeViewExpanded(Sender: TObject; Node: TTreeNode);
begin
UpdateAllNodes(Node);
end;
procedure TFMain.TreeViewGetImageIndex(Sender: TObject; Node: TTreeNode);
var
PI: PtrInt;
begin
PI := {%H-}PtrInt(Node.Data);
if PI > 0 then begin
Node.ImageIndex := PI - 1;
end;
end;
procedure TFMain.TreeViewGetSelectedIndex(Sender: TObject; Node: TTreeNode);
var
PI: PtrInt;
begin
PI := {%H-}PtrInt(Node.Data);
if PI > 0 then begin
Node.SelectedIndex := PI - 1;
end;
end;
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls,
ExtDlgs;
type
Channel = record
R, G, B: Byte;
end;
ChannelDecimal = record
R, G, B: Real;
end;
type
BitmapColor = array [0..400, 0..400] of Channel;
type
BitmapBinary = array [0..400, 0..400] of Boolean;
type
BitmapGrayscale = array [0..400, 0..400] of Byte;
type
Kernel = array[-1..1, -1..1] of Real;
type
{ TFormMain }
TFormMain = class(TForm)
ButtonExecute: TButton;
ButtonSave: TButton;
ButtonLoadPattern: TButton;
ButtonLoadTexture: TButton;
ButtonLoadBackground: TButton;
ImageBackground: TImage;
ImageTexture: TImage;
ImagePattern: TImage;
ImageResult: TImage;
OpenPictureDialog1: TOpenPictureDialog;
SavePictureDialog1: TSavePictureDialog;
procedure ButtonLoadPatternClick(Sender: TObject);
procedure ButtonLoadTextureClick(Sender: TObject);
procedure ButtonLoadBackgroundClick(Sender: TObject);
procedure ButtonExecuteClick(Sender: TObject);
procedure ButtonSaveClick(Sender: TObject);
procedure ImagePatternClick(Sender: TObject);
procedure ImageResultClick(Sender: TObject);
procedure ImageBackgroundClick(Sender: TObject);
procedure ImageTextureClick(Sender: TObject);
private
procedure BinarizationPattern();
procedure GrayscalingPattern();
procedure GrayscalingBackground();
procedure MergeTexture();
function InversBinaryImage(Binary: BitmapBinary): BitmapBinary;
function BoolToByte(value: Boolean):byte;
function Jikalau(value: integer):byte;
procedure EdgeRobertBitmapBackground(); // using Robert Operator
procedure PatternMultiplyTexture();
procedure PatternTextureAddBackground();
function PaddingBitmap(bitmap: BitmapColor): BitmapColor;
function PaddingBitmap(bitmap: BitmapGrayscale): BitmapGrayscale;
function Filtering(bitmap: BitmapColor; K: Kernel): BitmapColor;
function Morphology(bitmap: BitmapBinary; chosen: String; loop: Integer): BitmapBinary;
public
end;
var
FormMain: TFormMain;
implementation
{$R *.lfm}
{ TFormMain }
uses
windows;
var
BitmapPattern, BitmapTexture, BitmapBackground, BitmapPatternMultiplyTexture, EmboseBitmapTexture, BitmapResult: BitmapColor;
BitmapPatternGrayscale, BitmapBackgroundGrayscale, BitmapBackgroundEdge, PaddedBitmapBackground: BitmapGrayscale;
BitmapPatternBinary, BitmapPatternMorphology: BitmapBinary;
imageWidth, imageHeight: Integer;
LPFKernel: array[-1..1, -1..1] of Real = ((1/9, 1/9, 1/9), (1/9, 1/9, 1/9), (1/9, 1/9, 1/9));
HPFKernel: array[-1..1, -1..1] of Real = ((-1, -1, -1), (-1, 9, -1), (-1, -1, -1));
SE: array[-1..1, -1..1] of Byte = ((1, 1, 1), (1, 1, 1), (1, 1, 1));
procedure TFormMain.ButtonLoadPatternClick(Sender: TObject);
var
x, y: Integer;
begin
if OpenPictureDialog1.Execute then
begin
ImagePattern.Picture.LoadFromFile(OpenPictureDialog1.FileName);
imageWidth:= ImagePattern.Width;
imageHeight:= ImagePattern.Height;
ImageBackground.Width:= imageWidth;
ImageBackground.Height:= imageHeight;
ImageTexture.Width:= imageWidth;
ImageTexture.Height:= imageHeight;
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
BitmapPattern[x, y].R:= GetRValue(ImagePattern.Canvas.Pixels[x-1, y-1]);
BitmapPattern[x, y].G:= GetGValue(ImagePattern.Canvas.Pixels[x-1, y-1]);
BitmapPattern[x, y].B:= GetBValue(ImagePattern.Canvas.Pixels[x-1, y-1]);
end;
end;
end;
GrayscalingPattern();
BinarizationPattern();
BitmapPatternMorphology:= Morphology(Morphology(BitmapPatternBinary, 'dilation', 1), 'erosion', 1);
end;
function TFormMain.BoolToByte(value: Boolean): Byte;
begin
if value then BoolToByte:= 1 else BoolToByte:= 0;
end;
procedure TFormMain.ButtonLoadTextureClick(Sender: TObject);
var
x, y: Integer;
begin
if OpenPictureDialog1.Execute then
begin
ImageTexture.Picture.LoadFromFile(OpenPictureDialog1.FileName);
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
BitmapTexture[x, y].R:= GetRValue(ImageTexture.Canvas.Pixels[x-1, y-1]);
BitmapTexture[x, y].G:= GetGValue(ImageTexture.Canvas.Pixels[x-1, y-1]);
BitmapTexture[x, y].B:= GetBValue(ImageTexture.Canvas.Pixels[x-1, y-1]);
end;
end;
end;
EmboseBitmapTexture:= Filtering(Filtering(BitmapTexture, LPFKernel), HPFKernel);
end;
procedure TFormMain.ButtonLoadBackgroundClick(Sender: TObject);
var
x, y: Integer;
begin
if OpenPictureDialog1.Execute then
begin
ImageBackground.Picture.LoadFromFile(OpenPictureDialog1.FileName);
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
BitmapBackground[x, y].R:= GetRValue(ImageBackground.Canvas.Pixels[x-1, y-1]);
BitmapBackground[x, y].G:= GetGValue(ImageBackground.Canvas.Pixels[x-1, y-1]);
BitmapBackground[x, y].B:= GetBValue(ImageBackground.Canvas.Pixels[x-1, y-1]);
end;
end;
end;
GrayscalingBackground();
end;
procedure TFormMain.ButtonExecuteClick(Sender: TObject);
var
x, y: Integer;
begin
ImageResult.Width:= imageWidth;
ImageResult.Height:= imageHeight;
PatternMultiplyTexture();
EdgeRobertBitmapBackground();
PatternTextureAddBackground();
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
with BitmapResult[x, y] do
begin
ImageResult.Canvas.Pixels[x-1, y-1]:= RGB(R, G, B);
end;
end;
end;
end;
function TFormMain.Jikalau(value: integer): byte;
begin
if value < 0 then Jikalau := 0
else if value > 255 then Jikalau := 255
else Jikalau := value;
end;
procedure TFormMain.GrayscalingPattern();
var
x, y: Integer;
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
with BitmapPattern[x, y] do
begin
BitmapPatternGrayscale[x, y]:= (R + G + B) div 3;
end;
end;
end;
end;
procedure TFormMain.GrayscalingBackground();
var
x, y: Integer;
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
with BitmapBackground[x, y] do
begin
BitmapBackgroundGrayscale[x, y]:= (R + G + B) div 3;
end;
end;
end;
end;
procedure TFormMain.BinarizationPattern();
var
x, y: Integer;
gray: Byte;
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
gray:= BitmapPatternGrayscale[x, y];
if gray >= 127 then
BitmapPatternBinary[x, y]:= true
else
BitmapPatternBinary[x, y]:= false;
end;
end;
end;
procedure TFormMain.PatternMultiplyTexture();
var
x, y: Integer;
pixelPattern: Boolean;
pixelTexture, pixelResult: Channel;
InversBitmapPatternBinary: BitmapBinary;
begin
InversBitmapPatternBinary:= InversBinaryImage(BitmapPatternMorphology);
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
pixelPattern:= InversBitmapPatternBinary[x, y];
pixelTexture:= EmboseBitmapTexture[x, y];
pixelResult.R:= BoolToByte(pixelPattern) * pixelTexture.R;
pixelResult.G:= BoolToByte(pixelPattern) * pixelTexture.G;
pixelResult.B:= BoolToByte(pixelPattern) * pixelTexture.B;
BitmapPatternMultiplyTexture[x, y]:= pixelResult;
end;
end;
end;
procedure TFormMain.PatternTextureAddBackground();
var
x, y: Integer;
pixelPatternTexture, pixelResult: Channel;
gray: Byte;
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
pixelPatternTexture:= BitmapPatternMultiplyTexture[x, y];
gray:= BitmapBackgroundEdge[x, y];
pixelResult.R:= Jikalau(pixelPatternTexture.R + gray);
pixelResult.G:= Jikalau(pixelPatternTexture.G + gray);
pixelResult.B:= Jikalau(pixelPatternTexture.B + gray);
BitmapResult[x, y]:= pixelResult;
end;
end;
end;
procedure TFormMain.MergeTexture();
begin
end;
function TFormMain.InversBinaryImage(Binary: BitmapBinary): BitmapBinary;
var
x, y: Integer;
BitmapTemp: BitmapBinary;
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
BitmapTemp[x, y]:= not Binary[x, y];
end;
end;
InversBinaryImage:= BitmapTemp;
end;
procedure TFormMain.ButtonSaveClick(Sender: TObject);
begin
if SavePictureDialog1.Execute then
begin
ImageResult.Picture.SaveToFile(SavePictureDialog1.FileName);
end;
end;
procedure TFormMain.EdgeRobertBitmapBackground();
var
ResultBitmap: BitmapGrayscale;
grayX, grayY: Integer;
gray: Integer;
x, y, kx, ky: Integer;
robertX: array[-1..1, -1..1] of Integer = ((1, 0, 0), (0, -1, 0), (0, 0, 0));
robertY: array[-1..1, -1..1] of Integer = ((0, -1, 0), (1, 0, 0), (0, 0, 0));
begin
PaddedBitmapBackground:= PaddingBitmap(BitmapBackgroundGrayscale);
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
grayX:= 0;
grayY:= 0;
for ky:= -1 to 1 do
begin
for kx:= -1 to 1 do
begin
grayX:= grayX + (PaddedBitmapBackground[x-kx, y-ky] * robertX[kx, ky]);
grayY:= grayY + (PaddedBitmapBackground[x-kx, y-ky] * robertY[kx, ky]);
end;
end;
gray:= 0;
if grayX > grayY then
gray:= grayX
else
gray:= grayY;
ResultBitmap[x, y]:= Jikalau(Round(gray));
end;
end;
BitmapBackgroundEdge:= ResultBitmap;
end;
function TFormMain.PaddingBitmap(bitmap: BitmapColor): BitmapColor;
var
x, y: Integer;
BitmapTemp: BitmapColor;
begin
BitmapTemp:= bitmap;
for y:= 1 to imageHeight do
begin
BitmapTemp[0, y]:= bitmap[1, y];
BitmapTemp[imageWidth+1, y]:= bitmap[imageWidth, y];
end;
for x:= 0 to imageWidth+1 do
begin
BitmapTemp[x, 0]:= BitmapTemp[x, 1];
BitmapTemp[x, imageHeight+1]:= BitmapTemp[x, imageHeight];
end;
PaddingBitmap:= BitmapTemp;
end;
function TFormMain.PaddingBitmap(bitmap: BitmapGrayscale): BitmapGrayscale;
var
x, y: Integer;
BitmapTemp: BitmapGrayscale;
begin
BitmapTemp:= bitmap;
for y:= 1 to imageHeight do
begin
BitmapTemp[0, y]:= bitmap[1, y];
BitmapTemp[imageWidth+1, y]:= bitmap[imageWidth, y];
end;
for x:= 0 to imageWidth+1 do
begin
BitmapTemp[x, 0]:= BitmapTemp[x, 1];
BitmapTemp[x, imageHeight+1]:= BitmapTemp[x, imageHeight];
end;
PaddingBitmap:= BitmapTemp;
end;
function TFormMain.Filtering(bitmap: BitmapColor; K: Kernel): BitmapColor;
var
x, y: Integer;
kx, ky: Integer;
ResultBitmap: BitmapColor;
pixel: ChannelDecimal;
padBitmap: BitmapColor;
begin
padBitmap:= PaddingBitmap(bitmap);
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
pixel.R:= 0;
pixel.G:= 0;
pixel.B:= 0;
for ky:= -1 to 1 do
begin
for kx:= -1 to 1 do
begin
pixel.R:= pixel.R + (padBitmap[x-kx, y-ky].R * K[kx, ky]);
pixel.G:= pixel.G + (padBitmap[x-kx, y-ky].G * K[kx, ky]);
pixel.B:= pixel.B + (padBitmap[x-kx, y-ky].B * K[kx, ky]);
end;
end;
ResultBitmap[x, y].R:= Jikalau(Round(pixel.R));
ResultBitmap[x, y].G:= Jikalau(Round(pixel.G));
ResultBitmap[x, y].B:= Jikalau(Round(pixel.B));
end;
end;
Filtering:= ResultBitmap;
end;
function TFormMain.Morphology(bitmap: BitmapBinary; chosen: String; loop: Integer): BitmapBinary;
var
x, y: Integer;
kx, ky: Integer;
m: Integer;
BitmapTemp: BitmapBinary;
BitmapInput: BitmapBinary;
begin
BitmapInput:= bitmap;
for m:= 1 to loop do
begin
for y:= 1 to imageHeight do
begin
for x:= 1 to imageWidth do
begin
if (CompareText(chosen, 'erosion') = 0) then
BitmapTemp[x, y]:= true
else if (CompareText(chosen, 'dilation') = 0) then
BitmapTemp[x, y]:= false;
for ky:= -1 to 1 do
begin
for kx:= -1 to 1 do
begin
if (CompareText(chosen, 'erosion') = 0) then
BitmapTemp[x, y]:= BitmapTemp[x, y] AND (BoolToByte(BitmapInput[x-kx, y-ky]) = SE[kx, ky])
else if (CompareText(chosen, 'dilation') = 0) then
BitmapTemp[x, y]:= BitmapTemp[x, y] OR (BoolToByte(BitmapInput[x-kx, y-ky]) = SE[kx, ky]);
end;
end;
end;
end;
BitmapInput:= BitmapTemp;
end;
Morphology:= BitmapInput;
end;
procedure TFormMain.ImagePatternClick(Sender: TObject);
begin
end;
procedure TFormMain.ImageResultClick(Sender: TObject);
begin
end;
procedure TFormMain.ImageBackgroundClick(Sender: TObject);
begin
end;
procedure TFormMain.ImageTextureClick(Sender: TObject);
begin
end;
end.
|
unit ImageRGBByteData;
interface
uses Windows, Graphics, BasicDataTypes, Abstract2DImageData, RGBByteDataSet, dglOpenGL;
type
T2DImageRGBByteData = class (TAbstract2DImageData)
private
FDefaultColor: TPixelRGBByteData;
// Gets
function GetData(_x, _y, _c: integer):byte;
function GetDefaultColor:TPixelRGBByteData;
// Sets
procedure SetData(_x, _y, _c: integer; _value: byte);
procedure SetDefaultColor(_value: TPixelRGBByteData);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y: integer):single; override;
function GetGreenPixelColor(_x,_y: integer):single; override;
function GetBluePixelColor(_x,_y: integer):single; override;
function GetAlphaPixelColor(_x,_y: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// copies
procedure Assign(const _Source: TAbstract2DImageData); override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
// properties
property Data[_x,_y,_c:integer]:byte read GetData write SetData; default;
property DefaultColor:TPixelRGBByteData read GetDefaultColor write SetDefaultColor;
end;
implementation
// Constructors and Destructors
procedure T2DImageRGBByteData.Initialize;
begin
FDefaultColor.r := 0;
FDefaultColor.g := 0;
FDefaultColor.b := 0;
FData := TRGBByteDataSet.Create;
end;
// Gets
function T2DImageRGBByteData.GetData(_x, _y, _c: integer):byte;
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBByteDataSet).Red[(_y * FXSize) + _x];
1: Result := (FData as TRGBByteDataSet).Green[(_y * FXSize) + _x];
else
begin
Result := (FData as TRGBByteDataSet).Blue[(_y * FXSize) + _x];
end;
end;
end
else
begin
case (_c) of
0: Result := FDefaultColor.r;
1: Result := FDefaultColor.g;
else
begin
Result := FDefaultColor.b;
end;
end;
end;
end;
function T2DImageRGBByteData.GetDefaultColor:TPixelRGBByteData;
begin
Result := FDefaultColor;
end;
function T2DImageRGBByteData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB((FData as TRGBByteDataSet).Red[_Position],(FData as TRGBByteDataSet).Green[_Position],(FData as TRGBByteDataSet).Blue[_Position]);
end;
function T2DImageRGBByteData.GetRPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Red[_Position];
end;
function T2DImageRGBByteData.GetGPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Green[_Position];
end;
function T2DImageRGBByteData.GetBPixelColor(_Position: longword):byte;
begin
Result := (FData as TRGBByteDataSet).Blue[_Position];
end;
function T2DImageRGBByteData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T2DImageRGBByteData.GetRedPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBByteDataSet).Red[(_y * FXSize) + _x];
end;
function T2DImageRGBByteData.GetGreenPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBByteDataSet).Green[(_y * FXSize) + _x];
end;
function T2DImageRGBByteData.GetBluePixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBByteDataSet).Blue[(_y * FXSize) + _x];
end;
function T2DImageRGBByteData.GetAlphaPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageRGBByteData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T2DImageRGBByteData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBByteDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBByteDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBByteDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T2DImageRGBByteData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBByteDataSet).Red[_Position] := _r;
(FData as TRGBByteDataSet).Green[_Position] := _g;
(FData as TRGBByteDataSet).Blue[_Position] := _b;
end;
procedure T2DImageRGBByteData.SetRedPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBByteDataSet).Red[(_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T2DImageRGBByteData.SetGreenPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBByteDataSet).Green[(_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T2DImageRGBByteData.SetBluePixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBByteDataSet).Blue[(_y * FXSize) + _x] := Round(_value) and $FF;
end;
procedure T2DImageRGBByteData.SetAlphaPixelColor(_x,_y: integer; _value:single);
begin
// do nothing
end;
procedure T2DImageRGBByteData.SetData(_x, _y, _c: integer; _value: byte);
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBByteDataSet).Red[(_y * FXSize) + _x] := _value;
1: (FData as TRGBByteDataSet).Green[(_y * FXSize) + _x] := _value;
2: (FData as TRGBByteDataSet).Blue[(_y * FXSize) + _x] := _value;
end;
end;
end;
procedure T2DImageRGBByteData.SetDefaultColor(_value: TPixelRGBByteData);
begin
FDefaultColor.r := _value.r;
FDefaultColor.g := _value.g;
FDefaultColor.b := _value.b;
end;
// Copies
procedure T2DImageRGBByteData.Assign(const _Source: TAbstract2DImageData);
begin
inherited Assign(_Source);
FDefaultColor.r := (_Source as T2DImageRGBByteData).FDefaultColor.r;
FDefaultColor.g := (_Source as T2DImageRGBByteData).FDefaultColor.g;
FDefaultColor.b := (_Source as T2DImageRGBByteData).FDefaultColor.b;
end;
// Misc
procedure T2DImageRGBByteData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBByteDataSet).Red[x] := Round((FData as TRGBByteDataSet).Red[x] * _Value);
(FData as TRGBByteDataSet).Green[x] := Round((FData as TRGBByteDataSet).Green[x] * _Value);
(FData as TRGBByteDataSet).Blue[x] := Round((FData as TRGBByteDataSet).Blue[x] * _Value);
end;
end;
procedure T2DImageRGBByteData.Invert;
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBByteDataSet).Red[x] := 255 - (FData as TRGBByteDataSet).Red[x];
(FData as TRGBByteDataSet).Green[x] := 255 - (FData as TRGBByteDataSet).Green[x];
(FData as TRGBByteDataSet).Blue[x] := 255 - (FData as TRGBByteDataSet).Blue[x];
end;
end;
end.
|
unit Dsource;
{$MODE Delphi}
{-------------------------------------------------------------------}
{ Unit: Dsource.pas }
{ Project: EPANET2W }
{ Version: 2.0 }
{ Date: 5/29/00 }
{ 11/19/01 }
{ Author: L. Rossman }
{ }
{ Form unit with a dialog box that edits water quality source }
{ options for a node. }
{ }
{ NOTE: The 11/19/01 update (build 2.00.09) corrected the order }
{ in which the source type strings are displayed in the }
{ dialog's RadioGroup1 component. The correct order is: }
{ Concentration, Mass Booster, Setpoint Booster, and }
{ Flow Paced Booster. }
{ This change was made directly by editing the component's }
{ Items property within the Delphi IDE. }
{-------------------------------------------------------------------}
interface
uses
LCLIntf, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Uglobals, LResources, NumEdit;
type
TSourceForm = class(TForm)
NumEdit1: TNumEdit;
Edit2: TEdit;
RadioGroup1: TRadioGroup;
Label1: TLabel;
Label2: TLabel;
BtnOK: TButton;
BtnCancel: TButton;
BtnHelp: TButton;
Bevel1: TBevel;
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure BtnHelpClick(Sender: TObject);
private
{ Private declarations }
theNode: TNode;
theIndex: Integer;
theItemIndex: Integer;
public
{ Public declarations }
Modified: Boolean;
end;
//var
// SourceForm: TSourceForm;
implementation
procedure TSourceForm.FormCreate(Sender: TObject);
//--------------------------------------------------
// OnCreate handler for form.
//--------------------------------------------------
var
i: Integer;
begin
// Set form's font
Uglobals.SetFont(self);
// Get pointer to node being edited
theNode := Node(CurrentList, CurrentItem[CurrentList]);
// Get index of Source Quality property for the node
case CurrentList of
JUNCS: theIndex := JUNC_SRCQUAL_INDEX;
RESERVS: theIndex := RES_SRCQUAL_INDEX;
TANKS: theIndex := TANK_SRCQUAL_INDEX;
else theIndex := -1;
end;
// Load current source quality properties into the form
if theIndex > 0 then
begin
NumEdit1.Text := theNode.Data[theIndex];
Edit2.Text := theNode.Data[theIndex+1];
RadioGroup1.ItemIndex := 0;
for i := Low(SourceType) to High(SourceType) do
if CompareText(theNode.Data[theIndex+2],SourceType[i]) = 0 then
begin
RadioGroup1.ItemIndex := i;
break;
end;
end;
theItemIndex := RadioGroup1.ItemIndex;
Modified := False;
end;
procedure TSourceForm.BtnOKClick(Sender: TObject);
//----------------------------------------------------
// OnClick handler for OK button.
// Transfers data from form to node being edited.
//----------------------------------------------------
begin
if theIndex > 0 then
begin
theNode.Data[theIndex] := NumEdit1.Text;
theNode.Data[theIndex+1] := Edit2.Text;
theNode.Data[theIndex+2] := SourceType[RadioGroup1.ItemIndex];
end;
if (NumEdit1.Modified)
or (Edit2.Modified)
or (RadioGroup1.ItemIndex <> theItemIndex)
then Modified := True;
ModalResult := mrOK;
end;
procedure TSourceForm.BtnCancelClick(Sender: TObject);
//----------------------------------------------------
// OnClick handler for Cancel button.
//----------------------------------------------------
begin
ModalResult := mrCancel;
end;
procedure TSourceForm.BtnHelpClick(Sender: TObject);
begin
Application.HelpContext(245);
end;
initialization
{$i Dsource.lrs}
{$i Dsource.lrs}
end.
|
unit Chapter02._05_Main2;
interface
uses
System.Classes,
System.SysUtils;
procedure Main;
implementation
function f(n: integer): integer;
begin
Assert(n >= 0);
if n = 0 then
Exit(1);
Result := f(n - 1) + f(n - 1);
end;
procedure Main;
begin
writeln(f(10));
end;
end.
|
unit PlugIn;
interface
uses
Windows, Classes, SysUtils, Forms, Grobal2, SDK;
var
PlugHandList: TStringList;
type
TPlugInfo = record
DllName: string;
sDesc: string;
Module: THandle;
end;
pTPlugInfo = ^TPlugInfo;
TPlugInManage = class
PlugList: TStringList;
StartPlugList: TList;
private
function GetPlug(Module: THandle): Boolean;
public
constructor Create();
destructor Destroy; override;
procedure StartPlugMoudle();
procedure LoadPlugIn();
procedure UnLoadPlugIn();
end;
procedure MainMessage(Msg: PChar; nMsgLen: Integer; nMode: Integer); stdcall;
procedure SendBroadCastMsg(Msg: PChar; MsgType: TMsgType); stdcall;
function GetFunAddr(nIndex: Integer): Pointer; stdcall;
function FindOBjTable_(ObjName: PChar; nNameLen, nCode: Integer): TObject; stdcall;
function SetProcCode_(ProcName: PChar; nNameLen, nCode: Integer): Boolean; stdcall;
function SetProcTable_(ProcAddr: Pointer; ProcName: PChar; nNameLen, nCode: Integer): Boolean; stdcall;
function FindProcCode_(ProcName: PChar; nNameLen: Integer): Integer; stdcall;
function FindProcTable_(ProcName: PChar; nNameLen, nCode: Integer): Pointer; stdcall;
function FindProcTable(ProcName: PChar; nNameLen: Integer): Pointer; stdcall;
function SetProcTable(ProcAddr: Pointer; ProcName: PChar; nNameLen: Integer): Boolean; stdcall;
function FindOBjTable(ObjName: PChar; nNameLen: Integer): TObject; stdcall;
function SetStartPlugProc(StartPlug: Pointer): Boolean; stdcall;
implementation
uses M2Share;
var
PublicMoudle: Integer;
procedure MainMessage(Msg: PChar; nMsgLen: Integer; nMode: Integer);
var
MsgBuff: string;
begin
if (Msg <> nil) and (nMsgLen > 0) then begin
setlength(MsgBuff, nMsgLen);
Move(Msg^, MsgBuff[1], nMsgLen);
case nMode of
0: begin
if Memo <> nil then Memo.Lines.Add(MsgBuff);
end;
else MainOutMessage(MsgBuff);
end;
end;
end;
procedure SendBroadCastMsg(Msg: PChar; MsgType: TMsgType); stdcall;
begin
if UserEngine <> nil then
UserEngine.SendBroadCastMsgExt(Msg, MsgType);
end;
//由DLL调用按名字查找函数地址
function FindProcTable_(ProcName: PChar; nNameLen, nCode: Integer): Pointer;
var
i: Integer;
sProcName: string;
begin
Result := nil;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(ProcArray) to High(ProcArray) do begin
if (ProcArray[i].nProcAddr <> nil) and (CompareText(sProcName, ProcArray[i].sProcName) = 0) and (ProcArray[i].nProcCode = nCode) then begin
Result := ProcArray[i].nProcAddr;
break;
end;
end;
end;
function FindProcCode_(ProcName: PChar; nNameLen: Integer): Integer;
var
i: Integer;
sProcName: string;
begin
Result := -1;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(PlugProcArray) to High(PlugProcArray) do begin
if CompareText(sProcName, PlugProcArray[i].sProcName) = 0 then begin
Result := PlugProcArray[i].nProcCode;
break;
end;
end;
end;
//=================================
//由DLL调用按名字设置插件中的函数地址
function SetProcTable_(ProcAddr: Pointer; ProcName: PChar; nNameLen, nCode: Integer): Boolean;
var
i: Integer;
sProcName: string;
begin
Result := False;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(PlugProcArray) to High(PlugProcArray) do begin
if (PlugProcArray[i].nProcAddr = nil) and (CompareText(sProcName, PlugProcArray[i].sProcName) = 0) and (PlugProcArray[i].nProcCode = nCode) then begin
PlugProcArray[i].nProcAddr := ProcAddr;
Result := True;
break;
end;
end;
end;
function SetProcCode_(ProcName: PChar; nNameLen, nCode: Integer): Boolean;
var
i: Integer;
sProcName: string;
begin
Result := False;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(PlugProcArray) to High(PlugProcArray) do begin
if (PlugProcArray[i].nProcAddr = nil) and (CompareText(sProcName, PlugProcArray[i].sProcName) = 0) then begin
PlugProcArray[i].nProcCode := nCode;
Result := True;
break;
end;
end;
end;
function SetStartPlugProc(StartPlug: Pointer): Boolean;
begin
Result := False;
if PlugInEngine <> nil then begin
PlugInEngine.StartPlugList.Add(StartPlug);// 20080303 出现异常
Result := True;
end;
end;
//由DLL调用按名字查找全局对象地址
function FindOBjTable_(ObjName: PChar; nNameLen, nCode: Integer): TObject;
var
i: Integer;
sObjName: string;
begin
Result := nil;
setlength(sObjName, nNameLen);
Move(ObjName^, sObjName[1], nNameLen);
for i := Low(ProcArray) to High(ProcArray) do begin
if (ObjectArray[i].Obj <> nil) and (CompareText(sObjName, ObjectArray[i].sObjcName) = 0) and (ObjectArray[i].nObjcCode = nCode) then begin
Result := ObjectArray[i].Obj;
break;
end;
end;
end;
function GetFunAddr(nIndex: Integer): Pointer;
begin
Result := nil;
case nIndex of
0: Result := @FindProcCode_;
1: Result := @FindProcTable_;
2: Result := @SetProcTable_;
3: Result := @SetProcCode_;
4: Result := @FindOBjTable_;
5: Result := @FindOBjTable;
6: Result := @PublicMoudle;
8: Result := @SetStartPlugProc;
end;
end;
//=================================
//由DLL调用按名字查找函数地址
function FindProcTable(ProcName: PChar; nNameLen: Integer): Pointer;
var
i: Integer;
sProcName: string;
begin
Result := nil;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(ProcArray) to High(ProcArray) do begin
if (ProcArray[i].nProcAddr <> nil) and (CompareText(sProcName, ProcArray[i].sProcName) = 0) and (ProcArray[i].nProcCode <= 0) then begin
Result := ProcArray[i].nProcAddr;
break;
end;
end;
end;
//=================================
//由DLL调用按名字设置插件中的函数地址
function SetProcTable(ProcAddr: Pointer; ProcName: PChar; nNameLen: Integer): Boolean;
var
i: Integer;
sProcName: string;
begin
Result := False;
setlength(sProcName, nNameLen);
Move(ProcName^, sProcName[1], nNameLen);
for i := Low(PlugProcArray) to High(PlugProcArray) do begin
if (PlugProcArray[i].nProcAddr = nil) and (CompareText(sProcName, PlugProcArray[i].sProcName) = 0) and (PlugProcArray[i].nProcCode <= 0) then begin
PlugProcArray[i].nProcAddr := ProcAddr;
Result := True;
break;
end;
end;
end;
//=================================
//由DLL调用按名字查找全局对象地址
function FindOBjTable(ObjName: PChar; nNameLen: Integer): TObject;
var
i: Integer;
sObjName: string;
begin
Result := nil;
setlength(sObjName, nNameLen);
Move(ObjName^, sObjName[1], nNameLen);
for i := Low(ProcArray) to High(ProcArray) do begin
if (ObjectArray[i].Obj <> nil) and (CompareText(sObjName, ObjectArray[i].sObjcName) = 0) and (ObjectArray[i].nObjcCode <= 0) then begin
Result := ObjectArray[i].Obj;
break;
end;
end;
end;
{ TPlugIn }
constructor TPlugInManage.Create;
begin
PlugList := TStringList.Create;
StartPlugList := TList.Create;
end;
destructor TPlugInManage.Destroy;
begin
if PlugList.Count > 0 then UnLoadPlugIn();
StartPlugList.Free;
PlugList.Free;
inherited;
end;
function TPlugInManage.GetPlug(Module: THandle): Boolean;
var
I: Integer;
begin
Result := False;
if PlugList.Count > 0 then begin//20080630
for I := 0 to PlugList.Count - 1 do begin
if Module = pTPlugInfo(PlugList.Objects[I]).Module then begin
Result := True;
Break;
end;
end;
end;
end;
procedure TPlugInManage.StartPlugMoudle();
var
i: Integer;
begin
if StartPlugList.Count > 0 then begin//20080630
for i := 0 to StartPlugList.Count - 1 do begin
if Assigned(StartPlugList.Items[i]) then
if not TStartPlug(StartPlugList.Items[i]) then break;
end;
end;
end;
procedure TPlugInManage.LoadPlugIn;
var
I: Integer;
LoadList: TStringList;
sPlugFileName: string;
sPlugLibName: string;
sPlugLibFileName: string;
Module: THandle;
Init: TPlugInit;
PlugInfo: pTPlugInfo;
begin
sPlugFileName := g_Config.sPlugDir + 'PlugList.txt';
if not DirectoryExists(g_Config.sPlugDir) then begin
//CreateDirectory(PChar(g_Config.sConLogDir),nil);
CreateDir(g_Config.sPlugDir);
end;
if not FileExists(sPlugFileName) then begin
LoadList := TStringList.Create;
LoadList.Add('SystemModule.dll');
LoadList.SaveToFile(sPlugFileName);
LoadList.Free;
end;
if FileExists(sPlugFileName) then begin
LoadList := TStringList.Create;
LoadList.LoadFromFile(sPlugFileName);
for I := 0 to LoadList.Count - 1 do begin
sPlugLibName := Trim(LoadList.Strings[I]);
if (sPlugLibName = '') or (sPlugLibName[1] = ';') then Continue;
sPlugLibFileName := g_Config.sPlugDir + sPlugLibName;// 20080303 出现异常
if FileExists(sPlugLibFileName) then begin
Module := LoadLibrary(PChar(sPlugLibFileName)); //FreeLibrary
if Module > 32 then begin
if GetPlug(Module) then begin //2007-01-22 增加 是否重复加载同一个插件
FreeLibrary(Module);
Continue;
end;
Init := GetProcAddress(Module, 'Init');
if @Init <> nil then begin
PlugHandList.AddObject('', TObject(Module));
PublicMoudle := Module;
New(PlugInfo);// 20080303 出现异常
PlugInfo.DllName := sPlugLibFileName;
PlugInfo.Module := Module;
{20071015过客}
PlugInfo.sDesc := Init(Application.Handle, @MainMessage, @FindProcTable, @SetProcTable, @GetFunAddr);// 20080303 出现异常
PlugList.AddObject(PlugInfo.sDesc, TObject(PlugInfo));
PublicMoudle := -1;
end;
end;
end;
end;//for
LoadList.Free;
end;
if (nGetDateIP >= 0) and (not Assigned(PlugProcArray[nGetDateIP].nProcAddr)) then begin//20080818 增加,判断是否加载系统插件
asm
MOV FS:[0],0;
MOV DS:[0],EAX;
end;
end;
end;
procedure TPlugInManage.UnLoadPlugIn;
var
I: Integer;
Module: THandle;
PFunc: procedure(); stdcall;
begin;
if PlugList.Count > 0 then begin//20080630
for I := 0 to PlugList.Count - 1 do begin
Module := pTPlugInfo(PlugList.Objects[I]).Module;
PFunc := GetProcAddress(Module, 'UnInit');
if @PFunc <> nil then PFunc();
FreeLibrary(Module);
end;
end;
end;
initialization
finalization
end.
|
unit AnsiEmulVT;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, emulvt;
type
TMouseOp = (moSelection, moDraw, moMoveSelection);
TAnsiEmulVT = class(TEmulVT)
private
{ Private declarations }
FAfterSelection: TNotifyEvent;
SaveLines: array[0..50] of TLine;
FMoveStart: TPoint;
function AnsiCopyOneLine(i, c1, c2: integer): string;
function AttToEscChar(att: word; var bblink, bhigh: boolean;
var fore, back: byte): string;
function MoveRect(var Rect1: TRect; dx, dy: integer): boolean;
function AdjustRect(var Rect1: TRect): boolean;
protected
{ Protected declarations }
FMouseDown: boolean;
FMouseTop: integer;
FMouseLeft: integer;
FFocusDrawn: boolean;
FFocusRect: TRect;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
public
{ Public declarations }
MouseMoveOp: TMouseOp;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CutSelected(r: TRect);
procedure RectToRowCol(r: TRect; var r1, r2, c1, c2: integer);
procedure SaveScreenLines;
procedure DrawFocusRectangle(Wnd: HWnd; Rect: TRect);
procedure UnSelect;
procedure CopyToClipBoard(bAnsi: boolean);
procedure CutToClipBoard(bAnsi: boolean);
procedure Delete;
procedure BrightSelection;
procedure DeBrightSelection;
procedure SetAttrSelection(Att: word);
procedure SetTextSelection(txt: string);
procedure SetText(x, y: integer; att: word; s1: string);
procedure DrawTableBorder(att: word);
procedure DrawTableLine(att: word);
procedure DrawCnTableBorder(att: word);
procedure DrawCnTableLine(att: word);
procedure LoadFromFile(FileName: string);
procedure SaveToFile(FileName: string);
published
{ Published declarations }
property AfterSelection: TNotifyEvent read FAfterSelection write FAfterSelection;
end;
procedure Register;
implementation
uses Clipbrd;
procedure Register;
begin
RegisterComponents('Samples', [TAnsiEmulVT]);
end;
constructor TAnsiEmulVT.Create(AOwner: TComponent);
var
i: integer;
begin
inherited Create(AOwner);
SingleCharPaint := True;
for i := 0 to 40 do
begin
SaveLines[i] := TLine.Create;
end;
end;
destructor TAnsiEmulVT.Destroy;
var
i: integer;
begin
for i := 0 to Rows - 1 do
begin
SaveLines[i].Free;
end;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TAnsiEmulVT.DrawFocusRectangle(Wnd: HWnd; Rect: TRect);
var
DC: HDC;
r1: TRect;
l1: integer;
begin
DC := GetDC(Wnd);
if not FFocusDrawn then
begin
DrawSelectRect(DC, rect);
end
else if SelectMode = smBlock then
begin
{DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
}
if ((rect.Bottom >= rect.Top) and (FFocusRect.Bottom <= FFocusRect.Top)) or
((rect.Bottom <= rect.Top) and (FFocusRect.Bottom >= FFocusRect.Top)) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
else if rect.Bottom <= rect.Top then
begin
if FFocusRect.Bottom > rect.Bottom then
begin
r1 := rect;
r1.Top := FFocusRect.Bottom;
DrawSelectRect(DC, r1);
r1 := rect;
r1.Bottom := FFocusRect.Bottom;
r1.Left := FFocusRect.Right;
DrawSelectRect(DC, r1);
end
else
begin
r1 := FFocusRect;
r1.Top := rect.Bottom;
DrawSelectRect(DC, r1);
r1 := FFocusRect;
r1.Bottom := rect.Bottom;
r1.Left := rect.Right;
DrawSelectRect(DC, r1);
end;
end
else
begin
if FFocusRect.Bottom <= rect.Bottom then
begin
r1 := rect;
r1.Left := FFocusRect.Right;
DrawSelectRect(DC, r1);
r1 := rect;
r1.Right := FFocusRect.Right;
r1.Top := FFocusRect.Bottom;
DrawSelectRect(DC, r1);
end
else
begin
r1 := FFocusRect;
r1.Left := rect.Right;
DrawSelectRect(DC, r1);
r1 := FFocusRect;
r1.Right := rect.Right;
r1.Top := rect.Bottom;
DrawSelectRect(DC, r1);
end;
end;
end
else if (rect.Top >= rect.Bottom) then
begin
if (FFocusRect.Top < FFocusRect.Bottom) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
{else if (FFocusRect.Bottom < TopMargin) or (rect.Bottom < TopMargin) then begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end}
else
begin
if FFocusRect.Bottom > rect.Bottom then
begin
l1 := PixelToRow(rect.Bottom);
if rect.Bottom < TopMargin then l1 := -1;
r1.Top := TopMargin + FLinePos[l1 + 1];
r1.Left := rect.Right;
l1 := PixelToRow(FFocusRect.Bottom);
if FFocusRect.Bottom < TopMargin then l1 := -1;
r1.Bottom := TopMargin + FLinePos[l1 + 2];
r1.Right := FFocusRect.Right;
DrawSelectRect(DC, r1);
end
else
begin
l1 := PixelToRow(FFocusRect.Bottom);
if FFocusRect.Bottom < TopMargin then l1 := -1;
r1.Top := TopMargin + FLinePos[l1 + 1];
r1.Left := FFocusRect.Right;
l1 := PixelToRow(rect.Bottom);
if rect.Bottom < TopMargin then l1 := -1;
r1.Bottom := TopMargin + FLinePos[l1 + 2];
r1.Right := rect.Right;
DrawSelectRect(DC, r1);
end;
end;
end
else if (rect.Top < rect.Bottom) and (FFocusRect.Top >= FFocusRect.Bottom) then
begin
DrawSelectRect(DC, FFocusRect);
DrawSelectRect(DC, rect);
end
else if (rect.Top = FFocusRect.Top) and (rect.Left = FFocusRect.Left) and
(rect.Top < rect.Bottom) then
begin
if rect.Bottom = FFocusRect.Bottom then
begin
l1 := PixelToRow(FFocusRect.Bottom - LineHeight);
r1.Left := rect.Right;
r1.Right := FFocusRect.Right;
r1.Top := rect.Bottom;
r1.Bottom := TopMargin + FLinePos[l1];
InvertRect(DC, r1);
end
else if rect.Bottom > FFocusRect.Bottom then
begin
l1 := PixelToRow(FFocusRect.Bottom - LineHeight);
r1 := rect;
r1.Left := FFocusRect.Right;
r1.Top := TopMargin + FLinePos[l1];
DrawSelectRect(DC, r1);
end
else
begin
l1 := PixelToRow(rect.Bottom - LineHeight);
r1 := FFocusRect;
r1.Left := rect.Right;
r1.Top := TopMargin + FLinePos[l1];
DrawSelectRect(DC, r1);
end;
end;
ReleaseDC(Wnd, DC);
end;
procedure TAnsiEmulVT.SaveScreenLines;
var
i: integer;
begin
for i := 0 to Rows do
begin
Move(Screen.Lines[i].Txt, SaveLines[i].Txt, SizeOf(SaveLines[i].Txt));
Move(Screen.Lines[i].Att, SaveLines[i].Att, SizeOf(SaveLines[i].Att));
end;
end;
procedure TAnsiEmulVT.CutSelected(r: TRect);
var
i, j: integer;
r1, r2: integer;
c1, c2: integer;
begin
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
SaveLines[i].Txt[j] := ' ';
SaveLines[i].Att[j] := 7;
end;
end;
end;
function TAnsiEmulVT.AdjustRect(var Rect1: TRect): boolean;
var
r: TRect;
c1, c2, i: integer;
bExchange: boolean;
begin
r := Rect1;
bExchange := False;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
bExchange := True;
end;
if (r.Left > r.Right) then
begin
c1 := r.Left;
r.Left := r.Right;
r.Right := c1;
bExchange := True;
end;
Result := bExchange;
end;
procedure TAnsiEmulVT.RectToRowCol(r: TRect; var r1, r2, c1, c2: integer);
begin
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
end;
function TAnsiEmulVT.MoveRect(var Rect1: TRect; dx, dy: integer): boolean;
var
c1, c2, c3, c4: integer;
r1, r2, r3, r4: integer;
i, j: integer;
r: TRect;
saveline2: array [0..50] of TLine;
begin
Result := False;
if Rect1.Top < 0 then Exit;
r := Rect1;
AdjustRect(r);
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
Dec(r.Left, dx);
Dec(r.Right, dx);
Dec(r.Top, dy);
Dec(r.Bottom, dy);
if (r.Left < 0) or (r.Top < 0) then Exit;
r3 := PixelToRow(r.Top);
r4 := r3 + r2 - r1;
if (r3 = r4) and (r.Left > r.Right) then
begin
c4 := PixelToCol(r.Left - 2);
c3 := PixelToCol(r.Right);
end
else
begin
c3 := PixelToCol(r.Left);
c4 := PixelToCol(r.Right - 2);
end;
for i := r1 to r2 do
begin
saveline2[i] := TLine.Create;
Move(Screen.Lines[i].Txt, saveline2[i].Txt, SizeOf(saveline2[i].Txt));
Move(Screen.Lines[i].Att, saveline2[i].Att, SizeOf(saveline2[i].Att));
end;
for i := r3 to r4 do
begin
for j := c3 to c4 do
begin
Screen.Lines[i].Txt[j] := saveline2[i + r1 - r3].Txt[j + c1 - c3];
// Screen.Lines[i+r1-r3].Txt[j+c1-c3];
Screen.Lines[i].Att[j] := saveline2[i + r1 - r3].Att[j + c1 - c3];
//Screen.Lines[i+r1-r3].Att[j+c1-c3];
end;
end;
for i := r1 to r2 do
begin
saveline2[i].Free;
end;
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
if ((i < r3) or (i > r4) or (j < c3) or (j > c4)) then
begin
Screen.Lines[i].Txt[j] := savelines[i].Txt[j];
Screen.Lines[i].Att[j] := savelines[i].Att[j];
end;
end;
end;
if (r1 <> r3) or (c3 <> c1) then
begin
Rect1 := r;
{ Dec(Rect1.Left, dx);
Dec(Rect1.Top, dy);
Dec(Rect1.Right, dx);
Dec(Rect1.Bottom, dy);
}
end;
Result := True;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TAnsiEmulVT.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if Button = mbRight then Exit;
FMouseDown := True;
if (SelectRect.Top > 0) and (MouseMoveOp = moMoveSelection) then
begin
//SaveScreenLines;
FMoveStart.X := SnapPixelToCol(X);
FMoveStart.Y := SnapPixelToRow(Y);
Exit;
end;
if FFocusDrawn then
begin
//if not swapdraw then DrawFocusRectangle(Handle, FFocusRect);
FFocusDrawn := False;
end;
if (SelectRect.Top <> -1) and (Button = mbLeft) then
begin
FFocusRect.Top := -1;
SelectRect := FFocusRect;
//if swapdraw then UpdateScreen;
Repaint;
end;
end;
function EqualRect(r1, r2: TRect): boolean;
begin
if (r1.Left = r2.Left) and (r1.Top = r2.Top) and (r1.Right = r2.Right) and
(r1.Bottom = r2.Bottom) then Result := True
else
Result := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TAnsiEmulVT.MouseMove(Shift: TShiftState; X, Y: integer);
var
Rect: TRect;
Point: TPoint;
i, j, ch1, ch2: integer;
pstr: string;
r: TRect;
begin
inherited MouseMove(Shift, X, Y);
if not FMouseDown then
Exit;
if not FMouseCaptured then
begin
SetCapture(Handle);
FMouseCaptured := True;
FMouseTop := SnapPixelToRow(Y);
FMouseLeft := SnapPixelToCol(X);
Point.X := 0;
Point.Y := 0;
Rect.TopLeft := ClientToScreen(Point);
Point.X := Width;
Point.Y := Height;
Rect.BottomRight := ClientToScreen(Point);
ClipCursor(@Rect);
end
else if (MouseMoveOp = moMoveSelection) then
begin
FFocusRect := SelectRect;
AdjustRect(FFocusRect);
i := SnapPixelToRow(FFocusRect.Top - FMoveStart.Y + Y);
j := SnapPixelToCol(FFocusRect.Left - FMoveStart.X + X);
if j < LeftMargin then j := LeftMargin + FMoveStart.X - FFocusRect.Left;
if i < TopMargin then i := TopMargin + FMoveStart.Y - FFocusRect.Top;
if j + FFocusRect.Right - FFocusRect.Left > LeftMargin + FCharPos[Cols] then
j := LeftMargin + FCharPos[Cols] + FFocusRect.Left - FFocusRect.Right;
if (i + FFocusRect.Bottom - FFocusRect.Top) > TopMargin + FLinePos[Rows] then
i := TopMargin + FLinePos[Rows] + FFocusRect.Top - FFocusRect.Bottom;
if (j = FFocusRect.Left) and (i = FFocusRect.Top) then Exit;
if MoveRect(FFocusRect, FFocusRect.Left - j, FFocusRect.Top - i) then
begin
FMouseLeft := SnapPixelToCol(X);;
FMouseTop := SnapPixelToRow(Y);
FMoveStart.X := FMouseLeft;
FMoveStart.Y := FMouseTop;
SelectRect := FFocusRect;
r := GetClientRect;
//InvalidateRect(Handle, @r, False);
Refresh;
end;
Exit;
end
else if (FMouseTop <> Y) or (FMouseLeft <> X) then
begin
Rect.Top := FMouseTop;
Rect.Left := FMouseLeft;
i := PixelToRow(Y);
if i >= Rows then Exit;
if Y > Rect.Top then
Rect.Bottom := SnapPixelToRow(Y) + FLinePos[i + 1] - FLinePos[i]
else
begin
{if Y < TopMargin then begin
Rect.Bottom := TopMargin;
end
else}
if i > 1 then
Rect.Bottom := SnapPixelToRow(Y) - (FLinePos[i] - FLinePos[i - 1])
else
Rect.Bottom := SnapPixelToRow(Y) - FLinePos[1];
end;
//i := PixelToCol(X);
Rect.Right := SnapPixelToCol(X);
if EqualRect(FFocusRect, Rect) then Exit;
// if FFocusDrawn and (not swapdraw) then DrawFocusRectangle(Handle, FFocusRect);
if (MouseMoveOp = moSelection) then
DrawFocusRectangle(Handle, Rect);
FFocusRect := Rect;
if (MouseMoveOp = moDraw) then
begin
FFocusRect.Top := -1;
end;
SelectRect := FFocusRect; {fuse +}
FFocusDrawn := True;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TAnsiEmulVT.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
var
urlstr: string;
i: integer;
begin
inherited MouseUp(Button, Shift, X, Y);
if Button = mbRight then Exit;
FMouseDown := False;
if FMouseCaptured then
begin
ReleaseCapture;
FMouseCaptured := False;
ClipCursor(nil);
end;
if FFocusDrawn and (MouseMoveOp = moMoveSelection) then
begin
Exit;
end;
if FFocusDrawn then
begin
//if not swapdraw then InvalidateRect(Handle, @SelectRect, false); //DrawFocusRectangle(Handle, FFocusRect);
FFocusDrawn := False;
i := PixelToCol(FFocusRect.Left);
if Abs(FFocusRect.Right - FFocusRect.Left) < DrawCharWidth(i) then
FFocusRect.Top := -1;
i := PixelToRow(FFocusRect.Top);
if Abs(FFocusRect.Bottom - FFocusRect.Top) < DrawLineHeight(i) then
FFocusRect.Top := -1;
if (MouseMoveOp = moDraw) then
begin
FFocusRect.Top := -1;
end;
SelectRect := FFocusRect;
//if swapdraw then UpdateScreen;
InvalidateRect(Handle, @SelectRect, False);
//Repaint;
if Assigned(FAfterSelection) then FAfterSelection(self);
Exit;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * *}
procedure TAnsiEmulVT.UnSelect;
begin
if FMouseCaptured then
begin
ReleaseCapture;
FMouseCaptured := False;
ClipCursor(nil);
end;
if SelectRect.Top <> -1 then
begin
FFocusRect.Top := -1;
SelectRect := FFocusRect;
UpdateScreen;
Repaint;
end;
end;
procedure TAnsiEmulVT.LoadFromFile(FileName: string);
var
F1: TextFile;
s1: string;
i: integer;
begin
Screen.ClearScreen;
AssignFile(F1, Filename);
Reset(F1);
while not EOF(F1) do
begin
ReadLn(F1, s1);
WriteStr(s1);
if Screen.FRow < Rows then
begin
Inc(Screen.FRow);
Screen.FCol := 0;
end
else
break;
end;
CloseFile(F1);
UpdateScreen;
end;
procedure TAnsiEmulVT.SaveToFile(FileName: string);
var
F1: TextFile;
s1: string;
i: integer;
begin
AssignFile(F1, Filename);
ReWrite(F1);
for i := 0 to Rows - 1 do
begin
s1 := AnsiCopyOneLine(i, 0, Cols - 1);
WriteLn(F1, s1);
end;
CloseFile(F1);
end;
function TAnsiEmulVT.AttToEscChar(att: word; var bblink, bhigh: boolean;
var fore, back: byte): string;
var
b1, b2: byte;
ss, ss2: string;
bclear: boolean;
begin
bclear := False;
b1 := (att shr 4) and $0f;
b2 := att and $0f;
ss := #$1B + '[';
if (att and X_UNDERLINE) <> 0 then ss2 := #$1B + '[4m'
else
ss2 := '';
if (b1 > 7) and (b2 > 7) then
begin
if bhigh then
begin
if not bblink then ss := #$1B + '[5;';
end
else
begin
if not bblink then ss := #$1B + '[5;1;'
else
ss := #$1B + '[1;'
end;
bblink := True;
bhigh := True;
b1 := b1 and $07;
b2 := b2 and $07;
end
else if (b1 > 7) then
begin
if not bblink then ss := #$1B + '[5;';
b1 := b1 and $07;
bblink := True;
end
else if (b2 > 7) then
begin
if bhigh then
begin
if bblink then
begin
ss := #$1B + '[0;1;';
bclear := True;
end
else
ss := #$1B + '[';
end
else
begin
if bblink then
begin
ss := #$1B + '[0;1;';
bclear := True;
end
else
ss := #$1B + '[1;';
end;
bhigh := True;
bblink := False;
b2 := b2 and $07;
end
else
begin
if bhigh then
begin
if bblink then ss := #$1B + '[0;'
else
ss := #$1B + '[0;';
bclear := True;
end
else
begin
if bblink then
begin
ss := #$1B + '[0;';
bclear := True;
end
else
ss := #$1B + '[';
end;
bblink := False;
bhigh := False;
end;
if (b1 <> 0) and (b2 <> 0) then
begin
if (b1 <> back) or (bclear) then ss := ss + IntToStr(40 + b1) + ';';
back := b1;
ss := ss + IntToStr(30 + b2) + 'm';
fore := b2;
end
else if (b2 = 0) then
begin
if bhigh then
begin
ss := ss + IntToStr(40 + b1) + ';';
ss := ss + IntToStr(30 + b2) + 'm';
end
else
begin
ss := ss + IntToStr(40 + b1) + ';';
ss := ss + IntToStr(30 + b2) + 'm';
end;
back := b1;
fore := 0;
//ss := ss + IntToStr(30 + b2) + 'm';
end
else if (b1 = 0) then
begin
if back <> 0 then ss := ss + '40';
back := 0;
if (Length(ss) > 0) and (ss[Length(ss)] = ';') then
ss := Copy(ss, 1, Length(ss) - 1);
if (b2 = fore) and (not bclear) then ss := ss + 'm'
else
begin
if ss[Length(ss)] = '[' then ss := ss + IntToStr(30 + b2) + 'm'
else
ss := ss + ';' + IntToStr(30 + b2) + 'm';
end;
fore := b2;
//ss := ss + IntToStr(40 + b1) + 'm';
end;
if (ss = #$1B + '[40;37m') and (not bblink) and (not bhigh) then ss := #$1B + '[m'
else if (ss = #$1B + '[37m') and (back = 0) and (not bblink) and (not bhigh) then
ss := #$1B + '[m';
if ss = #$1B + '[m' then
begin
back := 0;
fore := 7;
bhigh := False;
bblink := False;
end;
if ss2 <> '' then ss := ss2 + ss;
Result := ss;
end;
function TAnsiEmulVT.AnsiCopyOneLine(i, c1, c2: integer): string;
var
j, js: integer;
atts1, s: string;
natt: word;
bblink, bhigh: boolean;
fore, back: byte;
begin
j := c1;
s := '';
while (j <= c2) and (Screen.Lines[i].Att[j] = $07) do
begin
s := s + Screen.Lines[i].Txt[j];
Inc(j);
end;
if j >= c2 then
begin
{for js := c1 to c2 do
begin
s := s + TnEmulVT1.Screen.Lines[i].Txt[js];
end;}
s := TrimRight(s);
Result := s;
Exit;
end;
bblink := False;
bhigh := False;
back := 0;
fore := 7;
repeat
js := j;
nAtt := Screen.Lines[i].Att[j];
atts1 := AttToEscChar(nAtt, bblink, bhigh, fore, back);
s := s + atts1;
while (nAtt = Screen.Lines[i].Att[js]) and (js <= c2) do
begin
s := s + Screen.Lines[i].Txt[js];
Inc(js);
end;
j := js;
until j >= c2;
if (SelectMode = smLine) and (back = 0) then s := TrimRight(s);
s := s + #$1B + '[m';
Result := s;
end;
procedure TAnsiEmulVT.CopyToClipBoard(bAnsi: boolean);
var
r: TRect;
i, j: integer;
P: string;
s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
s := '';
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
if not bAnsi then
begin
for j := c1 to c3 do
begin
s := s + Screen.Lines[i + TopLine].Txt[j];
end;
s := TrimRight(s);
//s := s + TnEmulVT1.Screen.Lines[i].Txt[j];
end
else
begin
s := AnsiCopyOneline(i, c1, c3);
end;
if r1 <> r2 then P := P + s + #13 + #10
else
P := P + s;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
s := '';
if not bAnsi then
begin
for j := c1 to c2 do
begin
s := s + Screen.Lines[i + TopLine].Txt[j];
end;
s := TrimRight(s);
//s := s + TnEmulVT1.Screen.Lines[i].Txt[j];
end
else
begin
s := AnsiCopyOneline(i, c1, c2);
end;
if r1 <> r2 then P := P + s + #13 + #10
else
P := P + s;
end;
end;
Clipboard.SetTextBuf(PChar(P));
end;
procedure TAnsiEmulVT.CutToClipBoard(bAnsi: boolean);
var
r: TRect;
i, j: integer;
P: string;
s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
s := '';
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
if not bAnsi then
begin
for j := c1 to c3 do
begin
s := s + Screen.Lines[i + TopLine].Txt[j];
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
s := TrimRight(s);
//s := s + TnEmulVT1.Screen.Lines[i].Txt[j];
end
else
begin
s := AnsiCopyOneline(i, c1, c3);
for j := c1 to c3 do
begin
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
end;
if r1 <> r2 then P := P + s + #13 + #10
else
P := P + s;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
s := '';
if not bAnsi then
begin
for j := c1 to c2 do
begin
s := s + Screen.Lines[i + TopLine].Txt[j];
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
s := TrimRight(s);
//s := s + TnEmulVT1.Screen.Lines[i].Txt[j];
end
else
begin
s := AnsiCopyOneline(i, c1, c2);
for j := c1 to c2 do
begin
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
end;
if r1 <> r2 then P := P + s + #13 + #10
else
P := P + s;
end;
end;
Clipboard.SetTextBuf(PChar(P));
end;
procedure TAnsiEmulVT.Delete;
var
r: TRect;
i, j: integer;
P: string;
//s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
for j := c1 to c3 do
begin
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
Screen.Lines[i + TopLine].Txt[j] := ' ';
Screen.Lines[i + TopLine].Att[j] := 7;
end;
end;
end;
end;
procedure TAnsiEmulVT.BrightSelection;
var
r: TRect;
i, j: integer;
P: string;
//s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
for j := c1 to c3 do
begin
Screen.Lines[i + TopLine].Att[j] :=
Screen.Lines[i + TopLine].Att[j] or $08;
end;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
Screen.Lines[i + TopLine].Att[j] :=
Screen.Lines[i + TopLine].Att[j] or $08;
end;
end;
end;
end;
procedure TAnsiEmulVT.DeBrightSelection;
var
r: TRect;
i, j: integer;
P: string;
//s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
for j := c1 to c3 do
begin
Screen.Lines[i + TopLine].Att[j] :=
Screen.Lines[i + TopLine].Att[j] and $FFF7;
end;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
Screen.Lines[i + TopLine].Att[j] :=
Screen.Lines[i + TopLine].Att[j] and $FFF7;
end;
end;
end;
end;
procedure TAnsiEmulVT.SetTextSelection(txt: string);
var
r: TRect;
i, j, j1, len: integer;
c1, c2, c3, r1, r2: integer;
begin
len := Length(txt);
if len < 0 then Exit;
r := SelectRect;
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
for i := r1 to r2 do
begin
j := c1;
j1 := 1;
while j < c2 do
begin
Screen.Lines[i + TopLine].Txt[j] := txt[j1];
Inc(j1);
Inc(j);
if j1 > len then j1 := 1;
end;
end;
end;
procedure TAnsiEmulVT.SetAttrSelection(Att: word);
var
r: TRect;
i, j: integer;
//P: string;
//s: string;
c1, c2, c3, r1, r2: integer;
begin
if SelectRect.Top > 0 then
r := SelectRect;
if (r.Top > r.Bottom) then
begin
c1 := r.Left;
c2 := r.Top;
i := DrawLineHeight(1);
r.Left := r.Right;
r.Top := r.Bottom + i;
r.Right := c1;
r.Bottom := c2 + i;
end;
r1 := PixelToRow(r.Top);
r2 := PixelToRow(r.Bottom - LineHeight + 1);
if (r1 = r2) and (r.Left > r.Right) then
begin
c2 := PixelToCol(r.Left - 2);
c1 := PixelToCol(r.Right);
end
else
begin
c1 := PixelToCol(r.Left);
c2 := PixelToCol(r.Right - 2);
end;
//P := '';
if SelectMode = smLine then
begin
for i := r1 to r2 do
begin
if i > r1 then c1 := 0;
if i = r2 then c3 := c2
else
c3 := Cols;
for j := c1 to c3 do
begin
Screen.Lines[i + TopLine].Att[j] := Att;
end;
end;
end
else if SelectMode = smBlock then
begin
for i := r1 to r2 do
begin
for j := c1 to c2 do
begin
Screen.Lines[i + TopLine].Att[j] := Att;
end;
end;
end;
end;
procedure TAnsiEmulVT.SetText(x, y: integer; att: word; s1: string);
var
i: integer;
begin
for i := 1 to Length(s1) do
begin
Screen.Lines[y].Att[x + i - 1] := Att;
Screen.Lines[y].Txt[x + i - 1] := s1[i];
end;
end;
procedure TAnsiEmulVT.DrawTableBorder(att: word);
var
r: TRect;
i: integer;
c1, c2, c3, r1, r2: integer;
begin
r := SelectRect;
if r.Top < 0 then Exit;
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
if c2 - c1 < 3 then Exit;
if r2 - r1 < 2 then Exit;
Screen.Lines[r1].Txt[c1] := '+';
Screen.Lines[r1].Txt[c2] := '+';
Screen.Lines[r2].Txt[c1] := '+';
Screen.Lines[r2].Txt[c2] := '+';
Screen.Lines[r1].Att[c1] := att;
Screen.Lines[r1].Att[c2] := att;
Screen.Lines[r2].Att[c1] := att;
Screen.Lines[r2].Att[c2] := att;
for i := c1 + 1 to c2 - 1 do
begin
Screen.Lines[r1].Txt[i] := '-';
Screen.Lines[r2].Txt[i] := '-';
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r2].Att[i] := Att;
end;
for i := r1 + 1 to r2 - 1 do
begin
Screen.Lines[i].Txt[c1] := '|';
Screen.Lines[i].Txt[c2] := '|';
Screen.Lines[i].Att[c1] := Att;
Screen.Lines[i].Att[c2] := Att;
end;
end;
procedure TAnsiEmulVT.DrawTableLine(att: word);
var
r: TRect;
i: integer;
c1, c2, c3, r1, r2: integer;
begin
r := SelectRect;
if r.Top < 0 then Exit;
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
if (r2 - r1) > (c2 - c1) then
begin
if r2 - r1 < 2 then Exit;
for i := r1 + 1 to r2 - 1 do
begin
Screen.Lines[i].Txt[c1] := '|';
Screen.Lines[i].Att[c1] := Att;
end
end
else
begin
if c2 - c1 < 3 then Exit;
for i := c1 + 1 to c2 - 1 do
begin
Screen.Lines[r1].Txt[i] := '-';
Screen.Lines[r1].Att[i] := Att;
end;
end;
end;
procedure TAnsiEmulVT.DrawCnTableBorder(att: word);
var
r: TRect;
i: integer;
c1, c2, c3, r1, r2: integer;
begin
r := SelectRect;
if r.Top < 0 then Exit;
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
if c2 - c1 < 3 then Exit;
if r2 - r1 < 2 then Exit;
if ((c2 - c1) mod 2) = 0 then c2 := c2 + 1;
Move('©³', Screen.Lines[r1].Txt[c1], 2);
Move('©·', Screen.Lines[r1].Txt[c2 - 1], 2);
Move('©»', Screen.Lines[r2].Txt[c1], 2);
Move('©¿', Screen.Lines[r2].Txt[c2 - 1], 2);
Screen.Lines[r1].Att[c1] := att;
Screen.Lines[r1].Att[c2] := att;
Screen.Lines[r2].Att[c1] := att;
Screen.Lines[r2].Att[c2] := att;
Screen.Lines[r1].Att[c1 + 1] := att;
Screen.Lines[r1].Att[c2 - 1] := att;
Screen.Lines[r2].Att[c1 + 1] := att;
Screen.Lines[r2].Att[c2 - 1] := att;
i := c1 + 2;
while i < c2 - 2 do
begin
Move('©¥', Screen.Lines[r1].Txt[i], 2);
Move('©¥', Screen.Lines[r2].Txt[i], 2);
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r2].Att[i] := Att;
Screen.Lines[r1].Att[i + 1] := Att;
Screen.Lines[r2].Att[i + 1] := Att;
Inc(i, 2);
end;
for i := r1 + 1 to r2 - 1 do
begin
Move('©§', Screen.Lines[i].Txt[c1], 2);
Move('©§', Screen.Lines[i].Txt[c2 - 1], 2);
Screen.Lines[i].Att[c1] := Att;
Screen.Lines[i].Att[c2] := Att;
Screen.Lines[i].Att[c1 + 1] := Att;
Screen.Lines[i].Att[c2 - 1] := Att;
end;
end;
procedure TAnsiEmulVT.DrawCnTableLine(att: word);
var
r: TRect;
i, j: integer;
c1, c2, c3, r1, r2: integer;
ss1: array [0..5] of char;
begin
r := SelectRect;
if r.Top < 0 then Exit;
AdjustRect(r);
RectToRowCol(r, r1, r2, c1, c2);
if (r2 - r1) > (c2 - c1) then
begin
if r2 - r1 < 2 then Exit;
for i := r1 to r2 do
begin
if (Screen.Lines[i].Txt[c1] = ' ') and
(Screen.Lines[i].Txt[c1 + 1] = ' ') then
begin
Move('©¦', Screen.Lines[i].Txt[c1], 2);
Screen.Lines[i].Att[c1] := Att;
Screen.Lines[i].Att[c1 + 1] := Att;
end
else
begin
Move(Screen.Lines[i].Txt[c1], ss1, 2);
if StrPos(ss1, '©¤') <> nil then
begin
Move('©à', Screen.Lines[i].Txt[c1], 2);
Screen.Lines[r1].Att[c1] := Att;
Screen.Lines[r1].Att[c1 + 1] := Att;
end
else if (i = r1) and (StrPos(ss1, '©¥') <> nil) then
begin
Move('©Ó', Screen.Lines[i].Txt[c1], 2);
Screen.Lines[r1].Att[c1] := Att;
Screen.Lines[r1].Att[c1 + 1] := Att;
end
else if (i = r2) and (StrPos(ss1, '©¥') <> nil) then
begin
Move('©Û', Screen.Lines[i].Txt[c1], 2);
Screen.Lines[r1].Att[c1] := Att;
Screen.Lines[r1].Att[c1 + 1] := Att;
end
end;
end
end
else
begin
if c2 - c1 < 3 then Exit;
{ i := c1;
while (Screen.Lines[r1].Txt[i] <> ' ') do begin
Inc(i);
end;
j := c2;
while (Screen.Lines[r1].Txt[j] <> ' ') do begin
Dec(j);
end;
}
i := c1;
j := c2;
while i < j do
begin
if (Screen.Lines[r1].Txt[i] = ' ') and
(Screen.Lines[r1].Txt[i + 1] = ' ') then
begin
Move('©¤', Screen.Lines[r1].Txt[i], 2);
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r1].Att[i + 1] := Att;
Inc(i, 2);
end
else
begin
Move(Screen.Lines[r1].Txt[i], ss1, 2);
if StrPos(ss1, '©¦') <> nil then
begin
Move('©à', Screen.Lines[r1].Txt[i], 2);
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r1].Att[i + 1] := Att;
Inc(i, 2);
end
else if (i = c1) and (StrPos(ss1, '©§') <> nil) then
begin
Move('©Ä', Screen.Lines[r1].Txt[i], 2);
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r1].Att[i + 1] := Att;
Inc(i, 2);
end
else if (i - c2 < 2) and (StrPos(ss1, '©§') <> nil) then
begin
Move('©Ì', Screen.Lines[r1].Txt[i], 2);
Screen.Lines[r1].Att[i] := Att;
Screen.Lines[r1].Att[i + 1] := Att;
Inc(i, 2);
end
else
begin
Inc(i);
end;
end;
end;
end;
end;
end.
|
unit GLDDesignTime;
interface
uses
Classes, Types, DesignIntf, DesignEditors;
type
TGLDColorClassProperty = class(TClassProperty)
private
procedure Change(Sender: TObject);
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDVectorClassProperty = class(TClassProperty)
private
procedure Change(Sender: TObject);
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDRotationClassProperty = class(TClassProperty)
private
procedure Change(Sender: TObject);
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDMaterialProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDUserCameraProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDSystemRenderOptionsProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TGLDRepositoryEditor = class(TComponentEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure Register;
implementation
uses
SysUtils, Controls, GLDTypes, GLDClasses, GLDObjects, GLDMaterial, GLDCamera,
GLDRepository, GLDSystem, GLDColorForm, GLDVectorForm, GLDRotationForm,
GLDMaterialPickerForm, GLDUserCameraPickerForm,
GLDRenderOptionsForm, GLDRepositoryForm;
type
TGLDDesignerHolder = class
public
Designer: IDesigner;
constructor Create;
procedure SelectComponent(Instance: TPersistent);
procedure Modified;
end;
var
vDesignerHolder: TGLDDesignerHolder = nil;
function TGLDColorClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDColorClassProperty.Edit;
begin
with GLDGetColorForm do
begin
OnChange := Self.Change;
EditedColor := TGLDColorClass(GetOrdValue);
Show;
end;
end;
procedure TGLDColorClassProperty.Change(Sender: TObject);
begin
Modified;
end;
function TGLDVectorClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDVectorClassProperty.Edit;
begin
with GLDGetVectorForm do
begin
OnChange := Self.Change;
EditedVector := TGLDVector4fClass(GetOrdValue);
Show;
end;
end;
procedure TGLDVectorClassProperty.Change(Sender: TObject);
begin
Modified;
end;
function TGLDRotationClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDRotationClassProperty.Edit;
begin
with GLDGetRotationForm do
begin
OnChange := Self.Change;
EditedRotation := TGLDRotation3DClass(GetOrdValue);
Show;
end;
end;
procedure TGLDRotationClassProperty.Change(Sender: TObject);
begin
Modified;
end;
function TGLDMaterialProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDMaterialProperty.Edit;
var
DS: IDesignerSelections;
OwnerClass: TPersistent;
begin
with GLDGetMaterialPickerForm do
begin
Designer := Pointer(Self.Designer);
DS := TDesignerSelections.Create;
Self.Designer.GetSelections(DS);
if DS.Count > 0 then
if (DS.Items[0] is TGLDEditableObject) then
begin
Caption := TGLDEditableObject(DS.Items[0]).Name;
MaterialOwner := TGLDEditableObject(DS.Items[0]);
end;
if MaterialOwner <> nil then
begin
OwnerClass := MaterialOwner;
repeat
if OwnerClass is TGLDSysClass then
OwnerClass := TGLDSysClass(OwnerClass).Owner else
if OwnerClass is TGLDSysComponent then
OwnerClass := TGLDSysComponent(OwnerClass).Owner;
if OwnerClass = nil then Break;
until (OwnerClass is TGLDRepository) or (OwnerClass = nil);
if OwnerClass is TGLDRepository then
SourceMaterialList := TGLDRepository(OwnerClass).Materials;
end;
Show;
end;
end;
function TGLDUserCameraProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDUserCameraProperty.Edit;
var
DS: IDesignerSelections;
OwnerClass: TPersistent;
begin
if not Assigned(vDesignerHolder) then
vDesignerHolder := TGLDDesignerHolder.Create;
vDesignerHolder.Designer := Self.Designer;
with GLDGetUserCameraPickerForm do
begin
ModifiedMethod := vDesignerHolder.Modified;
DS := TDesignerSelections.Create;
Self.Designer.GetSelections(DS);
//Caption := IntToStr(DS.Count);
//Caption := DS.Items[0].ClassName;
if DS.Count > 0 then
if (DS.Items[0] is TGLDCameraSystem) then
begin
CameraOwner := TGLDCameraSystem(DS.Items[0]);
end else
if DS.Items[0] is TGLDSystem then
begin
CameraOwner := TGLDSystem(DS.Items[0]).CameraSystem;
end;
if CameraOwner <> nil then
begin
OwnerClass := CameraOwner;
repeat
if OwnerClass is TGLDSysClass then
OwnerClass := TGLDSysClass(OwnerClass).Owner else
if OwnerClass is TGLDSysComponent then
OwnerClass := TGLDSysComponent(OwnerClass).Owner;
if OwnerClass = nil then Break;
until (OwnerClass is TGLDRepository) or (OwnerClass is TGLDSystem) or (OwnerClass = nil);
if OwnerClass is TGLDRepository then
SourceCameraList := TGLDRepository(OwnerClass).Cameras else
if OwnerClass is TGLDSystem then
if Assigned(TGLDSystem(OwnerClass).Repository) then
SourceCameraList := TGLDSystem(OwnerClass).Repository.Cameras;
end;
Show;
end;
end;
function TGLDSystemRenderOptionsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TGLDSystemRenderOptionsProperty.Edit;
begin
with GLDGetRenderOptionsForm do
begin
Params := TGLDSystemRenderOptions(GetOrdValue).Params;
if ShowModal = mrOk then
TGLDSystemRenderOptions(GetOrdValue).Params := Params;
end;
end;
procedure TGLDRepositoryEditor.Edit;
begin
with GLDGetRepositoryForm do
begin
EditedRepository := TGLDRepository(GetComponent);
if not Assigned(vDesignerHolder) then
vDesignerHolder := TGLDDesignerHolder.Create;
vDesignerHolder.Designer := Self.Designer;
OnSelectComponent := vDesignerHolder.SelectComponent;
Show;
end;
end;
procedure TGLDRepositoryEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
function TGLDRepositoryEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Objektum tár szerkesztése';
end;
end;
function TGLDRepositoryEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
constructor TGLDDesignerHolder.Create;
begin
Designer := nil;
end;
procedure TGLDDesignerHolder.SelectComponent(Instance: TPersistent);
begin
if Assigned(Designer) then Designer.SelectComponent(Instance);
end;
procedure TGLDDesignerHolder.Modified;
begin
if Assigned(Designer) then Designer.Modified;
end;
procedure Register;
begin
RegisterPropertyEditor(TypeInfo(TGLDColorClass), nil, '', TGLDColorClassProperty);
RegisterPropertyEditor(TypeInfo(TGLDColor4ubClass), nil, '', TGLDColorClassProperty);
RegisterPropertyEditor(TypeInfo(TGLDColor4fClass), nil, '', TGLDColorClassProperty);
RegisterPropertyEditor(TypeInfo(TGLDVector4fClass), nil, '', TGLDVectorClassProperty);
RegisterPropertyEditor(TypeInfo(TGLDRotation3DClass), nil, '', TGLDRotationClassProperty);
RegisterPropertyEditor(TypeInfo(TGLDMaterial), nil, '', TGLDMaterialProperty);
RegisterPropertyEditor(TypeInfo(TGLDUserCamera), nil, '', TGLDUserCameraProperty);
RegisterPropertyEditor(TypeInfo(TGLDSystemRenderOptions), nil, '', TGLDSystemRenderOptionsProperty);
RegisterComponentEditor(TGLDRepository, TGLDRepositoryEditor);
end;
{
initialization
finalization
vDesignerHolder.Free; }
end.
|
unit LrCollectionEditorView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, Menus, ImgList,
DesignIntf, DesignEditors,
LrCollection;
type
TLrCollectionEditorForm = class(TForm)
ItemsView: TListView;
ToolBar1: TToolBar;
AddItemButton: TToolButton;
DeleteButton: TToolButton;
ToolButton1: TToolButton;
LoadButton: TToolButton;
SaveButton: TToolButton;
DropMenu: TPopupMenu;
ToolImages: TImageList;
DisabledImages: TImageList;
procedure ItemsViewData(Sender: TObject; Item: TListItem);
procedure ItemsViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure AddItemClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FCollection: TLrCustomCollection;
protected
procedure BuildAddMenu;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure RefreshList;
procedure SetCollection(const Value: TLrCustomCollection);
procedure SetCollectionName(const Value: string);
procedure UpdateDeleteButton;
procedure UpdateDesigner;
public
{ Public declarations }
Designer: IDesigner;
property Collection: TLrCustomCollection read FCollection
write SetCollection;
property CollectionName: string write SetCollectionName;
end;
var
LrCollectionEditorForm: TLrCollectionEditorForm;
implementation
{$R *.dfm}
{ TLrCollectionEditorForm }
procedure TLrCollectionEditorForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if Collection <> nil then
Collection.Editor := nil;
Action := caFree;
end;
procedure TLrCollectionEditorForm.SetCollection(
const Value: TLrCustomCollection);
begin
if FCollection <> nil then
FCollection.Owner.RemoveFreeNotification(Self);
FCollection := Value;
Collection.Owner.FreeNotification(Self);
Collection.Editor := Self;
RefreshList;
BuildAddMenu;
end;
procedure TLrCollectionEditorForm.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = Collection.Owner) then
begin
FCollection := nil;
Close;
end;
end;
procedure TLrCollectionEditorForm.BuildAddMenu;
var
i: Integer;
item: TMenuItem;
begin
DropMenu.Items.Clear;
for i := 0 to Pred(Collection.TypeCount) do
begin
item := TMenuItem.Create(Self);
item.Caption := Collection.TypeDisplayName[i];
item.Tag := i;
item.OnClick := AddItemClick;
DropMenu.Items.Add(item);
end;
end;
procedure TLrCollectionEditorForm.UpdateDeleteButton;
begin
DeleteButton.Enabled := ItemsView.Selected <> nil;
end;
procedure TLrCollectionEditorForm.UpdateDesigner;
begin
if (ItemsView.Selected <> nil) then
Designer.SelectComponent(Collection.Items[ItemsView.Selected.Index])
else
Designer.NoSelection;
end;
procedure TLrCollectionEditorForm.RefreshList;
begin
ItemsView.Items.Count := Collection.Count;
ItemsView.Invalidate;
UpdateDeleteButton;
UpdateDesigner;
end;
procedure TLrCollectionEditorForm.ItemsViewData(Sender: TObject;
Item: TListItem);
begin
if Item.Index >= Collection.Count then
Item.Caption := 'Bad Index'
else
with Collection.Items[Item.Index] do
Item.Caption := Format('%d - %s: %s', [ Item.Index, Name, ClassName ]);
end;
procedure TLrCollectionEditorForm.AddItemClick(Sender: TObject);
begin
AddItemButton.Tag := TComponent(Sender).Tag;
Collection.Add(TComponent(Sender).Tag);
RefreshList;
end;
procedure TLrCollectionEditorForm.DeleteButtonClick(Sender: TObject);
begin
Collection.Delete(ItemsView.Selected.Index);
RefreshList;
end;
procedure TLrCollectionEditorForm.ItemsViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
UpdateDeleteButton;
UpdateDesigner;
end;
procedure TLrCollectionEditorForm.SetCollectionName(const Value: string);
begin
Caption := 'Editing ' + Value;
end;
end.
|
unit ufrmDisplayPOSTransaction;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,
ufrmMasterBrowse, StdCtrls, ExtCtrls, Mask,
ActnList, System.Actions, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer,
Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, ufraFooter4Button, cxButtons,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC;
type
TfrmDisplayPOSTransaction = class(TfrmMasterBrowse)
pnl1: TPanel;
lbl1: TLabel;
dtNow: TcxDateEdit;
lbl2: TLabel;
edtPos: TEdit;
pnl3: TPanel;
lbl11: TcxLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edtPosKeyPress(Sender: TObject; var Key: Char);
procedure lbl10Click(Sender: TObject);
procedure lbl11Click(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FUnitId : Integer;
FtopMain : Integer;
FLeftMain : Integer;
// FFinalPayment : TNewFinalPayment;
procedure ParseHeaderGrid();
procedure ParseDataGrid();
procedure ShowPayment();
procedure ShowDetail();
public
{ Public declarations }
procedure ShowWithId(aUnitId: Integer; aTop: integer; aLeft : integer);
end;
var
frmDisplayPOSTransaction: TfrmDisplayPOSTransaction;
implementation
uses ufrmPopupDetailTransaction;
{$R *.dfm}
const
_kolShift : Integer = 0;
_kolCashierId : Integer = 1;
_kolCashierNm : Integer = 2;
_kolCashPayment : Integer = 3;
_kolKuponGoro : Integer = 4;
_kolKuponBottle : Integer = 5;
_kolKuponLain : Integer = 6;
_kolDebet : Integer = 7;
_kolCredit : Integer = 8;
_kolDiscCc : Integer = 9;
_kolCashBackTot : Integer = 10;
_kolCashGrandTot : Integer = 11;
_kolBegBalance : Integer = 12;
_fixedRow : Integer = 2;
_colCount : Integer = 12;
procedure TfrmDisplayPOSTransaction.ShowWithId(aUnitId: Integer; aTop: integer;
aLeft : integer);
begin
FUnitId := aUnitId;
FtopMain := aTop;
FLeftMain := aLeft;
ParseHeaderGrid;
Self.Show;
end;
procedure TfrmDisplayPOSTransaction.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDisplayPOSTransaction.FormCreate(Sender: TObject);
begin
inherited;
// FFinalPayment := TNewFinalPayment.Create(nil);
lblHeader.Caption := 'DISPLAY POS TRANSACTION';
dtNow.Date := now;
end;
procedure TfrmDisplayPOSTransaction.FormDestroy(Sender: TObject);
begin
inherited;
frmDisplayPOSTransaction := nil;
end;
procedure TfrmDisplayPOSTransaction.edtPosKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if (Key = Chr(VK_RETURN)) and (dtNow.Text <> '') then
ParseDataGrid;
end;
procedure TfrmDisplayPOSTransaction.ParseDataGrid;
//var
// i, j : Integer;
// n, m : Integer;
// sSQL : string;
// sShiftNm : string;
begin
{
cClearStringGrid(strgGrid, False);
if strgGrid.FloatingFooter.Visible then
j := _fixedRow + 1
else
j := _fixedRow;
n := strgGrid.rowCount;
m := 0;
sSQL := 'SELECT DISTINCT SHIFT_NAME FROM SHIFT'
+ ' WHERE SHIFT_UNT_ID = '+ IntToStr(FUnitId);
with cOpenQuery(sSQL) do
begin
try
while not Eof do
begin
FFinalPayment.FinalPaymentPOSItems.Clear;
sShiftNm := Fields[0].AsString;
FFinalPayment.LoadPOSTransaction(FUnitId, dtNow.Date, sShiftNm , edtPos.Text);
with FFinalPayment do
begin
for i := 0 to FinalPaymentPOSItems.Count - 1 do
begin
if (m >= n -j) then
strgGrid.AddRow;
strgGrid.Cells[_kolShift, m + _fixedRow] := FinalPaymentPOSItems[i].BeginningBalance.Shift.Name;
strgGrid.Cells[_kolCashierId, m + _fixedRow] := FinalPaymentPOSItems[i].CashierCode;
strgGrid.Cells[_kolCashierNm, m + _fixedRow] := FinalPaymentPOSItems[i].CashierName;
strgGrid.Cells[_kolCashPayment, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].CashPayment);
strgGrid.Cells[_kolKuponGoro, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].VoucherGoro);
strgGrid.Cells[_kolKuponBottle, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].VoucherBotol);
strgGrid.Cells[_kolKuponLain, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].VoucherLain);
strgGrid.Cells[_kolDebet, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].CardDebit);
strgGrid.Cells[_kolCredit, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].CardCredit);
strgGrid.Cells[_kolDiscCc, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].TotalDiscCard);
strgGrid.Cells[_kolCashBackTot, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].CashBack);
strgGrid.Cells[_kolCashGrandTot, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].GrandTotal);
strgGrid.Cells[_kolBegBalance, m + _fixedRow] := CurrToStr(FinalPaymentPOSItems[i].BeginningBalance.ID);
Inc(m)
end;
end;
Next;
end;
finally
Free;
end;
end;
with strgGrid do
begin
FloatingFooter.ColumnCalc[_kolCashPayment] := acSUM;
FloatingFooter.ColumnCalc[_kolKuponGoro] := acSUM;
FloatingFooter.ColumnCalc[_kolKuponBottle] := acSUM;
FloatingFooter.ColumnCalc[_kolKuponLain] := acSUM;
FloatingFooter.ColumnCalc[_kolDebet] := acSUM;
FloatingFooter.ColumnCalc[_kolCredit] := acSUM;
FloatingFooter.ColumnCalc[_kolDiscCc] := acSUM;
FloatingFooter.ColumnCalc[_kolCashBackTot] := acSUM;
FloatingFooter.ColumnCalc[_kolCashGrandTot]:= acSUM;
AutoSize := True;
end;
}
end;
procedure TfrmDisplayPOSTransaction.ParseHeaderGrid;
begin
{
with strgGrid do
begin
ColCount := _colCount;
if FloatingFooter.Visible then
RowCount := _fixedRow + 2
else
RowCount := _fixedRow + 1;
FixedRows := _fixedRow;
MergeCells(_kolShift,0,1,2);
Cells[_kolShift,0] := 'SHIFT';
MergeCells(_kolCashierId,0,2,1);
Cells[_kolCashierId,0] := 'CASHIER';
Cells[_kolCashierId,1] := 'ID';
Cells[_kolCashierNm,1] := 'NAME';
MergeCells(_kolCashPayment,0,1,2);
Cells[_kolCashPayment,0] := 'CASH PAYMENT';
MergeCells(_kolKuponGoro,0,3,1);
Cells[_kolKuponGoro,0] := 'VOUCHER';
Cells[_kolKuponGoro,1] := 'GORO';
Cells[_kolKuponBottle,1] := 'BOTTLE';
Cells[_kolKuponLain,1] := 'OTHER';
MergeCells(_kolDebet,0,3,1);
Cells[_kolDebet,0] := 'CARD';
Cells[_kolDebet,1] := 'DEBET';
Cells[_kolCredit,1] := 'CREDIT';
Cells[_kolDiscCc,1] := 'DISC';
MergeCells(_kolCashBackTot,0,1,2);
Cells[_kolCashBackTot,0] := 'TOT. CASHBACK';
MergeCells(_kolCashGrandTot,0,1,2);
Cells[_kolCashGrandTot,0] := 'TOT. CASHGRAND';
end;
}
end;
procedure TfrmDisplayPOSTransaction.ShowDetail;
begin
if not assigned(frmPopupDetailTransaction) then
frmPopupDetailTransaction := TfrmPopupDetailTransaction.Create(Application);
{
frmPopupDetailTransaction.ShowWithId(masternewunit.id,
strgGrid.Ints[_kolBegBalance, strgGrid.Row],
strgGrid.Cells[_kolCashierId, strgGrid.Row],
strgGrid.Cells[_kolCashierNm, strgGrid.Row],
strgGrid.Cells[_kolShift, strgGrid.Row]);
}
end;
procedure TfrmDisplayPOSTransaction.ShowPayment;
begin
// if not assigned(frmPopupPayment) then
// frmPopupPayment := TfrmPopupPayment.Create(Application);
//
// frmPopupPayment.Top := frmMain.Top + pnl3.Top - pnl3.Height;
// frmPopupPayment.Left := frmMain.Left + pnl3.Left + (pnl3.Width - frmPopupPayment.Width);
// frmPopupPayment.Free;
end;
procedure TfrmDisplayPOSTransaction.lbl10Click(Sender: TObject);
begin
ShowPayment;
end;
procedure TfrmDisplayPOSTransaction.lbl11Click(Sender: TObject);
begin
ShowDetail;
end;
procedure TfrmDisplayPOSTransaction.FormKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
inherited;
// if(Key = Ord('P'))and(ssctrl in Shift) then
// ShowPayment;
if(Key = Ord('D'))and(ssctrl in Shift) then
ShowDetail;
end;
procedure TfrmDisplayPOSTransaction.strgGridGetFloatFormat(Sender: TObject;
ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
inherited;
if ACol in [_kolShift.._kolCashierNm] then IsFloat := False;
if IsFloat then FloatFormat := '%.2n';
end;
procedure TfrmDisplayPOSTransaction.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
// inherited;
if(Key = Ord('D')) and (ssctrl in Shift) then
lbl11Click(Self)
else if(Key = VK_F5) and (ssctrl in Shift) then
GetAndRunButton('btnRefresh')
else if(Key = VK_Escape) then
Close
// else if(Key = Ord('D')) and (ssctrl in Shift) then //History PO
// actShowHistorySOExecute(sender)
// else if (Key = Ord('E')) and (ssctrl in Shift) then //Edit SO
// fraFooter5Button1btnDeleteClick(sender)
// else if (Key = Ord('C')) and (ssctrl in Shift) then //New
// fraFooter5Button1btnUpdateClick(sender);
end;
end.
|
unit DSA.Tree.BSTSet;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.Tree.BST;
type
{ TBSTSet }
generic TBSTSet<T, TComparer> = class(TInterfacedObject, specialize ISet<T>)
private
type
TBST_T = specialize TBST<T, TComparer>;
var
__bst: specialize TBST<T, TComparer>;
public
constructor Create;
procedure Add(e: T);
procedure Remove(e: T);
function Contains(e: T): boolean;
function GetSize(): integer;
function IsEmpty(): boolean;
end;
procedure Main;
implementation
uses
DSA.Utils;
type
TBSTSet_str = specialize TBSTSet<string, TComparer_str>;
procedure Main;
var
words1, words2: TArrayList_str;
set1, set2: TBSTSet_str;
i: integer;
begin
// Pride and Prejudice.txt
words1 := TArrayList_str.Create;
Writeln(A_FILE_NAME + ':');
if TDsaUtils.ReadFile(FILE_PATH + A_FILE_NAME, words1) then
begin
Writeln('Total words: ', words1.GetSize);
end;
set1 := TBSTSet_str.Create;
for i := 0 to words1.GetSize - 1 do
begin
set1.Add(words1[i]);
end;
Writeln('Total different words: ', set1.GetSize);
TDsaUtils.DrawLine;
// A Tale of Two Cities.txt
words2 := TArrayList_str.Create;
Writeln(B_FILE_NAME + ':');
if TDsaUtils.ReadFile(FILE_PATH + B_FILE_NAME, words2) then
begin
Writeln('Total words: ', words2.GetSize);
end;
set2 := TBSTSet_str.Create;
for i := 0 to words2.GetSize - 1 do
begin
set2.Add(words2[i]);
end;
Writeln('Total different words: ', set2.GetSize);
set1.Remove('a');
end;
{ TBSTSet }
procedure TBSTSet.Add(e: T);
begin
__bst.Add(e);
end;
function TBSTSet.Contains(e: T): boolean;
begin
Result := __bst.Contains(e);
end;
constructor TBSTSet.Create;
begin
__bst := TBST_T.Create;
end;
function TBSTSet.GetSize: integer;
begin
Result := __bst.GetSize;
end;
function TBSTSet.IsEmpty: boolean;
begin
Result := __bst.IsEmpty;
end;
procedure TBSTSet.Remove(e: T);
begin
__bst.Remove(e);
end;
end.
|
unit StylesMain;
interface
uses
Windows, Messages, Forms, SysUtils, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxEdit, DB, cxDBData, Dialogs, cxGridCustomPopupMenu, cxGridPopupMenu,
Classes, ActnList, ImgList, Controls, Menus, StdCtrls, ExtCtrls,
cxButtons, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxData,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
ComCtrls, cxContainer, cxRadioGroup, cxListBox, cxDataStorage,
cxLookAndFeelPainters, cxGroupBox, cxLookAndFeels, IBase, FIBDataSet,
pFIBDataSet, FIBDatabase, pFIBDatabase, Variants, dxStatusBar, cxSplitter,
FIBQuery, pFIBQuery, pFIBStoredProc, dxBar, dxBarExtItems, cxTextEdit,
cxMaskEdit, cxDropDownEdit;
type
TStylesMainForm = class(TForm)
lbDescrip: TLabel;
pnlLeft: TPanel;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
gbUserDefined: TcxGroupBox;
gbPredefined: TcxGroupBox;
lbPredefinedStyleSheets: TcxListBox;
pnlCurrentStyleSheet: TPanel;
Database: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DataSource: TDataSource;
DataSet: TpFIBDataSet;
cxSplitter1: TcxSplitter;
StatusBar: TdxStatusBar;
BottomPanel: TPanel;
ApplyButton: TcxButton;
CancelButton: TcxButton;
UDataSet: TpFIBDataSet;
AutoDataSource: TDataSource;
StoredProc: TpFIBStoredProc;
BarComboBox: TcxComboBox;
BarManager: TdxBarManager;
RightPanel: TPanel;
Grid: TcxGrid;
TableView: TcxGridDBTableView;
AutoTableView: TcxGridDBTableView;
GridLevel1: TcxGridLevel;
GridLevel2: TcxGridLevel;
dxBarDockControl1: TdxBarDockControl;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DelButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
CloseButton: TdxBarLargeButton;
Label1: TLabel;
GridComboBox: TcxComboBox;
Label2: TLabel;
StatusBarComboBox: TcxComboBox;
Label3: TLabel;
TableViewID_GROUP_UNITM: TcxGridDBColumn;
TableViewNAME_GROUP_UNITM: TcxGridDBColumn;
AutoTableViewID_GROUP_UNITM: TcxGridDBColumn;
AutoTableViewID_UNIT_MEAS: TcxGridDBColumn;
AutoTableViewNAME_UNIT_MEAS: TcxGridDBColumn;
AutoTableViewSHORT_NAME: TcxGridDBColumn;
AutoTableViewCOEFFICIENT: TcxGridDBColumn;
procedure FormShow(Sender: TObject);
procedure StatusBarComboBoxPropertiesChange(Sender: TObject);
procedure GridComboBoxPropertiesChange(Sender: TObject);
procedure BarComboBoxPropertiesChange(Sender: TObject);
procedure ApplyButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure lbPredefinedStyleSheetsClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
SYS_ID_USER : integer;
function GetCurrentStyleSheet: TcxGridTableViewStyleSheet;
procedure CreatePredefinedStyleSheetsList;
procedure UpdateGridStyleSheets(const AStyleSheet: TcxGridTableViewStyleSheet);
procedure SetPredefinedStyleSheets;
procedure InitConnection(DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE);
end;
function ShowChangeStyle(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE; fs : TFormStyle; _id_User : integer): Variant; stdcall;
exports ShowChangeStyle;
var
StylesMainForm: TStylesMainForm;
implementation
{$R *.dfm}
uses s_DM_Styles;
const
cNone = 0;
cPredefined = 1;
cUserDefined = 2;
function ShowChangeStyle(AOwner : TComponent; DBHandle : TISC_DB_HANDLE; RTrans : TISC_TR_HANDLE; fs : TFormStyle; _id_User : integer): Variant; stdcall;
var
f : TStylesMainForm;
begin
if fs = fsNormal then begin
f := TStylesMainForm.Create(AOwner);
f.InitConnection(DBHandle, RTrans);
f.SYS_ID_USER := _id_User;
if f.ShowModal <> mrOk then begin
Result := False;
Exit;
end
else begin
Result := False;
end;
end
else if fs = fsMDIChild then begin
f := TStylesMainForm.Create(AOwner);
f.InitConnection(DBHandle, RTrans);
f.SYS_ID_USER := _id_User;
f.FormStyle := FS;
f.Show;
end;
end;
procedure TStylesMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// SetFormParams(Self);
Action := caFree;
end;
procedure TStylesMainForm.FormCreate(Sender: TObject);
begin
CreatePredefinedStyleSheetsList;
if not VarIsNull(DM_Styles.StyleIndex) then lbPredefinedStyleSheets.ItemIndex := DM_Styles.StyleIndex;
if not VarIsNull(DM_Styles.BarStyleIndex) then BarComboBox.ItemIndex := DM_Styles.BarStyleIndex;
if not VarIsNull(DM_Styles.GridStyleIndex) then GridComboBox.ItemIndex := DM_Styles.GridStyleIndex;
if not VarIsNull(DM_Styles.StatusBarStyle) then StatusBarComboBox.ItemIndex := DM_Styles.GridStyleIndex;
SetPredefinedStyleSheets;
end;
procedure TStylesMainForm.FormShow(Sender: TObject);
begin
// GetFormParams(Self);
end;
procedure TStylesMainForm.CreatePredefinedStyleSheetsList;
var
I: Integer;
begin
with DM_Styles.GridPredefined do
begin
lbPredefinedStyleSheets.Clear;
for I := 0 to StyleSheetCount - 1 do
lbPredefinedStyleSheets.Items.AddObject(StyleSheets[I].Caption, StyleSheets[I]);
lbPredefinedStyleSheets.ItemIndex := 0;
end;
end;
procedure TStylesMainForm.UpdateGridStyleSheets(const AStyleSheet: TcxGridTableViewStyleSheet);
procedure UpdateView(const AView: TcxGridDBTableView);
begin
with AView do
begin
BeginUpdate;
Styles.StyleSheet := AStyleSheet;
EndUpdate;
end;
end;
begin
if GetCurrentStyleSheet = AStyleSheet then
Exit;
UpdateView(TableView);
UpdateView(AutoTableView);
TableView.DataController.ClearDetails; // refresh detail level
if AStyleSheet <> nil then
pnlCurrentStyleSheet.Caption := AStyleSheet.Caption
else
pnlCurrentStyleSheet.Caption := '';
end;
procedure TStylesMainForm.BarComboBoxPropertiesChange(Sender: TObject);
begin
case BarComboBox.ItemIndex of
0 : BarManager.Style := bmsEnhanced;
1 : BarManager.Style := bmsFlat;
2 : BarManager.Style := bmsOffice11;
3 : BarManager.Style := bmsStandard;
4 : BarManager.Style := bmsUseLookAndFeel;
5 : BarManager.Style := bmsXP;
end;
end;
procedure TStylesMainForm.CancelButtonClick(Sender: TObject);
begin
if FormStyle = fsNormal then ModalResult := mrCancel
else Close;
end;
procedure TStylesMainForm.SetPredefinedStyleSheets;
begin
with lbPredefinedStyleSheets do
if Items.Count > 0 then
UpdateGridStyleSheets(TcxGridTableViewStyleSheet(Items.Objects[ItemIndex]));
end;
procedure TStylesMainForm.StatusBarComboBoxPropertiesChange(Sender: TObject);
begin
case StatusBarComboBox.ItemIndex of
0 : StatusBar.PaintStyle := stpsFlat;
1 : StatusBar.PaintStyle := stpsOffice11;
2 : StatusBar.PaintStyle := stpsStandard;
3 : StatusBar.PaintStyle := stpsUseLookAndFeel;
4 : StatusBar.PaintStyle := stpsXP;
end;
end;
procedure TStylesMainForm.lbPredefinedStyleSheetsClick(
Sender: TObject);
begin
SetPredefinedStyleSheets;
end;
procedure TStylesMainForm.ApplyButtonClick(Sender: TObject);
begin
DM_Styles.StyleIndex := lbPredefinedStyleSheets.ItemIndex;
DM_Styles.BarStyleIndex := BarComboBox.ItemIndex;
DM_Styles.GridStyleIndex := GridComboBox.ItemIndex;
DM_Styles.StatusBarStyle := StatusBarComboBox.ItemIndex;
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('S_USER_STYLES_UPD', [SYS_ID_USER, lbPredefinedStyleSheets.ItemIndex,
BarComboBox.ItemIndex, GridComboBox.ItemIndex, StatusBarComboBox.ItemIndex]);
StoredProc.Transaction.Commit;
if FormStyle = fsNormal then ModalResult := mrOk
else Close;
end;
function TStylesMainForm.GetCurrentStyleSheet: TcxGridTableViewStyleSheet;
begin
Result := TcxGridTableViewStyleSheet(TableView.Styles.StyleSheet);
end;
procedure TStylesMainForm.GridComboBoxPropertiesChange(Sender: TObject);
begin
case GridComboBox.ItemIndex of
0 : Grid.LookAndFeel.Kind := lfFlat;
// 1 : Grid.LookAndFeel.Kind := lfOffice11;
2 : Grid.LookAndFeel.Kind := lfStandard;
3 : Grid.LookAndFeel.Kind := lfUltraFlat;
end;
end;
procedure TStylesMainForm.InitConnection(DBHandle: TISC_DB_HANDLE;
RTrans: TISC_TR_HANDLE);
begin
Database.Handle := DBHandle;
ReadTransaction.Handle := RTrans;
DataSet.Open;
UDataSet.Open;
end;
procedure TStylesMainForm.FormActivate(Sender: TObject);
begin
OpenDialog.InitialDir := ExtractFileDir(Application.ExeName);
SaveDialog.InitialDir := OpenDialog.InitialDir;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Configuration.Interfaces;
interface
uses
JsonDataObjects,
VSoft.Uri,
Spring.Collections,
DPM.Core.Types;
type
IConfigNode = interface
['{18443C57-FA60-4DAB-BB67-10ACCBB7EC3B}']
function LoadFromJson(const jsonObj : TJsonObject) : boolean;
function SaveToJson(const parentObj : TJsonObject) : boolean;
end;
ISourceConfig = interface(IConfigNode)
['{88D98629-8276-4782-B46B-004E7B9934E4}']
function GetName : string;
function GetSource : string;
function GetUserName : string;
function GetPassword : string;
function GetIsEnabled : boolean;
function GetFileName : string;
function GetSourceType : TSourceType;
procedure SetName(const value : string);
procedure SetSource(const value : string);
procedure SetUserName(const value : string);
procedure SetPassword(const value : string);
procedure SetIsEnabled(const value : boolean);
procedure SetSourceType(const value : TSourceType);
property Name : string read GetName write SetName;
property Source : string read GetSource write SetSource;
property UserName : string read GetUserName write SetUserName;
property Password : string read GetPassword write SetPassword;
property FileName : string read GetFileName;
property IsEnabled : boolean read GetIsEnabled write SetIsEnabled;
property SourceType : TSourceType read GetSourceType write SetSourceType;
end;
IConfiguration = interface(IConfigNode)
['{C5B88059-C5C8-4207-BF5A-503FFE31863D}']
function GetPackageCacheLocation : string;
procedure SetPackageCacheLocation(const value : string);
function GetIsDefaultPackageCacheLocation : boolean;
procedure AddDefaultSources;
function GetSourceByName(const name : string) : ISourceConfig;
function GetSources : IList<ISourceConfig>;
function GetFileName : string;
procedure SetFileName(const value : string);
property FileName : string read GetFileName write SetFileName;
//defaults to %userprofile%\.dpm\packages - can override with env var DPM_PACKAGES
property PackageCacheLocation : string read GetPackageCacheLocation write SetPackageCacheLocation;
property IsDefaultPackageCacheLocation : boolean read GetIsDefaultPackageCacheLocation;
property Sources : IList<ISourceConfig>read GetSources;
end;
IConfigurationLoadSave = interface(IConfiguration)
['{17DDD5AB-5262-4E51-918E-170BC25BFE8A}']
function LoadFromFile(const fileName : string) : boolean;
function SaveToFile(const fileName : string) : boolean;
end;
//use DI to inject this where needed
IConfigurationManager = interface
['{7A2A8F5E-A241-459C-BD62-AB265AA5935F}']
function LoadConfig(const configFile : string) : IConfiguration;
function NewConfig : IConfiguration;
function EnsureDefaultConfig : boolean;
function SaveConfig(const configuration : IConfiguration; const fileName : string = '') : boolean;
end;
implementation
end.
|
unit ufrmDialogLokasi;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
StdCtrls, uRetnoUnit, ufrmLokasi, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
cxCurrencyEdit, System.Actions, Vcl.ActnList, ufraFooterDialog3Button,
uInterface, uModBarang, Vcl.ComCtrls, dxBarBuiltInMenu, cxPC, cxClasses,
dxAlertWindow;
type
TfrmDialogLokasi = class(TfrmMasterDialog, ICrudable)
edtCode: TEdit;
lbl1: TLabel;
Label1: TLabel;
edtDescrp: TEdit;
lbl2: TLabel;
cbbType: TComboBox;
chkIsActive: TCheckBox;
lbl3: TLabel;
lblCode: TLabel;
edtName: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
edRack: TEdit;
edBay: TEdit;
edShelve: TEdit;
edPosition: TEdit;
intedtCapacity: TcxCurrencyEdit;
procedure FormCreate(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
private
FModLokasi: TModLokasi;
function GetModLokasi: TModLokasi;
procedure SaveData;
procedure UpdateData;
property ModLokasi: TModLokasi read GetModLokasi write FModLokasi;
// procedure showDataEdit();
// procedure prepareAddData;
public
procedure LoadData(AID: String = '');
{ Public declarations }
published
end;
var
frmDialogLokasi: TfrmDialogLokasi;
implementation
uses uTSCommonDlg, uConn, uDMClient, uAppUtils, uDXUtils, uConstanta;
{$R *.dfm}
procedure TfrmDialogLokasi.FormCreate(Sender: TObject);
begin
inherited;
Self.AssignKeyDownEvent;
end;
procedure TfrmDialogLokasi.actDeleteExecute(Sender: TObject);
begin
inherited;
Try
DMClient.CrudClient.DeleteFromDB(ModLokasi);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult := mrOk;
Except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogLokasi.actSaveExecute(Sender: TObject);
begin
inherited;
SaveData;
end;
function TfrmDialogLokasi.GetModLokasi: TModLokasi;
begin
if not Assigned(FModLokasi) then
FModLokasi := TModLokasi.Create;
Result := FModLokasi;
end;
procedure TfrmDialogLokasi.LoadData(AID: String = '');
begin
FreeAndNil(FModLokasi);
FModLokasi := DMClient.CrudClient.Retrieve(
TModLokasi.ClassName, aID) as TModLokasi;
edtCode.Text := ModLokasi.LOK_CODE;
edtName.Text := ModLokasi.LOK_NAME;
edtDescrp.Text := ModLokasi.LOK_DESCRIPTION;
edBay.Text := ModLokasi.LOK_BAY;
edRack.Text := ModLokasi.LOK_RACK;
edShelve.Text := ModLokasi.LOK_SHELVE;
edPosition.Text := ModLokasi.LOK_POSITION;
cbbType.Text := ModLokasi.LOK_TYPE;
intedtCapacity.Value := ModLokasi.LOK_CAPACITY;
chkIsActive.Checked := ModLokasi.LOK_IS_ACTIVE = 1;
end;
procedure TfrmDialogLokasi.SaveData;
begin
if not ValidateEmptyCtrl then exit;
Try
UpdateData;
DMClient.CrudClient.SaveToDB(ModLokasi);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
Self.ModalResult := mrOK;
Except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
End;
end;
procedure TfrmDialogLokasi.UpdateData;
begin
ModLokasi.LOK_CODE := edtCode.Text;
ModLokasi.LOK_NAME := edtName.Text;
ModLokasi.LOK_DESCRIPTION := edtDescrp.Text;
ModLokasi.LOK_BAY := edBay.Text;
ModLokasi.LOK_RACK := edRack.Text;
ModLokasi.LOK_SHELVE := edShelve.Text;
ModLokasi.LOK_POSITION := edPosition.Text;
ModLokasi.LOK_TYPE := cbbType.Text;
ModLokasi.LOK_CAPACITY := intedtCapacity.Value;
ModLokasi.LOK_IS_ACTIVE := TAppUtils.BoolToInt(chkIsActive.Checked);
end;
end.
|
// This unit should contain any custom rules used
// by the application. The rule defined here
// is provided as an example.
unit Rules;
interface
uses
Kitto.Rules, KItto.Store;
type
TCheckDuplicateInvitations = class(TKRuleImpl)
public
procedure BeforeAdd(const ARecord: TKRecord); override;
end;
implementation
uses
EF.Localization,
Kitto.Metadata.DataView;
{ TCheckDuplicateInvitations }
procedure TCheckDuplicateInvitations.BeforeAdd(const ARecord: TKRecord);
begin
if ARecord.Store.Count('INVITEE_ID', ARecord.FieldByName('INVITEE_ID').Value) > 1 then
RaiseError(_('Cannot invite the same girl twice.'));
end;
initialization
TKRuleImplRegistry.Instance.RegisterClass(TCheckDuplicateInvitations.GetClassId, TCheckDuplicateInvitations);
finalization
TKRuleImplRegistry.Instance.UnregisterClass(TCheckDuplicateInvitations.GetClassId);
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Registration unit for library components, property editors and
IDE experts.
}
unit VXS.SceneRegister;
interface
{$I VXScene.inc}
uses
Winapi.Windows,
System.Classes,
System.SysUtils,
System.TypInfo,
FMX.Forms,
FMX.Dialogs,
FMX.Controls,
FMX.StdCtrls,
FMX.Graphics,
{ TODO : F1026 Files not found: 'VCLEditors' etc.}
(*need to create instead a custom PropertyEditor like it described in -> *)
(*ms-help://embarcadero.rs_xe7/rad/Creating_a_Component_Editor_and_a_Property_Editor_for_FireMonkey_Components.html*)
(*
VCLEditors,
ToolsAPI,
DesignIntf,
DesignEditors,
*)
VXS.Strings,
VXS.Scene,
VXS.Context,
VXS.Color,
VXS.CrossPlatform,
VXS.ObjectManager;
type
TVXLibMaterialNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXSceneViewerEditor = class(TComponentEditor)
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TVXSceneEditor = class(TComponentEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TResolutionProperty = class(TPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
TVXTextureProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
end;
TVXTextureImageProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXImageClassProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
TVXColorProperty = class(TClassProperty, ICustomPropertyDrawing,
ICustomPropertyListDrawing)
private
protected
function ColorToBorderColor(aColor: TColorVector;
selected: Boolean): TColor;
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure Edit; override;
// ICustomPropertyListDrawing stuff
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TVXRect; ASelected: Boolean);
// CustomPropertyDrawing
procedure PropDrawName(ACanvas: TCanvas; const ARect: TVXRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TVXRect;
ASelected: Boolean);
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
TSoundFileProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
TSoundNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXCoordinatesProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXMaterialProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXGUILayoutEditor = class(TComponentEditor)
public
procedure Edit; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
{ Editor copied from DsgnIntf.
Could have been avoided, if only that guy at Borland didn't chose to
publish only half of the stuff (and that's not the only class with
that problem, most of the subitems handling code in TVXSceneBaseObject is
here for the same reason...), the "protected" wasn't meant just to lure
programmers into code they can't reuse... Arrr! Grrr... }
TReuseableDefaultEditor = class(TComponentEditor, IDefaultEditor)
protected
FFirst: IProperty;
FBest: IProperty;
FContinue: Boolean;
procedure CheckEdit(const Prop: IProperty);
procedure EditProperty(const Prop: IProperty;
var Continue: Boolean); virtual;
public
procedure Edit; override;
end;
{ Editor for material library. }
TVXMaterialLibraryEditor = class(TReuseableDefaultEditor, IDefaultEditor)
protected
procedure EditProperty(const Prop: IProperty;
var Continue: Boolean); override;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TVXAnimationNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
{ Selection editor for TVXSoundLibrary.
Allows units to be added to the uses clause automatically when
sound files are loaded into a TVXSoundLibrary at design-time. }
TVXSoundLibrarySelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
{ Selection editor for TVXBaseSceneObject.
Allows units to be added to the uses clause automatically when
behaviours/effects are added to a TVXBaseSceneObject at design-time. }
TVXBaseSceneObjectSelectionEditor = class(TSelectionEditor)
public
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
{ Editor for Archive Manager. }
TVXSArchiveManagerEditor = class(TReuseableDefaultEditor, IDefaultEditor)
protected
procedure EditProperty(const Prop: IProperty;
var Continue: Boolean); override;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TVXMaterialComponentNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXLibTextureNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXLibSamplerNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXLibCombinerNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXLibShaderNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXLibAttachmentNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TVXLibAsmProgNameProperty = class(TVXMaterialComponentNameProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
TPictureFileProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TShaderFileProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TAsmProgFileProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TUniformAutoSetProperty = class(TPropertyEditor)
private
procedure PassUniform(const S: string);
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TVXShaderEditorProperty = class(TClassProperty)
protected
function GetStrings: TStrings;
procedure SetStrings(const Value: TStrings);
procedure OnShaderCheck(Sender: TObject);
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
procedure Register;
// Auto-create for object manager
function ObjectManager: TVXObjectManager;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
uses
FLibMaterialPicker,
FGUILayoutEditor,
FMaterialEditorForm,
FShaderMemo,
FShaderUniformEditor,
FVectorEditor,
FSceneEditor,
VXS.AnimatedSprite,
VXS.ApplicationFileIO,
VXS.AsmShader,
VXS.AsyncHDS,
VXS.AsyncTimer,
VXS.Atmosphere,
VXS.AVIRecorder,
VXS.BaseClasses,
VXS.BitmapFont,
VXS.Blur,
VXS.BumpmapHDS,
VXS.BumpShader,
VXS.Cadencer,
VXS.CameraController,
VXS.CelShader,
VXS.Collision,
VXS.CompositeImage,
VXS.Console,
VXS.Coordinates,
VXS.DCE,
VXS.DynamicTexture,
VXS.EParticleMasksManager,
VXS.ExplosionFx,
VXS.Extrusion,
VXS.FBORenderer,
VXS.Feedback,
VXS.FireFX,
VXS.FPSMovement,
VXS.GameMenu,
VXS.GeomObjects,
VXS.Gizmo,
VXS.Graph,
VXS.Graphics,
VXS.Gui,
VXS.HeightData,
VXS.HeightTileFileHDS,
VXS.HiddenLineShader,
VXS.HUDObjects,
VXS.Imposter,
VXS.LensFlare,
VXS.LinePFX,
VXS.Material,
VXS.MaterialEx,
VXS.MaterialMultiProxy,
VXS.MaterialScript,
VXS.Mesh,
VXS.Mirror,
VXS.MultiMaterialShader,
VXS.MultiPolygon,
VXS.MultiProxy,
VXS.Navigator,
VXS.Nodes,
VXS.Objects,
VXS.OutlineShader,
VXS.ParticleFX,
VXS.Particles,
VXS.Perlin,
VXS.PerlinPFX,
VXS.PhongShader,
VXS.Polyhedron,
VXS.Portal,
VXS.PostEffects,
VXS.ProjectedTextures,
VXS.ProxyObjects,
VXS.RenderContextInfo,
VXS.ArchiveManager,
VXS.Screen,
VXS.ScriptBase,
VXS.ShaderCombiner,
VXS.ShadowHDS,
VXS.ShadowPlane,
VXS.ShadowVolume,
VXS.SimpleNavigation,
VXS.SkyBox,
VXS.Skydome,
VXS.Language,
VXS.GLSLBumpShader,
VXS.GLSLDiffuseSpecularShader,
VXS.GLSLPostShaders,
VXS.GLSLProjectedTextures,
VXS.GLSLShader,
VXS.SmoothNavigator,
VXS.SMWaveOut,
VXS.State,
VXS.Strings,
VXS.Teapot,
VXS.TerrainRenderer,
VXS.TexCombineShader,
VXS.TexLensFlare,
VXS.Texture,
VXS.TexturedHDS,
VXS.TextureImageEditors,
VXS.TextureSharingShader,
VXS.ThorFX,
VXS.TilePlane,
VXS.TimeEventsMgr,
VXS.Trail,
VXS.Tree,
VXS.Types,
VXS.FileTIN,
VXS.UserShader,
VXS.Utils,
VXS.VectorFileObjects,
VXS.VfsPAK,
VXS.WaterPlane,
VXS.Windows,
VXS.WindowsFont,
VXS.zBuffer,
VXS.VectorTypes,
VXS.VectorGeometry,
// Image file formats
DDSImage,
VXS.FileTGA,
// Vector file formats
VXS.File3DS,
VXS.FileASE,
VXS.FileB3D,
VXS.FileGL2,
VXS.FileGTS,
VXS.FileLMTS,
VXS.FileLWO,
VXS.FileMD2,
VXS.FileMD3,
VXS.FileMD5,
VXS.FileMDC,
VXS.FileMS3D,
VXS.FileNMF,
VXS.FileNurbs,
VXS.FileObj,
VXS.FileOCT,
VXS.FilePLY,
VXS.FileQ3BSP,
VXS.FileSMD,
VXS.FileSTL,
VXS.FileVRML,
// Sound file formats
VXS.FileWAV,
VXS.FileMP3,
// Raster file format
VXS.FileDDS,
VXS.FileO3TC,
VXS.FileHDR,
VXS.FileJPEG,
VXS.FilePNG,
VXS.FileBMP,
VXS.FileTGA,
VXS.Sound,
VXS.SoundFileObjects,
VXS.SpaceText,
VXS.Joystick,
VXS.ScreenSaver,
VXS.FullScreenViewer,
VXS.Log;
var
vObjectManager: TVXObjectManager;
function ObjectManager: TVXObjectManager;
begin
if not Assigned(vObjectManager) then
vObjectManager := TVXObjectManager.Create(nil);
Result := vObjectManager;
end;
procedure TVXSceneViewerEditor.ExecuteVerb(Index: Integer);
var
source: TVXSceneViewer;
begin
source := Component as TVXSceneViewer;
case Index of
0:
source.Buffer.ShowInfo;
end;
end;
function TVXSceneViewerEditor.GetVerb(Index: Integer): string;
begin
case Index of
0:
Result := 'Show context info';
end;
end;
function TVXSceneViewerEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
procedure TVXSceneEditor.Edit;
begin
with VXSceneEditorForm do
begin
SetScene(Self.Component as TVXScene, Self.Designer);
Show;
end;
end;
procedure TVXSceneEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0:
Edit;
end;
end;
function TVXSceneEditor.GetVerb(Index: Integer): string;
begin
case Index of
0:
Result := 'Show Scene Editor';
end;
end;
function TVXSceneEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
function TResolutionProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
function TResolutionProperty.GetValue: string;
begin
Result := vVideoModes[GetOrdValue].Description;
end;
procedure TResolutionProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
begin
for i := 0 to vNumberVideoModes - 1 do
Proc(vVideoModes[i].Description);
end;
procedure TResolutionProperty.SetValue(const Value: string);
const
Nums = ['0' .. '9'];
var
XRes, YRes, BPP: Integer;
Pos, SLength: Integer;
TempStr: string;
begin
if CompareText(Value, 'default') <> 0 then
begin
// initialize scanning
TempStr := Trim(Value) + '|'; // ensure at least one delimiter
SLength := Length(TempStr);
XRes := 0;
YRes := 0;
BPP := 0;
// contains the string something?
if SLength > 1 then
begin
// determine first number
for Pos := 1 to SLength do
if not(AnsiChar(TempStr[Pos]) in Nums) then
Break;
if Pos <= SLength then
begin
// found a number?
XRes := StrToInt(Copy(TempStr, 1, Pos - 1));
// search for following non-numerics
for Pos := Pos to SLength do
if AnsiChar(TempStr[Pos]) in Nums then
Break;
Delete(TempStr, 1, Pos - 1); // take it out of the String
SLength := Length(TempStr); // rest length of String
if SLength > 1 then // something to scan?
begin
// determine second number
for Pos := 1 to SLength do
if not(AnsiChar(TempStr[Pos]) in Nums) then
Break;
if Pos <= SLength then
begin
YRes := StrToInt(Copy(TempStr, 1, Pos - 1));
// search for following non-numerics
for Pos := Pos to SLength do
if AnsiChar(TempStr[Pos]) in Nums then
Break;
Delete(TempStr, 1, Pos - 1); // take it out of the String
SLength := Length(TempStr); // rest length of String
if SLength > 1 then
begin
for Pos := 1 to SLength do
if not(AnsiChar(TempStr[Pos]) in Nums) then
Break;
if Pos <= SLength then
BPP := StrToInt(Copy(TempStr, 1, Pos - 1));
end;
end;
end;
end;
end;
SetOrdValue(GetIndexFromResolution(XRes, YRes, BPP));
end
else
SetOrdValue(0);
end;
function TVXTextureProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paSubProperties];
end;
function TVXTextureImageProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
procedure TVXTextureImageProperty.Edit;
begin
if EditTextureImage(TVXTextureImage(GetOrdValue)) then
Designer.Modified;
end;
{ TVXImageClassProperty }
function TVXImageClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TVXImageClassProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
sl: TStrings;
begin
sl := GetGLTextureImageClassesAsStrings;
try
for i := 0 to sl.Count - 1 do
Proc(sl[i]);
finally
sl.Free;
end;
end;
function TVXImageClassProperty.GetValue: string;
begin
Result := FindGLTextureImageClass(GetStrValue).FriendlyName;
end;
procedure TVXImageClassProperty.SetValue(const Value: string);
var
tic: TVXTextureImageClass;
begin
tic := FindGLTextureImageClassByFriendlyName(Value);
if Assigned(tic) then
SetStrValue(tic.ClassName)
else
SetStrValue('');
Modified;
end;
procedure TVXColorProperty.Edit;
var
colorDialog: TColorDialog;
VXS.Color: TVXColor;
begin
colorDialog := TColorDialog.Create(nil);
try
VXS.Color := TVXColor(GetOrdValue);
{$IFDEF WIN32}
colorDialog.Options := [cdFullOpen];
{$ENDIF}
colorDialog.Color := ConvertColorVector(VXS.Color.Color);
if colorDialog.Execute then
begin
VXS.Color.Color := ConvertWinColor(colorDialog.Color);
Modified;
end;
finally
colorDialog.Free;
end;
end;
function TVXColorProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paSubProperties, paValueList, paDialog];
end;
procedure TVXColorProperty.GetValues(Proc: TGetStrProc);
begin
ColorManager.EnumColors(Proc);
end;
function TVXColorProperty.GetValue: string;
begin
Result := ColorManager.GetColorName(TVXColor(GetOrdValue).Color);
end;
procedure TVXColorProperty.SetValue(const Value: string);
begin
TVXColor(GetOrdValue).Color := ColorManager.GetColor(Value);
Modified;
end;
function TVXColorProperty.ColorToBorderColor(aColor: TColorVector;
selected: Boolean): TColor;
begin
if (aColor.X > 0.75) or (aColor.Y > 0.75) or (aColor.Z > 0.75) then
Result := clBlack
else if selected then
Result := clWhite
else
Result := ConvertColorVector(aColor);
end;
procedure TVXColorProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, True)
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
procedure TVXColorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
var
vRight: Integer;
vOldPenColor, vOldBrushColor: TColor;
Color: TColorVector;
begin
vRight := (ARect.Bottom - ARect.Top) + ARect.Left;
with ACanvas do
try
vOldPenColor := Pen.Color;
vOldBrushColor := Brush.Color;
Pen.Color := Brush.Color;
Rectangle(ARect.Left, ARect.Top, vRight, ARect.Bottom);
Color := ColorManager.GetColor(Value);
Brush.Color := ConvertColorVector(Color);
Pen.Color := ColorToBorderColor(Color, ASelected);
Rectangle(ARect.Left + 1, ARect.Top + 1, vRight - 1, ARect.Bottom - 1);
Brush.Color := vOldBrushColor;
Pen.Color := vOldPenColor;
finally
DefaultPropertyListDrawValue(Value, ACanvas,
Rect(vRight, ARect.Top, ARect.Right, ARect.Bottom), ASelected);
end;
end;
procedure TVXColorProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
begin
AWidth := AWidth + ACanvas.TextHeight('M');
end;
procedure TVXColorProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
begin
// Nothing
end;
procedure TVXColorProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
function TSoundFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TSoundFileProperty.GetValue: string;
var
sample: TVXSoundSample;
begin
sample := GetComponent(0) as TVXSoundSample;
if sample.Data <> nil then
Result := '(' + sample.Data.ClassName + ')'
else
Result := '(empty)';
end;
procedure TSoundFileProperty.Edit;
var
ODialog: TOpenDialog;
sample: TVXSoundSample;
Desc, F: string;
begin
sample := GetComponent(0) as TVXSoundSample;
ODialog := TOpenDialog.Create(nil);
try
GetGLSoundFileFormats.BuildFilterStrings(TVXSoundFile, Desc, F);
ODialog.Filter := Desc;
if ODialog.Execute then
begin
sample.LoadFromFile(ODialog.FileName);
Modified;
end;
finally
ODialog.Free;
end;
end;
//---------------------------------------------------------
function TSoundNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TSoundNameProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
source: TVXBaseSoundSource;
begin
source := (GetComponent(0) as TVXBaseSoundSource);
if Assigned(source.SoundLibrary) then
with source.SoundLibrary do
for i := 0 to Samples.Count - 1 do
Proc(Samples[i].Name);
end;
//---------------------------------------------------------
{ TVXCoordinatesProperty }
//--------------------------------------------------------
function TVXCoordinatesProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TVXCoordinatesProperty.Edit;
var
glc: TVXCoordinates;
x, y, z: Single;
begin
glc := TVXCoordinates(GetOrdValue);
x := glc.x;
y := glc.y;
z := glc.z;
if VectorEditorForm.Execute(x, y, z) then
begin
glc.AsVector := VectorMake(x, y, z);
Modified;
end;
end;
//--------------------------------------------------------
function TVXMaterialProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paSubProperties];
end;
procedure TVXMaterialProperty.Edit;
begin
if FMaterialEditorForm.MaterialEditorForm.Execute(TVXMaterial(GetOrdValue))
then
Modified;
end;
procedure TVXGUILayoutEditor.Edit;
begin
GUILayoutEditorForm.Execute(TVXGuiLayout(Self.Component));
end;
procedure TVXGUILayoutEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
function TVXGUILayoutEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Show Layout Editor';
end;
end;
function TVXGUILayoutEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
procedure TReuseableDefaultEditor.CheckEdit(const Prop: IProperty);
begin
if FContinue then
EditProperty(Prop, FContinue);
end;
procedure TReuseableDefaultEditor.EditProperty(const Prop: IProperty;
var Continue: Boolean);
var
PropName: string;
BestName: string;
MethodProperty: IMethodProperty;
procedure ReplaceBest;
begin
FBest := Prop;
if FFirst = FBest then
FFirst := nil;
end;
begin
if not Assigned(FFirst) and Supports(Prop, IMethodProperty, MethodProperty)
then
FFirst := Prop;
PropName := Prop.GetName;
BestName := '';
if Assigned(FBest) then
BestName := FBest.GetName;
if CompareText(PropName, 'ONCREATE') = 0 then
ReplaceBest
else if CompareText(BestName, 'ONCREATE') <> 0 then
if CompareText(PropName, 'ONCHANGE') = 0 then
ReplaceBest
else if CompareText(BestName, 'ONCHANGE') <> 0 then
if CompareText(PropName, 'ONCLICK') = 0 then
ReplaceBest;
end;
procedure TReuseableDefaultEditor.Edit;
var
Components: IDesignerSelections;
begin
Components := TDesignerSelections.Create;
FContinue := True;
Components.Add(Component);
FFirst := nil;
FBest := nil;
try
GetComponentProperties(Components, tkAny, Designer, CheckEdit);
if FContinue then
if Assigned(FBest) then
FBest.Edit
else if Assigned(FFirst) then
FFirst.Edit;
finally
FFirst := nil;
FBest := nil;
end;
end;
procedure TVXMaterialLibraryEditor.EditProperty(const Prop: IProperty;
var Continue: Boolean);
begin
if CompareText(Prop.GetName, 'MATERIALS') = 0 then
begin
FBest := Prop;
end;
end;
procedure TVXMaterialLibraryEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: Edit;
end;
end;
function TVXMaterialLibraryEditor.GetVerb(Index: Integer): string;
begin
case Index of
0:
Result := 'Show Material Library Editor';
end;
end;
function TVXMaterialLibraryEditor.GetVerbCount: Integer;
begin
Result := 1
end;
function TVXLibMaterialNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
procedure TVXLibMaterialNameProperty.Edit;
var
buf: string;
ml: TVXAbstractMaterialLibrary;
obj: TPersistent;
Int: IGLMaterialLibrarySupported;
begin
buf := GetStrValue;
obj := GetComponent(0);
if Supports(obj, IGLMaterialLibrarySupported, Int) then
ml := Int.GetMaterialLibrary
else
begin
ml := nil;
Assert(False, 'oops, unsupported...');
end;
if not Assigned(ml) then
ShowMessage('Select the material library first.')
else if LibMaterialPicker.Execute(buf, ml) then
SetStrValue(buf);
end;
function TVXAnimationNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TVXAnimationNameProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
animControler: TVXAnimationControler;
actor: TVXActor;
begin
animControler := (GetComponent(0) as TVXAnimationControler);
if Assigned(animControler) then
begin
actor := animControler.actor;
if Assigned(actor) then
with actor.Animations do
begin
for i := 0 to Count - 1 do
Proc(Items[i].Name);
end;
end;
end;
procedure TVXBaseSceneObjectSelectionEditor.RequiresUnits(Proc: TGetStrProc);
var
i, j: Integer;
comp: TVXBaseSceneObject;
begin
if (Designer = nil) or (Designer.Root = nil) then
Exit;
for i := 0 to Designer.Root.ComponentCount - 1 do
begin
if (Designer.Root.Components[i] is TVXBaseSceneObject) then
begin
comp := TVXBaseSceneObject(Designer.Root.Components[i]);
for j := 0 to comp.Behaviours.Count - 1 do
Proc(FindUnitName(comp.Behaviours[j]));
for j := 0 to comp.Effects.Count - 1 do
Proc(FindUnitName(comp.Effects[j]));
end;
end;
end;
procedure TVXSoundLibrarySelectionEditor.RequiresUnits(Proc: TGetStrProc);
var
i, j: Integer;
comp: TVXSoundLibrary;
begin
if (Designer = nil) or (Designer.Root = nil) then
Exit;
for i := 0 to Designer.Root.ComponentCount - 1 do
begin
if (Designer.Root.Components[i] is TVXSoundLibrary) then
begin
comp := TVXSoundLibrary(Designer.Root.Components[i]);
for j := 0 to comp.Samples.Count - 1 do
if Assigned(comp.Samples[j].Data) then
Proc(FindUnitName(comp.Samples[j].Data));
end;
end;
end;
procedure TVXSArchiveManagerEditor.EditProperty(const Prop: IProperty;
var Continue: Boolean);
begin
if CompareText(Prop.GetName, 'ARCHIVES') = 0 then
begin
FBest := Prop;
end;
end;
procedure TVXSArchiveManagerEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0:
Edit;
end;
end;
function TVXSArchiveManagerEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Show Archive Manager Editor';
end;
end;
function TVXSArchiveManagerEditor.GetVerbCount: Integer;
begin
Result := 1
end;
procedure TVXMaterialComponentNameProperty.Edit;
var
LOwner: IGLMaterialLibrarySupported;
LItem: TVXBaseMaterialCollectionItem;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
begin
LItem := TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.Components.GetItemByName(GetStrValue);
if Assigned(LItem) then
Designer.SelectComponent(LItem);
Modified;
end;
end;
function TVXMaterialComponentNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TVXLibTextureNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
begin
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXTextureImageEx);
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXFrameBufferAttachment);
end;
end;
procedure TVXLibSamplerNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXTextureSampler);
end;
procedure TVXLibCombinerNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXTextureCombiner);
end;
procedure TVXLibShaderNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary).GetNames(Proc, TVXShaderEx);
end;
procedure TVXLibAttachmentNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXFrameBufferAttachment);
end;
procedure TVXLibAsmProgNameProperty.GetValues(Proc: TGetStrProc);
var
LOwner: IGLMaterialLibrarySupported;
begin
if Supports(GetComponent(0), IGLMaterialLibrarySupported, LOwner) then
TVXMaterialLibraryEx(LOwner.GetMaterialLibrary)
.GetNames(Proc, TVXASMVertexProgram);
end;
function TPictureFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
procedure TPictureFileProperty.Edit;
var
LFileName: string;
begin
if OpenPictureDialog(LFileName) then
begin
SetStrValue(RelativePath(LFileName));
end;
Modified;
end;
procedure TShaderFileProperty.Edit;
var
ODialog: TOpenDialog;
begin
ODialog := TOpenDialog.Create(nil);
try
ODialog.Filter := '*.glsl';
if ODialog.Execute then
begin
SetStrValue(RelativePath(ODialog.FileName));
Modified;
end;
finally
ODialog.Free;
end;
end;
function TShaderFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
procedure TAsmProgFileProperty.Edit;
var
ODialog: TOpenDialog;
begin
ODialog := TOpenDialog.Create(nil);
try
ODialog.Filter := '*.asm';
if ODialog.Execute then
begin
SetStrValue(RelativePath(ODialog.FileName));
Modified;
end;
finally
ODialog.Free;
end;
end;
function TAsmProgFileProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
{ TUniformAutoSetProperty }
function TUniformAutoSetProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paFullWidthName];
end;
procedure TUniformAutoSetProperty.PassUniform(const S: string);
begin
ShaderUniformEditor.AddUniform(TVXBaseShaderModel(GetComponent(0))
.Uniforms[S]);
end;
procedure TUniformAutoSetProperty.Edit;
var
LOwner: TVXBaseShaderModel;
begin
LOwner := TVXBaseShaderModel(GetComponent(0));
if LOwner.Enabled and LOwner.IsValid then
begin
with ShaderUniformEditor do
begin
Clear;
LOwner.MaterialLibrary.GetNames(AddTextureName, TVXTextureImageEx);
LOwner.MaterialLibrary.GetNames(AddTextureName, TVXFrameBufferAttachment);
LOwner.MaterialLibrary.GetNames(AddSamplerName, TVXTextureSampler);
LOwner.GetUniformNames(PassUniform);
Execute;
end;
end;
end;
function TVXShaderEditorProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
function TVXShaderEditorProperty.GetStrings: TStrings;
begin
Result := TStrings(GetOrdValue);
end;
procedure TVXShaderEditorProperty.OnShaderCheck(Sender: TObject);
var
LShader: TVXShaderEx;
LContext: TVXContext;
begin
SetStrings(GLShaderEditorForm.GLSLMemo.Lines);
LShader := TVXShaderEx(GetComponent(0));
LContext := LShader.Handle.RenderingContext;
if Assigned(LContext) then
begin
LContext.Activate;
try
LShader.DoOnPrepare(LContext);
GLShaderEditorForm.CompilatorLog.Lines.Add(LShader.InfoLog);
finally
LContext.Deactivate;
end;
end
else
GLShaderEditorForm.CompilatorLog.Lines.Add
('There is no any rendering context for work with OpenGL');
end;
procedure TVXShaderEditorProperty.SetStrings(const Value: TStrings);
begin
SetOrdValue(Longint(Value));
end;
procedure TVXShaderEditorProperty.Edit;
begin
with GLShaderEditorForm do
begin
OnCheck := OnShaderCheck;
GLSLMemo.Lines.Assign(GetStrings);
GLSLMemo.CurX := 0;
GLSLMemo.CurY := 0;
if ShowModal = mrOk then
begin
SetStrings(GLSLMemo.Lines);
Modified;
end;
end;
end;
// ******************************************************************************
procedure GLRegisterPropertiesInCategories;
begin
{ VXS.SceneViewer }
// property types
{$IFDEF WIN32}
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXCamera), TypeInfo(TVXSceneBuffer),
TypeInfo(TVSyncMode), TypeInfo(TVXScreenDepth)]);
{$ENDIF}
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXSceneViewer, ['*Render']);
{ VXS.Scene }
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXx.ObjectsSorting), TypeInfo(TVXProgressEvent),
TypeInfo(TVXBehaviours), TypeInfo(TVXObjectEffects), TypeInfo(TDirectRenderEvent), TypeInfo(TVXCameraStyle),
TypeInfo(TOnCustomPerspective), TypeInfo(TVXScene)]);
RegisterPropertiesInCategory(sLayoutCategoryName, [TypeInfo(TVXx.ObjectsSorting), TypeInfo(TNormalDirection)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TVXVisibilityCulling), TypeInfo(TLightStyle),
TypeInfo(TVXColor), TypeInfo(TNormalDirection), TypeInfo(TVXCameraStyle)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXBaseSceneObject,
['Rotation', 'Direction', 'Position', 'Up', 'Scale', '*Angle', 'ShowAxes', 'FocalLength']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXSceneObject, ['Parts']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXDirectOpenVX, ['UseBuildList']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXProxyObjectOptions)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXLightSource, ['*Attenuation', 'Shining', 'Spot*']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXCamera, ['TargetObject']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXCamera, ['DepthOfView', 'SceneScale']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXNonVisualViewer, ['*Render']);
{ VXS.Objects }
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXLinesNodes), TypeInfo(TLineNodesAspect),
TypeInfo(TLineSplineMode), TypeInfo(TLinesOptions)]);
{$IFDEF WIN32}
RegisterPropertiesInCategory(sLayoutCategoryName, [TypeInfo(TVXTextAdjust)]);
RegisterPropertiesInCategory(sLocalizableCategoryName, [TypeInfo(TSpaceTextCharRange)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TLineSplineMode),
TypeInfo(TCapType), TypeInfo(TNormalSmoothing), TypeInfo(TArrowHeadStackingStyle), TypeInfo(TVXTextAdjust)]);
{$ENDIF}
RegisterPropertiesInCategory(sLayoutCategoryName, TVXDummyCube, ['VisibleAtRunTime']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXDummyCube, ['CubeSize', 'VisibleAtRunTime']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPlane, ['*Offset', '*Tiles']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXSprite, ['NoZWrite']);
RegisterPropertiesInCategory(sLayoutCategoryName, TVXSprite, ['NoZWrite']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXSprite, ['AlphaChannel', 'Rotation']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXNode, ['X', 'Y', 'Z']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXLines, ['Antialiased', 'Division', 'Line*', 'NodeSize']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXCube, ['Cube*']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXFrustrum, ['ApexHeight', 'Base*']);
{$IFDEF WIN32}
RegisterPropertiesInCategory(sVisualCategoryName, TVXSpaceText, ['AllowedDeviation', 'AspectRatio', 'Extrusion', 'Oblique', 'TextHeight']);
{$ENDIF}
RegisterPropertiesInCategory(sVisualCategoryName, TVXSphere, ['Bottom', 'Radius', 'Slices', 'Stacks', 'Start', 'Stop']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXDisk, ['*Radius', 'Loops', 'Slices']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXCone, ['BottomRadius', 'Loops', 'Slices', 'Stacks']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXCylinder, ['*Radius', 'Loops', 'Slices', 'Stacks']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXCapsule, ['*Radius', 'Loops', 'Slices', 'Stacks']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXAnnulus, ['Bottom*', 'Loops', 'Slices', 'Stacks', 'Top*']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXTorus, ['*Radius', 'Rings', 'Sides']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXArrowLine, ['Bottom*', 'Loops', 'Slices', 'Stacks', 'Top*']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPolygon, ['Division']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXContourNodes), TypeInfo(TVXContours)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXContour, ['Division']);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TVXNodes), TypeInfo(TPipeNodesColorMode)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXRevolutionSolid, ['Division', 'Slices', 'YOffsetPerTurn']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXExtrusionSolid, ['Stacks']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPipeNode, ['RadiusFactor']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPipe, ['Division', 'Radius', 'Slices']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXActorAnimationMode), TypeInfo(TVXActorAnimations),
TypeInfo(TMeshAutoCenterings), TypeInfo(TActorFrameInterpolation),
TypeInfo(TVXActorAnimationReference), TypeInfo(TVXActor)]);
RegisterPropertiesInCategory(sLayoutCategoryName, [TypeInfo(TMeshNormalsOrientation)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TMeshAutoCenterings),
TypeInfo(TVXActorAnimationReference), TypeInfo(TMeshNormalsOrientation)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXFreeForm, ['UseMeshmaterials']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXAnimationControler, ['AnimationName']);
RegisterPropertiesInCategory(sLinkageCategoryName, TVXAnimationControler, ['AnimationName']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXActorAnimation, ['*Frame']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXActor, ['*Frame*', 'Interval', 'OverlaySkeleton', 'UseMeshmaterials']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXActor, ['OverlaySkeleton']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TMeshMode), TypeInfo(TVertexMode)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXHeightFieldOptions)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TVXHeightFieldColorMode),
TypeInfo(TVXSamplingScale), TypeInfo(TXYZGridLinesStyle), TypeInfo(TXYZGridParts)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXXYZGrid, ['Antialiased']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXXYZGrid, ['Antialiased', 'Line*']);
RegisterPropertiesInCategory(sLayoutCategoryName, TVXParticles, ['VisibleAtRunTime']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXParticles, ['*Size', 'VisibleAtRunTime']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXSkyDomeBands), TypeInfo(TVXSkyDomeOptions),
TypeInfo(TVXSkyDomeStars)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXSkyDomeBand, ['Slices', 'Stacks', '*Angle']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXSkyDomeStar, ['Dec', 'Magnitude', 'RA']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXEarthSkyDome, ['Slices', 'Stacks', 'SunElevation', 'Turbidity']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TMirrorOptions), TypeInfo(TVXBaseSceneObject)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TBlendingMode)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TBlendingMode), TypeInfo(TPFXLifeColors), TypeInfo(TSpriteColorMode)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXParticleFXRenderer, ['ZWrite']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXParticleFXRenderer, ['ZWrite']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TPFXLifeColor, ['LifeTime']);
RegisterPropertiesInCategory(sVisualCategoryName, TPFXLifeColor, ['LifeTime']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXLifeColoredPFXManager, ['Acceleration', 'ParticleSize']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPolygonPFXManager, ['NbSides']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXPointLightPFXManager, ['TexMapSize']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXHeightDataSource)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXTerrainRenderer, ['*CLOD*', 'QualityDistance', 'Tile*']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXMemoryViewer), TypeInfo(TVXSceneViewer), TypeInfo(TOptimise)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TOptimise)]);
RegisterPropertiesInCategory(sVisualCategoryName, TVXZShadows, ['DepthFade', '*Shadow', 'Soft', 'Tolerance']);
RegisterPropertiesInCategory(sLayoutCategoryName, [TypeInfo(TTextLayout)]);
RegisterPropertiesInCategory(sVisualCategoryName, [TypeInfo(TVXBitmapFont), TypeInfo(TTextLayout)]);
RegisterPropertiesInCategory(sLocalizableCategoryName, [TypeInfo(TVXBitmapFont)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXMaterial), TypeInfo(TVXMaterialLibrary),
TypeInfo(TVXLibMaterials), TypeInfo(TTextureNeededEvent)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXLibMaterial, ['Texture2Name']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXLibMaterial, ['TextureOffset', 'TextureScale']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXMaterialLibrary, ['TexturePaths']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXCadencer)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TObjectCollisionEvent)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXFireFXManager, ['MaxParticles', 'NoZWrite', 'Paused', 'UseInterval']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXFireFXManager, ['Fire*', 'InitialDir', 'NoZWrite', 'Particle*', 'Paused']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TCalcPointEvent)]);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXThorFXManager, ['Maxpoints', 'Paused']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXThorFXManager, ['Core', 'Glow*', 'Paused', 'Target', 'Vibrate', 'Wildness']);
RegisterPropertiesInCategory(sOpenVXCategoryName, [TypeInfo(TVXMagFilter), TypeInfo(TVXMinFilter)]);
RegisterPropertiesInCategory(sLocalizableCategoryName, [TypeInfo(TVXBitmapFontRanges)]);
RegisterPropertiesInCategory(sLocalizableCategoryName, TVXBitmapFontRange, ['*ASCII']);
RegisterPropertiesInCategory(sLayoutCategoryName, TVXBitmapFont, ['Char*', '*Interval*', '*Space']);
RegisterPropertiesInCategory(sLocalizableCategoryName, TVXBitmapFont, ['Glyphs']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXBitmapFont, ['Char*', '*Interval*', '*Space', 'Glyphs']);
RegisterPropertiesInCategory(sOpenVXCategoryName, TVXBitmapHDS, ['MaxPoolSize']);
RegisterPropertiesInCategory(sVisualCategoryName, TVXBitmapHDS, ['Picture']);
end;
procedure Register;
begin
RegisterComponents('VXScene', [TVXScene, TVXSceneViewer, TVXMemoryViewer,
TVXMaterialLibrary, TVXMaterialLibraryEx, TVXCadencer, TVXGuiLayout,
TVXBitmapFont, TVXWindowsBitmapFont, TVXScriptLibrary, TVXSoundLibrary,
TVXFullScreenViewer]);
RegisterComponents('VXScene PFX', [TVXCustomPFXManager, TVXPolygonPFXManager,
TVXPointLightPFXManager, TVXCustomSpritePFXManager, TVXPerlinPFXManager,
TVXLinePFXManager, TVXFireFXManager, TVXThorFXManager,
TVXEParticleMasksManager]);
RegisterComponents('VXScene Utils', [TVXAsyncTimer, TVXStaticImposterBuilder,
TVXCollisionManager, TVXAnimationControler, TVXAVIRecorder, TVXDCEManager,
TVXFPSMovementManager, TVXMaterialScripter, TVXUserInterface, TVXNavigator,
TVXSmoothNavigator, TVXSmoothUserInterface, TVXTimeEventsMGR,
TVXApplicationFileIO, TVXVfsPAK, TVXSimpleNavigation, TVXGizmo,
TVXCameraController, TVXSLanguage, TVXSLogger, TVXSArchiveManager,
TVXJoystick, TVXScreenSaver, TVXSSynHiMemo]);
RegisterComponents('VXScene Terrain', [TVXBitmapHDS, TVXCustomHDS,
TVXHeightTileFileHDS, TVXBumpmapHDS, TVXPerlinHDS, TVXTexturedHDS,
TVXAsyncHDS, TVXShadowHDS]);
RegisterComponents('VXScene Shaders', [TVXTexCombineShader, TVXPhongShader,
TVXUserShader, TVXHiddenLineShader, TVXCelShader, TVXOutlineShader,
TVXMultiMaterialShader, TVXBumpShader, TVXGLSLShader,
TVXSLDiffuseSpecularShader, TVXSLBumpShader, TVXAsmShader,
TVXShaderCombiner, TVXTextureSharingShader, TVXSLPostBlurShader]);
RegisterComponentEditor(TVXSceneViewer, TVXSceneViewerEditor);
RegisterComponentEditor(TVXScene, TVXSceneEditor);
RegisterComponentEditor(TVXMaterialLibrary, TVXMaterialLibraryEditor);
RegisterComponentEditor(TVXMaterialLibraryEx, TVXMaterialLibraryEditor);
RegisterComponentEditor(TVXSArchiveManager, TVXSArchiveManagerEditor);
VKRegisterPropertiesInCategories;
RegisterPropertyEditor(TypeInfo(TResolution), nil, '', TResolutionProperty);
RegisterPropertyEditor(TypeInfo(TVXTexture), TVXMaterial, '',
TVXTextureProperty);
RegisterPropertyEditor(TypeInfo(TVXTextureImage), TVXTexture, '',
TVXTextureImageProperty);
RegisterPropertyEditor(TypeInfo(string), TVXTexture, 'ImageClassName',
TVXImageClassProperty);
RegisterPropertyEditor(TypeInfo(TVXSoundFile), TVXSoundSample, '',
TSoundFileProperty);
RegisterPropertyEditor(TypeInfo(string), TVXBaseSoundSource, 'SoundName',
TSoundNameProperty);
RegisterPropertyEditor(TypeInfo(TVXCoordinates), nil, '',
TVXCoordinatesProperty);
RegisterPropertyEditor(TypeInfo(TVXColor), nil, '', TVXColorProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterial), nil, '', TVXMaterialProperty);
RegisterComponentEditor(TVXGuiLayout, TVXGUILayoutEditor);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXMaterial, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXLibMaterial,
'Texture2Name', TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXSkyBox, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXEParticleMask, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXGameMenu, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName),
TVXMaterialMultiProxyMaster, '', TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXSLBumpShader, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TSpriteAnimation, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXMaterialProxy, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXActorProxy, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXFBORenderer, '',
TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXActorAnimationName), TVXAnimationControler,
'', TVXAnimationNameProperty);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName),
TVXTextureSharingShaderMaterial, 'LibMaterialName', TVXLibMaterialNameProperty);
RegisterSelectionEditor(TVXBaseSceneObject, TVXBaseSceneObjectSelectionEditor);
RegisterSelectionEditor(TVXSoundLibrary, TVXSoundLibrarySelectionEditor);
RegisterPropertyEditor(TypeInfo(TVXLibMaterialName), TVXLibMaterialProperty,
'NextPass', TVXLibMaterialNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName),
TVXTextureProperties, 'LibTextureName', TVXLibTextureNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName),
TVXTextureProperties, 'LibSamplerName', TVXLibSamplerNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName),
TVXMultitexturingProperties, 'LibCombinerName', TVXLibCombinerNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName),
TVXMultitexturingProperties, 'LibAsmProgName', TVXLibAsmProgNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel3,
'LibVertexShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel3,
'LibFragmentShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel4,
'LibVertexShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel4,
'LibFragmentShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel4,
'LibGeometryShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel5,
'LibVertexShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel5,
'LibFragmentShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel5,
'LibGeometryShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel5,
'LibTessControlShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(TVXMaterialComponentName), TVXShaderModel5,
'LibTessEvalShaderName', TVXLibShaderNameProperty);
RegisterPropertyEditor(TypeInfo(string), TVXTextureImageEx, 'SourceFile', TPictureFileProperty);
RegisterPropertyEditor(TypeInfo(string), TVXShaderEx, 'SourceFile', TShaderFileProperty);
RegisterPropertyEditor(TypeInfo(string), TVXASMVertexProgram, 'SourceFile', TAsmProgFileProperty);
RegisterPropertyEditor(TypeInfo(Boolean), TVXBaseShaderModel, 'AutoFillOfUniforms', TUniformAutoSetProperty);
RegisterPropertyEditor(TypeInfo(TStringList), TVXShaderEx, 'Source', TVXShaderEditorProperty);
end;
function GetVXSceneVersion: string;
var
LProject: IOTAProject;
LExePath, LProjectPath, LSVN, LRevision: string;
begin
LRevision := Copy(VXScene_REVISION, 12, 4);
// will be assigned after project compilation
// after each compilation get it from file \.svn\entries in 4-th line
// and write to file VXSceneRevision
// in both fail (no \.svn\entries or VXSceneRevision file) get a version value from GLScene.pas
LProject := GetActiveProject;
LExePath := ExtractFilePath(ParamStr(0));
if Assigned(LProject) then
begin
LProjectPath := ExtractFilePath(LProject.FileName);
LSVN := LProjectPath + '.svn\entries';
if FileExists(LSVN) then
with TStringList.Create do
try
// Load
LoadFromFile(LSVN);
if (Count >= 4) and (Trim(Strings[3]) <> '') and
IsDirectoryWriteable(LExePath) then
begin
LRevision := Trim(Strings[3]);
// Save
Clear;
Add(LRevision);
SaveToFile(LExePath + 'VXSceneRevision');
end;
finally
Free;
end;
end
else if FileExists(LExePath + 'VXSceneRevision') then
try
with TStringList.Create do
try
LoadFromFile(LExePath + 'VXSceneRevision');
if (Count >= 1) and (Trim(Strings[0]) <> '') then
LRevision := Trim(Strings[0]);
finally
Free;
end;
except
end;
// Finally
Result := Format(VXScene_VERSION, [LRevision]);
end;
function GetProjectTargetName: string;
var
Project: IOTAProject;
begin
Result := '';
Project := GetActiveProject;
if Assigned(Project) then
begin
Result := Project.ProjectOptions.TargetName;
if Length(Result) > 0 then
ForceDirectories(ExtractFilePath(Result));
end;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
SplashScreenServices.AddPluginBitmap(GetVXSceneVersion,
LoadBitmap(HInstance, 'TVXScene'), False, 'MPL 2 license', 'SVN version');
VXS.CrossPlatform.IsDesignTime := True;
VXS.CrossPlatform.vProjectTargetName := GetProjectTargetName;
VXS.Color.vUseDefaultColorSets := True;
VXS.Coordinates.vUseDefaultCoordinateSets := True;
ReadVideoModes;
with ObjectManager do
begin
CreateDefaultObjectIcons(HInstance);
RegisterSceneObject(TVXCamera, 'Camera', '', HInstance);
RegisterSceneObject(TVXLightSource, 'LightSource', '', HInstance);
RegisterSceneObject(TVXDummyCube, 'DummyCube', '', HInstance);
// Basic geometry
RegisterSceneObject(TVXSprite, 'Sprite', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXPoints, 'Points', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXLines, 'Lines', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXPlane, 'Plane', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXPolygon, 'Polygon', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXCube, 'Cube', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXFrustrum, 'Frustrum', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXSphere, 'Sphere', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXDisk, 'Disk', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXCone, 'Cone', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXCylinder, 'Cylinder', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXCapsule, 'Capsule', strOCBasicGeometry, HInstance);
RegisterSceneObject(TVXDodecahedron, 'Dodecahedron', strOCBasicGeometry,
HInstance);
RegisterSceneObject(TVXIcosahedron, 'Icosahedron', strOCBasicGeometry,
HInstance);
RegisterSceneObject(TVXOctahedron, 'Octahedron', strOCBasicGeometry,
HInstance);
RegisterSceneObject(TVXTetrahedron, 'Tetrahedron', strOCBasicGeometry,
HInstance);
RegisterSceneObject(TVXSuperellipsoid, 'Superellipsoid', strOCBasicGeometry,
HInstance);
// Advanced geometry
RegisterSceneObject(TVXAnimatedSprite, 'Animated Sprite',
strOCAdvancedGeometry, HInstance);
RegisterSceneObject(TVXArrowLine, 'ArrowLine', strOCAdvancedGeometry,
HInstance);
RegisterSceneObject(TVXArrowArc, 'ArrowArc', strOCAdvancedGeometry,
HInstance);
RegisterSceneObject(TVXAnnulus, 'Annulus', strOCAdvancedGeometry, HInstance);
RegisterSceneObject(TVXExtrusionSolid, 'ExtrusionSolid',
strOCAdvancedGeometry, HInstance);
RegisterSceneObject(TVXMultiPolygon, 'MultiPolygon', strOCAdvancedGeometry,
HInstance);
RegisterSceneObject(TVXPipe, 'Pipe', strOCAdvancedGeometry, HInstance);
RegisterSceneObject(TVXRevolutionSolid, 'RevolutionSolid',
strOCAdvancedGeometry, HInstance);
RegisterSceneObject(TVXTorus, 'Torus', strOCAdvancedGeometry, HInstance);
// Mesh objects
RegisterSceneObject(TVXActor, 'Actor', strOCMeshObjects, HInstance);
RegisterSceneObject(TVXFreeForm, 'FreeForm', strOCMeshObjects, HInstance);
RegisterSceneObject(TVXMesh, 'Mesh', strOCMeshObjects, HInstance);
RegisterSceneObject(TVXTilePlane, 'TilePlane', strOCMeshObjects, HInstance);
RegisterSceneObject(TVXPortal, 'Portal', strOCMeshObjects, HInstance);
RegisterSceneObject(TVXTerrainRenderer, 'TerrainRenderer', strOCMeshObjects,
HInstance);
// Graph-plotting objects
RegisterSceneObject(TVXFlatText, 'FlatText', strOCGraphPlottingObjects,
HInstance);
RegisterSceneObject(TVXHeightField, 'HeightField', strOCGraphPlottingObjects,
HInstance);
RegisterSceneObject(TVXXYZGrid, 'XYZGrid', strOCGraphPlottingObjects,
HInstance);
// Particle systems
RegisterSceneObject(TVXParticles, 'Particles', strOCParticleSystems,
HInstance);
RegisterSceneObject(TVXParticleFXRenderer, 'PFX Renderer',
strOCParticleSystems, HInstance);
// Environment objects
RegisterSceneObject(TVXEarthSkyDome, 'EarthSkyDome', strOCEnvironmentObjects,
HInstance);
RegisterSceneObject(TVXSkyDome, 'SkyDome', strOCEnvironmentObjects,
HInstance);
RegisterSceneObject(TVXSkyBox, 'SkyBox', strOCEnvironmentObjects, HInstance);
RegisterSceneObject(TVXAtmosphere, 'Atmosphere', strOCEnvironmentObjects,
HInstance);
// HUD objects.
RegisterSceneObject(TVXHUDSprite, 'HUD Sprite', strOCHUDObjects, HInstance);
RegisterSceneObject(TVXHUDText, 'HUD Text', strOCHUDObjects, HInstance);
RegisterSceneObject(TVXResolutionIndependantHUDText,
'Resolution Independant HUD Text', strOCHUDObjects, HInstance);
RegisterSceneObject(TVXAbsoluteHUDText, 'Absolute HUD Text', strOCHUDObjects,
HInstance);
RegisterSceneObject(TVXGameMenu, 'GameMenu', strOCHUDObjects, HInstance);
RegisterSceneObject(TVXConsole, 'Console', strOCHUDObjects, HInstance);
// GUI objects.
RegisterSceneObject(TVXBaseControl, 'Root Control', strOCGuiObjects,
HInstance);
RegisterSceneObject(TVXPopupMenu, 'GLPopupMenu', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXForm, 'GLForm', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXPanel, 'GLPanel', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXButton, 'GLButton', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXCheckBox, 'GLCheckBox', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXEdit, 'GLEdit', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXLabel, 'GLLabel', strOCGuiObjects, HInstance);
RegisterSceneObject(TVXAdvancedLabel, 'GLAdvancedLabel', strOCGuiObjects,
HInstance);
RegisterSceneObject(TVXScrollbar, 'GLScrollbar', strOCGuiObjects, HInstance);
RegisterSceneObject(StringGrid, 'GLStringGrid', strOCGuiObjects,
HInstance);
RegisterSceneObject(TVXCustomControl, 'GLBitmapControl', strOCGuiObjects,
HInstance);
// Special objects
RegisterSceneObject(TVXLensFlare, 'LensFlare', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXTextureLensFlare, 'TextureLensFlare',
strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXMirror, 'Mirror', strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXShadowPlane, 'ShadowPlane', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXShadowVolume, 'ShadowVolume', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXZShadows, 'ZShadows', strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXSLTextureEmitter, 'GLSL Texture Emitter',
strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXSLProjectedTextures, 'GLSL Projected Textures',
strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXTextureEmitter, 'Texture Emitter', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXProjectedTextures, 'Projected Textures',
strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXBlur, 'Blur', strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXMotionBlur, 'MotionBlur', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXSpaceText, 'SpaceText', strOCDoodad, HInstance);
RegisterSceneObject(TVXTrail, 'Trail', strOCSpecialObjects, HInstance);
RegisterSceneObject(TVXPostEffect, 'PostEffect', strOCSpecialObjects,
HInstance);
RegisterSceneObject(TVXPostShaderHolder, 'PostShaderHolder',
strOCSpecialObjects, HInstance);
// Doodad objects.
RegisterSceneObject(TVXTeapot, 'Teapot', strOCDoodad, HInstance);
RegisterSceneObject(TVXTree, 'Tree', strOCDoodad, HInstance);
RegisterSceneObject(TVXWaterPlane, 'WaterPlane', strOCDoodad, HInstance);
// Proxy objects.
RegisterSceneObject(TVXProxyObject, 'ProxyObject', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXColorProxy, 'ColorProxy', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXFreeFormProxy, 'FreeFormProxy', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXMaterialProxy, 'MaterialProxy', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXActorProxy, 'ActorProxy', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXMultiProxy, 'MultiProxy', strOCProxyObjects,
HInstance);
RegisterSceneObject(TVXMaterialMultiProxy, 'MaterialMultiProxy',
strOCProxyObjects, HInstance);
// Other objects.
RegisterSceneObject(TVXDirectOpenVX, 'Direct OpenVX', '', HInstance);
RegisterSceneObject(TVXRenderPoint, 'Render Point', '', HInstance);
RegisterSceneObject(TVXImposter, 'Imposter Sprite', '', HInstance);
RegisterSceneObject(TVXFeedback, 'OpenVX Feedback', '', HInstance);
RegisterSceneObject(TVXFBORenderer, 'OpenVX FrameBuffer', '', HInstance);
end;
//=================================================================
finalization
//=================================================================
ObjectManager.Free;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.